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(mes,quality): shop-floor assembly & source-generic inspection execution (#1178)

Brad Barbincb6986513195
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 8a9ceeb407..6b4ac258cf 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -468,6 +468,16 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** `apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx`; any conditional twin-`ValidatedForm` pattern; `@carbon/form` controlled fields (`Select`/`Combobox`/anything on `useControlField`) that rely on `defaultValues` seeding.
+## Never blind-pop a stash in a Conductor worktree — the stash stack is shared/stale
+
+**Context:** During /execute, proving an erp typecheck failure pre-existing by temporarily parking three edited files with `git stash push -u <paths>` in a Conductor workspace.
+
+**Problem:** The `stash push` failed ("could not write index" — likely a concurrent git process from a sibling workspace; untracked-file pathspecs also fail plain `stash push`). No stash was created, but the follow-up `git stash pop` applied the TOP of the existing stash stack — an old stash from a *different branch's* work — half-applying unrelated files with merge conflicts (`UU`) and staged changes that then had to be surgically reverted.
+
+**Rule:** In Conductor/multi-worktree checkouts, don't use `git stash` for temporary file parking at all. Prove a failure is pre-existing with `git show HEAD~1:<file>` / `git log -- <file>` / a merge-base check instead. If stash is truly unavoidable: verify the push succeeded AND `git stash list` shows YOUR entry at stash@{0} before ever popping, and never `pop` after a failed `push`.
+
+**Applies to:** any git stash usage in Conductor workspaces; /execute and /check-and-commit loops; proving pre-existing test/typecheck failures.
+
## A public SECURITY DEFINER function that calls net.http_post is a remote-DoS surface — put it in an internal schema
**Context:** The push-based event-queue wake (`20260721184852_event-queue-wake.sql`) originally defined `wake_event_queue()` / `sweep_event_queue()` in the `public` schema. Both are SECURITY DEFINER and call `net.http_post` (pg_net) to POST to the `event-wake` edge function. The trigger (`dispatch_event_batch`) and pg_cron call them as the owner (superuser).
@@ -517,3 +527,33 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** (1) Any storage key that embeds a user-controlled filename must pass it through `stripSpecialCharacters` (canonical copy in `@carbon/utils`, re-exported by `~/utils/string` in ERP) with a `|| "file"` fallback for names that sanitize to empty. (2) The share-route path validation (`parseJobFilePath` in `apps/erp/app/utils/supabase.ts`, unit-tested) is coupled to every writer of the `companyId/job/...` prefix — changing an upload path shape requires updating the parser and its test in the same PR. (3) On upload failure, reset the picker UI so the user can retry; never leave a dead-end state.
**Applies to:** all `storage.from(...).upload(...)` call sites in `apps/mes` and `apps/erp`; `share+/customer.$id.$.tsx`; any new externally-shared file route.
+
+## Loader-computed "current unit" must match the component's, or per-unit attribution credits the wrong unit
+
+**Context:** The MES assembly view resolves the unit on screen twice: the loader (`apps/mes/app/routes/x+/assembly.$operationId.tsx`) computes `unitIndex` from `?unit`/`?trackedEntityId`, and `AssemblyView.currentUnitIndex` computes it again client-side. Per-unit material issue attribution (batch parents) was moved into the loader, keyed off the loader's `unitIndex`.
+
+**Problem:** The two defaults diverged. When there's no `?unit` param, `AssemblyView` lands on the NEXT unit still to build (`min(quantityComplete, units.length-1)`) — and the auto-complete effect DELETES `?unit` after finishing a unit — but the loader defaulted `unitIndex` to `0`. So on unit 2 (default landing) the loader attributed unit 1's stamped consumes (`Unit=1`) to the unit-2 view: parts showed `1/1`/`2/1` though nothing was issued to unit 2, and the scan gate (which reads the same values) let the operator Mark done. Serial parents were unaffected (attribution is per-entity, and both default to 0).
+
+**Rule:** When a loader and its component both compute the same "current X" and one feeds data the other renders, their resolution logic — including the no-param default — must be identical. For the assembly loader, mirror `AssemblyView.currentUnitIndex`: index-paged (batch/untracked) parents default to `min(quantityComplete, opQty-1)`, serial parents to `0`. If you make a loader-computed index load-bearing for attribution, re-derive it the exact same way the UI does.
+
+**Applies to:** `apps/mes/app/routes/x+/assembly.$operationId.tsx` (`unitIndex`) ↔ `apps/mes/app/components/AssemblyView.tsx` (`currentUnitIndex`); any loader/component pair where one computes an index the other renders.
+
+## Node-side re-exports from the Deno functions tree must dodge lib/database.ts
+
+**Context:** `@carbon/database` re-exports code from `packages/database/supabase/functions/` into the node world (`src/client.ts` → `lib/postgres/index.ts`). The shared inspection engine (`src/quality.ts`) needed `getNextSequence` from `supabase/functions/shared/get-next-sequence.ts`, which imported its `DB` type from `../lib/database.ts`.
+
+**Problem:** `lib/database.ts` imports `./driver.ts` — the Deno-postgres driver whose types (`queryObject`, deno `Pool`) don't typecheck under the node tsconfig. Pulling any `shared/*.ts` helper that touches `lib/database.ts` into a `src/*` file breaks `pnpm --filter @carbon/database typecheck`, even though the runtime graph would have been fine.
+
+**Rule:** When making a Deno-tree helper importable from `packages/database/src/*`, its type-only imports must come from `../lib/postgres/index.ts` (node-clean, already the `src/client.ts` re-export source), never `../lib/database.ts`. `import type { KyselyDatabase as DB } from "../lib/postgres/index.ts"` is behavior-neutral for Deno. Check the full import chain (`lib/utils.ts` is safe; `lib/database.ts`/`lib/driver.ts` are not) before re-exporting.
+
+**Applies to:** `packages/database/src/{client,sampling,quality}.ts`; any future node-side re-export of `packages/database/supabase/functions/{shared,lib}/*`.
+
+## A zod `.refine` that returns an object instead of a boolean silently disables the check
+
+**Context:** Cross-field validation in module `*.models.ts` zod schemas (real case: `processValidator` in `apps/erp/app/modules/resources/resources.models.ts`, lines 305–319).
+
+**Problem:** `.refine((data) => { if (bad) return { workCenters: ["..."] }; return true; })` looks like it reports a field error, but `.refine`'s callback is coerced to a boolean — any non-empty object is **truthy**, so the "failure" branch returns a value that passes validation. Both `processValidator` refinements (work-center-required and standard-factor-required) never fire: the object was meant to be an error map, but `.refine` has no such API. The schema typechecks and the form submits, so the missing validation is invisible until bad data lands.
+
+**Rule:** A `.refine` predicate must return a **boolean** (`false` = invalid). To attach a path/message, either pass the second `{ message, path }` argument to `.refine` and return `false` on failure, or use `.superRefine((data, ctx) => ctx.addIssue({ path, message }))` when you need per-field errors. Never return an object/array from a `.refine` callback expecting it to be an error map.
+
+**Applies to:** all `apps/erp/app/modules/**/*.models.ts` (and `apps/mes/app/services/models.ts`) zod schemas using `.refine`.
diff --git a/.ai/plans/2026-07-19-step-model-slides.md b/.ai/plans/2026-07-19-step-model-slides.md
new file mode 100644
index 0000000000..96e1ea7723
--- /dev/null
+++ b/.ai/plans/2026-07-19-step-model-slides.md
@@ -0,0 +1,53 @@
+# Step model slides — 3D models (STP → assembler → GLB) alongside pictures in BOP steps + MES assembly view
+
+## Context
+
+The `poc/mes-assembly-view` branch gives BOP steps "slides" (reference pictures with captions/pins) authored in the ERP BOP editors and shown in the MES assembly view. The user wants (a) the assembler service integrated into the BOP step section for parts and jobs, and (b) the MES assembly view to show **3D models (.stp, plus other supported formats) alongside pictures** per step — reversing the earlier "no 3D slides" non-goal in `.ai/specs/implemented/2026-07-14-mes-execution-views.md` §4.
+
+Everything heavy already exists and is reused, not rebuilt:
+
+- `modelUpload` table (modelPath, thumbnailPath, glbPath, graphPath, processingStatus, componentCount) + `/api/model/upload` route (inserts row, fires `model-thumbnail`).
+- Inngest `assembly-convert` task → assembler `POST /convert` (STEP → GLB + graph.json in `private` bucket at `{companyId}/models/{modelUploadId}/{jobId}/`), gated by `isAssemblerServiceHealthy()` (apps/erp/app/modules/production/production.server.ts).
+- `ModelViewer` (`@carbon/react`, online-3d-viewer + three) renders all of `supportedModelTypes` (packages/utils/src/file.ts) client-side, **including step/stp**, in both ERP and MES; MES preview proxy `/file/preview/private/...` already whitelists 3D types.
+- Slide system: `methodOperationStepSlide` / `jobOperationStepSlide` / `quoteOperationStepSlide` tables; `SlidesEditor.tsx` + `BillOfProcess.tsx` (items) + `JobBillOfProcess.tsx` (jobs); `operationStepSlideValidator` (apps/erp/app/modules/shared/shared.models.ts); get-method `copyStepSlides`; MES `getJobOperationProcedure` → `AssemblyView.tsx`.
+
+## Design
+
+A slide becomes **image XOR model**:
+
+- Add nullable `modelUploadId` (FK → `modelUpload` ON DELETE CASCADE) to the three slide tables; relax `imagePath` to nullable; CHECK at least one of the two is set. Annotations/pins remain image-only.
+- ERP step editors get "Add model" beside "Add slide": upload file to `{companyId}/models/{nanoid}.{ext}` in `private`, create `modelUpload` via the existing `/api/model/upload` action, save slide with `modelUploadId`.
+- Assembler integration: in the slide upsert actions (items + job tiers), when the attached model is STEP, `processingStatus` is `Idle`, and the assembler is healthy → `trigger("assembly-convert", { companyId, modelUploadId, userId })`. Non-STEP formats skip conversion.
+- MES assembly view: slide carousel mixes pictures and models. Model slide thumbnail = `modelUpload.thumbnailPath` (cube icon fallback); selected model slide renders `<ModelViewer url={getPrivateUrl(glbPath ?? modelPath)} />` — GLB when converted, raw model otherwise, so the feature degrades gracefully when the assembler is not deployed/running.
+- get-method copy carries `modelUploadId` verbatim (company-scoped row, same pattern as `imagePath`).
+
+## Tasks
+
+1. **Migration** `pnpm db:migrate:new step-model-slides`: for each of the 3 slide tables — add `modelUploadId` TEXT NULL REFERENCES `modelUpload(id)` ON DELETE CASCADE, `imagePath` DROP NOT NULL, CHECK (`imagePath` IS NOT NULL OR `modelUploadId` IS NOT NULL), index on `modelUploadId`. Apply with `pnpm db:migrate`, then `pnpm run generate:types`.
+2. **get-method** (`packages/database/supabase/functions/get-method/index.ts`): `copyStepSlides` select + insert carry `modelUploadId`.
+3. **Validators** (`apps/erp/app/modules/shared/shared.models.ts`): `operationStepSlideValidator` — `imagePath` optional, `modelUploadId` optional; slide services pass the new field through.
+4. **ERP routes**: items + job `operation.step.slide.new.tsx` accept `modelUploadId`; add STEP+Idle+healthy → `trigger("assembly-convert", …)` after upsert.
+5. **ERP UI**: `SlidesEditor.tsx` model-add input (accept `supportedModelTypes`) + model card (thumbnail/name, no Pin); wire upload flow in `BillOfProcess.tsx` (StepSlides + AttributesForm draft) and `JobBillOfProcess.tsx`.
+6. **MES**: `operations.service.ts` `getJobOperationProcedure` embeds `modelUpload(id,name,modelPath,glbPath,thumbnailPath,processingStatus)` on slides; `AssemblyView.tsx` renders model slides via `ModelViewer`, keeps pins/zoom for image slides only.
+7. **Verify**: `pnpm exec turbo run typecheck --filter=erp --filter=mes` (+ `@carbon/database`), `pnpm run lint`; browser-verify with dev stack if running.
+
+## Verification
+
+- Typecheck ERP + MES + database; lint.
+- Manual: in ERP part BOP editor add a `.stp` model slide to a step → row in `methodOperationStepSlide` with `modelUploadId`; with assembler up, `modelUpload.processingStatus` → Processing → Success with `glbPath`. Get method to a job → job slide carries model. MES assembly view for that operation shows the model slide in the carousel and renders it in 3D; picture slides unchanged.
+
+## Status (2026-07-19)
+
+All code tasks implemented. Verified: ERP and MES typechecks match the branch baseline exactly
+(13 / 11 pre-existing errors — broken generated `types.ts` duplicate `invoiceSettlement` from the
+origin merge, missing react-router `+types` artifacts, documents-package drift — none introduced
+by this change); biome diagnostics identical to baseline. Spec §4 updated (non-goal reversed).
+
+**Completed 2026-07-20 (stack up):** migrations applied + types regenerated (bridge-casts
+removed), browser-verified end-to-end in the running ERP + MES. Follow-on work shipped in the
+same branch: Assembly → BOP sync (`20260720025847_assembly-bop-sync.sql`,
+`syncAssemblyInstructionToOperation`, "Sync to BOP" modal), step-aware `AssemblyPlayer`
+playback in the MES assembly view (driven by the `assemblyInstructionStepId` marker), and the
+BOP steps-source panel (`AssemblyStepsSource`) bridging Assembly operations to the assemblies
+module. Still pending: `pnpm lingui:extract` for the two new translated strings
+(Converting…, Failed to upload model) next time translations are filled.
diff --git a/.ai/plans/2026-07-20-work-instructions-refactor.md b/.ai/plans/2026-07-20-work-instructions-refactor.md
new file mode 100644
index 0000000000..63491b333c
--- /dev/null
+++ b/.ai/plans/2026-07-20-work-instructions-refactor.md
@@ -0,0 +1,215 @@
+# Work Instructions Refactor — Implementation Plan
+
+**Date:** 2026-07-20
+**Branch:** `feat/mes-assembly`
+**Author:** planning session with Brad
+
+## Execution status (2026-07-20)
+
+Both workstreams **implemented in the working tree (uncommitted, per no-auto-commit)**.
+
+- **Workstream A** — migration `20260721014248_assembly-select-employee-role.sql` authored. Verified via rolled-back psql txn: before = `production_view`, after = `get_companies_with_employee_role()` on all 8 tables; clean apply, rolled back (not persisted — awaits `pnpm db:migrate`/deploy). Writes untouched; no type delta.
+- **Workstream B** — full relocation done (`git mv` preserves history). Gates: `turbo typecheck --filter=erp` clean, Biome clean, relocated `inspectionDocumentSave.test.ts` 2/2 pass, grep sweep for stale quality inspection imports empty. Two move-induced fixes applied beyond the plan: list-route breadcrumb `Quality`→`Inspection Documents`, and stale `/api/quality/...` doc-comments → `/api/production/...`.
+- **Remaining:** browser verification (Brad is handling) + commit (awaiting explicit go).
+
+## Goal
+
+Consolidate Carbon's three "work instruction" features under **Production → Work Instructions**:
+
+1. **Assembly Instructions** — already in Production + already in the Work Instructions group. Only change: normalize their RLS `SELECT` policy.
+2. **Procedures** — already in Production + already in the Work Instructions group. **No change.**
+3. **Inspection Documents** — currently in the `quality` module. **Relocate the code + list/create routes into the `production` module** and surface it in the Work Instructions group, while keeping its `quality_*` permissions and RLS.
+
+## Decisions (locked)
+
+- **Assembly RLS:** writes are already `production_*` (no change). The 8 older `assembly*` tables gate `SELECT` on the `production_view` **permission**, while the feature's newer MES step/slide tables and the sibling `procedure` table gate `SELECT` on `get_companies_with_employee_role()`. **Normalize the 8 `assembly*` tables' `SELECT` to `get_companies_with_employee_role()`** (any employee can read) via a fix-forward migration. This is a deliberate *loosening* of read for consistency.
+- **Inspection Documents:** **move everything** (service fns, validators, server/db helpers, UI, types) into `modules/production/`. Keep `requirePermissions(..., "quality")` and the `quality_*` RLS unchanged. Menu entry gated on `quality_view`.
+
+## Non-goals / stays put
+
+- **Inbound Inspections** and the AQL sampling plan (`itemSamplingPlan`, `inboundInspection*`, `samplingStandards.ts`) — stay in `quality`.
+- Inspection **table RLS / permission strings** — unchanged (`quality_*`).
+- Assembly **write** policies (`production_create/update/delete`) — unchanged.
+- The neutral full-screen editor URL namespace `/x/inspection/$id` — unchanged (mirrors `/x/assembly/$id`, `/x/procedure/$id`).
+- `PLAN_VERSION` / planner heuristics — untouched.
+
+---
+
+## Workstream A — Assembly `SELECT` policy normalization
+
+All 8 target tables are already on `origin/main` (applied) → **new fix-forward migration**, not an in-place edit. `DROP POLICY IF EXISTS` + `CREATE POLICY` (idempotent). Recreate in the canonical style (schema-qualified, `(SELECT …)`-wrapped, `::text[]`). **Leave INSERT/UPDATE/DELETE untouched.**
+
+Target tables (SELECT only):
+`assemblyPlanJob`, `assemblyInstruction`, `assemblyInstructionStep`, `assemblyInstructionStepRequirement`, `assemblyStandardNote`, `assemblyInstructionStepMaterial`, `assemblyUnit`, `assemblyComponentMapping`.
+
+### A1. Create the migration
+
+```bash
+pnpm db:migrate:new assembly-select-employee-role
+```
+(generates a properly-timestamped file — do **not** hand-pick `HHMMSS`; the generator randomizes.)
+
+Body (repeat the block for each of the 8 tables):
+
+```sql
+-- Normalize assembly* SELECT policies from the production_view permission to
+-- get_companies_with_employee_role(), matching the procedure table and the
+-- feature's own newer MES step/slide tables. Writes stay production_*.
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstruction";
+CREATE POLICY "SELECT" ON "public"."assemblyInstruction"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+-- … assemblyPlanJob, assemblyInstructionStep, assemblyInstructionStepRequirement,
+-- assemblyStandardNote, assemblyInstructionStepMaterial, assemblyUnit,
+-- assemblyComponentMapping — same DROP/CREATE, same USING clause.
+```
+
+**Verify:** `pnpm run generate:types` (no type delta expected — RLS-only), then the DB `SELECT` policy set for `assemblyInstruction` shows `get_companies_with_employee_role()` in its `qual`. Optional: validate via rolled-back psql txn (`supabase_admin` + `BEGIN … \i … ROLLBACK`) per the migration-rollback-validation approach — do **not** rebuild the DB.
+
+**Expected:** every `assembly*` table's `SELECT` now uses `employee_role`; a shop-floor employee without `production_view` can read assembly instructions + steps + slides consistently.
+
+---
+
+## Workstream B — Relocate Inspection Documents to `production`
+
+`~/modules/quality/*` → `~/modules/production/*`. Do it in this order so the compiler guides you.
+
+### B1. Move the standalone feature files (git mv, verbatim)
+
+```
+apps/erp/app/modules/quality/inspectionDocumentDb.ts → apps/erp/app/modules/production/inspectionDocumentDb.ts
+apps/erp/app/modules/quality/inspectionDocumentSave.server.ts → apps/erp/app/modules/production/inspectionDocumentSave.server.ts
+apps/erp/app/modules/quality/inspectionDocumentSave.test.ts → apps/erp/app/modules/production/inspectionDocumentSave.test.ts
+apps/erp/app/modules/quality/inspectionBalloonAnalyze.ts → apps/erp/app/modules/production/inspectionBalloonAnalyze.ts
+apps/erp/app/modules/quality/inspectionBalloonAnalyze.server.ts → apps/erp/app/modules/production/inspectionBalloonAnalyze.server.ts
+apps/erp/app/modules/quality/ui/InspectionDocument/ → apps/erp/app/modules/production/ui/InspectionDocument/ (all 6 files)
+```
+
+Internal relative imports (`./inspectionDocumentDb`, `./inspectionBalloonAnalyze`, `./cropInspectionAnchorToPng`, `./exportInspectionDocumentPdfWithOverlays`) stay valid after the move. What breaks and must be repointed to `~/modules/production/...`:
+- `inspectionDocumentSave.server.ts` → imports the `inspectionSave*PayloadValidator`s from `./quality.models` → change to `./production.models` (after B3).
+- `ui/InspectionDocument/InspectionDocumentForm.tsx:14` → `inspectionDocumentValidator` from `~/modules/quality/quality.models` → `~/modules/production/production.models`.
+- `ui/InspectionDocument/InspectionDocumentEditor.tsx:47` → `BalloonRegionAnalysis` from `~/modules/quality/inspectionBalloonAnalyze` → `~/modules/production/inspectionBalloonAnalyze`.
+
+### B2. Move service functions `quality.service.ts` → `production.service.ts`
+
+Move these functions (they carry the whole inspection-document read/write surface):
+`getInspectionDocuments`, `getInspectionDocument`, `getBalloons`, `getInspectionFeatures`, `getInspectionPlan`, `upsertInspectionDocument`, `deleteInspectionDocument`, `saveInspectionDocumentAtomic`.
+
+Also move the supporting line from `quality.service.ts`:
+```ts
+import { listBalloons, listInspectionFeatures, mapBalloonIdsToFeatureIdsForDocument } from "./inspectionDocumentDb";
+export { mapBalloonIdsToFeatureIdsForDocument };
+```
+→ into `production.service.ts` (relative path still `./inspectionDocumentDb` since that file also moved to production).
+
+**Watch:** confirm no other quality-internal helper is referenced by the moved functions; if one is, either it's a shared util (leave the import path as `~/...`) or it must move too. `getInboundInspections` and everything below it in `quality.service.ts` **stays**.
+
+### B3. Move validators `quality.models.ts` → `production.models.ts`
+
+Cut `quality.models.ts` lines **106–371** (from `inspectionDocumentValidator` through `inspectionSaveAnchorsPayloadValidator`, incl. the non-exported `normalizedCoordinateValidator`/`normalizedSizeValidator`/`pageNumberValidator` helpers at 164–166) into `production.models.ts`. `gaugeValidator` (line 373) onward **stays** in quality.
+
+These validators use `procedureStepType`. `production.models.ts` **already imports `procedureStepType`** (procedures use it) — reuse it; do **not** add a duplicate import. After cutting, `quality.models.ts` may no longer need `import { procedureStepType } from "../shared/shared.models"` — remove it there only if nothing else in the file uses it.
+
+### B4. Split the types `quality/types.ts` → `production/types.ts`
+
+Move the inspection-document type block (`InspectionDocument`, `InspectionDocumentDetail`, `Balloon`, `InspectionFeature`, `BalloonFeature`, `InspectionDocumentContent` — the `Awaited<ReturnType<…>>` derivations of the moved service fns, ~lines 31–60) into `production/types.ts`, repointing the `getBalloons/getInspectionDocument/getInspectionDocuments/getInspectionFeatures` imports to `./production.service`. Inbound-inspection types (~172–198) **stay** in `quality/types.ts`.
+
+### B5. Barrels
+
+- `apps/erp/app/modules/quality/index.ts` — **delete** line 1 `export * from "./inspectionBalloonAnalyze";`.
+- `apps/erp/app/modules/production/index.ts` — **add** `export * from "./inspectionBalloonAnalyze";`.
+- Create `apps/erp/app/modules/production/ui/InspectionDocument/index.ts` (copy of the quality one):
+ ```ts
+ export { default as InspectionDocumentForm } from "./InspectionDocumentForm";
+ export { default as InspectionDocumentTable } from "./InspectionDocumentTable";
+ ```
+ (Editor is intentionally **not** barrel-exported — SSR/`canvas` issue; keep the deep lazy import.)
+- Delete the old `apps/erp/app/modules/quality/ui/InspectionDocument/index.ts`.
+
+### B6. Move + repoint the list/create routes (URL changes to `/x/production/…`)
+
+```
+apps/erp/app/routes/x+/quality+/inspection.tsx → apps/erp/app/routes/x+/production+/inspection.tsx
+apps/erp/app/routes/x+/quality+/inspection.new.tsx → apps/erp/app/routes/x+/production+/inspection.new.tsx
+```
+In both: repoint `~/modules/quality*` imports → `~/modules/production*`. **Keep** `requirePermissions(request, { view: "quality", role: "employee" })` unchanged (verified safe — `production+/_layout.tsx` has no loader/permission gate, so the leaf's quality gate is the only check; a quality-only user passes and sees the Production sidebar).
+
+### B7. Repoint the editor + delete/save/update-name routes (URLs unchanged)
+
+These stay at `/x/inspection/$id…` (neutral namespace) — only fix imports:
+- `x+/inspection+/$id.tsx` — `getBalloons/getInspectionDocument/getInspectionFeatures` + `InspectionDocumentContent` type + the `lazy(() => import("~/modules/quality/ui/InspectionDocument/InspectionDocumentEditor"))` deep path → `~/modules/production/...`.
+- `x+/inspection+/$id.save.tsx` — `saveInspectionDocumentAtomic`, the `inspectionDocumentSave.server` helpers, and the `inspectionSave*Validator`s → `~/modules/production/...`.
+- `x+/inspection+/$id.delete.tsx` — `deleteInspectionDocument` → `~/modules/production`.
+- `x+/inspection+/$id.update-name.tsx` — no module import (inline table write); no change beyond confirming it still gates `update: "quality"`.
+
+### B8. API routes
+
+- `api+/quality.inspection-document.$inspectionDocumentId.balloon-analyze.ts` → rename to `api+/production.inspection-document.$inspectionDocumentId.balloon-analyze.ts` (internal POST, single caller). Repoint its 3 imports to `~/modules/production/...`. URL becomes `/api/production/inspection-document/:id/balloon-analyze`.
+- `api+/quality.inspection-plan.$id.ts` — **keep the URL** `/api/quality/inspection-plan/:id` (decided — leave as-is). It has no in-app caller and no `path.to` key, i.e. it is a raw-URL API likely consumed by an external/MES/assembler client; renaming would be a breaking change. **Do NOT rename the file** — only repoint its `getInspectionDocument, getInspectionPlan` imports to `~/modules/production`.
+
+### B9. `apps/erp/app/utils/path.ts`
+
+| Key | Change |
+|---|---|
+| `inspectionDocuments` (L1127) | `/x/quality/inspection` → `/x/production/inspection` |
+| `newInspectionDocument` (L1422) | `/x/quality/inspection/new` → `/x/production/inspection/new` |
+| `api.inspectionDocumentBalloonAnalyze` (L87–90) | `/api/quality/inspection-document/${id}/balloon-analyze` → `/api/production/inspection-document/${id}/balloon-analyze` |
+| `inspectionDocument` (L1126), `saveInspectionDocument` (L1902), `updateInspectionDocumentName` (L2087), `deleteInspectionDocument` (L628) | **unchanged** (`/x/inspection/${id}…`) |
+
+Then update the single caller of the balloon-analyze helper if the helper name/shape changed — `InspectionDocumentEditor.tsx:1185` `path.to.api.inspectionDocumentBalloonAnalyze(diagramId)` (name unchanged, only the produced URL changes → no code edit needed there).
+
+### B10. Hard cutover — no redirect (decided)
+
+**Hard cutover.** The old `/x/quality/inspection` (and `/x/quality/inspection/new`) URLs are retired outright — do **not** leave a redirect stub. After B6 removes those route files from `x+/quality+/`, the old paths 404; the Production → Work Instructions menu is the only entry point. Nothing in-app links to the old URLs (only `path.to.inspectionDocuments`/`newInspectionDocument`, both repointed in B9).
+
+### B11. Menus
+
+**`apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx`:**
+- Remove the "Inspection Documents" route object from the "Inspection" group (leaves only "Inbound Inspections").
+- Remove now-unused `import { IoBalloonOutline } from "react-icons/io5";`.
+- Keep the group named "Inspection" (single item). (Optional rename deferred.)
+
+**`apps/erp/app/modules/production/ui/useProductionSubmodules.tsx`:**
+- Add the permission gate to `isRouteVisible`:
+ ```tsx
+ if (route.permission && !permissions.can("view", route.permission)) return false;
+ ```
+- Add to the **Work Instructions** group's `routes` (alongside Assemblies + Procedures):
+ ```tsx
+ {
+ name: t`Inspection Documents`,
+ to: path.to.inspectionDocuments,
+ icon: <IoBalloonOutline />,
+ permission: "quality"
+ }
+ ```
+- Add `import { IoBalloonOutline } from "react-icons/io5";`.
+
+---
+
+## Verification (run after each workstream; final full pass at the end)
+
+1. `pnpm run generate:types` — after Workstream A's migration. Regenerate + commit `types.ts` (types regen is normal).
+2. `pnpm exec turbo run typecheck --filter=@carbon/erp` — scoped typecheck (confirm the exact filter name from `apps/erp/package.json`; **never** whole-repo typecheck — OOM). Expect zero errors; the compiler surfaces any missed import repoint.
+3. `pnpm run lint` — Biome.
+4. `pnpm run test` — must pick up the moved `inspectionDocumentSave.test.ts` at its new path and pass.
+5. Grep sweep — confirm **zero** remaining `~/modules/quality/inspection`, `~/modules/quality/inspectionBalloonAnalyze`, `~/modules/quality/inspectionDocument`, or quality-module inspection-symbol imports anywhere in `apps/erp`.
+6. `/translate` — if any UI/locale strings changed (new `t\`Inspection Documents\`` in production submodules — the msgid already exists, so likely nothing to fill).
+7. **Browser e2e (mandatory for the UI change)** — `crbn up`, `/auth`, `/test`: (a) Production sidebar shows **Work Instructions → Inspection Documents**; (b) it opens `/x/production/inspection` rendering the **Production** sidebar; (c) create/edit/save/delete an inspection document still works end-to-end; (d) the item is **hidden** for a user without `quality_view`; (e) Quality's "Inspection" group now shows only Inbound Inspections. Capture screenshots for the PR (net-new/surface change).
+
+## Risks & flags
+
+- **`inspection-plan.$id` external consumer** — **decided: leave URL-stable** (B8). Not renamed to `production.*`; only its imports move.
+- **Hard cutover on old inspection URLs** — **decided** (B10): no redirect; `/x/quality/inspection` retires. Acceptable because nav is menu-driven and no in-app link targets the literal old path.
+- **Permission/folder mismatch (intentional)** — moved production-module files call `requirePermissions(… "quality")`. Consistent with the `quality_*` table RLS; documented here so it's not mistaken for a bug.
+- **`production.service.ts` / `production.models.ts` growth** — these already-large files gain the inspection surface. Acceptable per "move everything"; keep the moved blocks contiguous and clearly sectioned.
+- **Redirect vs hard cutover** (B10) — decide whether stale `/x/quality/inspection` bookmarks must keep working.
+- **Docs/glossary** — check `packages/glossary/src/terms.ts` (already modified on this branch) + curated docs for any "Inspection Document" module association that should now read "Production"; update to keep docs in sync.
+
+## Commit / PR
+
+- Two logical commits (Workstream A migration; Workstream B relocation) on `feat/mes-assembly`, or split into a follow-up PR — Brad's call. No auto-commit; commit only on explicit ask via the check-and-commit gate.
+- PR surfaces the design change (feature moved modules) + browser screenshots.
diff --git a/.ai/plans/2026-07-21-inbound-inspection-execution.md b/.ai/plans/2026-07-21-inbound-inspection-execution.md
new file mode 100644
index 0000000000..6dc092ed88
--- /dev/null
+++ b/.ai/plans/2026-07-21-inbound-inspection-execution.md
@@ -0,0 +1,692 @@
+# Inbound Inspection Execution — implementation plan
+
+**Spec:** .ai/specs/implemented/2026-07-21-inbound-inspection-execution.md
+**Research:** .ai/research/inbound-inspection-execution.md
+**Branch:** feat/mes-assembly
+
+## Progress
+- [x] Task 1: Create the migration (enum, tables, columns, RPC fork)
+- [x] Task 2: Apply migration + regenerate types
+- [x] Task 3: Per-feature sampling resolution in both engine copies + unit test
+- [x] Task 4: Zod validators + row/type extensions
+- [x] Task 5: post-receipt — attach document + per-feature plan rows
+- [x] Task 6: quality.service reads + assignment upsert
+- [x] Task 7: quality.server — measurement upsert, derived status, reconcile, disposition gating
+- [x] Task 8: Route tree x+/inbound-inspection+ + path.ts
+- [x] Task 9: InspectionDrawingPane (read-only PDF + balloons)
+- [x] Task 10: InspectionMeasurementGrid (features × samples)
+- [x] Task 11: InboundInspectionView wiring + fallback + drawer retirement
+- [x] Task 12: Item Quality tab — documents card + assignments card (4 routes)
+- [x] Task 13: Reject NCR enrichment (failed-feature table)
+- [x] Task 14: Docs sync (rule + AGENTS.md)
+- [ ] Task 15: Browser verification (/test)
+
+## Dependencies
+- Task 2 needs Task 1. Task 3 is independent (can run parallel with 1–2).
+- Task 4 needs Task 2 (generated types). Task 5 needs Tasks 2 + 3.
+- Tasks 6, 7 need Tasks 2 + 4 (7 also uses 3's helper via app copy import in tests only — runtime valuation is local math).
+- Task 8 needs 6 + 7. Task 9 needs nothing DB-side (props only). Task 10 needs 4 + 6 types.
+- Task 11 needs 8 + 9 + 10. Task 12 needs 4 + 6. Task 13 needs 7.
+- Tasks 14, 15 last. Tasks 9 and 12 are independent of each other and of 5–8; parallelizable.
+
+---
+
+## Task 1: Create the migration (enum, tables, columns, RPC fork)
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_inbound-inspection-execution.sql` (via `pnpm db:migrate:new inbound-inspection-execution` — never hand-pick the timestamp; the generated HHMMSS must not be `000000`)
+- Copy from (precedent): `packages/database/supabase/migrations/20260419163058_inbound-inspection-sampling.sql` (table + RLS style for the inbound family), `packages/database/supabase/migrations/20260526142837_inspection-feature-type.sql` (newest `save_inspection_document_atomic` definition to fork)
+
+**Steps:**
+1. Run `pnpm db:migrate:new inbound-inspection-execution`. Confirm the generated filename's HHMMSS portion is not `000000`; if it is, rename the file changing only HHMMSS to a random value.
+2. Write the SQL below into the file. Notes on conventions used: the inbound-inspection family uses **PK ("id")** (not composite) and RLS SELECT tightened to `quality_view` — follow it exactly. NUMERIC columns carry **no precision**. `inspectionDocument`/`inspectionFeature` have `UNIQUE("id")` constraints, so single-column FKs to them are valid.
+
+```sql
+-- Inbound inspection execution: document assignment, per-feature sampling,
+-- per-lot feature plans, per-sample measurements.
+
+-- 1) Usage enum (extensible: 'FAI', 'Production' later)
+DO $$ BEGIN
+ CREATE TYPE "inspectionDocumentUsage" AS ENUM ('Receipt');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 2) Item-level document assignment per usage slot
+CREATE TABLE IF NOT EXISTS "itemInspectionDocumentAssignment" (
+ "itemId" TEXT NOT NULL,
+ "usage" "inspectionDocumentUsage" NOT NULL,
+ "inspectionDocumentId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "itemInspectionDocumentAssignment_pkey" PRIMARY KEY ("itemId", "usage"),
+ CONSTRAINT "itemInspectionDocumentAssignment_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_inspectionDocumentId_fkey" FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "itemInspectionDocumentAssignment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX IF NOT EXISTS "itemInspectionDocumentAssignment_companyId_idx" ON "itemInspectionDocumentAssignment" ("companyId");
+CREATE INDEX IF NOT EXISTS "itemInspectionDocumentAssignment_inspectionDocumentId_idx" ON "itemInspectionDocumentAssignment" ("inspectionDocumentId");
+
+ALTER TABLE "itemInspectionDocumentAssignment" ENABLE ROW LEVEL SECURITY;
+
+DO $$ BEGIN
+ CREATE POLICY "SELECT" ON "itemInspectionDocumentAssignment"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_view'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "INSERT" ON "itemInspectionDocumentAssignment"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_create'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "UPDATE" ON "itemInspectionDocumentAssignment"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_update'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "DELETE" ON "itemInspectionDocumentAssignment"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_delete'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 3) Per-feature sampling rule (nullable = inherit itemSamplingPlan)
+ALTER TABLE "inspectionFeature"
+ ADD COLUMN IF NOT EXISTS "samplingPlanType" "samplingPlanType",
+ ADD COLUMN IF NOT EXISTS "samplingSampleSize" INTEGER,
+ ADD COLUMN IF NOT EXISTS "samplingPercentage" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingAql" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingInspectionLevel" "inspectionLevel",
+ ADD COLUMN IF NOT EXISTS "samplingSeverity" "inspectionSeverity";
+
+-- 4) Lot → document live reference
+ALTER TABLE "inboundInspection"
+ ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+
+DO $$ BEGIN
+ ALTER TABLE "inboundInspection"
+ ADD CONSTRAINT "inboundInspection_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+CREATE INDEX IF NOT EXISTS "inboundInspection_inspectionDocumentId_idx" ON "inboundInspection" ("inspectionDocumentId");
+
+-- 5) Per-lot per-feature resolved sampling plan
+CREATE TABLE IF NOT EXISTS "inboundInspectionFeature" (
+ "id" TEXT NOT NULL DEFAULT id('iif'),
+ "inboundInspectionId" TEXT NOT NULL,
+ "inspectionFeatureId" TEXT NOT NULL,
+ "sampleSize" INTEGER NOT NULL,
+ "acceptanceNumber" INTEGER NOT NULL,
+ "rejectionNumber" INTEGER NOT NULL,
+ "codeLetter" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+
+ CONSTRAINT "inboundInspectionFeature_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionFeature_unique" UNIQUE ("inboundInspectionId", "inspectionFeatureId"),
+ CONSTRAINT "inboundInspectionFeature_inboundInspectionId_fkey" FOREIGN KEY ("inboundInspectionId") REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionFeature_inspectionFeatureId_fkey" FOREIGN KEY ("inspectionFeatureId") REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionFeature_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionFeature_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_companyId_idx" ON "inboundInspectionFeature" ("companyId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_inboundInspectionId_idx" ON "inboundInspectionFeature" ("inboundInspectionId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_inspectionFeatureId_idx" ON "inboundInspectionFeature" ("inspectionFeatureId");
+
+ALTER TABLE "inboundInspectionFeature" ENABLE ROW LEVEL SECURITY;
+
+-- RLS: same four policies as itemInspectionDocumentAssignment above, with
+-- quality_view / quality_create / quality_update / quality_delete. Copy the
+-- four DO-blocks, changing only the table name.
+
+-- 6) Per sample × feature measurement
+CREATE TABLE IF NOT EXISTS "inboundInspectionMeasurement" (
+ "id" TEXT NOT NULL DEFAULT id('iim'),
+ "inboundInspectionId" TEXT NOT NULL,
+ "inboundInspectionSampleId" TEXT NOT NULL,
+ "inspectionFeatureId" TEXT NOT NULL,
+ "value" NUMERIC,
+ "status" "inboundInspectionSampleStatus" NOT NULL DEFAULT 'Pending',
+ "notes" TEXT,
+ "inspectedBy" TEXT,
+ "inspectedAt" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "inboundInspectionMeasurement_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionMeasurement_unique" UNIQUE ("inboundInspectionSampleId", "inspectionFeatureId"),
+ CONSTRAINT "inboundInspectionMeasurement_inboundInspectionId_fkey" FOREIGN KEY ("inboundInspectionId") REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_sampleId_fkey" FOREIGN KEY ("inboundInspectionSampleId") REFERENCES "inboundInspectionSample"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_inspectionFeatureId_fkey" FOREIGN KEY ("inspectionFeatureId") REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_inspectedBy_fkey" FOREIGN KEY ("inspectedBy") REFERENCES "user"("id"),
+ CONSTRAINT "inboundInspectionMeasurement_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "inboundInspectionMeasurement_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_companyId_idx" ON "inboundInspectionMeasurement" ("companyId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_inboundInspectionId_idx" ON "inboundInspectionMeasurement" ("inboundInspectionId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_sampleId_idx" ON "inboundInspectionMeasurement" ("inboundInspectionSampleId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_inspectionFeatureId_idx" ON "inboundInspectionMeasurement" ("inspectionFeatureId");
+
+ALTER TABLE "inboundInspectionMeasurement" ENABLE ROW LEVEL SECURITY;
+
+-- RLS: same four DO-block policies again (quality_view/create/update/delete).
+```
+
+3. Write the four RLS DO-blocks for `inboundInspectionFeature` and the four for `inboundInspectionMeasurement` exactly like the `itemInspectionDocumentAssignment` set (only the table name changes).
+4. **Fork the RPC.** Extract the newest `save_inspection_document_atomic` body verbatim:
+ ```bash
+ grep -rln "save_inspection_document_atomic" packages/database/supabase/migrations/ | sort | tail -1
+ # Expected: .../20260526142837_inspection-feature-type.sql (verify; if a newer file appears, fork THAT one)
+ sed -n '/CREATE OR REPLACE FUNCTION/,$p' packages/database/supabase/migrations/20260526142837_inspection-feature-type.sql > /tmp/rpc-fork.sql
+ ```
+ Append to the migration: `DROP FUNCTION IF EXISTS save_inspection_document_atomic;` (match the exact signature from the source file if Postgres complains about ambiguity), then the copied `CREATE OR REPLACE FUNCTION` with exactly two edits, preserving everything else byte-for-byte (diff against the source to prove only these changed):
+ - In the `inspectionFeature` **create** INSERT: add columns `"samplingPlanType", "samplingSampleSize", "samplingPercentage", "samplingAql", "samplingInspectionLevel", "samplingSeverity"` and the corresponding value expressions reading the JSONB item keys `samplingPlanType` (`::"samplingPlanType"`, `NULLIF(item->>'samplingPlanType','')`), `samplingSampleSize` (`::integer`), `samplingPercentage` (`::numeric`), `samplingAql` (`::numeric`), `samplingInspectionLevel` (`::"inspectionLevel"`), `samplingSeverity` (`::"inspectionSeverity"`) — all NULL when absent.
+ - In the **update** branch: add the same six columns to the SET list with the same JSONB extraction, only overwriting when the key is present (follow how the existing optional keys in that function handle presence; if it overwrites unconditionally for other columns, do the same for consistency).
+5. If the assumption that `20260526142837` is the newest RPC definition turns out false (grep finds a newer file), fork from the newer file instead; if the function body structure differs materially from what Step 4 describes, STOP and report — do not improvise.
+
+**Verify:**
+```bash
+ls packages/database/supabase/migrations/ | tail -3
+# Expected: the new <timestamp>_inbound-inspection-execution.sql is the newest file, timestamp > 20260721170301
+grep -c "CREATE POLICY" packages/database/supabase/migrations/*inbound-inspection-execution.sql
+# Expected: 12 (4 policies × 3 new tables)
+```
+
+**Out of scope:** seeding data; touching `itemSamplingPlan`; editing any applied migration.
+
+---
+
+## Task 2: Apply migration + regenerate types
+
+**Depends on:** Task 1
+**Files:**
+- Modify (generated): `packages/database/src/types.ts`, `packages/database/src/swagger-docs-schema.ts`
+
+**Steps:**
+1. Run `pnpm db:migrate` (applies pending migrations to the local DB and regenerates types + swagger). If the local DB is unreachable, STOP and report — do not attempt to rebuild the database.
+
+**Verify:**
+```bash
+grep -c "itemInspectionDocumentAssignment\|inboundInspectionFeature\|inboundInspectionMeasurement" packages/database/src/types.ts
+# Expected: a number > 10 (all three tables present in generated types)
+grep "inspectionDocumentUsage" packages/database/src/types.ts | head -2
+# Expected: the enum with "Receipt"
+```
+
+**Out of scope:** hand-editing generated types.
+
+---
+
+## Task 3: Per-feature sampling resolution in both engine copies + unit test
+
+**Depends on:** none (parallel with 1–2)
+**Files:**
+- Modify: `apps/erp/app/modules/quality/samplingStandards.ts` — add `resolveFeatureSamplingPlan`
+- Modify: `packages/database/supabase/functions/shared/sampling-engine.ts` — add the identical function
+- Create: `apps/erp/app/modules/quality/samplingStandards.test.ts` (if a test file already exists, extend it)
+
+**Steps:**
+1. In `samplingStandards.ts`, below `resolveSamplingPlan` (L881), add and export:
+ ```ts
+ export type FeatureSamplingRule = {
+ samplingPlanType?: SamplingPlanType | null;
+ samplingSampleSize?: number | null;
+ samplingPercentage?: number | null;
+ samplingAql?: number | null;
+ samplingInspectionLevel?: InspectionLevel | null;
+ samplingSeverity?: InspectionSeverity | null;
+ };
+
+ export function resolveFeatureSamplingPlan(
+ feature: FeatureSamplingRule | null | undefined,
+ itemPlan: SamplingPlanInput | null | undefined,
+ lotSize: number,
+ standard: SamplingStandard
+ ): SamplingResult {
+ const plan: SamplingPlanInput = feature?.samplingPlanType
+ ? {
+ type: feature.samplingPlanType,
+ sampleSize: feature.samplingSampleSize ?? undefined,
+ percentage: feature.samplingPercentage ?? undefined,
+ aql: feature.samplingAql ?? undefined,
+ inspectionLevel: feature.samplingInspectionLevel ?? undefined,
+ severity: feature.samplingSeverity ?? undefined,
+ }
+ : itemPlan ?? { type: "All" };
+ return resolveSamplingPlan(plan, lotSize, standard);
+ }
+ ```
+2. Add the byte-equivalent function (adjusting only the type-import style to the edge file's inline-union types) to `sampling-engine.ts`, exported. Update the header comment noting both files must stay in sync.
+3. Write `samplingStandards.test.ts` (vitest, mirror the import style of `apps/erp/app/modules/production/inspectionDocumentSave.test.ts`) covering: feature rule present (AQL) overrides item plan; feature rule absent falls back to item plan (Percentage); both absent falls back to `All` (sampleSize === lotSize, acceptance 0); First-N clamps to lot size.
+
+**Verify:**
+```bash
+pnpm --filter=erp test -- samplingStandards
+# Expected: new tests pass (4+ passing, 0 failing)
+```
+
+**Out of scope:** changing `resolveSamplingPlan` itself or the AQL tables.
+
+---
+
+## Task 4: Zod validators + row/type extensions
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/quality/quality.models.ts` — new validators + const
+- Modify: `apps/erp/app/modules/quality/types.ts` — derived types
+- Modify: `apps/erp/app/modules/production/inspectionDocumentDb.ts` — extend `InspectionFeatureRow`
+- Modify: `apps/erp/app/modules/production/production.models.ts` — extend the feature-save payload validator
+
+**Steps:**
+1. `quality.models.ts` — add next to the inbound validators (L487+):
+ ```ts
+ export const inspectionDocumentUsages = ["Receipt"] as const;
+
+ export const itemInspectionDocumentAssignmentValidator = z.object({
+ itemId: z.string().min(1, { message: "Item is required" }),
+ usage: z.enum(inspectionDocumentUsages),
+ inspectionDocumentId: zfd.text(z.string().optional()), // empty = clear the slot
+ });
+
+ export const inboundInspectionMeasurementValidator = z.object({
+ inspectionId: z.string().min(1, { message: "Inspection is required" }),
+ sampleId: zfd.text(z.string().optional()), // absent = create anonymous sample (non-serial columns)
+ inspectionFeatureId: z.string().min(1, { message: "Feature is required" }),
+ value: zfd.text(z.string().optional()), // numeric string for Measurement features; empty clears
+ passed: zfd.text(z.enum(["true", "false"]).optional()), // attribute features only
+ notes: zfd.text(z.string().optional()),
+ });
+ ```
+ Also change `inboundInspectionSampleValidator.status` to `z.enum(["Pending", "Passed", "Failed"])` (adding `"Pending"`) so the identify-only scan flow (Task 11) can create a Pending sample; existing pass/fail submissions keep working.
+2. `quality.types.ts` (`apps/erp/app/modules/quality/types.ts`) — add after the existing inbound types:
+ ```ts
+ export type InboundInspectionFeature = NonNullable<
+ Awaited<ReturnType<typeof getInboundInspectionFeatures>>["data"]
+ >[number];
+ export type InboundInspectionMeasurement = NonNullable<
+ Awaited<ReturnType<typeof getInboundInspectionMeasurements>>["data"]
+ >[number];
+ export type ItemInspectionDocumentAssignment =
+ Database["public"]["Tables"]["itemInspectionDocumentAssignment"]["Row"];
+ ```
+ (Import the two service functions from `../quality.service` in the same style the file already uses. This compiles only after Task 6 adds them — if executing tasks strictly in order, add these two `Awaited<...>` types during Task 6 instead and only the `ItemInspectionDocumentAssignment` row type here.)
+3. `inspectionDocumentDb.ts` — add to `InspectionFeatureRow`: `samplingPlanType: Database["public"]["Enums"]["samplingPlanType"] | null; samplingSampleSize: number | null; samplingPercentage: number | null; samplingAql: number | null; samplingInspectionLevel: Database["public"]["Enums"]["inspectionLevel"] | null; samplingSeverity: Database["public"]["Enums"]["inspectionSeverity"] | null;`.
+4. `production.models.ts` — find `inspectionSaveFeaturesPayloadValidator`; add the six optional sampling keys to both the `create` and `update` item schemas: `samplingPlanType: z.enum(["All","First","Percentage","AQL"]).nullable().optional()`, `samplingSampleSize: z.number().int().positive().nullable().optional()`, `samplingPercentage: z.number().positive().max(100).nullable().optional()`, `samplingAql: z.number().positive().nullable().optional()`, `samplingInspectionLevel: z.enum(["I","II","III","S1","S2","S3","S4"]).nullable().optional()`, `samplingSeverity: z.enum(["Normal","Tightened","Reduced"]).nullable().optional()`. If the validator uses a shared item schema for create/update, edit it once. If the payload validator strips unknown keys elsewhere before reaching the RPC, STOP and report.
+5. Export the new quality validators/const from the module barrel if `index.ts` enumerates exports explicitly (check `apps/erp/app/modules/quality/index.ts`; mirror how `inboundInspectionSampleValidator` is exported).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0 (note: quality types referencing Task 6 functions may be deferred to Task 6 as described)
+```
+
+**Out of scope:** UI components; service functions.
+
+---
+
+## Task 5: post-receipt — attach document + per-feature plan rows
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Modify: `packages/database/supabase/functions/post-receipt/index.ts`
+
+**Steps:**
+1. In the parallel load block (~L108–142), add two loads for receipt items: `itemInspectionDocumentAssignment` rows (`.from("itemInspectionDocumentAssignment").select("itemId, inspectionDocumentId").eq("companyId", companyId).eq("usage", "Receipt").in("itemId", itemIds)`) and, for the assigned document ids, their features: `.from("inspectionFeature").select("id, inspectionDocumentId, type, samplingPlanType, samplingSampleSize, samplingPercentage, samplingAql, samplingInspectionLevel, samplingSeverity").in("inspectionDocumentId", assignedDocumentIds)`. Build `assignmentByItemId` and `featuresByDocumentId` Maps.
+2. Import `resolveFeatureSamplingPlan` from `../shared/sampling-engine.ts`.
+3. In the build block (~L663–711): for each line that gets an inspection, look up `assignmentByItemId.get(receiptLine.itemId)`. When present:
+ - Set `inspectionDocumentId` on the `inboundInspection` insert payload.
+ - For each feature of that document, compute `resolveFeatureSamplingPlan(feature, plan, safeReceivedQuantity, samplingStandard)` (where `plan` is the existing item plan variable, and pass `undefined` instead of the synthesized `{type:"All"}` default object when no `itemSamplingPlan` row existed, so the helper's own fallback applies). Collect pending child rows `{ receiptLineId, inspectionFeatureId, sampleSize, acceptanceNumber: r.acceptance, rejectionNumber: r.rejection, codeLetter: r.codeLetter, companyId, createdBy: userId }` keyed by receiptLineId.
+ - Set the lot-level snapshot `sampleSize` to `Math.max(...featureSampleSizes)` (keep `acceptanceNumber`/`rejectionNumber` from the item-plan resolution as today — they remain the fallback-flow numbers).
+4. In the transaction insert block (~L1815–1827): change the insert to `.returning(["id", "receiptLineId"])`; then map returned ids by `receiptLineId` and batch-insert the collected `inboundInspectionFeature` rows with `inboundInspectionId` filled in. All audit `createdBy` values are `userId` (non-null — it comes from the validated payload).
+5. If `.returning` is unavailable on this Kysely version, STOP and report — do not switch to a post-insert SELECT without flagging it.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-receipt/index.ts 2>&1 | tail -5
+# Expected: no errors mentioning post-receipt/index.ts or sampling-engine.ts (pre-existing unrelated
+# type noise from lib/types.ts is acceptable if it exists on main — compare with git stash if unsure)
+```
+
+**Out of scope:** the `Inbound Transfer` receipt branch (creates no inspections today — leave it); `config.toml` (post-receipt already registered).
+
+---
+
+## Task 6: quality.service reads + assignment upsert
+
+**Depends on:** Tasks 2, 4
+**Files:**
+- Modify: `apps/erp/app/modules/quality/quality.service.ts` — four functions near L2214–2330
+- Modify: `apps/erp/app/modules/quality/types.ts` — the two `Awaited<ReturnType>` types deferred from Task 4
+
+**Steps:**
+1. Add (client-first, return raw `{data, error}`, companyId-scoped — copy the style of `getItemSamplingPlan`):
+ ```ts
+ export async function getInboundInspectionFeatures(
+ client: SupabaseClient<Database>, inboundInspectionId: string, companyId: string
+ ) {
+ return client
+ .from("inboundInspectionFeature")
+ .select("*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit)")
+ .eq("inboundInspectionId", inboundInspectionId)
+ .eq("companyId", companyId);
+ }
+ ```
+ Embed by **target table name** (`inspectionFeature(...)`), never `alias:fkColumn(...)` — composite-FK embed lesson. `inspectionFeature`'s FK here is single-column, but use the table-name form regardless.
+2. `getInboundInspectionMeasurements(client, inboundInspectionId, companyId)` — `.from("inboundInspectionMeasurement").select("*").eq("inboundInspectionId", ...).eq("companyId", ...)`.
+3. `getItemInspectionDocumentAssignments(client, itemId, companyId)` — `.from("itemInspectionDocumentAssignment").select("*").eq("itemId", ...).eq("companyId", ...)`.
+4. `upsertItemInspectionDocumentAssignment(client, assignment: z.infer<typeof itemInspectionDocumentAssignmentValidator> & { companyId: string; userId: string })` — when `inspectionDocumentId` is empty/undefined: `.delete().eq("itemId").eq("usage").eq("companyId")`; else read-then-update-or-insert exactly like `upsertItemSamplingPlan` (keyed on itemId + usage + companyId; `createdBy` on insert, `updatedBy`/`updatedAt` on update).
+5. Complete the two deferred `Awaited<ReturnType>` types in `types.ts` (Task 4 Step 2).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** Kysely/write orchestration (Task 7); UI.
+
+---
+
+## Task 7: quality.server — measurement upsert, derived status, reconcile, disposition gating
+
+**Depends on:** Tasks 2, 4
+**Files:**
+- Modify: `apps/erp/app/modules/quality/quality.server.ts`
+
+**Steps:**
+1. **Extract the entity side-effect block** (L103–151 of `upsertInboundInspectionSample`: trackedEntity status flip + trackedActivity/input/output inserts) into a local async helper `applySampleEntityStatus(trx, args: { trackedEntityId: string; status: "Passed" | "Failed"; inspectionId: string; receiptId: string; notes: string | null; userId: string; companyId: string })`, and call it from `upsertInboundInspectionSample` unchanged. Also: when the incoming sample status is `"Pending"` (new identify-only flow), skip the entity flip entirely (leave the entity `On Hold`).
+2. Add a module-level pure helper (exported for tests):
+ ```ts
+ export function valuateMeasurement(feature: { type: string; nominalValue: string | null; tolerancePlus: string | null; toleranceMinus: string | null }, value: number | null, passed?: boolean | null): "Pending" | "Passed" | "Failed"
+ ```
+ Rules: for `type === "Measurement"`, parse `nominal = Number(nominalValue)`, `tolPlus = Math.abs(Number(tolerancePlus ?? 0))`, `tolMinus = Math.abs(Number(toleranceMinus ?? 0))` (strip a leading `+` before `Number()`; `Number.isNaN(nominal)` ⇒ treat the feature as attribute). Numeric path: `value == null` ⇒ `Pending`; in `[nominal - tolMinus, nominal + tolPlus]` ⇒ `Passed`; else `Failed`. Attribute path (non-Measurement type or unparseable nominal): `passed == null` ⇒ `Pending`, `passed` ⇒ `Passed`, else `Failed`.
+3. Add `export async function upsertInboundInspectionMeasurement(args: z.infer<typeof inboundInspectionMeasurementValidator> & { companyId: string; userId: string }): Promise<Result<{ sampleId: string; measurementId: string; measurementStatus: string; sampleStatus: string }>>`. One Kysely transaction:
+ - Load the inspection (`id, status, receiptId, inspectionDocumentId`); reject when terminal (`Passed`/`Failed`).
+ - Load the live feature (`inspectionFeature` by `inspectionFeatureId`: `type, nominalValue, tolerancePlus, toleranceMinus`).
+ - Resolve the sample: if `sampleId` present, load it (must belong to the inspection); else insert an anonymous `inboundInspectionSample` (`trackedEntityId: null, status: "Pending", companyId, createdBy: userId`).
+ - Compute `status = valuateMeasurement(feature, args.value ? Number(args.value) : null, args.passed ? args.passed === "true" : null)`.
+ - Upsert the measurement on `(inboundInspectionSampleId, inspectionFeatureId)`: insert with `createdBy`, or update `value/status/notes/updatedBy/updatedAt`; set `inspectedBy: userId, inspectedAt: nowIso` when status !== "Pending", clear both when an existing value is cleared back to Pending.
+ - **Derive the sample status**: load the lot's `inboundInspectionFeature` rows (`inspectionFeatureId, sampleSize`) and this sample's measurements; compute the sample's 1-based column index as its position in the lot's samples ordered by `createdAt, id`. Required features for this sample = those whose `sampleSize >= columnIndex`. Derived: any measurement `Failed` ⇒ `Failed`; else all required features have a `Passed` measurement ⇒ `Passed`; else `Pending`.
+ - When the derived status differs from the stored sample status: update it, and if the sample has a `trackedEntityId`, apply entity effects — `Passed` ⇒ flip via `applySampleEntityStatus` with `"Passed"`; `Failed` ⇒ `"Failed"`; back to `Pending` ⇒ set the entity's status back to `"On Hold"` directly (no trackedActivity for the revert; only write activity on Pending→Passed/Failed transitions, not on every cell edit).
+ - Recompute the lot's non-terminal status via the existing `computeLotStatus` logic (same as sample path).
+4. Add `export async function reconcileInboundInspectionFeatures(serviceRole client-or-db, inboundInspectionId, companyId)`: load the lot (`inspectionDocumentId, lotSize, createdBy`) — no document ⇒ no-op; load the document's current `inspectionFeature` ids + sampling fields, the lot's existing `inboundInspectionFeature` rows, the `itemSamplingPlan` for the lot's item, and `companySettings.samplingStandard`; for features with no row, `resolveFeatureSamplingPlan` + insert (`createdBy: COALESCE(lot.createdBy)` — never null). Leave rows whose live feature is gone.
+5. **Disposition gating** in `dispositionInboundInspection`: after loading samples (L253–264), also load the lot's `inboundInspectionFeature` rows and all measurements. When the lot has features (document flow), replace the caller-side gating data by returning richer errors: `Accept` must verify every feature has `recordedCount >= sampleSize` (recordedCount = measurements with status !== 'Pending' for that feature) and `failsForFeature <= acceptanceNumber`, else `errResult("Sampling incomplete or acceptance number exceeded", { featureId })`. `Reject` requires `failsForFeature >= rejectionNumber` for at least one feature OR at least one Failed sample. When the lot has no features, keep today's behavior untouched. Everything downstream (entity flips, history, ledger) stays as-is.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+pnpm --filter=erp test -- quality
+# Expected: existing quality tests still pass; add valuateMeasurement unit tests in
+# apps/erp/app/modules/quality/quality.server.test.ts if no test file exists (numeric in/out of
+# tolerance, unparseable nominal -> attribute, attribute passed/failed/null) and expect them green
+```
+
+**Out of scope:** routes; NCR enrichment (Task 13); touching `quality-disposition.server.ts`.
+
+---
+
+## Task 8: Route tree x+/inbound-inspection+ + path.ts
+
+**Depends on:** Tasks 6, 7
+**Files:**
+- Create: `apps/erp/app/routes/x+/inbound-inspection+/_layout.tsx`
+- Create: `apps/erp/app/routes/x+/inbound-inspection+/$id.tsx`
+- Create: `apps/erp/app/routes/x+/inbound-inspection+/$id.measurement.tsx`
+- Create: `apps/erp/app/routes/x+/inbound-inspection+/$id.document.tsx`
+- Move (create new + delete old): `$id.sample.tsx`, `$id.accept.tsx`, `$id.partial.tsx`, `$id.reject.tsx` from `x+/quality+/inbound-inspections.$id.*.tsx`
+- Modify: `apps/erp/app/routes/x+/quality+/inbound-inspections.$id.tsx` — becomes a redirect stub
+- Modify: `apps/erp/app/utils/path.ts`
+- Copy from (precedent): `apps/erp/app/routes/x+/assembly+/_layout.tsx` (layout), `apps/erp/app/routes/x+/inspection+/$id.tsx` (full-screen loader + ClientOnly/lazy pattern)
+
+**Steps:**
+1. `path.ts` — replace the two inbound entries (L1119–1121) with a full set (keep the same export names so existing imports keep compiling):
+ ```ts
+ inboundInspection: (id: string) => generatePath(`${x}/inbound-inspection/${id}`),
+ inboundInspections: `${x}/quality/inbound-inspections`,
+ inboundInspectionMeasurement: (id: string) => generatePath(`${x}/inbound-inspection/${id}/measurement`),
+ inboundInspectionSample: (id: string) => generatePath(`${x}/inbound-inspection/${id}/sample`),
+ inboundInspectionAccept: (id: string) => generatePath(`${x}/inbound-inspection/${id}/accept`),
+ inboundInspectionReject: (id: string) => generatePath(`${x}/inbound-inspection/${id}/reject`),
+ inboundInspectionPartial: (id: string) => generatePath(`${x}/inbound-inspection/${id}/partial`),
+ inboundInspectionDocument: (id: string) => generatePath(`${x}/inbound-inspection/${id}/document`),
+ ```
+ Then grep for the old ad-hoc concatenations (`${path.to.inboundInspection(...)}/accept` etc. in `InboundInspectionLotView.tsx`, `ScanInspectionSample.tsx`) — they will be replaced in Task 11; note them, don't fix here.
+2. `_layout.tsx`: copy the assembly layout verbatim, minus `requireAssembliesInternal`; permissions `view: "quality"`; `handle: { breadcrumb: msg\`Quality\`, to: path.to.quality, module: "quality" }`; title `Carbon | Inbound Inspection`.
+3. `$id.tsx` loader: `requirePermissions(request, { view: "quality", role: "employee" })`. Load in parallel: `getInboundInspection(client, id)`, `getCompanySettings(client, companyId)`, `getIssueTypesList(client, companyId)`. Company-mismatch/error ⇒ `throw redirect(path.to.inboundInspections)` (copy the old drawer route's guards verbatim). Then `await reconcileInboundInspectionFeatures(getCarbonServiceRole(), id, companyId)`, then load `getInboundInspectionFeatures(client, id, companyId)`, `getInboundInspectionMeasurements(client, id, companyId)`, `getInboundInspectionLotTrackedEntities(client, inspection.receiptLineId, companyId)`, and — when `inspection.inspectionDocumentId` — `getInspectionDocument(getCarbonServiceRole(), inspection.inspectionDocumentId)` (service role, same as `x+/inspection+/$id.tsx`; gives `content.pdfUrl`). Return everything the old drawer loader returned plus `features`, `measurements`, `document`. Default export renders `<InboundInspectionView …/>` (Task 11) — until Task 11 lands, a placeholder `<div/>` is acceptable to keep this task's verify green.
+4. `$id.measurement.tsx`: action-only, copy the shape of the old `$id.sample.tsx` (assertIsPost, `requirePermissions({ update: "quality", role: "employee" })`, validate `inboundInspectionMeasurementValidator`, guard `inspectionId === params.id`), call `upsertInboundInspectionMeasurement`, return `data(result)` **without** flash on success (per-cell saves must be quiet; return the `{sampleId, measurementStatus, sampleStatus}` payload so the grid can update) and a flash error on failure.
+5. Move `$id.sample.tsx`, `$id.accept.tsx`, `$id.partial.tsx`, `$id.reject.tsx` to the new tree unchanged except: redirect targets — accept keeps redirecting to `path.to.inboundInspections` list; partial/reject-no-NCR redirect to `path.to.inboundInspection(id)` (unchanged semantics, new URL).
+6. `$id.document.tsx`: action-only, `requirePermissions({ update: "quality" })`. FormData: `inspectionDocumentId` (may be empty). Guards: inspection non-terminal AND zero `inboundInspectionMeasurement` rows for the lot, else flash error "Cannot change document after measurements are recorded". On change: Kysely transaction — update `inboundInspection.inspectionDocumentId` (null when empty), delete the lot's `inboundInspectionFeature` rows; the next loader pass reconciles new rows. Redirect to `path.to.inboundInspection(id)`.
+7. Old `x+/quality+/inbound-inspections.$id.tsx`: replace body with a loader-only redirect `throw redirect(generatePath(\`${x}/inbound-inspection/${params.id}\`))` (preserve query string). Delete the old `$id.sample/accept/partial/reject` files.
+8. `x+/quality+/inbound-inspections.tsx`: remove `<Outlet />` if the drawer was its only child (check remaining children first; the redirect stub from step 7 still needs the parent to NOT swallow it — since the stub throws a redirect in its loader, keeping `<Outlet />` is harmless; keep it and note it).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+grep -rn "inbound-inspections/" apps/erp/app --include="*.tsx" | grep -v "quality+/inbound-inspections"
+# Expected: no stragglers building old-style /x/quality/inbound-inspections/{id} sub-URLs outside the list route
+```
+
+**Out of scope:** the view component internals (Tasks 9–11); MES.
+
+---
+
+## Task 9: InspectionDrawingPane (read-only PDF + balloons)
+
+**Depends on:** none (types from Task 2 helpful but not required)
+**Files:**
+- Create: `apps/erp/app/modules/quality/ui/InboundInspections/InspectionDrawingPane.tsx`
+- Copy from (precedent): `apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx` — Document/Page render L2782–2820, Konva overlay + positioning math L2822–2865, percent conversion L481–529; `apps/erp/app/modules/documents/ui/Documents/PdfViewer.tsx` (simple react-pdf usage + worker note)
+
+**Steps:**
+1. Props:
+ ```ts
+ type InspectionDrawingPaneProps = {
+ pdfUrl: string;
+ balloons: { id: string; inspectionFeatureId: string; pageNumber: number; xCoordinate: number; yCoordinate: number; regionX: number; regionY: number; regionWidth: number; regionHeight: number }[];
+ activeFeatureId: string | null;
+ onBalloonClick: (inspectionFeatureId: string) => void;
+ };
+ ```
+2. Render `react-pdf` `<Document file={pdfUrl}>` + single `<Page pageNumber={page} width={containerWidth} renderTextLayer={false} renderAnnotationLayer={false}/>` with page prev/next buttons and the container width measured via a `ResizeObserver` ref (the editor's `renderedWidth` pattern). The pdf.js worker is configured globally in `apps/erp/app/entry.client.tsx` — do not configure it again.
+3. Overlay: absolutely-positioned `<div className="pointer-events-auto absolute inset-0">` containing a react-konva `<Stage width height>` → `<Layer>`; for each balloon on the current page draw a `<Circle>` at `x = balloon.xCoordinate * renderedWidth`, `y = balloon.yCoordinate * pageHeightPx` (DB values are normalized 0–1 — multiply directly; the editor's ×100/÷100 percent round-trip is an editor-internal convention, skip it) with a `<Text>` label of the feature's balloon number, `fill` highlighted when `inspectionFeatureId === activeFeatureId`, and `onClick/onTap → onBalloonClick(inspectionFeatureId)`. `pageHeightPx = renderedWidth × (defaultPageHeight/defaultPageWidth)` from the Page `onLoadSuccess` viewport, mirroring the editor's `overlayHeight`.
+4. Auto-switch the visible page to the active feature's balloon page when `activeFeatureId` changes.
+5. Export the component lazily-safe: no top-level `window` access; the parent (Task 11) wraps in `ClientOnly` + `lazy()` like `x+/inspection+/$id.tsx` does for the editor.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** any editing/ballooning; zoom-box tooling (page fit-to-width only).
+
+---
+
+## Task 10: InspectionMeasurementGrid (features × samples)
+
+**Depends on:** Tasks 4, 6
+**Files:**
+- Create: `apps/erp/app/modules/quality/ui/InboundInspections/InspectionMeasurementGrid.tsx`
+- Copy from (precedent): `apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx` — `editableComponents` map + `EditableNumber` config (L26, 627–641), `onCellEdit` (L155–181), Table props (`withInlineEditing`, `forceEditMode`), keyboard-nav data-attribute pattern (L508–625)
+
+**Steps:**
+1. Props:
+ ```ts
+ type InspectionMeasurementGridProps = {
+ inspectionId: string;
+ lotStatus: string; // terminal => read-only
+ isSerial: boolean;
+ features: InboundInspectionFeature[]; // resolved plan + live inspectionFeature join
+ samples: InboundInspectionSample[]; // ordered createdAt asc, id asc
+ measurements: InboundInspectionMeasurement[];
+ maxSampleSize: number; // max over features
+ activeFeatureId: string | null;
+ onActiveFeatureChange: (id: string | null) => void;
+ onAddSample: () => void; // serial: opens scan modal
+ };
+ ```
+2. Row model: one row per feature, sorted by `inspectionFeature.pageNumber` then `label`. Fixed leading columns: balloon label, description, `Nom` / `Tol+` / `Tol−` / `Unit` (blank for attribute features), `n/Ac` (e.g. `8 / 1`), and a pass-count chip (`passed/recorded` of `n`, red when fails ≥ Re).
+3. Sample columns: for non-serial, render `maxSampleSize` columns headed `1…n` (columns beyond the existing sample rows have `sampleId=null` until the first save creates one — thread the `sampleId` returned by the measurement action back into local state, keyed by column index). For serial, one column per existing sample headed by `trackedEntity.readableId`, plus a trailing `+ Add sample` header button calling `onAddSample`. Cells where `columnIndex > feature.sampleSize` render disabled (muted, non-editable).
+4. Editing: build the columns with the shared `Table` (`~/components/Table`) exactly like `InventoryCountLines` — `withInlineEditing`, `forceEditMode={lotStatus is non-terminal}` (sync with an effect, not seeded state — stale-`forceEditMode` lesson), `editableComponents` mapping each sample column to `EditableNumber` for Measurement-type rows. `onCellEdit(rowFeatureId, columnIndex, value)` posts `FormData {inspectionId, sampleId?, inspectionFeatureId, value}` to `path.to.inboundInspectionMeasurement(inspectionId)` via `fetch` and returns the `{data, error}`-shaped result so the cell reverts on failure (copy the InventoryCountLines `onCellEdit` return contract). For attribute rows, render a compact Pass/Fail toggle cell (two small buttons; POST with `passed` instead of `value`).
+5. Cell state styling: measurement `Failed` ⇒ red text/background tint on the cell; `Passed` ⇒ default; empty required ⇒ subtle outline. Row focus (click anywhere in the row) calls `onActiveFeatureChange(feature.inspectionFeatureId)`; when `activeFeatureId` changes from outside (balloon click), scroll the row into view (`scrollIntoView({block:"nearest"})` via a ref keyed on active row).
+6. Keep the capture-phase keyboard model from the precedent: Enter/Tab advance across sample cells within a row then down; rely on the shared `Table`'s existing key handling — copy the `data-column`/`data-row` marker approach from `InventoryCountLines` (L508–625) adapted to multiple editable columns.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** disposition buttons, scan modal, PDF pane (Task 11 wires them).
+
+---
+
+## Task 11: InboundInspectionView wiring + fallback + drawer retirement
+
+**Depends on:** Tasks 8, 9, 10
+**Files:**
+- Create: `apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionView.tsx`
+- Create: `apps/erp/app/modules/quality/ui/InboundInspections/RejectLotModal.tsx` (extracted)
+- Modify: `apps/erp/app/modules/quality/ui/InboundInspections/ScanInspectionSample.tsx` — add identify-only mode
+- Modify: `apps/erp/app/routes/x+/inbound-inspection+/$id.tsx` — render the view
+- Modify: `apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx` — row link → new route (drop the `?${params}` suffix carry-over if it breaks nothing else; keep filters via the list URL only)
+- Delete: `apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionLotView.tsx`
+- Modify: barrel `apps/erp/app/modules/quality/ui/InboundInspections/index.ts` (if it exists) — swap exports
+- Copy from (precedent): `InboundInspectionLotView.tsx` (header KPIs, four-eyes alert, gating, Confirm/Reject wiring — port, don't redesign), `apps/erp/app/modules/documents/ui/Documents/DocumentView.tsx` + `apps/erp/app/components/Layout/Panels.tsx` (ResizablePanelGroup/Panel/Handle usage)
+
+**Steps:**
+1. `RejectLotModal.tsx`: lift the local component out of `InboundInspectionLotView.tsx` (L425–551) verbatim into its own file; add an optional `failedFeatureSummary?: { label: string; spec: string; failedValues: string[] }[]` prop rendered as a compact list above the checkbox (data supplied by the view; populated fully in Task 13).
+2. `ScanInspectionSample.tsx`: add prop `mode: "record" | "identify"` (default `"record"` preserves today's behavior). In `identify` mode: hide the Pass/Fail submit pair and Notes; render a single primary `Add sample` submit that posts `status="Pending"` with the selected `trackedEntityId` (serial identity still required); action path becomes `path.to.inboundInspectionSample(inspectionId)`.
+3. `InboundInspectionView.tsx` — props: everything the `$id` loader returns. Layout: full-height flex column; header bar (item + readableId, receipt link, supplier, status badge, plan summary `Std · Level · AQL`, document name + a `Change` button opening a small modal posting to `path.to.inboundInspectionDocument(id)` — options via `components/Form/InspectionDocument` combobox scoped to the item, disabled once measurements exist; four-eyes `Alert` when `enforceFourEyes && receiverId === currentUserId`); body:
+ - **Document flow** (`document && features.length`): `ResizablePanelGroup direction="horizontal"` → left `ResizablePanel` (defaultSize 45, minSize 25) with `InspectionDrawingPane` (wrapped `ClientOnly`+`Suspense`+`lazy` like `x+/inspection+/$id.tsx`), `ResizableHandle withHandle`, right panel with `InspectionMeasurementGrid`. `activeFeatureId` state lives here and links the two panes both directions.
+ - **Fallback flow** (no document): port the old drawer's body (progress bar, samples table, "Inspect Next Item" button opening `ScanInspectionSample mode="record"`) into the page unchanged.
+4. Footer (both flows): port the old gating with the per-feature upgrade — document flow: `canAccept = every feature recordedCount >= sampleSize && failsForFeature <= acceptanceNumber`, `canReject = any feature failsForFeature >= rejectionNumber || samples.some(Failed)`, `canPartial = any measurement recorded`; fallback flow keeps the old sample-count math verbatim. Buttons post to the new `path.to.inboundInspectionAccept/Partial(id)` via the existing `Confirm` component; Reject opens `RejectLotModal` with `action={path.to.inboundInspectionReject(id)}`. "Create Issue from Inspection" link ported as-is.
+5. Serial flow: `+ Add sample` (grid) opens `ScanInspectionSample mode={document ? "identify" : "record"}`.
+6. Update `$id.tsx` to render the view; update `InboundInspectionsTable` hyperlink to `path.to.inboundInspection(row.original.id)`; delete `InboundInspectionLotView.tsx` and fix the barrel + any imports (`grep -rn "InboundInspectionLotView" apps/erp`).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+grep -rn "InboundInspectionLotView" apps/erp/app | wc -l
+# Expected: 0
+```
+
+**Out of scope:** MES; NCR content payload (Task 13).
+
+---
+
+## Task 12: Item Quality tab — documents card + assignments card (4 routes)
+
+**Depends on:** Tasks 4, 6
+**Files:**
+- Create: `apps/erp/app/modules/quality/ui/SamplingPlan/ItemQualityView.tsx` (shared: two new cards + existing SamplingPlanForm)
+- Modify: `apps/erp/app/routes/x+/part+/$itemId.quality.tsx`, `x+/material+/$itemId.quality.tsx`, `x+/tool+/$itemId.quality.tsx`, `x+/consumable+/$itemId.quality.tsx`
+- Copy from (precedent): `apps/erp/app/modules/quality/ui/SamplingPlan/SamplingPlanForm.tsx` (Card + ValidatedForm layout), `apps/erp/app/routes/x+/production+/inspection.new.tsx` + `InspectionDocumentForm` (create-document modal), `apps/erp/app/components/Form/InspectionDocument.tsx` (item-scoped combobox)
+
+**Steps:**
+1. `ItemQualityView.tsx` props: `{ itemId: string; actionPath: string; standard: SamplingStandard; plan: ...; documents: { id: string; fileName: string | null; drawingNumber: string | null; version: number }[]; assignments: ItemInspectionDocumentAssignment[] }`. Renders a vertical stack:
+ - **Inspection Documents card**: `Card` with header action `New Inspection Document` (opens `InspectionDocumentForm` with `initialValues={{ name: "", partId: itemId, drawingNumber: "" }}`; on success the route revalidates). Body: simple table of documents (drawingNumber ?? fileName, `v{version}`), each row linking to `path.to.inspectionDocument(doc.id)`. Empty state: "No inspection documents".
+ - **Assignments card**: `Card` titled "Inspection Document Assignments"; one row per usage in `inspectionDocumentUsages` (v1: `Receipt`) — a `ValidatedForm` with `validator(itemInspectionDocumentAssignmentValidator)`, `Hidden` fields `itemId` + `usage` + hidden `intent="assignment"`, the `InspectionDocument` combobox (`itemId` prop scopes options, `isOptional`), and a `Submit`. Posts to `actionPath`.
+ - **Sampling plan**: render the existing `SamplingPlanForm` below, unchanged.
+2. Each of the four routes: extend the loader (`Promise.all` adds `getInspectionDocumentsForItem(client, itemId, companyId)` and `getItemInspectionDocumentAssignments(client, itemId, companyId)`); extend the action to branch on `formData.get("intent")` — `"assignment"` ⇒ validate `itemInspectionDocumentAssignmentValidator` ⇒ `upsertItemInspectionDocumentAssignment` (permissions stay `update: "quality"`); otherwise the existing sampling-plan path unchanged (its form gains a hidden `intent="samplingPlan"` — add via `SamplingPlanForm`'s ValidatedForm, one-line change). Render `<ItemQualityView …/>` instead of the bare `SamplingPlanForm`. Keep the four files byte-identical apart from the `path.to.*Quality` helper, as they are today.
+3. If `InspectionDocumentForm`'s props don't accept a preset `partId` initial value, STOP and report rather than modifying the production form's contract silently.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+diff <(sed 's/partQuality/XQuality/g' apps/erp/app/routes/x+/part+/\$itemId.quality.tsx) <(sed 's/materialQuality/XQuality/g' apps/erp/app/routes/x+/material+/\$itemId.quality.tsx)
+# Expected: no diff (routes identical modulo the path helper)
+```
+
+**Out of scope:** FAI/Production usage slots (enum stays Receipt-only); editing sampling fields in the document editor grid (see note below — the editor's `featureColumns` gains the six sampling fields only if trivially additive; otherwise defer to a follow-up and record it in the plan changelog. The RPC + validators already persist them from Task 1/4, and `reconcileInboundInspectionFeatures` + post-receipt consume them.)
+
+---
+
+## Task 13: Reject NCR enrichment (failed-feature table)
+
+**Depends on:** Task 7
+**Files:**
+- Modify: `apps/erp/app/routes/x+/inbound-inspection+/$id.reject.tsx`
+
+**Steps:**
+1. In the NCR branch (after `dispositionInboundInspection` succeeds and `createNcr` is true), load via the existing service-role client: `getInboundInspectionFeatures`, `getInboundInspectionMeasurements`, and the lot's samples (already loaded via `getInboundInspection`).
+2. Build `failedFeatureLines: string[]` — for each feature with ≥1 Failed measurement: `- ${label}: nominal ${nominalValue} +${tolerancePlus}/−${toleranceMinus} ${unit ?? ""} — failed values: ${failedValues.join(", ")} (${failsForFeature}/${recordedCount} failed, n=${sampleSize}, Ac=${acceptanceNumber})`. For attribute features: `- ${label}: ${failsForFeature}/${recordedCount} failed`.
+3. Append to the issue description passed to `insertIssue`: existing title/description + `\n\nFailed features:\n` + lines. When no measurements exist (fallback flow), skip — description unchanged.
+4. Pass the same summary to the `RejectLotModal` preview: the `$id.tsx` loader already returns features + measurements; compute `failedFeatureSummary` in `InboundInspectionView` and pass it down (wire the prop added in Task 11 Step 1).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** issue content JSON blocks; workflow tasks; notifications.
+
+---
+
+## Task 14: Docs sync (rule + AGENTS.md)
+
+**Depends on:** Tasks 1–13 (run after implementation is committed)
+**Files:**
+- Modify: `.claude/rules/inbound-inspection-system.md` — new tables, per-feature sampling, new route tree, derived sample status, document assignment; update the `paths:` frontmatter to include `apps/erp/app/routes/x+/inbound-inspection+/**`
+- Modify: `apps/erp/app/modules/quality/AGENTS.md` — data-model table + service-function list + inbound description
+- Modify: `apps/erp/app/modules/production/AGENTS.md` — only if it enumerates inspectionFeature columns or the RPC signature (check first)
+
+**Steps:**
+1. Update each file to describe the committed code only — verify every claim against the merged implementation (tables, function names, route paths). Follow `.claude/rules/keep-sources-in-sync.md`.
+
+**Verify:**
+```bash
+grep -n "inboundInspectionMeasurement" .claude/rules/inbound-inspection-system.md apps/erp/app/modules/quality/AGENTS.md
+# Expected: at least one hit in each file
+```
+
+**Out of scope:** product docs site (`docs/`) — separate follow-up if desired.
+
+---
+
+## Task 15: Browser verification (/test)
+
+**Depends on:** Tasks 1–13
+**Steps:**
+1. Boot the stack with plain `crbn up` (portless). Enable nothing extra; log in via `/auth`.
+2. Invoke the `/test` skill against this branch's diff with this scenario: (a) on a purchased part with `requiresInspection`, create an inspection document (upload any small PDF), add 2 Measurement features with numeric nominal/tolerances + 1 Checkbox feature, balloon them; assign the document to the Receipt slot on the part's Quality tab; set an item sampling plan (Percentage 10%); give one feature its own AQL rule. (b) Create + post a PO receipt for qty 20 of that part. (c) Verify an inbound inspection was created with the document attached and per-feature n/Ac/Re. (d) Open `/x/inbound-inspection/{id}`: PDF + balloons render; balloon↔row sync works; enter in-tolerance and out-of-tolerance values; verify cell coloring, derived sample status, disabled cells beyond n. (e) Verify Accept stays disabled until complete; force a feature past its Re and Reject with NCR — verify the issue contains the failed-features block. (f) Verify an item WITHOUT an assigned document still gets the fallback pass/fail flow.
+3. Capture screenshots of the split view and the item Quality tab for the PR (surface-designs memory).
+
+**Verify:** the /test run report shows every step above passing; screenshots saved.
+
+**Out of scope:** MES surfacing; load/perf testing.
diff --git a/.ai/plans/2026-07-22-inspections-refactor.md b/.ai/plans/2026-07-22-inspections-refactor.md
new file mode 100644
index 0000000000..cf31faa92b
--- /dev/null
+++ b/.ai/plans/2026-07-22-inspections-refactor.md
@@ -0,0 +1,96 @@
+# Inspections refactor (generic source documents) — implementation plan
+
+**Spec:** .ai/specs/implemented/2026-07-21-inbound-inspection-execution.md (see 2026-07-22 changelog entry)
+**Branch:** feat/mes-assembly
+
+User decisions: migrate to a new `inspection` table family; move the document
+editor route; seed `INS` prefix for new companies only (existing sequences keep
+their prefix/counter, re-keyed to the new table name). Assistant naming calls
+(surfaced for veto): `inboundInspectionFeature` → `inspectionSamplingPlan`;
+enums → `inspectionStatusType` / `inspectionSampleStatusType` (the clean names
+are taken by the document system's `inspectionFeature` and the Pass/Fail step
+enum `inspectionStatus`).
+
+## Progress
+- [x] Task 1: Migration — rename table family, generic source columns + backfill, sequence re-key
+- [x] Task 2: Apply migration + regenerate types (validates rename against live data)
+- [x] Task 3: Seed data — `inspection` sequence with INS prefix
+- [x] Task 4: post-receipt edge fn — new names + source columns
+- [x] Task 5: Quality module app-layer rename (models/service/server/types/barrel)
+- [x] Task 6: Routes — editor → x+/inspection-document+, execution → x+/inspection+, list → quality+/inspections, redirects, path.ts
+- [x] Task 7: UI — ui/Inspections rename, InspectionView, filterable Source column, nav label
+- [x] Task 8: Issue associations — table/key renames ("inspections")
+- [x] Task 9: Docs sync + verification (typecheck, tests, browser smoke)
+
+## Task summaries
+
+**Task 1 (migration `inspections-refactor`)** — all DDL guarded/idempotent:
+- Table renames (via `to_regclass` DO-blocks): `inboundInspection`→`inspection`,
+ `inboundInspectionSample`→`inspectionSample`, `inboundInspectionFeature`→
+ `inspectionSamplingPlan`, `inboundInspectionMeasurement`→`inspectionMeasurement`,
+ `inboundInspectionHistory`→`inspectionHistory`,
+ `nonConformanceInboundInspection`→`nonConformanceInspection`. (RLS policies
+ follow the table; old constraint/index NAMES keep their strings — documented.)
+- Enum renames (pg_type-guarded): `inboundInspectionStatus`→`inspectionStatusType`,
+ `inboundInspectionSampleStatus`→`inspectionSampleStatusType`.
+- Column renames (information_schema-guarded): readable
+ `inspection.inboundInspectionId`→`inspectionId` (nonConformance precedent:
+ readable on parent, FK of same name on children); child FKs
+ `inboundInspectionId`→`inspectionId` everywhere;
+ `inspectionMeasurement.inboundInspectionSampleId`→`inspectionSampleId`.
+- Source columns: enum `inspectionSourceDocument` ('Receipt','Job Operation');
+ add `sourceDocument`, `sourceDocumentId`, `sourceDocumentLineId`,
+ `sourceDocumentReadableId`; backfill from `receiptId`/`receiptLineId` + receipt
+ join inside a DO-block gated on the old columns still existing; then SET NOT
+ NULL (sourceDocument, sourceDocumentId), drop the receipt FKs + columns +
+ `receiptLineId` unique, add partial unique `(sourceDocument, sourceDocumentLineId)
+ WHERE "sourceDocumentLineId" IS NOT NULL` + indexes. No FKs on generic ids
+ (matches `receipt.sourceDocument*`).
+- Sequence: `UPDATE "sequence" SET "table"='inspection', "name"='Inspection'
+ WHERE "table"='inboundInspection'` (existing companies keep II + counters).
+
+**Task 3** — `seed.data.ts` sequence block: table `inspection`, name
+`Inspection`, prefix `INS` (new companies only; seed-company iterates this).
+
+**Task 4** — post-receipt: typed inserts into `inspection`/`inspectionSamplingPlan`,
+`getNextSequence(trx, "inspection", companyId)` → `row.inspectionId`; payload
+gains `sourceDocument:'Receipt'`, `sourceDocumentId: receiptId`,
+`sourceDocumentLineId: receiptLine.id`, `sourceDocumentReadableId` (receipt
+readable), drops `receiptId`/`receiptLineId`; `.returning(["id","sourceDocumentLineId"])`
+joins the sampling-plan child inserts. Deno check must stay at the 71-error baseline.
+
+**Task 5** — mechanical `inboundInspection`→`inspection` / `InboundInspection`→
+`Inspection` sweep in quality module (safe: "InspectionDocument" never matches),
+plus semantic fixes: `dispositionInspection` branches Receipt-only behavior
+(entity lookup via `attributes->>'Receipt Line' = sourceDocumentLineId`, ledger
+entry, `receiptLine.locationId`) on `sourceDocument === 'Receipt'`;
+`reconcileInspectionSamplingPlans`; service renames (`getInspections` adds
+`source` filter arg + `sourceDocumentReadableId` in search); models add
+`inspectionSourceDocuments` const; string literals `'Inbound Inspection'` for
+`itemLedger.documentType` and `trackedActivity.sourceDocument` are DB data
+values and stay. Types `Inspection*` via Awaited chains.
+
+**Task 6** — `git mv` route trees; `path.to.inspectionDocument*` URLs move to
+`${x}/inspection-document/...`; execution keys `inboundInspection*`→`inspection*`
+(`path.to.inspection(id)` etc.); `quality+/inspections.tsx` list; redirect stubs
+at old `/x/quality/inbound-inspections`(+`/$id`) URLs.
+
+**Task 7** — `ui/InboundInspections/`→`ui/Inspections/`; `InspectionsTable` gets
+a `Source` column (enum filter options from `inspectionSourceDocuments`, shows
+`sourceDocumentReadableId` as the link text where useful); nav entry label
+Inspections → `path.to.inspections`, `table: "inspection"`.
+
+**Task 8** — association const value `"inboundInspections"`→`"inspections"`;
+`nonConformanceInspection` table strings; switch cases in `IssueAssociations.tsx`,
+`x+/issue+/$id.tsx`, `$id.association.new.tsx`, `deleteIssueAssociation` +
+`getIssueAssociations` in the service; reject route link inserts.
+
+**Task 9** — rule file (`inbound-inspection-system.md` → renamed content/paths;
+consider file rename to `inspection-system.md` with Task Router update), quality
+AGENTS.md, spec changelog; verify: `pnpm exec turbo run typecheck --filter=erp`
+(only the known pre-existing error), `vitest run` quality/sampling, browser
+smoke (list + Source filter, execution view on existing lot, editor at
+/x/inspection-document/{id}, quality tab).
+
+Out of scope: renaming DB constraint/index name strings; `itemLedgerDocumentType`
+enum value 'Inbound Inspection'; MES; `x+/production+/inspection.tsx` list URL.
diff --git a/.ai/plans/2026-07-23-mes-assembly-per-unit-issue-attribution.md b/.ai/plans/2026-07-23-mes-assembly-per-unit-issue-attribution.md
new file mode 100644
index 0000000000..5c8ae7c931
--- /dev/null
+++ b/.ai/plans/2026-07-23-mes-assembly-per-unit-issue-attribution.md
@@ -0,0 +1,116 @@
+# MES Assembly — exact per-unit (and per-step) issued attribution
+
+**Goal:** Make the per-unit "issued" count in the assembly view accurate for **batch**
+(and untracked) parents the same way it already is for **serial** parents — including
+surfacing over-issues (scan 2 where 1 is required → shows `2/1`). Do it by capturing the
+**unit** and **step** at issue time and attributing consumed inputs to them, instead of
+reconstructing a per-unit share from the job-wide total.
+
+## Background / root cause (confirmed)
+
+Reproduced on job **J000003** (`SERIAL-BUY`: 3-unit job, 1/unit required, `quantityIssued = 4`
+— a real over-issue) which the UI rendered as `1/1` on unit 3.
+
+- **Serial parent works** because each unit is its own `trackedEntity`. The consume records
+ that unit's entity as the activity **output** (`issue/index.ts:2093-2102`,
+ `trackedActivityOutput.trackedEntityId = parentTrackedEntityId`). The loader reads
+ `getTrackedInputs(unitEntity)` and gets exactly what went into that unit
+ (`operations.service.ts:702-712`), so `MaterialRow` shows it raw (per-unit, no clamp).
+- **Batch parent can't**, because every unit shares **one lot entity**
+ (`assembly.$operationId.tsx:179-182`, `effectiveEntityId = navEntities[0]`). Every consume's
+ output points at that same lot — nothing records which unit (or step) a serial went into.
+ The loader falls to the `else` branch (`operations.service.ts:723-732`) returning the
+ **job-wide** `quantityIssued`, and `MaterialRow` reconstructs a per-unit share via
+ `Math.min(required, totalIssued − unitIndex*required)` (`AssemblyView.tsx`, `getIssuedForUnit`).
+ The `Math.min(required, …)` clamp hides the over-issue → `1/1`.
+- **The unit/step is never captured.** The Consume activity stores only
+ `attributes: { Job, "Job Make Method", "Job Material", Employee }` (`issue/index.ts:2082`),
+ and the issue payload (`issueTrackedEntityValidator`, `models.ts:161`) carries no step or unit.
+
+## Approach
+
+Stamp the **unit index** and **step id** onto the Consume activity at issue time (the
+assembly view knows both), then attribute consumed inputs by unit in the loader. Serial
+parents are unchanged (already exact). Batch/untracked become exact for newly-issued parts;
+consumes issued before this change (no stamp) fall back to today's heuristic.
+
+Decision (default; confirm): **stamp both `Unit` and `Job Operation Step`.** Unit is what
+fixes the count; step is the extra signal (which step within the unit) and is cheap to carry.
+
+## Changes
+
+### 1. Issue payload carries unit + step
+`apps/mes/app/services/models.ts` — extend `issueTrackedEntityValidator` (line 161):
+```ts
+jobOperationStepId: z.string().optional(),
+unitIndex: z.number().int().nonnegative().optional(),
+```
+
+`apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx`:
+- Add optional props `jobOperationStepId?: string` and `unitIndex?: number`.
+- Include them in the serial (`~:818-836`) and batch (`~:895-908`) `issueTrackedEntity`
+ payloads. The plain-inventory `path.to.issue` form (non-tracked) is out of scope — those
+ parts backflush and don't gate.
+
+`apps/mes/app/components/AssemblyView.tsx` — pass them where `<IssueMaterialModal>` is
+rendered (`~:1946`): `jobOperationStepId={step?.id}` and `unitIndex={currentUnitIndex}`.
+The operation view (`JobOperation.tsx`) omits them (undefined) → no behavior change there.
+
+### 2. Route passes through
+`apps/mes/app/routes/x+/issue-tracked-entity.tsx` — destructure the two new fields from
+`validation.data` and forward them in the `serviceRole.functions.invoke("issue", { body })`.
+
+### 3. Edge function stamps the Consume activity
+`packages/database/supabase/functions/issue/index.ts`, `trackedEntitiesToOperation` case:
+- Extend the payload validator (`~:849-868`) with optional `jobOperationStepId`, `unitIndex`.
+- Add to the Consume activity `attributes` (`~:2082`):
+ ```
+ ...(jobOperationStepId ? { "Job Operation Step": jobOperationStepId } : {}),
+ ...(unitIndex !== undefined ? { Unit: unitIndex } : {}),
+ ```
+ Additive JSONB keys — safe alongside existing `attributes->>` lookups. (Ships on merge to
+ `main`; the `[functions.issue]` config.toml entry already exists.)
+
+### 4. Loader attributes per unit for batch parents
+`apps/mes/app/services/operations.service.ts` — `getJobMaterialsByOperationId`:
+- Add `unitIndex: number` and `requiresBatchTracking: boolean` to args; the route already
+ computes both (`assembly.$operationId.tsx:170-182`) — pass them in (`~:184-190`).
+- For a **batch** parent (`requiresBatchTracking && !requiresSerialTracking`), the existing
+ `getTrackedInputs(effectiveEntityId=lot)` already returns every consumed serial descendant
+ of the lot. For each tracked material compute:
+ - `issuedThisUnit` = Σ `input.quantity` where `activityAttributes["Job Material"] === material.id`
+ **and** `activityAttributes["Unit"] === unitIndex` (stamped, exact).
+ - `issuedLegacy` = Σ for the same material where `activityAttributes["Unit"]` is absent
+ (pre-change consumes) → fall back to the job-wide heuristic share for those only.
+ - `quantityIssued = issuedThisUnit + heuristicShareOf(issuedLegacy)`.
+ Return this as a **per-unit** value (same contract as the serial branch).
+- Serial branch unchanged. Untracked parent (no lot entity) keeps current behavior.
+
+### 5. Component treats batch tracked issued as per-unit
+`apps/mes/app/components/AssemblyView.tsx`:
+- In `visibleMaterialsWithState`, set `issuedIsPerUnit` for tracked materials under a batch
+ parent too: `(requiresSerialTracking || requiresBatchTracking) && isTrackedMat`.
+- `getIssuedForUnit`'s per-unit branch already returns `totalIssued` **without** the
+ `Math.min` clamp, so an over-issue renders as `2/1` automatically. The clamp stays only on
+ the legacy heuristic branch (untracked / unstamped). No clamp change needed.
+
+## Backward compatibility
+- In-progress batch builds started before this ships have unstamped consumes → those units use
+ the heuristic (current behavior). Every new scan is exact. No migration/backfill required.
+- Serial parents and the operation view are behaviorally unchanged.
+
+## Verification
+- `pnpm exec turbo run typecheck --filter=mes` and `--filter=@carbon/database` green.
+- DB check: after issuing 2 serials on unit 3 of a **batch** parent (1/unit required), the
+ Consume activities carry `attributes->>Unit = '2'`; loader returns `quantityIssued = 2` for
+ that material on unit 3; `MaterialRow` shows `2/1`. Paging to a completed unit still shows its
+ own count (attributed by its `Unit`), not the job-wide total.
+- Serial parent unchanged: still exact.
+- `/test` browser pass on a batch-parent assembly: scan 1 → `1/1`; scan a 2nd → `2/1`; the
+ soft-gate (tracked parts must be scanned before Mark done) still behaves.
+
+## Decisions (confirmed)
+1. Stamp **both** `Unit` + `Job Operation Step`.
+2. Store `Unit` as a **1-based** unit number (`currentUnitIndex + 1`); loader compares against
+ `unitIndex + 1`. Payload/prop named `unitNumber` to signal 1-based.
+3. Legacy unstamped batch consumes fall back to the job-wide heuristic (current behavior).
diff --git a/.ai/plans/2026-07-23-mes-assembly-scan-gate.md b/.ai/plans/2026-07-23-mes-assembly-scan-gate.md
new file mode 100644
index 0000000000..0dd4feb1d3
--- /dev/null
+++ b/.ai/plans/2026-07-23-mes-assembly-scan-gate.md
@@ -0,0 +1,43 @@
+# MES Assembly View — scan-to-complete gate
+
+**File:** `apps/mes/app/components/AssemblyView.tsx`
+
+## Problem
+
+- The standalone "Scan Part" button pre-selects `firstTrackedMaterial`, which uses
+ a **job-wide** `remainingToIssue` (`estimatedQuantity − quantityIssued`). A serial
+ parent reports `quantityIssued` **per unit**, so the remaining never reaches 0 and
+ the button re-opens the **same part** every click instead of walking to the next.
+- A step can be completed (Mark done / Record) without its parts ever being issued.
+- The "Issue" framing + duplicate scan affordances are confusing.
+
+## Decisions (confirmed with user)
+
+1. **Only tracked (serial/batch) parts assigned to the step gate completion.**
+ Non-tracked parts do not gate — loose parts are added to the first step and
+ backflushed when that step is recorded.
+2. **Soft gate:** keep the Skip button always enabled; **disable** the primary
+ Mark done / Record button while the step's tracked parts are unissued, with a hint.
+
+## Changes
+
+1. **`getIssuedForUnit(material, { unitIndex, issuedIsPerUnit, issuedOverride })`** —
+ module-level helper returning `{ required, issued, fullyIssued }`. Replaces the
+ inline math in `MaterialRow` so the row and the gate share one source of truth.
+2. **`visibleMaterialsWithState`** — hoist the per-material `stepNumbers` / `isLoose`
+ / `issuedIsPerUnit` / `issuedOverride` / issue-state computation out of the Parts
+ JSX. Derive `pendingScanMaterials` = entries that are tracked **and** not
+ `fullyIssued` for the current unit; `hasPendingScans` gates the step.
+ Remove `rawMaterials`, `isTrackedMat`, `remainingToIssue`, `firstTrackedMaterial`.
+3. **Remove the standalone "Scan Part" section** and the now-unused `LuQrCode` import.
+ Scanning is per-part via the existing (clear) `MaterialRow` cards.
+4. **Soft-gate the action row:** show a "Scan N part(s)…" hint above the buttons when
+ `hasPendingScans`; pass `disabled={hasPendingScans}` to `StepCompleteAction`, which
+ disables Mark done / Record. Skip stays enabled.
+
+## Verification
+
+- `pnpm exec turbo run typecheck --filter=@carbon/mes` (or the app's package name).
+- Manual: a step with two serialized parts — primary action disabled + hint until
+ both scanned; each card scans its own part; Skip always works; non-tracked/loose
+ parts never block.
diff --git a/.ai/plans/2026-07-24-mes-assembly-setup-labor-clocking.md b/.ai/plans/2026-07-24-mes-assembly-setup-labor-clocking.md
new file mode 100644
index 0000000000..9fbd25640c
--- /dev/null
+++ b/.ai/plans/2026-07-24-mes-assembly-setup-labor-clocking.md
@@ -0,0 +1,60 @@
+# MES Assembly — Setup vs Labor clocking
+
+Date: 2026-07-24
+Area: `apps/mes` assembly view (`apps/mes/app/components/AssemblyView.tsx`)
+
+## Problem
+
+On an operation that has **both** setup time and labor time, the assembly view
+has no clear, single mechanism for clocking one vs the other, and the two clocks
+can run **simultaneously**:
+
+- The header timer button toggles whichever type is in `selectedWorkType`, which
+ is only changed by clicking a sidebar `TimeRows` row.
+- The step-record automation (`AssemblyView.tsx` ~944-1013) starts/stops a
+ **hardcoded `"Labor"`** event, ignoring `selectedWorkType`.
+- The shared `/x/event` route never ends one open type when another starts.
+
+Result on a setup+labor op: opening (with auto-start) starts **Setup**; recording
+the first step starts **Labor** on top of it → both run, Setup never stops.
+"Only labor" works because everything then targets the one Labor clock.
+
+## Design — one clock per type in the header, mutually exclusive
+
+Render one self-contained timer button per available work type in the top-right
+(Setup / Labor / [Machine]). Each shows its own elapsed + label + play/pause.
+
+1. **Header buttons** — one `TimerControl` per available work type (fallback to a
+ single Labor button when the op has no configured durations).
+2. **Mutual exclusion** — starting one type ends any other open type for the
+ operator on that operation (assembly-only, via an `exclusive` flag on the
+ submit; the operation view's `WorkTypeToggle` is untouched). Ended events are
+ posted (`post-production-event`) so cost still books.
+3. **Auto-transition** — recording the first step starts Labor with `exclusive`,
+ which ends any open Setup. All-steps-recorded ends Labor (unchanged).
+4. **Sidebar `TimeRows` → display-only** — the Setup/Labor progress rows stay as a
+ read-out; the green dot now means "this phase is currently running" (derived
+ from open events), not "selected". Removes the confusing selected-vs-accrued
+ mismatch.
+
+## Changes
+
+- `apps/mes/app/services/models.ts` — add optional `exclusive` to
+ `productionEventValidator`.
+- `apps/mes/app/routes/x+/event.tsx` — on `Start` with `exclusive`, end other-typed
+ open events (op+employee) and post each before starting.
+- `apps/mes/app/components/AssemblyView.tsx`
+ - drop `selectedWorkType`/`openEventForType`; add `headerWorkTypes` +
+ `openEventForWorkType(type)`.
+ - header: map `headerWorkTypes` → `TimerControl`.
+ - `TimerControl`: add hidden `exclusive=true`.
+ - step automation first-step Labor start: add `exclusive=true`.
+ - `AutoTimer`: start `headerWorkTypes[0]`, set `exclusive`.
+ - `TimeRows`/`TimerRow`: display-only, dot = running.
+
+## Verify
+
+- `pnpm exec turbo run typecheck --filter=mes`
+- Manual: setup+labor op → tapping Labor stops Setup and vice-versa; recording
+ first step auto-switches Setup→Labor; never both running. Labor-only op behaves
+ as before.
diff --git a/.ai/plans/2026-07-25-assembly-view-issue-additional-parts.md b/.ai/plans/2026-07-25-assembly-view-issue-additional-parts.md
new file mode 100644
index 0000000000..3530513e53
--- /dev/null
+++ b/.ai/plans/2026-07-25-assembly-view-issue-additional-parts.md
@@ -0,0 +1,165 @@
+# Plan: Issue additional (non-BOM) parts from the Assembly view
+
+**Date:** 2026-07-25
+**Branch:** feat/mes-assembly
+**Files:** `apps/mes/app/components/AssemblyView.tsx`, `apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx`, `apps/mes/app/routes/x+/issue.tsx`, `apps/mes/app/services/models.ts`, `packages/database/supabase/functions/issue/index.ts`
+
+## Goal
+
+In the MES **Assembly view** (`AssemblyView.tsx`), give the operator the same ability the
+standard Job Operation view has: **issue an additional part that isn't on the bill of
+material**. The added part must then appear in the **Parts** section of the *step/unit it
+was added on*, rendered as **X/0** (issued / required, where required is 0 because it's
+unplanned).
+
+## What already exists (no work needed)
+
+- `IssueMaterialModal` is **already wired** into `AssemblyView` (line ~1982). Opening it
+ with `selectedMaterial = null` → `material={undefined}` puts the modal into
+ "pick any item" mode (the same mode `JobOperation`'s "Issue Material" button uses).
+ The `issue` edge function already **creates a new `jobMaterial` on the fly** when
+ `materialId` is absent, for both the untracked (`partToOperation`) and tracked
+ (`trackedEntitiesToOperation`) paths. So the item-picker + create-material flow is done.
+- The `jobMaterialStep` join table (material ↔ step) already exists
+ (`20260705143722_mes-assembly-view.sql`). **No migration needed.**
+
+## The two gaps to close
+
+1. **No button** in the Assembly Parts section to open the modal in "add" mode.
+2. An unplanned part currently becomes an **unscoped "General" material** (it renders on
+ step 1 only, not the step it was added on) and its **X/0 renders wrong** (shows `×0`
+ with issued=0) because:
+ - The `issue` function never inserts a `jobMaterialStep` link when it creates a
+ material on the fly, so `jobOperationStepIds` comes back empty → "General".
+ - `getIssuedForUnit` caps issued at `Math.min(required, …)`; with `required === 0`
+ that forces `issued = 0`. And the loose-part backflush override sets it to `0`.
+
+## Design decisions (flag for veto)
+
+- **Scope the added part to the current step.** Plumb `jobOperationStepId` through the
+ untracked issue path and have the `issue` function insert a `jobMaterialStep` row
+ whenever it creates a material on the fly *and* a step id is present. This is what makes
+ it show "for that step" and (as a side effect) removes the loose-part override so X/0
+ renders correctly. Opt-in: `JobOperation`'s untracked flow sends no step id, so its
+ behavior is unchanged.
+- **Render an unplanned part (`required === 0`, `issued > 0`) as emerald `X/0 ✓`** plus a
+ subtle outline **"Added"** badge to distinguish it from BOM lines. (Alternative: neutral
+ muted `X/0`. Amber "partially issued" would be misleading — there's nothing outstanding.)
+- **An unplanned (required 0) tracked part must never gate step completion.** Exclude
+ `required === 0` from `pendingScanMaterials`.
+- **Button style:** compact `IconButton` (`LuPlus`, `variant="ghost"`, `size="sm"`,
+ `aria-label="Issue material"`) in the Parts section header — fits the 280–320px sidebar
+ better than `JobOperation`'s full-width `size="lg"` button.
+- **Per-unit for untracked extras:** untracked `quantityIssued` is job-wide, so a
+ multi-unit build shows the same total on step N of every unit. Acceptable for ad-hoc
+ parts; noted, not solved.
+
+---
+
+## Tasks
+
+### Task 1 — Add the "Add part" button to the Assembly Parts section
+
+`apps/mes/app/components/AssemblyView.tsx`
+
+- Add an optional `action?: React.ReactNode` prop to `SidebarSection` (~line 2387) and
+ render it right-aligned in the header (`flex items-center justify-between`).
+- Restructure the Parts block (~lines 1821-1852) so the `SidebarSection title="Parts"`
+ **always renders with the action**, showing the rows when present and the
+ "No materials assigned" text otherwise (so the button exists even on a step with no
+ parts).
+- Action = `IconButton` with `LuPlus`; onClick: `setSelectedMaterial(null); issueModal.onOpen();`
+ (no `flushSync` needed — the modal is conditionally mounted and reads the null value on
+ the next render; `onClose` already resets `selectedMaterial` to null).
+- Import `LuPlus` from `react-icons/lu`.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/mes` passes. Browser: an
+"add" (+) control appears in the Parts header on every step.
+
+### Task 2 — Fix the issued/required derivation & display for unplanned parts
+
+`apps/mes/app/components/AssemblyView.tsx`
+
+- `getIssuedForUnit` (~line 2429): when `required === 0`, return `issued = totalIssued`
+ (skip the `Math.min(required, …)` cap that otherwise forces 0). Keep
+ `fullyIssued = required > 0 && issued >= required` (extras are never "fully issued").
+- `MaterialRow` (~line 2453): add an `isExtra = required === 0` branch. When
+ `isExtra && issued > 0`, render emerald `{issued}/{required}` with `LuCheck` and an
+ emerald status dot; add an outline **"Added"** badge. When `isExtra && issued === 0`,
+ fall back to neutral `×0`.
+- `pendingScanMaterials` (~line 817): add `v.state.required > 0` to the filter so a
+ required-0 tracked extra never blocks step completion.
+
+**Verify:** typecheck passes. (Full visual proof in Task 6.)
+
+### Task 3 — Plumb `jobOperationStepId` through the untracked issue path
+
+- `IssueMaterialModal.tsx` untracked `ValidatedForm` (~lines 1165-1291): add
+ `<Hidden name="jobOperationStepId" value={jobOperationStepId ?? ""} />` (the prop is
+ already received by the modal).
+- `apps/mes/app/services/models.ts` `issueValidator` (~line 111): add
+ `jobOperationStepId: zfd.text(z.string().optional())`.
+- `apps/mes/app/routes/x+/issue.tsx` action: read `jobOperationStepId` from the validated
+ data and add it to the `functions.invoke("issue", { body: { … } })` body (~lines 80-91).
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/mes` passes.
+
+### Task 4 — Insert the `jobMaterialStep` link when the `issue` function creates a material
+
+`packages/database/supabase/functions/issue/index.ts`
+
+- Add `jobOperationStepId?: string` to the `partToOperation` payload validator (~line 826).
+- **Untracked** (`partToOperation`, new-material insert ~lines 1528-1546): after inserting
+ the `jobMaterial` (capture its `id`), if `jobOperationStepId` is present, insert into
+ `jobMaterialStep` `{ jobMaterialId, jobOperationStepId }` with
+ `.onConflict((oc) => oc.doNothing())`.
+- **Tracked** (`trackedEntitiesToOperation`, new-material insert ~lines 2012-2032):
+ `jobOperationStepId` already reaches this case; after creating the material (it already
+ `.returning("id")`), insert the same `jobMaterialStep` link (guarded on
+ `jobOperationStepId` present, `onConflict doNothing`).
+- Both inserts run inside the existing Kysely transaction. `jobMaterialStep` has no
+ `companyId` (RLS reaches company via the parent `jobMaterial`) — only the two FK columns.
+
+**Verify:** the function is exercised via the app in Task 6 (edge functions run in the
+local `edge-runtime` container, live-mounted — no deploy step). Sanity: `pnpm run lint`.
+
+### Task 5 — Ensure the view refreshes after an add
+
+`apps/mes/app/components/AssemblyView.tsx`
+
+- The untracked path submits via navigation `ValidatedForm` and the tracked path via
+ `fetcher.submit`; both trigger a React Router revalidation of the Assembly loader, which
+ re-runs `getJobMaterialsByOperationId` and returns the new material with its
+ `jobOperationStepIds`. Confirm this in Task 6.
+- If (and only if) revalidation proves flaky, add a `jobMaterial` subscription to the
+ existing `useRealtimeChannel` (~line 532). Do **not** add it speculatively.
+
+### Task 6 — Browser verification (mandatory)
+
+Use `/auth` + agent-browser against the running dev stack (`crbn up`).
+
+- Open an Assembly operation. On a middle step (e.g. step 3), click the new **+** in Parts.
+- **Untracked item:** pick a non-tracked part, issue qty 2. Confirm it appears in Parts on
+ step 3 (not step 1) as **`2/0`** (emerald, "Added" badge) and that step 3 can still be
+ completed.
+- **Tracked item:** pick a serial/batch part, scan/select, confirm it shows scoped to the
+ step and does **not** block completion.
+- Navigate to another step and confirm the added part is **not** shown there.
+- Screenshot both states for the PR (net-new UI).
+
+**Verify:** all of the above; capture screenshots to `.ai/scratch/e2e/` for the PR body.
+
+---
+
+## Out of scope / notes
+
+- No DB migration (`jobMaterialStep` already exists).
+- Per-unit attribution for untracked extras on multi-unit builds is job-wide (noted above).
+- `JobOperation`'s behavior is unchanged: it never passes `jobOperationStepId` on the
+ untracked path, so no link is created there.
+
+## Risk
+
+- Editing the shared `issue` edge function: change is guarded by `jobOperationStepId`
+ presence **and** the new-material branch, so BOM issuing and `JobOperation` are untouched.
+- `onConflict doNothing` keeps the link insert idempotent under the deploy runner's retry.
diff --git a/.ai/plans/2026-07-25-disposition-non-tracked-parts.md b/.ai/plans/2026-07-25-disposition-non-tracked-parts.md
new file mode 100644
index 0000000000..51446f2bcc
--- /dev/null
+++ b/.ai/plans/2026-07-25-disposition-non-tracked-parts.md
@@ -0,0 +1,73 @@
+# Disposition of non-tracked parts from a failed inspection
+
+## Problem
+
+Today disposition is driven entirely by tracked-entity links
+(`nonConformanceItemTrackedEntity`):
+
+- `AssociatedItemsList.tsx:220` filters to `rows.filter(r => r.links.length > 0)`
+ and returns `null` when nothing has links — a non-tracked part's disposition
+ card is **hidden**.
+- `closeIssue` (`quality-disposition.server.ts`) does `if (row.links.length === 0)
+ continue;` in its validation and posting loops — a non-tracked row's disposition
+ is **silently ignored** at close.
+
+So a non-tracked part (`Inventory` / `Non-Inventory`) that fails inspection — or a
+MES job-operation quality issue (`quality-issue.new.tsx`, which already creates a
+link-less `nonConformanceItem` with a real `quantity`) — gets an NCR row you can't
+see and a disposition that does nothing.
+
+## Decisions (resolved with user)
+
+- **Ledger model: Option A** — keep the inspection reject's compensating on-hand
+ removal for `Inventory` as-is (quarantine at reject). Disposition adds the
+ minimal inventory effect only.
+- **No split for non-tracked** — one disposition per non-tracked row (the existing
+ split/move UI stays gated on `links.length > 0`, so it's already excluded).
+- **Works for MES too** — MES-originated NCRs are dispositioned on the ERP Issue
+ page. `closeIssue`/`AssociatedItemsList` are source-agnostic, so no new MES UI is
+ built in this change. (A shop-floor disposition control in `AssemblyView` is a
+ possible follow-up, explicitly out of scope here.)
+
+### Correct ledger effect per origin × disposition (non-tracked)
+
+| Origin | Reject pre-removed on-hand? | Scrap / Return | Use As Is / Rework |
+|---|---|---|---|
+| Inspection, `Inventory` | yes (`−lot` at reject) | no-op (already gone) | **`+qty` restore** |
+| Inspection, `Non-Inventory` | no (never had a ledger) | no-op | no-op |
+| MES / manual | no | no-op (WIP scrap is a separate production concern) | no-op |
+
+Net: the **only** ledger `closeIssue` posts for a link-less row is a `+qty`
+`Positive Adjmt.` to restore on-hand when an **inspection-originated** **Inventory**
+lot is **kept** (Use As Is / Rework), undoing the reject's `Negative Adjmt.`
+Everything else non-tracked is a quality record only. Origin is detected via the
+presence of a `nonConformanceInspection` link on the NCR (only the reject route
+creates one, and it always removes on-hand for `Inventory`).
+
+## Tasks
+
+### 1. `apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx`
+- Stop hiding link-less rows: render all `rows` (was `rows.filter(r => r.links.length > 0)`).
+- `sumMismatch` only applies when links exist: `links.length > 0 && Math.abs(linkedSum - quantity) > 1e-6`.
+- Entity chips, split, and "Move entities" are already gated on `links.length > 0` — non-tracked rows show just quantity + the disposition `Select`. Update the stale header comment.
+- Verify: `pnpm exec turbo run typecheck --filter=@carbon/erp`.
+
+### 2. `apps/erp/app/modules/quality/quality-disposition.server.ts` (`closeIssue`)
+- Preflight + in-transaction validation loops: check `Pending` for **all** rows;
+ skip only the link-sum / link-status checks for link-less rows.
+- Before the posting loop, batch-load `item.itemTrackingType` for link-less rows'
+ item ids and detect inspection origin (`nonConformanceInspection` link).
+- In the posting loop, handle `row.links.length === 0`: post the `+qty` restore for
+ inspection-originated `Inventory` on Use As Is / Rework; otherwise record only.
+- Verify: `pnpm exec turbo run typecheck --filter=@carbon/erp` + `pnpm --filter @carbon/erp test`.
+
+### 3. Docs
+- Update `.claude/rules/issue-module.md` + `.claude/rules/inspection-system.md`
+ disposition notes to reflect non-tracked support.
+
+## Verification
+- Typecheck ERP.
+- Browser: reject a non-tracked (Inventory) inbound inspection → NCR opens → the
+ Disposition card now shows the quantity row; set Use As Is → close → on-hand
+ restored. Set Scrap → close → no extra ledger. MES quality issue on a non-tracked
+ part → dispositionable + closes on the ERP Issue page.
diff --git a/.ai/plans/2026-07-25-inspection-disposition-gl-posting.md b/.ai/plans/2026-07-25-inspection-disposition-gl-posting.md
new file mode 100644
index 0000000000..9c9b3f7181
--- /dev/null
+++ b/.ai/plans/2026-07-25-inspection-disposition-gl-posting.md
@@ -0,0 +1,89 @@
+# Plan: GL + cost posting for inspection reject & NCR disposition
+
+Addresses the gaps in `.ai/research/2026-07-25-inspection-disposition-accounting-audit.md`: inspection/disposition move inventory quantity but post no cost or GL. Goal: every inventory-value movement in these flows also relieves/creates cost layers and posts a balanced GL journal, gated on `accountingEnabled`, reusing the proven `bookAdjustment`/`calculateCOGS` core — with a proper scrap (cost-of-quality) expense.
+
+## Key decisions (recommendations — confirm before building)
+
+### D1 — Accounting model: **"GL follows the physical movement"** — ✅ LOCKED (A), grill 2026-07-25
+Post cost + GL at exactly the points inventory **quantity** already moves today, so the ledgers stay 1:1 with on-hand. Blocked-stock/quarantine model (B) explicitly rejected for v1 (no new Quarantine asset account, no GL on the tracked-reject path); acceptable that a tracked rejected lot's value sits in the normal Inventory GL through the MRB hold, and that non-tracked writes off at reject while tracked writes off at Scrap disposition. Quarantine remains the documented future end-state.
+
+| Event | Qty today | Cost + GL to add |
+|-------|-----------|------------------|
+| Reject, non-tracked `Inventory` (`-lotSize`) | removes on-hand | relieve layers (`calculateCOGS`); **Dr Scrap, Cr Inventory** |
+| Reject, tracked / `Non-Inventory` | status flip only | **none** (value stays until Scrap disposition) |
+| Disposition **Scrap** (tracked `-qty`/entity; non-tracked non-inspection `-qty`) | removes on-hand | relieve layers; **Dr Scrap, Cr Inventory** |
+| Disposition **Return to Supplier** | removes on-hand | v1 = same as Scrap write-off (see D3) |
+| Disposition **Use As Is / Rework** restore (non-tracked, inspection `Inventory`, `+qty`) | adds on-hand | create layer; **Dr Inventory, Cr Scrap** (reverse the reject write-off) |
+| Disposition Use As Is / Rework, tracked | status→Available | **none** (value never left Inventory) |
+| Batch split (net-zero) | net-zero | **none** (no value change) — leave as-is |
+
+Inventory side = `finishedGoodsAccount`/`rawMaterialsAccount` by `replenishmentSystem` (reuse `resolveInventoryAccount`). This directly fixes the user's complaint and reuses `bookAdjustment` unchanged in shape.
+
+*Alternative (not recommended for v1): blocked-stock model* — reject reclassifies Inventory→a new **Quarantine/Nonconforming Inventory** asset account for the whole lot (tracked + non-tracked, uniform), disposition settles Quarantine→Scrap/Inventory/Receivable. More correct (doesn't expense until the scrap decision; removes the tracked/non-tracked timing asymmetry of G1/G2) but needs a quarantine account, GL on the tracked-reject path, and cost-basis timing care. Note as the future end-state.
+
+### D2 — Scrap account: **add `scrapAccount` to `accountDefault`** — ✅ LOCKED (A + backfill), grill 2026-07-25
+Dedicated column for cost-of-quality visibility distinct from physical-count adjustments. Flat additive column (well-precedented: `20260711042617_add-overhead-absorption-account.sql` etc.) — **not** a posting-group matrix.
+- **Backfill (required, user-emphasized):** in the same migration, `UPDATE "accountDefault" SET "scrapAccount" = "inventoryAdjustmentVarianceAccount" WHERE "scrapAccount" IS NULL` — both are `account.id` FKs, valid per company; every existing company already has a seeded `inventoryAdjustmentVarianceAccount`, so none is left null. Idempotent (guarded on NULL). Column is **nullable** and the edge fn keeps a runtime fallback `offset = scrapAccount ?? inventoryAdjustmentVarianceAccount` as defense in depth.
+- **New companies:** add a distinct **`5320 "Scrap / Cost of Quality"`** account to the seed chart (`functions/lib/seed.data.ts`), seeded as a **child of the existing `inventory-adjustments` group** (sibling of `5310`, which sits under COGS) — `{ key: "5320", number: "5320", name: "Scrap / Cost of Quality", isGroup: false, parentKey: "inventory-adjustments", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" }`. It **must** have a parent (`parentKey: "inventory-adjustments"`) — no orphan accounts. Then seed `accountDefault.scrapAccount → 5320` so fresh companies get the separated P&L line out of the box. (Existing companies are NOT given a new 5320 row — the backfill points them at their existing variance account; they can reassign in the UI.)
+- Add `scrapAccount` to the zod validator (`accounting.models.ts`) + a field in `AccountDefaultsForm.tsx` (Inventory section).
+
+### D3 — Return to Supplier GL: **v1 = write-off to Scrap** — ✅ LOCKED (A), grill 2026-07-25
+Return to Supplier posts the **same** movement as Scrap — Dr `scrapAccount` / Cr Inventory + relieve cost layers — because no vendor-RMA/debit-memo flow exists to book a supplier receivable. Accepted trade-off: slightly overstates cost-of-quality scrap for the (small) return population; reclassify when the supplier credit is later booked in purchasing/AP. GR/IR-clearing (B) and defer (C) rejected: (B) leaves a GR/IR balance that may never clear (already-invoiced lines) and needs the missing credit-memo flow; (C) re-strands value in Inventory. Proper vendor-RMA/debit-memo (the real home for a supplier receivable) is documented future work.
+
+### D4 — Architecture: **new edge fn `post-nonconformance`** sharing `bookAdjustment`
+Cost/GL logic is Deno-only (`functions/shared/*`); app code can't call it. Add `packages/database/supabase/functions/post-nonconformance/index.ts` that takes a batch of movements + context and calls `bookAdjustment` per movement (extended to accept an **offset-account override** so the scrap account is used instead of the variance account). It resolves the accounting period once, is gated on `accountingEnabled`, and targets **specific existing `trackedEntityId`s** (disposition scrap of a serial/batch lot). Register in `config.toml`. This mirrors how `post-inventory-count` already reuses `bookAdjustment`.
+
+Consistency: keep tracked-entity **status flips + `trackedActivity`** where they are (app Kysely in `closeIssue`/`dispositionInspection`); the edge fn owns **itemLedger + costLedger + journal**. Order the calls so a GL failure aborts the close (invoke the edge fn, check `{error}`, only then set `status = Closed`). Reject already spans multiple route steps, so a second call there is consistent with the existing shape.
+
+### D5 — Reversal on NCR reopen: **block reopen once GL posted** — ✅ LOCKED (A, SAP-aligned), grill 2026-07-25
+When a close posted GL for this NCR, **block reopen** (`Closed→Registered`) with a clear message; guard on the existence of any `journal` (or `costLedger`/`itemLedger`) row with `documentType 'Non-Conformance'` + `documentId = ncrId`. Scope is narrow — only NCRs that actually posted GL are blocked (accounting-enabled + real inventory movements; an all-Use-As-Is/tracked NCR posts nothing and stays freely reopenable).
+- **Rationale (SAP-aligned):** SAP never reopens/edits a posted document — corrections are **forward compensating reversals** (MBST / reversal movement types), posted into the current open period, original preserved for audit. In QM you post *further* stock postings against the lot rather than un-making the Usage Decision.
+- **End-state (future, NOT (B)):** an explicit **"reverse & re-disposition"** action that posts compensating journals/movements in the current open period — deliberately **not** an in-place auto-unwind. This also sidesteps Carbon's real-time FIFO `costLedger` layer-relief problem (un-consuming specific layers), which SAP avoids only because its real-time valuation is MAP/standard.
+- Implement in `updateIssueStatus` / `x+/issue+/$id.status.tsx` (reopen path).
+
+## Tasks
+
+### Phase 0 — Account + schema (D2) — ✅ DONE (migration applied, types regen, erp typecheck green)
+- [x] `20260726012013_add_scrap_account.sql` — add `accountDefault.scrapAccount TEXT` (FK `account.id`, RESTRICT), idempotent backfill → `inventoryAdjustmentVarianceAccount`.
+- [x] Seed `5320 "Scrap / Cost of Quality"` (under `inventory-adjustments`) + `accountDefaults.scrapAccount: "5320"` in `functions/lib/seed.data.ts`.
+- [x] `scrapAccount` (optional) in `defaultIncomeAcountValidator` + field in `AccountDefaultsForm.tsx` (Standard Cost Variances, next to Inventory Adjustment).
+- [x] `pnpm run generate:types`; `turbo typecheck --filter=erp` green.
+
+### Phase 1 — `post-nonconformance` edge fn (D4) — ✅ DONE (deno check clean, erp typecheck green)
+- [x] **Discovered gap + fix:** `journalLineDocumentType` and `journalEntrySourceType` lacked `Non-Conformance`/`Inbound Inspection` (only `itemLedgerDocumentType` had them). Added via `20260726013204_add_nonconformance_journal_doctypes.sql` (additive `ALTER TYPE ADD VALUE`, mirrors `20260619142853`) so NCR/inspection GL journals are first-class + traceable (like `Asset Disposal`). Also updated the ERP `journalEntrySourceTypes` const array + `JournalEntrySourceTypeIcon` (LuTriangleAlert / LuClipboardCheck) so the enum widening typechecks.
+- [x] `functions/shared/post-adjustment.ts::bookAdjustment` extended additively: `accounting.offsetAccount`/`offsetDescription` (default `inventoryAdjustmentVarianceAccount`/"Inventory Adjustment") + `accounting.sourceType` + `createAdjustmentJournal` sourceType param + widened `ledger.documentType` union. `post-inventory-adjustment`/`post-inventory-count` unaffected (all new fields optional).
+- [x] `functions/post-nonconformance/index.ts` — payload `{ companyId, userId, documentType, documentId, description?, postingDate?, movements: [{ itemId, locationId?, trackedEntityId?, quantity(signed), comment? }] }`; `requirePermissions(update:"quality")`; resolves period + defaults + dimensions before the txn; ONE shared journal per call (lazy `getJournalId`); offset = `scrapAccount ?? inventoryAdjustmentVarianceAccount`; sourceType = documentType. Registered in `config.toml`.
+- [x] `deno check` clean (only the shared-lib baseline the reference function also shows); `turbo typecheck --filter=erp` green; biome clean.
+- [ ] Runtime-exercise via the reject/close routes locally → deferred to Phase 6 (needs wiring first).
+
+### Phase 2 — Wire inspection reject (D1 row 1) — ✅ DONE (erp typecheck + biome green)
+- [x] `dispositionInspection` no longer writes the non-tracked `itemLedger`; it returns a `writeOff { itemId, quantity: -lotSize, locationId } | null` (the `status !== "Failed"` guard dropped — idempotency covers retries).
+- [x] `x+/inspection+/$id.reject.tsx` invokes `post-nonconformance` with the write-off (documentType `Inbound Inspection`, documentId = inspection.id) after `dispositionInspection`; a posting failure is logged, not fatal (lot already Rejected).
+
+### Phase 3 — Wire NCR close (D1 rows 3–6) — ✅ DONE (erp typecheck + biome + 10 tests green)
+- [x] `closeIssue` refactored: preflight now loads issue + origin (`inventoryItemIds`, `inspectionOriginated`), builds `movements[]`, and invokes `post-nonconformance` (documentType `Non-Conformance`, documentId = ncrId) BEFORE the txn; a GL failure returns `errResult` and aborts the close. The txn now owns only re-validation + `trackedActivity` + status flips (`Available`/`Rejected`) + `status = Closed` — **all `itemLedger` inserts removed**.
+- [x] Movement rules: tracked Scrap/Return → `-link.qty` per link; non-tracked Inventory non-inspection Scrap → `-row.qty`; non-tracked Inventory inspection Use-As-Is/Rework → `+row.qty` restore; everything else no movement.
+- [x] Batch split: unchanged (net-zero, no GL).
+
+### Phase 4 — Reopen guard (D5) — ✅ DONE (erp typecheck + biome green)
+- [x] `x+/issue+/$id.status.tsx`: reopening (status ≠ Closed) an NCR that is currently `Closed` and has any `itemLedger` with `documentType='Non-Conformance'` + `documentId=ncrId` is blocked with a clear message. Guard reads via **service role** (itemLedger SELECT needs inventory/accounting_view; a quality user could fail open).
+
+### Phase 5 — Xero adjustment-sync guard (G7) — ✅ DONE (@carbon/ee typecheck + biome green)
+- [x] `InventoryAdjustmentSyncer.fetchAdjustmentsByIds` excludes `documentType IN ('Non-Conformance','Inbound Inspection','Batch Split')` while keeping NULL (manual) rows — prevents wrong/duplicate Xero ManualJournals now that NCR/inspection have their own local scrap-account journals.
+
+### Phase 6 — Verification — ⏳ USER-OWNED (browser). Static gates all green.
+- Static: `deno check` (post-nonconformance/post-adjustment, own-file clean), `turbo typecheck --filter=erp` + `--filter=@carbon/ee` green, biome clean, quality vitest 10/10.
+- **Edge-runtime note:** the new `post-nonconformance` function + `config.toml` entry may need the edge-runtime container to be restarted to be served locally (`crbn up` live-mounts the functions dir; a new `[functions.*]` entry can require a restart).
+- Enable accounting locally (`/x/settings/accounting`, per project memory) before testing GL.
+- Suggested matrix (accounting ON): (a) receive an inspection `Inventory` item → reject → assert `journal` (sourceType `Inbound Inspection`, Dr Scrap 5320 / Cr Inventory) + `costLedger` relief + `itemLedger`; (b) serial lot → NCR Scrap → close → per-entity GL + cost relief, entities `Rejected`; (c) inspection non-tracked → Use As Is → close → `+qty` restore reverses the reject write-off; (d) MES/manual non-tracked → Scrap → close → `-qty` write-off; (e) tracked Use As Is → close → entities `Available`, **no** GL; (f) accounting OFF → `itemLedger` + cost layers only, no journal; (g) try to Reopen a closed NCR that posted → blocked.
+- Confirm the inventory valuation report reconciles against the GL Inventory account; scrapped/rejected value lands in `5320`.
+
+## Decisions — all resolved (grill 2026-07-25)
+1. **Model** → **A** "GL follows the physical movement" (blocked-stock/quarantine deferred as future). See D1.
+2. **Scrap account** → **A** dedicated `accountDefault.scrapAccount`, backfilled to `inventoryAdjustmentVarianceAccount`, new `5320 "Scrap / Cost of Quality"` seeded under the `inventory-adjustments` group (must have a parent). See D2.
+3. **Return to Supplier** → **A** write-off to `scrapAccount`, same as Scrap. See D3.
+4. **Reopen after GL** → **A** block (SAP-aligned); future "reverse & re-disposition" compensating action. See D5.
+5. **Standard-cost items** → uniform: relieve `calculateCOGS` carrying cost, full amount Dr `scrapAccount` / Cr Inventory, **no variance split** at disposal (variance arises at purchase/production, not scrap). Applies in the Phase 1 valuation.
+
+### D4 — Architecture (plan of record, not re-grilled): new `post-nonconformance` edge fn sharing `bookAdjustment`
+Confirmed as the approach — cost/GL logic is Deno-only, so app code cannot post it; a new edge fn calling the shared `bookAdjustment` (extended for a scrap offset account + specific `trackedEntityId` targeting) is the consistent, atomic home. Status flips + `trackedActivity` stay in app code; the edge fn owns `itemLedger + costLedger + journal`. Details in the D4 section above and Phases 1–3.
diff --git a/.ai/plans/2026-07-25-unify-inspection-execution-ui.md b/.ai/plans/2026-07-25-unify-inspection-execution-ui.md
new file mode 100644
index 0000000000..9f46137043
--- /dev/null
+++ b/.ai/plans/2026-07-25-unify-inspection-execution-ui.md
@@ -0,0 +1,157 @@
+# Unify inspection execution UI (grid+drawing as the only flow)
+
+Date: 2026-07-25
+Status: Implemented (Option B). Typecheck/lint/tests green; browser verification
+pending.
+
+## Problem
+
+`/x/inspection/{id}` has two divergent execution screens, chosen purely by
+document presence (`InspectionView.tsx:148`):
+
+```ts
+const hasDocument = pdfUrl != null && liveFeatures.length > 0;
+```
+
+- **Grid + drawing** (`hasDocument`): ballooned PDF over a features × samples
+ grid (`InspectionMeasurementGrid.tsx`). Cells record measured values /
+ attribute pass-fail per feature. Sample status is derived.
+- **Fallback samples table** (no document): "Inspect Next Item" → scan modal in
+ `mode="record"` → one Passed/Failed `inspectionSample` per scanned entity. No
+ drawing, no per-feature values (`InspectionView.tsx:645-748`).
+
+The two screens differ in **both** axes at once (the observed serial lot had no
+document; the observed non-serial lot had one), which is why they look unrelated.
+
+## Key facts established from the code
+
+1. **The grid already scans tracked entities.** For serial lots it renders a
+ `+ Sample` column whose button calls `onAddSample` → `ScanInspectionSample`
+ in `mode="identify"`, creating a **Pending** sample with a `trackedEntityId`
+ (`InspectionMeasurementGrid.tsx:464-479`, `InspectionView.tsx:617`,
+ `ScanInspectionSample.tsx:155-158`).
+2. **The grid already labels serial columns with the entity, not `1,2,3`.**
+ Header = `sample?.trackedEntity?.readableId ?? \`${i+1}\`` for serial,
+ plain index for non-serial (`InspectionMeasurementGrid.tsx:369-374`).
+3. **The schema already supports "scanned entity + per-feature
+ measurements on the same sample."** A measurement attaches to a sample by
+ `inspectionSampleId`; the sample's `trackedEntityId` is orthogonal.
+ `upsertInspectionMeasurement` derives the sample's status from its
+ measurements and, when `sample.trackedEntityId` is set, flips that entity
+ `On Hold → Available/Rejected` (`quality.server.ts:678-750`). So a serial
+ part **with** a document already behaves exactly as requested.
+4. Both scan modes POST the same `inspectionSampleValidator` to `$id.sample.tsx`;
+ only the `status` differs (`identify` → `Pending`, `record` → `Passed/Failed`).
+5. `dispositionInspection` gates per-feature when the lot has
+ `inspectionSamplingPlan` rows, else lot-level on sample pass/fail counts
+ (`quality.server.ts:329-379`).
+
+**Conclusion:** the only thing making the flows feel exclusive is UI routing +
+the fact that a lot with no document has no feature rows to fill a grid with.
+Unification = make the grid+drawing shell the sole UI and give it a "no
+features" mode; retire the fallback table and `mode="record"`.
+
+## Target design
+
+One component (`InspectionView` + `InspectionMeasurementGrid`) for every lot:
+
+- **Drawing pane**: shown when `pdfUrl != null`; hidden otherwise (grid takes the
+ full height). No fallback screen.
+- **Rows**:
+ - Document lots → the real `inspectionFeature` rows (unchanged).
+ - No-document lots → a single synthetic **"Overall result"** attribute row
+ (pass/fail), so there is always something to record.
+- **Columns** (unchanged from today's grid):
+ - Serial → one column per scanned entity, header = `readableId`; new columns
+ added only via the scan step (`+ Sample`, identify mode). This is the "scan
+ the part we're observing" step the user wants, applied everywhere.
+ - Non-serial → anonymous numbered columns up to `sampleSize` (accepted for
+ non-tracked parts).
+- **Cells**:
+ - Numeric feature → measured value; attribute feature → P/F toggle
+ (unchanged).
+ - "Overall result" row → P/F toggle that sets the **sample's** status
+ directly (see D1).
+
+Net UX: identical grid+drawing everywhere; serial parts always scan the entity
+per column; non-document lots collapse to a one-row pass/fail grid instead of a
+separate screen.
+
+## D1 — How the "Overall result" row persists (DECISION NEEDED)
+
+A no-document lot has no `inspectionFeature` / `inspectionSamplingPlan` rows, so
+there is nothing for `upsertInspectionMeasurement` to attach to.
+
+- **Option A — synthetic feature at receipt.** Materialize one implicit
+ "Overall" `inspectionFeature` + `inspectionSamplingPlan` per no-document lot so
+ every path (grid, measurement save, derived status, per-feature disposition
+ gating) works with zero special-casing. *Downside:* `inspectionFeature` rows
+ belong to an `inspectionDocument`; creating them without one is a schema smell
+ and touches `post-receipt`.
+- **Option B — recommended — grid renders a client-only "Overall result" row;
+ its P/F cells write via the sample route** (`$id.sample.tsx`, setting the
+ column's sample `Passed`/`Failed`) rather than the measurement route. Server
+ stays as-is except: allow `upsertInspectionSample` to **update an existing
+ sample by id** (so toggling a non-serial anonymous column is idempotent, using
+ the grid's existing `sampleIdByColumn` binding). No phantom features; reuses
+ the lot-level disposition path that already exists for document-less lots.
+
+Recommendation: **Option B.** It keeps `inspectionFeature` semantically tied to
+documents, adds one small server capability (sample upsert-by-id), and leans on
+the derived-vs-direct status split the schema already has.
+
+## Tasks (assuming D1 = Option B)
+
+1. **Grid: "no features" mode.** In `InspectionMeasurementGrid.tsx`, when the lot
+ has no live features, render a single "Overall result" attribute row. Its P/F
+ buttons POST to `$id.sample.tsx` for the column's sample (create-on-demand for
+ non-serial via the same lazy `sampleIdByColumn` pattern used for
+ measurements). Mirror status locally like measurement saves.
+ - Verify: no-document serial lot — scan entity, toggle Pass, column shows
+ Passed, entity → Available; no-document non-serial lot — toggle Pass on
+ column 1 creates one Passed sample (toggling again updates, not duplicates).
+
+2. **Server: sample upsert-by-id.** Extend `upsertInspectionSample`
+ (`quality.server.ts:108-223`) / `inspectionSampleValidator` to accept an
+ optional `sampleId` and update that row's status in place (non-serial
+ anonymous case). Keep serial upsert-by-`trackedEntityId` behavior.
+ - Verify: `pnpm --filter erp test` for any sample tests; manual toggle twice
+ yields one row.
+
+3. **InspectionView: always render the grid shell.** Delete the fallback branch
+ (`InspectionView.tsx:645-748`) and always render the drawing (if `pdfUrl`) +
+ grid. Compute `hasDocument` only to decide drawing visibility and the
+ feature-vs-overall row set. Drop `mode="record"`; scanning always uses
+ `mode="identify"`.
+ - Verify: typecheck `erp`; both lot kinds render the grid.
+
+4. **Retire fallback-only code.** Remove `mode="record"` from
+ `ScanInspectionSample.tsx` (identify-only) and the now-unused fallback samples
+ table markup + `BarProgress`/manual pass-fail imports in `InspectionView`.
+ - Verify: `pnpm run lint`; no dead imports.
+
+5. **Disposition parity check.** Confirm `dispositionInspection` still gates
+ correctly for no-document lots now that status comes from the "Overall result"
+ row (lot-level path at `quality.server.ts:329-379` already keys off sample
+ pass/fail counts when there are no plan rows — should need no change; verify).
+
+6. **Docs.** Update `.claude/rules/inspection-system.md` (the "two execution
+ flows" section) to describe the single grid UI with an optional drawing and a
+ synthetic overall-result row; note `mode="record"` removed.
+
+## Out of scope / not changing
+
+- Sampling-plan resolution, AQL engine, receipt-time lot creation (except the
+ optional Option-A path, which we are not taking).
+- The already-correct document-driven serial behavior.
+- MES reuse (the component stays data-prop reusable for later).
+
+## Verification (end state)
+
+- Serial + no document: scan entity → grid column labeled with `readableId` →
+ Overall result P/F → entity releases. (Replaces screenshot-1 screen.)
+- Non-serial + document: unchanged rich grid. (Screenshot 2.)
+- Serial + document: unchanged rich grid, scanned columns.
+- Non-serial + no document: one-row pass/fail grid, anonymous columns.
+- `pnpm exec turbo run typecheck --filter=erp`, `pnpm run lint`, and browser
+ e2e per `/test` on each of the four quadrants.
diff --git a/.ai/plans/2026-07-26-mes-inspection-view.md b/.ai/plans/2026-07-26-mes-inspection-view.md
new file mode 100644
index 0000000000..1b9135215d
--- /dev/null
+++ b/.ai/plans/2026-07-26-mes-inspection-view.md
@@ -0,0 +1,92 @@
+# MES Inspection Execution View (`operationType = 'Inspection'`)
+
+## Context
+
+This branch (feat/mes-assembly) added three pillars: (1) the MES Assembly view, (2) the unified quality-module inspection execution UI (tracked + non-tracked, currently receipt-only), and (3) the `operationType` consolidation (`Process | Assembly | Inspection | Outside Processing`) that routes MES execution views. The final step ties them together: a MES view at `/x/inspection/:operationId` for Inspection operations that executes the operation's inspection plan using the same quality `inspection` lot system, while keeping shop-floor actions (time, parts, scrap, rework, quality issues).
+
+Everything is staged for this:
+- `jobOperation.inspectionDocumentId` FK = the plan link ("the FK is the truth", migration `20260721022847`)
+- `inspection.sourceDocument` enum already has `'Job Operation'`; unique partial index on `(sourceDocument, sourceDocumentLineId)`; `dispositionInspection` already guards receipt-only stock logic ("Job Operation inspections act on WIP")
+- MES `resolveOperationView('Inspection') → "inspection"` is a reserved slot; `operation.$operationId.tsx:77-82` documents the fall-through "until its route ships (Phase 3)"
+- The 2026-07-21 spec: InspectionView was built data-prop "so the same UI can be attached to job operations in MES next"
+
+Note: the older 2026-07-14 spec §5.4 designed a separate `jobOperationInspectionRecord` table — **superseded** by the 2026-07-22 inspections refactor (generic source documents). This plan updates the spec accordingly.
+
+## Key decisions (approved via this plan)
+
+1. **One shared engine, no duplication.** The inspection engine (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `valuateMeasurement`) moves from `apps/erp/app/modules/quality/quality.server.ts` to a new **`@carbon/database/quality`** export (`packages/database/src/quality.ts`). Functions gain a `db: Kysely<KyselyDatabase>` first param; ERP's `quality.server.ts` becomes thin wrappers with unchanged names/signatures (zero ERP route changes). Verified: the engine's only deps are kysely, `KyselyDatabase`, validator-inferred types (replaced by plain package-side types), and the sampling resolver — no ERP-only imports.
+ - `packages/database/src/sampling.ts` re-exports the pure Deno `supabase/functions/shared/sampling-engine.ts` (same pattern `src/client.ts` already uses for the postgres client).
+2. **Lot creation is lazy find-or-create.** New `getOrCreateJobOperationInspection(db, { jobOperationId, companyId, userId })` in the package, called by the MES loader on first open. Mirrors post-receipt: resolves `itemSamplingPlan` + `companySettings.samplingStandard` (lotSize = `operationQuantity`), per-feature plans from the operation's `inspectionDocumentId`, inserts `inspection` (+ `inspectionSamplingPlan`) idempotently against the partial unique index (select-first in txn + 23505 fallback). Fields: `sourceDocument='Job Operation'`, `sourceDocumentId=job.id`, `sourceDocumentLineId=jobOperationId`, `sourceDocumentReadableId=job.jobId`, human id via the node-safe Deno `get-next-sequence` helper (sequence key `inspection`). **No DB migration needed** — verified enum, index, sequence re-key, and RLS all exist.
+3. **MES-native UI, same concepts.** MES cannot import ERP app code; ERP's grid depends on ERP-only `~/components/Table`/`Editable`. So (AssemblyView precedent): a new MES `InspectionView` (full-screen, `size="lg"`) with a **new plain-table measurement matrix** implementing the same contract as ERP's grid (features × samples, live valuation, derived statuses, quiet per-cell POSTs, synthetic "Overall result" row when no features, disabled cells beyond a feature's n). `InspectionDrawingPane` (react-pdf + konva balloons) copies **verbatim** (zero ERP deps); `RejectLotModal` copies near-verbatim (action URL already a prop); `ScanInspectionSample` adapts (`@carbon/form` imports, make-method WIP entities instead of receipt entities).
+4. **Job-op lots never touch WIP entity status.** Add `sourceDocument === "Receipt"` guards at the two entity-flip call sites (`upsertInspectionSample` ~L187, `upsertInspectionMeasurement` ~L744-767) during the move — receipt behavior is bit-identical; job WIP entities stay Reserved. `dispositionInspection` is already guarded (job-op Reject returns `writeOff: null` → no post-nonconformance invoke in MES).
+5. **Shop-floor actions reuse existing MES routes/modals** exactly as AssemblyView does: TimerControl → `/x/event`, Log Completed → QuantityModal → complete/finish, Scrap → QuantityModal → `/x/scrap`, Rework → ReworkModal, Quality Issue → QualityIssueModal → `/x/quality-issue/new`.
+6. **Reject creates the NCR via MES's own path** (not ERP's `insertIssue` flow): extract the NCR creation from `quality-issue.new.tsx` into `apps/mes/app/services/quality.server.ts` `createQualityIssue(...)` (links `nonConformanceJobOperation`), and the reject route adds the `nonConformanceInspection` link + ERP's failed-features description block (pure string building, copied).
+7. **New MES deps** (mirror ERP pins; needs approval per repo rules): `kysely: catalog:`, `konva ^9.3.22`, `react-konva ^18.2.10`, `pdfjs-dist 5.4.296`, plus ERP's canvas SSR stub + vite alias + pdf.js worker bootstrap.
+
+## Tasks
+
+### 1. Deps + plumbing
+- `apps/mes/package.json`: add `kysely`, `konva`, `react-konva`, `pdfjs-dist` (mirror `apps/erp/package.json` pins).
+- Copy `apps/erp/app/ssr-shims/canvas-stub.cjs` → `apps/mes/app/ssr-shims/`; add vite `resolve.alias` `canvas` entry (mirror `apps/erp/vite.config.ts:65`).
+- Add pdf.js worker bootstrap to `apps/mes/app/entry.client.tsx` (from ERP `entry.client.tsx:1-5`).
+- NEW `apps/mes/app/services/database.server.ts` — copy ERP's 30-line Kysely singleton verbatim.
+- Verify: `pnpm install && pnpm exec turbo run typecheck --filter=mes`
+
+### 2. Shared engine package (`@carbon/database/quality` + `/sampling`)
+- NEW `packages/database/src/sampling.ts`: `export * from "../supabase/functions/shared/sampling-engine.ts"`.
+- NEW `packages/database/src/quality.ts`: move engine bodies from ERP `quality.server.ts` (inventory: `Result`/`errResult`, `computeLotStatus`, `applySampleEntityStatus` (private), `upsertInspectionSample`, `dispositionInspection`, `parseSpecNumber`, `valuateMeasurement`, `upsertInspectionMeasurement`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`). Add `db` first param (replace internal `getDatabaseClient()`); declare plain input types package-side (`InspectionSampleInput`, `InspectionMeasurementInput`, `InspectionDispositionInput` — structurally assignable from ERP's zod-inferred types); sampling imports from `./sampling.ts`. Apply the Receipt guards (decision 4) here.
+- `packages/database/package.json`: add `"./quality"` + `"./sampling"` exports.
+- Verify: `pnpm exec turbo run typecheck --filter=@carbon/database`
+
+### 3. ERP wrappers (behavior-preserving)
+- Rewrite `apps/erp/app/modules/quality/quality.server.ts` as ~60 lines of wrappers passing `getDatabaseClient()`; re-export `errResult`, `valuateMeasurement`, `type Result` (consumed by `quality-disposition.server.ts` and `quality.server.test.ts`). Zero changes to ERP routes.
+- Verify: `pnpm exec turbo run typecheck --filter=erp && pnpm --filter erp test`
+
+### 4. `getOrCreateJobOperationInspection` (package)
+- Append to `packages/database/src/quality.ts` per decision 2. Blueprint: `post-receipt/index.ts` L694-800 (plan resolution) + L1903-1935 (inserts); sequence via node-safe `../supabase/functions/shared/get-next-sequence.ts`. Stamp `inspectionDocumentId` from the operation FK; `sampleSize` = max across feature plans (or lot snapshot); insert `inspectionSamplingPlan` rows on create only.
+- Verify: `pnpm exec turbo run typecheck --filter=@carbon/database`
+
+### 5. MES validators + types + read services
+- `apps/mes/app/services/models.ts`: append `inspectionSampleValidator`, `inspectionMeasurementValidator` (copy shapes from ERP `quality.models.ts:487-535`).
+- NEW `apps/mes/app/services/quality.service.ts` (supabase-js reads, copied from ERP quality.service.ts): `getInspection`, `getInspectionSamplingPlans`, `getInspectionMeasurements`, `getIssueTypesList`, plus simplified `getInspectionDocumentWithBalloons` (doc name/content + the 5 balloon fields). Types via `Awaited<ReturnType<...>>` in `apps/mes/app/services/types.ts`.
+- Verify: `pnpm exec turbo run typecheck --filter=mes`
+
+### 6. MES path helpers + action routes + NCR helper
+- `apps/mes/app/utils/path.ts`: `inspection(operationId)` → `/x/inspection/:operationId`; lot actions under a distinct prefix (param is the **inspection id**, not operation id): `inspectionMeasurement|Sample|Accept|Reject(id)` → `/x/inspection-lot/:id/{measurement,sample,accept,reject}`.
+- NEW routes in `apps/mes/app/routes/x+/` (flat dot-notation, precedent `record.$id.delete.tsx`): `inspection-lot.$id.measurement.tsx`, `inspection-lot.$id.sample.tsx`, `inspection-lot.$id.accept.tsx`, `inspection-lot.$id.reject.tsx`. Each: `requirePermissions({ update: "quality" })` → MES validator → engine call with `getDatabaseClient()`. Response shapes must match the grid contract: measurement returns `data(result)` (`body.data.{sampleId,measurementStatus,sampleStatus,...}`); sample returns `{ success, sampleId }` honoring `quiet`.
+- NEW `apps/mes/app/services/quality.server.ts`: `createQualityIssue(serviceRole, args)` extracted verbatim from `quality-issue.new.tsx` (sequence RPC, `nonConformance` insert, `nonConformanceJobOperation`/item/entity links, `create` edge-fn tasks invoke, compensating deletes). Rewire `quality-issue.new.tsx` action as a thin wrapper (same UX).
+- Reject route: `dispositionInspection(Reject)` → if `createNcr`: failed-features description (copy ERP `$id.reject.tsx:159-196`), `createQualityIssue(...)` with `jobOperationId = inspection.sourceDocumentLineId`, then insert `nonConformanceInspection` link. Redirect back to `path.to.inspection(operationId)` (hidden field) with flash. No post-nonconformance invoke (writeOff is null for job-op source).
+- Verify: `pnpm exec turbo run typecheck --filter=mes`
+
+### 7. MES view route + redirect branch
+- `operation.$operationId.tsx:77-82`: replace the fall-through comment with `if (resolveOperationView(op?.operationType) === "inspection") throw redirect(path.to.inspection(operationId) + url.search);`
+- NEW `apps/mes/app/routes/x+/inspection.$operationId.tsx` mirroring `assembly.$operationId.tsx`: job/op fetch + error redirects; guard (`!== "inspection"` → operation route, no loops); `getOrCreateJobOperationInspection`; `reconcileInspectionSamplingPlans` when the lot has a document; parallel reads — inspection/features/measurements/doc+balloons/issue types (new quality.service), WIP entities via `getTrackedEntitiesByMakeMethodId` (NOT the receipt-specific read), plus the shop-floor set from the assembly loader (events, quantities reduced to `{scrap, production, rework}`, work center, make method, ncrs, thumbnail, company settings). Returns props for `<InspectionView />`; `pdfUrl = doc?.content?.pdfUrl ?? null`.
+- Verify: `pnpm exec turbo run typecheck --filter=mes`
+
+### 8. MES components (`apps/mes/app/components/Inspection/`)
+- `InspectionDrawingPane.tsx` — copy verbatim from ERP (lazy + ClientOnly).
+- `RejectLotModal.tsx` — copy; inline the `IssueTypeListItem` type; add hidden `operationId` field support.
+- `ScanInspectionSample.tsx` — adapt: `@carbon/form` (`Hidden`,`Submit`,`TextArea`), MES validator/path/types; `remaining` = make-method entities minus sampled; posts to `path.to.inspectionSample(id)`.
+- `InspectionMeasurementMatrix.tsx` — NEW plain `<table>` matrix, ERP grid contract (props incl. `activeFeatureId` sync, `OVERALL_ROW_ID`), big touch cells (`size="lg"` idiom, `inputMode="decimal"`, commit on blur/Enter, P/F toggles for attribute features), cells beyond a feature's n disabled; port `persistMeasurement`/`persistOverall` quiet-fetch logic + local status mirroring from ERP grid L174-265.
+- `InspectionView.tsx` — NEW full-screen AssemblyView-pattern: header (job/item/thumbnail, lot id + status badge, sampling summary n/Ac/Re, Add Sample for serial with auto-open-once on fresh lots, Accept/Reject); port ERP's pure-react gating state verbatim (`canAccept`/`canReject`/`failedFeatureSummary` etc., InspectionView.tsx:230-420); drawing pane above matrix when `pdfUrl` (fixed split for v1), balloon↔row sync; TimerControl (copy from AssemblyView L2355) posting `/x/event`; Log Completed mirroring AssemblyView's wiring; bottom action sheet: Scrap / Rework / Quality Issue / Finish via the shared JobOperation modals. No client-side permission gating (MES convention); four-eyes + document-switch are ERP-only for v1.
+- New strings use `Trans`/`useLingui`; run `pnpm lingui:extract` (+ fill via /translate flow) at the end.
+- Verify: `pnpm exec turbo run typecheck --filter=mes && pnpm --filter mes build` (gates konva SSR + pdf worker)
+
+### 9. Docs sync (same PR, keep-sources-in-sync)
+- `.claude/rules/inspection-system.md`: Job Operation source now live (creation path, MES routes, entity-flip guards, engine home `@carbon/database/quality`).
+- `.claude/rules/mes-job-operation-ui.md`: inspection route + redirect branch.
+- `apps/erp/app/modules/quality/AGENTS.md` (+ `packages/database/AGENTS.md` if it lists exports): engine move.
+- `.ai/specs/implemented/2026-07-14-mes-execution-views.md`: mark §5.4 result-record superseded by the unified inspection tables; §5.1 Phase-3 shipped. `.ai/specs/implemented/2026-07-21-inbound-inspection-execution.md`: MES attachment note.
+- Copy this plan to `.ai/plans/2026-07-26-mes-inspection-view.md` with checkboxes.
+
+### 10. Verification (end-to-end)
+- `pnpm exec turbo run typecheck --filter=@carbon/database --filter=erp --filter=mes`; `pnpm --filter erp test`; `pnpm run lint`.
+- No migration → no `generate:types`.
+- Browser (dev stack, /auth + /test skills, screenshots for PR): author method op `operationType='Inspection'` + inspection document → create job → `/x/operation/:id` redirects to `/x/inspection/:id` → lot auto-created (`sourceDocument='Job Operation'`, INS-seq readable id, idempotent on reload) → record measurements (live valuation, statuses without reload) → serial: Add Sample scan flow → clock in/out + Log Completed → Accept gated until n covered → Reject creates NCR with `nonConformanceJobOperation` + `nonConformanceInspection` links → WIP `trackedEntity.status` unchanged by failed samples → ERP regression: receipt inspection still records + flips entities (wrapper + guards preserved behavior) → ERP `/x/quality/inspections` list shows the job-op lot.
+
+## Risks
+- **Kysely ON CONFLICT vs partial unique index** — mitigated: select-first inside the txn + 23505-catch fallback.
+- **Node import of Deno-tree helpers** (`get-next-sequence.ts` chain) — verified side-effect-free/node-safe; `src/client.ts` is the precedent.
+- **konva/react-pdf first run in MES SSR** — config copied from working ERP; `pnpm --filter mes build` is the gate.
+- **Engine move regressions in ERP receipts** — guards are bit-identical for Receipt source; ERP vitest + manual receipt regression cover it.
+- **Ops prerequisites** — operators need `quality_update`; NCR path expects ≥1 `nonConformanceType`.
diff --git a/.ai/research/2026-07-25-inspection-disposition-accounting-audit.md b/.ai/research/2026-07-25-inspection-disposition-accounting-audit.md
new file mode 100644
index 0000000000..6b510be490
--- /dev/null
+++ b/.ai/research/2026-07-25-inspection-disposition-accounting-audit.md
@@ -0,0 +1,74 @@
+# Audit: accounting transactions for inspections & dispositions
+
+**Date:** 2026-07-25 · **Scope:** inbound-inspection reject, NCR disposition close, batch split, and the receipt posting that feeds them. Read-only trace of three flows against the canonical inventory-adjustment posting path.
+
+## TL;DR
+
+The inspection and disposition flows move inventory **quantity** (`itemLedger`) and tracked-entity **status**, but post **no cost and no GL**. Inventory **value** is booked once — at receipt — at full value *even for `requiresInspection` items whose entities are `On Hold`*, and is **never relieved** when that stock is rejected or scrapped. Result: the Inventory GL account overstates real inventory, cost layers (`costLedger`) never get consumed (FIFO/average drift), and there is no scrap/cost-of-quality expense.
+
+## How Carbon *should* post an inventory movement (reference)
+
+Canonical path: edge fn `packages/database/supabase/functions/post-inventory-adjustment/index.ts` → shared core `functions/shared/post-adjustment.ts::bookAdjustment`. In **one Kysely transaction** per signed movement it writes:
+
+1. **`itemLedger`** — signed quantity (always).
+2. **`costLedger`** — relieve layers via `shared/calculate-cogs.ts::calculateCOGS` on a decrease (honors `costingMethod` Standard/Average/FIFO/LIFO, `.forUpdate()` locks layers, decrements `remainingQuantity`); create a new layer at current carrying cost on an increase. Skipped for `Non-Inventory` / qty 0.
+3. **`journal` + `journalLine`** (balanced Dr/Cr pair) + **`journalLineDimension`** (Item / ItemPostingGroup / Location tags) — **only when `companySettings.accountingEnabled` and cost ≠ 0**.
+
+**Account resolution** (`shared/get-posting-group.ts`) is flat, one `accountDefault` row per company (posting-group matrix was **dropped** in `20260229000000_drop-posting-groups.sql`):
+- Inventory side by `replenishmentSystem`: `finishedGoodsAccount` (Make / Buy and Make) else `rawMaterialsAccount`.
+- Offset: `inventoryAdjustmentVarianceAccount` (seeded `5310 "Inventory Adjustment"`, COGS/Expense).
+- **No `valueLedger` / `generalLedger` tables** — `costLedger` is the value ledger, `journal`/`journalLine` are the GL. Use `accountId` (not the legacy `accountNumber`).
+
+When accounting is **disabled**, `bookAdjustment` still writes `itemLedger` + `costLedger`, but **no journal** — it fails *closed* (a failed `companySettings` read throws).
+
+## What the audited flows actually do
+
+### 1. Inspection reject — `apps/erp/app/modules/quality/quality.server.ts::dispositionInspection`
+- Flips lot tracked entities → `Rejected` (Accept → un-sampled `Available`; Partial → none). No ledger.
+- **Only** ledger write (non-tracked `Inventory`, receipt-sourced, not already Failed): one `itemLedger` `Negative Adjmt.`, `documentType "Inbound Inspection"`, `quantity: -lotSize`, `trackedEntityId: null`. **No `costLedger`, no `journal`.**
+- Updates `inspection` status + writes `inspectionHistory`.
+- Tracked / `Non-Inventory` rejects post **no ledger at all** — only the status flip.
+
+### 2. NCR disposition close — `apps/erp/app/modules/quality/quality-disposition.server.ts::closeIssue`
+- **Scrap / Return to Supplier** (tracked): one `itemLedger` `Negative Adjmt.` per linked entity, `documentType "Non-Conformance"`, `quantity: -link.quantity`; then flip entities → `Rejected`. **No cost/GL.**
+- **Use As Is / Rework** (tracked): flip entities → `Available`. No ledger.
+- **Non-tracked Use As Is / Rework restore** (my recent change, inspection-originated `Inventory` only): one `itemLedger` `Positive Adjmt.` `+quantity`. **No cost/GL.**
+- Sets `nonConformance.status = Closed`.
+
+### 3. Batch split — `quality-disposition.server.ts::subdivideBatchEntity` (via `splitIssueItem`)
+- Three `itemLedger` `Batch Split` rows that **net to zero** on-hand + `trackedActivity` genealogy. **Correctly** no GL (no value change). Non-tracked quantity split writes **no** `itemLedger` at all.
+
+### 4. Receipt — `packages/database/supabase/functions/post-receipt/index.ts`
+- `requiresInspection` has exactly two effects: creates the inspection lot, and sets tracked entities `On Hold`. **Neither gates the posting.** The main receipt loop books the **normal full-value `journal`/`journalLine` + `costLedger` layers + `itemLedger`** for every line regardless of inspection/On-Hold.
+- ⇒ At receipt, inspection stock's **value is on the GL** (`get_inventory_quantities` hides the *quantity* as `quantityOnHold`, but the value is booked). A later reject/scrap never reverses it.
+
+### 5. `itemLedger` is quantity-only
+No `cost`/`value`/`amount` column; its only triggers denormalize `trackedEntityStatus`. An `itemLedger` insert has **no GL fan-out** — cost/GL are always separate writes. Confirmed: zero `journalLine` / `costLedger` / `post-inventory-adjustment` / `accountingEnabled` references anywhere in the quality module or inspection/issue routes.
+
+## The gaps
+
+| # | Gap | Consequence |
+|---|-----|-------------|
+| G1 | Reject of non-tracked `Inventory` removes on-hand qty but **not value/cost** | Inventory GL overstated by the lot's cost; cost layers not relieved |
+| G2 | Reject of **tracked** stock changes status only — value stays in Inventory GL through the MRB hold and beyond | Rejected value commingled with good stock; relieved only if Scrap disposition eventually posts (it doesn't today) |
+| G3 | Disposition **Scrap / Return** posts qty-only | No cost relief, **no scrap/write-off expense** — cost of quality invisible; GL overstated |
+| G4 | Disposition **Use As Is / Rework** restore posts qty-only | If reject ever writes off value (post-fix), a kept lot's value isn't restored → understated |
+| G5 | No `accountingEnabled` gate / accounting-period awareness in these flows | Even correct-intent postings would ignore locked periods |
+| G6 | **NCR reopen** (Closed→Registered) doesn't reverse anything | Once GL is added, reopen must reverse the journals or be blocked |
+| G7 | **Xero landmine** — `packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts` sweeps **every** `itemLedger` row with `entryType ∈ {Positive/Negative Adjmt.}` (ignores `documentType`) and recomputes value from `itemCost.unitCost` | These NCR/inspection rows could push Xero ManualJournals with **no matching local GL** if adjustment sync is enqueued (currently disabled + push-only + backfill-only, so latent, not live) |
+
+## Account infrastructure (what exists to post against)
+
+- Flat `accountDefault` (PK `companyId`, one row/company). Relevant columns: `rawMaterialsAccount`, `finishedGoodsAccount`, `workInProgressAccount`, `costOfGoodsSoldAccount`, `goodsReceivedNotInvoicedAccount`, **`inventoryAdjustmentVarianceAccount`**, `materialVarianceAccount`, and the other variance/absorption accounts. Editable at `apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx`; seeded in `functions/lib/seed.data.ts`.
+- **No dedicated scrap / write-off / adjustment-expense inventory account exists.** Closest reusable = `inventoryAdjustmentVarianceAccount` (5310, already the offset for physical-count adjustments). (`customerWriteOffAccount`=bad debt, `supplierWriteOffAccount`=vendor write-off *income*, fixed-asset `writeDownAccount` — none fit inventory scrap.)
+- **Production scrap has no scrap-specific GL today:** scrapped-unit cost is absorbed into good-unit cost at `complete_job_to_inventory`; residual WIP at `close-job` sweeps to `materialVarianceAccount`; scrapping a tracked material (`functions/issue/index.ts::scrapTrackedEntity`) posts Dr `workInProgressAccount` / Cr `rawMaterials|finishedGoods` (treated as consumption into WIP), not an expense. `scrapReasons` are quantity labels with no account link.
+
+## Files
+
+- Reference: `functions/post-inventory-adjustment/index.ts`, `functions/shared/post-adjustment.ts`, `functions/shared/calculate-cogs.ts`, `functions/shared/get-posting-group.ts`.
+- Gap sites: `apps/erp/app/modules/quality/quality.server.ts` (`dispositionInspection`), `apps/erp/app/modules/quality/quality-disposition.server.ts` (`closeIssue`, `subdivideBatchEntity`, `splitIssueItem`), `apps/erp/app/routes/x+/inspection+/$id.reject.tsx`, `apps/erp/app/routes/x+/issue+/$id.close.tsx`.
+- Receipt: `functions/post-receipt/index.ts`.
+- Accounts: `packages/database/src/types.ts` (`accountDefault`), `apps/erp/app/modules/accounting/accounting.models.ts`, `functions/lib/seed.data.ts`.
+- Xero: `packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts`.
+
+→ Plan: `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`
diff --git a/.ai/research/inbound-inspection-execution.md b/.ai/research/inbound-inspection-execution.md
new file mode 100644
index 0000000000..1407a0bf61
--- /dev/null
+++ b/.ai/research/inbound-inspection-execution.md
@@ -0,0 +1,249 @@
+# Inbound Inspection Execution UI Research: Best Practices Survey
+
+## Summary
+
+Researched how ERP/QMS systems execute inbound/receiving inspection when a
+characteristic-based inspection plan (ballooned drawing → bill of
+characteristics) meets AQL sampling (sample size, accept/reject numbers),
+per-sample measurement entry, pass/fail disposition, and NCR creation. Key
+findings: (1) the industry-standard model is an **inspection lot** whose plan is
+a **bill of characteristics** extracted from a ballooned drawing; (2) sampling
+is resolved **per characteristic** (SAP, 1factory, High QA all do this — the
+lot sample size is the max across characteristics); (3) measurements are
+auto-valuated against tolerances (out-of-tolerance auto-rejects the reading)
+but the **lot disposition is always a human decision** — SAP has auto-accept
+for clean passes, never auto-reject; (4) NCRs are born from the inspection with
+one click / auto-activation, pre-populated with the failed characteristics and
+lot references; (5) the consensus execution UI is a **split view: PDF drawing
+with balloons beside a characteristics × sample-units grid**, with balloon↔row
+synchronization and out-of-tolerance color coding.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA / ECC (QM)** — the enterprise reference model: inspection lot,
+ master inspection characteristics, sampling procedures/schemes, usage
+ decision, quality notifications.
+- **1factory** — point-solution leader for incoming quality control in
+ machining/discrete; drawing ballooning → incoming inspection plans → grid
+ execution → NCR/SCAR.
+- **High QA (Inspection Manager)** — ballooning + bill-of-characteristics
+ authoring with shop-floor execution apps; per-dimension AQL sampling.
+- **ProShop ERP / Fulcrum / Net-Inspect** — adjacent references for
+ receiving-workflow integration, permission-tiered dispositions, and FAI
+ results-review UI.
+
+## Key Consensus Patterns
+
+### 1. Inspection plan = bill of characteristics from a ballooned drawing
+
+- **SAP**: inspection plan (task list) → operations → numbered inspection
+ characteristics referencing versioned Master Inspection Characteristics
+ (quantitative with tolerances, or qualitative pass/fail via catalogs). Plans
+ are selected per material or material+vendor.
+- **1factory**: "A Quality Control Plan defines the Bill of Characteristics
+ (what to measure), the associated specifications and tolerances, the
+ inspection methods (how to measure), and the sampling rules (how many to
+ measure)." Built by OCR auto-ballooning or point-and-click on the PDF.
+- **High QA**: one-click ballooning generates the Bill of Characteristics;
+ tools, criticality, and sampling get assigned per characteristic.
+- **Rationale**: the drawing is the contract; every measurable requirement
+ becomes a numbered characteristic that flows through FAI, incoming,
+ in-process, and final inspection from one master.
+
+### 2. Sampling resolves per characteristic; the lot inherits the max
+
+- **SAP**: each characteristic carries its own sampling procedure; sample size
+ is computed per characteristic at lot creation; the lot-level sample is the
+ largest characteristic sample. Sampling schemes are ISO 2859-1/3951 tables:
+ severity × AQL × lot-size → n, c (accept), d (reject), k-factor.
+- **1factory**: "Auto-calculate sample size for each feature based on lot size
+ and sampling plan. Ensure all required measurements are recorded before
+ inspections are closed." Supports C=0, ANSI Z1.4 (General I–III, Special
+ I–III), MIL-STD-1916, custom.
+- **High QA**: "define and apply sampling thresholds for each dimension"; AQL
+ sampling linked directly to the Bill of Characteristics.
+- **Rationale**: critical dimensions warrant larger samples than minor ones
+ (AQL tiers map to criticality: critical 0.065–0.65, major 1.0–2.5, minor
+ higher); a single lot-level sample size over- or under-inspects.
+
+### 3. Auto-valuation of readings; human disposition of the lot
+
+- **SAP**: a measured value outside tolerance is auto-valuated Rejected for
+ that unit; the characteristic accept/reject follows the valuation mode
+ (attributive: defects ≤ c accepts; variable: k-method). But the **usage
+ decision is a person**: a lot with rejected characteristics can still be
+ accepted ("accepted with deviation"); automatic UD exists only for the
+ clean-pass path (no rejected characteristics, no defects) — never automatic
+ rejection.
+- **1factory**: measurements verified against spec limits at entry; system
+ computes in-spec % and flags high-risk lots; lot accept/reject follows the
+ plan's accept number; Cp/Cpk-based lot acceptance offered as methodology.
+- **Net-Inspect / High QA**: out-of-tolerance color coding at entry; live
+ spec-limit display.
+- **Rationale**: instant feedback prevents bad data and surprises, but
+ disposition has business consequences (MRB, use-as-is, supplier chargeback)
+ that need judgment and authority.
+
+### 4. NCR born from the inspection, pre-populated
+
+- **SAP**: rejecting a characteristic auto-creates a defect record (defect
+ code per exceed-upper/below-lower/general, defect class critical/major/
+ minor); every defect record is an inactive quality notification that
+ activates automatically by defect class, manually, or implicitly. GR
+ inspections typically activate a Q2 vendor complaint carrying defect items +
+ lot/PO/vendor references.
+- **1factory**: "Generate a non-conformance report from within an inspection
+ with a single click… Autopopulate NCR details from Inspections." NCR → MRB
+ disposition, → CAPA/SCAR (8D) chains.
+- **ProShop**: NCR generation built into receiving; auto-linked to part, job,
+ operator, inspection tool; **permission-tiered dispositions** (anyone can
+ scrap obvious bad parts; use-as-is/rework requires QC/MRB).
+- **Rationale**: re-keying failure data loses fidelity; the inspection already
+ knows the item, supplier, PO, lot, failed characteristics, and measured
+ values.
+
+### 5. Execution UI: drawing + grid split view
+
+- **1factory**: three data-entry layouts — Feature View, Parameter View,
+ **Spreadsheet View** (characteristics × sample units); filter by operation,
+ method, sampling rule; keyboard + digital gauge + CMM import entry.
+- **High QA**: dual-pane drawing viewer beside the characteristic grid;
+ operators "input measurement data digitally directly onto drawings"; also a
+ wizard step-by-step mode for low-training operators.
+- **DISCUS**: find-a-characteristic highlights the row in the BoC **and** the
+ balloon on the drawing — the grid and drawing are a linked pair.
+- **Rationale**: the balloon number is the shared key between the drawing and
+ the grid; navigating either surface must move the other.
+
+### 6. Stock is quarantined during inspection; disposition posts it
+
+- **SAP**: GR posts to quality inspection stock (QM has exclusive control);
+ the UD posts quantities — splittable across unrestricted / blocked / scrap /
+ sample usage / new material / return-to-vendor, including per serial number.
+- **Carbon today** (parity note): tracked entities post `On Hold` and are
+ released by sample pass or lot disposition; non-tracked rejects post a
+ compensating item-ledger adjustment.
+
+## Answers to Research Questions
+
+1. **Entities/lifecycle** — Inspection lot (created from goods receipt) →
+ plan/characteristics assigned → sample sizes calculated → results recording
+ (per characteristic, per sample unit) → characteristics closed/valuated →
+ usage decision (coded, human) → stock posting + quality level update (SAP;
+ 1factory and High QA mirror this with lighter vocabulary: inspection lot,
+ bill of characteristics, results, disposition).
+2. **Sampling × characteristics** — measurement is recorded per sample unit ×
+ per characteristic; sample size is derived per characteristic from its
+ sampling rule + lot size (SAP, 1factory, High QA). Completeness gating:
+ inspection cannot close until all required cells are filled (1factory).
+3. **Out-of-tolerance roll-up** — reading auto-valuated fail; characteristic
+ valuated by accept/reject numbers (attributive) or k-method (variable); lot
+ disposition remains inspector judgment; auto-accept only for clean passes
+ (SAP).
+4. **NCR spawning** — both auto (by defect class / on rejection) and manual
+ (one click from inspection or usage-decision screen); carries defect codes,
+ counts, failed characteristics, lot/PO/supplier references (SAP, 1factory).
+5. **Drawing + grid presentation** — split view with balloon↔row sync
+ (High QA, DISCUS); out-of-tolerance color coding in the grid (Net-Inspect);
+ entry modes: spreadsheet grid, per-feature wizard, on-drawing entry.
+6. **Terminology** — inspection lot, characteristic (bill of characteristics),
+ sample unit, results recording, valuation, usage decision / disposition,
+ defect class, acceptance number (Ac/c) & rejection number (Re/d), skip-lot,
+ normal/tightened/reduced switching, dock-to-stock, C=0.
+
+## Competitor-Specific Details
+
+### SAP QM
+- Quality info record per material+vendor gates the relationship (skip GR
+ inspection for certified vendors, source inspection at vendor, cert checks).
+- Dynamic modification: quality level per material(+vendor) advances
+ normal/tightened/reduced/**skip** stages by acceptance/rejection history.
+- Recording forms per characteristic: summarized vs single values vs classed;
+ single-value rows can bind to serial numbers.
+- Characteristic control indicators worth borrowing: required vs optional,
+ documentation-required-on-rejection (forced comment), destructive (drives
+ sample-usage stock posting).
+
+### 1factory
+- Characteristic types: Variable (numeric), Attribute (pass/fail), Calculated.
+- Per-feature sample-size enforcement gates inspection close.
+- Lot switching (normal/reduced/tightened/skip-lot) is a data-assisted
+ *decision* per part+supplier, not fully automatic; dock-to-stock candidates
+ surfaced from history.
+- Certificates (material certs, plating, heat treat) attach to the inspection
+ lot; audit-readiness enforces required certs.
+
+### High QA
+- Batch automation mass-produces ballooned drawings + plans; 3D PMI extraction.
+- Execution via browser/tablet apps (IM Explorer/eXpress): ballooned drawing +
+ step-by-step wizard + direct on-drawing entry; live Cp/Cpk display.
+- ERP integration pattern: ERP work order clones a template inspection job.
+
+### ProShop / Fulcrum / Net-Inspect
+- ProShop: permission-tiered dispositions (scrap = anyone; use-as-is/rework =
+ MRB); NCR auto-linked to part/job/operator/gauge.
+- Fulcrum: quality checkpoints as routing-step gates; certs attach to received
+ lots and flow to jobs; NCR grid dashboard. No dedicated IQC module.
+- Net-Inspect: AS9102 Form 3 per-characteristic accountability; reviewer UI
+ with color-coded out-of-tolerance and field-level comments.
+- C=0 plans (Squeglia): single table lot-size × AQL → n, accept on zero
+ defects; simpler to administer/defend in audit than Z1.4 Ac/Re pairs; heavily
+ used in medical/aerospace receiving. Tools model it as one selectable plan
+ type alongside Z1.4/ISO 2859.
+
+## Recommended Approach for Carbon
+
+1. **Wire the two existing systems together, don't build a third**: the
+ `inspectionDocument`/`inspectionFeature`/`balloon` tables already are the
+ bill of characteristics (1factory/High QA pattern); the `inboundInspection`
+ lot already is the SAP inspection-lot analog with an AQL plan snapshot. The
+ redesign attaches the item's inspection features to the inbound lot and
+ records measurements per sample × feature.
+2. **Split-view execution screen** (High QA/DISCUS pattern): react-pdf drawing
+ with balloon overlay on one side, editable results grid (inventory-count
+ `EditableNumber` pattern) on the other; balloon click ↔ row focus sync;
+ out-of-tolerance color coding at entry (Net-Inspect pattern).
+3. **Auto-valuate readings, keep human disposition** (SAP pattern): a reading
+ outside nominal±tolerance marks the cell/sample failed automatically;
+ Accept/Reject/Partial lot disposition stays a button with authority attached
+ — never auto-reject.
+4. **Keep lot-level sampling in v1, structure for per-characteristic later**:
+ Carbon's plan snapshot (sampleSize/Ac/Re on the lot) applies to every
+ feature initially; the results table keys on (sample, feature) so
+ per-characteristic sampling rules can be added without a rebuild — this is
+ where SAP/1factory/High QA all end up.
+5. **NCR pre-population from failed features** (1factory pattern): the reject
+ flow already auto-creates an NCR; extend the payload with failed
+ features/measurements so MRB sees what failed and by how much.
+6. **Graceful degradation**: items with no inspection document keep today's
+ pass/fail-per-sample flow — the characteristics grid is additive, not a
+ prerequisite (matches how 1factory treats attribute-only plans).
+
+## Sources
+
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMIMIL/QMIMIL.PDF — inspection lot creation
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMIMRR/QMIMRR.PDF — results recording & valuation
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMIMDEF/QMIMDEF.PDF — defects recording / notification activation
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMIMUD/QMIMUD.PDF — usage decision & stock postings
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMPTBD/QMPTBD.PDF — MICs, sampling procedures/schemes, catalogs
+- https://download.consolut.com/direct/SAP_PrintDoku/en/QMQCDYN/QMQCDYN.PDF — dynamic modification
+- https://help.sap.com/docs/SAP_ERP/250374f0514e4e0f9057066374265eba/2514c453f57eb44ce10000000a174cb4.html — GR inspection
+- https://www.1factory.com/incoming-quality.html — IQC features
+- https://www.1factory.com/incoming-quality-control-iqc.html — IQC flow, skip-lot, dock-to-stock
+- https://www.1factory.com/fai-ballooning-software.html — ballooning detail
+- https://www.1factory.com/all-features.html — plan model, sampling standards, entry layouts, NCR/MRB
+- https://www.1factory.com/ncr-capa-scar-complaint.html — NCR/CAPA/SCAR
+- https://www.1factory.com/supplier-quality.html — supplier portal, SCAR 8D
+- https://www.1factory.com/case-studies/orbit-irrigation.html — receiving case study
+- https://highqa.com/ballooning-and-gdt-extraction/ — ballooning + BoC
+- https://highqa.com/aql-sampling-plans/ — per-dimension AQL
+- https://www.highqa.com/high-qa-software/ — end-to-end workflow
+- https://www.highqa.com/production-data-collection/ — shop-floor execution
+- https://www.highqa.com/inspection-explorer/ — browser execution app
+- https://www.net-inspect.com/solutions/first-article-inspection-software/ — FAI results review
+- https://proshoperp.com/blog/non-conformance-reports-can-positively-impact-your-shops-bottom-line/ — tiered dispositions
+- https://fulcrumpro.com/manufacturing-software/shipping-receiving — receiving flow
+- https://fulcrumpro.com/resources/as9100-requirements — checkpoint gates, certs
+- https://www.qualitydigest.com/inside/operations-article/when-and-how-use-zero-acceptance-number-sampling-041119.html — C=0 vs Z1.4
+- https://www.discussoftware.com/tips/find-a-characteristic/ — balloon↔row sync
+- https://ifactoryapp.com/article/incoming-quality-control-software-supplier-inspection-management — per-characteristic auto-calculation
diff --git a/.ai/research/operation-type-consolidation.md b/.ai/research/operation-type-consolidation.md
new file mode 100644
index 0000000000..c7e7233adc
--- /dev/null
+++ b/.ai/research/operation-type-consolidation.md
@@ -0,0 +1,107 @@
+# Research: How Manufacturing ERPs Classify Routing Operations
+
+Date: 2026-07-20
+Question: Validate Carbon's consolidation to a single per-operation `operationType` enum — `Process` (in-house), `Assembly` (guided assembly w/ 3D instructions), `Inspection` (quality step), `Outside Processing` (subcontract) — against industry practice.
+
+---
+
+## SAP PP / QM (S/4HANA, ECC)
+
+SAP puts **one field on every routing operation — the control key (STEUS)** — and that single field drives in-house vs external behavior, costing, confirmation, and inspection relevance. A control key is a named *profile of indicators*: scheduling, capacity planning, costing relevance, auto goods receipt, **external processing**, confirmation type (incl. milestone), print, and "inspection characteristics required" ([SAP Help: Control Key](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/efc7922405fd4d56b7571930c5eaa798/90a1b8535c39b44ce10000000a174cb4.html); [SAP Community: control key indicators](https://community.sap.com/t5/enterprise-resource-planning-q-a/operation-control-key/qaq-p/7090989)).
+
+Standard values:
+- **PP01 — in-house production**: operation is scheduled, capacity-planned, costed, confirmed; no auto-GR ([SAP Community](https://community.sap.com/t5/enterprise-resource-planning-q-a/control-key-in-pp/qaq-p/8095872)).
+- **PP02 — external processing**: flags the op as externally procured; requires a purchasing info record; the system **creates a purchase requisition when the production order is created/released**, and goods receipt against the resulting PO sets the operation status to EODL (externally delivered) — no shop-floor confirmation needed ([SAP Community: PP02](https://community.sap.com/t5/enterprise-resource-planning-q-a/control-key-pp02-external-processing/qaq-p/5902949); [PReq on release](https://community.sap.com/t5/enterprise-resource-planning-q-a/routing-and-externally-process-and-purchase-requisition/qaq-p/5678180)).
+- **PP03 — in-house with auto goods receipt** on confirmation ([Guru99: SAP Routing](https://www.guru99.com/create-change-routing-sap-pp.html)).
+- **QM01 — inspection operation** ("inspection characteristics required" set by default), used in inspection plans/task lists ([SAP Community: QM01](https://community.sap.com/t5/enterprise-resource-planning-q-a/sap-qm-control-key/qaq-p/5276394)).
+- **Milestone confirmation** is a *confirmation-type setting inside* the control key: confirming a milestone op auto-confirms all prior operations ([unogeeks: milestone confirmation](https://unogeeks.com/milestone-confirmation-in-sap-pp/)).
+
+In production routings, inspection is usually **attached to an operation** (in-process inspection characteristics on any op), not a distinct op type; dedicated inspection *operations* exist in QM inspection plans via QM* control keys. So SAP's answer to "one field or orthogonal flags?" is **both**: one field on the operation, whose *semantics* are a bundle of orthogonal indicators. Users can define custom control keys (Z*) without code changes — extensibility lives in configuration.
+
+## Oracle Fusion Cloud Manufacturing
+
+The closest match to Carbon's design. Work definition / standard operations carry an explicit **Operation Type enum: `In-House` or `Supplier`** (default In-House); REST payloads use `IN_HOUSE` / `SUPPLIER` ([Create a Standard Operation](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25c/faumf/create-a-standard-operation.html); [REST: work order operation](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25d/fasrp/op-maintenanceworkorders-workorderid-child-workorderoperation-wooperationid-patch.html)). Behavior branches on the enum: if In-House, the Supplier/Supplier Site/lead-time attributes "aren't collected"; if Supplier, you must specify an **outside-processing (OSP) item** (the value-added service as a product) and a supplier, and POs/receipts drive the operation ([Work orders with supplier operations](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26b/faims/how-you-create-and-manage-work-orders-with-supplier-operations.html); [Plan OSP operations](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/24b/fausp/plan-outside-processing-operations.html)). Oracle's feature name is **"Outside Processing (OSP)"** ([Outside Processing Services](https://docs.oracle.com/en/cloud/saas/supply-chain-management/21b/famli/outside-processing-services.html)).
+
+Orthogonal to the type enum, each operation is a **Count point / Automatically transact / Optional** operation (mutually exclusive reporting attributes). **Inspection is not an operation type**: quality inspection plans are attached at the operation level and enforced as inline WIP inspection — completion is blocked until the prescribed samples are inspected ([Perform Inline Inspections](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faumf/perform-inline-inspections.html); [inline WIP inspection REST use case](https://docs.oracle.com/en/cloud/saas/supply-chain-management/22c/fasrp/use_case_perform_inline_work_in_process_inspection.html)).
+
+Legacy contrast: classic **Oracle EBS WIP** had no operation-type enum — OSP was a *resource* with autocharge type PO Move/PO Receipt assigned to an operation, plus count-point/autocharge flags ([Oracle WIP: Overview of Routings and Operations](https://docs.oracle.com/cd/A60725_05/html/comnls/us/wip/ovwopctl.htm)). Fusion's move to a per-operation enum is a deliberate simplification. **JD Edwards** likewise flags outside operations on the work-order routing and generates POs per outside step (P3112, `*OP` service items) ([JDE: Understanding Outside Operations](https://docs.oracle.com/en/applications/jd-edwards/supply-chain-manufacturing/9.2/eoash/understanding-outside-operations.html)).
+
+## NetSuite (Advanced Manufacturing)
+
+Manufacturing routings are sequences of operation tasks; for subcontracted steps you **insert an outside-processing operation** carrying a vendor, lead time, cost driver, and an attached service item that captures the vendor charge; WIP ships to the vendor location and the vendor bill rolls into WIP/FG cost ([NetSuite: Manufacturing Routing and Work Orders](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2346224.html); [NetSuite: Outsourced Manufacturing](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_157833700001.html); [RSM walkthrough](https://technologyblog.rsmus.com/technologies/netsuite/netsuite-outsourced-manufacturing-starting-from-the-po-or-work-order/)). Terminology mixes "outsourced manufacturing" (feature) and "outside processing" (the routing step).
+
+## Epicor Kinetic
+
+Job/part routings distinguish plain operations from **"subcontract operations" — "a special type of operation"** added explicitly (Job Entry → Add Subcontract Operation) with a Supplier and unit price; job cost is broken into material / labor / burden / **subcontract** buckets; PO lines are created with **Buy For = Subcontract Operation**, and supplier price lists exist per subcontract operation ([epiusers: subcontract operations](https://www.epiusers.help/t/subcontract-operations-for-job-material/106830); [epiusers: subcontract price list](https://www.epiusers.help/t/subcontract-operation-price-list/76284); [job costing categories](https://scaledsolutionsgroup.com/how-to-use-epicor-kinetic-for-accurate-job-costing-and-margin-analysis/)). **Inspection is an attribute, not a type**: attaching an inspection plan to an operation auto-selects its "Inspection Required" checkbox for in-process inspection ([Epicor Community: Inspection Required](https://community.epicorusers.org/kinetic-epicor-erp-81/inspection-required-87136); [Tomerlin: Enhanced Quality Assurance](https://tomerlin-erp.com/epicor-enhanced-quality-assurance/)).
+
+## Infor SyteLine / CloudSuite Industrial
+
+Explicit per-operation classification: on the routing you **"set the operation type to Outside Process"** (stored in the routing table's `op_type` column), backed by a work center of **type Outside Process (O)** holding the default vendor and cost; a "Generate Outside Process POs" utility batch-creates POs for released jobs with pending outside-process operations ([Netray: How to Configure Outside Processing](https://www.netray.co/resources/how-to-configure-syteline-outside-processing); [Netray: OSP setup](https://www.netray.co/resources/syteline-outside-processing-setup)). Sage X3 similarly types the *work center* (machine / labor / subcontract) ([Sage X3 routing management](https://online-help.sagex3.com/erp/12/en-us/Content/FCT/GESROU.htm)).
+
+## Microsoft Dynamics 365
+
+**No operation-type enum.** In D365 Supply Chain Management a subcontracted route operation is one whose costing resource/resource requirement points to a **resource of type `Vendor`**, paired with a **BOM line of type `Vendor`** carrying a service product allocated to that operation; estimating the production order creates the PO ([Microsoft Learn: Manage subcontracting work in production](https://learn.microsoft.com/en-us/dynamics365/supply-chain/production-control/manage-subcontract-work-production)). Lean manufacturing has a second model ("activity-based subcontracting", Direct outsourcing cost group) ([Microsoft Learn: activity-based subcontracting](https://learn.microsoft.com/en-us/dynamics365/supply-chain/production-control/activity-based-subcontracting)). Practitioners find the resource-indirection model harder to reason about than an explicit flag — the classification is smeared across resource, BOM line, and service item.
+
+## Job shop software: Fulcrum, JobBOSS²/E2
+
+- **Fulcrum** treats **"outside processing operations"** as a first-class routing-step kind: OSP steps appear alongside material and internal steps in the BOM/routing builder, show their linked POs in the job operations drill-down, and support continuous flow (ship partials to the vendor) ([Fulcrum: PO info on outside processing operations](https://fulcrumpro.com/product-update/po-info-on-outside-processing-operations); [continuous flow on OSP operations](https://fulcrumpro.com/product-update/continuous-flow-on-outside-processing-operations)).
+- **JobBOSS² / E2** (ECI) uses **"outside services"** as the job-shop term — estimating pre-sets Outside Services alongside labor/burden rates, and outside services carry vendors and lead times for scheduling ([JobBOSS² estimating](https://jobboss.com/job-shop-manufacturing-software/jobboss2/quote-processing-software-for-manufacturing); [JobBOSS² scheduling blog](https://www.ecisolutions.com/blog/manufacturing/jobboss2/common-roadblocks-to-implementing-the-scheduling-module-in-jobboss2/)).
+
+## MES / work instructions: is "Assembly" ever an operation type?
+
+**No vendor surveyed classifies routing operations as "Assembly."** Assembly guidance is delivered as *content attached to an operation*, not as an operation taxonomy:
+- **Tulip**: routings order tasks/procedures; work instructions are apps attached to steps, with in-line quality inspection steps and poka-yoke inside the workflow ([Tulip: digital work instructions](https://tulip.co/digital-guidance/digital-work-instructions/); [Tulip: work instructions use case](https://support.tulip.co/docs/digital-work-instructions-use-case)). VKS and Poka are positioned the same way (work-instruction platforms layered on process steps).
+- **iBase-t Solumina** (aerospace assembly MES): operations carry work instructions with 3D model animations plus **buyoff points** — operator/inspector "stamps" recorded per unit; inspectors can raise discrepancies directly from a buyoff — i.e., inspection is an *embedded hold point on an operation*, per AS9100 practice ([iBase-t MES](https://www.ibaset.com/solutions/manufacturing-execution-system); [Solumina MES brochure](https://www.ibaset.com/wp-content/uploads/iBase-t-Solumina-MES-Brochure_v1.pdf)).
+- **Siemens Opcenter Execution** Discrete/Electronics: "complex assembly" is a *market segment*; execution guides operators with electronic work instructions (EWI) and step validation attached to operations ([Opcenter Execution](https://www.siemens.com/en-us/products/opcenter/execution/); [Opcenter Execution Electronics](https://www.siemens.com/en-us/products/opcenter/execution/electronics/)).
+
+Standards note: **ISA-95** classifies Level-3 operations into four categories — **production, quality, inventory, maintenance** — one categorical axis, with the same activity model applied to each. Treating a quality step as a first-class operation category has standards backing ([Rhize: What is ISA-95](https://rhize.com/blog/what-is-isa95/); [Symestic: MOM per ISA-95](https://www.symestic.com/en-us/what-is/manufacturing-operations-management)).
+
+---
+
+## Comparison table
+
+| System | Classification mechanism | In-house label | Subcontract label | Inspection | PO link for external ops |
+|---|---|---|---|---|---|
+| SAP PP | One field (control key) = named profile of indicators | "In-house production" (PP01) | **"External processing"** (PP02) | Indicator ("insp. char. required") / QM ops in inspection plans | PReq auto-created at order create/release |
+| Oracle Fusion | **Per-op enum `Operation Type`** | **In-House** (default) | **Supplier** ("Outside Processing"/OSP feature) | Inspection plans attached to any op (inline WIP) | OSP item + auto PO/receipt |
+| Oracle EBS (legacy) | Orthogonal flags + OSP *resource* | count-point/autocharge ops | OSP resource (PO Move/PO Receipt) | Quality plans at ops | PO via OSP resource charge |
+| JD Edwards | Outside-op flag on routing step | — | "Outside operation" | — | P3112 POs, `*OP` items |
+| NetSuite | Step kind inserted in routing | operation task | "Outside processing" op / outsourced mfg | — | Service item + vendor PO/bill |
+| Epicor Kinetic | Operation vs **subcontract operation** (special type) | "Operation" | **"Subcontract operation"** | "Inspection Required" checkbox + plans on any op | PO "Buy For: Subcontract Operation" |
+| Infor SyteLine | **Per-op `op_type`** + work center type | (standard op) | **"Outside Process"** | — | Generate Outside Process POs utility |
+| D365 SCM | No enum — Vendor-type resource + Vendor BOM line | (default) | "Subcontracting" | — | PO created at order estimation |
+| Fulcrum | Step kind in routing | (internal op) | **"Outside processing operation"** | — | PO shown on OSP op |
+| JobBOSS²/E2 | Estimating/routing line kind | (labor step) | **"Outside service"** | — | Vendor + lead time on service |
+| Tulip / Solumina / Opcenter (MES) | No op taxonomy — instructions attached | — | — | Inline inspection steps / buyoff hold points | — |
+| ISA-95 | Single category axis | Production | — | **Quality** (first-class category) | — |
+
+## Naming findings
+
+- **"Outside Processing" is the dominant modern term** (Oracle Fusion OSP, NetSuite, Infor "Outside Process", Fulcrum, legacy Oracle/JDE "outside operation"). SAP alone says "external processing"; Epicor/D365/Sage say "subcontract"; small job shops say "outside service." Carbon's `Outside Processing` matches the largest cluster and the term buyers see in Oracle/NetSuite/Fulcrum docs.
+- **No precedent for "Process" as the in-house label.** Oracle uses **In-House**; SAP "in-house production"; others leave the default unnamed ("operation", "standard"). "Process" is not wrong (Tulip/lean literature uses "process step"; D365 lean calls internal activities "process activities"), but In-House / Standard / Production are the attested labels.
+- **No precedent for "Assembly" as an operation type** in any ERP or MES surveyed — assembly is a work-instruction/content concern (Tulip, VKS, Solumina 3D instructions, Opcenter EWI) attached to ordinary operations.
+- **Inspection as a step**: attested both as dedicated operations (SAP QM01 inspection-plan operations; shops adding inspection ops to routings; Solumina buyoff/hold points) and as an attribute on any operation (Epicor checkbox, Oracle inline plans, SAP in-process characteristics). ISA-95 legitimizes "quality" as a peer category of "production."
+
+## Implications for Carbon
+
+1. **A single per-operation enum is the modern pattern.** Oracle Fusion (In-House|Supplier) and Infor (`op_type` = Outside Process) do exactly what Carbon proposes; both are simplifications of older orthogonal-flag models (EBS resources, D365 vendor-resource indirection) that practitioners found opaque. Oracle's docs even describe behavior as "if operation type is In-House, supplier attributes aren't collected" — the same branch shape as `operationType !== 'Outside Processing'`.
+2. **The in-house/outside boundary is the load-bearing distinction everywhere**: it decides PO generation, costing bucket (subcontract vs labor/overhead), scheduling by lead time vs capacity, and completion by receipt vs confirmation. Every vendor hard-wires exactly one binary: external or not. Writing all logic against `!== 'Outside Processing'` mirrors that and keeps the in-house side open for new values — SAP achieves the same openness via custom control keys whose *indicators* (not names) drive behavior; the lesson is to branch on the one semantic that matters (external), never on exhaustive lists of in-house types.
+3. **`Inspection` as a type is defensible but ahead of ERP practice.** ERPs model inspection as plans/flags attachable to *any* operation (Epicor, Oracle, SAP in-process); dedicated inspection steps are nonetheless common practice (SAP QM ops, aerospace hold points/buyoffs, ISA-95 quality category). Expect users to eventually want inspection *characteristics on non-inspection operations* too; the type should mean "this step exists to inspect," not "only here can inspection happen."
+4. **`Assembly` as a type is a Carbon-specific choice with no competitor precedent** — competitors attach 3D/guided instructions to ordinary operations. It is safe under the extensibility rule (it behaves in-house), but expect the same evolution: guided-instruction content may later be wanted on `Process` ops; keep the 3D-instruction machinery attachable rather than hard-bound to the type.
+5. **Naming**: `Outside Processing` — strongly validated. `Inspection` — validated (universal term). `Assembly` — novel but clear. `Process` — the only weakly-attested label; Oracle's `In-House` names the semantic the code branches on, while `Process`/`Standard` names the default work kind. If renaming is cheap, "Standard"/"In-House" have more precedent; if not, "Process" has no conflict with any competitor term.
+
+### Sources (primary)
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25c/faumf/create-a-standard-operation.html
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26b/faims/how-you-create-and-manage-work-orders-with-supplier-operations.html
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faumf/perform-inline-inspections.html
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/efc7922405fd4d56b7571930c5eaa798/90a1b8535c39b44ce10000000a174cb4.html
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/control-key-pp02-external-processing/qaq-p/5902949
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/production-control/manage-subcontract-work-production
+- https://www.netray.co/resources/how-to-configure-syteline-outside-processing
+- https://docs.oracle.com/en/applications/jd-edwards/supply-chain-manufacturing/9.2/eoash/understanding-outside-operations.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_157833700001.html
+- https://www.epiusers.help/t/subcontract-operations-for-job-material/106830
+- https://fulcrumpro.com/product-update/po-info-on-outside-processing-operations
+- https://www.ibaset.com/solutions/manufacturing-execution-system
+- https://tulip.co/digital-guidance/digital-work-instructions/
+- https://rhize.com/blog/what-is-isa95/
diff --git a/.ai/runs/2026-07-26-inspection-reject-writeoff.md b/.ai/runs/2026-07-26-inspection-reject-writeoff.md
new file mode 100644
index 0000000000..ddf3e15cbe
--- /dev/null
+++ b/.ai/runs/2026-07-26-inspection-reject-writeoff.md
@@ -0,0 +1,40 @@
+# Bugfix run: Inbound-inspection reject posts no inventory write-off
+
+- Date: 2026-07-26
+- Mode: fully-autonomous (stop at READY; commit only on explicit ask)
+- Request: Rejecting a non-tracked Inventory inbound-inspection lot posts no negative
+ inventory adjustment and no scrap-account journal. Ordered 5, rejected 5 (no -5),
+ NCR disposition use-as-is 3 (+3) → 8 on hand instead of 3.
+
+- Phase plan: root-cause [done — HIGH] · instrument [skip — HIGH confidence] ·
+ fix [run] · test [run — route-action unit test] · commit [skip — no explicit ask]
+
+## Decisions
+
+- instrument: skip — root cause HIGH, statically proven (git diff shows the engine
+ returns `writeOff` while committed HEAD reject route ignores it) — 2026-07-26
+- test approach: route-action unit test on `$id.reject.tsx` (mock requirePermissions +
+ dispositionInspection + fake client.functions.invoke), per traceability.search.test.ts
+ precedent — the defect is a missing route→edge-function call, so the route is the unit.
+
+## Phase log
+
+- root-cause: HIGH. 868f5c1bf moved the itemLedger reject write-off out of
+ `dispositionInspection` (now returns a `writeOff` descriptor); ERP reject route was
+ not updated to post it via `post-nonconformance`. Working tree already adds the wiring
+ but still swallows a failed post (logs + continues), so a failed write-off silently
+ proceeds to NCR creation whose Use-As-Is restore double-counts.
+
+- fix: hardened `$id.reject.tsx` — a failed `post-nonconformance` write-off now
+ surfaces (flash error) and aborts before NCR creation, instead of logging and
+ proceeding. Wiring (writeOff → post-nonconformance) confirmed present/correct.
+- test: added `$id.reject.test.ts` (3 cases). RED baseline: test 3 failed
+ (getInspection called after swallowed error); committed HEAD had 0 writeOff
+ references (wiring regression baseline). GREEN after fix: 3/3 pass.
+
+## Outcome
+
+- READY (not committed — no explicit ask). Gates: generate:types SKIP · biome PASS ·
+ typecheck(erp) PASS · test(erp quality+inspection) PASS 13/13.
+- Note: primary wiring fix was pre-existing uncommitted working-tree work; this run
+ adds the failure-surfacing hardening + the regression test that locks both.
diff --git a/.ai/specs/implemented/2026-07-14-mes-execution-views.md b/.ai/specs/implemented/2026-07-14-mes-execution-views.md
new file mode 100644
index 0000000000..e1e701f8cf
--- /dev/null
+++ b/.ai/specs/implemented/2026-07-14-mes-execution-views.md
@@ -0,0 +1,432 @@
+# PRD — MES Execution Views (Operation / Assembly / Inspection)
+
+Status: implemented (branch `feat/mes-assembly`) · Owner: MES execution-views
+
+Single consolidated spec for the MES execution-view work: the `operationKind` classification,
+the mobile Assembly view, part/tool ↔ step linking, step reference images ("slides"), and the
+planned Inspection view. Supersedes the earlier per-topic docs (CONTEXT.md, MES-FEEDBACK-STATUS.md,
+MES-PHASE2-DONE.md, MES-PHASE2-TEST-PLAN.md, PRD-step-reference-images.md, docs/adr/0001–0005 —
+all removed from the branch; recoverable from git history).
+
+---
+
+## 1. Problem & goal
+
+Operators on the shop floor execute three fundamentally different kinds of work from the MES:
+**machining/processing** (the existing Operation view), **assembly** (step-by-step build
+instructions with per-step parts, tools, and reference imagery), and **inspection** (executing a
+quality plan and recording actuals). Today the MES has one execution screen built around the first
+mode. This work introduces a per-operation classification that routes the operator to the right
+view, builds the Assembly view (mobile-first), scopes materials/tools/reference images to
+individual build steps, and lays the schema groundwork for the Inspection view.
+
+---
+
+## 2. Glossary (ubiquitous language)
+
+### jobOperation
+A single step of a job's routing (the live name for "BOP" — bill of process). The unit of work an
+operator executes. Each `jobOperation` is copied from a `methodOperation` template by the
+`get-method` edge function when a job is created.
+
+### operationType (formerly operationKind — superseded)
+> Superseded by [2026-07-20-operation-type-consolidation.md](2026-07-20-operation-type-consolidation.md):
+> `operationKind` was collapsed into a single `operationType` enum
+> (`Process | Assembly | Inspection | Outside Processing`, NOT NULL default `Process`),
+> shared with `process.processType`. The per-operation classification that decides
+> **which execution view** an operator sees: `Assembly` → assembly view, `Inspection` →
+> inspection view (falls through to Operation until Phase 3), everything else →
+> Operation view. Subcontract logic keys on `= 'Outside Processing'`; in-house logic on
+> `<> 'Outside Processing'`. Orthogonal to tracking type. Stored on `methodOperation`
+> (template) and copied verbatim to `jobOperation` / `quoteOperation` by `get-method`.
+> The process's own type is the authoring default (picking a process seeds the
+> operation's type).
+
+### tracking type
+The item's `itemTrackingType` — `Serial | Batch | Inventory | Non-Inventory`. Decides **per-unit
+vs. batch cadence inside a view**, never which view. `requiresSerialTracking` /
+`requiresBatchTracking` are **derived in code** from the item's `itemTrackingType`
+(`=== "Serial"` / `=== "Batch"`); they are not stored columns on `jobMakeMethod`.
+
+### unit axis
+The list of units an operator pages through ("Unit X of N"). Quantity-centric: length =
+`operationQuantity` for **every** tracking type. Unit *i* carries `trackedEntities[i] ?? null`.
+Serial binds a tracked entity per unit; Batch binds one lot entity to unit 0 only;
+Inventory/Non-Inventory bind none. This is the shared module (FIX-1) used by Assembly and
+(per-sample) Inspection.
+
+Record-index convention: `jobOperationStepRecord.index` = the unit's position *i* on the unit
+axis, for **all** tracking types (Serial = entity position in `trackedEntities`;
+Batch/Inventory = `0…N-1`). Identical to what the Operation view already writes, so the three
+views agree on per-unit done-state and no record backfill is needed. Relies on `trackedEntities`
+being returned in a stable, deterministic order.
+
+### slide
+One reference image attached to a step, with an optional caption and a `sortOrder`. The atomic
+unit operators page through. Slides are reference media on the step, *not* a step `type`.
+
+### inspection plan
+The quality definition for a part: an `inspectionDocument` (ballooned drawing) holding
+`inspectionFeature` rows (features with nominal ± tolerance and unit). Today an ERP-only
+definition with no link to a job/operation and no result-capture. The Inspection view executes a
+plan against a `jobOperation`, linked by an explicit nullable `inspectionDocumentId` FK on the
+operation (picker defaults via resolve-by-item: the part's sole `inspectionDocument` if exactly
+one exists).
+
+### variable / attribute feature
+An `inspectionFeature` is **variable** (numerically evaluated for pass/fail against
+`nominalNumeric ± tolerance`) iff its numeric columns are populated; otherwise it is an
+**attribute** feature the inspector marks pass/fail by hand (thread fits, surface-finish
+callouts, GD&T, visual). Numeric columns (`nominalNumeric`, `tolerancePlusNumeric`,
+`toleranceMinusNumeric`) are added alongside the existing TEXT, which is retained for display and
+non-numeric specs. See §5.3.
+
+### pass/fail evaluator
+A pure function `(actual, nominalNumeric, tolerance±, unit) → pass | fail | out-of-tolerance`,
+run only for variable features. Records actuals into the inspection result record.
+
+### result record
+The planned `jobOperationInspectionRecord` table — one row per `inspectionFeature` per
+unit/sample, keyed `(jobOperationId, inspectionFeatureId, index)`. Modeled column-for-column on
+`jobOperationStepRecord` (`numericValue` = actual; `value`/`booleanValue`/`userValue` for
+attribute features); `index` from the unit-axis module; optional `gaugeId`; a `result`
+(`pass | fail | out-of-tolerance`) **frozen at record time** for as-inspected evidence. A failing
+row links a `nonConformance` via the existing association. It is *not* a `jobOperationStepRecord`
+— inspection features are `inspectionFeature` rows, never synthetic procedure steps.
+See §5.4.
+
+---
+
+## 3. Delivered functionality
+
+### Phase 1 — Mobile/touch Assembly UI ✅
+- Primary operator actions (Complete, Flag issue, timer Start/Pause) sized `lg`; material
+ issue/scan tap targets enlarged 20px → 36px.
+- "Assy" label renamed to **"Completed item"**.
+- Fullscreen reference-image viewer with pinch/wheel zoom and pan (`ImageZoomViewer.tsx`).
+
+### Phase 2 — Part/Tool ↔ Step ✅ (end to end)
+
+**The idea in one line:** a material/tool is **owned by an operation** and may be **optionally
+assigned to one step** of that operation. The assignment is a **nullable FK** — `NULL = applies
+to the whole operation` (shown on every step, the legacy behavior). The link is authored on the
+**method template** (ERP) and **copied to the job** by the `get-method` edge function, exactly
+like steps, slides, tools, and parameters already are. The MES then filters per step.
+
+```
+methodOperationStep (a step of an operation)
+ ▲ ▲
+ │ methodOperationStepId │ methodOperationStepId (NULL = whole operation)
+ │ │
+ methodMaterial methodOperationTool ← authored in ERP (BoM / BoP editors)
+ │ │
+ │ get-method copy (method-step → job-step map)
+ ▼ ▼
+ jobMaterial.jobOperationStepId jobOperationTool.jobOperationStepId
+ │ │
+ ▼ ▼
+ MES assembly view filters materials & tools to the current step
+```
+
+**Data model.** Six nullable FK columns (3 tiers × {material, tool}), each indexed:
+
+| Table | Column | References | On delete |
+|-------|--------|-----------|-----------|
+| `methodMaterial` | `methodOperationStepId` | `methodOperationStep(id)` | `SET NULL` |
+| `jobMaterial` | `jobOperationStepId` | `jobOperationStep(id)` | `SET NULL` |
+| `quoteMaterial` | `quoteOperationStepId` | `quoteOperationStep(id)` | `SET NULL` |
+| `methodOperationTool` | `methodOperationStepId` | `methodOperationStep(id)` | `SET NULL` |
+| `jobOperationTool` | `jobOperationStepId` | `jobOperationStep(id)` | `SET NULL` |
+| `quoteOperationTool` | `quoteOperationStepId` | `quoteOperationStep(id)` | `SET NULL` |
+
+- **Backward compatible:** every existing row stays `NULL` (operation-level).
+- **`ON DELETE SET NULL`** is deliberate — the material/tool belongs to the *operation* and is
+ only *assigned* to a step. Deleting the step must revert the link to operation-level, not
+ delete the material/tool.
+
+**Authoring (ERP).**
+- Part → step: the BoM editor's operation row gains a **Step** picker listing the selected
+ operation's steps; changing the operation clears the step
+ (`apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx`; `methodMaterialValidator` gains
+ optional `methodOperationStepId`).
+- Tool → step: the BoP editor's tool **add and edit** forms render the same optional Step picker
+ (`apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx`). The tool routes read
+ `methodOperationStepId` straight from `formData` (not `validation.data`) so the shared
+ `operationToolValidator` stays tier-agnostic — job/quote tools use a different column name.
+
+**Copy to the job (`get-method` edge function).** Both job-copy paths (`itemToJob`,
+`itemToJobMakeMethod`) build a **method-step → job-step map** when steps are inserted (a bulk
+insert preserves order, so `insertedSteps[i] ↔ methodOperationStep[i]`).
+`jobMaterial.jobOperationStepId` and `jobOperationTool.jobOperationStepId` are set from that map;
+unmapped → `null`. Key fix for tools: the operation loop previously inserted **tools before
+steps**, so the step map didn't exist yet — the `jobOperationTool` insert was moved to after the
+step insert in both job paths. Tools on procedure-based operations (no steps) still copy, with
+`jobOperationStepId: null`. The accumulating step map is safe across operations because step ids
+are globally unique. The `get_method_tree` RPC surfaces `methodMaterial.methodOperationStepId`
+on material tree nodes, including top-level (root assembly) materials.
+
+**MES per-step filtering.** `getToolsByProcessId` (which looked up *any* method operation by
+`processId`) was replaced by `getToolsByOperationId`, which reads the job's own
+`jobOperationTool` rows and carries `jobOperationStepId`
+(`apps/mes/app/services/operations.service.ts`). In `AssemblyView.tsx`, materials and tools are
+filtered to the current step with the identical rule:
+
+```ts
+// applies to this step if unscoped (null) or scoped to this step
+m.jobOperationStepId == null || m.jobOperationStepId === (step?.id ?? null)
+```
+
+Serial/batch **scan-at-step** falls out for free: the per-step material list drives the
+"Scan Part" pre-selection, so the operator scans the tracked part on the step where it's used.
+
+### Phase 3 — Behavioral ✅
+- **Auto-start job + operation** on production-event Start (`startProductionEvent` →
+ `autoStartJobAndOperation`, status-guarded; both start paths). Gated by the
+ `companySettings.autoStartOperationTimer` flag.
+- **MES preview from the BOP tab with no live job** (`OperationPreview` read-only per-step view:
+ image + step text + per-step tools, in the BillOfProcess "Preview" tab).
+- **Realtime refresh** of BOP steps on a live job without closing (realtime channel on
+ `jobOperationStep`/`jobOperationStepRecord` → revalidate in JobBillOfProcess).
+
+### Operation Type + Kind merge ✅ (columns physically collapsed)
+Done — see [2026-07-20-operation-type-consolidation.md](2026-07-20-operation-type-consolidation.md).
+One enum `Process | Assembly | Inspection | Outside Processing` on `operationType`
+(operations AND `process.processType` — same Postgres type; the old `processType` and
+`operationKind` enums are gone). All three BOP editors (Item, Job, Quote) share the same
+single **Operation Type** picker; the classification shim (`operationClassifications` +
+mapping helpers) was deleted; every `=== "Outside"` site was rewritten to
+`=== 'Outside Processing'` and every `=== "Inside"` site to `!== 'Outside Processing'`.
+"Standard" was renamed to "Process"; "Batch" stays dropped (tracking type's job).
+
+---
+
+## 4. Step reference images ("slides")
+
+### Problem
+Operators need **reference imagery per build step** — "here's what this looks like when done /
+where this part goes." Previously there was no first-class way to attach one: images were
+embedded inside the step's rich-text `description` (TipTap `image` nodes) and scraped back out at
+render time by an `extractImages()` heuristic, so image order/captions weren't data and reference
+art was tangled with instruction prose.
+
+### Model
+A **slide** is a first-class child of a step holding **one image** plus optional caption and
+order. A step has zero or more slides; execution views render them as a per-step carousel.
+Slides are authored on the **method** (template) and copied to the **job/quote** operation by
+`get-method`, exactly like steps, materials, tools, and parameters.
+
+Three tables mirroring the step-copy chain: `methodOperationStepSlide` (authored in ERP),
+`jobOperationStepSlide` (copied per job), `quoteOperationStepSlide` (copied per quote). Columns:
+`id` (`id('slide')`), `stepId` FK → matching `*OperationStep` `ON DELETE CASCADE`, `imagePath`
+(private-bucket storage path; **nullable** since the step-model-slides migration), `modelUploadId`
+(nullable FK → `modelUpload` `ON DELETE CASCADE` — a slide is image XOR model, enforced by a
+CHECK), `caption` (nullable), `sortOrder` (double precision), `size` (display size, default
+`medium`), `annotations` (JSONB, default `[]`; image slides only), `companyId`, standard
+audit columns. RLS: identical policies to the parent step tables.
+
+**3D model slides** (added 2026-07-19, `20260719221229_step-model-slides.sql`): a slide can be
+a 3D model instead of a picture. The editors upload the file to `{companyId}/models/…` in the
+`private` bucket and register it via `/api/model/upload` with `convert` — which fires the
+`assembly-convert` Inngest task (assembler service STEP → GLB) when the source is STEP and the
+assembler is healthy. The MES assembly view renders model slides with `ModelViewer`, preferring
+`modelUpload.glbPath` and falling back to the raw `modelPath` (parsed client-side), so the
+feature degrades gracefully when the assembler is not deployed. get-method copies
+`modelUploadId` verbatim alongside `imagePath`.
+
+**Assembly → BOP sync** (added 2026-07-20, `20260720025847_assembly-bop-sync.sql`): a
+Published `assemblyInstruction`'s steps can be copied into a BOP operation ("Sync to BOP"
+on the instruction header) — target is a Draft method operation (jobs inherit via
+get-method) or an unlocked job operation. Synced steps carry an
+`assemblyInstructionStepId` provenance marker so re-sync updates/deletes only its own
+steps, per-step BOM parts become material↔step links, and the instruction's model is
+attached as a model slide per step. See `syncAssemblyInstructionToOperation`
+(production.service.ts).
+
+**Step-aware 3D playback in the MES assembly view** (added 2026-07-20): when the job
+operation carries `assemblyInstructionId` and the model has converted artifacts, the
+loader resolves `getAssemblyPlaybackByOperationId` and the view mounts the animated
+`AssemblyPlayer` (`@carbon/viewer`) pinned to the operator's current step — mapped via
+the step's `assemblyInstructionStepId` marker. It is the default media for mapped steps
+(a ▶ 3D carousel entry); picture and static-model slides remain selectable. get-method
+carries `assemblyInstructionId` onto job operations, so jobs made from a synced method
+get playback automatically. This supersedes the earlier note that the animated player
+stays out of the assembly view.
+
+### Non-goals
+- Replacing the rich-text `description` (prose stays; slides are separate reference media).
+- Video slides. (3D model slides shipped 2026-07-19 — see above; originally a non-goal.)
+- Animated per-step assembly playback (`AssemblyPlayer` / `assemblyInstruction`) inside the
+ assembly view — model slides are static/orbitable models per step.
+- Operator-captured photos at run time (that's the existing **File** step-record type).
+
+### Acceptance criteria
+1. An engineer can attach N slides (image + caption + order) to a BOP step in the ERP.
+2. Creating a job copies the step's slides into `jobOperationStepSlide` with order preserved.
+3. The assembly view shows the current step's slides as a carousel; "No reference image" only
+ when a step truly has none.
+4. Captions render; ordering respects `sortOrder`.
+5. Description prose no longer needs embedded images.
+6. RLS: an operator can only read slides for operations in their company/assignment.
+
+---
+
+## 5. Architecture decisions (consolidated ADRs)
+
+### 5.1 Separate MES route per execution view, with redirect guards (accepted)
+Each execution view gets its own route:
+
+```
+/x/operation/:id → JobOperation (operationType = Process / Outside Processing, the default)
+/x/assembly/:id → AssemblyView (operationType = Assembly)
+/x/inspection/:id → InspectionView (operationType = Inspection — shipped 2026-07-26)
+```
+(Originally keyed on `operationKind`; re-keyed on the consolidated `operationType` —
+see 2026-07-20-operation-type-consolidation.md. The value reaches the routes via
+`get_job_operation_by_id`.)
+
+Each route's loader returns **one** shape and renders **one** view. Every route opens with a
+**redirect guard**: it reads the operation's `operationKind` and, if the kind doesn't belong to
+that route, throws a `redirect` to the correct one (preserving search params) — so any URL
+self-corrects and a reclassified operation's saved link still lands on the right screen.
+
+This **reverses an earlier decision** to have one route (`/x/operation/:id`) switch on
+`operationKind` with a discriminated-union loader. Reversed because: a route shouldn't return
+three different response shapes (polymorphic-route smell); the three modes diverge over time
+(Assembly gains CAD-driven instructions, Inspection executes a quality plan); and the URL should
+communicate the mode. The deep-link-stability argument that justified the single route is
+preserved by the guards, at the cost of an occasional extra redirect hop.
+
+Consequences: the work queue navigates to `/x/operation/:id` and the guard redirects Assembly
+ops (one hop) — routing the queue directly by kind would need `operationKind` in the work-queue
+RPC (deferred optimization). Until the Phase-3 inspection route exists, `Inspection` ops fall
+through to `JobOperation` (no redirect) to avoid a loop. Guards must not create loops: a route
+only redirects kinds it does *not* serve, and only to routes that exist.
+
+### 5.2 One shared MES execution core for all three views (accepted)
+The Operation view (`JobOperation.tsx`, ~2,400 lines) and the Assembly POC (`AssemblyView.tsx`,
+~1,800 lines) independently re-implement timers/`productionEvent`, quantity reporting, material
+issue, NCR, realtime, completion, and unit navigation — and the two copies already drift. We
+extract a **single execution core** all three views consume.
+
+**Direction: lift the core out of the working Operation view, and re-point the Operation view at
+it first, as a behavior-preserving refactor verifiable against `main`.** Only after Operation
+consumes the extracted core (same screen, zero behavior change) do we re-point Assembly and build
+Inspection on it. Boundary: shared core = hook(s) + shared modal components + a layout shell
+(timer/`productionEvent`, quantity, material issue, NCR affordance, realtime channel,
+completion/finish, unit-axis navigation); view-specific body = Operation's procedure/step
+rendering, Assembly's build-step + static model, Inspection's feature list + record +
+pass/fail + gauge. Sequencing: unit-axis module first → extract the core while wiring Assembly,
+Operation re-pointed to prove parity → Inspection last. Rejected alternatives: a fresh core
+(no parity gate, discards proven behavior) and keeping Assembly's copy (guarantees drift).
+
+### 5.3 Numeric tolerance columns alongside TEXT on `inspectionFeature` (accepted)
+Pass/fail needs numbers, but `inspectionFeature.nominalValue / tolerancePlus / toleranceMinus /
+unit` are TEXT — deliberately, since not every feature is numeric (thread fits like `H7`,
+`≤Ra 1.6`, GD&T, visual go/no-go). We **add nullable numeric columns** (`nominalNumeric`,
+`tolerancePlusNumeric`, `toleranceMinusNumeric`, DOUBLE PRECISION) **alongside** the TEXT rather
+than replacing it or parsing at evaluation time. A feature is a **variable** feature iff
+`nominalNumeric` is non-null; otherwise **attribute** (manual pass/fail). No `featureType` enum
+in v1 — numeric-presence is the mode. The balloon-extraction/save path emits numeric for new
+features; a one-time lenient backfill parses existing TEXT where clean and leaves null otherwise
+(the backfill must never fail the migration). Numeric is authoritative for pass/fail, TEXT for
+display; consistency is the extraction/save path's responsibility.
+
+### 5.4 Inspection execution: explicit plan link and a dedicated result record (plan link accepted; result record SUPERSEDED)
+
+> **Superseded (result record), 2026-07-26.** The `jobOperationInspectionRecord`
+> table was never built. After this spec, the quality module's inspection system
+> was unified and made source-generic (`20260722132135_inspections-refactor.sql`:
+> `inspection` / `inspectionSample` / `inspectionSamplingPlan` /
+> `inspectionMeasurement` with `sourceDocument` = 'Receipt' | 'Job Operation').
+> The shipped MES Inspection view executes against those tables — a lot per
+> job operation created lazily on first open (`getOrCreateJobOperationInspection`
+> in `@carbon/database/quality`), per-feature AQL sampling, measurements
+> in `inspectionMeasurement`, Accept/Partial/Reject disposition. Since
+> 2026-07-27 the disposition carries its production outcome (one-shot
+> `requireOpen` close, then Accept completes the remainder while Reject/Partial
+> allocate the failed set per-unit between Scrap and Rework — the rework path
+> via `trigger-rework`'s routing clone, which re-inspects automatically;
+> provenance links on `productionQuantity.inspectionId`/`inspectionSampleId`
+> guard double-posting); the NCR is optional documentation only.
+> The **plan-link half of this ADR stands**: `inspectionDocumentId` FK on
+> method/quote/job operations, propagated by get-method. See
+> `.claude/rules/inspection-system.md` for the live model.
+**Plan link — explicit FK, not resolve-by-item.** A nullable `inspectionDocumentId` FK is added
+to `methodOperation` / `jobOperation` / `quoteOperation` and propagated through `get-method`
+(added in the Inspection workstream, not the `operationKind` migration, to keep the keystone
+classification migration independent). Resolve-by-item is ambiguous — a part can have multiple
+`inspectionDocument`s and different ops may inspect different feature subsets. The BOP-editor
+picker *defaults* via resolve-by-item; the stored FK is the source of truth.
+
+**Result record — a new table mirroring `jobOperationStepRecord`, not synthetic steps.**
+Inspection features are `inspectionFeature` rows, not `jobOperationStep` rows, so writing
+into `jobOperationStepRecord` would require synthesizing fake steps. Instead
+`jobOperationInspectionRecord` is keyed `(jobOperationId, inspectionFeatureId, index)`, one row
+per feature per unit/sample, with `index` from the shared unit-axis module, an optional
+`gaugeId`, and a `result` frozen at record time (as-inspected evidence that survives later
+tolerance edits; the numeric columns of §5.3 remain the source for re-evaluation). A failing row
+links a `nonConformance` via the existing association.
+
+Consequence: `operationKind` and `inspectionDocumentId` share the same `get-method` copy-lists —
+omitting either silently breaks propagation.
+
+---
+
+## 6. Known gaps & backward compatibility
+
+- **`quoteLineToJob` path**: the quote → job conversion copies neither part→step nor tool→step
+ (parity with the part-link scope). Jobs created directly from an item's method (the common
+ path) are fully covered.
+- **Legacy jobs**: rows created before this work carry `NULL` step links, so all materials/tools
+ show on every step — the legacy behavior, no regression.
+- **Procedure-based operations** (no steps): tools copy with `jobOperationStepId = NULL`;
+ no errors.
+- **Deleting a step** reverts its materials/tools to operation-level (`ON DELETE SET NULL`) —
+ it never deletes them.
+- **Type regen caveat (this branch only)**: a full `generate:types` run against the restored dev
+ DB is polluted; new columns were hand-added to `packages/database/src/types.ts` and
+ `packages/database/supabase/functions/lib/types.ts`. Regenerate cleanly before merge.
+
+---
+
+## 7. Remaining work (Phase 4 roadmap)
+
+- ~~Job/Quote BOP editors: mirror the unified Type picker; physical `operationType`+`operationKind`
+ column collapse~~ ✅ Done — 2026-07-20-operation-type-consolidation.md.
+- Production: shortage flag → close without consuming stock → auto-raise a future job; passive
+ step timer (cycle time); manager complete-all override; step overview screen.
+- Content authoring: image resize/grid in the editor; annotation; tool hotspots.
+- MES UX: navigate/filter incomplete steps; swipe between serials; hands-free advance.
+- Quality: NCR → step link; parts/tools on NCR.
+- ~~Inspection view (Phase 3 of the execution-views plan): route + guard, plan link, result
+ record, pass/fail evaluator, gauge picker.~~ ✅ Shipped 2026-07-26 on the unified
+ inspection tables (see §5.4 supersession note); gauge picker deferred.
+- Suggested (low priority): revision history, copy/clone steps, operator dashboard, step
+ sign-off, rework flag, NCR trend, first-pass rate.
+
+---
+
+## 8. Verification
+
+- `pnpm --filter mes typecheck` and `pnpm --filter erp typecheck` → 0 errors.
+- All schema changes live in the single squashed migration
+ `packages/database/supabase/migrations/20260705143722_mes-assembly-view.sql`.
+- Manual end-to-end check: author a method with an Assembly-kind operation, 3 steps, materials
+ and tools assigned to specific steps (one of each left operation-level), slides on two steps;
+ create a job from it; verify in the DB that `jobMaterial.jobOperationStepId` /
+ `jobOperationTool.jobOperationStepId` carry the mapped step ids (operation-level rows NULL);
+ open `/x/assembly/{jobOperationId}` and confirm parts/tools/slides filter per step,
+ operation-level items show on every step, scan-at-step pre-selects the tracked part on its
+ step, and per-unit step completion tracks the unit pager.
+
+```sql
+-- parts per step on a job
+SELECT jm."itemId", jos."name" FROM "jobMaterial" jm
+LEFT JOIN "jobOperationStep" jos ON jos."id" = jm."jobOperationStepId"
+WHERE jm."jobId" = '<JOB_ID>';
+
+-- tools per step on a job
+SELECT jot."toolId", jos."name" FROM "jobOperationTool" jot
+LEFT JOIN "jobOperationStep" jos ON jos."id" = jot."jobOperationStepId"
+WHERE jot."operationId" IN (SELECT "id" FROM "jobOperation" WHERE "jobId" = '<JOB_ID>');
+```
diff --git a/.ai/specs/implemented/2026-07-20-operation-type-consolidation.md b/.ai/specs/implemented/2026-07-20-operation-type-consolidation.md
new file mode 100644
index 0000000000..3a582b76aa
--- /dev/null
+++ b/.ai/specs/implemented/2026-07-20-operation-type-consolidation.md
@@ -0,0 +1,236 @@
+# Operation Type Consolidation — one enum for operations and processes
+
+> Status: implemented (branch feat/mes-assembly, migration 20260721004140)
+> Author: Brad Barbin (design) + Claude (spec)
+> Date: 2026-07-20
+> Research: [.ai/research/operation-type-consolidation.md](../research/operation-type-consolidation.md)
+> Supersedes: the "Operation Type + Kind merge" section and ADR §5.1 keying of [2026-07-14-mes-execution-views.md](2026-07-14-mes-execution-views.md)
+
+## TLDR
+
+The `feat/mes-assembly` branch added an `operationKind` column (`Operation | Assembly | Inspection`) alongside the pre-existing `operationType` enum (`Inside | Outside`), plus a UI-only "classification" shim that merges the two. That two-column model was a mistake. This spec collapses everything into a **single `operationType` Postgres enum with values `Process | Assembly | Inspection | Outside Processing`**, applied to `methodOperation`, `quoteOperation`, `jobOperation`, **and `process.processType`** (same enum type, so they can never drift). Data maps `Inside → Process`, `Outside → Outside Processing`, and folds `operationKind` in (`Assembly`/`Inspection` win over `Operation`; `Outside` wins over everything). All "inside" business logic becomes `operationType !== 'Outside Processing'` so future in-house types don't touch costing/scheduling/PO code; the MES assembly view keys on `operationType === 'Assembly'`.
+
+## Problem Statement
+
+- The branch shipped a bastardized model: the Items BoP editor uses a merged 4-value picker that writes two hidden columns; the Job BoP shows **two separate selects** (`operationType` + `operationKind`); the Quote BoP shows only the old binary select and can't classify at all. Three editors, three different UXes for the same concept.
+- Two columns encode one user-facing concept, with an app-side mapping shim (`classificationFromTypeKind` / `typeKindFromClassification` in `apps/erp/app/modules/shared/operationKind.ts`) that every consumer must know about. Contradictory states (`Outside` + `Assembly`) are representable in the DB but meaningless.
+- `process.processType` (`Inside | Outside | Inside and Outside`) uses the old vocabulary, so after the operation-side rename the two enums would describe the same axis with different words.
+- Competitor research validates the single-enum shape: Oracle Fusion models exactly one per-operation type (`In-House | Supplier`); "Outside Processing" is the dominant industry term. "Assembly" as a type is novel (others attach instructions to any op) but safe because it behaves in-house everywhere except the MES view router.
+
+## Proposed Solution
+
+One enum, four values, everywhere:
+
+```
+operationType: 'Process' | 'Assembly' | 'Inspection' | 'Outside Processing'
+```
+
+- **Semantic rule (the load-bearing invariant):** subcontract behavior keys on `=== 'Outside Processing'`; in-house behavior keys on `!== 'Outside Processing'`. Never enumerate the in-house values in business logic — that is what lets us add more in-house types later without touching costing, scheduling, PO generation, or the traveler.
+- **MES view routing:** `Assembly → /x/assembly`, `Inspection → /x/inspection` (falls through to the operation view until the Phase-3 inspection view exists), everything else → `/x/operation`. Same redirect-guard architecture as today, re-keyed.
+- **`process.processType` uses the same Postgres enum type** (`"operationType"`) and becomes the *default operation type* for operations using that process: BoP editors seed `operationType = process.processType` directly. The old "Inside and Outside" capability is expressed by data, not the enum: former "both" processes land as `Outside Processing` (their `workCenterProcess` links keep in-house execution possible), ProcessForm's work-center and supplier sections are both always visible, and an operation on any process can be overridden to either side.
+- **App layer:** a single `operationTypes` const in `apps/erp/app/modules/shared/shared.models.ts` serves operations *and* processes (the separate `processTypes` const is deleted). `shared/operationKind.ts` is deleted entirely.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Value names | `Process`, `Assembly`, `Inspection`, `Outside Processing` | Brad's directive (renames the PRD's "Standard" → "Process"). "Outside Processing" matches Oracle/NetSuite/Infor and Carbon's own `purchaseOrderType` value. "Batch" stays dropped — it's the item tracking type's job. |
+| Inside-logic pattern | `!== 'Outside Processing'` (never `=== 'Process'`, never in-house value lists) | Extensibility: new in-house types inherit costing/scheduling/PO behavior for free. Matches how SAP/Oracle hard-wire only the in-house/external boundary. |
+| Data mapping | `Outside → Outside Processing` first, then `operationKind Assembly/Inspection → same`, else `Process` | Outside-wins precedence is the existing `classificationFromTypeKind` precedent; contradictory rows can't round-trip into the UI today. |
+| processType | Same Postgres enum type as operations; `Inside → Process`, `Outside → Outside Processing`, `Inside and Outside → Outside Processing`; `processType` enum type dropped | Brad's decision (2026-07-20): "mirror the new enum exactly — use the same enum so it stays in sync; single const in shared.models.ts"; "inside and outside should land as outside processing". Former "both" processes keep in-house capability via their `workCenterProcess` links + per-operation override. |
+| Migration mechanism | Rename old type aside → create new `"operationType"` → per-table `ALTER COLUMN ... TYPE ... USING CASE` (reads `operationKind` in the same expression) → drop `operationKind` columns → drop old types | Equivalent to the temp-column approach (the "temporary" artifact is the renamed old *type*, not a column) with one atomic, easily-guarded conversion per table and no column-order churn. Temp-column variant remains a valid fallback if plan-time validation finds a blocker. |
+| Migration packaging | **(Amended by Brad, 2026-07-20)** Edit the squashed branch migration inline so `operationKind` never exists anywhere (branch SQL is unmerged); its `get_job_operation_by_id` redefinition surfaces `operationType` instead. One new forward migration (fresh timestamp `> 20260720094011`) handles only the enum swap for data that exists on deployed DBs. Local DBs are rebuilt with `crbn reset`, then types regenerate cleanly. | Cleanest possible history — no add-then-drop column. The reset eliminates the local-drift and polluted-types problems in one stroke (local Assembly/Inspection demo data is accepted as lost). |
+| Enum labels in UI | Render raw enum values (existing `Enumerable`/options-map pattern); icons via `OperationTypeIcon` | Matches every other enum in the app; "Outside" badges become "Outside Processing". |
+| H1 multi-tenancy | N/A — no new tables; columns live on existing tenant-scoped tables | Composite PKs/`companyId` untouched. |
+| H2 service shape | No new services; existing signatures unchanged | Only literals and copied field lists change. |
+| H3 RLS | Unchanged; recreated views keep `SECURITY_INVOKER=true` | No policy references either column (verified). |
+| H4 permissions | Unchanged — existing route scopes cover all touched routes | No new routes. |
+| H5 forms | Existing `ValidatedForm` validators keep field name `operationType`; `operationKind` fields removed | Single `z.enum(operationTypes)`; refines re-keyed. |
+| H6 module layout | Consts in `shared.models.ts`; `shared/operationKind.ts` deleted; barrel updated | One const per Brad's directive. |
+| H7 backward compatibility | Breaking for API filters/CSV templates that send `Inside`/`Outside`; CSV import accepts legacy aliases; configurator returns normalized at the get-method boundary | See Risks. Accepted as part of the directive; swagger schema regenerates. |
+
+## Data Model Changes
+
+New migration `2026XXXXXX_operation-type-consolidation.sql` (fresh timestamp newer than main's `20260720094011`, random HHMMSS per convention). Every step guarded so a deploy-runner retry over partially-committed state is safe. Sketch (guards elided for readability — the plan writes them; the pattern is `DO $$` blocks checking `pg_type`/`information_schema.columns` state):
+
+```sql
+-- 1. Move the old enum aside and create the new one under the same name
+-- (guard: skip if "operationType" already has label 'Process')
+ALTER TYPE "operationType" RENAME TO "operationType__old";
+CREATE TYPE "operationType" AS ENUM ('Process', 'Assembly', 'Inspection', 'Outside Processing');
+
+-- 2. Drop dependent views (they all project t.*)
+DROP VIEW IF EXISTS "jobOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "jobOperationsWithDependencies";
+DROP VIEW IF EXISTS "quoteOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "processes";
+
+-- 3. Convert the three operation tables (guard per table: skip if already new type)
+-- Same block for "quoteOperation" and "jobOperation". No operationKind anywhere:
+-- the squashed branch migration is edited inline so the column never existed.
+ALTER TABLE "methodOperation" ALTER COLUMN "operationType" DROP DEFAULT;
+ALTER TABLE "methodOperation"
+ ALTER COLUMN "operationType" TYPE "operationType"
+ USING (CASE
+ WHEN "operationType"::text = 'Outside' THEN 'Outside Processing'
+ ELSE 'Process'
+ END)::"operationType";
+ALTER TABLE "methodOperation" ALTER COLUMN "operationType" SET DEFAULT 'Process';
+
+-- 4. Convert process.processType to the SAME enum type
+ALTER TABLE "process" ALTER COLUMN "processType" DROP DEFAULT;
+ALTER TABLE "process"
+ ALTER COLUMN "processType" TYPE "operationType"
+ USING (CASE
+ WHEN "processType"::text = 'Inside' THEN 'Process'
+ ELSE 'Outside Processing' -- 'Outside' and 'Inside and Outside' both land here
+ END)::"operationType";
+ALTER TABLE "process" ALTER COLUMN "processType" SET DEFAULT 'Process';
+
+-- 5. Drop the retired types (after the function redefinitions below — the old
+-- get_job_operation_by_id signature references the old enum type)
+DROP TYPE IF EXISTS "operationType__old";
+DROP TYPE IF EXISTS "processType";
+
+-- 6. Recreate the four views, forked verbatim from their NEWEST definitions:
+-- jobOperationsWithMakeMethods, jobOperationsWithDependencies → 20260610151942_assembly-instructions.sql
+-- quoteOperationsWithMakeMethods → 20250603011801_make-method-version.sql
+-- processes → 20260120171236_process-active-column.sql
+
+-- 7. Redefine get_job_operation_by_id: DROP FUNCTION + recreate bound to the NEW enum
+-- (the edited squashed migration already surfaces "operationType" instead of
+-- operationKind, but its signature is bound to the OLD enum type at that point in
+-- history — recreate here before dropping "operationType__old").
+
+-- 8. Re-land get_method_tree forked from main's NEWEST definition (20260714084035_remove-bom-line-effectivity.sql)
+-- merged with the branch's methodOperationStepIds additions — see Risks (ordering bug).
+```
+
+Facts the sketch relies on (verified):
+- `operationType` columns exist on exactly three tables, all `NOT NULL DEFAULT 'Inside'` (`20240823024502`, `20240915192542`). No other table has one.
+- `operationKind` existed only in the squashed branch migration `20260705143722_mes-assembly-view.sql` (enum + 3 columns), which is edited inline by this work so the column and enum never exist; its `get_job_operation_by_id` redefinition now surfaces `operationType` (the MES router's input). Requires `crbn reset` on local DBs that applied the old version.
+- No indexes, CHECK constraints, or triggers reference either column; no seed data writes them.
+- Only two SQL functions reference them: `get_job_operation_by_id` (returns `operationKind` — the MES router's source) and `get_sales_order_lines_by_customer_id` (surfaces `jo."operationType"` into JSON pass-through — needs **no change**; converted row values flow through).
+- `supplierProcesses` and `workCenters` views don't project `process.processType` — no recreation needed (verify at plan time).
+- On prod at deploy time, migrations apply in timestamp order: the squashed branch migration adds `operationKind` (all rows default `'Operation'`), then this migration folds and drops it — so the `USING` expression is valid on both prod and already-migrated local DBs.
+
+Post-migration: `pnpm run generate:types` (against a clean local DB — the branch previously hand-edited `types.ts`, see Risks), then propagate via the type chain. Generated diff: `Enums.operationType` → 4 values; `Enums.operationKind` and `Enums.processType` disappear; `process.processType` typed as `Enums.operationType`; `swagger-docs-schema.ts` regenerates.
+
+## API / Service Changes
+
+**Deleted:** `apps/erp/app/modules/shared/operationKind.ts` (whole file: `operationKinds`, `operationClassifications`, `OperationClassification`, `classificationFromTypeKind`, `typeKindFromClassification`) and its barrel line in `shared/index.ts:2`.
+
+**Changed const (single source of truth):** `shared.models.ts:205` → `export const operationTypes = ["Process", "Assembly", "Inspection", "Outside Processing"] as const;` + `export type OperationType = (typeof operationTypes)[number];`. Delete `processTypes` (`shared.models.ts:223-227`); all its importers switch to `operationTypes`.
+
+**Zod validators** — drop `operationKind` field, re-key refines (`=== "Inside"` → `!== "Outside Processing"`, `=== "Outside"` → `=== "Outside Processing"`):
+- `items.models.ts:483-488` + Inside refines `:520,532,544,556,568,580`
+- `production.models.ts:291-296` + Outside refines `:337,349,361,500,512,524,536` + Inside refines `:373-644` (19 sites)
+- `sales.models.ts:434-439` + Outside refines `:474,486,498` + Inside refines `:510-606`
+- `sales/ui/CustomerPortal/shared.ts:11` (picks up new values via the const)
+- Resources: `resources.models.ts:306,312` (`processType !== "Outside"` → `!== "Outside Processing"`)
+
+**Services / logic sites (ERP):**
+- `production.service.ts:1638` `.eq("operationType", "Outside")` → `"Outside Processing"` (`getOutsideOperationsByJobId`)
+- `sales.service.ts:4111` (`Inside` cost rollup → `!==`), `:4168` (`Outside` → `===`)
+- `useLineCosts.tsx:152,360` (client mirror of the same)
+- `utils/bom.ts:126` `calculateOperationUnitCost` (`Outside` → `Outside Processing`)
+- `JobHeader.tsx:549` outside-ops PO check; `JobEstimatesVsActuals.tsx:297` `isOutside`
+- BOM/cost API routes and CSV exports pass values through unchanged (plumbing): `api+/items.$itemId.recalculate-cost.ts:130`, `api+/*.bom.tsx`, `api+/*.bom[.]csv.tsx`
+
+**Edge functions (Deno):**
+- `get-method/index.ts` — remove `operationKind` from all 11 copy sites (`:730,1502,2261,2815,4961,5290,5792` verbatim; `:3216,3530,4178,4491` defaulted); `operationType: op.operationType ?? "Inside"` → `?? "Process"`; **normalize configurator returns**: `getConfiguredValue({ field: "operationType" })` (`:648,707,2169,2228`) may execute stored configuration-rule code returning legacy `'Inside'`/`'Outside'` — map them (`Inside → Process`, `Outside → Outside Processing`) before insert.
+- `lib/methods.ts:667,748` — costing engine branches re-keyed
+- `lib/scheduling/work-center-selector.ts:266` — skip `=== "Outside Processing"`
+- `create/index.ts:421-422` — outside-ops filter for PO generation (`purchaseOrderType: "Outside Processing"` at `:586` is a different enum, already correct — untouched)
+- `import-csv/method-import.ts:433-434,671,678,694` — gate on new values; **accept legacy aliases** `Inside → Process`, `Outside → Outside Processing` so existing CSV templates keep importing
+- `import-csv/index.ts:2203-2204` — process import: map legacy `processType` values the same way
+- `trigger-rework/index.ts:229` — copies `operationType`; no change beyond types
+
+**MES:**
+- `utils/operationView.ts` — resolver takes the new `OperationType`; `Assembly → "assembly"`, `Inspection → "inspection"`, default `"operation"` (Process, Outside Processing, null). Delete the local `OperationKind` type.
+- `routes/x+/operation.$operationId.tsx:80` and `assembly.$operationId.tsx:78` — guards read `op.operationType` (now returned by the redefined RPC). Inspection still falls through to the operation view (no loop) until the inspection view ships.
+- `services/operations.service.ts` — no literal changes; RPC return type flows from regenerated types.
+
+**Packages:**
+- `documents/pdf/blocks/jobTraveler/OperationsBlock.tsx:60` `isInside` → `!== "Outside Processing"`; `jobTraveler.samples.ts:50,66,82` fixture values updated
+- `ee/paperless-parts/lib/lib.ts:2114-2115,3125-3126` → `operationType: process.processType` (identity — same enum now); `:2591` → `processType: is_outside_service ? "Outside Processing" : "Process"`
+- `glossary/src/terms.ts` — rewrite `"operation-type"` definition for the 4-value model (currently describes binary inside/outside; the working tree is mid-edit on it); review `"outside-operation"` wording
+- `packages/jobs`, `packages/utils`, academy, MCP routes: verified clean — no changes
+
+## UI Changes
+
+**All three BoP editors converge on one picker** (Items `BillOfProcess.tsx`, `JobBillOfProcess.tsx`, `QuoteBillOfProcess.tsx`): a single `SelectControlled name="operationType"` with the 4 options, `termId="operation-type"`, and `OperationTypeIcon` per option — replacing the Items editor's classification picker + 2 hidden inputs (`:1156-1196`), the Job editor's two separate selects (`:2987-3024`), and the Quote editor's binary select (`:1982-2001`).
+- Defaults: `"Inside"` → `"Process"` (items `:211,1035`; job `:375,2836`; quote `:240,1836`); delete all `operationKind` defaults/state fields (`:212,1015,1036`; `:376,2816,2837`; `:241`)
+- Process seeding: `onProcessChange` becomes `operationType: process.data?.processType ?? "Process"` (items `:1066`, job `:2906`, quote `:1905`) — the auto-suggest the PRD wanted, for free
+- Unit-reset on change: reset setup/labor/machine units only when crossing the Outside Processing boundary (`(next === 'Outside Processing') !== (prev === 'Outside Processing')`), not on Process↔Assembly↔Inspection changes
+- Conditional sections: `=== "Outside"` supplier fields → `=== "Outside Processing"` (items `:1298`-region, job `:3040`-region, quote `:2010`-region); `=== "Inside"` time fields → `!== "Outside Processing"` (items `:1346`, job `:3122`, quote `:2097`); tab-disabled logic (`Outside` ops have no steps/tools tabs): items `:578,618,664,719`; job `:867,904,929,964,989,1016`; quote `:586,650,693,735`
+- Assembly steps sync gate: `item.data.operationKind === "Assembly"` → `operationType === "Assembly"` (items `:689`, job `:940`). Quote BoP intentionally still has no `AssemblyStepsSource` (non-goal)
+- Cards/badges: `<Badge>Outside</Badge>` → renders the enum value ("Outside Processing") (items `:3824-3837`, job `:251-264`, quote `:183-196`, `SalesOrderLineJobs.tsx:434,470`)
+
+**Icons** (`components/Icons.tsx`, currently uncommitted WIP): `OperationTypeIcon` re-typed to the new `OperationType`; `case "Standard"` → `case "Process"`; wire it into the new unified selects (it's currently defined but unused).
+
+**Assembly sync UI:** `AssemblySyncModal.tsx:24,96-97` — `TargetOperation.operationKind` → `operationType`; badge shows when `operationType !== "Process"`; `routes/x+/assembly+/$id.sync-bop.tsx:49,68` select `operationType` instead of `operationKind`.
+
+**Tables:** `MethodOperationsTable.tsx:63-71`, `JobOperationsTable.tsx:153-159` — filter options come from the new const automatically; `Enumerable` cells render new values.
+
+**Process/resources UI (same-enum convergence):** `ProcessForm.tsx:137,152` — work-center and supplier sections both **always visible** (the enum is a default-type hint, not a capability gate; former "both" processes keep their work-center config on screen); `ProcessesTable.tsx:67,91`; `Form/Process.tsx:75`, `Form/Processes.tsx:48` defaults → `"Process"`; routes `processes.$processId.tsx:97`, `processes.new.tsx:78`; `imports.models.ts:1484-1494` (process import options) and `:254-266` (BoP import field: options → 4 values, default `Process`).
+
+**Docs:** update docs-site pages describing inside/outside operations (carbon-docs sweep at implementation), and amend the MES execution-views PRD (glossary entry, ADR §5.1, Phase-4 roadmap item → done, changelog).
+
+## Acceptance Criteria
+
+- [ ] Migration on a DB with legacy rows maps: `(Inside, Operation) → Process`; `(Inside, Assembly) → Assembly`; `(Inside, Inspection) → Inspection`; `(Outside, anything) → Outside Processing`; `process` rows `Inside → Process`, `Outside → Outside Processing`, `Inside and Outside → Outside Processing`. Validated in a rolled-back psql transaction seeded with all combinations before applying anywhere.
+- [ ] After migration: `operationKind` columns and the `operationKind`/`processType`/old `operationType` enum types no longer exist; all four converted columns are `NOT NULL DEFAULT 'Process'`; re-running the migration file end-to-end is a no-op (idempotency proof).
+- [ ] All three BoP editors show one "Operation Type" select with exactly the 4 options + icons; choosing Outside Processing shows supplier-process fields and hides in-house time fields; the other three show time fields; submitted form data contains a single `operationType` field (no `operationKind`).
+- [ ] Selecting a process whose `processType` is `Assembly` seeds the operation's type to Assembly (same for all values).
+- [ ] Items + Job BoP show the assembly steps sync source exactly when `operationType === 'Assembly'`.
+- [ ] MES: an Assembly operation opened at `/x/operation/:id` redirects to `/x/assembly/:id` and renders `AssemblyView`; a Process operation at `/x/assembly/:id` redirects back; an Inspection operation renders the standard operation view with no redirect loop.
+- [ ] Costing parity: a quote line whose operations were `Inside` costs identically after conversion (labor/machine/overhead path for Process/Assembly/Inspection); an `Outside` operation costs identically as Outside Processing (min-clamped unit cost). Verified against a pre-migration costing snapshot.
+- [ ] Job release still generates outside-processing POs for `Outside Processing` operations (`create` edge function), and JobHeader's outside-PO check finds them.
+- [ ] Scheduling work-center assignment skips `Outside Processing` operations.
+- [ ] CSV method import accepts the 4 new values AND legacy `Inside`/`Outside` (aliased); job traveler PDF renders in-house ops with the in-house layout and Outside Processing ops with the outside layout.
+- [ ] get-method copies `operationType` verbatim method→job and method→quote for all 4 values; a configuration rule returning legacy `'Outside'` produces an `Outside Processing` operation.
+- [ ] `pnpm run generate:types` produces a clean diff (4-value enum; no operationKind/processType enums); scoped typechecks pass for `erp`, `mes`, `@carbon/database`, `@carbon/documents`, `@carbon/ee`; `pnpm run lint` passes.
+- [ ] Browser e2e (per house rule): create/edit operations of each type in the Items BoP, verify MES assembly routing, verify an outside-processing quote line's costs render.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Missed literal `'Inside'`/`'Outside'` site (loosely-typed: `bom.ts`, Deno edge functions, RPC JSON consumers) | High | Generated enum change turns typed comparisons into TS errors (impossible-comparison); finish with a repo-wide grep for `"Inside"`/`"Outside"` excluding the verified adjacent concepts (below). |
+| Adjacent same-string concepts accidentally "fixed" | Med | Explicit exclusion list: `purchaseOrderType`/`supplierQuoteType` `= 'Outside Processing'` (already correct), `outsideCost` bucket label "Outside", `jobOperationStep.type = 'Inspection'` (step type), `itemTrackingType` "Batch". `processType` is now IN scope. |
+| `get_method_tree` ordering bug (pre-existing): main's `20260714084035` redefines it NEWER than the squashed branch migration's step-link redefs — timestamp-ordered prod deploy would silently revert the branch's `methodOperationStepIds` feature | High | This migration re-lands `get_method_tree` forked from the newest definition merged with the branch's additions; extract verbatim + diff-verify (lessons: fork newest, sed-extract). |
+| Squashed branch migration sub-section 8 (six `*MaterialStep`/`*ToolStep` join tables) has unguarded `CREATE TABLE`/`CREATE POLICY` — a deploy-retry over partial state would wedge | Med | Harden that section with `IF NOT EXISTS`/`DROP POLICY IF EXISTS` guards in the same PR (editing an unshipped branch file is safe; already-applied local DBs skip it by filename). |
+| Enum swap rewrites 4 tables under ACCESS EXCLUSIVE locks | Low | Operation tables are moderate-sized; single-transaction migration during normal deploy window. |
+| Configuration rules (`configurationRule` code) returning legacy values post-migration | Med | Normalize at the get-method boundary (only consumer); acceptance criterion covers it. |
+| Branch `types.ts` was hand-edited (PRD §6 caveat); regen against a polluted dev DB | Med | Regenerate against a clean local DB after applying the migration; review the diff before commit. |
+| API consumers filtering `rowFilter.*.operationType=Inside/Outside` break at deploy | Low | Accepted (Brad's directive). Swagger schema regenerates; note in release notes. No MCP/AI tool schemas reference the values (verified). |
+| Paperless Parts import writes legacy values after deploy | Med | Mappings updated in the same PR (`packages/ee`); enum rejects stragglers loudly rather than corrupting. |
+| Branch migrations remain backdated vs main (applied out of order on remotes) | Med | Contained: only `get_method_tree` collides (re-landed here); everything else in the squashed file creates new objects. Re-timestamping rejected — it would force a full re-run on local DBs through the non-idempotent section. |
+
+## Open Questions
+
+> All resolved before this spec was written (2026-07-20). Autonomous resolutions were surfaced in-session before writing; veto any and the spec gets amended.
+
+- [x] What do the new `processType` values become, and where does `'Inside and Outside'` land? — **Answer (Brad):** mirror the new enum exactly and use the *same* Postgres enum type so it stays in sync, with a single const in `shared.models.ts`. `Inside → Process`, `Outside → Outside Processing`, and — per Brad's follow-up correction — `'Inside and Outside' → Outside Processing`. Consequence (autonomous): ProcessForm's work-center and supplier sections are both always visible so former "both" processes keep their work-center config reachable; capability lives in `workCenterProcess`/`supplierProcess` rows, not the enum.
+- [x] Value naming: PRD had agreed "Standard"; directive says "Process" — **Answer (Brad, this request):** `Process`. Research note: no direct industry precedent for the label ("In-House"/"Standard" elsewhere) but conflict-free; adjacent "Process" entity (work center process) disambiguated by the select label "Operation Type" + glossary term.
+- [x] Enum conversion mechanism: literal temporary column (as suggested) vs type-rename + `USING` cast? — **Autonomous (surfaced, no objection):** type-rename + `USING` cast; identical outcome and lock profile, one atomic guarded step per table, no column-order churn. Temp-column variant documented as fallback.
+- [x] Contradictory rows (`Outside` + `Assembly`/`Inspection`)? — **Autonomous:** Outside wins → `Outside Processing`, matching `classificationFromTypeKind` precedence. Such rows can't be produced by the current UI.
+- [x] Migration packaging: edit the squashed branch migration to never add `operationKind`, vs one new forward migration? — **Answer (Brad, implementation kickoff):** the branch SQL is unmerged — edit it inline so `operationKind` never exists, run `crbn reset` locally, regenerate types from the clean DB. The forward consolidation migration remains only for the enum swap of columns that exist on deployed DBs (`operationType` since 2024, `processType`). Section-8 idempotency hardening happens in the same inline edit.
+- [x] CSV templates and API callers sending legacy values? — **Autonomous:** import boundary accepts `Inside`/`Outside` as aliases; REST/PostgREST filters are hard-switched (regenerated schema).
+- [x] MES Inspection routing before the inspection view exists? — **Autonomous (PRD precedent):** unchanged — falls through to the operation view, no redirect, no loop.
+- [x] Work-queue navigating directly by type (skip the redirect hop)? — **Autonomous:** deferred non-goal; guards are required regardless for stale links. Noted as follow-up now that the RPC returns `operationType`.
+- [x] Should the Quote BoP gain assembly steps authoring now that quote ops can be `Assembly`? — **Autonomous:** no; out of scope (parity with today). Known gap recorded in the PRD.
+
+## Non-Goals
+
+- `purchaseOrderType` / `supplierQuoteType` enums (already use "Outside Processing"), the `outsideCost` cost bucket and its "Outside" label, `jobOperationStep.type` (step types include an unrelated "Inspection"), and item tracking types.
+- The MES inspection view (Phase 3 of the PRD) — this refactor only preserves its routing slot.
+- Quote BoP steps/assembly authoring; work-queue direct-by-type navigation (both recorded as follow-ups).
+
+## Changelog
+
+- 2026-07-20: Created after full-codebase inventory (DB, ERP, MES/packages) + competitor research. All open questions resolved pre-writing: processType/same-enum/single-const decisions by Brad in-session; remaining resolutions autonomous per spec-writing skill (surfaced for veto). Scope addition by Brad: `processType` folded into the same enum.
+- 2026-07-20: Amended per Brad: `'Inside and Outside' → Outside Processing` (was Process). Knock-on folded in: ProcessForm sections fully ungated so converted "both" processes keep work-center config visible.
+- 2026-07-20: Packaging amended per Brad at implementation kickoff: squashed branch migration edited inline (`operationKind` never exists), local DBs rebuilt via `crbn reset`, types regenerated clean. Consolidation migration simplifies accordingly (no operationKind folding).
+- 2026-07-21: Implemented and verified. Migrations validated in rolled-back psql txns (all CASE branches + idempotent re-runs; the re-run test caught and fixed a would-be prod-deploy failure: the squashed file's `LANGUAGE sql` get_method_tree defs referenced effectivity columns main had already dropped — all transient defs removed, final def lives only in the consolidation migration). Post-reset: clean type regen; typechecks green (erp, mes, database, documents, ee); lint green; zero `operationKind` repo-wide. Browser-verified end-to-end: process form (4 values, ungated sections), BoP unified picker + process-type seeding (Assembly process → Assembly op), Outside Processing branch (supplier/costing fields, time fields hidden), saved method op → job via get-method (type copied verbatim) → MES `/x/operation` → `/x/assembly` redirect with AssemblyView rendering, and the reverse guard (Process op at `/x/assembly` → back). Drive-by fix: `useSupplierProcesses` no longer fires its fetcher with an empty processId (pre-existing route-error-boundary 404 when picking Outside Processing before a process). Docs: `reference/jobs.mdx` operation-type section rewritten; glossary terms updated.
diff --git a/.ai/specs/implemented/2026-07-21-inbound-inspection-execution.md b/.ai/specs/implemented/2026-07-21-inbound-inspection-execution.md
new file mode 100644
index 0000000000..368839827f
--- /dev/null
+++ b/.ai/specs/implemented/2026-07-21-inbound-inspection-execution.md
@@ -0,0 +1,387 @@
+# Inbound Inspection Execution — Drawing + Features Grid
+
+> Status: implemented (branch feat/mes-assembly, migration 20260722040401)
+> Author: Brad Barbin (designed with Claude)
+> Date: 2026-07-21
+
+Research: [.ai/research/inbound-inspection-execution.md](../research/inbound-inspection-execution.md)
+
+## TLDR
+
+Merge Carbon's two disconnected quality systems into one inbound inspection
+execution screen: the `inboundInspection` lot (AQL sampling, pass/fail samples,
+Accept/Reject/Partial, reject→NCR) gains the item's `inspectionDocument`
+(ballooned PDF + `inspectionFeature` nominal/tolerance features) as its
+inspection plan. The lot opens in a new full-screen split view — PDF drawing
+with balloon overlay beside an editable features × samples measurement grid
+(inventory-count editing pattern) — with per-feature AQL sampling,
+auto-valuation of readings against tolerance, derived sample status, and the
+existing human-only disposition + NCR flow. The view is built as a reusable
+component so the same UI can be attached to job operations in MES next
+(AssemblyView pattern; that attachment is out of scope here).
+
+> **Update 2026-07-26 (2):** the sampling hierarchy changed after this spec —
+> the per-item `itemSamplingPlan` tier was **removed** (it "just adds
+> confusion"). Sampling now lives entirely in the inspection plan: a feature's
+> own rule → the document's default rule (six `sampling*` columns on
+> `inspectionDocument`, edited in the document editor) → All. Migration
+> `20260726231401_document-sampling-default.sql` backfilled item plans onto
+> their documents and dropped the table.
+
+> **Update 2026-07-26:** the MES attachment shipped. Job operations with
+> `operationType = 'Inspection'` execute at `/x/inspection/{jobOperationId}` in
+> apps/mes against the same (now source-generic) inspection tables; the engine
+> moved to `@carbon/database/quality` so both apps share it. See
+> `.claude/rules/inspection-system.md` → "Job Operation → inspection flow".
+
+## Problem Statement
+
+Today an inspector receiving parts gets a lot drawer with anonymous Pass/Fail
+buttons — no connection to *what* to inspect. The ballooned drawing with its
+measurable features (`inspectionDocument`/`inspectionFeature`/`balloon`,
+built for FAI) is never surfaced at receiving, so inspectors work from paper
+prints or tribal knowledge, and a "Fail" records no evidence of which dimension
+failed or by how much. Sampling is one lot-level sample size applied blindly,
+while every reference system (SAP QM, 1factory, High QA) resolves sampling per
+feature — a critical bore and a cosmetic chamfer should not share a
+sample size. NCRs created from rejects carry no measurement data for MRB.
+
+Concrete example: a lot of 200 machined housings arrives. The plan says sample
+32. The inspector taps Fail on sample 7 with a note "OD oversize". The NCR
+says "Rejected lot II000042" — no feature, no reading, no tolerance. MRB
+re-measures everything from scratch.
+
+## Proposed Solution
+
+One execution screen at `/x/inbound-inspection/{id}` (full-screen route tree,
+`handle.module: "quality"`), replacing the `InboundInspectionLotView` drawer:
+
+- **Left pane**: the assigned inspection document's PDF rendered with
+ `react-pdf` + read-only balloon overlay (reusing the viewer pieces of
+ `InspectionDocumentEditor`). Clicking a balloon focuses the matching grid
+ row; focusing a grid row highlights its balloon (DISCUS/High QA pattern).
+- **Right pane**: an editable grid — one row per `inspectionFeature` (balloon
+ number, description, nominal, +tol/−tol, unit, per-feature n/Ac/Re, pass
+ count), one column per sample. Cells are `EditableNumber`-style inputs with
+ the inventory-count keyboard navigation (Enter/Tab advance). Out-of-tolerance
+ values color the cell red at entry (Net-Inspect pattern). The grid is ragged:
+ cells beyond a feature's own resolved sample size are disabled.
+- **Sampling** resolves **per feature**: feature-level rule → item's
+ `itemSamplingPlan` → company default ("All"). Resolved n/Ac/Re per feature
+ are stored on the lot at receipt.
+- **Valuation** is automatic and strict: an out-of-tolerance reading fails the
+ measurement; a sample's status is fully **derived** (any failed required
+ measurement ⇒ Failed; all required cells filled and passing ⇒ Passed); no
+ sample-level override. Lot disposition (Accept/Reject/Partial) remains a
+ human decision; deviations are resolved through MRB/NCR, not overrides.
+- **Serial** lots create sample columns by scanning (existing
+ `ScanInspectionSample` flow); non-serial lots pre-create anonymous columns.
+ Entity status side effects (Available/Rejected) now follow the derived
+ sample status and re-derive on cell edits while the lot is non-terminal.
+- **NCR** creation on reject is unchanged in mechanism but enriched: the issue
+ carries the failed features with measured vs. nominal/tolerance values.
+- **Fallback**: items with no assigned inspection document keep today's flow —
+ manual Pass/Fail per sample, no grid, no drawing.
+
+Document assignment lives on the item's Quality tab as two new cards:
+an **Inspection Documents** card (list + "New" action) and an **Assignments**
+card with usage-slot dropdowns — v1 ships only the **Receipt** slot; the model
+extends to FAI/Production slots later without schema change.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Sampling granularity | Per feature (feature rule → item plan → "All" default) | Industry end-state (SAP/1factory/High QA); user decision Q1. Flat default with per-child override, no matrix config |
+| Plan reference | Live: lot stores `inspectionDocumentId` only; no feature snapshot | User decision Q2b. Measurement rows store value + valuation at entry, so later tolerance edits don't silently rewrite recorded results |
+| Document selection | `itemInspectionDocumentAssignment` junction (itemId × usage), Receipt slot only in v1, edited on item Quality tab | User decision Q2a. Extensible to FAI/Production via new enum values, mirroring SAP task-list usage without a per-receipt choice |
+| Valuation roll-up | Strict: cell auto-valuated vs tolerance, sample status fully derived, no override; disposition human-only | User decision Q3 (SAP: auto-valuate readings, never auto-reject the lot; overrides happen at MRB) |
+| Serial sample identity | Scan-first: scanning creates the sample column; non-serial pre-creates anonymous columns to max n | User decision Q4. Preserves sampled-once partial unique index and entity side effects |
+| Screen form factor | Dedicated full-screen tree `x+/inbound-inspection+/`, drawer retired | User decision Q5. Matches `x+/inspection+`/`x+/assembly+` editor pattern from `.ai/lessons.md` |
+| Execution view reuse | `InboundInspectionView` built as a data-prop component (AssemblyView pattern) | Next step on this branch surfaces the same UI in MES against job operations; that attachment is out of this spec's scope |
+| Grid editing pattern | Inventory-count pattern: shared `Table` + `~/components/Editable` cells, `onCellEdit` posting per cell, spreadsheet keyboard nav | Explicit product direction; proven pattern in `InventoryCountLines.tsx` |
+| Feature cell types | Numeric features (nominal/tolerance) → number cell; non-numeric feature types → Pass/Fail toggle cell | 1factory Variable vs Attribute features |
+| Multi-tenancy (heuristic 1) | New tables carry `companyId` + RLS; PKs follow the inbound-inspection family (surrogate `id` PK, not composite) | Sibling tables `inboundInspection`/`inboundInspectionSample` use `id` PKs (Phase-2 rebuild, newest pattern for this subsystem); `itemInspectionDocumentAssignment` keys on `(itemId, usage, companyId)` like `itemSamplingPlan` keys on `itemId` |
+| Service shape (heuristic 2) | New reads in `quality.service.ts` (client first, `{data,error}`); write orchestration in `quality.server.ts` | Matches `upsertInboundInspectionSample`/`dispositionInboundInspection` |
+| RLS (heuristic 3) | SELECT/INSERT/UPDATE/DELETE policies gated by `quality_view/create/update/delete` on all new tables | Same as existing inbound-inspection tables |
+| Permissions (heuristic 4) | View = `quality_view`; record/disposition/assign = `quality_update` via `requirePermissions` | Same scopes the current routes use |
+| Forms (heuristic 5) | Assignment card uses `ValidatedForm` + zod validator + route action; grid cells post per-cell like inventory count (not a form) | Grid precedent is `onCellEdit` fetch, forms precedent is everywhere else |
+| Module layout (heuristic 6) | New validators in `quality.models.ts`, services in `quality.service.ts`/`quality.server.ts`, UI in `quality/ui/InboundInspections/`; inspection-document services stay in production module and are imported | No new module; inspection documents already live in production and are surfaced under quality nav |
+| Backward compatibility (heuristic 7) | No frozen surface touched. Old drawer routes replaced; in-flight lots (no `inspectionDocumentId`) run the fallback flow untouched | Inbound inspection is a recent internal surface; API docs regenerate from schema |
+| Four-eyes | `enforceInspectionFourEyes` warning behavior preserved on the new screen | Preserve behavior |
+| Sampling engine | Extend both copies (`sampling-engine.ts` edge + `samplingStandards.ts` app) with per-feature resolution; keep manual sync discipline | Existing dual-copy reality; consolidating is out of scope |
+
+## Data Model Changes
+
+New enum + one column, three new tables, feature sampling columns:
+
+```sql
+-- Usage slots for item-level inspection document assignment (extensible: 'FAI', 'Production' later)
+CREATE TYPE "inspectionDocumentUsage" AS ENUM ('Receipt');
+
+-- Which document drives which usage for an item (flat assignment, per-child override pattern)
+CREATE TABLE "itemInspectionDocumentAssignment" (
+ "itemId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "usage" "inspectionDocumentUsage" NOT NULL,
+ "inspectionDocumentId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "itemInspectionDocumentAssignment_pkey" PRIMARY KEY ("itemId", "usage", "companyId"),
+ CONSTRAINT "itemInspectionDocumentAssignment_itemId_fkey" FOREIGN KEY ("itemId", "companyId") REFERENCES "item"("id", "companyId") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_document_fkey" FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+-- Per-feature sampling rule (nullable = inherit itemSamplingPlan; mirrors itemSamplingPlan fields)
+ALTER TABLE "inspectionFeature"
+ ADD COLUMN "samplingPlanType" "samplingPlanType",
+ ADD COLUMN "samplingSampleSize" INTEGER,
+ ADD COLUMN "samplingPercentage" NUMERIC,
+ ADD COLUMN "samplingAql" NUMERIC,
+ ADD COLUMN "samplingInspectionLevel" "inspectionLevel",
+ ADD COLUMN "samplingSeverity" "samplingSeverity";
+
+-- The document assigned to a lot at receipt (live reference)
+ALTER TABLE "inboundInspection"
+ ADD COLUMN "inspectionDocumentId" TEXT REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+
+-- Per-lot, per-feature resolved sampling plan (computed at receipt; lazily reconciled
+-- for features added to the live document while the lot is open)
+CREATE TABLE "inboundInspectionFeature" (
+ "id" TEXT NOT NULL DEFAULT id('iif'),
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "inboundInspectionId" TEXT NOT NULL REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ "inspectionFeatureId" TEXT NOT NULL REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ "sampleSize" INTEGER NOT NULL,
+ "acceptanceNumber" INTEGER NOT NULL,
+ "rejectionNumber" INTEGER NOT NULL,
+ "codeLetter" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "inboundInspectionFeature_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionFeature_unique" UNIQUE ("inboundInspectionId", "inspectionFeatureId")
+);
+
+-- One recorded reading per sample × feature; value AND valuation stored at entry
+-- so later tolerance edits never rewrite recorded results
+CREATE TABLE "inboundInspectionMeasurement" (
+ "id" TEXT NOT NULL DEFAULT id('iim'),
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "inboundInspectionId" TEXT NOT NULL REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ "inboundInspectionSampleId" TEXT NOT NULL REFERENCES "inboundInspectionSample"("id") ON DELETE CASCADE,
+ "inspectionFeatureId" TEXT NOT NULL REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ "value" NUMERIC, -- numeric features; NULL for attribute features
+ "status" "inboundInspectionSampleStatus" NOT NULL DEFAULT 'Pending', -- valuation at entry
+ "notes" TEXT,
+ "inspectedBy" TEXT REFERENCES "user"("id"),
+ "inspectedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "inboundInspectionMeasurement_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionMeasurement_unique" UNIQUE ("inboundInspectionSampleId", "inspectionFeatureId")
+);
+
+-- RLS on all three: standard SELECT/INSERT/UPDATE/DELETE policies gated by
+-- quality_view/create/update/delete + companyId, matching inboundInspectionSample.
+```
+
+Notes:
+- `inboundInspection`'s existing lot-level snapshot columns (`sampleSize`,
+ `acceptanceNumber`, …) remain and keep powering the fallback (no-document)
+ flow; when a document is assigned they are set to the max/derived values
+ across features for list-view display.
+- No change to `inboundInspectionSample`; its `status` becomes derived (server
+ logic, not schema) when a document is assigned.
+- Migration is idempotent (guards on every DDL), forward-dated, randomized
+ HHMMSS. Run `pnpm run generate:types` after.
+
+## API / Service Changes
+
+**`post-receipt` edge function** (`packages/database/supabase/functions/post-receipt/index.ts`):
+- After resolving the lot plan: look up `itemInspectionDocumentAssignment`
+ (usage `Receipt`) for the item; if found, set `inspectionDocumentId` on the
+ `inboundInspection` insert, load the document's features, resolve each
+ feature's plan (feature rule → item plan → All) via the extended
+ `resolveSamplingPlan`, and insert `inboundInspectionFeature` rows.
+
+**Sampling engine** (`shared/sampling-engine.ts` + app copy `samplingStandards.ts`):
+- New `resolveFeatureSamplingPlan(feature, itemPlan, lotSize, standard)`
+ helper wrapping the existing `resolveSamplingPlan` with the inheritance
+ chain. Both copies updated together.
+
+**`quality.service.ts`** (client-first, `{data,error}`):
+- `getInboundInspectionFeatures(client, inboundInspectionId, companyId)` —
+ resolved per-feature plans joined to live `inspectionFeature` + `balloon`.
+- `getInboundInspectionMeasurements(client, inboundInspectionId, companyId)`.
+- `getItemInspectionDocumentAssignments(client, itemId, companyId)` /
+ `upsertItemInspectionDocumentAssignment(...)`.
+
+**`quality.server.ts`**:
+- `upsertInboundInspectionMeasurement` — validates + valuates the reading
+ against the feature's live nominal/tolerance at entry (numeric: in/out of
+ tolerance; attribute: explicit pass/fail), writes the measurement, then
+ **derives the sample status** (any Failed required measurement ⇒ Failed; all
+ required filled + passing ⇒ Passed; else Pending) and applies the existing
+ entity side effects (flip `trackedEntity` status, `trackedActivity`) through
+ the same code path as `upsertInboundInspectionSample`. Re-derivation on edit
+ is allowed only while the lot is non-terminal.
+- `reconcileInboundInspectionFeatures` — on lot load, upserts
+ `inboundInspectionFeature` rows for features added to the live document
+ since receipt (and leaves removed-feature rows in place, ignored by the grid).
+- `dispositionInboundInspection` — gating updated for per-feature sampling:
+ `canAccept` ⇔ every feature has ≥ its `sampleSize` recorded measurements and
+ fails ≤ its `acceptanceNumber`; `canReject` ⇔ any feature's fails ≥ its
+ `rejectionNumber` (or any failed sample, matching today's semantics for the
+ fallback flow); `canPartial` unchanged. Fallback flow keeps lot-level gating.
+- Reject route NCR enrichment: issue description/content includes a failed-
+ feature table (balloon label, nominal ± tolerance, measured values, sample
+ ids); associations unchanged (`nonConformanceInboundInspection`,
+ `nonConformanceReceiptLine`, tracked entities).
+
+**`quality.models.ts`**: `inboundInspectionMeasurementValidator`,
+`itemInspectionDocumentAssignmentValidator`, `inspectionDocumentUsage` const;
+`inspectionFeature` sampling fields added to the feature validator (production
+module's `saveInspectionDocumentAtomic` RPC extended to persist them —
+new migration forking the newest RPC definition).
+
+**Routes** — new tree `apps/erp/app/routes/x+/inbound-inspection+/`:
+- `_layout.tsx` (`handle.module: "quality"`), `$id.tsx` (loader: lot +
+ features + measurements + samples + document URL; renders
+ `InboundInspectionView`), `$id.sample.tsx` (add/scan sample),
+ `$id.measurement.tsx` (per-cell upsert action), `$id.accept.tsx`,
+ `$id.reject.tsx`, `$id.partial.tsx` (moved from `x+/quality+/`), plus
+ `$id.document.tsx` (swap assigned document while non-terminal).
+- `x+/quality+/inbound-inspections.tsx` row click navigates to
+ `/x/inbound-inspection/{id}`; old `$id.*` drawer routes removed.
+- Item Quality tab route (`x+/{part,material,tool,consumable}+/$itemId.quality.tsx`):
+ loads documents + assignments; new action for assignment upsert.
+- `path.ts`: `path.to.inboundInspection(id)` + measurement/sample/document
+ action paths.
+
+## UI Changes
+
+- **`InboundInspectionView`** (new, `quality/ui/InboundInspections/`) — the
+ reusable split-view component (data props, no loaders inside): resizable
+ panels; left = PDF pane, right = grid + header (progress, plan summary,
+ disposition buttons, four-eyes warning). Replaces
+ `InboundInspectionLotView` (deleted). MES will consume this component later.
+- **`InspectionDrawingPane`** — `react-pdf` viewer + read-only balloon
+ overlay extracted/adapted from `InspectionDocumentEditor`; balloon click →
+ scroll/focus grid row; active row → highlighted balloon; page switcher.
+- **`InspectionMeasurementGrid`** — features × samples grid on the shared
+ `Table` + `~/components/Editable` cells (inventory-count pattern:
+ `onCellEdit` per-cell POST returning `{data,error}` for optimistic revert,
+ Enter/Tab keyboard nav). Row header: balloon number, description, nominal,
+ ±tol, unit, n/Ac/Re, pass-count chip. Cell states: empty, passed (default),
+ failed (red), disabled (beyond feature's n). Attribute features render a
+ Pass/Fail toggle cell. Column header: sample number or scanned entity
+ `readableId`; "Add sample" column button (serial → `ScanInspectionSample`
+ scan/select modal, unchanged; non-serial columns are pre-created).
+- **Fallback view**: no assigned document → today's samples table + manual
+ Pass/Fail (`ScanInspectionSample` with Pass/Fail buttons) inside the new
+ full-screen route, so the drawer can still be retired.
+- **Item Quality tab** — two new cards above/beside `SamplingPlanForm`:
+ - *Inspection Documents*: list of the item's documents (name, drawing
+ number, version, feature count), card action "New Inspection Document" →
+ creates + navigates to the editor; row click opens the editor.
+ - *Assignments*: one dropdown per usage slot; v1 shows only **Receipt**
+ (options = the item's documents + "None"); designed so FAI/Production
+ slots are additive.
+- **Inspection document editor** (production module): feature properties panel
+ gains the optional sampling-rule fields (type/size/percentage/AQL/level/
+ severity) with "Inherit item plan" as the null state.
+- **`RejectLotModal`**: unchanged mechanics (NCR checkbox default on, issue
+ type picker); preview of the failed-feature summary that will be attached.
+
+## Acceptance Criteria
+
+- [ ] Posting a receipt for an item with `requiresInspection`, an assigned
+ Receipt inspection document, and a lot of 200 creates an
+ `inboundInspection` with `inspectionDocumentId` set and one
+ `inboundInspectionFeature` row per document feature, each with its own
+ resolved n/Ac/Re (feature rule when set, else item plan, else All).
+- [ ] Opening `/x/inbound-inspection/{id}` shows the PDF with balloons beside
+ the grid; clicking balloon 5 focuses feature 5's row; focusing a row
+ highlights its balloon.
+- [ ] Typing an in-tolerance value into a cell saves it (Passed), advances
+ focus on Enter/Tab; an out-of-tolerance value renders red and marks the
+ measurement Failed with no override control at cell or sample level.
+- [ ] A sample whose required cells are all filled and passing shows Passed;
+ entering one out-of-tolerance value flips it to Failed; correcting that
+ value back in-tolerance re-derives it to Passed (lot non-terminal), and
+ for a serial sample the tracked entity's status follows each transition.
+- [ ] For a serial lot, "Add sample" requires scan/select and creates a column
+ headed by the entity `readableId`; scanning the same entity twice is
+ rejected. A non-serial lot shows pre-created columns up to max n.
+- [ ] A feature with n=8 accepts no more than 8 measurements (cells beyond n
+ disabled); Accept is disabled until every feature has ≥ its own n
+ measurements with fails ≤ its Ac; Reject enables when any feature's
+ fails ≥ its Re.
+- [ ] Rejecting with "Open an NCR" creates the issue with the failed-feature
+ table (balloon, nominal ± tol, measured values) in its content, plus the
+ existing associations, and redirects to the issue.
+- [ ] Editing a feature's tolerance in the document editor mid-lot changes the
+ grid's displayed tolerance but does not change any recorded
+ measurement's stored status.
+- [ ] An item with no assigned document still gets a lot at receipt and the
+ full-screen view shows the manual Pass/Fail flow (no grid, no PDF);
+ disposition gating matches today's lot-level rules.
+- [ ] Item Quality tab shows the two cards; creating a document from the card
+ lands in the editor; assigning it to Receipt makes the next receipt pick
+ it up.
+- [ ] `pnpm exec turbo run typecheck --filter=@carbon/erp` passes;
+ `pnpm run generate:types` run after migrations.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Dual sampling-engine copies (edge + app) drift when adding per-feature resolution | Med | Change both in the same commit; shared test vectors in the app copy's tests |
+| Live document reference: feature deleted mid-lot orphans measurements | Med | Grid ignores `inboundInspectionFeature` rows whose live feature is gone; measurements retained for audit; completeness gating recomputed from live features |
+| Derived sample status flipping tracked-entity state on every edit could spam `trackedActivity` | Low | Only write activity on actual status transitions, not on every cell save |
+| Grid performance (e.g. 60 features × 50 samples) with per-cell POSTs | Med | Per-cell save matches inventory-count precedent; virtualize rows if needed; measurements loaded once and patched optimistically |
+| `saveInspectionDocumentAtomic` RPC change (new feature columns) must fork the newest definition | Med | Follow migration-function-redefinition rule: fork latest, `DROP IF EXISTS`, preserve attributes |
+| In-flight lots at deploy have no document/feature rows | Low | `inspectionDocumentId` null ⇒ fallback flow; no backfill needed |
+
+## Open Questions
+
+> All resolved with the user before this spec was written (2026-07-21).
+
+- [x] Sampling granularity: lot-level (today) or per-feature? —
+ **Answer:** per-feature. Feature-level rule inherits from
+ `itemSamplingPlan`, then company default "All"; grid gates completeness
+ per feature. (Q1)
+- [x] Which inspection document drives an inbound lot? — **Answer:** item
+ Quality tab gets an Inspection Documents card (list + create) and an
+ Assignments card of usage-slot dropdowns; v1 ships only the **Receipt**
+ slot, modeled as an extensible junction (`itemId × usage → documentId`)
+ so FAI/Production slots come later without schema change. Job-operation
+ attachment (MES) is the next branch step, out of this spec. (Q2a)
+- [x] Snapshot features at receipt or reference live? — **Answer:** live; the
+ lot stores only `inspectionDocumentId`. Measurements store value +
+ valuation at entry, so tolerance edits never silently rewrite recorded
+ results. (Q2b)
+- [x] Out-of-tolerance semantics and sample status source? — **Answer:**
+ strict. Readings auto-valuate; sample status is fully derived with no
+ override; deviations are handled at lot disposition via MRB/NCR. (Q3)
+- [x] Serial sample identity in the grid? — **Answer:** scan-first; scanning
+ creates the sample column; non-serial lots pre-create anonymous columns.
+ (Q4)
+- [x] Screen form factor? — **Answer:** dedicated full-screen route tree
+ `x+/inbound-inspection+/` (`handle.module: "quality"`); the ModalDrawer
+ is retired. (Q5)
+
+## Changelog
+
+- 2026-07-22: Generalized to source documents (user directive): the lot family
+ is renamed to `inspection`/`inspectionSample`/`inspectionSamplingPlan`/
+ `inspectionMeasurement`/`inspectionHistory` with `sourceDocument` (enum:
+ Receipt, Job Operation) + `sourceDocumentId`/`sourceDocumentLineId`/
+ `sourceDocumentReadableId` replacing `receiptId`/`receiptLineId`; the
+ submodule is renamed **Inspections** (list `/x/quality/inspections`,
+ execution `/x/inspection/{id}`, document editor moved to
+ `/x/inspection-document/{id}`); new-company sequence prefix INS (existing
+ companies keep II). Plan: .ai/plans/2026-07-22-inspections-refactor.md.
+- 2026-07-21: Created after research
+ (`.ai/research/inbound-inspection-execution.md`) and grill interview; all
+ six open questions resolved with Brad before writing.
diff --git a/.ai/specs/implemented/2026-07-21-operation-instruction-sources.md b/.ai/specs/implemented/2026-07-21-operation-instruction-sources.md
new file mode 100644
index 0000000000..5136effb65
--- /dev/null
+++ b/.ai/specs/implemented/2026-07-21-operation-instruction-sources.md
@@ -0,0 +1,301 @@
+# Operation Instruction Sources — per-type source pickers on the Bill of Process
+
+> Status: implemented (branch feat/mes-assembly, migration 20260721022847)
+> Author: Brad Barbin (design) + Claude (spec)
+> Date: 2026-07-21
+> Depends on: [2026-07-20-operation-type-consolidation.md](2026-07-20-operation-type-consolidation.md) (implemented)
+> Extends: [2026-07-14-mes-execution-views.md](2026-07-14-mes-execution-views.md) §5.4 (accepted ADR — inspection plan link)
+> Related: `.ai/plans/2026-07-20-work-instructions-refactor.md` (Workstreams A + B already landed on this branch)
+
+## TLDR
+
+Generalize the procedure pattern to the other operation types. Today a **Process**
+operation can link a procedure: the method/quote editors lock Steps, Parameters,
+and Work Instructions ("inherited from the procedure"), get-method materializes
+the procedure's content onto the **job** operation, and the job editor offers
+re-sync instead of locking. This spec gives **Assembly** operations the same
+pattern with an **Assembly Instruction** picker (resolves to steps at get-method
+time, re-sync on jobs), and **Inspection** operations an **Inspection Document**
+picker (a plan-link pointer per PRD §5.4 — features never materialize as steps).
+Both pickers are scoped to the parent make method's item. Time fields slim down
+by type: Assembly and Inspection show Setup + Labor only (no Machine, no machine
+rate), and the Procedure card shows only for Process operations.
+
+## Problem Statement
+
+- The BoP editors expose one instruction source (Procedure) to every in-house
+ operation type, even though a procedure is the wrong source for an Assembly op
+ (its steps come from a published 3D assembly instruction) and for an
+ Inspection op (its features live on an inspection document).
+- The current assembly wiring is a one-off: `AssemblyStepsSource` (internal-flag
+ gated) manually syncs instruction steps into `methodOperationStep` rows at
+ authoring time — duplicating content on the template instead of inheriting it
+ at get-method time like procedures do, and auto-resolving "the item's one
+ instruction" instead of letting the author pick.
+- Inspection operations have no way to declare *which* inspection document they
+ execute. PRD §5.4 already accepted the design (explicit nullable FK,
+ propagated by get-method, picker defaults by item) but it was deferred out of
+ the classification migration.
+- Assembly and Inspection operations show and *require* Machine time/unit (and
+ machine rate on job/quote), which is noise — both are setup + labor work.
+
+## Proposed Solution
+
+One rule set, keyed on `operationType`:
+
+| operationType | Source card | Stored FK | Method/Quote editors | Job editor | get-method → job | Time fields |
+|---|---|---|---|---|---|---|
+| Process | Procedure (existing) | `procedureId` | Lock Instructions + Parameters + Steps when set (existing) | No lock; "Sync Procedure" (existing) | Materialize procedure steps/params/content (existing) | Setup + Labor + Machine (+ rates) |
+| Assembly | **Assembly Instruction (new picker)** | `assemblyInstructionId` | **Lock Steps when set** | No lock; **"Sync Assembly Steps"** (existing sync-bop action, per-operation) | **Materialize instruction steps (+ model slide + material↔step links) when set; else copy method steps** | **Setup + Labor only** |
+| Inspection | **Inspection Document (new picker)** | `inspectionDocumentId` (new column) | No lock (pointer only — no step content to inherit) | No lock | **Copy the pointer only** — features never become steps (PRD §5.4) | **Setup + Labor only** |
+| Outside Processing | none | — | Tabs already disabled | Tabs already disabled | — | none (supplier costing, existing) |
+
+- Every source card renders **conditionally on its type** and the Procedure card
+ disappears for Assembly / Inspection / Outside Processing.
+- Both new pickers are **scoped to the parent item**: `assemblyInstruction.itemId
+ = <make method itemId>` and `inspectionDocument.partId = <make method itemId>`
+ (both editors already have the make-method itemId in scope — it's what
+ `AssemblyStepsSource` receives today).
+- Switching `operationType` **clears the now-inapplicable pointers** in form
+ state, and the operation upsert normalizes server-side (a pointer that doesn't
+ match the type is written as `null`) so stale links can't survive a type change.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Assembly inheritance model | Method/quote carry the FK + lock Steps; **jobs materialize at get-method time** (mirror of `insertProcedureDataForJobOperation`) | Brad's directive ("inherit from the procedure at get-method time… similar approach for Assembly"). Kills the author-time duplication of instruction steps into `methodOperationStep`. |
+| Assembly lock scope | **Steps only** (not Instructions/Parameters) | An assembly instruction provides steps (+ slides/parts); it has no parameters and no work-instruction doc. Locking only what is inherited keeps params/instructions authorable on Assembly ops. Procedure locks all three because a procedure has all three. |
+| Inspection inheritance model | **Pointer only** — no materialization, no locking | PRD §5.4 (accepted): features are `inspectionFeature` rows executed by the Phase-3 inspection view against `jobOperationInspectionRecord`; "not `jobOperationStep` rows". The FK is the plan link. |
+| `inspectionDocumentId` columns | Nullable TEXT FK on `methodOperation`, `quoteOperation`, `jobOperation` → `inspectionDocument(id)` ON DELETE SET NULL + indexes | Exactly PRD §5.4's shape ("explicit FK, not resolve-by-item"); SET NULL matches the assemblyInstructionId precedent (a deleted source shouldn't delete operations — note `procedureId`'s CASCADE is the odd one out, left as-is). Single-column FK is legal: `inspectionDocument.id` carries a UNIQUE constraint. |
+| `quoteOperation.assemblyInstructionId` | Add it (same shape as method/job) | Quote ops can be typed Assembly since the consolidation; the pointer must survive item→quote→job. `quoteLineToJob` already copies the column name — it just doesn't exist on the source yet. |
+| Picker options | All statuses/versions for the item, with status badge (assembly) / version + drawing number (inspection) | Parity with the Procedure picker (shows Draft/Active/Archived with badges). The **stored FK is the source of truth**; resolve-by-item is only how the list is scoped (PRD §5.4). |
+| Job-side assembly sync | Reuse the existing `assembly+/$id.sync-bop` action (per-operation, Published-only guard, provenance-marker reconcile) via a "Sync Assembly Steps" affordance in the assembly card | The machinery exists and is provenance-safe; the card replaces the internal-flag `AssemblyStepsSource` widget in both editors. |
+| get-method materialization vs sync guard | get-method materializes **whatever instruction is linked** (any status), like procedures materialize Draft procedures; the manual job-side sync keeps its Published-only guard | The author's explicit link is authoritative; blocking job creation on instruction status would silently produce step-less operations. |
+| Machine fields | Hidden AND not required unless `operationType === "Process"`; Setup/Labor stay `!== "Outside Processing"`; job/quote Costing card keeps laborRate + overheadRate for Assembly/Inspection, hides machineRate | Brad's directive ("only setup and labor"). `=== "Process"` here is correct (a per-type field set, not the subcontract boundary — a future in-house type decides its own fields); the subcontract invariant (`!== 'Outside Processing'`) still governs costing/scheduling/PO logic. |
+| Procedure card visibility | Only when `operationType === "Process"` | Brad's directive. |
+| Internal-flag gating | **Neither card is flag-gated** (Brad, 2026-07-21: "get rid of the isInternal flag on the assembly card") | The BoP assembly card ships for everyone; the assemblies module's own `requireAssembliesInternal` route gate is untouched by this spec. |
+| H1 multi-tenancy | New columns live on existing tenant tables; FKs single-column against UNIQUE ids (matching `assemblyInstructionId` precedent) | No new tables. |
+| H2 service shape | New reads follow `(client, …) → {data,error}`; new API routes mirror `api+/production.assembly-for-item.$itemId.ts` | Existing conventions. |
+| H3 RLS | Unchanged — new columns on tables with existing policies | No policy references pointers. |
+| H4 permissions | Pickers/API routes gate like their editors (parts/production/sales view); sync keeps its target-dependent gate | Existing. |
+| H5 forms | New `AssemblyInstruction` + `InspectionDocument` comboboxes in `~/components/Form` mirroring `Procedure.tsx`; validators gain the two optional fields | Existing pattern. |
+| H6 module layout | Service additions in `production.service.ts`; models in the three `*.models.ts` | One service per module. |
+| H7 backward compatibility | Additive columns; get-method copy-list additions; legacy method-level synced assembly steps become dead weight (skipped at get-method) — harmless, internal-only data | No breaking surface. |
+
+## Data Model Changes
+
+One new migration (`pnpm db:migrate:new operation-instruction-sources`), guarded/idempotent:
+
+```sql
+-- Assembly pointer for quotes (method/job already have it)
+ALTER TABLE "quoteOperation" ADD COLUMN IF NOT EXISTS "assemblyInstructionId" TEXT;
+ALTER TABLE "quoteOperation" ADD CONSTRAINT "quoteOperation_assemblyInstructionId_fkey"
+ FOREIGN KEY ("assemblyInstructionId") REFERENCES "assemblyInstruction"("id") ON DELETE SET NULL;
+CREATE INDEX IF NOT EXISTS "quoteOperation_assemblyInstructionId_idx" ON "quoteOperation"("assemblyInstructionId");
+
+-- Inspection plan link (PRD §5.4) on all three operation tables
+ALTER TABLE "methodOperation" ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+ALTER TABLE "methodOperation" ADD CONSTRAINT "methodOperation_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+CREATE INDEX IF NOT EXISTS "methodOperation_inspectionDocumentId_idx" ON "methodOperation"("inspectionDocumentId");
+-- … same for "quoteOperation" and "jobOperation" (ADD CONSTRAINT guarded via DO $$ … duplicate_object)
+```
+
+No enum changes, no view changes (`jobOperationsWithMakeMethods` etc. project
+`t.*` and pick the new columns up automatically on regen), no RLS changes.
+`pnpm run generate:types` after.
+
+## API / Service Changes
+
+**New reads (production.service.ts):**
+- `getAssemblyInstructionsForItem(client, itemId, companyId)` — thin wrapper over
+ the existing `getAssemblyInstructions` (`production.service.ts:4077`) with
+ `itemId` + ordered `updatedAt DESC`, selecting `id, name, version, status`.
+- `getInspectionDocumentsForItem(client, itemId, companyId)` —
+ `inspectionDocument` filtered `.eq("partId", itemId)`, selecting
+ `id, fileName, drawingNumber, version`.
+
+**New API routes (company-cached like `api+/production.procedures.ts`):**
+- `api+/production.assembly-instructions.$itemId.ts` — list for the picker.
+- `api+/production.inspection-documents.$itemId.ts` — list for the picker.
+- (The existing single-resolver `api+/production.assembly-for-item.$itemId.ts`
+ stays for MES/other callers; the picker uses the list.)
+
+**get-method edge function (`packages/database/supabase/functions/get-method/index.ts`):**
+- New `insertAssemblyDataForJobOperation(...)` mirroring
+ `insertProcedureDataForJobOperation` (`:6167-6242`): reads
+ `assemblyInstructionStep` rows; inserts `jobOperationStep` rows carrying the
+ typed fields **and the `assemblyInstructionStepId` provenance marker** (so the
+ job-side re-sync reconciles instead of duplicating); attaches the
+ instruction's `modelUploadId` as a step slide; resolves
+ `assemblyInstructionStepMaterial.itemId` against the job's just-created
+ `jobMaterial` rows into `jobMaterialStep` links (same resolution the app-side
+ sync performs at `production.service.ts:5801-5947`).
+- Branch order anywhere a job operation is created (`itemToJob :790-939`,
+ `itemToJobMakeMethod :1553+`, `quoteLineToJob`):
+ `if (procedureId) materialize procedure; else if (assemblyInstructionId)
+ materialize assembly; else copy source steps`.
+- Method→method (`itemToItem :336`) and →quote (`itemToQuoteLine :2349`,
+ `itemToQuoteMakeMethod :2876`) step-copy guards widen from `if (!procedureId)`
+ to `if (!procedureId && !assemblyInstructionId)` (templates/quotes carry
+ pointers, never materialized content).
+- **Copy-lists**: add `assemblyInstructionId` + `inspectionDocumentId` to every
+ explicit operation insert list (`itemToJob :722-753`, `itemToJobMakeMethod
+ :1497+`, `itemToQuoteLine :2250-2280`, `itemToQuoteMakeMethod :2808+`,
+ `quoteLineToJob :4964` area) and audit the remaining directions
+ (`jobToItem`, `jobMakeMethodToItem`, `quoteLineToItem`, `quoteMakeMethodToItem`,
+ `makeMethodToMakeMethod`, `quoteLineToQuoteLine`, `quoteToQuote`) — spread-based
+ lists inherit automatically; explicit lists must name both columns
+ (PRD §5.4: "omitting either silently breaks propagation").
+
+**Upsert normalization (app services):** `upsertMethodOperation` /
+`upsertQuoteOperation` / `upsertJobOperation` write the three pointers
+type-consistently: `procedureId` only for Process, `assemblyInstructionId` only
+for Assembly, `inspectionDocumentId` only for Inspection — anything else is
+explicitly `null` (not merely omitted, since `sanitize()` would preserve stale
+values).
+
+**Validators:** add `assemblyInstructionId: zfd.text(z.string().optional())` and
+`inspectionDocumentId: zfd.text(z.string().optional())` to
+`methodOperationValidator` (items.models.ts:489 area), `baseJobOperationValidator`
+(production.models.ts:296 area), `quoteOperationValidator` (sales.models.ts:439
+area). Re-gate the machine refines: `machineUnit`/`machineTime` (all three) and
+`machineRate` (job :441-451, quote :578-589) require only when
+`operationType === "Process"`; setup/labor refines stay `!== "Outside Processing"`.
+(While editing: fix the pre-existing copy/paste where the machineUnit refine
+guards read `data.laborUnit` — items :540-551, production :393-403.)
+
+## UI Changes
+
+**All three BoP editors** (items `BillOfProcess.tsx`, `JobBillOfProcess.tsx`,
+`QuoteBillOfProcess.tsx`):
+
+- **Procedure card** (items :1675, job :3450, quote :2442): render only when
+ `processData.operationType === "Process"`.
+- **New Assembly Instruction card** (same collapsible-card pattern), rendered when
+ `operationType === "Assembly"`: new `AssemblyInstruction`
+ combobox (`~/components/Form/AssemblyInstruction.tsx`, mirroring
+ `Procedure.tsx` — options `name · v{version}` + status badge, scoped by
+ `itemId` prop), storing `assemblyInstructionId`. Job editor adds the
+ "Sync Assembly Steps" button + changed-but-not-synced hint (mirroring the
+ Sync Procedure affordance, job :3506-3531) posting
+ `{ targetKind: "job", operationId }` to `path.to.assemblySyncBop(assemblyInstructionId)`.
+- **New Inspection Document card**, rendered when `operationType === "Inspection"`:
+ new `InspectionDocument` combobox (options `drawingNumber ?? fileName · v{version}`,
+ scoped by `itemId`), storing `inspectionDocumentId`. No sync, no lock.
+- **Locking** — method (items :572/:612/:658) and quote (:584/:648/:691) tab
+ disables gain the assembly term: Steps tab also disables when
+ `!!item.data.assemblyInstructionId` (tooltip "Steps are inherited from the
+ assembly instruction"); Instructions/Parameters lock only on `procedureId` as
+ today. Job editor stays lock-free.
+- **`AssemblyStepsSource` retired** from both editors (items :686-693, job
+ :941-948) — superseded by the card (picker + sync). The component itself is
+ deleted with its imports.
+- **Time fields** — the Machine card (items :1561-1672, job :3285-3362, quote
+ :2275-2352) renders only when `operationType === "Process"`; the job/quote
+ Costing cards keep Labor + Overhead rates but render `machineRate` only for
+ Process. Type-switch onChange also resets machine values to defaults when
+ leaving Process (matching the existing unit-reset pattern).
+- **Type switch clears pointers**: the operationType onChange resets
+ `procedureId`/`assemblyInstructionId`/`inspectionDocumentId` in `processData`
+ to `""` for whichever no longer applies.
+
+**MES:** no changes. The assembly view already resolves playback via
+`jobOperation.assemblyInstructionId`; job steps arrive materialized exactly as
+they do for procedures; the inspection pointer waits for the Phase-3 view.
+
+## Acceptance Criteria
+
+- [ ] Migration: `quoteOperation.assemblyInstructionId` +
+ `inspectionDocumentId` on all three operation tables exist with SET NULL
+ FKs + indexes; re-running the migration is a no-op; types regenerate clean.
+- [ ] Items BoP, operation typed **Process**: Procedure card visible; Machine
+ card + all three time cards visible; no Assembly/Inspection cards.
+- [ ] Items BoP, operation typed **Assembly**: Procedure card gone; Assembly
+ Instruction picker lists only instructions whose `itemId` = the method's
+ item (with status badges); selecting one locks the Steps tab with the
+ inherited tooltip; Machine card gone; Setup + Labor still shown and still
+ required by the validator; machine fields not required.
+- [ ] Items BoP, operation typed **Inspection**: Inspection Document picker
+ lists only documents whose `partId` = the method's item; no locking; no
+ Machine card; Procedure card gone.
+- [ ] Switching an operation from Assembly → Process clears
+ `assemblyInstructionId` (form and DB after save); Process → Inspection
+ clears `procedureId`.
+- [ ] Creating a job from a method whose Assembly operation links a published
+ instruction produces `jobOperationStep` rows matching the instruction's
+ steps (typed fields + `assemblyInstructionStepId` markers + model slide +
+ `jobMaterialStep` links for resolvable parts), and the job operation
+ carries `assemblyInstructionId`; the method's own (empty/locked) steps are
+ not copied.
+- [ ] Creating a job from a method whose Inspection operation links a document
+ copies `inspectionDocumentId` onto the job operation and creates **no**
+ steps from features.
+- [ ] Quote path: item→quote carries both pointers (no materialization);
+ quote→job materializes assembly steps.
+- [ ] Job editor, Assembly op: picker + "Sync Assembly Steps" re-syncs via the
+ existing sync-bop action (update/insert/delete by provenance marker);
+ changing the picked instruction shows the not-synced hint.
+- [ ] Validators: machine unit/time (and job/quote machineRate) required only
+ for Process; an Assembly op saves without machine values.
+- [ ] Typecheck (erp, mes, @carbon/database), lint, and existing tests green;
+ browser e2e passes for the three editor states + the job materialization
+ chain.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| get-method copy-list drift — one of the 14 directions misses the new columns | Med | Audit every explicit insert list in one pass; the PRD calls this exact failure out; grep `procedureId` in the file as the checklist of sites. |
+| Assembly materialization in Deno duplicates app-side sync logic imperfectly (slides/material links) | Med | Mirror `insertProcedureDataForJobOperation`'s placement + port the resolution rules from `syncAssemblyInstructionToOperation` (:5801-5973); job-side re-sync remains available to reconcile. |
+| Stale method-level synced steps (old AssemblyStepsSource flow) linger on templates | Low | They're skipped at get-method once the FK is set; internal-only data; no cleanup migration. |
+| `sanitize()` preserving stale pointers on type change | Med | Explicit server-side null-normalization in the three upserts (spec'd above); acceptance criterion covers it. |
+| Hidden-but-required machine fields breaking saves for Assembly/Inspection | Med | Validator re-gate ships in the same change as the UI hiding; acceptance criterion covers it. |
+| `inspectionDocument` has no status; picker can select any version | Low | Version shown in the option label; PRD's result-record phase adds execution-time semantics. |
+
+## Open Questions
+
+> Autonomous resolutions below follow the spec-writing skill's autonomous mode —
+> surfaced for veto before implementation.
+
+- [x] Assembly lock scope at method/quote level — **Autonomous:** Steps only
+ (Instructions/Parameters stay authorable); procedure keeps locking all
+ three. Veto → lock all three for assembly too.
+- [x] Inspection = pointer only, no steps, no locking — **Resolved by PRD §5.4**
+ (accepted ADR) and Brad's phrasing (only Assembly "resolves to steps").
+- [x] Machine-fields gate written as `=== "Process"` — **Autonomous:** correct
+ semantics for a per-type field set; the `!== 'Outside Processing'`
+ invariant remains reserved for subcontract-boundary logic.
+- [x] Costing card for Assembly/Inspection — **Autonomous:** keep laborRate +
+ overheadRate, hide machineRate ("only setup and labor" read as the
+ machine axis disappearing, not costing disappearing).
+- [x] get-method materializes a linked instruction of any status (procedure
+ parity), while manual job sync keeps its Published guard — **Autonomous.**
+- [x] `quoteOperation.assemblyInstructionId` added — **Autonomous:** required
+ for pointer continuity item→quote→job.
+- [x] Flag gating — **Answer (Brad):** no `isInternal` gate on the assembly
+ card; both cards ship ungated. (Superseded the autonomous parity
+ recommendation.)
+- [x] `AssemblyStepsSource` deleted (both editors) — **Autonomous:** fully
+ superseded by picker + lock (method) and picker + sync (job).
+
+## Non-Goals
+
+- The Phase-3 inspection execution view, `jobOperationInspectionRecord`, pass/fail
+ evaluator, gauge picker (PRD §5.4's remaining scope).
+- Numeric tolerance columns on `inspectionFeature` (PRD §5.3).
+- Auto-defaulting the picker to "the item's sole document/instruction" — the
+ list is scoped, the author picks.
+- Retiring the method-level `assemblyInstructionStepId` provenance column or
+ cleaning historical synced steps.
+- MES changes of any kind.
+
+## Changelog
+
+- 2026-07-21: Created from Brad's phase brief + two full-codebase research
+ passes (procedure mechanics end-to-end; assembly/inspection source schemas).
+ All open questions resolved (one PRD-decided, rest autonomous, surfaced for
+ veto).
+- 2026-07-21: Approved by Brad with one amendment — no `isInternal` gate on the
+ assembly card. Implementation started.
diff --git a/.claude/rules/inbound-inspection-system.md b/.claude/rules/inbound-inspection-system.md
deleted file mode 100644
index a166b5a5f2..0000000000
--- a/.claude/rules/inbound-inspection-system.md
+++ /dev/null
@@ -1,107 +0,0 @@
----
-paths:
- - "apps/erp/app/modules/quality/ui/InboundInspections/**"
- - "apps/erp/app/modules/quality/quality.{server,service,models}.ts"
- - "packages/database/supabase/migrations/*inbound-inspection*.sql"
- - "packages/database/supabase/functions/post-receipt/index.ts"
----
-
-# Inbound Inspection System
-
-Receiving-side quality gate. When a receipt is posted, a **lot-level** inspection is
-created for each received line whose item has `requiresInspection = true`. Inspectors
-record per-sample pass/fail, then disposition the lot Accept / Reject / Partial.
-
-## Data model (newest migration wins)
-
-The shipped schema is the **Phase 2 rebuild** in `20260419163058_inbound-inspection-sampling.sql`,
-which `DROP ... CASCADE`s the original Phase-1 `inboundInspection` table from
-`20260419094132_inbound-inspections.sql` and recreates it lot-based. Don't trust the
-Phase-1 shape (it was per-tracked-entity with `trackedEntityId`/`inspectedBy` columns).
-
-- `item.requiresInspection` BOOLEAN (default false) — added `20260419094132`.
-- `companySettings.samplingStandard` enum `samplingStandard` (`ANSI_Z1_4` | `ISO_2859_1`,
- default `ANSI_Z1_4`) and `companySettings.enforceInspectionFourEyes` BOOLEAN.
-- `itemSamplingPlan` (PK = **`itemId`** only, not composite) — per-item plan, created lazily:
- `type` (`samplingPlanType`: All/First/Percentage/AQL), `sampleSize`, `percentage`,
- `aql`, `inspectionLevel` (I/II/III/S1–S4), `severity` (Normal/Tightened/Reduced).
-- `inboundInspection` (lot level, PK = `id`) — `inboundInspectionId` (human id, `II` seq,
- unique per company), `receiptLineId` (**unique** — one lot per receipt line), `receiptId`,
- `itemId`, `itemReadableId`, `supplierId`, `lotSize`, snapshot of the resolved plan
- (`samplingStandard`, `samplingPlanType`, `sampleSize`, `acceptanceNumber`,
- `rejectionNumber`, `aql`, `inspectionLevel`, `severity`, `codeLetter`),
- `status` (`inboundInspectionStatus`: Pending/In Progress/Passed/Failed/Partial),
- `dispositionedBy`/`dispositionedAt`. **No `itemTrackingType` column** — joined from `item`.
-- `inboundInspectionSample` — one row per recorded result: `inboundInspectionId`,
- `trackedEntityId` (**nullable** since `20260612151947`), `status`
- (`inboundInspectionSampleStatus`: Pending/Passed/Failed), `inspectedBy`/`inspectedAt`.
- A **partial** unique index `inboundInspectionSample_trackedEntityId_key WHERE trackedEntityId
- IS NOT NULL` keeps a serial entity sampleable once while allowing many anonymous samples.
-- `inboundInspectionHistory` — one row per disposition (skeleton for future plan auto-switching).
-- `nonConformanceInboundInspection` (`20260421091238`) — links an auto-created NCR back to
- the inspection (unique `(nonConformanceId, inboundInspectionId)`).
-
-RLS on all tables: standard SELECT/INSERT/UPDATE/DELETE gated by `quality_view/create/update/delete`.
-
-## Receipt → inspection flow (`post-receipt/index.ts`, Supabase edge fn)
-
-`packages/database/supabase/functions/post-receipt/index.ts` (inserts ~line 630):
-1. Loads items (`id, itemTrackingType, requiresInspection`), company `samplingStandard`, and
- `itemSamplingPlan` rows for the receipt.
-2. Per receipt line whose item `requiresInspection` and `receivedQuantity > 0`: resolves the
- plan via `resolveSamplingPlan(plan, lotSize, standard)` from
- `packages/database/supabase/functions/shared/sampling-engine.ts` (ANSI Z1.4 / ISO 2859-1
- tables; returns `{ sampleSize, acceptance, rejection, codeLetter }`). No configured plan →
- defaults to `type: "All"`, level `II`, `Normal`. Pushes an `inboundInspection` insert (with
- `inboundInspectionId` from `getNextSequence`).
-3. **Tracked entities for inspection-required items are set to `"On Hold"` at receipt** (not
- Available); everything else flips to `Available`. They are released individually by sample
- inspection or en masse by lot disposition.
-
-## Tracking types
-
-All four `itemTrackingType` values support inbound inspection (the only UI gate is purchased
-items — see Code map). Serial parts produce N tracked entities and the inspector scans/selects a
-discrete entity per sample; non-serial (Batch/Inventory/Non-Inventory) record pass/fail with
-`trackedEntityId = NULL` (same UI, no scan). Inventory items that aren't tracked have no per-row
-status to flip, so a Reject posts a compensating ledger entry instead (see disposition).
-
-## Code map (ERP)
-
-- **Items toggle**: `apps/erp/app/modules/items/ui/{Parts,Materials,Tools,Consumables}/*Properties.tsx`
- render the `requiresInspection` checkbox only when `replenishmentSystem?.includes("Buy")` (i.e.
- purchased items) — **gated by Buy replenishment, NOT by tracking type**.
-- **Sampling plan editor**: `apps/erp/app/modules/quality/ui/SamplingPlan/SamplingPlanForm.tsx`,
- mounted on `routes/x+/{part,material,tool,consumable}+/$itemId.quality.tsx`.
-- **Inspection detail drawer**: `.../ui/InboundInspections/InboundInspectionLotView.tsx` — progress,
- samples table, Accept/Reject/Partial. Branches on `isSerial = itemTrackingType === "Serial"`.
- Reject modal has an "Open an NCR" checkbox (`createNcr`, defaults on).
-- **Sample modal**: `.../ui/InboundInspections/ScanInspectionSample.tsx` — `isSerial` prop; serial
- shows Scan/Select tabs (entity required), non-serial shows just Notes + Pass/Fail.
-- **Routes** `apps/erp/app/routes/x+/quality+/`: `inbound-inspections.tsx` (list),
- `.$id.tsx` (loader passes `itemTrackingType`), `.$id.sample.tsx`, `.$id.{accept,reject,partial}.tsx`.
-- **Server** `quality.server.ts`:
- - `upsertInboundInspectionSample` — flips entity status + writes `trackedActivity` input/output
- only when `trackedEntityId` is present; anonymous (null) samples are always inserts (no dedupe).
- - `dispositionInboundInspection` — Accept releases un-sampled entities to Available; Reject flips
- all lot entities to Rejected (and for a non-tracked Inventory item posts an `itemLedger`
- `Inbound Inspection` negative adjustment, doc-type added `20260619142853`); Partial leaves
- entities; always writes `inboundInspectionHistory`.
- - NCR auto-creation lives in the **reject route** (`.$id.reject.tsx`), optional via `createNcr`,
- linking through `nonConformanceInboundInspection`.
-- **Service** `quality.service.ts`: `getInboundInspections` (list), `getInboundInspection` (selects
- `item(... itemTrackingType)`), `getInboundInspectionLotTrackedEntities`.
-- **Validators** `quality.models.ts`: `inboundInspectionSampleValidator` (`trackedEntityId`
- optional), `itemSamplingPlanValidator`, `inboundInspectionDispositionValidator`.
-
-## Gotchas
-
-- **Lot-based, not entity-based.** The Phase-1 per-entity `inboundInspection` was dropped; read
- the `20260419163058` migration (and newer) for the real shape. `receiptLineId` is unique — one
- inspection lot per received line.
-- **Inspection-required tracked entities post `On Hold`, not Available.** They are not on-hand
- until released by sampling/disposition.
-- **`trackedEntityId` is nullable** on samples; serial uniqueness is enforced by a *partial* index.
-- **Don't confuse with inspection *documents*.** `inspectionDocument`/`inspectionFeature`/`balloon`
- + `save_inspection_document_atomic` (`20260526142837`, `20260526153412`) are the first-article /
- ballooned-drawing feature — a separate system from this receiving lot flow.
diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.md
new file mode 100644
index 0000000000..f75f0018ef
--- /dev/null
+++ b/.claude/rules/inspection-system.md
@@ -0,0 +1,393 @@
+---
+paths:
+ - "apps/erp/app/modules/quality/ui/Inspections/**"
+ - "apps/erp/app/modules/quality/quality.{server,service,models}.ts"
+ - "apps/erp/app/routes/x+/inspection+/**"
+ - "apps/mes/app/components/Inspection/**"
+ - "apps/mes/app/routes/x+/inspection*.tsx"
+ - "packages/database/src/quality.ts"
+ - "packages/database/supabase/migrations/*inspection*.sql"
+ - "packages/database/supabase/functions/post-receipt/index.ts"
+---
+
+# Inspection System
+
+Generic quality-inspection execution keyed by `sourceDocument` /
+`sourceDocumentId` / `sourceDocumentLineId` / `sourceDocumentReadableId`
+(enum `inspectionSourceDocument`: 'Receipt' and 'Job Operation', both live; no
+FKs on the generic ids, unique per `(sourceDocument, sourceDocumentLineId)` —
+a **partial** unique index `WHERE "sourceDocumentLineId" IS NOT NULL`).
+Renamed from the receipt-only "Inbound Inspections" in `20260722132135_inspections-refactor.sql`
+(tables `inspection`/`inspectionSample`/`inspectionSamplingPlan`/
+`inspectionMeasurement`/`inspectionHistory`/`nonConformanceInspection`;
+readable id column `inspectionId`, sequence key `inspection` — existing
+companies keep their II prefix, new companies seed INS).
+
+Receipt flow: when a receipt is posted, a **lot-level** inspection is created
+for each received line whose item has a **Receipt-usage inspection plan** — i.e.
+an `itemInspectionDocumentAssignment` row for `usage = 'Receipt'` (the item-level
+`requiresInspection` flag was removed 2026-07-26; the assigned document IS the
+gate). A **single**
+full-screen execution UI at `/x/inspection/{id}` (`InspectionView` +
+`InspectionMeasurementGrid`) covers every lot (spec
+`.ai/specs/implemented/2026-07-21-inbound-inspection-execution.md`):
+
+- **Drawing pane** — shown when the lot has an assigned PDF (`pdfUrl != null`);
+ hidden otherwise (the grid takes the full body).
+- **Feature rows** — when the assigned document resolved features, the grid is a
+ features × samples measurement grid: readings auto-valuate against live
+ tolerances, sample status is **derived** (strict, no override), per-feature AQL
+ sampling (feature rule → document default → All; the per-item
+ `itemSamplingPlan` tier was removed 2026-07-26, migration
+ `20260726231401_document-sampling-default.sql`).
+- **No document** — the grid collapses to a single synthetic **"Overall result"**
+ pass/fail row (client-only, `featureId = "__overall__"`). Its P/F cells set the
+ sample's status **directly** via the sample route (`upsertInspectionSample`,
+ status Passed/Failed) rather than recording a measurement; lot-level AQL gating.
+- **Columns** — serial lots add one column per **scanned** tracked entity
+ (`ScanInspectionSample`, identify-only → a Pending sample with a
+ `trackedEntityId`; the column header shows the entity `readableId`); non-serial
+ lots pre-create anonymous numbered columns up to the resolved sample size, and
+ an anonymous `inspectionSample` is materialized lazily on the first cell save
+ (measurement → `upsertInspectionMeasurement`; overall-result → the sample route
+ with `sampleId` for idempotent re-toggle).
+- **Scanning (serial)** — a header **"Add Sample"** button (not an in-grid column)
+ opens the scanner; it is `variant="primary"` until `samples.length >=
+ inspection.sampleSize`, then `secondary`. A fresh serial lot (0 samples)
+ auto-opens the scanner once on mount.
+
+(The pre-unification "fallback" samples table and the scanner's `mode="record"`
+pass/fail path were removed 2026-07-25; scanning is always identify.)
+
+Disposition is always a human decision; Reject/Partial can auto-create an NCR
+whose description includes the failed features (documentation only — never
+required, and the NCR does not drive the physical outcome). The **ERP receipt
+UI** exposes **Accept** and **Reject** (its `$id.partial.tsx` route exists but
+has no header button). The **MES job-operation UI** exposes **Accept**,
+**Partial**, and **Reject**, and its dispositions carry their physical
+production outcome (see "Disposition → production outcome" below). All three
+terminal statuses (Passed/Failed/**Partial**) are hard-terminal in the engine
+since 2026-07-27: samples and measurements are guarded closed on all of them.
+
+## Data model (newest migration wins: `20260722132135_inspections-refactor.sql`)
+
+Lineage: Phase-1 `20260419094132_inbound-inspections.sql` (dropped) → Phase-2
+lot rebuild `20260419163058_inbound-inspection-sampling.sql` → execution layer
+`20260722040401_inbound-inspection-execution.sql` → the rename/source refactor
+`20260722132135`. Old constraint/index NAMES still carry `inboundInspection`
+strings (cosmetic).
+
+- ~~`item.requiresInspection`~~ — **dropped 2026-07-26** (along with the vestigial
+ `purchaseOrderLine.requiresInspection` / `salesOrderLine.requiresInspection`
+ columns). Receipt inspection is now gated by the item's Receipt-usage
+ `itemInspectionDocumentAssignment` (see Receipt flow above), not a boolean flag.
+- `companySettings.samplingStandard` enum `samplingStandard` (`ANSI_Z1_4` | `ISO_2859_1`,
+ default `ANSI_Z1_4`) and `companySettings.enforceInspectionFourEyes` BOOLEAN.
+- `inspectionDocument.sampling*` — the document-level **default sampling rule**
+ (six nullable columns mirroring the per-feature set; added
+ `20260726231401_document-sampling-default.sql`, which also **dropped
+ `itemSamplingPlan`** — plans that existed were backfilled onto the item's
+ documents via `partId`). NULL default = All (100%).
+- `inspection` (lot level, PK = `id`) — `inspectionId` (human id, `II` seq,
+ unique per company), `receiptLineId` (**unique** — one lot per receipt line), `receiptId`,
+ `itemId`, `itemReadableId`, `supplierId`, `lotSize`, snapshot of the resolved plan
+ (`samplingStandard`, `samplingPlanType`, `sampleSize`, `acceptanceNumber`,
+ `rejectionNumber`, `aql`, `inspectionLevel`, `severity`, `codeLetter`),
+ `status` (`inspectionStatusType`: Pending/In Progress/Passed/Failed/Partial),
+ `dispositionedBy`/`dispositionedAt`. **No `itemTrackingType` column** — joined from `item`.
+- `inspectionSample` — one row per recorded result: `inspectionId`,
+ `trackedEntityId` (**nullable** since `20260612151947`), `status`
+ (`inspectionSampleStatusType`: Pending/Passed/Failed), `inspectedBy`/`inspectedAt`.
+ A **partial** unique index `inspectionSample_trackedEntityId_key WHERE trackedEntityId
+ IS NOT NULL` keeps a serial entity sampleable once while allowing many anonymous samples.
+- `inspectionHistory` — one row per disposition (skeleton for future plan auto-switching).
+- `nonConformanceInspection` (`20260421091238`) — links an auto-created NCR back to
+ the inspection (unique `(nonConformanceId, inspectionId)`).
+- `productionQuantity.inspectionId` / `.inspectionSampleId`
+ (`20260727031247_inspection-production-links.sql`) — nullable FKs (ON DELETE
+ SET NULL) recording which inspection/sample drove a posting. The **partial
+ UNIQUE index on `inspectionSampleId`** is the double-count guard: a sample's
+ verdict can produce at most one posting. The same migration forks
+ `sync_finish_job_operation` (the zero-completions fallback to the full job
+ quantity now applies ONLY when the job recorded no scrap/rework — a fully
+ scrapped job closes with `quantityComplete = 0` and receives nothing) and
+ `complete_job_to_inventory` (the serial branch excludes `Rejected` entities
+ from the Assembly Output ledger loop AND the Available release).
+
+Execution-layer tables (`20260722040401_inbound-inspection-execution.sql`):
+
+- `inspection.inspectionDocumentId` — **live** reference to the assigned
+ `inspectionDocument` (ON DELETE SET NULL); no feature snapshot.
+- `itemInspectionDocumentAssignment` — PK `(itemId, usage)`; `usage` enum
+ `inspectionDocumentUsage` (v1: only `'Receipt'`; FAI/Production are additive
+ enum values later). Edited on the item Quality tab (`ItemQualityView`).
+- `inspectionFeature` gained six nullable per-feature sampling columns
+ (`samplingPlanType/SampleSize/Percentage/Aql/InspectionLevel/Severity`);
+ NULL = inherit the document's default rule. Persisted through the
+ `save_inspection_document_atomic` fork in the same migration (newest def).
+- `inspectionSamplingPlan` — per-lot per-feature **resolved** plan
+ (`sampleSize`, `acceptanceNumber`, `rejectionNumber`, `codeLetter`), unique
+ `(inspectionId, inspectionFeatureId)`. Created at receipt; lazily
+ reconciled by the `$id` loader for features added to the live document later.
+- `inspectionMeasurement` — one reading per `(sampleId, featureId)`
+ (unique): `value NUMERIC` (NULL for attribute features), `status`
+ (`inspectionSampleStatusType` — the valuation at entry; tolerance edits
+ never rewrite recorded statuses), `notes`, `inspectedBy/At`.
+
+RLS on all tables: standard SELECT/INSERT/UPDATE/DELETE gated by `quality_view/create/update/delete`.
+
+## Receipt → inspection flow (`post-receipt/index.ts`, Supabase edge fn)
+
+`packages/database/supabase/functions/post-receipt/index.ts` (inserts ~line 700):
+1. Loads items (`id, itemTrackingType, replenishmentSystem`), company `samplingStandard`,
+ Receipt-usage `itemInspectionDocumentAssignment` rows (`assignmentByItemId`), and the
+ assigned documents' `inspectionFeature` rows + default sampling columns.
+2. Per receipt line whose item **has a Receipt-usage assignment** (`assignmentByItemId.get(itemId)`)
+ and `receivedQuantity > 0`: the assigned document is the plan gate — no assignment, no lot.
+ Resolves the lot plan via `resolveSamplingPlan(plan, lotSize, standard)` from
+ `packages/database/supabase/functions/shared/sampling-engine.ts` (ANSI Z1.4 / ISO 2859-1
+ tables; returns `{ sampleSize, acceptance, rejection, codeLetter }`). Document with no
+ default rule → `type: "All"`, level `II`, `Normal`. Always resolves **each feature** via
+ `resolveFeatureSamplingPlan(feature, documentDefault, lotSize, standard)` (feature rule →
+ document default → All), **always** stamps `inspectionDocumentId = assignedDocumentId` on the
+ lot (even a drawing-only document with no features), sets the lot-level `sampleSize` to the max
+ across features (or the snapshot size when featureless), and (after the insert `.returning`s
+ the lot ids) batch-inserts the `inspectionSamplingPlan` rows.
+3. **Tracked entities for items with a Receipt-usage assignment are set to `"On Hold"` at
+ receipt** (not Available); everything else flips to `Available`. They are released
+ individually by sample inspection / derived measurement status or en masse by lot disposition.
+
+## Job Operation → inspection flow (MES, added 2026-07-26)
+
+Job operations with `operationType = 'Inspection'` execute in the MES at
+`/x/inspection/{jobOperationId}` (`apps/mes/app/routes/x+/inspection.$operationId.tsx`,
+guard-redirect pattern per ADR-0005; `operation.$operationId.tsx` redirects
+Inspection ops here). The lot is **created lazily on first open** by
+`getOrCreateJobOperationInspection` (`@carbon/database/quality`): mirrors
+post-receipt plan resolution (document default → All; per-feature plans
+from the operation's `inspectionDocumentId` FK — stamped even when the document
+has no features yet, so drawing-only docs render and later features reconcile
+in), `sourceDocument='Job Operation'`, `sourceDocumentId=job.id`,
+`sourceDocumentLineId=jobOperationId`, `sourceDocumentReadableId=job.jobId`,
+`itemId` = the make method's item (subassembly ops inspect the subassembly),
+`lotSize = operationQuantity`, human id from the `inspection` sequence.
+Concurrent first-opens are settled by the partial unique index (23505 → reselect).
+
+- **MES UI**: `apps/mes/app/components/Inspection/` — `InspectionView` (AssemblyView
+ shell: header segments for Add Sample / Complete passed (n) / Reject / Partial /
+ Accept, TimerControl → `/x/event` — the labor clock **auto-starts on open
+ whenever no clock is running**, always on for inspections, independent of the
+ company `autoStartOperationTimer` setting; action sheet for Scrap/Rework/Finish/Quality
+ Issue via the shared JobOperation modals), `InspectionMeasurementMatrix` (plain
+ touch-first table, SAME per-cell quiet POST contract as the ERP grid),
+ `InspectionDrawingPane` (verbatim copy of the ERP pane; MES gained
+ `konva`/`react-konva`/`pdfjs-dist` deps + canvas SSR stub + worker bootstrap),
+ `ScanInspectionSample` (adapted: `@carbon/form` fields, samples from
+ make-method WIP entities), `DispositionModal` (the Reject/Partial failed-set
+ allocator; replaced `RejectLotModal` 2026-07-27).
+- **MES routes**: view param is the jobOperationId; lot actions use the lot id
+ under a distinct prefix — `x+/inspection-lot.$id.{measurement,sample,disposition,complete-passed}.tsx`
+ (`path.to.inspectionMeasurement|Sample|Disposition|CompletePassed`; the old
+ accept/reject routes were retired 2026-07-27), each
+ `requirePermissions({ update: "quality" })` → MES validators
+ (`~/services/models`) → the shared engine with `getDatabaseClient()`
+ (`apps/mes/app/services/database.server.ts`, same singleton as ERP's).
+- **WIP entities are never flipped by sampling or by the quality engine.** The
+ entity flips in `upsertInspectionSample` / `upsertInspectionMeasurement` (and
+ their `applySampleEntityStatus` activity writes) are guarded
+ `sourceDocument === "Receipt"`, matching `dispositionInspection`'s existing
+ guard — job WIP entities keep their job-owned status (Reserved etc.). The
+ ONE exception lives in the production-outcome layer, not the engine: the MES
+ disposition route flips the **scrap-allocated** serial subset to `Rejected`
+ (see below).
+- **MES reads**: `apps/mes/app/services/quality.service.ts` (copies of the ERP
+ reads + a simplified `getInspectionDocumentWithBalloons` that builds the
+ `/file/preview/private/` pdfUrl from `inspectionDocument.storagePath`).
+
+### Disposition → production outcome (MES, added 2026-07-27)
+
+The MES verdict carries its physical posting — one decision surface instead of
+parallel Accept/Reject + menu Log-Completed/Scrap/Rework vocabularies. The
+quality engine stays pure (verdicts only); orchestration lives in
+`x+/inspection-lot.$id.disposition.tsx` on top of shared helpers in
+`apps/mes/app/services/quality.server.ts`
+(`getInspectionOutcomeState` — buckets recomputed fresh from the DB per POST;
+`getSerialCompletionCandidates` / `postSerialCompletions` /
+`postBulkCompletion`; `createInspectionRejectionIssue` — the NCR block lifted
+from the retired reject route).
+
+| Decision | Physical postings |
+|---|---|
+| **Accept** | Completes the open remainder (serial: per-entity `issue` `jobOperationSerialComplete`, Pending-sampled and un-sampled units included, failed-sample units EXCLUDED; non-serial: one bulk posting of the op-column remaining via `jobOperationBatchComplete` or `insertProductionQuantity`+backflush) |
+| **Reject** | The operator allocates the open remainder in `DispositionModal`: serial per-unit Scrap/Rework toggles, non-serial scrap+rework quantity fields; the rest is record-only. Scrap subset → one `insertScrapQuantity` (+reason, + backflush) and the serial subset flips → `Rejected`. Rework subset → ONE `trigger-rework` invoke (targets from `rework-targets`; the routing clone includes the inspection op → fresh lot → automatic re-inspection) + `recalculate jobRequirements`; reworked entities are NOT flipped. |
+| **Partial** | Terminal mixed close, gated `inspected >= lotSize && passes > 0 && fails > 0`. Passed units complete; the failed set is allocated exactly like Reject (allocation restricted to failed units). |
+| **Complete passed (n)** header chip | Progressive completion of passed-but-unposted units any time the lot is open (`$id.complete-passed.tsx`) — explicit button, not auto-on-pass, so verdict typos need no compensating transaction. |
+
+Mechanics (in order, per POST):
+1. Buckets recomputed server-side and validated (allocation ids must be open
+ make-method entities; quantities clamped to the **op-column remaining** =
+ `target − complete − scrapped − reworked`, so escape-hatch menu postings are
+ never double-counted; serial divergence blocks with an error).
+2. `dispositionInspection({ requireOpen: true })` closes the lot FIRST — the
+ one-shot status UPDATE is the serialization point; a concurrent second POST
+ dies before any posting can re-run (a re-POST can never re-clone the rework
+ path).
+3. Postings, each carrying provenance links (`productionQuantity.inspectionId`
+ + `inspectionSampleId`; serial completes processed in ascending sample order;
+ non-serial bulk rows link the lowest unlinked passed sample as a serializing
+ representative). Failures after step 2 leave a closed lot with partial
+ postings — surfaced loudly in the flash; the links make the arithmetic
+ self-heal for manual ERP fixes.
+4. Optional NCR (`createNcr`), `willBeFinished` mirror from `complete.tsx` for
+ `targetQuantity = 0` operations.
+
+The action sheet keeps Scrap/Rework (escape hatches for non-quality losses),
+Finish, and Quality Issue; **Log Completed was removed** (verdict-driven
+completion replaced it).
+
+## Tracking types
+
+All four `itemTrackingType` values support inbound inspection (the only UI gate is purchased
+items — see Code map). Serial parts produce N tracked entities and the inspector scans/selects a
+discrete entity per sample; non-serial (Batch/Inventory/Non-Inventory) record pass/fail with
+`trackedEntityId = NULL` (same UI, no scan). Inventory items that aren't tracked have no per-row
+status to flip, so a Reject posts a compensating write-off instead (see disposition).
+
+**Reject / disposition GL posting.** A non-tracked `Inventory` reject and every NCR disposition
+route their inventory value through the **`post-nonconformance` edge function** (`itemLedger` +
+`costLedger` relief + a `journal` offset to `accountDefault.scrapAccount`, gated on
+`accountingEnabled`; idempotent per `(documentType, documentId)`). The reject route
+(`$id.reject.tsx`) invokes it with the lot write-off (`documentType 'Inbound Inspection'`,
+`documentId = inspection.id`) after `dispositionInspection` commits — `dispositionInspection`
+itself no longer writes `itemLedger`, it returns a `writeOff` descriptor. Disposition close
+(`closeIssue`) invokes it with `documentType 'Non-Conformance'`, `documentId = ncrId`. Non-tracked
+disposition rows are dispositionable in `AssociatedItemsList.tsx` (quantity + `Select`, split by
+quantity, no move); Use-As-Is/Rework on an inspection-rejected `Inventory` lot restores value,
+non-inspection Scrap writes it off, `Non-Inventory` never posts. See `issue-module.md` → Disposition
+GL/cost posting and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
+
+## Code map (ERP)
+
+- **No items toggle**: the `requiresInspection` checkbox was removed from the item
+ Properties sidebars (Parts/Materials/Tools/Consumables) 2026-07-26. Inbound
+ inspection is configured entirely on the item **Quality tab** by assigning a
+ Receipt-usage inspection document; there is no per-item boolean.
+- **Item Quality tab**: `.../ui/Item/ItemQualityView.tsx` (documents card + usage-slot
+ assignments card; sampling lives on the document, not the item), mounted on
+ `routes/x+/{part,material,tool,consumable,service}+/$itemId.quality.tsx` (actions branch on
+ `intent=assignment`). The tab is **always shown** (no `requiresInspection` gate in the item
+ navigation hooks), for every item type, gated only by the `quality` view permission.
+- **Execution view**: `.../ui/Inspections/InspectionView.tsx` — full-screen,
+ data-prop reusable (AssemblyView pattern, for later MES reuse). Renders
+ `InspectionDrawingPane.tsx` (lazy react-pdf + Konva balloons, click ↔ row sync) above
+ `InspectionMeasurementGrid.tsx` when `pdfUrl != null`, else the grid alone.
+ `InspectionMeasurementGrid.tsx` (shared Table inline editing, per-cell quiet POSTs, capture-phase
+ Enter/Tab nav, attribute P/F toggle cells; every cell is recordable — a feature's n is the
+ required MINIMUM, extra readings up to the lot size are allowed) shows feature
+ rows when `liveFeatures.length > 0`, otherwise the single `OVERALL_ROW_ID` pass/fail row whose
+ cells write the sample status via the sample route. `RejectLotModal.tsx` (extracted) previews
+ failed features.
+- **Sample modal**: `.../ui/Inspections/ScanInspectionSample.tsx` — identify-only; opened by the
+ header **"Add Sample"** button (`InspectionView`, serial lots; primary until the sample size is
+ covered, auto-opened once on a fresh 0-sample lot). `isSerial` shows Scan/Select tabs (entity
+ required) and posts a **Pending** sample column with a `trackedEntityId` (verdict set later in the
+ grid). Non-serial columns are pre-created, so the modal is serial-only in practice.
+- **Routes**: list stays `x+/quality+/inspections.tsx`; the old
+ `inspections.$id.tsx` is a redirect stub to the full-screen tree
+ `x+/inspection+/` (`_layout.tsx` module `quality`; `$id.tsx` loader reconciles features +
+ loads document/balloons via service role; actions: `$id.measurement.tsx` (per-cell),
+ `$id.sample.tsx`, `$id.document.tsx` (swap, only unmeasured non-terminal lots),
+ `$id.{accept,reject,partial}.tsx`). Path helpers: `path.to.inspection*`.
+- **Server** — the transactional engine lives in **`@carbon/database/quality`**
+ (`packages/database/src/quality.ts`; moved 2026-07-26 so ERP and MES run one
+ engine). Every function takes a `Kysely<KyselyDatabase>` first param; ERP's
+ `quality.server.ts` is thin wrappers currying `getDatabaseClient()` (names and
+ signatures unchanged — ERP routes/tests untouched). `packages/database/src/sampling.ts`
+ re-exports the pure Deno `shared/sampling-engine.ts` node-side (client.ts
+ pattern); the engine consumes it, so package + edge share ONE resolver copy
+ (ERP's `samplingStandards.ts` client copy remains for UI previews).
+ - **Closed guards + linked-sample locks (2026-07-27):** all three terminal
+ statuses (Passed/Failed/**Partial**) block `upsertInspectionSample` (guard
+ is NEW — it had none) and `upsertInspectionMeasurement` ("Inspection is
+ closed") and `changeInspectionDocument`. Updating an EXISTING sample (or a
+ measurement on one) additionally fails when a `productionQuantity` row
+ links its `inspectionSampleId` — the unit was already completed from that
+ verdict; deleting the row in the ERP unlocks it (`assertSampleNotLinked`).
+ - `upsertInspectionSample` — upsert precedence: by `trackedEntityId` (serial),
+ else by `sampleId` (the "Overall result" row re-toggling an anonymous column
+ in place), else insert a fresh anonymous sample. Entity flip + `trackedActivity`
+ via the shared `applySampleEntityStatus` helper; skipped for `Pending`
+ (identify-only) samples. The `$id.sample.tsx` route returns the `sampleId` and,
+ when `quiet=true` (grid overall-result POST), suppresses the success flash.
+ - `valuateMeasurement` (exported, unit-tested) — numeric in `[nominal − |tol−|, nominal + |tol+|]`;
+ unparseable nominal / non-Measurement types valuate as attributes.
+ - `upsertInspectionMeasurement` — creates anonymous samples on demand, upserts the
+ reading, **derives** the sample status count-based (not positional): any failed
+ reading ⇒ Failed; every plan feature Passed on the sample ⇒ Passed; else Pending.
+ A feature's n is the required minimum across ANY samples (per-feature disposition
+ gating enforces the counts); extra readings up to the lot size are allowed.
+ Applies entity transitions (revert → On Hold, no activity), recomputes
+ non-terminal lot status.
+ - `reconcileInspectionSamplingPlans` — lazy per-lot plan rows for features added post-receipt.
+ - `changeInspectionDocument` — swap/clear guarded to unmeasured non-terminal lots; wipes
+ plan rows for re-resolution.
+ - `dispositionInspection` — per-feature gating when the lot has features (Accept: every
+ feature `recorded >= n && failed <= Ac`; Reject: some feature `failed >= Re` or a failed
+ sample); Accept releases every non-failed lot entity to Available (un-sampled AND
+ partially-inspected Pending samples included); Reject flips all lot entities to
+ Rejected (and for a non-tracked Inventory item posts an `itemLedger` `Inbound Inspection`
+ negative adjustment); Partial leaves entities; always writes `inspectionHistory`.
+ Optional **`requireOpen`** (one-shot mode, MES disposition route only): the
+ status UPDATE gains `WHERE status NOT IN (Passed,Failed,Partial)` and the
+ call throws "Inspection is already dispositioned" on zero rows — concurrency
+ safe because a second transaction blocks on the row lock, re-evaluates the
+ predicate against the committed terminal status, and matches nothing. ERP
+ receipt lots do NOT pass it, preserving re-disposition (write-off retry)
+ semantics.
+ - NCR auto-creation lives in the **reject route** (`x+/inspection+/$id.reject.tsx`),
+ optional via `createNcr`, linking through `nonConformanceInspection`; the description
+ includes a "Failed features" block built from the lot's measurements.
+- **Service** `quality.service.ts`: `getInspections` (list), `getInspection`,
+ `getInspectionTrackedEntities`, `getInspectionSamplingPlans` (embeds
+ `inspectionFeature(...)` by table name), `getInspectionMeasurements`,
+ `getItemInspectionDocumentAssignments` / `upsertItemInspectionDocumentAssignment` (empty
+ documentId deletes the slot).
+- **Validators** `quality.models.ts`: `inspectionSampleValidator` (`trackedEntityId`
+ optional; status includes `Pending`),
+ `inspectionDispositionValidator`, `inspectionMeasurementValidator`
+ (`value` xor `passed`), `itemInspectionDocumentAssignmentValidator`,
+ `inspectionDocumentUsages` const.
+- **Sampling engines** (kept in sync manually): `resolveSamplingPlan` +
+ `resolveFeatureSamplingPlan` in both `apps/erp/app/modules/quality/samplingStandards.ts` and
+ `packages/database/supabase/functions/shared/sampling-engine.ts`.
+
+## Gotchas
+
+- **Lot-based, not entity-based.** The Phase-1 per-entity `inspection` was dropped; read
+ the `20260419163058` migration (and newer) for the real shape. `receiptLineId` is unique — one
+ inspection lot per received line.
+- **Inspection-required tracked entities post `On Hold`, not Available.** They are not on-hand
+ until released by sampling/disposition.
+- **`trackedEntityId` is nullable** on samples; serial uniqueness is enforced by a *partial* index.
+- **Inspection *documents* are authored in the production module** (`inspectionDocument`/
+ `inspectionFeature`/`balloon` + `save_inspection_document_atomic`, newest def
+ `20260722040401`) and are now *consumed* by this flow via the item's Receipt-usage
+ assignment. The lot references the document **live** — measurement rows store the
+ valuation at entry, so later tolerance edits never rewrite recorded results.
+- **Sample status is derived on document-driven lots** — do not add manual sample
+ pass/fail UI there; deviations resolve at disposition via MRB/NCR (spec decision).
+- **Per-cell measurement saves are quiet** (plain `fetch`, no revalidation) — the grid and
+ the view mirror statuses locally from the action's returned
+ `{sampleId, measurementStatus, sampleStatus}`.
+- **MES dispositions are one-shot; ERP receipt dispositions are not.** Only the
+ MES disposition route passes `requireOpen` — don't add it to ERP receipt
+ routes (their Reject retry re-invokes the idempotent `post-nonconformance`).
+- **A crash between the one-shot close and the postings** leaves a closed lot
+ with missing postings (by design — close-first is what makes rework
+ un-repeatable). Recovery is manual: post the missing rows from the ERP
+ (`productionQuantity` links make completed-vs-not arithmetic self-healing);
+ deleting a linked Production row makes that sample's unit completable again.
+- **ERP inspection views of Job Operation lots are verdict-only.** The
+ execution surface (postings, allocation, complete-passed) is the MES; the
+ ERP shows the lot, samples, and measurements but exposes no outcome
+ orchestration for job-op lots.
diff --git a/.claude/rules/issue-module.md b/.claude/rules/issue-module.md
index 9ad9289557..4d67e392b1 100644
--- a/.claude/rules/issue-module.md
+++ b/.claude/rules/issue-module.md
@@ -45,6 +45,28 @@ in the migrations — **newest wins**; core tables created in
in `quality.models.ts` currently has most values **commented out** (only `Pending`,
`Return to Supplier`, `Rework`, `Scrap`, `Use As Is` active) — the picker is a
deliberate subset of the DB enum.
+- **Non-tracked disposition**: `nonConformanceItem` rows exist for non-tracked items
+ (`Inventory` / `Non-Inventory`, e.g. a job-operation NCR from `apps/mes` or a
+ rejected non-tracked inbound-inspection lot) — they carry a `quantity` and no
+ `nonConformanceItemTrackedEntity` links. `AssociatedItemsList.tsx` renders these as
+ a quantity + disposition `Select` (no entity chips; "Move entities" stays gated on
+ `links.length > 0`). **Split** works for a non-tracked row as a pure quantity split
+ (`splitIssueItem` creates a new `Pending` row for the split-off quantity and shrinks
+ the original, no entity subdivision), so MRB can e.g. scrap N and use-as-is the
+ rest. `closeIssue` still requires every row (tracked or not) to be non-`Pending`.
+- **Disposition GL/cost posting** (`closeIssue` + inspection reject): inventory value
+ movements go through the **`post-nonconformance` edge function** (`itemLedger` +
+ `costLedger` relief via `calculateCOGS` + a balanced `journal` offset to
+ `accountDefault.scrapAccount`, gated on `accountingEnabled`), **not** raw `itemLedger`
+ inserts. `closeIssue` builds `movements[]` and invokes it BEFORE the status-flip
+ transaction (idempotent per `(documentType,documentId)`, so a retry is safe; a GL
+ failure aborts the close). Movement rules: tracked Scrap/Return → `-link.qty` per
+ entity; non-tracked `Inventory` **non-inspection** Scrap → `-row.qty` write-off;
+ non-tracked `Inventory` **inspection-originated** Use-As-Is/Rework → `+row.qty` restore
+ (undoing the reject write-off); tracked Use-As-Is/Rework and any `Non-Inventory` move
+ no value. Origin detected via the `nonConformanceInspection` link. Reopen is blocked
+ once a `Non-Conformance` `itemLedger` row exists (`$id.status.tsx`). See
+ `.claude/rules/inspection-system.md` and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
## Workflow (header buttons → routes)
@@ -117,7 +139,7 @@ Reviewers managed in `ReviewersList.tsx` (`nonConformanceReviewerValidator` = ju
`externalLink`), `nonConformanceJobOperation`, `nonConformancePurchaseOrderLine`,
`nonConformanceSalesOrderLine`, `nonConformanceShipmentLine`,
`nonConformanceReceiptLine`, `nonConformanceTrackedEntity`,
- `nonConformanceInboundInspection` (`20260421091238`).
+ `nonConformanceInspection` (created `20260421091238` as nonConformanceInboundInspection; renamed `20260722132135`).
## `issues` view
diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.md
index 1c3c98641e..1a98d1e47a 100644
--- a/.claude/rules/mes-job-operation-ui.md
+++ b/.claude/rules/mes-job-operation-ui.md
@@ -11,6 +11,13 @@ steps/parameters, files, serials, and scrap/rework/finish actions.
## Route & data flow
+Execution views are routed by `jobOperation.operationType` via
+`resolveOperationView` (`apps/mes/app/utils/operationView.ts`): `Assembly` →
+`/x/assembly/:id` (`AssemblyView`), `Inspection` → `/x/inspection/:id`
+(`components/Inspection/InspectionView`, see `inspection-system.md`), everything
+else → this operation view. Each route opens with a redirect guard that only
+redirects kinds it does not serve (no loops).
+
- **Route:** `apps/mes/app/routes/x+/operation.$operationId.tsx` — `/x/operation/:operationId`.
- **Loader** (uses `getCarbonServiceRole()`, not the user client) fetches via
`~/services/operations.service`: `getJobOperationById`, `getJobByOperationId`,
diff --git a/.claude/rules/revision-system.md b/.claude/rules/revision-system.md
index 487c6604e5..799512902f 100644
--- a/.claude/rules/revision-system.md
+++ b/.claude/rules/revision-system.md
@@ -93,5 +93,6 @@ Make methods are independently **versioned** (`20250603011801_make-method-versio
generated column all special-case them together — handle all three.
- **No `itemId` FK on type tables**; join on `readableId` + `companyId`. Adding an
`itemReadableId` column is explicitly disallowed by the DB conventions.
-- The detail RPCs select `i."requiresInspection"` (added after the original
- revision migrations) — older RPC bodies in earlier migrations omit it; newest wins.
+- The detail RPCs no longer select `i."requiresInspection"` — that column was dropped
+ 2026-07-26 and the RPCs recreated without it (older RPC bodies in migrations between
+ `20260419094132` and the drop still select it; newest wins).
diff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.md
index e8bc4c4e30..480e388d64 100644
--- a/.claude/rules/shipments-receipts-ui-patterns.md
+++ b/.claude/rules/shipments-receipts-ui-patterns.md
@@ -81,8 +81,9 @@ slip PDF; receipt may invoke `update-purchased-prices` when `updateLeadTimesOnRe
- **post-receipt** handles `Purchase Order` and `Inbound Transfer`. PO path: inserts `itemLedger`
(entry types `Positive/Negative Adjmt.` by sign), GR/IR + inventory `journalLine`s when
`accountingEnabled`, advances PO line `quantityReceived`/`receivedComplete` and PO `status`,
- flips tracked entities to `Available` (**`On Hold` if the item `requiresInspection`**), and
- creates one `inboundInspection` lot per inspected line (see `inbound-inspection-system.md`).
+ flips tracked entities to `Available` (**`On Hold` if the item has a Receipt-usage inspection
+ document assignment**), and
+ creates one `inspection` lot per inspected line (see `inspection-system.md`).
- **post-shipment** handles `Sales Order`, `Purchase Order`, `Outbound Transfer`. SO path: COGS
`journalLine`s via `calculateCOGS` + `costLedger`, negative `itemLedger`, advances SO line
`quantitySent`/`sentComplete` and SO `status`, updates `job.quantityShipped`/status for Job
diff --git a/README.md b/README.md
index 6a6518196f..f4d93fa9fe 100644
--- a/README.md
+++ b/README.md
@@ -178,10 +178,12 @@ $ pnpm install # install dependencies
```bash
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Rust, if not already installed
- $ brew install fcl cmake ninja # collision libs (+ libccd/eigen/octomap) and build tools
+ $ brew install fcl cmake ninja draco # collision libs (+ libccd/eigen/octomap), build tools, Draco mesh compression
```
- On Linux, install the equivalents from your package manager: `libfcl-dev libccd-dev libeigen3-dev liboctomap-dev cmake ninja-build` plus a C/C++ toolchain.
+ On Linux, install the equivalents from your package manager: `libfcl-dev libccd-dev libeigen3-dev liboctomap-dev libdraco-dev cmake ninja-build` plus a C/C++ toolchain.
+
+ `./setup.sh` already installs Draco on macOS. If yours lives outside the Homebrew keg (`/opt/homebrew/opt/draco` on arm64), point `draco-bridge`'s build at it with `DRACO_PREFIX=/path/to/draco cargo build`.
2. **Build OCCT once** — a patched static OpenCASCADE, cached in `~/.cache/carbon-occt`. Slow (~15–30 min) but one-time per machine; re-running is a no-op once cached:
@@ -485,19 +487,6 @@ const { data, error } = await carbon
```
-## Translations
-
-In order to run `pnpm run translate` you must first run:
-
-```bash
-brew install ollama
-brew services start ollama
-ollama pull llama3.2
-curl http://localhost:11434/api/tags
-npx linguito config set \
- llmSettings.provider=ollama \
- llmSettings.url=http://127.0.0.1:11434/api
-```
## Migration Notes
### Trigger.dev to Inngest
diff --git a/apps/erp/app/components/Form/AssemblyInstruction.tsx b/apps/erp/app/components/Form/AssemblyInstruction.tsx
new file mode 100644
index 0000000000..10be9735fe
--- /dev/null
+++ b/apps/erp/app/components/Form/AssemblyInstruction.tsx
@@ -0,0 +1,71 @@
+import type { ComboboxProps } from "@carbon/form";
+import { Combobox } from "@carbon/form";
+import { HStack } from "@carbon/react";
+import { useEffect, useMemo } from "react";
+import { useFetcher } from "react-router";
+import type { getAssemblyInstructionsForItem } from "~/modules/production/production.service";
+import AssemblyInstructionStatus from "~/modules/production/ui/Assemblies/AssemblyInstructionStatus";
+import { path } from "~/utils/path";
+
+type AssemblyInstructionSelectProps = Omit<ComboboxProps, "options"> & {
+ itemId?: string;
+};
+
+const AssemblyInstruction = ({
+ itemId,
+ ...props
+}: AssemblyInstructionSelectProps) => {
+ const { options, loading } = useAssemblyInstructions({ itemId });
+
+ return (
+ <Combobox
+ options={options}
+ isOptional={props?.isOptional ?? true}
+ isLoading={loading}
+ {...props}
+ label={props?.label ?? "Assembly Instruction"}
+ />
+ );
+};
+
+AssemblyInstruction.displayName = "AssemblyInstruction";
+
+export default AssemblyInstruction;
+
+export const useAssemblyInstructions = (args: { itemId?: string }) => {
+ const { itemId } = args;
+ const assemblyInstructionFetcher =
+ useFetcher<Awaited<ReturnType<typeof getAssemblyInstructionsForItem>>>();
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher.load is not referentially stable; reload only when itemId changes
+ useEffect(() => {
+ if (itemId) {
+ assemblyInstructionFetcher.load(path.to.api.assemblyInstructions(itemId));
+ }
+ }, [itemId]);
+
+ const loading = assemblyInstructionFetcher.state !== "idle";
+
+ const options = useMemo(
+ () =>
+ itemId && assemblyInstructionFetcher.data?.data
+ ? assemblyInstructionFetcher.data.data.map((c) => ({
+ value: c.id,
+ label: (
+ <div className="flex justify-between items-center gap-1 w-full">
+ <HStack className="items-end">
+ <span className="text-sm truncate">{c.name} </span>
+ <span className="text-xs text-muted-foreground">
+ v{c.version}
+ </span>
+ </HStack>
+ <AssemblyInstructionStatus status={c.status} />
+ </div>
+ )
+ }))
+ : [],
+ [assemblyInstructionFetcher.data, itemId]
+ );
+
+ return { options, loading };
+};
diff --git a/apps/erp/app/components/Form/InspectionDocument.tsx b/apps/erp/app/components/Form/InspectionDocument.tsx
new file mode 100644
index 0000000000..2180667c40
--- /dev/null
+++ b/apps/erp/app/components/Form/InspectionDocument.tsx
@@ -0,0 +1,71 @@
+import type { ComboboxProps } from "@carbon/form";
+import { Combobox } from "@carbon/form";
+import { HStack } from "@carbon/react";
+import { useEffect, useMemo } from "react";
+import { useFetcher } from "react-router";
+import type { getInspectionDocumentsForItem } from "~/modules/production/production.service";
+import { path } from "~/utils/path";
+
+type InspectionDocumentSelectProps = Omit<ComboboxProps, "options"> & {
+ itemId?: string;
+};
+
+const InspectionDocument = ({
+ itemId,
+ ...props
+}: InspectionDocumentSelectProps) => {
+ const { options, loading } = useInspectionDocuments({ itemId });
+
+ return (
+ <Combobox
+ options={options}
+ isOptional={props?.isOptional ?? true}
+ isLoading={loading}
+ {...props}
+ label={props?.label ?? "Inspection Plan"}
+ />
+ );
+};
+
+InspectionDocument.displayName = "InspectionDocument";
+
+export default InspectionDocument;
+
+export const useInspectionDocuments = (args: { itemId?: string }) => {
+ const { itemId } = args;
+ const inspectionDocumentFetcher =
+ useFetcher<Awaited<ReturnType<typeof getInspectionDocumentsForItem>>>();
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher.load is not referentially stable; reload only when itemId changes
+ useEffect(() => {
+ if (itemId) {
+ inspectionDocumentFetcher.load(path.to.api.inspectionDocuments(itemId));
+ }
+ }, [itemId]);
+
+ const loading = inspectionDocumentFetcher.state !== "idle";
+
+ const options = useMemo(
+ () =>
+ itemId && inspectionDocumentFetcher.data?.data
+ ? inspectionDocumentFetcher.data.data.map((c) => ({
+ value: c.id,
+ label: (
+ <div className="flex justify-between items-center gap-1 w-full">
+ <HStack className="items-end">
+ <span className="text-sm truncate">
+ {c.drawingNumber ?? c.fileName ?? c.id}{" "}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ v{c.version}
+ </span>
+ </HStack>
+ </div>
+ )
+ }))
+ : [],
+ [inspectionDocumentFetcher.data, itemId]
+ );
+
+ return { options, loading };
+};
diff --git a/apps/erp/app/components/Form/Process.tsx b/apps/erp/app/components/Form/Process.tsx
index ade08cc449..b0b95b7545 100644
--- a/apps/erp/app/components/Form/Process.tsx
+++ b/apps/erp/app/components/Form/Process.tsx
@@ -72,7 +72,7 @@ const Process = ({
}}
initialValues={{
name: created,
- processType: "Inside",
+ processType: "Process",
defaultStandardFactor: "Minutes/Piece",
completeAllOnScan: false,
workCenters: []
diff --git a/apps/erp/app/components/Form/Processes.tsx b/apps/erp/app/components/Form/Processes.tsx
index ba29df33db..522cc90062 100644
--- a/apps/erp/app/components/Form/Processes.tsx
+++ b/apps/erp/app/components/Form/Processes.tsx
@@ -45,7 +45,7 @@ const Processes = (props: ProcessSelectProps) => {
initialValues={{
name: created,
defaultStandardFactor: "Minutes/Piece",
- processType: "Inside",
+ processType: "Process",
workCenters: [],
completeAllOnScan: false
}}
diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.ts
index d2e062b96e..3e4ebd3d6b 100644
--- a/apps/erp/app/components/Form/index.ts
+++ b/apps/erp/app/components/Form/index.ts
@@ -30,6 +30,7 @@ import Abilities from "./Abilities";
import Ability from "./Ability";
import Account, { AccountControlled } from "./Account";
import AddressAutocomplete from "./AddressAutocomplete";
+import AssemblyInstruction from "./AssemblyInstruction";
import AssetClass, { useAssetClasses } from "./AssetClass";
import Color from "./Color";
import ConversionFactor from "./ConversionFactor";
@@ -50,6 +51,7 @@ import EmojiPicker from "./EmojiPicker";
import Employee from "./Employee";
import Employees from "./Employees";
import { useEmptyState } from "./emptyStates";
+import InspectionDocument from "./InspectionDocument";
import Item, { useConfigurableItems } from "./Item";
import ItemPostingGroup from "./ItemPostingGroup";
import Items from "./Items";
@@ -98,6 +100,7 @@ export {
AddressAutocomplete,
Array,
ArrayNumeric,
+ AssemblyInstruction,
Boolean,
Color,
Combobox,
@@ -128,6 +131,7 @@ export {
Hidden,
Input,
InputControlled,
+ InspectionDocument,
Item,
ItemPostingGroup,
Items,
diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsx
index c2cfc0eb19..41ef9457c4 100644
--- a/apps/erp/app/components/Icons.tsx
+++ b/apps/erp/app/components/Icons.tsx
@@ -47,16 +47,19 @@ import {
LuImage,
LuLandmark,
LuList,
+ LuListChecks,
LuMapPin,
LuPizza,
LuQrCode,
LuRotateCcw,
LuShoppingCart,
LuSquare,
+ LuStepForward,
LuTags,
LuTarget,
LuTimer,
LuToggleLeft,
+ LuTriangleAlert,
LuTruck,
LuUser,
LuUsers,
@@ -74,7 +77,7 @@ import type {
} from "~/modules/accounting";
import type { JobOperation } from "~/modules/production/types";
import type { nonConformanceTaskStatus } from "~/modules/quality";
-import type { MethodType } from "~/modules/shared";
+import type { MethodType, OperationType } from "~/modules/shared";
export const ModuleIcon = ({ icon }: { icon: ReactNode }) => {
return (
@@ -375,6 +378,31 @@ export const ProcedureStepTypeIcon = ({
}
};
+export const OperationTypeIcon = ({
+ type,
+ className
+}: {
+ type: OperationType;
+ className?: string;
+}) => {
+ switch (type) {
+ // Process mirrors the Procedures nav icon
+ case "Process":
+ return <LuListChecks className={cn("text-foreground", className)} />;
+ // Assembly mirrors the Assembly Instructions nav icon
+ case "Assembly":
+ return <LuStepForward className={cn("text-emerald-500", className)} />;
+ // Inspection mirrors the Inspections nav icon
+ case "Inspection":
+ return <LuClipboardCheck className={cn("text-amber-500", className)} />;
+ // Outside Processing is subcontracted to a supplier (creates a PO)
+ case "Outside Processing":
+ return <LuTruck className={cn("text-blue-500", className)} />;
+ default:
+ return <LuListChecks className={cn("text-foreground", className)} />;
+ }
+};
+
export const ReplenishmentSystemIcon = ({
type,
className
@@ -603,6 +631,10 @@ export const JournalEntrySourceTypeIcon = ({
return <LuCreditCard className={className} />;
case "Debit Memo":
return <LuCreditCard className={className} />;
+ case "Non-Conformance":
+ return <LuTriangleAlert className={className} />;
+ case "Inbound Inspection":
+ return <LuClipboardCheck className={className} />;
}
return <LuSquare className={cn("text-muted-foreground", className)} />;
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 038e6427e9..7f3cf14696 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -1,4 +1,10 @@
-import { cn, useDisclosure, VStack } from "@carbon/react";
+import {
+ cn,
+ ShortcutKey,
+ useDisclosure,
+ useShortcutKeys,
+ VStack
+} from "@carbon/react";
import {
closestCenter,
DndContext,
@@ -11,14 +17,21 @@ import {
SortableContext,
verticalListSortingStrategy
} from "@dnd-kit/sortable";
-import { Trans } from "@lingui/react/macro";
+import { Trans, useLingui } from "@lingui/react/macro";
import type { AnchorHTMLAttributes } from "react";
import { forwardRef, memo, useEffect } from "react";
-import { LuSettings2 } from "react-icons/lu";
+import { LuSearch, LuSettings2 } from "react-icons/lu";
import { Link, useMatches } from "react-router";
-import { useModules, useOptimisticLocation, useSettingsModule } from "~/hooks";
+import {
+ useModules,
+ useOptimisticLocation,
+ usePermissions,
+ useSettingsModule
+} from "~/hooks";
import { useImplementationNavItem } from "~/hooks/useImplementationNavItem";
+import { useUIStore } from "~/stores/ui";
import type { Authenticated, NavItem } from "~/types";
+import { SearchModal, searchShortcut } from "../Topbar/Search";
import { HiddenModulesPopover } from "./HiddenModulesPopover";
import { NavigationEditBar } from "./NavigationEditBar";
import { SortableNavItem } from "./SortableNavItem";
@@ -26,6 +39,7 @@ import { useNavigationEditMode } from "./useNavigationEditMode";
const PrimaryNavigation = () => {
const navigationPanel = useDisclosure();
+ const permissions = usePermissions();
const location = useOptimisticLocation();
const currentModule = getModule(location.pathname);
const links = useModules();
@@ -77,6 +91,9 @@ const PrimaryNavigation = () => {
className="flex flex-col justify-between h-full px-2"
>
<VStack spacing={1}>
+ {permissions.is("employee") && (
+ <NavigationSearchButton isOpen={isOpen} />
+ )}
{!editMode.isEditing && implementationNav ? (
<NavigationIconLink
link={implementationNav}
@@ -165,7 +182,6 @@ const PrimaryNavigation = () => {
"group-data-[state=collapsed]:justify-center",
"group-data-[state=expanded]:-space-x-2",
"font-medium shrink-0 inline-flex select-none",
- "text-muted-foreground",
"hover:bg-accent hover:text-accent-foreground",
"transition-[background-color,color,width] duration-100 ease-out",
"focus:!outline-none focus:!ring-0 active:!outline-none active:!ring-0",
@@ -192,6 +208,62 @@ const PrimaryNavigation = () => {
);
};
+const NavigationSearchButton = ({ isOpen = false }: { isOpen?: boolean }) => {
+ const { t } = useLingui();
+ const { openSearchModal } = useUIStore();
+
+ useShortcutKeys({
+ shortcut: searchShortcut,
+ action: openSearchModal
+ });
+
+ return (
+ <>
+ <button
+ type="button"
+ aria-label={t`Search`}
+ onClick={openSearchModal}
+ className={cn(
+ "relative",
+ "h-10 w-10 group-data-[state=expanded]:w-full",
+ "flex items-center rounded-md",
+ "group-data-[state=collapsed]:justify-center",
+ "group-data-[state=expanded]:-space-x-2",
+ "font-medium shrink-0 inline-flex select-none",
+ "hover:bg-accent hover:text-accent-foreground",
+ "transition-[background-color,color,width] duration-100 ease-out",
+ "focus:!outline-none focus:!ring-0 active:!outline-none active:!ring-0",
+ "after:pointer-events-none after:absolute after:-inset-[3px] after:rounded-lg after:border after:border-blue-500 after:opacity-0 after:ring-2 after:ring-blue-500/20 after:transition-opacity focus-visible:after:opacity-100 active:after:opacity-0",
+ "group/item"
+ )}
+ >
+ <LuSearch className="absolute left-3 top-3 flex items-center justify-center" />
+ <span
+ aria-hidden={isOpen || undefined}
+ className={cn(
+ "min-w-[128px] text-sm text-left",
+ "absolute left-7 group-data-[state=expanded]:left-12",
+ "opacity-0 group-data-[state=expanded]:opacity-100"
+ )}
+ >
+ <Trans>Search</Trans>
+ </span>
+ {/* ⌘K hint — only meaningful when expanded (the shortcut itself is wired
+ via useShortcutKeys above, same as the old topbar search). */}
+ <ShortcutKey
+ shortcut={searchShortcut}
+ variant="small"
+ className={cn(
+ "pointer-events-none absolute right-3 top-1/2 mx-0 -translate-y-1/2",
+ "opacity-0 transition-opacity duration-100 group-data-[state=expanded]:opacity-100"
+ )}
+ />
+ </button>
+ <SearchModal />
+ </>
+ );
+};
+
interface NavigationIconButtonProps
extends AnchorHTMLAttributes<HTMLAnchorElement> {
link: Authenticated<NavItem>;
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index 8bde32db55..ecd32dfdcc 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -585,8 +585,10 @@ const Notifications = () => {
isIcon
className="w-8 h-8 flex items-center relative"
>
- {hasUnseenNotifications && (
- <div className="w-2 h-2 bg-red-500 rounded-full absolute top-0 right-0" />
+ {unreadNotifications.length > 0 && (
+ <span className="absolute top-0 right-0 min-w-4 h-4 px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-medium leading-4 text-center tabular-nums">
+ {unreadNotifications.length}
+ </span>
)}
<LuBell size={16} />
</Button>
@@ -601,7 +603,7 @@ const Notifications = () => {
value={activeTab}
onValueChange={setActiveTab}
>
- <TabsList className="w-full border-b py-6 rounded-none bg-muted/50">
+ <TabsList className="w-full border-b py-2 rounded-none bg-muted/50">
<TabsTrigger value="inbox" className="font-normal">
<Trans>Inbox</Trans>
</TabsTrigger>
diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsx
index 5d1daedc96..eb81f24ff0 100644
--- a/apps/erp/app/components/Layout/Topbar/Search.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx
@@ -1,24 +1,20 @@
import type { ShortcutDefinition } from "@carbon/react";
import {
- Button,
Command,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
- HStack,
Modal,
ModalContent,
- ShortcutKey,
useDebounce,
- useShortcutKeys,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import idb from "localforage";
import { nanoid } from "nanoid";
-import { memo, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
import {
LuChevronRight,
LuCirclePlay,
@@ -26,7 +22,6 @@ import {
LuDraftingCompass,
LuFileCheck,
LuPackageSearch,
- LuSearch,
LuShieldX,
LuShoppingCart,
LuSquareUser,
@@ -69,12 +64,12 @@ type RecentSearch = Route & {
description?: string;
};
-const shortcut: ShortcutDefinition = {
+export const searchShortcut: ShortcutDefinition = {
key: "K",
modifiers: ["mod"]
};
-const SearchModal = () => {
+export const SearchModal = () => {
const { t } = useLingui();
const navigate = useNavigate();
const fetcher = useFetcher<SearchResponse>();
@@ -438,38 +433,6 @@ function ResultIcon({ entityType }: { entityType: string }) {
}
}
-const SearchButton = () => {
- const { openSearchModal } = useUIStore();
-
- useShortcutKeys({
- shortcut: shortcut,
- action: openSearchModal
- });
-
- return (
- <div>
- <Button
- leftIcon={<LuSearch />}
- variant="secondary"
- className="w-[200px] px-2 hover:scale-100"
- onClick={openSearchModal}
- >
- <HStack className="w-full">
- <div className="flex flex-grow">
- <Trans>Search</Trans>
- </div>
- <ShortcutKey
- variant="small"
- shortcut={shortcut}
- className="hidden sm:grid"
- />
- </HStack>
- </Button>
- <SearchModal />
- </div>
- );
-};
-
function useGroupedSubmodules() {
const modules = useModules();
const items = useItemsSubmodules();
@@ -549,5 +512,3 @@ function useGroupedSubmodules() {
return shortcuts;
}
-
-export default memo(SearchButton);
diff --git a/apps/erp/app/components/Layout/Topbar/Topbar.tsx b/apps/erp/app/components/Layout/Topbar/Topbar.tsx
index 707a3da192..b817fa3585 100644
--- a/apps/erp/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Topbar.tsx
@@ -1,33 +1,28 @@
import { HStack, IconButton } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { LuSquarePen } from "react-icons/lu";
-import { usePermissions, useUser } from "~/hooks";
+import { useUser } from "~/hooks";
import AvatarMenu from "../../AvatarMenu";
import AskDocs from "./AskDocs";
import Breadcrumbs from "./Breadcrumbs";
import CompanySwitcher from "./CompanySwitcher";
import CreateMenu from "./CreateMenu";
import Notifications from "./Notifications";
-import Search from "./Search";
import Suggestion from "./Suggestion";
const Topbar = () => {
const { t } = useLingui();
- const permissions = usePermissions();
const user = useUser();
const notificationsKey = `${user.id}:${user.company.id}`;
return (
- <div className="h-[49px] grid grid-cols-[1fr_200px_1fr] bg-background text-foreground px-4 top-0 sticky z-10 items-center">
+ <div className="h-[49px] grid grid-cols-[1fr_auto] bg-background text-foreground px-4 top-0 sticky z-10 items-center">
<div className="flex-1 hidden md:block">
<Breadcrumbs />
</div>
<div className="flex-1 md:hidden">
<CompanySwitcher />
</div>
- <div className="flex justify-center">
- {permissions.is("employee") ? <Search /> : <div />}
- </div>
<HStack spacing={1} className="flex-1 justify-end py-2">
<div className="hidden sm:block">
<AskDocs />
diff --git a/apps/erp/app/components/SlideAnnotator.tsx b/apps/erp/app/components/SlideAnnotator.tsx
new file mode 100644
index 0000000000..a639dba241
--- /dev/null
+++ b/apps/erp/app/components/SlideAnnotator.tsx
@@ -0,0 +1,242 @@
+import {
+ Button,
+ cn,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle
+} from "@carbon/react";
+import { nanoid } from "nanoid";
+import { useEffect, useRef, useState } from "react";
+import { LuTrash2 } from "react-icons/lu";
+import type { SlideAnnotation } from "~/modules/shared";
+
+// Fixed pin palette — a handful of high-contrast colors that read on any photo. Stored as
+// hex on the annotation so the MES overlay renders identically without a theme lookup.
+const PIN_COLORS = [
+ "#ef4444", // red
+ "#f59e0b", // amber
+ "#22c55e", // green
+ "#3b82f6", // blue
+ "#a855f7" // violet
+] as const;
+
+const clamp01 = (n: number) => Math.min(1, Math.max(0, n));
+
+/**
+ * Modal image annotator for a step reference slide. Click the image to drop a numbered pin,
+ * drag a pin to reposition, edit its label/color, or delete it. Coordinates are stored as
+ * fractions (0..1) of the image box so pins survive any rendered size. Save hands the full
+ * pin array back to the caller, which persists it via the slide route.
+ */
+export function SlideAnnotator({
+ open,
+ imageUrl,
+ initial,
+ onSave,
+ onClose
+}: {
+ open: boolean;
+ imageUrl: string;
+ initial: SlideAnnotation[];
+ onSave: (annotations: SlideAnnotation[]) => void;
+ onClose: () => void;
+}) {
+ const [pins, setPins] = useState<SlideAnnotation[]>(initial);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ // The pin currently being dragged, and a flag that suppresses the click fired right after
+ // a drag so releasing a pin over the image doesn't also drop a new pin.
+ const drag = useRef<{ id: string; moved: boolean } | null>(null);
+ const justDragged = useRef(false);
+
+ // Reseed from the source every time the annotator opens for a slide.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset on open only
+ useEffect(() => {
+ if (open) {
+ setPins(initial);
+ setSelectedId(null);
+ }
+ }, [open]);
+
+ const selected = pins.find((p) => p.id === selectedId) ?? null;
+
+ const toFraction = (clientX: number, clientY: number) => {
+ const rect = wrapperRef.current?.getBoundingClientRect();
+ if (!rect || rect.width === 0 || rect.height === 0) return null;
+ return {
+ x: clamp01((clientX - rect.left) / rect.width),
+ y: clamp01((clientY - rect.top) / rect.height)
+ };
+ };
+
+ const addPin = (e: React.MouseEvent) => {
+ // Ignore the click that ends a drag.
+ if (justDragged.current) {
+ justDragged.current = false;
+ return;
+ }
+ const point = toFraction(e.clientX, e.clientY);
+ if (!point) return;
+ const pin: SlideAnnotation = {
+ id: nanoid(),
+ x: point.x,
+ y: point.y,
+ color: PIN_COLORS[0]
+ };
+ setPins((prev) => [...prev, pin]);
+ setSelectedId(pin.id);
+ };
+
+ const onPointerMove = (e: React.PointerEvent) => {
+ if (!drag.current) return;
+ const point = toFraction(e.clientX, e.clientY);
+ if (!point) return;
+ drag.current.moved = true;
+ const id = drag.current.id;
+ setPins((prev) =>
+ prev.map((p) => (p.id === id ? { ...p, x: point.x, y: point.y } : p))
+ );
+ };
+
+ const endDrag = () => {
+ if (drag.current?.moved) justDragged.current = true;
+ drag.current = null;
+ };
+
+ const updateSelected = (patch: Partial<SlideAnnotation>) => {
+ if (!selected) return;
+ setPins((prev) =>
+ prev.map((p) => (p.id === selected.id ? { ...p, ...patch } : p))
+ );
+ };
+
+ const deleteSelected = () => {
+ if (!selected) return;
+ setPins((prev) => prev.filter((p) => p.id !== selected.id));
+ setSelectedId(null);
+ };
+
+ return (
+ <Modal
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ >
+ <ModalContent size="xxlarge">
+ <ModalHeader>
+ <ModalTitle>Annotate image</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-4 lg:flex-row">
+ <div className="flex flex-1 items-center justify-center">
+ <div
+ ref={wrapperRef}
+ className="relative inline-block cursor-crosshair select-none"
+ onClick={addPin}
+ onPointerMove={onPointerMove}
+ onPointerUp={endDrag}
+ onPointerCancel={endDrag}
+ >
+ <img
+ src={imageUrl}
+ alt="Slide"
+ draggable={false}
+ className="block max-h-[65vh] w-auto max-w-full rounded-md"
+ />
+ {pins.map((pin, index) => (
+ <button
+ key={pin.id}
+ type="button"
+ aria-label={pin.label || `Pin ${index + 1}`}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ (e.target as Element).setPointerCapture?.(e.pointerId);
+ drag.current = { id: pin.id, moved: false };
+ setSelectedId(pin.id);
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className={cn(
+ "absolute flex size-7 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border-2 text-xs font-semibold text-white shadow-md",
+ "cursor-grab active:cursor-grabbing",
+ selectedId === pin.id
+ ? "border-white ring-2 ring-white/60"
+ : "border-white/70"
+ )}
+ style={{
+ left: `${pin.x * 100}%`,
+ top: `${pin.y * 100}%`,
+ backgroundColor: pin.color ?? PIN_COLORS[0]
+ }}
+ >
+ {index + 1}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex w-full flex-col gap-3 lg:w-64">
+ <p className="text-xs text-muted-foreground">
+ {pins.length === 0
+ ? "Click the image to add a numbered pin."
+ : `${pins.length} pin${pins.length === 1 ? "" : "s"} · click a pin to edit`}
+ </p>
+
+ {selected ? (
+ <div className="flex flex-col gap-3 rounded-lg border p-3">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">
+ Pin {pins.findIndex((p) => p.id === selected.id) + 1}
+ </span>
+ <IconButton
+ aria-label="Delete pin"
+ icon={<LuTrash2 />}
+ variant="ghost"
+ size="sm"
+ onClick={deleteSelected}
+ />
+ </div>
+ <input
+ type="text"
+ aria-label="Pin label"
+ placeholder="Label (optional)"
+ value={selected.label ?? ""}
+ onChange={(e) => updateSelected({ label: e.target.value })}
+ className="w-full rounded-md border bg-transparent px-2 py-1 text-sm"
+ />
+ <div className="flex items-center gap-2">
+ {PIN_COLORS.map((color) => (
+ <button
+ key={color}
+ type="button"
+ aria-label={`Color ${color}`}
+ onClick={() => updateSelected({ color })}
+ className={cn(
+ "size-6 rounded-full border-2 transition-transform active:scale-[0.9]",
+ (selected.color ?? PIN_COLORS[0]) === color
+ ? "border-foreground"
+ : "border-transparent"
+ )}
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button onClick={() => onSave(pins)}>Save</Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/components/SlidesEditor.tsx b/apps/erp/app/components/SlidesEditor.tsx
new file mode 100644
index 0000000000..9ea90a2708
--- /dev/null
+++ b/apps/erp/app/components/SlidesEditor.tsx
@@ -0,0 +1,350 @@
+import { useCarbon } from "@carbon/auth";
+import type { Database } from "@carbon/database";
+import { Button, cn, IconButton, Label, VStack } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
+import { useLingui } from "@lingui/react/macro";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { nanoid } from "nanoid";
+import { useEffect, useMemo, useState } from "react";
+import { LuBox, LuCirclePlus, LuMapPin, LuX } from "react-icons/lu";
+import type { SlideAnnotation, SlideSize } from "~/modules/shared";
+import { getPrivateUrl, path } from "~/utils/path";
+import { SlideAnnotator } from "./SlideAnnotator";
+
+// Single fixed slide card size — slides are no longer individually resizable.
+const SLIDE_CARD_WIDTH = "w-40";
+const SLIDE_IMAGE_HEIGHT = "h-28";
+
+// File-input accept for 3D model slides — everything the ModelViewer can parse
+// client-side (STEP additionally gets converted to GLB by the assembler service).
+export const MODEL_FILE_ACCEPT = supportedModelTypes
+ .map((type) => `.${type}`)
+ .join(",");
+
+// Upload a 3D model file for a step slide: the raw file goes to the private bucket
+// under the models prefix, then the model-upload API registers the modelUpload row —
+// `convert` also starts the assembler's STEP → GLB conversion (best-effort, so the
+// slide still works via client-side parsing when the assembler is unavailable).
+// Returns the new modelUpload id, or null on failure.
+export async function uploadStepSlideModel(
+ carbon: SupabaseClient<Database>,
+ companyId: string,
+ file: File
+): Promise<string | null> {
+ const modelUploadId = nanoid();
+ const ext = file.name.split(".").pop();
+ const upload = await carbon.storage
+ .from("private")
+ .upload(`${companyId}/models/${modelUploadId}.${ext}`, file, {
+ upsert: true
+ });
+ if (upload.error || !upload.data) return null;
+
+ const formData = new FormData();
+ formData.append("name", file.name);
+ formData.append("modelId", modelUploadId);
+ formData.append("modelPath", upload.data.path);
+ formData.append("size", String(file.size));
+ formData.append("convert", "true");
+
+ const response = await fetch(path.to.api.modelUpload, {
+ method: "POST",
+ body: formData
+ });
+ if (!response.ok) return null;
+ return modelUploadId;
+}
+
+export type EditorSlide = {
+ key: string;
+ // A slide is image XOR model: exactly one of imagePath / modelUploadId is set.
+ imagePath: string | null;
+ modelUploadId?: string | null;
+ caption: string | null;
+ size: SlideSize | null;
+ annotations: SlideAnnotation[] | null;
+};
+
+type SlideModelMeta = {
+ id: string;
+ name: string | null;
+ thumbnailPath: string | null;
+ processingStatus: string | null;
+};
+
+// Display metadata for the model slides (name, thumbnail, conversion status), fetched
+// client-side so the editors don't have to thread a modelUpload join through their
+// loaders. Re-polls while a STEP → GLB conversion is in flight so the "Converting…"
+// badge resolves without a reload.
+function useSlideModels(slides: EditorSlide[]) {
+ const { carbon } = useCarbon();
+ const [models, setModels] = useState<Record<string, SlideModelMeta>>({});
+
+ const idsKey = useMemo(
+ () =>
+ Array.from(
+ new Set(
+ slides
+ .map((slide) => slide.modelUploadId)
+ .filter((id): id is string => !!id)
+ )
+ )
+ .sort()
+ .join(","),
+ [slides]
+ );
+
+ const hasPending = Object.values(models).some(
+ (model) =>
+ model.processingStatus === "Queued" ||
+ model.processingStatus === "Processing"
+ );
+
+ useEffect(() => {
+ if (!carbon || !idsKey) {
+ setModels({});
+ return;
+ }
+ let cancelled = false;
+ const load = async () => {
+ const { data } = await carbon
+ .from("modelUpload")
+ .select("id, name, thumbnailPath, processingStatus")
+ .in("id", idsKey.split(","));
+ if (cancelled || !data) return;
+ setModels(Object.fromEntries(data.map((model) => [model.id, model])));
+ };
+ load();
+ const interval = hasPending ? setInterval(load, 8000) : undefined;
+ return () => {
+ cancelled = true;
+ if (interval) clearInterval(interval);
+ };
+ }, [carbon, idsKey, hasPending]);
+
+ return models;
+}
+
+// Presentational slides grid — header + "Add slide" / "Add model" + cards. An image
+// slide shows the picture with its numbered pins; a model slide shows the 3D model's
+// thumbnail (or a placeholder) with a 3D badge — pins are image-only. Shared by the
+// create form (draft buffer, attached after the step is saved) and the edit form
+// (persisted immediately via the slide routes). Used by both the item method editor
+// (BillOfProcess) and the job editor (JobBillOfProcess). See
+// .ai/specs/2026-07-14-mes-execution-views.md §4.
+export function SlidesEditor({
+ slides,
+ isDisabled,
+ busy,
+ fileInputRef,
+ onFileChange,
+ modelInputRef,
+ onModelFileChange,
+ onRemove,
+ onCaptionBlur,
+ onAnnotationsChange
+}: {
+ slides: EditorSlide[];
+ isDisabled: boolean;
+ busy: boolean;
+ fileInputRef: React.RefObject<HTMLInputElement>;
+ onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ // Optional 3D-model upload wiring; when absent the editor is image-only.
+ modelInputRef?: React.RefObject<HTMLInputElement>;
+ onModelFileChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ onRemove: (index: number) => void;
+ onCaptionBlur: (index: number, caption: string) => void;
+ onAnnotationsChange: (index: number, annotations: SlideAnnotation[]) => void;
+}) {
+ const { t } = useLingui();
+ const [annotatingIndex, setAnnotatingIndex] = useState<number | null>(null);
+ const annotating = annotatingIndex == null ? null : slides[annotatingIndex];
+ const models = useSlideModels(slides);
+
+ if (isDisabled && slides.length === 0) return null;
+
+ const withModels = !!modelInputRef && !!onModelFileChange;
+
+ return (
+ <VStack spacing={2} className="w-full col-span-2 border-t pt-4">
+ <div className="flex w-full items-center justify-between">
+ <Label className="text-xs text-muted-foreground">Slides</Label>
+ {!isDisabled && (
+ <div className="flex items-center gap-2">
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ onChange={onFileChange}
+ />
+ {withModels && (
+ <input
+ ref={modelInputRef}
+ type="file"
+ accept={MODEL_FILE_ACCEPT}
+ className="hidden"
+ onChange={onModelFileChange}
+ />
+ )}
+ <Button
+ variant="secondary"
+ size="sm"
+ leftIcon={<LuCirclePlus />}
+ isLoading={busy}
+ isDisabled={busy}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ Add slide
+ </Button>
+ {withModels && (
+ <Button
+ variant="secondary"
+ size="sm"
+ leftIcon={<LuBox />}
+ isLoading={busy}
+ isDisabled={busy}
+ onClick={() => modelInputRef?.current?.click()}
+ >
+ Add model
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ {slides.length === 0 ? (
+ <p className="w-full text-xs text-muted-foreground">No slides</p>
+ ) : (
+ <div className="flex w-full flex-wrap items-start gap-3">
+ {slides.map((slide, index) => {
+ const pins = slide.annotations ?? [];
+ const model = slide.modelUploadId
+ ? models[slide.modelUploadId]
+ : undefined;
+ const converting =
+ model?.processingStatus === "Queued" ||
+ model?.processingStatus === "Processing";
+ return (
+ <div
+ key={slide.key}
+ className={cn(
+ "flex flex-col gap-1 rounded-lg border p-2",
+ SLIDE_CARD_WIDTH
+ )}
+ >
+ <div className="relative">
+ {slide.modelUploadId ? (
+ <div
+ className={cn(
+ "flex w-full items-center justify-center rounded-md bg-muted/40",
+ SLIDE_IMAGE_HEIGHT
+ )}
+ >
+ {model?.thumbnailPath ? (
+ <img
+ src={getPrivateUrl(model.thumbnailPath)}
+ alt={slide.caption ?? model?.name ?? "3D model"}
+ className="h-full w-full rounded-md object-contain"
+ />
+ ) : (
+ <LuBox className="size-8 text-muted-foreground" />
+ )}
+ <span className="pointer-events-none absolute left-1 top-1 rounded bg-muted px-1 text-[9px] font-semibold text-muted-foreground">
+ 3D
+ </span>
+ {converting && (
+ <span className="pointer-events-none absolute bottom-1 left-1 rounded bg-muted px-1 text-[9px] text-muted-foreground">
+ {t`Converting…`}
+ </span>
+ )}
+ </div>
+ ) : (
+ <>
+ <img
+ src={
+ slide.imagePath ? getPrivateUrl(slide.imagePath) : ""
+ }
+ alt={slide.caption ?? "Slide"}
+ className={cn(
+ "w-full rounded-md bg-muted/40 object-contain",
+ SLIDE_IMAGE_HEIGHT
+ )}
+ />
+ {/* Read-only pin preview so an annotated slide reads at a glance. */}
+ {pins.map((pin, i) => (
+ <span
+ key={pin.id}
+ className="pointer-events-none absolute flex size-4 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border border-white text-[8px] font-semibold text-white shadow"
+ style={{
+ left: `${pin.x * 100}%`,
+ top: `${pin.y * 100}%`,
+ backgroundColor: pin.color ?? "#ef4444"
+ }}
+ >
+ {i + 1}
+ </span>
+ ))}
+ </>
+ )}
+ {!isDisabled && (
+ <IconButton
+ aria-label={t`Remove slide`}
+ icon={<LuX />}
+ variant="secondary"
+ size="sm"
+ className="absolute right-1 top-1"
+ onClick={() => onRemove(index)}
+ />
+ )}
+ </div>
+ {slide.modelUploadId && model?.name && (
+ <p
+ className="w-full truncate text-[10px] text-muted-foreground"
+ title={model.name}
+ >
+ {model.name}
+ </p>
+ )}
+ {!isDisabled && !slide.modelUploadId && (
+ <div className="flex items-center justify-end gap-1">
+ <Button
+ variant="secondary"
+ size="sm"
+ className="h-6 px-2 text-[10px]"
+ leftIcon={<LuMapPin className="size-3" />}
+ onClick={() => setAnnotatingIndex(index)}
+ >
+ {pins.length > 0 ? pins.length : t`Pin`}
+ </Button>
+ </div>
+ )}
+ <input
+ type="text"
+ aria-label={t`Caption`}
+ placeholder={t`Caption`}
+ defaultValue={slide.caption ?? ""}
+ disabled={isDisabled}
+ onBlur={(e) => onCaptionBlur(index, e.target.value)}
+ className="w-full rounded-md border bg-transparent px-2 py-1 text-xs"
+ />
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {annotating?.imagePath && annotatingIndex != null && (
+ <SlideAnnotator
+ open
+ imageUrl={getPrivateUrl(annotating.imagePath)}
+ initial={annotating.annotations ?? []}
+ onSave={(next) => {
+ onAnnotationsChange(annotatingIndex, next);
+ setAnnotatingIndex(null);
+ }}
+ onClose={() => setAnnotatingIndex(null)}
+ />
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/components/StepLinkEditor.tsx b/apps/erp/app/components/StepLinkEditor.tsx
new file mode 100644
index 0000000000..407c77060b
--- /dev/null
+++ b/apps/erp/app/components/StepLinkEditor.tsx
@@ -0,0 +1,159 @@
+import {
+ Button,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ IconButton,
+ Label,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ VStack
+} from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { useState } from "react";
+import { LuCirclePlus, LuX } from "react-icons/lu";
+
+export type StepLinkItem = {
+ id: string;
+ name: string;
+ // Optional muted second line (e.g. a tool's descriptive name under its id).
+ secondary?: string;
+ quantity: number;
+};
+
+// Step-side link picker: assign an operation's BOM parts OR tools to a step (the inverse of the
+// old BOM/tool "Steps" picker). Presentational — the caller owns the linked set and persists
+// changes (immediately via a route for saved steps, or a draft buffer for a step being created).
+// Generic over the noun so both the Parts and Tools sections share one searchable combobox + list.
+// Used by the item method editor (BillOfProcess) and the job editor (JobBillOfProcess).
+export function StepLinkEditor({
+ label,
+ addLabel,
+ emptyLabel,
+ searchPlaceholder,
+ removeLabel,
+ icon,
+ items,
+ linkedIds,
+ isDisabled,
+ busy,
+ onAdd,
+ onRemove
+}: {
+ label: string;
+ addLabel: string;
+ emptyLabel: string;
+ searchPlaceholder: string;
+ removeLabel: string;
+ // Leading glyph for the trigger button (defaults to a plus).
+ icon?: JSX.Element;
+ items: StepLinkItem[];
+ linkedIds: string[];
+ isDisabled: boolean;
+ busy?: boolean;
+ onAdd: (id: string) => void;
+ onRemove: (id: string) => void;
+}) {
+ const { t } = useLingui();
+ const [open, setOpen] = useState(false);
+
+ const linkedSet = new Set(linkedIds);
+ const linked = items.filter((p) => linkedSet.has(p.id));
+ const available = items.filter((p) => !linkedSet.has(p.id));
+
+ if (isDisabled && linked.length === 0) return null;
+
+ return (
+ <VStack spacing={2} className="w-full col-span-2 border-t pt-4">
+ <div className="flex w-full items-center justify-between">
+ <Label className="text-xs text-muted-foreground">{label}</Label>
+ {!isDisabled && (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="secondary"
+ size="sm"
+ leftIcon={icon ?? <LuCirclePlus />}
+ isLoading={busy}
+ isDisabled={busy || available.length === 0}
+ >
+ {addLabel}
+ </Button>
+ </PopoverTrigger>
+ {/* A searchable combobox (vs a plain dropdown) so 30-50 parts/tools stay usable.
+ Stays open after each pick so several can be added in a row. */}
+ <PopoverContent
+ align="end"
+ className="w-[280px] p-0"
+ onWheel={(e) => e.stopPropagation()}
+ onTouchMove={(e) => e.stopPropagation()}
+ >
+ <Command>
+ <CommandInput placeholder={searchPlaceholder} />
+ <CommandList>
+ <CommandEmpty>{t`No results`}</CommandEmpty>
+ <CommandGroup>
+ {available.map((item) => (
+ <CommandItem
+ key={item.id}
+ value={`${item.name} ${item.secondary ?? ""} ${item.id}`}
+ onSelect={() => onAdd(item.id)}
+ className="flex items-center justify-between gap-4"
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {item.name}
+ </span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ ×{item.quantity}
+ </span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ {linked.length === 0 ? (
+ <p className="w-full text-xs text-muted-foreground">{emptyLabel}</p>
+ ) : (
+ <div className="flex w-full flex-col gap-2">
+ {linked.map((item) => (
+ <div
+ key={item.id}
+ className="flex items-center gap-3 rounded-lg border px-3 py-2"
+ >
+ <span className="size-2 shrink-0 rounded-full bg-muted-foreground/40" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm">{item.name}</span>
+ {item.secondary && (
+ <span className="truncate text-xs text-muted-foreground">
+ {item.secondary}
+ </span>
+ )}
+ </div>
+ <span className="shrink-0 rounded-md border px-2 py-0.5 text-xs text-muted-foreground">
+ ×{item.quantity}
+ </span>
+ {!isDisabled && (
+ <IconButton
+ aria-label={removeLabel}
+ icon={<LuX />}
+ variant="secondary"
+ size="sm"
+ isDisabled={busy}
+ onClick={() => onRemove(item.id)}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index 0010297b09..602d80f7b4 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -1120,7 +1120,13 @@ const Table = <T extends object>({
(sortable ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <div className="group flex justify-start items-center gap-2">
+ <div
+ className={cn(
+ "group flex items-center gap-2",
+ header.column.columnDef.meta
+ ?.headerClassName ?? "justify-start"
+ )}
+ >
{header.column.columnDef.meta?.icon}
{typeof header.column.columnDef.header ===
"string"
@@ -1181,7 +1187,13 @@ const Table = <T extends object>({
</DropdownMenuContent>
</DropdownMenu>
) : (
- <div className="flex justify-start items-center gap-2">
+ <div
+ className={cn(
+ "flex items-center gap-2",
+ header.column.columnDef.meta
+ ?.headerClassName ?? "justify-start"
+ )}
+ >
{header.column.columnDef.meta?.icon}
{typeof header.column.columnDef.header ===
"string"
diff --git a/apps/erp/app/components/Table/types.ts b/apps/erp/app/components/Table/types.ts
index a0218abee2..6caa58508b 100644
--- a/apps/erp/app/components/Table/types.ts
+++ b/apps/erp/app/components/Table/types.ts
@@ -9,6 +9,9 @@ declare module "@tanstack/react-table" {
// Filter dropdown/chip label when `header` is JSX instead of a string.
filterHeader?: string;
pluralHeader?: string;
+ // Extra classes for the header content wrapper (e.g. "justify-center" to
+ // center a header). Defaults to left-aligned (`justify-start`).
+ headerClassName?: string;
icon?: ReactElement;
renderTotal?: boolean;
formatter?: (
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index 0e55f6a9ce..2fad30b19b 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -23,6 +23,7 @@ import {
MethodItemTypeIcon,
ModuleIcon,
OperationStatusIcon,
+ OperationTypeIcon,
SourcingTypeIcon,
TimeTypeIcon,
TrackingTypeIcon
@@ -71,6 +72,7 @@ export {
ModuleIcon,
New,
OperationStatusIcon,
+ OperationTypeIcon,
PeriodSelector,
PrintButton,
RealtimeDataProvider,
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index 6e526e5681..25ffc30ac7 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -297,6 +297,7 @@ export const defaultIncomeAcountValidator = z.object({
inventoryAdjustmentVarianceAccount: z.string().min(1, {
message: "Inventory adjustment variance account is required"
}),
+ scrapAccount: z.string().optional(),
materialVarianceAccount: z.string().min(1, {
message: "Material usage variance account is required"
}),
@@ -483,7 +484,9 @@ export const journalEntrySourceTypes = [
"Asset Disposal",
"Payment",
"Credit Memo",
- "Debit Memo"
+ "Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection"
] as const;
export const journalEntryStatuses = ["Draft", "Posted", "Reversed"] as const;
diff --git a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
index 43966625cf..765c96ef7f 100644
--- a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx
@@ -356,6 +356,12 @@ const AccountDefaultsForm = ({
badgeType: "Expense",
termId: "account-default-inventory-adjustment"
},
+ {
+ name: "scrapAccount",
+ label: t`Scrap / Cost of Quality`,
+ description: t`Write-off of stock scrapped or returned via inspection rejects and NCR dispositions`,
+ badgeType: "Expense"
+ },
{
name: "materialVarianceAccount",
label: t`Material Usage Variance`,
diff --git a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx
index f3cc442059..1e48b7c1eb 100644
--- a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx
@@ -122,7 +122,7 @@ const DimensionForm = ({ initialValues, onClose }: DimensionFormProps) => {
termId="dimension-values"
/>
)}
- <Boolean name="active" label={t`Active`} />
+ <Boolean name="active" label={t`Active`} bordered />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/jobs.md b/apps/erp/app/modules/agent/kb/docs/reference/jobs.md
index ba6f5f15ae..7fac0e6f18 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/jobs.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/jobs.md
@@ -50,11 +50,11 @@ The job's routing is copied into job-specific **operations** on release, each a
- **Done**: Finished. Completing it closes any open events and promotes downstream operations whose dependencies are now all done.
- **Canceled**: Won't run.
-### Inside and outside
+### Operation type
-Each operation is **Inside** or **Outside**. An Inside operation runs on one of your work centers and prices against its rates. An **outside** operation is subcontracted: instead of a work center it points at a supplier process, copies that supplier's cost and lead time, and drives an outside-processing purchase order.
+Each operation carries an operation type: **Process**, **Assembly**, **Inspection**, or **Outside Processing**. The first three run in-house on one of your work centers and price against its rates, and the type decides which execution view the operator sees on the shop floor. A plain **Process** operation runs the standard operation view. An **Assembly** operation opens a guided, step-by-step build view: 3D animated work instructions play each step's insertion motion, with the parts, tools, and reference images scoped to the step in front of the operator. An **Inspection** operation runs a quality check, recording measured features against a ballooned drawing (the same execution screen the quality module uses for received goods). An **Outside Processing** operation is subcontracted: instead of a work center it points at a supplier process, copies that supplier's cost and lead time, and drives an outside-processing purchase order. The process you pick carries the same type and defaults it on new operations.
-An outside operation's cost and lead time are copied when you set the supplier process, not linked live. If the supplier's pricing changes, re-select the supplier process to refresh it.
+An Outside Processing operation's cost and lead time are copied when you set the supplier process, not linked live. If the supplier's pricing changes, re-select the supplier process to refresh it.
### Sequencing
@@ -66,7 +66,7 @@ The floor reports two separate things against an operation. A production event m
### Procedures
-Each operation can attach a procedure: a reusable set of work instructions keyed to a process. A procedure carries an ordered list of typed **steps** the operator completes (a value, a measurement with a min/max range, a checkbox, a list choice, a timestamp, a person, or a file), any of which can be marked required. It also carries **parameters**, the process settings the work runs at, such as a temperature or speed. Separately, the operation lists the **tools** it requires.
+Each operation can attach a procedure: a reusable set of work instructions keyed to a process. A procedure carries an ordered list of typed **steps** the operator completes (a value, a measurement with a min/max range, a checkbox, a list choice, a timestamp, a person, or a file), any of which can be marked required. It also carries **parameters**, the process settings the work runs at, such as a temperature or speed. Separately, the operation lists the **tools** it requires. A material or tool can be assigned to a single step, or left to apply across the whole operation — so an assembly view shows the operator exactly the parts and tools each step needs as they advance.
Because a procedure is keyed by process, you author it once and every operation running that process can attach it. It's versioned, moving through **Draft** while it's written, **Active** once ready for live work, and **Archived** when retired.
@@ -100,4 +100,4 @@ Creating the job needs a location and the company has none (or no default). Add
Completing the job to inventory referenced a serial or batch that no longer exists — usually consumed or deleted since the job's output was recorded. Re-check the job's tracked outputs and materials before completing again.
### "Failed to schedule job"
-The scheduling engine errored while placing the job's operations. Check that every operation has a work center (inside operations) or supplier process (outside operations) and that the job has a due date, then retry from the job's status menu.
+The scheduling engine errored while placing the job's operations. Check that every operation has a work center (in-house Process, Assembly, and Inspection operations) or a supplier process (Outside Processing operations) and that the job has a due date, then retry from the job's status menu.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/quality.md b/apps/erp/app/modules/agent/kb/docs/reference/quality.md
index 4d604fc821..4ab84578f7 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/quality.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/quality.md
@@ -14,6 +14,8 @@ Issues open from several places: by hand, from the shop floor in MES, from Slack
An issue can run a configurable workflow, often an **8D**. The workflow attaches **required actions** and **approvals** as tasks; each task advances *Pending → In Progress → Completed* as the team works it. Adding a **Material Review Board** approval gates closing the issue: it can't close until a **disposition** is chosen for the affected material. The five options are *Pending* (not yet decided), *Return to Supplier*, *Rework*, *Scrap*, and *Use As Is*.
+When accounting is enabled, closing the issue posts each disposition's stock movement to the general ledger. *Scrap* and *Return to Supplier* write the material off — relieving its inventory cost layers and posting **debit Scrap / Cost of Quality, credit Inventory** — so scrapped and returned value lands on a dedicated cost-of-quality account rather than distorting on-hand inventory. *Use As Is* and *Rework* keep the material as stock, restoring any value an earlier rejection had written off. Once an issue has posted these entries it can no longer be reopened; a correction is booked forward as a new adjustment, never by unwinding the original.
+
There's no dedicated supplier scorecard in Carbon. **Supplier quality is a derived metric**, counted from the issues linked to each supplier. The data comes from the issues themselves, not a separate record.
## Inbound inspection
@@ -24,9 +26,13 @@ An inspection moves through **Pending**, **In Progress**, and one of three outco
Inbound inspection only fires on **purchase-order receipts** of items flagged to require it. Until a lot is dispositioned, its units sit On Hold: received, but not yet stock you can sell or consume.
+### Executing an inspection
+
+Whatever raised it, an inspection is worked on one screen: a features × samples grid laid over the item's ballooned drawing. Each column is a sample (scanned serials and batches label their own column); each row is a feature to measure, recording a value or a pass/fail. Sample and lot status are derived from those readings against tolerance. The same screen serves an inbound lot held off a receipt and an in-house **Inspection** job operation — an Inspection operation resolves the part's inspection document and runs this grid on the shop floor.
+
## Also in quality
-The module also covers `docs/reference/calibration` (with calibration-due tracking), **controlled documents** (versioned procedures and work instructions, with one active version at a time), **inspection documents** (ballooned FAI drawings and their characteristics), and a **risk register**.
+The module also covers `docs/reference/calibration` (with calibration-due tracking), **controlled documents** (versioned procedures and work instructions, with one active version at a time), **inspection documents** (ballooned FAI drawings and their features), and a **risk register**.
## Related
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index 4b1c6e0916..f98b4ec5d5 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -785,7 +785,7 @@
"Fields",
"Status lifecycle",
"Operations",
- "Inside and outside",
+ "Operation type",
"Sequencing",
"Time and output",
"Procedures",
@@ -1160,6 +1160,7 @@
"Issues",
"Workflows and actions",
"Inbound inspection",
+ "Executing an inspection",
"Also in quality",
"Related",
"Troubleshooting",
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index 469d58965f..bd2594491f 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -83,7 +83,7 @@ import { inventoryAdjustmentValidator, receiptValidator } from "~/modules/invent
- **production** — job completion posts finished goods; materials issued from inventory
- **items** — `itemTrackingType` (Inventory/Serial/Batch/Non-Inventory) determines tracking behavior
- **sales** — shipments fulfill sales order lines
-- **quality** — inbound inspections triggered on receipt for items with `requiresInspection`
+- **quality** — inbound inspections triggered on receipt for items with a Receipt-usage inspection-document assignment
## Rules References
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
index f6b9b31acf..34eaa6bc33 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
@@ -92,6 +92,7 @@ const InventoryCountForm = ({
name="isBlind"
label={t`Blind Count`}
description={t`Hide system quantities until the review step`}
+ bordered
/>
<TextArea name="notes" label={t`Notes`} />
</VStack>
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
index 3aa273a00b..230889cde8 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -4,15 +4,21 @@ import {
Card,
CardContent,
CardFooter,
+ DropdownMenu,
+ DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ HStack,
useDisclosure,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import {
LuCheckCheck,
+ LuChevronDown,
+ LuClipboardCheck,
LuCreditCard,
LuShoppingCart,
LuTicketX,
@@ -47,6 +53,7 @@ import {
receiptSourceDocumentType,
receiptValidator
} from "~/modules/inventory";
+import { InspectionStatus } from "~/modules/quality/ui/Inspections/InspectionStatus";
import { path } from "~/utils/path";
import useReceiptForm from "./useReceiptForm";
@@ -69,6 +76,7 @@ const ReceiptForm = ({
const routeData = useRouteData<{
receipt: Receipt;
receiptLineTracking: ItemTracking[];
+ receiptInspections: ReceiptInspection[];
fixedAssetLines: { id: string; received: boolean }[];
}>(path.to.receipt(receiptId));
@@ -193,6 +201,9 @@ const ReceiptForm = ({
routeData?.receipt?.sourceDocumentReadableId ?? undefined
}
/>
+ <InspectionsLink
+ inspections={routeData?.receiptInspections ?? []}
+ />
<Button
variant={canInvoice ? "primary" : "secondary"}
isDisabled={!canInvoice || isInvoicing}
@@ -359,4 +370,66 @@ function SourceDocumentLink({
}
}
+type ReceiptInspection = {
+ id: string;
+ inspectionId: string;
+ itemId: string | null;
+ itemReadableId: string | null;
+ status: string;
+};
+
+// Link the receipt header to the inspection lots created on posting (one per
+// inspected line). A single lot renders a button; multiple render a dropdown —
+// mirrors the sales order header's Invoices link.
+function InspectionsLink({
+ inspections
+}: {
+ inspections: ReceiptInspection[];
+}) {
+ const permissions = usePermissions();
+
+ if (!permissions.can("view", "quality") || inspections.length === 0)
+ return null;
+
+ if (inspections.length === 1) {
+ const inspection = inspections[0];
+ return (
+ <Button variant="secondary" leftIcon={<LuClipboardCheck />} asChild>
+ <Link to={path.to.inspection(inspection.id)}>
+ <Trans>Inspection</Trans>
+ </Link>
+ </Button>
+ );
+ }
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ leftIcon={<LuClipboardCheck />}
+ rightIcon={<LuChevronDown />}
+ >
+ <Trans>Inspections</Trans>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {inspections.map((inspection) => (
+ <DropdownMenuItem key={inspection.id} asChild>
+ <Link to={path.to.inspection(inspection.id)}>
+ <DropdownMenuIcon icon={<LuClipboardCheck />} />
+ <HStack spacing={8}>
+ <span>
+ {inspection.itemReadableId ?? inspection.inspectionId}
+ </span>
+ <InspectionStatus status={inspection.status} />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
export default ReceiptForm;
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
index a6323e1d27..3d18d667f0 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
@@ -130,11 +130,18 @@ export function TraceabilitySidebar({
const stepRecordsForActivity = useMemo(() => {
const list = stepRecordsFetcher.data?.stepRecords ?? [];
if (!activity || list.length === 0) return [];
- const opId = (activity.attributes as Record<string, any> | null)?.[
- "Job Operation"
- ];
+ const attrs = activity.attributes as Record<string, any> | null;
+ const opId = attrs?.["Job Operation"];
if (!opId) return [];
- return list.filter((r) => r.operationId === opId);
+ // A production activity is scoped to one unit (its "Unit" is the 0-based
+ // unit-axis index that step records key off). Isolate this unit's records
+ // from the operation's other units. Activities without a Unit (older data
+ // or the operation view) fall back to all records for the operation.
+ const unit = attrs?.Unit;
+ const hasUnit = typeof unit === "number";
+ return list.filter(
+ (r) => r.operationId === opId && (!hasUnit || r.index === unit)
+ );
}, [activity, stepRecordsFetcher.data]);
const containmentsForEntity = useMemo(() => {
@@ -145,7 +152,7 @@ export function TraceabilitySidebar({
const hasMultiSelect = selectedIds && selectedIds.length > 1;
return (
- <aside className="w-[426px] flex-shrink-0 bg-sidebar h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border text-sm">
+ <aside className="w-[426px] flex-shrink-0 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border text-sm">
{hasMultiSelect && (
<div className="flex items-center justify-between gap-2 bg-muted/40 mx-3 mt-3 rounded-md px-2 py-1">
<div className="flex items-center gap-2 min-w-0">
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index 4eab3a4b1d..664b9999d5 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -137,7 +137,7 @@ Change-order code follows the one-service/models/server-per-module convention
- **production** — jobs manufacture items; make methods copied to jobs via `get-method` edge function
- **sales** — quote lines and sales order lines reference items; `itemUnitSalePrice` is base price
- **accounting** — `itemPostingGroup` maps items to GL accounts
-- **quality** — `requiresInspection` flag on items; inspection documents reference parts
+- **quality** — inbound inspection is driven by the item's Receipt-usage inspection-document assignment (`itemInspectionDocumentAssignment`), configured on the item Quality tab; inspection documents reference parts
## Rules References
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index fef7d12604..38b64fccd6 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -227,8 +227,7 @@ export const itemValidator = z.object({
// capped by the earliest input expiry — the output cannot outlast its
// raw materials. Falls back to today + days when no input has a date.
// Mirrors the inventory-settings "Calculate from BOM" copy.
- shelfLifeCalculateFromBom: zfd.checkbox(),
- requiresInspection: zfd.checkbox().optional()
+ shelfLifeCalculateFromBom: zfd.checkbox()
});
// Common storage / shelf-life refines. Shared across all item-type
@@ -487,6 +486,8 @@ export const methodOperationValidator = z
processId: z.string().min(1, { message: "Process is required" }),
workCenterId: zfd.text(z.string().optional()),
procedureId: zfd.text(z.string().optional()),
+ assemblyInstructionId: zfd.text(z.string().optional()),
+ inspectionDocumentId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
),
@@ -515,7 +516,7 @@ export const methodOperationValidator = z
})
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.setupUnit;
}
return true;
@@ -527,7 +528,7 @@ export const methodOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.laborUnit;
}
return true;
@@ -539,8 +540,10 @@ export const methodOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
- return !!data.laborUnit;
+ // Machine only applies to Process operations — Assembly and Inspection
+ // are setup + labor work.
+ if (data.operationType === "Process") {
+ return !!data.machineUnit;
}
return true;
},
@@ -551,7 +554,7 @@ export const methodOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.setupTime);
}
return true;
@@ -563,7 +566,7 @@ export const methodOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborTime);
}
return true;
@@ -575,7 +578,7 @@ export const methodOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineTime);
}
return true;
@@ -584,6 +587,18 @@ export const methodOperationValidator = z
message: "Machine time is required",
path: ["machineTime"]
}
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inspection") {
+ return !!data.inspectionDocumentId;
+ }
+ return true;
+ },
+ {
+ message: "Inspection Plan is required",
+ path: ["inspectionDocumentId"]
+ }
);
export const itemCostValidator = z.object({
diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.ts
index a3366b87c8..1ba8af782a 100644
--- a/apps/erp/app/modules/items/items.service.test.ts
+++ b/apps/erp/app/modules/items/items.service.test.ts
@@ -13,7 +13,9 @@ vi.mock("@carbon/glossary", () => ({
termSlug: vi.fn()
}));
-const { diffMethod } = await import("./items.service");
+const { diffMethod, duplicateMethodOperationStep } = await import(
+ "./items.service"
+);
// A minimal live methodMaterial row (only the fields diffMethod compares + id).
function baseMaterial(over: Record<string, unknown> = {}) {
@@ -261,6 +263,172 @@ describe("diffMethod — operation children", () => {
});
});
+// ── duplicateMethodOperationStep: link-carrying copy ─────────────────────────
+// Tiny fake supabase client mirroring the chain shapes this function uses:
+// canned rows for selects, records inserts.
+function makeFakeClient(opts: {
+ rows: Record<string, Record<string, unknown>[]>;
+ newIdByTable?: Record<string, string>;
+ errorOnInsert?: string;
+}) {
+ const inserts: { table: string; rows: Record<string, unknown>[] }[] = [];
+
+ function resolve(state: {
+ table: string;
+ op?: "insert";
+ filters: Record<string, unknown>;
+ insertRows?: Record<string, unknown>[];
+ single: boolean;
+ }) {
+ if (state.op === "insert") {
+ inserts.push({ table: state.table, rows: state.insertRows ?? [] });
+ if (opts.errorOnInsert === state.table) {
+ return {
+ data: null,
+ error: { message: `insert failed: ${state.table}` }
+ };
+ }
+ if (state.single) {
+ const id = opts.newIdByTable?.[state.table] ?? `new_${state.table}`;
+ return { data: { id }, error: null };
+ }
+ return { data: null, error: null };
+ }
+ let data = opts.rows[state.table] ?? [];
+ for (const [col, val] of Object.entries(state.filters)) {
+ data = data.filter((r) => r[col] === val);
+ }
+ return state.single
+ ? { data: data[0] ?? null, error: null }
+ : { data, error: null };
+ }
+
+ function builder(table: string) {
+ const state = {
+ table,
+ filters: {} as Record<string, unknown>,
+ op: undefined as "insert" | undefined,
+ insertRows: undefined as Record<string, unknown>[] | undefined,
+ single: false
+ };
+ const b = {
+ select: () => b,
+ eq: (col: string, val: unknown) => {
+ state.filters[col] = val;
+ return b;
+ },
+ insert: (rows: Record<string, unknown> | Record<string, unknown>[]) => {
+ state.op = "insert";
+ state.insertRows = Array.isArray(rows) ? rows : [rows];
+ return b;
+ },
+ single: () => {
+ state.single = true;
+ return Promise.resolve(resolve(state));
+ },
+ then: (onF: (v: unknown) => unknown, onR?: (e: unknown) => unknown) =>
+ Promise.resolve(resolve(state)).then(onF, onR)
+ };
+ return b;
+ }
+
+ return { client: { from: builder } as never, inserts };
+}
+
+describe("duplicateMethodOperationStep", () => {
+ function sourceRows() {
+ return {
+ methodOperationStep: [
+ {
+ id: "step-1",
+ operationId: "op-1",
+ name: "Deburr",
+ description: null,
+ type: "Task",
+ unitOfMeasureCode: null,
+ minValue: null,
+ maxValue: null,
+ listValues: null,
+ sortOrder: 2
+ },
+ { id: "step-2", operationId: "op-1", sortOrder: 5 }
+ ],
+ methodOperationStepSlide: [
+ {
+ stepId: "step-1",
+ imagePath: "/x.png",
+ modelUploadId: null,
+ caption: "c",
+ sortOrder: 1,
+ size: "medium",
+ annotations: "[]"
+ }
+ ],
+ methodOperationToolStep: [
+ { methodOperationToolId: "tool-1", methodOperationStepId: "step-1" }
+ ],
+ methodMaterialStep: [
+ { methodMaterialId: "mat-1", methodOperationStepId: "step-1" }
+ ]
+ };
+ }
+
+ it("copies the step and carries its slides/tool-links/material-links onto the clone", async () => {
+ const { client, inserts } = makeFakeClient({
+ rows: sourceRows(),
+ newIdByTable: { methodOperationStep: "step-new" }
+ });
+
+ const result = await duplicateMethodOperationStep(client, {
+ id: "step-1",
+ companyId: "c1",
+ createdBy: "u1"
+ });
+ expect(result.error).toBeNull();
+ expect(result.data).toEqual({ id: "step-new" });
+
+ expect(
+ inserts.find((i) => i.table === "methodOperationStep")?.rows[0]
+ ).toMatchObject({
+ operationId: "op-1",
+ name: "Deburr (copy)",
+ sortOrder: 6, // max sibling sortOrder (5) + 1
+ companyId: "c1",
+ createdBy: "u1"
+ });
+ expect(
+ inserts.find((i) => i.table === "methodOperationStepSlide")?.rows[0]
+ ).toMatchObject({ stepId: "step-new", imagePath: "/x.png" });
+ expect(
+ inserts.find((i) => i.table === "methodOperationToolStep")?.rows
+ ).toEqual([
+ { methodOperationToolId: "tool-1", methodOperationStepId: "step-new" }
+ ]);
+ expect(inserts.find((i) => i.table === "methodMaterialStep")?.rows).toEqual(
+ [{ methodMaterialId: "mat-1", methodOperationStepId: "step-new" }]
+ );
+ });
+
+ it("aborts and surfaces the error if a child copy fails (no further inserts)", async () => {
+ const { client, inserts } = makeFakeClient({
+ rows: sourceRows(),
+ newIdByTable: { methodOperationStep: "step-new" },
+ errorOnInsert: "methodOperationToolStep"
+ });
+
+ const result = await duplicateMethodOperationStep(client, {
+ id: "step-1",
+ companyId: "c1",
+ createdBy: "u1"
+ });
+
+ expect(result.data).toBeNull();
+ expect(result.error).not.toBeNull();
+ // Tool-link copy failed → the material-link copy must never run.
+ expect(inserts.some((i) => i.table === "methodMaterialStep")).toBe(false);
+ });
+});
+
describe("diffMethod — attributes", () => {
it("reports one entry per changed attribute column", () => {
const { attributes } = diffMethod({
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 85b3de8df7..79f51e1630 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -8,7 +8,7 @@ import type {
} from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import { getLocalTimeZone, now, today } from "@internationalized/date";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
@@ -17,12 +17,14 @@ import { sanitize } from "~/utils/supabase";
import type { nonConformancePriority } from "../quality/quality.models";
import type {
operationParameterValidator,
+ operationStepSlideValidator,
operationStepValidator,
operationToolValidator
} from "../shared";
import {
lookupBuyPriceFromMap,
type MethodType,
+ normalizeOperationSourceIds,
type PriceBreak,
type SourcingType,
type SupplierPriceMap
@@ -201,7 +203,6 @@ export async function createRevision(
// only differences the user (and the CO diff) sees are ones they made.
description: item.description,
sourcingType: item.sourcingType,
- requiresInspection: item.requiresInspection,
thumbnailPath: item.thumbnailPath,
mpn: item.mpn,
active,
@@ -420,6 +421,13 @@ export async function deleteMethodOperationStep(
return client.from("methodOperationStep").delete().eq("id", id);
}
+export async function deleteMethodOperationStepSlide(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("methodOperationStepSlide").delete().eq("id", id);
+}
+
export async function deleteMethodOperationParameter(
client: SupabaseClient<Database>,
id: string
@@ -1053,6 +1061,7 @@ export async function getMaterialUsedIn(
salesOrderLines,
shipmentLines,
supplierQuotes,
+ inspections,
jobMaterialUsage
] = await Promise.all([
client
@@ -1136,6 +1145,13 @@ export async function getMaterialUsedIn(
.eq("itemId", itemId)
.eq("companyId", companyId)
.limit(100),
+ client
+ .from("inspection")
+ .select("id, documentReadableId:inspectionId")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .limit(100)
+ .order("createdAt", { ascending: false }),
getJobMaterialUsageForItem(client, { itemId, companyId })
]);
@@ -1150,6 +1166,7 @@ export async function getMaterialUsedIn(
salesOrderLines: salesOrderLines.data ?? [],
shipmentLines: shipmentLines.data ?? [],
supplierQuotes: supplierQuotes.data ?? [],
+ inspections: inspections.data ?? [],
jobMaterialUsage
};
}
@@ -1507,7 +1524,7 @@ export async function getMethodMaterialsByMakeMethod(
return client
.from("methodMaterial")
.select(
- "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType)"
+ "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType), methodMaterialStep(methodOperationStepId)"
)
.eq("makeMethodId", makeMethodId)
.order("order", { ascending: true });
@@ -1548,7 +1565,7 @@ export async function getMethodOperationsByMakeMethodId(
return client
.from("methodOperation")
.select(
- "*, methodOperationTool(*), methodOperationParameter(*), methodOperationStep(*)"
+ "*, methodOperationTool(*, methodOperationToolStep(methodOperationStepId)), methodOperationParameter(*), methodOperationStep(*, methodOperationStepSlide(*))"
)
.eq("makeMethodId", makeMethodId)
.order("order", { ascending: true });
@@ -1794,6 +1811,7 @@ export async function getPartUsedIn(
shipmentLines,
supplierQuotes,
assemblyInstructions,
+ inspections,
jobMaterialUsage
] = await Promise.all([
client
@@ -1902,6 +1920,13 @@ export async function getPartUsedIn(
.eq("companyId", companyId)
.limit(100)
.order("createdAt", { ascending: false }),
+ client
+ .from("inspection")
+ .select("id, documentReadableId:inspectionId")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .limit(100)
+ .order("createdAt", { ascending: false }),
getJobMaterialUsageForItem(client, { itemId, companyId })
]);
@@ -1919,6 +1944,7 @@ export async function getPartUsedIn(
shipmentLines: shipmentLines.data ?? [],
supplierQuotes: supplierQuotes.data ?? [],
assemblyInstructions: assemblyInstructions.data ?? [],
+ inspections: inspections.data ?? [],
jobMaterialUsage
};
}
@@ -3961,13 +3987,13 @@ export async function upsertMethodOperation(
if ("createdBy" in methodOperation) {
return client
.from("methodOperation")
- .insert([methodOperation])
+ .insert([normalizeOperationSourceIds(methodOperation)])
.select("id")
.single();
}
return client
.from("methodOperation")
- .update(sanitize(methodOperation))
+ .update(sanitize(normalizeOperationSourceIds(methodOperation)))
.eq("id", methodOperation.id)
.select("id")
.single();
@@ -4007,6 +4033,161 @@ export async function upsertMethodOperationStep(
.single();
}
+// Clone a step within the same operation: a "(copy)" appended after all siblings,
+// carrying its reference slides (image + caption + size + annotations, incl. tool
+// hotspots). Sequential supabase writes — a step is created first, then its slides,
+// so a slide-copy failure surfaces without a half-written step blocking the editor.
+export async function duplicateMethodOperationStep(
+ client: SupabaseClient<Database>,
+ args: { id: string; companyId: string; createdBy: string }
+): Promise<{ data: { id: string } | null; error: PostgrestError | null }> {
+ const source = await client
+ .from("methodOperationStep")
+ .select("*")
+ .eq("id", args.id)
+ .single();
+ if (source.error || !source.data) {
+ return { data: null, error: source.error };
+ }
+ const src = source.data;
+
+ // Append after the highest sortOrder in the operation.
+ const siblings = await client
+ .from("methodOperationStep")
+ .select("sortOrder")
+ .eq("operationId", src.operationId);
+ const nextSortOrder =
+ (siblings.data ?? []).reduce(
+ (max, s) => Math.max(max, s.sortOrder ?? 0),
+ 0
+ ) + 1;
+
+ const insert = await client
+ .from("methodOperationStep")
+ .insert({
+ operationId: src.operationId,
+ name: `${src.name} (copy)`,
+ description: src.description,
+ type: src.type,
+ unitOfMeasureCode: src.unitOfMeasureCode,
+ minValue: src.minValue,
+ maxValue: src.maxValue,
+ listValues: src.listValues,
+ sortOrder: nextSortOrder,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ })
+ .select("id")
+ .single();
+ if (insert.error || !insert.data) {
+ return { data: null, error: insert.error };
+ }
+ const newStepId = insert.data.id;
+
+ // select("*") (not an explicit column list) so `size`/`annotations` — added by the
+ // step-slide migration — resolve once types are regenerated, without a bad column in
+ // the select string poisoning the whole row type before then.
+ const slides = await client
+ .from("methodOperationStepSlide")
+ .select("*")
+ .eq("stepId", args.id);
+ if (slides.error) {
+ return { data: null, error: slides.error };
+ }
+ if (slides.data && slides.data.length > 0) {
+ const slideRows = slides.data.map((s) => ({
+ stepId: newStepId,
+ imagePath: s.imagePath,
+ modelUploadId: s.modelUploadId,
+ caption: s.caption,
+ sortOrder: s.sortOrder,
+ size: s.size,
+ annotations: s.annotations,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ }));
+ const slideInsert = await client
+ .from("methodOperationStepSlide")
+ .insert(slideRows);
+ if (slideInsert.error) {
+ return { data: null, error: slideInsert.error };
+ }
+ }
+
+ // Copy step-scoped tool links. A tool with NO join rows is operation-level (shown on
+ // every step) and needs nothing copied; only tools scoped to this specific step carry
+ // a row here, and those must be repointed at the clone or the copy silently loses them.
+ const toolLinks = await client
+ .from("methodOperationToolStep")
+ .select("methodOperationToolId")
+ .eq("methodOperationStepId", args.id);
+ if (toolLinks.error) {
+ return { data: null, error: toolLinks.error };
+ }
+ if (toolLinks.data && toolLinks.data.length > 0) {
+ const toolLinkInsert = await client.from("methodOperationToolStep").insert(
+ toolLinks.data.map((l) => ({
+ methodOperationToolId: l.methodOperationToolId,
+ methodOperationStepId: newStepId
+ }))
+ );
+ if (toolLinkInsert.error) {
+ return { data: null, error: toolLinkInsert.error };
+ }
+ }
+
+ // Copy step-scoped part/material links (same operation-level-vs-scoped semantics as tools).
+ const materialLinks = await client
+ .from("methodMaterialStep")
+ .select("methodMaterialId")
+ .eq("methodOperationStepId", args.id);
+ if (materialLinks.error) {
+ return { data: null, error: materialLinks.error };
+ }
+ if (materialLinks.data && materialLinks.data.length > 0) {
+ const materialLinkInsert = await client.from("methodMaterialStep").insert(
+ materialLinks.data.map((l) => ({
+ methodMaterialId: l.methodMaterialId,
+ methodOperationStepId: newStepId
+ }))
+ );
+ if (materialLinkInsert.error) {
+ return { data: null, error: materialLinkInsert.error };
+ }
+ }
+
+ return { data: { id: newStepId }, error: null };
+}
+
+export async function upsertMethodOperationStepSlide(
+ client: SupabaseClient<Database>,
+ slide:
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ updatedAt: string;
+ })
+) {
+ if ("createdBy" in slide) {
+ return client
+ .from("methodOperationStepSlide")
+ .insert(slide)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("methodOperationStepSlide")
+ .update(sanitize(slide))
+ .eq("id", slide.id)
+ .select("id")
+ .single();
+}
+
export async function upsertMethodOperationParameter(
client: SupabaseClient<Database>,
methodOperationParameter:
@@ -4065,6 +4246,90 @@ export async function upsertMethodOperationTool(
.single();
}
+// Replace a method tool's step links (tool ↔ step is many-to-many). No ids = the tool
+// applies to the whole operation (shown on every step in the MES). Delete-then-insert.
+// Replace a method material's step links (part ↔ step, many-to-many). See above.
+export async function replaceMethodMaterialSteps(
+ client: SupabaseClient<Database>,
+ methodMaterialId: string,
+ methodOperationStepIds: string[]
+) {
+ const del = await client
+ .from("methodMaterialStep")
+ .delete()
+ .eq("methodMaterialId", methodMaterialId);
+ if (del.error || methodOperationStepIds.length === 0) return del;
+ return client.from("methodMaterialStep").insert(
+ methodOperationStepIds.map((methodOperationStepId) => ({
+ methodMaterialId,
+ methodOperationStepId
+ }))
+ );
+}
+
+// Toggle a single part↔step link from the STEP side (the step editor's Parts picker).
+// `linked` true = link the material to the step, false = unlink. Idempotent on link.
+export async function setMethodMaterialStepLink(
+ client: SupabaseClient<Database>,
+ args: {
+ methodMaterialId: string;
+ methodOperationStepId: string;
+ linked: boolean;
+ }
+) {
+ if (args.linked) {
+ return client.from("methodMaterialStep").upsert(
+ [
+ {
+ methodMaterialId: args.methodMaterialId,
+ methodOperationStepId: args.methodOperationStepId
+ }
+ ],
+ {
+ onConflict: "methodMaterialId,methodOperationStepId",
+ ignoreDuplicates: true
+ }
+ );
+ }
+ return client
+ .from("methodMaterialStep")
+ .delete()
+ .eq("methodMaterialId", args.methodMaterialId)
+ .eq("methodOperationStepId", args.methodOperationStepId);
+}
+
+// Toggle a single tool↔step link from the STEP side (the step editor's Tools picker).
+// `linked` true = link the tool to the step, false = unlink. Idempotent on link. Twin of
+// setMethodMaterialStepLink.
+export async function setMethodOperationToolStepLink(
+ client: SupabaseClient<Database>,
+ args: {
+ methodOperationToolId: string;
+ methodOperationStepId: string;
+ linked: boolean;
+ }
+) {
+ if (args.linked) {
+ return client.from("methodOperationToolStep").upsert(
+ [
+ {
+ methodOperationToolId: args.methodOperationToolId,
+ methodOperationStepId: args.methodOperationStepId
+ }
+ ],
+ {
+ onConflict: "methodOperationToolId,methodOperationStepId",
+ ignoreDuplicates: true
+ }
+ );
+ }
+ return client
+ .from("methodOperationToolStep")
+ .delete()
+ .eq("methodOperationToolId", args.methodOperationToolId)
+ .eq("methodOperationStepId", args.methodOperationStepId);
+}
+
export async function upsertMaterial(
client: SupabaseClient<Database>,
material:
@@ -5726,7 +5991,6 @@ export async function createChangeOrderDraftMethod(
// user's edits, not gaps left by an incomplete copy.
description: source.data.description,
sourcingType: source.data.sourcingType,
- requiresInspection: source.data.requiresInspection,
thumbnailPath: source.data.thumbnailPath,
mpn: source.data.mpn,
active: false,
@@ -6953,7 +7217,7 @@ export type ChangeOrderDiff = {
// separately by readItemAttributes. `active` is intentionally excluded — a CO
// draft is created inactive until release, so it always differs (not a real edit).
const ITEM_ATTRIBUTE_COLUMNS =
- "name, description, unitOfMeasureCode, itemTrackingType, defaultMethodType, replenishmentSystem, sourcingType, requiresInspection, thumbnailPath, mpn";
+ "name, description, unitOfMeasureCode, itemTrackingType, defaultMethodType, replenishmentSystem, sourcingType, thumbnailPath, mpn";
// Read one make method's materials + operations + per-operation children (real
// method tables — the v2 substrate). Empty for a null makeMethodId (e.g. a Buy
diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx
index 0e2187f6ae..5886f1579a 100644
--- a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx
+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx
@@ -62,7 +62,6 @@ const FIELD_LABELS: Record<string, string> = {
itemTrackingType: "Tracking",
replenishmentSystem: "Replenishment",
sourcingType: "Sourcing",
- requiresInspection: "Requires inspection",
defaultMethodType: "Default method",
itemPostingGroupId: "Item group",
mpn: "MPN",
diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts b/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts
index f5e3be84a1..f2664afcf4 100644
--- a/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts
+++ b/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts
@@ -46,6 +46,8 @@ export type DraftOperationMapped = Omit<
DraftOperation,
| "description"
| "procedureId"
+ | "assemblyInstructionId"
+ | "inspectionDocumentId"
| "operationSupplierProcessId"
| "operationMinimumCost"
| "operationLeadTime"
@@ -56,6 +58,8 @@ export type DraftOperationMapped = Omit<
> & {
description: string;
procedureId: string | undefined;
+ assemblyInstructionId: string | undefined;
+ inspectionDocumentId: string | undefined;
operationSupplierProcessId: string | undefined;
operationMinimumCost: number;
operationLeadTime: number;
diff --git a/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx
index a59ea373de..96db60566f 100644
--- a/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx
+++ b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx
@@ -90,7 +90,7 @@ const ChangeOrderRequiredActionForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label={t`Action`} />
- <Boolean name="active" label={t`Active`} />
+ <Boolean name="active" label={t`Active`} bordered />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx
index cf5a1654a7..5166f80ebe 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx
@@ -130,8 +130,7 @@ const ConsumableProperties = ({ data }: ConsumablePropertiesProps) => {
| "itemPostingGroupId"
| "consumableId"
| "active"
- | "mpn"
- | "requiresInspection",
+ | "mpn",
value: string | null
) => {
const formData = new FormData();
@@ -465,27 +464,6 @@ const ConsumableProperties = ({ data }: ConsumablePropertiesProps) => {
}}
/>
</ValidatedForm>
- {routeData?.consumableSummary?.replenishmentSystem?.includes("Buy") && (
- <ValidatedForm
- defaultValues={{
- requiresInspection:
- (routeData?.consumableSummary as any)?.requiresInspection ?? false
- }}
- validator={z.object({
- requiresInspection: zfd.checkbox()
- })}
- className="w-full"
- >
- <Boolean
- label={t`Requires Inspection`}
- name="requiresInspection"
- variant="small"
- onChange={(value) => {
- onUpdate("requiresInspection", value ? "on" : "off");
- }}
- />
- </ValidatedForm>
- )}
{routeData?.consumableSummary?.replenishmentSystem?.includes("Buy") && (
<ValidatedForm
defaultValues={{
diff --git a/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx b/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
index 894debc26c..8e9ebea44b 100644
--- a/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
@@ -69,7 +69,6 @@ export function useConsumableNavigation() {
{
name: t`Quality`,
to: path.to.consumableQuality(itemId),
- isDisabled: !routeData?.consumableSummary?.requiresInspection,
role: ["employee"],
permission: "quality",
icon: LuClipboardCheck,
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index 12d0fd40ab..a423ace3a3 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -119,7 +119,11 @@ type Material = z.infer<typeof methodMaterialValidator> & {
};
};
-type Operation = z.infer<typeof methodOperationValidator>;
+type Operation = z.infer<typeof methodOperationValidator> & {
+ // The same operations data BillOfProcess gets — carries its steps at runtime, so the
+ // BoM editor can offer a per-step assignment (Phase 2). Narrow type, optional here.
+ methodOperationStep?: { id: string; name: string | null }[];
+};
type ItemWithData = SortableItem & {
data: Material;
@@ -631,6 +635,7 @@ function MaterialForm({
description: string;
unitOfMeasureCode: string;
methodOperationId: string | undefined;
+ methodOperationStepIds?: string[];
quantity: number;
kit: boolean;
storageUnitIds: Record<string, string>;
@@ -644,6 +649,13 @@ function MaterialForm({
description: item.data.description ?? "",
unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
methodOperationId: item.data.methodOperationId ?? undefined,
+ methodOperationStepIds: (
+ (
+ item.data as {
+ methodMaterialStep?: { methodOperationStepId: string }[];
+ }
+ ).methodMaterialStep ?? []
+ ).map((s) => s.methodOperationStepId),
quantity: item.data.quantity ?? 1,
kit: item.data.kit ?? false,
storageUnitIds: item.data.storageUnitIds ?? {},
@@ -1076,10 +1088,14 @@ function MaterialForm({
onChange={(value) => {
setItemData((d) => ({
...d,
- methodOperationId: value?.value
+ methodOperationId: value?.value,
+ // Steps belong to an operation — clear them when the operation changes.
+ methodOperationStepIds: []
}));
}}
/>
+ {/* Part ↔ step assignment now lives on the STEP (the BoP step editor's "Parts"
+ picker), not here — so there is no per-material "Steps" dropdown in the BOM. */}
</div>
</div>
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 5ea7c9f09b..6e60a77d9a 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -46,6 +46,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import {
LuActivity,
+ LuChevronLeft,
LuChevronRight,
LuCirclePlus,
LuEllipsisVertical,
@@ -60,7 +61,12 @@ import {
LuSquareFunction,
LuTriangleAlert
} from "react-icons/lu";
-import { useFetcher, useFetchers, useParams } from "react-router";
+import {
+ useFetcher,
+ useFetchers,
+ useParams,
+ useRevalidator
+} from "react-router";
import { z } from "zod";
import {
DirectionAwareTabs,
@@ -87,12 +93,15 @@ import {
UnitOfMeasure,
WorkCenter
} from "~/components/Form";
+import AssemblyInstruction from "~/components/Form/AssemblyInstruction";
+import InspectionDocument from "~/components/Form/InspectionDocument";
import Procedure from "~/components/Form/Procedure";
import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";
import { getUnitHint } from "~/components/Form/UnitHint";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { ProcedureStepTypeIcon } from "~/components/Icons";
+import { OperationTypeIcon, ProcedureStepTypeIcon } from "~/components/Icons";
import { ConfirmDelete } from "~/components/Modals";
+import { SlidesEditor, uploadStepSlideModel } from "~/components/SlidesEditor";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import {
SortableList,
@@ -100,12 +109,16 @@ import {
SortableListItemPanel,
SortableListItemToggle
} from "~/components/SortableList";
+import { StepLinkEditor } from "~/components/StepLinkEditor";
import { useDateFormatter, usePermissions, useUser } from "~/hooks";
import { useTags } from "~/hooks/useTags";
import type {
OperationParameter,
OperationStep,
- OperationTool
+ OperationStepSlide,
+ OperationTool,
+ SlideAnnotation,
+ SlideSize
} from "~/modules/shared";
import {
methodOperationOrders,
@@ -142,7 +155,12 @@ type ItemWithData = Item & {
};
type MethodMaterialType = {
+ id: string;
itemId: string;
+ description?: string | null;
+ quantity?: number | null;
+ methodOperationId?: string | null;
+ methodMaterialStep?: { methodOperationStepId: string }[] | null;
};
type BillOfProcessProps = {
@@ -186,7 +204,9 @@ const initialOperation: Omit<
machineTime: 0,
machineUnit: "Minutes/Piece",
operationOrder: "After Previous",
- operationType: "Inside",
+ operationType: "Process",
+ assemblyInstructionId: "",
+ inspectionDocumentId: "",
processId: "",
procedureId: "",
setupTime: 0,
@@ -485,6 +505,8 @@ const BillOfProcess = ({
[];
const hasProcedure = !!item.data.procedureId;
+ const hasAssemblyInstruction = !!item.data.assemblyInstructionId;
+ const hasInspectionDocument = !!item.data.inspectionDocumentId;
const tabs = [
{
@@ -496,6 +518,7 @@ const BillOfProcess = ({
isReadOnly={isReadOnly}
configurable={configurable}
item={item}
+ itemId={makeMethod.itemId}
rulesByField={rulesByField}
workInstruction={workInstructions[item.id] ?? {}}
temporaryItems={temporaryItems}
@@ -541,7 +564,7 @@ const BillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ item.data.operationType === "Outside Processing",
content: (
<div className="flex flex-col">
<div>
@@ -581,7 +604,7 @@ const BillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>Parameters</span>
@@ -627,11 +650,15 @@ const BillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ hasAssemblyInstruction ||
+ hasInspectionDocument ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>Steps</span>
- {hasProcedure && (
+ {(hasProcedure ||
+ hasAssemblyInstruction ||
+ hasInspectionDocument) && (
<Tooltip>
<TooltipTrigger>
<Badge variant="secondary">
@@ -640,20 +667,35 @@ const BillOfProcess = ({
</TooltipTrigger>
<TooltipContent side="bottom" className="opacity-100">
<p>
- <Trans>Attributes are inherited from the procedure.</Trans>
+ {hasAssemblyInstruction ? (
+ <Trans>
+ Steps are inherited from the assembly instruction.
+ </Trans>
+ ) : hasInspectionDocument ? (
+ <Trans>
+ Steps are inherited from the inspection plan.
+ </Trans>
+ ) : (
+ <Trans>
+ Attributes are inherited from the procedure.
+ </Trans>
+ )}
</p>
</TooltipContent>
</Tooltip>
)}
- {!hasProcedure && steps.length > 0 && (
- <Count count={steps.length} />
- )}
+ {!hasProcedure &&
+ !hasAssemblyInstruction &&
+ !hasInspectionDocument &&
+ steps.length > 0 && <Count count={steps.length} />}
</span>
),
content: (
<div className="flex w-full flex-col py-4">
<AttributesForm
steps={steps}
+ tools={tools}
+ materials={materials}
operationId={item.id!}
temporaryItems={temporaryItems}
isDisabled={
@@ -672,7 +714,8 @@ const BillOfProcess = ({
{
id: 4,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>Tools</span>
@@ -693,6 +736,19 @@ const BillOfProcess = ({
/>
</div>
)
+ },
+ {
+ // Phase 3: read-only preview of how the operator sees this operation in the MES
+ // assembly view — step-by-step, with each step's reference image and the tools
+ // scoped to it. No live job needed; renders straight off the method.
+ id: 5,
+ disabled: item.id in temporaryItems,
+ label: <span>Preview</span>,
+ content: (
+ <div className="flex w-full flex-col py-4">
+ <OperationPreview steps={steps} tools={tools} />
+ </div>
+ )
}
];
@@ -825,6 +881,7 @@ type OperationFormProps = {
configurable: boolean;
isReadOnly: boolean;
item: ItemWithData;
+ itemId: string;
rulesByField: Map<string, ConfigurationRule>;
workInstruction: JSONContent;
temporaryItems: TemporaryItems;
@@ -839,6 +896,7 @@ function OperationForm({
isReadOnly,
configurable,
item,
+ itemId,
rulesByField,
workInstruction,
temporaryItems,
@@ -877,6 +935,7 @@ function OperationForm({
const machineDisclosure = useDisclosure();
const laborDisclosure = useDisclosure();
+ const assemblyDisclosure = useDisclosure();
const setupDisclosure = useDisclosure();
const procedureDisclosure = useDisclosure();
@@ -889,6 +948,8 @@ function OperationForm({
machineUnit: string;
machineUnitHint: string;
operationType: string;
+ assemblyInstructionId: string;
+ inspectionDocumentId: string;
operationOrder: string;
processId: string;
procedureId: string;
@@ -908,7 +969,9 @@ function OperationForm({
machineUnit: item.data.machineUnit ?? "Hours/Piece",
machineUnitHint: getUnitHint(item.data.machineUnit),
operationOrder: item.data.operationOrder ?? "After Previous",
- operationType: item.data.operationType ?? "Inside",
+ operationType: item.data.operationType ?? "Process",
+ assemblyInstructionId: item.data.assemblyInstructionId ?? "",
+ inspectionDocumentId: item.data.inspectionDocumentId ?? "",
processId: item.data.processId ?? "",
procedureId: item.data.procedureId ?? "",
workCenterId: item.data.workCenterId ?? "",
@@ -938,8 +1001,9 @@ function OperationForm({
laborUnitHint: getUnitHint(process.data?.defaultStandardFactor),
machineUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
machineUnitHint: getUnitHint(process.data?.defaultStandardFactor),
- operationType:
- process.data?.processType === "Outside" ? "Outside" : "Inside",
+ // processType and operationType share one enum — the process's type is the
+ // default operation type.
+ operationType: process.data?.processType ?? "Process",
operationMinimumCost:
supplierProcesses.data && supplierProcesses.data.length > 0
? supplierProcesses.data.reduce((acc, sp) => {
@@ -1024,103 +1088,49 @@ function OperationForm({
}}
/>
- <Select
- name="operationOrder"
- label={t`Operation Order`}
- placeholder={t`Operation Order`}
- options={methodOperationOrders.map((o) => ({
- value: o,
- label: o
- }))}
- onChange={(value) => {
- setProcessData((d) => ({
- ...d,
- operationOrder: value?.value as string
- }));
- }}
- isConfigured={rulesByField.has(key("operationOrder"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Operation Order`,
- field: key("operationOrder"),
- code: rulesByField.get(key("operationOrder"))?.code,
- defaultValue: processData.operationOrder,
- returnType: {
- type: "enum",
- listOptions: ["After Previous", "With Previous"]
- }
- });
- }
- : undefined
- }
- />
-
<SelectControlled
name="operationType"
label={t`Operation Type`}
+ termId="operation-type"
placeholder={t`Operation Type`}
options={operationTypes.map((o) => ({
value: o,
- label: o
+ label: (
+ <span className="flex items-center gap-2">
+ <OperationTypeIcon type={o} />
+ <span>{o}</span>
+ </span>
+ )
}))}
value={processData.operationType}
onChange={(value) => {
+ const next = (value?.value as string) ?? "Process";
setProcessData((d) => ({
...d,
- setupUnit: "Total Minutes",
- laborUnit: "Minutes/Piece",
- machineUnit: "Minutes/Piece",
- operationType: value?.value as string
+ operationType: next,
+ // Each type has exactly one instruction source — clear the ones
+ // that no longer apply (the upsert normalizes server-side too).
+ ...(next !== "Process" ? { procedureId: "" } : {}),
+ ...(next !== "Assembly" ? { assemblyInstructionId: "" } : {}),
+ ...(next !== "Inspection" ? { inspectionDocumentId: "" } : {}),
+ // Machine only applies to Process operations.
+ ...(next !== "Process" ? { machineTime: 0 } : {}),
+ // Crossing the in-house <-> Outside Processing boundary changes the
+ // meaningful time units; reset to defaults. Switching between in-house
+ // types keeps whatever units the user picked.
+ ...((next === "Outside Processing") !==
+ (d.operationType === "Outside Processing")
+ ? {
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece"
+ }
+ : {})
}));
}}
- isConfigured={rulesByField.has(key("operationType"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Operation Type`,
- field: key("operationType"),
- code: rulesByField.get(key("operationType"))?.code,
- defaultValue: processData.operationType,
- returnType: {
- type: "enum",
- listOptions: ["Inside", "Outside"]
- }
- });
- }
- : undefined
- }
- />
-
- <InputControlled
- name="description"
- label={t`Description`}
- value={processData.description}
- onChange={(newValue) => {
- setProcessData((d) => ({ ...d, description: newValue }));
- }}
- className="col-span-2"
- isConfigured={rulesByField.has(key("description"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Description`,
- field: key("description"),
- code: rulesByField.get(key("description"))?.code,
- defaultValue: processData.description,
- returnType: {
- type: "text"
- }
- });
- }
- : undefined
- }
/>
- {processData.operationType === "Outside" ? (
+ {processData.operationType === "Outside Processing" ? (
<>
<SupplierProcess
name="operationSupplierProcessId"
@@ -1207,9 +1217,68 @@ function OperationForm({
/>
</>
)}
+
+ <InputControlled
+ name="description"
+ label={t`Description`}
+ value={processData.description}
+ onChange={(newValue) => {
+ setProcessData((d) => ({ ...d, description: newValue }));
+ }}
+ className="col-span-2"
+ isConfigured={rulesByField.has(key("description"))}
+ onConfigure={
+ configurable && !temporaryItems[item.id]
+ ? () => {
+ onConfigure({
+ label: t`Description`,
+ field: key("description"),
+ code: rulesByField.get(key("description"))?.code,
+ defaultValue: processData.description,
+ returnType: {
+ type: "text"
+ }
+ });
+ }
+ : undefined
+ }
+ />
+
+ <Select
+ name="operationOrder"
+ label={t`Operation Order`}
+ placeholder={t`Operation Order`}
+ options={methodOperationOrders.map((o) => ({
+ value: o,
+ label: o
+ }))}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ operationOrder: value?.value as string
+ }));
+ }}
+ isConfigured={rulesByField.has(key("operationOrder"))}
+ onConfigure={
+ configurable && !temporaryItems[item.id]
+ ? () => {
+ onConfigure({
+ label: t`Operation Order`,
+ field: key("operationOrder"),
+ code: rulesByField.get(key("operationOrder"))?.code,
+ defaultValue: processData.operationOrder,
+ returnType: {
+ type: "enum",
+ listOptions: ["After Previous", "With Previous"]
+ }
+ });
+ }
+ : undefined
+ }
+ />
</div>
- {processData.operationType === "Inside" && (
+ {processData.operationType !== "Outside Processing" && (
<>
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -1440,195 +1509,294 @@ function OperationForm({
/>
</div>
</div>
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={machineDisclosure.onToggle}
- >
- <HStack>
- <TimeTypeIcon type="Machine" />
- <Label>
- <Trans>Machine</Trans>
- </Label>
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={machineDisclosure.onToggle}
+ >
+ <HStack>
+ <TimeTypeIcon type="Machine" />
+ <Label>
+ <Trans>Machine</Trans>
+ </Label>
+ </HStack>
+ <HStack>
+ {(processData?.machineTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
+ {processData.machineTime} {processData.machineUnit}
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ machineDisclosure.isOpen
+ ? t`Collapse Machine`
+ : t`Expand Machine`
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ machineDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ machineDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- <HStack>
- {(processData?.machineTime ?? 0) > 0 && (
- <Badge variant="secondary">
- <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
- {processData.machineTime} {processData.machineUnit}
- </Badge>
- )}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- machineDisclosure.isOpen
- ? t`Collapse Machine`
- : t`Expand Machine`
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ machineDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="machineHint"
+ label={t`Machine`}
+ value={processData.machineUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnitHint: hint,
+ machineUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
+ }));
+ }}
+ />
+ <NumberControlled
+ name="machineTime"
+ label={t`Machine Time`}
+ isOptional={false}
+ minValue={0}
+ value={processData.machineTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineTime: newValue
+ }))
}
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- machineDisclosure.onToggle();
+ isConfigured={rulesByField.has(key("machineTime"))}
+ onConfigure={
+ configurable && !temporaryItems[item.id]
+ ? () => {
+ onConfigure({
+ label: t`Machine Time`,
+ field: key("machineTime"),
+ code: rulesByField.get(key("machineTime"))?.code,
+ defaultValue: processData.machineTime,
+ returnType: {
+ type: "numeric"
+ }
+ });
+ }
+ : undefined
+ }
+ />
+ <StandardFactor
+ name="machineUnit"
+ label={t`Machine Unit`}
+ isOptional={false}
+ hint={processData.machineUnitHint}
+ value={processData.machineUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnit: newValue?.value ?? "Total Minutes"
+ }));
}}
- className={`transition-transform ${
- machineDisclosure.isOpen ? "rotate-90" : ""
- }`}
+ isConfigured={rulesByField.has(key("machineUnit"))}
+ onConfigure={
+ configurable && !temporaryItems[item.id]
+ ? () => {
+ onConfigure({
+ label: t`Machine Unit`,
+ field: key("machineUnit"),
+ code: rulesByField.get(key("machineUnit"))?.code,
+ defaultValue: processData.machineUnit,
+ returnType: {
+ type: "enum",
+ listOptions: standardFactorType
+ }
+ });
+ }
+ : undefined
+ }
/>
- </HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- machineDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <UnitHint
- name="machineHint"
- label={t`Machine`}
- value={processData.machineUnitHint}
- onChange={(hint) => {
- setProcessData((d) => ({
- ...d,
- machineUnitHint: hint,
- machineUnit:
- hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
- }));
- }}
- />
- <NumberControlled
- name="machineTime"
- label={t`Machine Time`}
- isOptional={false}
- minValue={0}
- value={processData.machineTime}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- machineTime: newValue
- }))
- }
- isConfigured={rulesByField.has(key("machineTime"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Machine Time`,
- field: key("machineTime"),
- code: rulesByField.get(key("machineTime"))?.code,
- defaultValue: processData.machineTime,
- returnType: {
- type: "numeric"
- }
- });
- }
- : undefined
- }
- />
- <StandardFactor
- name="machineUnit"
- label={t`Machine Unit`}
- isOptional={false}
- hint={processData.machineUnitHint}
- value={processData.machineUnit}
- onChange={(newValue) => {
- setProcessData((d) => ({
- ...d,
- machineUnit: newValue?.value ?? "Total Minutes"
- }));
- }}
- isConfigured={rulesByField.has(key("machineUnit"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Machine Unit`,
- field: key("machineUnit"),
- code: rulesByField.get(key("machineUnit"))?.code,
- defaultValue: processData.machineUnit,
- returnType: {
- type: "enum",
- listOptions: standardFactorType
- }
- });
- }
- : undefined
- }
- />
+ </div>
</div>
- </div>
+ )}
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={procedureDisclosure.onToggle}
- >
- <HStack>
- <LuListChecks />
- <Label>Procedure</Label>
- </HStack>
- <HStack>
- {processData.procedureId && (
- <Badge variant="secondary">
- <LuListChecks className="h-3 w-3 mr-1" />
- Procedure
- </Badge>
- )}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- procedureDisclosure.isOpen
- ? "Collapse Procedure"
- : "Expand Procedure"
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuListChecks />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuListChecks className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label={t`Procedure`}
+ processId={processData.processId}
+ value={processData.procedureId}
+ isConfigured={rulesByField.has(key("procedureId"))}
+ onConfigure={
+ configurable && !temporaryItems[item.id]
+ ? () => {
+ onConfigure({
+ label: t`Procedure`,
+ field: key("procedureId"),
+ code: rulesByField.get(key("procedureId"))?.code,
+ defaultValue: processData.procedureId,
+ returnType: {
+ type: "text",
+ helperText:
+ "the unique identifier for the procedure. you can get this from the URL when editing a procedure"
+ }
+ });
+ }
+ : undefined
}
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- procedureDisclosure.onToggle();
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string
+ }));
}}
- className={`transition-transform ${
- procedureDisclosure.isOpen ? "rotate-90" : ""
- }`}
/>
+ </div>
+ </div>
+ )}
+
+ {processData.operationType === "Assembly" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={assemblyDisclosure.onToggle}
+ >
+ <HStack>
+ <OperationTypeIcon type="Assembly" />
+ <Label>Assembly Instruction</Label>
+ </HStack>
+ <HStack>
+ {processData.assemblyInstructionId && (
+ <Badge variant="secondary">
+ <OperationTypeIcon
+ type="Assembly"
+ className="h-3 w-3 mr-1"
+ />
+ Assembly Instruction
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ assemblyDisclosure.isOpen
+ ? "Collapse Assembly Instruction"
+ : "Expand Assembly Instruction"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ assemblyDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ assemblyDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
- procedureDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <Procedure
- name="procedureId"
- label={t`Procedure`}
- processId={processData.processId}
- value={processData.procedureId}
- isConfigured={rulesByField.has(key("procedureId"))}
- onConfigure={
- configurable && !temporaryItems[item.id]
- ? () => {
- onConfigure({
- label: t`Procedure`,
- field: key("procedureId"),
- code: rulesByField.get(key("procedureId"))?.code,
- defaultValue: processData.procedureId,
- returnType: {
- type: "text",
- helperText:
- "the unique identifier for the procedure. you can get this from the URL when editing a procedure"
- }
- });
- }
- : undefined
- }
- onChange={(value) => {
- setProcessData((d) => ({
- ...d,
- procedureId: value?.value as string
- }));
- }}
- />
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ assemblyDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <AssemblyInstruction
+ name="assemblyInstructionId"
+ label={t`Assembly Instruction`}
+ itemId={itemId}
+ value={processData.assemblyInstructionId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ assemblyInstructionId: value?.value as string
+ }));
+ }}
+ />
+ </div>
</div>
- </div>
+ )}
+
+ {processData.operationType === "Inspection" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <OperationTypeIcon type="Inspection" />
+ <Label>Inspection Plan</Label>
+ </HStack>
+ {processData.inspectionDocumentId && (
+ <Badge variant="secondary">
+ <OperationTypeIcon
+ type="Inspection"
+ className="h-3 w-3 mr-1"
+ />
+ Inspection Plan
+ </Badge>
+ )}
+ </HStack>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4">
+ <InspectionDocument
+ name="inspectionDocumentId"
+ label={t`Inspection Plan`}
+ isOptional={false}
+ itemId={itemId}
+ value={processData.inspectionDocumentId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ inspectionDocumentId: value?.value as string
+ }));
+ }}
+ />
+ </div>
+ </div>
+ )}
</>
)}
<motion.div
@@ -1659,6 +1827,8 @@ function AttributesForm({
configurable,
isDisabled,
steps,
+ tools,
+ materials,
temporaryItems,
rulesByField,
onConfigure,
@@ -1668,6 +1838,8 @@ function AttributesForm({
configurable: boolean;
isDisabled: boolean;
steps: OperationStep[];
+ tools: OperationTool[];
+ materials: MethodMaterialType[];
temporaryItems: TemporaryItems;
rulesByField: Map<string, ConfigurationRule>;
onConfigure?: (c: Configuration) => void;
@@ -1735,9 +1907,60 @@ function AttributesForm({
);
const { carbon } = useCarbon();
- const {
- company: { id: companyId }
- } = useUser();
+ const user = useUser();
+ const companyId = user.company.id;
+ const revalidator = useRevalidator();
+
+ // Slides chosen while creating a step are buffered here (the step has no id yet);
+ // they're attached to the new step right after it's created. See the effect below.
+ // A buffered slide is image XOR model (imagePath / modelUploadId).
+ const [draftSlides, setDraftSlides] = useState<
+ {
+ id: string;
+ imagePath: string | null;
+ modelUploadId: string | null;
+ caption: string;
+ size: SlideSize;
+ annotations: SlideAnnotation[];
+ }[]
+ >([]);
+ const [draftUploading, setDraftUploading] = useState(false);
+ const draftFileInputRef = useRef<HTMLInputElement>(null);
+ const draftModelInputRef = useRef<HTMLInputElement>(null);
+
+ // Parts (this operation's BOM materials) the operator can assign to a step. Parts picked
+ // while CREATING a step are buffered here and attached right after the step is created.
+ const operationParts = useMemo(
+ () =>
+ (materials ?? [])
+ .filter((m) => m.methodOperationId === operationId)
+ .map((m) => ({
+ id: m.id,
+ name: m.description || m.itemId,
+ quantity: m.quantity ?? 1
+ })),
+ [materials, operationId]
+ );
+ const [draftParts, setDraftParts] = useState<string[]>([]);
+
+ // Tools (this operation's tools) the operator can assign to a step — the tool twin of
+ // operationParts/draftParts. Tools picked while CREATING a step are buffered here and
+ // attached right after the step is created (see the effect below).
+ const allTools = useTools();
+ const operationTools = useMemo(
+ () =>
+ (tools ?? []).map((tl) => {
+ const tool = allTools.find((x) => x.id === tl.toolId);
+ return {
+ id: tl.id ?? "",
+ name: tool?.readableIdWithRevision ?? tl.toolId ?? "",
+ secondary: tool?.name ?? undefined,
+ quantity: tl.quantity ?? 1
+ };
+ }),
+ [tools, allTools]
+ );
+ const [draftTools, setDraftTools] = useState<string[]>([]);
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
@@ -1757,6 +1980,154 @@ function AttributesForm({
return getPrivateUrl(result.data.path);
};
+ // Upload a chosen image to storage immediately and buffer it as a draft slide.
+ const onAddDraftSlide = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setDraftUploading(true);
+ try {
+ const ext = file.name.split(".").pop();
+ const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
+ const result = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+ if (result.error || !result.data) {
+ toast.error(t`Failed to upload image`);
+ return;
+ }
+ setDraftSlides((prev) => [
+ ...prev,
+ {
+ id: nanoid(),
+ imagePath: result.data.path,
+ modelUploadId: null,
+ caption: "",
+ size: "medium",
+ annotations: []
+ }
+ ]);
+ } finally {
+ setDraftUploading(false);
+ }
+ };
+
+ // Upload a chosen 3D model, register it as a modelUpload (which also kicks the
+ // assembler's STEP → GLB conversion), and buffer it as a draft model slide.
+ const onAddDraftModel = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setDraftUploading(true);
+ try {
+ const modelUploadId = await uploadStepSlideModel(carbon, companyId, file);
+ if (!modelUploadId) {
+ toast.error(t`Failed to upload model`);
+ return;
+ }
+ setDraftSlides((prev) => [
+ ...prev,
+ {
+ id: nanoid(),
+ imagePath: null,
+ modelUploadId,
+ caption: "",
+ size: "medium",
+ annotations: []
+ }
+ ]);
+ } finally {
+ setDraftUploading(false);
+ }
+ };
+
+ // When the new step is created, attach any buffered slides to it, then revalidate so
+ // they show on the step and reset the buffer for the next step.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftSlides.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const slideRows = draftSlides.map((slide, index) => ({
+ stepId: newStepId,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption || null,
+ sortOrder: index + 1,
+ size: slide.size,
+ annotations: slide.annotations,
+ companyId,
+ createdBy: user.id
+ }));
+ const { error } = await carbon
+ .from("methodOperationStepSlide")
+ .insert(slideRows);
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save slides`);
+ return;
+ }
+ setDraftSlides([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
+ // When the new step is created, attach any buffered parts, then revalidate + reset.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftParts.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const { error } = await carbon.from("methodMaterialStep").insert(
+ draftParts.map((methodMaterialId) => ({
+ methodMaterialId,
+ methodOperationStepId: newStepId
+ }))
+ );
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save parts`);
+ return;
+ }
+ setDraftParts([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
+ // When the new step is created, attach any buffered tools, then revalidate + reset.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftTools.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const { error } = await carbon.from("methodOperationToolStep").insert(
+ draftTools.map((methodOperationToolId) => ({
+ methodOperationToolId,
+ methodOperationStepId: newStepId
+ }))
+ );
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save tools`);
+ return;
+ }
+ setDraftTools([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
if (isDisabled && temporaryItems[operationId]) {
return (
<Alert className="max-w-[420px] mx-auto my-8">
@@ -1886,6 +2257,79 @@ function AttributesForm({
<ArrayInput name="listValues" label={t`List Options`} />
)}
+ <SlidesEditor
+ slides={draftSlides.map((slide) => ({
+ key: slide.id,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption,
+ size: slide.size,
+ annotations: slide.annotations
+ }))}
+ isDisabled={isDisabled}
+ busy={draftUploading}
+ fileInputRef={draftFileInputRef}
+ onFileChange={onAddDraftSlide}
+ modelInputRef={draftModelInputRef}
+ onModelFileChange={onAddDraftModel}
+ onRemove={(index) =>
+ setDraftSlides((prev) => prev.filter((_, i) => i !== index))
+ }
+ onCaptionBlur={(index, caption) =>
+ setDraftSlides((prev) =>
+ prev.map((slide, i) =>
+ i === index ? { ...slide, caption } : slide
+ )
+ )
+ }
+ onAnnotationsChange={(index, annotations) =>
+ setDraftSlides((prev) =>
+ prev.map((slide, i) =>
+ i === index ? { ...slide, annotations } : slide
+ )
+ )
+ }
+ />
+
+ <StepLinkEditor
+ label={t`Parts`}
+ addLabel={t`Add parts`}
+ emptyLabel={t`No parts`}
+ searchPlaceholder={t`Search parts...`}
+ removeLabel={t`Remove part`}
+ items={operationParts}
+ linkedIds={draftParts}
+ isDisabled={isDisabled}
+ onAdd={(partId) =>
+ setDraftParts((prev) =>
+ prev.includes(partId) ? prev : [...prev, partId]
+ )
+ }
+ onRemove={(partId) =>
+ setDraftParts((prev) => prev.filter((id) => id !== partId))
+ }
+ />
+
+ <StepLinkEditor
+ label={t`Tools`}
+ addLabel={t`Add tools`}
+ emptyLabel={t`No tools`}
+ searchPlaceholder={t`Search tools...`}
+ removeLabel={t`Remove tool`}
+ icon={<LuHammer />}
+ items={operationTools}
+ linkedIds={draftTools}
+ isDisabled={isDisabled}
+ onAdd={(toolId) =>
+ setDraftTools((prev) =>
+ prev.includes(toolId) ? prev : [...prev, toolId]
+ )
+ }
+ onRemove={(toolId) =>
+ setDraftTools((prev) => prev.filter((id) => id !== toolId))
+ }
+ />
+
<Submit
leftIcon={<LuCirclePlus />}
isDisabled={isDisabled || fetcher.state !== "idle"}
@@ -1921,6 +2365,8 @@ function AttributesForm({
attribute={step}
operationId={operationId}
typeOptions={typeOptions}
+ materials={materials}
+ tools={tools}
isDisabled={isDisabled}
dragControls={dragControls}
className={cn(
@@ -1975,6 +2421,8 @@ function AttributesListItem({
attribute,
operationId,
typeOptions,
+ materials,
+ tools,
className,
configurable,
rulesByField,
@@ -1986,6 +2434,8 @@ function AttributesListItem({
attribute: OperationStep;
operationId: string;
typeOptions: { label: JSX.Element; value: string }[];
+ materials: MethodMaterialType[];
+ tools: OperationTool[];
className?: string;
configurable: boolean;
rulesByField: Map<string, ConfigurationRule>;
@@ -2012,6 +2462,7 @@ function AttributesListItem({
const deleteModalDisclosure = useDisclosure();
const submitted = useRef(false);
const fetcher = useFetcher<typeof editMethodOperationStepAction>();
+ const duplicateFetcher = useFetcher();
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
@@ -2223,6 +2674,14 @@ function AttributesListItem({
{type === "List" && (
<ArrayInput name="listValues" label={t`List Options`} />
)}
+ <StepSlides step={attribute} isDisabled={isDisabled} />
+ <StepParts
+ step={attribute}
+ operationId={operationId}
+ materials={materials}
+ isDisabled={isDisabled}
+ />
+ <StepTools step={attribute} tools={tools} isDisabled={isDisabled} />
<HStack className="w-full justify-end" spacing={2}>
<Button variant="secondary" onClick={disclosure.onClose}>
Cancel
@@ -2341,9 +2800,24 @@ function AttributesListItem({
</HStack>
<div className="flex items-center justify-end gap-2">
<HStack spacing={2}>
- <span className="text-xs text-muted-foreground">
- {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
- </span>
+ {/* Light revision surface: relative time inline, full created + updated
+ history (who / when) on hover. */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-xs text-muted-foreground">
+ {isUpdated ? "Updated" : "Created"}{" "}
+ {formatRelativeTime(date)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <div className="flex flex-col gap-0.5 text-xs">
+ <span>Created {formatRelativeTime(createdAt)}</span>
+ {updatedAt ? (
+ <span>Updated {formatRelativeTime(updatedAt)}</span>
+ ) : null}
+ </div>
+ </TooltipContent>
+ </Tooltip>
<EmployeeAvatar employeeId={person} withName={false} />
</HStack>
{!isDisabled && (
@@ -2359,6 +2833,16 @@ function AttributesListItem({
<DropdownMenuItem onClick={disclosure.onOpen}>
Edit
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ duplicateFetcher.submit(null, {
+ method: "post",
+ action: path.to.duplicateMethodOperationStep(id)
+ })
+ }
+ >
+ Duplicate
+ </DropdownMenuItem>
<DropdownMenuItem
destructive
onClick={deleteModalDisclosure.onOpen}
@@ -2389,6 +2873,280 @@ function AttributesListItem({
);
}
+// Parts assigned to an EXISTING step — the step-side of the part↔step link. Lists this
+// operation's BOM parts and toggles each link immediately via the material route. Replaces
+// the old BOM "Steps" dropdown (assignment now lives on the step).
+function StepParts({
+ step,
+ operationId,
+ materials,
+ isDisabled
+}: {
+ step: OperationStep;
+ operationId: string;
+ materials: MethodMaterialType[];
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+
+ const operationParts = (materials ?? [])
+ .filter((m) => m.methodOperationId === operationId)
+ .map((m) => ({
+ id: m.id,
+ name: m.description || m.itemId,
+ quantity: m.quantity ?? 1
+ }));
+
+ const linkedPartIds = (materials ?? [])
+ .filter((m) =>
+ (m.methodMaterialStep ?? []).some(
+ (s) => s.methodOperationStepId === step.id
+ )
+ )
+ .map((m) => m.id);
+
+ const toggle = (partId: string, linked: boolean) => {
+ if (!step.id) return;
+ const fd = new FormData();
+ fd.append("materialId", partId);
+ fd.append("stepId", step.id);
+ fd.append("linked", String(linked));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.methodOperationStepMaterial
+ });
+ };
+
+ return (
+ <StepLinkEditor
+ label={t`Parts`}
+ addLabel={t`Add parts`}
+ emptyLabel={t`No parts`}
+ searchPlaceholder={t`Search parts...`}
+ removeLabel={t`Remove part`}
+ items={operationParts}
+ linkedIds={linkedPartIds}
+ isDisabled={isDisabled}
+ busy={fetcher.state !== "idle"}
+ onAdd={(id) => toggle(id, true)}
+ onRemove={(id) => toggle(id, false)}
+ />
+ );
+}
+
+// Tools assigned to an EXISTING step — the step-side of the tool↔step link. Lists this
+// operation's tools and toggles each link immediately via the tool route (assignment now
+// lives on the step, not the tool modal). Twin of StepParts.
+function StepTools({
+ step,
+ tools,
+ isDisabled
+}: {
+ step: OperationStep;
+ tools: OperationTool[];
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+ const allTools = useTools();
+
+ const operationTools = (tools ?? []).map((tl) => {
+ const tool = allTools.find((x) => x.id === tl.toolId);
+ return {
+ id: tl.id ?? "",
+ name: tool?.readableIdWithRevision ?? tl.toolId ?? "",
+ secondary: tool?.name ?? undefined,
+ quantity: tl.quantity ?? 1
+ };
+ });
+
+ const linkedToolIds = (tools ?? [])
+ .filter((tl) =>
+ (
+ tl.methodOperationStepIds ??
+ (
+ (
+ tl as {
+ methodOperationToolStep?: { methodOperationStepId: string }[];
+ }
+ ).methodOperationToolStep ?? []
+ ).map((s) => s.methodOperationStepId)
+ ).some((stepId) => stepId === step.id)
+ )
+ .map((tl) => tl.id ?? "");
+
+ const toggle = (toolId: string, linked: boolean) => {
+ if (!step.id) return;
+ const fd = new FormData();
+ fd.append("toolId", toolId);
+ fd.append("stepId", step.id);
+ fd.append("linked", String(linked));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.methodOperationStepTool
+ });
+ };
+
+ return (
+ <StepLinkEditor
+ label={t`Tools`}
+ addLabel={t`Add tools`}
+ emptyLabel={t`No tools`}
+ searchPlaceholder={t`Search tools...`}
+ removeLabel={t`Remove tool`}
+ icon={<LuHammer />}
+ items={operationTools}
+ linkedIds={linkedToolIds}
+ isDisabled={isDisabled}
+ busy={fetcher.state !== "idle"}
+ onAdd={(id) => toggle(id, true)}
+ onRemove={(id) => toggle(id, false)}
+ />
+ );
+}
+
+// Reference images ("slides") for an EXISTING step — upload (one image/slide to the
+// private bucket), caption, delete, persisted immediately via the slide routes. Copied
+// to job/quote by get-method. See .ai/specs/2026-07-14-mes-execution-views.md §4.
+function StepSlides({
+ step,
+ isDisabled
+}: {
+ step: OperationStep;
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+ const captionFetcher = useFetcher();
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId }
+ } = useUser();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const modelInputRef = useRef<HTMLInputElement>(null);
+ const [uploading, setUploading] = useState(false);
+
+ const slides = ((step.methodOperationStepSlide ?? []) as OperationStepSlide[])
+ .slice()
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
+
+ const nextSortOrder = () =>
+ slides.reduce((m, s) => Math.max(m, s.sortOrder ?? 0), 0) + 1;
+
+ const onAddFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon || !step.id) return;
+ setUploading(true);
+ try {
+ const ext = file.name.split(".").pop();
+ const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
+ const result = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+ if (result.error || !result.data) {
+ toast.error(t`Failed to upload image`);
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", step.id);
+ fd.append("imagePath", result.data.path);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newMethodOperationStepSlide
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Upload a 3D model and attach it to the step as a model slide. The model-upload
+ // API also starts the assembler's STEP → GLB conversion.
+ const onAddModelFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon || !step.id) return;
+ setUploading(true);
+ try {
+ const modelUploadId = await uploadStepSlideModel(carbon, companyId, file);
+ if (!modelUploadId) {
+ toast.error(t`Failed to upload model`);
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", step.id);
+ fd.append("modelUploadId", modelUploadId);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newMethodOperationStepSlide
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Update one slide: always carries the required fields (id → the route updates rather
+ // than inserts; stepId + the slide's content field satisfy the validator) plus whatever
+ // changed. Fields not sent are preserved, so a caption edit never wipes size/annotations
+ // and vice-versa.
+ function saveSlide(
+ slide: OperationStepSlide,
+ fields: Record<string, string>
+ ) {
+ const fd = new FormData();
+ fd.append("id", slide.id);
+ fd.append("stepId", slide.stepId);
+ if (slide.imagePath) fd.append("imagePath", slide.imagePath);
+ if (slide.modelUploadId) fd.append("modelUploadId", slide.modelUploadId);
+ fd.append("sortOrder", String(slide.sortOrder ?? 1));
+ for (const [key, value] of Object.entries(fields)) fd.append(key, value);
+ captionFetcher.submit(fd, {
+ method: "post",
+ action: path.to.newMethodOperationStepSlide
+ });
+ }
+
+ return (
+ <SlidesEditor
+ slides={slides.map((s) => ({
+ key: s.id,
+ imagePath: s.imagePath,
+ modelUploadId: s.modelUploadId,
+ caption: s.caption,
+ size: s.size,
+ annotations: s.annotations
+ }))}
+ isDisabled={isDisabled}
+ busy={uploading || fetcher.state !== "idle"}
+ fileInputRef={fileInputRef}
+ onFileChange={onAddFile}
+ modelInputRef={modelInputRef}
+ onModelFileChange={onAddModelFile}
+ onRemove={(index) => {
+ const slide = slides[index];
+ if (!slide) return;
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.deleteMethodOperationStepSlide(slide.id)
+ });
+ }}
+ onCaptionBlur={(index, caption) => {
+ const slide = slides[index];
+ if (slide && (slide.caption ?? "") !== caption)
+ saveSlide(slide, { caption });
+ }}
+ onAnnotationsChange={(index, annotations) => {
+ const slide = slides[index];
+ if (slide)
+ saveSlide(slide, { annotations: JSON.stringify(annotations) });
+ }}
+ />
+ );
+}
+
function ParametersForm({
operationId,
configurable,
@@ -2685,6 +3443,153 @@ function ParametersListItem({
);
}
+// Read-only MES assembly preview for an operation (Phase 3). Mirrors the MES per-step
+// layout: a step pager, the step's first reference slide, the step text, and the tools
+// scoped to that step (unscoped tools show on every step). No live job, no mutations.
+function OperationPreview({
+ steps,
+ tools
+}: {
+ steps: OperationStep[];
+ tools: OperationTool[];
+}) {
+ const { t } = useLingui();
+ const allTools = useTools();
+ const [current, setCurrent] = useState(0);
+
+ const sorted = [...steps].sort(
+ (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)
+ );
+
+ if (sorted.length === 0) {
+ return (
+ <div className="rounded-lg border bg-card p-6 text-center text-sm text-muted-foreground">
+ <Trans>Add steps to preview the operator view.</Trans>
+ </div>
+ );
+ }
+
+ const idx = Math.min(current, sorted.length - 1);
+ const step = sorted[idx];
+ const slides = [...(step.methodOperationStepSlide ?? [])].sort(
+ (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)
+ );
+ // First IMAGE slide for the preview panel — model slides render only in the MES
+ // assembly view; here they'd have no picture to show.
+ const firstImagePath = slides.find((s) => s.imagePath)?.imagePath;
+ const image = firstImagePath ? getPrivateUrl(firstImagePath) : null;
+
+ // Tools scoped to this step + operation-level (no links) tools shown on every step
+ // (tool ↔ step is many-to-many).
+ const stepTools = tools.filter((tl) => {
+ const ids: string[] =
+ tl.methodOperationStepIds ??
+ (
+ (
+ tl as {
+ methodOperationToolStep?: { methodOperationStepId: string }[];
+ }
+ ).methodOperationToolStep ?? []
+ ).map((s) => s.methodOperationStepId);
+ return ids.length === 0 || (!!step.id && ids.includes(step.id));
+ });
+
+ const descriptionHtml =
+ step.description && typeof step.description === "object"
+ ? generateHTML(step.description as Parameters<typeof generateHTML>[0])
+ : "";
+
+ return (
+ <div className="flex flex-col gap-4 rounded-lg border bg-card p-4">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-muted-foreground">
+ {t`Step`} {idx + 1} / {sorted.length}
+ </span>
+ <div className="flex gap-1">
+ <Button
+ variant="ghost"
+ size="md"
+ isIcon
+ aria-label={t`Previous step`}
+ isDisabled={idx <= 0}
+ onClick={() => setCurrent((c) => Math.max(0, c - 1))}
+ >
+ <LuChevronLeft />
+ </Button>
+ <Button
+ variant="ghost"
+ size="md"
+ isIcon
+ aria-label={t`Next step`}
+ isDisabled={idx >= sorted.length - 1}
+ onClick={() =>
+ setCurrent((c) => Math.min(sorted.length - 1, c + 1))
+ }
+ >
+ <LuChevronRight />
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex aspect-video items-center justify-center overflow-hidden rounded-md border bg-muted/40">
+ {image ? (
+ <img
+ src={image}
+ alt=""
+ className="max-h-full max-w-full object-contain"
+ />
+ ) : (
+ <span className="text-xs text-muted-foreground">
+ <Trans>No reference image</Trans>
+ </span>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <span className="flex size-6 items-center justify-center rounded-full bg-foreground text-xs font-bold text-background">
+ {idx + 1}
+ </span>
+ {step.type ? <Badge variant="secondary">{step.type}</Badge> : null}
+ </div>
+ <p className="text-sm font-medium">{step.name ?? t`Step`}</p>
+ {descriptionHtml ? (
+ <div
+ className="prose prose-sm max-w-none text-sm dark:prose-invert"
+ dangerouslySetInnerHTML={{ __html: descriptionHtml }}
+ />
+ ) : null}
+
+ <div className="flex flex-col gap-1 border-t pt-3">
+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
+ <Trans>Tools</Trans>
+ </span>
+ {stepTools.length > 0 ? (
+ stepTools.map((tl, i) => {
+ const tool = allTools.find((x) => x.id === tl.toolId);
+ return (
+ <div key={tl.id ?? i} className="flex items-center gap-2 py-0.5">
+ <LuHammer className="size-3 shrink-0 text-muted-foreground" />
+ <span className="flex-1 text-xs">
+ {tool?.readableIdWithRevision ?? tl.toolId}
+ </span>
+ {tl.quantity > 1 ? (
+ <span className="text-xs text-muted-foreground">
+ ×{tl.quantity}
+ </span>
+ ) : null}
+ </div>
+ );
+ })
+ ) : (
+ <span className="text-xs text-muted-foreground">
+ <Trans>No tools for this step</Trans>
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
+
function ToolsForm({
operationId,
isDisabled,
@@ -2742,6 +3647,9 @@ function ToolsForm({
<Number name="quantity" label={t`Quantity`} />
</div>
+ {/* Tool↔step assignment lives on the step editor now, not here — a tool added
+ from this form starts operation-level (shown on every step in the MES). */}
+
<Submit
leftIcon={<LuCirclePlus />}
isDisabled={isDisabled || fetcher.state !== "idle"}
@@ -2843,6 +3751,9 @@ function ToolsListItem({
<Tool name="toolId" label={t`Tool`} autoFocus />
<Number name="quantity" label={t`Quantity`} />
</div>
+
+ {/* Tool↔step assignment lives on the step editor now (not here). */}
+
<HStack className="w-full justify-end" spacing={2}>
<Button variant="secondary" onClick={disclosure.onClose}>
Cancel
@@ -2944,7 +3855,7 @@ function makeItem(
<h3 className="font-semibold truncate cursor-pointer">
{operation.description}
</h3>
- {operation.operationType === "Outside" && (
+ {operation.operationType === "Outside Processing" && (
<SupplierProcessPreview
processId={operation.processId}
supplierProcessId={operation.operationSupplierProcessId}
@@ -2956,8 +3867,8 @@ function makeItem(
order: operation.operationOrder,
details: (
<HStack spacing={1}>
- {operation.operationType === "Outside" ? (
- <Badge>Outside</Badge>
+ {operation.operationType === "Outside Processing" ? (
+ <Badge>Outside Processing</Badge>
) : (
<>
{(operation?.setupTime ?? 0) > 0 && (
diff --git a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
index 2b1df6b13d..f726be9318 100644
--- a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
@@ -448,6 +448,7 @@ function ShelfLifeFields({
description={t`Output never outlasts its raw materials. Falls back to the fixed duration when no input has an expiry date.`}
value={!!shelfLifeCalculateFromBom}
onChange={(v) => setShelfLifeCalculateFromBom(v)}
+ bordered
/>
</div>
</>
diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
index 6e7cc2c487..1e76a63128 100644
--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
@@ -64,6 +64,7 @@ export function UsedInSkeleton() {
export type UsedInKey =
| Database["public"]["Enums"]["itemType"]
| "assemblyInstructions"
+ | "inspections"
| "issues"
| "jobMaterials"
| "jobs"
@@ -171,16 +172,18 @@ export function UsedInTree({
maxRevision={revisions?.[0]?.revision ?? ""}
hasSizesInsteadOfRevisions={hasSizesInsteadOfRevisions}
/>
- {tree.map((node) => (
- <UsedInItem
- key={node.key}
- filterText={filterText}
- node={node}
- itemReadableIdWithRevision={itemReadableIdWithRevision}
- jobMaterialQuantities={jobMaterialQuantities}
- jobQuantities={jobQuantities}
- />
- ))}
+ {[...tree]
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((node) => (
+ <UsedInItem
+ key={node.key}
+ filterText={filterText}
+ node={node}
+ itemReadableIdWithRevision={itemReadableIdWithRevision}
+ jobMaterialQuantities={jobMaterialQuantities}
+ jobQuantities={jobQuantities}
+ />
+ ))}
</VStack>
</VStack>
);
@@ -531,6 +534,8 @@ function getUseInLink(
return path.to.consumableDetails(child.id);
case "Service":
return path.to.serviceDetails(child.id);
+ case "inspections":
+ return path.to.inspection(child.id);
case "issues":
if (!child.documentId) return "#";
return path.to.issue(child.documentId);
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
index 39464c9e87..d9a23cdcca 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
@@ -175,8 +175,7 @@ const MaterialProperties = ({ data }: MaterialPropertiesProps) => {
| "finishId"
| "materialTypeId"
| "materialId"
- | "mpn"
- | "requiresInspection",
+ | "mpn",
value: string | null
) => {
const formData = new FormData();
@@ -727,27 +726,6 @@ const MaterialProperties = ({ data }: MaterialPropertiesProps) => {
}}
/>
</ValidatedForm>
- {routeData?.materialSummary?.replenishmentSystem?.includes("Buy") && (
- <ValidatedForm
- defaultValues={{
- requiresInspection:
- routeData?.materialSummary?.requiresInspection ?? false
- }}
- validator={z.object({
- requiresInspection: zfd.checkbox()
- })}
- className="w-full"
- >
- <Boolean
- label={t`Requires Inspection`}
- name="requiresInspection"
- variant="small"
- onChange={(value) => {
- onUpdate("requiresInspection", value ? "on" : "off");
- }}
- />
- </ValidatedForm>
- )}
{routeData?.materialSummary?.replenishmentSystem?.includes("Buy") && (
<ValidatedForm
defaultValues={{
diff --git a/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx b/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx
index f7316efc01..6de82fbaf5 100644
--- a/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx
@@ -69,7 +69,6 @@ export function useMaterialNavigation() {
{
name: t`Quality`,
to: path.to.materialQuality(itemId),
- isDisabled: !routeData?.materialSummary?.requiresInspection,
role: ["employee"],
permission: "quality",
icon: LuClipboardCheck,
diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
index 208399903b..94dd79e46a 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
@@ -172,8 +172,7 @@ const PartProperties = ({
| "description"
| "mpn"
| "replenishmentSystem"
- | "unitOfMeasureCode"
- | "requiresInspection",
+ | "unitOfMeasureCode",
value: string | null
) => {
const formData = new FormData();
@@ -747,32 +746,9 @@ const PartProperties = ({
/>
</ValidatedForm>
)}
- {/* Requires Inspection + Manufacturer Part Number are purchasing
- attributes — hidden on the CO affected-item card; they stay editable on
- the part page (non-embedded), same as Active/Tags above. */}
- {!embedded &&
- routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (
- <ValidatedForm
- defaultValues={{
- requiresInspection:
- routeData?.partSummary?.requiresInspection ?? false
- }}
- validator={z.object({
- requiresInspection: zfd.checkbox()
- })}
- className="w-full"
- isReadOnly={isReadOnly}
- >
- <Boolean
- label={t`Requires Inspection`}
- name="requiresInspection"
- variant="small"
- onChange={(value) => {
- onUpdate("requiresInspection", value ? "on" : "off");
- }}
- />
- </ValidatedForm>
- )}
+ {/* Manufacturer Part Number is a purchasing attribute — hidden on the CO
+ affected-item card; it stays editable on the part page (non-embedded),
+ same as Active/Tags above. */}
{!embedded &&
routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (
<ValidatedForm
diff --git a/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx b/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx
index 379ce561ed..d40e4e7c22 100644
--- a/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx
@@ -81,7 +81,6 @@ export function usePartNavigation() {
{
name: t`Quality`,
to: path.to.partQuality(itemId),
- isDisabled: !routeData?.partSummary?.requiresInspection,
role: ["employee"],
permission: "quality",
icon: LuClipboardCheck,
diff --git a/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx b/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx
index 2818373277..aadd7ae890 100644
--- a/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx
+++ b/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx
@@ -60,7 +60,6 @@ export function useServiceNavigation() {
{
name: t`Quality`,
to: path.to.serviceQuality(itemId),
- isDisabled: !routeData?.serviceSummary?.requiresInspection,
role: ["employee"],
permission: "quality",
icon: LuClipboardCheck,
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
index cc9096ec8d..269d5f3b46 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
@@ -125,8 +125,7 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {
| "itemPostingGroupId"
| "toolId"
| "active"
- | "mpn"
- | "requiresInspection",
+ | "mpn",
value: string | null
) => {
const formData = new FormData();
@@ -569,27 +568,6 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {
}}
/>
</ValidatedForm>
- {routeData?.toolSummary?.replenishmentSystem?.includes("Buy") && (
- <ValidatedForm
- defaultValues={{
- requiresInspection:
- (routeData?.toolSummary as any)?.requiresInspection ?? false
- }}
- validator={z.object({
- requiresInspection: zfd.checkbox()
- })}
- className="w-full"
- >
- <Boolean
- label={t`Requires Inspection`}
- name="requiresInspection"
- variant="small"
- onChange={(value) => {
- onUpdate("requiresInspection", value ? "on" : "off");
- }}
- />
- </ValidatedForm>
- )}
{routeData?.toolSummary?.replenishmentSystem?.includes("Buy") && (
<ValidatedForm
defaultValues={{
diff --git a/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx b/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx
index 99a367ce72..18a8543f5e 100644
--- a/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx
@@ -73,7 +73,6 @@ export function useToolNavigation() {
{
name: t`Quality`,
to: path.to.toolQuality(itemId),
- isDisabled: !routeData?.toolSummary?.requiresInspection,
role: ["employee"],
permission: "quality",
icon: LuClipboardCheck,
diff --git a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoryForm.tsx b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoryForm.tsx
index 1d607cea44..d9827c44b0 100644
--- a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoryForm.tsx
+++ b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoryForm.tsx
@@ -74,6 +74,7 @@ const AttributeCategoryForm = ({
label={t`Public`}
termId="attribute-category-public"
description={t`Visible on a user's public profile`}
+ bordered
/>
</VStack>
</DrawerBody>
diff --git a/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx b/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx
index f0c99a21c5..aae6ab8b20 100644
--- a/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx
+++ b/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx
@@ -132,6 +132,7 @@ const AttributeForm = ({
label={t`Self Managed`}
termId="attribute-self-managed"
description={t`Users can update this value for themselves`}
+ bordered
/>
</VStack>
</DrawerBody>
diff --git a/apps/erp/app/modules/people/ui/Shifts/ShiftForm.tsx b/apps/erp/app/modules/people/ui/Shifts/ShiftForm.tsx
index 87b2b736b1..ff050263a1 100644
--- a/apps/erp/app/modules/people/ui/Shifts/ShiftForm.tsx
+++ b/apps/erp/app/modules/people/ui/Shifts/ShiftForm.tsx
@@ -78,13 +78,17 @@ const ShiftForm = ({ initialValues }: ShiftFormProps) => {
<Trans>Days</Trans>
</FormLabel>
<VStack>
- <Boolean name="monday" description={t`Monday`} />
- <Boolean name="tuesday" description={t`Tuesday`} />
- <Boolean name="wednesday" description={t`Wednesday`} />
- <Boolean name="thursday" description={t`Thursday`} />
- <Boolean name="friday" description={t`Friday`} />
- <Boolean name="saturday" description={t`Saturday`} />
- <Boolean name="sunday" description={t`Sunday`} />
+ <Boolean name="monday" description={t`Monday`} bordered />
+ <Boolean name="tuesday" description={t`Tuesday`} bordered />
+ <Boolean
+ name="wednesday"
+ description={t`Wednesday`}
+ bordered
+ />
+ <Boolean name="thursday" description={t`Thursday`} bordered />
+ <Boolean name="friday" description={t`Friday`} bordered />
+ <Boolean name="saturday" description={t`Saturday`} bordered />
+ <Boolean name="sunday" description={t`Sunday`} bordered />
</VStack>
</FormControl>
<CustomFormFields table="shift" />
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index e286476f46..4285c08da2 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -6,7 +6,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Job** — production work order. Statuses: Draft → Planned → Ready → In Progress → Paused → Completed → Closed → Cancelled. `isJobLocked(status)` returns true for Completed/Closed/Cancelled. MUST check before allowing edits.
- **Job Make Method** — a job's manufacturing method (BOM + routing). Root method has `parentMaterialId = null`; sub-assemblies nest via `parentMaterialId`. Created by the `get-method` edge function.
-- **Job Operation** — routing step within a make method. Types: Inside (in-house) or Outside (subcontracted). Statuses: Todo → Ready → In Progress → Done. Ordered by `order` column.
+- **Job Operation** — routing step within a make method. `operationType` (shared enum): `Process`, `Assembly`, `Inspection` (in-house on a work center), or `Outside Processing` (subcontracted to a supplier process). Statuses: Todo → Ready → In Progress → Done. Ordered by `order` column.
- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.
- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.
- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.
@@ -56,7 +56,8 @@ pnpm --filter @carbon/erp test
| `procedure` / `procedureStep` / `procedureParameter` | Versioned work instructions |
| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a "Hold" badge) AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion; "Set view" captures the camera pose), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
| `assemblyInstructionStepMaterial` | BOM parts consumed at a step (`stepId` → `itemId` + optional quantity; stored by itemId so links survive make-method re-versioning; picker limited to the item's make-method BOM; UNIQUE `(stepId, itemId)`). Auto-populated from `assemblyComponentMapping` via `syncAssemblyStepMaterialsFromMappings` — additive only (manual quantities/deletions survive), triggered on step generation, component add, mapping create, and "Match BOM" |
-| `assemblyInstructionStepRequirement` / `assemblyStandardNote` | Per-step tools/fixtures/consumables/notes/media; reusable note templates |
+| `assemblyInstructionStepSlide` | Per-step reference slides (image XOR 3D model via `modelUploadId`, caption, `size`, `annotations` JSONB pins), mirroring `methodOperationStepSlide`; authored in the step editor's Details tab and copied to `jobOperationStepSlide` by the BOP sync / get-method. The former `assemblyInstructionStepRequirement` / `assemblyStandardNote` tables (fixtures/consumables/notes/media) were dropped — a step definition is parts + tools + slides |
+| `assemblyInstructionStepTool` | Tools used at a step (`stepId` → `itemId` of a tool-type item + `quantity`, UNIQUE `(stepId, itemId)`) — `itemId` is the same target `jobOperationTool.toolId` references, so the BOP sync maps rows 1:1 |
| `assemblyComponentMapping` / `assemblyUnit` / `assemblyPlanJob` | Geometry↔BOM item mapping, authored planner units (model-scoped "plan as one component" overrides), and geometry-service plan/convert job tracking. Planning is LAZY — conversion does not chain a plan run; the first "Generate Steps" click (or an explicit re-plan) starts it, pre-creating a Queued `assemblyPlanJob` row the worker adopts via `planJobId`. The clicking tab polls and auto-generates the steps when the plan lands |
| `maintenanceDispatch` / `maintenanceSchedule` | Equipment maintenance tracking |
| `demandForecast` / `demandProjection` | Demand planning data |
@@ -83,6 +84,7 @@ pnpm --filter @carbon/erp test
- `getAssemblyUnits` / `upsertAssemblyUnit` / `deleteAssemblyUnit` — model-scoped "plan as one component" overrides (`assemblyUnit`: `componentNodeIds[]` + optional `itemId`), authored from the BOM tree
- **Unit derivation**: the geometry planner itself auto-detects "detail swarms" — a populated PCB's hundreds of tiny components seated on a board — from pure geometry (`detect_swarm_units`, `crates/planner/src/pipeline2.rs`: a substantial host part + many tiny parts in narrowphase contact with it, each dwarfed by the host; fastener-named parts never join so screws keep their own animations). No BOM or LLM involved. The only TS-side unit source is the user-authored `assemblyUnit` rows ("plan as one component" from the BOM tree), which `loadPlanUnits` (`@carbon/jobs`) sends as `options.units`; the planner merges units for planning and expands them back to member leaves with a named `groups` entry (→ one titled step). Detected groups are ALSO materialized as `assemblyUnit` rows at step generation (`sourceGroupId` = the plan group id, e.g. `swarm:<hostNodeId>`; UNIQUE `(modelUploadId, sourceGroupId)`, upsert DO NOTHING so user renames/edits/deletions win within a plan — a regenerate re-materializes deleted ones) — the Components tab shows them like authored units with an "Auto" badge, and `loadPlanUnits` feeds them back to the planner as caller units so re-plans respect user edits. Flat multi-body STEP uploads (one PRODUCT, many solids, no assembly tree — the common Fusion/SolidWorks export shape) are split into per-solid components by the converter (`crates/occt-bridge` `read_step`), so they plan like proper assemblies instead of one un-plannable blob
- `getFlattenedBomMaterials` — the item's engineering BOM flattened through Make subassemblies; feeds the assembly BOM tree and the per-step material picker
+- `syncAssemblyInstructionToOperation` — Assembly → job-operation re-sync (Kysely txn): copies an instruction's steps (any status) into a `jobOperation` as `jobOperationStep` rows (typed fields mirror 1:1), links per-step BOM parts via `jobMaterialStep` (itemId resolved against the operation's own `jobMaterial`), refreshes slides on synced steps (delete + recreate: the instruction's 3D model leads as a model slide at sortOrder 0, then the step's authored `assemblyInstructionStepSlide` rows), syncs tools (ensures a `jobOperationTool` per distinct tool item — never deleted, quantity only ratchets up — and rebuilds `jobOperationToolStep` links on synced steps), and sets `jobOperation.assemblyInstructionId`. Re-runnable via the `assemblyInstructionStepId` provenance marker (update matched / insert new / delete stale; hand-authored NULL-marker steps untouched; ON DELETE SET NULL demotes to hand-authored). Route `x+/assembly+/$id.sync-bop.tsx` (action-only, `production_update`, guarded to unlocked jobs); UI = "Sync Assembly Steps" on an Assembly operation in `JobBillOfProcess` (`AssemblyStepsSyncModal`), mirroring the "Sync Procedure" flow. **Method/quote operations only store the `assemblyInstructionId` pointer** — they never materialize steps; jobs inherit steps at get-method time (`insertAssemblyDataForJobOperation`, reading straight from the instruction) and re-sync on demand here. The MES assembly view uses the marker for **step-aware 3D playback**: `getAssemblyPlaybackByOperationId` (apps/mes operations.service) loads the linked instruction's GLB/graph/steps and `AssemblyView` mounts the `@carbon/viewer` `AssemblyPlayer` pinned to the operator's current step
## Key Exports
diff --git a/apps/erp/app/modules/production/index.ts b/apps/erp/app/modules/production/index.ts
index ef8f9462f1..5a03a8e61a 100644
--- a/apps/erp/app/modules/production/index.ts
+++ b/apps/erp/app/modules/production/index.ts
@@ -1,3 +1,4 @@
+export * from "./inspectionBalloonAnalyze";
export * from "./production.models";
export * from "./production.service";
// @ts-ignore
diff --git a/apps/erp/app/modules/quality/inspectionBalloonAnalyze.server.ts b/apps/erp/app/modules/production/inspectionBalloonAnalyze.server.ts
similarity index 100%
rename from apps/erp/app/modules/quality/inspectionBalloonAnalyze.server.ts
rename to apps/erp/app/modules/production/inspectionBalloonAnalyze.server.ts
diff --git a/apps/erp/app/modules/quality/inspectionBalloonAnalyze.ts b/apps/erp/app/modules/production/inspectionBalloonAnalyze.ts
similarity index 94%
rename from apps/erp/app/modules/quality/inspectionBalloonAnalyze.ts
rename to apps/erp/app/modules/production/inspectionBalloonAnalyze.ts
index 1a57ffe93c..e426dbe123 100644
--- a/apps/erp/app/modules/quality/inspectionBalloonAnalyze.ts
+++ b/apps/erp/app/modules/production/inspectionBalloonAnalyze.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
/**
- * POST `/api/quality/inspection-document/:inspectionDocumentId/balloon-analyze` — request body
+ * POST `/api/production/inspection-document/:inspectionDocumentId/balloon-analyze` — request body
* uses `balloonRegionAnalysisRequestSchema`. Successful JSON body includes `analysis`
* matching `balloonRegionAnalysisResultSchema`:
*
@@ -15,7 +15,7 @@ import { z } from "zod";
* Server-only vision + prompts: `inspectionBalloonAnalyze.server.ts` (not exported from `index.ts`).
*/
-/** POST body for `/api/quality/inspection-document/:id/balloon-analyze` */
+/** POST body for `/api/production/inspection-document/:id/balloon-analyze` */
export const balloonRegionAnalysisRequestSchema = z.object({
/** Base64-encoded image bytes (no `data:` prefix). */
imageBase64: z.string().min(1).max(28_000_000),
diff --git a/apps/erp/app/modules/quality/inspectionDocumentDb.ts b/apps/erp/app/modules/production/inspectionDocumentDb.ts
similarity index 91%
rename from apps/erp/app/modules/quality/inspectionDocumentDb.ts
rename to apps/erp/app/modules/production/inspectionDocumentDb.ts
index 262d470635..947cbf20f6 100644
--- a/apps/erp/app/modules/quality/inspectionDocumentDb.ts
+++ b/apps/erp/app/modules/production/inspectionDocumentDb.ts
@@ -16,6 +16,14 @@ export type InspectionFeatureRow = {
toleranceMinus: string | null;
unit: string | null;
type: ProcedureStepType;
+ samplingPlanType: Database["public"]["Enums"]["samplingPlanType"] | null;
+ samplingSampleSize: number | null;
+ samplingPercentage: number | null;
+ samplingAql: number | null;
+ samplingInspectionLevel:
+ | Database["public"]["Enums"]["inspectionLevel"]
+ | null;
+ samplingSeverity: Database["public"]["Enums"]["inspectionSeverity"] | null;
createdBy: string;
createdAt: string;
updatedBy: string | null;
diff --git a/apps/erp/app/modules/quality/inspectionDocumentSave.server.ts b/apps/erp/app/modules/production/inspectionDocumentSave.server.ts
similarity index 99%
rename from apps/erp/app/modules/quality/inspectionDocumentSave.server.ts
rename to apps/erp/app/modules/production/inspectionDocumentSave.server.ts
index 85914487d2..4045bfa023 100644
--- a/apps/erp/app/modules/quality/inspectionDocumentSave.server.ts
+++ b/apps/erp/app/modules/production/inspectionDocumentSave.server.ts
@@ -6,7 +6,7 @@ import type {
inspectionSaveBalloonsGeometryPayloadValidator,
inspectionSaveBalloonsPayloadValidator,
inspectionSaveFeaturesPayloadValidator
-} from "./quality.models";
+} from "./production.models";
export type InspectionSaveFeaturesPayload = ReturnType<
typeof inspectionSaveFeaturesPayloadValidator.parse
diff --git a/apps/erp/app/modules/quality/inspectionDocumentSave.test.ts b/apps/erp/app/modules/production/inspectionDocumentSave.test.ts
similarity index 100%
rename from apps/erp/app/modules/quality/inspectionDocumentSave.test.ts
rename to apps/erp/app/modules/production/inspectionDocumentSave.test.ts
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 1819fc2e32..14e8eab81b 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -2,6 +2,11 @@ import type { Database } from "@carbon/database";
import { textToTiptap } from "@carbon/utils";
import { z } from "zod";
import { zfd } from "zod-form-data";
+import {
+ inspectionLevels,
+ inspectionSeverities,
+ samplingPlanTypes
+} from "../quality/samplingStandards";
import {
methodItemType,
methodOperationOrders,
@@ -304,6 +309,8 @@ export const baseJobOperationValidator = z.object({
}),
processId: z.string().min(1, { message: "Process is required" }),
procedureId: zfd.text(z.string().optional()),
+ assemblyInstructionId: zfd.text(z.string().optional()),
+ inspectionDocumentId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
),
@@ -342,7 +349,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationMinimumCost);
}
return true;
@@ -354,7 +361,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationUnitCost);
}
return true;
@@ -366,7 +373,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationLeadTime);
}
return true;
@@ -378,7 +385,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.setupUnit;
}
return true;
@@ -390,7 +397,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.laborUnit;
}
return true;
@@ -402,8 +409,10 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
- return !!data.laborUnit;
+ // Machine only applies to Process operations — Assembly and Inspection
+ // are setup + labor work.
+ if (data.operationType === "Process") {
+ return !!data.machineUnit;
}
return true;
},
@@ -414,7 +423,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.setupTime);
}
return true;
@@ -426,7 +435,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborTime);
}
return true;
@@ -438,7 +447,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineTime);
}
return true;
@@ -450,7 +459,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineRate);
}
return true;
@@ -462,7 +471,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.overheadRate);
}
return true;
@@ -474,7 +483,7 @@ export const jobOperationValidator = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborRate);
}
return true;
@@ -483,6 +492,18 @@ export const jobOperationValidator = baseJobOperationValidator
message: "Labor rate is required",
path: ["laborRate"]
}
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inspection") {
+ return !!data.inspectionDocumentId;
+ }
+ return true;
+ },
+ {
+ message: "Inspection Plan is required",
+ path: ["inspectionDocumentId"]
+ }
);
export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
@@ -493,7 +514,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.workCenterId;
}
return true;
@@ -505,7 +526,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationMinimumCost);
}
return true;
@@ -517,7 +538,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationUnitCost);
}
return true;
@@ -529,7 +550,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationLeadTime);
}
return true;
@@ -541,7 +562,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return !!data.operationSupplierProcessId;
}
return true;
@@ -553,7 +574,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.setupUnit;
}
return true;
@@ -565,7 +586,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.laborUnit;
}
return true;
@@ -577,8 +598,10 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
- return !!data.laborUnit;
+ // Machine only applies to Process operations — Assembly and Inspection
+ // are setup + labor work.
+ if (data.operationType === "Process") {
+ return !!data.machineUnit;
}
return true;
},
@@ -589,7 +612,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.setupTime);
}
return true;
@@ -601,7 +624,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborTime);
}
return true;
@@ -613,7 +636,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineTime);
}
return true;
@@ -625,7 +648,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineRate);
}
return true;
@@ -637,7 +660,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.overheadRate);
}
return true;
@@ -649,7 +672,7 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborRate);
}
return true;
@@ -658,6 +681,18 @@ export const jobOperationValidatorForReleasedJob = baseJobOperationValidator
message: "Labor rate is required",
path: ["laborRate"]
}
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inspection") {
+ return !!data.inspectionDocumentId;
+ }
+ return true;
+ },
+ {
+ message: "Inspection Plan is required",
+ path: ["inspectionDocumentId"]
+ }
);
const baseMaterialValidator = z.object({
@@ -694,6 +729,8 @@ const baseMaterialValidator = z.object({
export const jobMaterialValidator = baseMaterialValidator
.extend({
jobOperationId: zfd.text(z.string().optional())
+ // Per-step assignment (part ↔ step) is many-to-many: the route reads
+ // formData.getAll("jobOperationStepIds") and writes jobMaterialStep rows.
})
.refine(
(data) => {
@@ -735,6 +772,8 @@ export const jobMaterialValidator = baseMaterialValidator
export const jobMaterialValidatorForReleasedJob = baseMaterialValidator
.extend({
jobOperationId: z.string().min(1, { message: "Operation is required" })
+ // Per-step assignment (part ↔ step) is many-to-many: the route reads
+ // formData.getAll("jobOperationStepIds") and writes jobMaterialStep rows.
})
.refine(
(data) => {
@@ -1055,16 +1094,6 @@ export const planConfidences = ["high", "low", "manual"] as const;
export const assemblyStepStatuses = ["Todo", "Review", "Done"] as const;
-export const assemblyRequirementTypes = [
- "Tool",
- "Fixture",
- "Consumable",
- "Note",
- "Media"
-] as const;
-
-export const assemblyNoteSeverities = ["Info", "Caution", "Warning"] as const;
-
const vector3 = z.tuple([z.number(), z.number(), z.number()]);
const quaternion = z.tuple([z.number(), z.number(), z.number(), z.number()]);
@@ -1172,6 +1201,13 @@ export const assemblyInstructionValidator = z.object({
itemId: zfd.text(z.string().optional())
});
+// Assembly → BOP sync: which operation receives the instruction's steps. "method"
+// targets the item's (Draft) make-method operation; "job" targets a live job's
+// operation directly.
+export const syncAssemblyToBopValidator = z.object({
+ operationId: z.string().min(1, { message: "Operation is required" })
+});
+
export type AssemblyModelState =
| "converted" // GLB + graph artifacts exist — ready for the viewer
| "processing" // conversion job is queued or running
@@ -1366,51 +1402,16 @@ export const assemblyStepMaterialValidator = z.object({
sortOrder: zfd.numeric(z.number().min(0).optional())
});
-export const assemblyStepRequirementValidator = z
- .object({
- id: zfd.text(z.string().optional()),
- stepId: z.string().min(1),
- type: z.enum(assemblyRequirementTypes),
- itemId: zfd.text(z.string().optional()),
- name: zfd.text(z.string().optional()),
- text: zfd.text(z.string().optional()),
- severity: zfd.text(z.enum(assemblyNoteSeverities).optional()),
- filePath: zfd.text(z.string().optional()),
- quantity: zfd.numeric(z.number().int().positive().optional())
- })
- .superRefine((data, ctx) => {
- if (data.type === "Note" && !data.text?.trim()) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["text"],
- message: "Note text is required"
- });
- }
- if (data.type === "Media" && !data.filePath?.trim()) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["filePath"],
- message: "A file is required"
- });
- }
- if (
- ["Tool", "Fixture", "Consumable"].includes(data.type) &&
- !data.itemId?.trim() &&
- !data.name?.trim()
- ) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["name"],
- message: "Pick a catalog item or enter a name"
- });
- }
- });
-
-export const assemblyStandardNoteValidator = z.object({
+/**
+ * Tools used at a step. itemId is a tool-type item — the same target
+ * jobOperationTool.toolId references, so the BOP sync maps rows 1:1.
+ */
+export const assemblyStepToolValidator = z.object({
id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }),
- content: z.string().min(1, { message: "Content is required" }),
- severity: z.enum(assemblyNoteSeverities)
+ stepId: z.string().min(1),
+ itemId: z.string().min(1, { message: "Tool is required" }),
+ quantity: zfd.numeric(z.number().int().positive().optional()),
+ sortOrder: zfd.numeric(z.number().min(0).optional())
});
// An assembly unit: model leaf nodes the planner treats as one rigid body — a
@@ -1514,3 +1515,294 @@ export function getJobOrderStatusCategory(
if (status?.supplyJobStatus) return "plannedJob";
return null;
}
+
+// ─── Inspection Documents ─────────────────────────────────────────────────────
+
+export const inspectionDocumentValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: zfd.text(z.string().optional()),
+ partId: z.string().min(1, { message: "Part is required" }),
+ drawingNumber: zfd.text(z.string().optional()),
+ pdfUrl: zfd.text(z.string().optional()),
+ annotations: zfd.text(z.string().optional()),
+ features: zfd.text(z.string().optional())
+});
+
+export const balloonFeatureValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ inspectionDocumentId: z.string().min(1, { message: "Diagram is required" }),
+ balloonNumber: zfd.numeric(z.number().min(1)),
+ description: z.string().min(1, { message: "Description is required" }),
+ nominalValue: zfd.numeric(z.number().optional()),
+ tolerancePlus: zfd.numeric(z.number().optional()),
+ toleranceMinus: zfd.numeric(z.number().optional()),
+ unitOfMeasureCode: zfd.text(z.string().optional())
+});
+
+export const balloonCreateFromPayloadItemValidator = z.object({
+ pageNumber: z.number(),
+ regionX: z.number(),
+ regionY: z.number(),
+ regionWidth: z.number(),
+ regionHeight: z.number(),
+ label: z.string().min(1),
+ xCoordinate: z.number(),
+ yCoordinate: z.number(),
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ description: z.string().nullable().optional()
+});
+
+export const balloonUpdateItemValidator = z.object({
+ id: z.string().min(1),
+ pageNumber: z.number().optional(),
+ regionX: z.number().optional(),
+ regionY: z.number().optional(),
+ regionWidth: z.number().optional(),
+ regionHeight: z.number().optional(),
+ label: z.string().optional(),
+ xCoordinate: z.number().optional(),
+ yCoordinate: z.number().optional(),
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ description: z.string().nullable().optional()
+});
+
+export const balloonDeleteValidator = z.object({
+ ids: z.array(z.string().min(1))
+});
+
+const normalizedCoordinateValidator = z.number().min(0).max(1);
+const normalizedSizeValidator = z.number().gt(0).max(1);
+const pageNumberValidator = z.number().int().min(1);
+
+export const balloonAnchorCreateItemValidator = z
+ .object({
+ pageNumber: pageNumberValidator,
+ regionX: normalizedCoordinateValidator,
+ regionY: normalizedCoordinateValidator,
+ regionWidth: normalizedSizeValidator,
+ regionHeight: normalizedSizeValidator
+ })
+ .strict();
+
+export const balloonCreateItemWithOverlayValidator = z
+ .object({
+ pageNumber: pageNumberValidator,
+ regionX: normalizedCoordinateValidator,
+ regionY: normalizedCoordinateValidator,
+ regionWidth: normalizedSizeValidator,
+ regionHeight: normalizedSizeValidator,
+ label: z.string().min(1),
+ xCoordinate: normalizedCoordinateValidator,
+ yCoordinate: normalizedCoordinateValidator,
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ description: z.string().nullable().optional(),
+ type: z.enum(procedureStepType).optional(),
+ data: z.record(z.unknown()).optional()
+ })
+ .strict();
+
+export const balloonCreateItemsValidator = z.array(
+ z.union([
+ balloonCreateItemWithOverlayValidator,
+ balloonAnchorCreateItemValidator
+ ])
+);
+
+export const balloonUpdateItemsValidator = z.array(
+ balloonUpdateItemValidator.extend({
+ pageNumber: pageNumberValidator.optional(),
+ regionX: normalizedCoordinateValidator.optional(),
+ regionY: normalizedCoordinateValidator.optional(),
+ regionWidth: normalizedSizeValidator.optional(),
+ regionHeight: normalizedSizeValidator.optional(),
+ xCoordinate: normalizedCoordinateValidator.optional(),
+ yCoordinate: normalizedCoordinateValidator.optional(),
+ data: z.record(z.unknown()).optional()
+ })
+);
+
+export const balloonDeleteIdsValidator = z.array(z.string().min(1));
+
+// The document-level default sampling rule (fallback for features without
+// their own rule; the lot-level plan base). Sent by the editor as JSON.
+export const inspectionDocumentSamplingValidator = z.object({
+ samplingPlanType: z.enum(samplingPlanTypes).nullable(),
+ samplingSampleSize: z.number().int().positive().nullable(),
+ samplingPercentage: z.number().positive().max(100).nullable(),
+ samplingAql: z.number().positive().nullable(),
+ samplingInspectionLevel: z.enum(inspectionLevels).nullable(),
+ samplingSeverity: z.enum(inspectionSeverities).nullable()
+});
+
+const inspectionFeatureSamplingFieldsValidator = {
+ samplingPlanType: z.enum(samplingPlanTypes).nullable().optional(),
+ samplingSampleSize: z.number().int().positive().nullable().optional(),
+ samplingPercentage: z.number().positive().max(100).nullable().optional(),
+ samplingAql: z.number().positive().nullable().optional(),
+ samplingInspectionLevel: z.enum(inspectionLevels).nullable().optional(),
+ samplingSeverity: z.enum(inspectionSeverities).nullable().optional()
+};
+
+export const inspectionSaveFeatureCreateItemValidator = z
+ .object({
+ tempId: z.string().min(1),
+ pageNumber: pageNumberValidator,
+ label: z.string().min(1),
+ description: z.string().nullable().optional(),
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ type: z.enum(procedureStepType).optional(),
+ ...inspectionFeatureSamplingFieldsValidator
+ })
+ .strict();
+
+export const inspectionSaveFeatureUpdateItemValidator = z
+ .object({
+ id: z.string().min(1),
+ pageNumber: pageNumberValidator.optional(),
+ label: z.string().min(1).optional(),
+ description: z.string().nullable().optional(),
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ type: z.enum(procedureStepType).optional(),
+ ...inspectionFeatureSamplingFieldsValidator
+ })
+ .strict();
+
+export const inspectionSaveFeaturesPayloadValidator = z
+ .object({
+ create: z.array(inspectionSaveFeatureCreateItemValidator).default([]),
+ update: z.array(inspectionSaveFeatureUpdateItemValidator).default([]),
+ delete: z.array(z.string().min(1)).default([])
+ })
+ .strict();
+
+export const inspectionSaveBalloonGeometryCreateItemValidator = z
+ .object({
+ tempInspectionFeatureId: z.string().min(1).optional(),
+ inspectionFeatureId: z.string().min(1).optional(),
+ tempBalloonAnchorId: z.string().min(1).optional(),
+ pageNumber: pageNumberValidator,
+ regionX: normalizedCoordinateValidator,
+ regionY: normalizedCoordinateValidator,
+ regionWidth: normalizedSizeValidator,
+ regionHeight: normalizedSizeValidator,
+ xCoordinate: normalizedCoordinateValidator,
+ yCoordinate: normalizedCoordinateValidator
+ })
+ .strict()
+ .refine(
+ (data) =>
+ Boolean(data.tempInspectionFeatureId) ||
+ Boolean(data.inspectionFeatureId),
+ { message: "tempInspectionFeatureId or inspectionFeatureId is required" }
+ );
+
+export const inspectionSaveBalloonGeometryUpdateItemValidator = z
+ .object({
+ id: z.string().min(1),
+ pageNumber: pageNumberValidator.optional(),
+ regionX: normalizedCoordinateValidator.optional(),
+ regionY: normalizedCoordinateValidator.optional(),
+ regionWidth: normalizedSizeValidator.optional(),
+ regionHeight: normalizedSizeValidator.optional(),
+ xCoordinate: normalizedCoordinateValidator.optional(),
+ yCoordinate: normalizedCoordinateValidator.optional()
+ })
+ .strict();
+
+export const inspectionSaveBalloonsGeometryPayloadValidator = z
+ .object({
+ create: z
+ .array(inspectionSaveBalloonGeometryCreateItemValidator)
+ .default([]),
+ update: z
+ .array(inspectionSaveBalloonGeometryUpdateItemValidator)
+ .default([]),
+ delete: z.array(z.string().min(1)).default([])
+ })
+ .strict();
+
+/** @deprecated Legacy combined payload; use features + balloons geometry split. */
+export const inspectionSaveBalloonCreateItemValidator = z
+ .object({
+ tempBalloonAnchorId: z.string().min(1),
+ label: z.string().min(1),
+ xCoordinate: normalizedCoordinateValidator,
+ yCoordinate: normalizedCoordinateValidator,
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ description: z.string().nullable().optional(),
+ type: z.enum(procedureStepType).optional()
+ })
+ .strict();
+
+/** @deprecated Legacy combined payload. */
+export const inspectionSaveBalloonUpdateItemValidator = z
+ .object({
+ id: z.string().min(1),
+ label: z.string().min(1).optional(),
+ xCoordinate: normalizedCoordinateValidator.optional(),
+ yCoordinate: normalizedCoordinateValidator.optional(),
+ nominalValue: z.string().nullable().optional(),
+ tolerancePlus: z.string().nullable().optional(),
+ toleranceMinus: z.string().nullable().optional(),
+ unit: z.string().nullable().optional(),
+ description: z.string().nullable().optional(),
+ type: z.enum(procedureStepType).optional()
+ })
+ .strict();
+
+/** @deprecated Legacy combined payload. */
+export const inspectionSaveBalloonsPayloadValidator = z
+ .object({
+ create: z.array(inspectionSaveBalloonCreateItemValidator).default([]),
+ update: z.array(inspectionSaveBalloonUpdateItemValidator).default([]),
+ delete: z.array(z.string().min(1)).default([])
+ })
+ .strict();
+
+export const inspectionSaveAnchorCreateItemValidator = z
+ .object({
+ tempId: z.string().min(1),
+ pageNumber: pageNumberValidator,
+ xCoordinate: normalizedCoordinateValidator,
+ yCoordinate: normalizedCoordinateValidator,
+ width: normalizedSizeValidator,
+ height: normalizedSizeValidator
+ })
+ .strict();
+
+export const inspectionSaveAnchorUpdateItemValidator = z
+ .object({
+ id: z.string().min(1),
+ pageNumber: pageNumberValidator.optional(),
+ xCoordinate: normalizedCoordinateValidator.optional(),
+ yCoordinate: normalizedCoordinateValidator.optional(),
+ width: normalizedSizeValidator.optional(),
+ height: normalizedSizeValidator.optional()
+ })
+ .strict();
+
+export const inspectionSaveAnchorsPayloadValidator = z
+ .object({
+ create: z.array(inspectionSaveAnchorCreateItemValidator).default([]),
+ update: z.array(inspectionSaveAnchorUpdateItemValidator).default([]),
+ delete: z.array(z.string().min(1)).default([])
+ })
+ .strict();
diff --git a/apps/erp/app/modules/production/production.service.test.ts b/apps/erp/app/modules/production/production.service.test.ts
new file mode 100644
index 0000000000..afebcd8eed
--- /dev/null
+++ b/apps/erp/app/modules/production/production.service.test.ts
@@ -0,0 +1,302 @@
+import { describe, expect, it, vi } from "vitest";
+
+// production.service's module graph transitively loads @carbon/glossary, whose
+// module-load-time Lingui `msg` macros aren't transformed under plain vitest and
+// throw. The functions under test need none of it, so stub glossary; the real
+// implementations stay under test.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+
+// The module graph also pulls @carbon/onboarding, whose content builds Lingui
+// `msg` descriptors at module load — the macro isn't transformed under plain
+// vitest, so raw `msg` throws. Stub it to a plain string builder so the content
+// evaluates without the compiler.
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>
+ Array.isArray(strings)
+ ? strings.reduce(
+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),
+ ""
+ )
+ : String(strings)
+}));
+
+const {
+ planAssemblyStepMarkerSync,
+ maxToolQuantityByItem,
+ buildAssemblyToolStepLinks,
+ duplicateJobOperationStep
+} = await import("./production.service");
+
+// ── Assembly → BoP sync: marker reconciliation ───────────────────────────────
+describe("planAssemblyStepMarkerSync", () => {
+ it("maps existing synced steps by their source marker (update targets)", () => {
+ const { targetIdBySourceId } = planAssemblyStepMarkerSync(
+ ["src-1", "src-2"],
+ [
+ { id: "job-1", assemblyInstructionStepId: "src-1" },
+ { id: "job-2", assemblyInstructionStepId: "src-2" }
+ ]
+ );
+ expect(targetIdBySourceId.get("src-1")).toBe("job-1");
+ expect(targetIdBySourceId.get("src-2")).toBe("job-2");
+ });
+
+ it("leaves a brand-new source unmapped (insert target)", () => {
+ const { targetIdBySourceId, staleTargetIds } = planAssemblyStepMarkerSync(
+ ["src-1", "src-new"],
+ [{ id: "job-1", assemblyInstructionStepId: "src-1" }]
+ );
+ expect(targetIdBySourceId.has("src-new")).toBe(false);
+ expect(staleTargetIds).toEqual([]);
+ });
+
+ it("marks a synced step whose source was removed as stale (delete target)", () => {
+ const { staleTargetIds } = planAssemblyStepMarkerSync(
+ ["src-1"],
+ [
+ { id: "job-1", assemblyInstructionStepId: "src-1" },
+ { id: "job-2", assemblyInstructionStepId: "src-removed" }
+ ]
+ );
+ expect(staleTargetIds).toEqual(["job-2"]);
+ });
+});
+
+// ── Assembly → BoP sync: tool quantity ratchet ───────────────────────────────
+describe("maxToolQuantityByItem", () => {
+ it("takes the max quantity any step asks for, defaulting null to 1", () => {
+ const max = maxToolQuantityByItem([
+ { itemId: "T1", quantity: 1 },
+ { itemId: "T1", quantity: 3 },
+ { itemId: "T2", quantity: null }
+ ]);
+ expect(max.get("T1")).toBe(3);
+ expect(max.get("T2")).toBe(1);
+ });
+});
+
+// ── Assembly → BoP sync: tool step links (orphan contract) ────────────────────
+describe("buildAssemblyToolStepLinks", () => {
+ const sourceSteps = [{ id: "src-1" }, { id: "src-2" }];
+ const targetIdBySource = new Map([
+ ["src-1", "job-1"],
+ ["src-2", "job-2"]
+ ]);
+
+ it("links each step's tools to its synced target step", () => {
+ const links = buildAssemblyToolStepLinks(
+ sourceSteps,
+ new Map([
+ ["src-1", [{ itemId: "T1" }]],
+ ["src-2", [{ itemId: "T2" }]]
+ ]),
+ new Map([
+ ["T1", "row-T1"],
+ ["T2", "row-T2"]
+ ]),
+ targetIdBySource
+ );
+ expect(links).toEqual([
+ { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" },
+ { jobOperationToolId: "row-T2", jobOperationStepId: "job-2" }
+ ]);
+ });
+
+ it("produces NO link for a tool dropped from every source step — its jobOperationTool row (never deleted) becomes operation-level, shown on every step", () => {
+ // T2 still has a jobOperationTool row from a prior sync (in toolRowIdByItemId)
+ // but no source step references it anymore. The rebuilt links must omit it.
+ const links = buildAssemblyToolStepLinks(
+ sourceSteps,
+ new Map([["src-1", [{ itemId: "T1" }]]]),
+ new Map([
+ ["T1", "row-T1"],
+ ["T2", "row-T2"]
+ ]),
+ targetIdBySource
+ );
+ expect(links).toEqual([
+ { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" }
+ ]);
+ expect(links.some((l) => l.jobOperationToolId === "row-T2")).toBe(false);
+ });
+});
+
+// ── duplicateJobOperationStep: link-carrying copy ────────────────────────────
+// A tiny fake supabase client: canned rows for selects, records inserts. Only
+// the chain shapes these functions use are supported (.select/.eq/.single, bare
+// await, .insert(...).select("id").single(), bare-await .insert(...)).
+function makeFakeClient(opts: {
+ rows: Record<string, Record<string, unknown>[]>;
+ newIdByTable?: Record<string, string>;
+ errorOnInsert?: string;
+}) {
+ const inserts: { table: string; rows: Record<string, unknown>[] }[] = [];
+
+ function resolve(state: {
+ table: string;
+ op?: "insert";
+ filters: Record<string, unknown>;
+ insertRows?: Record<string, unknown>[];
+ single: boolean;
+ }) {
+ if (state.op === "insert") {
+ inserts.push({ table: state.table, rows: state.insertRows ?? [] });
+ if (opts.errorOnInsert === state.table) {
+ return {
+ data: null,
+ error: { message: `insert failed: ${state.table}` }
+ };
+ }
+ if (state.single) {
+ const id = opts.newIdByTable?.[state.table] ?? `new_${state.table}`;
+ return { data: { id }, error: null };
+ }
+ return { data: null, error: null };
+ }
+ let data = opts.rows[state.table] ?? [];
+ for (const [col, val] of Object.entries(state.filters)) {
+ data = data.filter((r) => r[col] === val);
+ }
+ return state.single
+ ? { data: data[0] ?? null, error: null }
+ : { data, error: null };
+ }
+
+ function builder(table: string) {
+ const state = {
+ table,
+ filters: {} as Record<string, unknown>,
+ op: undefined as "insert" | undefined,
+ insertRows: undefined as Record<string, unknown>[] | undefined,
+ single: false
+ };
+ const b = {
+ select: () => b,
+ eq: (col: string, val: unknown) => {
+ state.filters[col] = val;
+ return b;
+ },
+ insert: (rows: Record<string, unknown> | Record<string, unknown>[]) => {
+ state.op = "insert";
+ state.insertRows = Array.isArray(rows) ? rows : [rows];
+ return b;
+ },
+ single: () => {
+ state.single = true;
+ return Promise.resolve(resolve(state));
+ },
+ then: (onF: (v: unknown) => unknown, onR?: (e: unknown) => unknown) =>
+ Promise.resolve(resolve(state)).then(onF, onR)
+ };
+ return b;
+ }
+
+ return { client: { from: builder } as never, inserts };
+}
+
+describe("duplicateJobOperationStep", () => {
+ function sourceRows() {
+ return {
+ jobOperationStep: [
+ {
+ id: "step-1",
+ operationId: "op-1",
+ name: "Attach bracket",
+ description: null,
+ type: "Task",
+ unitOfMeasureCode: null,
+ minValue: null,
+ maxValue: null,
+ listValues: null,
+ sortOrder: 1
+ },
+ { id: "step-2", operationId: "op-1", sortOrder: 3 }
+ ],
+ jobOperationStepSlide: [
+ {
+ stepId: "step-1",
+ imagePath: "/a.png",
+ modelUploadId: null,
+ caption: "c",
+ sortOrder: 1,
+ size: "medium",
+ annotations: "[]"
+ }
+ ],
+ jobOperationToolStep: [
+ { jobOperationToolId: "tool-1", jobOperationStepId: "step-1" }
+ ],
+ jobMaterialStep: [
+ { jobMaterialId: "mat-1", jobOperationStepId: "step-1" }
+ ]
+ };
+ }
+
+ it("copies the step and carries its slides/tool-links/material-links onto the clone", async () => {
+ const { client, inserts } = makeFakeClient({
+ rows: sourceRows(),
+ newIdByTable: { jobOperationStep: "step-new" }
+ });
+
+ const result = await duplicateJobOperationStep(client, {
+ id: "step-1",
+ companyId: "c1",
+ createdBy: "u1"
+ });
+ expect(result.error).toBeNull();
+ expect(result.data).toEqual({ id: "step-new" });
+
+ const stepInsert = inserts.find((i) => i.table === "jobOperationStep");
+ expect(stepInsert?.rows[0]).toMatchObject({
+ operationId: "op-1",
+ name: "Attach bracket (copy)",
+ sortOrder: 4, // max sibling sortOrder (3) + 1
+ companyId: "c1",
+ createdBy: "u1"
+ });
+
+ // Every child is repointed at the clone.
+ expect(
+ inserts.find((i) => i.table === "jobOperationStepSlide")?.rows[0]
+ ).toMatchObject({
+ stepId: "step-new",
+ imagePath: "/a.png",
+ companyId: "c1"
+ });
+ expect(
+ inserts.find((i) => i.table === "jobOperationToolStep")?.rows
+ ).toEqual([
+ { jobOperationToolId: "tool-1", jobOperationStepId: "step-new" }
+ ]);
+ expect(inserts.find((i) => i.table === "jobMaterialStep")?.rows).toEqual([
+ { jobMaterialId: "mat-1", jobOperationStepId: "step-new" }
+ ]);
+ });
+
+ it("aborts and surfaces the error if copying a child link fails (no further inserts)", async () => {
+ const { client, inserts } = makeFakeClient({
+ rows: sourceRows(),
+ newIdByTable: { jobOperationStep: "step-new" },
+ errorOnInsert: "jobOperationStepSlide"
+ });
+
+ const result = await duplicateJobOperationStep(client, {
+ id: "step-1",
+ companyId: "c1",
+ createdBy: "u1"
+ });
+
+ expect(result.data).toBeNull();
+ expect(result.error).not.toBeNull();
+ // The slide copy failed, so the tool/material link copies must never run.
+ expect(inserts.some((i) => i.table === "jobOperationToolStep")).toBe(false);
+ expect(inserts.some((i) => i.table === "jobMaterialStep")).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 5b45cc6c9b..499d2da5ea 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -31,16 +31,23 @@ import { getEmployeeJob } from "../people";
import type {
MethodType,
operationParameterValidator,
+ operationStepSlideValidator,
operationStepValidator,
operationToolValidator
} from "../shared";
+import { normalizeOperationSourceIds } from "../shared";
+import {
+ listBalloons,
+ listInspectionFeatures,
+ mapBalloonIdsToFeatureIdsForDocument
+} from "./inspectionDocumentDb";
import type {
assemblyInstructionStatuses,
- assemblyNoteSeverities,
- assemblyRequirementTypes,
assemblyStepStatuses,
deadlineTypes,
failureModeValidator,
+ inspectionDocumentSamplingValidator,
+ inspectionDocumentValidator,
jobMaterialValidator,
jobOperationStatus,
jobOperationValidator,
@@ -80,6 +87,8 @@ import type {
JobMaterialSupplyJobLine
} from "./types";
+export { mapBalloonIdsToFeatureIdsForDocument };
+
const logger = getLogger("erp", "production");
export async function convertSalesOrderLinesToJobs(
@@ -506,6 +515,13 @@ export async function deleteJobOperationStep(
return client.from("jobOperationStep").delete().eq("id", id);
}
+export async function deleteJobOperationStepSlide(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("jobOperationStepSlide").delete().eq("id", id);
+}
+
export async function deleteJobOperationParameter(
client: SupabaseClient<Database>,
id: string
@@ -1466,7 +1482,7 @@ export async function getJobMaterialsByMethodId(
) {
return client
.from("jobMaterial")
- .select("*, item(replenishmentSystem)")
+ .select("*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId)")
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true });
}
@@ -1587,7 +1603,7 @@ export async function getJobOperationsByMethodId(
return client
.from("jobOperation")
.select(
- "*, jobOperationTool(*), jobOperationParameter(*), jobOperationStep(*, jobOperationStepRecord(*))"
+ "*, jobOperationTool(*, jobOperationToolStep(jobOperationStepId)), jobOperationParameter(*), jobOperationStep(*, jobOperationStepRecord(*), jobOperationStepSlide(*))"
)
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true });
@@ -1627,7 +1643,7 @@ export async function getOutsideOperationsByJobId(
.select("id, description")
.eq("jobId", jobId)
.eq("companyId", companyId)
- .eq("operationType", "Outside");
+ .eq("operationType", "Outside Processing");
}
export async function getProcedure(
@@ -2964,17 +2980,18 @@ export async function upsertJobOperation(
customFields?: Json;
})
) {
- if ("updatedBy" in jobOperation) {
+ const normalized = normalizeOperationSourceIds(jobOperation);
+ if ("updatedBy" in normalized) {
return client
.from("jobOperation")
- .update(sanitize(jobOperation))
- .eq("id", jobOperation.id)
+ .update(sanitize(normalized))
+ .eq("id", normalized.id)
.select("id")
.single();
}
const operationInsert = await client
.from("jobOperation")
- .insert([jobOperation])
+ .insert([normalized])
.select("id")
.single();
@@ -2984,14 +3001,14 @@ export async function upsertJobOperation(
const operationId = operationInsert.data?.id;
if (!operationId) return operationInsert;
- if (jobOperation.procedureId) {
+ if (normalized.procedureId && "createdBy" in normalized) {
const { error } = await client.functions.invoke("get-method", {
body: {
type: "procedureToOperation",
- sourceId: jobOperation.procedureId,
+ sourceId: normalized.procedureId,
targetId: operationId,
- companyId: jobOperation.companyId,
- userId: jobOperation.createdBy
+ companyId: normalized.companyId,
+ userId: normalized.createdBy
}
});
if (error) {
@@ -3038,6 +3055,162 @@ export async function upsertJobOperationStep(
.single();
}
+// Job-tier twin of duplicateMethodOperationStep (items.service.ts). Deep-copies a job
+// step's DEFINITION — the step row, its slides (incl. size/annotations), and its
+// step-scoped tool + part/material links — but NOT its jobOperationStepRecord rows: those
+// are captured operator results, not part of the template, and must start empty on a copy.
+// NCR linkage (nonConformance*Id) is intentionally dropped so a clone isn't a second step
+// claiming the same containment action.
+export async function duplicateJobOperationStep(
+ client: SupabaseClient<Database>,
+ args: { id: string; companyId: string; createdBy: string }
+): Promise<{ data: { id: string } | null; error: PostgrestError | null }> {
+ const source = await client
+ .from("jobOperationStep")
+ .select("*")
+ .eq("id", args.id)
+ .single();
+ if (source.error || !source.data) {
+ return { data: null, error: source.error };
+ }
+ const src = source.data;
+
+ // Append after the highest sortOrder in the operation.
+ const siblings = await client
+ .from("jobOperationStep")
+ .select("sortOrder")
+ .eq("operationId", src.operationId);
+ const nextSortOrder =
+ (siblings.data ?? []).reduce(
+ (max, s) => Math.max(max, s.sortOrder ?? 0),
+ 0
+ ) + 1;
+
+ const insert = await client
+ .from("jobOperationStep")
+ .insert({
+ operationId: src.operationId,
+ name: `${src.name} (copy)`,
+ description: src.description,
+ type: src.type,
+ unitOfMeasureCode: src.unitOfMeasureCode,
+ minValue: src.minValue,
+ maxValue: src.maxValue,
+ listValues: src.listValues,
+ sortOrder: nextSortOrder,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ })
+ .select("id")
+ .single();
+ if (insert.error || !insert.data) {
+ return { data: null, error: insert.error };
+ }
+ const newStepId = insert.data.id;
+
+ const slides = await client
+ .from("jobOperationStepSlide")
+ .select("*")
+ .eq("stepId", args.id);
+ if (slides.error) {
+ return { data: null, error: slides.error };
+ }
+ if (slides.data && slides.data.length > 0) {
+ const slideRows = slides.data.map((s) => ({
+ stepId: newStepId,
+ imagePath: s.imagePath,
+ modelUploadId: s.modelUploadId,
+ caption: s.caption,
+ sortOrder: s.sortOrder,
+ size: s.size,
+ annotations: s.annotations,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ }));
+ const slideInsert = await client
+ .from("jobOperationStepSlide")
+ .insert(slideRows);
+ if (slideInsert.error) {
+ return { data: null, error: slideInsert.error };
+ }
+ }
+
+ // Copy step-scoped tool links. No join rows = operation-level (shown on every step) and
+ // needs nothing copied; only tools scoped to this step carry a row to repoint at the clone.
+ const toolLinks = await client
+ .from("jobOperationToolStep")
+ .select("jobOperationToolId")
+ .eq("jobOperationStepId", args.id);
+ if (toolLinks.error) {
+ return { data: null, error: toolLinks.error };
+ }
+ if (toolLinks.data && toolLinks.data.length > 0) {
+ const toolLinkInsert = await client.from("jobOperationToolStep").insert(
+ toolLinks.data.map((l) => ({
+ jobOperationToolId: l.jobOperationToolId,
+ jobOperationStepId: newStepId
+ }))
+ );
+ if (toolLinkInsert.error) {
+ return { data: null, error: toolLinkInsert.error };
+ }
+ }
+
+ // Copy step-scoped part/material links (same operation-level-vs-scoped semantics as tools).
+ const materialLinks = await client
+ .from("jobMaterialStep")
+ .select("jobMaterialId")
+ .eq("jobOperationStepId", args.id);
+ if (materialLinks.error) {
+ return { data: null, error: materialLinks.error };
+ }
+ if (materialLinks.data && materialLinks.data.length > 0) {
+ const materialLinkInsert = await client.from("jobMaterialStep").insert(
+ materialLinks.data.map((l) => ({
+ jobMaterialId: l.jobMaterialId,
+ jobOperationStepId: newStepId
+ }))
+ );
+ if (materialLinkInsert.error) {
+ return { data: null, error: materialLinkInsert.error };
+ }
+ }
+
+ return { data: { id: newStepId }, error: null };
+}
+
+// Job-tier twin of upsertMethodOperationStepSlide (items.service.ts). Same generic
+// validator; `stepId` here is a jobOperationStep id. On update we sanitize() so an
+// omitted optional field (caption-only save) never wipes size/annotations.
+export async function upsertJobOperationStepSlide(
+ client: SupabaseClient<Database>,
+ slide:
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ updatedAt: string;
+ })
+) {
+ if ("createdBy" in slide) {
+ return client
+ .from("jobOperationStepSlide")
+ .insert(slide)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("jobOperationStepSlide")
+ .update(sanitize(slide))
+ .eq("id", slide.id)
+ .select("id")
+ .single();
+}
+
export async function upsertJobOperationParameter(
client: SupabaseClient<Database>,
jobOperationParameter:
@@ -3096,6 +3269,86 @@ export async function upsertJobOperationTool(
.single();
}
+// Replace a job tool's step links (part/tool ↔ step is many-to-many). No ids = the tool
+// applies to the whole operation (shown on every step in the MES). Delete-then-insert.
+// Replace a job material's step links (part ↔ step, many-to-many). See above.
+export async function replaceJobMaterialSteps(
+ client: SupabaseClient<Database>,
+ jobMaterialId: string,
+ jobOperationStepIds: string[]
+) {
+ const del = await client
+ .from("jobMaterialStep")
+ .delete()
+ .eq("jobMaterialId", jobMaterialId);
+ if (del.error || jobOperationStepIds.length === 0) return del;
+ return client.from("jobMaterialStep").insert(
+ jobOperationStepIds.map((jobOperationStepId) => ({
+ jobMaterialId,
+ jobOperationStepId
+ }))
+ );
+}
+
+// Toggle a single part↔step link from the STEP side (the step editor's Parts picker).
+// `linked` true = link the material to the step, false = unlink. Idempotent on link.
+export async function setJobMaterialStepLink(
+ client: SupabaseClient<Database>,
+ args: { jobMaterialId: string; jobOperationStepId: string; linked: boolean }
+) {
+ if (args.linked) {
+ return client.from("jobMaterialStep").upsert(
+ [
+ {
+ jobMaterialId: args.jobMaterialId,
+ jobOperationStepId: args.jobOperationStepId
+ }
+ ],
+ {
+ onConflict: "jobMaterialId,jobOperationStepId",
+ ignoreDuplicates: true
+ }
+ );
+ }
+ return client
+ .from("jobMaterialStep")
+ .delete()
+ .eq("jobMaterialId", args.jobMaterialId)
+ .eq("jobOperationStepId", args.jobOperationStepId);
+}
+
+// Toggle a single tool↔step link from the STEP side (the step editor's Tools picker).
+// `linked` true = link the tool to the step, false = unlink. Idempotent on link. Twin of
+// setJobMaterialStepLink.
+export async function setJobOperationToolStepLink(
+ client: SupabaseClient<Database>,
+ args: {
+ jobOperationToolId: string;
+ jobOperationStepId: string;
+ linked: boolean;
+ }
+) {
+ if (args.linked) {
+ return client.from("jobOperationToolStep").upsert(
+ [
+ {
+ jobOperationToolId: args.jobOperationToolId,
+ jobOperationStepId: args.jobOperationStepId
+ }
+ ],
+ {
+ onConflict: "jobOperationToolId,jobOperationStepId",
+ ignoreDuplicates: true
+ }
+ );
+ }
+ return client
+ .from("jobOperationToolStep")
+ .delete()
+ .eq("jobOperationToolId", args.jobOperationToolId)
+ .eq("jobOperationStepId", args.jobOperationStepId);
+}
+
export async function upsertJobMethod(
client: SupabaseClient<Database>,
type: "itemToJob" | "quoteLineToJob",
@@ -3909,6 +4162,19 @@ export async function getAssemblyInstructions(
return query.order("updatedAt", { ascending: false, nullsFirst: false });
}
+export async function getAssemblyInstructionsForItem(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("assemblyInstruction")
+ .select("id, name, version, status")
+ .eq("companyId", companyId)
+ .eq("itemId", itemId)
+ .order("updatedAt", { ascending: false, nullsFirst: false });
+}
+
/**
* Resolves a made item's CAD model for assembly instructions. Items link to
* their model via item.modelUploadId. Conversion to viewer artifacts (GLB +
@@ -4584,7 +4850,57 @@ export async function deleteAssemblyInstructionStep(
return client.from("assemblyInstructionStep").delete().eq("id", id);
}
-export async function getAssemblyInstructionStepRequirements(
+export async function getAssemblyInstructionStepSlides(
+ client: SupabaseClient<Database>,
+ stepIds: string[]
+) {
+ if (stepIds.length === 0) {
+ return { data: [], error: null };
+ }
+ return client
+ .from("assemblyInstructionStepSlide")
+ .select("*")
+ .in("stepId", stepIds)
+ .order("sortOrder", { ascending: true });
+}
+
+export async function upsertAssemblyInstructionStepSlide(
+ client: SupabaseClient<Database>,
+ slide:
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof operationStepSlideValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ updatedAt: string;
+ })
+) {
+ if ("createdBy" in slide) {
+ return client
+ .from("assemblyInstructionStepSlide")
+ .insert(slide)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyInstructionStepSlide")
+ .update(sanitize(slide))
+ .eq("id", slide.id)
+ .select("id")
+ .single();
+}
+
+export async function deleteAssemblyInstructionStepSlide(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyInstructionStepSlide").delete().eq("id", id);
+}
+
+export async function getAssemblyInstructionStepTools(
client: SupabaseClient<Database>,
stepIds: string[]
) {
@@ -4592,23 +4908,18 @@ export async function getAssemblyInstructionStepRequirements(
return { data: [], error: null };
}
return client
- .from("assemblyInstructionStepRequirement")
+ .from("assemblyInstructionStepTool")
.select("*, item(id, name, readableIdWithRevision)")
.in("stepId", stepIds)
.order("sortOrder", { ascending: true });
}
-export async function upsertAssemblyInstructionStepRequirement(
+export async function upsertAssemblyInstructionStepTool(
client: SupabaseClient<Database>,
data: {
id?: string;
stepId: string;
- type: (typeof assemblyRequirementTypes)[number];
- itemId?: string | null;
- name?: string | null;
- text?: string | null;
- severity?: (typeof assemblyNoteSeverities)[number] | null;
- filePath?: string | null;
+ itemId: string;
quantity?: number;
sortOrder?: number;
companyId: string;
@@ -4616,28 +4927,12 @@ export async function upsertAssemblyInstructionStepRequirement(
updatedBy?: string;
}
) {
- // Snapshot the catalog item name so display never needs a join and
- // survives item deletion
- let name = data.name ?? null;
- if (!name && data.itemId) {
- const item = await client
- .from("item")
- .select("name")
- .eq("id", data.itemId)
- .single();
- name = item.data?.name ?? null;
- }
-
if (data.id) {
return client
- .from("assemblyInstructionStepRequirement")
+ .from("assemblyInstructionStepTool")
.update({
- itemId: data.itemId ?? null,
- name,
- text: data.text ?? null,
- severity: data.severity ?? null,
- ...(data.filePath !== undefined ? { filePath: data.filePath } : {}),
- ...(data.quantity !== undefined ? { quantity: data.quantity } : {}),
+ itemId: data.itemId,
+ quantity: data.quantity ?? 1,
...(data.sortOrder !== undefined ? { sortOrder: data.sortOrder } : {}),
updatedBy: data.updatedBy ?? data.createdBy,
updatedAt: new Date().toISOString()
@@ -4648,18 +4943,13 @@ export async function upsertAssemblyInstructionStepRequirement(
}
return client
- .from("assemblyInstructionStepRequirement")
+ .from("assemblyInstructionStepTool")
.insert({
stepId: data.stepId,
- type: data.type,
- itemId: data.itemId ?? null,
- name,
- text: data.text ?? null,
- severity: data.severity ?? null,
- filePath: data.filePath ?? null,
+ itemId: data.itemId,
quantity: data.quantity ?? 1,
sortOrder:
- data.sortOrder ?? (await getNextRequirementSortOrder(client, data)),
+ data.sortOrder ?? (await getNextStepToolSortOrder(client, data)),
companyId: data.companyId,
createdBy: data.createdBy
})
@@ -4667,15 +4957,14 @@ export async function upsertAssemblyInstructionStepRequirement(
.single();
}
-async function getNextRequirementSortOrder(
+async function getNextStepToolSortOrder(
client: SupabaseClient<Database>,
- data: { stepId: string; type: (typeof assemblyRequirementTypes)[number] }
+ data: { stepId: string }
) {
const last = await client
- .from("assemblyInstructionStepRequirement")
+ .from("assemblyInstructionStepTool")
.select("sortOrder")
.eq("stepId", data.stepId)
- .eq("type", data.type)
.order("sortOrder", { ascending: false })
.limit(1)
.maybeSingle();
@@ -4683,40 +4972,11 @@ async function getNextRequirementSortOrder(
return (last.data?.sortOrder ?? 0) + 1;
}
-export async function getAssemblyInstructionStepRequirement(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client
- .from("assemblyInstructionStepRequirement")
- .select("*")
- .eq("id", id)
- .single();
-}
-
-export async function updateAssemblyInstructionStepRequirementOrder(
- db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
-) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("assemblyInstructionStepRequirement")
- .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
- .where("id", "=", id)
- .execute();
- }
- });
-}
-
-export async function deleteAssemblyInstructionStepRequirement(
+export async function deleteAssemblyInstructionStepTool(
client: SupabaseClient<Database>,
id: string
) {
- return client
- .from("assemblyInstructionStepRequirement")
- .delete()
- .eq("id", id);
+ return client.from("assemblyInstructionStepTool").delete().eq("id", id);
}
export async function getAssemblyInstructionStepMaterials(
@@ -4975,64 +5235,6 @@ export async function syncAssemblyStepMaterialsFromMappings(
return { created: insert.error ? 0 : seeds.length };
}
-export async function getAssemblyStandardNotes(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("assemblyStandardNote")
- .select("*")
- .eq("companyId", companyId)
- .order("name", { ascending: true });
-}
-
-export async function upsertAssemblyStandardNote(
- client: SupabaseClient<Database>,
- data: {
- id?: string;
- name: string;
- content: string;
- severity: (typeof assemblyNoteSeverities)[number];
- companyId: string;
- createdBy: string;
- updatedBy?: string;
- }
-) {
- if (data.id) {
- return client
- .from("assemblyStandardNote")
- .update({
- name: data.name,
- content: data.content,
- severity: data.severity,
- updatedBy: data.updatedBy ?? data.createdBy,
- updatedAt: new Date().toISOString()
- })
- .eq("id", data.id)
- .select("id")
- .single();
- }
-
- return client
- .from("assemblyStandardNote")
- .insert({
- name: data.name,
- content: data.content,
- severity: data.severity,
- companyId: data.companyId,
- createdBy: data.createdBy
- })
- .select("id")
- .single();
-}
-
-export async function deleteAssemblyStandardNote(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("assemblyStandardNote").delete().eq("id", id);
-}
-
export async function getAssemblyUnits(
client: SupabaseClient<Database>,
modelUploadId: string
@@ -5500,23 +5702,492 @@ type GenerateStepsResult =
message?: string;
};
+// Minimal tiptap document wrapping a plain-text instruction, for source steps that
+// have text but no rich description.
+function plainTextToTiptap(text: string) {
+ return {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }]
+ };
+}
+
/**
- * Creates draft steps from the motion plan: walks the planned assembly
- * sequence, groups consecutive identical parts (same geometry, same motion
- * shape) into one step, and inserts them in order with status Review. Parts
- * the planner flagged (blockedBy: no collision-free path exists) are stored
- * with motion "none" plus a `warnings` payload — the viewer fades them in
- * rather than animating a fabricated colliding path. The author
- * validates/edits the drafts instead of authoring motions by hand.
+ * Assembly → BOP sync: copy a Published instruction's steps into a BOP operation
+ * as real method/job operation steps (the typed fields mirror by design), link
+ * each step's BOM parts via the material↔step join table, attach the
+ * instruction's 3D model as a model slide on every synced step, and point the
+ * operation at the instruction. Re-runnable: rows carry an
+ * `assemblyInstructionStepId` provenance marker, so a re-sync updates matched
+ * steps in place (keeping their ids — slides, records, and links survive),
+ * inserts new ones, and deletes synced steps whose source step is gone.
+ * Hand-authored steps (NULL marker) are never touched. One transaction: a
+ * half-synced BOP would be a real bug. Guards (Draft method / unlocked job,
+ * permissions) belong to the route — Kysely bypasses RLS.
*/
-export async function generateAssemblyStepsFromPlan(
- client: SupabaseClient<Database>,
+/**
+ * Marker-based step reconciliation for the assembly→BoP sync. Given the current
+ * source step ids and the operation's existing synced steps (each carrying the
+ * `assemblyInstructionStepId` provenance marker), decide which source maps onto
+ * an existing target (update) vs. is new (insert), and which existing synced
+ * steps are stale — their source step was removed, so they must be deleted
+ * (cascading their slides/links). Hand-authored steps (null marker) are excluded
+ * by the caller's `assemblyInstructionStepId is not null` filter; a null marker
+ * here is treated as stale. Pure so the reconciliation is unit-testable.
+ */
+export function planAssemblyStepMarkerSync(
+ sourceStepIds: string[],
+ existingSynced: { id: string; assemblyInstructionStepId: string | null }[]
+): { targetIdBySourceId: Map<string, string>; staleTargetIds: string[] } {
+ const targetIdBySourceId = new Map<string, string>();
+ for (const step of existingSynced) {
+ if (step.assemblyInstructionStepId) {
+ targetIdBySourceId.set(step.assemblyInstructionStepId, step.id);
+ }
+ }
+ const sourceIdSet = new Set(sourceStepIds);
+ const staleTargetIds = existingSynced
+ .filter(
+ (step) =>
+ !step.assemblyInstructionStepId ||
+ !sourceIdSet.has(step.assemblyInstructionStepId)
+ )
+ .map((step) => step.id);
+ return { targetIdBySourceId, staleTargetIds };
+}
+
+/**
+ * The re-sync ratchets a tool's operation-level quantity up to the max quantity
+ * any source step asks for (operation-level rows are never lowered or deleted).
+ */
+export function maxToolQuantityByItem(
+ sourceTools: { itemId: string; quantity: number | null }[]
+): Map<string, number> {
+ const max = new Map<string, number>();
+ for (const tool of sourceTools) {
+ max.set(
+ tool.itemId,
+ Math.max(max.get(tool.itemId) ?? 0, tool.quantity ?? 1)
+ );
+ }
+ return max;
+}
+
+/**
+ * Build the `jobOperationToolStep` link rows for a re-sync. Links are rebuilt
+ * ONLY from the current source tools, so a tool removed from the instruction —
+ * whose `jobOperationTool` row is intentionally never deleted — ends up with
+ * zero links and therefore behaves as an operation-level tool (shown on every
+ * step). That is the documented re-sync contract; this returns exactly the links
+ * to (re)insert on the synced steps.
+ */
+export function buildAssemblyToolStepLinks(
+ sourceSteps: { id: string }[],
+ toolsByStep: Map<string, { itemId: string }[]>,
+ toolRowIdByItemId: Map<string, string>,
+ targetIdBySource: Map<string, string>
+): { jobOperationToolId: string; jobOperationStepId: string }[] {
+ const rows: { jobOperationToolId: string; jobOperationStepId: string }[] = [];
+ for (const source of sourceSteps) {
+ const targetStepId = targetIdBySource.get(source.id);
+ if (!targetStepId) continue;
+ for (const tool of toolsByStep.get(source.id) ?? []) {
+ const jobOperationToolId = toolRowIdByItemId.get(tool.itemId);
+ if (jobOperationToolId) {
+ rows.push({ jobOperationToolId, jobOperationStepId: targetStepId });
+ }
+ }
+ }
+ return rows;
+}
+
+export async function syncAssemblyInstructionToOperation(
+ db: Kysely<KyselyDatabase>,
args: {
assemblyInstructionId: string;
+ operationId: string;
companyId: string;
userId: string;
- /**
- * "regenerate" replaces the existing steps with fresh drafts from the
+ }
+) {
+ const { assemblyInstructionId, operationId, companyId, userId } = args;
+ const stepTable = "jobOperationStep" as const;
+ const slideTable = "jobOperationStepSlide" as const;
+
+ return db.transaction().execute(async (trx) => {
+ const instruction = await trx
+ .selectFrom("assemblyInstruction")
+ .select(["id", "itemId", "modelUploadId"])
+ .where("id", "=", assemblyInstructionId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!instruction) throw new Error("Assembly instruction not found");
+
+ const sourceSteps = await trx
+ .selectFrom("assemblyInstructionStep")
+ .select([
+ "id",
+ "title",
+ "type",
+ "description",
+ "instructionText",
+ "required",
+ "unitOfMeasureCode",
+ "minValue",
+ "maxValue",
+ "listValues",
+ "fileTypes",
+ "sortOrder"
+ ])
+ .where("assemblyInstructionId", "=", instruction.id)
+ .where("companyId", "=", companyId)
+ .orderBy("sortOrder", "asc")
+ .execute();
+ if (sourceSteps.length === 0) {
+ throw new Error("The assembly instruction has no steps to sync");
+ }
+
+ const sourceMaterials = await trx
+ .selectFrom("assemblyInstructionStepMaterial")
+ .select(["stepId", "itemId"])
+ .where("companyId", "=", companyId)
+ .where(
+ "stepId",
+ "in",
+ sourceSteps.map((step) => step.id)
+ )
+ .execute();
+ const materialsByStep = new Map<string, string[]>();
+ for (const material of sourceMaterials) {
+ const list = materialsByStep.get(material.stepId) ?? [];
+ list.push(material.itemId);
+ materialsByStep.set(material.stepId, list);
+ }
+
+ const sourceSlides = await trx
+ .selectFrom("assemblyInstructionStepSlide")
+ .select([
+ "stepId",
+ "imagePath",
+ "modelUploadId",
+ "caption",
+ "sortOrder",
+ "size",
+ "annotations"
+ ])
+ .where("companyId", "=", companyId)
+ .where(
+ "stepId",
+ "in",
+ sourceSteps.map((step) => step.id)
+ )
+ .orderBy("sortOrder", "asc")
+ .execute();
+ const slidesByStep = new Map<string, typeof sourceSlides>();
+ for (const slide of sourceSlides) {
+ const list = slidesByStep.get(slide.stepId) ?? [];
+ list.push(slide);
+ slidesByStep.set(slide.stepId, list);
+ }
+
+ const sourceTools = await trx
+ .selectFrom("assemblyInstructionStepTool")
+ .select(["stepId", "itemId", "quantity"])
+ .where("companyId", "=", companyId)
+ .where(
+ "stepId",
+ "in",
+ sourceSteps.map((step) => step.id)
+ )
+ .execute();
+ const toolsByStep = new Map<
+ string,
+ { itemId: string; quantity: number }[]
+ >();
+ for (const tool of sourceTools) {
+ const list = toolsByStep.get(tool.stepId) ?? [];
+ list.push({ itemId: tool.itemId, quantity: tool.quantity ?? 1 });
+ toolsByStep.set(tool.stepId, list);
+ }
+
+ // The target operation's own BOM lines, keyed by item — instruction step
+ // materials are itemIds; the link table wants the material row on THIS
+ // operation (a link to another operation's material never shows in the MES).
+ const operationMaterials = await trx
+ .selectFrom("jobMaterial")
+ .select(["id", "itemId"])
+ .where("jobOperationId", "=", operationId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const materialIdByItemId = new Map<string, string>();
+ for (const material of operationMaterials) {
+ if (material.itemId && !materialIdByItemId.has(material.itemId)) {
+ materialIdByItemId.set(material.itemId, material.id);
+ }
+ }
+
+ const existingSynced = await trx
+ .selectFrom(stepTable)
+ .select(["id", "assemblyInstructionStepId"])
+ .where("operationId", "=", operationId)
+ .where("companyId", "=", companyId)
+ .where("assemblyInstructionStepId", "is not", null)
+ .execute();
+ const { targetIdBySourceId, staleTargetIds } = planAssemblyStepMarkerSync(
+ sourceSteps.map((step) => step.id),
+ existingSynced
+ );
+
+ const now = new Date().toISOString();
+ let created = 0;
+ let updated = 0;
+ const syncedTargetIds: string[] = [];
+ // source assembly step id → synced job step id, for slide/tool copying
+ const targetIdBySource = new Map<string, string>();
+ const linkPairs: { materialId: string; stepId: string }[] = [];
+ let partsUnmatched = 0;
+
+ for (const [index, source] of sourceSteps.entries()) {
+ const payload = {
+ name: source.title || `Step ${index + 1}`,
+ type: source.type ?? "Task",
+ description:
+ source.description ??
+ (source.instructionText
+ ? plainTextToTiptap(source.instructionText)
+ : null),
+ required: source.required ?? false,
+ unitOfMeasureCode: source.unitOfMeasureCode,
+ minValue: source.minValue,
+ maxValue: source.maxValue,
+ listValues: source.listValues,
+ fileTypes: source.fileTypes,
+ sortOrder: source.sortOrder ?? index + 1
+ };
+
+ const existingId = targetIdBySourceId.get(source.id);
+ let targetStepId: string;
+ if (existingId) {
+ await trx
+ .updateTable(stepTable)
+ .set({ ...payload, updatedBy: userId, updatedAt: now })
+ .where("id", "=", existingId)
+ .where("companyId", "=", companyId)
+ .execute();
+ targetStepId = existingId;
+ updated++;
+ } else {
+ const inserted = await trx
+ .insertInto(stepTable)
+ .values({
+ ...payload,
+ operationId,
+ assemblyInstructionStepId: source.id,
+ companyId,
+ createdBy: userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ targetStepId = inserted.id;
+ created++;
+ }
+ syncedTargetIds.push(targetStepId);
+ targetIdBySource.set(source.id, targetStepId);
+
+ for (const itemId of materialsByStep.get(source.id) ?? []) {
+ const materialId = materialIdByItemId.get(itemId);
+ if (materialId) {
+ linkPairs.push({ materialId, stepId: targetStepId });
+ } else {
+ partsUnmatched++;
+ }
+ }
+ }
+
+ // Synced steps whose source step no longer exists — deleting cascades their
+ // slides and material/tool step links (staleTargetIds computed above).
+ if (staleTargetIds.length > 0) {
+ await trx
+ .deleteFrom(stepTable)
+ .where("id", "in", staleTargetIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ // Refresh part links on the synced steps only (hand-authored steps keep theirs).
+ await trx
+ .deleteFrom("jobMaterialStep")
+ .where("jobOperationStepId", "in", syncedTargetIds)
+ .execute();
+ if (linkPairs.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(
+ linkPairs.map((pair) => ({
+ jobMaterialId: pair.materialId,
+ jobOperationStepId: pair.stepId
+ }))
+ )
+ .execute();
+ }
+
+ // Refresh slides on the synced steps only (hand-authored steps keep theirs):
+ // the instruction's 3D model leads as a model slide, followed by the step's
+ // authored slides. Delete + recreate mirrors the jobMaterialStep refresh —
+ // the assembly instruction is authoritative for what a synced step shows.
+ await trx
+ .deleteFrom(slideTable)
+ .where("stepId", "in", syncedTargetIds)
+ .execute();
+ const slideRows: {
+ stepId: string;
+ imagePath: string | null;
+ modelUploadId: string | null;
+ caption: string | null;
+ sortOrder: number;
+ size: string;
+ annotations: string;
+ companyId: string;
+ createdBy: string;
+ }[] = [];
+ for (const source of sourceSteps) {
+ const targetStepId = targetIdBySource.get(source.id);
+ if (!targetStepId) continue;
+ const authored = slidesByStep.get(source.id) ?? [];
+ if (
+ instruction.modelUploadId &&
+ !authored.some(
+ (slide) => slide.modelUploadId === instruction.modelUploadId
+ )
+ ) {
+ slideRows.push({
+ stepId: targetStepId,
+ imagePath: null,
+ modelUploadId: instruction.modelUploadId,
+ caption: null,
+ sortOrder: 0,
+ size: "medium",
+ annotations: JSON.stringify([]),
+ companyId,
+ createdBy: userId
+ });
+ }
+ for (const slide of authored) {
+ slideRows.push({
+ stepId: targetStepId,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption,
+ sortOrder: slide.sortOrder ?? 1,
+ size: slide.size ?? "medium",
+ annotations: JSON.stringify(slide.annotations ?? []),
+ companyId,
+ createdBy: userId
+ });
+ }
+ }
+ if (slideRows.length > 0) {
+ await trx.insertInto(slideTable).values(slideRows).execute();
+ }
+
+ // Tools: ensure a jobOperationTool row per distinct tool item, then refresh
+ // the step links on the synced steps. Operation-level tool rows are never
+ // deleted (no provenance column) and quantities only ratchet up, so
+ // hand-added tools survive a re-sync.
+ const existingTools = await trx
+ .selectFrom("jobOperationTool")
+ .select(["id", "toolId", "quantity"])
+ .where("operationId", "=", operationId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const toolRowIdByItemId = new Map(
+ existingTools.map((tool) => [tool.toolId, tool.id])
+ );
+ const maxQuantityByItemId = maxToolQuantityByItem(sourceTools);
+ for (const [itemId, quantity] of maxQuantityByItemId) {
+ const existingId = toolRowIdByItemId.get(itemId);
+ if (!existingId) {
+ const inserted = await trx
+ .insertInto("jobOperationTool")
+ .values({
+ operationId,
+ toolId: itemId,
+ quantity,
+ companyId,
+ createdBy: userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ toolRowIdByItemId.set(itemId, inserted.id);
+ } else {
+ const existing = existingTools.find((tool) => tool.id === existingId);
+ if ((existing?.quantity ?? 1) < quantity) {
+ await trx
+ .updateTable("jobOperationTool")
+ .set({ quantity, updatedBy: userId, updatedAt: now })
+ .where("id", "=", existingId)
+ .execute();
+ }
+ }
+ }
+ await trx
+ .deleteFrom("jobOperationToolStep")
+ .where("jobOperationStepId", "in", syncedTargetIds)
+ .execute();
+ const toolLinkRows = buildAssemblyToolStepLinks(
+ sourceSteps,
+ toolsByStep,
+ toolRowIdByItemId,
+ targetIdBySource
+ );
+ if (toolLinkRows.length > 0) {
+ await trx
+ .insertInto("jobOperationToolStep")
+ .values(toolLinkRows)
+ .execute();
+ }
+
+ // Point the operation at its instruction (also how the re-sync UI knows
+ // what this operation was synced from).
+ await trx
+ .updateTable("jobOperation")
+ .set({
+ assemblyInstructionId: instruction.id,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", operationId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ return {
+ created,
+ updated,
+ deleted: staleTargetIds.length,
+ partsLinked: linkPairs.length,
+ partsUnmatched,
+ slidesSynced: slideRows.length,
+ toolsLinked: toolLinkRows.length
+ };
+ });
+}
+
+/**
+ * Creates draft steps from the motion plan: walks the planned assembly
+ * sequence, groups consecutive identical parts (same geometry, same motion
+ * shape) into one step, and inserts them in order with status Review. Parts
+ * the planner flagged (blockedBy: no collision-free path exists) are stored
+ * with motion "none" plus a `warnings` payload — the viewer fades them in
+ * rather than animating a fabricated colliding path. The author
+ * validates/edits the drafts instead of authoring motions by hand.
+ */
+export async function generateAssemblyStepsFromPlan(
+ client: SupabaseClient<Database>,
+ args: {
+ assemblyInstructionId: string;
+ companyId: string;
+ userId: string;
+ /**
+ * "regenerate" replaces the existing steps with fresh drafts from the
* latest plan — refused while any step is manually authored
* (planConfidence "manual") or already Done.
*/
@@ -5856,3 +6527,611 @@ export async function getJobMaterialSupplyJobLines(
status: job.status
}));
}
+
+// ─── Inspection Documents ─────────────────────────────────────────────────────
+
+function toStoragePath(pdfUrl?: string | null) {
+ if (!pdfUrl) return null;
+ const previewPrefix = "/file/preview/private/";
+ if (pdfUrl.startsWith(previewPrefix)) {
+ return pdfUrl.slice(previewPrefix.length);
+ }
+ return pdfUrl;
+}
+
+function toPreviewUrl(storagePath?: string | null) {
+ if (!storagePath) return null;
+ return storagePath.startsWith("/file/preview/private/")
+ ? storagePath
+ : `/file/preview/private/${storagePath}`;
+}
+
+function fileNameFromPath(storagePath?: string | null) {
+ if (!storagePath) return "drawing.pdf";
+ return storagePath.split("/").at(-1) ?? "drawing.pdf";
+}
+
+function mapInspectionDocument(row: Record<string, unknown>) {
+ const drawingNumber = (row.drawingNumber as string | null) ?? null;
+ return {
+ id: String(row.id),
+ name: String(drawingNumber ?? row.fileName ?? "Untitled Diagram"),
+ companyId: String(row.companyId),
+ partId: (row.partId as string | null) ?? null,
+ createdBy: String(row.createdBy),
+ updatedBy: (row.updatedBy as string | null) ?? null,
+ createdAt: String(row.createdAt),
+ updatedAt: (row.updatedAt as string | null) ?? null,
+ content: {
+ drawingNumber,
+ pdfUrl: toPreviewUrl((row.storagePath as string | null) ?? null),
+ annotations: [],
+ features: []
+ },
+ // The document's default sampling rule (feature rule -> document default
+ // -> All). NUMERIC columns arrive as strings from PostgREST — coerce.
+ sampling: {
+ samplingPlanType: (row.samplingPlanType as string | null) ?? null,
+ samplingSampleSize: (row.samplingSampleSize as number | null) ?? null,
+ samplingPercentage:
+ row.samplingPercentage == null ? null : Number(row.samplingPercentage),
+ samplingAql: row.samplingAql == null ? null : Number(row.samplingAql),
+ samplingInspectionLevel:
+ (row.samplingInspectionLevel as string | null) ?? null,
+ samplingSeverity: (row.samplingSeverity as string | null) ?? null
+ }
+ };
+}
+
+export async function getInspectionDocuments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: { search: string | null } & GenericQueryFilters
+) {
+ const documentClient = client as unknown as {
+ from: (table: string) => {
+ select: (
+ columns: string,
+ options?: { count?: "exact" | "planned" | "estimated"; head?: boolean }
+ ) => any;
+ };
+ };
+
+ let query = documentClient
+ .from("inspectionDocuments")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.or(
+ `drawingNumber.ilike.%${args.search}%,fileName.ilike.%${args.search}%,partReadableId.ilike.%${args.search}%`
+ );
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "drawingNumber", ascending: true }
+ ]);
+ }
+
+ const result = await query;
+
+ return {
+ data: (result.data ?? []).map((row: Record<string, unknown>) =>
+ mapInspectionDocument(row)
+ ),
+ count: result.count ?? 0,
+ error: result.error
+ };
+}
+
+export async function getInspectionDocumentsForItem(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("inspectionDocument")
+ .select("id, fileName, drawingNumber, version")
+ .eq("companyId", companyId)
+ .eq("partId", itemId)
+ .order("updatedAt", { ascending: false, nullsFirst: false });
+}
+
+export async function getInspectionDocument(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ const result = await client
+ .from("inspectionDocument")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ return {
+ data: result.data ? mapInspectionDocument(result.data) : null,
+ error: result.error
+ };
+}
+
+/**
+ * When an inspection plan is created without a drawing number, fall back to the
+ * part's readableIdWithRevision. If a plan with that drawing number already
+ * exists for the company, append " (1)", " (2)", etc. until it is unique.
+ */
+async function resolveInspectionDocumentDrawingNumber(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ partId: string
+): Promise<string | null> {
+ const partResult = await client
+ .from("item")
+ .select("readableIdWithRevision")
+ .eq("id", partId)
+ .eq("companyId", companyId)
+ .single();
+
+ const base = partResult.data?.readableIdWithRevision?.trim();
+ if (!base) return null;
+
+ const existingResult = await client
+ .from("inspectionDocument")
+ .select("drawingNumber")
+ .eq("companyId", companyId)
+ .not("drawingNumber", "is", null);
+
+ const taken = new Set(
+ (existingResult.data ?? [])
+ .map((row) => row.drawingNumber)
+ .filter((value): value is string => Boolean(value))
+ );
+
+ if (!taken.has(base)) return base;
+
+ let suffix = 1;
+ while (taken.has(`${base} (${suffix})`)) {
+ suffix += 1;
+ }
+ return `${base} (${suffix})`;
+}
+
+export async function upsertInspectionDocument(
+ client: SupabaseClient<Database>,
+ diagram:
+ | (Omit<z.infer<typeof inspectionDocumentValidator>, "id"> & {
+ id?: undefined;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ pageCount?: number;
+ defaultPageWidth?: number;
+ defaultPageHeight?: number;
+ })
+ | (Omit<z.infer<typeof inspectionDocumentValidator>, "id"> & {
+ id: string;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ pageCount?: number;
+ defaultPageWidth?: number;
+ defaultPageHeight?: number;
+ })
+) {
+ const {
+ id,
+ partId,
+ drawingNumber,
+ pdfUrl,
+ pageCount,
+ defaultPageWidth,
+ defaultPageHeight,
+ companyId,
+ createdBy,
+ updatedBy
+ } = diagram;
+
+ const documentClient = client as unknown as {
+ from: (table: string) => {
+ select: (columns: string) => {
+ eq: (
+ column: string,
+ value: unknown
+ ) => {
+ single: () => Promise<{
+ data: Record<string, unknown> | null;
+ error: unknown;
+ }>;
+ };
+ };
+ update: (payload: Record<string, unknown>) => {
+ eq: (
+ column: string,
+ value: unknown
+ ) => {
+ eq: (
+ column: string,
+ value: unknown
+ ) => {
+ select: (columns: string) => {
+ single: () => Promise<{
+ data: { id: string } | null;
+ error: unknown;
+ }>;
+ };
+ };
+ };
+ };
+ insert: (payload: Record<string, unknown>) => {
+ select: (columns: string) => {
+ single: () => Promise<{
+ data: { id: string } | null;
+ error: unknown;
+ }>;
+ };
+ };
+ };
+ };
+
+ const storagePath = toStoragePath(pdfUrl);
+
+ if (id) {
+ if (!companyId) {
+ return {
+ data: null,
+ error: {
+ message: "companyId is required to update inspection plan"
+ }
+ };
+ }
+
+ const existingResult = await documentClient
+ .from("inspectionDocument")
+ .select("*")
+ .eq("id", id)
+ .single();
+
+ const existing = existingResult.data;
+ if (!existing) {
+ return {
+ data: null,
+ error: {
+ message: "Inspection plan not found"
+ }
+ };
+ }
+ if (String(existing.companyId ?? "") !== companyId) {
+ return {
+ data: null,
+ error: {
+ message: "Inspection plan does not belong to this company"
+ }
+ };
+ }
+
+ const updatePayload: Record<string, unknown> = {
+ updatedBy: updatedBy ?? createdBy,
+ updatedAt: new Date().toISOString()
+ };
+ if (drawingNumber !== undefined) {
+ updatePayload.drawingNumber = drawingNumber ?? null;
+ }
+ if (partId !== undefined) {
+ updatePayload.partId = partId;
+ }
+
+ if (storagePath) {
+ updatePayload.storagePath = storagePath;
+ updatePayload.fileName = fileNameFromPath(storagePath);
+ }
+ if (pageCount && pageCount > 0) {
+ updatePayload.pageCount = pageCount;
+ }
+ if (defaultPageWidth && defaultPageWidth > 0) {
+ updatePayload.defaultPageWidth = defaultPageWidth;
+ }
+ if (defaultPageHeight && defaultPageHeight > 0) {
+ updatePayload.defaultPageHeight = defaultPageHeight;
+ }
+
+ return documentClient
+ .from("inspectionDocument")
+ .update(updatePayload)
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+ }
+
+ if (!companyId) {
+ return {
+ data: null,
+ error: { message: "companyId is required to create inspection plan" }
+ };
+ }
+
+ const resolvedDrawingNumber = drawingNumber?.trim()
+ ? drawingNumber.trim()
+ : await resolveInspectionDocumentDrawingNumber(client, companyId, partId);
+
+ return documentClient
+ .from("inspectionDocument")
+ .insert({
+ companyId,
+ partId,
+ drawingNumber: resolvedDrawingNumber ?? null,
+ version: 0,
+ ...(storagePath
+ ? {
+ storagePath,
+ fileName: fileNameFromPath(storagePath),
+ uploadedBy: createdBy
+ }
+ : {}),
+ ...(pageCount && pageCount > 0 ? { pageCount } : {}),
+ ...(defaultPageWidth && defaultPageWidth > 0 ? { defaultPageWidth } : {}),
+ ...(defaultPageHeight && defaultPageHeight > 0
+ ? { defaultPageHeight }
+ : {}),
+ createdBy
+ })
+ .select("id")
+ .single();
+}
+
+export async function deleteInspectionDocument(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ const existingResult = await client
+ .from("inspectionDocument")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!existingResult.data) {
+ return {
+ data: null,
+ error: { message: "Inspection plan not found" }
+ };
+ }
+
+ const storagePath =
+ (existingResult.data.storagePath as string | null) ?? null;
+
+ const deleteResult = await client
+ .from("inspectionDocument")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+
+ if (deleteResult.error) {
+ return { data: null, error: deleteResult.error };
+ }
+
+ return {
+ data: { storagePath },
+ error: null
+ };
+}
+
+function mapInspectionFeature(row: Record<string, unknown>) {
+ const balloonIdRaw = row.balloonId ?? row.balloon_id;
+ return {
+ id: String(row.id),
+ inspectionDocumentId: String(row.inspectionDocumentId),
+ companyId: String(row.companyId),
+ pageNumber: Number(row.pageNumber),
+ label: String(row.label),
+ description: (row.description as string | null) ?? null,
+ nominalValue: (row.nominalValue as string | null) ?? null,
+ tolerancePlus: (row.tolerancePlus as string | null) ?? null,
+ toleranceMinus: (row.toleranceMinus as string | null) ?? null,
+ unit: (row.unit as string | null) ?? null,
+ type: (row.type as string) ?? "Measurement",
+ // Per-feature sampling rule (NULL = inherit the document default). NUMERIC
+ // columns arrive as strings from PostgREST — coerce, mirroring the document
+ // default rule in mapInspectionDocument.
+ samplingPlanType: (row.samplingPlanType as string | null) ?? null,
+ samplingSampleSize: (row.samplingSampleSize as number | null) ?? null,
+ samplingPercentage:
+ row.samplingPercentage == null ? null : Number(row.samplingPercentage),
+ samplingAql: row.samplingAql == null ? null : Number(row.samplingAql),
+ samplingInspectionLevel:
+ (row.samplingInspectionLevel as string | null) ?? null,
+ samplingSeverity: (row.samplingSeverity as string | null) ?? null,
+ balloonId:
+ typeof balloonIdRaw === "string"
+ ? balloonIdRaw
+ : balloonIdRaw != null
+ ? String(balloonIdRaw)
+ : null,
+ createdBy: String(row.createdBy),
+ updatedBy: (row.updatedBy as string | null) ?? null,
+ createdAt: String(row.createdAt),
+ updatedAt: (row.updatedAt as string | null) ?? null
+ };
+}
+
+function mapBalloon(row: Record<string, unknown>) {
+ return {
+ id: String(row.id),
+ inspectionDocumentId: String(row.inspectionDocumentId),
+ companyId: String(row.companyId),
+ inspectionFeatureId: String(row.inspectionFeatureId),
+ pageNumber: Number(row.pageNumber),
+ regionX: Number(row.regionX),
+ regionY: Number(row.regionY),
+ regionWidth: Number(row.regionWidth),
+ regionHeight: Number(row.regionHeight),
+ xCoordinate: Number(row.xCoordinate),
+ yCoordinate: Number(row.yCoordinate),
+ createdBy: String(row.createdBy),
+ updatedBy: (row.updatedBy as string | null) ?? null,
+ createdAt: String(row.createdAt),
+ updatedAt: (row.updatedAt as string | null) ?? null,
+ balloonAnchorId: String(row.id)
+ };
+}
+
+export async function getInspectionFeatures(
+ client: SupabaseClient<Database>,
+ inspectionDocumentId: string
+) {
+ const [featuresResult, balloonsResult] = await Promise.all([
+ getInspectionFeaturesRaw(client, inspectionDocumentId),
+ getBalloons(client, inspectionDocumentId)
+ ]);
+
+ if (featuresResult.error) {
+ return { data: null, error: featuresResult.error };
+ }
+ if (balloonsResult.error) {
+ return { data: null, error: balloonsResult.error };
+ }
+
+ const balloonByFeatureId = new Map(
+ (balloonsResult.data ?? []).map((b) => [b.inspectionFeatureId, b.id])
+ );
+
+ return {
+ data: (featuresResult.data ?? []).map((row) =>
+ mapInspectionFeature({
+ ...row,
+ balloonId: balloonByFeatureId.get(String(row.id)) ?? null
+ })
+ ),
+ error: null
+ };
+}
+
+async function getInspectionFeaturesRaw(
+ client: SupabaseClient<Database>,
+ inspectionDocumentId: string
+) {
+ return listInspectionFeatures(client, inspectionDocumentId);
+}
+
+export async function getBalloons(
+ client: SupabaseClient<Database>,
+ inspectionDocumentId: string
+) {
+ const result = await listBalloons(client, inspectionDocumentId);
+
+ return {
+ data: (result.data ?? []).map((row) =>
+ mapBalloon(row as unknown as Record<string, unknown>)
+ ),
+ error: result.error
+ };
+}
+
+export async function getInspectionPlan(
+ client: SupabaseClient<Database>,
+ inspectionDocumentId: string
+) {
+ const [featuresResult, balloonsResult] = await Promise.all([
+ getInspectionFeaturesRaw(client, inspectionDocumentId),
+ getBalloons(client, inspectionDocumentId)
+ ]);
+
+ if (featuresResult.error) {
+ return { data: null, error: featuresResult.error };
+ }
+ if (balloonsResult.error) {
+ return { data: null, error: balloonsResult.error };
+ }
+
+ const balloonByFeatureId = new Map(
+ (balloonsResult.data ?? []).map((b) => [b.inspectionFeatureId, b])
+ );
+
+ return {
+ data: (featuresResult.data ?? []).map((row) => {
+ const b = balloonByFeatureId.get(row.id);
+ const featureId = row.id;
+ return {
+ /** Feature id (primary key for plan rows). */
+ id: featureId,
+ featureId,
+ /** Balloon id when placed; null for table-only features. */
+ balloonId: b?.id ?? null,
+ inspectionDocumentId: row.inspectionDocumentId,
+ pageNumber: b?.pageNumber ?? row.pageNumber,
+ label: row.label,
+ description: row.description,
+ nominalValue: row.nominalValue,
+ tolerancePlus: row.tolerancePlus,
+ toleranceMinus: row.toleranceMinus,
+ unit: row.unit,
+ regionX: b ? b.regionX : null,
+ regionY: b ? b.regionY : null,
+ regionWidth: b ? b.regionWidth : null,
+ regionHeight: b ? b.regionHeight : null,
+ xCoordinate: b ? b.xCoordinate : null,
+ yCoordinate: b ? b.yCoordinate : null
+ };
+ }),
+ error: null
+ };
+}
+
+export async function updateInspectionDocumentSampling(
+ client: SupabaseClient<Database>,
+ args: z.infer<typeof inspectionDocumentSamplingValidator> & {
+ inspectionDocumentId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { inspectionDocumentId, companyId, userId, ...sampling } = args;
+ return client
+ .from("inspectionDocument")
+ .update({
+ ...sampling,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", inspectionDocumentId)
+ .eq("companyId", companyId);
+}
+
+export async function saveInspectionDocumentAtomic(
+ client: SupabaseClient<Database>,
+ args: {
+ inspectionDocumentId: string;
+ companyId: string;
+ userId: string;
+ pdfUrl?: string | null;
+ pageCount?: number;
+ defaultPageWidth?: number;
+ defaultPageHeight?: number;
+ features: unknown;
+ balloons: unknown;
+ }
+) {
+ return (
+ client as unknown as {
+ rpc: (
+ fn: string,
+ args: Record<string, unknown>
+ ) => Promise<{
+ data: unknown;
+ error: unknown;
+ }>;
+ }
+ ).rpc("save_inspection_document_atomic", {
+ p_inspection_document_id: args.inspectionDocumentId,
+ p_company_id: args.companyId,
+ p_user_id: args.userId,
+ p_pdf_url: args.pdfUrl ?? null,
+ p_page_count: args.pageCount ?? null,
+ p_default_page_width: args.defaultPageWidth ?? null,
+ p_default_page_height: args.defaultPageHeight ?? null,
+ p_features: args.features,
+ p_balloons: args.balloons
+ });
+}
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index c6ce5a4526..6314297e2f 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -4,13 +4,17 @@ import type {
getAssemblyComponentMappings,
getAssemblyInstruction,
getAssemblyInstructionStepMaterials,
- getAssemblyInstructionStepRequirements,
+ getAssemblyInstructionStepSlides,
getAssemblyInstructionSteps,
+ getAssemblyInstructionStepTools,
getAssemblyInstructions,
- getAssemblyStandardNotes,
getAssemblyUnits,
+ getBalloons,
getFailureMode,
getFailureModes,
+ getInspectionDocument,
+ getInspectionDocuments,
+ getInspectionFeatures,
getJob,
getJobMakeMethodById,
getJobMaterialsWithQuantityOnHand,
@@ -204,16 +208,16 @@ export type AssemblyInstructionStepRow = NonNullable<
Awaited<ReturnType<typeof getAssemblyInstructionSteps>>["data"]
>[number];
-export type AssemblyStepRequirement = NonNullable<
- Awaited<ReturnType<typeof getAssemblyInstructionStepRequirements>>["data"]
->[number];
-
export type AssemblyStepMaterial = NonNullable<
Awaited<ReturnType<typeof getAssemblyInstructionStepMaterials>>["data"]
>[number];
-export type AssemblyStandardNote = NonNullable<
- Awaited<ReturnType<typeof getAssemblyStandardNotes>>["data"]
+export type AssemblyStepSlide = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructionStepSlides>>["data"]
+>[number];
+
+export type AssemblyStepTool = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructionStepTools>>["data"]
>[number];
export type AssemblyUnit = NonNullable<
@@ -223,3 +227,37 @@ export type AssemblyUnit = NonNullable<
export type AssemblyComponentMapping = NonNullable<
Awaited<ReturnType<typeof getAssemblyComponentMappings>>["data"]
>[number];
+
+// --- Inspection Documents -----------------------------------------------
+
+export type InspectionDocument = NonNullable<
+ Awaited<ReturnType<typeof getInspectionDocuments>>["data"]
+>[number];
+
+export type InspectionDocumentDetail = NonNullable<
+ Awaited<ReturnType<typeof getInspectionDocument>>["data"]
+>;
+
+export type Balloon = NonNullable<
+ Awaited<ReturnType<typeof getBalloons>>["data"]
+>[number];
+
+export type InspectionFeature = NonNullable<
+ Awaited<ReturnType<typeof getInspectionFeatures>>["data"]
+>[number];
+
+export type BalloonFeature = {
+ id: string;
+ balloonNumber: number;
+ description: string;
+ nominalValue: number | null;
+ tolerancePlus: number | null;
+ toleranceMinus: number | null;
+ unitOfMeasureCode: string | null;
+};
+
+export type InspectionDocumentContent = {
+ pdfUrl: string | null;
+ drawingNumber: string | null;
+ features: BalloonFeature[];
+};
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx
index ae308f5152..e97e77ed9e 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx
@@ -18,7 +18,6 @@ import { LuCircleCheck, LuInfo, LuTriangleAlert } from "react-icons/lu";
import type { z } from "zod";
import { Hidden, Item, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
import {
assemblyInstructionFromItemValidator,
@@ -52,8 +51,6 @@ const AssemblyInstructionForm = ({
state: "idle"
});
- const [itemType, setItemType] = useState<MethodItemType | "Item">("Item");
-
// Mirrors getModelForItem on the server: conversion is lazy, so any STEP
// model is usable — the state just tells the user what will happen on save
const checkModel = useCallback(
@@ -176,9 +173,8 @@ const AssemblyInstructionForm = ({
<VStack spacing={1} className="w-full">
<Item
name="itemId"
- label="Item"
- type={itemType}
- onTypeChange={setItemType}
+ label="Part"
+ type="Part"
replenishmentSystem="Make"
onChange={(selected) => {
checkModel(selected?.value ?? "");
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
index 960f4c55ec..a55ce987b2 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
@@ -49,13 +49,14 @@ import {
import type { FlattenedBomMaterial } from "../../production.service";
import type {
AssemblyInstructionStepRow,
- AssemblyStandardNote,
AssemblyStepMaterial,
- AssemblyStepRequirement
+ AssemblyStepSlide,
+ AssemblyStepTool
} from "../../types";
import AssemblyStepBom, { ComponentColorSwatch } from "./AssemblyStepBom";
import AssemblyStepMaterials from "./AssemblyStepMaterials";
-import AssemblyStepRequirements from "./AssemblyStepRequirements";
+import AssemblyStepSlides from "./AssemblyStepSlides";
+import AssemblyStepTools from "./AssemblyStepTools";
type AssemblyInstructionPropertiesProps = {
step: AssemblyInstructionStepRow | null;
@@ -72,10 +73,10 @@ type AssemblyInstructionPropertiesProps = {
graphIndex: AssemblyGraphIndex | null;
/** Authored subassembly units — a step matching one is titled by its name. */
units: NamedUnit[];
- requirements: AssemblyStepRequirement[];
stepMaterials: AssemblyStepMaterial[];
+ stepSlides: AssemblyStepSlide[];
+ stepTools: AssemblyStepTool[];
bomMaterials: FlattenedBomMaterial[];
- standardNotes: AssemblyStandardNote[];
onSelectComponents: (nodeIds: string[]) => void;
onStartAddComponents: () => void;
onStopAddComponents: () => void;
@@ -98,10 +99,10 @@ const AssemblyInstructionProperties = ({
isDisabled,
graphIndex,
units,
- requirements,
stepMaterials,
+ stepSlides,
+ stepTools,
bomMaterials,
- standardNotes,
onSelectComponents,
onStartAddComponents,
onStopAddComponents,
@@ -126,6 +127,21 @@ const AssemblyInstructionProperties = ({
step != null &&
stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true;
+ // BOM parts the author can @-mention in a step's instruction — mirrors the
+ // step-description editor in JobBillOfProcess (scoped to the item's BOM).
+ const itemMentions = useMemo(
+ () =>
+ bomMaterials.map((material) => ({
+ id: material.itemId,
+ label:
+ material.name ?? material.readableIdWithRevision ?? material.itemId,
+ helper: material.name
+ ? (material.readableIdWithRevision ?? undefined)
+ : undefined
+ })),
+ [bomMaterials]
+ );
+
return (
<VStack
spacing={0}
@@ -178,8 +194,8 @@ const AssemblyInstructionProperties = ({
<TabsTrigger className="flex-1" value="bom">
BOM
</TabsTrigger>
- <TabsTrigger className="flex-1" value="requirements">
- Requirements
+ <TabsTrigger className="flex-1" value="slides">
+ Slides
</TabsTrigger>
</TabsList>
{/* forceMount keeps unsaved form edits alive while the BOM tab is open */}
@@ -197,6 +213,7 @@ const AssemblyInstructionProperties = ({
isDisabled={isDisabled}
graphIndex={graphIndex}
units={units}
+ itemMentions={itemMentions}
onSelectComponents={onSelectComponents}
onStartAddComponents={onStartAddComponents}
onStopAddComponents={onStopAddComponents}
@@ -217,6 +234,12 @@ const AssemblyInstructionProperties = ({
bomMaterials={bomMaterials}
isDisabled={isDisabled}
/>
+ <AssemblyStepTools
+ stepId={step.id}
+ instructionId={instructionId}
+ tools={stepTools}
+ isDisabled={isDisabled}
+ />
<AssemblyStepBom
componentNodeIds={
draftComponentNodeIds ?? step.componentNodeIds ?? []
@@ -225,14 +248,15 @@ const AssemblyInstructionProperties = ({
/>
</VStack>
</TabsContent>
- <TabsContent value="requirements">
- <AssemblyStepRequirements
- stepId={step.id}
- instructionId={instructionId}
- requirements={requirements}
- standardNotes={standardNotes}
- isDisabled={isDisabled}
- />
+ <TabsContent value="slides">
+ <VStack spacing={4} className="w-full py-2">
+ <AssemblyStepSlides
+ stepId={step.id}
+ instructionId={instructionId}
+ slides={stepSlides}
+ isDisabled={isDisabled}
+ />
+ </VStack>
</TabsContent>
</Tabs>
) : (
@@ -299,6 +323,7 @@ function StepForm({
isDisabled,
graphIndex,
units,
+ itemMentions,
onSelectComponents,
onStartAddComponents,
onStopAddComponents,
@@ -316,6 +341,7 @@ function StepForm({
isDisabled: boolean;
graphIndex: AssemblyGraphIndex | null;
units: NamedUnit[];
+ itemMentions: { id: string; label: string; helper?: string }[];
onSelectComponents: (nodeIds: string[]) => void;
onStartAddComponents: () => void;
onStopAddComponents: () => void;
@@ -459,6 +485,7 @@ function StepForm({
onChange={(value) => {
setDescription(value);
}}
+ mentions={[{ char: "@", items: itemMentions }]}
className="[&_.is-empty]:text-muted-foreground min-h-[88px] max-h-[360px] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent p-3 rounded-lg border w-full"
/>
</VStack>
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx
deleted file mode 100644
index 288e8e3160..0000000000
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-import { Hidden, Input, Submit, TextArea, ValidatedForm } from "@carbon/form";
-import {
- Button,
- HStack,
- IconButton,
- Modal,
- ModalBody,
- ModalContent,
- ModalHeader,
- ModalTitle,
- ToggleGroup,
- ToggleGroupItem,
- VStack
-} from "@carbon/react";
-import { useEffect, useState } from "react";
-import { LuPencil, LuTrash } from "react-icons/lu";
-import { useFetcher } from "react-router";
-import { usePermissions } from "~/hooks";
-import { path } from "~/utils/path";
-import {
- type assemblyNoteSeverities,
- assemblyStandardNoteValidator
-} from "../../production.models";
-import type { AssemblyStandardNote } from "../../types";
-import { SeverityIcon } from "./AssemblyStepRequirements";
-
-type Severity = (typeof assemblyNoteSeverities)[number];
-
-/**
- * CRUD for company-level standard note templates. Templates are copied into
- * steps on insert, so edits here never change authored instructions.
- */
-export default function AssemblyStandardNotesModal({
- standardNotes,
- onClose
-}: {
- standardNotes: AssemblyStandardNote[];
- onClose: () => void;
-}) {
- const permissions = usePermissions();
- const formFetcher = useFetcher<{ success: boolean }>();
- const deleteFetcher = useFetcher<{ success: boolean }>();
-
- const [editing, setEditing] = useState<AssemblyStandardNote | null>(null);
- const [severity, setSeverity] = useState<Severity>("Info");
- const [formKey, setFormKey] = useState(0);
-
- useEffect(() => {
- if (formFetcher.state === "idle" && formFetcher.data?.success) {
- setEditing(null);
- setSeverity("Info");
- setFormKey((key) => key + 1);
- }
- }, [formFetcher.state, formFetcher.data]);
-
- const onEdit = (note: AssemblyStandardNote) => {
- setEditing(note);
- setSeverity(note.severity);
- setFormKey((key) => key + 1);
- };
-
- return (
- <Modal
- open
- onOpenChange={(open) => {
- if (!open) onClose();
- }}
- >
- <ModalContent>
- <ModalHeader>
- <ModalTitle>Standard Notes</ModalTitle>
- </ModalHeader>
- <ModalBody>
- <VStack spacing={4} className="w-full">
- {standardNotes.length > 0 && (
- <ul className="w-full">
- {standardNotes.map((note) => (
- <li
- key={note.id}
- className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm"
- >
- <SeverityIcon severity={note.severity} />
- <VStack spacing={0} className="min-w-0 flex-1">
- <span className="truncate font-medium">{note.name}</span>
- <span
- className="truncate text-xs text-muted-foreground"
- title={note.content}
- >
- {note.content}
- </span>
- </VStack>
- <IconButton
- aria-label={`Edit ${note.name}`}
- icon={<LuPencil />}
- variant="ghost"
- size="sm"
- onClick={() => onEdit(note)}
- />
- {permissions.can("delete", "production") && (
- <IconButton
- aria-label={`Delete ${note.name}`}
- icon={<LuTrash />}
- variant="ghost"
- size="sm"
- isDisabled={deleteFetcher.state !== "idle"}
- onClick={() => {
- deleteFetcher.submit(new FormData(), {
- method: "post",
- action: path.to.deleteAssemblyStandardNote(note.id)
- });
- }}
- />
- )}
- </li>
- ))}
- </ul>
- )}
- <ValidatedForm
- key={formKey}
- validator={assemblyStandardNoteValidator}
- method="post"
- action={
- editing
- ? path.to.assemblyStandardNote(editing.id)
- : path.to.newAssemblyStandardNote
- }
- defaultValues={{
- name: editing?.name ?? "",
- content: editing?.content ?? ""
- }}
- fetcher={formFetcher}
- className="w-full"
- >
- <Hidden name="severity" value={severity} />
- <VStack spacing={2} className="w-full">
- <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
- {editing ? `Edit "${editing.name}"` : "New standard note"}
- </h4>
- <Input name="name" placeholder="e.g. Apply threadlocker" />
- <TextArea
- name="content"
- placeholder="e.g. Apply Loctite 242 to threads before insertion"
- />
- <HStack className="w-full justify-between">
- <ToggleGroup
- type="single"
- value={severity}
- onValueChange={(value) => {
- if (value) setSeverity(value as Severity);
- }}
- >
- <ToggleGroupItem value="Info" aria-label="Info">
- <SeverityIcon severity="Info" />
- </ToggleGroupItem>
- <ToggleGroupItem value="Caution" aria-label="Caution">
- <SeverityIcon severity="Caution" />
- </ToggleGroupItem>
- <ToggleGroupItem value="Warning" aria-label="Warning">
- <SeverityIcon severity="Warning" />
- </ToggleGroupItem>
- </ToggleGroup>
- <HStack spacing={2}>
- {editing && (
- <Button
- variant="ghost"
- onClick={() => {
- setEditing(null);
- setSeverity("Info");
- setFormKey((key) => key + 1);
- }}
- >
- Cancel
- </Button>
- )}
- <Submit isDisabled={formFetcher.state !== "idle"}>
- {editing ? "Save" : "Create"}
- </Submit>
- </HStack>
- </HStack>
- </VStack>
- </ValidatedForm>
- </VStack>
- </ModalBody>
- </ModalContent>
- </Modal>
- );
-}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx
deleted file mode 100644
index 2da38f54ee..0000000000
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx
+++ /dev/null
@@ -1,614 +0,0 @@
-import { useCarbon } from "@carbon/auth";
-import { Hidden, Input, Submit, TextArea, ValidatedForm } from "@carbon/form";
-import {
- Badge,
- Button,
- cn,
- HStack,
- IconButton,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- ToggleGroup,
- ToggleGroupItem,
- VStack
-} from "@carbon/react";
-import { nanoid } from "nanoid";
-import { useCallback, useEffect, useState } from "react";
-import { useDropzone } from "react-dropzone";
-import {
- LuCirclePlus,
- LuFileVideo,
- LuInfo,
- LuOctagonAlert,
- LuTrash,
- LuTriangleAlert,
- LuUpload
-} from "react-icons/lu";
-import { useFetcher } from "react-router";
-import { toast } from "sonner";
-import { Empty } from "~/components";
-import { Tool } from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
-import { getPrivateUrl, path } from "~/utils/path";
-import {
- type assemblyNoteSeverities,
- assemblyStepRequirementValidator
-} from "../../production.models";
-import type {
- AssemblyStandardNote,
- AssemblyStepRequirement
-} from "../../types";
-import AssemblyStandardNotesModal from "./AssemblyStandardNotesModal";
-
-type Severity = (typeof assemblyNoteSeverities)[number];
-
-type AssemblyStepRequirementsProps = {
- stepId: string;
- instructionId: string;
- requirements: AssemblyStepRequirement[];
- standardNotes: AssemblyStandardNote[];
- isDisabled: boolean;
-};
-
-/**
- * Per-step process data: tools/fixtures/consumables (catalog-linked or free
- * text), classified notes, reusable standard-note templates, and media
- * attachments.
- */
-export default function AssemblyStepRequirements({
- stepId,
- instructionId,
- requirements,
- standardNotes,
- isDisabled
-}: AssemblyStepRequirementsProps) {
- const byType = (type: AssemblyStepRequirement["type"]) =>
- requirements.filter((requirement) => requirement.type === type);
-
- return (
- <Tabs defaultValue="tools" className="w-full">
- <TabsList className="w-full">
- <TabsTrigger className="flex-1" value="tools">
- Tools
- </TabsTrigger>
- <TabsTrigger className="flex-1" value="notes">
- Notes
- </TabsTrigger>
- <TabsTrigger className="flex-1" value="standard-notes">
- Std Notes
- </TabsTrigger>
- <TabsTrigger className="flex-1" value="media">
- Media
- </TabsTrigger>
- </TabsList>
- <TabsContent value="tools">
- <VStack spacing={4} className="w-full py-2">
- <RequirementSection
- title="Tools"
- type="Tool"
- placeholder="e.g. 4mm hex key"
- requirements={byType("Tool")}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- <RequirementSection
- title="Fixtures"
- type="Fixture"
- placeholder="e.g. Assembly jig #3"
- requirements={byType("Fixture")}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- <RequirementSection
- title="Consumables"
- type="Consumable"
- placeholder="e.g. Loctite 242"
- requirements={byType("Consumable")}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- </VStack>
- </TabsContent>
- <TabsContent value="notes">
- <NotesSection
- notes={byType("Note")}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- </TabsContent>
- <TabsContent value="standard-notes">
- <StandardNotesSection
- standardNotes={standardNotes}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- </TabsContent>
- <TabsContent value="media">
- <MediaSection
- media={byType("Media")}
- stepId={stepId}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- </TabsContent>
- </Tabs>
- );
-}
-
-function RequirementSection({
- title,
- type,
- placeholder,
- requirements,
- stepId,
- instructionId,
- isDisabled
-}: {
- title: string;
- type: "Tool" | "Fixture" | "Consumable";
- placeholder: string;
- requirements: AssemblyStepRequirement[];
- stepId: string;
- instructionId: string;
- isDisabled: boolean;
-}) {
- const fetcher = useFetcher<{ success: boolean }>();
- // Remount the form after a successful add so the input clears
- const [formKey, setFormKey] = useState(0);
-
- useEffect(() => {
- if (fetcher.state === "idle" && fetcher.data?.success) {
- setFormKey((key) => key + 1);
- }
- }, [fetcher.state, fetcher.data]);
-
- return (
- <VStack spacing={2} className="w-full">
- <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
- {title}
- </h4>
- {requirements.length === 0 ? (
- <p className="text-xs text-muted-foreground">
- No {title.toLowerCase()} to display
- </p>
- ) : (
- <ul className="w-full">
- {requirements.map((requirement) => (
- <RequirementRow
- key={requirement.id}
- requirement={requirement}
- instructionId={instructionId}
- isDisabled={isDisabled}
- />
- ))}
- </ul>
- )}
- {!isDisabled && (
- <ValidatedForm
- key={formKey}
- validator={assemblyStepRequirementValidator}
- method="post"
- action={path.to.newAssemblyStepRequirement(instructionId)}
- fetcher={fetcher}
- className="w-full"
- >
- <Hidden name="stepId" value={stepId} />
- <Hidden name="type" value={type} />
- <VStack spacing={2} className="w-full">
- {type === "Tool" && <Tool name="itemId" />}
- <HStack className="w-full items-start" spacing={2}>
- <div className="flex-1 min-w-0">
- <Input
- name="name"
- placeholder={
- type === "Tool"
- ? `or enter a name: ${placeholder}`
- : placeholder
- }
- />
- </div>
- <Submit
- variant="secondary"
- leftIcon={<LuCirclePlus />}
- isDisabled={fetcher.state !== "idle"}
- >
- Add
- </Submit>
- </HStack>
- </VStack>
- </ValidatedForm>
- )}
- </VStack>
- );
-}
-
-function RequirementRow({
- requirement,
- instructionId,
- isDisabled,
- children
-}: {
- requirement: AssemblyStepRequirement;
- instructionId: string;
- isDisabled: boolean;
- children?: React.ReactNode;
-}) {
- const deleteFetcher = useFetcher<{ success: boolean }>();
- const permissions = usePermissions();
-
- // Optimistically remove the row while the delete is in flight
- if (deleteFetcher.state !== "idle") return null;
-
- return (
- <li className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm">
- {children ?? (
- <>
- <span
- className="min-w-0 flex-1 truncate"
- title={requirement.name ?? undefined}
- >
- {requirement.name}
- </span>
- {requirement.item?.readableIdWithRevision && (
- <span className="text-xs text-muted-foreground">
- {requirement.item.readableIdWithRevision}
- </span>
- )}
- {requirement.quantity > 1 && (
- <Badge variant="secondary" className="tabular-nums">
- ×{requirement.quantity}
- </Badge>
- )}
- </>
- )}
- {!isDisabled && permissions.can("delete", "production") && (
- <IconButton
- aria-label={`Delete ${requirement.name ?? "requirement"}`}
- icon={<LuTrash />}
- variant="ghost"
- size="sm"
- onClick={() => {
- deleteFetcher.submit(new FormData(), {
- method: "post",
- action: path.to.deleteAssemblyStepRequirement(
- instructionId,
- requirement.id
- )
- });
- }}
- />
- )}
- </li>
- );
-}
-
-const severityStyles: Record<
- Severity,
- { icon: typeof LuInfo; className: string }
-> = {
- Info: { icon: LuInfo, className: "text-blue-500" },
- Caution: { icon: LuTriangleAlert, className: "text-yellow-500" },
- Warning: { icon: LuOctagonAlert, className: "text-red-500" }
-};
-
-export function SeverityIcon({ severity }: { severity: Severity | null }) {
- const { icon: Icon, className } = severityStyles[severity ?? "Info"];
- return <Icon className={cn("h-4 w-4 shrink-0", className)} aria-hidden />;
-}
-
-function NotesSection({
- notes,
- stepId,
- instructionId,
- isDisabled
-}: {
- notes: AssemblyStepRequirement[];
- stepId: string;
- instructionId: string;
- isDisabled: boolean;
-}) {
- const fetcher = useFetcher<{ success: boolean }>();
- const [formKey, setFormKey] = useState(0);
- const [severity, setSeverity] = useState<Severity>("Info");
-
- useEffect(() => {
- if (fetcher.state === "idle" && fetcher.data?.success) {
- setFormKey((key) => key + 1);
- setSeverity("Info");
- }
- }, [fetcher.state, fetcher.data]);
-
- return (
- <VStack spacing={2} className="w-full py-2">
- {notes.length === 0 ? (
- <p className="text-xs text-muted-foreground">No notes to display</p>
- ) : (
- <ul className="w-full">
- {notes.map((note) => (
- <RequirementRow
- key={note.id}
- requirement={note}
- instructionId={instructionId}
- isDisabled={isDisabled}
- >
- <SeverityIcon severity={note.severity} />
- <span className="min-w-0 flex-1 whitespace-pre-wrap text-sm">
- {note.text}
- </span>
- </RequirementRow>
- ))}
- </ul>
- )}
- {!isDisabled && (
- <ValidatedForm
- key={formKey}
- validator={assemblyStepRequirementValidator}
- method="post"
- action={path.to.newAssemblyStepRequirement(instructionId)}
- fetcher={fetcher}
- className="w-full"
- >
- <Hidden name="stepId" value={stepId} />
- <Hidden name="type" value="Note" />
- <Hidden name="severity" value={severity} />
- <VStack spacing={2} className="w-full">
- <TextArea name="text" placeholder="Add a note for this step" />
- <HStack className="w-full justify-between">
- <ToggleGroup
- type="single"
- value={severity}
- onValueChange={(value) => {
- if (value) setSeverity(value as Severity);
- }}
- >
- <ToggleGroupItem value="Info" aria-label="Info">
- <SeverityIcon severity="Info" />
- </ToggleGroupItem>
- <ToggleGroupItem value="Caution" aria-label="Caution">
- <SeverityIcon severity="Caution" />
- </ToggleGroupItem>
- <ToggleGroupItem value="Warning" aria-label="Warning">
- <SeverityIcon severity="Warning" />
- </ToggleGroupItem>
- </ToggleGroup>
- <Submit
- variant="secondary"
- leftIcon={<LuCirclePlus />}
- isDisabled={fetcher.state !== "idle"}
- >
- Add Note
- </Submit>
- </HStack>
- </VStack>
- </ValidatedForm>
- )}
- </VStack>
- );
-}
-
-function StandardNotesSection({
- standardNotes,
- stepId,
- instructionId,
- isDisabled
-}: {
- standardNotes: AssemblyStandardNote[];
- stepId: string;
- instructionId: string;
- isDisabled: boolean;
-}) {
- const permissions = usePermissions();
- const [manageOpen, setManageOpen] = useState(false);
- const insertFetcher = useFetcher<{ success: boolean }>();
-
- const onInsert = (note: AssemblyStandardNote) => {
- // Copy semantics: editing the template later never changes the step
- const formData = new FormData();
- formData.append("stepId", stepId);
- formData.append("type", "Note");
- formData.append("text", note.content);
- formData.append("severity", note.severity);
- insertFetcher.submit(formData, {
- method: "post",
- action: path.to.newAssemblyStepRequirement(instructionId)
- });
- };
-
- return (
- <VStack spacing={2} className="w-full py-2">
- {standardNotes.length === 0 ? (
- <Empty className="border-none">
- <p className="text-sm text-muted-foreground max-w-[300px] text-center">
- Standard notes are reusable note templates shared across your
- company
- </p>
- </Empty>
- ) : (
- <ul className="w-full">
- {standardNotes.map((note) => (
- <li
- key={note.id}
- className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm"
- >
- <SeverityIcon severity={note.severity} />
- <VStack spacing={0} className="min-w-0 flex-1">
- <span className="truncate font-medium">{note.name}</span>
- <span
- className="truncate text-xs text-muted-foreground"
- title={note.content}
- >
- {note.content}
- </span>
- </VStack>
- {!isDisabled && (
- <Button
- variant="secondary"
- size="sm"
- isDisabled={insertFetcher.state !== "idle"}
- onClick={() => onInsert(note)}
- >
- Insert
- </Button>
- )}
- </li>
- ))}
- </ul>
- )}
- {permissions.can("update", "production") && (
- <Button
- variant="ghost"
- size="sm"
- className="self-end"
- onClick={() => setManageOpen(true)}
- >
- Manage
- </Button>
- )}
- {manageOpen && (
- <AssemblyStandardNotesModal
- standardNotes={standardNotes}
- onClose={() => setManageOpen(false)}
- />
- )}
- </VStack>
- );
-}
-
-const MAX_MEDIA_BYTES = 50 * 1024 * 1024;
-
-function MediaSection({
- media,
- stepId,
- instructionId,
- isDisabled
-}: {
- media: AssemblyStepRequirement[];
- stepId: string;
- instructionId: string;
- isDisabled: boolean;
-}) {
- const { carbon } = useCarbon();
- const { company } = useUser();
- const fetcher = useFetcher<{ success: boolean }>();
- const [isUploading, setIsUploading] = useState(false);
-
- const onDrop = useCallback(
- async (acceptedFiles: File[]) => {
- if (!carbon || !company.id) return;
- setIsUploading(true);
- try {
- for (const file of acceptedFiles) {
- if (file.size > MAX_MEDIA_BYTES) {
- toast.error(`${file.name} is larger than 50MB`);
- continue;
- }
- const extension = file.name.split(".").pop() ?? "bin";
- const filePath = `${company.id}/assembly/${instructionId}/${stepId}/${nanoid()}.${extension}`;
- const upload = await carbon.storage
- .from("private")
- .upload(filePath, file);
- if (upload.error || !upload.data) {
- toast.error(`Failed to upload ${file.name}`);
- continue;
- }
- const formData = new FormData();
- formData.append("stepId", stepId);
- formData.append("type", "Media");
- formData.append("name", file.name);
- formData.append("filePath", upload.data.path);
- fetcher.submit(formData, {
- method: "post",
- action: path.to.newAssemblyStepRequirement(instructionId)
- });
- }
- } finally {
- setIsUploading(false);
- }
- },
- [carbon, company.id, instructionId, stepId, fetcher]
- );
-
- const { getRootProps, getInputProps, isDragActive } = useDropzone({
- onDrop,
- accept: { "image/*": [], "video/*": [] },
- disabled: isDisabled || isUploading
- });
-
- return (
- <VStack spacing={2} className="w-full py-2">
- {media.length === 0 ? (
- <p className="text-xs text-muted-foreground">No media to display</p>
- ) : (
- <ul className="w-full">
- {media.map((item) => (
- <RequirementRow
- key={item.id}
- requirement={item}
- instructionId={instructionId}
- isDisabled={isDisabled}
- >
- <MediaThumbnail requirement={item} />
- <span
- className="min-w-0 flex-1 truncate"
- title={item.name ?? undefined}
- >
- {item.name}
- </span>
- </RequirementRow>
- ))}
- </ul>
- )}
- {!isDisabled && (
- <div
- {...getRootProps()}
- className={cn(
- "flex w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border p-4 text-center text-sm text-muted-foreground hover:bg-accent/30",
- isDragActive && "border-primary bg-accent/30",
- isUploading && "pointer-events-none opacity-50"
- )}
- >
- <input {...getInputProps()} />
- <LuUpload className="h-4 w-4" />
- <p>
- {isUploading
- ? "Uploading…"
- : "Drop images or videos here, or click to browse"}
- </p>
- </div>
- )}
- </VStack>
- );
-}
-
-function MediaThumbnail({
- requirement
-}: {
- requirement: AssemblyStepRequirement;
-}) {
- if (!requirement.filePath) return null;
- const isVideo = /\.(mp4|mov|webm|avi|mkv)$/i.test(requirement.filePath);
- if (isVideo) {
- return <LuFileVideo className="h-8 w-8 shrink-0 text-muted-foreground" />;
- }
- return (
- <a
- href={getPrivateUrl(requirement.filePath)}
- target="_blank"
- rel="noreferrer"
- onClick={(event) => event.stopPropagation()}
- >
- <img
- src={getPrivateUrl(requirement.filePath)}
- alt={requirement.name ?? "Attachment"}
- className="h-8 w-8 shrink-0 rounded-sm border border-border object-cover"
- />
- </a>
- );
-}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx
new file mode 100644
index 0000000000..c6dc96621c
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepSlides.tsx
@@ -0,0 +1,155 @@
+import { useCarbon } from "@carbon/auth";
+import { toast } from "@carbon/react";
+import { nanoid } from "nanoid";
+import { useRef, useState } from "react";
+import { useFetcher } from "react-router";
+import { SlidesEditor, uploadStepSlideModel } from "~/components/SlidesEditor";
+import { useUser } from "~/hooks";
+import type { SlideAnnotation, SlideSize } from "~/modules/shared";
+import { path } from "~/utils/path";
+import type { AssemblyStepSlide } from "../../types";
+
+type AssemblyStepSlidesProps = {
+ stepId: string;
+ instructionId: string;
+ slides: AssemblyStepSlide[];
+ isDisabled: boolean;
+};
+
+/**
+ * Reference slides (images + 3D models) for an assembly step — upload, caption,
+ * annotate, delete, persisted immediately via the slide routes. Mirrors the BOP
+ * step editor's StepSlides; copied to job operations by the assembly sync.
+ */
+export default function AssemblyStepSlides({
+ stepId,
+ instructionId,
+ slides: slideRows,
+ isDisabled
+}: AssemblyStepSlidesProps) {
+ const fetcher = useFetcher();
+ const captionFetcher = useFetcher();
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId }
+ } = useUser();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const modelInputRef = useRef<HTMLInputElement>(null);
+ const [uploading, setUploading] = useState(false);
+
+ const slides = slideRows
+ .slice()
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
+
+ const nextSortOrder = () =>
+ slides.reduce((m, s) => Math.max(m, s.sortOrder ?? 0), 0) + 1;
+
+ const onAddFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setUploading(true);
+ try {
+ const ext = file.name.split(".").pop();
+ const fileName = `${companyId}/assembly/${instructionId}/${nanoid()}.${ext}`;
+ const result = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+ if (result.error || !result.data) {
+ toast.error("Failed to upload image");
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", stepId);
+ fd.append("imagePath", result.data.path);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newAssemblyStepSlide(instructionId)
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Upload a 3D model and attach it to the step as a model slide. The model-upload
+ // API also starts the assembler's STEP → GLB conversion.
+ const onAddModelFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setUploading(true);
+ try {
+ const modelUploadId = await uploadStepSlideModel(carbon, companyId, file);
+ if (!modelUploadId) {
+ toast.error("Failed to upload model");
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", stepId);
+ fd.append("modelUploadId", modelUploadId);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newAssemblyStepSlide(instructionId)
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Update one slide: always carries the required fields (id → the route updates rather
+ // than inserts; stepId + the slide's content field satisfy the validator) plus whatever
+ // changed. Fields not sent are preserved, so a caption edit never wipes size/annotations
+ // and vice-versa.
+ function saveSlide(slide: AssemblyStepSlide, fields: Record<string, string>) {
+ const fd = new FormData();
+ fd.append("id", slide.id);
+ fd.append("stepId", slide.stepId);
+ if (slide.imagePath) fd.append("imagePath", slide.imagePath);
+ if (slide.modelUploadId) fd.append("modelUploadId", slide.modelUploadId);
+ fd.append("sortOrder", String(slide.sortOrder ?? 1));
+ for (const [key, value] of Object.entries(fields)) fd.append(key, value);
+ captionFetcher.submit(fd, {
+ method: "post",
+ action: path.to.newAssemblyStepSlide(instructionId)
+ });
+ }
+
+ return (
+ <SlidesEditor
+ slides={slides.map((s) => ({
+ key: s.id,
+ imagePath: s.imagePath,
+ modelUploadId: s.modelUploadId,
+ caption: s.caption,
+ size: (s.size as SlideSize | null) ?? null,
+ annotations: (s.annotations as SlideAnnotation[] | null) ?? null
+ }))}
+ isDisabled={isDisabled}
+ busy={uploading || fetcher.state !== "idle"}
+ fileInputRef={fileInputRef}
+ onFileChange={onAddFile}
+ modelInputRef={modelInputRef}
+ onModelFileChange={onAddModelFile}
+ onRemove={(index) => {
+ const slide = slides[index];
+ if (!slide) return;
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.deleteAssemblyStepSlide(instructionId, slide.id)
+ });
+ }}
+ onCaptionBlur={(index, caption) => {
+ const slide = slides[index];
+ if (slide && (slide.caption ?? "") !== caption)
+ saveSlide(slide, { caption });
+ }}
+ onAnnotationsChange={(index, annotations) => {
+ const slide = slides[index];
+ if (slide)
+ saveSlide(slide, { annotations: JSON.stringify(annotations) });
+ }}
+ />
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx
new file mode 100644
index 0000000000..c450d52c2e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx
@@ -0,0 +1,146 @@
+import { Hidden, Number, Submit, ValidatedForm } from "@carbon/form";
+import { Badge, HStack, IconButton, VStack } from "@carbon/react";
+import { useEffect, useState } from "react";
+import { LuCirclePlus, LuTrash } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Tool } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { assemblyStepToolValidator } from "../../production.models";
+import type { AssemblyStepTool } from "../../types";
+
+type AssemblyStepToolsProps = {
+ stepId: string;
+ instructionId: string;
+ tools: AssemblyStepTool[];
+ isDisabled: boolean;
+};
+
+/**
+ * Tools used at this step. Stored by itemId (a tool-type item) — the same
+ * target jobOperationTool.toolId references, so the BOP sync maps rows 1:1.
+ */
+export default function AssemblyStepTools({
+ stepId,
+ instructionId,
+ tools,
+ isDisabled
+}: AssemblyStepToolsProps) {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{ success: boolean }>();
+ // Remount the form after a successful add so the fields clear
+ const [formKey, setFormKey] = useState(0);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ setFormKey((key) => key + 1);
+ }
+ }, [fetcher.state, fetcher.data]);
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ Tools
+ </h4>
+ {tools.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No tools to display</p>
+ ) : (
+ <ul className="w-full">
+ {tools.map((tool) => (
+ <ToolRow
+ key={tool.id}
+ tool={tool}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ ))}
+ </ul>
+ )}
+ {!isDisabled && permissions.can("create", "production") && (
+ <ValidatedForm
+ key={formKey}
+ validator={assemblyStepToolValidator}
+ method="post"
+ action={path.to.newAssemblyStepTool(instructionId)}
+ fetcher={fetcher}
+ className="w-full"
+ >
+ <Hidden name="stepId" value={stepId} />
+ <VStack spacing={2} className="w-full">
+ <Tool
+ name="itemId"
+ placeholder="Pick a tool"
+ disabledTools={tools.map((tool) => tool.itemId)}
+ />
+ <HStack className="w-full items-end" spacing={2}>
+ <div className="flex-1 min-w-0">
+ <Number
+ name="quantity"
+ label="Quantity"
+ minValue={1}
+ defaultValue={1}
+ />
+ </div>
+ <Submit
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Add
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ )}
+ </VStack>
+ );
+}
+
+function ToolRow({
+ tool,
+ instructionId,
+ isDisabled
+}: {
+ tool: AssemblyStepTool;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const deleteFetcher = useFetcher<{ success: boolean }>();
+ const permissions = usePermissions();
+
+ // Optimistically remove the row while the delete is in flight
+ if (deleteFetcher.state !== "idle") return null;
+
+ return (
+ <li className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm">
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={tool.item?.name ?? undefined}
+ >
+ {tool.item?.name}
+ </span>
+ {tool.item?.readableIdWithRevision && (
+ <span className="text-xs text-muted-foreground">
+ {tool.item.readableIdWithRevision}
+ </span>
+ )}
+ <Badge variant="secondary" className="tabular-nums">
+ ×{tool.quantity}
+ </Badge>
+ {!isDisabled && permissions.can("delete", "production") && (
+ <IconButton
+ aria-label={`Delete ${tool.item?.name ?? "tool"}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ deleteFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyStepTool(instructionId, tool.id)
+ });
+ }}
+ />
+ )}
+ </li>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/index.ts b/apps/erp/app/modules/production/ui/Assemblies/index.ts
index 1d1dbe66d0..5512d6e7bf 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/index.ts
+++ b/apps/erp/app/modules/production/ui/Assemblies/index.ts
@@ -5,4 +5,6 @@ export { default as AssemblyInstructionProperties } from "./AssemblyInstructionP
export { default as AssemblyInstructionStatus } from "./AssemblyInstructionStatus";
export { default as AssemblyInstructionsTable } from "./AssemblyInstructionsTable";
export { default as AssemblyStepMaterials } from "./AssemblyStepMaterials";
+export { default as AssemblyStepSlides } from "./AssemblyStepSlides";
+export { default as AssemblyStepTools } from "./AssemblyStepTools";
export { ModelConvertProgress } from "./ModelConvertProgress";
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
similarity index 90%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx
rename to apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
index 555856bbe7..daab699022 100644
--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx
+++ b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx
@@ -1,6 +1,11 @@
import { useCarbon } from "@carbon/auth";
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
HStack,
IconButton,
Input,
@@ -13,6 +18,7 @@ import {
ModalTitle,
toast,
useDebounce,
+ useDisclosure,
VStack
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -29,27 +35,38 @@ import {
LuChevronLeft,
LuChevronRight,
LuChevronUp,
+ LuEllipsisVertical,
+ LuExternalLink,
LuFileDown,
LuLoader,
+ LuMaximize,
LuMinus,
LuPlus,
LuRectangleHorizontal,
LuSave,
+ LuScan,
+ LuSlidersHorizontal,
LuTrash2,
LuUpload
} from "react-icons/lu";
-import { useFetcher } from "react-router";
+import { useFetcher, useNavigate } from "react-router";
import type { EditableTableCellComponentProps } from "~/components/Editable";
import { EditableList, EditableText } from "~/components/Editable";
import Grid from "~/components/Grid";
import { ProcedureStepTypeIcon } from "~/components/Icons";
-import { useUser } from "~/hooks";
-import type { BalloonRegionAnalysis } from "~/modules/quality/inspectionBalloonAnalyze";
-import type { InspectionDocumentContent } from "~/modules/quality/types";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions, useUser } from "~/hooks";
+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import type { BalloonRegionAnalysis } from "~/modules/production/inspectionBalloonAnalyze";
+import type { InspectionDocumentContent } from "~/modules/production/types";
+import type { SamplingStandard } from "~/modules/quality/samplingStandards";
import { procedureStepType } from "~/modules/shared/shared.models";
+import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
import { cropInspectionAnchorToPngBlob } from "./cropInspectionAnchorToPng";
import { buildInspectionDocumentPdfWithOverlaysBytes } from "./exportInspectionDocumentPdfWithOverlays";
+import type { SamplingRule } from "./SamplingRuleModal";
+import SamplingRuleModal, { EMPTY_SAMPLING_RULE } from "./SamplingRuleModal";
type DragState = {
startX: number;
@@ -103,10 +120,15 @@ type AnnotationEditDraft = {
type InspectionDocumentEditorProps = {
diagramId: string;
name: string;
+ partId: string | null;
content: InspectionDocumentContent | null;
features: Array<Record<string, unknown>>;
balloons: Array<Record<string, unknown>>;
unitOfMeasures: Array<{ code: string; name: string }>;
+ // The document's default sampling rule (fallback for features without a
+ // rule) and the company's sampling standard for previews.
+ sampling: SamplingRule | null;
+ samplingStandard: SamplingStandard;
};
type PdfMetrics = {
@@ -349,6 +371,12 @@ type FeatureRow = {
toleranceMinus: string;
units: string;
type: (typeof procedureStepType)[number];
+ samplingPlanType: SamplingRule["samplingPlanType"];
+ samplingSampleSize: number | null;
+ samplingPercentage: number | null;
+ samplingAql: number | null;
+ samplingInspectionLevel: SamplingRule["samplingInspectionLevel"];
+ samplingSeverity: SamplingRule["samplingSeverity"];
featureDirty?: boolean;
geometryDirty?: boolean;
};
@@ -358,6 +386,23 @@ const featureTypeOptions = procedureStepType.map((t) => ({
value: t
}));
+// Compact display of a sampling rule ("AQL 1 · II · Normal"); null = no rule
+// (a feature inherits the document default; the document falls back to All).
+function samplingRuleSummary(rule: SamplingRule): string | null {
+ switch (rule.samplingPlanType) {
+ case "All":
+ return "100%";
+ case "First":
+ return `First ${rule.samplingSampleSize ?? 1}`;
+ case "Percentage":
+ return `${rule.samplingPercentage ?? 100}%`;
+ case "AQL":
+ return `AQL ${rule.samplingAql ?? 1} · ${rule.samplingInspectionLevel ?? "II"} · ${rule.samplingSeverity ?? "Normal"}`;
+ default:
+ return null;
+ }
+}
+
type FeatureMutationFn = (
accessorKey: string,
newValue: string,
@@ -535,6 +580,20 @@ function mapFeatureRowFromRecords(
toleranceMinus: String(feature.toleranceMinus ?? ""),
units: String(feature.unit ?? ""),
type: (feature.type as (typeof procedureStepType)[number]) ?? "Measurement",
+ samplingPlanType:
+ (feature.samplingPlanType as SamplingRule["samplingPlanType"]) ?? null,
+ samplingSampleSize: (feature.samplingSampleSize as number | null) ?? null,
+ samplingPercentage:
+ feature.samplingPercentage == null
+ ? null
+ : Number(feature.samplingPercentage),
+ samplingAql:
+ feature.samplingAql == null ? null : Number(feature.samplingAql),
+ samplingInspectionLevel:
+ (feature.samplingInspectionLevel as SamplingRule["samplingInspectionLevel"]) ??
+ null,
+ samplingSeverity:
+ (feature.samplingSeverity as SamplingRule["samplingSeverity"]) ?? null,
featureDirty: false,
geometryDirty: false
};
@@ -560,12 +619,25 @@ function buildFeatureRowsFromLoader(
export default function InspectionDocumentEditor({
diagramId,
name,
+ partId,
content,
features: initialFeatures,
balloons,
- unitOfMeasures
+ unitOfMeasures,
+ sampling,
+ samplingStandard
}: InspectionDocumentEditorProps) {
const { t } = useLingui();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [items] = useItems();
+ const deleteDisclosure = useDisclosure();
+
+ const part = partId ? items.find((i) => i.id === partId) : undefined;
+ const itemMasterLink =
+ part && part.type !== "Fixture"
+ ? getLinkToItemDetails(part.type, part.id)
+ : null;
const fetcher = useFetcher<{
success: boolean;
message?: string;
@@ -592,6 +664,14 @@ export default function InspectionDocumentEditor({
const companyId = user.company.id;
const [pdfUrl, setPdfUrl] = useState<string>(content?.pdfUrl ?? "");
+ // The document's default sampling rule; persisted with Save alongside the
+ // feature rows. "document" | featureId targets the sampling modal.
+ const [docSampling, setDocSampling] = useState<SamplingRule>(
+ sampling ?? EMPTY_SAMPLING_RULE
+ );
+ const [samplingTarget, setSamplingTarget] = useState<
+ "document" | string | null
+ >(null);
const [pdfFile, setPdfFile] = useState<File | null>(null);
const [uploading, setUploading] = useState(false);
const [replacePdfConfirmOpen, setReplacePdfConfirmOpen] = useState(false);
@@ -1145,7 +1225,13 @@ export default function InspectionDocumentEditor({
tolerancePlus: "",
toleranceMinus: "",
units: "",
- type: "Measurement"
+ type: "Measurement",
+ samplingPlanType: null,
+ samplingSampleSize: null,
+ samplingPercentage: null,
+ samplingAql: null,
+ samplingInspectionLevel: null,
+ samplingSeverity: null
}
];
});
@@ -1982,7 +2068,13 @@ export default function InspectionDocumentEditor({
tolerancePlus: getBalloonValueOrNull(r.tolerancePlus),
toleranceMinus: getBalloonValueOrNull(r.toleranceMinus),
unit: getBalloonValueOrNull(r.units),
- type: r.type
+ type: r.type,
+ samplingPlanType: r.samplingPlanType,
+ samplingSampleSize: r.samplingSampleSize,
+ samplingPercentage: r.samplingPercentage,
+ samplingAql: r.samplingAql,
+ samplingInspectionLevel: r.samplingInspectionLevel,
+ samplingSeverity: r.samplingSeverity
}));
const featuresUpdate = featureRows
@@ -2000,7 +2092,13 @@ export default function InspectionDocumentEditor({
tolerancePlus: getBalloonValueOrNull(r.tolerancePlus),
toleranceMinus: getBalloonValueOrNull(r.toleranceMinus),
unit: getBalloonValueOrNull(r.units),
- type: r.type
+ type: r.type,
+ samplingPlanType: r.samplingPlanType,
+ samplingSampleSize: r.samplingSampleSize,
+ samplingPercentage: r.samplingPercentage,
+ samplingAql: r.samplingAql,
+ samplingInspectionLevel: r.samplingInspectionLevel,
+ samplingSeverity: r.samplingSeverity
}));
formData.set(
@@ -2093,11 +2191,21 @@ export default function InspectionDocumentEditor({
formData.set("defaultPageWidth", String(pdfMetrics.defaultPageWidth));
formData.set("defaultPageHeight", String(pdfMetrics.defaultPageHeight));
}
+ formData.set("samplingDefault", JSON.stringify(docSampling));
fetcher.submit(formData, {
method: "post",
action: path.to.saveInspectionDocument(diagramId)
});
- }, [diagramId, name, pdfUrl, anchorRects, featureRows, pdfMetrics, fetcher]);
+ }, [
+ diagramId,
+ name,
+ pdfUrl,
+ anchorRects,
+ featureRows,
+ pdfMetrics,
+ docSampling,
+ fetcher
+ ]);
const uploadPdfAndSave = useCallback(
async (file: File, options: { clearBalloons: boolean }) => {
@@ -2236,7 +2344,13 @@ export default function InspectionDocumentEditor({
tolerancePlus: "",
toleranceMinus: "",
units: "",
- type: "Measurement"
+ type: "Measurement",
+ samplingPlanType: null,
+ samplingSampleSize: null,
+ samplingPercentage: null,
+ samplingAql: null,
+ samplingInspectionLevel: null,
+ samplingSeverity: null
}
];
});
@@ -2331,6 +2445,17 @@ export default function InspectionDocumentEditor({
[updateFeatureField]
);
+ const updateFeatureSampling = useCallback(
+ (featureId: string, rule: SamplingRule) => {
+ setFeatureRows((prev) =>
+ prev.map((r) =>
+ r.featureId !== featureId ? r : { ...r, ...rule, featureDirty: true }
+ )
+ );
+ },
+ []
+ );
+
const unitOfMeasureOptions = useMemo(
() => unitOfMeasures.map((uom) => ({ value: uom.code, label: uom.name })),
[unitOfMeasures]
@@ -2410,39 +2535,34 @@ export default function InspectionDocumentEditor({
: null
},
{
- id: "actions",
- header: t`Actions`,
+ id: "sampling",
+ header: t`Sampling`,
size: 148,
- cell: ({ row }) => (
- <HStack spacing={0} className="items-center">
- <IconButton
+ cell: ({ row }) => {
+ const summary = samplingRuleSummary(row.original);
+ return (
+ <button
type="button"
- variant="ghost"
- size="sm"
- aria-label={t`Remove feature`}
- icon={<LuTrash2 className="h-4 w-4 text-destructive" />}
+ className="text-left text-sm underline-offset-2 hover:underline"
onClick={(e) => {
e.stopPropagation();
- handleDeleteFeature(row.original.featureId);
+ setSamplingTarget(row.original.featureId);
}}
- />
- <span
- className="mx-1.5 h-5 w-px shrink-0 bg-foreground/20 dark:bg-white/30"
- aria-hidden
- />
- {row.original.balloonId ? (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleUnballoon(row.original.featureId);
- }}
- >
- {t`Unballoon`}
- </Button>
- ) : (
+ >
+ {summary ?? (
+ <span className="text-muted-foreground">{t`Inherit`}</span>
+ )}
+ </button>
+ );
+ }
+ },
+ {
+ id: "actions",
+ header: t`Actions`,
+ size: 148,
+ cell: ({ row }) => (
+ <HStack spacing={1} className="items-center">
+ {!row.original.balloonId && (
<Button
type="button"
variant="outline"
@@ -2457,6 +2577,35 @@ export default function InspectionDocumentEditor({
{t`Balloon`}
</Button>
)}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t`More actions`}
+ icon={<LuEllipsisVertical />}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {row.original.balloonId && (
+ <DropdownMenuItem
+ onClick={() => handleUnballoon(row.original.featureId)}
+ >
+ <LuRectangleHorizontal className="mr-2 size-4" />
+ {t`Unballoon`}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ destructive
+ onClick={() => handleDeleteFeature(row.original.featureId)}
+ >
+ <LuTrash2 className="mr-2 size-4" />
+ {t`Delete`}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</HStack>
)
}
@@ -2587,17 +2736,67 @@ export default function InspectionDocumentEditor({
{/* Header bar — min-height only so controls are not clipped when the row wraps */}
<div className="flex min-h-[50px] flex-shrink-0 flex-wrap items-center justify-between gap-x-3 gap-y-2 overflow-x-auto border-b border-border bg-card px-4 py-2 scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
- <div className="min-w-0 flex-1 pr-2">
+ <div className="flex min-w-0 items-center gap-1 pr-2">
<Input
borderless
value={title}
placeholder={t`Untitled Diagram`}
- className="font-semibold text-base truncate"
+ className="field-sizing-content min-w-[6rem] max-w-[28rem] font-semibold text-base truncate"
onChange={(e) => {
setTitle(e.target.value);
debouncedSaveName(e.target.value);
}}
/>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label={t`More actions`}
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-56">
+ <DropdownMenuItem
+ disabled={!itemMasterLink}
+ onClick={() => {
+ if (itemMasterLink) navigate(itemMasterLink);
+ }}
+ >
+ <LuExternalLink className="mr-2 size-4" />
+ {t`View Item Master`}
+ </DropdownMenuItem>
+ {hasPdf && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={uploading}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <LuUpload className="mr-2 size-4" />
+ {uploading ? t`Uploading…` : t`Replace PDF`}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={pdfExporting}
+ onClick={handleDownloadPdfWithBalloons}
+ >
+ <LuFileDown className="mr-2 size-4" />
+ {t`Download PDF`}
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ destructive
+ disabled={!permissions.can("delete", "quality")}
+ onClick={() => deleteDisclosure.onOpen()}
+ >
+ <LuTrash2 className="mr-2 size-4" />
+ {t`Delete Inspection Plan`}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
<HStack spacing={2} className="flex-shrink-0 flex-wrap justify-end">
<Button
@@ -2619,43 +2818,13 @@ export default function InspectionDocumentEditor({
{placing ? t`Drag to place on drawing` : t`Add Selector`}
</Button>
<Button
- variant={zoomBoxMode ? "primary" : "secondary"}
- onClick={() => {
- setZoomBoxMode((v) => {
- const next = !v;
- if (next) {
- setPlacing(false);
- setPlacingAnnotation(false);
- }
- return next;
- });
- }}
- isDisabled={!isOverlayReady}
+ type="button"
+ variant="secondary"
+ leftIcon={<LuSlidersHorizontal className="h-4 w-4" />}
+ onClick={() => setSamplingTarget("document")}
>
- {zoomBoxMode ? t`Drag to zoom` : t`Zoom Box`}
+ {samplingRuleSummary(docSampling) ?? t`Sampling`}
</Button>
- {hasPdf && (
- <Button
- variant="secondary"
- leftIcon={<LuUpload />}
- onClick={() => fileInputRef.current?.click()}
- isDisabled={uploading}
- >
- {uploading ? t`Uploading…` : t`Replace PDF`}
- </Button>
- )}
- {hasPdf && (
- <Button
- type="button"
- variant="secondary"
- leftIcon={<LuFileDown className="h-4 w-4" />}
- onClick={handleDownloadPdfWithBalloons}
- isDisabled={pdfExporting}
- isLoading={pdfExporting}
- >
- {t`Download PDF`}
- </Button>
- )}
<Button
leftIcon={<LuSave />}
onClick={handleSave}
@@ -2663,7 +2832,29 @@ export default function InspectionDocumentEditor({
>
{t`Save`}
</Button>
- <HStack className="ml-1 rounded-md border bg-background px-1 py-1">
+ <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"
@@ -2687,10 +2878,13 @@ export default function InspectionDocumentEditor({
setZoomScale((z) => Math.min(3, Number((z + 0.1).toFixed(2))))
}
/>
- <Button
+ <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(() => {
@@ -2699,13 +2893,22 @@ export default function InspectionDocumentEditor({
containerRef.current.scrollTop = 0;
});
}}
- >
- {t`Reset View`}
- </Button>
+ />
</HStack>
</HStack>
</div>
+ {deleteDisclosure.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteInspectionDocument(diagramId)}
+ isOpen
+ name={title || t`this inspection plan`}
+ text={t`Are you sure you want to delete this inspection plan? This cannot be undone.`}
+ onCancel={() => deleteDisclosure.onClose()}
+ onSubmit={() => deleteDisclosure.onClose()}
+ />
+ )}
+
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">
<div
ref={editorStackRef}
@@ -3344,7 +3547,7 @@ export default function InspectionDocumentEditor({
: undefined
}
>
- <div className="flex min-h-10 flex-shrink-0 items-center justify-between gap-2 bg-muted/40 px-2 py-2 pl-3">
+ <div className="flex min-h-10 flex-shrink-0 items-center justify-between gap-2 px-2 py-2 pl-3">
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{t`Features`} ({featureRows.length})
</span>
@@ -3396,6 +3599,45 @@ export default function InspectionDocumentEditor({
</div>
</div>
</div>
+
+ {samplingTarget !== null && (
+ <SamplingRuleModal
+ context={samplingTarget === "document" ? "document" : "feature"}
+ featureLabel={
+ samplingTarget === "document"
+ ? undefined
+ : featureRows.find((r) => r.featureId === samplingTarget)?.label
+ }
+ standard={samplingStandard}
+ initial={
+ samplingTarget === "document"
+ ? docSampling
+ : (() => {
+ const row = featureRows.find(
+ (r) => r.featureId === samplingTarget
+ );
+ return {
+ samplingPlanType: row?.samplingPlanType ?? null,
+ samplingSampleSize: row?.samplingSampleSize ?? null,
+ samplingPercentage: row?.samplingPercentage ?? null,
+ samplingAql: row?.samplingAql ?? null,
+ samplingInspectionLevel:
+ row?.samplingInspectionLevel ?? null,
+ samplingSeverity: row?.samplingSeverity ?? null
+ };
+ })()
+ }
+ inheritedRule={samplingTarget === "document" ? null : docSampling}
+ onSave={(rule) => {
+ if (samplingTarget === "document") {
+ setDocSampling(rule);
+ } else if (samplingTarget) {
+ updateFeatureSampling(samplingTarget, rule);
+ }
+ }}
+ onClose={() => setSamplingTarget(null)}
+ />
+ )}
</div>
);
}
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentForm.tsx b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentForm.tsx
similarity index 90%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentForm.tsx
rename to apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentForm.tsx
index 9efcaffec2..52ab797d40 100644
--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentForm.tsx
+++ b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentForm.tsx
@@ -11,7 +11,7 @@ import {
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { Hidden, Input, Item, Submit } from "~/components/Form";
-import { inspectionDocumentValidator } from "~/modules/quality/quality.models";
+import { inspectionDocumentValidator } from "~/modules/production/production.models";
import { path } from "~/utils/path";
type InspectionDocumentFormProps = {
@@ -47,9 +47,7 @@ export default function InspectionDocumentForm({
>
<DrawerHeader>
<DrawerTitle>
- {isEditing
- ? t`Edit Inspection Document`
- : t`New Inspection Document`}
+ {isEditing ? t`Edit Inspection Plan` : t`New Inspection Plan`}
</DrawerTitle>
</DrawerHeader>
<DrawerBody>
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentTable.tsx
similarity index 98%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx
rename to apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentTable.tsx
index 0eee09c436..b5213a8106 100644
--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx
+++ b/apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentTable.tsx
@@ -160,13 +160,13 @@ const InspectionDocumentTable = memo(
primaryAction={
permissions.can("create", "quality") && (
<New
- label={t`Inspection Document`}
+ label={t`Inspection Plan`}
to={`${path.to.newInspectionDocument}?${params?.toString()}`}
/>
)
}
renderContextMenu={renderContextMenu}
- title={t`Inspection Documents`}
+ title={t`Inspection Plans`}
/>
{deleteDisclosure.isOpen && selectedDiagram && (
<ConfirmDelete
@@ -181,7 +181,7 @@ const InspectionDocumentTable = memo(
deleteDisclosure.onClose();
}}
name={selectedDiagram.name}
- text={t`Are you sure you want to delete this inspection document?`}
+ text={t`Are you sure you want to delete this inspection plan?`}
/>
)}
</>
diff --git a/apps/erp/app/modules/production/ui/InspectionDocument/SamplingRuleModal.tsx b/apps/erp/app/modules/production/ui/InspectionDocument/SamplingRuleModal.tsx
new file mode 100644
index 0000000000..ed422dc909
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/InspectionDocument/SamplingRuleModal.tsx
@@ -0,0 +1,376 @@
+import {
+ Button,
+ HStack,
+ Input,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useState } from "react";
+import type {
+ InspectionLevel,
+ InspectionSeverity,
+ SamplingPlanType,
+ SamplingStandard
+} from "~/modules/quality/samplingStandards";
+import {
+ resolveSamplingPlan,
+ standardAqlValues
+} from "~/modules/quality/samplingStandards";
+
+// One sampling rule, as stored on inspectionDocument (the default) and on
+// inspectionFeature (the per-feature override). All-null = no rule.
+export type SamplingRule = {
+ samplingPlanType: SamplingPlanType | null;
+ samplingSampleSize: number | null;
+ samplingPercentage: number | null;
+ samplingAql: number | null;
+ samplingInspectionLevel: InspectionLevel | null;
+ samplingSeverity: InspectionSeverity | null;
+};
+
+export const EMPTY_SAMPLING_RULE: SamplingRule = {
+ samplingPlanType: null,
+ samplingSampleSize: null,
+ samplingPercentage: null,
+ samplingAql: null,
+ samplingInspectionLevel: null,
+ samplingSeverity: null
+};
+
+export function samplingRuleToPlan(rule: SamplingRule | null | undefined) {
+ if (!rule?.samplingPlanType) return null;
+ return {
+ type: rule.samplingPlanType,
+ sampleSize: rule.samplingSampleSize,
+ percentage: rule.samplingPercentage,
+ aql: rule.samplingAql,
+ inspectionLevel: rule.samplingInspectionLevel,
+ severity: rule.samplingSeverity
+ };
+}
+
+const SAMPLE_LOT_SIZES = [10, 50, 100, 500, 1000];
+
+type SamplingRuleModalProps = {
+ // "document" edits the document's default rule (the fallback for features
+ // without their own rule); "feature" edits one feature's override, with an
+ // Inherit choice that clears it.
+ context: "document" | "feature";
+ featureLabel?: string;
+ standard: SamplingStandard;
+ initial: SamplingRule;
+ // The document default, used to preview what Inherit resolves to.
+ inheritedRule?: SamplingRule | null;
+ onSave: (rule: SamplingRule) => void;
+ onClose: () => void;
+};
+
+const INHERIT = "__inherit__";
+
+const SamplingRuleModal = ({
+ context,
+ featureLabel,
+ standard,
+ initial,
+ inheritedRule,
+ onSave,
+ onClose
+}: SamplingRuleModalProps) => {
+ const { t } = useLingui();
+
+ const [type, setType] = useState<string>(
+ initial.samplingPlanType ?? (context === "feature" ? INHERIT : "All")
+ );
+ const [sampleSize, setSampleSize] = useState<number>(
+ initial.samplingSampleSize ?? 1
+ );
+ const [percentage, setPercentage] = useState<number>(
+ initial.samplingPercentage ?? 10
+ );
+ const [aql, setAql] = useState<number>(initial.samplingAql ?? 1.0);
+ const [inspectionLevel, setInspectionLevel] = useState<InspectionLevel>(
+ initial.samplingInspectionLevel ?? "II"
+ );
+ const [severity, setSeverity] = useState<InspectionSeverity>(
+ initial.samplingSeverity ?? "Normal"
+ );
+
+ const typeOptions: { value: string; label: string }[] = [
+ ...(context === "feature"
+ ? [{ value: INHERIT, label: t`Inherit document default` }]
+ : []),
+ { value: "All", label: t`Inspect All` },
+ { value: "First", label: t`Inspect First N` },
+ { value: "Percentage", label: t`Percentage` },
+ { value: "AQL", label: t`AQL (Z1.4 / ISO 2859-1)` }
+ ];
+
+ const inspectionLevelOptions: { value: InspectionLevel; label: string }[] = [
+ { value: "S1", label: t`S-1 (coarsest special)` },
+ { value: "S2", label: t`S-2` },
+ { value: "S3", label: t`S-3` },
+ { value: "S4", label: t`S-4 (finest special)` },
+ { value: "I", label: t`I (reduced)` },
+ { value: "II", label: t`II (normal default)` },
+ { value: "III", label: t`III (tightened)` }
+ ];
+
+ const severityOptions: { value: InspectionSeverity; label: string }[] = [
+ { value: "Normal", label: t`Normal` },
+ { value: "Tightened", label: t`Tightened` },
+ { value: "Reduced", label: t`Reduced` }
+ ];
+
+ const isInherit = type === INHERIT;
+
+ // The plan the preview resolves: the selected rule, or (for Inherit) the
+ // document default, or All when nothing is defined anywhere.
+ const previewPlan = isInherit
+ ? (samplingRuleToPlan(inheritedRule) ?? { type: "All" as const })
+ : {
+ type: type as SamplingPlanType,
+ sampleSize,
+ percentage,
+ aql,
+ inspectionLevel,
+ severity
+ };
+
+ const handleSave = () => {
+ if (isInherit) {
+ onSave(EMPTY_SAMPLING_RULE);
+ onClose();
+ return;
+ }
+ const planType = type as SamplingPlanType;
+ onSave({
+ samplingPlanType: planType,
+ samplingSampleSize: planType === "First" ? sampleSize : null,
+ samplingPercentage: planType === "Percentage" ? percentage : null,
+ samplingAql: planType === "AQL" ? aql : null,
+ samplingInspectionLevel: planType === "AQL" ? inspectionLevel : null,
+ samplingSeverity: planType === "AQL" ? severity : null
+ });
+ onClose();
+ };
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ {context === "document" ? (
+ <Trans>Default Sampling</Trans>
+ ) : (
+ <Trans>Sampling — Feature {featureLabel}</Trans>
+ )}
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4} className="w-full">
+ {context === "document" ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Applies to features without their own rule, and to the lot
+ when this plan drives an inspection.
+ </Trans>
+ </p>
+ ) : null}
+ <div className="flex flex-col gap-2 w-full">
+ <Label>
+ <Trans>Plan Type</Trans>
+ </Label>
+ <Select value={type} onValueChange={setType}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {typeOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {type === "First" && (
+ <div className="flex flex-col gap-2 w-full">
+ <Label>
+ <Trans>Sample Size</Trans>
+ </Label>
+ <Input
+ type="number"
+ min={1}
+ value={String(sampleSize)}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) setSampleSize(Math.max(1, n));
+ }}
+ />
+ </div>
+ )}
+
+ {type === "Percentage" && (
+ <div className="flex flex-col gap-2 w-full">
+ <Label>
+ <Trans>Percentage of Lot</Trans>
+ </Label>
+ <Input
+ type="number"
+ min={1}
+ max={100}
+ value={String(percentage)}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) {
+ setPercentage(Math.min(100, Math.max(1, n)));
+ }
+ }}
+ />
+ </div>
+ )}
+
+ {type === "AQL" && (
+ <div className="grid grid-cols-3 gap-4 w-full">
+ <div className="flex flex-col gap-2">
+ <Label>
+ <Trans>AQL</Trans>
+ </Label>
+ <Select
+ value={String(aql)}
+ onValueChange={(v) => setAql(parseFloat(v))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {standardAqlValues.map((v) => (
+ <SelectItem key={v} value={String(v)}>
+ {v.toString()}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>
+ <Trans>Inspection Level</Trans>
+ </Label>
+ <Select
+ value={inspectionLevel}
+ onValueChange={(v) =>
+ setInspectionLevel(v as InspectionLevel)
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {inspectionLevelOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>
+ <Trans>Severity</Trans>
+ </Label>
+ <Select
+ value={severity}
+ onValueChange={(v) => setSeverity(v as InspectionSeverity)}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {severityOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ )}
+
+ <div className="flex flex-col gap-2 w-full border rounded-md p-4">
+ <HStack className="justify-between">
+ <span className="text-sm font-medium">
+ <Trans>Preview</Trans>
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {standard === "ANSI_Z1_4" ? "ANSI/ASQ Z1.4" : "ISO 2859-1"}
+ </span>
+ </HStack>
+ <table className="text-sm w-full">
+ <thead className="text-xs text-muted-foreground">
+ <tr>
+ <th className="text-left font-medium py-1">
+ <Trans>Lot</Trans>
+ </th>
+ <th className="text-left font-medium py-1">
+ <Trans>Sample</Trans>
+ </th>
+ <th className="text-left font-medium py-1">Ac</th>
+ <th className="text-left font-medium py-1">Re</th>
+ <th className="text-left font-medium py-1">
+ <Trans>Letter</Trans>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {SAMPLE_LOT_SIZES.map((n) => {
+ const res = resolveSamplingPlan(previewPlan, n, standard);
+ return (
+ <tr key={n}>
+ <td className="py-1 tabular-nums">{n}</td>
+ <td className="py-1 tabular-nums">{res.sampleSize}</td>
+ <td className="py-1 tabular-nums">{res.acceptance}</td>
+ <td className="py-1 tabular-nums">{res.rejection}</td>
+ <td className="py-1">{res.codeLetter ?? "—"}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button onClick={handleSave}>
+ <Trans>Save</Trans>
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default SamplingRuleModal;
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/cropInspectionAnchorToPng.ts b/apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts
similarity index 100%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/cropInspectionAnchorToPng.ts
rename to apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts b/apps/erp/app/modules/production/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts
similarity index 100%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts
rename to apps/erp/app/modules/production/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/index.ts b/apps/erp/app/modules/production/ui/InspectionDocument/index.ts
similarity index 100%
rename from apps/erp/app/modules/quality/ui/InspectionDocument/index.ts
rename to apps/erp/app/modules/production/ui/InspectionDocument/index.ts
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 2437a9d79f..b4cd7fc842 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -95,7 +95,11 @@ type Material = z.infer<typeof jobMaterialValidator> & {
} | null;
};
-type Operation = z.infer<typeof jobOperationValidator>;
+type Operation = z.infer<typeof jobOperationValidator> & {
+ // The same operations data BillOfProcess gets — carries its steps at runtime, so the BoM
+ // editor can offer a per-step assignment. Narrow type, optional here.
+ jobOperationStep?: { id: string; name: string | null }[];
+};
type ItemWithData = SortableItem & {
data: Material;
@@ -638,6 +642,7 @@ function MaterialForm({
methodType: MethodType;
description: string;
jobOperationId: string;
+ jobOperationStepIds?: string[];
unitCost: number;
unitOfMeasureCode: string;
quantity: number;
@@ -651,6 +656,10 @@ function MaterialForm({
methodType: item.data.methodType ?? "Pull from Inventory",
description: item.data.description ?? "",
jobOperationId: item.data.jobOperationId ?? "",
+ jobOperationStepIds: (
+ (item.data as { jobMaterialStep?: { jobOperationStepId: string }[] })
+ .jobMaterialStep ?? []
+ ).map((s) => s.jobOperationStepId),
unitCost: item.data.unitCost ?? 0,
unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
quantity: item.data.quantity ?? 1,
@@ -985,10 +994,14 @@ function MaterialForm({
onChange={(newValue) => {
setItemData((d) => ({
...d,
- jobOperationId: newValue?.value as string
+ jobOperationId: newValue?.value as string,
+ // Steps belong to an operation — clear them when the operation changes.
+ jobOperationStepIds: []
}));
}}
/>
+ {/* Part ↔ step assignment now lives on the STEP (the BoP step editor's "Parts"
+ picker), not here — so there is no per-material "Steps" dropdown in the BOM. */}
</div>
</div>
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 96c7b3a083..910ac704c0 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -78,7 +78,13 @@ import {
LuShieldX,
LuTriangleAlert
} from "react-icons/lu";
-import { Link, useFetcher, useFetchers, useParams } from "react-router";
+import {
+ Link,
+ useFetcher,
+ useFetchers,
+ useParams,
+ useRevalidator
+} from "react-router";
import type { z } from "zod";
import {
Assignee,
@@ -103,15 +109,18 @@ import {
UnitHint,
WorkCenter
} from "~/components/Form";
+import AssemblyInstruction from "~/components/Form/AssemblyInstruction";
+import InspectionDocument from "~/components/Form/InspectionDocument";
import Procedure from "~/components/Form/Procedure";
import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";
import { getUnitHint } from "~/components/Form/UnitHint";
import UnitOfMeasure, {
useUnitOfMeasure
} from "~/components/Form/UnitOfMeasure";
-import { ProcedureStepTypeIcon } from "~/components/Icons";
+import { OperationTypeIcon, ProcedureStepTypeIcon } from "~/components/Icons";
import InfiniteScroll from "~/components/InfiniteScroll";
import { ConfirmDelete } from "~/components/Modals";
+import { SlidesEditor, uploadStepSlideModel } from "~/components/SlidesEditor";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import {
SortableList,
@@ -119,6 +128,7 @@ import {
SortableListItemPanel,
SortableListItemToggle
} from "~/components/SortableList";
+import { StepLinkEditor } from "~/components/StepLinkEditor";
import {
useDateFormatter,
usePermissions,
@@ -129,7 +139,10 @@ import {
import type {
OperationParameter,
OperationStep,
- OperationTool
+ OperationStepSlide,
+ OperationTool,
+ SlideAnnotation,
+ SlideSize
} from "~/modules/shared";
import {
methodOperationOrders,
@@ -149,7 +162,8 @@ import { getPrivateUrl, path } from "~/utils/path";
import {
jobOperationValidator,
jobOperationValidatorForReleasedJob,
- procedureSyncValidator
+ procedureSyncValidator,
+ syncAssemblyToBopValidator
} from "../../production.models";
import { getProductionEventsPage } from "../../production.service";
import type { Job, JobOperation } from "../../types";
@@ -176,10 +190,16 @@ type JobOperationStep = OperationStep & {
jobOperationStepRecord?:
| Database["public"]["Tables"]["jobOperationStepRecord"]["Row"][]
| null;
+ jobOperationStepSlide?: OperationStepSlide[] | null;
};
type JobMaterial = {
+ id: string;
itemId: string;
+ description?: string | null;
+ quantity?: number | null;
+ jobOperationId?: string | null;
+ jobMaterialStep?: { jobOperationStepId: string }[] | null;
};
type JobBillOfProcessProps = {
@@ -226,7 +246,7 @@ function makeItem(
</h3>
{operation.reworkId && <Badge variant="red">Rework</Badge>}
</HStack>
- {operation.operationType === "Outside" && (
+ {operation.operationType === "Outside Processing" && (
<SupplierProcessPreview
processId={operation.processId}
supplierProcessId={operation.operationSupplierProcessId}
@@ -238,8 +258,8 @@ function makeItem(
order: operation.operationOrder,
details: (
<HStack spacing={1}>
- {operation.operationType === "Outside" ? (
- <Badge>Outside</Badge>
+ {operation.operationType === "Outside Processing" ? (
+ <Badge>Outside Processing</Badge>
) : (
<>
{(operation?.setupTime ?? 0) > 0 && (
@@ -350,7 +370,9 @@ const initialOperation: Omit<
operationUnitCost: 0,
operationLeadTime: 0,
operationOrder: "After Previous",
- operationType: "Inside",
+ operationType: "Process",
+ assemblyInstructionId: "",
+ inspectionDocumentId: "",
overheadRate: 0,
processId: "",
procedureId: "",
@@ -715,6 +737,34 @@ const JobBillOfProcess = ({
}
});
+ // Phase 3: keep the live job's BOP steps fresh without closing the panel. When steps are
+ // added/edited/reordered for the open operation, or an operator records a step on the shop
+ // floor (jobOperationStepRecord), revalidate so the loader re-serves the latest steps.
+ const revalidator = useRevalidator();
+ useRealtimeChannel({
+ topic: `bop-steps:${selectedItemId}`,
+ enabled: !!selectedItemId && !temporaryItems[selectedItemId],
+ setup(channel) {
+ const refresh = () => revalidator.revalidate();
+ return channel
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "jobOperationStep",
+ filter: `operationId=eq.${selectedItemId}`
+ },
+ refresh
+ )
+ .on(
+ "postgres_changes",
+ { event: "*", schema: "public", table: "jobOperationStepRecord" },
+ refresh
+ );
+ }
+ });
+
const loadMoreProductionEvents = useCallback(async () => {
if (isLoading || !hasMore || !selectedItemId) return;
@@ -788,6 +838,7 @@ const JobBillOfProcess = ({
>
<OperationForm
item={item}
+ itemId={itemId}
isDisabled={isDisabled}
job={jobData?.job}
locationId={locationId}
@@ -813,7 +864,8 @@ const JobBillOfProcess = ({
id: 1,
label: t`Instructions`,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
content: (
<div className="flex flex-col">
<div>
@@ -850,7 +902,8 @@ const JobBillOfProcess = ({
{
id: 2,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -875,7 +928,8 @@ const JobBillOfProcess = ({
{
id: 3,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -894,6 +948,7 @@ const JobBillOfProcess = ({
}
temporaryItems={temporaryItems}
materials={materials}
+ tools={tools}
/>
</div>
)
@@ -901,7 +956,8 @@ const JobBillOfProcess = ({
{
id: 4,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -926,7 +982,8 @@ const JobBillOfProcess = ({
{
id: 5,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: t`Events`,
content: (
<div className="flex w-full flex-col pr-2 py-6 min-h-[300px]">
@@ -953,7 +1010,8 @@ const JobBillOfProcess = ({
{
id: 6,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: t`Chat`,
content: <OperationChat jobOperationId={item.id} />
}
@@ -1033,16 +1091,19 @@ function StepsForm({
isDisabled,
steps,
temporaryItems,
- materials
+ materials,
+ tools
}: {
operationId: string;
isDisabled: boolean;
steps: JobOperationStep[];
temporaryItems: TemporaryItems;
materials: JobMaterial[];
+ tools: OperationTool[];
}) {
const fetcher = useFetcher<typeof newJobOperationParameterAction>();
const { t } = useLingui();
+ const revalidator = useRevalidator();
const sortOrderFetcher = useFetcher<{ success: boolean }>();
const [type, setType] = useState<OperationStep["type"]>("Task");
const [description, setDescription] = useState<JSONContent>({});
@@ -1107,9 +1168,60 @@ function StepsForm({
const { carbon } = useCarbon();
const {
+ id: userId,
company: { id: companyId }
} = useUser();
const [allItems] = useItems();
+ // Slides chosen while creating a step are buffered here (the step has no id yet); they're
+ // attached to the new step right after it's created. See the effect below.
+ // A buffered slide is image XOR model (imagePath / modelUploadId).
+ const [draftSlides, setDraftSlides] = useState<
+ {
+ id: string;
+ imagePath: string | null;
+ modelUploadId: string | null;
+ caption: string;
+ size: SlideSize;
+ annotations: SlideAnnotation[];
+ }[]
+ >([]);
+ const [draftUploading, setDraftUploading] = useState(false);
+ const draftFileInputRef = useRef<HTMLInputElement>(null);
+ const draftModelInputRef = useRef<HTMLInputElement>(null);
+
+ // Parts (this operation's BOM materials) the operator can assign to a step. Parts picked
+ // while CREATING a step are buffered here and attached right after the step is created.
+ const operationParts = useMemo(
+ () =>
+ (materials ?? [])
+ .filter((m) => m.jobOperationId === operationId)
+ .map((m) => ({
+ id: m.id,
+ name: m.description || m.itemId,
+ quantity: m.quantity ?? 1
+ })),
+ [materials, operationId]
+ );
+ const [draftParts, setDraftParts] = useState<string[]>([]);
+
+ // Tools (this operation's tools) the operator can assign to a step — the tool twin of
+ // operationParts/draftParts. Tools picked while CREATING a step are buffered here and
+ // attached right after the step is created (see the effect below).
+ const allTools = useTools();
+ const operationTools = useMemo(
+ () =>
+ (tools ?? []).map((tl) => {
+ const tool = allTools.find((x) => x.id === tl.toolId);
+ return {
+ id: tl.id ?? "",
+ name: tool?.readableIdWithRevision ?? tl.toolId ?? "",
+ secondary: tool?.name ?? undefined,
+ quantity: tl.quantity ?? 1
+ };
+ }),
+ [tools, allTools]
+ );
+ const [draftTools, setDraftTools] = useState<string[]>([]);
const materialItemIds = useMemo(
() => new Set((materials ?? []).map((m) => m.itemId)),
@@ -1146,6 +1258,153 @@ function StepsForm({
return getPrivateUrl(result.data.path);
};
+ const onAddDraftSlide = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setDraftUploading(true);
+ try {
+ const ext = file.name.split(".").pop();
+ const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
+ const result = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+ if (result.error || !result.data) {
+ toast.error(t`Failed to upload image`);
+ return;
+ }
+ setDraftSlides((prev) => [
+ ...prev,
+ {
+ id: nanoid(),
+ imagePath: result.data.path,
+ modelUploadId: null,
+ caption: "",
+ size: "medium",
+ annotations: []
+ }
+ ]);
+ } finally {
+ setDraftUploading(false);
+ }
+ };
+
+ // Upload a chosen 3D model, register it as a modelUpload (which also kicks the
+ // assembler's STEP → GLB conversion), and buffer it as a draft model slide.
+ const onAddDraftModel = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon) return;
+ setDraftUploading(true);
+ try {
+ const modelUploadId = await uploadStepSlideModel(carbon, companyId, file);
+ if (!modelUploadId) {
+ toast.error(t`Failed to upload model`);
+ return;
+ }
+ setDraftSlides((prev) => [
+ ...prev,
+ {
+ id: nanoid(),
+ imagePath: null,
+ modelUploadId,
+ caption: "",
+ size: "medium",
+ annotations: []
+ }
+ ]);
+ } finally {
+ setDraftUploading(false);
+ }
+ };
+
+ // When the new step is created, attach any buffered slides to it, then revalidate so they
+ // show on the step and reset the buffer for the next step.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftSlides.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const slideRows = draftSlides.map((slide, index) => ({
+ stepId: newStepId,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption || null,
+ sortOrder: index + 1,
+ size: slide.size,
+ annotations: slide.annotations,
+ companyId,
+ createdBy: userId
+ }));
+ const { error } = await carbon
+ .from("jobOperationStepSlide")
+ .insert(slideRows);
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save slides`);
+ return;
+ }
+ setDraftSlides([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
+ // When the new step is created, attach any buffered parts, then revalidate + reset.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftParts.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const { error } = await carbon.from("jobMaterialStep").insert(
+ draftParts.map((jobMaterialId) => ({
+ jobMaterialId,
+ jobOperationStepId: newStepId
+ }))
+ );
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save parts`);
+ return;
+ }
+ setDraftParts([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
+ // When the new step is created, attach any buffered tools, then revalidate + reset.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step id
+ useEffect(() => {
+ const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;
+ if (!newStepId || draftTools.length === 0 || !carbon) return;
+ let cancelled = false;
+ (async () => {
+ const { error } = await carbon.from("jobOperationToolStep").insert(
+ draftTools.map((jobOperationToolId) => ({
+ jobOperationToolId,
+ jobOperationStepId: newStepId
+ }))
+ );
+ if (cancelled) return;
+ if (error) {
+ toast.error(t`Failed to save tools`);
+ return;
+ }
+ setDraftTools([]);
+ revalidator.revalidate();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fetcher.data]);
+
if (isDisabled && temporaryItems[operationId]) {
return (
<Alert className="max-w-[420px] mx-auto my-8">
@@ -1276,6 +1535,79 @@ function StepsForm({
<ArrayInput name="listValues" label={t`List Options`} />
)}
+ <SlidesEditor
+ slides={draftSlides.map((slide) => ({
+ key: slide.id,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption,
+ size: slide.size,
+ annotations: slide.annotations
+ }))}
+ isDisabled={isDisabled}
+ busy={draftUploading}
+ fileInputRef={draftFileInputRef}
+ onFileChange={onAddDraftSlide}
+ modelInputRef={draftModelInputRef}
+ onModelFileChange={onAddDraftModel}
+ onRemove={(index) =>
+ setDraftSlides((prev) => prev.filter((_, i) => i !== index))
+ }
+ onCaptionBlur={(index, caption) =>
+ setDraftSlides((prev) =>
+ prev.map((slide, i) =>
+ i === index ? { ...slide, caption } : slide
+ )
+ )
+ }
+ onAnnotationsChange={(index, annotations) =>
+ setDraftSlides((prev) =>
+ prev.map((slide, i) =>
+ i === index ? { ...slide, annotations } : slide
+ )
+ )
+ }
+ />
+
+ <StepLinkEditor
+ label={t`Parts`}
+ addLabel={t`Add parts`}
+ emptyLabel={t`No parts`}
+ searchPlaceholder={t`Search parts...`}
+ removeLabel={t`Remove part`}
+ items={operationParts}
+ linkedIds={draftParts}
+ isDisabled={isDisabled}
+ onAdd={(partId) =>
+ setDraftParts((prev) =>
+ prev.includes(partId) ? prev : [...prev, partId]
+ )
+ }
+ onRemove={(partId) =>
+ setDraftParts((prev) => prev.filter((id) => id !== partId))
+ }
+ />
+
+ <StepLinkEditor
+ label={t`Tools`}
+ addLabel={t`Add tools`}
+ emptyLabel={t`No tools`}
+ searchPlaceholder={t`Search tools...`}
+ removeLabel={t`Remove tool`}
+ icon={<LuHammer />}
+ items={operationTools}
+ linkedIds={draftTools}
+ isDisabled={isDisabled}
+ onAdd={(toolId) =>
+ setDraftTools((prev) =>
+ prev.includes(toolId) ? prev : [...prev, toolId]
+ )
+ }
+ onRemove={(toolId) =>
+ setDraftTools((prev) => prev.filter((id) => id !== toolId))
+ }
+ />
+
<Submit
leftIcon={<LuCirclePlus />}
isDisabled={isDisabled || fetcher.state !== "idle"}
@@ -1317,6 +1649,8 @@ function StepsForm({
attribute={step}
operationId={operationId}
typeOptions={typeOptions}
+ materials={materials}
+ tools={tools}
isDisabled={isDisabled}
dragControls={dragControls}
itemMentions={itemMentions}
@@ -1337,6 +1671,274 @@ function StepsForm({
);
}
+// Parts assigned to an EXISTING job step — the step-side of the part↔step link. Toggles each
+// jobMaterialStep link immediately via the material route. Job-tier twin of StepParts.
+function JobStepParts({
+ step,
+ operationId,
+ materials,
+ isDisabled
+}: {
+ step: JobOperationStep;
+ operationId: string;
+ materials: JobMaterial[];
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+
+ const operationParts = (materials ?? [])
+ .filter((m) => m.jobOperationId === operationId)
+ .map((m) => ({
+ id: m.id,
+ name: m.description || m.itemId,
+ quantity: m.quantity ?? 1
+ }));
+
+ const linkedPartIds = (materials ?? [])
+ .filter((m) =>
+ (m.jobMaterialStep ?? []).some((s) => s.jobOperationStepId === step.id)
+ )
+ .map((m) => m.id);
+
+ const toggle = (partId: string, linked: boolean) => {
+ if (!step.id) return;
+ const fd = new FormData();
+ fd.append("materialId", partId);
+ fd.append("stepId", step.id);
+ fd.append("linked", String(linked));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.jobOperationStepMaterial
+ });
+ };
+
+ return (
+ <StepLinkEditor
+ label={t`Parts`}
+ addLabel={t`Add parts`}
+ emptyLabel={t`No parts`}
+ searchPlaceholder={t`Search parts...`}
+ removeLabel={t`Remove part`}
+ items={operationParts}
+ linkedIds={linkedPartIds}
+ isDisabled={isDisabled}
+ busy={fetcher.state !== "idle"}
+ onAdd={(id) => toggle(id, true)}
+ onRemove={(id) => toggle(id, false)}
+ />
+ );
+}
+
+// Tools assigned to an EXISTING job step — the step-side of the tool↔step link. Toggles each
+// jobOperationToolStep link immediately via the tool route. Job-tier twin of StepTools.
+function JobStepTools({
+ step,
+ tools,
+ isDisabled
+}: {
+ step: JobOperationStep;
+ tools: OperationTool[];
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+ const allTools = useTools();
+
+ const operationTools = (tools ?? []).map((tl) => {
+ const tool = allTools.find((x) => x.id === tl.toolId);
+ return {
+ id: tl.id ?? "",
+ name: tool?.readableIdWithRevision ?? tl.toolId ?? "",
+ secondary: tool?.name ?? undefined,
+ quantity: tl.quantity ?? 1
+ };
+ });
+
+ const linkedToolIds = (tools ?? [])
+ .filter((tl) =>
+ (
+ tl.jobOperationStepIds ??
+ (
+ (tl as { jobOperationToolStep?: { jobOperationStepId: string }[] })
+ .jobOperationToolStep ?? []
+ ).map((s) => s.jobOperationStepId)
+ ).some((stepId) => stepId === step.id)
+ )
+ .map((tl) => tl.id ?? "");
+
+ const toggle = (toolId: string, linked: boolean) => {
+ if (!step.id) return;
+ const fd = new FormData();
+ fd.append("toolId", toolId);
+ fd.append("stepId", step.id);
+ fd.append("linked", String(linked));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.jobOperationStepTool
+ });
+ };
+
+ return (
+ <StepLinkEditor
+ label={t`Tools`}
+ addLabel={t`Add tools`}
+ emptyLabel={t`No tools`}
+ searchPlaceholder={t`Search tools...`}
+ removeLabel={t`Remove tool`}
+ icon={<LuHammer />}
+ items={operationTools}
+ linkedIds={linkedToolIds}
+ isDisabled={isDisabled}
+ busy={fetcher.state !== "idle"}
+ onAdd={(id) => toggle(id, true)}
+ onRemove={(id) => toggle(id, false)}
+ />
+ );
+}
+
+// Reference images ("slides") for an EXISTING job step — upload, caption, resize, annotate,
+// delete; persisted immediately via the job slide routes. Job-tier twin of the item
+// StepSlides (BillOfProcess); reuses the shared SlidesEditor. Lets an operator's reference
+// content be corrected on the job without recreating it, since the MES reads the job copy.
+function JobStepSlides({
+ step,
+ isDisabled
+}: {
+ step: JobOperationStep;
+ isDisabled: boolean;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+ const captionFetcher = useFetcher();
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId }
+ } = useUser();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const modelInputRef = useRef<HTMLInputElement>(null);
+ const [uploading, setUploading] = useState(false);
+
+ const slides = ((step.jobOperationStepSlide ?? []) as OperationStepSlide[])
+ .slice()
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
+
+ const nextSortOrder = () =>
+ slides.reduce((m, s) => Math.max(m, s.sortOrder ?? 0), 0) + 1;
+
+ const onAddFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon || !step.id) return;
+ setUploading(true);
+ try {
+ const ext = file.name.split(".").pop();
+ const fileName = `${companyId}/parts/${nanoid()}.${ext}`;
+ const result = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+ if (result.error || !result.data) {
+ toast.error(t`Failed to upload image`);
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", step.id);
+ fd.append("imagePath", result.data.path);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newJobOperationStepSlide
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Upload a 3D model and attach it to the step as a model slide. The model-upload
+ // API also starts the assembler's STEP → GLB conversion.
+ const onAddModelFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file || !carbon || !step.id) return;
+ setUploading(true);
+ try {
+ const modelUploadId = await uploadStepSlideModel(carbon, companyId, file);
+ if (!modelUploadId) {
+ toast.error(t`Failed to upload model`);
+ return;
+ }
+ const fd = new FormData();
+ fd.append("stepId", step.id);
+ fd.append("modelUploadId", modelUploadId);
+ fd.append("sortOrder", String(nextSortOrder()));
+ fetcher.submit(fd, {
+ method: "post",
+ action: path.to.newJobOperationStepSlide
+ });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ // Update one slide: always carries the required fields (id → the route updates rather
+ // than inserts; stepId + the slide's content field satisfy the validator) plus whatever
+ // changed. Fields not sent are preserved, so a caption edit never wipes size/annotations
+ // and vice-versa.
+ function saveSlide(
+ slide: OperationStepSlide,
+ fields: Record<string, string>
+ ) {
+ const fd = new FormData();
+ fd.append("id", slide.id);
+ fd.append("stepId", slide.stepId);
+ if (slide.imagePath) fd.append("imagePath", slide.imagePath);
+ if (slide.modelUploadId) fd.append("modelUploadId", slide.modelUploadId);
+ fd.append("sortOrder", String(slide.sortOrder ?? 1));
+ for (const [key, value] of Object.entries(fields)) fd.append(key, value);
+ captionFetcher.submit(fd, {
+ method: "post",
+ action: path.to.newJobOperationStepSlide
+ });
+ }
+
+ return (
+ <SlidesEditor
+ slides={slides.map((s) => ({
+ key: s.id,
+ imagePath: s.imagePath,
+ modelUploadId: s.modelUploadId,
+ caption: s.caption,
+ size: s.size,
+ annotations: s.annotations
+ }))}
+ isDisabled={isDisabled}
+ busy={uploading || fetcher.state !== "idle"}
+ fileInputRef={fileInputRef}
+ onFileChange={onAddFile}
+ modelInputRef={modelInputRef}
+ onModelFileChange={onAddModelFile}
+ onRemove={(index) => {
+ const slide = slides[index];
+ if (!slide) return;
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.deleteJobOperationStepSlide(slide.id)
+ });
+ }}
+ onCaptionBlur={(index, caption) => {
+ const slide = slides[index];
+ if (slide && (slide.caption ?? "") !== caption)
+ saveSlide(slide, { caption });
+ }}
+ onAnnotationsChange={(index, annotations) => {
+ const slide = slides[index];
+ if (slide)
+ saveSlide(slide, { annotations: JSON.stringify(annotations) });
+ }}
+ />
+ );
+}
+
function DraggableStepItem({
stepId,
isDisabled,
@@ -1363,6 +1965,8 @@ function StepsListItem({
attribute,
operationId,
typeOptions,
+ materials,
+ tools,
isDisabled = false,
dragControls,
itemMentions,
@@ -1371,6 +1975,8 @@ function StepsListItem({
attribute: JobOperationStep;
operationId: string;
typeOptions: { label: JSX.Element; value: string }[];
+ materials: JobMaterial[];
+ tools: OperationTool[];
isDisabled?: boolean;
dragControls?: DragControls;
itemMentions: { id: string; label: string }[];
@@ -1393,6 +1999,7 @@ function StepsListItem({
const deleteModalDisclosure = useDisclosure();
const submitted = useRef(false);
const fetcher = useFetcher<typeof editJobOperationStepAction>();
+ const duplicateStepFetcher = useFetcher();
const { t } = useLingui();
const [description, setDescription] = useState<JSONContent>(() => {
if (!attribute.description) return {};
@@ -1558,6 +2165,18 @@ function StepsListItem({
{type === "List" && (
<ArrayInput name="listValues" label={t`List Options`} />
)}
+ <JobStepSlides step={attribute} isDisabled={isDisabled} />
+ <JobStepParts
+ step={attribute}
+ operationId={operationId}
+ materials={materials}
+ isDisabled={isDisabled}
+ />
+ <JobStepTools
+ step={attribute}
+ tools={tools}
+ isDisabled={isDisabled}
+ />
<HStack className="w-full justify-end" spacing={2}>
<Button variant="secondary" onClick={disclosure.onClose}>
Cancel
@@ -1660,6 +2279,16 @@ function StepsListItem({
<DropdownMenuItem onClick={disclosure.onOpen}>
Edit
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ duplicateStepFetcher.submit(null, {
+ method: "post",
+ action: path.to.duplicateJobOperationStep(id)
+ })
+ }
+ >
+ Duplicate
+ </DropdownMenuItem>
<DropdownMenuItem
destructive
onClick={deleteModalDisclosure.onOpen}
@@ -2049,6 +2678,7 @@ function ParametersListItem({
function OperationForm({
item,
+ itemId,
isDisabled,
job,
locationId,
@@ -2060,6 +2690,7 @@ function OperationForm({
onSubmit
}: {
item: ItemWithData;
+ itemId: string;
isDisabled: boolean;
job?: Job;
locationId: string;
@@ -2099,6 +2730,9 @@ function OperationForm({
const machineDisclosure = useDisclosure();
const laborDisclosure = useDisclosure();
+ const assemblyDisclosure = useDisclosure();
+ const [assemblyWasChanged, setAssemblyWasChanged] = useState(false);
+ const assemblySyncDisclosure = useDisclosure();
const setupDisclosure = useDisclosure();
const costingDisclosure = useDisclosure();
const procedureDisclosure = useDisclosure();
@@ -2122,6 +2756,8 @@ function OperationForm({
overheadRate: number;
processId: string;
procedureId: string;
+ assemblyInstructionId: string;
+ inspectionDocumentId: string;
setupTime: number;
setupUnit: string;
setupUnitHint: string;
@@ -2137,7 +2773,9 @@ function OperationForm({
machineUnitHint: getUnitHint(item.data.machineUnit),
operationMinimumCost: item.data.operationMinimumCost ?? 0,
operationLeadTime: item.data.operationLeadTime ?? 0,
- operationType: item.data.operationType ?? "Inside",
+ operationType: item.data.operationType ?? "Process",
+ assemblyInstructionId: item.data.assemblyInstructionId ?? "",
+ inspectionDocumentId: item.data.inspectionDocumentId ?? "",
operationUnitCost: item.data.operationUnitCost ?? 0,
overheadRate: item.data.overheadRate ?? 0,
processId: item.data.processId ?? "",
@@ -2206,8 +2844,9 @@ function OperationForm({
return (acc += sp.leadTime ?? 0);
}, 0) / supplierProcesses.data.length
: p.operationLeadTime,
- operationType:
- process.data?.processType === "Outside" ? "Outside" : "Inside"
+ // processType and operationType share one enum — the process's type is the
+ // default operation type.
+ operationType: process.data?.processType ?? "Process"
}));
};
@@ -2287,47 +2926,49 @@ function OperationForm({
onProcessChange(value?.value as string);
}}
/>
- <Select
- name="operationOrder"
- label={t`Operation Order`}
- placeholder={t`Operation Order`}
- options={methodOperationOrders.map((o) => ({
- value: o,
- label: o
- }))}
- />
<SelectControlled
name="operationType"
label={t`Operation Type`}
+ termId="operation-type"
placeholder={t`Operation Type`}
options={operationTypes.map((o) => ({
value: o,
- label: o
+ label: (
+ <span className="flex items-center gap-2">
+ <OperationTypeIcon type={o} />
+ <span>{o}</span>
+ </span>
+ )
}))}
value={processData.operationType}
onChange={(value) => {
+ const next = (value?.value as string) ?? "Process";
setProcessData((d) => ({
...d,
-
- setupUnit: "Total Minutes",
- laborUnit: "Minutes/Piece",
- machineUnit: "Minutes/Piece",
- operationType: value?.value as string
+ operationType: next,
+ // Each type has exactly one instruction source — clear the ones
+ // that no longer apply (the upsert normalizes server-side too).
+ ...(next !== "Process" ? { procedureId: "" } : {}),
+ ...(next !== "Assembly" ? { assemblyInstructionId: "" } : {}),
+ ...(next !== "Inspection" ? { inspectionDocumentId: "" } : {}),
+ // Machine only applies to Process operations.
+ ...(next !== "Process" ? { machineTime: 0 } : {}),
+ // Crossing the in-house <-> Outside Processing boundary changes the
+ // meaningful time units; reset to defaults. Switching between in-house
+ // types keeps whatever units the user picked.
+ ...((next === "Outside Processing") !==
+ (d.operationType === "Outside Processing")
+ ? {
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece"
+ }
+ : {})
}));
}}
/>
- <InputControlled
- name="description"
- label={t`Description`}
- value={processData.description}
- onChange={(newValue) => {
- setProcessData((d) => ({ ...d, description: newValue }));
- }}
- className="col-span-2"
- />
-
- {processData.operationType === "Outside" ? (
+ {processData.operationType === "Outside Processing" ? (
<>
<SupplierProcess
name="operationSupplierProcessId"
@@ -2401,9 +3042,29 @@ function OperationForm({
}}
/>
)}
+
+ <InputControlled
+ name="description"
+ label={t`Description`}
+ value={processData.description}
+ onChange={(newValue) => {
+ setProcessData((d) => ({ ...d, description: newValue }));
+ }}
+ className="col-span-2"
+ />
+
+ <Select
+ name="operationOrder"
+ label={t`Operation Order`}
+ placeholder={t`Operation Order`}
+ options={methodOperationOrders.map((o) => ({
+ value: o,
+ label: o
+ }))}
+ />
</div>
- {processData.operationType === "Inside" && (
+ {processData.operationType !== "Outside Processing" && (
<>
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -2569,89 +3230,91 @@ function OperationForm({
</div>
</div>
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={machineDisclosure.onToggle}
- >
- <HStack>
- <TimeTypeIcon type="Machine" />
- <Label>
- <Trans>Machine</Trans>
- </Label>
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={machineDisclosure.onToggle}
+ >
+ <HStack>
+ <TimeTypeIcon type="Machine" />
+ <Label>
+ <Trans>Machine</Trans>
+ </Label>
+ </HStack>
+ <HStack>
+ {(processData.machineTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
+ {processData.machineTime} {processData.machineUnit}
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ machineDisclosure.isOpen
+ ? t`Collapse Machine`
+ : t`Expand Machine`
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ machineDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ machineDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- <HStack>
- {(processData.machineTime ?? 0) > 0 && (
- <Badge variant="secondary">
- <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
- {processData.machineTime} {processData.machineUnit}
- </Badge>
- )}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- machineDisclosure.isOpen
- ? t`Collapse Machine`
- : t`Expand Machine`
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ machineDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="machineHint"
+ label={t`Machine`}
+ value={processData.machineUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnitHint: hint,
+ machineUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
+ }));
+ }}
+ />
+ <NumberControlled
+ name="machineTime"
+ label={t`Machine Time`}
+ isOptional={false}
+ minValue={0}
+ value={processData.machineTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineTime: newValue
+ }))
}
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- machineDisclosure.onToggle();
+ />
+ <StandardFactor
+ name="machineUnit"
+ label={t`Machine Unit`}
+ isOptional={false}
+ hint={processData.machineUnitHint}
+ value={processData.machineUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnit: newValue?.value ?? "Total Minutes"
+ }));
}}
- className={`transition-transform ${
- machineDisclosure.isOpen ? "rotate-90" : ""
- }`}
/>
- </HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- machineDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <UnitHint
- name="machineHint"
- label={t`Machine`}
- value={processData.machineUnitHint}
- onChange={(hint) => {
- setProcessData((d) => ({
- ...d,
- machineUnitHint: hint,
- machineUnit:
- hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
- }));
- }}
- />
- <NumberControlled
- name="machineTime"
- label={t`Machine Time`}
- isOptional={false}
- minValue={0}
- value={processData.machineTime}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- machineTime: newValue
- }))
- }
- />
- <StandardFactor
- name="machineUnit"
- label={t`Machine Unit`}
- isOptional={false}
- hint={processData.machineUnitHint}
- value={processData.machineUnit}
- onChange={(newValue) => {
- setProcessData((d) => ({
- ...d,
- machineUnit: newValue?.value ?? "Total Minutes"
- }));
- }}
- />
+ </div>
</div>
- </div>
+ )}
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -2703,22 +3366,24 @@ function OperationForm({
}))
}
/>
- <NumberControlled
- name="machineRate"
- label={t`Machine Rate`}
- minValue={0}
- value={processData.machineRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- machineRate: newValue
- }))
- }
- />
+ {processData.operationType === "Process" && (
+ <NumberControlled
+ name="machineRate"
+ label={t`Machine Rate`}
+ minValue={0}
+ value={processData.machineRate}
+ formatOptions={{
+ style: "currency",
+ currency: baseCurrency
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineRate: newValue
+ }))
+ }
+ />
+ )}
<NumberControlled
name="overheadRate"
label={t`Overhead Rate`}
@@ -2738,89 +3403,221 @@ function OperationForm({
</div>
</div>
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={procedureDisclosure.onToggle}
- >
- <HStack>
- <LuListChecks />
- <Label>Procedure</Label>
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuListChecks />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuListChecks className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- <HStack>
- {processData.procedureId && (
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label={t`Procedure`}
+ processId={processData.processId}
+ value={processData.procedureId}
+ onChange={(value) => {
+ if (value && value.value !== item.data.procedureId) {
+ setProcedureWasChanged(true);
+ }
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string
+ }));
+ }}
+ />
+ {!temporaryItems[item.id] && processData.procedureId && (
+ <div className="flex flex-col gap-2 w-auto">
+ {procedureWasChanged && (
+ <span className="text-sm text-muted-foreground">
+ The procedure was changed, but not synced to the
+ operation.
+ </span>
+ )}
+ <div>
+ <Button
+ variant="secondary"
+ rightIcon={<LuRefreshCcw />}
+ onClick={procedureSyncDisclosure.onOpen}
+ >
+ Sync Procedure
+ </Button>
+ {procedureSyncDisclosure.isOpen && (
+ <ProcedureSyncModal
+ operationId={item.id}
+ procedureId={processData.procedureId}
+ onClose={procedureSyncDisclosure.onClose}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {processData.operationType === "Assembly" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={assemblyDisclosure.onToggle}
+ >
+ <HStack>
+ <OperationTypeIcon type="Assembly" />
+ <Label>Assembly Instruction</Label>
+ </HStack>
+ <HStack>
+ {processData.assemblyInstructionId && (
+ <Badge variant="secondary">
+ <OperationTypeIcon
+ type="Assembly"
+ className="h-3 w-3 mr-1"
+ />
+ Assembly Instruction
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ assemblyDisclosure.isOpen
+ ? "Collapse Assembly Instruction"
+ : "Expand Assembly Instruction"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ assemblyDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ assemblyDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ assemblyDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <AssemblyInstruction
+ name="assemblyInstructionId"
+ label={t`Assembly Instruction`}
+ itemId={itemId}
+ value={processData.assemblyInstructionId}
+ onChange={(value) => {
+ if (
+ value &&
+ value.value !== item.data.assemblyInstructionId
+ ) {
+ setAssemblyWasChanged(true);
+ }
+ setProcessData((d) => ({
+ ...d,
+ assemblyInstructionId: value?.value as string
+ }));
+ }}
+ />
+ {!temporaryItems[item.id] &&
+ processData.assemblyInstructionId && (
+ <div className="flex flex-col gap-2 w-auto">
+ {assemblyWasChanged && (
+ <span className="text-sm text-muted-foreground">
+ The assembly instruction was changed, but its steps
+ were not synced to the operation.
+ </span>
+ )}
+ <div>
+ <Button
+ variant="secondary"
+ rightIcon={<LuRefreshCcw />}
+ onClick={assemblySyncDisclosure.onOpen}
+ >
+ Sync Assembly Steps
+ </Button>
+ {assemblySyncDisclosure.isOpen && (
+ <AssemblyStepsSyncModal
+ operationId={item.id}
+ assemblyInstructionId={
+ processData.assemblyInstructionId
+ }
+ onClose={assemblySyncDisclosure.onClose}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {processData.operationType === "Inspection" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <OperationTypeIcon type="Inspection" />
+ <Label>Inspection Plan</Label>
+ </HStack>
+ {processData.inspectionDocumentId && (
<Badge variant="secondary">
- <LuListChecks className="h-3 w-3 mr-1" />
- Procedure
+ <OperationTypeIcon
+ type="Inspection"
+ className="h-3 w-3 mr-1"
+ />
+ Inspection Plan
</Badge>
)}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- procedureDisclosure.isOpen
- ? "Collapse Procedure"
- : "Expand Procedure"
- }
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- procedureDisclosure.onToggle();
+ </HStack>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4">
+ <InspectionDocument
+ name="inspectionDocumentId"
+ label={t`Inspection Plan`}
+ isOptional={false}
+ itemId={itemId}
+ value={processData.inspectionDocumentId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ inspectionDocumentId: value?.value as string
+ }));
}}
- className={`transition-transform ${
- procedureDisclosure.isOpen ? "rotate-90" : ""
- }`}
/>
- </HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
- procedureDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <Procedure
- name="procedureId"
- label={t`Procedure`}
- processId={processData.processId}
- value={processData.procedureId}
- onChange={(value) => {
- if (value && value.value !== item.data.procedureId) {
- setProcedureWasChanged(true);
- }
- setProcessData((d) => ({
- ...d,
- procedureId: value?.value as string
- }));
- }}
- />
- {!temporaryItems[item.id] && processData.procedureId && (
- <div className="flex flex-col gap-2 w-auto">
- {procedureWasChanged && (
- <span className="text-sm text-muted-foreground">
- The procedure was changed, but not synced to the
- operation.
- </span>
- )}
- <div>
- <Button
- variant="secondary"
- rightIcon={<LuRefreshCcw />}
- onClick={procedureSyncDisclosure.onOpen}
- >
- Sync Procedure
- </Button>
- {procedureSyncDisclosure.isOpen && (
- <ProcedureSyncModal
- operationId={item.id}
- procedureId={processData.procedureId}
- onClose={procedureSyncDisclosure.onClose}
- />
- )}
- </div>
- </div>
- )}
+ </div>
</div>
- </div>
+ )}
</>
)}
<motion.div
@@ -2916,6 +3713,77 @@ function ProcedureSyncModal({
);
}
+function AssemblyStepsSyncModal({
+ operationId,
+ assemblyInstructionId,
+ onClose
+}: {
+ operationId: string;
+ assemblyInstructionId: string;
+ onClose: () => void;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ onClose();
+ }
+ }, [fetcher.data?.success, onClose]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ validator={syncAssemblyToBopValidator}
+ action={path.to.assemblySyncBop(assemblyInstructionId)}
+ method="post"
+ fetcher={fetcher}
+ defaultValues={{
+ operationId
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Are you sure?</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody className="py-4">
+ <Hidden name="operationId" />
+ <Alert variant="warning">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>
+ <Trans>Potential Data Loss</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ Syncing updates the operation's steps from the assembly
+ instruction. Steps previously synced from an instruction are
+ updated or removed to match; hand-authored steps are kept.
+ </AlertDescription>
+ </Alert>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Submit
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Sync
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
+
type ProductionEventActivityProps = {
item: Database["public"]["Tables"]["productionEvent"]["Row"];
};
@@ -3024,6 +3892,9 @@ function ToolsListItem({
<Tool name="toolId" label={t`Tool`} autoFocus />
<Number name="quantity" label={t`Quantity`} />
</div>
+
+ {/* Tool↔step assignment lives on the step editor now (not here). */}
+
<HStack className="w-full justify-end" spacing={2}>
<Button variant="secondary" onClick={disclosure.onClose}>
Cancel
@@ -3157,6 +4028,9 @@ function ToolsForm({
<Number name="quantity" label={t`Quantity`} />
</div>
+ {/* Tool↔step assignment lives on the step editor now, not here — a tool added
+ from this form starts operation-level (shown on every step in the MES). */}
+
<Submit
leftIcon={<LuCirclePlus />}
isDisabled={isDisabled || fetcher.state !== "idle"}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
index 845dbe89d6..cf9749a7d3 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
@@ -261,7 +261,7 @@ const JobEstimatesVsActuals = ({
let totalScrap = 0;
operations.forEach((op) => {
- if (op.operationType !== "Outside") {
+ if (op.operationType !== "Outside Processing") {
const est = getEstimatedTime(op);
const act = getActualTime(op);
totalEstimated += est.total;
@@ -349,7 +349,8 @@ const JobEstimatesVsActuals = ({
const actual = getActualTime(operation);
const notes = getJobOperationNotes(operation);
- const isOutside = operation.operationType === "Outside";
+ const isOutside =
+ operation.operationType === "Outside Processing";
if (isOutside) return null;
return (
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index 82bcc8827d..70433041f0 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -546,7 +546,9 @@ export function JobStartModal({
// Check for existing purchase order lines for outside operations
const outsideOperations =
- operations.data?.filter((op) => op.operationType === "Outside") || [];
+ operations.data?.filter(
+ (op) => op.operationType === "Outside Processing"
+ ) || [];
const existingPurchaseOrderLines =
outsideOperations.length > 0
? await carbon
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index 37353f4642..00eae6c41a 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -1,4 +1,5 @@
import { useLingui } from "@lingui/react/macro";
+import { IoBalloonOutline } from "react-icons/io5";
import {
LuChartLine,
LuCirclePlay,
@@ -64,6 +65,12 @@ export default function useProductionSubmodules() {
icon: <LuStepForward />,
role: "employee"
},
+ {
+ name: t`Inspection Plans`,
+ to: path.to.inspectionDocuments,
+ icon: <IoBalloonOutline />,
+ permission: "quality"
+ },
{
name: t`Procedures`,
to: path.to.procedures,
@@ -89,6 +96,8 @@ export default function useProductionSubmodules() {
const isRouteVisible = (route: AuthenticatedRouteGroup["routes"][number]) => {
if (route.role && !permissions.is(route.role)) return false;
+ if (route.permission && !permissions.can("view", route.permission))
+ return false;
if (!isInternal && internalOnlyRoutes.has(route.to)) return false;
return true;
};
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 4e84d8a769..603d1d230d 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -133,7 +133,7 @@ export async function duplicatePurchaseOrder(
client
.from("purchaseOrderLine")
.select(
- "purchaseOrderLineType, itemId, assetId, description, purchaseQuantity, supplierUnitPrice, inventoryUnitOfMeasureCode, purchaseUnitOfMeasureCode, locationId, storageUnitId, setupPrice, requiresInspection, customFields, conversionFactor, tags, internalNotes, externalNotes, exchangeRate, supplierShippingCost, modelUploadId, supplierTaxAmount, jobId, jobOperationId, promisedDate, requiredDate, accountId, costCenterId, ownerId, sortOrder, supplierPartId"
+ "purchaseOrderLineType, itemId, assetId, description, purchaseQuantity, supplierUnitPrice, inventoryUnitOfMeasureCode, purchaseUnitOfMeasureCode, locationId, storageUnitId, setupPrice, customFields, conversionFactor, tags, internalNotes, externalNotes, exchangeRate, supplierShippingCost, modelUploadId, supplierTaxAmount, jobId, jobOperationId, promisedDate, requiredDate, accountId, costCenterId, ownerId, sortOrder, supplierPartId"
)
.eq("purchaseOrderId", sourcePurchaseOrderId)
]);
diff --git a/apps/erp/app/modules/quality/AGENTS.md b/apps/erp/app/modules/quality/AGENTS.md
index f4cdd90a01..c086b14657 100644
--- a/apps/erp/app/modules/quality/AGENTS.md
+++ b/apps/erp/app/modules/quality/AGENTS.md
@@ -1,13 +1,13 @@
# Quality Module
-Non-conformances (issues/NCRs), corrective/preventive actions (CAPAs), gauge management and calibration, quality documents, inspection documents with balloon annotations, inbound inspections with AQL sampling plans, and risk registers.
+Non-conformances (issues/NCRs), corrective/preventive actions (CAPAs), gauge management and calibration, quality documents, inspection documents with balloon annotations, inspections (source-generic: receipts and job operations) with AQL sampling plans, and risk registers.
## Key Domain Concepts
-- **Issue (NCR)** — non-conformance record. Statuses: Registered → In Progress → Closed. `isIssueLocked(status)` returns true for Closed. Has 10+ association types (items, customers, suppliers, job operations, PO/SO lines, shipment/receipt lines, tracked entities, inbound inspections).
+- **Issue (NCR)** — non-conformance record. Statuses: Registered → In Progress → Closed. `isIssueLocked(status)` returns true for Closed. Has 10+ association types (items, customers, suppliers, job operations, PO/SO lines, shipment/receipt lines, tracked entities, inspections).
- **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). Used for FAI and in-process inspection. MUST use `saveInspectionDocumentAtomic` RPC for atomic saves.
-- **Inbound Inspection** — lot-level inspection triggered on receipt for items with `requiresInspection = true`. Uses AQL-based sampling plans (ANSI Z1.4 / ISO 2859-1). Tracked entities post as `On Hold` until disposition.
+- **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** — 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).
- **Risk Register** — risks and opportunities tracked by source (Customer, Supplier, Item, Job, etc.). Severity and likelihood are independent 1–5 ratings with no computed score.
@@ -47,10 +47,11 @@ pnpm --filter @carbon/erp test
| `nonConformanceRequiredAction` | Actions required before closure (with `systemType`) |
| `nonConformanceActionTask` / `nonConformanceApprovalTask` | Workflow task instances |
| `nonConformanceItem` | Issue-to-item junction with `disposition` |
-| `nonConformanceCustomer` / `...Supplier` / `...JobOperation` / `...PurchaseOrderLine` / `...ReceiptLine` / `...ShipmentLine` / `...TrackedEntity` / `...InboundInspection` | Association tables (10+ types) |
+| `nonConformanceCustomer` / `...Supplier` / `...JobOperation` / `...PurchaseOrderLine` / `...ReceiptLine` / `...ShipmentLine` / `...TrackedEntity` / `...Inspection` | Association tables (10+ types) |
| `inspectionDocument` | PDF drawing with balloon overlay |
-| `inboundInspection` / `inboundInspectionSample` | Lot-level receipt inspection with sampling |
-| `itemSamplingPlan` | AQL sampling plan per item |
+| `inspection` / `inspectionSample` | Source-generic inspection lots with sampling; live `inspectionDocumentId` + `sourceDocument*` columns |
+| `inspectionSamplingPlan` / `inspectionMeasurement` | Per-inspection resolved feature plans (n/Ac/Re) and per sample × feature readings |
+| `itemInspectionDocumentAssignment` | Item × usage slot → inspection document (v1 usage: `Receipt`) |
| `gauge` / `gaugeCalibrationRecord` / `gaugeType` | Measurement instrument tracking |
| `qualityDocument` / `qualityDocumentStep` | Versioned SOPs with ordered steps |
| `riskRegister` / `riskRegisters` (view) | Risk/opportunity tracking by source |
@@ -61,13 +62,15 @@ pnpm --filter @carbon/erp test
- `getIssueAssociations` / `getIssueItems` / `getIssueReviewers` — NCR details and associations
- `getIssueWorkflow` / `getIssueActionTasks` / `getIssueApprovalTasks` — workflow state
- `updateIssueStatus` / `updateIssueTaskStatus` — status transitions
-- `getInspectionDocument` / `getBalloons` / `getInspectionFeatures` / `getInspectionPlan` — drawing inspection
-- `getInboundInspection` / `getInboundInspections` / `getInboundInspectionLotTrackedEntities` — receipt inspections
+- `getInspectionDocument` / `getBalloons` / `getInspectionFeatures` / `getInspectionPlan` — drawing-inspection reads; NOTE these live in `production.service.ts`, not this module
+- `getInspection` / `getInspections` (status + source filters) / `getInspectionTrackedEntities` — inspections
+- `getInspectionSamplingPlans` / `getInspectionMeasurements` — per-inspection feature plans and grid readings
+- `getItemInspectionDocumentAssignments` / `upsertItemInspectionDocumentAssignment` — Receipt-usage document assignment
+- `upsertInspectionMeasurement` / `reconcileInspectionSamplingPlans` / `changeInspectionDocument` / `valuateMeasurement` (quality.server.ts) — measurement recording, lazy plan resolution, document swap, pure valuation. The transactional engine lives in `@carbon/database/quality` (shared with the MES inspection routes); quality.server.ts is thin wrappers currying the ERP Kysely singleton
- `getGauge` / `getGauges` / `getGaugeCalibrationRecords` — gauge management
- `getRisk` / `getRisks` / `upsertRisk` / `updateRiskStatus` — risk register
- `getQualityDocument` / `getQualityDocumentSteps` — versioned SOPs
- `getQualityActions` — corrective/preventive action reads
-- `upsertItemSamplingPlan` — per-item AQL sampling plan configuration
## Key Exports
@@ -83,10 +86,10 @@ import { inspectionDocumentValidator, riskRegisterValidator } from "~/modules/qu
- **production** — job operations can be NCR associations; scrap reasons shared with production
- **purchasing** — PO lines and receipt lines can be NCR associations; supplier NCRs
- **sales** — SO lines and shipment lines can be NCR associations; customer NCRs
-- **items** — items linked to NCRs via `nonConformanceItem`; `requiresInspection` flag; inspection documents reference parts
+- **items** — items linked to NCRs via `nonConformanceItem`; inbound inspection driven by the item's Receipt-usage inspection-document assignment; inspection documents reference parts
## Rules References
- `.claude/rules/issue-module.md` — NCR status lifecycle, workflow tasks, associations, and route structure
- `.claude/rules/risk-register-module.md` — risk register schema, enums, and entity integration
-- `.claude/rules/inbound-inspection-system.md` — receipt inspection flow, sampling engine, and disposition
+- `.claude/rules/inspection-system.md` — inspection execution flow, sampling engine, and disposition
diff --git a/apps/erp/app/modules/quality/index.ts b/apps/erp/app/modules/quality/index.ts
index b860545a03..81feefa273 100644
--- a/apps/erp/app/modules/quality/index.ts
+++ b/apps/erp/app/modules/quality/index.ts
@@ -1,4 +1,3 @@
-export * from "./inspectionBalloonAnalyze";
export * from "./quality.models";
export * from "./quality.service";
export * from "./types";
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.ts
index 91e4c2d338..e315efea7f 100644
--- a/apps/erp/app/modules/quality/quality-disposition.server.ts
+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts
@@ -1,6 +1,6 @@
import type { Database } from "@carbon/database";
import type { KyselyTx } from "@carbon/database/client";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
import { getDatabaseClient } from "~/services/database.server";
import { isIssueLocked } from "./quality.models";
@@ -453,7 +453,48 @@ export async function splitIssueItem(args: {
.orderBy("te.quantity", "asc")
.execute();
- if (links.length === 0) throw new Error("No linked entities to split");
+ // Non-tracked row: no entities to move, so split is a pure quantity split
+ // (e.g. scrap N, use-as-is the rest). Create a new Pending row for the
+ // split-off quantity and shrink the original — no entity subdivision.
+ if (links.length === 0) {
+ const current = Number(item.quantity ?? 0);
+ const splitQty =
+ typeof splitQuantity === "number" ? splitQuantity : NaN;
+ if (!(splitQty > 0)) {
+ throw new Error("Missing split parameters");
+ }
+ if (splitQty >= current) {
+ throw new Error(
+ `Split quantity (${splitQty}) must be less than the current quantity (${current})`
+ );
+ }
+
+ const newRow = await trx
+ .insertInto("nonConformanceItem")
+ .values({
+ nonConformanceId: item.nonConformanceId,
+ itemId: item.itemId,
+ quantity: splitQty,
+ disposition: "Pending",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: current - splitQty,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ return { id: newRow.id };
+ }
// entityAssignments are whole-lot picks from the multi-entity checkbox UI;
// splitQuantity fills greedily from the smallest lots, subdividing the
@@ -590,11 +631,13 @@ export async function splitIssueItem(args: {
// closeIssue
// -------------------------------------------------------------
// Validates disposition plan (qty sums, no Pending rows, no Consumed entities),
-// then for each row with linked entities:
-// - insert trackedActivity + trackedActivityInput
-// - flip trackedEntity status (Use As Is / Rework → Available;
-// Scrap / Return to Supplier → Rejected and write a Negative Adjmt. ledger)
-// Finally sets nonConformance.status = Closed.
+// posts inventory value movements (Scrap/Return write-offs + non-tracked restores)
+// through the post-nonconformance edge function (itemLedger + cost relief + GL,
+// idempotent per NCR), THEN in one transaction re-validates under a row lock,
+// writes disposition genealogy (trackedActivity + input), flips trackedEntity
+// status (Use As Is / Rework → Available; Scrap / Return to Supplier → Rejected),
+// and sets nonConformance.status = Closed. The value posting runs first so a GL
+// failure aborts the close; the txn owns only status/genealogy.
type DispositionLink = {
id: string;
@@ -663,7 +706,7 @@ export async function closeIssue(
const blockers: IssueClosureBlocker[] = [];
for (const row of plan) {
- if (row.links.length === 0) continue;
+ // Every row must be dispositioned before closing, tracked or not.
if (!row.disposition || row.disposition === "Pending") {
blockers.push({
nonConformanceItemId: row.id,
@@ -671,6 +714,9 @@ export async function closeIssue(
});
continue;
}
+ // Non-tracked rows carry no entity links — there is no per-entity quantity
+ // sum or status to reconcile, so the disposition alone is enough.
+ if (row.links.length === 0) continue;
const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
if (Math.abs(sum - row.quantity) > 1e-6) {
blockers.push({
@@ -700,11 +746,134 @@ export async function closeIssue(
);
}
+ // Load the issue + disposition origin up front — needed to build the inventory
+ // write-off movements and to short-circuit an already-closed NCR.
+ const issueResult = await client
+ .from("nonConformance")
+ .select("id, nonConformanceId, status, locationId")
+ .eq("id", nonConformanceId)
+ .eq("companyId", companyId)
+ .single();
+ if (issueResult.error || !issueResult.data) {
+ return errResult("Issue not found");
+ }
+ if (issueResult.data.status === "Closed") {
+ return { data: { id: issueResult.data.id }, error: null };
+ }
+ const readableNc = issueResult.data.nonConformanceId ?? nonConformanceId;
+ const locationId = issueResult.data.locationId;
+
+ // Non-tracked origin: an inspection-rejected Inventory lot was already written
+ // off at reject (so Use As Is / Rework restores value); a MES/manual non-tracked
+ // scrap must be written off now. Detected via the NCR's inspection link (only
+ // the reject route creates one).
+ const linklessRows = plan.filter((r) => r.links.length === 0);
+ const inventoryItemIds = new Set<string>();
+ let inspectionOriginated = false;
+ if (linklessRows.length > 0) {
+ const linklessItemIds = [...new Set(linklessRows.map((r) => r.itemId))];
+ const [trackingRes, inspectionRes] = await Promise.all([
+ client
+ .from("item")
+ .select("id, itemTrackingType")
+ .in("id", linklessItemIds)
+ .eq("companyId", companyId),
+ client
+ .from("nonConformanceInspection")
+ .select("id")
+ .eq("nonConformanceId", nonConformanceId)
+ .eq("companyId", companyId)
+ .limit(1)
+ ]);
+ for (const it of trackingRes.data ?? []) {
+ if (it.itemTrackingType === "Inventory") inventoryItemIds.add(it.id);
+ }
+ inspectionOriginated = (inspectionRes.data?.length ?? 0) > 0;
+ }
+
+ // Build the inventory value movements: tracked Scrap/Return → one −qty per
+ // linked entity; non-tracked Inventory → −qty write-off (MES/manual scrap) or
+ // +qty restore (inspection-kept). Use As Is / Rework on tracked, and any
+ // Non-Inventory row, move no value.
+ const movements: {
+ itemId: string;
+ locationId: string | null;
+ trackedEntityId: string | null;
+ quantity: number;
+ comment: string;
+ }[] = [];
+ for (const row of plan) {
+ const isScrap =
+ row.disposition === "Scrap" || row.disposition === "Return to Supplier";
+ const isKeep =
+ row.disposition === "Use As Is" || row.disposition === "Rework";
+ if (row.links.length > 0) {
+ if (isScrap) {
+ const suffix =
+ row.disposition === "Scrap" ? "scrap" : "return to supplier";
+ for (const link of row.links) {
+ movements.push({
+ itemId: row.itemId,
+ locationId,
+ trackedEntityId: link.trackedEntityId,
+ quantity: -link.quantity,
+ comment: `NC ${readableNc} ${suffix}`
+ });
+ }
+ }
+ continue;
+ }
+ if (!inventoryItemIds.has(row.itemId)) continue; // Non-Inventory: no ledger
+ if (isScrap && !inspectionOriginated) {
+ movements.push({
+ itemId: row.itemId,
+ locationId,
+ trackedEntityId: null,
+ quantity: -row.quantity,
+ comment: `NC ${readableNc} scrap`
+ });
+ } else if (isKeep && inspectionOriginated) {
+ movements.push({
+ itemId: row.itemId,
+ locationId,
+ trackedEntityId: null,
+ quantity: row.quantity,
+ comment: `NC ${readableNc} ${
+ row.disposition === "Rework" ? "rework" : "use as is"
+ } — restore on-hand`
+ });
+ }
+ }
+
+ // Post the inventory value movements (itemLedger + cost relief + GL) through
+ // the edge function BEFORE flipping statuses / closing. Idempotent per NCR, so
+ // a retry after a later failure is safe; a posting failure aborts the close.
+ if (movements.length > 0) {
+ const post = await client.functions.invoke("post-nonconformance", {
+ body: {
+ companyId,
+ userId,
+ documentType: "Non-Conformance",
+ documentId: nonConformanceId,
+ description: `NC ${readableNc} disposition`,
+ movements
+ },
+ region: FunctionRegion.UsEast1
+ });
+ if (post.error) {
+ return errResult(
+ post.error instanceof Error
+ ? post.error.message
+ : "Failed to post disposition to the ledger"
+ );
+ }
+ }
+
try {
const result = await db.transaction().execute(async (trx) => {
const issue = await trx
.selectFrom("nonConformance")
- .select(["id", "nonConformanceId", "status", "locationId"])
+ .select(["id", "status"])
.where("id", "=", nonConformanceId)
.where("companyId", "=", companyId)
.executeTakeFirst();
@@ -713,8 +882,6 @@ export async function closeIssue(
const nowIso = new Date().toISOString();
const today = nowIso.slice(0, 10);
- const readableNc = issue.nonConformanceId ?? nonConformanceId;
- const locationId = issue.locationId;
// The preflight plan above was read outside this transaction and can be
// stale (a concurrent split/move changes rows and link quantities). Re-read
@@ -770,10 +937,10 @@ export async function closeIssue(
}));
for (const row of freshPlan) {
- if (row.links.length === 0) continue;
if (!row.disposition || row.disposition === "Pending") {
throw new Error("Disposition changed while closing; please retry.");
}
+ if (row.links.length === 0) continue;
const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
if (Math.abs(sum - row.quantity) > 1e-6) {
throw new Error("Quantities changed while closing; please retry.");
@@ -790,6 +957,10 @@ export async function closeIssue(
}
}
+ // Inventory value movements (write-offs / restores) were already posted by
+ // post-nonconformance above. Here we only write disposition genealogy and
+ // flip tracked-entity statuses; non-tracked rows have no entities, so they
+ // need nothing further.
for (const row of freshPlan) {
if (row.links.length === 0) continue;
@@ -843,27 +1014,6 @@ export async function closeIssue(
row.disposition === "Scrap" ||
row.disposition === "Return to Supplier"
) {
- const commentSuffix =
- row.disposition === "Scrap" ? "scrap" : "return to supplier";
-
- await trx
- .insertInto("itemLedger")
- .values(
- row.links.map((link) => ({
- itemId: row.itemId,
- locationId,
- entryType: "Negative Adjmt." as const,
- documentType: "Non-Conformance" as const,
- documentId: nonConformanceId,
- quantity: -link.quantity,
- trackedEntityId: link.trackedEntityId,
- companyId,
- createdBy: userId,
- comment: `NC ${readableNc} ${commentSuffix}`
- }))
- )
- .execute();
-
const idsToFlip = row.links
.filter((l) => l.trackedEntityStatus !== "Rejected")
.map((l) => l.trackedEntityId);
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index 90c1b1c3f2..89678964d0 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -78,7 +78,7 @@ export const nonConformanceAssociationType = [
"shipmentLines",
"receiptLines",
"trackedEntities",
- "inboundInspections"
+ "inspections"
] as const;
export const qualityDocumentStatus = ["Draft", "Active", "Archived"] as const;
@@ -103,273 +103,6 @@ export const riskStatus = [
export const riskRegisterType = ["Risk", "Opportunity"] as const;
-export const inspectionDocumentValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: zfd.text(z.string().optional()),
- partId: z.string().min(1, { message: "Part is required" }),
- drawingNumber: zfd.text(z.string().optional()),
- pdfUrl: zfd.text(z.string().optional()),
- annotations: zfd.text(z.string().optional()),
- features: zfd.text(z.string().optional())
-});
-
-export const balloonFeatureValidator = z.object({
- id: zfd.text(z.string().optional()),
- inspectionDocumentId: z.string().min(1, { message: "Diagram is required" }),
- balloonNumber: zfd.numeric(z.number().min(1)),
- description: z.string().min(1, { message: "Description is required" }),
- nominalValue: zfd.numeric(z.number().optional()),
- tolerancePlus: zfd.numeric(z.number().optional()),
- toleranceMinus: zfd.numeric(z.number().optional()),
- unitOfMeasureCode: zfd.text(z.string().optional())
-});
-
-export const balloonCreateFromPayloadItemValidator = z.object({
- pageNumber: z.number(),
- regionX: z.number(),
- regionY: z.number(),
- regionWidth: z.number(),
- regionHeight: z.number(),
- label: z.string().min(1),
- xCoordinate: z.number(),
- yCoordinate: z.number(),
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- description: z.string().nullable().optional()
-});
-
-export const balloonUpdateItemValidator = z.object({
- id: z.string().min(1),
- pageNumber: z.number().optional(),
- regionX: z.number().optional(),
- regionY: z.number().optional(),
- regionWidth: z.number().optional(),
- regionHeight: z.number().optional(),
- label: z.string().optional(),
- xCoordinate: z.number().optional(),
- yCoordinate: z.number().optional(),
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- description: z.string().nullable().optional()
-});
-
-export const balloonDeleteValidator = z.object({
- ids: z.array(z.string().min(1))
-});
-
-const normalizedCoordinateValidator = z.number().min(0).max(1);
-const normalizedSizeValidator = z.number().gt(0).max(1);
-const pageNumberValidator = z.number().int().min(1);
-
-export const balloonAnchorCreateItemValidator = z
- .object({
- pageNumber: pageNumberValidator,
- regionX: normalizedCoordinateValidator,
- regionY: normalizedCoordinateValidator,
- regionWidth: normalizedSizeValidator,
- regionHeight: normalizedSizeValidator
- })
- .strict();
-
-export const balloonCreateItemWithOverlayValidator = z
- .object({
- pageNumber: pageNumberValidator,
- regionX: normalizedCoordinateValidator,
- regionY: normalizedCoordinateValidator,
- regionWidth: normalizedSizeValidator,
- regionHeight: normalizedSizeValidator,
- label: z.string().min(1),
- xCoordinate: normalizedCoordinateValidator,
- yCoordinate: normalizedCoordinateValidator,
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- description: z.string().nullable().optional(),
- type: z.enum(procedureStepType).optional(),
- data: z.record(z.unknown()).optional()
- })
- .strict();
-
-export const balloonCreateItemsValidator = z.array(
- z.union([
- balloonCreateItemWithOverlayValidator,
- balloonAnchorCreateItemValidator
- ])
-);
-
-export const balloonUpdateItemsValidator = z.array(
- balloonUpdateItemValidator.extend({
- pageNumber: pageNumberValidator.optional(),
- regionX: normalizedCoordinateValidator.optional(),
- regionY: normalizedCoordinateValidator.optional(),
- regionWidth: normalizedSizeValidator.optional(),
- regionHeight: normalizedSizeValidator.optional(),
- xCoordinate: normalizedCoordinateValidator.optional(),
- yCoordinate: normalizedCoordinateValidator.optional(),
- data: z.record(z.unknown()).optional()
- })
-);
-
-export const balloonDeleteIdsValidator = z.array(z.string().min(1));
-
-export const inspectionSaveFeatureCreateItemValidator = z
- .object({
- tempId: z.string().min(1),
- pageNumber: pageNumberValidator,
- label: z.string().min(1),
- description: z.string().nullable().optional(),
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- type: z.enum(procedureStepType).optional()
- })
- .strict();
-
-export const inspectionSaveFeatureUpdateItemValidator = z
- .object({
- id: z.string().min(1),
- pageNumber: pageNumberValidator.optional(),
- label: z.string().min(1).optional(),
- description: z.string().nullable().optional(),
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- type: z.enum(procedureStepType).optional()
- })
- .strict();
-
-export const inspectionSaveFeaturesPayloadValidator = z
- .object({
- create: z.array(inspectionSaveFeatureCreateItemValidator).default([]),
- update: z.array(inspectionSaveFeatureUpdateItemValidator).default([]),
- delete: z.array(z.string().min(1)).default([])
- })
- .strict();
-
-export const inspectionSaveBalloonGeometryCreateItemValidator = z
- .object({
- tempInspectionFeatureId: z.string().min(1).optional(),
- inspectionFeatureId: z.string().min(1).optional(),
- tempBalloonAnchorId: z.string().min(1).optional(),
- pageNumber: pageNumberValidator,
- regionX: normalizedCoordinateValidator,
- regionY: normalizedCoordinateValidator,
- regionWidth: normalizedSizeValidator,
- regionHeight: normalizedSizeValidator,
- xCoordinate: normalizedCoordinateValidator,
- yCoordinate: normalizedCoordinateValidator
- })
- .strict()
- .refine(
- (data) =>
- Boolean(data.tempInspectionFeatureId) ||
- Boolean(data.inspectionFeatureId),
- { message: "tempInspectionFeatureId or inspectionFeatureId is required" }
- );
-
-export const inspectionSaveBalloonGeometryUpdateItemValidator = z
- .object({
- id: z.string().min(1),
- pageNumber: pageNumberValidator.optional(),
- regionX: normalizedCoordinateValidator.optional(),
- regionY: normalizedCoordinateValidator.optional(),
- regionWidth: normalizedSizeValidator.optional(),
- regionHeight: normalizedSizeValidator.optional(),
- xCoordinate: normalizedCoordinateValidator.optional(),
- yCoordinate: normalizedCoordinateValidator.optional()
- })
- .strict();
-
-export const inspectionSaveBalloonsGeometryPayloadValidator = z
- .object({
- create: z
- .array(inspectionSaveBalloonGeometryCreateItemValidator)
- .default([]),
- update: z
- .array(inspectionSaveBalloonGeometryUpdateItemValidator)
- .default([]),
- delete: z.array(z.string().min(1)).default([])
- })
- .strict();
-
-/** @deprecated Legacy combined payload; use features + balloons geometry split. */
-export const inspectionSaveBalloonCreateItemValidator = z
- .object({
- tempBalloonAnchorId: z.string().min(1),
- label: z.string().min(1),
- xCoordinate: normalizedCoordinateValidator,
- yCoordinate: normalizedCoordinateValidator,
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- description: z.string().nullable().optional(),
- type: z.enum(procedureStepType).optional()
- })
- .strict();
-
-/** @deprecated Legacy combined payload. */
-export const inspectionSaveBalloonUpdateItemValidator = z
- .object({
- id: z.string().min(1),
- label: z.string().min(1).optional(),
- xCoordinate: normalizedCoordinateValidator.optional(),
- yCoordinate: normalizedCoordinateValidator.optional(),
- nominalValue: z.string().nullable().optional(),
- tolerancePlus: z.string().nullable().optional(),
- toleranceMinus: z.string().nullable().optional(),
- unit: z.string().nullable().optional(),
- description: z.string().nullable().optional(),
- type: z.enum(procedureStepType).optional()
- })
- .strict();
-
-/** @deprecated Legacy combined payload. */
-export const inspectionSaveBalloonsPayloadValidator = z
- .object({
- create: z.array(inspectionSaveBalloonCreateItemValidator).default([]),
- update: z.array(inspectionSaveBalloonUpdateItemValidator).default([]),
- delete: z.array(z.string().min(1)).default([])
- })
- .strict();
-
-export const inspectionSaveAnchorCreateItemValidator = z
- .object({
- tempId: z.string().min(1),
- pageNumber: pageNumberValidator,
- xCoordinate: normalizedCoordinateValidator,
- yCoordinate: normalizedCoordinateValidator,
- width: normalizedSizeValidator,
- height: normalizedSizeValidator
- })
- .strict();
-
-export const inspectionSaveAnchorUpdateItemValidator = z
- .object({
- id: z.string().min(1),
- pageNumber: pageNumberValidator.optional(),
- xCoordinate: normalizedCoordinateValidator.optional(),
- yCoordinate: normalizedCoordinateValidator.optional(),
- width: normalizedSizeValidator.optional(),
- height: normalizedSizeValidator.optional()
- })
- .strict();
-
-export const inspectionSaveAnchorsPayloadValidator = z
- .object({
- create: z.array(inspectionSaveAnchorCreateItemValidator).default([]),
- update: z.array(inspectionSaveAnchorUpdateItemValidator).default([]),
- delete: z.array(z.string().min(1)).default([])
- })
- .strict();
-
export const gaugeValidator = z.object({
id: zfd.text(z.string().optional()),
gaugeId: zfd.text(z.string().optional()),
@@ -439,14 +172,14 @@ export const issueAssociationValidator = z
.refine(
(data) => {
// For types other than items, customer, supplier, trackedEntity, or
- // inboundInspection, lineId is required
+ // inspection, lineId is required
if (
![
"items",
"customers",
"suppliers",
"trackedEntities",
- "inboundInspections"
+ "inspections"
].includes(data.type) &&
!data.lineId
) {
@@ -695,7 +428,7 @@ export const riskRegisterValidator = z.object({
type: z.enum(riskRegisterType)
});
-export const inboundInspectionStatus = [
+export const inspectionStatusType = [
"Pending",
"In Progress",
"Passed",
@@ -703,47 +436,13 @@ export const inboundInspectionStatus = [
"Partial"
] as const;
-export const inboundInspectionSampleStatus = [
+export const inspectionSampleStatusType = [
"Pending",
"Passed",
"Failed"
] as const;
-export const itemSamplingPlanValidator = z
- .object({
- itemId: z.string().min(1, { message: "Item is required" }),
- type: z.enum(samplingPlanTypes),
- sampleSize: zfd.numeric(z.number().int().positive().optional()),
- percentage: zfd.numeric(z.number().positive().max(100).optional()),
- aql: zfd.numeric(z.number().positive().optional()),
- inspectionLevel: z.enum(inspectionLevels).default("II"),
- severity: z.enum(inspectionSeverities).default("Normal")
- })
- .superRefine((value, ctx) => {
- if (value.type === "First" && !value.sampleSize) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["sampleSize"],
- message: "Sample size is required for 'First N' plans"
- });
- }
- if (value.type === "Percentage" && !value.percentage) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["percentage"],
- message: "Percentage is required for percentage plans"
- });
- }
- if (value.type === "AQL" && !value.aql) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["aql"],
- message: "AQL is required for AQL plans"
- });
- }
- });
-
-export const inboundInspectionValidator = z.object({
+export const inspectionValidator = z.object({
id: z.string().min(1, { message: "Id is required" }),
status: z.enum(["Passed", "Failed"], {
errorMap: () => ({ message: "Status is required" })
@@ -751,21 +450,52 @@ export const inboundInspectionValidator = z.object({
notes: zfd.text(z.string().optional())
});
-export const inboundInspectionSampleValidator = z.object({
+export const inspectionSampleValidator = z.object({
inspectionId: z.string().min(1, { message: "Inspection is required" }),
+ // Optional: update an existing sample in place (the grid's "Overall result"
+ // row re-toggles an anonymous non-serial column). Serial parts upsert by the
+ // tracked entity instead, so they don't need it.
+ sampleId: zfd.text(z.string().optional()),
// Optional: serial parts scan a discrete tracked entity; batch / inventory /
// non-inventory parts record pass/fail without one.
trackedEntityId: zfd.text(z.string().optional()),
- status: z.enum(["Passed", "Failed"], {
+ // "Pending" registers a sample without a verdict (identify-only scan when an
+ // inspection document drives per-feature measurements).
+ status: z.enum(["Pending", "Passed", "Failed"], {
errorMap: () => ({ message: "Status is required" })
}),
notes: zfd.text(z.string().optional())
});
-export const inboundInspectionDispositionValidator = z.object({
+export const inspectionDispositionValidator = z.object({
id: z.string().min(1, { message: "Id is required" }),
decision: z.enum(["Accept", "Reject", "Partial"], {
errorMap: () => ({ message: "Decision is required" })
}),
notes: zfd.text(z.string().optional())
});
+
+export const inspectionSourceDocuments = ["Receipt", "Job Operation"] as const;
+
+export const inspectionDocumentUsages = ["Receipt"] as const;
+
+export const itemInspectionDocumentAssignmentValidator = z.object({
+ itemId: z.string().min(1, { message: "Item is required" }),
+ usage: z.enum(inspectionDocumentUsages, {
+ errorMap: () => ({ message: "Usage is required" })
+ }),
+ // Empty clears the slot.
+ inspectionDocumentId: zfd.text(z.string().optional())
+});
+
+export const inspectionMeasurementValidator = z.object({
+ inspectionId: z.string().min(1, { message: "Inspection is required" }),
+ // Absent = create an anonymous sample (non-serial grid columns).
+ sampleId: zfd.text(z.string().optional()),
+ inspectionFeatureId: z.string().min(1, { message: "Feature is required" }),
+ // Numeric string for Measurement features; empty clears the reading.
+ value: zfd.text(z.string().optional()),
+ // Attribute (non-numeric) features toggle pass/fail instead of a value.
+ passed: zfd.text(z.enum(["true", "false"]).optional()),
+ notes: zfd.text(z.string().optional())
+});
diff --git a/apps/erp/app/modules/quality/quality.server.test.ts b/apps/erp/app/modules/quality/quality.server.test.ts
new file mode 100644
index 0000000000..202dbb3add
--- /dev/null
+++ b/apps/erp/app/modules/quality/quality.server.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { valuateMeasurement } from "./quality.server";
+
+const numericFeature = {
+ type: "Measurement",
+ nominalValue: "10",
+ tolerancePlus: "0.1",
+ toleranceMinus: "0.05"
+};
+
+describe("valuateMeasurement", () => {
+ it("passes an in-tolerance reading", () => {
+ expect(valuateMeasurement(numericFeature, 10.05)).toBe("Passed");
+ expect(valuateMeasurement(numericFeature, 9.95)).toBe("Passed");
+ });
+
+ it("fails an out-of-tolerance reading on either side", () => {
+ expect(valuateMeasurement(numericFeature, 10.11)).toBe("Failed");
+ expect(valuateMeasurement(numericFeature, 9.94)).toBe("Failed");
+ });
+
+ it("treats a cleared value as Pending", () => {
+ expect(valuateMeasurement(numericFeature, null)).toBe("Pending");
+ });
+
+ it("takes tolerance magnitudes regardless of sign and strips a leading plus", () => {
+ const feature = {
+ type: "Measurement",
+ nominalValue: "+10",
+ tolerancePlus: "+0.1",
+ toleranceMinus: "-0.05"
+ };
+ expect(valuateMeasurement(feature, 9.96)).toBe("Passed");
+ expect(valuateMeasurement(feature, 9.94)).toBe("Failed");
+ });
+
+ it("falls back to attribute valuation when the nominal does not parse", () => {
+ const gdtFeature = {
+ type: "Measurement",
+ nominalValue: "⌖ 0.2 A B C",
+ tolerancePlus: null,
+ toleranceMinus: null
+ };
+ expect(valuateMeasurement(gdtFeature, null, true)).toBe("Passed");
+ expect(valuateMeasurement(gdtFeature, null, false)).toBe("Failed");
+ expect(valuateMeasurement(gdtFeature, null, null)).toBe("Pending");
+ });
+
+ it("valuates non-Measurement features as attributes", () => {
+ const checkbox = {
+ type: "Checkbox",
+ nominalValue: null,
+ tolerancePlus: null,
+ toleranceMinus: null
+ };
+ expect(valuateMeasurement(checkbox, null, true)).toBe("Passed");
+ expect(valuateMeasurement(checkbox, null, false)).toBe("Failed");
+ expect(valuateMeasurement(checkbox, null)).toBe("Pending");
+ });
+});
diff --git a/apps/erp/app/modules/quality/quality.server.ts b/apps/erp/app/modules/quality/quality.server.ts
index 1bd74d9c57..c97c762e94 100644
--- a/apps/erp/app/modules/quality/quality.server.ts
+++ b/apps/erp/app/modules/quality/quality.server.ts
@@ -1,376 +1,65 @@
-import { sql } from "kysely";
+/**
+ * ERP bindings for the shared inspection execution engine
+ * (@carbon/database/quality). The engine moved there so the MES inspection
+ * routes can run the same transactional core; these wrappers keep the ERP
+ * call sites unchanged by currying in the ERP Kysely singleton.
+ */
+import * as engine from "@carbon/database/quality";
import type { z } from "zod";
import { getDatabaseClient } from "~/services/database.server";
import type {
- inboundInspectionDispositionValidator,
- inboundInspectionSampleValidator
+ inspectionDispositionValidator,
+ inspectionMeasurementValidator,
+ inspectionSampleValidator
} from "./quality.models";
-type Ok<T> = { data: T; error: null };
-type Err = { data: null; error: { message: string; blockers?: unknown } };
-export type Result<T> = Ok<T> | Err;
+export type { Result } from "@carbon/database/quality";
+export { errResult, valuateMeasurement } from "@carbon/database/quality";
-export function errResult(message: string, blockers?: unknown): Err {
- return { data: null, error: { message, ...(blockers ? { blockers } : {}) } };
-}
-
-// Mirrors the old in-service helper. Terminal states (Passed/Failed/Partial)
-// are owned by the disposition path, so the per-sample recompute only flips
-// between Pending and In Progress.
-function computeLotStatus(
- samples: { status: string }[]
-): "Pending" | "In Progress" {
- const inspected = samples.filter((s) => s.status !== "Pending").length;
- return inspected > 0 ? "In Progress" : "Pending";
-}
-
-// -------------------------------------------------------------
-// 1. upsertInboundInspectionSample
-// -------------------------------------------------------------
-// Writes that must stay consistent:
-// - inboundInspectionSample (insert or update)
-// - trackedEntity.status (flip to Available or Rejected)
-// - trackedActivity + trackedActivityInput + trackedActivityOutput
-// - inboundInspection.status (recompute if non-terminal)
-
-export async function upsertInboundInspectionSample(
- sample: z.infer<typeof inboundInspectionSampleValidator> & {
+export async function upsertInspectionSample(
+ sample: z.infer<typeof inspectionSampleValidator> & {
companyId: string;
inspectedBy: string;
}
-): Promise<Result<{ id: string }>> {
- const db = getDatabaseClient();
- const nowIso = new Date().toISOString();
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- const inspection = await trx
- .selectFrom("inboundInspection")
- .select(["id", "status", "receiptId"])
- .where("id", "=", sample.inspectionId)
- .where("companyId", "=", sample.companyId)
- .executeTakeFirst();
- if (!inspection) throw new Error("Inspection not found");
-
- // Serial parts carry a tracked entity that may only be sampled once, so we
- // upsert by it. Batch / inventory / non-inventory parts have no entity —
- // each recorded result is a fresh anonymous sample.
- const trackedEntityId = sample.trackedEntityId || null;
- const existing = trackedEntityId
- ? await trx
- .selectFrom("inboundInspectionSample")
- .select(["id"])
- .where("trackedEntityId", "=", trackedEntityId)
- .executeTakeFirst()
- : undefined;
-
- const samplePayload = {
- inboundInspectionId: sample.inspectionId,
- trackedEntityId,
- status: sample.status,
- notes: sample.notes ?? null,
- inspectedBy: sample.inspectedBy,
- inspectedAt: nowIso,
- companyId: sample.companyId
- };
-
- let sampleId: string;
- if (existing) {
- const updated = await trx
- .updateTable("inboundInspectionSample")
- .set({
- ...samplePayload,
- updatedBy: sample.inspectedBy,
- updatedAt: nowIso
- })
- .where("id", "=", existing.id)
- .returning(["id"])
- .executeTakeFirstOrThrow();
- sampleId = updated.id;
- } else {
- const inserted = await trx
- .insertInto("inboundInspectionSample")
- .values({ ...samplePayload, createdBy: sample.inspectedBy })
- .returning(["id"])
- .executeTakeFirstOrThrow();
- sampleId = inserted.id;
- }
-
- // Entity-level side effects only apply when a tracked entity is present
- // (serial parts). For anonymous samples the lot's disposition handles any
- // status changes.
- if (trackedEntityId) {
- const trackedEntityStatus =
- sample.status === "Passed" ? "Available" : "Rejected";
- await trx
- .updateTable("trackedEntity")
- .set({ status: trackedEntityStatus })
- .where("id", "=", trackedEntityId)
- .where("companyId", "=", sample.companyId)
- .execute();
-
- const activity = await trx
- .insertInto("trackedActivity")
- .values({
- type: "Inspect",
- sourceDocument: "Inbound Inspection",
- sourceDocumentId: sample.inspectionId,
- attributes: {
- Result: sample.status,
- Receipt: inspection.receiptId,
- Inspector: sample.inspectedBy,
- ...(sample.notes ? { Notes: sample.notes } : {})
- },
- companyId: sample.companyId,
- createdBy: sample.inspectedBy
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- await trx
- .insertInto("trackedActivityInput")
- .values({
- trackedActivityId: activity.id,
- trackedEntityId,
- quantity: 0,
- companyId: sample.companyId,
- createdBy: sample.inspectedBy
- })
- .execute();
- await trx
- .insertInto("trackedActivityOutput")
- .values({
- trackedActivityId: activity.id,
- trackedEntityId,
- quantity: 0,
- companyId: sample.companyId,
- createdBy: sample.inspectedBy
- })
- .execute();
- }
-
- const isTerminal =
- inspection.status === "Passed" ||
- inspection.status === "Failed" ||
- inspection.status === "Partial";
- if (!isTerminal) {
- const samples = await trx
- .selectFrom("inboundInspectionSample")
- .select(["status"])
- .where("inboundInspectionId", "=", sample.inspectionId)
- .execute();
- const nextStatus = computeLotStatus(samples);
- if (nextStatus !== inspection.status) {
- await trx
- .updateTable("inboundInspection")
- .set({
- status: nextStatus,
- updatedBy: sample.inspectedBy,
- updatedAt: nowIso
- })
- .where("id", "=", sample.inspectionId)
- .execute();
- }
- }
-
- return { id: sampleId };
- });
-
- return { data: result, error: null };
- } catch (err) {
- return errResult(
- err instanceof Error ? err.message : "Failed to save sample"
- );
- }
+) {
+ return engine.upsertInspectionSample(getDatabaseClient(), sample);
}
-// -------------------------------------------------------------
-// 2. dispositionInboundInspection
-// -------------------------------------------------------------
-// Writes:
-// - trackedEntity.status (bulk flip for Accept/Reject; nothing for Partial)
-// - inboundInspection (status, dispositionedBy/At, notes)
-// - inboundInspectionHistory (1 row for future plan auto-switching)
-
-export async function dispositionInboundInspection(
- args: z.infer<typeof inboundInspectionDispositionValidator> & {
+export async function dispositionInspection(
+ args: z.infer<typeof inspectionDispositionValidator> & {
companyId: string;
dispositionedBy: string;
- }
-): Promise<Result<{ id: string; status: string }>> {
- const db = getDatabaseClient();
- const nowIso = new Date().toISOString();
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- const inspection = await trx
- .selectFrom("inboundInspection")
- .select([
- "id",
- "receiptLineId",
- "receiptId",
- "itemId",
- "status",
- "supplierId",
- "samplingStandard",
- "severity",
- "inspectionLevel",
- "aql",
- "lotSize",
- "sampleSize"
- ])
- .where("id", "=", args.id)
- .where("companyId", "=", args.companyId)
- .executeTakeFirst();
- if (!inspection) throw new Error("Inspection not found");
-
- const item = await trx
- .selectFrom("item")
- .select(["itemTrackingType"])
- .where("id", "=", inspection.itemId)
- .where("companyId", "=", args.companyId)
- .executeTakeFirst();
-
- const receiptLine = await trx
- .selectFrom("receiptLine")
- .select(["locationId"])
- .where("id", "=", inspection.receiptLineId)
- .where("companyId", "=", args.companyId)
- .executeTakeFirst();
-
- const lotEntities = await trx
- .selectFrom("trackedEntity")
- .select(["id"])
- .where(
- sql<string>`attributes ->> 'Receipt Line'`,
- "=",
- inspection.receiptLineId
- )
- .where("companyId", "=", args.companyId)
- .execute();
-
- const existingSamples = await trx
- .selectFrom("inboundInspectionSample")
- .select(["trackedEntityId", "status"])
- .where("inboundInspectionId", "=", args.id)
- .execute();
-
- const sampledIds = new Set(existingSamples.map((s) => s.trackedEntityId));
- const allLotIds = lotEntities.map((e) => e.id);
- const unsampledIds = allLotIds.filter((id) => !sampledIds.has(id));
- const failures = existingSamples.filter(
- (s) => s.status === "Failed"
- ).length;
-
- // Reject = entire lot non-conforming (ISO 9001:2015 §8.7). Accept only
- // releases un-sampled entities (sampled outcomes already flipped
- // per-sample). Partial leaves un-sampled entities On Hold.
- let lotStatus: "Passed" | "Failed" | "Partial";
- let idsToFlip: string[] = [];
- let flipStatus: "Available" | "Rejected" | null = null;
- switch (args.decision) {
- case "Accept":
- lotStatus = "Passed";
- idsToFlip = unsampledIds;
- flipStatus = "Available";
- break;
- case "Reject":
- lotStatus = "Failed";
- idsToFlip = allLotIds;
- flipStatus = "Rejected";
- break;
- case "Partial":
- lotStatus = "Partial";
- idsToFlip = [];
- flipStatus = null;
- break;
- }
-
- if (flipStatus && idsToFlip.length > 0) {
- await trx
- .updateTable("trackedEntity")
- .set({ status: flipStatus })
- .where("id", "in", idsToFlip)
- .where("companyId", "=", args.companyId)
- .execute();
- }
-
- // Non-tracked (Inventory) items have no tracked entities to flip, so the
- // received quantity sits in itemLedger with no per-row status to exclude
- // it from on-hand. Rejecting the lot must post a compensating
- // Negative Adjmt. to reverse the full received quantity. Tracked items
- // are already handled by the status flip above; Non-Inventory items never
- // posted a ledger entry at receipt, so neither needs this.
- if (
- args.decision === "Reject" &&
- inspection.status !== "Failed" &&
- item?.itemTrackingType === "Inventory" &&
- inspection.lotSize > 0
- ) {
- await trx
- .insertInto("itemLedger")
- .values({
- itemId: inspection.itemId,
- locationId: receiptLine?.locationId ?? null,
- entryType: "Negative Adjmt.",
- documentType: "Inbound Inspection",
- documentId: inspection.id,
- quantity: -inspection.lotSize,
- trackedEntityId: null,
- companyId: args.companyId,
- createdBy: args.dispositionedBy,
- comment: "Inbound inspection lot rejected"
- })
- .execute();
- }
-
- const updated = await trx
- .updateTable("inboundInspection")
- .set({
- status: lotStatus,
- notes: args.notes ?? null,
- dispositionedBy: args.dispositionedBy,
- dispositionedAt: nowIso,
- updatedBy: args.dispositionedBy,
- updatedAt: nowIso
- })
- .where("id", "=", args.id)
- .where("companyId", "=", args.companyId)
- .returning(["id", "status"])
- .executeTakeFirstOrThrow();
+ } & Pick<engine.InspectionDispositionInput, "requireOpen" | "requireSource">
+) {
+ return engine.dispositionInspection(getDatabaseClient(), args);
+}
- await trx
- .insertInto("inboundInspectionHistory")
- .values({
- inboundInspectionId: args.id,
- itemId: inspection.itemId,
- supplierId: inspection.supplierId ?? null,
- samplingStandard: inspection.samplingStandard,
- severity: inspection.severity ?? "Normal",
- inspectionLevel: inspection.inspectionLevel ?? null,
- aql: inspection.aql ?? null,
- lotSize: inspection.lotSize,
- sampleSize: inspection.sampleSize,
- defectsFound: failures,
- outcome:
- args.decision === "Accept"
- ? "Accepted"
- : args.decision === "Reject"
- ? "Rejected"
- : "Partial",
- companyId: args.companyId,
- createdBy: args.dispositionedBy
- })
- .execute();
+export async function upsertInspectionMeasurement(
+ args: z.infer<typeof inspectionMeasurementValidator> & {
+ companyId: string;
+ userId: string;
+ }
+) {
+ return engine.upsertInspectionMeasurement(getDatabaseClient(), args);
+}
- return { id: updated.id, status: updated.status };
- });
+export async function reconcileInspectionSamplingPlans(
+ inspectionId: string,
+ companyId: string
+) {
+ return engine.reconcileInspectionSamplingPlans(
+ getDatabaseClient(),
+ inspectionId,
+ companyId
+ );
+}
- return { data: result, error: null };
- } catch (err) {
- return errResult(
- err instanceof Error ? err.message : "Failed to disposition inspection"
- );
- }
+export async function changeInspectionDocument(args: {
+ inspectionId: string;
+ inspectionDocumentId: string | null;
+ companyId: string;
+ userId: string;
+}) {
+ return engine.changeInspectionDocument(getDatabaseClient(), args);
}
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index b4390a327f..3bf9ad316c 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -11,14 +11,6 @@ import { sanitize } from "~/utils/supabase";
const logger = getLogger("erp", "quality");
-import {
- listBalloons,
- listInspectionFeatures,
- mapBalloonIdsToFeatureIdsForDocument
-} from "./inspectionDocumentDb";
-
-export { mapBalloonIdsToFeatureIdsForDocument };
-
import type { inspectionStatus } from "../shared";
import type {
gaugeCalibrationRecordValidator,
@@ -26,11 +18,10 @@ import type {
gaugeRole,
gaugeTypeValidator,
gaugeValidator,
- inspectionDocumentValidator,
issueTypeValidator,
issueValidator,
issueWorkflowValidator,
- itemSamplingPlanValidator,
+ itemInspectionDocumentAssignmentValidator,
nonConformanceApprovalRequirement,
nonConformanceReviewerValidator,
nonConformanceStatus,
@@ -142,9 +133,9 @@ export async function deleteIssueAssociation(
.from("nonConformanceTrackedEntity")
.delete()
.eq("id", associationId);
- case "inboundInspections":
+ case "inspections":
return await (client as any)
- .from("nonConformanceInboundInspection")
+ .from("nonConformanceInspection")
.delete()
.eq("id", associationId);
default:
@@ -517,7 +508,7 @@ export async function getIssueAssociations(
trackedEntities,
customers,
suppliers,
- inboundInspections
+ inspections
] = await Promise.all([
// Items
(client as any)
@@ -699,14 +690,14 @@ export async function getIssueAssociations(
// Inbound Inspections
(client as any)
- .from("nonConformanceInboundInspection")
+ .from("nonConformanceInspection")
.select(
`
id,
- inboundInspectionId,
- inboundInspection:inboundInspection (
+ inspectionId,
+ inspection:inspection (
id,
- inboundInspectionId,
+ inspectionId,
itemReadableId,
lotSize,
status,
@@ -811,17 +802,15 @@ export async function getIssueAssociations(
documentLineId: "",
documentReadableId: item.supplier.name
})) || [],
- inboundInspections: ((inboundInspections as any)?.data ?? []).map(
- (link: any) => ({
- id: link.id,
- type: "inboundInspections",
- documentId: link.inboundInspectionId ?? "",
- documentLineId: "",
- documentReadableId: link.inboundInspection?.inboundInspectionId ?? "",
- quantity: link.inboundInspection?.lotSize ?? 0,
- status: link.inboundInspection?.status ?? null
- })
- )
+ inspections: ((inspections as any)?.data ?? []).map((link: any) => ({
+ id: link.id,
+ type: "inspections",
+ documentId: link.inspectionId ?? "",
+ documentLineId: "",
+ documentReadableId: link.inspection?.inspectionId ?? "",
+ quantity: link.inspection?.lotSize ?? 0,
+ status: link.inspection?.status ?? null
+ }))
};
}
@@ -2216,665 +2205,180 @@ export async function upsertRisk(
}
}
-// ─── Inspection Documents ─────────────────────────────────────────────────────
-
-function toStoragePath(pdfUrl?: string | null) {
- if (!pdfUrl) return null;
- const previewPrefix = "/file/preview/private/";
- if (pdfUrl.startsWith(previewPrefix)) {
- return pdfUrl.slice(previewPrefix.length);
- }
- return pdfUrl;
-}
-
-function toPreviewUrl(storagePath?: string | null) {
- if (!storagePath) return null;
- return storagePath.startsWith("/file/preview/private/")
- ? storagePath
- : `/file/preview/private/${storagePath}`;
-}
-
-function fileNameFromPath(storagePath?: string | null) {
- if (!storagePath) return "drawing.pdf";
- return storagePath.split("/").at(-1) ?? "drawing.pdf";
-}
-
-function mapInspectionDocument(row: Record<string, unknown>) {
- const drawingNumber = (row.drawingNumber as string | null) ?? null;
- return {
- id: String(row.id),
- name: String(drawingNumber ?? row.fileName ?? "Untitled Diagram"),
- companyId: String(row.companyId),
- partId: (row.partId as string | null) ?? null,
- createdBy: String(row.createdBy),
- updatedBy: (row.updatedBy as string | null) ?? null,
- createdAt: String(row.createdAt),
- updatedAt: (row.updatedAt as string | null) ?? null,
- content: {
- drawingNumber,
- pdfUrl: toPreviewUrl((row.storagePath as string | null) ?? null),
- annotations: [],
- features: []
- }
- };
-}
+// -------------------------------------------------------------
+// Inbound Inspections (lot-based)
+// -------------------------------------------------------------
-export async function getInspectionDocuments(
+export async function getInspections(
client: SupabaseClient<Database>,
companyId: string,
- args?: { search: string | null } & GenericQueryFilters
+ args?: GenericQueryFilters & {
+ search: string | null;
+ status: string | null;
+ source: string | null;
+ }
) {
- const documentClient = client as unknown as {
- from: (table: string) => {
- select: (
- columns: string,
- options?: { count?: "exact" | "planned" | "estimated"; head?: boolean }
- ) => any;
- };
- };
-
- let query = documentClient
- .from("inspectionDocuments")
- .select("*", { count: "exact" })
+ // No receipt embed: the generic sourceDocumentId carries no FK, so the
+ // source document is denormalized onto the row (sourceDocumentReadableId).
+ let query = (client as any)
+ .from("inspection")
+ .select(
+ "*, item(readableId, name), supplier(name), inspectionSample(status)",
+ { count: "exact" }
+ )
.eq("companyId", companyId);
if (args?.search) {
query = query.or(
- `drawingNumber.ilike.%${args.search}%,fileName.ilike.%${args.search}%,partReadableId.ilike.%${args.search}%`
+ `itemReadableId.ilike.%${args.search}%,sourceDocumentReadableId.ilike.%${args.search}%,notes.ilike.%${args.search}%`
);
}
- if (args) {
- query = setGenericQueryFilters(query, args, [
- { column: "drawingNumber", ascending: true }
- ]);
+ if (args?.status) {
+ // @ts-ignore - status is a valid enum value
+ query = query.eq("status", args.status);
}
- const result = await query;
-
- return {
- data: (result.data ?? []).map((row: Record<string, unknown>) =>
- mapInspectionDocument(row)
- ),
- count: result.count ?? 0,
- error: result.error
- };
-}
-
-export async function getInspectionDocument(
- client: SupabaseClient<Database>,
- id: string
-) {
- const documentClient = client as unknown as {
- from: (table: string) => {
- select: (columns: string) => {
- eq: (
- column: string,
- value: unknown
- ) => {
- single: () => Promise<{
- data: Record<string, unknown> | null;
- error: unknown;
- }>;
- };
- };
- };
- };
-
- const result = await documentClient
- .from("inspectionDocument")
- .select("*")
- .eq("id", id)
- .single();
-
- return {
- data: result.data ? mapInspectionDocument(result.data) : null,
- error: result.error
- };
-}
-
-export async function upsertInspectionDocument(
- client: SupabaseClient<Database>,
- diagram:
- | (Omit<z.infer<typeof inspectionDocumentValidator>, "id"> & {
- id?: undefined;
- companyId: string;
- createdBy: string;
- updatedBy?: string;
- pageCount?: number;
- defaultPageWidth?: number;
- defaultPageHeight?: number;
- })
- | (Omit<z.infer<typeof inspectionDocumentValidator>, "id"> & {
- id: string;
- companyId: string;
- createdBy: string;
- updatedBy?: string;
- pageCount?: number;
- defaultPageWidth?: number;
- defaultPageHeight?: number;
- })
-) {
- const {
- id,
- partId,
- drawingNumber,
- pdfUrl,
- pageCount,
- defaultPageWidth,
- defaultPageHeight,
- companyId,
- createdBy,
- updatedBy
- } = diagram;
-
- const documentClient = client as unknown as {
- from: (table: string) => {
- select: (columns: string) => {
- eq: (
- column: string,
- value: unknown
- ) => {
- single: () => Promise<{
- data: Record<string, unknown> | null;
- error: unknown;
- }>;
- };
- };
- update: (payload: Record<string, unknown>) => {
- eq: (
- column: string,
- value: unknown
- ) => {
- eq: (
- column: string,
- value: unknown
- ) => {
- select: (columns: string) => {
- single: () => Promise<{
- data: { id: string } | null;
- error: unknown;
- }>;
- };
- };
- };
- };
- insert: (payload: Record<string, unknown>) => {
- select: (columns: string) => {
- single: () => Promise<{
- data: { id: string } | null;
- error: unknown;
- }>;
- };
- };
- };
- };
-
- const storagePath = toStoragePath(pdfUrl);
-
- if (id) {
- if (!companyId) {
- return {
- data: null,
- error: {
- message: "companyId is required to update inspection document"
- }
- };
- }
-
- const existingResult = await documentClient
- .from("inspectionDocument")
- .select("*")
- .eq("id", id)
- .single();
-
- const existing = existingResult.data;
- if (!existing) {
- return {
- data: null,
- error: {
- message: "Inspection document not found"
- }
- };
- }
- if (String(existing.companyId ?? "") !== companyId) {
- return {
- data: null,
- error: {
- message: "Inspection document does not belong to this company"
- }
- };
- }
-
- const updatePayload: Record<string, unknown> = {
- updatedBy: updatedBy ?? createdBy,
- updatedAt: new Date().toISOString()
- };
- if (drawingNumber !== undefined) {
- updatePayload.drawingNumber = drawingNumber ?? null;
- }
- if (partId !== undefined) {
- updatePayload.partId = partId;
- }
-
- if (storagePath) {
- updatePayload.storagePath = storagePath;
- updatePayload.fileName = fileNameFromPath(storagePath);
- }
- if (pageCount && pageCount > 0) {
- updatePayload.pageCount = pageCount;
- }
- if (defaultPageWidth && defaultPageWidth > 0) {
- updatePayload.defaultPageWidth = defaultPageWidth;
- }
- if (defaultPageHeight && defaultPageHeight > 0) {
- updatePayload.defaultPageHeight = defaultPageHeight;
- }
-
- return documentClient
- .from("inspectionDocument")
- .update(updatePayload)
- .eq("id", id)
- .eq("companyId", companyId)
- .select("id")
- .single();
+ if (args?.source) {
+ // @ts-ignore - source is a valid enum value
+ query = query.eq("sourceDocument", args.source);
}
- if (!companyId) {
- return {
- data: null,
- error: { message: "companyId is required to create inspection document" }
- };
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "createdAt", ascending: false }
+ ]);
}
- return documentClient
- .from("inspectionDocument")
- .insert({
- companyId,
- partId,
- drawingNumber: drawingNumber ?? null,
- version: 0,
- ...(storagePath
- ? {
- storagePath,
- fileName: fileNameFromPath(storagePath),
- uploadedBy: createdBy
- }
- : {}),
- ...(pageCount && pageCount > 0 ? { pageCount } : {}),
- ...(defaultPageWidth && defaultPageWidth > 0 ? { defaultPageWidth } : {}),
- ...(defaultPageHeight && defaultPageHeight > 0
- ? { defaultPageHeight }
- : {}),
- createdBy
- })
- .select("id")
- .single();
+ return query;
}
-export async function deleteInspectionDocument(
+export async function getInspection(
client: SupabaseClient<Database>,
id: string
) {
- const documentClient = client as unknown as {
- from: (table: string) => {
- select: (columns: string) => {
- eq: (
- column: string,
- value: unknown
- ) => {
- single: () => Promise<{
- data: Record<string, unknown> | null;
- error: unknown;
- }>;
- };
- };
- delete: () => {
- eq: (
- column: string,
- value: unknown
- ) => Promise<{
- error: unknown;
- }>;
- };
- };
- };
-
- const existingResult = await documentClient
- .from("inspectionDocument")
- .select("*")
+ return (client as any)
+ .from("inspection")
+ .select(
+ "*, item(readableId, name, type, itemTrackingType), supplier(name), inspectionSample(*, trackedEntity(id, readableId, attributes, status, sourceDocumentReadableId))"
+ )
.eq("id", id)
.single();
-
- if (!existingResult.data) {
- return {
- data: null,
- error: { message: "Inspection document not found" }
- };
- }
-
- const storagePath =
- (existingResult.data.storagePath as string | null) ?? null;
-
- const deleteResult = await documentClient
- .from("inspectionDocument")
- .delete()
- .eq("id", id);
-
- if (deleteResult.error) {
- return { data: null, error: deleteResult.error };
- }
-
- return {
- data: { storagePath },
- error: null
- };
}
-function mapInspectionFeature(row: Record<string, unknown>) {
- const balloonIdRaw = row.balloonId ?? row.balloon_id;
- return {
- id: String(row.id),
- inspectionDocumentId: String(row.inspectionDocumentId),
- companyId: String(row.companyId),
- pageNumber: Number(row.pageNumber),
- label: String(row.label),
- description: (row.description as string | null) ?? null,
- nominalValue: (row.nominalValue as string | null) ?? null,
- tolerancePlus: (row.tolerancePlus as string | null) ?? null,
- toleranceMinus: (row.toleranceMinus as string | null) ?? null,
- unit: (row.unit as string | null) ?? null,
- type: (row.type as string) ?? "Measurement",
- balloonId:
- typeof balloonIdRaw === "string"
- ? balloonIdRaw
- : balloonIdRaw != null
- ? String(balloonIdRaw)
- : null,
- createdBy: String(row.createdBy),
- updatedBy: (row.updatedBy as string | null) ?? null,
- createdAt: String(row.createdAt),
- updatedAt: (row.updatedAt as string | null) ?? null
- };
-}
-
-function mapBalloon(row: Record<string, unknown>) {
- return {
- id: String(row.id),
- inspectionDocumentId: String(row.inspectionDocumentId),
- companyId: String(row.companyId),
- inspectionFeatureId: String(row.inspectionFeatureId),
- pageNumber: Number(row.pageNumber),
- regionX: Number(row.regionX),
- regionY: Number(row.regionY),
- regionWidth: Number(row.regionWidth),
- regionHeight: Number(row.regionHeight),
- xCoordinate: Number(row.xCoordinate),
- yCoordinate: Number(row.yCoordinate),
- createdBy: String(row.createdBy),
- updatedBy: (row.updatedBy as string | null) ?? null,
- createdAt: String(row.createdAt),
- updatedAt: (row.updatedAt as string | null) ?? null,
- balloonAnchorId: String(row.id)
- };
-}
-
-export async function getInspectionFeatures(
+// All inspection lots created for a receipt (one per inspected receipt line),
+// keyed by the source-generic columns. Powers the receipt header's link/dropdown
+// to its inspections.
+export async function getReceiptInspections(
client: SupabaseClient<Database>,
- inspectionDocumentId: string
+ receiptId: string,
+ companyId: string
) {
- const [featuresResult, balloonsResult] = await Promise.all([
- getInspectionFeaturesRaw(client, inspectionDocumentId),
- getBalloons(client, inspectionDocumentId)
- ]);
-
- if (featuresResult.error) {
- return { data: null, error: featuresResult.error };
- }
- if (balloonsResult.error) {
- return { data: null, error: balloonsResult.error };
- }
-
- const balloonByFeatureId = new Map(
- (balloonsResult.data ?? []).map((b) => [b.inspectionFeatureId, b.id])
- );
-
- return {
- data: (featuresResult.data ?? []).map((row) =>
- mapInspectionFeature({
- ...row,
- balloonId: balloonByFeatureId.get(String(row.id)) ?? null
- })
- ),
- error: null
- };
+ return (client as any)
+ .from("inspection")
+ .select("id, inspectionId, itemId, itemReadableId, status")
+ .eq("sourceDocument", "Receipt")
+ .eq("sourceDocumentId", receiptId)
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: true });
}
-async function getInspectionFeaturesRaw(
+// Receipt-sourced lots only: the received tracked entities are linked to the
+// receipt line through their attributes.
+export async function getInspectionTrackedEntities(
client: SupabaseClient<Database>,
- inspectionDocumentId: string
+ receiptLineId: string,
+ companyId: string
) {
- return listInspectionFeatures(client, inspectionDocumentId);
+ return client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes ->> Receipt Line", receiptLineId)
+ .eq("companyId", companyId);
}
-export async function getBalloons(
+export async function getInspectionSamplingPlans(
client: SupabaseClient<Database>,
- inspectionDocumentId: string
+ inspectionId: string,
+ companyId: string
) {
- const result = await listBalloons(client, inspectionDocumentId);
-
- return {
- data: (result.data ?? []).map((row) =>
- mapBalloon(row as unknown as Record<string, unknown>)
- ),
- error: result.error
- };
+ // Embed by target table name, never alias:fkColumn — composite-FK embeds
+ // break with the alias form.
+ return client
+ .from("inspectionSamplingPlan")
+ .select(
+ "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit)"
+ )
+ .eq("inspectionId", inspectionId)
+ .eq("companyId", companyId);
}
-export async function getInspectionPlan(
+export async function getInspectionMeasurements(
client: SupabaseClient<Database>,
- inspectionDocumentId: string
+ inspectionId: string,
+ companyId: string
) {
- const [featuresResult, balloonsResult] = await Promise.all([
- getInspectionFeaturesRaw(client, inspectionDocumentId),
- getBalloons(client, inspectionDocumentId)
- ]);
-
- if (featuresResult.error) {
- return { data: null, error: featuresResult.error };
- }
- if (balloonsResult.error) {
- return { data: null, error: balloonsResult.error };
- }
-
- const balloonByFeatureId = new Map(
- (balloonsResult.data ?? []).map((b) => [b.inspectionFeatureId, b])
- );
-
- return {
- data: (featuresResult.data ?? []).map((row) => {
- const b = balloonByFeatureId.get(row.id);
- const featureId = row.id;
- return {
- /** Feature id (primary key for plan rows). */
- id: featureId,
- featureId,
- /** Balloon id when placed; null for table-only characteristics. */
- balloonId: b?.id ?? null,
- inspectionDocumentId: row.inspectionDocumentId,
- pageNumber: b?.pageNumber ?? row.pageNumber,
- characteristic: row.label,
- description: row.description,
- nominalValue: row.nominalValue,
- tolerancePlus: row.tolerancePlus,
- toleranceMinus: row.toleranceMinus,
- unit: row.unit,
- regionX: b ? b.regionX : null,
- regionY: b ? b.regionY : null,
- regionWidth: b ? b.regionWidth : null,
- regionHeight: b ? b.regionHeight : null,
- xCoordinate: b ? b.xCoordinate : null,
- yCoordinate: b ? b.yCoordinate : null
- };
- }),
- error: null
- };
+ return client
+ .from("inspectionMeasurement")
+ .select("*")
+ .eq("inspectionId", inspectionId)
+ .eq("companyId", companyId);
}
-export async function saveInspectionDocumentAtomic(
- client: SupabaseClient<Database>,
- args: {
- inspectionDocumentId: string;
- companyId: string;
- userId: string;
- pdfUrl?: string | null;
- pageCount?: number;
- defaultPageWidth?: number;
- defaultPageHeight?: number;
- features: unknown;
- balloons: unknown;
- }
-) {
- return (
- client as unknown as {
- rpc: (
- fn: string,
- args: Record<string, unknown>
- ) => Promise<{
- data: unknown;
- error: unknown;
- }>;
- }
- ).rpc("save_inspection_document_atomic", {
- p_inspection_document_id: args.inspectionDocumentId,
- p_company_id: args.companyId,
- p_user_id: args.userId,
- p_pdf_url: args.pdfUrl ?? null,
- p_page_count: args.pageCount ?? null,
- p_default_page_width: args.defaultPageWidth ?? null,
- p_default_page_height: args.defaultPageHeight ?? null,
- p_features: args.features,
- p_balloons: args.balloons
- });
-}
-
-// -------------------------------------------------------------
-// Inbound Inspections (lot-based)
-// -------------------------------------------------------------
-
-export async function getItemSamplingPlan(
+export async function getItemInspectionDocumentAssignments(
client: SupabaseClient<Database>,
itemId: string,
companyId: string
) {
- return (client as any)
- .from("itemSamplingPlan")
+ return client
+ .from("itemInspectionDocumentAssignment")
.select("*")
.eq("itemId", itemId)
- .eq("companyId", companyId)
- .maybeSingle();
+ .eq("companyId", companyId);
}
-export async function upsertItemSamplingPlan(
+export async function upsertItemInspectionDocumentAssignment(
client: SupabaseClient<Database>,
- plan: z.infer<typeof itemSamplingPlanValidator> & {
+ assignment: z.infer<typeof itemInspectionDocumentAssignmentValidator> & {
companyId: string;
- updatedBy: string;
+ userId: string;
}
) {
- const existing = await (client as any)
- .from("itemSamplingPlan")
+ if (!assignment.inspectionDocumentId) {
+ return client
+ .from("itemInspectionDocumentAssignment")
+ .delete()
+ .eq("itemId", assignment.itemId)
+ .eq("usage", assignment.usage)
+ .eq("companyId", assignment.companyId);
+ }
+
+ const existing = await client
+ .from("itemInspectionDocumentAssignment")
.select("itemId")
- .eq("itemId", plan.itemId)
- .eq("companyId", plan.companyId)
+ .eq("itemId", assignment.itemId)
+ .eq("usage", assignment.usage)
+ .eq("companyId", assignment.companyId)
.maybeSingle();
- const payload = {
- itemId: plan.itemId,
- type: plan.type,
- sampleSize: plan.sampleSize ?? null,
- percentage: plan.percentage ?? null,
- aql: plan.aql ?? null,
- inspectionLevel: plan.inspectionLevel,
- severity: plan.severity,
- companyId: plan.companyId
- };
-
if (existing.data) {
- return (client as any)
- .from("itemSamplingPlan")
+ return client
+ .from("itemInspectionDocumentAssignment")
.update({
- ...payload,
- updatedBy: plan.updatedBy,
+ inspectionDocumentId: assignment.inspectionDocumentId,
+ updatedBy: assignment.userId,
updatedAt: new Date().toISOString()
})
- .eq("itemId", plan.itemId)
- .eq("companyId", plan.companyId);
+ .eq("itemId", assignment.itemId)
+ .eq("usage", assignment.usage)
+ .eq("companyId", assignment.companyId);
}
- return (client as any).from("itemSamplingPlan").insert({
- ...payload,
- createdBy: plan.updatedBy
+ return client.from("itemInspectionDocumentAssignment").insert({
+ itemId: assignment.itemId,
+ usage: assignment.usage,
+ inspectionDocumentId: assignment.inspectionDocumentId,
+ companyId: assignment.companyId,
+ createdBy: assignment.userId
});
}
-
-export async function getInboundInspections(
- client: SupabaseClient<Database>,
- companyId: string,
- args?: GenericQueryFilters & {
- search: string | null;
- status: string | null;
- }
-) {
- let query = (client as any)
- .from("inboundInspection")
- .select(
- "*, item(readableId, name), receipt(receiptId, supplierId), supplier(name), inboundInspectionSample(status)",
- { count: "exact" }
- )
- .eq("companyId", companyId);
-
- if (args?.search) {
- query = query.or(
- `itemReadableId.ilike.%${args.search}%,notes.ilike.%${args.search}%`
- );
- }
-
- if (args?.status) {
- // @ts-ignore - status is a valid enum value
- query = query.eq("status", args.status);
- }
-
- if (args) {
- query = setGenericQueryFilters(query, args, [
- { column: "createdAt", ascending: false }
- ]);
- }
-
- return query;
-}
-
-export async function getInboundInspection(
- client: SupabaseClient<Database>,
- id: string
-) {
- return (client as any)
- .from("inboundInspection")
- .select(
- "*, item(readableId, name, type, itemTrackingType), receipt(receiptId, supplierId, createdBy), supplier(name), inboundInspectionSample(*, trackedEntity(id, readableId, attributes, status, sourceDocumentReadableId))"
- )
- .eq("id", id)
- .single();
-}
-
-export async function getInboundInspectionLotTrackedEntities(
- client: SupabaseClient<Database>,
- receiptLineId: string,
- companyId: string
-) {
- return client
- .from("trackedEntity")
- .select("*")
- .eq("attributes ->> Receipt Line", receiptLineId)
- .eq("companyId", companyId);
-}
diff --git a/apps/erp/app/modules/quality/samplingStandards.test.ts b/apps/erp/app/modules/quality/samplingStandards.test.ts
new file mode 100644
index 0000000000..40ff9ee96e
--- /dev/null
+++ b/apps/erp/app/modules/quality/samplingStandards.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import {
+ resolveFeatureSamplingPlan,
+ resolveSamplingPlan
+} from "./samplingStandards";
+
+describe("resolveFeatureSamplingPlan", () => {
+ it("uses the feature's own AQL rule over the item plan", () => {
+ const result = resolveFeatureSamplingPlan(
+ {
+ samplingPlanType: "AQL",
+ samplingAql: 1.0,
+ samplingInspectionLevel: "II",
+ samplingSeverity: "Normal"
+ },
+ { type: "Percentage", percentage: 50 },
+ 200,
+ "ANSI_Z1_4"
+ );
+ expect(result).toEqual(
+ resolveSamplingPlan(
+ { type: "AQL", aql: 1.0, inspectionLevel: "II", severity: "Normal" },
+ 200,
+ "ANSI_Z1_4"
+ )
+ );
+ expect(result.codeLetter).not.toBeNull();
+ expect(result.sampleSize).toBeLessThan(200);
+ });
+
+ it("falls back to the item plan when the feature has no rule", () => {
+ const result = resolveFeatureSamplingPlan(
+ { samplingPlanType: null },
+ { type: "Percentage", percentage: 10 },
+ 200,
+ "ANSI_Z1_4"
+ );
+ expect(result.sampleSize).toBe(20);
+ expect(result.acceptance).toBe(0);
+ expect(result.rejection).toBe(1);
+ });
+
+ it("falls back to 100% inspection when neither feature rule nor item plan exist", () => {
+ const result = resolveFeatureSamplingPlan(null, null, 37, "ANSI_Z1_4");
+ expect(result.sampleSize).toBe(37);
+ expect(result.acceptance).toBe(0);
+ expect(result.rejection).toBe(1);
+ expect(result.codeLetter).toBeNull();
+ });
+
+ it("clamps a First-N feature rule to the lot size", () => {
+ const result = resolveFeatureSamplingPlan(
+ { samplingPlanType: "First", samplingSampleSize: 10 },
+ null,
+ 4,
+ "ANSI_Z1_4"
+ );
+ expect(result.sampleSize).toBe(4);
+ });
+});
diff --git a/apps/erp/app/modules/quality/samplingStandards.ts b/apps/erp/app/modules/quality/samplingStandards.ts
index 3de4dfde68..1503a37b21 100644
--- a/apps/erp/app/modules/quality/samplingStandards.ts
+++ b/apps/erp/app/modules/quality/samplingStandards.ts
@@ -960,3 +960,33 @@ export function resolveSamplingPlan(
standard
};
}
+
+export type FeatureSamplingRule = {
+ samplingPlanType?: SamplingPlanType | null;
+ samplingSampleSize?: number | null;
+ samplingPercentage?: number | null;
+ samplingAql?: number | null;
+ samplingInspectionLevel?: InspectionLevel | null;
+ samplingSeverity?: InspectionSeverity | null;
+};
+
+// Per-feature resolution: a feature's own rule wins, else the inspection
+// document's default rule, else 100% inspection.
+export function resolveFeatureSamplingPlan(
+ feature: FeatureSamplingRule | null | undefined,
+ defaultPlan: SamplingPlanInput | null | undefined,
+ lotSize: number,
+ standard: SamplingStandard
+): SamplingResult {
+ const plan: SamplingPlanInput = feature?.samplingPlanType
+ ? {
+ type: feature.samplingPlanType,
+ sampleSize: feature.samplingSampleSize ?? undefined,
+ percentage: feature.samplingPercentage ?? undefined,
+ aql: feature.samplingAql ?? undefined,
+ inspectionLevel: feature.samplingInspectionLevel ?? undefined,
+ severity: feature.samplingSeverity ?? undefined
+ }
+ : (defaultPlan ?? { type: "All" });
+ return resolveSamplingPlan(plan, lotSize, standard);
+}
diff --git a/apps/erp/app/modules/quality/types.ts b/apps/erp/app/modules/quality/types.ts
index ef71b2dd5d..2068e9821a 100644
--- a/apps/erp/app/modules/quality/types.ts
+++ b/apps/erp/app/modules/quality/types.ts
@@ -1,15 +1,13 @@
import type { Database } from "@carbon/database";
import type { nonConformanceAssociationType } from "./quality.models";
import type {
- getBalloons,
getGaugeCalibrationRecords,
getGauges,
getGaugeTypes,
- getInboundInspection,
- getInboundInspections,
- getInspectionDocument,
- getInspectionDocuments,
- getInspectionFeatures,
+ getInspection,
+ getInspectionMeasurements,
+ getInspectionSamplingPlans,
+ getInspections,
getIssueActionTasks,
getIssueApprovalTasks,
getIssueAssociations,
@@ -28,38 +26,6 @@ import type {
getRisks
} from "./quality.service";
-export type InspectionDocument = NonNullable<
- Awaited<ReturnType<typeof getInspectionDocuments>>["data"]
->[number];
-
-export type InspectionDocumentDetail = NonNullable<
- Awaited<ReturnType<typeof getInspectionDocument>>["data"]
->;
-
-export type Balloon = NonNullable<
- Awaited<ReturnType<typeof getBalloons>>["data"]
->[number];
-
-export type InspectionFeature = NonNullable<
- Awaited<ReturnType<typeof getInspectionFeatures>>["data"]
->[number];
-
-export type BalloonFeature = {
- id: string;
- balloonNumber: number;
- description: string;
- nominalValue: number | null;
- tolerancePlus: number | null;
- toleranceMinus: number | null;
- unitOfMeasureCode: string | null;
-};
-
-export type InspectionDocumentContent = {
- pdfUrl: string | null;
- drawingNumber: string | null;
- features: BalloonFeature[];
-};
-
export type Gauge = NonNullable<
Awaited<ReturnType<typeof getGauges>>["data"]
>[number];
@@ -169,35 +135,48 @@ export type Risk = NonNullable<
Awaited<ReturnType<typeof getRisks>>["data"]
>[number];
-export type InboundInspection = NonNullable<
- Awaited<ReturnType<typeof getInboundInspections>>["data"]
+export type Inspection = NonNullable<
+ Awaited<ReturnType<typeof getInspections>>["data"]
>[number];
-export type InboundInspectionDetail = NonNullable<
- Awaited<ReturnType<typeof getInboundInspection>>["data"]
+export type InspectionDetail = NonNullable<
+ Awaited<ReturnType<typeof getInspection>>["data"]
>;
-export type InboundInspectionStatus =
- Database["public"]["Enums"]["inboundInspectionStatus"];
+export type InspectionStatus =
+ Database["public"]["Enums"]["inspectionStatusType"];
-export type InboundInspectionSampleStatus =
- Database["public"]["Enums"]["inboundInspectionSampleStatus"];
+export type InspectionSampleStatus =
+ Database["public"]["Enums"]["inspectionSampleStatusType"];
-export type InboundInspectionRow =
- Database["public"]["Tables"]["inboundInspection"]["Row"];
+export type InspectionRow = Database["public"]["Tables"]["inspection"]["Row"];
-export type InboundInspectionSampleRow =
- Database["public"]["Tables"]["inboundInspectionSample"]["Row"];
+export type InspectionSampleRow =
+ Database["public"]["Tables"]["inspectionSample"]["Row"];
export type InspectionTrackedEntity = Pick<
Database["public"]["Tables"]["trackedEntity"]["Row"],
"id" | "readableId" | "attributes" | "status" | "sourceDocumentReadableId"
>;
-export type InboundInspectionSample = InboundInspectionSampleRow & {
+export type InspectionSample = InspectionSampleRow & {
trackedEntity: InspectionTrackedEntity | null;
};
+export type ItemInspectionDocumentAssignment =
+ Database["public"]["Tables"]["itemInspectionDocumentAssignment"]["Row"];
+
+export type InspectionMeasurementRow =
+ Database["public"]["Tables"]["inspectionMeasurement"]["Row"];
+
+export type InspectionSamplingPlan = NonNullable<
+ Awaited<ReturnType<typeof getInspectionSamplingPlans>>["data"]
+>[number];
+
+export type InspectionMeasurement = NonNullable<
+ Awaited<ReturnType<typeof getInspectionMeasurements>>["data"]
+>[number];
+
export type IssueTypeListItem = NonNullable<
Awaited<ReturnType<typeof getIssueTypesList>>["data"]
>[number];
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
index b148dc954f..57b59497bf 100644
--- a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
@@ -298,16 +298,19 @@ const GaugeCalibrationRecordForm = ({
name="requiresAction"
label={t`Requires Action`}
termId="calibration-requires-action"
+ bordered
/>
<Boolean
name="requiresAdjustment"
label={t`Requires Adjustment`}
termId="calibration-requires-adjustment"
+ bordered
/>
<Boolean
name="requiresRepair"
label={t`Requires Repair`}
termId="calibration-requires-repair"
+ bordered
/>
<Number
name="temperature"
diff --git a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionLotView.tsx b/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionLotView.tsx
deleted file mode 100644
index ee19b2e08d..0000000000
--- a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionLotView.tsx
+++ /dev/null
@@ -1,571 +0,0 @@
-import {
- Alert,
- AlertDescription,
- AlertTitle,
- Badge,
- BarProgress,
- Button,
- Checkbox,
- HStack,
- Label,
- Modal,
- ModalBody,
- ModalContent,
- ModalDrawer,
- ModalDrawerBody,
- ModalDrawerContent,
- ModalDrawerFooter,
- ModalDrawerHeader,
- ModalDrawerProvider,
- ModalDrawerTitle,
- ModalFooter,
- ModalHeader,
- ModalOverlay,
- ModalTitle,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- useDisclosure,
- VStack
-} from "@carbon/react";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useMemo, useRef, useState } from "react";
-import {
- LuCircleCheck,
- LuCircleX,
- LuScan,
- LuShieldAlert,
- LuTriangleAlert
-} from "react-icons/lu";
-import { useFetcher, useNavigate } from "react-router";
-import { EmployeeAvatar } from "~/components";
-import { Confirm } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
-import type {
- InboundInspectionRow,
- InboundInspectionSample,
- InspectionTrackedEntity,
- IssueTypeListItem
-} from "~/modules/quality/types";
-import { useItems } from "~/stores/items";
-import { path } from "~/utils/path";
-import { getReadableIdWithRevision } from "~/utils/string";
-import ScanInspectionSample from "./ScanInspectionSample";
-
-export type InboundInspectionLotViewProps = {
- inspection: InboundInspectionRow;
- receiptReadableId: string | null;
- receiverId: string | null;
- itemName: string;
- itemTrackingType: string | null;
- supplierName: string | null;
- samples: InboundInspectionSample[];
- lotEntities: InspectionTrackedEntity[];
- issueTypes: IssueTypeListItem[];
- currentUserId: string;
- enforceFourEyes: boolean;
- open?: boolean;
-};
-
-export default function InboundInspectionLotView({
- inspection,
- receiptReadableId,
- receiverId,
- itemName,
- itemTrackingType,
- supplierName,
- samples,
- lotEntities,
- issueTypes,
- currentUserId,
- enforceFourEyes,
- open = true
-}: InboundInspectionLotViewProps) {
- const { t } = useLingui();
- const navigate = useNavigate();
- const permissions = usePermissions();
- const canUpdate = permissions.can("update", "quality");
- const [items] = useItems();
-
- // Serial parts are inspected by scanning a discrete tracked entity. Batch /
- // inventory / non-inventory parts record pass/fail for each sampled item
- // without a tracked entity.
- const isSerial = itemTrackingType === "Serial";
-
- const scannerDisclosure = useDisclosure();
- const rejectConfirmDisclosure = useDisclosure();
- const acceptConfirmDisclosure = useDisclosure();
- const partialConfirmDisclosure = useDisclosure();
-
- // Look up the item in the live items store so we show the current
- // readable id (and revision) even if the snapshot stored on the
- // inspection row is stale.
- const item = items.find((i) => i.id === inspection.itemId);
- // The store exposes `readableIdWithRevision` pre-computed; split it so we
- // can run it through getReadableIdWithRevision for consistent formatting.
- const [storeReadableId, storeRevision] = (() => {
- const combined = (item as any)?.readableIdWithRevision as
- | string
- | undefined;
- if (!combined) return [undefined, undefined] as const;
- const dot = combined.lastIndexOf(".");
- if (dot < 0) return [combined, undefined] as const;
- return [combined.slice(0, dot), combined.slice(dot + 1)] as const;
- })();
- const displayReadableId =
- storeReadableId != null
- ? getReadableIdWithRevision(storeReadableId, storeRevision)
- : (inspection.itemReadableId ?? "");
- const displayItemName = item?.name ?? itemName;
-
- const passes = samples.filter((s) => s.status === "Passed").length;
- const fails = samples.filter((s) => s.status === "Failed").length;
- const inspected = passes + fails;
-
- const sampledIds = useMemo(
- () => new Set(samples.map((s) => s.trackedEntityId)),
- [samples]
- );
- const remaining = lotEntities.filter((e) => !sampledIds.has(e.id));
-
- const showFourEyesWarning =
- enforceFourEyes && !!receiverId && receiverId === currentUserId;
-
- // The lot is "closed" only after the inspector has pressed Accept or Reject
- // (setting dispositionedAt + a terminal status). Partial is explicitly not
- // closed — the inspector can keep scanning and disposition again later.
- const lotClosed =
- inspection.dispositionedAt != null &&
- (inspection.status === "Passed" || inspection.status === "Failed");
-
- const canAccept =
- !lotClosed &&
- inspected >= inspection.sampleSize &&
- fails <= inspection.acceptanceNumber;
- const canReject = !lotClosed && fails > inspection.acceptanceNumber;
- const canPartial = !lotClosed && inspected > 0;
-
- const failedTrackedEntityIds = samples
- .filter((s) => s.status === "Failed")
- .map((s) => s.trackedEntityId);
-
- const newIssueHref = `/x/issue/new?itemId=${encodeURIComponent(inspection.itemId)}&trackedEntityIds=${encodeURIComponent(failedTrackedEntityIds.join(","))}&sourceInspectionId=${encodeURIComponent(inspection.id)}`;
-
- const acceptUrl = `${path.to.inboundInspection(inspection.id)}/accept`;
- const rejectUrl = `${path.to.inboundInspection(inspection.id)}/reject`;
- const partialUrl = `${path.to.inboundInspection(inspection.id)}/partial`;
-
- return (
- <ModalDrawerProvider type="drawer">
- <ModalDrawer
- open={open}
- onOpenChange={(next) => {
- if (!next) navigate(-1);
- }}
- >
- <ModalDrawerContent size="full">
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- <Trans>Inspect</Trans> {displayReadableId || displayItemName}
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <VStack spacing={4} className="w-full">
- {/* Summary */}
- <div className="grid grid-cols-2 md:grid-cols-4 gap-4 w-full text-sm">
- <Kv
- label={t`Item`}
- value={displayReadableId}
- sub={displayItemName}
- />
- <Kv
- label={t`Receipt`}
- value={receiptReadableId ?? ""}
- sub={supplierName ?? undefined}
- />
- <Kv
- label={t`Plan`}
- value={
- inspection.samplingPlanType === "AQL"
- ? `AQL ${inspection.aql ?? ""} · Lvl ${inspection.inspectionLevel ?? ""} · ${inspection.severity ?? ""}`
- : inspection.samplingPlanType
- }
- sub={
- inspection.samplingStandard === "ANSI_Z1_4"
- ? "ANSI/ASQ Z1.4"
- : "ISO 2859-1"
- }
- />
- <Kv
- label={t`Sample`}
- value={`${inspected} / ${inspection.sampleSize}`}
- sub={`Ac ${inspection.acceptanceNumber} · Re ${inspection.rejectionNumber}${inspection.codeLetter ? ` · ${inspection.codeLetter}` : ""}`}
- />
- </div>
-
- {showFourEyesWarning && (
- <Alert variant="warning">
- <LuTriangleAlert className="size-4" />
- <AlertTitle>
- <Trans>You received this lot</Trans>
- </AlertTitle>
- <AlertDescription>
- <Trans>
- Company policy asks for a different person to inspect
- inbound items than the one who received them.
- </Trans>
- </AlertDescription>
- </Alert>
- )}
-
- {/* Progress */}
- <BarProgress
- label={t`Progress`}
- value={`${inspected} / ${inspection.sampleSize} · ${fails} ${fails === 1 ? "failure" : "failures"} · Ac ${inspection.acceptanceNumber}`}
- progress={inspected}
- max={Math.max(1, inspection.sampleSize)}
- activeClassName={
- fails > inspection.acceptanceNumber
- ? "bg-red-500"
- : "bg-emerald-500"
- }
- />
-
- {/* Scan button */}
- {!lotClosed && canUpdate && (
- <Button
- leftIcon={<LuScan />}
- onClick={scannerDisclosure.onOpen}
- className="self-start"
- >
- <Trans>Inspect Next Item</Trans>
- </Button>
- )}
-
- {/* Samples */}
- <div className="w-full border rounded-md overflow-hidden">
- <table className="text-sm w-full">
- <thead className="bg-muted text-xs text-muted-foreground">
- <tr>
- <th className="text-left px-3 py-2 font-medium">
- <Trans>Entity</Trans>
- </th>
- <th className="text-left px-3 py-2 font-medium">
- <Trans>Result</Trans>
- </th>
- <th className="text-left px-3 py-2 font-medium">
- <Trans>Inspector</Trans>
- </th>
- <th className="text-left px-3 py-2 font-medium">
- <Trans>Notes</Trans>
- </th>
- </tr>
- </thead>
- <tbody>
- {samples.length === 0 && (
- <tr>
- <td
- colSpan={4}
- className="px-3 py-6 text-center text-muted-foreground"
- >
- <Trans>No samples inspected yet.</Trans>
- </td>
- </tr>
- )}
- {samples.map((s, idx) => {
- const readable = s.trackedEntity?.readableId ?? null;
- return (
- <tr key={s.id} className="border-t">
- <td className="px-3 py-2">
- <div className="flex flex-col">
- <span className="font-mono text-sm">
- {readable ??
- s.trackedEntityId ??
- t`Sample ${idx + 1}`}
- </span>
- {readable && (
- <span className="text-xs text-muted-foreground">
- {s.trackedEntityId}
- </span>
- )}
- </div>
- </td>
- <td className="px-3 py-2">
- {s.status === "Passed" ? (
- <Badge variant="green">
- <LuCircleCheck className="size-3 mr-1" /> Passed
- </Badge>
- ) : s.status === "Failed" ? (
- <Badge variant="red">
- <LuCircleX className="size-3 mr-1" /> Failed
- </Badge>
- ) : (
- <Badge variant="secondary">{s.status}</Badge>
- )}
- </td>
- <td className="px-3 py-2">
- {s.inspectedBy ? (
- <EmployeeAvatar employeeId={s.inspectedBy} />
- ) : (
- ""
- )}
- </td>
- <td className="px-3 py-2 text-muted-foreground">
- {s.notes ?? ""}
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
- </VStack>
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack spacing={2} className="w-full justify-between">
- <Button
- variant="secondary"
- leftIcon={<LuShieldAlert />}
- asChild
- isDisabled={failedTrackedEntityIds.length === 0}
- >
- <a href={newIssueHref} target="_blank" rel="noreferrer">
- <Trans>Create Issue from Inspection</Trans>
- </a>
- </Button>
- <HStack spacing={2}>
- <Button
- variant="secondary"
- onClick={partialConfirmDisclosure.onOpen}
- isDisabled={!canUpdate || !canPartial}
- >
- <Trans>Partial</Trans>
- </Button>
- <Button
- variant="destructive"
- onClick={rejectConfirmDisclosure.onOpen}
- isDisabled={!canUpdate || !canReject}
- >
- <Trans>Reject Lot</Trans>
- </Button>
- <Button
- onClick={acceptConfirmDisclosure.onOpen}
- isDisabled={!canUpdate || !canAccept}
- >
- <Trans>Accept Lot</Trans>
- </Button>
- </HStack>
- </HStack>
- </ModalDrawerFooter>
- </ModalDrawerContent>
- </ModalDrawer>
-
- {scannerDisclosure.isOpen && (
- <ScanInspectionSample
- inspectionId={inspection.id}
- isSerial={isSerial}
- remaining={remaining}
- inspected={inspected}
- sampleSize={inspection.sampleSize}
- fails={fails}
- acceptanceNumber={inspection.acceptanceNumber}
- onClose={scannerDisclosure.onClose}
- />
- )}
-
- {acceptConfirmDisclosure.isOpen && (
- <Confirm
- action={acceptUrl}
- title={t`Accept lot?`}
- text={
- isSerial
- ? t`${lotEntities.length - inspected} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected.`
- : t`The lot will be marked Passed. ${fails} sampled failure(s) are recorded for your records.`
- }
- confirmText={t`Accept Lot`}
- onCancel={acceptConfirmDisclosure.onClose}
- onSubmit={acceptConfirmDisclosure.onClose}
- />
- )}
-
- {partialConfirmDisclosure.isOpen && (
- <Confirm
- action={partialUrl}
- title={t`Mark lot as partial?`}
- text={
- isSerial
- ? t`Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved.`
- : t`The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved.`
- }
- confirmText={t`Mark Partial`}
- onCancel={partialConfirmDisclosure.onClose}
- onSubmit={partialConfirmDisclosure.onClose}
- />
- )}
-
- {rejectConfirmDisclosure.isOpen && (
- <RejectLotModal
- action={rejectUrl}
- issueTypes={issueTypes}
- summary={
- isSerial
- ? t`Statistical acceptance failed, so the entire lot is considered non-conforming (ISO 9001:2015 §8.7). All ${lotEntities.length} entities — ${passes} sampled pass(es), ${fails} failure(s), and ${Math.max(0, lotEntities.length - inspected)} un-inspected — will be marked Rejected.`
- : t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s).`
- }
- onCancel={rejectConfirmDisclosure.onClose}
- onSubmit={rejectConfirmDisclosure.onClose}
- />
- )}
- </ModalDrawerProvider>
- );
-}
-
-function RejectLotModal({
- action,
- issueTypes,
- summary,
- onCancel,
- onSubmit
-}: {
- action: string;
- issueTypes: IssueTypeListItem[];
- summary: string;
- onCancel: () => void;
- onSubmit: () => void;
-}) {
- const { t } = useLingui();
- const fetcher = useFetcher<{}>();
- const submitted = useRef(false);
- const [createNcr, setCreateNcr] = useState(true);
- const [issueTypeId, setIssueTypeId] = useState<string>(
- issueTypes[0]?.id ?? ""
- );
-
- useEffect(() => {
- if (fetcher.state === "idle" && submitted.current) {
- onSubmit();
- submitted.current = false;
- }
- }, [fetcher.state, onSubmit]);
-
- const hasIssueTypes = issueTypes.length > 0;
-
- return (
- <Modal
- open
- onOpenChange={(open) => {
- if (!open) onCancel();
- }}
- >
- <ModalOverlay />
- <ModalContent>
- <ModalHeader>
- <ModalTitle>
- <Trans>Reject Lot</Trans>
- </ModalTitle>
- </ModalHeader>
- <ModalBody>
- <VStack spacing={4}>
- <p className="text-sm text-muted-foreground">{summary}</p>
- <label className="flex items-center gap-2 w-full cursor-pointer">
- <Checkbox
- isChecked={createNcr}
- onCheckedChange={(checked) => setCreateNcr(!!checked)}
- />
- <span className="text-sm font-medium">
- <Trans>Open an NCR for MRB disposition</Trans>
- </span>
- </label>
- {createNcr &&
- (hasIssueTypes ? (
- <div className="flex flex-col gap-2 w-full">
- <Label htmlFor="nonConformanceTypeId">
- <Trans>Issue Type</Trans>
- </Label>
- <Select value={issueTypeId} onValueChange={setIssueTypeId}>
- <SelectTrigger id="nonConformanceTypeId">
- <SelectValue placeholder={t`Select an issue type`} />
- </SelectTrigger>
- <SelectContent>
- {issueTypes.map((type) => (
- <SelectItem key={type.id} value={type.id}>
- {type.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- ) : (
- <Alert variant="warning">
- <LuTriangleAlert className="size-4" />
- <AlertTitle>
- <Trans>No issue types configured</Trans>
- </AlertTitle>
- <AlertDescription>
- <Trans>
- The lot will still be rejected, but an NCR cannot be
- created until at least one Issue Type is configured.
- </Trans>
- </AlertDescription>
- </Alert>
- ))}
- </VStack>
- </ModalBody>
- <ModalFooter>
- <Button variant="secondary" onClick={onCancel}>
- <Trans>Cancel</Trans>
- </Button>
- <fetcher.Form
- method="post"
- action={action}
- onSubmit={() => (submitted.current = true)}
- >
- <input
- type="hidden"
- name="createNcr"
- value={createNcr ? "true" : "false"}
- />
- <input
- type="hidden"
- name="nonConformanceTypeId"
- value={createNcr ? issueTypeId : ""}
- />
- <Button
- variant="destructive"
- type="submit"
- isLoading={fetcher.state !== "idle"}
- isDisabled={
- fetcher.state !== "idle" ||
- (createNcr && hasIssueTypes && !issueTypeId)
- }
- >
- <Trans>Reject Lot</Trans>
- </Button>
- </fetcher.Form>
- </ModalFooter>
- </ModalContent>
- </Modal>
- );
-}
-
-function Kv({
- label,
- value,
- sub
-}: {
- label: string;
- value: string;
- sub?: string;
-}) {
- return (
- <div className="flex flex-col gap-0">
- <span className="text-xs text-muted-foreground">{label}</span>
- <span className="text-sm font-medium truncate">{value || "—"}</span>
- {sub && (
- <span className="text-xs text-muted-foreground truncate">{sub}</span>
- )}
- </div>
- );
-}
diff --git a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx b/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx
deleted file mode 100644
index 7111fb23da..0000000000
--- a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { Badge } from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
-import { useLingui } from "@lingui/react/macro";
-import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useMemo } from "react";
-import {
- LuBlocks,
- LuBookMarked,
- LuCalendar,
- LuClipboardCheck,
- LuHash,
- LuTruck
-} from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, Table } from "~/components";
-import { useDateFormatter, useUrlParams } from "~/hooks";
-import { inboundInspectionStatus } from "~/modules/quality/quality.models";
-import type { InboundInspection } from "~/modules/quality/types";
-import { useItems } from "~/stores/items";
-import { path } from "~/utils/path";
-
-type InboundInspectionsTableProps = {
- data: InboundInspection[];
- count: number;
-};
-
-function getStatusVariant(status: string) {
- if (status === "Passed") return "green";
- if (status === "Failed") return "red";
- if (status === "Partial") return "yellow";
- if (status === "In Progress") return "blue";
- return "secondary";
-}
-
-function computeProgress(row: InboundInspection): {
- inspected: number;
- total: number;
-} {
- // The list loader selects `inboundInspectionSample(status)` as an array of
- // child rows; count the non-Pending ones.
- const samples: { status: string }[] =
- ((row as any).inboundInspectionSample as { status: string }[]) ?? [];
- const inspected = samples.filter((s) => s.status !== "Pending").length;
- return { inspected, total: (row as any).sampleSize ?? 0 };
-}
-
-const InboundInspectionsTable = memo(
- ({ data, count }: InboundInspectionsTableProps) => {
- const { t } = useLingui();
- const { formatDate } = useDateFormatter();
- const [params] = useUrlParams();
- const [items] = useItems();
-
- const columns = useMemo<ColumnDef<InboundInspection>[]>(() => {
- return [
- {
- accessorKey: "inboundInspectionId",
- header: t`Inspection`,
- cell: ({ row }) => (
- <Hyperlink
- to={`${path.to.inboundInspection(row.original.id!)}?${params.toString()}`}
- >
- {(row.original as any).inboundInspectionId}
- </Hyperlink>
- ),
- meta: {
- icon: <LuBookMarked />
- }
- },
- {
- accessorKey: "itemId",
- header: t`Item`,
- cell: ({ row }) => (
- <div className="flex flex-col gap-0">
- <span className="text-sm font-medium">
- {getItemReadableId(items, (row.original as any).itemId) ??
- (row.original as any).itemReadableId ??
- ""}
- </span>
- <span className="text-xs text-muted-foreground">
- {(row.original as any).item?.name}
- </span>
- </div>
- ),
- meta: {
- icon: <LuBookMarked />,
- filter: {
- type: "static",
- options: items.map((item) => ({
- value: item.id,
- label: item.readableIdWithRevision
- }))
- }
- }
- },
- {
- id: "receipt",
- header: t`Receipt`,
- cell: ({ row }) => (
- <div className="flex flex-col gap-0 text-sm">
- <span>{(row.original as any).receipt?.receiptId}</span>
- <span className="text-xs text-muted-foreground">
- {(row.original as any).supplier?.name}
- </span>
- </div>
- ),
- meta: {
- icon: <LuTruck />,
- exportValue: (row) => (row as any).receipt?.receiptId ?? null
- }
- },
- {
- accessorKey: "lotSize",
- header: t`Lot Size`,
- cell: ({ row }) => (
- <span className="text-sm">
- {(row.original as any).lotSize ?? 0}
- </span>
- ),
- meta: { icon: <LuBlocks /> }
- },
- {
- accessorKey: "sampleSize",
- header: t`Sample`,
- cell: ({ row }) => {
- const p = computeProgress(row.original);
- return (
- <span className="text-sm">
- {p.inspected} / {p.total}
- </span>
- );
- },
- meta: { icon: <LuHash /> }
- },
- {
- accessorKey: "status",
- header: t`Status`,
- cell: ({ row }) => (
- <Badge variant={getStatusVariant(row.original.status)}>
- {row.original.status}
- </Badge>
- ),
- meta: {
- icon: <LuClipboardCheck />,
- filter: {
- type: "static",
- options: inboundInspectionStatus.map((s) => ({
- value: s,
- label: <Badge variant={getStatusVariant(s)}>{s}</Badge>
- }))
- }
- }
- },
- {
- accessorKey: "createdBy",
- header: t`Received By`,
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.createdBy} />
- ),
- meta: { icon: <LuBlocks /> }
- },
- {
- accessorKey: "createdAt",
- header: t`Received At`,
- cell: ({ row }) =>
- row.original.createdAt ? formatDate(row.original.createdAt) : "",
- meta: { icon: <LuCalendar /> }
- }
- ];
- }, [items, t, params, formatDate]);
-
- return (
- <Table<InboundInspection>
- data={data}
- columns={columns}
- count={count ?? 0}
- title={t`Inbound Inspections`}
- table="inboundInspection"
- withSavedView
- />
- );
- }
-);
-
-InboundInspectionsTable.displayName = "InboundInspectionsTable";
-export default InboundInspectionsTable;
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionDrawingPane.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionDrawingPane.tsx
new file mode 100644
index 0000000000..ce20de9904
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionDrawingPane.tsx
@@ -0,0 +1,211 @@
+import { IconButton } from "@carbon/react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { LuChevronLeft, LuChevronRight } from "react-icons/lu";
+import { Circle, Group, Layer, Stage, Text } from "react-konva";
+import { Document, Page } from "react-pdf";
+import "react-pdf/dist/Page/AnnotationLayer.css";
+import "react-pdf/dist/Page/TextLayer.css";
+
+const CALLOUT_STROKE = "#f97316";
+
+export type DrawingBalloon = {
+ id: string;
+ inspectionFeatureId: string;
+ pageNumber: number;
+ xCoordinate: number;
+ yCoordinate: number;
+ label: string;
+};
+
+type InspectionDrawingPaneProps = {
+ pdfUrl: string;
+ balloons: DrawingBalloon[];
+ activeFeatureId: string | null;
+ onBalloonClick: (inspectionFeatureId: string) => void;
+};
+
+// Read-only PDF + balloon viewer for the inbound inspection execution screen.
+// A stripped-down sibling of InspectionDocumentEditor's viewer: no ballooning,
+// no zoom box — fit-to-width with page navigation and clickable balloons.
+// The pdf.js worker is configured globally in entry.client.tsx. This module
+// must be imported lazily (ClientOnly) — react-pdf and react-konva are
+// client-only.
+const InspectionDrawingPane = ({
+ pdfUrl,
+ balloons,
+ activeFeatureId,
+ onBalloonClick
+}: InspectionDrawingPaneProps) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const pageWrapperRef = useRef<HTMLDivElement>(null);
+ const [containerWidth, setContainerWidth] = useState(0);
+ const [overlayHeight, setOverlayHeight] = useState(0);
+ const [numPages, setNumPages] = useState(0);
+ const [page, setPage] = useState(1);
+ const [pageRendered, setPageRendered] = useState(false);
+
+ // Fit-to-width: track the container so the Page re-renders on pane resize.
+ useEffect(() => {
+ if (!containerRef.current) return;
+ const ro = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width;
+ if (width) setContainerWidth(width);
+ });
+ ro.observe(containerRef.current);
+ return () => ro.disconnect();
+ }, []);
+
+ // The Konva overlay matches the rendered page's real height.
+ useEffect(() => {
+ if (!pageWrapperRef.current) return;
+ const ro = new ResizeObserver((entries) => {
+ const height = entries[0]?.contentRect.height ?? 0;
+ if (height > 0) setOverlayHeight(height);
+ });
+ ro.observe(pageWrapperRef.current);
+ return () => ro.disconnect();
+ }, []);
+
+ // Balloon click in the grid direction: jump to the active feature's page.
+ useEffect(() => {
+ if (!activeFeatureId) return;
+ const balloon = balloons.find(
+ (b) => b.inspectionFeatureId === activeFeatureId
+ );
+ if (balloon && balloon.pageNumber !== page) {
+ setPage(balloon.pageNumber);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeFeatureId]);
+
+ const pageBalloons = useMemo(
+ () => balloons.filter((b) => b.pageNumber === page),
+ [balloons, page]
+ );
+
+ const balloonRadius = Math.max(10, containerWidth * 0.012);
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ {numPages > 1 && (
+ <div className="flex shrink-0 items-center justify-center gap-3 border-b border-border bg-card px-3 py-2.5 shadow-sm">
+ <IconButton
+ type="button"
+ aria-label="Previous page"
+ variant="secondary"
+ size="sm"
+ icon={<LuChevronLeft className="h-4 w-4" />}
+ isDisabled={page <= 1}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
+ />
+ <span className="min-w-[8.5rem] select-none text-center text-sm font-medium tabular-nums text-foreground">
+ Page {page} of {numPages}
+ </span>
+ <IconButton
+ type="button"
+ aria-label="Next page"
+ variant="secondary"
+ size="sm"
+ icon={<LuChevronRight className="h-4 w-4" />}
+ isDisabled={page >= numPages}
+ onClick={() => setPage((p) => Math.min(numPages, p + 1))}
+ />
+ </div>
+ )}
+ <div ref={containerRef} className="relative flex-1 overflow-auto">
+ <div
+ className="relative select-none"
+ style={{ width: containerWidth > 0 ? containerWidth : "100%" }}
+ >
+ <div ref={pageWrapperRef} className="pointer-events-none">
+ <Document
+ file={pdfUrl}
+ onLoadSuccess={(pdf) => {
+ setNumPages(pdf.numPages);
+ setPage(1);
+ }}
+ >
+ {containerWidth > 0 ? (
+ <Page
+ key={page}
+ pageNumber={page}
+ width={containerWidth}
+ renderTextLayer={false}
+ renderAnnotationLayer={false}
+ className="w-full"
+ onRenderSuccess={() => setPageRendered(true)}
+ />
+ ) : null}
+ </Document>
+ </div>
+
+ {pageRendered && containerWidth > 0 && overlayHeight > 0 && (
+ <div className="pointer-events-auto absolute inset-0 z-[9]">
+ <Stage width={containerWidth} height={overlayHeight} listening>
+ <Layer>
+ {pageBalloons.map((balloon) => {
+ // DB coordinates are normalized 0–1.
+ const x = balloon.xCoordinate * containerWidth;
+ const y = balloon.yCoordinate * overlayHeight;
+ const isActive =
+ balloon.inspectionFeatureId === activeFeatureId;
+ return (
+ <Group
+ key={balloon.id}
+ onClick={() =>
+ onBalloonClick(balloon.inspectionFeatureId)
+ }
+ onTap={() =>
+ onBalloonClick(balloon.inspectionFeatureId)
+ }
+ onMouseEnter={(e) => {
+ const stage = e.target.getStage();
+ if (stage) stage.container().style.cursor = "pointer";
+ }}
+ onMouseLeave={(e) => {
+ const stage = e.target.getStage();
+ if (stage) stage.container().style.cursor = "";
+ }}
+ >
+ <Circle
+ x={x}
+ y={y}
+ radius={balloonRadius}
+ stroke={CALLOUT_STROKE}
+ strokeWidth={isActive ? 3 : 2}
+ fill={
+ isActive
+ ? "rgba(249,115,22,0.25)"
+ : "rgba(255,255,255,0.75)"
+ }
+ />
+ <Text
+ x={x - balloonRadius}
+ y={y - balloonRadius * 0.55}
+ width={balloonRadius * 2}
+ align="center"
+ text={balloon.label}
+ fontSize={balloonRadius}
+ fontStyle="bold"
+ fill={CALLOUT_STROKE}
+ listening={false}
+ />
+ </Group>
+ );
+ })}
+ </Layer>
+ </Stage>
+ </div>
+ )}
+ </div>
+ </div>
+ {pdfUrl === "" && (
+ <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
+ No drawing available
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default InspectionDrawingPane;
diff --git a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionForm.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionForm.tsx
similarity index 94%
rename from apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionForm.tsx
rename to apps/erp/app/modules/quality/ui/Inspections/InspectionForm.tsx
index 8df4c8a251..33c7c4c723 100644
--- a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionForm.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionForm.tsx
@@ -19,9 +19,9 @@ import { LuTriangleAlert } from "react-icons/lu";
import { useFetcher } from "react-router";
import { Hidden, Select, Submit, TextArea } from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { inboundInspectionValidator } from "~/modules/quality/quality.models";
+import { inspectionValidator } from "~/modules/quality/quality.models";
-type InboundInspectionFormProps = {
+type InspectionFormProps = {
inspectionId: string;
itemReadableId: string;
itemName: string;
@@ -36,7 +36,7 @@ type InboundInspectionFormProps = {
onClose: () => void;
};
-const InboundInspectionForm = ({
+const InspectionForm = ({
inspectionId,
itemReadableId,
itemName,
@@ -49,7 +49,7 @@ const InboundInspectionForm = ({
open = true,
action,
onClose
-}: InboundInspectionFormProps) => {
+}: InspectionFormProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const fetcher = useFetcher<{}>();
@@ -76,7 +76,7 @@ const InboundInspectionForm = ({
<ValidatedForm
method="post"
action={action}
- validator={inboundInspectionValidator}
+ validator={inspectionValidator}
defaultValues={{
id: inspectionId,
status: undefined,
@@ -157,4 +157,4 @@ const InboundInspectionForm = ({
);
};
-export default InboundInspectionForm;
+export default InspectionForm;
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionMeasurementGrid.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionMeasurementGrid.tsx
new file mode 100644
index 0000000000..f7c33430d0
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionMeasurementGrid.tsx
@@ -0,0 +1,761 @@
+import { Badge, cn, toast } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import type { PostgrestSingleResponse } from "@supabase/supabase-js";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { LuCheck, LuX } from "react-icons/lu";
+import { Table } from "~/components";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+import { EditableNumber } from "~/components/Editable";
+import type {
+ InspectionMeasurement,
+ InspectionSample,
+ InspectionSamplingPlan
+} from "~/modules/quality/types";
+import { path } from "~/utils/path";
+
+// A cell save's response payload (the measurement action returns it so the
+// grid can update without a revalidation roundtrip).
+export type MeasurementSaveResult = {
+ sampleId: string;
+ measurementId: string;
+ measurementStatus: "Pending" | "Passed" | "Failed";
+ sampleStatus: "Pending" | "Passed" | "Failed";
+ inspectionFeatureId: string;
+ columnIndex: number;
+ value: number | null;
+ passed: boolean | null;
+};
+
+type FeatureGridRow = {
+ featureId: string;
+ label: string;
+ description: string | null;
+ pageNumber: number;
+ isNumeric: boolean;
+ specLabel: string;
+ sampleSize: number;
+ acceptanceNumber: number;
+ rejectionNumber: number;
+} & Record<string, unknown>;
+
+type InspectionMeasurementGridProps = {
+ inspectionId: string;
+ isReadOnly: boolean;
+ isSerial: boolean;
+ features: InspectionSamplingPlan[];
+ samples: InspectionSample[];
+ measurements: InspectionMeasurement[];
+ maxSampleSize: number;
+ // Lot size caps how many sample columns can exist — a feature's n is the
+ // required minimum, but the inspector may record up to the whole lot.
+ lotSize: number;
+ // Lot-level acceptance/rejection numbers, used only for the synthetic
+ // "Overall result" row shown when the lot has no inspection-document features.
+ lotAcceptanceNumber: number;
+ lotRejectionNumber: number;
+ activeFeatureId: string | null;
+ onActiveFeatureChange: (id: string | null) => void;
+ onMeasurementSaved: (result: MeasurementSaveResult) => void;
+ // Rendered in the Table header (e.g. the collapse/expand toggle when the
+ // grid is the bottom panel of the execution view).
+ primaryAction?: React.ReactNode;
+};
+
+const sampleKey = (columnIndex: number) => `sample-${columnIndex}`;
+
+// Synthetic feature id for the single pass/fail row shown when the lot has no
+// inspection document. Its cells write the sample's status directly (via the
+// sample route) rather than a per-feature measurement.
+const OVERALL_ROW_ID = "__overall__";
+
+function parseSpecNumber(value: string | null | undefined): number | null {
+ if (value == null) return null;
+ const trimmed = value.trim();
+ if (trimmed === "") return null;
+ const parsed = Number(trimmed.replace(/^\+/, ""));
+ return Number.isNaN(parsed) ? null : parsed;
+}
+
+// Features x samples measurement grid (1factory "Spreadsheet View"). Built on
+// the shared Table's inline-editing machinery — the same pattern as
+// InventoryCountLines, with N editable sample columns instead of one.
+const InspectionMeasurementGrid = ({
+ inspectionId,
+ isReadOnly,
+ isSerial,
+ features,
+ samples,
+ measurements,
+ maxSampleSize,
+ lotSize,
+ lotAcceptanceNumber,
+ lotRejectionNumber,
+ activeFeatureId,
+ onActiveFeatureChange,
+ onMeasurementSaved,
+ primaryAction
+}: InspectionMeasurementGridProps) => {
+ const { t } = useLingui();
+
+ // Grid ignores plan rows whose live feature was deleted from the document.
+ const liveFeatures = useMemo(
+ () =>
+ features
+ .filter((f) => f.inspectionFeature != null)
+ .sort((a, b) => {
+ const fa = a.inspectionFeature!;
+ const fb = b.inspectionFeature!;
+ return (
+ (fa.pageNumber ?? 1) - (fb.pageNumber ?? 1) ||
+ fa.label.localeCompare(fb.label, undefined, { numeric: true })
+ );
+ }),
+ [features]
+ );
+
+ // Lots without an inspection document have no features to measure, so
+ // the grid collapses to a single "Overall result" pass/fail row per sample.
+ const hasFeatures = liveFeatures.length > 0;
+
+ // Column model: serial lots get one column per scanned sample; non-serial
+ // lots pre-create columns up to the max required n plus one spare, growing
+ // as columns are used, capped at the lot size (sample rows are created
+ // server-side on the first measurement into a column). n is a minimum —
+ // recording MORE than n samples is always allowed, up to the full lot.
+ const columnCount = isSerial
+ ? samples.length
+ : Math.min(lotSize, Math.max(maxSampleSize, samples.length + 1));
+
+ // Column index -> sample id. Anonymous columns resolve lazily from save
+ // responses; keyed by index because unsaved columns have no id yet.
+ const [sampleIdByColumn, setSampleIdByColumn] = useState<
+ Record<number, string>
+ >({});
+ useEffect(() => {
+ setSampleIdByColumn((prev) => {
+ const next = { ...prev };
+ samples.forEach((sample, index) => {
+ next[index] = sample.id;
+ });
+ return next;
+ });
+ }, [samples]);
+
+ // Measurement status + value per cell, seeded from the loader and patched by
+ // save responses (per-cell saves are quiet — no revalidation). The value
+ // mirror matters because the rows memo rebuilds from loader data on every
+ // local-state change, which would otherwise discard the Table's in-place
+ // patch and blank the cell until a reload.
+ const [statusByCell, setStatusByCell] = useState<Record<string, string>>({});
+ const [valueByCell, setValueByCell] = useState<Record<string, number | null>>(
+ {}
+ );
+ const measurementFor = useCallback(
+ (sampleId: string | undefined, featureId: string) =>
+ sampleId
+ ? measurements.find(
+ (m) =>
+ m.inspectionSampleId === sampleId &&
+ m.inspectionFeatureId === featureId
+ )
+ : undefined,
+ [measurements]
+ );
+ const cellStatus = useCallback(
+ (columnIndex: number, featureId: string): string | undefined => {
+ const override = statusByCell[`${columnIndex}:${featureId}`];
+ if (override) return override;
+ // The "Overall result" row has no measurement — its verdict is the
+ // sample's own status (Pending shows as an untoggled cell).
+ if (featureId === OVERALL_ROW_ID) {
+ return samples[columnIndex]?.status;
+ }
+ return measurementFor(sampleIdByColumn[columnIndex], featureId)?.status;
+ },
+ [statusByCell, sampleIdByColumn, measurementFor, samples]
+ );
+
+ // Document-driven cell: record a per-feature measurement.
+ const persistMeasurement = useCallback(
+ async (
+ row: FeatureGridRow,
+ columnIndex: number,
+ payload: { value?: string; passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ const formData = new FormData();
+ formData.set("inspectionId", inspectionId);
+ const sampleId = sampleIdByColumn[columnIndex];
+ if (sampleId) formData.set("sampleId", sampleId);
+ formData.set("inspectionFeatureId", row.featureId);
+ if (payload.value !== undefined) formData.set("value", payload.value);
+ if (payload.passed !== undefined) formData.set("passed", payload.passed);
+
+ const response = await fetch(
+ path.to.inspectionMeasurement(inspectionId),
+ { method: "post", body: formData }
+ );
+ const body = (await response.json().catch(() => null)) as {
+ data?: {
+ sampleId: string;
+ measurementId: string;
+ measurementStatus: string;
+ sampleStatus: string;
+ } | null;
+ error?: { message: string } | null;
+ } | null;
+
+ if (!response.ok || !body?.data || body.error) {
+ toast.error(body?.error?.message ?? t`Failed to save measurement`);
+ return null;
+ }
+
+ return {
+ sampleId: body.data.sampleId,
+ measurementId: body.data.measurementId,
+ measurementStatus: body.data
+ .measurementStatus as MeasurementSaveResult["measurementStatus"],
+ sampleStatus: body.data
+ .sampleStatus as MeasurementSaveResult["sampleStatus"],
+ inspectionFeatureId: row.featureId,
+ columnIndex,
+ value:
+ payload.value !== undefined && payload.value !== ""
+ ? Number(payload.value)
+ : null,
+ passed: payload.passed !== undefined ? payload.passed === "true" : null
+ };
+ },
+ [inspectionId, sampleIdByColumn, t]
+ );
+
+ // No-document cell: set the sample's Pass/Fail status directly. Serial
+ // columns already carry a scanned tracked entity (upsert by it); anonymous
+ // columns update in place by sampleId once one exists.
+ const persistOverall = useCallback(
+ async (
+ columnIndex: number,
+ payload: { passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ const status = payload.passed === "true" ? "Passed" : "Failed";
+ const formData = new FormData();
+ formData.set("inspectionId", inspectionId);
+ formData.set("status", status);
+ formData.set("quiet", "true");
+ const sampleId = sampleIdByColumn[columnIndex];
+ if (sampleId) formData.set("sampleId", sampleId);
+ const trackedEntityId = samples[columnIndex]?.trackedEntityId;
+ if (trackedEntityId) formData.set("trackedEntityId", trackedEntityId);
+
+ const response = await fetch(
+ `${path.to.inspection(inspectionId)}/sample`,
+ { method: "post", body: formData }
+ );
+ const body = (await response.json().catch(() => null)) as {
+ sampleId?: string;
+ error?: { message: string } | null;
+ } | null;
+
+ if (!response.ok || !body?.sampleId || body.error) {
+ toast.error(body?.error?.message ?? t`Failed to save result`);
+ return null;
+ }
+
+ return {
+ sampleId: body.sampleId,
+ measurementId: "",
+ measurementStatus: status,
+ sampleStatus: status,
+ inspectionFeatureId: OVERALL_ROW_ID,
+ columnIndex,
+ value: null,
+ passed: status === "Passed"
+ };
+ },
+ [inspectionId, sampleIdByColumn, samples, t]
+ );
+
+ const persistCell = useCallback(
+ async (
+ row: FeatureGridRow,
+ columnIndex: number,
+ payload: { value?: string; passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ // The "Overall result" row (no-document lots) sets the sample's status
+ // directly through the sample route instead of recording a measurement.
+ const result =
+ row.featureId === OVERALL_ROW_ID
+ ? await persistOverall(columnIndex, payload)
+ : await persistMeasurement(row, columnIndex, payload);
+ if (!result) return null;
+
+ setSampleIdByColumn((prev) =>
+ prev[columnIndex] === result.sampleId
+ ? prev
+ : { ...prev, [columnIndex]: result.sampleId }
+ );
+ setStatusByCell((prev) => ({
+ ...prev,
+ [`${columnIndex}:${row.featureId}`]: result.measurementStatus
+ }));
+ setValueByCell((prev) => ({
+ ...prev,
+ [`${columnIndex}:${row.featureId}`]: result.value
+ }));
+ onMeasurementSaved(result);
+ return result;
+ },
+ [persistMeasurement, persistOverall, onMeasurementSaved]
+ );
+
+ // EditableNumber-compatible mutation for numeric cells.
+ const onCellEdit = useCallback(
+ async (
+ accessorKey: string,
+ value: unknown,
+ row: FeatureGridRow
+ ): Promise<PostgrestSingleResponse<unknown>> => {
+ const columnIndex = Number(accessorKey.replace("sample-", ""));
+ const result = await persistCell(row, columnIndex, {
+ value: value === "" || value == null ? "" : String(value)
+ });
+ return {
+ data: null,
+ error: result ? null : { message: t`Failed to save measurement` }
+ } as unknown as PostgrestSingleResponse<unknown>;
+ },
+ [persistCell, t]
+ );
+
+ const rows = useMemo<FeatureGridRow[]>(() => {
+ if (!hasFeatures) {
+ // Single synthetic pass/fail row for lots with no inspection document.
+ return [
+ {
+ featureId: OVERALL_ROW_ID,
+ label: "1",
+ description: t`Overall result`,
+ pageNumber: 1,
+ isNumeric: false,
+ specLabel: "",
+ sampleSize: maxSampleSize,
+ acceptanceNumber: lotAcceptanceNumber,
+ rejectionNumber: lotRejectionNumber
+ }
+ ];
+ }
+ return liveFeatures.map((lotFeature) => {
+ const feature = lotFeature.inspectionFeature!;
+ const isNumeric =
+ feature.type === "Measurement" &&
+ parseSpecNumber(feature.nominalValue) !== null;
+ const spec = isNumeric
+ ? [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ")
+ : (feature.nominalValue ?? "");
+
+ const row: FeatureGridRow = {
+ featureId: feature.id,
+ label: feature.label,
+ description: feature.description,
+ pageNumber: feature.pageNumber ?? 1,
+ isNumeric,
+ specLabel: spec,
+ sampleSize: lotFeature.sampleSize,
+ acceptanceNumber: lotFeature.acceptanceNumber,
+ rejectionNumber: lotFeature.rejectionNumber
+ };
+ for (let i = 0; i < columnCount; i++) {
+ const override = valueByCell[`${i}:${feature.id}`];
+ const measurement = measurementFor(sampleIdByColumn[i], feature.id);
+ row[sampleKey(i)] =
+ override !== undefined ? override : (measurement?.value ?? null);
+ }
+ return row;
+ });
+ }, [
+ hasFeatures,
+ liveFeatures,
+ columnCount,
+ sampleIdByColumn,
+ valueByCell,
+ measurementFor,
+ maxSampleSize,
+ lotAcceptanceNumber,
+ lotRejectionNumber,
+ t
+ ]);
+
+ // Pass/fail chip counts per feature (loader data + local overrides).
+ const featureCounts = useCallback(
+ (row: FeatureGridRow) => {
+ let passed = 0;
+ let failed = 0;
+ for (let i = 0; i < columnCount; i++) {
+ const status = cellStatus(i, row.featureId);
+ if (status === "Passed") passed += 1;
+ if (status === "Failed") failed += 1;
+ }
+ return { passed, failed, recorded: passed + failed };
+ },
+ [columnCount, cellStatus]
+ );
+
+ // Attribute pass/fail: a segmented, color-coded toggle. Each half is a
+ // full-height tap target (shop-floor friendly), green ✓ pass / red ✗ fail,
+ // filled when selected and tinted on hover otherwise. Shared by the display
+ // cell AND the editable cell so opening a cell (keyboard nav / focus) keeps
+ // the same buttons on screen instead of swapping them for an empty editor.
+ const renderPassFail = useCallback(
+ (original: FeatureGridRow, i: number) => {
+ const status = cellStatus(i, original.featureId);
+ const passed = status === "Passed";
+ const failed = status === "Failed";
+ return (
+ <div
+ data-sample-col={i}
+ className="-mx-4 -my-2 flex justify-center px-1.5 py-1"
+ >
+ {/* Negative margins cancel the cell's px-4 py-2 so the segmented
+ control fills the full cell for a large, finger-friendly target;
+ a shared divider splits pass / fail. */}
+ <div className="flex h-10 w-full min-w-[92px] max-w-[152px] items-stretch overflow-hidden rounded-lg border border-border bg-background">
+ <button
+ type="button"
+ aria-label={t`Pass`}
+ aria-pressed={passed}
+ disabled={isReadOnly}
+ tabIndex={-1}
+ onClick={(e) => {
+ e.stopPropagation();
+ persistCell(original, i, { passed: "true" });
+ }}
+ className={cn(
+ "flex flex-1 items-center justify-center transition-transform active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50",
+ passed
+ ? "bg-emerald-500 text-white"
+ : "text-muted-foreground hover:bg-emerald-500/10 hover:text-emerald-600"
+ )}
+ >
+ <LuCheck className="h-5 w-5" />
+ </button>
+ <button
+ type="button"
+ aria-label={t`Fail`}
+ aria-pressed={failed}
+ disabled={isReadOnly}
+ tabIndex={-1}
+ onClick={(e) => {
+ e.stopPropagation();
+ persistCell(original, i, { passed: "false" });
+ }}
+ className={cn(
+ "flex flex-1 items-center justify-center border-l border-border transition-transform active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50",
+ failed
+ ? "bg-red-500 text-white"
+ : "text-muted-foreground hover:bg-red-500/10 hover:text-red-600"
+ )}
+ >
+ <LuX className="h-5 w-5" />
+ </button>
+ </div>
+ </div>
+ );
+ },
+ [cellStatus, isReadOnly, persistCell, t]
+ );
+
+ const columns = useMemo<ColumnDef<FeatureGridRow>[]>(() => {
+ const cols: ColumnDef<FeatureGridRow>[] = [
+ {
+ accessorKey: "label",
+ header: "#",
+ cell: ({ row }) => (
+ <span className="font-mono text-xs font-semibold">
+ {row.original.label}
+ </span>
+ )
+ },
+ {
+ accessorKey: "description",
+ header: t`Feature`,
+ cell: ({ row }) => (
+ <span
+ className="line-clamp-2 max-w-[180px] text-xs"
+ title={row.original.description ?? undefined}
+ >
+ {row.original.description ?? "—"}
+ </span>
+ )
+ },
+ {
+ accessorKey: "specLabel",
+ header: t`Spec`,
+ cell: ({ row }) => (
+ <span className="whitespace-nowrap font-mono text-xs">
+ {row.original.specLabel || "—"}
+ </span>
+ )
+ },
+ {
+ accessorKey: "sampleSize",
+ header: "n / Ac",
+ cell: ({ row }) => (
+ <span className="whitespace-nowrap font-mono text-xs text-muted-foreground">
+ {row.original.sampleSize} / {row.original.acceptanceNumber}
+ </span>
+ )
+ },
+ {
+ id: "progress",
+ header: t`Result`,
+ cell: ({ row }) => {
+ const counts = featureCounts(row.original);
+ const exceeded = counts.failed >= row.original.rejectionNumber;
+ return (
+ <Badge
+ variant={
+ exceeded
+ ? "destructive"
+ : counts.recorded >= row.original.sampleSize &&
+ counts.failed <= row.original.acceptanceNumber
+ ? "green"
+ : "secondary"
+ }
+ className="font-mono text-[10px]"
+ >
+ {counts.passed}/{row.original.sampleSize}
+ {counts.failed > 0 ? ` · ${counts.failed}F` : ""}
+ </Badge>
+ );
+ }
+ }
+ ];
+
+ for (let i = 0; i < columnCount; i++) {
+ const key = sampleKey(i);
+ const sample = samples[i];
+ const header = isSerial
+ ? (sample?.trackedEntity?.readableId ?? `${i + 1}`)
+ : `${i + 1}`;
+ cols.push({
+ accessorKey: key,
+ header,
+ meta: { headerClassName: "justify-center" },
+ cell: ({ row }) => {
+ const original = row.original;
+ const status = cellStatus(i, original.featureId);
+ if (original.isNumeric) {
+ const value = original[key];
+ return (
+ <span
+ data-sample-col={i}
+ className={cn(
+ "block min-w-[48px] text-center font-mono text-xs tabular-nums",
+ status === "Failed" && "font-semibold text-red-500",
+ value == null && "text-muted-foreground/60"
+ )}
+ >
+ {value == null ? "—" : String(value)}
+ </span>
+ );
+ }
+ // Attribute pass/fail toggle — shared with the editable cell so
+ // focusing the cell keeps the buttons visible.
+ return renderPassFail(original, i);
+ }
+ });
+ }
+
+ return cols;
+ }, [
+ columnCount,
+ samples,
+ isSerial,
+ featureCounts,
+ cellStatus,
+ renderPassFail,
+ t
+ ]);
+
+ // Numeric sample cells edit through the shared Editable machinery; attribute
+ // cells render the SAME Pass/Fail control as the display cell, so opening a
+ // cell (single click, or keyboard nav that clicks the next cell) keeps the
+ // buttons on screen instead of swapping them for an empty placeholder.
+ const editableComponents = useMemo(() => {
+ const components: Record<
+ string,
+ (props: EditableTableCellComponentProps<FeatureGridRow>) => JSX.Element
+ > = {};
+ for (let i = 0; i < columnCount; i++) {
+ const key = sampleKey(i);
+ const numberEditor = EditableNumber<FeatureGridRow>(
+ onCellEdit,
+ // react-aria NumberField defaults to 3 fraction digits, which rounds
+ // fine measurements (e.g. thousandths/ten-thousandths of an inch) on
+ // blur. Allow up to 6 so precision readings persist intact.
+ { formatOptions: { maximumFractionDigits: 6 } },
+ {
+ clearable: true
+ }
+ );
+ components[key] = (props) => {
+ if (!props.row.isNumeric) {
+ // Attribute feature: keep the Pass/Fail toggle visible when focused.
+ return renderPassFail(props.row, i);
+ }
+ return numberEditor(props);
+ };
+ }
+ return components;
+ }, [columnCount, onCellEdit, renderPassFail]);
+
+ const gridRef = useRef<HTMLDivElement>(null);
+
+ // Balloon click direction: scroll the active feature's row into view.
+ useEffect(() => {
+ if (!activeFeatureId) return;
+ const index = rows.findIndex((r) => r.featureId === activeFeatureId);
+ if (index < 0) return;
+ gridRef.current
+ ?.querySelector(`[data-row="${index}"]`)
+ ?.scrollIntoView({ block: "nearest" });
+ }, [activeFeatureId, rows]);
+
+ // Spreadsheet-style entry across the sample columns: Enter/Tab advance to
+ // the next sample cell in the row, wrapping to the next row; Shift+Tab
+ // reverses. Adapted from InventoryCountLines' capture-phase model — sample
+ // columns are resolved live from the DOM via the `data-sample-col` markers.
+ const onGridKeyDownCapture = useCallback(
+ (event: React.KeyboardEvent) => {
+ if (isReadOnly) return;
+ if (event.key !== "Enter" && event.key !== "Tab") return;
+ const cell = (event.target as HTMLElement).closest<HTMLElement>(
+ "[data-row][data-column]"
+ );
+ if (!cell || !gridRef.current?.contains(cell)) return;
+
+ const rowIndex = Number(cell.getAttribute("data-row"));
+ const currentColumn = Number(cell.getAttribute("data-column"));
+
+ const sampleColumnsForRow = (r: number): number[] => {
+ const markers = gridRef.current?.querySelectorAll<HTMLElement>(
+ `[data-row="${r}"][data-column] [data-sample-col]`
+ );
+ const columnsSet = new Set<number>();
+ markers?.forEach((marker) => {
+ const column = marker
+ .closest<HTMLElement>("[data-column]")
+ ?.getAttribute("data-column");
+ if (column != null) columnsSet.add(Number(column));
+ });
+ return [...columnsSet].sort((a, b) => a - b);
+ };
+
+ // The cell currently being edited has its marker replaced by the editor —
+ // include it explicitly.
+ const columns = sampleColumnsForRow(rowIndex);
+ if (!columns.includes(currentColumn)) columns.push(currentColumn);
+ columns.sort((a, b) => a - b);
+ if (columns.length === 0) return;
+
+ const active = document.activeElement as HTMLElement | null;
+
+ // From a non-sample cell, jump into the row's first sample cell.
+ const position = columns.indexOf(currentColumn);
+ if (position < 0) {
+ event.preventDefault();
+ event.stopPropagation();
+ gridRef.current
+ ?.querySelector<HTMLElement>(
+ `[data-row="${rowIndex}"][data-column="${columns[0]}"]`
+ )
+ ?.click();
+ return;
+ }
+
+ const reverse = event.key === "Tab" && event.shiftKey;
+ let targetRow = rowIndex;
+ let targetColumn: number | undefined = reverse
+ ? columns[position - 1]
+ : columns[position + 1];
+
+ if (targetColumn === undefined) {
+ // Wrap to the adjacent row.
+ targetRow = rowIndex + (reverse ? -1 : 1);
+ const nextColumns = sampleColumnsForRow(targetRow);
+ targetColumn = reverse
+ ? nextColumns[nextColumns.length - 1]
+ : nextColumns[0];
+ }
+
+ const target =
+ targetColumn !== undefined
+ ? gridRef.current?.querySelector<HTMLElement>(
+ `[data-row="${targetRow}"][data-column="${targetColumn}"]`
+ )
+ : null;
+
+ // Let Tab exit the grid at the boundary rather than trapping focus.
+ if (event.key === "Tab" && !target) {
+ event.stopPropagation();
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ if (active?.tagName === "INPUT") active.blur(); // commit before moving
+ if (target) {
+ target.click();
+ } else {
+ cell.focus();
+ }
+ },
+ [isReadOnly]
+ );
+
+ return (
+ <div
+ ref={gridRef}
+ onKeyDownCapture={onGridKeyDownCapture}
+ onClickCapture={(event) => {
+ const cell = (event.target as HTMLElement).closest<HTMLElement>(
+ "[data-row][data-column]"
+ );
+ if (!cell) return;
+ const rowIndex = Number(cell.getAttribute("data-row"));
+ const featureId = rows[rowIndex]?.featureId;
+ if (featureId) onActiveFeatureChange(featureId);
+ }}
+ className="flex h-full min-h-0 w-full flex-col"
+ >
+ <Table<FeatureGridRow>
+ compact
+ columns={columns}
+ data={rows}
+ count={rows.length}
+ editableComponents={editableComponents}
+ getRowClassName={(row) =>
+ row.featureId === activeFeatureId ? "bg-accent/40" : undefined
+ }
+ titleBadge={
+ <span className="min-w-0 truncate text-sm font-medium text-foreground">
+ {hasFeatures ? `${t`Features`} (${rows.length})` : t`Result`}
+ </span>
+ }
+ primaryAction={primaryAction}
+ withInlineEditing={!isReadOnly}
+ forceEditMode={!isReadOnly}
+ />
+ </div>
+ );
+};
+
+export default InspectionMeasurementGrid;
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionStatus.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionStatus.tsx
new file mode 100644
index 0000000000..3bbbef18b8
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionStatus.tsx
@@ -0,0 +1,18 @@
+import { Badge } from "@carbon/react";
+
+export function getInspectionStatusVariant(status: string) {
+ if (status === "Passed") return "green";
+ if (status === "Failed") return "red";
+ if (status === "Partial") return "yellow";
+ if (status === "In Progress") return "blue";
+ return "secondary";
+}
+
+type InspectionStatusProps = {
+ status?: string | null;
+};
+
+export function InspectionStatus({ status }: InspectionStatusProps) {
+ if (!status) return null;
+ return <Badge variant={getInspectionStatusVariant(status)}>{status}</Badge>;
+}
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
new file mode 100644
index 0000000000..c45a6bde47
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
@@ -0,0 +1,854 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Badge,
+ Button,
+ ClientOnly,
+ HStack,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Spinner,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import {
+ lazy,
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import {
+ LuChevronDown,
+ LuChevronUp,
+ LuFileText,
+ LuScan,
+ LuShieldAlert,
+ LuTriangleAlert
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Confirm } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type {
+ InspectionMeasurement,
+ InspectionRow,
+ InspectionSample,
+ InspectionSamplingPlan,
+ InspectionTrackedEntity,
+ IssueTypeListItem
+} from "~/modules/quality/types";
+import { useItems } from "~/stores/items";
+import { path } from "~/utils/path";
+import { getReadableIdWithRevision } from "~/utils/string";
+import type { DrawingBalloon } from "./InspectionDrawingPane";
+import type { MeasurementSaveResult } from "./InspectionMeasurementGrid";
+import InspectionMeasurementGrid from "./InspectionMeasurementGrid";
+import type { FailedFeatureSummary } from "./RejectLotModal";
+import RejectLotModal from "./RejectLotModal";
+import ScanInspectionSample from "./ScanInspectionSample";
+
+const InspectionDrawingPane = lazy(() => import("./InspectionDrawingPane"));
+
+// Vertical-stack sizing, mirrored from InspectionDocumentEditor: the PDF pane
+// keeps a pinned height while the features grid is expanded; a draggable
+// splitter trades space between them.
+const STACK_SPLITTER_H = 8;
+const MIN_PDF_PANE_PX = 160;
+
+/** When the grid is expanded it keeps at least half the stack; PDF height is capped accordingly. */
+function clampPdfPaneHeight(
+ pdfPx: number,
+ stackH: number,
+ gridExpanded: boolean
+): number {
+ if (!gridExpanded || stackH <= STACK_SPLITTER_H + MIN_PDF_PANE_PX) {
+ return Math.max(MIN_PDF_PANE_PX, pdfPx);
+ }
+ const minGrid = stackH * 0.5;
+ const maxPdf = Math.max(MIN_PDF_PANE_PX, stackH - STACK_SPLITTER_H - minGrid);
+ return Math.min(maxPdf, Math.max(MIN_PDF_PANE_PX, pdfPx));
+}
+
+export type InspectionViewProps = {
+ inspection: InspectionRow;
+ sourceDocumentReadableId: string | null;
+ receiverId: string | null;
+ itemName: string;
+ itemTrackingType: string | null;
+ supplierName: string | null;
+ samples: InspectionSample[];
+ features: InspectionSamplingPlan[];
+ measurements: InspectionMeasurement[];
+ balloons: {
+ id: string;
+ inspectionFeatureId: string;
+ pageNumber: number;
+ xCoordinate: number;
+ yCoordinate: number;
+ }[];
+ documentName: string | null;
+ pdfUrl: string | null;
+ lotEntities: InspectionTrackedEntity[];
+ issueTypes: IssueTypeListItem[];
+ currentUserId: string;
+ enforceFourEyes: boolean;
+};
+
+// Full-screen inbound inspection execution view. One UI for every lot: the
+// measurement grid, with a ballooned drawing above it when the lot has a PDF and
+// a single "Overall result" pass/fail row when the document resolved no
+// features. Serial lots build their sample columns by scanning tracked entities.
+// Reusable as a data-prop component (AssemblyView pattern) so MES can consume it.
+const InspectionView = ({
+ inspection,
+ sourceDocumentReadableId,
+ receiverId,
+ itemName,
+ itemTrackingType,
+ supplierName,
+ samples,
+ features,
+ measurements,
+ balloons,
+ documentName,
+ pdfUrl,
+ lotEntities,
+ issueTypes,
+ currentUserId,
+ enforceFourEyes
+}: InspectionViewProps) => {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const canUpdate = permissions.can("update", "quality");
+ const [items] = useItems();
+
+ const isSerial = itemTrackingType === "Serial";
+ // Accept/Reject dispositions here carry no physical production posting, so they
+ // are Receipt-only. Job Operation lots are verdict-only in the ERP — their
+ // complete/scrap/rework outcome is orchestrated by the MES disposition route
+ // (which closes the lot one-shot). Exposing Accept/Reject on a job-op lot would
+ // hard-terminate it with no posting and wedge the operation.
+ const isReceiptSource = inspection.sourceDocument === "Receipt";
+ const liveFeatures = useMemo(
+ () => features.filter((f) => f.inspectionFeature != null),
+ [features]
+ );
+ // The measurement grid is the single execution UI. A drawing pane shows when
+ // 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 hasFeatures = liveFeatures.length > 0;
+
+ const scannerDisclosure = useDisclosure();
+ const rejectConfirmDisclosure = useDisclosure();
+ const acceptConfirmDisclosure = useDisclosure();
+ const documentSwitchDisclosure = useDisclosure();
+
+ const [activeFeatureId, setActiveFeatureId] = useState<string | null>(null);
+
+ // PDF-over-grid stack (InspectionDocumentEditor's layout model).
+ const [gridExpanded, setGridExpanded] = useState(true);
+ const [pdfPaneHeightPx, setPdfPaneHeightPx] = useState(360);
+ const [stackHeightPx, setStackHeightPx] = useState(0);
+ const [isResizingSplit, setIsResizingSplit] = useState(false);
+ const splitDragRef = useRef<{ startY: number; startPdfPx: number } | null>(
+ null
+ );
+ // Until the user drags the splitter, the PDF takes ~45% of the measured
+ // stack (capped by the grid's half-stack minimum) instead of a fixed pixel
+ // default — portrait drawings get a usable slice on tall viewports.
+ const hasUserResizedRef = useRef(false);
+ const stackRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!stackRef.current) return;
+ const el = stackRef.current;
+ const ro = new ResizeObserver(() => {
+ const h = el.clientHeight;
+ setStackHeightPx(h);
+ setPdfPaneHeightPx((prev) =>
+ clampPdfPaneHeight(
+ hasUserResizedRef.current ? prev : h * 0.45,
+ h,
+ gridExpanded
+ )
+ );
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [gridExpanded]);
+
+ useEffect(() => {
+ if (!isResizingSplit) return;
+ const onMove = (e: MouseEvent) => {
+ const start = splitDragRef.current;
+ if (!start) return;
+ const dy = e.clientY - start.startY;
+ setPdfPaneHeightPx(
+ clampPdfPaneHeight(start.startPdfPx + dy, stackHeightPx, gridExpanded)
+ );
+ };
+ const onUp = () => {
+ setIsResizingSplit(false);
+ splitDragRef.current = null;
+ };
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", onUp);
+ return () => {
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", onUp);
+ };
+ }, [isResizingSplit, stackHeightPx, gridExpanded]);
+
+ const onSplitResizeMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ if (!gridExpanded) return;
+ e.preventDefault();
+ hasUserResizedRef.current = true;
+ splitDragRef.current = {
+ startY: e.clientY,
+ startPdfPx: pdfPaneHeightPx
+ };
+ setIsResizingSplit(true);
+ },
+ [gridExpanded, pdfPaneHeightPx]
+ );
+
+ // Per-cell saves are quiet (no revalidation), so measurement + derived
+ // sample statuses are mirrored locally from the save responses and merged
+ // with the loader data for gating.
+ const [measurementOverrides, setMeasurementOverrides] = useState<
+ Record<string, "Pending" | "Passed" | "Failed">
+ >({});
+ const [sampleStatusOverrides, setSampleStatusOverrides] = useState<
+ Record<string, "Pending" | "Passed" | "Failed">
+ >({});
+ const [measurementValueOverrides, setMeasurementValueOverrides] = useState<
+ Record<string, number | null>
+ >({});
+ const onMeasurementSaved = useCallback((result: MeasurementSaveResult) => {
+ const key = `${result.sampleId}:${result.inspectionFeatureId}`;
+ setMeasurementOverrides((prev) => ({
+ ...prev,
+ [key]: result.measurementStatus
+ }));
+ setMeasurementValueOverrides((prev) => ({ ...prev, [key]: result.value }));
+ setSampleStatusOverrides((prev) => ({
+ ...prev,
+ [result.sampleId]: result.sampleStatus
+ }));
+ }, []);
+
+ // Effective measurement statuses: loader data + local overrides (new cells
+ // exist only in overrides).
+ const effectiveMeasurements = useMemo(() => {
+ const byKey = new Map<
+ string,
+ { featureId: string; status: string; value: number | null }
+ >();
+ for (const m of measurements) {
+ byKey.set(`${m.inspectionSampleId}:${m.inspectionFeatureId}`, {
+ featureId: m.inspectionFeatureId,
+ status: m.status,
+ value: m.value == null ? null : Number(m.value)
+ });
+ }
+ for (const [key, status] of Object.entries(measurementOverrides)) {
+ const featureId = key.split(":")[1] ?? "";
+ byKey.set(key, {
+ featureId,
+ status,
+ value: measurementValueOverrides[key] ?? null
+ });
+ }
+ return byKey;
+ }, [measurements, measurementOverrides, measurementValueOverrides]);
+
+ const featureCounts = useMemo(() => {
+ const counts = new Map<string, { recorded: number; failed: number }>();
+ for (const feature of liveFeatures) {
+ counts.set(feature.inspectionFeatureId, { recorded: 0, failed: 0 });
+ }
+ for (const measurement of effectiveMeasurements.values()) {
+ const entry = counts.get(measurement.featureId);
+ if (!entry) continue;
+ if (measurement.status !== "Pending") entry.recorded += 1;
+ if (measurement.status === "Failed") entry.failed += 1;
+ }
+ return counts;
+ }, [liveFeatures, effectiveMeasurements]);
+
+ // Effective sample statuses: loader samples + derived-status overrides +
+ // anonymous samples created during this session (only in overrides).
+ const sampleStatuses = useMemo(() => {
+ const statuses = new Map<string, string>();
+ for (const sample of samples) {
+ statuses.set(sample.id, sample.status);
+ }
+ for (const [sampleId, status] of Object.entries(sampleStatusOverrides)) {
+ statuses.set(sampleId, status);
+ }
+ return statuses;
+ }, [samples, sampleStatusOverrides]);
+
+ const passes = [...sampleStatuses.values()].filter(
+ (s) => s === "Passed"
+ ).length;
+ const fails = [...sampleStatuses.values()].filter(
+ (s) => s === "Failed"
+ ).length;
+ const inspected = passes + fails;
+
+ const sampledIds = useMemo(
+ () => new Set(samples.map((s) => s.trackedEntityId)),
+ [samples]
+ );
+ const remaining = lotEntities.filter((e) => !sampledIds.has(e.id));
+
+ // Item display id from the live items store (snapshot may be stale).
+ const item = items.find((i) => i.id === inspection.itemId);
+ const [storeReadableId, storeRevision] = (() => {
+ const combined = (item as any)?.readableIdWithRevision as
+ | string
+ | undefined;
+ if (!combined) return [undefined, undefined] as const;
+ const dot = combined.lastIndexOf(".");
+ if (dot < 0) return [combined, undefined] as const;
+ return [combined.slice(0, dot), combined.slice(dot + 1)] as const;
+ })();
+ const displayReadableId =
+ storeReadableId != null
+ ? getReadableIdWithRevision(storeReadableId, storeRevision)
+ : (inspection.itemReadableId ?? "");
+ const displayItemName = item?.name ?? itemName;
+
+ const showFourEyesWarning =
+ enforceFourEyes && !!receiverId && receiverId === currentUserId;
+
+ const lotClosed =
+ inspection.dispositionedAt != null &&
+ (inspection.status === "Passed" || inspection.status === "Failed");
+
+ // Serial lots build their sample columns by scanning tracked entities. The
+ // header "Add Sample" button stays primary until the plan's sample size is
+ // covered; a fresh serial lot auto-opens the scanner so the first scan is one
+ // tap away.
+ const allSamplesLoaded = samples.length >= inspection.sampleSize;
+ const hasAutoOpenedScanRef = useRef(false);
+ useEffect(() => {
+ if (hasAutoOpenedScanRef.current) return;
+ if (isSerial && samples.length === 0 && !lotClosed && canUpdate) {
+ hasAutoOpenedScanRef.current = true;
+ scannerDisclosure.onOpen();
+ }
+ }, [isSerial, samples.length, lotClosed, canUpdate, scannerDisclosure]);
+
+ const maxSampleSize = hasFeatures
+ ? Math.max(1, ...liveFeatures.map((f) => f.sampleSize))
+ : inspection.sampleSize;
+
+ // Gating. Feature-driven lots gate per feature (mirrors the
+ // server-side disposition guards); lots without features gate at the lot
+ // level on the "Overall result" pass/fail counts.
+ let canAccept: boolean;
+ let canReject: boolean;
+ if (hasFeatures) {
+ const allFeaturesSatisfied = liveFeatures.every((feature) => {
+ const counts = featureCounts.get(feature.inspectionFeatureId) ?? {
+ recorded: 0,
+ failed: 0
+ };
+ return (
+ counts.recorded >= feature.sampleSize &&
+ counts.failed <= feature.acceptanceNumber
+ );
+ });
+ const anyFeatureRejectable = liveFeatures.some((feature) => {
+ const counts = featureCounts.get(feature.inspectionFeatureId);
+ return counts != null && counts.failed >= feature.rejectionNumber;
+ });
+ canAccept = isReceiptSource && !lotClosed && allFeaturesSatisfied;
+ canReject =
+ isReceiptSource && !lotClosed && (anyFeatureRejectable || fails > 0);
+ } else {
+ canAccept =
+ isReceiptSource &&
+ !lotClosed &&
+ inspected >= inspection.sampleSize &&
+ fails <= inspection.acceptanceNumber;
+ canReject =
+ isReceiptSource && !lotClosed && fails > inspection.acceptanceNumber;
+ }
+
+ const failedFeatureSummary = useMemo<FailedFeatureSummary[]>(() => {
+ if (!hasFeatures) return [];
+ return liveFeatures
+ .map((lotFeature) => {
+ const feature = lotFeature.inspectionFeature!;
+ const failedValues: string[] = [];
+ for (const [key, m] of effectiveMeasurements.entries()) {
+ if (m.featureId !== feature.id || m.status !== "Failed") continue;
+ failedValues.push(m.value == null ? "F" : String(m.value));
+ void key;
+ }
+ if (failedValues.length === 0) return null;
+ const spec = [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ");
+ return { label: feature.label, spec, failedValues };
+ })
+ .filter(Boolean) as FailedFeatureSummary[];
+ }, [hasFeatures, liveFeatures, effectiveMeasurements]);
+
+ const failedTrackedEntityIds = samples
+ .filter((s) => (sampleStatuses.get(s.id) ?? s.status) === "Failed")
+ .map((s) => s.trackedEntityId)
+ .filter(Boolean) as string[];
+
+ const newIssueHref = `/x/issue/new?itemId=${encodeURIComponent(inspection.itemId)}&trackedEntityIds=${encodeURIComponent(failedTrackedEntityIds.join(","))}&sourceInspectionId=${encodeURIComponent(inspection.id)}`;
+
+ const drawingBalloons = useMemo<DrawingBalloon[]>(() => {
+ const labelByFeatureId = new Map(
+ liveFeatures.map((f) => [
+ f.inspectionFeatureId,
+ f.inspectionFeature!.label
+ ])
+ );
+ return balloons
+ .filter((b) => labelByFeatureId.has(b.inspectionFeatureId))
+ .map((b) => ({
+ id: b.id,
+ inspectionFeatureId: b.inspectionFeatureId,
+ pageNumber: b.pageNumber,
+ xCoordinate: b.xCoordinate,
+ yCoordinate: b.yCoordinate,
+ label: labelByFeatureId.get(b.inspectionFeatureId) ?? ""
+ }));
+ }, [balloons, liveFeatures]);
+
+ const hasMeasurements = effectiveMeasurements.size > 0;
+
+ const statusBadgeVariant =
+ inspection.status === "Passed"
+ ? ("green" as const)
+ : inspection.status === "Failed"
+ ? ("red" as const)
+ : ("secondary" as const);
+
+ const planSummary =
+ inspection.samplingPlanType === "AQL"
+ ? `AQL ${inspection.aql ?? ""} · Lvl ${inspection.inspectionLevel ?? ""} · ${inspection.severity ?? ""}`
+ : inspection.samplingPlanType;
+
+ const metaLine = [
+ `${displayReadableId} · ${displayItemName}`,
+ [sourceDocumentReadableId, supplierName].filter(Boolean).join(" — "),
+ planSummary,
+ `${inspected} / ${inspection.sampleSize} · Ac ${inspection.acceptanceNumber} · Re ${inspection.rejectionNumber}${inspection.codeLetter ? ` · ${inspection.codeLetter}` : ""}`,
+ documentName ?? null
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ {/* Header bar — mirrors InspectionDocumentEditor's header */}
+ <div className="flex min-h-[50px] flex-shrink-0 flex-wrap items-center justify-between gap-x-3 gap-y-2 overflow-x-auto border-b border-border bg-card px-4 py-2 scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
+ <div className="min-w-0 flex-1 pr-2">
+ <HStack spacing={2} className="items-center">
+ <h1 className="truncate text-base font-semibold">
+ {inspection.inspectionId}
+ </h1>
+ <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>
+ </HStack>
+ <p className="truncate text-xs text-muted-foreground">{metaLine}</p>
+ </div>
+ <HStack spacing={2} className="flex-shrink-0 flex-wrap justify-end">
+ <Button
+ variant="secondary"
+ leftIcon={<LuShieldAlert />}
+ asChild
+ isDisabled={failedTrackedEntityIds.length === 0}
+ >
+ <a href={newIssueHref} target="_blank" rel="noreferrer">
+ <Trans>Create Issue</Trans>
+ </a>
+ </Button>
+ {canUpdate && !lotClosed && !hasMeasurements && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuFileText />}
+ onClick={documentSwitchDisclosure.onOpen}
+ >
+ <Trans>Change Document</Trans>
+ </Button>
+ )}
+ {isSerial && !lotClosed && (
+ <Button
+ variant={allSamplesLoaded ? "secondary" : "primary"}
+ leftIcon={<LuScan />}
+ onClick={scannerDisclosure.onOpen}
+ isDisabled={!canUpdate}
+ >
+ <Trans>Add Sample</Trans>
+ </Button>
+ )}
+ {isReceiptSource && (
+ <>
+ <Button
+ variant="destructive"
+ onClick={rejectConfirmDisclosure.onOpen}
+ isDisabled={!canUpdate || !canReject}
+ >
+ <Trans>Reject Lot</Trans>
+ </Button>
+ <Button
+ onClick={acceptConfirmDisclosure.onOpen}
+ isDisabled={!canUpdate || !canAccept}
+ >
+ <Trans>Accept Lot</Trans>
+ </Button>
+ </>
+ )}
+ </HStack>
+ </div>
+
+ {showFourEyesWarning && (
+ <div className="shrink-0 px-4 pt-2">
+ <Alert variant="warning">
+ <LuTriangleAlert className="size-4" />
+ <AlertTitle>
+ <Trans>You received this lot</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ Company policy asks for a different person to inspect inbound
+ items than the one who received them.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ </div>
+ )}
+
+ {/* ── Body ── */}
+ {showDrawing ? (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">
+ <div
+ ref={stackRef}
+ className="flex min-h-0 flex-1 flex-col gap-0 overflow-hidden"
+ >
+ {/* PDF viewer — pinned height while the grid is expanded */}
+ <div
+ className={`flex min-h-0 min-w-full flex-col overflow-hidden rounded-lg border bg-muted ${
+ gridExpanded ? "shrink-0" : "min-h-[220px] flex-1"
+ }`}
+ style={{
+ ...(gridExpanded ? { height: pdfPaneHeightPx } : undefined),
+ minWidth: "100%"
+ }}
+ >
+ <ClientOnly
+ fallback={
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ }
+ >
+ {() => (
+ <Suspense
+ fallback={
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ }
+ >
+ <InspectionDrawingPane
+ pdfUrl={pdfUrl!}
+ balloons={drawingBalloons}
+ activeFeatureId={activeFeatureId}
+ onBalloonClick={setActiveFeatureId}
+ />
+ </Suspense>
+ )}
+ </ClientOnly>
+ </div>
+
+ {gridExpanded ? (
+ <div
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label={t`Drag to resize drawing and features`}
+ aria-valuenow={Math.round(pdfPaneHeightPx)}
+ className={`group flex h-2 shrink-0 cursor-row-resize touch-none items-center justify-center rounded-md px-2 hover:bg-muted/80 ${
+ isResizingSplit ? "bg-muted" : ""
+ }`}
+ onMouseDown={onSplitResizeMouseDown}
+ >
+ <span className="h-1 w-14 shrink-0 rounded-full bg-muted-foreground/40 group-hover:bg-muted-foreground/65" />
+ </div>
+ ) : null}
+
+ {/* Features grid — collapsible bottom panel */}
+ <div
+ className={
+ gridExpanded
+ ? "flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg bg-card"
+ : "flex max-h-[14rem] min-w-0 shrink-0 flex-col overflow-hidden rounded-lg bg-card"
+ }
+ style={
+ gridExpanded && stackHeightPx > 0
+ ? { minHeight: stackHeightPx * 0.5 }
+ : undefined
+ }
+ >
+ <div
+ className={
+ gridExpanded
+ ? "min-h-0 flex-1 overflow-auto"
+ : "overflow-hidden"
+ }
+ >
+ <InspectionMeasurementGrid
+ inspectionId={inspection.id}
+ isReadOnly={!canUpdate || lotClosed}
+ isSerial={isSerial}
+ features={features}
+ samples={samples}
+ measurements={measurements}
+ maxSampleSize={maxSampleSize}
+ lotSize={inspection.lotSize}
+ lotAcceptanceNumber={inspection.acceptanceNumber}
+ lotRejectionNumber={inspection.rejectionNumber}
+ activeFeatureId={activeFeatureId}
+ onActiveFeatureChange={setActiveFeatureId}
+ onMeasurementSaved={onMeasurementSaved}
+ primaryAction={
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-expanded={gridExpanded}
+ aria-label={
+ gridExpanded
+ ? t`Collapse features table`
+ : t`Expand features table`
+ }
+ icon={
+ gridExpanded ? (
+ <LuChevronDown className="h-4 w-4" />
+ ) : (
+ <LuChevronUp className="h-4 w-4" />
+ )
+ }
+ onClick={() => setGridExpanded((v) => !v)}
+ />
+ }
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ ) : (
+ // No drawing: the grid takes the full body. Feature-driven lots still
+ // render their features; lots without a document collapse to the
+ // single "Overall result" row inside the same grid.
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg bg-card">
+ <div className="min-h-0 flex-1 overflow-auto">
+ <InspectionMeasurementGrid
+ inspectionId={inspection.id}
+ isReadOnly={!canUpdate || lotClosed}
+ isSerial={isSerial}
+ features={features}
+ samples={samples}
+ measurements={measurements}
+ maxSampleSize={maxSampleSize}
+ lotSize={inspection.lotSize}
+ lotAcceptanceNumber={inspection.acceptanceNumber}
+ lotRejectionNumber={inspection.rejectionNumber}
+ activeFeatureId={activeFeatureId}
+ onActiveFeatureChange={setActiveFeatureId}
+ onMeasurementSaved={onMeasurementSaved}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ {scannerDisclosure.isOpen && (
+ <ScanInspectionSample
+ inspectionId={inspection.id}
+ isSerial={isSerial}
+ remaining={remaining}
+ inspected={inspected}
+ sampleSize={inspection.sampleSize}
+ fails={fails}
+ acceptanceNumber={inspection.acceptanceNumber}
+ onClose={scannerDisclosure.onClose}
+ />
+ )}
+
+ {acceptConfirmDisclosure.isOpen && (
+ <Confirm
+ action={path.to.inspectionAccept(inspection.id)}
+ title={t`Accept lot?`}
+ text={
+ isSerial
+ ? t`${lotEntities.length - inspected} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected.`
+ : t`The lot will be marked Passed. ${fails} sampled failure(s) are recorded for your records.`
+ }
+ confirmText={t`Accept Lot`}
+ onCancel={acceptConfirmDisclosure.onClose}
+ onSubmit={acceptConfirmDisclosure.onClose}
+ />
+ )}
+
+ {rejectConfirmDisclosure.isOpen && (
+ <RejectLotModal
+ action={path.to.inspectionReject(inspection.id)}
+ issueTypes={issueTypes}
+ summary={
+ isSerial
+ ? t`Statistical acceptance failed, so the entire lot is considered non-conforming (ISO 9001:2015 §8.7). All ${lotEntities.length} entities — ${passes} sampled pass(es), ${fails} failure(s), and ${Math.max(0, lotEntities.length - inspected)} un-inspected — will be marked Rejected.`
+ : t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s).`
+ }
+ failedFeatureSummary={failedFeatureSummary}
+ onCancel={rejectConfirmDisclosure.onClose}
+ onSubmit={rejectConfirmDisclosure.onClose}
+ />
+ )}
+
+ {documentSwitchDisclosure.isOpen && (
+ <DocumentSwitchModal
+ inspectionId={inspection.id}
+ itemId={inspection.itemId}
+ currentDocumentId={inspection.inspectionDocumentId ?? null}
+ onClose={documentSwitchDisclosure.onClose}
+ />
+ )}
+ </div>
+ );
+};
+
+// Swap the assigned inspection document on an open, unmeasured lot. Options
+// are the item's documents (same source as the Form/InspectionDocument
+// combobox's api route).
+function DocumentSwitchModal({
+ inspectionId,
+ itemId,
+ currentDocumentId,
+ onClose
+}: {
+ inspectionId: string;
+ itemId: string;
+ currentDocumentId: string | null;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{}>();
+ const optionsFetcher = useFetcher<{
+ data:
+ | {
+ id: string;
+ fileName: string | null;
+ drawingNumber: string | null;
+ version: number;
+ }[]
+ | null;
+ }>();
+ const [documentId, setDocumentId] = useState(currentDocumentId ?? "none");
+
+ useEffect(() => {
+ if (optionsFetcher.state === "idle" && optionsFetcher.data == null) {
+ optionsFetcher.load(path.to.api.inspectionDocuments(itemId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = optionsFetcher.data?.data ?? [];
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Change Inspection Plan</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={2}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ The lot's per-feature sampling plan will be re-resolved from the
+ selected document.
+ </Trans>
+ </p>
+ <Select value={documentId} onValueChange={setDocumentId}>
+ <SelectTrigger>
+ <SelectValue placeholder={t`Select a document`} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{t`None`}</SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {(option.drawingNumber ?? option.fileName ?? option.id) +
+ ` v${option.version}`}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <fetcher.Form
+ method="post"
+ action={path.to.inspectionAssignedDocument(inspectionId)}
+ onSubmit={onClose}
+ >
+ <input
+ type="hidden"
+ name="inspectionDocumentId"
+ value={documentId === "none" ? "" : documentId}
+ />
+ <Button type="submit" isLoading={fetcher.state !== "idle"}>
+ <Trans>Save</Trans>
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+export default InspectionView;
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
new file mode 100644
index 0000000000..89f74364a6
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
@@ -0,0 +1,191 @@
+import { Badge } from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
+import { useLingui } from "@lingui/react/macro";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import {
+ LuBlocks,
+ LuBookMarked,
+ LuCalendar,
+ LuClipboardCheck,
+ LuHash,
+ LuTruck
+} from "react-icons/lu";
+import { EmployeeAvatar, Hyperlink, Table } from "~/components";
+import { useDateFormatter, useUrlParams } from "~/hooks";
+import {
+ inspectionSourceDocuments,
+ inspectionStatusType
+} from "~/modules/quality/quality.models";
+import type { Inspection } from "~/modules/quality/types";
+import { useItems } from "~/stores/items";
+import { path } from "~/utils/path";
+import { getInspectionStatusVariant } from "./InspectionStatus";
+
+type InspectionsTableProps = {
+ data: Inspection[];
+ count: number;
+};
+
+function computeProgress(row: Inspection): {
+ inspected: number;
+ total: number;
+} {
+ // The list loader selects `inspectionSample(status)` as an array of
+ // child rows; count the non-Pending ones.
+ const samples: { status: string }[] =
+ ((row as any).inspectionSample as { status: string }[]) ?? [];
+ const inspected = samples.filter((s) => s.status !== "Pending").length;
+ return { inspected, total: (row as any).sampleSize ?? 0 };
+}
+
+const InspectionsTable = memo(({ data, count }: InspectionsTableProps) => {
+ const { t } = useLingui();
+ const { formatDate } = useDateFormatter();
+ const [params] = useUrlParams();
+ const [items] = useItems();
+
+ const columns = useMemo<ColumnDef<Inspection>[]>(() => {
+ return [
+ {
+ accessorKey: "inspectionId",
+ header: t`Inspection`,
+ cell: ({ row }) => (
+ <Hyperlink
+ to={`${path.to.inspection(row.original.id!)}?${params.toString()}`}
+ >
+ {(row.original as any).inspectionId}
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuBookMarked />
+ }
+ },
+ {
+ accessorKey: "itemId",
+ header: t`Item`,
+ cell: ({ row }) => (
+ <div className="flex flex-col gap-0">
+ <span className="text-sm font-medium">
+ {getItemReadableId(items, (row.original as any).itemId) ??
+ (row.original as any).itemReadableId ??
+ ""}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {(row.original as any).item?.name}
+ </span>
+ </div>
+ ),
+ meta: {
+ icon: <LuBookMarked />,
+ filter: {
+ type: "static",
+ options: items.map((item) => ({
+ value: item.id,
+ label: item.readableIdWithRevision
+ }))
+ }
+ }
+ },
+ {
+ accessorKey: "sourceDocument",
+ header: t`Source`,
+ cell: ({ row }) => (
+ <div className="flex flex-col gap-0 text-sm">
+ <span>
+ {(row.original as any).sourceDocumentReadableId ??
+ (row.original as any).sourceDocument}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {(row.original as any).supplier?.name ??
+ (row.original as any).sourceDocument}
+ </span>
+ </div>
+ ),
+ meta: {
+ icon: <LuTruck />,
+ filter: {
+ type: "static",
+ options: inspectionSourceDocuments.map((source) => ({
+ value: source,
+ label: source
+ }))
+ },
+ exportValue: (row) =>
+ (row as any).sourceDocumentReadableId ??
+ (row as any).sourceDocument ??
+ null
+ }
+ },
+ {
+ accessorKey: "lotSize",
+ header: t`Lot Size`,
+ cell: ({ row }) => (
+ <span className="text-sm">{(row.original as any).lotSize ?? 0}</span>
+ ),
+ meta: { icon: <LuBlocks /> }
+ },
+ {
+ accessorKey: "sampleSize",
+ header: t`Sample`,
+ cell: ({ row }) => {
+ const p = computeProgress(row.original);
+ return (
+ <span className="text-sm">
+ {p.inspected} / {p.total}
+ </span>
+ );
+ },
+ meta: { icon: <LuHash /> }
+ },
+ {
+ accessorKey: "status",
+ header: t`Status`,
+ cell: ({ row }) => (
+ <Badge variant={getInspectionStatusVariant(row.original.status)}>
+ {row.original.status}
+ </Badge>
+ ),
+ meta: {
+ icon: <LuClipboardCheck />,
+ filter: {
+ type: "static",
+ options: inspectionStatusType.map((s) => ({
+ value: s,
+ label: <Badge variant={getInspectionStatusVariant(s)}>{s}</Badge>
+ }))
+ }
+ }
+ },
+ {
+ accessorKey: "createdBy",
+ header: t`Received By`,
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: { icon: <LuBlocks /> }
+ },
+ {
+ accessorKey: "createdAt",
+ header: t`Received At`,
+ cell: ({ row }) =>
+ row.original.createdAt ? formatDate(row.original.createdAt) : "",
+ meta: { icon: <LuCalendar /> }
+ }
+ ];
+ }, [items, t, params, formatDate]);
+
+ return (
+ <Table<Inspection>
+ data={data}
+ columns={columns}
+ count={count ?? 0}
+ title={t`Inspections`}
+ table="inspection"
+ withSavedView
+ />
+ );
+});
+
+InspectionsTable.displayName = "InspectionsTable";
+export default InspectionsTable;
diff --git a/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx
new file mode 100644
index 0000000000..efacdfb8d0
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx
@@ -0,0 +1,189 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ Checkbox,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useRef, useState } from "react";
+import { LuTriangleAlert } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import type { IssueTypeListItem } from "~/modules/quality/types";
+
+export type FailedFeatureSummary = {
+ label: string;
+ spec: string;
+ failedValues: string[];
+};
+
+type RejectLotModalProps = {
+ action: string;
+ issueTypes: IssueTypeListItem[];
+ summary: string;
+ // Document-driven lots: the features that failed, previewed here and
+ // written into the NCR description by the reject action.
+ failedFeatureSummary?: FailedFeatureSummary[];
+ onCancel: () => void;
+ onSubmit: () => void;
+};
+
+const RejectLotModal = ({
+ action,
+ issueTypes,
+ summary,
+ failedFeatureSummary,
+ onCancel,
+ onSubmit
+}: RejectLotModalProps) => {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{}>();
+ const submitted = useRef(false);
+ const [createNcr, setCreateNcr] = useState(true);
+ const [issueTypeId, setIssueTypeId] = useState<string>(
+ issueTypes[0]?.id ?? ""
+ );
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && submitted.current) {
+ onSubmit();
+ submitted.current = false;
+ }
+ }, [fetcher.state, onSubmit]);
+
+ const hasIssueTypes = issueTypes.length > 0;
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onCancel();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Reject Lot</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">{summary}</p>
+ {failedFeatureSummary && failedFeatureSummary.length > 0 && (
+ <div className="w-full rounded-md border p-3">
+ <p className="mb-1 text-xs font-medium text-muted-foreground">
+ <Trans>Failed features</Trans>
+ </p>
+ <ul className="flex flex-col gap-0.5">
+ {failedFeatureSummary.map((feature) => (
+ <li
+ key={feature.label}
+ className="font-mono text-xs text-red-500"
+ >
+ {feature.label}
+ {feature.spec ? ` (${feature.spec})` : ""}
+ {feature.failedValues.length > 0
+ ? `: ${feature.failedValues.join(", ")}`
+ : ""}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <label className="flex items-center gap-2 w-full cursor-pointer">
+ <Checkbox
+ isChecked={createNcr}
+ onCheckedChange={(checked) => setCreateNcr(!!checked)}
+ />
+ <span className="text-sm font-medium">
+ <Trans>Open an NCR for MRB disposition</Trans>
+ </span>
+ </label>
+ {createNcr &&
+ (hasIssueTypes ? (
+ <div className="flex flex-col gap-2 w-full">
+ <Label htmlFor="nonConformanceTypeId">
+ <Trans>Issue Type</Trans>
+ </Label>
+ <Select value={issueTypeId} onValueChange={setIssueTypeId}>
+ <SelectTrigger id="nonConformanceTypeId">
+ <SelectValue placeholder={t`Select an issue type`} />
+ </SelectTrigger>
+ <SelectContent>
+ {issueTypes.map((type) => (
+ <SelectItem key={type.id} value={type.id}>
+ {type.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ) : (
+ <Alert variant="warning">
+ <LuTriangleAlert className="size-4" />
+ <AlertTitle>
+ <Trans>No issue types configured</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ The lot will still be rejected, but an NCR cannot be
+ created until at least one Issue Type is configured.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ ))}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onCancel}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <fetcher.Form
+ method="post"
+ action={action}
+ onSubmit={() => (submitted.current = true)}
+ >
+ <input
+ type="hidden"
+ name="createNcr"
+ value={createNcr ? "true" : "false"}
+ />
+ <input
+ type="hidden"
+ name="nonConformanceTypeId"
+ value={createNcr ? issueTypeId : ""}
+ />
+ <Button
+ variant="destructive"
+ type="submit"
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" ||
+ (createNcr && hasIssueTypes && !issueTypeId)
+ }
+ >
+ <Trans>Reject Lot</Trans>
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default RejectLotModal;
diff --git a/apps/erp/app/modules/quality/ui/InboundInspections/ScanInspectionSample.tsx b/apps/erp/app/modules/quality/ui/Inspections/ScanInspectionSample.tsx
similarity index 87%
rename from apps/erp/app/modules/quality/ui/InboundInspections/ScanInspectionSample.tsx
rename to apps/erp/app/modules/quality/ui/Inspections/ScanInspectionSample.tsx
index de92317a6c..8b7c348cf7 100644
--- a/apps/erp/app/modules/quality/ui/InboundInspections/ScanInspectionSample.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/ScanInspectionSample.tsx
@@ -22,17 +22,10 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
-import {
- LuCheck,
- LuCircleCheck,
- LuCircleX,
- LuList,
- LuQrCode,
- LuX
-} from "react-icons/lu";
+import { LuCheck, LuList, LuQrCode, LuX } from "react-icons/lu";
import { useFetcher } from "react-router";
import { Hidden, Submit, TextArea } from "~/components/Form";
-import { inboundInspectionSampleValidator } from "~/modules/quality/quality.models";
+import { inspectionSampleValidator } from "~/modules/quality/quality.models";
import type { InspectionTrackedEntity } from "~/modules/quality/types";
import { path } from "~/utils/path";
@@ -64,9 +57,6 @@ export default function ScanInspectionSample({
const [selected, setSelected] = useState<InspectionTrackedEntity | null>(
null
);
- const [pendingStatus, setPendingStatus] = useState<"Passed" | "Failed">(
- "Passed"
- );
// Bumped after each successful save so the form (notes) remounts and clears,
// even for non-serial parts where there's no entity selection to change.
const [resetKey, setResetKey] = useState(0);
@@ -98,7 +88,7 @@ export default function ScanInspectionSample({
const isSubmitting = fetcher.state !== "idle";
// Serial parts require a scanned/selected tracked entity; other tracking
- // types record pass/fail without one.
+ // types add a sample column without one.
const canRecord = isSerial ? !!selected : true;
return (
@@ -114,33 +104,29 @@ export default function ScanInspectionSample({
<Trans>Inspect Item</Trans>
</ModalTitle>
<ModalDescription>
- {isSerial ? (
- <Trans>
- Scan or select a tracked entity from this lot and record the
- inspection result.
- </Trans>
- ) : (
- <Trans>Record the inspection result for this sample.</Trans>
- )}
+ <Trans>
+ Scan or select a tracked entity from this lot to add it as a
+ sample column, then record its result in the grid.
+ </Trans>
</ModalDescription>
</ModalHeader>
<ValidatedForm
key={`${selected?.id ?? "none"}-${resetKey}`}
fetcher={fetcher}
method="post"
- action={`${path.to.inboundInspection(inspectionId)}/sample`}
- validator={inboundInspectionSampleValidator}
+ action={`${path.to.inspection(inspectionId)}/sample`}
+ validator={inspectionSampleValidator}
defaultValues={{
inspectionId,
trackedEntityId: selected?.id ?? "",
- status: pendingStatus,
+ status: "Pending",
notes: ""
}}
>
<ModalBody>
<Hidden name="inspectionId" value={inspectionId} />
<Hidden name="trackedEntityId" value={selected?.id ?? ""} />
- <Hidden name="status" value={pendingStatus} />
+ <Hidden name="status" value="Pending" />
<VStack spacing={4} className="w-full">
<BarProgress
@@ -259,19 +245,10 @@ export default function ScanInspectionSample({
<Trans>Close</Trans>
</Button>
<Submit
- variant="destructive"
- leftIcon={<LuCircleX />}
- isDisabled={!canRecord || isSubmitting}
- onClick={() => setPendingStatus("Failed")}
- >
- <Trans>Fail</Trans>
- </Submit>
- <Submit
- leftIcon={<LuCircleCheck />}
+ leftIcon={<LuCheck />}
isDisabled={!canRecord || isSubmitting}
- onClick={() => setPendingStatus("Passed")}
>
- <Trans>Pass</Trans>
+ <Trans>Add Sample</Trans>
</Submit>
</HStack>
</ModalFooter>
diff --git a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
index 268f37bf53..68e2f90ebc 100644
--- a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
@@ -76,7 +76,7 @@ type EntityLink = {
function EntityLabel({ link }: { link: EntityLink }) {
const readableId = link.trackedEntity?.readableId;
- const idSlice = link.trackedEntityId.slice(-8);
+ const idSlice = link.trackedEntityId.slice(0, 8);
if (readableId) {
return (
<span className="font-mono truncate">
@@ -204,7 +204,9 @@ export function AssociatedItemsList({
disposition: row.disposition as string | null | undefined,
pending:
!row.disposition || row.disposition === "Pending" ? true : false,
- sumMismatch: Math.abs(linkedSum - quantity) > 1e-6
+ // Only tracked rows reconcile a per-entity quantity sum; a non-tracked
+ // row carries its quantity directly with no links to add up.
+ sumMismatch: links.length > 0 && Math.abs(linkedSum - quantity) > 1e-6
};
});
}, [associatedItems]);
@@ -213,11 +215,11 @@ export function AssociatedItemsList({
return null;
}
- // Disposition only applies to rows that route physical tracked entities.
- // Hide the entire card when nothing here is dispositionable (e.g. an NCR
- // from a non-tracked job-operation part), matching the closure validator's
- // skip-on-no-links rule.
- const dispositionableRows = rows.filter((r) => r.links.length > 0);
+ // Every associated item row is dispositionable — tracked rows route physical
+ // entities (chips, split, move), non-tracked rows (Inventory / Non-Inventory,
+ // e.g. an NCR from a job-operation part) carry a plain quantity and just get
+ // the disposition Select. The closure validator applies the same rule.
+ const dispositionableRows = rows;
if (dispositionableRows.length === 0) {
return null;
}
@@ -267,12 +269,15 @@ export function AssociatedItemsList({
disposition: (s.disposition ?? "Pending") as string,
itemReadableId: item.readableIdWithRevision
}));
- // Split breaks a portion of the row onto a new disposition row.
+ // Split breaks a portion of the row onto a new disposition row so
+ // MRB can decide each portion (e.g. scrap N, use-as-is the rest).
// A single batch lot is subdivided server-side (a new tracked
- // entity is created for the split-off quantity), so any row with
- // quantity > 1 is splittable, even when it's one indivisible lot.
+ // entity is created for the split-off quantity); a non-tracked row
+ // is a pure quantity split. Any row with quantity > 1 is splittable.
const canSplit = r.quantity > 1;
- const hasRowActions = canSplit || siblings.length > 0;
+ // Moving entities only applies to tracked rows that own links.
+ const canMove = r.links.length > 0 && siblings.length > 0;
+ const hasRowActions = canSplit || canMove;
const isDropTarget =
canEdit &&
sameItemSiblings.length > 0 &&
@@ -374,7 +379,7 @@ export function AssociatedItemsList({
/>
</ValidatedForm>
<div className="w-10 shrink-0 flex items-start justify-end">
- {canEdit && r.links.length > 0 && hasRowActions && (
+ {canEdit && hasRowActions && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
@@ -401,7 +406,7 @@ export function AssociatedItemsList({
<Trans>Split line</Trans>
</DropdownMenuItem>
)}
- {siblings.length > 0 && (
+ {canMove && (
<DropdownMenuItem
onClick={() =>
setMoveTarget({
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
index 49084bd4e4..af31095df1 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
@@ -316,7 +316,7 @@ function getAssociationIcon(key: IssueAssociationKey) {
return <LuHandCoins className="text-red-600" />;
case "trackedEntities":
return <LuQrCode />;
- case "inboundInspections":
+ case "inspections":
return <LuClipboardCheck className="text-teal-600" />;
default:
return <LuFileText />;
@@ -897,7 +897,7 @@ function NewTrackedEntityAssociation({ items }: { items?: string[] }) {
);
}
-function NewInboundInspectionAssociation() {
+function NewInspectionAssociation() {
const { t } = useLingui();
const { carbon } = useCarbon();
const [storedItems] = useItems();
@@ -912,8 +912,8 @@ function NewInboundInspectionAssociation() {
return;
}
const { data, error } = await carbon
- .from("inboundInspection")
- .select("id, inboundInspectionId, itemId, status");
+ .from("inspection")
+ .select("id, inspectionId, itemId, status");
if (error) {
toast.error(t`Failed to load inbound inspections`);
@@ -921,7 +921,7 @@ function NewInboundInspectionAssociation() {
setInspections(
data?.map((inspection) => ({
- label: (inspection as any).inboundInspectionId ?? inspection.id,
+ label: (inspection as any).inspectionId ?? inspection.id,
value: inspection.id,
helper: [
getItemReadableId(storedItems, inspection.itemId),
@@ -941,7 +941,7 @@ function NewInboundInspectionAssociation() {
return (
<Combobox
name="id"
- label={t`Inbound Inspection`}
+ label={t`Inspection`}
options={inspections}
isLoading={inspectionsAreLoading}
/>
@@ -996,8 +996,8 @@ function NewAssociationModal({
return <NewReceiptLineAssociation items={items} />;
case "trackedEntities":
return <NewTrackedEntityAssociation items={items} />;
- case "inboundInspections":
- return <NewInboundInspectionAssociation />;
+ case "inspections":
+ return <NewInspectionAssociation />;
default:
return null;
}
@@ -1068,8 +1068,8 @@ function getAssociationLink(
return path.to.customer(child.documentId);
case "suppliers":
return path.to.supplier(child.documentId);
- case "inboundInspections":
- return path.to.inboundInspection(child.documentId);
+ case "inspections":
+ return path.to.inspection(child.documentId);
default:
return "#";
}
diff --git a/apps/erp/app/modules/quality/ui/Item/ItemQualityView.tsx b/apps/erp/app/modules/quality/ui/Item/ItemQualityView.tsx
new file mode 100644
index 0000000000..8165531205
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Item/ItemQualityView.tsx
@@ -0,0 +1,167 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ HStack,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { LuPlus } from "react-icons/lu";
+import { Hyperlink } from "~/components";
+import { Hidden, InspectionDocument, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import InspectionDocumentForm from "~/modules/production/ui/InspectionDocument/InspectionDocumentForm";
+import {
+ inspectionDocumentUsages,
+ itemInspectionDocumentAssignmentValidator
+} from "~/modules/quality";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import { path } from "~/utils/path";
+
+type ItemQualityViewProps = {
+ itemId: string;
+ actionPath: string;
+ documents: {
+ id: string;
+ fileName: string | null;
+ drawingNumber: string | null;
+ version: number;
+ }[];
+ assignments: ItemInspectionDocumentAssignment[];
+};
+
+// The item Quality tab: the item's inspection documents and the usage-slot
+// assignments driving which document each inspection flow uses (v1: Receipt
+// for inbound inspection; FAI / Production slots are additive later). Sampling
+// rules live on the inspection document itself (default + per-feature).
+const ItemQualityView = ({
+ itemId,
+ actionPath,
+ documents,
+ assignments
+}: ItemQualityViewProps) => {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const canUpdate = permissions.can("update", "quality");
+ const newDocumentDisclosure = useDisclosure();
+
+ return (
+ <VStack spacing={4} className="w-full">
+ <Card>
+ <HStack className="w-full justify-between items-start">
+ <CardHeader>
+ <CardTitle>
+ <Trans>Inspection Plans</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>Ballooned drawings with inspection features.</Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardAction>
+ {permissions.can("create", "quality") && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuPlus />}
+ onClick={newDocumentDisclosure.onOpen}
+ >
+ <Trans>New</Trans>
+ </Button>
+ )}
+ </CardAction>
+ </HStack>
+ <CardContent>
+ {documents.length === 0 ? (
+ <p className="py-4 text-center text-sm text-muted-foreground">
+ <Trans>No inspection plans</Trans>
+ </p>
+ ) : (
+ <VStack spacing={0} className="w-full">
+ {documents.map((doc) => (
+ <HStack
+ key={doc.id}
+ className="w-full justify-between border-b py-2 last:border-b-0"
+ >
+ <Hyperlink to={path.to.inspectionDocument(doc.id)}>
+ <span className="text-sm font-medium">
+ {doc.drawingNumber ?? doc.fileName ?? doc.id}
+ </span>
+ </Hyperlink>
+ <Badge variant="secondary" className="font-mono text-[10px]">
+ v{doc.version}
+ </Badge>
+ </HStack>
+ ))}
+ </VStack>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Inspection Plan Assignments</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>
+ Which document drives each inspection flow for this item.
+ </Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4} className="w-full">
+ {inspectionDocumentUsages.map((usage) => {
+ const assignment = assignments.find((a) => a.usage === usage);
+ return (
+ <ValidatedForm
+ key={usage}
+ method="post"
+ action={actionPath}
+ validator={itemInspectionDocumentAssignmentValidator}
+ defaultValues={{
+ itemId,
+ usage,
+ inspectionDocumentId: assignment?.inspectionDocumentId ?? ""
+ }}
+ className="w-full"
+ >
+ <Hidden name="intent" value="assignment" />
+ <Hidden name="itemId" value={itemId} />
+ <Hidden name="usage" value={usage} />
+ <HStack className="w-full items-end gap-4">
+ <div className="flex-1">
+ <InspectionDocument
+ name="inspectionDocumentId"
+ label={usage === "Receipt" ? t`Receipt` : usage}
+ itemId={itemId}
+ isOptional
+ />
+ </div>
+ <Submit isDisabled={!canUpdate} variant="secondary">
+ <Trans>Save</Trans>
+ </Submit>
+ </HStack>
+ </ValidatedForm>
+ );
+ })}
+ </VStack>
+ </CardContent>
+ </Card>
+
+ {newDocumentDisclosure.isOpen && (
+ <InspectionDocumentForm
+ initialValues={{ name: "", partId: itemId, drawingNumber: "" }}
+ onClose={newDocumentDisclosure.onClose}
+ />
+ )}
+ </VStack>
+ );
+};
+
+export default ItemQualityView;
diff --git a/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionForm.tsx b/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionForm.tsx
index e0180987e8..ed3eebe1fd 100644
--- a/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionForm.tsx
+++ b/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionForm.tsx
@@ -98,6 +98,7 @@ const RequiredActionForm = ({
name="active"
label={t`Active`}
description={t`Inactive actions will not appear in selection lists`}
+ bordered
/>
<CustomFormFields table="nonConformanceRequiredAction" />
</VStack>
diff --git a/apps/erp/app/modules/quality/ui/SamplingPlan/SamplingPlanForm.tsx b/apps/erp/app/modules/quality/ui/SamplingPlan/SamplingPlanForm.tsx
deleted file mode 100644
index d07d23a177..0000000000
--- a/apps/erp/app/modules/quality/ui/SamplingPlan/SamplingPlanForm.tsx
+++ /dev/null
@@ -1,339 +0,0 @@
-import { ValidatedForm } from "@carbon/form";
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
- HStack,
- Label,
- LabelWithHelp,
- VStack
-} from "@carbon/react";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useState } from "react";
-import {
- Hidden,
- Number as NumberInput,
- Select,
- Submit
-} from "~/components/Form";
-import { usePermissions } from "~/hooks";
-import { itemSamplingPlanValidator } from "~/modules/quality/quality.models";
-import {
- type InspectionLevel,
- type InspectionSeverity,
- resolveSamplingPlan,
- type SamplingPlanType,
- type SamplingStandard,
- standardAqlValues
-} from "~/modules/quality/samplingStandards";
-
-type SamplingPlanFormProps = {
- action: string;
- itemId: string;
- standard: SamplingStandard;
- initial?: {
- type: SamplingPlanType;
- sampleSize?: number | null;
- percentage?: number | string | null;
- aql?: number | string | null;
- inspectionLevel?: InspectionLevel;
- severity?: InspectionSeverity;
- } | null;
-};
-
-function useSamplingPlanOptions() {
- const { t } = useLingui();
- const typeOptions: { value: SamplingPlanType; label: string }[] = [
- { value: "All", label: t`Inspect All` },
- { value: "First", label: t`Inspect First N` },
- { value: "Percentage", label: t`Percentage` },
- { value: "AQL", label: t`AQL (Z1.4 / ISO 2859-1)` }
- ];
-
- const inspectionLevelOptions: { value: InspectionLevel; label: string }[] = [
- { value: "S1", label: t`S-1 (coarsest special)` },
- { value: "S2", label: t`S-2` },
- { value: "S3", label: t`S-3` },
- { value: "S4", label: t`S-4 (finest special)` },
- { value: "I", label: t`I (reduced)` },
- { value: "II", label: t`II (normal default)` },
- { value: "III", label: t`III (tightened)` }
- ];
-
- const severityOptions: { value: InspectionSeverity; label: string }[] = [
- { value: "Normal", label: t`Normal` },
- { value: "Tightened", label: t`Tightened` },
- { value: "Reduced", label: t`Reduced` }
- ];
-
- return { typeOptions, inspectionLevelOptions, severityOptions };
-}
-
-// Canonical string form of an AQL value, so options match stored values.
-// DB returns NUMERIC(5,3) as e.g. "1.500" — normalize everything to "1.5".
-function normalizeAql(v: number | string | null | undefined): string | null {
- if (v == null || v === "") return null;
- const n = typeof v === "number" ? v : parseFloat(v);
- if (Number.isNaN(n)) return null;
- return String(n);
-}
-
-function toNumberOrUndefined(
- v: number | string | null | undefined
-): number | undefined {
- if (v == null || v === "") return undefined;
- const n = typeof v === "number" ? v : parseFloat(v);
- return Number.isNaN(n) ? undefined : n;
-}
-
-const aqlOptions = standardAqlValues.map((v) => ({
- value: String(v),
- label: v.toString()
-}));
-
-const SAMPLE_LOT_SIZES = [10, 50, 100, 500, 1000];
-
-export default function SamplingPlanForm({
- action,
- itemId,
- standard,
- initial
-}: SamplingPlanFormProps) {
- const permissions = usePermissions();
- const canUpdate = permissions.can("update", "quality");
- const { typeOptions, inspectionLevelOptions, severityOptions } =
- useSamplingPlanOptions();
-
- const initialType = initial?.type ?? "All";
- const initialSampleSize = initial?.sampleSize ?? null;
- const initialPercentage = toNumberOrUndefined(initial?.percentage) ?? null;
- const initialAqlString = normalizeAql(initial?.aql);
- const initialAqlNumber = toNumberOrUndefined(initial?.aql) ?? 1.0;
- const initialLevel: InspectionLevel = initial?.inspectionLevel ?? "II";
- const initialSeverity: InspectionSeverity = initial?.severity ?? "Normal";
-
- const [type, setType] = useState<SamplingPlanType>(initialType);
- const [sampleSize, setSampleSize] = useState<number>(initialSampleSize ?? 1);
- const [percentage, setPercentage] = useState<number>(initialPercentage ?? 10);
- const [aql, setAql] = useState<number>(initialAqlNumber);
- const [inspectionLevel, setInspectionLevel] =
- useState<InspectionLevel>(initialLevel);
- const [severity, setSeverity] = useState<InspectionSeverity>(initialSeverity);
-
- // Re-seed local state when the loader returns a new plan (e.g. after save).
- useEffect(() => {
- setType(initialType);
- setSampleSize(initialSampleSize ?? 1);
- setPercentage(initialPercentage ?? 10);
- setAql(initialAqlNumber);
- setInspectionLevel(initialLevel);
- setSeverity(initialSeverity);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- initialType,
- initialSampleSize,
- initialPercentage,
- initialAqlNumber,
- initialLevel,
- initialSeverity
- ]);
-
- const planForPreview = {
- type,
- sampleSize,
- percentage,
- aql,
- inspectionLevel,
- severity
- };
-
- // Remount key — forces ValidatedForm (and all its name-bound fields) to
- // re-initialize from defaultValues whenever the saved plan changes.
- const formKey = [
- initialType,
- initialSampleSize ?? "",
- initialPercentage ?? "",
- initialAqlString ?? "",
- initialLevel,
- initialSeverity
- ].join("|");
-
- return (
- <Card>
- <ValidatedForm
- key={formKey}
- method="post"
- action={action}
- validator={itemSamplingPlanValidator}
- defaultValues={{
- itemId,
- type: initialType,
- sampleSize: initialSampleSize ?? undefined,
- percentage: initialPercentage ?? undefined,
- aql: (initialAqlString ?? "1") as any,
- inspectionLevel: initialLevel,
- severity: initialSeverity
- }}
- >
- <Hidden name="itemId" />
- <CardHeader>
- <CardTitle>
- <Trans>Sampling Plan</Trans>
- </CardTitle>
- <CardDescription>
- <Trans>
- Defines how many tracked entities are inspected per lot, and how
- many failures are tolerated before the lot is rejected.
- </Trans>
- </CardDescription>
- </CardHeader>
- <CardContent>
- <VStack spacing={4} className="w-full">
- <div className="flex flex-col gap-2 w-full">
- <Label>
- <LabelWithHelp termId="sampling-plan-type">
- <Trans>Plan Type</Trans>
- </LabelWithHelp>
- </Label>
- <Select
- name="type"
- options={typeOptions}
- onChange={(v) => v && setType(v.value as SamplingPlanType)}
- />
- </div>
-
- {type === "First" && (
- <div className="flex flex-col gap-2 w-full">
- <Label>
- <LabelWithHelp termId="sampling-plan-sample-size">
- <Trans>Sample Size</Trans>
- </LabelWithHelp>
- </Label>
- <NumberInput
- name="sampleSize"
- minValue={1}
- onChange={(n) => typeof n === "number" && setSampleSize(n)}
- />
- </div>
- )}
-
- {type === "Percentage" && (
- <div className="flex flex-col gap-2 w-full">
- <Label>
- <LabelWithHelp termId="sampling-plan-percentage">
- <Trans>Percentage of Lot</Trans>
- </LabelWithHelp>
- </Label>
- <NumberInput
- name="percentage"
- minValue={1}
- maxValue={100}
- onChange={(n) => typeof n === "number" && setPercentage(n)}
- />
- </div>
- )}
-
- {type === "AQL" && (
- <div className="grid grid-cols-3 gap-4 w-full">
- <div className="flex flex-col gap-2">
- <Label>
- <LabelWithHelp termId="sampling-plan-aql">
- <Trans>AQL</Trans>
- </LabelWithHelp>
- </Label>
- <Select
- name="aql"
- options={aqlOptions}
- onChange={(v) => v && setAql(parseFloat(v.value))}
- />
- </div>
- <div className="flex flex-col gap-2">
- <Label>
- <LabelWithHelp termId="sampling-plan-inspection-level">
- <Trans>Inspection Level</Trans>
- </LabelWithHelp>
- </Label>
- <Select
- name="inspectionLevel"
- options={inspectionLevelOptions}
- onChange={(v) =>
- v && setInspectionLevel(v.value as InspectionLevel)
- }
- />
- </div>
- <div className="flex flex-col gap-2">
- <Label>
- <LabelWithHelp termId="sampling-plan-severity">
- <Trans>Severity</Trans>
- </LabelWithHelp>
- </Label>
- <Select
- name="severity"
- options={severityOptions}
- onChange={(v) =>
- v && setSeverity(v.value as InspectionSeverity)
- }
- />
- </div>
- </div>
- )}
-
- <div className="flex flex-col gap-2 w-full border rounded-md p-4">
- <HStack className="justify-between">
- <span className="text-sm font-medium">
- <Trans>Preview</Trans>
- </span>
- <span className="text-xs text-muted-foreground">
- {standard === "ANSI_Z1_4" ? "ANSI/ASQ Z1.4" : "ISO 2859-1"}
- </span>
- </HStack>
- <table className="text-sm w-full">
- <thead className="text-xs text-muted-foreground">
- <tr>
- <th className="text-left font-medium py-1">
- <Trans>Lot</Trans>
- </th>
- <th className="text-left font-medium py-1">
- <Trans>Sample</Trans>
- </th>
- <th className="text-left font-medium py-1">Ac</th>
- <th className="text-left font-medium py-1">Re</th>
- <th className="text-left font-medium py-1">
- <Trans>Letter</Trans>
- </th>
- </tr>
- </thead>
- <tbody>
- {SAMPLE_LOT_SIZES.map((n) => {
- const res = resolveSamplingPlan(
- planForPreview,
- n,
- standard
- );
- return (
- <tr key={n}>
- <td className="py-1">{n}</td>
- <td className="py-1">{res.sampleSize}</td>
- <td className="py-1">{res.acceptance}</td>
- <td className="py-1">{res.rejection}</td>
- <td className="py-1">{res.codeLetter ?? "—"}</td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
- </VStack>
- </CardContent>
- <CardFooter>
- <Submit isDisabled={!canUpdate}>
- <Trans>Save</Trans>
- </Submit>
- </CardFooter>
- </ValidatedForm>
- </Card>
- );
-}
diff --git a/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx b/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
index 2116bd50e3..1a88bb4bc8 100644
--- a/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
+++ b/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
@@ -1,5 +1,4 @@
import { useLingui } from "@lingui/react/macro";
-import { IoBalloonOutline } from "react-icons/io5";
import {
LuCircleGauge,
LuClipboardCheck,
@@ -67,15 +66,10 @@ export default function useQualitySubmodules() {
name: t`Inspection`,
routes: [
{
- name: t`Inbound Inspections`,
- to: path.to.inboundInspections,
+ name: t`Inspections`,
+ to: path.to.inspections,
icon: <LuClipboardCheck />,
- table: "inboundInspection"
- },
- {
- name: t`Inspection Documents`,
- to: path.to.inspectionDocuments,
- icon: <IoBalloonOutline />
+ table: "inspection"
}
]
},
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index 35212df0da..e48c86b933 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
-import { processTypes, standardFactorType } from "../shared";
+import { operationTypes, standardFactorType } from "../shared";
export const abilityCurveValidator = z.object({
data: z
@@ -289,7 +289,7 @@ export const processValidator = z
.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Process name is required" }),
- processType: z.enum(processTypes, {
+ processType: z.enum(operationTypes, {
errorMap: () => ({ message: "Process type is required" })
}),
defaultStandardFactor: z
@@ -303,13 +303,16 @@ export const processValidator = z
completeAllOnScan: zfd.checkbox()
})
.refine((data) => {
- if (data.processType !== "Outside" && !data.workCenters) {
+ if (data.processType !== "Outside Processing" && !data.workCenters) {
return { workCenters: ["Work center is required for inside process"] };
}
return true;
})
.refine((data) => {
- if (data.processType !== "Outside" && !data.defaultStandardFactor) {
+ if (
+ data.processType !== "Outside Processing" &&
+ !data.defaultStandardFactor
+ ) {
return { defaultStandardFactor: ["Standard factor is required"] };
}
return true;
diff --git a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
index c50040eb2e..764e3889b2 100644
--- a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
+++ b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
@@ -89,6 +89,7 @@ function DailyScheduleOptions() {
name="skipHolidays"
label={t`Skip Holidays`}
description={t`Skip scheduled maintenance on company holidays`}
+ bordered
/>
</>
);
@@ -203,7 +204,7 @@ const MaintenanceScheduleForm = ({
label={t`Procedure`}
termId="maintenance-schedule-procedure"
/>
- <Boolean name="active" label={t`Active`} />
+ <Boolean name="active" label={t`Active`} bordered />
<DailyScheduleOptions />
</VStack>
</ModalDrawerBody>
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
index fd539de7b3..d983136810 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
@@ -1,4 +1,4 @@
-import { ValidatedForm } from "@carbon/form";
+import { useControlField, ValidatedForm } from "@carbon/form";
import {
Button,
DropdownMenu,
@@ -22,7 +22,7 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import {
LuCirclePlus,
LuEllipsisVertical,
@@ -31,7 +31,7 @@ import {
} from "react-icons/lu";
import { useFetcher, useNavigate } from "react-router";
import type { z } from "zod";
-import { SupplierAvatar } from "~/components";
+import { OperationTypeIcon, SupplierAvatar } from "~/components";
import {
Boolean,
CustomFormFields,
@@ -47,7 +47,7 @@ import { usePermissions } from "~/hooks";
import { SupplierProcessForm } from "~/modules/purchasing/ui/Supplier";
import { processValidator } from "~/modules/resources";
-import { processTypes } from "~/modules/shared";
+import { operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
type ProcessFormProps = {
@@ -83,8 +83,6 @@ const ProcessForm = ({
? !permissions.can("update", "resources")
: !permissions.can("create", "resources");
- const [processType, setProcessType] = useState(initialValues.processType);
-
return (
<ModalDrawerProvider type={type}>
<ModalDrawer
@@ -124,38 +122,36 @@ const ProcessForm = ({
name="processType"
label={t`Process Type`}
termId="process-type"
- options={processTypes.map((pt) => ({
+ options={operationTypes.map((pt) => ({
value: pt,
- label: pt
+ label: (
+ <span className="flex items-center gap-2">
+ <OperationTypeIcon type={pt} />
+ <span>{pt}</span>
+ </span>
+ )
}))}
- onChange={(newValue) => {
- setProcessType(
- newValue?.value as (typeof processTypes)[number]
- );
- }}
/>
- {processType !== "Outside" && (
- <>
- <StandardFactor
- name="defaultStandardFactor"
- label={t`Default Unit`}
- termId="process-default-unit"
- value={initialValues.defaultStandardFactor}
- />
- <WorkCenters
- name="workCenters"
- label={t`Work Centers`}
- termId="work-center"
- />
- </>
- )}
- {processType !== "Inside" && (
- <SupplierProcesses processId={initialValues.id} />
- )}
+ {/* Work centers apply to any type (the type is just a default
+ for new operations), but supplier links only make sense for
+ Outside Processing — SupplierProcesses gates itself on it. */}
+ <StandardFactor
+ name="defaultStandardFactor"
+ label={t`Default Unit`}
+ termId="process-default-unit"
+ value={initialValues.defaultStandardFactor}
+ />
+ <WorkCenters
+ name="workCenters"
+ label={t`Work Centers`}
+ termId="work-center"
+ />
+ <SupplierProcesses processId={initialValues.id} />
<Boolean
name="completeAllOnScan"
label={t`Complete all quantities on barcode scan`}
termId="process-complete-all-on-scan"
+ bordered
/>
<CustomFormFields table="process" />
</VStack>
@@ -186,6 +182,10 @@ function SupplierProcesses({ processId }: { processId?: string }) {
const navigate = useNavigate();
const isEditing = processId !== undefined;
const newSupplierProcessModal = useDisclosure();
+ const [processType] = useControlField<string>("processType");
+
+ // Suppliers only apply to outside-processing operations.
+ if (processType !== "Outside Processing") return null;
return (
<>
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
index 8b3b15559c..442a9e34a1 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -27,13 +27,23 @@ import {
LuUsers
} from "react-icons/lu";
import { useNavigate } from "react-router";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import {
+ EmployeeAvatar,
+ Hyperlink,
+ New,
+ OperationTypeIcon,
+ Table
+} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenter";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { Process } from "~/modules/resources";
-import { standardFactorType } from "~/modules/shared";
+import {
+ type OperationType,
+ operationTypes,
+ standardFactorType
+} from "~/modules/shared";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
@@ -64,7 +74,7 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
accessorKey: "name",
header: t`Process`,
cell: ({ row }) =>
- row.original.processType === "Outside" ||
+ row.original.processType === "Outside Processing" ||
((row.original.workCenters as any[]) ?? []).length > 0 ? (
<Hyperlink to={row.original.id!}>
<Enumerable
@@ -87,14 +97,40 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
{
accessorKey: "processType",
header: t`Process Type`,
- cell: (item) =>
- item.getValue() === "Outside" ? (
- <Badge>Outside</Badge>
+ cell: (item) => {
+ const value = item.getValue<string>();
+ const icon = (
+ <OperationTypeIcon
+ type={value as OperationType}
+ className="mr-1 h-3 w-3 text-current"
+ />
+ );
+ return value === "Outside Processing" ? (
+ <Badge>
+ {icon}
+ Outside Processing
+ </Badge>
) : (
- <Badge variant="secondary">{item.getValue<string>()}</Badge>
- ),
+ <Badge variant="secondary">
+ {icon}
+ {value}
+ </Badge>
+ );
+ },
meta: {
- icon: <LuFactory />
+ icon: <LuFactory />,
+ filter: {
+ type: "static",
+ options: operationTypes.map((pt) => ({
+ value: pt,
+ label: (
+ <span className="flex items-center gap-2">
+ <OperationTypeIcon type={pt} />
+ <span>{pt}</span>
+ </span>
+ )
+ }))
+ }
}
},
{
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index bf80873849..ad66a3a1fa 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -437,6 +437,8 @@ export const quoteOperationValidator = z
}),
processId: z.string().min(1, { message: "Process is required" }),
procedureId: zfd.text(z.string().optional()),
+ assemblyInstructionId: zfd.text(z.string().optional()),
+ inspectionDocumentId: zfd.text(z.string().optional()),
workCenterId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
@@ -469,7 +471,7 @@ export const quoteOperationValidator = z
})
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationMinimumCost);
}
return true;
@@ -481,7 +483,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationUnitCost);
}
return true;
@@ -493,7 +495,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Outside") {
+ if (data.operationType === "Outside Processing") {
return Number.isFinite(data.operationLeadTime);
}
return true;
@@ -505,7 +507,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.setupUnit;
}
return true;
@@ -517,7 +519,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return !!data.laborUnit;
}
return true;
@@ -529,8 +531,10 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
- return !!data.laborUnit;
+ // Machine only applies to Process operations — Assembly and Inspection
+ // are setup + labor work.
+ if (data.operationType === "Process") {
+ return !!data.machineUnit;
}
return true;
},
@@ -541,7 +545,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.setupTime);
}
return true;
@@ -553,7 +557,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborTime);
}
return true;
@@ -565,7 +569,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineTime);
}
return true;
@@ -577,7 +581,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType === "Process") {
return Number.isFinite(data.machineRate);
}
return true;
@@ -589,7 +593,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.overheadRate);
}
return true;
@@ -601,7 +605,7 @@ export const quoteOperationValidator = z
)
.refine(
(data) => {
- if (data.operationType === "Inside") {
+ if (data.operationType !== "Outside Processing") {
return Number.isFinite(data.laborRate);
}
return true;
@@ -610,6 +614,18 @@ export const quoteOperationValidator = z
message: "Labor rate is required",
path: ["laborRate"]
}
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inspection") {
+ return !!data.inspectionDocumentId;
+ }
+ return true;
+ },
+ {
+ message: "Inspection Plan is required",
+ path: ["inspectionDocumentId"]
+ }
);
export const quoteFinalizeValidator = z
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index ffe7be1f48..4728daa501 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -21,6 +21,7 @@ import type {
operationStepValidator,
operationToolValidator
} from "../shared";
+import { normalizeOperationSourceIds } from "../shared";
import {
lookupBuyPriceFromMap,
upsertExternalLink
@@ -4108,7 +4109,17 @@ async function buildCostEffects(
);
for (const op of nodeOps) {
- if (op.operationType === "Inside") {
+ // Outside Processing is subcontracted — its cost is the supplier's per-unit
+ // price (with a minimum). Every other operationType (Process, Assembly,
+ // Inspection, and any future in-house type) is costed in-house from
+ // labor/machine/setup times. Match the subcontract case explicitly so a new
+ // operationType can't silently inherit the outside-cost branch.
+ if (op.operationType === "Outside Processing") {
+ effects.outsideCost.push((outerQty) => {
+ const cost = op.operationUnitCost * qty * outerQty;
+ return Math.max(op.operationMinimumCost, cost);
+ });
+ } else {
if (op.setupTime) {
const { fixedHours, hoursPerUnit } = normalizeTime(
op.setupTime,
@@ -4165,11 +4176,6 @@ async function buildCostEffects(
}
return fh * (op.overheadRate ?? 0);
});
- } else if (op.operationType === "Outside") {
- effects.outsideCost.push((outerQty) => {
- const cost = op.operationUnitCost * qty * outerQty;
- return Math.max(op.operationMinimumCost, cost);
- });
}
}
@@ -4755,13 +4761,13 @@ export async function upsertQuoteOperation(
if ("createdBy" in operation) {
return client
.from("quoteOperation")
- .insert([operation])
+ .insert([normalizeOperationSourceIds(operation)])
.select("id")
.single();
}
return client
.from("quoteOperation")
- .update(sanitize(operation))
+ .update(sanitize(normalizeOperationSourceIds(operation)))
.eq("id", operation.id)
.select("id")
.single();
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
index 1e054a3fc8..698f45ab42 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx
@@ -101,6 +101,7 @@ const CustomerTaxForm = ({ initialValues }: CustomerTaxFormProps) => {
label={t`Tax Exempt`}
termId="tax-exempt"
onChange={(value) => setTaxExempt(value)}
+ bordered
/>
</div>
{taxExempt && (
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
index b36835d78c..ff9c72ddf4 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
@@ -154,7 +154,7 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
/>
)}
- <BooleanField name="active" label={t`Active`} />
+ <BooleanField name="active" label={t`Active`} bordered />
<p className="text-sm font-medium text-muted-foreground pt-2">
{t`Scope`}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index ca5b2c4f17..e420827ff7 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -59,7 +59,12 @@ import {
} from "react-icons/lu";
import { useFetcher, useFetchers, useParams } from "react-router";
import type { z } from "zod";
-import { DirectionAwareTabs, EmployeeAvatar, TimeTypeIcon } from "~/components";
+import {
+ DirectionAwareTabs,
+ EmployeeAvatar,
+ OperationTypeIcon,
+ TimeTypeIcon
+} from "~/components";
import {
Hidden,
InputControlled,
@@ -75,6 +80,8 @@ import {
UnitHint,
WorkCenter
} from "~/components/Form";
+import AssemblyInstruction from "~/components/Form/AssemblyInstruction";
+import InspectionDocument from "~/components/Form/InspectionDocument";
import Procedure from "~/components/Form/Procedure";
import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";
import { getUnitHint } from "~/components/Form/UnitHint";
@@ -134,6 +141,7 @@ type QuoteMaterial = {
type QuoteBillOfProcessProps = {
quoteMakeMethodId: string;
+ itemId: string;
materials: QuoteMaterial[];
operations: (Operation & {
quoteOperationTool: OperationTool[];
@@ -177,7 +185,7 @@ function makeItem(
<h3 className="font-semibold truncate cursor-pointer">
{operation.description}
</h3>
- {operation.operationType === "Outside" && (
+ {operation.operationType === "Outside Processing" && (
<SupplierProcessPreview
processId={operation.processId}
supplierProcessId={operation.operationSupplierProcessId}
@@ -189,8 +197,8 @@ function makeItem(
order: operation.operationOrder,
details: (
<HStack spacing={1}>
- {operation.operationType === "Outside" ? (
- <Badge>Outside</Badge>
+ {operation.operationType === "Outside Processing" ? (
+ <Badge>Outside Processing</Badge>
) : (
<>
{(operation?.setupTime ?? 0) > 0 && (
@@ -234,7 +242,9 @@ const initialOperation: Omit<
operationUnitCost: 0,
operationLeadTime: 0,
operationOrder: "After Previous",
- operationType: "Inside",
+ operationType: "Process",
+ assemblyInstructionId: "",
+ inspectionDocumentId: "",
overheadRate: 0,
processId: "",
procedureId: "",
@@ -277,6 +287,7 @@ const usePendingOperations = () => {
const QuoteBillOfProcess = ({
quoteMakeMethodId,
+ itemId,
materials,
operations: initialOperations,
tags
@@ -536,6 +547,7 @@ const QuoteBillOfProcess = ({
initialOperations.find((o) => o.id === item.id)?.quoteOperationStep ?? [];
const hasProcedure = !!item.data.procedureId;
+ const hasAssemblyInstruction = !!item.data.assemblyInstructionId;
const tabs = [
{
@@ -555,6 +567,7 @@ const QuoteBillOfProcess = ({
>
<OperationForm
item={item}
+ itemId={itemId}
isDisabled={isDisabled}
workInstruction={workInstructions[item.id] ?? {}}
setWorkInstructions={setWorkInstructions}
@@ -579,7 +592,7 @@ const QuoteBillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -643,7 +656,7 @@ const QuoteBillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -686,13 +699,14 @@ const QuoteBillOfProcess = ({
disabled:
item.id in temporaryItems ||
hasProcedure ||
- item.data.operationType === "Outside",
+ hasAssemblyInstruction ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
<Trans>Steps</Trans>
</span>
- {hasProcedure && (
+ {(hasProcedure || hasAssemblyInstruction) && (
<Tooltip>
<TooltipTrigger>
<Badge variant="secondary">
@@ -701,12 +715,20 @@ const QuoteBillOfProcess = ({
</TooltipTrigger>
<TooltipContent side="bottom" className="opacity-100">
<p>
- <Trans>Attributes are inherited from the procedure.</Trans>
+ {hasAssemblyInstruction ? (
+ <Trans>
+ Steps are inherited from the assembly instruction.
+ </Trans>
+ ) : (
+ <Trans>
+ Attributes are inherited from the procedure.
+ </Trans>
+ )}
</p>
</TooltipContent>
</Tooltip>
)}
- {!hasProcedure && steps.length > 0 && (
+ {!hasProcedure && !hasAssemblyInstruction && steps.length > 0 && (
<Count count={steps.length} />
)}
</span>
@@ -728,7 +750,8 @@ const QuoteBillOfProcess = ({
{
id: 4,
disabled:
- item.id in temporaryItems || item.data.operationType === "Outside",
+ item.id in temporaryItems ||
+ item.data.operationType === "Outside Processing",
label: (
<span className="flex items-center gap-2">
<span>
@@ -1683,6 +1706,7 @@ function ParametersListItem({
function OperationForm({
item,
+ itemId,
isDisabled,
workInstruction,
setWorkInstructions,
@@ -1692,6 +1716,7 @@ function OperationForm({
onSubmit
}: {
item: ItemWithData;
+ itemId: string;
isDisabled: boolean;
workInstruction: JSONContent;
setWorkInstructions: Dispatch<SetStateAction<PendingWorkInstructions>>;
@@ -1731,6 +1756,7 @@ function OperationForm({
}, [item.id, fetcher.data, setTemporaryItems, onSubmit]);
const machineDisclosure = useDisclosure();
+ const assemblyDisclosure = useDisclosure();
const laborDisclosure = useDisclosure();
const setupDisclosure = useDisclosure();
const costingDisclosure = useDisclosure();
@@ -1749,6 +1775,8 @@ function OperationForm({
operationMinimumCost: number;
operationLeadTime: number;
operationType: string;
+ assemblyInstructionId: string;
+ inspectionDocumentId: string;
operationUnitCost: number;
overheadRate: number;
processId: string;
@@ -1768,7 +1796,9 @@ function OperationForm({
machineUnitHint: getUnitHint(item.data.machineUnit),
operationMinimumCost: item.data.operationMinimumCost ?? 0,
operationLeadTime: item.data.operationLeadTime ?? 0,
- operationType: item.data.operationType ?? "Inside",
+ operationType: item.data.operationType ?? "Process",
+ assemblyInstructionId: item.data.assemblyInstructionId ?? "",
+ inspectionDocumentId: item.data.inspectionDocumentId ?? "",
operationUnitCost: item.data.operationUnitCost ?? 0,
overheadRate: item.data.overheadRate ?? 0,
processId: item.data.processId ?? "",
@@ -1837,8 +1867,9 @@ function OperationForm({
return (acc += sp.leadTime ?? 0);
}, 0) / supplierProcesses.data.length
: p.operationLeadTime,
- operationType:
- process.data?.processType === "Outside" ? "Outside" : "Inside"
+ // processType and operationType share one enum — the process's type is the
+ // default operation type.
+ operationType: process.data?.processType ?? "Process"
}));
};
@@ -1914,46 +1945,49 @@ function OperationForm({
onProcessChange(value?.value as string);
}}
/>
- <Select
- name="operationOrder"
- label={t`Operation Order`}
- placeholder={t`Operation Order`}
- options={methodOperationOrders.map((o) => ({
- value: o,
- label: o
- }))}
- />
<SelectControlled
name="operationType"
label={t`Operation Type`}
+ termId="operation-type"
placeholder={t`Operation Type`}
options={operationTypes.map((o) => ({
value: o,
- label: o
+ label: (
+ <span className="flex items-center gap-2">
+ <OperationTypeIcon type={o} />
+ <span>{o}</span>
+ </span>
+ )
}))}
value={processData.operationType}
onChange={(value) => {
+ const next = (value?.value as string) ?? "Process";
setProcessData((d) => ({
...d,
- setupUnit: "Total Minutes",
- laborUnit: "Minutes/Piece",
- machineUnit: "Minutes/Piece",
- operationType: value?.value as string
+ operationType: next,
+ // Each type has exactly one instruction source — clear the ones
+ // that no longer apply (the upsert normalizes server-side too).
+ ...(next !== "Process" ? { procedureId: "" } : {}),
+ ...(next !== "Assembly" ? { assemblyInstructionId: "" } : {}),
+ ...(next !== "Inspection" ? { inspectionDocumentId: "" } : {}),
+ // Machine only applies to Process operations.
+ ...(next !== "Process" ? { machineTime: 0 } : {}),
+ // Crossing the in-house <-> Outside Processing boundary changes the
+ // meaningful time units; reset to defaults. Switching between in-house
+ // types keeps whatever units the user picked.
+ ...((next === "Outside Processing") !==
+ (d.operationType === "Outside Processing")
+ ? {
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece"
+ }
+ : {})
}));
}}
/>
- <InputControlled
- name="description"
- label={t`Description`}
- value={processData.description}
- onChange={(newValue) => {
- setProcessData((d) => ({ ...d, description: newValue }));
- }}
- className="col-span-2"
- />
-
- {processData.operationType === "Outside" ? (
+ {processData.operationType === "Outside Processing" ? (
<>
<SupplierProcess
name="operationSupplierProcessId"
@@ -2025,9 +2059,29 @@ function OperationForm({
termId="work-center"
/>
)}
+
+ <InputControlled
+ name="description"
+ label={t`Description`}
+ value={processData.description}
+ onChange={(newValue) => {
+ setProcessData((d) => ({ ...d, description: newValue }));
+ }}
+ className="col-span-2"
+ />
+
+ <Select
+ name="operationOrder"
+ label={t`Operation Order`}
+ placeholder={t`Operation Order`}
+ options={methodOperationOrders.map((o) => ({
+ value: o,
+ label: o
+ }))}
+ />
</div>
- {processData.operationType === "Inside" && (
+ {processData.operationType !== "Outside Processing" && (
<>
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -2192,89 +2246,91 @@ function OperationForm({
</div>
</div>
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={machineDisclosure.onToggle}
- >
- <HStack>
- <TimeTypeIcon type="Machine" />
- <Label>
- <Trans>Machine</Trans>
- </Label>
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={machineDisclosure.onToggle}
+ >
+ <HStack>
+ <TimeTypeIcon type="Machine" />
+ <Label>
+ <Trans>Machine</Trans>
+ </Label>
+ </HStack>
+ <HStack>
+ {(processData.machineTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
+ {processData.machineTime} {processData.machineUnit}
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ machineDisclosure.isOpen
+ ? t`Collapse Machine`
+ : t`Expand Machine`
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ machineDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ machineDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- <HStack>
- {(processData.machineTime ?? 0) > 0 && (
- <Badge variant="secondary">
- <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
- {processData.machineTime} {processData.machineUnit}
- </Badge>
- )}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- machineDisclosure.isOpen
- ? t`Collapse Machine`
- : t`Expand Machine`
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ machineDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="machineHint"
+ label={t`Machine`}
+ value={processData.machineUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnitHint: hint,
+ machineUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
+ }));
+ }}
+ />
+ <NumberControlled
+ name="machineTime"
+ label={t`Machine Time`}
+ isOptional={false}
+ minValue={0}
+ value={processData.machineTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineTime: newValue
+ }))
}
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- machineDisclosure.onToggle();
+ />
+ <StandardFactor
+ name="machineUnit"
+ label={t`Machine Unit`}
+ isOptional={false}
+ hint={processData.machineUnitHint}
+ value={processData.machineUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnit: newValue?.value ?? "Total Minutes"
+ }));
}}
- className={`transition-transform ${
- machineDisclosure.isOpen ? "rotate-90" : ""
- }`}
/>
- </HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- machineDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <UnitHint
- name="machineHint"
- label={t`Machine`}
- value={processData.machineUnitHint}
- onChange={(hint) => {
- setProcessData((d) => ({
- ...d,
- machineUnitHint: hint,
- machineUnit:
- hint === "Fixed" ? "Total Minutes" : "Minutes/Piece"
- }));
- }}
- />
- <NumberControlled
- name="machineTime"
- label={t`Machine Time`}
- isOptional={false}
- minValue={0}
- value={processData.machineTime}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- machineTime: newValue
- }))
- }
- />
- <StandardFactor
- name="machineUnit"
- label={t`Machine Unit`}
- isOptional={false}
- hint={processData.machineUnitHint}
- value={processData.machineUnit}
- onChange={(newValue) => {
- setProcessData((d) => ({
- ...d,
- machineUnit: newValue?.value ?? "Total Minutes"
- }));
- }}
- />
+ </div>
</div>
- </div>
+ )}
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -2324,22 +2380,24 @@ function OperationForm({
}))
}
/>
- <NumberControlled
- name="machineRate"
- label={t`Machine Rate`}
- minValue={0}
- value={processData.machineRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- machineRate: newValue
- }))
- }
- />
+ {processData.operationType === "Process" && (
+ <NumberControlled
+ name="machineRate"
+ label={t`Machine Rate`}
+ minValue={0}
+ value={processData.machineRate}
+ formatOptions={{
+ style: "currency",
+ currency: baseCurrency
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineRate: newValue
+ }))
+ }
+ />
+ )}
<NumberControlled
name="overheadRate"
label={t`Overhead Rate`}
@@ -2359,60 +2417,157 @@ function OperationForm({
</div>
</div>
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={procedureDisclosure.onToggle}
- >
- <HStack>
- <LuListChecks />
- <Label>Procedure</Label>
+ {processData.operationType === "Process" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuListChecks />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuListChecks className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
</HStack>
- <HStack>
- {processData.procedureId && (
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label={t`Procedure`}
+ processId={processData.processId}
+ value={processData.procedureId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string
+ }));
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ {processData.operationType === "Assembly" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={assemblyDisclosure.onToggle}
+ >
+ <HStack>
+ <OperationTypeIcon type="Assembly" />
+ <Label>Assembly Instruction</Label>
+ </HStack>
+ <HStack>
+ {processData.assemblyInstructionId && (
+ <Badge variant="secondary">
+ <OperationTypeIcon
+ type="Assembly"
+ className="h-3 w-3 mr-1"
+ />
+ Assembly Instruction
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ assemblyDisclosure.isOpen
+ ? "Collapse Assembly Instruction"
+ : "Expand Assembly Instruction"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ assemblyDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ assemblyDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ assemblyDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <AssemblyInstruction
+ name="assemblyInstructionId"
+ label={t`Assembly Instruction`}
+ itemId={itemId}
+ value={processData.assemblyInstructionId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ assemblyInstructionId: value?.value as string
+ }));
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ {processData.operationType === "Inspection" && (
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <OperationTypeIcon type="Inspection" />
+ <Label>Inspection Plan</Label>
+ </HStack>
+ {processData.inspectionDocumentId && (
<Badge variant="secondary">
- <LuListChecks className="h-3 w-3 mr-1" />
- Procedure
+ <OperationTypeIcon
+ type="Inspection"
+ className="h-3 w-3 mr-1"
+ />
+ Inspection Plan
</Badge>
)}
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- procedureDisclosure.isOpen
- ? "Collapse Procedure"
- : "Expand Procedure"
- }
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- procedureDisclosure.onToggle();
+ </HStack>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4">
+ <InspectionDocument
+ name="inspectionDocumentId"
+ label={t`Inspection Plan`}
+ isOptional={false}
+ itemId={itemId}
+ value={processData.inspectionDocumentId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ inspectionDocumentId: value?.value as string
+ }));
}}
- className={`transition-transform ${
- procedureDisclosure.isOpen ? "rotate-90" : ""
- }`}
/>
- </HStack>
- </HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
- procedureDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <Procedure
- name="procedureId"
- label={t`Procedure`}
- processId={processData.processId}
- value={processData.procedureId}
- onChange={(value) => {
- setProcessData((d) => ({
- ...d,
- procedureId: value?.value as string
- }));
- }}
- />
+ </div>
</div>
- </div>
+ )}
</>
)}
<motion.div
diff --git a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
index 4ba41f3cd7..e8485c7a92 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
@@ -149,7 +149,7 @@ export function useLineCosts({
}
data.operations?.forEach((operation: QuotationOperation) => {
- if (operation.operationType === "Inside") {
+ if (operation.operationType !== "Outside Processing") {
if (operation.setupTime) {
// normalize production standard to hours
let hoursPerUnit = 0;
@@ -357,7 +357,7 @@ export function useLineCosts({
return fixedHours * (operation.overheadRate ?? 0);
}
});
- } else if (operation.operationType === "Outside") {
+ } else {
effects.outsideCost.push((quantity) => {
const unitCost =
operation.operationUnitCost * data.quantity * quantity;
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
index 8c4899e1e5..fac7b3586b 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
@@ -431,8 +431,8 @@ function JobDetails({ job }: { job: Job }) {
{operation.description}
</h3>
<HStack spacing={1}>
- {operation.operationType === "Outside" ? (
- <Badge>Outside</Badge>
+ {operation.operationType === "Outside Processing" ? (
+ <Badge>Outside Processing</Badge>
) : (
<>
{(operation?.setupTime ?? 0) > 0 && (
@@ -467,7 +467,7 @@ function JobDetails({ job }: { job: Job }) {
)}
</HStack>
</HStack>
- {operation.operationType === "Outside" ? (
+ {operation.operationType === "Outside Processing" ? (
<SupplierProcessPreview
processId={operation.processId}
supplierProcessId={
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index cfac4e18f4..af841078ac 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -144,6 +144,10 @@ export const jobCompletedValidator = z.object({
salesJobCompletedNotificationGroup: z.array(z.string()).optional()
});
+export const operationTimerValidator = z.object({
+ autoStartOperationTimer: zfd.checkbox()
+});
+
export const kanbanOutputValidator = z.object({
kanbanOutput: z.enum(kanbanOutputTypes)
});
diff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx
index 1678725a5b..c9e9387021 100644
--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx
+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx
@@ -134,7 +134,7 @@ const CustomFieldForm = ({
/>
)}
- <Boolean name="required" label={t`Required`} />
+ <Boolean name="required" label={t`Required`} bordered />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx
index 7cafffdc0d..3e8cc374f2 100644
--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx
@@ -127,7 +127,7 @@ const WebhookForm = ({
<Separator />
- <Boolean name="active" label={t`Active`} />
+ <Boolean name="active" label={t`Active`} bordered />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index 129b487c0a..22ad15abe1 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -3,6 +3,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import {
incoterms,
+ operationTypes,
procedureStepType,
standardFactorType
} from "./shared.models";
@@ -252,17 +253,20 @@ const methodBomFields = {
}
} as const;
-// BOP operation. Inside operations require time units; Outside operations carry
-// costing and an optional supplier-process link — enforced in the edge function.
+// BOP operation. In-house operations (anything but Outside Processing) require time
+// units; Outside Processing operations carry costing and an optional supplier-process
+// link — enforced in the edge function, which also normalizes the legacy
+// Inside/Outside values from older CSV templates.
const methodBopFields = {
operationType: {
label: "Operation Type",
required: false,
type: "enum",
enumData: {
- description: "Whether the operation is performed in-house or outsourced",
- options: ["Inside", "Outside"],
- default: "Inside"
+ description:
+ "The operation's classification: Process, Assembly, and Inspection run in-house; Outside Processing is subcontracted",
+ options: operationTypes,
+ default: "Process"
}
},
operationOrder: {
@@ -1502,9 +1506,9 @@ export const fieldMappings = {
type: "enum",
enumData: {
description:
- "Whether the process is Inside (in-house), Outside (outsourced), or both",
- options: ["Inside", "Outside", "Inside and Outside"],
- default: "Inside"
+ "The default operation type for operations using this process: Process, Assembly, and Inspection run in-house; Outside Processing is subcontracted. Legacy Inside/Outside values are normalized on import",
+ options: operationTypes,
+ default: "Process"
}
},
defaultStandardFactor: {
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 3f82ee7a39..694c4ff4bb 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -202,7 +202,51 @@ export const noteValidator = z.object({
note: z.string().min(1, { message: "Note is required" })
});
-export const operationTypes = ["Inside", "Outside"] as const;
+// The single operation classification, shared by operations (methodOperation /
+// quoteOperation / jobOperation) and by processes (process.processType) — one
+// Postgres enum backs both so they can never drift. Subcontract logic keys on
+// === "Outside Processing"; in-house logic keys on !== "Outside Processing"
+// (never an enumeration of the in-house values) so future in-house types inherit
+// costing/scheduling/PO behavior unchanged.
+// See .ai/specs/2026-07-20-operation-type-consolidation.md.
+export const operationTypes = [
+ "Process",
+ "Assembly",
+ "Inspection",
+ "Outside Processing"
+] as const;
+
+export type OperationType = (typeof operationTypes)[number];
+
+// Each operation type has exactly one instruction-source pointer: Process →
+// procedureId, Assembly → assemblyInstructionId, Inspection →
+// inspectionDocumentId. Writes go through this so a stale pointer can't survive
+// a type change (sanitize() only nullifies present-undefined keys — it never
+// clears an omitted field). See .ai/specs/2026-07-21-operation-instruction-sources.md.
+export function normalizeOperationSourceIds<
+ T extends {
+ operationType?: string;
+ procedureId?: string | null;
+ assemblyInstructionId?: string | null;
+ inspectionDocumentId?: string | null;
+ }
+>(operation: T): T {
+ return {
+ ...operation,
+ procedureId:
+ operation.operationType === "Process"
+ ? operation.procedureId || null
+ : null,
+ assemblyInstructionId:
+ operation.operationType === "Assembly"
+ ? operation.assemblyInstructionId || null
+ : null,
+ inspectionDocumentId:
+ operation.operationType === "Inspection"
+ ? operation.inspectionDocumentId || null
+ : null
+ };
+}
export const procedureStepType = [
"Task",
@@ -216,6 +260,12 @@ export const procedureStepType = [
"Inspection"
] as const;
+export const feedbackValidator = z.object({
+ feedback: z.string().min(1, { message: "" }),
+ attachmentPath: z.string().optional(),
+ location: z.string()
+});
+
export const processTypes = [
"Inside",
"Outside",
@@ -312,6 +362,68 @@ export const operationStepValidator = z
}
);
+// Display sizes for a step reference image, honored in the BOP editor grid and the MES
+// operator view. Kept as a plain const tuple so both the zod enum and the UI reuse it.
+export const slideSizes = ["small", "medium", "large"] as const;
+export type SlideSize = (typeof slideSizes)[number];
+
+// A single numbered annotation pin overlaid on a slide image. x/y are fractions (0..1) of
+// the image box so a pin stays put at any rendered size. The pin's number is its position
+// in the array (index + 1); label + color are optional.
+export const slideAnnotationValidator = z.object({
+ id: z.string(),
+ x: z.number().min(0).max(1),
+ y: z.number().min(0).max(1),
+ label: z.string().optional(),
+ color: z.string().optional(),
+ // Optional "smart hotspot" link: the tool (item) this pin points at. Matches an
+ // operationTool.toolId, so the MES view can name the tool and badge it with the
+ // pin's sequence number. The pin's number (array index + 1) is the fastener order.
+ toolId: z.string().optional()
+});
+export type SlideAnnotation = z.infer<typeof slideAnnotationValidator>;
+
+// A reference "slide" attached to an operation step — either an image (`imagePath`) or a
+// 3D model (`modelUploadId` → modelUpload; STEP sources are converted to GLB by the
+// assembler service). Authored on the method and copied to job/quote by get-method.
+// A create must carry one of the two; updates may omit both (sanitize() drops absent
+// fields so a caption/size-only save never wipes the content). Pins are image-only.
+// `annotations` arrives over FormData as a JSON string and is parsed into an array here.
+export const operationStepSlideValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ stepId: z.string().min(1, { message: "Step is required" }),
+ imagePath: zfd.text(z.string().optional()),
+ modelUploadId: zfd.text(z.string().optional()),
+ caption: zfd.text(z.string().optional()),
+ sortOrder: zfd.numeric(z.number().min(0).optional()),
+ size: zfd.text(z.enum(slideSizes).optional()),
+ // Absent = "not changed" (preserve on update / default on insert); a JSON string (incl.
+ // "[]" to clear) = the new pin set. Returning undefined when absent lets sanitize() drop
+ // it so a caption/size-only save never wipes existing annotations.
+ annotations: zfd.text(z.string().optional()).transform((value, ctx) => {
+ if (!value) return undefined;
+ try {
+ return z.array(slideAnnotationValidator).parse(JSON.parse(value));
+ } catch {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Invalid annotations"
+ });
+ return z.NEVER;
+ }
+ })
+ })
+ .superRefine((slide, ctx) => {
+ if (!slide.id && !slide.imagePath && !slide.modelUploadId) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "An image or model is required",
+ path: ["imagePath"]
+ });
+ }
+ });
+
export const operationToolValidator = z.object({
id: zfd.text(z.string().optional()),
operationId: z.string().min(1, { message: "Operation is required" }),
diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.ts
index ae36943ece..4fd3712867 100644
--- a/apps/erp/app/modules/shared/types.ts
+++ b/apps/erp/app/modules/shared/types.ts
@@ -12,6 +12,8 @@ import type {
operationParameterValidator,
operationStepValidator,
operationToolValidator,
+ SlideAnnotation,
+ SlideSize,
sourcingType,
standardFactorType
} from "./shared.models";
@@ -102,11 +104,24 @@ export type Note = NonNullable<
Awaited<ReturnType<typeof getNotes>>["data"]
>[number];
+export type OperationStepSlide = {
+ id: string;
+ stepId: string;
+ // A slide is image XOR model: exactly one of imagePath / modelUploadId is set.
+ imagePath: string | null;
+ modelUploadId: string | null;
+ caption: string | null;
+ sortOrder: number;
+ size: SlideSize | null;
+ annotations: SlideAnnotation[] | null;
+};
+
export type OperationStep = z.infer<typeof operationStepValidator> & {
createdBy: string;
createdAt: string;
updatedBy: string | null;
updatedAt: string | null;
+ methodOperationStepSlide?: OperationStepSlide[];
};
export type OperationTool = z.infer<typeof operationToolValidator> & {
@@ -114,6 +129,11 @@ export type OperationTool = z.infer<typeof operationToolValidator> & {
createdAt: string;
updatedBy: string | null;
updatedAt: string | null;
+ // Phase 2 (tool ↔ step, many-to-many): the step ids this tool is scoped to. Empty = the
+ // whole operation. Not part of the tier-agnostic validator; populated by the loader from
+ // the methodOperationToolStep / jobOperationToolStep join rows.
+ methodOperationStepIds?: string[];
+ jobOperationStepIds?: string[];
};
export type OperationParameter = z.infer<typeof operationParameterValidator> & {
diff --git a/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx b/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx
index 36f8789205..2cc396f306 100644
--- a/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx
+++ b/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx
@@ -158,6 +158,7 @@ export default function StorageRuleForm({
name="appliesToAll"
label={t`Applies to all work centers`}
description={t`When on, this rule fires for every target of its type. Assignment rows are ignored but preserved.`}
+ bordered
/>
)}
<SurfacesField
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index b1e9a5f8c1..01181f5a12 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-07-23T20:18:33.549Z",
- "totalTools": 1377,
+ "generated": "2026-07-28T02:27:47.871Z",
+ "totalTools": 1397,
"modules": 15,
"tools": [
{
@@ -1636,7 +1636,7 @@
"module": "accounting",
"classification": "WRITE",
"description": "update default income accounts",
- "paramCount": 27,
+ "paramCount": 28,
"serviceParams": [
"client",
"defaultAccounts"
@@ -1663,6 +1663,9 @@
"inventoryAdjustmentVarianceAccount": {
"type": "string"
},
+ "scrapAccount": {
+ "type": "string"
+ },
"materialVarianceAccount": {
"type": "string"
},
@@ -10753,6 +10756,31 @@
]
}
},
+ {
+ "name": "items_deleteMethodOperationStepSlide",
+ "module": "items",
+ "classification": "DESTRUCTIVE",
+ "description": "delete method operation step slide",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
{
"name": "items_deleteMethodOperationParameter",
"module": "items",
@@ -14165,6 +14193,58 @@
]
}
},
+ {
+ "name": "items_duplicateMethodOperationStep",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "duplicate method operation step",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "items_upsertMethodOperationStepSlide",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "upsert method operation step slide",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "slide"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "slide": {}
+ },
+ "required": [
+ "slide"
+ ]
+ }
+ },
{
"name": "items_upsertMethodOperationParameter",
"module": "items",
@@ -14215,6 +14295,107 @@
]
}
},
+ {
+ "name": "items_replaceMethodMaterialSteps",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "replace method material steps",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "methodMaterialId",
+ "methodOperationStepIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "methodMaterialId": {
+ "type": "string"
+ },
+ "methodOperationStepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "methodMaterialId",
+ "methodOperationStepIds"
+ ]
+ }
+ },
+ {
+ "name": "items_setMethodMaterialStepLink",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "set method material step link",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "methodMaterialId": {
+ "type": "string"
+ },
+ "methodOperationStepId": {
+ "type": "string"
+ },
+ "linked": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "methodMaterialId",
+ "methodOperationStepId",
+ "linked"
+ ]
+ }
+ },
+ {
+ "name": "items_setMethodOperationToolStepLink",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "set method operation tool step link",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "methodOperationToolId": {
+ "type": "string"
+ },
+ "methodOperationStepId": {
+ "type": "string"
+ },
+ "linked": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "methodOperationToolId",
+ "methodOperationStepId",
+ "linked"
+ ]
+ }
+ },
{
"name": "items_upsertMaterial",
"module": "items",
@@ -17469,6 +17650,31 @@
]
}
},
+ {
+ "name": "production_deleteJobOperationStepSlide",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete job operation step slide",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
{
"name": "production_deleteJobOperationParameter",
"module": "production",
@@ -20727,6 +20933,58 @@
]
}
},
+ {
+ "name": "production_duplicateJobOperationStep",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "duplicate job operation step",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertJobOperationStepSlide",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert job operation step slide",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "slide"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "slide": {}
+ },
+ "required": [
+ "slide"
+ ]
+ }
+ },
{
"name": "production_upsertJobOperationParameter",
"module": "production",
@@ -20778,30 +21036,131 @@
}
},
{
- "name": "production_upsertJobMethod",
+ "name": "production_replaceJobMaterialSteps",
"module": "production",
"classification": "WRITE",
- "description": "upsert job method",
+ "description": "replace job material steps",
"paramCount": 2,
"serviceParams": [
"client",
- "type",
- "jobMethod"
+ "jobMaterialId",
+ "jobOperationStepIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "jobMaterialId": {
+ "type": "string"
+ },
+ "jobOperationStepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "jobMaterialId",
+ "jobOperationStepIds"
+ ]
+ }
+ },
+ {
+ "name": "production_setJobMaterialStepLink",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "set job material step link",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "args"
],
"injectAuth": [
"companyId",
- "createdBy",
"updatedBy"
],
"schema": {
"type": "object",
"properties": {
- "type": {
- "type": "string",
- "enum": [
- "itemToJob",
- "quoteLineToJob"
- ]
+ "jobMaterialId": {
+ "type": "string"
+ },
+ "jobOperationStepId": {
+ "type": "string"
+ },
+ "linked": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "jobMaterialId",
+ "jobOperationStepId",
+ "linked"
+ ]
+ }
+ },
+ {
+ "name": "production_setJobOperationToolStepLink",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "set job operation tool step link",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "jobOperationToolId": {
+ "type": "string"
+ },
+ "jobOperationStepId": {
+ "type": "string"
+ },
+ "linked": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "jobOperationToolId",
+ "jobOperationStepId",
+ "linked"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertJobMethod",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert job method",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "type",
+ "jobMethod"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "itemToJob",
+ "quoteLineToJob"
+ ]
},
"jobMethod": {
"type": "object",
@@ -21670,6 +22029,32 @@
}
}
},
+ {
+ "name": "production_getAssemblyInstructionsForItem",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instructions for item",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "itemId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
{
"name": "production_getModelForItem",
"module": "production",
@@ -22136,10 +22521,10 @@
}
},
{
- "name": "production_getAssemblyInstructionStepRequirements",
+ "name": "production_getAssemblyInstructionStepSlides",
"module": "production",
"classification": "READ",
- "description": "get assembly instruction step requirements",
+ "description": "get assembly instruction step slides",
"paramCount": 1,
"serviceParams": [
"client",
@@ -22164,14 +22549,14 @@
}
},
{
- "name": "production_upsertAssemblyInstructionStepRequirement",
+ "name": "production_upsertAssemblyInstructionStepSlide",
"module": "production",
"classification": "WRITE",
- "description": "upsert assembly instruction step requirement",
- "paramCount": 10,
+ "description": "upsert assembly instruction step slide",
+ "paramCount": 1,
"serviceParams": [
"client",
- "data"
+ "slide"
],
"injectAuth": [
"companyId",
@@ -22181,63 +22566,18 @@
"schema": {
"type": "object",
"properties": {
- "id": {
- "type": "string"
- },
- "stepId": {
- "type": "string"
- },
- "type": {
- "type": "string"
- },
- "itemId": {
- "type": [
- "string",
- "null"
- ]
- },
- "name": {
- "type": [
- "string",
- "null"
- ]
- },
- "text": {
- "type": [
- "string",
- "null"
- ]
- },
- "severity": {
- "type": [
- "string",
- "null"
- ]
- },
- "filePath": {
- "type": [
- "string",
- "null"
- ]
- },
- "quantity": {
- "type": "number"
- },
- "sortOrder": {
- "type": "number"
- }
+ "slide": {}
},
"required": [
- "stepId",
- "type"
+ "slide"
]
}
},
{
- "name": "production_getAssemblyInstructionStepRequirement",
+ "name": "production_deleteAssemblyInstructionStepSlide",
"module": "production",
- "classification": "READ",
- "description": "get assembly instruction step requirement",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly instruction step slide",
"paramCount": 1,
"serviceParams": [
"client",
@@ -22259,17 +22599,46 @@
}
},
{
- "name": "production_updateAssemblyInstructionStepRequirementOrder",
+ "name": "production_getAssemblyInstructionStepTools",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction step tools",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "stepIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "stepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "stepIds"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyInstructionStepTool",
"module": "production",
"classification": "WRITE",
- "description": "update assembly instruction step requirement order",
- "paramCount": 2,
+ "description": "upsert assembly instruction step tool",
+ "paramCount": 5,
"serviceParams": [
- "db",
- "updates"
+ "client",
+ "data"
],
"injectAuth": [
"companyId",
+ "createdBy",
"updatedBy"
],
"schema": {
@@ -22278,21 +22647,30 @@
"id": {
"type": "string"
},
+ "stepId": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": "number"
+ },
"sortOrder": {
"type": "number"
}
},
"required": [
- "id",
- "sortOrder"
+ "stepId",
+ "itemId"
]
}
},
{
- "name": "production_deleteAssemblyInstructionStepRequirement",
+ "name": "production_deleteAssemblyInstructionStepTool",
"module": "production",
"classification": "DESTRUCTIVE",
- "description": "delete assembly instruction step requirement",
+ "description": "delete assembly instruction step tool",
"paramCount": 1,
"serviceParams": [
"client",
@@ -22484,29 +22862,36 @@
}
},
{
- "name": "production_getAssemblyStandardNotes",
+ "name": "production_getAssemblyUnits",
"module": "production",
"classification": "READ",
- "description": "get assembly standard notes",
- "paramCount": 0,
+ "description": "get assembly units",
+ "paramCount": 1,
"serviceParams": [
"client",
- "companyId"
+ "modelUploadId"
],
"injectAuth": [
"companyId"
],
"schema": {
"type": "object",
- "properties": {}
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
}
},
{
- "name": "production_upsertAssemblyStandardNote",
+ "name": "production_upsertAssemblyUnit",
"module": "production",
"classification": "WRITE",
- "description": "upsert assembly standard note",
- "paramCount": 4,
+ "description": "upsert assembly unit",
+ "paramCount": 5,
"serviceParams": [
"client",
"data"
@@ -22522,28 +22907,37 @@
"id": {
"type": "string"
},
- "name": {
+ "modelUploadId": {
"type": "string"
},
- "content": {
+ "name": {
"type": "string"
},
- "severity": {
- "type": "string"
+ "componentNodeIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "itemId": {
+ "type": [
+ "string",
+ "null"
+ ]
}
},
"required": [
+ "modelUploadId",
"name",
- "content",
- "severity"
+ "componentNodeIds"
]
}
},
{
- "name": "production_deleteAssemblyStandardNote",
+ "name": "production_deleteAssemblyUnit",
"module": "production",
"classification": "DESTRUCTIVE",
- "description": "delete assembly standard note",
+ "description": "delete assembly unit",
"paramCount": 1,
"serviceParams": [
"client",
@@ -22565,10 +22959,10 @@
}
},
{
- "name": "production_getAssemblyUnits",
+ "name": "production_getLatestAssemblyPlan",
"module": "production",
"classification": "READ",
- "description": "get assembly units",
+ "description": "get latest assembly plan",
"paramCount": 1,
"serviceParams": [
"client",
@@ -22590,114 +22984,17 @@
}
},
{
- "name": "production_upsertAssemblyUnit",
+ "name": "production_getLatestAssemblyPlanJob",
"module": "production",
- "classification": "WRITE",
- "description": "upsert assembly unit",
- "paramCount": 5,
+ "classification": "READ",
+ "description": "get latest assembly plan job",
+ "paramCount": 1,
"serviceParams": [
"client",
- "data"
+ "modelUploadId"
],
"injectAuth": [
- "companyId",
- "createdBy",
- "updatedBy"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string"
- },
- "modelUploadId": {
- "type": "string"
- },
- "name": {
- "type": "string"
- },
- "componentNodeIds": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "itemId": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "modelUploadId",
- "name",
- "componentNodeIds"
- ]
- }
- },
- {
- "name": "production_deleteAssemblyUnit",
- "module": "production",
- "classification": "DESTRUCTIVE",
- "description": "delete assembly unit",
- "paramCount": 1,
- "serviceParams": [
- "client",
- "id"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string"
- }
- },
- "required": [
- "id"
- ]
- }
- },
- {
- "name": "production_getLatestAssemblyPlan",
- "module": "production",
- "classification": "READ",
- "description": "get latest assembly plan",
- "paramCount": 1,
- "serviceParams": [
- "client",
- "modelUploadId"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "modelUploadId": {
- "type": "string"
- }
- },
- "required": [
- "modelUploadId"
- ]
- }
- },
- {
- "name": "production_getLatestAssemblyPlanJob",
- "module": "production",
- "classification": "READ",
- "description": "get latest assembly plan job",
- "paramCount": 1,
- "serviceParams": [
- "client",
- "modelUploadId"
- ],
- "injectAuth": [
- "companyId"
+ "companyId"
],
"schema": {
"type": "object",
@@ -22906,6 +23203,152 @@
]
}
},
+ {
+ "name": "production_planAssemblyStepMarkerSync",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "plan assembly step marker sync",
+ "paramCount": 2,
+ "serviceParams": [
+ "sourceStepIds",
+ "existingSynced"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "sourceStepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "existingSynced": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "assemblyInstructionStepId": {
+ "type": "array",
+ "items": {}
+ }
+ },
+ "required": [
+ "id",
+ "assemblyInstructionStepId"
+ ]
+ }
+ },
+ "required": [
+ "sourceStepIds",
+ "existingSynced"
+ ]
+ }
+ },
+ {
+ "name": "production_maxToolQuantityByItem",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "max tool quantity by item",
+ "paramCount": 2,
+ "serviceParams": [
+ "sourceTools"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": "array",
+ "items": {}
+ }
+ },
+ "required": [
+ "itemId",
+ "quantity"
+ ]
+ }
+ },
+ {
+ "name": "production_buildAssemblyToolStepLinks",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "build assembly tool step links",
+ "paramCount": 4,
+ "serviceParams": [
+ "sourceSteps",
+ "toolsByStep",
+ "toolRowIdByItemId",
+ "targetIdBySource"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "sourceSteps": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "array",
+ "items": {}
+ }
+ },
+ "required": [
+ "id"
+ ]
+ },
+ "toolsByStep": {},
+ "toolRowIdByItemId": {},
+ "targetIdBySource": {}
+ },
+ "required": [
+ "sourceSteps",
+ "toolsByStep",
+ "toolRowIdByItemId",
+ "targetIdBySource"
+ ]
+ }
+ },
+ {
+ "name": "production_syncAssemblyInstructionToOperation",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "sync assembly instruction to operation",
+ "paramCount": 2,
+ "serviceParams": [
+ "db",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "assemblyInstructionId": {
+ "type": "string"
+ },
+ "operationId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "assemblyInstructionId",
+ "operationId"
+ ]
+ }
+ },
{
"name": "production_generateAssemblyStepsFromPlan",
"module": "production",
@@ -23014,8 +23457,324 @@
}
},
"required": [
- "materials",
- "locationId"
+ "materials",
+ "locationId"
+ ]
+ }
+ },
+ {
+ "name": "production_getInspectionDocuments",
+ "module": "production",
+ "classification": "READ",
+ "description": "get inspection documents",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "search": {
+ "type": "object",
+ "properties": {
+ "limit": {
+ "type": "integer",
+ "default": 100
+ },
+ "offset": {
+ "type": "integer",
+ "default": 0
+ }
+ }
+ }
+ },
+ "required": [
+ "search"
+ ]
+ }
+ },
+ {
+ "name": "production_getInspectionDocumentsForItem",
+ "module": "production",
+ "classification": "READ",
+ "description": "get inspection documents for item",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "itemId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "production_getInspectionDocument",
+ "module": "production",
+ "classification": "READ",
+ "description": "get inspection document",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertInspectionDocument",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert inspection document",
+ "paramCount": 7,
+ "serviceParams": [
+ "client",
+ "diagram"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "partId": {
+ "type": "string"
+ },
+ "drawingNumber": {
+ "type": "string"
+ },
+ "pdfUrl": {
+ "type": "string"
+ },
+ "annotations": {
+ "type": "string"
+ },
+ "features": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "partId"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteInspectionDocument",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete inspection document",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getInspectionFeatures",
+ "module": "production",
+ "classification": "READ",
+ "description": "get inspection features",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "inspectionDocumentId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "inspectionDocumentId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "inspectionDocumentId"
+ ]
+ }
+ },
+ {
+ "name": "production_getBalloons",
+ "module": "production",
+ "classification": "READ",
+ "description": "get balloons",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "inspectionDocumentId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "inspectionDocumentId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "inspectionDocumentId"
+ ]
+ }
+ },
+ {
+ "name": "production_getInspectionPlan",
+ "module": "production",
+ "classification": "READ",
+ "description": "get inspection plan",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "inspectionDocumentId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "inspectionDocumentId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "inspectionDocumentId"
+ ]
+ }
+ },
+ {
+ "name": "production_updateInspectionDocumentSampling",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update inspection document sampling",
+ "paramCount": 6,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "samplingPlanType": {
+ "type": "string"
+ },
+ "samplingSampleSize": {
+ "type": "number"
+ },
+ "samplingPercentage": {
+ "type": "number"
+ },
+ "samplingAql": {
+ "type": "number"
+ },
+ "samplingInspectionLevel": {
+ "type": "string"
+ },
+ "samplingSeverity": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ {
+ "name": "production_saveInspectionDocumentAtomic",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "save inspection document atomic",
+ "paramCount": 7,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "inspectionDocumentId": {
+ "type": "string"
+ },
+ "pdfUrl": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "pageCount": {
+ "type": "number"
+ },
+ "defaultPageWidth": {
+ "type": "number"
+ },
+ "defaultPageHeight": {
+ "type": "number"
+ },
+ "features": {},
+ "balloons": {}
+ },
+ "required": [
+ "inspectionDocumentId",
+ "features",
+ "balloons"
]
}
},
@@ -28796,11 +29555,11 @@
}
},
{
- "name": "quality_getInspectionDocuments",
+ "name": "quality_getInspections",
"module": "quality",
"classification": "READ",
- "description": "get inspection documents",
- "paramCount": 1,
+ "description": "get inspections",
+ "paramCount": 5,
"serviceParams": [
"client",
"companyId",
@@ -28812,7 +29571,7 @@
"schema": {
"type": "object",
"properties": {
- "search": {
+ "args": {
"type": "object",
"properties": {
"limit": {
@@ -28822,20 +29581,35 @@
"offset": {
"type": "integer",
"default": 0
+ },
+ "search": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "status": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "source": {
+ "type": [
+ "string",
+ "null"
+ ]
}
}
}
- },
- "required": [
- "search"
- ]
+ }
}
},
{
- "name": "quality_getInspectionDocument",
+ "name": "quality_getInspection",
"module": "quality",
"classification": "READ",
- "description": "get inspection document",
+ "description": "get inspection",
"paramCount": 1,
"serviceParams": [
"client",
@@ -28857,59 +29631,15 @@
}
},
{
- "name": "quality_upsertInspectionDocument",
- "module": "quality",
- "classification": "WRITE",
- "description": "upsert inspection document",
- "paramCount": 7,
- "serviceParams": [
- "client",
- "diagram"
- ],
- "injectAuth": [
- "companyId",
- "createdBy",
- "updatedBy"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string"
- },
- "name": {
- "type": "string"
- },
- "partId": {
- "type": "string"
- },
- "drawingNumber": {
- "type": "string"
- },
- "pdfUrl": {
- "type": "string"
- },
- "annotations": {
- "type": "string"
- },
- "features": {
- "type": "string"
- }
- },
- "required": [
- "partId"
- ]
- }
- },
- {
- "name": "quality_deleteInspectionDocument",
+ "name": "quality_getReceiptInspections",
"module": "quality",
- "classification": "DESTRUCTIVE",
- "description": "delete inspection document",
+ "classification": "READ",
+ "description": "get receipt inspections",
"paramCount": 1,
"serviceParams": [
"client",
- "id"
+ "receiptId",
+ "companyId"
],
"injectAuth": [
"companyId"
@@ -28917,24 +29647,25 @@
"schema": {
"type": "object",
"properties": {
- "id": {
+ "receiptId": {
"type": "string"
}
},
"required": [
- "id"
+ "receiptId"
]
}
},
{
- "name": "quality_getInspectionFeatures",
+ "name": "quality_getInspectionTrackedEntities",
"module": "quality",
"classification": "READ",
- "description": "get inspection features",
+ "description": "get inspection tracked entities",
"paramCount": 1,
"serviceParams": [
"client",
- "inspectionDocumentId"
+ "receiptLineId",
+ "companyId"
],
"injectAuth": [
"companyId"
@@ -28942,24 +29673,25 @@
"schema": {
"type": "object",
"properties": {
- "inspectionDocumentId": {
+ "receiptLineId": {
"type": "string"
}
},
"required": [
- "inspectionDocumentId"
+ "receiptLineId"
]
}
},
{
- "name": "quality_getBalloons",
+ "name": "quality_getInspectionSamplingPlans",
"module": "quality",
"classification": "READ",
- "description": "get balloons",
+ "description": "get inspection sampling plans",
"paramCount": 1,
"serviceParams": [
"client",
- "inspectionDocumentId"
+ "inspectionId",
+ "companyId"
],
"injectAuth": [
"companyId"
@@ -28967,89 +29699,46 @@
"schema": {
"type": "object",
"properties": {
- "inspectionDocumentId": {
+ "inspectionId": {
"type": "string"
}
},
"required": [
- "inspectionDocumentId"
+ "inspectionId"
]
}
},
{
- "name": "quality_getInspectionPlan",
+ "name": "quality_getInspectionMeasurements",
"module": "quality",
"classification": "READ",
- "description": "get inspection plan",
+ "description": "get inspection measurements",
"paramCount": 1,
"serviceParams": [
"client",
- "inspectionDocumentId"
- ],
- "injectAuth": [
+ "inspectionId",
"companyId"
],
- "schema": {
- "type": "object",
- "properties": {
- "inspectionDocumentId": {
- "type": "string"
- }
- },
- "required": [
- "inspectionDocumentId"
- ]
- }
- },
- {
- "name": "quality_saveInspectionDocumentAtomic",
- "module": "quality",
- "classification": "WRITE",
- "description": "save inspection document atomic",
- "paramCount": 7,
- "serviceParams": [
- "client",
- "args"
- ],
"injectAuth": [
"companyId"
],
"schema": {
"type": "object",
"properties": {
- "inspectionDocumentId": {
+ "inspectionId": {
"type": "string"
- },
- "pdfUrl": {
- "type": [
- "string",
- "null"
- ]
- },
- "pageCount": {
- "type": "number"
- },
- "defaultPageWidth": {
- "type": "number"
- },
- "defaultPageHeight": {
- "type": "number"
- },
- "features": {},
- "balloons": {}
+ }
},
"required": [
- "inspectionDocumentId",
- "features",
- "balloons"
+ "inspectionId"
]
}
},
{
- "name": "quality_getItemSamplingPlan",
+ "name": "quality_getItemInspectionDocumentAssignments",
"module": "quality",
"classification": "READ",
- "description": "get item sampling plan",
+ "description": "get item inspection document assignments",
"paramCount": 1,
"serviceParams": [
"client",
@@ -29072,14 +29761,14 @@
}
},
{
- "name": "quality_upsertItemSamplingPlan",
+ "name": "quality_upsertItemInspectionDocumentAssignment",
"module": "quality",
"classification": "WRITE",
- "description": "upsert item sampling plan",
- "paramCount": 1,
+ "description": "upsert item inspection document assignment",
+ "paramCount": 2,
"serviceParams": [
"client",
- "plan"
+ "assignment"
],
"injectAuth": [
"companyId",
@@ -29089,106 +29778,15 @@
"schema": {
"type": "object",
"properties": {
- "plan": {}
- },
- "required": [
- "plan"
- ]
- }
- },
- {
- "name": "quality_getInboundInspections",
- "module": "quality",
- "classification": "READ",
- "description": "get inbound inspections",
- "paramCount": 4,
- "serviceParams": [
- "client",
- "companyId",
- "args"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "args": {
- "type": "object",
- "properties": {
- "limit": {
- "type": "integer",
- "default": 100
- },
- "offset": {
- "type": "integer",
- "default": 0
- },
- "search": {
- "type": [
- "string",
- "null"
- ]
- },
- "status": {
- "type": [
- "string",
- "null"
- ]
- }
- }
- }
- }
- }
- },
- {
- "name": "quality_getInboundInspection",
- "module": "quality",
- "classification": "READ",
- "description": "get inbound inspection",
- "paramCount": 1,
- "serviceParams": [
- "client",
- "id"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "id": {
+ "itemId": {
"type": "string"
- }
- },
- "required": [
- "id"
- ]
- }
- },
- {
- "name": "quality_getInboundInspectionLotTrackedEntities",
- "module": "quality",
- "classification": "READ",
- "description": "get inbound inspection lot tracked entities",
- "paramCount": 1,
- "serviceParams": [
- "client",
- "receiptLineId",
- "companyId"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "receiptLineId": {
+ },
+ "usage": {
"type": "string"
}
},
"required": [
- "receiptLineId"
+ "itemId"
]
}
},
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index b6b6ce1122..a2567b5776 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -2,6 +2,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { trigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
+import { isAssemblerServiceHealthy } from "~/modules/production/production.server";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
@@ -13,6 +14,7 @@ export async function action({ request }: ActionFunctionArgs) {
const name = formData.get("name") as string;
const modelPath = formData.get("modelPath") as string;
const size = parseInt(formData.get("size") as string);
+ const convert = formData.get("convert") === "true";
const itemId = formData.get("itemId") as string | null;
const salesRfqLineId = formData.get("salesRfqLineId") as string | null;
@@ -86,6 +88,27 @@ export async function action({ request }: ActionFunctionArgs) {
// Thumbnail is generated by model-optimize on success (it renders the GLB the
// optimise produces) — firing it here, before the GLB exists, always failed.
+ // Conversion to assembly-instruction artifacts (GLB + graph) is lazy by
+ // default: most uploaded models never become assemblies. Callers that will
+ // render the model on the shop floor (e.g. BOP step model slides) opt in
+ // with `convert` so the assembler service produces the fast-loading GLB up
+ // front. Best-effort: STEP-only, skipped when the assembler is down — the
+ // viewer falls back to parsing the raw model client-side.
+ const isStep = [".step", ".stp"].some((ext) =>
+ modelPath.toLowerCase().endsWith(ext)
+ );
+ if (convert && isStep && (await isAssemblerServiceHealthy())) {
+ try {
+ await trigger("assembly-convert", {
+ companyId,
+ modelUploadId: modelId,
+ userId
+ });
+ } catch (err) {
+ console.error("Failed to start model conversion", err);
+ }
+ }
+
// Eager optimisation: the assembler's /v1/optimize turns a mesh model into a
// compact optimised GLB. The job derives the format from the stored file and
// skips non-mesh inputs, so trigger unconditionally. Independent of the lazy
diff --git a/apps/erp/app/routes/api+/production.assembly-for-item.$itemId.ts b/apps/erp/app/routes/api+/production.assembly-for-item.$itemId.ts
new file mode 100644
index 0000000000..0bae348985
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.assembly-for-item.$itemId.ts
@@ -0,0 +1,29 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+
+// The item's most relevant assembly instruction for the BOP editors' steps-source
+// panel: a Published one wins (it can be synced), else the newest Draft/Archived
+// (it can be opened/finished), else null (one can be created from the item's model).
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production"
+ });
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const instructions = await client
+ .from("assemblyInstruction")
+ .select("id, status, name")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .order("updatedAt", { ascending: false, nullsFirst: false });
+
+ const rows = instructions.data ?? [];
+ const instruction =
+ rows.find((row) => row.status === "Published") ??
+ rows.find((row) => row.status === "Draft") ??
+ rows[0] ??
+ null;
+
+ return { instruction };
+}
diff --git a/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts b/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts
new file mode 100644
index 0000000000..2834dd1afd
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts
@@ -0,0 +1,47 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type {
+ ClientLoaderFunctionArgs,
+ LoaderFunctionArgs
+} from "react-router";
+import { data } from "react-router";
+import { getAssemblyInstructionsForItem } from "~/modules/production";
+import { assemblyInstructionsQuery, getCompanyId } from "~/utils/react-query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production"
+ });
+
+ const { itemId } = params;
+ if (!itemId) {
+ return data({ error: "Item ID is required" }, { status: 400 });
+ }
+
+ return await getAssemblyInstructionsForItem(client, itemId, companyId);
+}
+
+export async function clientLoader({
+ params,
+ serverLoader
+}: ClientLoaderFunctionArgs) {
+ const companyId = getCompanyId();
+
+ if (!companyId || !params.itemId) {
+ return await serverLoader<typeof loader>();
+ }
+
+ const query = assemblyInstructionsQuery(params.itemId, companyId);
+ const data = window?.clientCache?.getQueryData<
+ Awaited<ReturnType<typeof loader>>
+ >(query.queryKey);
+
+ if (!data) {
+ const serverData = await serverLoader<typeof loader>();
+ window?.clientCache?.setQueryData(query.queryKey, serverData);
+ return serverData;
+ }
+
+ return data;
+}
+
+clientLoader.hydrate = true;
diff --git a/apps/erp/app/routes/api+/quality.inspection-document.$inspectionDocumentId.balloon-analyze.ts b/apps/erp/app/routes/api+/production.inspection-document.$inspectionDocumentId.balloon-analyze.ts
similarity index 82%
rename from apps/erp/app/routes/api+/quality.inspection-document.$inspectionDocumentId.balloon-analyze.ts
rename to apps/erp/app/routes/api+/production.inspection-document.$inspectionDocumentId.balloon-analyze.ts
index 9e5b24fa5d..aa24453721 100644
--- a/apps/erp/app/routes/api+/quality.inspection-document.$inspectionDocumentId.balloon-analyze.ts
+++ b/apps/erp/app/routes/api+/production.inspection-document.$inspectionDocumentId.balloon-analyze.ts
@@ -2,12 +2,12 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { balloonRegionAnalysisRequestSchema } from "~/modules/quality/inspectionBalloonAnalyze";
+import { balloonRegionAnalysisRequestSchema } from "~/modules/production/inspectionBalloonAnalyze";
import {
INSPECTION_BALLOON_ANALYZE_MAX_IMAGE_BYTES,
runInspectionBalloonRegionVisionAnalysis
-} from "~/modules/quality/inspectionBalloonAnalyze.server";
-import { getInspectionDocument } from "~/modules/quality/quality.service";
+} from "~/modules/production/inspectionBalloonAnalyze.server";
+import { getInspectionDocument } from "~/modules/production/production.service";
function getErrorMessage(error: unknown, fallback: string) {
if (error instanceof Error) return error.message;
@@ -32,27 +32,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
const inspectionDocumentId = params.inspectionDocumentId;
if (!inspectionDocumentId) {
return data(
- { success: false as const, message: "Missing inspection document id" },
+ { success: false as const, message: "Missing inspection plan id" },
{ status: 400 }
);
}
- const docResult = await getInspectionDocument(client, inspectionDocumentId);
+ const docResult = await getInspectionDocument(
+ client,
+ inspectionDocumentId,
+ companyId
+ );
if (docResult.error || !docResult.data) {
return data(
{
success: false as const,
- message: getErrorMessage(
- docResult.error,
- "Inspection document not found"
- )
+ message: getErrorMessage(docResult.error, "Inspection plan not found")
},
{ status: 404 }
);
}
if (docResult.data.companyId !== companyId) {
return data(
- { success: false as const, message: "Inspection document not found" },
+ { success: false as const, message: "Inspection plan not found" },
{ status: 404 }
);
}
diff --git a/apps/erp/app/routes/api+/production.inspection-documents.$itemId.ts b/apps/erp/app/routes/api+/production.inspection-documents.$itemId.ts
new file mode 100644
index 0000000000..a445f2fd40
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.inspection-documents.$itemId.ts
@@ -0,0 +1,47 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type {
+ ClientLoaderFunctionArgs,
+ LoaderFunctionArgs
+} from "react-router";
+import { data } from "react-router";
+import { getInspectionDocumentsForItem } from "~/modules/production";
+import { getCompanyId, inspectionDocumentsQuery } from "~/utils/react-query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production"
+ });
+
+ const { itemId } = params;
+ if (!itemId) {
+ return data({ error: "Item ID is required" }, { status: 400 });
+ }
+
+ return await getInspectionDocumentsForItem(client, itemId, companyId);
+}
+
+export async function clientLoader({
+ params,
+ serverLoader
+}: ClientLoaderFunctionArgs) {
+ const companyId = getCompanyId();
+
+ if (!companyId || !params.itemId) {
+ return await serverLoader<typeof loader>();
+ }
+
+ const query = inspectionDocumentsQuery(params.itemId, companyId);
+ const data = window?.clientCache?.getQueryData<
+ Awaited<ReturnType<typeof loader>>
+ >(query.queryKey);
+
+ if (!data) {
+ const serverData = await serverLoader<typeof loader>();
+ window?.clientCache?.setQueryData(query.queryKey, serverData);
+ return serverData;
+ }
+
+ return data;
+}
+
+clientLoader.hydrate = true;
diff --git a/apps/erp/app/routes/api+/quality.inspection-plan.$id.ts b/apps/erp/app/routes/api+/quality.inspection-plan.$id.ts
index 6460a83404..d371de2be9 100644
--- a/apps/erp/app/routes/api+/quality.inspection-plan.$id.ts
+++ b/apps/erp/app/routes/api+/quality.inspection-plan.$id.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
-import { getInspectionDocument, getInspectionPlan } from "~/modules/quality";
+import { getInspectionDocument, getInspectionPlan } from "~/modules/production";
function getErrorMessage(error: unknown, fallback: string) {
if (error instanceof Error) return error.message;
@@ -24,19 +24,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) {
return data(
- { success: false, message: "Missing inspection document id" },
+ { success: false, message: "Missing inspection plan id" },
{ status: 400 }
);
}
- const documentResult = await getInspectionDocument(client, id);
+ const documentResult = await getInspectionDocument(client, id, companyId);
if (documentResult.error) {
return data(
{
success: false,
message: getErrorMessage(
documentResult.error,
- "Failed to load inspection document"
+ "Failed to load inspection plan"
)
},
{ status: 400 }
@@ -44,7 +44,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
if (!documentResult.data || documentResult.data.companyId !== companyId) {
return data(
- { success: false, message: "Inspection document not found" },
+ { success: false, message: "Inspection plan not found" },
{ status: 404 }
);
}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx
deleted file mode 100644
index 73694fdaee..0000000000
--- a/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import {
- assemblyStepRequirementValidator,
- upsertAssemblyInstructionStepRequirement
-} from "~/modules/production";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- update: "production"
- });
-
- const { requirementId } = params;
- if (!requirementId) throw new Error("requirementId is not found");
-
- const validation = await validator(assemblyStepRequirementValidator).validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const update = await upsertAssemblyInstructionStepRequirement(client, {
- ...validation.data,
- id: requirementId,
- companyId,
- createdBy: userId,
- updatedBy: userId
- });
-
- if (update.error) {
- return data(
- { success: false },
- await flash(request, error(update.error, "Failed to update requirement"))
- );
- }
-
- return { success: true };
-}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx
deleted file mode 100644
index c9710961a9..0000000000
--- a/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import {
- deleteAssemblyInstructionStepRequirement,
- getAssemblyInstructionStepRequirement
-} from "~/modules/production";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
- delete: "production"
- });
-
- const { requirementId } = params;
- if (!requirementId) throw new Error("requirementId is not found");
-
- // Media rows own a storage object — remove it before the row
- const requirement = await getAssemblyInstructionStepRequirement(
- client,
- requirementId
- );
- if (requirement.data?.type === "Media" && requirement.data.filePath) {
- await client.storage.from("private").remove([requirement.data.filePath]);
- }
-
- const deleteRequirement = await deleteAssemblyInstructionStepRequirement(
- client,
- requirementId
- );
- if (deleteRequirement.error) {
- return data(
- { success: false },
- await flash(
- request,
- error(deleteRequirement.error, "Failed to delete requirement")
- )
- );
- }
-
- return data(
- { success: true },
- await flash(request, success("Successfully deleted requirement"))
- );
-}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx
deleted file mode 100644
index c62ebada91..0000000000
--- a/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { updateAssemblyInstructionStepRequirementOrder } from "~/modules/production";
-import { getDatabaseClient } from "~/services/database.server";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { userId } = await requirePermissions(request, {
- update: "production"
- });
-
- if (!params.id) throw new Error("Could not find id");
-
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
- return data(
- { success: false },
- await flash(request, error(null, "Failed to receive a new sort order"))
- );
- }
-
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
- try {
- await updateAssemblyInstructionStepRequirementOrder(
- getDatabaseClient(),
- updates
- );
- } catch (err) {
- return data(
- { success: false },
- await flash(request, error(err, "Failed to update sort order"))
- );
- }
-
- return { success: true };
-}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.slides.delete.$slideId.tsx b/apps/erp/app/routes/x+/assembly+/$id.slides.delete.$slideId.tsx
new file mode 100644
index 0000000000..d16d335f30
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.slides.delete.$slideId.tsx
@@ -0,0 +1,25 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyInstructionStepSlide } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { slideId } = params;
+ if (!slideId) throw new Error("slideId is not found");
+
+ const deleteSlide = await deleteAssemblyInstructionStepSlide(client, slideId);
+ if (deleteSlide.error) {
+ return data(
+ { success: false },
+ await flash(request, error(deleteSlide.error, "Failed to delete slide"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.slides.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.slides.new.tsx
new file mode 100644
index 0000000000..3aded03bda
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.slides.new.tsx
@@ -0,0 +1,81 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { upsertAssemblyInstructionStepSlide } from "~/modules/production";
+import { operationStepSlideValidator } from "~/modules/shared";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(operationStepSlideValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // Same route handles create (upload) and edit (caption/size/annotations): an `id` means
+ // update the existing slide, otherwise insert a new one. Passing createdBy unconditionally
+ // would force the insert branch and PK-conflict on every edit.
+ //
+ // On update we send ONLY the fields that were actually submitted: upsert runs sanitize(),
+ // which turns any `undefined` into `null`, so including an omitted optional field (e.g. on
+ // a caption-only save) would wipe size/annotations. stepId is always present; the slide's
+ // content is imagePath (image slide) XOR modelUploadId (3D model slide).
+ const {
+ id,
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations
+ } = validation.data;
+ const upsert = await upsertAssemblyInstructionStepSlide(
+ client,
+ id
+ ? {
+ id,
+ stepId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ ...(imagePath !== undefined ? { imagePath } : {}),
+ ...(modelUploadId !== undefined ? { modelUploadId } : {}),
+ ...(caption !== undefined ? { caption } : {}),
+ ...(sortOrder !== undefined ? { sortOrder } : {}),
+ ...(size !== undefined ? { size } : {}),
+ ...(annotations !== undefined ? { annotations } : {})
+ }
+ : {
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations,
+ companyId,
+ createdBy: userId
+ }
+ );
+ if (upsert.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(upsert.error, "Failed to save assembly step slide")
+ )
+ );
+ }
+
+ return { id: upsert.data?.id ?? null };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx b/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx
new file mode 100644
index 0000000000..135c8e1ab2
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx
@@ -0,0 +1,92 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ isJobLocked,
+ syncAssemblyInstructionToOperation,
+ syncAssemblyToBopValidator
+} from "~/modules/production";
+import { getDatabaseClient } from "~/services/database.server";
+
+// Syncs a Published assembly instruction's steps onto a live job operation.
+// The part's Bill of Process only stores the instruction pointer — job
+// operations inherit the steps at get-method time and re-sync here on demand.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const validation = await validator(syncAssemblyToBopValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const { operationId } = validation.data;
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const operation = await client
+ .from("jobOperation")
+ .select("id, job(status)")
+ .eq("id", operationId)
+ .single();
+ if (operation.error) {
+ return data(
+ { success: false },
+ await flash(request, error(operation.error, "Operation not found"))
+ );
+ }
+ const status = (operation.data.job as { status: string } | null)?.status;
+ if (isJobLocked(status)) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(null, "This job is locked — steps can't be synced to it")
+ )
+ );
+ }
+
+ try {
+ const summary = await syncAssemblyInstructionToOperation(
+ getDatabaseClient(),
+ {
+ assemblyInstructionId: id,
+ operationId,
+ companyId,
+ userId
+ }
+ );
+ const unmatched =
+ summary.partsUnmatched > 0
+ ? ` — ${summary.partsUnmatched} part link(s) had no matching BOM line on the operation`
+ : "";
+ return data(
+ { success: true },
+ await flash(
+ request,
+ success(
+ `Synced ${summary.created + summary.updated} steps to the BOP (${summary.created} new, ${summary.updated} updated, ${summary.deleted} removed, ${summary.slidesSynced} slides, ${summary.toolsLinked} tool links)${unmatched}`
+ )
+ )
+ );
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(
+ err,
+ err instanceof Error ? err.message : "Failed to sync assembly to BOP"
+ )
+ )
+ );
+ }
+}
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx b/apps/erp/app/routes/x+/assembly+/$id.tools.delete.$toolId.tsx
similarity index 54%
rename from apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx
rename to apps/erp/app/routes/x+/assembly+/$id.tools.delete.$toolId.tsx
index 235294bdeb..f367cdd1a7 100644
--- a/apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tools.delete.$toolId.tsx
@@ -3,29 +3,26 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { deleteAssemblyStandardNote } from "~/modules/production";
+import { deleteAssemblyInstructionStepTool } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
const { client } = await requirePermissions(request, {
delete: "production"
});
- const { noteId } = params;
- if (!noteId) throw new Error("noteId is not found");
+ const { toolId } = params;
+ if (!toolId) throw new Error("toolId is not found");
- const deleteNote = await deleteAssemblyStandardNote(client, noteId);
- if (deleteNote.error) {
+ const deleteTool = await deleteAssemblyInstructionStepTool(client, toolId);
+ if (deleteTool.error) {
return data(
{ success: false },
- await flash(
- request,
- error(deleteNote.error, "Failed to delete standard note")
- )
+ await flash(request, error(deleteTool.error, "Failed to delete tool"))
);
}
return data(
{ success: true },
- await flash(request, success("Successfully deleted standard note"))
+ await flash(request, success("Successfully deleted tool"))
);
}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.tools.new.tsx
similarity index 59%
rename from apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx
rename to apps/erp/app/routes/x+/assembly+/$id.tools.new.tsx
index 52193e4c2c..a213411768 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tools.new.tsx
@@ -5,8 +5,8 @@ import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import {
- assemblyStepRequirementValidator,
- upsertAssemblyInstructionStepRequirement
+ assemblyStepToolValidator,
+ upsertAssemblyInstructionStepTool
} from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -18,36 +18,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id: assemblyInstructionId } = params;
if (!assemblyInstructionId) throw new Error("id is not found");
- const validation = await validator(assemblyStepRequirementValidator).validate(
+ const validation = await validator(assemblyStepToolValidator).validate(
await request.formData()
);
if (validation.error) {
return data(
{ success: false },
- await flash(
- request,
- error(validation.error, "Failed to create requirement")
- )
+ await flash(request, error(validation.error, "Failed to add tool"))
);
}
- // Media uploads must live under this company's path for this instruction
- const { filePath } = validation.data;
- if (filePath) {
- const expectedPrefix = `${companyId}/assembly/${assemblyInstructionId}/`;
- if (!filePath.startsWith(expectedPrefix) || filePath.includes("..")) {
- return data(
- { success: false },
- await flash(request, error(null, "Invalid file path"))
- );
- }
- }
-
// biome-ignore lint/correctness/noUnusedVariables: id is never set on create
const { id, ...rest } = validation.data;
- const create = await upsertAssemblyInstructionStepRequirement(client, {
+ const create = await upsertAssemblyInstructionStepTool(client, {
...rest,
companyId,
createdBy: userId
@@ -55,7 +40,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (create.error) {
return data(
{ success: false },
- await flash(request, error(create.error, "Failed to insert requirement"))
+ await flash(request, error(create.error, "Failed to insert tool"))
);
}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsx
index 7bc47d6dc1..c1544f5181 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx
@@ -36,10 +36,10 @@ import {
getAssemblyComponentMappings,
getAssemblyInstruction,
getAssemblyInstructionStepMaterials,
- getAssemblyInstructionStepRequirements,
+ getAssemblyInstructionStepSlides,
getAssemblyInstructionSteps,
+ getAssemblyInstructionStepTools,
getAssemblyPlanJson,
- getAssemblyStandardNotes,
getAssemblyUnits,
getFlattenedBomMaterials,
getLatestAssemblyPlanJob,
@@ -72,10 +72,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find id");
- const [instruction, steps, standardNotes] = await Promise.all([
+ const [instruction, steps] = await Promise.all([
getAssemblyInstruction(client, id),
- getAssemblyInstructionSteps(client, id),
- getAssemblyStandardNotes(client, companyId)
+ getAssemblyInstructionSteps(client, id)
]);
const instructionError = instruction.error;
@@ -101,8 +100,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const stepIds = (steps.data ?? []).map((step) => step.id);
const [
- requirements,
stepMaterials,
+ stepSlides,
+ stepTools,
plan,
planJob,
componentMappings,
@@ -110,8 +110,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
bomMaterials,
assemblerAvailable
] = await Promise.all([
- getAssemblyInstructionStepRequirements(client, stepIds),
getAssemblyInstructionStepMaterials(client, stepIds),
+ getAssemblyInstructionStepSlides(client, stepIds),
+ getAssemblyInstructionStepTools(client, stepIds),
instruction.data.modelUploadId
? getAssemblyPlanJson(client, instruction.data.modelUploadId)
: Promise.resolve(null),
@@ -133,9 +134,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
instruction: instruction.data,
steps: steps.data ?? [],
- requirements: requirements.data ?? [],
stepMaterials: stepMaterials.data ?? [],
- standardNotes: standardNotes.data ?? [],
+ stepSlides: stepSlides.data ?? [],
+ stepTools: stepTools.data ?? [],
units: units.data ?? [],
plan,
planJob: planJob.data ?? null,
@@ -193,9 +194,9 @@ export default function AssemblyInstructionRoute() {
const {
instruction,
steps,
- requirements,
stepMaterials,
- standardNotes,
+ stepSlides,
+ stepTools,
units,
plan,
planJob,
@@ -385,15 +386,10 @@ export default function AssemblyInstructionRoute() {
const viewerSteps = useMemo(() => steps.map(toViewerStep), [steps]);
- // Per-step requirements/materials for the properties panel — memoized so a
+ // Per-step slides/tools/materials for the properties panel — memoized so a
// per-frame motion-drag re-render (draftMotion) doesn't hand the panel new
// array identities and re-render it.
const activeStepId = selectedStep?.id ?? null;
- const stepRequirements = useMemo(
- () =>
- activeStepId ? requirements.filter((r) => r.stepId === activeStepId) : [],
- [requirements, activeStepId]
- );
const selectedStepMaterials = useMemo(
() =>
activeStepId
@@ -401,6 +397,16 @@ export default function AssemblyInstructionRoute() {
: [],
[stepMaterials, activeStepId]
);
+ const selectedStepSlides = useMemo(
+ () =>
+ activeStepId ? stepSlides.filter((s) => s.stepId === activeStepId) : [],
+ [stepSlides, activeStepId]
+ );
+ const selectedStepTools = useMemo(
+ () =>
+ activeStepId ? stepTools.filter((t) => t.stepId === activeStepId) : [],
+ [stepTools, activeStepId]
+ );
// Authored subassembly units, normalized for step-title derivation: a step
// whose components are exactly a unit is titled by the unit's name ("Add Board").
@@ -671,10 +677,10 @@ export default function AssemblyInstructionRoute() {
onStopEditMotion={onStopEditMotion}
onSetCamera={onSetCamera}
onClearCamera={onClearCamera}
- requirements={stepRequirements}
stepMaterials={selectedStepMaterials}
+ stepSlides={selectedStepSlides}
+ stepTools={selectedStepTools}
bomMaterials={bomMaterials}
- standardNotes={standardNotes}
/>
}
/>
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx b/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx
deleted file mode 100644
index 075aab5328..0000000000
--- a/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import {
- assemblyStandardNoteValidator,
- upsertAssemblyStandardNote
-} from "~/modules/production";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- update: "production"
- });
-
- const { noteId } = params;
- if (!noteId) throw new Error("noteId is not found");
-
- const validation = await validator(assemblyStandardNoteValidator).validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const update = await upsertAssemblyStandardNote(client, {
- ...validation.data,
- id: noteId,
- companyId,
- createdBy: userId,
- updatedBy: userId
- });
-
- if (update.error) {
- return data(
- { success: false },
- await flash(
- request,
- error(update.error, "Failed to update standard note")
- )
- );
- }
-
- return { success: true };
-}
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx b/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx
deleted file mode 100644
index 5664363f7a..0000000000
--- a/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import {
- assemblyStandardNoteValidator,
- upsertAssemblyStandardNote
-} from "~/modules/production";
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "production"
- });
-
- const validation = await validator(assemblyStandardNoteValidator).validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
- const { id, ...rest } = validation.data;
-
- const create = await upsertAssemblyStandardNote(client, {
- ...rest,
- companyId,
- createdBy: userId
- });
- if (create.error) {
- return data(
- { success: false },
- await flash(
- request,
- error(create.error, "Failed to create standard note")
- )
- );
- }
-
- return { success: true, id: create.data?.id };
-}
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.quality.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.quality.tsx
index 74f5d720fb..0191c18577 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.quality.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.quality.tsx
@@ -5,13 +5,14 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useParams } from "react-router";
import invariant from "tiny-invariant";
+import { getInspectionDocumentsForItem } from "~/modules/production";
import {
- getItemSamplingPlan,
- itemSamplingPlanValidator,
- upsertItemSamplingPlan
+ getItemInspectionDocumentAssignments,
+ itemInspectionDocumentAssignmentValidator,
+ upsertItemInspectionDocumentAssignment
} from "~/modules/quality";
-import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
-import { getCompanySettings } from "~/modules/settings";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import ItemQualityView from "~/modules/quality/ui/Item/ItemQualityView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -21,17 +22,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
invariant(itemId, "itemId is required");
- const [plan, settings] = await Promise.all([
- getItemSamplingPlan(client, itemId, companyId),
- getCompanySettings(client, companyId)
+ const [documents, assignments] = await Promise.all([
+ getInspectionDocumentsForItem(client, itemId, companyId),
+ getItemInspectionDocumentAssignments(client, itemId, companyId)
]);
return data({
- plan: plan.data,
- samplingStandard:
- ((settings.data as any)?.samplingStandard as
- | "ANSI_Z1_4"
- | "ISO_2859_1") ?? "ANSI_Z1_4"
+ documents: documents.data ?? [],
+ assignments: (assignments.data ?? []) as ItemInspectionDocumentAssignment[]
});
}
@@ -44,40 +42,48 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(itemId, "itemId is required");
const formData = await request.formData();
- const validation = await validator(itemSamplingPlanValidator).validate(
- formData
- );
- if (validation.error) return validationError(validation.error);
- const result = await upsertItemSamplingPlan(client, {
- ...validation.data,
- companyId,
- updatedBy: userId
- });
- if (result.error) {
+ if (formData.get("intent") === "assignment") {
+ const validation = await validator(
+ itemInspectionDocumentAssignmentValidator
+ ).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemInspectionDocumentAssignment(client, {
+ ...validation.data,
+ companyId,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.consumableQuality(itemId),
+ await flash(request, error(result.error, "Failed to save assignment"))
+ );
+ }
+
throw redirect(
path.to.consumableQuality(itemId),
- await flash(request, error(result.error, "Failed to save sampling plan"))
+ await flash(request, success("Inspection plan assignment updated"))
);
}
throw redirect(
path.to.consumableQuality(itemId),
- await flash(request, success("Sampling plan updated"))
+ await flash(request, error(null, "Unknown intent"))
);
}
export default function ConsumableQualityRoute() {
- const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { documents, assignments } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("itemId is required");
return (
- <div className="p-4">
- <SamplingPlanForm
- action={path.to.consumableQuality(itemId)}
+ <div className="p-4 w-full">
+ <ItemQualityView
itemId={itemId}
- standard={samplingStandard}
- initial={plan ?? undefined}
+ actionPath={path.to.consumableQuality(itemId)}
+ documents={documents}
+ assignments={assignments}
/>
</div>
);
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.tsx
index dab4875098..84b972cdb7 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.tsx
@@ -124,6 +124,7 @@ export default function ConsumableRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -204,6 +205,13 @@ export default function ConsumableRoute() {
}
];
+ tree.push({
+ key: "inspections",
+ name: "Inspections",
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.accept.tsx b/apps/erp/app/routes/x+/inspection+/$id.accept.tsx
similarity index 67%
rename from apps/erp/app/routes/x+/quality+/inbound-inspections.$id.accept.tsx
rename to apps/erp/app/routes/x+/inspection+/$id.accept.tsx
index 2532d491b5..0a71cae224 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.accept.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.accept.tsx
@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import invariant from "tiny-invariant";
-import { dispositionInboundInspection } from "~/modules/quality/quality.server";
+import { dispositionInspection } from "~/modules/quality/quality.server";
import { getParams, path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -16,22 +16,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id } = params;
invariant(id, "id is required");
- const result = await dispositionInboundInspection({
+ const result = await dispositionInspection({
id,
decision: "Accept",
companyId,
- dispositionedBy: userId
+ dispositionedBy: userId,
+ // ERP verdict carries no production posting — Receipt lots only. Job Operation
+ // lots are dispositioned (with their physical outcome) by the MES route.
+ requireSource: "Receipt"
});
if (result.error) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(request, error(result.error, "Failed to accept lot"))
);
}
throw redirect(
- `${path.to.inboundInspections}?${getParams(request)}`,
+ `${path.to.inspections}?${getParams(request)}`,
await flash(request, success("Lot accepted"))
);
}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.document.tsx b/apps/erp/app/routes/x+/inspection+/$id.document.tsx
new file mode 100644
index 0000000000..73242fecaf
--- /dev/null
+++ b/apps/erp/app/routes/x+/inspection+/$id.document.tsx
@@ -0,0 +1,41 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import invariant from "tiny-invariant";
+import { changeInspectionDocument } from "~/modules/quality/quality.server";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "quality",
+ role: "employee"
+ });
+ const { id } = params;
+ invariant(id, "id is required");
+
+ const formData = await request.formData();
+ const inspectionDocumentId =
+ (formData.get("inspectionDocumentId") as string | null)?.trim() || null;
+
+ const result = await changeInspectionDocument({
+ inspectionId: id,
+ inspectionDocumentId,
+ companyId,
+ userId
+ });
+
+ if (result.error) {
+ throw redirect(
+ path.to.inspection(id),
+ await flash(request, error(result.error, "Failed to change document"))
+ );
+ }
+
+ throw redirect(
+ path.to.inspection(id),
+ await flash(request, success("Inspection plan updated"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.measurement.tsx b/apps/erp/app/routes/x+/inspection+/$id.measurement.tsx
new file mode 100644
index 0000000000..08490c7635
--- /dev/null
+++ b/apps/erp/app/routes/x+/inspection+/$id.measurement.tsx
@@ -0,0 +1,49 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import invariant from "tiny-invariant";
+import { inspectionMeasurementValidator } from "~/modules/quality";
+import { upsertInspectionMeasurement } from "~/modules/quality/quality.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "quality",
+ role: "employee"
+ });
+ const { id } = params;
+ invariant(id, "id is required");
+
+ const formData = await request.formData();
+ const validation = await validator(inspectionMeasurementValidator).validate(
+ formData
+ );
+ if (validation.error) return validationError(validation.error);
+
+ if (validation.data.inspectionId !== id) {
+ return data(
+ { error: { message: "Inspection id mismatch" } },
+ await flash(request, error(null, "Inspection id mismatch"))
+ );
+ }
+
+ const result = await upsertInspectionMeasurement({
+ ...validation.data,
+ companyId,
+ userId
+ });
+
+ if (result.error) {
+ return data(
+ { error: result.error },
+ await flash(request, error(result.error, "Failed to save measurement"))
+ );
+ }
+
+ // No success flash — per-cell saves must be quiet; the grid consumes the
+ // returned ids/statuses to update itself.
+ return data(result);
+}
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.partial.tsx b/apps/erp/app/routes/x+/inspection+/$id.partial.tsx
similarity index 74%
rename from apps/erp/app/routes/x+/quality+/inbound-inspections.$id.partial.tsx
rename to apps/erp/app/routes/x+/inspection+/$id.partial.tsx
index 6b68796735..eeea0f4e60 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.partial.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.partial.tsx
@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import invariant from "tiny-invariant";
-import { dispositionInboundInspection } from "~/modules/quality/quality.server";
+import { dispositionInspection } from "~/modules/quality/quality.server";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -16,22 +16,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id } = params;
invariant(id, "id is required");
- const result = await dispositionInboundInspection({
+ const result = await dispositionInspection({
id,
decision: "Partial",
companyId,
- dispositionedBy: userId
+ dispositionedBy: userId,
+ // ERP verdict carries no production posting — Receipt lots only.
+ requireSource: "Receipt"
});
if (result.error) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(request, error(result.error, "Failed to mark partial"))
);
}
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(request, success("Lot marked partial"))
);
}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.reject.test.ts b/apps/erp/app/routes/x+/inspection+/$id.reject.test.ts
new file mode 100644
index 0000000000..3b46ac1829
--- /dev/null
+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.test.ts
@@ -0,0 +1,189 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { getInspection } from "~/modules/quality";
+import { dispositionInspection } from "~/modules/quality/quality.server";
+import { action } from "./$id.reject";
+
+// The reject route hands the disposition engine's `writeOff` descriptor to the
+// post-nonconformance edge function. These tests lock that wiring (the 868f5c1bf
+// refactor moved the itemLedger write out of the engine) and the failure
+// handling (a failed write-off must NOT silently proceed to NCR creation, whose
+// Use-As-Is restore assumes the reject already wrote the value off).
+
+// @carbon/glossary's terms.ts evaluates Lingui `msg` macros at module load,
+// which vitest doesn't transform; the route graph pulls it in transitively.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+vi.mock("@carbon/auth/auth.server", () => ({
+ requirePermissions: vi.fn()
+}));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: vi.fn(async () => ({
+ from: vi.fn(),
+ functions: { invoke: vi.fn() }
+ }))
+}));
+vi.mock("@carbon/ee/notifications", () => ({ notifyIssueCreated: vi.fn() }));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })
+}));
+vi.mock("~/modules/quality/quality.server", () => ({
+ dispositionInspection: vi.fn()
+}));
+vi.mock("~/modules/quality", () => ({
+ getInspection: vi.fn(),
+ getInspectionMeasurements: vi.fn(),
+ getInspectionSamplingPlans: vi.fn(),
+ getIssueTypesList: vi.fn(),
+ insertIssue: vi.fn(),
+ deleteIssue: vi.fn()
+}));
+vi.mock("~/modules/settings/settings.server", () => ({
+ getCompanyIntegrations: vi.fn()
+}));
+vi.mock("~/modules/users/users.server", () => ({
+ getUserDefaults: vi.fn()
+}));
+
+function rejectRequest(fields: Record<string, string> = {}) {
+ const body = new FormData();
+ for (const [k, v] of Object.entries(fields)) body.set(k, v);
+ return new Request("http://localhost/x/inspection/insp-1/reject", {
+ method: "POST",
+ body
+ });
+}
+
+async function runAction(request: Request) {
+ try {
+ return {
+ thrown: null,
+ response: await action({
+ request,
+ params: { id: "insp-1" },
+ context: {}
+ } as any)
+ };
+ } catch (e) {
+ return { thrown: e as Response, response: null };
+ }
+}
+
+const invoke = vi.fn();
+const client = { functions: { invoke }, from: vi.fn() };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client,
+ companyId: "company-1",
+ userId: "user-1"
+ } as any);
+ invoke.mockResolvedValue({ data: { success: true }, error: null });
+});
+
+describe("inspection reject route — inventory write-off", () => {
+ it("posts the disposition engine's writeOff to post-nonconformance", async () => {
+ vi.mocked(dispositionInspection).mockResolvedValue({
+ data: {
+ id: "insp-1",
+ status: "Failed",
+ writeOff: { itemId: "part-2", quantity: -5, locationId: "loc-1" }
+ },
+ error: null
+ } as any);
+
+ const { thrown } = await runAction(rejectRequest({ createNcr: "false" }));
+
+ expect(invoke).toHaveBeenCalledWith(
+ "post-nonconformance",
+ expect.objectContaining({
+ body: expect.objectContaining({
+ documentType: "Inbound Inspection",
+ documentId: "insp-1",
+ movements: [
+ expect.objectContaining({
+ itemId: "part-2",
+ quantity: -5,
+ trackedEntityId: null,
+ locationId: "loc-1"
+ })
+ ]
+ })
+ })
+ );
+ // Lot rejected → redirect back to the inspection.
+ expect(thrown).toBeInstanceOf(Response);
+ expect(thrown?.headers.get("Location")).toContain("insp-1");
+ });
+
+ it("does not post a write-off when the engine returns none (tracked / Non-Inventory / Accept)", async () => {
+ vi.mocked(dispositionInspection).mockResolvedValue({
+ data: { id: "insp-1", status: "Failed", writeOff: null },
+ error: null
+ } as any);
+
+ await runAction(rejectRequest({ createNcr: "false" }));
+
+ expect(invoke).not.toHaveBeenCalledWith(
+ "post-nonconformance",
+ expect.anything()
+ );
+ });
+
+ it("restricts the disposition to Receipt lots (Job Operation lots are verdict-only in the ERP)", async () => {
+ // The ERP reject carries no production posting and does receipt-specific NCR
+ // work, so it must scope the engine to Receipt source — otherwise accepting/
+ // rejecting a Job Operation lot here hard-terminates it and wedges the op.
+ vi.mocked(dispositionInspection).mockResolvedValue({
+ data: { id: "insp-1", status: "Failed", writeOff: null },
+ error: null
+ } as any);
+
+ await runAction(rejectRequest({ createNcr: "false" }));
+
+ expect(dispositionInspection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "insp-1",
+ decision: "Reject",
+ requireSource: "Receipt"
+ })
+ );
+ });
+
+ it("aborts (does not create the NCR) when the write-off post fails", async () => {
+ vi.mocked(dispositionInspection).mockResolvedValue({
+ data: {
+ id: "insp-1",
+ status: "Failed",
+ writeOff: { itemId: "part-2", quantity: -5, locationId: "loc-1" }
+ },
+ error: null
+ } as any);
+ // The edge function fails — a failed reject write-off must surface, not be
+ // swallowed, because closeIssue's Use-As-Is restore assumes it succeeded.
+ invoke.mockResolvedValue({ data: null, error: { message: "boom" } });
+ // If the route proceeds anyway, this is where NCR creation starts.
+ vi.mocked(getInspection).mockResolvedValue({
+ data: null,
+ error: { message: "should not reach here" }
+ } as any);
+
+ const { thrown } = await runAction(rejectRequest());
+
+ // Must redirect back to the inspection with the failure surfaced, and must
+ // NOT begin NCR creation (which would double-count on disposition).
+ expect(thrown).toBeInstanceOf(Response);
+ expect(thrown?.headers.get("Location")).toContain("insp-1");
+ expect(getInspection).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.reject.tsx b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
similarity index 63%
rename from apps/erp/app/routes/x+/quality+/inbound-inspections.$id.reject.tsx
rename to apps/erp/app/routes/x+/inspection+/$id.reject.tsx
index 137480a899..f3e06e76fb 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.reject.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
@@ -11,16 +11,18 @@ import { redirect } from "react-router";
import invariant from "tiny-invariant";
import {
deleteIssue,
- getInboundInspection,
+ getInspection,
+ getInspectionMeasurements,
+ getInspectionSamplingPlans,
getIssueTypesList,
insertIssue
} from "~/modules/quality";
-import { dispositionInboundInspection } from "~/modules/quality/quality.server";
+import { dispositionInspection } from "~/modules/quality/quality.server";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
import { getUserDefaults } from "~/modules/users/users.server";
import { path } from "~/utils/path";
-const logger = getLogger("erp", "inbound-inspections-id-reject");
+const logger = getLogger("erp", "inspections-id-reject");
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -41,15 +43,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
// 1. Cascade reject — mark every tracked entity in the lot as Rejected
// and flip the lot's status to Failed (ISO 9001:2015 §8.7).
- const dispositionResult = await dispositionInboundInspection({
+ const dispositionResult = await dispositionInspection({
id,
decision: "Reject",
companyId,
- dispositionedBy: userId
+ dispositionedBy: userId,
+ // ERP reject does receipt-specific NCR/write-off work — Receipt lots only.
+ // Job Operation lots are rejected (with scrap/rework) by the MES route.
+ requireSource: "Receipt"
});
if (dispositionResult.error) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(
request,
error(dispositionResult.error, "Failed to reject lot")
@@ -57,10 +62,55 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Post the inventory write-off (itemLedger + cost relief + GL) for a
+ // non-tracked Inventory lot through the post-nonconformance edge function.
+ // Idempotent per (documentType, documentId), so retrying the reject after a
+ // failure here re-posts safely (the lot stays Rejected). A failed write-off
+ // MUST abort before NCR creation: the NCR's disposition (closeIssue) restores
+ // value on Use-As-Is/Rework on the assumption this write-off already removed
+ // it, so proceeding would leave the received quantity double-counted on hand.
+ const writeOff = dispositionResult.data?.writeOff;
+ if (writeOff) {
+ const post = await client.functions.invoke("post-nonconformance", {
+ body: {
+ companyId,
+ userId,
+ documentType: "Inbound Inspection",
+ documentId: id,
+ description: "Inbound inspection lot rejected",
+ movements: [
+ {
+ itemId: writeOff.itemId,
+ locationId: writeOff.locationId,
+ trackedEntityId: null,
+ quantity: writeOff.quantity
+ }
+ ]
+ },
+ region: FunctionRegion.UsEast1
+ });
+ if (post.error) {
+ logger.error("Failed to post inspection reject write-off", {
+ error: post.error,
+ inspectionId: id
+ });
+ throw redirect(
+ path.to.inspection(id),
+ await flash(
+ request,
+ error(
+ post.error,
+ "Lot rejected, but the inventory write-off failed to post — resolve the accounting error and reject again to retry."
+ )
+ )
+ );
+ }
+ }
+
// If the inspector opted out of an NCR, we're done — the lot is rejected.
if (!createNcr) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(request, success("Lot rejected"))
);
}
@@ -70,14 +120,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
const [inspection, userDefaults, issueTypes] = await Promise.all([
- getInboundInspection(client, id),
+ getInspection(client, id),
getUserDefaults(client, userId, companyId),
getIssueTypesList(client, companyId)
]);
if (inspection.error || !inspection.data) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(
request,
error(inspection.error, "Lot rejected, but failed to load it for NCR")
@@ -93,7 +143,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!issueType || !locationId) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(
request,
error(
@@ -105,23 +155,64 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const supplierName = insp.supplier?.name ?? "supplier";
- const receiptReadableId = insp.receipt?.receiptId ?? "";
+ const sourceReadableId = insp.sourceDocumentReadableId ?? "";
const itemReadableId =
insp.item?.readableId ?? insp.itemReadableId ?? insp.itemId;
- const inspectionReadableId = insp.inboundInspectionId ?? "";
+ const inspectionReadableId = insp.inspectionId ?? "";
const issueTitle = [
"Rejected lot",
inspectionReadableId,
itemReadableId && `— ${itemReadableId}`,
- receiptReadableId && `on ${receiptReadableId}`
+ sourceReadableId && `on ${sourceReadableId}`
]
.filter(Boolean)
.join(" ");
+ // Document-driven lots: attach the failed features (measured values
+ // vs. spec) so MRB sees what failed and by how much without re-measuring.
+ const [lotFeatures, lotMeasurements] = await Promise.all([
+ getInspectionSamplingPlans(serviceRole, id, companyId),
+ getInspectionMeasurements(serviceRole, id, companyId)
+ ]);
+ const failedFeatureLines: string[] = [];
+ for (const lotFeature of lotFeatures.data ?? []) {
+ const feature = lotFeature.inspectionFeature;
+ if (!feature) continue;
+ const featureMeasurements = (lotMeasurements.data ?? []).filter(
+ (m) => m.inspectionFeatureId === feature.id
+ );
+ const recorded = featureMeasurements.filter(
+ (m) => m.status !== "Pending"
+ ).length;
+ const failed = featureMeasurements.filter((m) => m.status === "Failed");
+ if (failed.length === 0) continue;
+ const failedValues = failed
+ .map((m) => (m.value == null ? "F" : String(m.value)))
+ .join(", ");
+ const spec = [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ");
+ failedFeatureLines.push(
+ spec
+ ? `- ${feature.label}: nominal ${spec} — failed values: ${failedValues} (${failed.length}/${recorded} failed, n=${lotFeature.sampleSize}, Ac=${lotFeature.acceptanceNumber})`
+ : `- ${feature.label}: ${failed.length}/${recorded} failed (n=${lotFeature.sampleSize}, Ac=${lotFeature.acceptanceNumber})`
+ );
+ }
+ const failedFeaturesBlock =
+ failedFeatureLines.length > 0
+ ? `\n\nFailed features:\n${failedFeatureLines.join("\n")}`
+ : "";
+
const createResult = await insertIssue(serviceRole, {
name: issueTitle,
- description: `Auto-created from inbound inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}. Supplier: ${supplierName}.`,
+ description: `Auto-created from inbound inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}. Supplier: ${supplierName}.${failedFeaturesBlock}`,
priority: "Medium",
source: "Internal",
locationId,
@@ -135,7 +226,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (createResult.error || !createResult.data) {
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(
request,
error(createResult.error, "Lot rejected, but failed to create NCR")
@@ -174,35 +265,39 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Link the source inspection to the NCR so the issue explorer can surface
// the origin and deep-link back to the inspection lot.
- await serviceRole.from("nonConformanceInboundInspection").insert({
+ await serviceRole.from("nonConformanceInspection").insert({
nonConformanceId: ncrId,
- inboundInspectionId: insp.id,
+ inspectionId: insp.id,
companyId,
createdBy: userId
});
// Also link the receipt line — gives the explorer the supplier / receipt
// context through the existing "Receipt Lines" association branch.
- if (insp.receiptLineId && insp.receiptId) {
+ if (
+ insp.sourceDocument === "Receipt" &&
+ insp.sourceDocumentLineId &&
+ insp.sourceDocumentId
+ ) {
await serviceRole.from("nonConformanceReceiptLine").insert({
nonConformanceId: ncrId,
- receiptLineId: insp.receiptLineId,
- receiptId: insp.receiptId,
- receiptReadableId: insp.receipt?.receiptId ?? null,
+ receiptLineId: insp.sourceDocumentLineId,
+ receiptId: insp.sourceDocumentId,
+ receiptReadableId: insp.sourceDocumentReadableId ?? null,
companyId,
createdBy: userId
});
}
// Link every tracked entity in the lot to the NCR.
- const trackedEntityIds = ((insp.inboundInspectionSample as any[]) ?? [])
+ const trackedEntityIds = ((insp.inspectionSample as any[]) ?? [])
.map((s) => s.trackedEntityId as string)
.filter(Boolean);
// Include un-sampled entities too (they were also Rejected by the cascade).
const receiptLineEntities = await client
.from("trackedEntity")
.select("id")
- .eq("attributes ->> Receipt Line", insp.receiptLineId)
+ .eq("attributes ->> Receipt Line", insp.sourceDocumentLineId ?? "")
.eq("companyId", companyId);
const allLotEntityIds = Array.from(
new Set([
@@ -257,7 +352,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (tasks.error) {
await deleteIssue(serviceRole, ncrId);
throw redirect(
- path.to.inboundInspection(id),
+ path.to.inspection(id),
await flash(
request,
error(tasks.error, "Lot rejected, but failed to create NCR tasks")
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.sample.tsx b/apps/erp/app/routes/x+/inspection+/$id.sample.tsx
similarity index 65%
rename from apps/erp/app/routes/x+/quality+/inbound-inspections.$id.sample.tsx
rename to apps/erp/app/routes/x+/inspection+/$id.sample.tsx
index adfb075aa2..8d2bc003ff 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.sample.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.sample.tsx
@@ -5,8 +5,8 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import invariant from "tiny-invariant";
-import { inboundInspectionSampleValidator } from "~/modules/quality";
-import { upsertInboundInspectionSample } from "~/modules/quality/quality.server";
+import { inspectionSampleValidator } from "~/modules/quality";
+import { upsertInspectionSample } from "~/modules/quality/quality.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -18,7 +18,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(id, "id is required");
const formData = await request.formData();
- const validation = await validator(inboundInspectionSampleValidator).validate(
+ // Quiet saves come from the measurement grid's "Overall result" cells via a
+ // raw fetch (no revalidation), so a flash cookie would surface as a stray
+ // toast on the next navigation — suppress it and just return the sample id.
+ const quiet = formData.get("quiet") === "true";
+ const validation = await validator(inspectionSampleValidator).validate(
formData
);
if (validation.error) return validationError(validation.error);
@@ -30,7 +34,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const result = await upsertInboundInspectionSample({
+ const result = await upsertInspectionSample({
...validation.data,
companyId,
inspectedBy: userId
@@ -43,8 +47,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (quiet) {
+ return data({ success: true, sampleId: result.data.id });
+ }
+
return data(
- { success: true },
+ { success: true, sampleId: result.data.id },
await flash(request, success("Sample recorded"))
);
}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.tsx b/apps/erp/app/routes/x+/inspection+/$id.tsx
index e4c67c290e..991ca6c932 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.tsx
@@ -2,115 +2,168 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { ClientOnly, Spinner } from "@carbon/react";
import { msg } from "@lingui/core/macro";
-import { lazy, Suspense } from "react";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect, useLoaderData } from "react-router";
-import { getUnitOfMeasuresList } from "~/modules/items/items.service";
+import { data, redirect, useLoaderData } from "react-router";
+import invariant from "tiny-invariant";
+import { getBalloons, getInspectionDocument } from "~/modules/production";
import {
- getBalloons,
- getInspectionDocument,
- getInspectionFeatures
+ getInspection,
+ getInspectionMeasurements,
+ getInspectionSamplingPlans,
+ getInspectionTrackedEntities,
+ getIssueTypesList
} from "~/modules/quality";
-import type { InspectionDocumentContent } from "~/modules/quality/types";
+import { reconcileInspectionSamplingPlans } from "~/modules/quality/quality.server";
+import type {
+ InspectionMeasurement,
+ InspectionRow,
+ InspectionSample,
+ InspectionSamplingPlan,
+ InspectionTrackedEntity,
+ IssueTypeListItem
+} from "~/modules/quality/types";
+import InspectionView from "~/modules/quality/ui/Inspections/InspectionView";
+import { getCompanySettings } from "~/modules/settings";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
-const InspectionDocumentEditor = lazy(
- () =>
- import("~/modules/quality/ui/InspectionDocument/InspectionDocumentEditor")
-);
-
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
- { breadcrumb: msg`Inspection Document`, to: path.to.inspectionDocuments },
- (data) => data?.diagram?.name
- ),
- module: "quality"
+ { breadcrumb: msg`Inspections`, to: path.to.inspections },
+ (data) => data?.inspection?.inspectionId
+ )
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "quality"
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "quality",
+ role: "employee"
});
-
const { id } = params;
- if (!id) throw new Error("Could not find id");
+ invariant(id, "id is required");
- const serviceRole = await getCarbonServiceRole();
- const [diagram, featuresResult, balloonsResult, unitOfMeasuresResult] =
- await Promise.all([
- getInspectionDocument(serviceRole, id),
- getInspectionFeatures(serviceRole, id),
- getBalloons(serviceRole, id),
- getUnitOfMeasuresList(client, companyId)
- ]);
+ const [inspection, settings, issueTypes] = await Promise.all([
+ getInspection(client, id),
+ getCompanySettings(client, companyId),
+ getIssueTypesList(client, companyId)
+ ]);
- if (diagram.error) {
+ if (inspection.error || !inspection.data) {
throw redirect(
- path.to.inspectionDocuments,
- await flash(
- request,
- error(diagram.error, "Failed to load inspection document")
- )
+ path.to.inspections,
+ await flash(request, error(inspection.error, "Failed to load inspection"))
);
}
- if (!diagram.data) {
- throw redirect(path.to.inspectionDocuments);
+ const insp = inspection.data as InspectionRow & {
+ item: {
+ readableId: string | null;
+ name: string;
+ type: string;
+ itemTrackingType: string | null;
+ } | null;
+ supplier: { name: string } | null;
+ inspectionSample: InspectionSample[];
+ };
+
+ if (insp.companyId !== companyId) {
+ throw redirect(path.to.inspections);
}
- if (diagram.data.companyId !== companyId) {
- throw redirect(path.to.inspectionDocuments);
+ // The lot references its inspection document live — resolve per-lot plan
+ // rows for any features added to the document after receipt.
+ if (insp.inspectionDocumentId) {
+ await reconcileInspectionSamplingPlans(id, companyId);
}
- const features = featuresResult.data ?? [];
- const balloons = balloonsResult.data ?? [];
+ const isReceiptSource = insp.sourceDocument === "Receipt";
+ const serviceRole = getCarbonServiceRole();
+ const [features, measurements, lotEntities, document, balloons, receipt] =
+ await Promise.all([
+ getInspectionSamplingPlans(client, id, companyId),
+ getInspectionMeasurements(client, id, companyId),
+ isReceiptSource && insp.sourceDocumentLineId
+ ? getInspectionTrackedEntities(
+ client,
+ insp.sourceDocumentLineId,
+ companyId
+ )
+ : Promise.resolve({ data: null, error: null }),
+ insp.inspectionDocumentId
+ ? getInspectionDocument(
+ serviceRole,
+ insp.inspectionDocumentId,
+ companyId
+ )
+ : Promise.resolve({ data: null, error: null }),
+ insp.inspectionDocumentId
+ ? getBalloons(serviceRole, insp.inspectionDocumentId)
+ : Promise.resolve({ data: null, error: null }),
+ // Four-eyes: the receiver is the receipt's creator (no FK on the generic
+ // source id, so this is a separate lookup).
+ isReceiptSource
+ ? client
+ .from("receipt")
+ .select("createdBy")
+ .eq("id", insp.sourceDocumentId)
+ .maybeSingle()
+ : Promise.resolve({ data: null, error: null })
+ ]);
- const unitOfMeasures = unitOfMeasuresResult?.data ?? [];
+ const doc = document.data as {
+ name?: string | null;
+ content?: { pdfUrl?: string | null };
+ } | null;
- return {
- diagram: diagram.data,
- features,
- balloons,
- unitOfMeasures
- };
+ return data({
+ inspection: insp,
+ sourceDocumentReadableId: insp.sourceDocumentReadableId ?? null,
+ receiverId: receipt.data?.createdBy ?? null,
+ itemName: insp.item?.name ?? "",
+ itemTrackingType: insp.item?.itemTrackingType ?? null,
+ supplierName: insp.supplier?.name ?? null,
+ samples: insp.inspectionSample ?? [],
+ features: (features.data ?? []) as InspectionSamplingPlan[],
+ measurements: (measurements.data ?? []) as InspectionMeasurement[],
+ balloons: ((balloons.data ?? []) as any[]).map((b) => ({
+ id: b.id as string,
+ inspectionFeatureId: b.inspectionFeatureId as string,
+ pageNumber: Number(b.pageNumber ?? 1),
+ xCoordinate: Number(b.xCoordinate ?? 0),
+ yCoordinate: Number(b.yCoordinate ?? 0)
+ })),
+ documentName: doc?.name ?? null,
+ pdfUrl: doc?.content?.pdfUrl ?? null,
+ lotEntities: (lotEntities.data ?? []) as InspectionTrackedEntity[],
+ issueTypes: (issueTypes.data ?? []) as IssueTypeListItem[],
+ enforceFourEyes:
+ ((settings.data as any)?.enforceInspectionFourEyes as boolean) ?? false,
+ currentUserId: userId
+ });
}
-export default function BalloonDetailRoute() {
- const { diagram, features, balloons, unitOfMeasures } =
- useLoaderData<typeof loader>();
- const content = diagram.content as InspectionDocumentContent | null;
+export default function InspectionExecutionRoute() {
+ const loaderData = useLoaderData<typeof loader>();
return (
- <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
- <ClientOnly
- fallback={
- <div className="flex h-full w-full items-center justify-center">
- <Spinner className="h-8 w-8" />
- </div>
- }
- >
- {() => (
- <Suspense
- fallback={
- <div className="flex h-full w-full items-center justify-center">
- <Spinner className="h-8 w-8" />
- </div>
- }
- >
- <InspectionDocumentEditor
- diagramId={diagram.id}
- name={diagram.name}
- content={content}
- features={features}
- balloons={balloons}
- unitOfMeasures={unitOfMeasures}
- />
- </Suspense>
- )}
- </ClientOnly>
- </div>
+ <InspectionView
+ inspection={loaderData.inspection as InspectionRow}
+ sourceDocumentReadableId={loaderData.sourceDocumentReadableId}
+ receiverId={loaderData.receiverId}
+ itemName={loaderData.itemName}
+ itemTrackingType={loaderData.itemTrackingType}
+ supplierName={loaderData.supplierName}
+ samples={loaderData.samples as InspectionSample[]}
+ features={loaderData.features as InspectionSamplingPlan[]}
+ measurements={loaderData.measurements as InspectionMeasurement[]}
+ balloons={loaderData.balloons}
+ documentName={loaderData.documentName}
+ pdfUrl={loaderData.pdfUrl}
+ lotEntities={loaderData.lotEntities as InspectionTrackedEntity[]}
+ issueTypes={loaderData.issueTypes as IssueTypeListItem[]}
+ currentUserId={loaderData.currentUserId}
+ enforceFourEyes={loaderData.enforceFourEyes}
+ />
);
}
diff --git a/apps/erp/app/routes/x+/inspection+/_layout.tsx b/apps/erp/app/routes/x+/inspection+/_layout.tsx
new file mode 100644
index 0000000000..b7ed2f304e
--- /dev/null
+++ b/apps/erp/app/routes/x+/inspection+/_layout.tsx
@@ -0,0 +1,28 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs, MetaFunction } from "react-router";
+import { Outlet } from "react-router";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Inspection" }];
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ view: "quality"
+ });
+
+ return null;
+}
+
+export const handle: Handle = {
+ breadcrumb: msg`Quality`,
+ to: path.to.quality,
+ module: "quality"
+};
+
+export default function InspectionRoute() {
+ return <Outlet />;
+}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.delete.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
similarity index 59%
rename from apps/erp/app/routes/x+/inspection+/$id.delete.tsx
rename to apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
index 163355173e..82d3483e3e 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.delete.tsx
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx
@@ -2,28 +2,32 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
+import type {
+ ActionFunctionArgs,
+ ClientActionFunctionArgs
+} from "react-router";
import { redirect } from "react-router";
-import { deleteInspectionDocument } from "~/modules/quality";
+import { deleteInspectionDocument } from "~/modules/production";
import { path } from "~/utils/path";
+import { invalidateInspectionDocuments } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
delete: "quality"
});
const { id } = params;
if (!id) throw new Error("Could not find id");
- const result = await deleteInspectionDocument(client, id);
+ const result = await deleteInspectionDocument(client, id, companyId);
if (result.error) {
throw redirect(
path.to.inspectionDocuments,
await flash(
request,
- error(result.error, "Failed to delete inspection document")
+ error(result.error, "Failed to delete inspection plan")
)
);
}
@@ -36,6 +40,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
throw redirect(
path.to.inspectionDocuments,
- await flash(request, success("Inspection document deleted"))
+ await flash(request, success("Inspection plan deleted"))
);
}
+
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ invalidateInspectionDocuments();
+ return await serverAction();
+}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.save.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.save.tsx
similarity index 79%
rename from apps/erp/app/routes/x+/inspection+/$id.save.tsx
rename to apps/erp/app/routes/x+/inspection-document+/$id.save.tsx
index 8a68c69cae..405debe9e9 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.save.tsx
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.save.tsx
@@ -1,8 +1,14 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import type { ActionFunctionArgs } from "react-router";
+import type {
+ ActionFunctionArgs,
+ ClientActionFunctionArgs
+} from "react-router";
import { data } from "react-router";
-import { saveInspectionDocumentAtomic } from "~/modules/quality";
+import {
+ saveInspectionDocumentAtomic,
+ updateInspectionDocumentSampling
+} from "~/modules/production";
import {
type InspectionSaveBalloonsGeometryPayload,
type InspectionSaveFeaturesPayload,
@@ -10,13 +16,15 @@ import {
mergeInspectionFeaturesPayload,
resolveInspectionFeaturePayloadIds,
translateLegacyInspectionSavePayload
-} from "~/modules/quality/inspectionDocumentSave.server";
+} from "~/modules/production/inspectionDocumentSave.server";
import {
+ inspectionDocumentSamplingValidator,
inspectionSaveAnchorsPayloadValidator,
inspectionSaveBalloonsGeometryPayloadValidator,
inspectionSaveBalloonsPayloadValidator,
inspectionSaveFeaturesPayloadValidator
-} from "~/modules/quality/quality.models";
+} from "~/modules/production/production.models";
+import { invalidateInspectionDocuments } from "~/utils/react-query";
function getErrorMessage(error: unknown, fallback: string) {
if (error instanceof Error) return error.message;
@@ -46,6 +54,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const featuresRaw = formData.get("features") as string | null;
const balloonsRaw = formData.get("balloons") as string | null;
const anchorsRaw = formData.get("anchors") as string | null;
+ const samplingDefaultRaw = formData.get("samplingDefault") as string | null;
const pageCountRaw = formData.get("pageCount");
const defaultPageWidthRaw = formData.get("defaultPageWidth");
const defaultPageHeightRaw = formData.get("defaultPageHeight");
@@ -193,13 +202,42 @@ export async function action({ request, params }: ActionFunctionArgs) {
success: false,
message: getErrorMessage(
rpcResult.error,
- "Failed to save inspection document"
+ "Failed to save inspection plan"
)
},
{ status: 400 }
);
}
+ // The document's default sampling rule rides the same save (a single
+ // UPDATE; not part of the features/balloons atomic contract).
+ if (samplingDefaultRaw) {
+ try {
+ const json = JSON.parse(samplingDefaultRaw) as unknown;
+ const validated = inspectionDocumentSamplingValidator.safeParse(json);
+ if (!validated.success) {
+ throw new Error("Invalid sampling payload");
+ }
+ const samplingResult = await updateInspectionDocumentSampling(client, {
+ ...validated.data,
+ inspectionDocumentId: id,
+ companyId,
+ userId
+ });
+ if (samplingResult.error) {
+ return data(
+ { success: false, message: "Failed to save default sampling" },
+ { status: 400 }
+ );
+ }
+ } catch {
+ return data(
+ { success: false, message: "Invalid sampling payload" },
+ { status: 400 }
+ );
+ }
+ }
+
return rpcResult.data as {
success: boolean;
featureIdMap: Record<string, string>;
@@ -209,3 +247,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
balloons: unknown[];
};
}
+
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ invalidateInspectionDocuments();
+ return await serverAction();
+}
diff --git a/apps/erp/app/routes/x+/inspection-document+/$id.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.tsx
new file mode 100644
index 0000000000..05a2014783
--- /dev/null
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.tsx
@@ -0,0 +1,137 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { ClientOnly, Spinner } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import { lazy, Suspense } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import { getUnitOfMeasuresList } from "~/modules/items/items.service";
+import {
+ getBalloons,
+ getInspectionDocument,
+ getInspectionFeatures
+} from "~/modules/production";
+import type { InspectionDocumentContent } from "~/modules/production/types";
+import type { SamplingRule } from "~/modules/production/ui/InspectionDocument/SamplingRuleModal";
+import { getCompanySettings } from "~/modules/settings";
+import type { BreadcrumbSegment, Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+const InspectionDocumentEditor = lazy(
+ () =>
+ import(
+ "~/modules/production/ui/InspectionDocument/InspectionDocumentEditor"
+ )
+);
+
+export const handle: Handle = {
+ breadcrumb: (_params: unknown, data: any): BreadcrumbSegment[] => {
+ const segments: BreadcrumbSegment[] = [
+ { breadcrumb: msg`Production`, to: path.to.production },
+ { breadcrumb: msg`Inspection Plans`, to: path.to.inspectionDocuments }
+ ];
+ const name = data?.diagram?.name;
+ return name ? [...segments, { breadcrumb: name }] : segments;
+ },
+ module: "production"
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "quality"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const serviceRole = await getCarbonServiceRole();
+ const [
+ diagram,
+ featuresResult,
+ balloonsResult,
+ unitOfMeasuresResult,
+ companySettings
+ ] = await Promise.all([
+ getInspectionDocument(serviceRole, id, companyId),
+ getInspectionFeatures(serviceRole, id),
+ getBalloons(serviceRole, id),
+ getUnitOfMeasuresList(client, companyId),
+ getCompanySettings(client, companyId)
+ ]);
+
+ if (diagram.error) {
+ throw redirect(
+ path.to.inspectionDocuments,
+ await flash(
+ request,
+ error(diagram.error, "Failed to load inspection plan")
+ )
+ );
+ }
+
+ if (!diagram.data) {
+ throw redirect(path.to.inspectionDocuments);
+ }
+
+ if (diagram.data.companyId !== companyId) {
+ throw redirect(path.to.inspectionDocuments);
+ }
+
+ const features = featuresResult.data ?? [];
+ const balloons = balloonsResult.data ?? [];
+
+ const unitOfMeasures = unitOfMeasuresResult?.data ?? [];
+
+ return {
+ diagram: diagram.data,
+ features,
+ balloons,
+ unitOfMeasures,
+ samplingStandard:
+ ((companySettings.data as any)?.samplingStandard as
+ | "ANSI_Z1_4"
+ | "ISO_2859_1") ?? "ANSI_Z1_4"
+ };
+}
+
+export default function BalloonDetailRoute() {
+ const { diagram, features, balloons, unitOfMeasures, samplingStandard } =
+ useLoaderData<typeof loader>();
+ const content = diagram.content as InspectionDocumentContent | null;
+
+ return (
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-8 w-8" />
+ </div>
+ }
+ >
+ {() => (
+ <Suspense
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-8 w-8" />
+ </div>
+ }
+ >
+ <InspectionDocumentEditor
+ diagramId={diagram.id}
+ name={diagram.name}
+ partId={diagram.partId}
+ content={content}
+ features={features}
+ balloons={balloons}
+ unitOfMeasures={unitOfMeasures}
+ sampling={(diagram.sampling as SamplingRule | null) ?? null}
+ samplingStandard={samplingStandard}
+ />
+ </Suspense>
+ )}
+ </ClientOnly>
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/inspection+/$id.update-name.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx
similarity index 72%
rename from apps/erp/app/routes/x+/inspection+/$id.update-name.tsx
rename to apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx
index 74c6600317..a40919f22d 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.update-name.tsx
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx
@@ -1,6 +1,10 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import type { ActionFunctionArgs } from "react-router";
+import type {
+ ActionFunctionArgs,
+ ClientActionFunctionArgs
+} from "react-router";
+import { invalidateInspectionDocuments } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -29,3 +33,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
return { success: true };
}
+
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ invalidateInspectionDocuments();
+ return await serverAction();
+}
diff --git a/apps/erp/app/routes/x+/issue+/$id.association.new.tsx b/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
index e9ce7cbb55..86a0cc2a2c 100644
--- a/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
@@ -305,11 +305,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
}
break;
- case "inboundInspections": {
+ case "inspections": {
const inspection = await (client as any)
- .from("inboundInspection")
+ .from("inspection")
.select(
- "id, itemId, lotSize, receiptLineId, inboundInspectionSample(trackedEntityId)"
+ "id, itemId, lotSize, receiptLineId, inspectionSample(trackedEntityId)"
)
.eq("id", id)
.single();
@@ -324,10 +324,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const linkResult = await (client as any)
- .from("nonConformanceInboundInspection")
+ .from("nonConformanceInspection")
.insert({
nonConformanceId,
- inboundInspectionId: inspection.data.id,
+ inspectionId: inspection.data.id,
createdBy: userId,
companyId: companyId
});
@@ -342,7 +342,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const sampledIds = (
- (inspection.data.inboundInspectionSample ?? []) as {
+ (inspection.data.inspectionSample ?? []) as {
trackedEntityId: string;
}[]
)
@@ -367,7 +367,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- await autoLinkInboundInspectionContext(client, {
+ await autoLinkInspectionContext(client, {
nonConformanceId,
companyId,
userId,
@@ -436,7 +436,7 @@ async function autoLinkJobOperationContext(
});
}
-async function autoLinkInboundInspectionContext(
+async function autoLinkInspectionContext(
client: Awaited<ReturnType<typeof requirePermissions>>["client"],
args: {
nonConformanceId: string;
diff --git a/apps/erp/app/routes/x+/issue+/$id.status.tsx b/apps/erp/app/routes/x+/issue+/$id.status.tsx
index 6158ac5f60..78c652f1b8 100644
--- a/apps/erp/app/routes/x+/issue+/$id.status.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.status.tsx
@@ -1,5 +1,6 @@
import { assertIsPost, ERP_URL, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { notifyIssueStatusChanged } from "@carbon/ee/notifications";
import { getLogger } from "@carbon/logger";
@@ -32,6 +33,43 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Block reopening an NCR whose disposition already posted inventory value.
+ // Reversing posted GL must be an explicit compensating action (SAP-aligned),
+ // not a casual reopen. Narrow: only NCRs that actually posted a ledger movement
+ // are blocked (an all-Use-As-Is/tracked NCR posts nothing and stays reopenable).
+ // Read via service role — itemLedger SELECT needs inventory/accounting_view,
+ // which a quality user may lack, so a user-client read would fail open.
+ if (status !== "Closed") {
+ const serviceRole = getCarbonServiceRole();
+ const current = await serviceRole
+ .from("nonConformance")
+ .select("status")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (current.data?.status === "Closed") {
+ const posted = await serviceRole
+ .from("itemLedger")
+ .select("id")
+ .eq("documentType", "Non-Conformance")
+ .eq("documentId", id)
+ .eq("companyId", companyId)
+ .limit(1);
+ if ((posted.data?.length ?? 0) > 0) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.issueDetails(id),
+ await flash(
+ request,
+ error(
+ null,
+ "This NCR posted inventory transactions and can't be reopened. Create a correcting entry instead."
+ )
+ )
+ );
+ }
+ }
+ }
+
const update = await updateIssueStatus(client, {
id,
status,
diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsx
index 99cadd1ff9..9225115cbb 100644
--- a/apps/erp/app/routes/x+/issue+/$id.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.tsx
@@ -172,13 +172,12 @@ export default function IssueRoute() {
children: resolvedAssociations.suppliers
},
{
- key: "inboundInspections",
- name: t`Inbound Inspection`,
- pluralName: t`Inbound Inspections`,
+ key: "inspections",
+ name: t`Inspection`,
+ pluralName: t`Inspections`,
module: "quality",
children:
- (resolvedAssociations as any).inboundInspections ??
- []
+ (resolvedAssociations as any).inspections ?? []
}
];
return (
diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.tsx
index f645f5218d..f8a319b3e8 100644
--- a/apps/erp/app/routes/x+/items+/change-order+/$id.tsx
+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.tsx
@@ -226,6 +226,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...operation,
description: operation.description ?? "",
procedureId: operation.procedureId ?? undefined,
+ assemblyInstructionId: operation.assemblyInstructionId ?? undefined,
+ inspectionDocumentId: operation.inspectionDocumentId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
operationMinimumCost: operation.operationMinimumCost ?? 0,
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
index 1a9c2549f5..0088400f07 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
@@ -71,6 +71,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Part ↔ step links are managed from the STEP side (the BoP step editor's "Parts" picker),
+ // so the material save no longer touches methodMaterialStep.
const result = {
id: methodMaterialId,
success: true,
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx b/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
index 01f3629e80..3bf7baac36 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
@@ -66,6 +66,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Part ↔ step links are managed from the STEP side (the BoP step editor's "Parts" picker),
+ // so the material save no longer touches methodMaterialStep.
const result = {
id: methodMaterialId,
success: true,
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.duplicate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.duplicate.$id.tsx
new file mode 100644
index 0000000000..18fa90a8d7
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.duplicate.$id.tsx
@@ -0,0 +1,50 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assertMethodOperationIsDraft,
+ duplicateMethodOperationStep
+} from "~/modules/items";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts"
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const step = await client
+ .from("methodOperationStep")
+ .select("operationId")
+ .eq("id", id)
+ .single();
+
+ if (step.error || !step.data) {
+ throw new Error("Step not found");
+ }
+
+ await assertMethodOperationIsDraft(client, step.data.operationId);
+
+ const duplicate = await duplicateMethodOperationStep(client, {
+ id,
+ companyId,
+ createdBy: userId
+ });
+ if (duplicate.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(duplicate.error, "Failed to duplicate method operation step")
+ )
+ );
+ }
+
+ return { id: duplicate.data?.id ?? null };
+}
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx
new file mode 100644
index 0000000000..ab60c6c2c3
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assertMethodOperationIsDraft,
+ setMethodMaterialStepLink
+} from "~/modules/items";
+
+// Toggle a part↔step link from the step editor's "Parts" picker (method/item tier).
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, { update: "parts" });
+
+ const formData = await request.formData();
+ const methodMaterialId = String(formData.get("materialId") ?? "");
+ const methodOperationStepId = String(formData.get("stepId") ?? "");
+ const linked = formData.get("linked") === "true";
+
+ if (!methodMaterialId || !methodOperationStepId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ const step = await client
+ .from("methodOperationStep")
+ .select("operationId")
+ .eq("id", methodOperationStepId)
+ .single();
+ if (step.error || !step.data) {
+ return data({ success: false }, { status: 404 });
+ }
+ await assertMethodOperationIsDraft(client, step.data.operationId);
+
+ const result = await setMethodMaterialStepLink(client, {
+ methodMaterialId,
+ methodOperationStepId,
+ linked
+ });
+ if (result.error) {
+ return data(
+ { success: false },
+ await flash(request, error(result.error, "Failed to update step parts"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.delete.$id.tsx
new file mode 100644
index 0000000000..e84d7a64d7
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.delete.$id.tsx
@@ -0,0 +1,56 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assertMethodOperationIsDraft,
+ deleteMethodOperationStepSlide
+} from "~/modules/items";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "parts"
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const slide = await client
+ .from("methodOperationStepSlide")
+ .select("stepId")
+ .eq("id", id)
+ .single();
+
+ if (slide.error || !slide.data) {
+ throw new Error("Slide not found");
+ }
+
+ const step = await client
+ .from("methodOperationStep")
+ .select("operationId")
+ .eq("id", slide.data.stepId)
+ .single();
+
+ if (step.error || !step.data) {
+ throw new Error("Step not found");
+ }
+
+ await assertMethodOperationIsDraft(client, step.data.operationId);
+
+ const deleteSlide = await deleteMethodOperationStepSlide(client, id);
+ if (deleteSlide.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(deleteSlide.error, "Failed to delete operation step slide")
+ )
+ );
+ }
+
+ return {};
+}
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.new.tsx
new file mode 100644
index 0000000000..3c1df0eb45
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.slide.new.tsx
@@ -0,0 +1,96 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assertMethodOperationIsDraft,
+ upsertMethodOperationStepSlide
+} from "~/modules/items";
+import { operationStepSlideValidator } from "~/modules/shared";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(operationStepSlideValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const step = await client
+ .from("methodOperationStep")
+ .select("operationId")
+ .eq("id", validation.data.stepId)
+ .single();
+
+ if (step.error || !step.data) {
+ throw new Error("Step not found");
+ }
+
+ await assertMethodOperationIsDraft(client, step.data.operationId);
+
+ // Same route handles create (upload) and edit (caption/size/annotations): an `id` means
+ // update the existing slide, otherwise insert a new one. Passing createdBy unconditionally
+ // would force the insert branch and PK-conflict on every edit.
+ //
+ // On update we send ONLY the fields that were actually submitted: upsert runs sanitize(),
+ // which turns any `undefined` into `null`, so including an omitted optional field (e.g. on
+ // a caption-only save) would wipe size/annotations. stepId is always present; the slide's
+ // content is imagePath (image slide) XOR modelUploadId (3D model slide).
+ const {
+ id,
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations
+ } = validation.data;
+ const upsert = await upsertMethodOperationStepSlide(
+ client,
+ id
+ ? {
+ id,
+ stepId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ ...(imagePath !== undefined ? { imagePath } : {}),
+ ...(modelUploadId !== undefined ? { modelUploadId } : {}),
+ ...(caption !== undefined ? { caption } : {}),
+ ...(sortOrder !== undefined ? { sortOrder } : {}),
+ ...(size !== undefined ? { size } : {}),
+ ...(annotations !== undefined ? { annotations } : {})
+ }
+ : {
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations,
+ companyId,
+ createdBy: userId
+ }
+ );
+ if (upsert.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(upsert.error, "Failed to save operation step slide")
+ )
+ );
+ }
+
+ return { id: upsert.data?.id ?? null };
+}
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx
new file mode 100644
index 0000000000..dfbe083ed0
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assertMethodOperationIsDraft,
+ setMethodOperationToolStepLink
+} from "~/modules/items";
+
+// Toggle a tool↔step link from the step editor's "Tools" picker (method/item tier).
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, { update: "parts" });
+
+ const formData = await request.formData();
+ const methodOperationToolId = String(formData.get("toolId") ?? "");
+ const methodOperationStepId = String(formData.get("stepId") ?? "");
+ const linked = formData.get("linked") === "true";
+
+ if (!methodOperationToolId || !methodOperationStepId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ const step = await client
+ .from("methodOperationStep")
+ .select("operationId")
+ .eq("id", methodOperationStepId)
+ .single();
+ if (step.error || !step.data) {
+ return data({ success: false }, { status: 404 });
+ }
+ await assertMethodOperationIsDraft(client, step.data.operationId);
+
+ const result = await setMethodOperationToolStepLink(client, {
+ methodOperationToolId,
+ methodOperationStepId,
+ linked
+ });
+ if (result.error) {
+ return data(
+ { success: false },
+ await flash(request, error(result.error, "Failed to update step tools"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
index 74e12fc5a4..a248c06c27 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
@@ -28,6 +28,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id: _id, ...d } = validation.data;
+ // Tool↔step links are managed by the step editor (methodOperationStepTool route), so this
+ // edit deliberately leaves them untouched.
+
// Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.
const lock = await checkRevisionLock(client, { kind: "tool", id, companyId });
if (!lock.ok) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
index 9fa7f514d8..8f8b111c44 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
@@ -21,6 +21,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // Tool↔step assignment now lives on the step editor (methodOperationStepTool route),
+ // not this tool form — a new tool starts operation-level (shown on every step).
+
// Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.
const lock = await checkRevisionLock(client, {
kind: "operation",
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 799081af1f..6c0c05ca52 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -323,17 +323,6 @@ export async function action({ request }: ActionFunctionArgs) {
.in("id", items as string[])
.eq("companyId", companyId);
- case "requiresInspection":
- return await client
- .from("item")
- .update({
- requiresInspection: value === "on",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .in("id", items as string[])
- .eq("companyId", companyId);
-
case "itemPostingGroupId":
// Update itemCost table for all selected items
const itemCostUpdates = await Promise.all(
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 887c232b36..da22f7b237 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -89,6 +89,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Part ↔ step links are managed from the STEP side (the BoP step editor's "Parts" picker),
+ // so the material save no longer touches jobMaterialStep.
+
// On transition Pull/Purchase → Make to Order, pull the subassembly's method
// (BOM + operations) into the newly-created child make method, mirroring the
// create route. Without this the material flips to Make to Order but stays empty.
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index 1a2ef8da40..34d5c7546a 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -65,6 +65,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Part ↔ step links are managed from the STEP side (the BoP step editor's "Parts" picker),
+ // so the material save no longer touches jobMaterialStep.
+
// Check if job is released (not Draft or Planned)
const job = await serviceRole
.from("job")
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.duplicate.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.duplicate.$id.tsx
new file mode 100644
index 0000000000..a6d8642348
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.duplicate.$id.tsx
@@ -0,0 +1,35 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { duplicateJobOperationStep } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const duplicate = await duplicateJobOperationStep(client, {
+ id,
+ companyId,
+ createdBy: userId
+ });
+ if (duplicate.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(duplicate.error, "Failed to duplicate job operation step")
+ )
+ );
+ }
+
+ return { id: duplicate.data?.id ?? null };
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx
new file mode 100644
index 0000000000..c4231e7b10
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx
@@ -0,0 +1,50 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { setJobMaterialStepLink } from "~/modules/production";
+
+// Toggle a part↔step link from the step editor's "Parts" picker (job tier).
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const formData = await request.formData();
+ const jobMaterialId = String(formData.get("materialId") ?? "");
+ const jobOperationStepId = String(formData.get("stepId") ?? "");
+ const linked = formData.get("linked") === "true";
+
+ if (!jobMaterialId || !jobOperationStepId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ // Verify the step belongs to the caller's company before linking. The
+ // join-table RLS only checks the material's company, not the step side
+ // (jobMaterialStep has no companyId), so an unscoped stepId could otherwise
+ // link across tenants. The RLS-scoped read returns nothing for a foreign step.
+ const step = await client
+ .from("jobOperationStep")
+ .select("id")
+ .eq("id", jobOperationStepId)
+ .single();
+ if (step.error || !step.data) {
+ return data({ success: false }, { status: 404 });
+ }
+
+ const result = await setJobMaterialStepLink(client, {
+ jobMaterialId,
+ jobOperationStepId,
+ linked
+ });
+ if (result.error) {
+ return data(
+ { success: false },
+ await flash(request, error(result.error, "Failed to update step parts"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.delete.$id.tsx
new file mode 100644
index 0000000000..7cdac40942
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.delete.$id.tsx
@@ -0,0 +1,31 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteJobOperationStepSlide } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const deleteSlide = await deleteJobOperationStepSlide(client, id);
+ if (deleteSlide.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(deleteSlide.error, "Failed to delete job operation step slide")
+ )
+ );
+ }
+
+ return {};
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.new.tsx
new file mode 100644
index 0000000000..1f9d714e74
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.slide.new.tsx
@@ -0,0 +1,83 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { upsertJobOperationStepSlide } from "~/modules/production";
+import { operationStepSlideValidator } from "~/modules/shared";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+
+ // Same route handles create (no `id`) and update (`id` present). Gate each branch on the
+ // matching permission so a create-only user can't edit an existing slide by passing an `id`.
+ const formData = await request.formData();
+ const isUpdate = Boolean(formData.get("id"));
+ const { client, companyId, userId } = await requirePermissions(
+ request,
+ isUpdate ? { update: "production" } : { create: "production" }
+ );
+
+ const validation = await validator(operationStepSlideValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // Same route handles create (upload) and edit (caption/size/annotations): an `id` means
+ // update the existing slide, otherwise insert. On update we send ONLY the fields actually
+ // submitted — upsert runs sanitize() (undefined → null), so a caption-only save never
+ // wipes size/annotations. stepId (a jobOperationStep id) is always present; the slide's
+ // content is imagePath (image slide) XOR modelUploadId (3D model slide).
+ const {
+ id,
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations
+ } = validation.data;
+ const upsert = await upsertJobOperationStepSlide(
+ client,
+ id
+ ? {
+ id,
+ stepId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ ...(imagePath !== undefined ? { imagePath } : {}),
+ ...(modelUploadId !== undefined ? { modelUploadId } : {}),
+ ...(caption !== undefined ? { caption } : {}),
+ ...(sortOrder !== undefined ? { sortOrder } : {}),
+ ...(size !== undefined ? { size } : {}),
+ ...(annotations !== undefined ? { annotations } : {})
+ }
+ : {
+ stepId,
+ imagePath,
+ modelUploadId,
+ caption,
+ sortOrder,
+ size,
+ annotations,
+ companyId,
+ createdBy: userId
+ }
+ );
+ if (upsert.error) {
+ return data(
+ { id: null },
+ await flash(
+ request,
+ error(upsert.error, "Failed to save job operation step slide")
+ )
+ );
+ }
+
+ return { id: upsert.data?.id ?? null };
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx
new file mode 100644
index 0000000000..d58e1d1756
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx
@@ -0,0 +1,51 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { setJobOperationToolStepLink } from "~/modules/production";
+
+// Toggle a tool↔step link from the step editor's "Tools" picker (job tier).
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const formData = await request.formData();
+ const jobOperationToolId = String(formData.get("toolId") ?? "");
+ const jobOperationStepId = String(formData.get("stepId") ?? "");
+ const linked = formData.get("linked") === "true";
+
+ if (!jobOperationToolId || !jobOperationStepId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ // Verify the step belongs to the caller's company before linking. The
+ // join-table RLS only checks the tool's company, not the step side
+ // (jobOperationToolStep has no companyId), so an unscoped stepId could
+ // otherwise link across tenants. The RLS-scoped read returns nothing for a
+ // foreign step.
+ const step = await client
+ .from("jobOperationStep")
+ .select("id")
+ .eq("id", jobOperationStepId)
+ .single();
+ if (step.error || !step.data) {
+ return data({ success: false }, { status: 404 });
+ }
+
+ const result = await setJobOperationToolStepLink(client, {
+ jobOperationToolId,
+ jobOperationStepId,
+ linked
+ });
+ if (result.error) {
+ return data(
+ { success: false },
+ await flash(request, error(result.error, "Failed to update step tools"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
index 4ded8f5403..bf21da7b77 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
@@ -27,6 +27,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id: _id, ...d } = validation.data;
+ // Tool↔step links are managed by the step editor (jobOperationStepTool route), so this
+ // edit deliberately leaves them untouched.
const update = await upsertJobOperationTool(client, {
id,
...d,
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
index 5ed975713a..cf2f8d2d33 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
@@ -20,6 +20,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // Tool↔step assignment now lives on the step editor (jobOperationStepTool route),
+ // not this tool form — a new tool starts operation-level (shown on every step).
const insert = await upsertJobOperationTool(client, {
...validation.data,
companyId,
diff --git a/apps/erp/app/routes/x+/material+/$itemId.quality.tsx b/apps/erp/app/routes/x+/material+/$itemId.quality.tsx
index cfbda191fc..e992c7ee12 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.quality.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.quality.tsx
@@ -5,13 +5,14 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useParams } from "react-router";
import invariant from "tiny-invariant";
+import { getInspectionDocumentsForItem } from "~/modules/production";
import {
- getItemSamplingPlan,
- itemSamplingPlanValidator,
- upsertItemSamplingPlan
+ getItemInspectionDocumentAssignments,
+ itemInspectionDocumentAssignmentValidator,
+ upsertItemInspectionDocumentAssignment
} from "~/modules/quality";
-import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
-import { getCompanySettings } from "~/modules/settings";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import ItemQualityView from "~/modules/quality/ui/Item/ItemQualityView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -21,17 +22,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
invariant(itemId, "itemId is required");
- const [plan, settings] = await Promise.all([
- getItemSamplingPlan(client, itemId, companyId),
- getCompanySettings(client, companyId)
+ const [documents, assignments] = await Promise.all([
+ getInspectionDocumentsForItem(client, itemId, companyId),
+ getItemInspectionDocumentAssignments(client, itemId, companyId)
]);
return data({
- plan: plan.data,
- samplingStandard:
- ((settings.data as any)?.samplingStandard as
- | "ANSI_Z1_4"
- | "ISO_2859_1") ?? "ANSI_Z1_4"
+ documents: documents.data ?? [],
+ assignments: (assignments.data ?? []) as ItemInspectionDocumentAssignment[]
});
}
@@ -44,40 +42,48 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(itemId, "itemId is required");
const formData = await request.formData();
- const validation = await validator(itemSamplingPlanValidator).validate(
- formData
- );
- if (validation.error) return validationError(validation.error);
- const result = await upsertItemSamplingPlan(client, {
- ...validation.data,
- companyId,
- updatedBy: userId
- });
- if (result.error) {
+ if (formData.get("intent") === "assignment") {
+ const validation = await validator(
+ itemInspectionDocumentAssignmentValidator
+ ).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemInspectionDocumentAssignment(client, {
+ ...validation.data,
+ companyId,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.materialQuality(itemId),
+ await flash(request, error(result.error, "Failed to save assignment"))
+ );
+ }
+
throw redirect(
path.to.materialQuality(itemId),
- await flash(request, error(result.error, "Failed to save sampling plan"))
+ await flash(request, success("Inspection plan assignment updated"))
);
}
throw redirect(
path.to.materialQuality(itemId),
- await flash(request, success("Sampling plan updated"))
+ await flash(request, error(null, "Unknown intent"))
);
}
export default function MaterialQualityRoute() {
- const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { documents, assignments } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("itemId is required");
return (
- <div className="p-4">
- <SamplingPlanForm
- action={path.to.materialQuality(itemId)}
+ <div className="p-4 w-full">
+ <ItemQualityView
itemId={itemId}
- standard={samplingStandard}
- initial={plan ?? undefined}
+ actionPath={path.to.materialQuality(itemId)}
+ documents={documents}
+ assignments={assignments}
/>
</div>
);
diff --git a/apps/erp/app/routes/x+/material+/$itemId.tsx b/apps/erp/app/routes/x+/material+/$itemId.tsx
index c111941670..4e28fdcd5f 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.tsx
@@ -126,6 +126,7 @@ export default function MaterialRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -206,6 +207,13 @@ export default function MaterialRoute() {
}
];
+ tree.push({
+ key: "inspections",
+ name: "Inspections",
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
index 1fde3e4262..1ae4a4fcc5 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
@@ -117,6 +117,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...operation,
description: operation.description ?? "",
procedureId: operation.procedureId ?? undefined,
+ assemblyInstructionId: operation.assemblyInstructionId ?? undefined,
+ inspectionDocumentId: operation.inspectionDocumentId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
operationMinimumCost: operation.operationMinimumCost ?? 0,
diff --git a/apps/erp/app/routes/x+/part+/$itemId.quality.tsx b/apps/erp/app/routes/x+/part+/$itemId.quality.tsx
index 8a18c69d70..f9589a8dab 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.quality.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.quality.tsx
@@ -5,13 +5,14 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useParams } from "react-router";
import invariant from "tiny-invariant";
+import { getInspectionDocumentsForItem } from "~/modules/production";
import {
- getItemSamplingPlan,
- itemSamplingPlanValidator,
- upsertItemSamplingPlan
+ getItemInspectionDocumentAssignments,
+ itemInspectionDocumentAssignmentValidator,
+ upsertItemInspectionDocumentAssignment
} from "~/modules/quality";
-import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
-import { getCompanySettings } from "~/modules/settings";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import ItemQualityView from "~/modules/quality/ui/Item/ItemQualityView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -21,17 +22,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
invariant(itemId, "itemId is required");
- const [plan, settings] = await Promise.all([
- getItemSamplingPlan(client, itemId, companyId),
- getCompanySettings(client, companyId)
+ const [documents, assignments] = await Promise.all([
+ getInspectionDocumentsForItem(client, itemId, companyId),
+ getItemInspectionDocumentAssignments(client, itemId, companyId)
]);
return data({
- plan: plan.data,
- samplingStandard:
- ((settings.data as any)?.samplingStandard as
- | "ANSI_Z1_4"
- | "ISO_2859_1") ?? "ANSI_Z1_4"
+ documents: documents.data ?? [],
+ assignments: (assignments.data ?? []) as ItemInspectionDocumentAssignment[]
});
}
@@ -44,40 +42,48 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(itemId, "itemId is required");
const formData = await request.formData();
- const validation = await validator(itemSamplingPlanValidator).validate(
- formData
- );
- if (validation.error) return validationError(validation.error);
- const result = await upsertItemSamplingPlan(client, {
- ...validation.data,
- companyId,
- updatedBy: userId
- });
- if (result.error) {
+ if (formData.get("intent") === "assignment") {
+ const validation = await validator(
+ itemInspectionDocumentAssignmentValidator
+ ).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemInspectionDocumentAssignment(client, {
+ ...validation.data,
+ companyId,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.partQuality(itemId),
+ await flash(request, error(result.error, "Failed to save assignment"))
+ );
+ }
+
throw redirect(
path.to.partQuality(itemId),
- await flash(request, error(result.error, "Failed to save sampling plan"))
+ await flash(request, success("Inspection plan assignment updated"))
);
}
throw redirect(
path.to.partQuality(itemId),
- await flash(request, success("Sampling plan updated"))
+ await flash(request, error(null, "Unknown intent"))
);
}
export default function PartQualityRoute() {
- const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { documents, assignments } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("itemId is required");
return (
- <div className="p-4">
- <SamplingPlanForm
- action={path.to.partQuality(itemId)}
+ <div className="p-4 w-full">
+ <ItemQualityView
itemId={itemId}
- standard={samplingStandard}
- initial={plan ?? undefined}
+ actionPath={path.to.partQuality(itemId)}
+ documents={documents}
+ assignments={assignments}
/>
</div>
);
diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsx
index db486b9512..b4095de655 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx
@@ -269,6 +269,7 @@ export default function PartRoute() {
shipmentLines,
supplierQuotes,
assemblyInstructions,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -374,6 +375,13 @@ export default function PartRoute() {
});
}
+ tree.push({
+ key: "inspections",
+ name: t`Inspections`,
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
@@ -428,6 +436,7 @@ export default function PartRoute() {
shipmentLines,
supplierQuotes,
assemblyInstructions,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -533,6 +542,13 @@ export default function PartRoute() {
});
}
+ tree.push({
+ key: "inspections",
+ name: "Inspections",
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
diff --git a/apps/erp/app/routes/x+/quality+/inspection.new.tsx b/apps/erp/app/routes/x+/production+/inspection.new.tsx
similarity index 68%
rename from apps/erp/app/routes/x+/quality+/inspection.new.tsx
rename to apps/erp/app/routes/x+/production+/inspection.new.tsx
index bd640873f0..93026ef3fc 100644
--- a/apps/erp/app/routes/x+/quality+/inspection.new.tsx
+++ b/apps/erp/app/routes/x+/production+/inspection.new.tsx
@@ -2,12 +2,17 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import type {
+ ActionFunctionArgs,
+ ClientActionFunctionArgs,
+ LoaderFunctionArgs
+} from "react-router";
import { redirect, useNavigate } from "react-router";
-import { upsertInspectionDocument } from "~/modules/quality";
-import { inspectionDocumentValidator } from "~/modules/quality/quality.models";
-import { InspectionDocumentForm } from "~/modules/quality/ui/InspectionDocument";
+import { upsertInspectionDocument } from "~/modules/production";
+import { inspectionDocumentValidator } from "~/modules/production/production.models";
+import { InspectionDocumentForm } from "~/modules/production/ui/InspectionDocument";
import { path } from "~/utils/path";
+import { invalidateInspectionDocuments } from "~/utils/react-query";
export async function loader({ request }: LoaderFunctionArgs) {
await requirePermissions(request, { create: "quality" });
@@ -40,17 +45,22 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.inspectionDocuments,
await flash(
request,
- error(result.error, "Failed to create inspection document")
+ error(result.error, "Failed to create inspection plan")
)
);
}
throw redirect(
path.to.inspectionDocument(result.data.id),
- await flash(request, success("Inspection document created"))
+ await flash(request, success("Inspection plan created"))
);
}
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ invalidateInspectionDocuments();
+ return await serverAction();
+}
+
export default function BalloonNewRoute() {
const navigate = useNavigate();
diff --git a/apps/erp/app/routes/x+/quality+/inspection.tsx b/apps/erp/app/routes/x+/production+/inspection.tsx
similarity index 85%
rename from apps/erp/app/routes/x+/quality+/inspection.tsx
rename to apps/erp/app/routes/x+/production+/inspection.tsx
index 41da61ddbe..133143e7f7 100644
--- a/apps/erp/app/routes/x+/quality+/inspection.tsx
+++ b/apps/erp/app/routes/x+/production+/inspection.tsx
@@ -3,15 +3,15 @@ import { VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, useLoaderData } from "react-router";
-import { getInspectionDocuments } from "~/modules/quality";
-import { InspectionDocumentTable } from "~/modules/quality/ui/InspectionDocument";
+import { getInspectionDocuments } from "~/modules/production";
+import { InspectionDocumentTable } from "~/modules/production/ui/InspectionDocument";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
- breadcrumb: msg`Quality`,
- to: path.to.quality
+ breadcrumb: msg`Inspection Plans`,
+ to: path.to.inspectionDocuments
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.tsx b/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.tsx
index fcb7428b6a..8519b8fd0d 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/inbound-inspections.$id.tsx
@@ -1,115 +1,14 @@
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import type { LoaderFunctionArgs } from "react-router";
-import { data, redirect, useLoaderData } from "react-router";
+import { redirect } from "react-router";
import invariant from "tiny-invariant";
-import {
- getInboundInspection,
- getInboundInspectionLotTrackedEntities,
- getIssueTypesList
-} from "~/modules/quality";
-import type {
- InboundInspectionRow,
- InboundInspectionSample,
- InspectionTrackedEntity,
- IssueTypeListItem
-} from "~/modules/quality/types";
-import InboundInspectionLotView from "~/modules/quality/ui/InboundInspections/InboundInspectionLotView";
-import { getCompanySettings } from "~/modules/settings";
import { path } from "~/utils/path";
+// The inbound inspection drawer moved to a full-screen execution view at
+// /x/inspection/{id}. Keep old links (notifications, bookmarks)
+// working with a redirect.
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
- view: "quality",
- role: "employee"
- });
const { id } = params;
invariant(id, "id is required");
-
- const [inspection, settings, issueTypes] = await Promise.all([
- getInboundInspection(client, id),
- getCompanySettings(client, companyId),
- getIssueTypesList(client, companyId)
- ]);
-
- if (inspection.error || !inspection.data) {
- throw redirect(
- path.to.inboundInspections,
- await flash(request, error(inspection.error, "Failed to load inspection"))
- );
- }
-
- const insp = inspection.data as InboundInspectionRow & {
- item: {
- readableId: string | null;
- name: string;
- type: string;
- itemTrackingType: string | null;
- } | null;
- receipt: {
- receiptId: string;
- supplierId: string | null;
- createdBy: string;
- } | null;
- supplier: { name: string } | null;
- inboundInspectionSample: InboundInspectionSample[];
- };
-
- if (insp.companyId !== companyId) {
- throw redirect(path.to.inboundInspections);
- }
-
- const lotEntities = await getInboundInspectionLotTrackedEntities(
- client,
- insp.receiptLineId,
- companyId
- );
-
- return data({
- inspection: insp,
- receiptReadableId: insp.receipt?.receiptId ?? null,
- receiverId: insp.receipt?.createdBy ?? null,
- itemName: insp.item?.name ?? "",
- itemTrackingType: insp.item?.itemTrackingType ?? null,
- supplierName: insp.supplier?.name ?? null,
- samples: insp.inboundInspectionSample ?? [],
- lotEntities: (lotEntities.data ?? []) as InspectionTrackedEntity[],
- issueTypes: (issueTypes.data ?? []) as IssueTypeListItem[],
- enforceFourEyes:
- ((settings.data as any)?.enforceInspectionFourEyes as boolean) ?? false,
- currentUserId: userId
- });
-}
-
-export default function InboundInspectionRoute() {
- const {
- inspection,
- receiptReadableId,
- receiverId,
- itemName,
- itemTrackingType,
- supplierName,
- samples,
- lotEntities,
- issueTypes,
- enforceFourEyes,
- currentUserId
- } = useLoaderData<typeof loader>();
-
- return (
- <InboundInspectionLotView
- inspection={inspection as InboundInspectionRow}
- receiptReadableId={receiptReadableId}
- receiverId={receiverId}
- itemName={itemName}
- itemTrackingType={itemTrackingType}
- supplierName={supplierName}
- samples={samples as InboundInspectionSample[]}
- lotEntities={lotEntities as InspectionTrackedEntity[]}
- issueTypes={issueTypes as IssueTypeListItem[]}
- currentUserId={currentUserId}
- enforceFourEyes={enforceFourEyes}
- />
- );
+ const search = new URL(request.url).search;
+ throw redirect(`${path.to.inspection(id)}${search}`);
}
diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx b/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx
index b2334aa6d3..537ca3881b 100644
--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx
+++ b/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx
@@ -1,66 +1,9 @@
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { VStack } from "@carbon/react";
-import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
-import { Outlet, redirect, useLoaderData } from "react-router";
-import { getInboundInspections } from "~/modules/quality";
-import InboundInspectionsTable from "~/modules/quality/ui/InboundInspections/InboundInspectionsTable";
-import type { Handle } from "~/utils/handle";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
-import { getGenericQueryFilters } from "~/utils/query";
-
-export const handle: Handle = {
- breadcrumb: msg`Inbound Inspections`,
- to: path.to.inboundInspections
-};
+// The Inbound Inspections submodule was renamed to Inspections.
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "quality",
- role: "employee"
- });
-
- const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const search = searchParams.get("search");
- const status = searchParams.get("status");
- const { limit, offset, sorts, filters } =
- getGenericQueryFilters(searchParams);
-
- const inspections = await getInboundInspections(client, companyId, {
- search,
- status,
- limit,
- offset,
- sorts,
- filters
- });
-
- if (inspections.error) {
- throw redirect(
- path.to.quality,
- await flash(
- request,
- error(inspections.error, "Failed to load inspections")
- )
- );
- }
-
- return {
- inspections: inspections.data ?? [],
- count: inspections.count ?? 0
- };
-}
-
-export default function InboundInspectionsRoute() {
- const { inspections, count } = useLoaderData<typeof loader>();
-
- return (
- <VStack spacing={0} className="h-full">
- <InboundInspectionsTable data={inspections} count={count} />
- <Outlet />
- </VStack>
- );
+ const search = new URL(request.url).search;
+ throw redirect(`${path.to.inspections}${search}`);
}
diff --git a/apps/erp/app/routes/x+/quality+/inspections.tsx b/apps/erp/app/routes/x+/quality+/inspections.tsx
new file mode 100644
index 0000000000..c6efc0645a
--- /dev/null
+++ b/apps/erp/app/routes/x+/quality+/inspections.tsx
@@ -0,0 +1,68 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, redirect, useLoaderData } from "react-router";
+import { getInspections } from "~/modules/quality";
+import InspectionsTable from "~/modules/quality/ui/Inspections/InspectionsTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: msg`Inspections`,
+ to: path.to.inspections
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "quality",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const status = searchParams.get("status");
+ const source = searchParams.get("source");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const inspections = await getInspections(client, companyId, {
+ search,
+ status,
+ source,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+
+ if (inspections.error) {
+ throw redirect(
+ path.to.quality,
+ await flash(
+ request,
+ error(inspections.error, "Failed to load inspections")
+ )
+ );
+ }
+
+ return {
+ inspections: inspections.data ?? [],
+ count: inspections.count ?? 0
+ };
+}
+
+export default function InspectionsRoute() {
+ const { inspections, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <InspectionsTable data={inspections} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 5545c190fc..bcc66fab99 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -355,6 +355,7 @@ export default function QuoteLine() {
<QuoteBillOfProcess
key={`bop:${methodData.rootMethodId}`}
quoteMakeMethodId={methodData.rootMethodId}
+ itemId={line?.itemId ?? ""}
// @ts-expect-error
operations={methodData.methodOperations}
tags={methodData.tags ?? []}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
index 3d4a227d43..b2d87d14cb 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
@@ -83,6 +83,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...o,
description: o.description ?? "",
procedureId: o.procedureId ?? undefined,
+ assemblyInstructionId: o.assemblyInstructionId ?? undefined,
+ inspectionDocumentId: o.inspectionDocumentId ?? undefined,
workCenterId: o.workCenterId ?? undefined,
laborRate: o.laborRate ?? 0,
machineRate: o.machineRate ?? 0,
@@ -103,7 +105,7 @@ export default function QuoteMakeMethodRoute() {
if (!methodId) throw new Error("Could not find methodId");
const loaderData = useLoaderData<typeof loader>();
- const { materials, operations, tags } = loaderData;
+ const { makeMethod, materials, operations, tags } = loaderData;
return (
<VStack spacing={2}>
@@ -119,6 +121,7 @@ export default function QuoteMakeMethodRoute() {
<QuoteBillOfProcess
key={`bop:${methodId}`}
quoteMakeMethodId={methodId}
+ itemId={makeMethod.itemId ?? ""}
materials={materials}
// @ts-expect-error
operations={operations}
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index 225e3f3659..d23faf3025 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -13,6 +13,7 @@ import {
getReceiptTracking,
getShelfLifeForItems
} from "~/modules/inventory";
+import { getReceiptInspections } from "~/modules/quality";
import { getCompanySettings } from "~/modules/settings";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -34,11 +35,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { receiptId } = params;
if (!receiptId) throw new Error("Could not find receiptId");
- const [receipt, receiptLines, receiptLineTracking] = await Promise.all([
- getReceipt(serviceRole, receiptId),
- getReceiptLines(serviceRole, receiptId),
- getReceiptTracking(serviceRole, receiptId, companyId)
- ]);
+ const [receipt, receiptLines, receiptLineTracking, receiptInspections] =
+ await Promise.all([
+ getReceipt(serviceRole, receiptId),
+ getReceiptLines(serviceRole, receiptId),
+ getReceiptTracking(serviceRole, receiptId, companyId),
+ getReceiptInspections(serviceRole, receiptId, companyId)
+ ]);
if (receipt.error) {
throw redirect(
@@ -113,6 +116,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
receipt: receipt.data,
receiptLines: receiptLines.data ?? [],
+ receiptInspections: receiptInspections.data ?? [],
fixedAssetLines,
receiptFiles: getReceiptFiles(serviceRole, companyId, receiptLineIds) ?? [],
receiptLineTracking: receiptLineTracking.data ?? [],
diff --git a/apps/erp/app/routes/x+/resources+/processes.$processId.tsx b/apps/erp/app/routes/x+/resources+/processes.$processId.tsx
index 4f8bc64273..f05f419966 100644
--- a/apps/erp/app/routes/x+/resources+/processes.$processId.tsx
+++ b/apps/erp/app/routes/x+/resources+/processes.$processId.tsx
@@ -94,7 +94,7 @@ export default function ProcessRoute() {
const initialValues = {
id: process.id!,
name: process.name!,
- processType: process.processType ?? "Inside",
+ processType: process.processType ?? "Process",
defaultStandardFactor: process.defaultStandardFactor ?? "Minutes/Piece",
workCenters: process.workCenters ?? [],
// @ts-ignore
diff --git a/apps/erp/app/routes/x+/resources+/processes.new.tsx b/apps/erp/app/routes/x+/resources+/processes.new.tsx
index b578a05e6d..f058babcf6 100644
--- a/apps/erp/app/routes/x+/resources+/processes.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/processes.new.tsx
@@ -75,7 +75,7 @@ export default function NewProcessRoute() {
const initialValues = {
name: "",
- processType: "Inside" as const,
+ processType: "Process" as const,
defaultStandardFactor: "Minutes/Piece" as const,
completeAllOnScan: false
};
diff --git a/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx
index 9e988c8eab..26f2604643 100644
--- a/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx
+++ b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx
@@ -84,6 +84,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...operation,
description: operation.description ?? "",
procedureId: operation.procedureId ?? undefined,
+ assemblyInstructionId: operation.assemblyInstructionId ?? undefined,
+ inspectionDocumentId: operation.inspectionDocumentId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
operationMinimumCost: operation.operationMinimumCost ?? 0,
diff --git a/apps/erp/app/routes/x+/service+/$itemId.quality.tsx b/apps/erp/app/routes/x+/service+/$itemId.quality.tsx
index df883d6985..50ff14d822 100644
--- a/apps/erp/app/routes/x+/service+/$itemId.quality.tsx
+++ b/apps/erp/app/routes/x+/service+/$itemId.quality.tsx
@@ -5,13 +5,14 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useParams } from "react-router";
import invariant from "tiny-invariant";
+import { getInspectionDocumentsForItem } from "~/modules/production";
import {
- getItemSamplingPlan,
- itemSamplingPlanValidator,
- upsertItemSamplingPlan
+ getItemInspectionDocumentAssignments,
+ itemInspectionDocumentAssignmentValidator,
+ upsertItemInspectionDocumentAssignment
} from "~/modules/quality";
-import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
-import { getCompanySettings } from "~/modules/settings";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import ItemQualityView from "~/modules/quality/ui/Item/ItemQualityView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -21,17 +22,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
invariant(itemId, "itemId is required");
- const [plan, settings] = await Promise.all([
- getItemSamplingPlan(client, itemId, companyId),
- getCompanySettings(client, companyId)
+ const [documents, assignments] = await Promise.all([
+ getInspectionDocumentsForItem(client, itemId, companyId),
+ getItemInspectionDocumentAssignments(client, itemId, companyId)
]);
return data({
- plan: plan.data,
- samplingStandard:
- ((settings.data as any)?.samplingStandard as
- | "ANSI_Z1_4"
- | "ISO_2859_1") ?? "ANSI_Z1_4"
+ documents: documents.data ?? [],
+ assignments: (assignments.data ?? []) as ItemInspectionDocumentAssignment[]
});
}
@@ -44,40 +42,48 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(itemId, "itemId is required");
const formData = await request.formData();
- const validation = await validator(itemSamplingPlanValidator).validate(
- formData
- );
- if (validation.error) return validationError(validation.error);
- const result = await upsertItemSamplingPlan(client, {
- ...validation.data,
- companyId,
- updatedBy: userId
- });
- if (result.error) {
+ if (formData.get("intent") === "assignment") {
+ const validation = await validator(
+ itemInspectionDocumentAssignmentValidator
+ ).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemInspectionDocumentAssignment(client, {
+ ...validation.data,
+ companyId,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.serviceQuality(itemId),
+ await flash(request, error(result.error, "Failed to save assignment"))
+ );
+ }
+
throw redirect(
path.to.serviceQuality(itemId),
- await flash(request, error(result.error, "Failed to save sampling plan"))
+ await flash(request, success("Inspection plan assignment updated"))
);
}
throw redirect(
path.to.serviceQuality(itemId),
- await flash(request, success("Sampling plan updated"))
+ await flash(request, error(null, "Unknown intent"))
);
}
export default function ServiceQualityRoute() {
- const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { documents, assignments } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("itemId is required");
return (
- <div className="p-4">
- <SamplingPlanForm
- action={path.to.serviceQuality(itemId)}
+ <div className="p-4 w-full">
+ <ItemQualityView
itemId={itemId}
- standard={samplingStandard}
- initial={plan ?? undefined}
+ actionPath={path.to.serviceQuality(itemId)}
+ documents={documents}
+ assignments={assignments}
/>
</div>
);
diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsx
index ad30244cad..6fdc4d2d3c 100644
--- a/apps/erp/app/routes/x+/settings+/production.tsx
+++ b/apps/erp/app/routes/x+/settings+/production.tsx
@@ -20,8 +20,12 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
-import { Users } from "~/components/Form";
-import { getCompanySettings, jobCompletedValidator } from "~/modules/settings";
+import { Boolean, Users } from "~/components/Form";
+import {
+ getCompanySettings,
+ jobCompletedValidator,
+ operationTimerValidator
+} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -80,6 +84,27 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, message: "Job notification settings updated" };
}
+ if (intent === "operationTimer") {
+ const validation = await validator(operationTimerValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const update = await client
+ .from("companySettings")
+ .update({
+ autoStartOperationTimer: validation.data.autoStartOperationTimer
+ })
+ .eq("id", companyId);
+
+ if (update.error) return { success: false, message: update.error.message };
+
+ return { success: true, message: "Operation timer settings updated" };
+ }
+
return { success: false, message: "Unknown intent" };
}
@@ -87,6 +112,7 @@ export default function ProductionSettingsRoute() {
const { t } = useLingui();
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ const timerFetcher = useFetcher<typeof action>();
useEffect(() => {
if (fetcher.data?.success === true && fetcher?.data?.message) {
@@ -98,6 +124,16 @@ export default function ProductionSettingsRoute() {
}
}, [fetcher.data?.message, fetcher.data?.success]);
+ useEffect(() => {
+ if (timerFetcher.data?.success === true && timerFetcher?.data?.message) {
+ toast.success(timerFetcher.data.message);
+ }
+
+ if (timerFetcher.data?.success === false && timerFetcher?.data?.message) {
+ toast.error(timerFetcher.data.message);
+ }
+ }, [timerFetcher.data?.message, timerFetcher.data?.success]);
+
return (
<ScrollArea className="w-full h-[calc(100dvh-49px)]">
<VStack
@@ -165,6 +201,49 @@ export default function ProductionSettingsRoute() {
</CardFooter>
</ValidatedForm>
</Card>
+
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={operationTimerValidator}
+ defaultValues={{
+ autoStartOperationTimer:
+ companySettings.autoStartOperationTimer ?? false
+ }}
+ fetcher={timerFetcher}
+ >
+ <input type="hidden" name="intent" value="operationTimer" />
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Trans>Operation Timer</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>
+ Auto-start the operator's timer when they open an operation in
+ the MES so time logs are captured from the start.
+ </Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-8 max-w-[400px]">
+ <Boolean
+ name="autoStartOperationTimer"
+ label={t`Auto-start timer on open`}
+ description={t`When on, opening an operation starts its timer automatically.`}
+ bordered
+ />
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={timerFetcher.state !== "idle"}
+ isLoading={timerFetcher.state !== "idle"}
+ >
+ <Trans>Save</Trans>
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
</VStack>
</ScrollArea>
);
diff --git a/apps/erp/app/routes/x+/settings+/quality.tsx b/apps/erp/app/routes/x+/settings+/quality.tsx
index 0383ee0305..f887934c84 100644
--- a/apps/erp/app/routes/x+/settings+/quality.tsx
+++ b/apps/erp/app/routes/x+/settings+/quality.tsx
@@ -302,9 +302,7 @@ export default function QualitySettingsRoute() {
<HStack className="justify-between items-center">
<div>
<CardTitle>
- <Trans>
- Inbound Inspections: Require Different Inspector
- </Trans>
+ <Trans>Inspections: Require Different Inspector</Trans>
</CardTitle>
<CardDescription>
<Trans>
diff --git a/apps/erp/app/routes/x+/settings+/resources.tsx b/apps/erp/app/routes/x+/settings+/resources.tsx
index 9b8a738e22..7ffb3d8fb9 100644
--- a/apps/erp/app/routes/x+/settings+/resources.tsx
+++ b/apps/erp/app/routes/x+/settings+/resources.tsx
@@ -314,6 +314,7 @@ export default function ResourcesSettingsRoute() {
description="Create maintenance dispatches in advance"
value={maintenanceGenerateInAdvance}
onChange={setMaintenanceGenerateInAdvance}
+ bordered
/>
</div>
{maintenanceGenerateInAdvance && (
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
index 3d95c7a11b..bfc339edec 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
@@ -89,6 +89,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...operation,
description: operation.description ?? "",
procedureId: operation.procedureId ?? undefined,
+ assemblyInstructionId: operation.assemblyInstructionId ?? undefined,
+ inspectionDocumentId: operation.inspectionDocumentId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
operationMinimumCost: operation.operationMinimumCost ?? 0,
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.quality.tsx b/apps/erp/app/routes/x+/tool+/$itemId.quality.tsx
index 9bbe1f0306..847b9a88c3 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.quality.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.quality.tsx
@@ -5,13 +5,14 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useParams } from "react-router";
import invariant from "tiny-invariant";
+import { getInspectionDocumentsForItem } from "~/modules/production";
import {
- getItemSamplingPlan,
- itemSamplingPlanValidator,
- upsertItemSamplingPlan
+ getItemInspectionDocumentAssignments,
+ itemInspectionDocumentAssignmentValidator,
+ upsertItemInspectionDocumentAssignment
} from "~/modules/quality";
-import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
-import { getCompanySettings } from "~/modules/settings";
+import type { ItemInspectionDocumentAssignment } from "~/modules/quality/types";
+import ItemQualityView from "~/modules/quality/ui/Item/ItemQualityView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -21,17 +22,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
invariant(itemId, "itemId is required");
- const [plan, settings] = await Promise.all([
- getItemSamplingPlan(client, itemId, companyId),
- getCompanySettings(client, companyId)
+ const [documents, assignments] = await Promise.all([
+ getInspectionDocumentsForItem(client, itemId, companyId),
+ getItemInspectionDocumentAssignments(client, itemId, companyId)
]);
return data({
- plan: plan.data,
- samplingStandard:
- ((settings.data as any)?.samplingStandard as
- | "ANSI_Z1_4"
- | "ISO_2859_1") ?? "ANSI_Z1_4"
+ documents: documents.data ?? [],
+ assignments: (assignments.data ?? []) as ItemInspectionDocumentAssignment[]
});
}
@@ -44,40 +42,48 @@ export async function action({ request, params }: ActionFunctionArgs) {
invariant(itemId, "itemId is required");
const formData = await request.formData();
- const validation = await validator(itemSamplingPlanValidator).validate(
- formData
- );
- if (validation.error) return validationError(validation.error);
- const result = await upsertItemSamplingPlan(client, {
- ...validation.data,
- companyId,
- updatedBy: userId
- });
- if (result.error) {
+ if (formData.get("intent") === "assignment") {
+ const validation = await validator(
+ itemInspectionDocumentAssignmentValidator
+ ).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemInspectionDocumentAssignment(client, {
+ ...validation.data,
+ companyId,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.toolQuality(itemId),
+ await flash(request, error(result.error, "Failed to save assignment"))
+ );
+ }
+
throw redirect(
path.to.toolQuality(itemId),
- await flash(request, error(result.error, "Failed to save sampling plan"))
+ await flash(request, success("Inspection plan assignment updated"))
);
}
throw redirect(
path.to.toolQuality(itemId),
- await flash(request, success("Sampling plan updated"))
+ await flash(request, error(null, "Unknown intent"))
);
}
export default function ToolQualityRoute() {
- const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { documents, assignments } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("itemId is required");
return (
- <div className="p-4">
- <SamplingPlanForm
- action={path.to.toolQuality(itemId)}
+ <div className="p-4 w-full">
+ <ItemQualityView
itemId={itemId}
- standard={samplingStandard}
- initial={plan ?? undefined}
+ actionPath={path.to.toolQuality(itemId)}
+ documents={documents}
+ assignments={assignments}
/>
</div>
);
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.tsx
index ed1ae945ca..c670031837 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.tsx
@@ -256,6 +256,7 @@ export default function ToolRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -351,6 +352,13 @@ export default function ToolRoute() {
}
];
+ tree.push({
+ key: "inspections",
+ name: t`Inspections`,
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
@@ -404,6 +412,7 @@ export default function ToolRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ inspections,
jobMaterialUsage
} = resolvedUsedIn;
@@ -499,6 +508,13 @@ export default function ToolRoute() {
}
];
+ tree.push({
+ key: "inspections",
+ name: "Inspections",
+ module: "quality",
+ children: inspections
+ });
+
return (
<UsedInTree
tree={tree}
diff --git a/apps/erp/app/utils/bom.ts b/apps/erp/app/utils/bom.ts
index 47899c4f93..a178a20bc0 100644
--- a/apps/erp/app/utils/bom.ts
+++ b/apps/erp/app/utils/bom.ts
@@ -123,7 +123,7 @@ function calculateOperationUnitCost(
op: BomOperation,
batchSize: number
): number {
- if (op.operationType === "Outside") {
+ if (op.operationType === "Outside Processing") {
return Math.max(op.operationMinimumCost, op.operationUnitCost);
}
diff --git a/apps/erp/app/utils/form.ts b/apps/erp/app/utils/form.ts
index e68ecb4653..ad338fc854 100644
--- a/apps/erp/app/utils/form.ts
+++ b/apps/erp/app/utils/form.ts
@@ -24,6 +24,29 @@ export const getCustomFields = (
}, {});
};
+// Read a repeated/array form field straight off raw FormData, tolerating both the plain
+// repeated name ("field") and the bracket-indexed names our MultiSelect emits ("field[0]",
+// "field[1]", ...). Used where the value is read outside the zod validator (e.g. the
+// tier-agnostic operationToolValidator) — the validator itself decodes brackets via
+// objectFromPathEntries, but formData.getAll does not.
+export const getFormDataArray = (
+ formData: FormData,
+ name: string
+): string[] => {
+ const out: string[] = [];
+ const prefix = `${name}[`;
+ for (const [key, value] of formData.entries()) {
+ if (
+ (key === name || key.startsWith(prefix)) &&
+ typeof value === "string" &&
+ value.length > 0
+ ) {
+ out.push(value);
+ }
+ }
+ return out;
+};
+
export const setCustomFields = (
formData: FormData
): Record<string, string | number | boolean> => {
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index cc3ff3c46e..115809e2ab 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -48,6 +48,10 @@ export const path = {
agentFeedback: `${api}/agent/feedback`,
agentThread: (id: string) => `${api}/agent/thread/${id}`,
agentThreads: `${api}/agent/threads`,
+ assemblyForItem: (itemId: string) =>
+ generatePath(`${api}/production/assembly-for-item/${itemId}`),
+ assemblyInstructions: (itemId: string) =>
+ generatePath(`${api}/production/assembly-instructions/${itemId}`),
assetClasses: `${api}/accounting/asset-classes`,
assign: `${api}/assign`,
batchNumbers: (itemId: string) =>
@@ -88,8 +92,10 @@ export const path = {
generatePath(`${api}/ai/csv/${table}/columns`),
inspectionDocumentBalloonAnalyze: (inspectionDocumentId: string) =>
generatePath(
- `${api}/quality/inspection-document/${inspectionDocumentId}/balloon-analyze`
+ `${api}/production/inspection-document/${inspectionDocumentId}/balloon-analyze`
),
+ inspectionDocuments: (itemId: string) =>
+ generatePath(`${api}/production/inspection-documents/${itemId}`),
item: (type: string) => generatePath(`${api}/item/${type}`),
itemConfigurable: `${api}/items/configurable`,
itemCostRecalculate: (itemId: string) =>
@@ -306,16 +312,12 @@ export const path = {
generatePath(`${x}/assembly/${id}/model/invalidate`),
assemblyPlanRerun: (id: string) =>
generatePath(`${x}/assembly/${id}/plan/rerun`),
- assemblyStandardNote: (noteId: string) =>
- generatePath(`${x}/assembly/standard-notes/${noteId}`),
assemblyStepMaterial: (id: string, materialId: string) =>
generatePath(`${x}/assembly/${id}/materials/${materialId}`),
assemblyStepMaterialOrder: (id: string) =>
generatePath(`${x}/assembly/${id}/materials/order`),
- assemblyStepRequirement: (id: string, requirementId: string) =>
- generatePath(`${x}/assembly/${id}/requirements/${requirementId}`),
- assemblyStepRequirementOrder: (id: string) =>
- generatePath(`${x}/assembly/${id}/requirements/order`),
+ assemblySyncBop: (id: string) =>
+ generatePath(`${x}/assembly/${id}/sync-bop`),
assetClass: (id: string) =>
generatePath(`${x}/accounting/asset-class/${id}`),
assetClasses: `${x}/accounting/asset-classes`,
@@ -536,12 +538,12 @@ export const path = {
generatePath(`${x}/assembly/delete/${id}`),
deleteAssemblyInstructionStep: (id: string, stepId: string) =>
generatePath(`${x}/assembly/${id}/steps/delete/${stepId}`),
- deleteAssemblyStandardNote: (noteId: string) =>
- generatePath(`${x}/assembly/standard-notes/delete/${noteId}`),
deleteAssemblyStepMaterial: (id: string, materialId: string) =>
generatePath(`${x}/assembly/${id}/materials/delete/${materialId}`),
- deleteAssemblyStepRequirement: (id: string, requirementId: string) =>
- generatePath(`${x}/assembly/${id}/requirements/delete/${requirementId}`),
+ deleteAssemblyStepSlide: (id: string, slideId: string) =>
+ generatePath(`${x}/assembly/${id}/slides/delete/${slideId}`),
+ deleteAssemblyStepTool: (id: string, toolId: string) =>
+ generatePath(`${x}/assembly/${id}/tools/delete/${toolId}`),
deleteAssemblyUnit: (id: string, unitId: string) =>
generatePath(`${x}/assembly/${id}/units/delete/${unitId}`),
deleteAssetClass: (id: string) =>
@@ -630,7 +632,7 @@ export const path = {
deleteHoliday: (id: string) =>
generatePath(`${x}/people/holidays/delete/${id}`),
deleteInspectionDocument: (id: string) =>
- generatePath(`${x}/inspection/${id}/delete`),
+ generatePath(`${x}/inspection-document/${id}/delete`),
deleteInvestigationType: (id: string) =>
generatePath(`${x}/quality/investigation-types/delete/${id}`),
deleteIssue: (id: string) => generatePath(`${x}/issue/delete/${id}`),
@@ -652,6 +654,8 @@ export const path = {
generatePath(`${x}/job/methods/operation/parameter/delete/${id}`),
deleteJobOperationStep: (id: string) =>
generatePath(`${x}/job/methods/operation/step/delete/${id}`),
+ deleteJobOperationStepSlide: (id: string) =>
+ generatePath(`${x}/job/methods/operation/step/slide/delete/${id}`),
deleteJobOperationTool: (id: string) =>
generatePath(`${x}/job/methods/operation/tool/delete/${id}`),
deleteJournalEntry: (id: string) =>
@@ -688,6 +692,8 @@ export const path = {
generatePath(`${x}/items/methods/operation/parameter/delete/${id}`),
deleteMethodOperationStep: (id: string) =>
generatePath(`${x}/items/methods/operation/step/delete/${id}`),
+ deleteMethodOperationStepSlide: (id: string) =>
+ generatePath(`${x}/items/methods/operation/step/slide/delete/${id}`),
deleteMethodOperationTool: (id: string) =>
generatePath(`${x}/items/methods/operation/tool/delete/${id}`),
deleteNoQuoteReason: (id: string) =>
@@ -840,6 +846,10 @@ export const path = {
generatePath(`${x}/documents/search/view/${id}`),
download: (token: string) => `/download/${token}`,
downloadError: (reason: string) => `/download/error?reason=${reason}`,
+ duplicateJobOperationStep: (id: string) =>
+ generatePath(`${x}/job/methods/operation/step/duplicate/${id}`),
+ duplicateMethodOperationStep: (id: string) =>
+ generatePath(`${x}/items/methods/operation/step/duplicate/${id}`),
duplicatePriceList: `${x}/sales/price-list/duplicate`,
editMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>
generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}`),
@@ -1112,14 +1122,26 @@ export const path = {
holiday: (id: string) => generatePath(`${x}/people/holidays/${id}`),
holidays: `${x}/people/holidays`,
import: (tableId: string) => generatePath(`${x}/shared/import/${tableId}`),
- inboundInspection: (id: string) =>
- generatePath(`${x}/quality/inbound-inspections/${id}`),
- inboundInspections: `${x}/quality/inbound-inspections`,
incomeStatement: `${x}/accounting/income-statement`,
incomeStatementLedger: (id: string) =>
generatePath(`${x}/accounting/income-statement/${id}`),
- inspectionDocument: (id: string) => generatePath(`${x}/inspection/${id}`),
- inspectionDocuments: `${x}/quality/inspection`,
+ inspection: (id: string) => generatePath(`${x}/inspection/${id}`),
+ inspectionAccept: (id: string) =>
+ generatePath(`${x}/inspection/${id}/accept`),
+ inspectionAssignedDocument: (id: string) =>
+ generatePath(`${x}/inspection/${id}/document`),
+ inspectionDocument: (id: string) =>
+ generatePath(`${x}/inspection-document/${id}`),
+ inspectionDocuments: `${x}/production/inspection`,
+ inspectionMeasurement: (id: string) =>
+ generatePath(`${x}/inspection/${id}/measurement`),
+ inspectionPartial: (id: string) =>
+ generatePath(`${x}/inspection/${id}/partial`),
+ inspectionReject: (id: string) =>
+ generatePath(`${x}/inspection/${id}/reject`),
+ inspectionSample: (id: string) =>
+ generatePath(`${x}/inspection/${id}/sample`),
+ inspections: `${x}/quality/inspections`,
integration: (id: string) =>
generatePath(`${x}/settings/integrations/${id}`),
integrationDeactivate: (id: string) =>
@@ -1209,10 +1231,12 @@ export const path = {
jobOperationStatus: `${x}/job/methods/operation/status`,
jobOperationStep: (id: string) =>
generatePath(`${x}/job/methods/operation/step/${id}`),
+ jobOperationStepMaterial: `${x}/job/methods/operation/step/material`,
jobOperationStepOrder: (operationId: string) =>
generatePath(`${x}/job/methods/operation/${operationId}/step/order`),
jobOperationStepRecords: (id: string) =>
generatePath(`${x}/job/${id}/steps`),
+ jobOperationStepTool: `${x}/job/methods/operation/step/tool`,
jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),
jobOperationsDelete: (jobId: string) =>
generatePath(`${x}/job/methods/${jobId}/operation/delete`),
@@ -1324,8 +1348,10 @@ export const path = {
generatePath(`${x}/items/methods/operation/parameter/${id}`),
methodOperationStep: (id: string) =>
generatePath(`${x}/items/methods/operation/step/${id}`),
+ methodOperationStepMaterial: `${x}/items/methods/operation/step/material`,
methodOperationStepOrder: (operationId: string) =>
generatePath(`${x}/items/methods/operation/${operationId}/step/order`),
+ methodOperationStepTool: `${x}/items/methods/operation/step/tool`,
methodOperations: `${x}/items/methods/operations`,
methodOperationsDelete: `${x}/items/methods/operation/delete`,
methodOperationsOrder: `${x}/items/methods/operation/order`,
@@ -1344,11 +1370,12 @@ export const path = {
newAssemblyInstruction: `${x}/production/assemblies/new`,
newAssemblyInstructionStep: (id: string) =>
generatePath(`${x}/assembly/${id}/steps/new`),
- newAssemblyStandardNote: `${x}/assembly/standard-notes/new`,
newAssemblyStepMaterial: (id: string) =>
generatePath(`${x}/assembly/${id}/materials/new`),
- newAssemblyStepRequirement: (id: string) =>
- generatePath(`${x}/assembly/${id}/requirements/new`),
+ newAssemblyStepSlide: (id: string) =>
+ generatePath(`${x}/assembly/${id}/slides/new`),
+ newAssemblyStepTool: (id: string) =>
+ generatePath(`${x}/assembly/${id}/tools/new`),
newAssemblyUnit: (id: string) =>
generatePath(`${x}/assembly/${id}/units/new`),
newAssetClass: `${x}/accounting/asset-classes/new`,
@@ -1410,7 +1437,7 @@ export const path = {
newGaugeType: `${x}/quality/gauge-types/new`,
newGroup: `${x}/users/groups/new`,
newHoliday: `${x}/people/holidays/new`,
- newInspectionDocument: `${x}/quality/inspection/new`,
+ newInspectionDocument: `${x}/production/inspection/new`,
newIntercompanyTransaction: `${x}/accounting/intercompany/new`,
newInventoryCount: `${x}/inventory/inventory-count/new`,
newInvestigationType: `${x}/quality/investigation-types/new`,
@@ -1427,6 +1454,7 @@ export const path = {
generatePath(`${x}/job/methods/${jobId}/operation/new`),
newJobOperationParameter: `${x}/job/methods/operation/parameter/new`,
newJobOperationStep: `${x}/job/methods/operation/step/new`,
+ newJobOperationStepSlide: `${x}/job/methods/operation/step/slide/new`,
newJobOperationTool: `${x}/job/methods/operation/tool/new`,
newJournalEntry: `${x}/accounting/journals/new`,
newKanban: `${x}/inventory/kanbans/new`,
@@ -1451,6 +1479,7 @@ export const path = {
newMethodOperation: `${x}/items/methods/operation/new`,
newMethodOperationParameter: `${x}/items/methods/operation/parameter/new`,
newMethodOperationStep: `${x}/items/methods/operation/step/new`,
+ newMethodOperationStepSlide: `${x}/items/methods/operation/step/slide/new`,
newMethodOperationTool: `${x}/items/methods/operation/tool/new`,
newNoQuoteReason: `${x}/sales/no-quote-reasons/new`,
newNote: `${x}/shared/notes/new`,
@@ -1889,7 +1918,7 @@ export const path = {
salesRfqs: `${x}/sales/rfqs`,
salesSettings: `${x}/settings/sales`,
saveInspectionDocument: (id: string) =>
- generatePath(`${x}/inspection/${id}/save`),
+ generatePath(`${x}/inspection-document/${id}/save`),
saveViewOrder: `${x}/shared/view/order`,
@@ -2074,7 +2103,7 @@ export const path = {
generatePath(`${x}/assembly/${id}/units/${unitId}`),
updateChangeOrder: `${x}/items/change-order/update`,
updateInspectionDocumentName: (id: string) =>
- generatePath(`${x}/inspection/${id}/update-name`),
+ generatePath(`${x}/inspection-document/${id}/update-name`),
updateIssueItem: `${x}/issue/item/update`,
userAttribute: (id: string) => generatePath(`${x}/account/${id}/attribute`),
users: `${x}/users`,
diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.ts
index 7748ed6c71..4fed5100d0 100644
--- a/apps/erp/app/utils/react-query.ts
+++ b/apps/erp/app/utils/react-query.ts
@@ -37,6 +37,14 @@ export const accountsQuery = (companyId: string | null) => ({
staleTime: RefreshRate.Low
});
+export const assemblyInstructionsQuery = (
+ itemId: string,
+ companyId: string | null
+) => ({
+ queryKey: ["assemblyInstructions", itemId, companyId ?? "null"],
+ staleTime: RefreshRate.Low
+});
+
export const countriesQuery = () => ({
queryKey: ["countries"],
staleTime: RefreshRate.Never
@@ -72,6 +80,34 @@ export const docsQuery = () => ({
staleTime: RefreshRate.Never
});
+export const inspectionDocumentsQuery = (
+ itemId: string,
+ companyId: string | null
+) => ({
+ queryKey: ["inspectionDocuments", itemId, companyId ?? "null"],
+ staleTime: RefreshRate.Low
+});
+
+// Clears every cached inspection-document list for the current company. Mutation
+// routes are keyed by document `id`, not `itemId`, so they can't rebuild the
+// exact per-item key — a predicate on the key prefix covers all item entries.
+// `removeQueries` (not `invalidateQueries`) is required: the read route's
+// clientLoader gates on `if (!data)`, and the combobox reads via an imperative
+// `useFetcher().load()` with no active observer, so a merely stale-marked entry
+// would keep returning the cached array and never refetch.
+export const invalidateInspectionDocuments = () => {
+ const companyId = getCompanyId();
+ getClientCache()?.removeQueries({
+ predicate: (query) => {
+ const queryKey = query.queryKey as string[];
+ return (
+ queryKey[0] === "inspectionDocuments" &&
+ (!companyId || queryKey[2] === companyId)
+ );
+ }
+ });
+};
+
export const itemPostingGroupsQuery = (companyId: string | null) => ({
queryKey: ["itemPostingGroups", companyId ?? "null"],
staleTime: RefreshRate.Low
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
new file mode 100644
index 0000000000..4948512d81
--- /dev/null
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -0,0 +1,3147 @@
+import type { Json } from "@carbon/database";
+import { PrintButton } from "@carbon/printing/ui";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Badge,
+ BarProgress,
+ BottomSheet,
+ BottomSheetBody,
+ BottomSheetContent,
+ Button,
+ ClientOnly,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ generateHTML,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ Separator,
+ SidebarTrigger,
+ Spinner,
+ Status,
+ TruncatedTooltipText,
+ useDisclosure,
+ useKeyboardWedge,
+ useMode,
+ useRealtimeChannel,
+ useRouteData
+} from "@carbon/react";
+import { formatDurationMilliseconds } from "@carbon/utils";
+import type {
+ AssemblyStep,
+ CameraPose,
+ Fastener,
+ Motion
+} from "@carbon/viewer";
+import { AssemblyPlayer } from "@carbon/viewer";
+import { ModelPreview } from "@carbon/viewer/model-preview";
+import { getLocalTimeZone } from "@internationalized/date";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ LuBox,
+ LuCheck,
+ LuChevronLeft,
+ LuChevronRight,
+ LuCircle,
+ LuCircleCheck,
+ LuCircleDot,
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuExpand,
+ LuEye,
+ LuEyeOff,
+ LuFlag,
+ LuGitPullRequest,
+ LuHammer,
+ LuHardHat,
+ LuImage,
+ LuListChecks,
+ LuListFilter,
+ LuPause,
+ LuPlay,
+ LuSkipForward,
+ LuTimer,
+ LuTrash,
+ LuUndo2,
+ LuWrench,
+ LuX
+} from "react-icons/lu";
+import {
+ useFetcher,
+ useNavigate,
+ useRevalidator,
+ useSearchParams
+} from "react-router";
+import { TrackingTypeIcon } from "~/components/Icons";
+import { ImageZoomViewer } from "~/components/ImageZoomViewer";
+import { OperationChat } from "~/components/JobOperation/components/Chat";
+import { IssueMaterialModal } from "~/components/JobOperation/components/IssueMaterialModal";
+import { MaintenanceDispatch } from "~/components/JobOperation/components/MaintenanceDispatch";
+import { QualityIssueModal } from "~/components/JobOperation/components/QualityIssueModal";
+import { QuantityModal } from "~/components/JobOperation/components/QuantityModal";
+import { ReworkModal } from "~/components/JobOperation/components/ReworkModal";
+import { SerialSelectorModal } from "~/components/JobOperation/components/SerialSelectorModal";
+import { RecordModal } from "~/components/JobOperation/components/Step";
+import { useUser } from "~/hooks";
+import type {
+ JobMaterial,
+ JobOperationStep,
+ OperationWithDetails,
+ ProductionEvent as ProductionEventType
+} from "~/services/types";
+import { getPrivateUrl, path } from "~/utils/path";
+import { deriveUnits } from "~/utils/units";
+
+type StepRecord = {
+ id: string;
+ index: number;
+ value?: string | null;
+ numericValue?: number | null;
+ booleanValue?: boolean | null;
+ userValue?: string | null;
+ createdBy?: string | null;
+};
+
+type SlideAnnotation = {
+ id: string;
+ x: number;
+ y: number;
+ label?: string | null;
+ color?: string | null;
+ // Smart hotspot: item id of the tool this pin points at (matches a tool's item.id).
+ toolId?: string | null;
+};
+
+type Slide = {
+ id: string;
+ // A slide is image XOR model: exactly one of imagePath / modelUploadId is set.
+ imagePath: string | null;
+ modelUploadId?: string | null;
+ caption?: string | null;
+ sortOrder?: number | null;
+ annotations?: SlideAnnotation[] | null;
+};
+
+// The assembler serves an optimised GLB per model (no client-side tessellation).
+// Derive its private preview URL from the raw modelPath
+// `${co}/models/${id}.ext[.zst]` → `${co}/models/${id}/optimized.glb`. Mirrors
+// the helper in JobOperation.tsx — the raw upload alone no longer renders (the
+// pipeline compacts it to `.zst` and the WASM tier is build-flag gated off).
+function optimizedModelPreviewUrl(rawModelPath: string | null): string | null {
+ if (!rawModelPath) return null;
+ const slash = rawModelPath.lastIndexOf("/");
+ if (slash < 0) return null;
+ const dir = rawModelPath.slice(0, slash);
+ let base = rawModelPath.slice(slash + 1);
+ if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
+ const id = base.replace(/\.[^.]+$/, "");
+ if (!id) return null;
+ return `/file/preview/private/${dir}/${id}/optimized.glb`;
+}
+
+// Render metadata for a 3D model slide (resolved by the loader from modelUpload).
+// glbPath is the assembler-converted artifact (fast to load); modelPath is the raw
+// upload the viewer parses client-side when no conversion exists (yet).
+type SlideModel = {
+ id: string;
+ name: string | null;
+ modelPath: string | null;
+ thumbnailPath: string | null;
+ glbPath: string | null;
+ processingStatus?: string | null;
+};
+
+type Step = {
+ id: string;
+ name?: string | null;
+ description?: unknown;
+ type?: string | null;
+ sortOrder?: number | null;
+ unitOfMeasureCode?: string | null;
+ minValue?: number | null;
+ maxValue?: number | null;
+ listValues?: string[] | null;
+ // Assembly → BOP sync provenance: the assemblyInstructionStep this step was
+ // synced from. Maps the operator's current step to the animated 3D playback.
+ assemblyInstructionStepId?: string | null;
+ jobOperationStepRecord?: StepRecord[];
+ jobOperationStepSlide?: Slide[];
+};
+
+// The linked instruction's animated steps + converted artifacts (loader-resolved
+// when the operation carries an assemblyInstructionId and the model is converted).
+type AssemblyPlayback = {
+ glbPath: string;
+ graphPath: string;
+ steps: {
+ id: string;
+ title: string | null;
+ instructionText: string | null;
+ componentNodeIds: string[] | null;
+ motion: Json;
+ camera: Json | null;
+ fastener: Json | null;
+ durationSeconds: number | null;
+ warnings: Json | null;
+ }[];
+};
+
+const playerMotionTypes = ["linear", "L", "helix", "path", "none"];
+
+// DB row → @carbon/viewer AssemblyStep.
+function toViewerStep(step: AssemblyPlayback["steps"][number]): AssemblyStep {
+ const motion = step.motion as Motion | null;
+ const warnings = step.warnings as { flagged?: boolean } | null;
+ return {
+ id: step.id,
+ title: step.title,
+ instructionText: step.instructionText,
+ componentNodeIds: step.componentNodeIds ?? [],
+ motion:
+ motion &&
+ typeof motion === "object" &&
+ playerMotionTypes.includes(motion.type)
+ ? motion
+ : { type: "none" },
+ camera: (step.camera as CameraPose | null) ?? null,
+ fastener: (step.fastener as Fastener | null) ?? null,
+ durationSeconds: step.durationSeconds,
+ flagged: warnings?.flagged === true ? true : undefined
+ };
+}
+
+type ProductionEvent = {
+ id: string;
+ type?: string | null;
+ startTime: string;
+ endTime?: string | null;
+ duration?: number | null;
+ employeeId?: string | null;
+};
+
+type ContainmentAction = {
+ id: string;
+ actionTypeName: string;
+ nonConformanceId: string;
+ notes: unknown;
+};
+
+type Operation = {
+ id: string;
+ description?: string | null;
+ workCenterId?: string | null;
+ operationQuantity?: number | null;
+ quantityComplete?: number | null;
+ laborDuration?: number | null;
+ setupDuration?: number | null;
+ machineDuration?: number | null;
+ itemDescription?: string | null;
+ itemReadableId?: string | null;
+ jobReadableId?: string | null;
+ operationStatus?: string | null;
+ jobStatus?: string | null;
+ duration?: number | null;
+ jobDeadlineType?: string | null;
+};
+
+type Props = {
+ operationId: string;
+ job: { itemReadableIdWithRevision?: string | null } | null;
+ operation: Operation | null;
+ thumbnailPath: string | null | undefined;
+ trackedEntities: {
+ id: string;
+ readableId?: string | null;
+ status?: string | null;
+ }[];
+ trackedEntityId: string | null;
+ materials: { materials?: any[]; trackedInputs?: any[] } | null;
+ procedure: { attributes: Step[]; parameters: any[] };
+ tools: {
+ quantity: number;
+ jobOperationStepIds?: string[];
+ item: {
+ id: string;
+ name: string;
+ type: string;
+ readableId?: string | null;
+ } | null;
+ }[];
+ ncrs: any[];
+ requiresSerialTracking: boolean;
+ requiresBatchTracking: boolean;
+ openEvent: { id: string; startTime: string } | null;
+ events: ProductionEvent[];
+ nonConformanceActions: ContainmentAction[];
+ expiredEntityPolicy?: "Warn" | "Block" | "BlockWithOverride";
+ autoStartOperationTimer?: boolean;
+ productionQuantities?: { scrap: number; production: number; rework: number };
+ workCenter?: {
+ id: string;
+ name: string;
+ isBlocked: boolean | null;
+ blockingDispatchId: string | null;
+ blockingDispatchReadableId: string | null;
+ } | null;
+ kanban?: { id?: string; completedBarcodeOverride?: string | null } | null;
+ jobId?: string | null;
+ canOverrideComplete?: boolean;
+ modelPath?: string | null;
+ slideModels?: Record<string, SlideModel> | null;
+ assemblyPlayback?: AssemblyPlayback | null;
+};
+
+// Real Carbon item types, in display order. Fasteners is NOT a Carbon concept.
+const TYPE_ORDER = [
+ "Part",
+ "Material",
+ "Consumable",
+ "Fixture",
+ "Tool",
+ "Service"
+];
+
+// Walk a TipTap/ProseMirror doc and collect text (incl. @mention labels).
+function richTextToPlainText(doc: unknown): string {
+ if (typeof doc === "string") return doc;
+ if (!doc || typeof doc !== "object") return "";
+ const parts: string[] = [];
+ const walk = (node: any) => {
+ if (!node || typeof node !== "object") return;
+ if (typeof node.text === "string") parts.push(node.text);
+ else if (node.type === "mention" && node.attrs?.label)
+ parts.push(node.attrs.label);
+ if (Array.isArray(node.content)) node.content.forEach(walk);
+ };
+ walk(doc);
+ return parts.join(" ").replace(/\s+/g, " ").trim();
+}
+
+// Strip any inline image nodes so the prose shows text only — reference imagery
+// now lives in first-class slides, not embedded in the description.
+function stripImages(doc: any): any {
+ if (!doc || typeof doc !== "object") return doc;
+ if (Array.isArray(doc.content)) {
+ return {
+ ...doc,
+ content: doc.content
+ .filter((n: any) => n?.type !== "image")
+ .map(stripImages)
+ };
+ }
+ return doc;
+}
+
+function formatElapsed(s: number) {
+ const h = Math.floor(s / 3600)
+ .toString()
+ .padStart(2, "0");
+ const m = Math.floor((s % 3600) / 60)
+ .toString()
+ .padStart(2, "0");
+ const sec = (s % 60).toString().padStart(2, "0");
+ return `${h}:${m}:${sec}`;
+}
+
+// Live elapsed seconds from an open production event's startTime (survives reload).
+function useElapsed(openEvent: { startTime: string } | null) {
+ const [, setTick] = useState(0);
+ useEffect(() => {
+ if (!openEvent) return;
+ const id = setInterval(() => setTick((t) => t + 1), 1000);
+ return () => clearInterval(id);
+ }, [openEvent]);
+ if (!openEvent) return 0;
+ const start = new Date(openEvent.startTime).getTime();
+ return Math.max(0, Math.floor((Date.now() - start) / 1000));
+}
+
+// Numbered pins overlaid on a reference image for the operator. Absolutely positioned by
+// fraction of the box, so the parent must be sized to the rendered image (an inline wrapper
+// around <img>). Tapping a pin that carries a note/tool reveals it in a bar along the bottom
+// of the image — hover `title` tooltips are dead on the shop floor's touch devices. Pins
+// without any detail stay non-interactive so taps fall through to open the fullscreen viewer.
+function SlidePins({
+ annotations,
+ toolNameById
+}: {
+ annotations: SlideAnnotation[];
+ toolNameById?: Map<string, string>;
+}) {
+ const [openPinId, setOpenPinId] = useState<string | null>(null);
+
+ if (annotations.length === 0) return null;
+
+ const openIndex = annotations.findIndex((p) => p.id === openPinId);
+ const openPin = openIndex >= 0 ? annotations[openIndex] : null;
+ const openToolName = openPin?.toolId
+ ? toolNameById?.get(openPin.toolId)
+ : undefined;
+
+ return (
+ <>
+ {annotations.map((pin, i) => {
+ const toolName = pin.toolId ? toolNameById?.get(pin.toolId) : undefined;
+ const hasDetail = Boolean(toolName || pin.label);
+ const isOpen = pin.id === openPinId;
+ return (
+ <button
+ key={pin.id}
+ type="button"
+ disabled={!hasDetail}
+ aria-label={
+ [`Annotation ${i + 1}`, toolName, pin.label]
+ .filter(Boolean)
+ .join(": ") || `Annotation ${i + 1}`
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpenPinId((cur) => (cur === pin.id ? null : pin.id));
+ }}
+ className={cn(
+ "absolute z-20 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border-2 border-white text-xs font-semibold text-white shadow-md transition-transform",
+ hasDetail
+ ? "cursor-pointer active:scale-[0.96]"
+ : "pointer-events-none",
+ isOpen && "ring-2 ring-white ring-offset-1 ring-offset-black/40"
+ )}
+ style={{
+ left: `${pin.x * 100}%`,
+ top: `${pin.y * 100}%`,
+ backgroundColor: pin.color ?? "#ef4444"
+ }}
+ >
+ {i + 1}
+ </button>
+ );
+ })}
+
+ {openPin && (openToolName || openPin.label) && (
+ <div className="absolute inset-x-0 bottom-0 z-20 flex items-start gap-2 bg-background/90 px-3 py-2 text-left shadow-sm backdrop-blur-sm">
+ <span
+ className="mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold text-white"
+ style={{ backgroundColor: openPin.color ?? "#ef4444" }}
+ >
+ {openIndex + 1}
+ </span>
+ <div className="min-w-0 flex-1">
+ {openToolName && (
+ <div className="truncate text-sm font-semibold text-foreground">
+ {openToolName}
+ </div>
+ )}
+ {openPin.label && (
+ <div className="text-xs text-muted-foreground">
+ {openPin.label}
+ </div>
+ )}
+ </div>
+ <button
+ type="button"
+ aria-label="Dismiss annotation"
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpenPinId(null);
+ }}
+ className="shrink-0 text-muted-foreground hover:text-foreground"
+ >
+ <LuX className="size-4" />
+ </button>
+ </div>
+ )}
+ </>
+ );
+}
+
+export function AssemblyView({
+ operationId,
+ job,
+ operation,
+ thumbnailPath,
+ trackedEntities,
+ trackedEntityId,
+ materials,
+ procedure,
+ tools,
+ ncrs,
+ requiresSerialTracking,
+ requiresBatchTracking,
+ openEvent,
+ events,
+ nonConformanceActions,
+ expiredEntityPolicy = "Block",
+ autoStartOperationTimer = false,
+ workCenter,
+ kanban,
+ jobId,
+ canOverrideComplete = false,
+ modelPath,
+ slideModels,
+ assemblyPlayback,
+ productionQuantities = { scrap: 0, production: 0, rework: 0 }
+}: Props) {
+ const user = useUser();
+ const mode = useMode();
+ const navigate = useNavigate();
+ const revalidator = useRevalidator();
+ const [searchParams, setSearchParams] = useSearchParams();
+ // Which main panel is shown: the assembly details, the 3D model, or chat.
+ const [tab, setTab] = useState<"details" | "model" | "chat">("details");
+
+ const issueModal = useDisclosure();
+ const qualityModal = useDisclosure();
+ const completeModal = useDisclosure();
+ const scrapModal = useDisclosure();
+ const reworkModal = useDisclosure();
+ const finishModal = useDisclosure();
+ const maintenanceModal = useDisclosure();
+ const serialModal = useDisclosure();
+ const actionsSheet = useDisclosure();
+ const completeAllModal = useDisclosure();
+ const completeAllFetcher = useFetcher<{ success?: boolean }>();
+ // Silent auto-completion of a single unit once its final step is recorded
+ // (multi-quantity assembly builds one at a time — see the effect below).
+ const completeUnitFetcher = useFetcher<{ id?: string }>();
+ const imageViewer = useDisclosure();
+ // Which reference image fills the main panel: a step photo (index) or the
+ // finished-product image ("finished").
+ const [selected, setSelected] = useState<number | "finished" | "playback">(
+ "finished"
+ );
+ // Operator toggle for the reference-image annotation pins (always-on vs tap-to-hide).
+ const [showPins, setShowPins] = useState(true);
+ // Steps-bar filter: which steps the segmented bar shows for the current unit.
+ const [stepFilter, setStepFilter] = useState<
+ "all" | "completed" | "incomplete"
+ >("all");
+ // For non-tracked material inline issue
+ const [selectedMaterial, setSelectedMaterial] = useState<any | null>(null);
+
+ // Live sync — refresh loader data when this operation's events, step records,
+ // job, or tracked entities change (incl. edits from the operation view).
+ useRealtimeChannel({
+ topic: `assembly:${operationId}`,
+ dependencies: [operationId],
+ setup(channel) {
+ const refresh = () => revalidator.revalidate();
+ return channel
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `jobOperationId=eq.${operationId}`
+ },
+ refresh
+ )
+ .on(
+ "postgres_changes",
+ { event: "*", schema: "public", table: "jobOperationStepRecord" },
+ refresh
+ )
+ .on(
+ "postgres_changes",
+ { event: "*", schema: "public", table: "trackedActivity" },
+ refresh
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "jobOperation",
+ filter: `id=eq.${operationId}`
+ },
+ refresh
+ );
+ }
+ });
+
+ // Kanban barcode scan → complete the operation (matches the operation view).
+ const completeFetcher = useFetcher();
+ useKeyboardWedge({
+ test: (input) =>
+ kanban?.completedBarcodeOverride
+ ? input === kanban.completedBarcodeOverride
+ : kanban?.id
+ ? input === path.to.kanbanComplete(kanban.id)
+ : false,
+ callback: () => completeFetcher.load(path.to.endOperation(operationId)),
+ active: !!kanban?.id
+ });
+
+ // Which work types this operation actually uses (only show/select these).
+ const workTypes = (
+ [
+ (operation?.setupDuration ?? 0) > 0 ? "Setup" : null,
+ (operation?.laborDuration ?? 0) > 0 ? "Labor" : null,
+ (operation?.machineDuration ?? 0) > 0 ? "Machine" : null
+ ] as const
+ ).filter(Boolean) as ("Setup" | "Labor" | "Machine")[];
+ // Each available work type gets its own header clock button. If the operation
+ // has no configured durations, still surface a single Labor clock so time can
+ // always be recorded.
+ const headerWorkTypes: ("Setup" | "Labor" | "Machine")[] =
+ workTypes.length > 0 ? workTypes : ["Labor"];
+ // Open (running) event for a work type, derived from events. A freshly-started
+ // Labor event may not be in `events` yet (the realtime channel keeps the
+ // `openEvent` prop fresher), so fall back to it for Labor.
+ const openEventForWorkType = (type: "Setup" | "Labor" | "Machine") =>
+ events.find((e) => e.type === type && !e.endTime) ??
+ (type === "Labor" ? openEvent : null);
+
+ const isTracked = requiresSerialTracking || requiresBatchTracking;
+ // Only serial parents rotate a distinct tracked entity per unit, so only they
+ // navigate the unit axis by ?trackedEntityId. A batch parent shares ONE lot across
+ // every unit — like an untracked parent it pages by ?unit index and rolls forward
+ // on quantityComplete; the lot still binds to every unit (materials + completion).
+ const navigatesByEntity = requiresSerialTracking;
+
+ // Source location for material issuing — same source the Operation view uses. FIX-7:
+ // the issue modal needs it (and the work center) to resolve a stock source, which most
+ // affects Inventory/Non-Inventory components.
+ const layoutData = useRouteData<{ location: string }>(
+ path.to.authenticatedRoot
+ );
+ const locationId = layoutData?.location;
+
+ // Real build steps only. NCR actions are surfaced through the dedicated "Open NCRs"
+ // sidebar + Flag-issue affordance, never injected as synthetic build steps (story 20).
+ const steps = (procedure.attributes ?? [])
+ .filter(
+ (s) =>
+ !(
+ s.type === "Inspection" &&
+ (s as { nonConformanceActionId?: string | null })
+ .nonConformanceActionId != null
+ )
+ )
+ .toSorted((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
+ const parameters = procedure.parameters ?? [];
+
+ // Current step, computed early so materials/tools can be filtered to it. Mirrors the
+ // clamp reused below for slides and step records.
+ const currentStep = Math.max(
+ 0,
+ Math.min(
+ Number.parseInt(searchParams.get("step") ?? "0", 10) || 0,
+ Math.max(0, steps.length - 1)
+ )
+ );
+ const step = steps[currentStep] ?? null;
+
+ // Part ↔ step (many-to-many): a part is shown ONLY on the step(s) it's assigned to. Parts
+ // with NO step link are unassigned ("General") and show on the FIRST step only — loose
+ // untracked parts are backflushed when the unit's first step is recorded, so that's
+ // where the operator sees and handles them; repeating them on every step just buries
+ // the step-specific parts. Quantity and issuing live on the jobMaterial (the part), so
+ // a part on several assigned steps never multiplies the requirement.
+ const stepNumberById = new Map(steps.map((s, i) => [s.id, i + 1] as const));
+ const allMaterials: any[] = materials?.materials ?? [];
+ const isGeneralMaterial = (m: any) =>
+ (m.jobOperationStepIds ?? []).length === 0;
+ const isOnCurrentStep = (m: any) =>
+ step?.id != null && (m.jobOperationStepIds ?? []).includes(step.id);
+ // Visible here = parts assigned to the current step, plus (first step only) the
+ // unassigned General parts. Parts assigned only to other steps are hidden. Assigned
+ // parts sort first, General after.
+ const visibleMaterials: any[] = allMaterials
+ .filter(
+ (m) => isOnCurrentStep(m) || (currentStep === 0 && isGeneralMaterial(m))
+ )
+ .sort((a, b) => {
+ const r = (isOnCurrentStep(a) ? 0 : 1) - (isOnCurrentStep(b) ? 0 : 1);
+ if (r !== 0) return r;
+ const at = TYPE_ORDER.indexOf(a.itemType ?? "");
+ const bt = TYPE_ORDER.indexOf(b.itemType ?? "");
+ return (at < 0 ? 99 : at) - (bt < 0 ? 99 : bt);
+ });
+
+ // Phase 2 (tool ↔ step, many-to-many): show only the tools involved in the current step —
+ // a tool scoped to steps (jobOperationStepIds) appears on those steps; operation-level tools
+ // (no links) appear on every step. Backward compatible: with no assignments, every tool is
+ // operation-level and shows everywhere. Mirrors the per-step material filter above.
+ const stepTools = tools.filter((t) => {
+ const ids: string[] = t.jobOperationStepIds ?? [];
+ // No links = operation-level (every step); otherwise only the linked steps.
+ return ids.length === 0 || (step?.id != null && ids.includes(step.id));
+ });
+
+ // FIX-1: quantity-centric unit axis — pages "Unit X of N" for EVERY tracking type.
+ // operationQuantity is the unit count; unit i carries trackedEntities[i] ?? null, so
+ // Serial binds a serial per unit, Batch binds the lot to unit 0, and Inventory binds
+ // none — all still page 1..N with per-unit step records. A job can pre-generate more
+ // serials than the quantity, so the count caps the entity list.
+ // See apps/mes/app/utils/units.ts + .ai/specs/2026-07-14-mes-execution-views.md
+ // §2 ("unit axis").
+ const unitCount = Math.max(
+ 1,
+ Math.round(operation?.operationQuantity ?? trackedEntities.length)
+ );
+ // Only serial/batch parents bind entities to the unit axis; inventory/non-inventory
+ // page purely by index, so stray inventory entities must not surface as units or "S/N".
+ const axisEntities = isTracked ? trackedEntities : [];
+ const units = deriveUnits(unitCount, axisEntities);
+ // The tracked entities within the navigable set (for the serial picker; empty when
+ // the parent is untracked).
+ const unitEntities = axisEntities.slice(0, unitCount);
+
+ // Units already built. Drives the quantity progress indicator and, for untracked
+ // parents, the default landing unit (the next one still to build).
+ const quantityComplete = Math.max(
+ 0,
+ Math.round(operation?.quantityComplete ?? 0)
+ );
+
+ // Resolve the current unit: by tracked entity from the URL when present, else by the
+ // ?unit index — untracked parents have no entity to key off. (FIX-3 / FIX-4)
+ const unitParam = Number.parseInt(searchParams.get("unit") ?? "", 10);
+ const hasUnitParam =
+ Number.isInteger(unitParam) && unitParam >= 0 && unitParam < units.length;
+ const currentUnitIndex = (() => {
+ if (navigatesByEntity && trackedEntityId) {
+ const i = units.findIndex((u) => u.entity?.id === trackedEntityId);
+ if (i >= 0) return i;
+ }
+ if (hasUnitParam) return unitParam;
+ // No explicit unit: land on the next unit still to build (quantityComplete)
+ // rather than an already-finished unit 0 — for EVERY tracking type. A serial
+ // parent normally resolves by entity above (the loader seeds trackedEntityId
+ // to this same unit); this is the fallback when no entity is resolvable.
+ return Math.min(quantityComplete, Math.max(0, units.length - 1));
+ })();
+ const currentUnit = units[currentUnitIndex] ?? units[0];
+ // Serial binds the per-unit entity; batch shares one lot across all units, so the
+ // sole tracked entity binds to every unit (unit i > 0 has no entity of its own).
+ const currentEntity = requiresBatchTracking
+ ? (axisEntities[0] ?? undefined)
+ : (currentUnit?.entity ?? undefined);
+
+ // Step records key off the unit index for ALL tracking types, identical to the
+ // Operation view (FIX-1 / FIX-5) — this is what isolates unit i's records.
+ const activeIndex = currentUnitIndex;
+
+ const isStepDone = (step: Step) =>
+ (step.jobOperationStepRecord ?? []).some((r) => r.index === activeIndex);
+ // A recorded step whose value FAILS its acceptance criteria for a given unit:
+ // a Measurement out of [min, max], or a pass/fail step (Inspection) recorded as
+ // not passing. Mirrors the out-of-spec red styling in the operation view's Step
+ // component. Drives the red bar/badge and the red unit indicators below.
+ const isStepBadResultAtIndex = (step: Step, index: number) => {
+ const record = (step.jobOperationStepRecord ?? []).find(
+ (r) => r.index === index
+ );
+ if (!record) return false;
+ if (step.type === "Measurement") {
+ const value = record.numericValue;
+ if (value == null) return false;
+ return (
+ (step.minValue != null && value < step.minValue) ||
+ (step.maxValue != null && value > step.maxValue)
+ );
+ }
+ if (step.type === "Inspection") return record.booleanValue === false;
+ return false;
+ };
+ const isStepBadResult = (step: Step) =>
+ isStepBadResultAtIndex(step, activeIndex);
+ // Does any step have an out-of-spec record for this unit? Flags the unit red in
+ // the sidebar navigator so a bad build is visible without opening each unit.
+ const unitHasBadResult = (index: number) =>
+ steps.some((s) => isStepBadResultAtIndex(s, index));
+ // Every step recorded for this unit — flags a fully-built unit green in the
+ // navigator (mirrors `allStepsRecorded`, but for an arbitrary unit index).
+ const unitIsRecorded = (index: number) =>
+ steps.length > 0 &&
+ steps.every((s) =>
+ (s.jobOperationStepRecord ?? []).some((r) => r.index === index)
+ );
+ const doneCount = steps.filter(isStepDone).length;
+ // All steps recorded for the current unit — drives the "Steps are missing"
+ // warning in the complete/finish flow (soft warning, mirrors operation view).
+ const allStepsRecorded = steps.length > 0 && doneCount === steps.length;
+
+ // Per-material issue state for the current step + unit, computed once so the
+ // Parts cards and the completion gate agree. `issuedIsPerUnit`/`issuedOverride`
+ // mirror the props the rows receive (serial parents report per-unit consumption
+ // for tracked parts; untracked parts are backflushed on the server when the
+ // step that owns them is recorded).
+ const firstStep = steps[0];
+ const visibleMaterialsWithState = visibleMaterials.map((m) => {
+ const stepNumbers = ((m.jobOperationStepIds ?? []) as string[])
+ .map((id) => stepNumberById.get(id))
+ .filter((n): n is number => n != null)
+ .sort((a, b) => a - b);
+ const isTrackedMat = m.requiresSerialTracking || m.requiresBatchTracking;
+ const isLoose = !isTrackedMat && stepNumbers.length === 0;
+ // The loader returns a per-unit quantityIssued for tracked materials under BOTH
+ // serial parents (attributed by the unit's own entity) and batch parents
+ // (attributed by the "Unit" stamp), so render it raw — no per-unit heuristic.
+ const issuedIsPerUnit =
+ (requiresSerialTracking || requiresBatchTracking) && isTrackedMat;
+ // Untracked parts are auto-issued server-side when their owning step is
+ // recorded for a unit — loose parts on the operation's FIRST step, and
+ // step-assigned parts on any of their assigned step(s). Mirror that so the
+ // row flips to issued the instant the owning step is done. Extra parts
+ // (perUnit 0, issued ad-hoc from the floor) are excluded so their raw
+ // quantityIssued drives the X/0 display instead.
+ const perUnit = m.quantity ?? 0;
+ const ownedStepDoneForUnit = isLoose
+ ? !!firstStep && isStepDone(firstStep)
+ : steps.some(
+ (s) => (m.jobOperationStepIds ?? []).includes(s.id) && isStepDone(s)
+ );
+ const issuedOverride =
+ !isTrackedMat && perUnit > 0
+ ? ownedStepDoneForUnit
+ ? perUnit
+ : 0
+ : undefined;
+ const state = getIssuedForUnit(m, {
+ unitIndex: currentUnitIndex,
+ issuedIsPerUnit,
+ issuedOverride
+ });
+ return {
+ m,
+ stepNumbers,
+ isTrackedMat,
+ issuedIsPerUnit,
+ issuedOverride,
+ state
+ };
+ });
+
+ // Tracked parts assigned to the current step that still need scanning for THIS
+ // unit. They soft-gate the step: the operator can still Skip, but the primary
+ // Mark done / Record action is disabled until they're issued. Non-tracked/loose
+ // parts never gate — they're backflushed when the step is recorded. Unplanned
+ // extras (required 0) never gate either — there's no requirement to satisfy.
+ const pendingScanMaterials = visibleMaterialsWithState.filter(
+ (v) => v.isTrackedMat && v.state.required > 0 && !v.state.fullyIssued
+ );
+ const hasPendingScans = pendingScanMaterials.length > 0;
+
+ // Open production events per work type (to pass to the complete flow so it
+ // can close them on completion).
+ const openByType = (type: string) =>
+ (events.find((e) => e.type === type && !e.endTime) ?? undefined) as
+ | ProductionEventType
+ | undefined;
+
+ const stepHasDescription = richTextToPlainText(step?.description).length > 0;
+ const stepDescriptionHtml =
+ step && stepHasDescription
+ ? generateHTML(
+ stripImages(step.description) as Parameters<typeof generateHTML>[0]
+ )
+ : "";
+ const isLastStep = steps.length === 0 || currentStep >= steps.length - 1;
+
+ // Reference slides for this step (first-class media, ordered) + "Completed item"
+ // = the finished product (the assembly item's thumbnail). See
+ // .ai/specs/2026-07-14-mes-execution-views.md §4.
+ const stepSlides = (step?.jobOperationStepSlide ?? [])
+ .slice()
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
+ // Per-slide media: an image slide renders as a picture (with pins); a 3D model
+ // slide renders in ModelPreview — preferring the assembler-converted GLB (glbPath,
+ // else the optimised GLB derived from the raw path) and keeping the raw upload
+ // only as a last-resort fallback.
+ const slideMedia = stepSlides.map((slide) => {
+ if (slide.modelUploadId) {
+ const model = slideModels?.[slide.modelUploadId] ?? null;
+ // ModelPreview loads the assembler-converted GLB fast tier when present and
+ // falls back to parsing the raw upload client-side (WASM tier).
+ const glbUrl = model?.glbPath
+ ? getPrivateUrl(model.glbPath)
+ : optimizedModelPreviewUrl(model?.modelPath ?? null);
+ const rawUrl = model?.modelPath ? getPrivateUrl(model.modelPath) : null;
+ return {
+ kind: "model" as const,
+ url: glbUrl ?? rawUrl,
+ glbUrl,
+ rawUrl,
+ thumbnail: model?.thumbnailPath
+ ? getPrivateUrl(model.thumbnailPath)
+ : null
+ };
+ }
+ return {
+ kind: "image" as const,
+ url: slide.imagePath ? getPrivateUrl(slide.imagePath) : null,
+ thumbnail: slide.imagePath ? getPrivateUrl(slide.imagePath) : null
+ };
+ });
+ const assemblyImage = thumbnailPath ? getPrivateUrl(thumbnailPath) : null;
+ const selectedMedia =
+ typeof selected === "number" ? (slideMedia[selected] ?? null) : null;
+ const selectedModelUrl =
+ selectedMedia?.kind === "model" ? selectedMedia.url : null;
+ const mainImage =
+ selected === "finished"
+ ? assemblyImage
+ : selectedMedia?.kind === "image"
+ ? (selectedMedia.url ?? assemblyImage)
+ : assemblyImage;
+
+ // Step-aware 3D playback: when this BOP step was synced from an assembly
+ // instruction (assemblyInstructionStepId marker) and the instruction's model
+ // has converted artifacts, drive the animated player to exactly this step —
+ // parts installed so far, the incoming part's motion, the planner's camera.
+ const viewerSteps = useMemo(
+ () => (assemblyPlayback?.steps ?? []).map(toViewerStep),
+ [assemblyPlayback]
+ );
+ const playbackIndex = useMemo(() => {
+ if (!assemblyPlayback || !step?.assemblyInstructionStepId) return null;
+ const index = assemblyPlayback.steps.findIndex(
+ (playbackStep) => playbackStep.id === step.assemblyInstructionStepId
+ );
+ return index >= 0 ? index : null;
+ }, [assemblyPlayback, step]);
+ const playbackAvailable = playbackIndex !== null && viewerSteps.length > 0;
+ const selectedCaption =
+ typeof selected === "number"
+ ? (stepSlides[selected]?.caption ?? null)
+ : null;
+ // Annotation pins for the shown slide (empty for the finished-item view).
+ const selectedAnnotations =
+ typeof selected === "number"
+ ? (stepSlides[selected]?.annotations ?? [])
+ : [];
+
+ // Smart hotspots: link a pin's toolId to the step's tools. `toolNameById` names a pin's
+ // tool on hover; `pinSeqByToolId` lets the Tools sidebar badge each tool with the pin
+ // sequence number(s) that point at it — i.e. the fastener/assembly order.
+ const toolNameById = new Map<string, string>();
+ for (const t of stepTools) {
+ if (t.item?.id) toolNameById.set(t.item.id, t.item.name);
+ }
+ const pinSeqByToolId = new Map<string, number[]>();
+ selectedAnnotations.forEach((pin, i) => {
+ if (!pin.toolId) return;
+ const seq = pinSeqByToolId.get(pin.toolId) ?? [];
+ seq.push(i + 1);
+ pinSeqByToolId.set(pin.toolId, seq);
+ });
+
+ // On step change, default the main panel to the animated step playback when this
+ // step maps to an instruction step; otherwise the step's first slide, and only
+ // fall back to the finished-assembly image when the step has neither.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the current step
+ useEffect(() => {
+ setSelected(
+ playbackAvailable ? "playback" : stepSlides.length > 0 ? 0 : "finished"
+ );
+ }, [currentStep, stepSlides.length, playbackAvailable]);
+
+ function goToStep(n: number) {
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.set("step", String(n));
+ return next;
+ },
+ { replace: true, preventScrollReset: true }
+ );
+ }
+
+ // ── Auto-advance + labor automation ──────────────────────────────────────
+ // Reduce keystrokes on the shop floor: the moment the step the operator is
+ // looking at flips to "done" (a record just landed — Mark done, Record, a
+ // measurement, a file upload — all revalidate `isStepDone`), advance to the
+ // next step and kick off the labor clock. Gated on the step index being
+ // unchanged so navigating BACK to an already-done step never bounces forward.
+ const laborFetcher = useFetcher();
+ const openLaborEvent = openByType("Labor");
+ const currentStepDone = step ? isStepDone(step) : false;
+ const stepDoneRef = useRef({ step: currentStep, done: currentStepDone });
+ // biome-ignore lint/correctness/useExhaustiveDependencies: transition-detect on the current step only
+ useEffect(() => {
+ const prev = stepDoneRef.current;
+ stepDoneRef.current = { step: currentStep, done: currentStepDone };
+ const justCompleted =
+ prev.step === currentStep && !prev.done && currentStepDone;
+ if (!justCompleted) return;
+
+ // Start the labor clock on the first completion when nothing is running yet.
+ // Skip it on the completion that finishes the whole operation — the stop
+ // effect below handles that and a zero-length event helps no one.
+ if (
+ operation &&
+ !openLaborEvent &&
+ !allStepsRecorded &&
+ laborFetcher.state === "idle"
+ ) {
+ const fd = new FormData();
+ fd.set("jobOperationId", operation.id);
+ fd.set("timezone", getLocalTimeZone());
+ fd.set("type", "Labor");
+ fd.set("action", "Start");
+ // Recording the first step means hands-on build has begun: end any open
+ // Setup clock and switch to Labor (auto-transition).
+ fd.set("exclusive", "true");
+ if (operation.workCenterId)
+ fd.set("workCenterId", operation.workCenterId);
+ const entityId = isTracked ? currentEntity?.id : undefined;
+ if (entityId) fd.set("trackedEntityId", entityId);
+ fd.set("unitIndex", String(currentUnitIndex));
+ laborFetcher.submit(fd, {
+ method: "post",
+ action: path.to.productionEvent
+ });
+ }
+
+ if (!isLastStep) goToStep(currentStep + 1);
+ }, [currentStep, currentStepDone, isLastStep, allStepsRecorded]);
+
+ // Stop the labor clock automatically once every step is recorded for this unit.
+ const allDoneRef = useRef(allStepsRecorded);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: transition-detect on all-complete
+ useEffect(() => {
+ const wasAllDone = allDoneRef.current;
+ allDoneRef.current = allStepsRecorded;
+ if (
+ !wasAllDone &&
+ allStepsRecorded &&
+ operation &&
+ openLaborEvent &&
+ laborFetcher.state === "idle"
+ ) {
+ const fd = new FormData();
+ fd.set("jobOperationId", operation.id);
+ fd.set("timezone", getLocalTimeZone());
+ fd.set("type", "Labor");
+ fd.set("action", "End");
+ fd.set("id", openLaborEvent.id);
+ laborFetcher.submit(fd, {
+ method: "post",
+ action: path.to.productionEvent
+ });
+ }
+ }, [allStepsRecorded]);
+
+ // ── Auto-complete one unit + roll to the next ────────────────────────────
+ // Assembly builds one unit at a time. For a multi-quantity operation, the
+ // moment every step is recorded for the current unit we silently log a single
+ // completed quantity (POST /x/complete, quantity 1) and return to step 1 of
+ // the next unit — until the whole quantity is built, where the final
+ // completion finishes the operation server-side (willBeFinished → redirect).
+ // Single-quantity operations keep the manual "Complete" flow untouched.
+ const isMultiQuantity = unitCount > 1;
+ const unitsRemaining = unitCount - quantityComplete;
+ const autoCompleteSubmittedRef = useRef(false);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: transition-detect on all-complete
+ useEffect(() => {
+ if (!isMultiQuantity || unitsRemaining <= 0) return;
+ // Only auto-complete the unit currently being built. Guards against
+ // re-completing an already-finished unit whose step records still read
+ // "done" if the operator navigates back to it.
+ if (currentUnitIndex < quantityComplete) return;
+ if (!allStepsRecorded) {
+ // On a not-yet-finished unit — arm for its eventual completion.
+ autoCompleteSubmittedRef.current = false;
+ return;
+ }
+ if (autoCompleteSubmittedRef.current) return;
+ if (!operation || completeUnitFetcher.state !== "idle") return;
+ autoCompleteSubmittedRef.current = true;
+
+ const fd = new FormData();
+ fd.set("jobOperationId", operation.id);
+ fd.set("quantity", "1");
+ if (requiresSerialTracking) fd.set("trackingType", "Serial");
+ else if (requiresBatchTracking) fd.set("trackingType", "Batch");
+ if (isTracked && currentEntity?.id)
+ fd.set("trackedEntityId", currentEntity.id);
+ // Link the open production events so the completion is attributed to them.
+ const setup = openByType("Setup");
+ const labor = openByType("Labor");
+ const machine = openByType("Machine");
+ if (setup?.id) fd.set("setupProductionEventId", setup.id);
+ if (labor?.id) fd.set("laborProductionEventId", labor.id);
+ if (machine?.id) fd.set("machineProductionEventId", machine.id);
+ completeUnitFetcher.submit(fd, {
+ method: "post",
+ action: path.to.complete
+ });
+
+ // Batch + untracked parents track the unit-being-built by quantityComplete (they
+ // page by index), so drop any explicit ?unit and let currentUnitIndex fall back to
+ // quantityComplete — which the completion rolls forward. Serial completions redirect
+ // to a fresh entity instead, so leave their params be.
+ if (!navigatesByEntity && hasUnitParam) {
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete("unit");
+ return next;
+ },
+ { replace: true, preventScrollReset: true }
+ );
+ }
+ }, [allStepsRecorded, isMultiQuantity, unitsRemaining]);
+
+ // Re-arm auto-complete when a completion POST fails. complete.tsx returns
+ // data({}, flash-error) on any failure (insufficient stock, serial-mint
+ // failure, …) — an empty object — while success returns the production row(s)
+ // or a redirect. Without this, autoCompleteSubmittedRef stays latched: every
+ // step reads green, the unit never advances, and the error flash is the only
+ // (transient) signal. Re-arming lets the operator retry (re-record a step, or
+ // the manual Complete flow) without wedging the unit. This does NOT loop: the
+ // auto-complete effect only re-fires when its deps actually change, and a
+ // failed completion leaves quantityComplete (hence unitsRemaining) unchanged.
+ const prevCompleteUnitStateRef = useRef(completeUnitFetcher.state);
+ useEffect(() => {
+ const settled =
+ prevCompleteUnitStateRef.current !== "idle" &&
+ completeUnitFetcher.state === "idle";
+ prevCompleteUnitStateRef.current = completeUnitFetcher.state;
+ if (!settled) return;
+ const result = completeUnitFetcher.data;
+ const failed =
+ !!result &&
+ !Array.isArray(result) &&
+ typeof result === "object" &&
+ Object.keys(result).length === 0;
+ if (failed) autoCompleteSubmittedRef.current = false;
+ }, [completeUnitFetcher.state, completeUnitFetcher.data]);
+
+ // Return to step 1 on a new unit. Whenever the active unit changes — the
+ // auto-complete rolls quantityComplete forward (untracked), a serial/batch
+ // completion redirects to a fresh entity, or the operator pages units by hand —
+ // jump to that unit's first step still to record (step 1 for a fresh unit). This
+ // is what returns the operator to the top after finishing a unit's last step.
+ const lastUnitRef = useRef(currentUnitIndex);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: transition-detect on the unit index
+ useEffect(() => {
+ if (lastUnitRef.current === currentUnitIndex) return;
+ lastUnitRef.current = currentUnitIndex;
+ const firstIncomplete = steps.findIndex((s) => !isStepDone(s));
+ goToStep(firstIncomplete >= 0 ? firstIncomplete : 0);
+ }, [currentUnitIndex]);
+
+ // On first open (no explicit ?step in the URL), land on the first step that
+ // isn't done for this unit rather than always step 1 — the operator resumes
+ // where they left off. Resolves once, as soon as steps are available; an
+ // explicit ?step (a shared/bookmarked link) is always respected.
+ const initialStepResolvedRef = useRef(false);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: one-shot once steps load
+ useEffect(() => {
+ if (initialStepResolvedRef.current) return;
+ if (searchParams.get("step") != null) {
+ initialStepResolvedRef.current = true;
+ return;
+ }
+ if (steps.length === 0) return; // wait for steps to load
+ initialStepResolvedRef.current = true;
+ const firstIncomplete = steps.findIndex((s) => !isStepDone(s));
+ if (firstIncomplete > 0) goToStep(firstIncomplete);
+ }, [steps.length]);
+
+ function navigateEntity(entity: { id: string }) {
+ const url = new URL(window.location.href);
+ url.searchParams.set("trackedEntityId", entity.id);
+ url.searchParams.delete("unit");
+ navigate(url.pathname + url.search);
+ }
+
+ // Serial parents mint one serial at a time — the next unit's tracked entity is only
+ // created when the current unit completes — so units beyond the created serials have
+ // no entity yet and can't be worked on (scanning tracked parts and completing the unit
+ // both require it). Cap navigation to the last unit that has a serial. Batch/untracked
+ // parents page purely by index, so every unit stays reachable.
+ const maxNavigableUnitIndex = navigatesByEntity
+ ? units.reduce((max, u) => (u.entity ? Math.max(max, u.index) : max), 0)
+ : unitCount - 1;
+
+ // Navigate to a unit by its axis position (the prev/next pager). Serial units key
+ // off their entity so the loader refetches that entity's materials; batch + untracked
+ // units key off ?unit (batch shares one lot, untracked has no entity to scan —
+ // FIX-3/FIX-4). The unit-change effect above then moves the step cursor to that unit's
+ // first incomplete step. The clamp to maxNavigableUnitIndex blocks paging onto a unit
+ // whose serial hasn't been minted yet.
+ function goToUnit(n: number) {
+ const clamped = Math.max(0, Math.min(n, maxNavigableUnitIndex));
+ if (clamped === currentUnitIndex) return;
+ const entity = units[clamped]?.entity;
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ if (navigatesByEntity && entity?.id) {
+ next.set("trackedEntityId", entity.id);
+ next.delete("unit");
+ } else {
+ next.set("unit", String(clamped));
+ next.delete("trackedEntityId");
+ }
+ return next;
+ },
+ { replace: true, preventScrollReset: true }
+ );
+ }
+
+ const companyLogo =
+ mode === "dark" ? user.company.logoDarkIcon : user.company.logoLightIcon;
+
+ return (
+ <div className="relative flex h-screen w-full flex-col overflow-hidden bg-background text-foreground">
+ {/* ── HEADER ── */}
+ <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border">
+ {/* Full-height segment matching the Flag issue / Complete / timer buttons. */}
+ <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />
+ {companyLogo ? (
+ <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">
+ <img
+ src={companyLogo}
+ alt={`${user.company.name} logo`}
+ className="h-7 w-auto max-w-[140px] object-contain"
+ />
+ </div>
+ ) : null}
+
+ <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">
+ <span className="truncate text-sm font-semibold">
+ {job?.itemReadableIdWithRevision ?? "—"}
+ </span>
+ {operation?.description ? (
+ <>
+ <span className="hidden text-muted-foreground md:inline">·</span>
+ <span className="hidden truncate text-sm text-foreground/90 lg:inline">
+ {operation.description}
+ </span>
+ </>
+ ) : null}
+ </div>
+
+ <div className="flex-1" />
+
+ {/* Full-height segmented actions — same treatment as the timer button:
+ flush, no rounded corners, a left-border divider, hover highlight. */}
+ <button
+ type="button"
+ onClick={qualityModal.onOpen}
+ className="hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex"
+ >
+ <LuFlag className="size-4" />
+ Flag issue
+ </button>
+ {operation ? (
+ <button
+ type="button"
+ onClick={completeModal.onOpen}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"
+ >
+ <LuCheck className="size-4" />
+ <span className="hidden sm:inline">Complete</span>
+ <span className="sm:hidden">Done</span>
+ </button>
+ ) : null}
+ {operation ? (
+ <button
+ type="button"
+ aria-label="More actions"
+ onClick={actionsSheet.onOpen}
+ className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:px-4"
+ >
+ <LuEllipsisVertical className="size-4" />
+ </button>
+ ) : null}
+
+ {operation
+ ? headerWorkTypes.map((wt) => (
+ <TimerControl
+ key={wt}
+ operation={operation}
+ openEvent={openEventForWorkType(wt)}
+ workType={wt}
+ trackedEntityId={isTracked ? currentEntity?.id : undefined}
+ unitIndex={currentUnitIndex}
+ />
+ ))
+ : null}
+ </header>
+
+ {/* ── STEPS BAR (segmented, click to jump; green = done) ── */}
+ {steps.length > 0 && (
+ <div className="flex h-9 shrink-0 items-center gap-3 bg-card border-b border-border px-5">
+ {/* Label reflects the active filter so a filtered bar (e.g. only the completed,
+ all-green steps) is never mistaken for "everything done". */}
+ <span className="whitespace-nowrap text-xs text-muted-foreground">
+ {stepFilter === "completed"
+ ? `${doneCount} completed`
+ : stepFilter === "incomplete"
+ ? `${steps.length - doneCount} incomplete`
+ : `${doneCount} / ${steps.length} done`}
+ </span>
+ <div className="flex flex-1 items-center gap-1">
+ {steps
+ .map((s, i) => [s, i] as const)
+ .filter(([s]) =>
+ stepFilter === "all"
+ ? true
+ : stepFilter === "completed"
+ ? isStepDone(s)
+ : !isStepDone(s)
+ )
+ .map(([s, i]) => (
+ <button
+ key={s.id}
+ type="button"
+ aria-label={`Go to step ${i + 1}`}
+ onClick={() => goToStep(i)}
+ className={cn(
+ "h-3 flex-1 rounded-[2px] transition-colors",
+ isStepDone(s)
+ ? isStepBadResult(s)
+ ? "bg-red-500"
+ : "bg-emerald-500"
+ : i === currentStep
+ ? "bg-foreground"
+ : "bg-border hover:bg-muted-foreground/40"
+ )}
+ />
+ ))}
+ {stepFilter === "incomplete" && doneCount === steps.length && (
+ <span className="text-xs text-emerald-500">All steps done</span>
+ )}
+ {stepFilter === "completed" && doneCount === 0 && (
+ <span className="text-xs text-muted-foreground">
+ No completed steps yet
+ </span>
+ )}
+ </div>
+ {/* Filter which steps the bar emphasizes (all / completed / incomplete). */}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Filter steps"
+ variant={stepFilter === "all" ? "ghost" : "active"}
+ size="sm"
+ icon={<LuListFilter />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup
+ value={stepFilter}
+ onValueChange={(v) =>
+ setStepFilter(v as "all" | "completed" | "incomplete")
+ }
+ >
+ <DropdownMenuRadioItem value="all">
+ Show all
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="completed">
+ Show completed
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="incomplete">
+ Show incomplete
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">
+ {currentStep + 1} / {steps.length}
+ </span>
+ {/* Unit pager — fallback for narrow screens (< lg) where the left sidebar
+ is hidden; on lg+ the richer sidebar UnitNavigator takes over. Assembly
+ builds one at a time, but the operator can page back to review or fix a
+ prior unit's step records — mirrors the operation view. */}
+ {isMultiQuantity && (
+ <div className="flex items-center gap-0.5 lg:hidden">
+ <IconButton
+ aria-label="Previous unit"
+ variant="ghost"
+ size="sm"
+ icon={<LuChevronLeft />}
+ isDisabled={currentUnitIndex <= 0}
+ onClick={() => goToUnit(currentUnitIndex - 1)}
+ />
+ <Badge
+ variant="secondary"
+ className="whitespace-nowrap tabular-nums"
+ >
+ Unit {Math.min(currentUnitIndex + 1, unitCount)} / {unitCount}
+ </Badge>
+ <IconButton
+ aria-label="Next unit"
+ variant="ghost"
+ size="sm"
+ icon={<LuChevronRight />}
+ isDisabled={currentUnitIndex >= maxNavigableUnitIndex}
+ onClick={() => goToUnit(currentUnitIndex + 1)}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* ── BODY ── stacks vertically (page scrolls) on phones/tablets,
+ three columns side-by-side on lg+. ── */}
+ <div className="flex flex-1 flex-col overflow-y-auto lg:flex-row lg:overflow-hidden">
+ {/* ── LEFT PANEL: part detail + timer + containment ── */}
+ <aside className="hidden w-[220px] shrink-0 flex-col overflow-hidden border-r border-border bg-card lg:flex xl:w-[280px]">
+ {/* Part info. For a multi-quantity build the tracked-entity identity moves
+ into the dedicated Units section below the timers. */}
+ <div className="shrink-0 border-b border-border px-3 py-2.5">
+ <p className="truncate text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
+ {job?.itemReadableIdWithRevision ?? "—"}
+ </p>
+ {operation?.itemDescription && (
+ <p className="mt-0.5 line-clamp-2 text-xs text-foreground/80">
+ {operation.itemDescription}
+ </p>
+ )}
+ {!isMultiQuantity && currentEntity ? (
+ <div className="mt-1.5 flex items-center gap-1.5">
+ <Badge variant="secondary" className="font-mono text-[10px]">
+ {requiresBatchTracking ? "Batch" : "S/N"}
+ </Badge>
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {currentEntity.readableId ?? currentEntity.id.slice(0, 8)}
+ </span>
+ </div>
+ ) : null}
+ </div>
+
+ {/* Cumulative timer — click a row to choose which clock the play
+ button tracks. Only work types this operation uses are shown. */}
+ <div className="flex shrink-0 flex-col gap-3 border-b border-border px-3 py-3">
+ <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ Progress
+ </p>
+ {/* The live tick lives inside TimeRows so the per-second re-render is
+ scoped to the timer display — it must NOT re-render the whole view,
+ which would disrupt an open RecordModal's in-progress number entry. */}
+ <TimeRows
+ events={events}
+ setupDuration={operation?.setupDuration ?? 0}
+ laborDuration={operation?.laborDuration ?? 0}
+ machineDuration={operation?.machineDuration ?? 0}
+ />
+ {/* Quantity progress — units completed / reworked / scrapped of the
+ operation quantity. Segments mirror the operation view: completed
+ (emerald), reworked (yellow), scrapped (red). Only shown when
+ building more than one (single-qty stays lean). */}
+ {isMultiQuantity && (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-muted-foreground">
+ Quantity
+ </span>
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {Math.min(quantityComplete, unitCount)}/{unitCount}
+ </span>
+ </div>
+ <BarProgress
+ max={unitCount || 1}
+ progress={quantityComplete}
+ segments={[
+ {
+ value: Math.min(quantityComplete, unitCount),
+ className: "bg-emerald-500"
+ },
+ {
+ value: productionQuantities.rework,
+ className: "bg-yellow-500"
+ },
+ {
+ value: productionQuantities.scrap,
+ className: "bg-red-500"
+ }
+ ]}
+ />
+ </div>
+ )}
+ {/* Steps done count */}
+ {steps.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-muted-foreground">Steps</span>
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {doneCount}/{steps.length}
+ </span>
+ </div>
+ <BarProgress max={steps.length || 1} progress={doneCount} />
+ </div>
+ )}
+ </div>
+
+ {/* Units — the full, scrollable list of every unit/serial being built,
+ with its own section header + compact pager. Sits under Time. */}
+ {isMultiQuantity && (
+ <UnitNavigator
+ units={units}
+ currentUnitIndex={currentUnitIndex}
+ maxNavigableIndex={maxNavigableUnitIndex}
+ isTracked={isTracked}
+ labelByEntity={requiresSerialTracking}
+ trackingLabel={requiresBatchTracking ? "Batch" : "S/N"}
+ // Print the current unit's serial/lot label. Only tracked units have
+ // an entity to print; untracked builds have nothing to label.
+ headerAction={
+ isTracked && currentEntity?.id ? (
+ <PrintButton
+ isIcon
+ variant="ghost"
+ size="lg"
+ sourceDocument="Entity"
+ sourceDocumentId={currentEntity.id}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={operation?.workCenterId ?? undefined}
+ fileRoutes={{
+ pdf: path.to.file.trackedEntityLabelPdf,
+ zpl: path.to.file.trackedEntityLabelZpl
+ }}
+ />
+ ) : null
+ }
+ unitHasBadResult={unitHasBadResult}
+ unitIsRecorded={unitIsRecorded}
+ onSelectUnit={goToUnit}
+ />
+ )}
+
+ {/* Containment actions (NCR-driven) — collapsible accordion at the
+ bottom of the left panel. Click a row to expand/collapse. */}
+ {(() => {
+ const containments = nonConformanceActions.filter(
+ (a) => a.notes && Object.keys(a.notes as object).length > 0
+ );
+ if (containments.length === 0) return null;
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-3">
+ <p className="mb-1 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ Containment
+ </p>
+ <Accordion type="multiple" className="flex flex-col">
+ {containments.map((action) => (
+ <AccordionItem
+ key={action.id}
+ value={action.id}
+ className="border-b-0"
+ >
+ <AccordionTrigger className="gap-2 py-2 text-left text-xs hover:no-underline">
+ <span className="flex min-w-0 flex-1 flex-col items-start gap-1">
+ <span className="truncate font-semibold leading-tight text-foreground">
+ {action.actionTypeName}
+ </span>
+ <Badge
+ variant="outline"
+ className="w-fit font-mono text-[9px]"
+ >
+ {action.nonConformanceId}
+ </Badge>
+ </span>
+ </AccordionTrigger>
+ <AccordionContent className="pb-2 pt-0">
+ <div
+ className="prose prose-sm max-w-none rounded-md border border-amber-500/30 bg-amber-500/5 p-2 text-[11px] leading-snug text-foreground/90 dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ action.notes as Parameters<typeof generateHTML>[0]
+ )
+ }}
+ />
+ </AccordionContent>
+ </AccordionItem>
+ ))}
+ </Accordion>
+ </div>
+ );
+ })()}
+
+ {/* Operation status — mirrors the operation view's header strip. */}
+ {operation && (
+ <div className="mt-auto flex shrink-0 flex-col gap-1.5 border-t border-border px-3 py-3">
+ <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ Status
+ </p>
+ {operation.jobReadableId && (
+ <StatusRow label="Job" value={operation.jobReadableId} mono />
+ )}
+ {operation.description && (
+ <StatusRow label="Operation" value={operation.description} />
+ )}
+ <StatusRow
+ label="Status"
+ value={
+ operation.jobStatus === "Paused"
+ ? "Paused"
+ : (operation.operationStatus ?? "—")
+ }
+ />
+ <StatusRow
+ label="Duration"
+ value={formatDurationMilliseconds(operation.duration ?? 0, {
+ style: "short"
+ })}
+ />
+ <StatusRow
+ label="Deadline"
+ value={operation.jobDeadlineType ?? "—"}
+ />
+ </div>
+ )}
+ </aside>
+
+ {/* ── MAIN: tabbed — details (image + step) · model · chat ── */}
+ <main className="flex w-full flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden">
+ {/* Tab bar */}
+ <div className="flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5">
+ <TabButton
+ active={tab === "details"}
+ onClick={() => setTab("details")}
+ >
+ Details
+ </TabButton>
+ {modelPath ? (
+ <TabButton
+ active={tab === "model"}
+ onClick={() => setTab("model")}
+ >
+ Model
+ </TabButton>
+ ) : null}
+ <TabButton active={tab === "chat"} onClick={() => setTab("chat")}>
+ Chat
+ </TabButton>
+ </div>
+
+ {tab === "model" && modelPath ? (
+ <div className="min-h-0 flex-1">
+ <ModelPreview
+ key={`model-${modelPath}`}
+ glbUrl={optimizedModelPreviewUrl(modelPath)}
+ rawUrl={`/file/preview/private/${modelPath}`}
+ mode={mode}
+ className="rounded-none"
+ />
+ </div>
+ ) : tab === "chat" && operation ? (
+ <div className="min-h-0 flex-1 overflow-hidden">
+ <OperationChat
+ operation={operation as unknown as OperationWithDetails}
+ />
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
+ <div className="flex shrink-0 flex-col gap-2 border-b border-border p-4">
+ {selected === "playback" &&
+ playbackAvailable &&
+ assemblyPlayback ? (
+ // Animated instruction playback pinned to the operator's current
+ // step. The player owns orbit/zoom; replay via the step's motion.
+ <div className="relative mx-auto h-[55vh] max-h-[65vh] w-full overflow-hidden rounded-lg border border-border bg-muted/40">
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-8 w-8" />
+ </div>
+ }
+ >
+ {() => (
+ <AssemblyPlayer
+ glbUrl={getPrivateUrl(assemblyPlayback.glbPath)}
+ graphUrl={getPrivateUrl(assemblyPlayback.graphPath)}
+ steps={viewerSteps}
+ activeStepIndex={playbackIndex ?? 0}
+ playStepNonce={currentStep}
+ autoPlay
+ loop
+ readOnly
+ // Shop floor: the step name/description is shown in the
+ // details panel below, so the in-player caption is redundant.
+ hideCaption
+ mode={mode}
+ className="h-full"
+ />
+ )}
+ </ClientOnly>
+ </div>
+ ) : selectedMedia?.kind === "model" ? (
+ // 3D model slide: the interactive viewer replaces the picture. The
+ // viewer has its own orbit/zoom controls, so no fullscreen overlay
+ // button and no annotation pins (pins are image-only).
+ <div className="relative mx-auto h-[55vh] max-h-[65vh] w-full overflow-hidden rounded-lg border border-border bg-muted/40">
+ {selectedModelUrl ? (
+ <ModelPreview
+ key={`slide-model-${selectedModelUrl}`}
+ glbUrl={
+ selectedMedia?.kind === "model"
+ ? selectedMedia.glbUrl
+ : null
+ }
+ rawUrl={
+ selectedMedia?.kind === "model"
+ ? selectedMedia.rawUrl
+ : null
+ }
+ mode={mode}
+ className="h-full w-full rounded-lg"
+ />
+ ) : (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 text-muted-foreground">
+ <LuBox className="size-8" />
+ <span className="text-xs">Model unavailable</span>
+ </div>
+ )}
+ </div>
+ ) : mainImage ? (
+ // Both step slides and the finished-item image fill the panel (large by
+ // default). Height follows the image's own aspect ratio (capped at 65vh);
+ // the details column scrolls if it overflows.
+ <div className="relative mx-auto w-full max-w-full overflow-hidden rounded-lg border border-border bg-muted/40">
+ <img
+ src={mainImage}
+ alt="Assembly reference"
+ className="block h-auto max-h-[65vh] w-full object-contain"
+ />
+ {showPins && (
+ <SlidePins
+ key={selected}
+ annotations={selectedAnnotations}
+ toolNameById={toolNameById}
+ />
+ )}
+ {/* Tap the image to open full screen. */}
+ <button
+ type="button"
+ aria-label="View image full screen"
+ onClick={imageViewer.onOpen}
+ className="absolute inset-0"
+ />
+ {/* Operator control: show/hide the annotation pins (always vs tap). */}
+ {selectedAnnotations.length > 0 && (
+ <Button
+ variant="secondary"
+ size="sm"
+ className="absolute left-2 top-2 z-10 gap-1.5"
+ leftIcon={
+ showPins ? (
+ <LuEye className="size-4" />
+ ) : (
+ <LuEyeOff className="size-4" />
+ )
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowPins((v) => !v);
+ }}
+ >
+ {showPins ? "Hide pins" : "Show pins"}
+ </Button>
+ )}
+ <span className="pointer-events-none absolute right-2 top-2 z-10 flex items-center justify-center rounded-md bg-background/80 p-1.5 text-muted-foreground shadow-sm">
+ <LuExpand className="size-4" />
+ </span>
+ </div>
+ ) : (
+ <div className="flex aspect-video w-full flex-col items-center justify-center gap-2 rounded-lg border border-border bg-muted/40 text-muted-foreground">
+ <LuImage className="size-8" />
+ <span className="text-xs">No reference image</span>
+ </div>
+ )}
+
+ {selectedCaption && (
+ <p className="shrink-0 truncate text-center text-xs text-muted-foreground">
+ {selectedCaption}
+ </p>
+ )}
+
+ {/* Slots = animated step playback (when synced) · this step's slides.
+ The finished-product image is the fallback when a step has neither. */}
+ <div className="flex shrink-0 items-center gap-2">
+ {playbackAvailable && (
+ <button
+ type="button"
+ aria-label="Animated assembly step"
+ title="Animated assembly step"
+ onClick={() => setSelected("playback")}
+ className={cn(
+ "relative flex h-12 w-16 shrink-0 items-center justify-center overflow-hidden rounded-md border-2 bg-muted/40",
+ selected === "playback"
+ ? "border-foreground"
+ : "border-transparent"
+ )}
+ >
+ <LuPlay className="size-5 text-muted-foreground" />
+ <span className="pointer-events-none absolute bottom-0.5 right-0.5 rounded bg-background/80 px-0.5 text-[8px] font-semibold text-muted-foreground">
+ 3D
+ </span>
+ </button>
+ )}
+ {stepSlides.map((slide, i) => {
+ const media = slideMedia[i];
+ return (
+ <button
+ key={slide.id}
+ type="button"
+ aria-label={slide.caption || `Slide ${i + 1}`}
+ title={slide.caption ?? undefined}
+ onClick={() => setSelected(i)}
+ className={cn(
+ "relative flex h-12 w-16 shrink-0 items-center justify-center overflow-hidden rounded-md border-2 bg-muted/40",
+ selected === i
+ ? "border-foreground"
+ : "border-transparent"
+ )}
+ >
+ {media?.thumbnail ? (
+ <img
+ src={media.thumbnail}
+ alt=""
+ className="h-full w-full object-contain"
+ />
+ ) : (
+ <LuBox className="size-5 text-muted-foreground" />
+ )}
+ {media?.kind === "model" && (
+ <span className="pointer-events-none absolute bottom-0.5 right-0.5 rounded bg-background/80 px-0.5 text-[8px] font-semibold text-muted-foreground">
+ 3D
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Current step */}
+ <div className="flex shrink-0 flex-col gap-3 p-6">
+ {step ? (
+ <>
+ <div className="flex items-center gap-2">
+ <span className="flex size-7 items-center justify-center rounded-full bg-foreground text-xs font-bold text-background">
+ {currentStep + 1}
+ </span>
+ {isStepDone(step) &&
+ (isStepBadResult(step) ? (
+ <Badge variant="red">Out of spec</Badge>
+ ) : (
+ <Badge variant="green">Done</Badge>
+ ))}
+ {step.type ? (
+ <Badge variant="secondary" className="normal-case">
+ {step.type}
+ </Badge>
+ ) : null}
+ </div>
+ <p className="text-lg font-medium leading-relaxed">
+ {step.name ?? `Step ${currentStep + 1}`}
+ </p>
+ {stepDescriptionHtml ? (
+ <div
+ className="prose prose-sm max-w-none text-sm text-foreground dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: stepDescriptionHtml
+ }}
+ />
+ ) : null}
+ </>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ No steps defined for this operation.
+ </p>
+ )}
+ </div>
+ </div>
+ )}
+ </main>
+
+ {/* ── SIDEBAR: materials, tools, NCRs, parameters ── */}
+ <aside className="flex w-full shrink-0 flex-col border-t border-border bg-card lg:w-[280px] lg:overflow-hidden lg:border-l lg:border-t-0 xl:w-[320px]">
+ <div className="flex flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden">
+ {/* Parts assigned to this step (+ unassigned "General" parts). Each part appears
+ once with its part-level quantity/issue status and chips for the step(s) it's
+ assigned to; the current step's chip is highlighted. Rendering once keeps the
+ requirement from ever being double-counted. */}
+ <SidebarSection
+ title="Parts"
+ scrollable={visibleMaterialsWithState.length > 0}
+ action={
+ <IconButton
+ aria-label="Issue material"
+ variant="ghost"
+ size="lg"
+ icon={<LuCirclePlus />}
+ onClick={() => {
+ // Clear any per-row selection so the modal opens in
+ // "pick any item" mode → issue a part not on the BOM.
+ setSelectedMaterial(null);
+ issueModal.onOpen();
+ }}
+ />
+ }
+ >
+ {visibleMaterialsWithState.length > 0 ? (
+ <div className="flex flex-col gap-1.5">
+ {visibleMaterialsWithState.map(
+ (
+ { m, stepNumbers, issuedIsPerUnit, issuedOverride },
+ i
+ ) => (
+ <MaterialRow
+ key={m.id ?? i}
+ material={m}
+ stepNumbers={stepNumbers}
+ currentStepNumber={currentStep + 1}
+ unitIndex={currentUnitIndex}
+ issuedIsPerUnit={issuedIsPerUnit}
+ issuedOverride={issuedOverride}
+ onIssue={() => {
+ setSelectedMaterial(m);
+ issueModal.onOpen();
+ }}
+ />
+ )
+ )}
+ </div>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ No materials assigned
+ </p>
+ )}
+ </SidebarSection>
+
+ {stepTools.length > 0 && (
+ <SidebarSection title="Tools" scrollable>
+ {/* Tools mirror the Parts cards — a bordered row with a leading
+ wrench (in place of the part's issue-status dot), the name +
+ type stacked, and the count/pin badges hard-right. */}
+ <div className="flex flex-col gap-1.5">
+ {stepTools.map((t, i) => {
+ // Pin sequence number(s) on the current slide that point at this tool.
+ const seq = t.item?.id
+ ? pinSeqByToolId.get(t.item.id)
+ : undefined;
+ return (
+ <div
+ key={t.item?.id ?? i}
+ className="flex w-full items-start gap-2.5 rounded-lg border border-border bg-accent/30 px-3 py-2.5 text-left"
+ >
+ <LuWrench className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ {/* Name + readableId stacked; each stays on a single line
+ (mirrors the Parts card's description + item id). */}
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-sm font-medium leading-snug text-foreground">
+ {t.item?.name ?? "Unknown tool"}
+ </span>
+ {t.item?.readableId && (
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {t.item.readableId}
+ </span>
+ )}
+ </div>
+ {/* Count hard-right, with any pin-sequence badges tucked
+ beneath it (mirrors the tracking badges on Parts). */}
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ <span className="text-xs tabular-nums text-muted-foreground">
+ ×{t.quantity}
+ </span>
+ {seq && seq.length > 0 && (
+ <div className="flex flex-wrap items-center justify-end gap-1">
+ {seq.map((n) => (
+ <span
+ key={n}
+ className="flex size-4 items-center justify-center rounded-full bg-foreground text-[9px] font-bold text-background"
+ >
+ {n}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </SidebarSection>
+ )}
+
+ {ncrs.length > 0 && (
+ <SidebarSection title="Open NCRs">
+ {ncrs.map((ncr, i) => {
+ const nc = ncr.nonConformance;
+ const isClosed = nc?.status === "Closed";
+ const readableId =
+ nc?.nonConformanceId ?? ncr.nonConformanceId;
+ return (
+ <div key={readableId ?? i} className="py-1">
+ <Status color={isClosed ? "green" : "red"}>
+ {readableId}
+ </Status>
+ </div>
+ );
+ })}
+ </SidebarSection>
+ )}
+
+ {parameters.length > 0 ? (
+ <SidebarSection title="Parameters">
+ {parameters.map((p, i) => (
+ <div
+ key={p.id ?? p.key ?? i}
+ className="flex justify-between py-0.5"
+ >
+ <span className="text-xs text-muted-foreground">
+ {p.key}
+ </span>
+ <span className="text-xs font-medium">{p.value}</span>
+ </div>
+ ))}
+ </SidebarSection>
+ ) : null}
+ </div>
+
+ {/* ── ACTIONS: Complete Step + Skip ── Tracked parts assigned to this
+ step must be scanned before the step can be completed; Skip is always
+ available as the escape hatch when the operator can't finish it. */}
+ <div className="flex w-full shrink-0 flex-col gap-2 border-t border-border p-3">
+ {hasPendingScans && step && !isStepDone(step) && (
+ <p className="flex items-center gap-1.5 text-xs text-foreground">
+ <LuCircleDot className="size-3.5 shrink-0 text-amber-500" />
+ Scan {pendingScanMaterials.length} part
+ {pendingScanMaterials.length > 1 ? "s" : ""} to complete this
+ step
+ </p>
+ )}
+ <div className="flex w-full items-stretch gap-2">
+ {step && (
+ <div className="min-w-0 flex-1">
+ <StepCompleteAction
+ step={step}
+ activeIndex={activeIndex}
+ done={isStepDone(step)}
+ disabled={hasPendingScans}
+ />
+ </div>
+ )}
+ <Button
+ variant="outline"
+ size="lg"
+ className="shrink-0"
+ rightIcon={<LuSkipForward />}
+ isDisabled={isLastStep}
+ onClick={() => goToStep(currentStep + 1)}
+ >
+ Skip
+ </Button>
+ </div>
+ </div>
+ </aside>
+ </div>
+
+ {issueModal.isOpen && (
+ <IssueMaterialModal
+ operationId={operationId}
+ // Assembly builds one unit at a time: each scan issues one unit's
+ // worth (issuePerUnit), so the pick order can never be attributed
+ // to the unit on screen — never pre-select tracked entities; the
+ // operator scans what goes into THIS unit.
+ allowPrefill={false}
+ issuePerUnit
+ expiredEntityPolicy={expiredEntityPolicy}
+ locationId={locationId}
+ workCenterId={operation?.workCenterId ?? undefined}
+ material={selectedMaterial ?? undefined}
+ // Untracked parents have no unit-axis entity, but tracked child
+ // consumes still need a genealogy parent — fall back to the make
+ // method's seed entity, same as the operation view.
+ parentId={currentEntity?.id ?? trackedEntities[0]?.id ?? ""}
+ parentIdIsSerialized={requiresSerialTracking}
+ // Stamp the current step + 1-based unit onto the consume so issued
+ // quantities can be attributed per-unit even for a batch parent (where
+ // all units share one lot). See the loader's batch attribution.
+ jobOperationStepId={step?.id}
+ unitNumber={currentUnitIndex + 1}
+ trackedInputs={materials?.trackedInputs ?? []}
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ )}
+
+ <QualityIssueModal
+ operationId={operationId}
+ trackedEntityId={isTracked ? currentEntity?.id : undefined}
+ isOpen={qualityModal.isOpen}
+ onClose={qualityModal.onClose}
+ />
+
+ {completeModal.isOpen && operation && (
+ <QuantityModal
+ type="complete"
+ operation={operation as unknown as OperationWithDetails}
+ materials={(materials?.materials ?? []) as JobMaterial[]}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ trackedEntityId={currentEntity?.id ?? ""}
+ setupProductionEvent={openByType("Setup")}
+ laborProductionEvent={openByType("Labor")}
+ machineProductionEvent={openByType("Machine")}
+ allStepsRecorded={allStepsRecorded}
+ onClose={completeModal.onClose}
+ />
+ )}
+
+ {scrapModal.isOpen && operation && (
+ <QuantityModal
+ type="scrap"
+ operation={operation as unknown as OperationWithDetails}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ trackedEntityId={currentEntity?.id ?? ""}
+ setupProductionEvent={openByType("Setup")}
+ laborProductionEvent={openByType("Labor")}
+ machineProductionEvent={openByType("Machine")}
+ onClose={scrapModal.onClose}
+ />
+ )}
+
+ {finishModal.isOpen && operation && (
+ <QuantityModal
+ type="finish"
+ operation={operation as unknown as OperationWithDetails}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ trackedEntityId={currentEntity?.id ?? ""}
+ setupProductionEvent={openByType("Setup")}
+ laborProductionEvent={openByType("Labor")}
+ machineProductionEvent={openByType("Machine")}
+ allStepsRecorded={allStepsRecorded}
+ onClose={finishModal.onClose}
+ />
+ )}
+
+ {reworkModal.isOpen && operation && jobId && (
+ <ReworkModal
+ operation={operation as unknown as OperationWithDetails}
+ jobId={jobId}
+ isOpen={reworkModal.isOpen}
+ onClose={reworkModal.onClose}
+ trackedEntities={trackedEntities as never}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ />
+ )}
+
+ {workCenter && (
+ <MaintenanceDispatch
+ workCenter={workCenter}
+ isOpen={maintenanceModal.isOpen}
+ onClose={maintenanceModal.onClose}
+ />
+ )}
+
+ {serialModal.isOpen && (
+ <SerialSelectorModal
+ availableEntities={unitEntities as never}
+ onClose={serialModal.onClose}
+ onCancel={serialModal.onClose}
+ onSelect={(entity) => {
+ navigateEntity(entity);
+ serialModal.onClose();
+ }}
+ />
+ )}
+
+ <BottomSheet
+ open={actionsSheet.isOpen}
+ onOpenChange={(open) => {
+ if (!open) actionsSheet.onClose();
+ }}
+ >
+ <BottomSheetContent className="mx-auto max-w-md">
+ <BottomSheetBody>
+ <div className="flex flex-col gap-2 pb-2">
+ <ActionSheetButton
+ icon={<LuTrash className="size-4 shrink-0" />}
+ label="Scrap"
+ onClick={() => {
+ actionsSheet.onClose();
+ scrapModal.onOpen();
+ }}
+ />
+ <ActionSheetButton
+ icon={<LuGitPullRequest className="size-4 shrink-0" />}
+ label="Rework"
+ onClick={() => {
+ actionsSheet.onClose();
+ reworkModal.onOpen();
+ }}
+ />
+ <ActionSheetButton
+ icon={<LuCheck className="size-4 shrink-0" />}
+ label="Finish"
+ onClick={() => {
+ actionsSheet.onClose();
+ finishModal.onOpen();
+ }}
+ />
+ {workCenter && !workCenter.isBlocked ? (
+ <ActionSheetButton
+ icon={<LuWrench className="size-4 shrink-0" />}
+ label="Maintenance"
+ onClick={() => {
+ actionsSheet.onClose();
+ maintenanceModal.onOpen();
+ }}
+ />
+ ) : null}
+ <ActionSheetButton
+ icon={<LuFlag className="size-4 shrink-0" />}
+ label="Quality Issue"
+ onClick={() => {
+ actionsSheet.onClose();
+ qualityModal.onOpen();
+ }}
+ />
+ {/* Manager-only override: record every remaining step for this unit at once.
+ Shown only to users with the Production DELETE permission, and only when
+ there are unrecorded steps left. */}
+ {canOverrideComplete &&
+ steps.length > 0 &&
+ doneCount < steps.length && (
+ <ActionSheetButton
+ icon={<LuListChecks className="size-4 shrink-0" />}
+ label="Complete all steps"
+ onClick={() => {
+ actionsSheet.onClose();
+ completeAllModal.onOpen();
+ }}
+ />
+ )}
+ </div>
+ </BottomSheetBody>
+ </BottomSheetContent>
+ </BottomSheet>
+
+ {completeAllModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) completeAllModal.onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Complete all steps?</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <p className="text-sm text-muted-foreground">
+ This records the{" "}
+ <span className="font-semibold text-foreground">
+ {steps.length - doneCount}
+ </span>{" "}
+ remaining step(s) as complete for{" "}
+ <span className="font-semibold text-foreground">
+ Unit {currentUnitIndex + 1}
+ </span>{" "}
+ without capturing their values. This is a manager override; each
+ step can still be undone individually.
+ </p>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={completeAllModal.onClose}>
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ isLoading={completeAllFetcher.state !== "idle"}
+ onClick={() => {
+ const fd = new FormData();
+ fd.append("operationId", operationId);
+ fd.append("index", String(activeIndex));
+ completeAllFetcher.submit(fd, {
+ method: "post",
+ action: path.to.completeAllSteps
+ });
+ completeAllModal.onClose();
+ }}
+ >
+ Complete all
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+
+ <ImageZoomViewer
+ open={imageViewer.isOpen}
+ src={mainImage}
+ caption={selectedCaption}
+ annotations={selectedAnnotations}
+ toolNameById={toolNameById}
+ onClose={imageViewer.onClose}
+ />
+
+ {/* Only auto-start when the operation actually has a timer to track (a configured
+ Setup/Labor/Machine duration). With no work types there's nothing to time, so we
+ don't start a stray Labor event. */}
+ {operation && autoStartOperationTimer && workTypes.length > 0 && (
+ <AutoTimer
+ operationId={operationId}
+ enabled={autoStartOperationTimer}
+ workType={headerWorkTypes[0]}
+ workCenterId={operation.workCenterId ?? undefined}
+ openEvent={openEventForWorkType(headerWorkTypes[0])}
+ trackedEntityId={isTracked ? currentEntity?.id : undefined}
+ unitIndex={currentUnitIndex}
+ />
+ )}
+ </div>
+ );
+}
+
+// Passive operation timer (opt-in). Auto-starts the operator's production event when the
+// assembly view opens (so it isn't forgotten). It never auto-ends ("clocks out") a timer —
+// stopping is always a manual action via the header pause button. Drives off the loader's
+// `openEvent`, which the assembly realtime channel keeps fresh after each Start.
+function AutoTimer({
+ operationId,
+ enabled,
+ workType,
+ workCenterId,
+ openEvent,
+ trackedEntityId,
+ unitIndex
+}: {
+ operationId: string;
+ enabled: boolean;
+ workType: "Setup" | "Labor" | "Machine";
+ workCenterId?: string;
+ openEvent: { id: string; startTime: string } | null;
+ trackedEntityId?: string;
+ unitIndex?: number;
+}) {
+ const fetcher = useFetcher();
+ const startedRef = useRef(false);
+
+ const busy = fetcher.state !== "idle";
+ const running = !!openEvent;
+
+ // Auto-start once when the view opens and nothing is running yet.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: one-shot on open
+ useEffect(() => {
+ if (!enabled || startedRef.current) return;
+ startedRef.current = true;
+ if (running || busy) return;
+ const fd = new FormData();
+ fd.set("jobOperationId", operationId);
+ fd.set("timezone", getLocalTimeZone());
+ fd.set("type", workType);
+ fd.set("action", "Start");
+ fd.set("exclusive", "true");
+ if (workCenterId) fd.set("workCenterId", workCenterId);
+ if (trackedEntityId) fd.set("trackedEntityId", trackedEntityId);
+ if (typeof unitIndex === "number") fd.set("unitIndex", String(unitIndex));
+ fetcher.submit(fd, { method: "post", action: path.to.productionEvent });
+ }, [enabled]);
+
+ return null;
+}
+
+function ActionSheetButton({
+ icon,
+ label,
+ onClick
+}: {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ className="flex items-center gap-3 rounded-lg bg-accent px-4 py-4 text-accent-foreground ring-1 ring-black/5 transition-transform active:scale-[0.98]"
+ onClick={onClick}
+ >
+ {icon}
+ <span className="text-base/6 font-medium">{label}</span>
+ </button>
+ );
+}
+
+function TimerControl({
+ operation,
+ openEvent,
+ workType,
+ trackedEntityId,
+ unitIndex
+}: {
+ operation: Operation;
+ openEvent: { id: string; startTime: string } | null;
+ workType: "Setup" | "Labor" | "Machine";
+ trackedEntityId?: string;
+ unitIndex?: number;
+}) {
+ const fetcher = useFetcher();
+
+ // Optimistic state: the moment Start/End is submitted, flip immediately
+ // instead of waiting for the (slow) post-production-event round-trip. This
+ // stops the clock the instant you press pause — no lingering "spinning"
+ // while the timer keeps climbing.
+ const pendingAction = fetcher.formData?.get("action");
+ const active =
+ pendingAction === "Start"
+ ? true
+ : pendingAction === "End"
+ ? false
+ : !!openEvent;
+
+ // Freeze the clock while a stop is in flight; otherwise tick live.
+ const liveElapsed = useElapsed(pendingAction === "End" ? null : openEvent);
+ const elapsed = pendingAction === "End" ? 0 : liveElapsed;
+
+ return (
+ // The entire time display is the start/stop trigger — a big, obvious tap
+ // target on the shop floor beats a small icon button.
+ <fetcher.Form
+ method="post"
+ action={path.to.productionEvent}
+ className="h-full shrink-0"
+ >
+ <input type="hidden" name="jobOperationId" value={operation.id} />
+ <input type="hidden" name="timezone" value={getLocalTimeZone()} />
+ <input type="hidden" name="type" value={workType} />
+ {/* Single-phase clocking: starting this type ends any other open type. */}
+ <input type="hidden" name="exclusive" value="true" />
+ <input type="hidden" name="action" value={openEvent ? "End" : "Start"} />
+ {operation.workCenterId ? (
+ <input
+ type="hidden"
+ name="workCenterId"
+ value={operation.workCenterId}
+ />
+ ) : null}
+ {openEvent ? (
+ <input type="hidden" name="id" value={openEvent.id} />
+ ) : null}
+ {trackedEntityId ? (
+ <input type="hidden" name="trackedEntityId" value={trackedEntityId} />
+ ) : null}
+ {typeof unitIndex === "number" ? (
+ <input type="hidden" name="unitIndex" value={unitIndex} />
+ ) : null}
+ <button
+ type="submit"
+ aria-label={active ? "Pause timer" : "Start timer"}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"
+ >
+ <span className="hidden flex-col items-end leading-none sm:flex">
+ <span className="text-sm font-medium tabular-nums">
+ {formatElapsed(elapsed)}
+ </span>
+ <span className="text-[9px] uppercase tracking-wider text-muted-foreground">
+ {workType}
+ </span>
+ </span>
+ {active ? (
+ <LuPause className="size-4" />
+ ) : (
+ <LuPlay className="size-4" />
+ )}
+ </button>
+ </fetcher.Form>
+ );
+}
+
+function SidebarSection({
+ title,
+ children,
+ scrollable,
+ action
+}: {
+ title: string;
+ children: React.ReactNode;
+ scrollable?: boolean;
+ // Optional right-aligned control in the section header (e.g. an "add" button).
+ action?: React.ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex flex-col",
+ // On mobile every section flows at its natural height (the page
+ // scrolls). On lg+ scrollable sections share the panel and scroll
+ // internally.
+ scrollable ? "lg:min-h-0 lg:flex-1" : "shrink-0"
+ )}
+ >
+ <Separator />
+ <div className="flex shrink-0 items-center justify-between gap-2 px-3.5 pb-1 pt-2.5">
+ <h3 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ {title}
+ </h3>
+ {action}
+ </div>
+ <div
+ className={cn(
+ "px-3.5 pb-2.5",
+ scrollable && "lg:min-h-0 lg:flex-1 lg:overflow-y-auto"
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
+
+// Per-unit issue state for a material. Assembly builds unit-by-unit, so the
+// requirement is ALWAYS the per-unit BOM quantity (`quantity`), never the job
+// total. Serial parents already report per-unit consumption for tracked parts;
+// batch/untracked parents report a job-wide total, so we derive this unit's share
+// by assuming prior units each consumed their per-unit quantity. `issuedOverride`
+// short-circuits both (loose parts backflushed on the unit's first step record).
+// Shared by MaterialRow and the step's scan gate so they never diverge.
+function getIssuedForUnit(
+ material: any,
+ {
+ unitIndex,
+ issuedIsPerUnit,
+ issuedOverride
+ }: {
+ unitIndex: number;
+ issuedIsPerUnit: boolean;
+ issuedOverride?: number;
+ }
+) {
+ const required = material.quantity ?? material.estimatedQuantity ?? 0;
+ const totalIssued = material.quantityIssued ?? 0;
+ const issued =
+ issuedOverride !== undefined
+ ? issuedOverride
+ : issuedIsPerUnit
+ ? totalIssued
+ : // An unplanned/extra part has no per-unit requirement (required 0), so the
+ // per-unit derivation would clamp it to 0 — surface the raw issued total
+ // instead. Planned parts derive this unit's share from the job-wide total.
+ required === 0
+ ? totalIssued
+ : Math.min(required, Math.max(0, totalIssued - unitIndex * required));
+ const fullyIssued = required > 0 && issued >= required;
+ return { required, issued, fullyIssued };
+}
+
+function MaterialRow({
+ material,
+ onIssue,
+ stepNumbers = [],
+ currentStepNumber,
+ unitIndex = 0,
+ issuedIsPerUnit = false,
+ issuedOverride
+}: {
+ material: any;
+ onIssue?: () => void;
+ // 1-based step numbers where this part is used ("where used"); empty = General.
+ stepNumbers?: number[];
+ currentStepNumber?: number;
+ // 0-based unit currently being built; attributes job-total issued
+ // quantities to the unit on screen.
+ unitIndex?: number;
+ // True when material.quantityIssued is already scoped to the current unit
+ // (serial parent + tracked material — the service recomputes it from the
+ // parent entity's consumed inputs). Otherwise it's a job-wide total.
+ issuedIsPerUnit?: boolean;
+ // When set, use this as the unit's issued quantity instead of deriving it —
+ // loose (untracked, step-unassigned) parts are backflushed when the unit's
+ // first step is recorded, so their status mirrors that trigger directly.
+ issuedOverride?: number;
+}) {
+ const isTracked =
+ material.requiresSerialTracking || material.requiresBatchTracking;
+ const { required, issued, fullyIssued } = getIssuedForUnit(material, {
+ unitIndex,
+ issuedIsPerUnit,
+ issuedOverride
+ });
+ // An unplanned/extra part (issued from the shop floor, not on the BOM) has no
+ // required quantity. Once any quantity is issued it's "done" — there's nothing
+ // outstanding — so it reads as issued rather than perpetually "partial".
+ const isExtra = required === 0;
+ const extraIssued = isExtra && issued > 0;
+ const partiallyIssued = !isExtra && issued > 0 && !fullyIssued;
+
+ // Leading status dot: issued (green check) · partially issued (amber) · not issued (hollow).
+ const issueStatus =
+ fullyIssued || extraIssued
+ ? { icon: LuCircleCheck, className: "text-emerald-500", label: "Issued" }
+ : partiallyIssued
+ ? {
+ icon: LuCircleDot,
+ className: "text-amber-500",
+ label: "Partially issued"
+ }
+ : {
+ icon: LuCircle,
+ className: "text-muted-foreground/50",
+ label: "Not issued"
+ };
+ const StatusIcon = issueStatus.icon;
+
+ const usedHere =
+ currentStepNumber != null && stepNumbers.includes(currentStepNumber);
+
+ // The whole card is the action: clicking it opens the scan/issue flow. Tracked
+ // parts stay clickable even once issued, so with several serialized parts each
+ // one can be (re)scanned straight from its own card instead of the single
+ // bottom Scan button. Non-tracked parts drop the affordance once fully issued
+ // (nothing left to add).
+ const interactive = !!onIssue && (isTracked || !fullyIssued);
+ const Wrapper = interactive ? "button" : "div";
+
+ return (
+ <Wrapper
+ {...(interactive
+ ? {
+ type: "button" as const,
+ onClick: onIssue,
+ "aria-label": isTracked ? "Scan material" : "Issue material"
+ }
+ : {})}
+ className={cn(
+ "flex w-full items-start gap-2.5 rounded-lg border border-border bg-accent/30 px-3 py-2.5 text-left transition-colors",
+ interactive && "cursor-pointer hover:bg-accent/60 active:scale-[0.99]",
+ usedHere && "ring-1 ring-inset ring-foreground/20"
+ )}
+ >
+ <StatusIcon
+ aria-label={issueStatus.label}
+ className={cn("mt-0.5 size-3.5 shrink-0", issueStatus.className)}
+ />
+ {/* Name + id stacked; each stays on a single line and truncates if long. */}
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-sm font-medium leading-snug text-foreground">
+ {material.description}
+ </span>
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {material.itemReadableId}
+ </span>
+ </div>
+ {/* Count hard-right, with the tracking badges tucked beneath it. */}
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ {fullyIssued || extraIssued ? (
+ <span className="flex items-center gap-1 text-[11px] font-medium tabular-nums text-emerald-500">
+ {issued}/{required}
+ <LuCheck className="size-3" />
+ </span>
+ ) : partiallyIssued ? (
+ <span className="text-[11px] tabular-nums text-amber-500">
+ {issued}/{required}
+ </span>
+ ) : (
+ <span className="text-xs tabular-nums text-muted-foreground">
+ ×{required}
+ </span>
+ )}
+ {/* Distinguish an unplanned part (issued from the floor, not on the BOM). */}
+ {isExtra && <Badge variant="outline">Added</Badge>}
+ {isTracked && (
+ <div className="flex flex-wrap items-center justify-end gap-1">
+ {material.requiresSerialTracking && (
+ <Badge variant="secondary">
+ <TrackingTypeIcon type="Serial" className="shrink-0" />
+ </Badge>
+ )}
+ {material.requiresBatchTracking && (
+ <Badge variant="secondary">
+ <TrackingTypeIcon type="Batch" className="shrink-0" />
+ </Badge>
+ )}
+ {!fullyIssued && <Badge variant="orange">Requires Scan</Badge>}
+ </div>
+ )}
+ </div>
+ </Wrapper>
+ );
+}
+
+// ── Per-step completion action ──────────────────────────────────────────────
+
+function StepCompleteAction({
+ step,
+ activeIndex,
+ done,
+ disabled = false
+}: {
+ step: Step;
+ activeIndex: number;
+ done: boolean;
+ // Soft gate: the step's tracked parts aren't fully issued for this unit, so
+ // block completion (Mark done / Record) until they're scanned. Skip bypasses.
+ disabled?: boolean;
+}) {
+ const fetcher = useFetcher();
+ const user = useUser();
+ const busy = fetcher.state !== "idle";
+ const recordModal = useDisclosure();
+
+ // Find the existing record for this unit (if done)
+ const record = (step.jobOperationStepRecord ?? []).find(
+ (r) => r.index === activeIndex
+ );
+ // A record can only be undone by whoever created it (the delete RPC filters
+ // by createdBy) — mirror the operation view and disable undo otherwise.
+ const canUndo = !!record && record.createdBy === user.id;
+
+ const type = step.type ?? "Task";
+
+ // Undo: delete the record so step can be re-done
+ function handleUndo() {
+ if (!record) return;
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.recordDelete(record.id)
+ });
+ }
+
+ // Quick-complete a Task step (no captured value — matches the operation view).
+ function markTaskDone() {
+ const fd = new FormData();
+ fd.append("jobOperationStepId", step.id);
+ fd.append("index", String(activeIndex));
+ fd.append("booleanValue", "true");
+ fetcher.submit(fd, { method: "post", action: path.to.record });
+ }
+
+ // ── Already done: show recorded value + Undo button ──
+ if (done && record) {
+ let recordedDisplay: string | null = null;
+ if (record.numericValue != null)
+ recordedDisplay = `${record.numericValue}${step.unitOfMeasureCode ? ` ${step.unitOfMeasureCode}` : ""}`;
+ else if (record.booleanValue != null)
+ recordedDisplay = record.booleanValue ? "Yes" : "No";
+ else if (record.value) recordedDisplay = record.value;
+ else if (record.userValue) recordedDisplay = record.userValue;
+
+ // File steps store a long storage path — show just the file name; the full
+ // path stays available in the truncation tooltip.
+ const displayText =
+ type === "File" && recordedDisplay
+ ? recordedDisplay.split("/").pop() || recordedDisplay
+ : recordedDisplay;
+
+ return (
+ <div className="flex h-full items-center gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2">
+ <LuCheck className="size-4 shrink-0 text-emerald-500" />
+ {displayText ? (
+ <TruncatedTooltipText
+ tooltip={recordedDisplay}
+ className="min-w-0 flex-1 truncate text-sm text-emerald-600 dark:text-emerald-400"
+ >
+ Recorded: {displayText}
+ </TruncatedTooltipText>
+ ) : (
+ <span className="min-w-0 flex-1 truncate text-sm text-emerald-600 dark:text-emerald-400">
+ Completed
+ </span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ isIcon
+ aria-label="Undo"
+ isLoading={busy}
+ isDisabled={!canUndo}
+ title={
+ canUndo ? "Undo" : "Only the operator who recorded this can undo it"
+ }
+ onClick={handleUndo}
+ >
+ <LuUndo2 className="size-3.5 text-muted-foreground" />
+ </Button>
+ </div>
+ );
+ }
+
+ // ── Not done ──
+ // Task → quick "Mark done" submit. Every other type (Value, Measurement,
+ // Checkbox, List, Person, Timestamp, File, Inspection) opens the shared
+ // RecordModal — same component the operation view uses (incl. file upload).
+ if (type === "Task") {
+ return (
+ <Button
+ variant="primary"
+ size="lg"
+ leftIcon={<LuCheck />}
+ isLoading={busy}
+ isDisabled={disabled}
+ className="w-full"
+ onClick={markTaskDone}
+ >
+ Mark done
+ </Button>
+ );
+ }
+
+ return (
+ <>
+ <Button
+ variant="primary"
+ size="lg"
+ leftIcon={<LuCheck />}
+ isDisabled={disabled}
+ className="w-full"
+ onClick={recordModal.onOpen}
+ >
+ Record
+ </Button>
+ {recordModal.isOpen && (
+ <RecordModal
+ attribute={step as unknown as JobOperationStep}
+ activeStep={activeIndex}
+ onClose={recordModal.onClose}
+ />
+ )}
+ </>
+ );
+}
+
+// Units section for the left sidebar — its own labeled section (like Time), sitting
+// directly below the timers. A compact prev/next pager sits top-right by the label,
+// and the full, scrollable list of EVERY unit gives full visibility. A serial parent
+// binds a distinct entity per unit, so it lists those by readableId; a batch parent
+// binds a single lot to unit 0 (the rest are null), so listing that one id is more
+// noise than signal — batch and untracked parents both list "Unit 1 / Unit 2 / …".
+// The list auto-scrolls to keep the current unit in view; units with an out-of-spec
+// measurement (or a failed inspection) are flagged red, fully-recorded units green.
+function UnitNavigator({
+ units,
+ currentUnitIndex,
+ maxNavigableIndex,
+ isTracked,
+ labelByEntity,
+ trackingLabel,
+ headerAction,
+ unitHasBadResult,
+ unitIsRecorded,
+ onSelectUnit
+}: {
+ units: {
+ index: number;
+ entity: { id: string; readableId?: string | null } | null;
+ }[];
+ currentUnitIndex: number;
+ // Highest unit index the operator may open. For a serial parent this is the last
+ // unit whose serial has been minted; beyond it the unit has no entity and can't
+ // be worked on, so its row is disabled.
+ maxNavigableIndex: number;
+ isTracked: boolean;
+ labelByEntity: boolean;
+ trackingLabel: string;
+ // Optional control in the section header, left of the pager (e.g. print label).
+ headerAction?: React.ReactNode;
+ unitHasBadResult: (index: number) => boolean;
+ unitIsRecorded: (index: number) => boolean;
+ onSelectUnit: (index: number) => void;
+}) {
+ const isEntityLabel = (u: (typeof units)[number]) =>
+ labelByEntity && !!u.entity;
+ const isNavigable = (u: (typeof units)[number]) =>
+ u.index <= maxNavigableIndex;
+ const labelFor = (u: (typeof units)[number]) =>
+ labelByEntity && u.entity
+ ? (u.entity.readableId ?? u.entity.id.slice(0, 8))
+ : `Unit ${u.index + 1}`;
+
+ // Keep the selected unit visible as the operator pages/jumps between units.
+ // currentUnitIndex is a real dep: the ref points at a different row after it
+ // changes, so re-run the scroll even though the body only reads the ref.
+ const currentRef = useRef<HTMLButtonElement>(null);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll on unit change
+ useEffect(() => {
+ currentRef.current?.scrollIntoView({ block: "nearest" });
+ }, [currentUnitIndex]);
+
+ return (
+ <div className="flex shrink-0 flex-col border-b border-border">
+ {/* Section header: label + compact pager grouped top-right. */}
+ <div className="flex items-center justify-between px-3 pb-1.5 pt-3">
+ <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ {isTracked ? trackingLabel : "Units"}
+ </p>
+ <div className="flex items-center gap-0.5">
+ {headerAction}
+ <IconButton
+ aria-label="Previous unit"
+ variant="ghost"
+ size="lg"
+ icon={<LuChevronLeft />}
+ isDisabled={currentUnitIndex <= 0}
+ onClick={() => onSelectUnit(currentUnitIndex - 1)}
+ />
+ <IconButton
+ aria-label="Next unit"
+ variant="ghost"
+ size="lg"
+ icon={<LuChevronRight />}
+ isDisabled={currentUnitIndex >= maxNavigableIndex}
+ onClick={() => onSelectUnit(currentUnitIndex + 1)}
+ />
+ </div>
+ </div>
+
+ {/* Full, scrollable, full-bleed list — bounded so it never crowds out the
+ rest of the sidebar. No inner box/rounding; the section border divides it
+ from the next section like every other card section. */}
+ <div className="max-h-48 overflow-y-auto pb-2">
+ {units.map((u) => {
+ const isCurrent = u.index === currentUnitIndex;
+ const bad = unitHasBadResult(u.index);
+ const recorded = unitIsRecorded(u.index);
+ // A serial unit with no minted serial yet can't be opened (nothing to
+ // scan or complete against). Show it as a disabled placeholder.
+ const navigable = isNavigable(u);
+ return (
+ <button
+ key={u.index}
+ type="button"
+ ref={isCurrent ? currentRef : undefined}
+ aria-pressed={isCurrent}
+ disabled={!navigable}
+ title={navigable ? undefined : "Not started yet"}
+ onClick={() => onSelectUnit(u.index)}
+ className={cn(
+ "flex w-full items-center gap-2 px-3 py-2 text-left text-xs transition-colors",
+ isCurrent
+ ? "bg-accent font-semibold text-foreground"
+ : navigable
+ ? "text-muted-foreground hover:bg-muted/60"
+ : "cursor-not-allowed text-muted-foreground/40",
+ bad && "text-red-500"
+ )}
+ >
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ bad
+ ? "bg-red-500"
+ : recorded
+ ? "bg-emerald-500"
+ : "bg-transparent"
+ )}
+ />
+ <span className={cn("truncate", isEntityLabel(u) && "font-mono")}>
+ {labelFor(u)}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+// Compact tab button for the main panel (Details / Model / Chat).
+function TabButton({
+ active,
+ onClick,
+ children
+}: {
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "rounded-md px-3 py-1 text-xs font-medium transition-colors",
+ active
+ ? "bg-foreground text-background"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+// Label · value row for the left-panel Status section.
+function StatusRow({
+ label,
+ value,
+ mono
+}: {
+ label: string;
+ value: string;
+ mono?: boolean;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="shrink-0 text-xs text-muted-foreground">{label}</span>
+ <span
+ className={cn(
+ "min-w-0 truncate text-xs font-medium text-foreground",
+ mono && "font-mono"
+ )}
+ >
+ {value}
+ </span>
+ </div>
+ );
+}
+
+// ── Cumulative production event timer ───────────────────────────────────────
+
+function useCumulativeProgress(events: ProductionEvent[]) {
+ const [, setTick] = useState(0);
+
+ useEffect(() => {
+ const hasOpen = events.some((e) => !e.endTime);
+ if (!hasOpen) return;
+ const id = setInterval(() => setTick((t) => t + 1), 1000);
+ return () => clearInterval(id);
+ }, [events]);
+
+ const totals = { setup: 0, labor: 0, machine: 0 };
+ const now = Date.now();
+
+ for (const ev of events) {
+ const rawKey = (ev.type ?? "labor").toLowerCase();
+ const key = rawKey as keyof typeof totals;
+ if (!(key in totals)) continue;
+ if (ev.endTime) {
+ // Completed event — use stored duration (ms) if present, else calculate
+ totals[key] +=
+ ev.duration != null
+ ? ev.duration * 1000
+ : new Date(ev.endTime).getTime() - new Date(ev.startTime).getTime();
+ } else {
+ // Open event — live elapsed
+ totals[key] += Math.max(0, now - new Date(ev.startTime).getTime());
+ }
+ }
+
+ return totals;
+}
+
+// The Setup/Labor/Machine timer rows. Isolated into its own component so the
+// per-second `useCumulativeProgress` tick re-renders ONLY these rows — not the
+// entire AssemblyView. A whole-view re-render every second was resetting an open
+// RecordModal's react-aria number input back to its default while the operator
+// was mid-edit (the "measurement keeps going to 0" bug).
+function TimeRows({
+ events,
+ setupDuration,
+ laborDuration,
+ machineDuration
+}: {
+ events: ProductionEvent[];
+ setupDuration: number;
+ laborDuration: number;
+ machineDuration: number;
+}) {
+ const progress = useCumulativeProgress(events);
+ // A work type is "running" when it has an open (un-ended) event. Control lives
+ // in the header clock buttons now; these rows are a live read-out.
+ const isRunning = (type: "Setup" | "Labor" | "Machine") =>
+ events.some((e) => e.type === type && !e.endTime);
+ return (
+ <>
+ {setupDuration > 0 && (
+ <TimerRow
+ icon={<LuTimer className="size-3" />}
+ label="Setup"
+ elapsed={progress.setup}
+ total={setupDuration}
+ running={isRunning("Setup")}
+ />
+ )}
+ {laborDuration > 0 && (
+ <TimerRow
+ icon={<LuHardHat className="size-3" />}
+ label="Labor"
+ elapsed={progress.labor}
+ total={laborDuration}
+ running={isRunning("Labor")}
+ />
+ )}
+ {machineDuration > 0 && (
+ <TimerRow
+ icon={<LuHammer className="size-3" />}
+ label="Machine"
+ elapsed={progress.machine}
+ total={machineDuration}
+ running={isRunning("Machine")}
+ />
+ )}
+ </>
+ );
+}
+
+// Single timer row: running dot · icon · "3s / 6m" · progress bar
+function TimerRow({
+ icon,
+ label,
+ elapsed,
+ total,
+ running
+}: {
+ icon: React.ReactNode;
+ label: string;
+ elapsed: number;
+ total: number;
+ running?: boolean;
+}) {
+ const overrun = total > 0 && elapsed > total;
+
+ return (
+ <div className="flex w-full flex-col gap-1 px-1.5 py-1 text-left">
+ <div className="flex items-center justify-between gap-1">
+ <span
+ className={cn(
+ "flex items-center gap-1 text-[10px]",
+ running ? "font-semibold text-foreground" : "text-muted-foreground"
+ )}
+ >
+ {/* running indicator dot */}
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ running ? "bg-emerald-500" : "bg-muted-foreground/40"
+ )}
+ />
+ {icon}
+ {label}
+ </span>
+ <span
+ className={cn(
+ "font-mono text-[10px] tabular-nums",
+ overrun ? "text-red-500" : "text-muted-foreground"
+ )}
+ >
+ {formatDurationMilliseconds(elapsed, { style: "short" })}
+ {total > 0 && (
+ <>/{formatDurationMilliseconds(total, { style: "short" })}</>
+ )}
+ </span>
+ </div>
+ <BarProgress
+ max={total || 1}
+ progress={total > 0 ? elapsed : 0}
+ activeClassName={overrun ? "bg-red-500" : "bg-emerald-500"}
+ />
+ </div>
+ );
+}
diff --git a/apps/mes/app/components/ImageZoomViewer.tsx b/apps/mes/app/components/ImageZoomViewer.tsx
new file mode 100644
index 0000000000..22fa532795
--- /dev/null
+++ b/apps/mes/app/components/ImageZoomViewer.tsx
@@ -0,0 +1,252 @@
+import { cn, IconButton } from "@carbon/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { LuX } from "react-icons/lu";
+
+const MIN_SCALE = 1;
+const MAX_SCALE = 6;
+
+const clampScale = (s: number) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
+
+/**
+ * Fullscreen reference-image viewer for the shop floor. Pointer-events based so the same
+ * code handles a mouse (wheel to zoom, drag to pan) and an iPad (two-finger pinch to zoom,
+ * one-finger drag to pan). Double-tap toggles between fit and a 2.5× zoom. Escape, the close
+ * button, or tapping the backdrop while at fit-scale dismisses it.
+ */
+type Annotation = {
+ id: string;
+ x: number;
+ y: number;
+ label?: string | null;
+ color?: string | null;
+ toolId?: string | null;
+};
+
+export function ImageZoomViewer({
+ open,
+ src,
+ caption,
+ annotations = [],
+ toolNameById,
+ alt = "Reference image",
+ onClose
+}: {
+ open: boolean;
+ src: string | null;
+ caption?: string | null;
+ annotations?: Annotation[];
+ toolNameById?: Map<string, string>;
+ alt?: string;
+ onClose: () => void;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [scale, setScale] = useState(1);
+ const [tx, setTx] = useState(0);
+ const [ty, setTy] = useState(0);
+
+ // Active pointers (id → screen position) + last pinch distance/midpoint for gesture math.
+ const pointers = useRef<Map<number, { x: number; y: number }>>(new Map());
+ const lastDist = useRef<number | null>(null);
+ const lastMid = useRef<{ x: number; y: number } | null>(null);
+ const lastTapAt = useRef(0);
+
+ const reset = useCallback(() => {
+ setScale(1);
+ setTx(0);
+ setTy(0);
+ pointers.current.clear();
+ lastDist.current = null;
+ lastMid.current = null;
+ }, []);
+
+ // Reset transform every time the viewer opens or the image changes.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset on open/src only
+ useEffect(() => {
+ if (open) reset();
+ }, [open, src, reset]);
+
+ // Escape to close.
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [open, onClose]);
+
+ if (!open || !src) return null;
+
+ // Focal point in container-center coordinates (origin at the container's center, matching
+ // the image's transform-origin), so zooming keeps the point under the cursor/fingers fixed.
+ const toFocal = (clientX: number, clientY: number) => {
+ const rect = containerRef.current?.getBoundingClientRect();
+ if (!rect) return { x: 0, y: 0 };
+ return {
+ x: clientX - (rect.left + rect.width / 2),
+ y: clientY - (rect.top + rect.height / 2)
+ };
+ };
+
+ // Zoom toward a focal point, anchoring it so it doesn't drift under the gesture. Each
+ // setter is called once (no nested setState) so StrictMode's double-invoke is harmless.
+ const zoomTo = (nextScaleRaw: number, focal: { x: number; y: number }) => {
+ const next = clampScale(nextScaleRaw);
+ if (next === 1) {
+ setScale(1);
+ setTx(0);
+ setTy(0);
+ return;
+ }
+ const ratio = next / scale;
+ setScale(next);
+ setTx((px) => focal.x - (focal.x - px) * ratio);
+ setTy((py) => focal.y - (focal.y - py) * ratio);
+ };
+
+ const onWheel = (e: React.WheelEvent) => {
+ e.preventDefault();
+ zoomTo(
+ scale * (e.deltaY < 0 ? 1.15 : 1 / 1.15),
+ toFocal(e.clientX, e.clientY)
+ );
+ };
+
+ const onPointerDown = (e: React.PointerEvent) => {
+ (e.target as Element).setPointerCapture?.(e.pointerId);
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+
+ // Double-tap / double-click to toggle zoom.
+ const now = Date.now();
+ if (pointers.current.size === 1) {
+ if (now - lastTapAt.current < 300) {
+ if (scale > 1) reset();
+ else zoomTo(2.5, toFocal(e.clientX, e.clientY));
+ }
+ lastTapAt.current = now;
+ }
+ };
+
+ const onPointerMove = (e: React.PointerEvent) => {
+ if (!pointers.current.has(e.pointerId)) return;
+ const prev = pointers.current.get(e.pointerId)!;
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+
+ const pts = [...pointers.current.values()];
+
+ if (pts.length >= 2) {
+ // Pinch: scale by the change in finger distance, pan by the midpoint shift.
+ const [a, b] = pts;
+ const dist = Math.hypot(a.x - b.x, a.y - b.y);
+ const midClient = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
+ const mid = toFocal(midClient.x, midClient.y);
+ if (lastDist.current != null && lastMid.current) {
+ zoomTo((scale * dist) / lastDist.current, mid);
+ setTx((px) => px + (mid.x - lastMid.current!.x));
+ setTy((py) => py + (mid.y - lastMid.current!.y));
+ }
+ lastDist.current = dist;
+ lastMid.current = mid;
+ return;
+ }
+
+ // Single pointer: pan only when zoomed in.
+ if (scale > 1) {
+ setTx((px) => px + (e.clientX - prev.x));
+ setTy((py) => py + (e.clientY - prev.y));
+ }
+ };
+
+ const endPointer = (e: React.PointerEvent) => {
+ pointers.current.delete(e.pointerId);
+ // Dropping below two pointers ends the active pinch — clear its anchors so the next
+ // single-finger move doesn't jump.
+ if (pointers.current.size < 2) {
+ lastDist.current = null;
+ lastMid.current = null;
+ }
+ };
+
+ return (
+ <div
+ className="fixed inset-0 z-[60] flex flex-col bg-black/90 backdrop-blur-sm"
+ // Tapping the backdrop at fit-scale closes; while zoomed it's reserved for panning.
+ onClick={(e) => {
+ if (e.target === e.currentTarget && scale === 1) onClose();
+ }}
+ >
+ <div className="flex shrink-0 items-center justify-end p-3">
+ <IconButton
+ aria-label="Close"
+ variant="ghost"
+ size="lg"
+ className="text-white hover:bg-white/10 hover:text-white"
+ icon={<LuX className="size-6" />}
+ onClick={onClose}
+ />
+ </div>
+
+ <div
+ ref={containerRef}
+ className="relative flex min-h-0 flex-1 select-none items-center justify-center overflow-hidden"
+ style={{ touchAction: "none" }}
+ onWheel={onWheel}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endPointer}
+ onPointerCancel={endPointer}
+ >
+ {/* Image + pins share one transformed wrapper so annotations pan/zoom with the art. */}
+ <div
+ className={cn(
+ "relative inline-flex max-h-full max-w-full will-change-transform",
+ scale > 1 ? "cursor-grab" : "cursor-zoom-in"
+ )}
+ style={{
+ transform: `translate(${tx}px, ${ty}px) scale(${scale})`,
+ transformOrigin: "center center"
+ }}
+ >
+ <img
+ src={src}
+ alt={alt}
+ draggable={false}
+ className="max-h-full max-w-full object-contain"
+ />
+ {annotations.map((pin, i) => {
+ const toolName = pin.toolId
+ ? toolNameById?.get(pin.toolId)
+ : undefined;
+ const title =
+ [`#${i + 1}`, toolName, pin.label].filter(Boolean).join(" · ") ||
+ undefined;
+ return (
+ <span
+ key={pin.id}
+ className="pointer-events-none absolute flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border-2 border-white text-xs font-semibold text-white shadow-md"
+ style={{
+ left: `${pin.x * 100}%`,
+ top: `${pin.y * 100}%`,
+ backgroundColor: pin.color ?? "#ef4444"
+ }}
+ title={title}
+ >
+ {i + 1}
+ </span>
+ );
+ })}
+ </div>
+ </div>
+
+ {caption ? (
+ <p className="shrink-0 px-4 pb-4 pt-2 text-center text-sm text-white/80">
+ {caption}
+ </p>
+ ) : (
+ <p className="shrink-0 px-4 pb-4 pt-2 text-center text-xs text-white/40">
+ Pinch or scroll to zoom · drag to pan · double-tap to reset
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/mes/app/components/Inspection/DispositionModal.tsx b/apps/mes/app/components/Inspection/DispositionModal.tsx
new file mode 100644
index 0000000000..831b78f7e6
--- /dev/null
+++ b/apps/mes/app/components/Inspection/DispositionModal.tsx
@@ -0,0 +1,515 @@
+import {
+ Hidden,
+ NumberControlled,
+ Select,
+ TextArea,
+ ValidatedForm
+} from "@carbon/form";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ Checkbox,
+ cn,
+ HStack,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Select as StaticSelect,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { LuTriangleAlert } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import ScrapReason from "~/components/JobOperation/components/ScrapReason";
+import { inspectionDispositionValidator } from "~/services/models";
+import type { IssueTypeListItem } from "~/services/types";
+import { path } from "~/utils/path";
+
+export type FailedFeatureSummary = {
+ label: string;
+ spec: string;
+ failedValues: string[];
+};
+
+export type AllocatableUnit = {
+ trackedEntityId: string;
+ label: string;
+ failed: boolean;
+};
+
+type UnitOutcome = "none" | "scrap" | "rework";
+
+type UpstreamOperation = {
+ id: string;
+ processId: string;
+ description: string | null;
+ jobMakeMethod: {
+ item: { name: string | null } | null;
+ } | null;
+};
+
+type DispositionModalProps = {
+ decision: "Reject" | "Partial";
+ inspectionId: string;
+ // Threads the jobOperationId through the action so it can post against the
+ // operation and redirect back to this inspection view.
+ operationId: string;
+ isSerial: boolean;
+ // Serial: the units the operator may allocate (failed first). Reject offers
+ // the whole open remainder; Partial offers only the failed units.
+ units: AllocatableUnit[];
+ // Non-serial: the ceiling on scrap + rework (failed count for Partial, the
+ // operation's remaining quantity for Reject).
+ maxAllocatable: number;
+ // Partial: how many passed units the disposition will complete (display).
+ completions: number;
+ issueTypes: IssueTypeListItem[];
+ summary: string;
+ failedFeatureSummary?: FailedFeatureSummary[];
+ eventIds: {
+ setupProductionEventId?: string;
+ laborProductionEventId?: string;
+ machineProductionEventId?: string;
+ };
+ onCancel: () => void;
+ onSubmit: () => void;
+};
+
+// The failed-set allocator: whenever a lot is rejected (or partially
+// accepted), the operator routes the failed units to Scrap (reason) or Rework
+// (an upstream operation — the routing clone re-inspects automatically), or
+// records the verdict only. One decision surface; the server recomputes and
+// clamps every bucket.
+const DispositionModal = ({
+ decision,
+ inspectionId,
+ operationId,
+ isSerial,
+ units,
+ maxAllocatable,
+ completions,
+ issueTypes,
+ summary,
+ failedFeatureSummary,
+ eventIds,
+ onCancel,
+ onSubmit
+}: DispositionModalProps) => {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{}>();
+ const targetsFetcher = useFetcher<{ operations: UpstreamOperation[] }>();
+ const submitted = useRef(false);
+ const loadedTargetsRef = useRef(false);
+
+ // Scrapping the failed units is the common outcome — default to it so the
+ // usual flow is one tap; "record only" is a bulk shortcut away.
+ const [unitOutcomes, setUnitOutcomes] = useState<Map<string, UnitOutcome>>(
+ () =>
+ new Map(
+ units.map((unit) => [
+ unit.trackedEntityId,
+ unit.failed ? "scrap" : "none"
+ ])
+ )
+ );
+ const [scrapQuantity, setScrapQuantity] = useState(
+ isSerial ? 0 : maxAllocatable
+ );
+ const [reworkQuantity, setReworkQuantity] = useState(0);
+ const [createNcr, setCreateNcr] = useState(decision === "Reject");
+ const [issueTypeId, setIssueTypeId] = useState<string>(
+ issueTypes[0]?.id ?? ""
+ );
+
+ useEffect(() => {
+ if (loadedTargetsRef.current) return;
+ loadedTargetsRef.current = true;
+ targetsFetcher.load(path.to.reworkTargets(operationId));
+ }, [operationId, targetsFetcher.load]);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && submitted.current) {
+ onSubmit();
+ submitted.current = false;
+ }
+ }, [fetcher.state, onSubmit]);
+
+ const targets = targetsFetcher.data?.operations ?? [];
+ const hasIssueTypes = issueTypes.length > 0;
+
+ const scrapEntityIds = useMemo(
+ () =>
+ units
+ .map((unit) => unit.trackedEntityId)
+ .filter((id) => unitOutcomes.get(id) === "scrap"),
+ [units, unitOutcomes]
+ );
+ const reworkEntityIds = useMemo(
+ () =>
+ units
+ .map((unit) => unit.trackedEntityId)
+ .filter((id) => unitOutcomes.get(id) === "rework"),
+ [units, unitOutcomes]
+ );
+
+ const scrapCount = isSerial ? scrapEntityIds.length : scrapQuantity;
+ const reworkCount = isSerial ? reworkEntityIds.length : reworkQuantity;
+ const overAllocated = !isSerial && scrapCount + reworkCount > maxAllocatable;
+
+ const setAll = (outcome: UnitOutcome) => {
+ setUnitOutcomes(
+ new Map(units.map((unit) => [unit.trackedEntityId, outcome]))
+ );
+ };
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onCancel();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.inspectionDisposition(inspectionId)}
+ validator={inspectionDispositionValidator}
+ defaultValues={{
+ decision,
+ operationId
+ }}
+ fetcher={fetcher}
+ onSubmit={() => {
+ submitted.current = true;
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>
+ {decision === "Reject" ? (
+ <Trans>Reject Lot</Trans>
+ ) : (
+ <Trans>Partial Disposition</Trans>
+ )}
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="decision" value={decision} />
+ <Hidden name="operationId" value={operationId} />
+ {isSerial ? (
+ <>
+ <Hidden
+ name="scrapEntityIds"
+ value={JSON.stringify(scrapEntityIds)}
+ />
+ <Hidden
+ name="reworkEntityIds"
+ value={JSON.stringify(reworkEntityIds)}
+ />
+ </>
+ ) : null}
+ {eventIds.setupProductionEventId ? (
+ <Hidden
+ name="setupProductionEventId"
+ value={eventIds.setupProductionEventId}
+ />
+ ) : null}
+ {eventIds.laborProductionEventId ? (
+ <Hidden
+ name="laborProductionEventId"
+ value={eventIds.laborProductionEventId}
+ />
+ ) : null}
+ {eventIds.machineProductionEventId ? (
+ <Hidden
+ name="machineProductionEventId"
+ value={eventIds.machineProductionEventId}
+ />
+ ) : null}
+ <input
+ type="hidden"
+ name="createNcr"
+ value={createNcr ? "true" : "false"}
+ />
+ <input
+ type="hidden"
+ name="nonConformanceTypeId"
+ value={createNcr ? issueTypeId : ""}
+ />
+
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">{summary}</p>
+ {decision === "Partial" && completions > 0 ? (
+ <p className="text-sm text-emerald-600 dark:text-emerald-400">
+ <Trans>{completions} passed unit(s) will be completed.</Trans>
+ </p>
+ ) : null}
+ {failedFeatureSummary && failedFeatureSummary.length > 0 && (
+ <div className="w-full rounded-md border p-3">
+ <p className="mb-1 text-xs font-medium text-muted-foreground">
+ <Trans>Failed features</Trans>
+ </p>
+ <ul className="flex flex-col gap-0.5">
+ {failedFeatureSummary.map((feature) => (
+ <li
+ key={feature.label}
+ className="font-mono text-xs text-red-500"
+ >
+ {feature.label}
+ {feature.spec ? ` (${feature.spec})` : ""}
+ {feature.failedValues.length > 0
+ ? `: ${feature.failedValues.join(", ")}`
+ : ""}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {isSerial ? (
+ <div className="flex w-full flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <Label>
+ {decision === "Reject" ? (
+ <Trans>Allocate units</Trans>
+ ) : (
+ <Trans>Allocate failed units</Trans>
+ )}
+ </Label>
+ <div className="flex gap-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAll("scrap")}
+ >
+ <Trans>All scrap</Trans>
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAll("rework")}
+ >
+ <Trans>All rework</Trans>
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAll("none")}
+ >
+ <Trans>Record only</Trans>
+ </Button>
+ </div>
+ </div>
+ <div className="max-h-48 w-full overflow-y-auto rounded-lg border">
+ {units.length === 0 ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ <Trans>No open units to allocate</Trans>
+ </div>
+ ) : (
+ units.map((unit) => {
+ const outcome =
+ unitOutcomes.get(unit.trackedEntityId) ?? "none";
+ return (
+ <div
+ key={unit.trackedEntityId}
+ className="flex items-center justify-between gap-3 border-b px-3 py-2 last:border-b-0"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-mono text-sm">
+ {unit.label}
+ </span>
+ {unit.failed ? (
+ <span className="shrink-0 text-xs font-medium text-red-500">
+ <Trans>Failed</Trans>
+ </span>
+ ) : null}
+ </div>
+ <div className="flex shrink-0 overflow-hidden rounded-md border">
+ {(
+ [
+ ["none", t`Record`],
+ ["scrap", t`Scrap`],
+ ["rework", t`Rework`]
+ ] as const
+ ).map(([value, label]) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() =>
+ setUnitOutcomes((prev) => {
+ const next = new Map(prev);
+ next.set(unit.trackedEntityId, value);
+ return next;
+ })
+ }
+ className={cn(
+ "px-2 py-1 text-xs font-medium transition-colors",
+ outcome === value
+ ? value === "scrap"
+ ? "bg-red-500 text-white"
+ : value === "rework"
+ ? "bg-blue-500 text-white"
+ : "bg-accent text-accent-foreground"
+ : "hover:bg-muted"
+ )}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="grid w-full grid-cols-2 gap-4">
+ <NumberControlled
+ name="scrapQuantity"
+ label={t`Scrap quantity`}
+ value={scrapQuantity}
+ onChange={setScrapQuantity}
+ minValue={0}
+ maxValue={maxAllocatable}
+ />
+ <NumberControlled
+ name="reworkQuantity"
+ label={t`Rework quantity`}
+ value={reworkQuantity}
+ onChange={setReworkQuantity}
+ minValue={0}
+ maxValue={maxAllocatable}
+ />
+ </div>
+ )}
+ {!isSerial ? (
+ <p
+ className={cn(
+ "text-xs",
+ overAllocated
+ ? "font-medium text-red-500"
+ : "text-muted-foreground"
+ )}
+ >
+ <Trans>
+ Up to {maxAllocatable} unit(s) can be allocated; the rest is
+ recorded without a posting.
+ </Trans>
+ </p>
+ ) : null}
+
+ {scrapCount > 0 ? (
+ <ScrapReason name="scrapReasonId" label={t`Scrap Reason`} />
+ ) : null}
+
+ {reworkCount > 0 ? (
+ <>
+ <Select
+ name="targetOperationId"
+ label={t`Go back to operation`}
+ options={targets.map((op) => ({
+ value: op.id,
+ label: op.description || op.processId
+ }))}
+ />
+ <TextArea
+ name="reworkReason"
+ label={t`Reason for rework`}
+ placeholder={t`Describe what needs to be reworked...`}
+ />
+ </>
+ ) : null}
+
+ <label className="flex w-full cursor-pointer items-center gap-2">
+ <Checkbox
+ isChecked={createNcr}
+ onCheckedChange={(checked) => setCreateNcr(!!checked)}
+ />
+ <span className="text-sm font-medium">
+ <Trans>Open an NCR for MRB disposition</Trans>
+ </span>
+ </label>
+ {createNcr &&
+ (hasIssueTypes ? (
+ <div className="flex w-full flex-col gap-2">
+ <Label htmlFor="nonConformanceTypeId">
+ <Trans>Issue Type</Trans>
+ </Label>
+ <StaticSelect
+ value={issueTypeId}
+ onValueChange={setIssueTypeId}
+ >
+ <SelectTrigger id="nonConformanceTypeId">
+ <SelectValue placeholder={t`Select an issue type`} />
+ </SelectTrigger>
+ <SelectContent>
+ {issueTypes.map((type) => (
+ <SelectItem key={type.id} value={type.id}>
+ {type.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </StaticSelect>
+ </div>
+ ) : (
+ <Alert variant="warning">
+ <LuTriangleAlert className="size-4" />
+ <AlertTitle>
+ <Trans>No issue types configured</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ The lot will still be dispositioned, but an NCR cannot
+ be created until at least one Issue Type is configured.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ ))}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button variant="secondary" onClick={onCancel}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ variant={decision === "Reject" ? "destructive" : "primary"}
+ type="submit"
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" ||
+ overAllocated ||
+ (createNcr && hasIssueTypes && !issueTypeId)
+ }
+ >
+ {decision === "Reject" ? (
+ <Trans>Reject Lot</Trans>
+ ) : (
+ <Trans>Record Partial</Trans>
+ )}
+ </Button>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default DispositionModal;
diff --git a/apps/mes/app/components/Inspection/InspectionDrawingPane.tsx b/apps/mes/app/components/Inspection/InspectionDrawingPane.tsx
new file mode 100644
index 0000000000..ce20de9904
--- /dev/null
+++ b/apps/mes/app/components/Inspection/InspectionDrawingPane.tsx
@@ -0,0 +1,211 @@
+import { IconButton } from "@carbon/react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { LuChevronLeft, LuChevronRight } from "react-icons/lu";
+import { Circle, Group, Layer, Stage, Text } from "react-konva";
+import { Document, Page } from "react-pdf";
+import "react-pdf/dist/Page/AnnotationLayer.css";
+import "react-pdf/dist/Page/TextLayer.css";
+
+const CALLOUT_STROKE = "#f97316";
+
+export type DrawingBalloon = {
+ id: string;
+ inspectionFeatureId: string;
+ pageNumber: number;
+ xCoordinate: number;
+ yCoordinate: number;
+ label: string;
+};
+
+type InspectionDrawingPaneProps = {
+ pdfUrl: string;
+ balloons: DrawingBalloon[];
+ activeFeatureId: string | null;
+ onBalloonClick: (inspectionFeatureId: string) => void;
+};
+
+// Read-only PDF + balloon viewer for the inbound inspection execution screen.
+// A stripped-down sibling of InspectionDocumentEditor's viewer: no ballooning,
+// no zoom box — fit-to-width with page navigation and clickable balloons.
+// The pdf.js worker is configured globally in entry.client.tsx. This module
+// must be imported lazily (ClientOnly) — react-pdf and react-konva are
+// client-only.
+const InspectionDrawingPane = ({
+ pdfUrl,
+ balloons,
+ activeFeatureId,
+ onBalloonClick
+}: InspectionDrawingPaneProps) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const pageWrapperRef = useRef<HTMLDivElement>(null);
+ const [containerWidth, setContainerWidth] = useState(0);
+ const [overlayHeight, setOverlayHeight] = useState(0);
+ const [numPages, setNumPages] = useState(0);
+ const [page, setPage] = useState(1);
+ const [pageRendered, setPageRendered] = useState(false);
+
+ // Fit-to-width: track the container so the Page re-renders on pane resize.
+ useEffect(() => {
+ if (!containerRef.current) return;
+ const ro = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width;
+ if (width) setContainerWidth(width);
+ });
+ ro.observe(containerRef.current);
+ return () => ro.disconnect();
+ }, []);
+
+ // The Konva overlay matches the rendered page's real height.
+ useEffect(() => {
+ if (!pageWrapperRef.current) return;
+ const ro = new ResizeObserver((entries) => {
+ const height = entries[0]?.contentRect.height ?? 0;
+ if (height > 0) setOverlayHeight(height);
+ });
+ ro.observe(pageWrapperRef.current);
+ return () => ro.disconnect();
+ }, []);
+
+ // Balloon click in the grid direction: jump to the active feature's page.
+ useEffect(() => {
+ if (!activeFeatureId) return;
+ const balloon = balloons.find(
+ (b) => b.inspectionFeatureId === activeFeatureId
+ );
+ if (balloon && balloon.pageNumber !== page) {
+ setPage(balloon.pageNumber);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeFeatureId]);
+
+ const pageBalloons = useMemo(
+ () => balloons.filter((b) => b.pageNumber === page),
+ [balloons, page]
+ );
+
+ const balloonRadius = Math.max(10, containerWidth * 0.012);
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ {numPages > 1 && (
+ <div className="flex shrink-0 items-center justify-center gap-3 border-b border-border bg-card px-3 py-2.5 shadow-sm">
+ <IconButton
+ type="button"
+ aria-label="Previous page"
+ variant="secondary"
+ size="sm"
+ icon={<LuChevronLeft className="h-4 w-4" />}
+ isDisabled={page <= 1}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
+ />
+ <span className="min-w-[8.5rem] select-none text-center text-sm font-medium tabular-nums text-foreground">
+ Page {page} of {numPages}
+ </span>
+ <IconButton
+ type="button"
+ aria-label="Next page"
+ variant="secondary"
+ size="sm"
+ icon={<LuChevronRight className="h-4 w-4" />}
+ isDisabled={page >= numPages}
+ onClick={() => setPage((p) => Math.min(numPages, p + 1))}
+ />
+ </div>
+ )}
+ <div ref={containerRef} className="relative flex-1 overflow-auto">
+ <div
+ className="relative select-none"
+ style={{ width: containerWidth > 0 ? containerWidth : "100%" }}
+ >
+ <div ref={pageWrapperRef} className="pointer-events-none">
+ <Document
+ file={pdfUrl}
+ onLoadSuccess={(pdf) => {
+ setNumPages(pdf.numPages);
+ setPage(1);
+ }}
+ >
+ {containerWidth > 0 ? (
+ <Page
+ key={page}
+ pageNumber={page}
+ width={containerWidth}
+ renderTextLayer={false}
+ renderAnnotationLayer={false}
+ className="w-full"
+ onRenderSuccess={() => setPageRendered(true)}
+ />
+ ) : null}
+ </Document>
+ </div>
+
+ {pageRendered && containerWidth > 0 && overlayHeight > 0 && (
+ <div className="pointer-events-auto absolute inset-0 z-[9]">
+ <Stage width={containerWidth} height={overlayHeight} listening>
+ <Layer>
+ {pageBalloons.map((balloon) => {
+ // DB coordinates are normalized 0–1.
+ const x = balloon.xCoordinate * containerWidth;
+ const y = balloon.yCoordinate * overlayHeight;
+ const isActive =
+ balloon.inspectionFeatureId === activeFeatureId;
+ return (
+ <Group
+ key={balloon.id}
+ onClick={() =>
+ onBalloonClick(balloon.inspectionFeatureId)
+ }
+ onTap={() =>
+ onBalloonClick(balloon.inspectionFeatureId)
+ }
+ onMouseEnter={(e) => {
+ const stage = e.target.getStage();
+ if (stage) stage.container().style.cursor = "pointer";
+ }}
+ onMouseLeave={(e) => {
+ const stage = e.target.getStage();
+ if (stage) stage.container().style.cursor = "";
+ }}
+ >
+ <Circle
+ x={x}
+ y={y}
+ radius={balloonRadius}
+ stroke={CALLOUT_STROKE}
+ strokeWidth={isActive ? 3 : 2}
+ fill={
+ isActive
+ ? "rgba(249,115,22,0.25)"
+ : "rgba(255,255,255,0.75)"
+ }
+ />
+ <Text
+ x={x - balloonRadius}
+ y={y - balloonRadius * 0.55}
+ width={balloonRadius * 2}
+ align="center"
+ text={balloon.label}
+ fontSize={balloonRadius}
+ fontStyle="bold"
+ fill={CALLOUT_STROKE}
+ listening={false}
+ />
+ </Group>
+ );
+ })}
+ </Layer>
+ </Stage>
+ </div>
+ )}
+ </div>
+ </div>
+ {pdfUrl === "" && (
+ <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
+ No drawing available
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default InspectionDrawingPane;
diff --git a/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx b/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx
new file mode 100644
index 0000000000..0c04d0a69b
--- /dev/null
+++ b/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx
@@ -0,0 +1,593 @@
+import { cn, toast } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { LuCheck, LuX } from "react-icons/lu";
+import type {
+ InspectionMeasurement,
+ InspectionSample,
+ InspectionSamplingPlan
+} from "~/services/types";
+import { path } from "~/utils/path";
+
+// A cell save's response payload (the measurement action returns it so the
+// matrix can update without a revalidation roundtrip). Same contract as the
+// ERP quality module's InspectionMeasurementGrid.
+export type MeasurementSaveResult = {
+ sampleId: string;
+ measurementId: string;
+ measurementStatus: "Pending" | "Passed" | "Failed";
+ sampleStatus: "Pending" | "Passed" | "Failed";
+ inspectionFeatureId: string;
+ columnIndex: number;
+ value: number | null;
+ passed: boolean | null;
+};
+
+// Synthetic feature id for the single pass/fail row shown when the lot has no
+// inspection document. Its cells write the sample's status directly (via the
+// sample route) rather than a per-feature measurement.
+export const OVERALL_ROW_ID = "__overall__";
+
+type MatrixRow = {
+ featureId: string;
+ label: string;
+ description: string | null;
+ isNumeric: boolean;
+ specLabel: string;
+ sampleSize: number;
+ acceptanceNumber: number;
+ rejectionNumber: number;
+};
+
+type InspectionMeasurementMatrixProps = {
+ inspectionId: string;
+ isReadOnly: boolean;
+ isSerial: boolean;
+ features: InspectionSamplingPlan[];
+ samples: InspectionSample[];
+ measurements: InspectionMeasurement[];
+ maxSampleSize: number;
+ // Lot size caps how many sample columns can exist — a feature's n is the
+ // required minimum, but the inspector may record up to the whole lot.
+ lotSize: number;
+ // Lot-level acceptance/rejection numbers, used only for the synthetic
+ // "Overall result" row shown when the lot has no inspection-document features.
+ lotAcceptanceNumber: number;
+ lotRejectionNumber: number;
+ activeFeatureId: string | null;
+ onActiveFeatureChange: (id: string | null) => void;
+ onMeasurementSaved: (result: MeasurementSaveResult) => void;
+};
+
+function parseSpecNumber(value: string | null | undefined): number | null {
+ if (value == null) return null;
+ const trimmed = value.trim();
+ if (trimmed === "") return null;
+ const parsed = Number(trimmed.replace(/^\+/, ""));
+ return Number.isNaN(parsed) ? null : parsed;
+}
+
+// Shop-floor features × samples matrix. Implements the same per-cell quiet
+// POST contract as the ERP grid (measurement route for feature cells,
+// sample route for the "Overall result" row) with plain touch-sized cells
+// instead of the ERP Table's inline-editing machinery.
+const InspectionMeasurementMatrix = ({
+ inspectionId,
+ isReadOnly,
+ isSerial,
+ features,
+ samples,
+ measurements,
+ maxSampleSize,
+ lotSize,
+ lotAcceptanceNumber,
+ lotRejectionNumber,
+ activeFeatureId,
+ onActiveFeatureChange,
+ onMeasurementSaved
+}: InspectionMeasurementMatrixProps) => {
+ const { t } = useLingui();
+
+ // The matrix ignores plan rows whose live feature was deleted from the document.
+ const liveFeatures = useMemo(
+ () =>
+ features
+ .filter((f) => f.inspectionFeature != null)
+ .sort((a, b) => {
+ const fa = a.inspectionFeature!;
+ const fb = b.inspectionFeature!;
+ return (
+ (fa.pageNumber ?? 1) - (fb.pageNumber ?? 1) ||
+ fa.label.localeCompare(fb.label, undefined, { numeric: true })
+ );
+ }),
+ [features]
+ );
+ const hasFeatures = liveFeatures.length > 0;
+
+ const rows = useMemo<MatrixRow[]>(() => {
+ if (!hasFeatures) {
+ return [
+ {
+ featureId: OVERALL_ROW_ID,
+ label: t`Overall result`,
+ description: null,
+ isNumeric: false,
+ specLabel: "",
+ sampleSize: maxSampleSize,
+ acceptanceNumber: lotAcceptanceNumber,
+ rejectionNumber: lotRejectionNumber
+ }
+ ];
+ }
+ return liveFeatures.map((lotFeature) => {
+ const feature = lotFeature.inspectionFeature!;
+ const nominal = parseSpecNumber(feature.nominalValue);
+ const isNumeric = feature.type === "Measurement" && nominal != null;
+ const specLabel = [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ");
+ return {
+ featureId: feature.id,
+ label: feature.label,
+ description: feature.description,
+ isNumeric,
+ specLabel,
+ sampleSize: lotFeature.sampleSize,
+ acceptanceNumber: lotFeature.acceptanceNumber,
+ rejectionNumber: lotFeature.rejectionNumber
+ };
+ });
+ }, [
+ hasFeatures,
+ liveFeatures,
+ maxSampleSize,
+ lotAcceptanceNumber,
+ lotRejectionNumber,
+ t
+ ]);
+
+ // Column model: serial lots get one column per scanned sample; non-serial
+ // lots pre-create columns up to the max required n plus one spare, growing
+ // as columns are used, capped at the lot size (sample rows are created
+ // server-side on the first measurement into a column). n is a minimum —
+ // recording MORE than n samples is always allowed, up to the full lot.
+ const columnCount = isSerial
+ ? samples.length
+ : Math.min(lotSize, Math.max(maxSampleSize, samples.length + 1));
+
+ // Column index -> sample id. Anonymous columns resolve lazily from save
+ // responses; keyed by index because unsaved columns have no id yet.
+ const [sampleIdByColumn, setSampleIdByColumn] = useState<
+ Record<number, string>
+ >({});
+ useEffect(() => {
+ setSampleIdByColumn((prev) => {
+ const next = { ...prev };
+ samples.forEach((sample, index) => {
+ next[index] = sample.id;
+ });
+ return next;
+ });
+ }, [samples]);
+
+ // Measurement status + value per cell, seeded from the loader and patched by
+ // save responses (per-cell saves are quiet — no revalidation).
+ const [statusByCell, setStatusByCell] = useState<Record<string, string>>({});
+ const [valueByCell, setValueByCell] = useState<Record<string, number | null>>(
+ {}
+ );
+
+ const measurementFor = useCallback(
+ (sampleId: string | undefined, featureId: string) =>
+ sampleId
+ ? measurements.find(
+ (m) =>
+ m.inspectionSampleId === sampleId &&
+ m.inspectionFeatureId === featureId
+ )
+ : undefined,
+ [measurements]
+ );
+
+ const cellStatus = useCallback(
+ (columnIndex: number, featureId: string): string | undefined => {
+ const override = statusByCell[`${columnIndex}:${featureId}`];
+ if (override) return override;
+ // The "Overall result" row has no measurement — its verdict is the
+ // sample's own status (Pending shows as an untoggled cell).
+ if (featureId === OVERALL_ROW_ID) {
+ return samples[columnIndex]?.status;
+ }
+ return measurementFor(sampleIdByColumn[columnIndex], featureId)?.status;
+ },
+ [statusByCell, sampleIdByColumn, measurementFor, samples]
+ );
+
+ const cellValue = useCallback(
+ (columnIndex: number, featureId: string): number | null => {
+ const key = `${columnIndex}:${featureId}`;
+ if (key in valueByCell) return valueByCell[key];
+ const measurement = measurementFor(
+ sampleIdByColumn[columnIndex],
+ featureId
+ );
+ return measurement?.value == null ? null : Number(measurement.value);
+ },
+ [valueByCell, sampleIdByColumn, measurementFor]
+ );
+
+ // Document-driven cell: record a per-feature measurement.
+ const persistMeasurement = useCallback(
+ async (
+ row: MatrixRow,
+ columnIndex: number,
+ payload: { value?: string; passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ const formData = new FormData();
+ formData.set("inspectionId", inspectionId);
+ const sampleId = sampleIdByColumn[columnIndex];
+ if (sampleId) formData.set("sampleId", sampleId);
+ formData.set("inspectionFeatureId", row.featureId);
+ if (payload.value !== undefined) formData.set("value", payload.value);
+ if (payload.passed !== undefined) formData.set("passed", payload.passed);
+
+ const response = await fetch(
+ path.to.inspectionMeasurement(inspectionId),
+ { method: "post", body: formData }
+ );
+ const body = (await response.json().catch(() => null)) as {
+ data?: {
+ sampleId: string;
+ measurementId: string;
+ measurementStatus: string;
+ sampleStatus: string;
+ } | null;
+ error?: { message: string } | null;
+ } | null;
+
+ if (!response.ok || !body?.data || body.error) {
+ toast.error(body?.error?.message ?? t`Failed to save measurement`);
+ return null;
+ }
+
+ return {
+ sampleId: body.data.sampleId,
+ measurementId: body.data.measurementId,
+ measurementStatus: body.data
+ .measurementStatus as MeasurementSaveResult["measurementStatus"],
+ sampleStatus: body.data
+ .sampleStatus as MeasurementSaveResult["sampleStatus"],
+ inspectionFeatureId: row.featureId,
+ columnIndex,
+ value:
+ payload.value !== undefined && payload.value !== ""
+ ? Number(payload.value)
+ : null,
+ passed: payload.passed !== undefined ? payload.passed === "true" : null
+ };
+ },
+ [inspectionId, sampleIdByColumn, t]
+ );
+
+ // No-document cell: set the sample's Pass/Fail status directly. Serial
+ // columns already carry a scanned tracked entity (upsert by it); anonymous
+ // columns update in place by sampleId once one exists.
+ const persistOverall = useCallback(
+ async (
+ columnIndex: number,
+ payload: { passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ const status = payload.passed === "true" ? "Passed" : "Failed";
+ const formData = new FormData();
+ formData.set("inspectionId", inspectionId);
+ formData.set("status", status);
+ formData.set("quiet", "true");
+ const sampleId = sampleIdByColumn[columnIndex];
+ if (sampleId) formData.set("sampleId", sampleId);
+ const trackedEntityId = samples[columnIndex]?.trackedEntityId;
+ if (trackedEntityId) formData.set("trackedEntityId", trackedEntityId);
+
+ const response = await fetch(path.to.inspectionSample(inspectionId), {
+ method: "post",
+ body: formData
+ });
+ const body = (await response.json().catch(() => null)) as {
+ sampleId?: string;
+ error?: { message: string } | null;
+ } | null;
+
+ if (!response.ok || !body?.sampleId || body.error) {
+ toast.error(body?.error?.message ?? t`Failed to save result`);
+ return null;
+ }
+
+ return {
+ sampleId: body.sampleId,
+ measurementId: "",
+ measurementStatus: status,
+ sampleStatus: status,
+ inspectionFeatureId: OVERALL_ROW_ID,
+ columnIndex,
+ value: null,
+ passed: status === "Passed"
+ };
+ },
+ [inspectionId, sampleIdByColumn, samples, t]
+ );
+
+ const persistCell = useCallback(
+ async (
+ row: MatrixRow,
+ columnIndex: number,
+ payload: { value?: string; passed?: "true" | "false" }
+ ): Promise<MeasurementSaveResult | null> => {
+ const result =
+ row.featureId === OVERALL_ROW_ID
+ ? await persistOverall(columnIndex, payload)
+ : await persistMeasurement(row, columnIndex, payload);
+ if (!result) return null;
+
+ setSampleIdByColumn((prev) =>
+ prev[columnIndex] === result.sampleId
+ ? prev
+ : { ...prev, [columnIndex]: result.sampleId }
+ );
+ setStatusByCell((prev) => ({
+ ...prev,
+ [`${columnIndex}:${row.featureId}`]: result.measurementStatus
+ }));
+ setValueByCell((prev) => ({
+ ...prev,
+ [`${columnIndex}:${row.featureId}`]: result.value
+ }));
+ onMeasurementSaved(result);
+ return result;
+ },
+ [persistMeasurement, persistOverall, onMeasurementSaved]
+ );
+
+ const columnHeaders = useMemo(
+ () =>
+ Array.from({ length: columnCount }, (_, index) => {
+ const sample = samples[index];
+ // MES entity display convention (AssemblyView precedent): readableId,
+ // else the first 8 characters of the entity id.
+ const entityLabel =
+ sample?.trackedEntity?.readableId ??
+ sample?.trackedEntityId?.slice(0, 8);
+ return {
+ label: isSerial && entityLabel ? entityLabel : `${index + 1}`,
+ status: sample?.status ?? "Pending"
+ };
+ }),
+ [columnCount, samples, isSerial]
+ );
+
+ if (columnCount === 0) {
+ return (
+ <div className="flex h-full items-center justify-center p-8 text-center text-sm text-muted-foreground">
+ {isSerial
+ ? t`Scan a tracked entity to add the first sample column.`
+ : t`No samples required.`}
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-0 flex-1 overflow-auto">
+ <table className="w-full border-separate border-spacing-0 text-sm">
+ <thead className="sticky top-0 z-20">
+ <tr>
+ <th className="sticky left-0 z-30 min-w-[220px] border-b border-r border-border bg-card px-3 py-2 text-left font-medium text-muted-foreground">
+ {hasFeatures ? (
+ <span>{t`Feature`}</span>
+ ) : (
+ <span>{t`Result`}</span>
+ )}
+ </th>
+ {columnHeaders.map((column, index) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: columns are positional
+ <th
+ key={`column-${index}`}
+ className="min-w-[96px] border-b border-r border-border bg-card px-2 py-2 text-center font-medium last:border-r-0"
+ >
+ <div className="flex flex-col items-center gap-0.5">
+ <span className="max-w-[140px] truncate font-mono text-xs">
+ {column.label}
+ </span>
+ </div>
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => {
+ const isActive = hasFeatures && activeFeatureId === row.featureId;
+ return (
+ <tr
+ key={row.featureId}
+ className={cn(isActive && "bg-accent/40")}
+ >
+ <td
+ className={cn(
+ "sticky left-0 z-10 cursor-pointer border-b border-r border-border bg-card px-3 py-2 align-top",
+ isActive && "bg-accent"
+ )}
+ onClick={() =>
+ hasFeatures
+ ? onActiveFeatureChange(isActive ? null : row.featureId)
+ : undefined
+ }
+ >
+ <div className="flex items-start gap-3">
+ {row.featureId !== OVERALL_ROW_ID ? (
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted font-mono text-sm font-semibold text-foreground tabular-nums">
+ {row.label}
+ </div>
+ ) : null}
+ <div className="flex min-w-0 flex-col gap-1">
+ <div
+ className="line-clamp-2 text-sm font-semibold text-foreground"
+ title={row.description ?? undefined}
+ >
+ {row.description ??
+ (row.featureId === OVERALL_ROW_ID ? row.label : "—")}
+ </div>
+ {row.specLabel ? (
+ <div className="font-mono text-xs text-muted-foreground">
+ {row.specLabel}
+ </div>
+ ) : null}
+ <div className="text-xs text-muted-foreground tabular-nums">
+ n {row.sampleSize} · Ac {row.acceptanceNumber} · Re{" "}
+ {row.rejectionNumber}
+ </div>
+ </div>
+ </div>
+ </td>
+ {Array.from({ length: columnCount }, (_, columnIndex) => {
+ const disabled = isReadOnly;
+ const status = cellStatus(columnIndex, row.featureId);
+ return (
+ // biome-ignore lint/suspicious/noArrayIndexKey: columns are positional
+ <td
+ key={`${row.featureId}-${columnIndex}`}
+ className="h-px border-b border-r border-border p-0 text-center align-middle last:border-r-0"
+ >
+ {row.isNumeric ? (
+ <NumericCell
+ disabled={disabled}
+ status={status}
+ value={cellValue(columnIndex, row.featureId)}
+ onCommit={(value) =>
+ persistCell(row, columnIndex, { value })
+ }
+ />
+ ) : (
+ <PassFailCell
+ disabled={disabled}
+ status={status}
+ onToggle={(passed) =>
+ persistCell(row, columnIndex, { passed })
+ }
+ />
+ )}
+ </td>
+ );
+ })}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+function statusClasses(status: string | undefined) {
+ switch (status) {
+ case "Passed":
+ return "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400";
+ case "Failed":
+ return "bg-red-500/10 text-red-600 dark:text-red-400";
+ default:
+ return "bg-transparent text-foreground hover:bg-muted/40 focus:bg-background";
+ }
+}
+
+function NumericCell({
+ disabled,
+ status,
+ value,
+ onCommit
+}: {
+ disabled: boolean;
+ status: string | undefined;
+ value: number | null;
+ onCommit: (value: string) => void;
+}) {
+ const [draft, setDraft] = useState(value == null ? "" : String(value));
+
+ // Re-sync when the persisted value changes underneath (e.g. save response).
+ useEffect(() => {
+ setDraft(value == null ? "" : String(value));
+ }, [value]);
+
+ const commit = () => {
+ const persisted = value == null ? "" : String(value);
+ if (draft.trim() === persisted) return;
+ onCommit(draft.trim());
+ };
+
+ return (
+ <input
+ type="text"
+ inputMode="decimal"
+ disabled={disabled}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.currentTarget.blur();
+ }
+ }}
+ className={cn(
+ "block h-full min-h-12 w-full min-w-[88px] text-center font-mono text-base tabular-nums outline-none transition-colors focus:ring-2 focus:ring-inset focus:ring-ring disabled:cursor-not-allowed disabled:opacity-40",
+ statusClasses(status)
+ )}
+ />
+ );
+}
+
+function PassFailCell({
+ disabled,
+ status,
+ onToggle
+}: {
+ disabled: boolean;
+ status: string | undefined;
+ onToggle: (passed: "true" | "false") => void;
+}) {
+ return (
+ <div className="flex h-full min-h-12 items-stretch">
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label="Pass"
+ onClick={() => onToggle("true")}
+ className={cn(
+ "flex flex-1 items-center justify-center border-r border-border transition-colors disabled:cursor-not-allowed disabled:opacity-40",
+ status === "Passed"
+ ? "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400"
+ : "text-muted-foreground hover:bg-accent"
+ )}
+ >
+ <LuCheck className="size-5" />
+ </button>
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label="Fail"
+ onClick={() => onToggle("false")}
+ className={cn(
+ "flex flex-1 items-center justify-center transition-colors disabled:cursor-not-allowed disabled:opacity-40",
+ status === "Failed"
+ ? "bg-red-500/15 text-red-600 dark:text-red-400"
+ : "text-muted-foreground hover:bg-accent"
+ )}
+ >
+ <LuX className="size-5" />
+ </button>
+ </div>
+ );
+}
+
+export default InspectionMeasurementMatrix;
diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsx
new file mode 100644
index 0000000000..dd4ce9c4d0
--- /dev/null
+++ b/apps/mes/app/components/Inspection/InspectionView.tsx
@@ -0,0 +1,1352 @@
+import {
+ Badge,
+ BottomSheet,
+ BottomSheetBody,
+ BottomSheetContent,
+ Button,
+ ClientOnly,
+ cn,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ SidebarTrigger,
+ Spinner,
+ useDisclosure,
+ useMode,
+ VStack
+} from "@carbon/react";
+import { getLocalTimeZone } from "@internationalized/date";
+import { Trans, useLingui } from "@lingui/react/macro";
+import {
+ lazy,
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import {
+ LuCheck,
+ LuCheckCheck,
+ LuChevronDown,
+ LuChevronUp,
+ LuContrast,
+ LuEllipsisVertical,
+ LuFlag,
+ LuGitPullRequest,
+ LuPause,
+ LuPlay,
+ LuScan,
+ LuTrash,
+ LuX
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { QualityIssueModal } from "~/components/JobOperation/components/QualityIssueModal";
+import { QuantityModal } from "~/components/JobOperation/components/QuantityModal";
+import { ReworkModal } from "~/components/JobOperation/components/ReworkModal";
+import { useUser } from "~/hooks";
+import type {
+ InspectionMeasurement,
+ Inspection as InspectionRow,
+ InspectionSample,
+ InspectionSamplingPlan,
+ IssueTypeListItem,
+ Job,
+ OperationWithDetails,
+ ProductionEvent,
+ TrackedEntity
+} from "~/services/types";
+import { path } from "~/utils/path";
+import type { AllocatableUnit, FailedFeatureSummary } from "./DispositionModal";
+import DispositionModal from "./DispositionModal";
+import type { MeasurementSaveResult } from "./InspectionMeasurementMatrix";
+import InspectionMeasurementMatrix from "./InspectionMeasurementMatrix";
+import ScanInspectionSample from "./ScanInspectionSample";
+
+const InspectionDrawingPane = lazy(() => import("./InspectionDrawingPane"));
+
+// Vertical-stack sizing, mirrored from the ERP quality InspectionView: the PDF
+// pane keeps a pinned height while the features table is expanded; a draggable
+// splitter trades space between them.
+const STACK_SPLITTER_H = 8;
+const MIN_PDF_PANE_PX = 160;
+
+/** When the table is expanded it keeps at least half the stack; PDF height is capped accordingly. */
+function clampPdfPaneHeight(
+ pdfPx: number,
+ stackH: number,
+ gridExpanded: boolean
+): number {
+ if (!gridExpanded || stackH <= STACK_SPLITTER_H + MIN_PDF_PANE_PX) {
+ return Math.max(MIN_PDF_PANE_PX, pdfPx);
+ }
+ const minGrid = stackH * 0.5;
+ const maxPdf = Math.max(MIN_PDF_PANE_PX, stackH - STACK_SPLITTER_H - minGrid);
+ return Math.min(maxPdf, Math.max(MIN_PDF_PANE_PX, pdfPx));
+}
+
+type DrawingBalloonRow = {
+ id: string;
+ inspectionFeatureId: string;
+ pageNumber: number;
+ xCoordinate: number;
+ yCoordinate: number;
+};
+
+type WorkType = "Setup" | "Labor" | "Machine";
+
+type InspectionViewProps = {
+ operationId: string;
+ job: Job;
+ operation: OperationWithDetails;
+ inspection: InspectionRow & {
+ item?: {
+ readableId: string | null;
+ name: string | null;
+ type: string | null;
+ itemTrackingType: string | null;
+ } | null;
+ };
+ samples: InspectionSample[];
+ features: InspectionSamplingPlan[];
+ measurements: InspectionMeasurement[];
+ balloons: DrawingBalloonRow[];
+ documentName: string | null;
+ pdfUrl: string | null;
+ issueTypes: IssueTypeListItem[];
+ trackedEntities: TrackedEntity[];
+ requiresSerialTracking: boolean;
+ requiresBatchTracking: boolean;
+ events: ProductionEvent[];
+ productionQuantities: { scrap: number; production: number; rework: number };
+ // Verdict-driven postings link back to their sample; the header derives
+ // "Complete passed (n)" from what is passed but not yet posted.
+ linkedSampleIds: string[];
+ linkedProductionQuantity: number;
+ jobId: string | null;
+};
+
+// Shop-floor inspection execution view for job operations with
+// operationType = 'Inspection'. Same concepts as the ERP quality module's
+// InspectionView (features × samples matrix, ballooned drawing, AQL gating,
+// Accept/Reject disposition) in the MES AssemblyView shell, with the standard
+// shop-floor actions (timer, complete, scrap, rework, quality issue).
+export function InspectionView({
+ operationId,
+ job,
+ operation,
+ inspection,
+ samples,
+ features,
+ measurements,
+ balloons,
+ documentName,
+ pdfUrl,
+ issueTypes,
+ trackedEntities,
+ requiresSerialTracking,
+ requiresBatchTracking,
+ events,
+ productionQuantities,
+ linkedSampleIds,
+ linkedProductionQuantity,
+ jobId
+}: InspectionViewProps) {
+ const { t } = useLingui();
+ const user = useUser();
+ const mode = useMode();
+
+ // Which entity the produced lot samples come from: the job make method's
+ // WIP entities (the part being made), not receipt entities.
+ const isSerial = requiresSerialTracking;
+ const isTracked = requiresSerialTracking || requiresBatchTracking;
+
+ const liveFeatures = useMemo(
+ () => features.filter((f) => f.inspectionFeature != null),
+ [features]
+ );
+ const hasFeatures = liveFeatures.length > 0;
+ const showDrawing = pdfUrl != null;
+
+ const scannerDisclosure = useDisclosure();
+ const rejectDisclosure = useDisclosure();
+ const partialDisclosure = useDisclosure();
+ const acceptDisclosure = useDisclosure();
+ const actionsSheet = useDisclosure();
+ const qualityModal = useDisclosure();
+ const scrapModal = useDisclosure();
+ const finishModal = useDisclosure();
+ const reworkModal = useDisclosure();
+
+ const [activeFeatureId, setActiveFeatureId] = useState<string | null>(null);
+
+ // PDF-over-table stack (ERP quality InspectionView's layout model): pinned PDF
+ // height while the table is expanded, with a draggable splitter between them.
+ const [gridExpanded, setGridExpanded] = useState(true);
+ const [pdfPaneHeightPx, setPdfPaneHeightPx] = useState(360);
+ const [stackHeightPx, setStackHeightPx] = useState(0);
+ const [isResizingSplit, setIsResizingSplit] = useState(false);
+ const splitDragRef = useRef<{ startY: number; startPdfPx: number } | null>(
+ null
+ );
+ // Until the user drags the splitter, the PDF takes ~45% of the measured stack
+ // (capped by the table's half-stack minimum) instead of a fixed pixel default.
+ const hasUserResizedRef = useRef(false);
+ const stackRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!stackRef.current) return;
+ const el = stackRef.current;
+ const ro = new ResizeObserver(() => {
+ const h = el.clientHeight;
+ setStackHeightPx(h);
+ setPdfPaneHeightPx((prev) =>
+ clampPdfPaneHeight(
+ hasUserResizedRef.current ? prev : h * 0.45,
+ h,
+ gridExpanded
+ )
+ );
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [gridExpanded]);
+
+ useEffect(() => {
+ if (!isResizingSplit) return;
+ const onMove = (e: MouseEvent) => {
+ const start = splitDragRef.current;
+ if (!start) return;
+ const dy = e.clientY - start.startY;
+ setPdfPaneHeightPx(
+ clampPdfPaneHeight(start.startPdfPx + dy, stackHeightPx, gridExpanded)
+ );
+ };
+ const onUp = () => {
+ setIsResizingSplit(false);
+ splitDragRef.current = null;
+ };
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", onUp);
+ return () => {
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", onUp);
+ };
+ }, [isResizingSplit, stackHeightPx, gridExpanded]);
+
+ const onSplitResizeMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ if (!gridExpanded) return;
+ e.preventDefault();
+ hasUserResizedRef.current = true;
+ splitDragRef.current = {
+ startY: e.clientY,
+ startPdfPx: pdfPaneHeightPx
+ };
+ setIsResizingSplit(true);
+ },
+ [gridExpanded, pdfPaneHeightPx]
+ );
+
+ // Per-cell saves are quiet (no revalidation), so measurement + derived
+ // sample statuses are mirrored locally from the save responses and merged
+ // with the loader data for gating.
+ const [measurementOverrides, setMeasurementOverrides] = useState<
+ Record<string, "Pending" | "Passed" | "Failed">
+ >({});
+ const [sampleStatusOverrides, setSampleStatusOverrides] = useState<
+ Record<string, "Pending" | "Passed" | "Failed">
+ >({});
+ const [measurementValueOverrides, setMeasurementValueOverrides] = useState<
+ Record<string, number | null>
+ >({});
+ const onMeasurementSaved = useCallback((result: MeasurementSaveResult) => {
+ const key = `${result.sampleId}:${result.inspectionFeatureId}`;
+ setMeasurementOverrides((prev) => ({
+ ...prev,
+ [key]: result.measurementStatus
+ }));
+ setMeasurementValueOverrides((prev) => ({ ...prev, [key]: result.value }));
+ setSampleStatusOverrides((prev) => ({
+ ...prev,
+ [result.sampleId]: result.sampleStatus
+ }));
+ }, []);
+
+ const effectiveMeasurements = useMemo(() => {
+ const byKey = new Map<
+ string,
+ { featureId: string; status: string; value: number | null }
+ >();
+ for (const m of measurements) {
+ byKey.set(`${m.inspectionSampleId}:${m.inspectionFeatureId}`, {
+ featureId: m.inspectionFeatureId,
+ status: m.status,
+ value: m.value == null ? null : Number(m.value)
+ });
+ }
+ for (const [key, status] of Object.entries(measurementOverrides)) {
+ const featureId = key.split(":")[1] ?? "";
+ byKey.set(key, {
+ featureId,
+ status,
+ value: measurementValueOverrides[key] ?? null
+ });
+ }
+ return byKey;
+ }, [measurements, measurementOverrides, measurementValueOverrides]);
+
+ const featureCounts = useMemo(() => {
+ const counts = new Map<string, { recorded: number; failed: number }>();
+ for (const feature of liveFeatures) {
+ counts.set(feature.inspectionFeatureId, { recorded: 0, failed: 0 });
+ }
+ for (const measurement of effectiveMeasurements.values()) {
+ const entry = counts.get(measurement.featureId);
+ if (!entry) continue;
+ if (measurement.status !== "Pending") entry.recorded += 1;
+ if (measurement.status === "Failed") entry.failed += 1;
+ }
+ return counts;
+ }, [liveFeatures, effectiveMeasurements]);
+
+ const sampleStatuses = useMemo(() => {
+ const statuses = new Map<string, string>();
+ for (const sample of samples) {
+ statuses.set(sample.id, sample.status);
+ }
+ for (const [sampleId, status] of Object.entries(sampleStatusOverrides)) {
+ statuses.set(sampleId, status);
+ }
+ return statuses;
+ }, [samples, sampleStatusOverrides]);
+
+ const passes = [...sampleStatuses.values()].filter(
+ (s) => s === "Passed"
+ ).length;
+ const fails = [...sampleStatuses.values()].filter(
+ (s) => s === "Failed"
+ ).length;
+ const inspected = passes + fails;
+
+ const sampledIds = useMemo(
+ () => new Set(samples.map((s) => s.trackedEntityId)),
+ [samples]
+ );
+ const remaining = useMemo(
+ () => trackedEntities.filter((e) => !sampledIds.has(e.id)),
+ [trackedEntities, sampledIds]
+ );
+
+ const lotClosed =
+ inspection.dispositionedAt != null &&
+ (inspection.status === "Passed" ||
+ inspection.status === "Failed" ||
+ inspection.status === "Partial");
+
+ // Outcome bookkeeping, mirrored from the disposition route's server-side
+ // buckets (which recompute and clamp — these drive the header affordances).
+ const opAttrKey = `Operation ${operationId}`;
+ const entityOpenAtOp = useCallback(
+ (entity: TrackedEntity) => {
+ if (entity.status === "Consumed" || entity.status === "Rejected") {
+ return false;
+ }
+ const attributes = (entity.attributes ?? {}) as Record<string, unknown>;
+ return !attributes[opAttrKey];
+ },
+ [opAttrKey]
+ );
+ const linkedSampleIdSet = useMemo(
+ () => new Set(linkedSampleIds),
+ [linkedSampleIds]
+ );
+ const entityById = useMemo(
+ () => new Map(trackedEntities.map((e) => [e.id, e])),
+ [trackedEntities]
+ );
+ const failedEntityIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const sample of samples) {
+ if (
+ sampleStatuses.get(sample.id) === "Failed" &&
+ sample.trackedEntityId
+ ) {
+ ids.add(sample.trackedEntityId);
+ }
+ }
+ return ids;
+ }, [samples, sampleStatuses]);
+
+ const opRemaining = Math.max(
+ 0,
+ (operation.targetQuantity ?? operation.operationQuantity ?? 0) -
+ (operation.quantityComplete ?? 0) -
+ (operation.quantityScrapped ?? 0) -
+ (operation.quantityReworked ?? 0)
+ );
+
+ // Passed but not yet posted — the "Complete passed (n)" affordance.
+ const completablePassed = isSerial
+ ? samples.filter((sample) => {
+ if (sampleStatuses.get(sample.id) !== "Passed") return false;
+ if (linkedSampleIdSet.has(sample.id)) return false;
+ const entity = sample.trackedEntityId
+ ? entityById.get(sample.trackedEntityId)
+ : undefined;
+ return entity != null && entityOpenAtOp(entity);
+ }).length
+ : Math.min(
+ Math.max(0, passes - linkedProductionQuantity),
+ Math.max(0, opRemaining)
+ );
+
+ // What Accept will complete: the open remainder, minus failed units.
+ const acceptRemaining = isSerial
+ ? trackedEntities.filter(
+ (entity) => entityOpenAtOp(entity) && !failedEntityIds.has(entity.id)
+ ).length
+ : opRemaining;
+
+ // Serial units the reject/partial allocator can route: Reject condemns the
+ // whole open remainder; Partial routes only the failed units.
+ const allocatableUnits = useMemo<AllocatableUnit[]>(() => {
+ if (!isSerial) return [];
+ const units = trackedEntities
+ .filter((entity) => entityOpenAtOp(entity))
+ .map((entity) => ({
+ trackedEntityId: entity.id,
+ label: entity.readableId ?? entity.id.slice(0, 8),
+ failed: failedEntityIds.has(entity.id)
+ }));
+ // Failed first — they're the reason the operator is here.
+ return units.sort((a, b) => Number(b.failed) - Number(a.failed));
+ }, [isSerial, trackedEntities, entityOpenAtOp, failedEntityIds]);
+
+ const eventIds = {
+ setupProductionEventId: events.find((e) => e.type === "Setup" && !e.endTime)
+ ?.id,
+ laborProductionEventId: events.find((e) => e.type === "Labor" && !e.endTime)
+ ?.id,
+ machineProductionEventId: events.find(
+ (e) => e.type === "Machine" && !e.endTime
+ )?.id
+ };
+
+ // Partial is the terminal mixed close — only once every unit has a verdict.
+ const canPartial =
+ !lotClosed && inspected >= inspection.lotSize && passes > 0 && fails > 0;
+
+ // Serial lots build their sample columns by scanning tracked entities. The
+ // header "Add Sample" button stays primary until the plan's sample size is
+ // covered; a fresh serial lot auto-opens the scanner so the first scan is
+ // one tap away.
+ const allSamplesLoaded = samples.length >= inspection.sampleSize;
+ const hasAutoOpenedScanRef = useRef(false);
+ useEffect(() => {
+ if (hasAutoOpenedScanRef.current) return;
+ if (isSerial && samples.length === 0 && !lotClosed) {
+ hasAutoOpenedScanRef.current = true;
+ scannerDisclosure.onOpen();
+ }
+ }, [isSerial, samples.length, lotClosed, scannerDisclosure]);
+
+ const maxSampleSize = hasFeatures
+ ? Math.max(1, ...liveFeatures.map((f) => f.sampleSize))
+ : inspection.sampleSize;
+
+ // Gating mirrors the server-side disposition guards: feature-driven lots
+ // gate per feature; lots without features gate at the lot level on
+ // the "Overall result" pass/fail counts.
+ let canAccept: boolean;
+ let canReject: boolean;
+ if (hasFeatures) {
+ const allFeaturesSatisfied = liveFeatures.every((feature) => {
+ const counts = featureCounts.get(feature.inspectionFeatureId) ?? {
+ recorded: 0,
+ failed: 0
+ };
+ return (
+ counts.recorded >= feature.sampleSize &&
+ counts.failed <= feature.acceptanceNumber
+ );
+ });
+ const anyFeatureRejectable = liveFeatures.some((feature) => {
+ const counts = featureCounts.get(feature.inspectionFeatureId);
+ return counts != null && counts.failed >= feature.rejectionNumber;
+ });
+ canAccept = !lotClosed && allFeaturesSatisfied;
+ canReject = !lotClosed && (anyFeatureRejectable || fails > 0);
+ } else {
+ canAccept =
+ !lotClosed &&
+ inspected >= inspection.sampleSize &&
+ fails <= inspection.acceptanceNumber;
+ canReject = !lotClosed && fails > inspection.acceptanceNumber;
+ }
+
+ const failedFeatureSummary = useMemo<FailedFeatureSummary[]>(() => {
+ if (!hasFeatures) return [];
+ return liveFeatures
+ .map((lotFeature) => {
+ const feature = lotFeature.inspectionFeature!;
+ const failedValues: string[] = [];
+ for (const m of effectiveMeasurements.values()) {
+ if (m.featureId !== feature.id || m.status !== "Failed") continue;
+ failedValues.push(m.value == null ? "F" : String(m.value));
+ }
+ if (failedValues.length === 0) return null;
+ const spec = [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ");
+ return { label: feature.label, spec, failedValues };
+ })
+ .filter(Boolean) as FailedFeatureSummary[];
+ }, [hasFeatures, liveFeatures, effectiveMeasurements]);
+
+ const drawingBalloons = useMemo(() => {
+ const labelByFeatureId = new Map(
+ liveFeatures.map((f) => [
+ f.inspectionFeatureId,
+ f.inspectionFeature!.label
+ ])
+ );
+ return balloons
+ .filter((b) => labelByFeatureId.has(b.inspectionFeatureId))
+ .map((b) => ({
+ id: b.id,
+ inspectionFeatureId: b.inspectionFeatureId,
+ pageNumber: b.pageNumber,
+ xCoordinate: b.xCoordinate,
+ yCoordinate: b.yCoordinate,
+ label: labelByFeatureId.get(b.inspectionFeatureId) ?? ""
+ }));
+ }, [balloons, liveFeatures]);
+
+ const statusBadgeVariant =
+ inspection.status === "Passed"
+ ? ("green" as const)
+ : inspection.status === "Failed"
+ ? ("red" as const)
+ : inspection.status === "Partial"
+ ? ("yellow" as const)
+ : ("secondary" as const);
+
+ const planSummary =
+ inspection.samplingPlanType === "AQL"
+ ? `AQL ${inspection.aql ?? ""} · Lvl ${inspection.inspectionLevel ?? ""} · ${inspection.severity ?? ""}`
+ : inspection.samplingPlanType;
+
+ // Timers: one control per configured work type (single-phase clocking, same
+ // contract as the assembly view's TimerControl → /x/event).
+ const workTypes = useMemo<WorkType[]>(() => {
+ const list: WorkType[] = [];
+ if ((operation.setupDuration ?? 0) > 0) list.push("Setup");
+ if ((operation.laborDuration ?? 0) > 0) list.push("Labor");
+ if ((operation.machineDuration ?? 0) > 0) list.push("Machine");
+ return list.length > 0 ? list : ["Labor"];
+ }, [operation]);
+
+ const openEventForWorkType = useCallback(
+ (type: WorkType) =>
+ (events.find((e) => e.type === type && !e.endTime) as
+ | { id: string; startTime: string }
+ | undefined) ?? null,
+ [events]
+ );
+ const openByType = (type: string) =>
+ (events.find((e) => e.type === type && !e.endTime) ?? undefined) as
+ | ProductionEvent
+ | undefined;
+
+ // The next unit still to build is the natural target for completes; a batch
+ // parent shares one lot entity across every unit.
+ const quantityComplete = Math.max(
+ 0,
+ Math.round((operation.quantityComplete as number) ?? 0)
+ );
+ const completeEntityId = requiresBatchTracking
+ ? (trackedEntities[0]?.id ?? "")
+ : requiresSerialTracking
+ ? (trackedEntities[quantityComplete]?.id ?? trackedEntities[0]?.id ?? "")
+ : "";
+
+ const companyLogo =
+ mode === "dark" ? user.company.logoDarkIcon : user.company.logoLightIcon;
+
+ return (
+ <div className="relative flex h-screen w-full flex-col overflow-hidden bg-background text-foreground">
+ {/* ── HEADER ── */}
+ <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border">
+ <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />
+ {companyLogo ? (
+ <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">
+ <img
+ src={companyLogo}
+ alt={`${user.company.name} logo`}
+ className="h-7 w-auto max-w-[140px] object-contain"
+ />
+ </div>
+ ) : null}
+
+ <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">
+ <span className="truncate text-sm font-semibold">
+ {inspection.inspectionId}
+ </span>
+ <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>
+ <span className="hidden text-muted-foreground md:inline">·</span>
+ <span className="hidden truncate text-sm text-foreground/90 md:inline">
+ {inspection.itemReadableId ?? job?.itemReadableIdWithRevision}
+ </span>
+ {operation?.description ? (
+ <>
+ <span className="hidden text-muted-foreground lg:inline">·</span>
+ <span className="hidden truncate text-sm text-foreground/90 lg:inline">
+ {operation.description}
+ </span>
+ </>
+ ) : null}
+ </div>
+
+ <div className="flex-1" />
+
+ {isSerial && !lotClosed ? (
+ <button
+ type="button"
+ onClick={scannerDisclosure.onOpen}
+ className={cn(
+ "hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex",
+ !allSamplesLoaded && "text-primary"
+ )}
+ >
+ <LuScan className="size-4" />
+ <Trans>Add Sample</Trans>
+ </button>
+ ) : null}
+ {!lotClosed && completablePassed > 0 ? (
+ <CompletePassedButton
+ inspectionId={inspection.id}
+ operationId={operationId}
+ count={completablePassed}
+ eventIds={eventIds}
+ />
+ ) : null}
+ <button
+ type="button"
+ onClick={rejectDisclosure.onOpen}
+ disabled={!canReject}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-red-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-red-400 md:gap-2 md:px-4"
+ >
+ <LuX className="size-4" />
+ <span className="hidden sm:inline">
+ <Trans>Reject</Trans>
+ </span>
+ </button>
+ {canPartial ? (
+ <button
+ type="button"
+ onClick={partialDisclosure.onOpen}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-amber-600 transition-colors hover:bg-accent active:scale-[0.98] dark:text-amber-400 md:gap-2 md:px-4"
+ >
+ <LuContrast className="size-4" />
+ <span className="hidden sm:inline">
+ <Trans>Partial</Trans>
+ </span>
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={acceptDisclosure.onOpen}
+ disabled={!canAccept}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-emerald-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-emerald-400 md:gap-2 md:px-4"
+ >
+ <LuCheck className="size-4" />
+ <span className="hidden sm:inline">
+ <Trans>Accept</Trans>
+ </span>
+ </button>
+ <button
+ type="button"
+ aria-label={t`More actions`}
+ onClick={actionsSheet.onOpen}
+ className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:px-4"
+ >
+ <LuEllipsisVertical className="size-4" />
+ </button>
+
+ {workTypes.map((wt) => (
+ <TimerControl
+ key={wt}
+ operationId={operationId}
+ workCenterId={operation.workCenterId ?? undefined}
+ openEvent={openEventForWorkType(wt)}
+ workType={wt}
+ />
+ ))}
+ </header>
+
+ {/* ── META BAR ── */}
+ <div className="flex h-9 shrink-0 items-center gap-3 overflow-x-auto bg-card border-b border-border px-5 scrollbar-hide">
+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">
+ {inspected} / {inspection.sampleSize} <Trans>inspected</Trans> · Ac{" "}
+ {inspection.acceptanceNumber} · Re {inspection.rejectionNumber}
+ {inspection.codeLetter ? ` · ${inspection.codeLetter}` : ""}
+ </span>
+ <span className="whitespace-nowrap text-xs text-muted-foreground">
+ {planSummary}
+ </span>
+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">
+ <Trans>Lot</Trans> {inspection.lotSize}
+ </span>
+ {documentName ? (
+ <span className="truncate text-xs text-muted-foreground">
+ {documentName}
+ </span>
+ ) : null}
+ <div className="flex-1" />
+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">
+ <Trans>Completed</Trans> {productionQuantities.production} ·{" "}
+ <Trans>Scrap</Trans> {productionQuantities.scrap} ·{" "}
+ <Trans>Rework</Trans> {productionQuantities.rework}
+ </span>
+ </div>
+
+ {/* ── BODY ── */}
+ {showDrawing ? (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">
+ <div
+ ref={stackRef}
+ className="flex min-h-0 flex-1 flex-col gap-0 overflow-hidden"
+ >
+ {/* PDF viewer — pinned height while the features table is expanded */}
+ <div
+ className={cn(
+ "flex min-h-0 min-w-full flex-col overflow-hidden rounded-lg border bg-muted",
+ gridExpanded ? "shrink-0" : "min-h-[220px] flex-1"
+ )}
+ style={{
+ ...(gridExpanded ? { height: pdfPaneHeightPx } : undefined),
+ minWidth: "100%"
+ }}
+ >
+ <ClientOnly
+ fallback={
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ }
+ >
+ {() => (
+ <Suspense
+ fallback={
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ }
+ >
+ <InspectionDrawingPane
+ pdfUrl={pdfUrl!}
+ balloons={drawingBalloons}
+ activeFeatureId={activeFeatureId}
+ onBalloonClick={setActiveFeatureId}
+ />
+ </Suspense>
+ )}
+ </ClientOnly>
+ </div>
+
+ {gridExpanded ? (
+ <div
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label={t`Drag to resize drawing and features`}
+ aria-valuenow={Math.round(pdfPaneHeightPx)}
+ className={cn(
+ "group flex h-2 shrink-0 cursor-row-resize touch-none items-center justify-center rounded-md px-2 hover:bg-muted/80",
+ isResizingSplit && "bg-muted"
+ )}
+ onMouseDown={onSplitResizeMouseDown}
+ >
+ <span className="h-1 w-14 shrink-0 rounded-full bg-muted-foreground/40 group-hover:bg-muted-foreground/65" />
+ </div>
+ ) : null}
+
+ {/* Features table — collapsible bottom panel */}
+ <div
+ className={cn(
+ "flex min-w-0 flex-col overflow-hidden rounded-lg border bg-card",
+ gridExpanded ? "min-h-0 flex-1" : "max-h-[14rem] shrink-0"
+ )}
+ style={
+ gridExpanded && stackHeightPx > 0
+ ? { minHeight: stackHeightPx * 0.5 }
+ : undefined
+ }
+ >
+ <div className="flex min-h-10 flex-shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2">
+ <span className="truncate text-sm font-medium text-foreground">
+ {t`Features`}
+ </span>
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-expanded={gridExpanded}
+ aria-label={
+ gridExpanded
+ ? t`Collapse features table`
+ : t`Expand features table`
+ }
+ icon={
+ gridExpanded ? (
+ <LuChevronDown className="h-4 w-4" />
+ ) : (
+ <LuChevronUp className="h-4 w-4" />
+ )
+ }
+ onClick={() => setGridExpanded((v) => !v)}
+ />
+ </div>
+ <InspectionMeasurementMatrix
+ inspectionId={inspection.id}
+ isReadOnly={lotClosed}
+ isSerial={isSerial}
+ features={features}
+ samples={samples}
+ measurements={measurements}
+ maxSampleSize={maxSampleSize}
+ lotSize={inspection.lotSize}
+ lotAcceptanceNumber={inspection.acceptanceNumber}
+ lotRejectionNumber={inspection.rejectionNumber}
+ activeFeatureId={activeFeatureId}
+ onActiveFeatureChange={setActiveFeatureId}
+ onMeasurementSaved={onMeasurementSaved}
+ />
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border bg-card">
+ <InspectionMeasurementMatrix
+ inspectionId={inspection.id}
+ isReadOnly={lotClosed}
+ isSerial={isSerial}
+ features={features}
+ samples={samples}
+ measurements={measurements}
+ maxSampleSize={maxSampleSize}
+ lotSize={inspection.lotSize}
+ lotAcceptanceNumber={inspection.acceptanceNumber}
+ lotRejectionNumber={inspection.rejectionNumber}
+ activeFeatureId={activeFeatureId}
+ onActiveFeatureChange={setActiveFeatureId}
+ onMeasurementSaved={onMeasurementSaved}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* ── MODALS ── */}
+ {scannerDisclosure.isOpen && (
+ <ScanInspectionSample
+ inspectionId={inspection.id}
+ isSerial={isSerial}
+ remaining={remaining}
+ inspected={inspected}
+ sampleSize={inspection.sampleSize}
+ fails={fails}
+ acceptanceNumber={inspection.acceptanceNumber}
+ onClose={scannerDisclosure.onClose}
+ />
+ )}
+
+ {acceptDisclosure.isOpen && (
+ <AcceptLotModal
+ inspectionId={inspection.id}
+ operationId={operationId}
+ fails={fails}
+ remaining={acceptRemaining}
+ eventIds={eventIds}
+ onClose={acceptDisclosure.onClose}
+ />
+ )}
+
+ {rejectDisclosure.isOpen && (
+ <DispositionModal
+ decision="Reject"
+ inspectionId={inspection.id}
+ operationId={operationId}
+ isSerial={isSerial}
+ units={allocatableUnits}
+ maxAllocatable={opRemaining}
+ completions={0}
+ issueTypes={issueTypes}
+ summary={t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s). Route the units below to scrap or rework, or record the verdict only.`}
+ failedFeatureSummary={failedFeatureSummary}
+ eventIds={eventIds}
+ onCancel={rejectDisclosure.onClose}
+ onSubmit={rejectDisclosure.onClose}
+ />
+ )}
+
+ {partialDisclosure.isOpen && (
+ <DispositionModal
+ decision="Partial"
+ inspectionId={inspection.id}
+ operationId={operationId}
+ isSerial={isSerial}
+ units={allocatableUnits.filter((unit) => unit.failed)}
+ maxAllocatable={isSerial ? fails : Math.min(fails, opRemaining)}
+ completions={completablePassed}
+ issueTypes={issueTypes}
+ summary={t`Every unit has a verdict: ${passes} passed and ${fails} failed. The lot closes with each unit routed to its own outcome.`}
+ failedFeatureSummary={failedFeatureSummary}
+ eventIds={eventIds}
+ onCancel={partialDisclosure.onClose}
+ onSubmit={partialDisclosure.onClose}
+ />
+ )}
+
+ <QualityIssueModal
+ operationId={operationId}
+ trackedEntityId={
+ isTracked ? (trackedEntities[0]?.id ?? undefined) : undefined
+ }
+ isOpen={qualityModal.isOpen}
+ onClose={qualityModal.onClose}
+ />
+
+ {scrapModal.isOpen && operation && (
+ <QuantityModal
+ type="scrap"
+ operation={operation}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ trackedEntityId={completeEntityId}
+ setupProductionEvent={openByType("Setup")}
+ laborProductionEvent={openByType("Labor")}
+ machineProductionEvent={openByType("Machine")}
+ onClose={scrapModal.onClose}
+ />
+ )}
+
+ {finishModal.isOpen && operation && (
+ <QuantityModal
+ type="finish"
+ operation={operation}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ trackedEntityId={completeEntityId}
+ setupProductionEvent={openByType("Setup")}
+ laborProductionEvent={openByType("Labor")}
+ machineProductionEvent={openByType("Machine")}
+ allStepsRecorded
+ onClose={finishModal.onClose}
+ />
+ )}
+
+ {reworkModal.isOpen && operation && jobId && (
+ <ReworkModal
+ operation={operation}
+ jobId={jobId}
+ isOpen={reworkModal.isOpen}
+ onClose={reworkModal.onClose}
+ trackedEntities={trackedEntities as never}
+ parentIsSerial={requiresSerialTracking}
+ parentIsBatch={requiresBatchTracking}
+ />
+ )}
+
+ <BottomSheet
+ open={actionsSheet.isOpen}
+ onOpenChange={(open) => {
+ if (!open) actionsSheet.onClose();
+ }}
+ >
+ <BottomSheetContent className="mx-auto max-w-md">
+ <BottomSheetBody>
+ <div className="flex flex-col gap-2 pb-2">
+ <ActionSheetButton
+ icon={<LuTrash className="size-4 shrink-0" />}
+ label={t`Scrap`}
+ onClick={() => {
+ actionsSheet.onClose();
+ scrapModal.onOpen();
+ }}
+ />
+ <ActionSheetButton
+ icon={<LuGitPullRequest className="size-4 shrink-0" />}
+ label={t`Rework`}
+ onClick={() => {
+ actionsSheet.onClose();
+ reworkModal.onOpen();
+ }}
+ />
+ <ActionSheetButton
+ icon={<LuCheck className="size-4 shrink-0" />}
+ label={t`Finish`}
+ onClick={() => {
+ actionsSheet.onClose();
+ finishModal.onOpen();
+ }}
+ />
+ <ActionSheetButton
+ icon={<LuFlag className="size-4 shrink-0" />}
+ label={t`Quality Issue`}
+ onClick={() => {
+ actionsSheet.onClose();
+ qualityModal.onOpen();
+ }}
+ />
+ {isSerial && !lotClosed ? (
+ <ActionSheetButton
+ icon={<LuScan className="size-4 shrink-0" />}
+ label={t`Add Sample`}
+ onClick={() => {
+ actionsSheet.onClose();
+ scannerDisclosure.onOpen();
+ }}
+ />
+ ) : null}
+ </div>
+ </BottomSheetBody>
+ </BottomSheetContent>
+ </BottomSheet>
+
+ {/* Inspecting is work: start the labor clock on open whenever no clock
+ is running (any work type — the exclusive start would end it).
+ Always on for inspections, independent of the company-level
+ autoStartOperationTimer setting. */}
+ <AutoTimer
+ operationId={operationId}
+ workType={workTypes.includes("Labor") ? "Labor" : workTypes[0]}
+ workCenterId={operation.workCenterId ?? undefined}
+ openEvent={
+ (events.find((e) => !e.endTime) as
+ | { id: string; startTime: string }
+ | undefined) ?? null
+ }
+ />
+ </div>
+ );
+}
+
+type ProductionEventIdFields = {
+ setupProductionEventId?: string;
+ laborProductionEventId?: string;
+ machineProductionEventId?: string;
+};
+
+function EventIdInputs({ eventIds }: { eventIds: ProductionEventIdFields }) {
+ return (
+ <>
+ {eventIds.setupProductionEventId ? (
+ <input
+ type="hidden"
+ name="setupProductionEventId"
+ value={eventIds.setupProductionEventId}
+ />
+ ) : null}
+ {eventIds.laborProductionEventId ? (
+ <input
+ type="hidden"
+ name="laborProductionEventId"
+ value={eventIds.laborProductionEventId}
+ />
+ ) : null}
+ {eventIds.machineProductionEventId ? (
+ <input
+ type="hidden"
+ name="machineProductionEventId"
+ value={eventIds.machineProductionEventId}
+ />
+ ) : null}
+ </>
+ );
+}
+
+// Progressive completion of what has passed so far, while the lot stays open.
+function CompletePassedButton({
+ inspectionId,
+ operationId,
+ count,
+ eventIds
+}: {
+ inspectionId: string;
+ operationId: string;
+ count: number;
+ eventIds: ProductionEventIdFields;
+}) {
+ const fetcher = useFetcher();
+ const busy = fetcher.state !== "idle";
+
+ return (
+ <fetcher.Form
+ method="post"
+ action={path.to.inspectionCompletePassed(inspectionId)}
+ className="h-full shrink-0"
+ >
+ <input type="hidden" name="operationId" value={operationId} />
+ <EventIdInputs eventIds={eventIds} />
+ <button
+ type="submit"
+ disabled={busy}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-emerald-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-emerald-400 md:gap-2 md:px-4"
+ >
+ <LuCheckCheck className="size-4" />
+ <span className="hidden tabular-nums sm:inline">
+ <Trans>Complete passed</Trans> {count}
+ </span>
+ </button>
+ </fetcher.Form>
+ );
+}
+
+function AcceptLotModal({
+ inspectionId,
+ operationId,
+ fails,
+ remaining,
+ eventIds,
+ onClose
+}: {
+ inspectionId: string;
+ operationId: string;
+ fails: number;
+ remaining: number;
+ eventIds: ProductionEventIdFields;
+ onClose: () => void;
+}) {
+ const fetcher = useFetcher<{}>();
+ const submitted = useRef(false);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && submitted.current) {
+ onClose();
+ submitted.current = false;
+ }
+ }, [fetcher.state, onClose]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Accept lot?</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={2}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ The lot will be marked Passed and {remaining} remaining unit(s)
+ will be completed at this operation.
+ </Trans>
+ </p>
+ {fails > 0 ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ {fails} sampled failure(s) are recorded and will NOT be
+ completed — resolve them from the actions menu.
+ </Trans>
+ </p>
+ ) : null}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <fetcher.Form
+ method="post"
+ action={path.to.inspectionDisposition(inspectionId)}
+ onSubmit={() => (submitted.current = true)}
+ >
+ <input type="hidden" name="decision" value="Accept" />
+ <input type="hidden" name="operationId" value={operationId} />
+ <EventIdInputs eventIds={eventIds} />
+ <Button
+ type="submit"
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ <Trans>Accept Lot</Trans>
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+function ActionSheetButton({
+ icon,
+ label,
+ onClick
+}: {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ className="flex items-center gap-3 rounded-lg bg-accent px-4 py-4 text-accent-foreground ring-1 ring-black/5 transition-transform active:scale-[0.98]"
+ onClick={onClick}
+ >
+ {icon}
+ <span className="text-base/6 font-medium">{label}</span>
+ </button>
+ );
+}
+
+// Passive operation timer (opt-in) — same one-shot contract as the assembly
+// view's AutoTimer: auto-starts the operator's production event on open,
+// never auto-ends one.
+function AutoTimer({
+ operationId,
+ workType,
+ workCenterId,
+ openEvent
+}: {
+ operationId: string;
+ workType: WorkType;
+ workCenterId?: string;
+ openEvent: { id: string; startTime: string } | null;
+}) {
+ const fetcher = useFetcher();
+ const startedRef = useRef(false);
+
+ const busy = fetcher.state !== "idle";
+ const running = !!openEvent;
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: one-shot on open
+ useEffect(() => {
+ if (startedRef.current) return;
+ startedRef.current = true;
+ if (running || busy) return;
+ const fd = new FormData();
+ fd.set("jobOperationId", operationId);
+ fd.set("timezone", getLocalTimeZone());
+ fd.set("type", workType);
+ fd.set("action", "Start");
+ fd.set("exclusive", "true");
+ if (workCenterId) fd.set("workCenterId", workCenterId);
+ fetcher.submit(fd, { method: "post", action: path.to.productionEvent });
+ }, []);
+
+ return null;
+}
+
+function formatElapsed(s: number) {
+ const h = Math.floor(s / 3600)
+ .toString()
+ .padStart(2, "0");
+ const m = Math.floor((s % 3600) / 60)
+ .toString()
+ .padStart(2, "0");
+ const sec = (s % 60).toString().padStart(2, "0");
+ return `${h}:${m}:${sec}`;
+}
+
+// Live elapsed seconds from an open production event's startTime.
+function useElapsed(openEvent: { startTime: string } | null) {
+ const [, setTick] = useState(0);
+ useEffect(() => {
+ if (!openEvent) return;
+ const id = setInterval(() => setTick((t) => t + 1), 1000);
+ return () => clearInterval(id);
+ }, [openEvent]);
+ if (!openEvent) return 0;
+ const start = new Date(openEvent.startTime).getTime();
+ return Math.max(0, Math.floor((Date.now() - start) / 1000));
+}
+
+// Single-phase clocking control — posts Start/End to /x/event with
+// exclusive=true so starting one work type ends any other open one. Same
+// contract as the assembly view's TimerControl.
+function TimerControl({
+ operationId,
+ workCenterId,
+ openEvent,
+ workType
+}: {
+ operationId: string;
+ workCenterId?: string;
+ openEvent: { id: string; startTime: string } | null;
+ workType: WorkType;
+}) {
+ const fetcher = useFetcher();
+
+ // Optimistic state: flip the moment Start/End is submitted instead of
+ // waiting for the post-production-event round-trip.
+ const pendingAction = fetcher.formData?.get("action");
+ const active =
+ pendingAction === "Start"
+ ? true
+ : pendingAction === "End"
+ ? false
+ : !!openEvent;
+
+ const liveElapsed = useElapsed(pendingAction === "End" ? null : openEvent);
+ const elapsed = pendingAction === "End" ? 0 : liveElapsed;
+
+ return (
+ <fetcher.Form
+ method="post"
+ action={path.to.productionEvent}
+ className="h-full shrink-0"
+ >
+ <input type="hidden" name="jobOperationId" value={operationId} />
+ <input type="hidden" name="timezone" value={getLocalTimeZone()} />
+ <input type="hidden" name="type" value={workType} />
+ <input type="hidden" name="exclusive" value="true" />
+ <input type="hidden" name="action" value={openEvent ? "End" : "Start"} />
+ {workCenterId ? (
+ <input type="hidden" name="workCenterId" value={workCenterId} />
+ ) : null}
+ {openEvent ? (
+ <input type="hidden" name="id" value={openEvent.id} />
+ ) : null}
+ <button
+ type="submit"
+ aria-label={active ? "Pause timer" : "Start timer"}
+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"
+ >
+ <span className="hidden flex-col items-end leading-none sm:flex">
+ <span className="text-sm font-medium tabular-nums">
+ {formatElapsed(elapsed)}
+ </span>
+ <span className="text-[9px] uppercase tracking-wider text-muted-foreground">
+ {workType}
+ </span>
+ </span>
+ {active ? (
+ <LuPause className="size-4" />
+ ) : (
+ <LuPlay className="size-4" />
+ )}
+ </button>
+ </fetcher.Form>
+ );
+}
+
+export default InspectionView;
diff --git a/apps/mes/app/components/Inspection/ScanInspectionSample.tsx b/apps/mes/app/components/Inspection/ScanInspectionSample.tsx
new file mode 100644
index 0000000000..6522f87c6d
--- /dev/null
+++ b/apps/mes/app/components/Inspection/ScanInspectionSample.tsx
@@ -0,0 +1,258 @@
+import { Hidden, Submit, TextArea, ValidatedForm } from "@carbon/form";
+import {
+ BarProgress,
+ Button,
+ HStack,
+ Input,
+ InputGroup,
+ InputRightElement,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ ScrollArea,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useState } from "react";
+import { LuCheck, LuList, LuQrCode, LuX } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { inspectionSampleValidator } from "~/services/models";
+import type { InspectionTrackedEntity } from "~/services/types";
+import { path } from "~/utils/path";
+
+type Props = {
+ inspectionId: string;
+ isSerial: boolean;
+ remaining: InspectionTrackedEntity[];
+ inspected: number;
+ sampleSize: number;
+ fails: number;
+ acceptanceNumber: number;
+ onClose: () => void;
+};
+
+export default function ScanInspectionSample({
+ inspectionId,
+ isSerial,
+ remaining,
+ inspected,
+ sampleSize,
+ fails,
+ acceptanceNumber,
+ onClose
+}: Props) {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{ error?: unknown; success?: boolean }>();
+
+ const [serial, setSerial] = useState("");
+ const [selected, setSelected] = useState<InspectionTrackedEntity | null>(
+ null
+ );
+ // Bumped after each successful save so the form (notes) remounts and clears,
+ // even for non-serial parts where there's no entity selection to change.
+ const [resetKey, setResetKey] = useState(0);
+
+ const findMatch = (value: string): InspectionTrackedEntity | null => {
+ if (!value) return null;
+ const needle = value.toLowerCase();
+ return (
+ remaining.find((e) => {
+ if (e.id === value) return true;
+ if (e.readableId && e.readableId.toLowerCase() === needle) return true;
+ return false;
+ }) ?? null
+ );
+ };
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keep findMatch around for future UI without re-introducing unused-variable churn
+ useEffect(() => {
+ setSelected(findMatch(serial));
+ }, [serial, remaining]);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data && !fetcher.data.error) {
+ setSerial("");
+ setSelected(null);
+ setResetKey((k) => k + 1);
+ }
+ }, [fetcher.state, fetcher.data]);
+
+ const isSubmitting = fetcher.state !== "idle";
+ // Serial parts require a scanned/selected tracked entity; other tracking
+ // types add a sample column without one.
+ const canRecord = isSerial ? !!selected : true;
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent size="large">
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Inspect Item</Trans>
+ </ModalTitle>
+ <ModalDescription>
+ <Trans>
+ Scan or select a tracked entity from this lot to add it as a
+ sample column, then record its result in the grid.
+ </Trans>
+ </ModalDescription>
+ </ModalHeader>
+ <ValidatedForm
+ key={`${selected?.id ?? "none"}-${resetKey}`}
+ fetcher={fetcher}
+ method="post"
+ action={path.to.inspectionSample(inspectionId)}
+ validator={inspectionSampleValidator}
+ defaultValues={{
+ inspectionId,
+ trackedEntityId: selected?.id ?? "",
+ status: "Pending",
+ notes: ""
+ }}
+ >
+ <ModalBody>
+ <Hidden name="inspectionId" value={inspectionId} />
+ <Hidden name="trackedEntityId" value={selected?.id ?? ""} />
+ <Hidden name="status" value="Pending" />
+
+ <VStack spacing={4} className="w-full">
+ <BarProgress
+ label={t`Progress`}
+ value={`${inspected} / ${sampleSize} · ${fails} ${fails === 1 ? "failure" : "failures"} · Ac ${acceptanceNumber}`}
+ progress={inspected}
+ max={Math.max(1, sampleSize)}
+ activeClassName={
+ fails > acceptanceNumber ? "bg-red-500" : "bg-emerald-500"
+ }
+ />
+
+ {isSerial && (
+ <Tabs defaultValue="scan" className="w-full">
+ <TabsList className="grid w-full grid-cols-2 mb-4">
+ <TabsTrigger value="scan">
+ <LuQrCode className="mr-2" />
+ <Trans>Scan</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="select">
+ <LuList className="mr-2" />
+ <Trans>Select</Trans>
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="scan" className="mt-0 w-full">
+ <VStack spacing={3} className="w-full">
+ <InputGroup className="w-full">
+ <Input
+ autoFocus
+ placeholder={t`Scan or enter tracked entity ID, serial, or batch`}
+ value={serial}
+ onChange={(e) => setSerial(e.target.value)}
+ />
+ <InputRightElement>
+ {serial &&
+ (selected ? (
+ <LuCheck className="text-green-500" />
+ ) : (
+ <LuX className="text-red-500" />
+ ))}
+ </InputRightElement>
+ </InputGroup>
+
+ {selected && (
+ <div className="w-full rounded-md border p-3">
+ <div className="text-xs text-muted-foreground">
+ <Trans>Tracked Entity</Trans>
+ </div>
+ <div className="font-mono text-sm">
+ {selected.readableId ?? selected.id}
+ </div>
+ {selected.readableId && (
+ <div className="text-xs text-muted-foreground mt-1">
+ {selected.id}
+ </div>
+ )}
+ </div>
+ )}
+ </VStack>
+ </TabsContent>
+ <TabsContent value="select" className="mt-0 w-full">
+ <ScrollArea className="h-[40dvh] w-full">
+ <VStack spacing={2} className="w-full pr-3">
+ {remaining.length === 0 ? (
+ <p className="text-center text-muted-foreground w-full py-6">
+ <Trans>No remaining entities to inspect.</Trans>
+ </p>
+ ) : (
+ remaining.map((e) => {
+ const isSelected = selected?.id === e.id;
+ return (
+ <HStack
+ key={e.id}
+ className="w-full justify-between p-4 border rounded-md"
+ >
+ <VStack
+ spacing={0}
+ className="w-full items-start min-w-0"
+ >
+ <p className="font-mono text-sm truncate w-full">
+ {e.readableId ?? e.id}
+ </p>
+ {e.readableId && (
+ <p className="text-xs text-muted-foreground truncate w-full">
+ {e.id}
+ </p>
+ )}
+ </VStack>
+ <Button
+ size="sm"
+ variant={isSelected ? "primary" : "secondary"}
+ onClick={() => setSerial(e.id)}
+ >
+ {isSelected ? (
+ <Trans>Selected</Trans>
+ ) : (
+ <Trans>Select</Trans>
+ )}
+ </Button>
+ </HStack>
+ );
+ })
+ )}
+ </VStack>
+ </ScrollArea>
+ </TabsContent>
+ </Tabs>
+ )}
+
+ <TextArea name="notes" label={t`Notes`} isDisabled={!canRecord} />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack spacing={2}>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Close</Trans>
+ </Button>
+ <Submit
+ leftIcon={<LuCheck />}
+ isDisabled={!canRecord || isSubmitting}
+ >
+ <Trans>Add Sample</Trans>
+ </Submit>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 3c639b1e54..0828ce1785 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -1456,6 +1456,16 @@ export const JobOperation = ({
{issueModal.isOpen && (
<IssueMaterialModal
operationId={operation.id}
+ // The process view issues the whole quantity at
+ // once, so picked lots may pre-fill when the
+ // parent is a single entity. The modal enforces
+ // the full rule: a picking list exists AND (the
+ // parent is not serialized OR the operation
+ // makes exactly one unit).
+ allowPrefill
+ parentUnitCount={
+ operation.operationQuantity ?? undefined
+ }
expiredEntityPolicy={expiredEntityPolicy}
locationId={locationId}
workCenterId={operation.workCenterId ?? undefined}
diff --git a/apps/mes/app/components/JobOperation/components/Assembly.tsx b/apps/mes/app/components/JobOperation/components/Assembly.tsx
deleted file mode 100644
index 002aac7b93..0000000000
--- a/apps/mes/app/components/JobOperation/components/Assembly.tsx
+++ /dev/null
@@ -1,255 +0,0 @@
-import type { Json } from "@carbon/database";
-import { Badge, Button, ClientOnly, cn, Spinner } from "@carbon/react";
-import type {
- AssemblyStep,
- CameraPose,
- Fastener,
- Motion
-} from "@carbon/viewer";
-import { AssemblyPlayer } from "@carbon/viewer";
-import { Trans } from "@lingui/react/macro";
-import { useMemo, useState } from "react";
-import {
- LuChevronLeft,
- LuChevronRight,
- LuFileVideo,
- LuInfo,
- LuOctagonAlert,
- LuTriangleAlert,
- LuWrench
-} from "react-icons/lu";
-import { getPrivateUrl } from "~/utils/path";
-
-export type AssemblyInstructionData = {
- name: string | null;
- glbPath: string;
- graphPath: string;
- steps: {
- id: string;
- title: string | null;
- instructionText: string | null;
- componentNodeIds: string[];
- motion: Json;
- camera: Json | null;
- fastener: Json | null;
- durationSeconds: number | null;
- warnings: Json | null;
- }[];
- requirements: {
- id: string;
- stepId: string;
- type: "Tool" | "Fixture" | "Consumable" | "Note" | "Media";
- name: string | null;
- text: string | null;
- severity: "Info" | "Caution" | "Warning" | null;
- filePath: string | null;
- quantity: number;
- }[];
-};
-
-type StepRequirement = AssemblyInstructionData["requirements"][number];
-
-const motionTypes = ["linear", "L", "helix", "path", "none"];
-
-function toViewerStep(
- step: AssemblyInstructionData["steps"][number]
-): AssemblyStep {
- const motion = step.motion as Motion | null;
- // Planner flag: no collision-free path — the player fades the components in
- const warnings = step.warnings as { flagged?: boolean } | null;
- return {
- id: step.id,
- title: step.title,
- instructionText: step.instructionText,
- componentNodeIds: step.componentNodeIds ?? [],
- motion:
- motion && typeof motion === "object" && motionTypes.includes(motion.type)
- ? motion
- : { type: "none" },
- camera: (step.camera as CameraPose | null) ?? null,
- fastener: (step.fastener as Fastener | null) ?? null,
- durationSeconds: step.durationSeconds,
- flagged: warnings?.flagged === true ? true : undefined
- };
-}
-
-type AssemblyInstructionsProps = {
- assembly: AssemblyInstructionData;
- mode: "light" | "dark";
-};
-
-export function AssemblyInstructions({
- assembly,
- mode
-}: AssemblyInstructionsProps) {
- const [activeStepIndex, setActiveStepIndex] = useState(0);
-
- const steps = useMemo(
- () => assembly.steps.map(toViewerStep),
- [assembly.steps]
- );
-
- const stepCount = steps.length;
- const activeStepId = assembly.steps[activeStepIndex]?.id;
- const activeRequirements = useMemo(
- () =>
- (assembly.requirements ?? []).filter(
- (requirement) => requirement.stepId === activeStepId
- ),
- [assembly.requirements, activeStepId]
- );
-
- return (
- <div className="flex h-full w-full flex-col">
- <div className="min-h-0 flex-1">
- <ClientOnly
- fallback={
- <div className="flex h-full w-full items-center justify-center">
- <Spinner className="h-10 w-10" />
- </div>
- }
- >
- {() => (
- <AssemblyPlayer
- glbUrl={getPrivateUrl(assembly.glbPath)}
- graphUrl={getPrivateUrl(assembly.graphPath)}
- steps={steps}
- activeStepIndex={activeStepIndex}
- onStepChange={setActiveStepIndex}
- readOnly
- mode={mode}
- className="h-full"
- />
- )}
- </ClientOnly>
- </div>
- {activeRequirements.length > 0 && (
- <StepRequirements requirements={activeRequirements} />
- )}
- <div className="grid grid-cols-2 gap-2 border-t border-border bg-background p-3">
- <Button
- size="lg"
- variant="secondary"
- className="h-16 text-lg active:scale-[0.96] transition-transform"
- leftIcon={<LuChevronLeft className="size-6" />}
- isDisabled={activeStepIndex <= 0}
- onClick={() => setActiveStepIndex((index) => Math.max(index - 1, 0))}
- >
- <Trans>Previous</Trans>
- </Button>
- <Button
- size="lg"
- className="h-16 text-lg active:scale-[0.96] transition-transform"
- rightIcon={<LuChevronRight className="size-6" />}
- isDisabled={activeStepIndex >= stepCount - 1}
- onClick={() =>
- setActiveStepIndex((index) => Math.min(index + 1, stepCount - 1))
- }
- >
- <Trans>Next</Trans>
- </Button>
- </div>
- </div>
- );
-}
-
-const severityStyles = {
- Info: { icon: LuInfo, className: "border-blue-500/40 text-blue-600" },
- Caution: {
- icon: LuTriangleAlert,
- className: "border-yellow-500/40 text-yellow-600"
- },
- Warning: {
- icon: LuOctagonAlert,
- className: "border-red-500/40 text-red-600"
- }
-} as const;
-
-/** The active step's process data: notes, tools/fixtures/consumables, media */
-function StepRequirements({
- requirements
-}: {
- requirements: StepRequirement[];
-}) {
- const notes = requirements.filter((r) => r.type === "Note");
- const resources = requirements.filter((r) =>
- ["Tool", "Fixture", "Consumable"].includes(r.type)
- );
- const media = requirements.filter((r) => r.type === "Media" && r.filePath);
-
- return (
- <div className="max-h-56 overflow-y-auto border-t border-border bg-background px-3 py-2">
- <div className="flex flex-col gap-2">
- {notes.map((note) => {
- const { icon: Icon, className } =
- severityStyles[note.severity ?? "Info"];
- return (
- <div
- key={note.id}
- className={cn(
- "flex items-start gap-2 rounded-md border px-3 py-2 text-sm",
- className
- )}
- >
- <Icon className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
- <span className="whitespace-pre-wrap text-foreground">
- {note.text}
- </span>
- </div>
- );
- })}
- {resources.length > 0 && (
- <div className="flex flex-wrap items-center gap-2">
- <LuWrench
- className="h-4 w-4 shrink-0 text-muted-foreground"
- aria-hidden
- />
- {resources.map((resource) => (
- <Badge key={resource.id} variant="secondary">
- {resource.name}
- {resource.quantity > 1 ? ` ×${resource.quantity}` : ""}
- {resource.type !== "Tool" && (
- <span className="ml-1 text-muted-foreground">
- · {resource.type}
- </span>
- )}
- </Badge>
- ))}
- </div>
- )}
- {media.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {media.map((item) => {
- const url = getPrivateUrl(item.filePath ?? "");
- const isVideo = /\.(mp4|mov|webm|avi|mkv)$/i.test(
- item.filePath ?? ""
- );
- return (
- <a
- key={item.id}
- href={url}
- target="_blank"
- rel="noreferrer"
- className="block"
- title={item.name ?? undefined}
- >
- {isVideo ? (
- <span className="flex h-16 w-16 items-center justify-center rounded-md border border-border">
- <LuFileVideo className="h-6 w-6 text-muted-foreground" />
- </span>
- ) : (
- <img
- src={url}
- alt={item.name ?? "Attachment"}
- className="h-16 w-16 rounded-md border border-border object-cover"
- />
- )}
- </a>
- );
- })}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index d928672422..1d7d8fdaa8 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -86,22 +86,48 @@ type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
export function IssueMaterialModal({
operationId,
+ allowPrefill = false,
+ parentUnitCount,
+ issuePerUnit = false,
expiredEntityPolicy = "Block",
locationId,
workCenterId,
material,
parentId,
parentIdIsSerialized,
+ jobOperationStepId,
+ unitNumber,
trackedInputs = [],
onClose
}: {
operationId: string;
+ // Opt-in from the call site to pre-select tracked entities from the picking
+ // list. The process view passes true; the assembly view issues one unit at
+ // a time and never opts in. Even when true, the modal only seeds when the
+ // whole pick provably belongs to the parent entity being issued to: a
+ // picking list exists AND (the parent is not serialized — one entity spans
+ // the whole quantity — or the operation makes exactly one unit, so there is
+ // exactly one parent serial). See canPrefill below.
+ allowPrefill?: boolean;
+ // How many units the operation makes (parent tracked entities for a serial
+ // parent). Required for prefill when the parent is serialized — without it
+ // a serialized parent never prefills.
+ parentUnitCount?: number;
+ // Issue one unit's worth per submission (the assembly view's build-one-at-
+ // a-time flow) instead of defaulting to the whole remaining quantity.
+ // Serial parents always behave this way regardless of this flag.
+ issuePerUnit?: boolean;
expiredEntityPolicy?: ExpiredEntityPolicy;
locationId?: string;
workCenterId?: string;
material?: JobMaterial;
parentId?: string;
parentIdIsSerialized?: boolean;
+ // Assembly view only: the step + 1-based unit the operator is on, stamped onto the
+ // consume so issued quantities can be attributed per-unit/per-step even for a batch
+ // parent (where all units share one lot entity). Omitted by the operation view.
+ jobOperationStepId?: string;
+ unitNumber?: number;
trackedInputs?: TrackedInput[];
onClose: () => void;
}) {
@@ -274,15 +300,25 @@ export function IssueMaterialModal({
}));
}, [trackedInputs]);
- // Quantity for inventory items
+ // Default issue quantity. Serial parents always issue per-unit
+ // (material.quantity is the per-unit requirement and quantityIssued is
+ // scoped to the parent entity). The assembly view issues per-unit for
+ // EVERY parent type (issuePerUnit) — a 10-unit build consumes its parts
+ // one unit at a time, never the whole remaining total in one shot.
+ // Otherwise (process view, non-serial parent) default to the remaining
+ // total for the operation.
const initialQuantity = useMemo(() => {
if (!material) return 1;
- const total = parentIdIsSerialized
- ? (material.quantity ?? material.estimatedQuantity ?? 1)
- : (material.estimatedQuantity ?? material.quantity ?? 1);
- const remaining = total - (material.quantityIssued ?? 0);
- return Math.max(1, remaining);
- }, [material, parentIdIsSerialized]);
+ const perUnit = material.quantity ?? material.estimatedQuantity ?? 1;
+ if (parentIdIsSerialized) {
+ return Math.max(1, perUnit - (material.quantityIssued ?? 0));
+ }
+ if (issuePerUnit) {
+ return Math.max(1, perUnit);
+ }
+ const total = material.estimatedQuantity ?? material.quantity ?? 1;
+ return Math.max(1, total - (material.quantityIssued ?? 0));
+ }, [material, parentIdIsSerialized, issuePerUnit]);
// Serial numbers selection state
const [selectedSerialNumbers, setSelectedSerialNumbers] = useState<
@@ -308,24 +344,40 @@ export function IssueMaterialModal({
const [activeTab, setActiveTab] = useState("scan");
// Pre-fill the selection with the picking list's recommendation (a default
- // only — fully editable below). Two sources feed it, in priority order:
+ // only — fully editable below). Pre-selecting tracked entities is a
+ // traceability hazard: a wrong default an operator blindly accepts records
+ // the wrong genealogy. Every issue submission binds ALL children to ONE
+ // parent tracked entity, so seeding is only trustworthy when the whole
+ // pick provably belongs to that parent. That requires ALL of:
+ // - the call site opted in (`allowPrefill` — the process view; the
+ // assembly view issues one unit at a time so the pick can never be
+ // attributed to the unit on screen),
+ // - the material is actually on a picking list, and
+ // - the parent is a single entity: not serialized (one batch/lot spans
+ // the whole quantity) OR the operation makes exactly one unit (one
+ // parent serial).
+ // Otherwise the modal opens on the Scan tab with nothing selected.
+ // When seeding is allowed, two sources feed it, in priority order:
// 1. the exact lots a picking list already PICKED for this material
// (`pickedAllocation`, from pickingListLineTrackedEntity), and
// 2. the on-the-fly pickMethod suggestion of what to pick
// (`suggestedAllocation`, netted + FEFO/FIFO sorted).
// A material can be on a picking list (quantityToPick > 0) with nothing picked
// yet — e.g. a multi-line list where other lines were picked first. In that
- // state `pickedAllocation` is empty, so we must still surface the suggestion
- // rather than leaving the operator with the default first lot. Hence the
- // suggestion is ALWAYS loaded and used as the fallback, not gated off whenever
- // a picking allocation merely exists.
+ // state `pickedAllocation` is empty, so we still surface the suggestion as
+ // the fallback rather than leaving the operator with the default first lot.
const pickedOverlay = material as
| { quantityToPick?: number | null; quantityPicked?: number | null }
| undefined;
const hasPickingAllocation =
Number(pickedOverlay?.quantityToPick ?? 0) > 0 ||
Number(pickedOverlay?.quantityPicked ?? 0) > 0;
+ const canPrefill =
+ allowPrefill &&
+ hasPickingAllocation &&
+ (!parentIdIsSerialized || parentUnitCount === 1);
const shouldSuggestAllocation =
+ canPrefill &&
!!material &&
!!selectedItemId &&
!!locationId &&
@@ -340,8 +392,8 @@ export function IssueMaterialModal({
: undefined
);
const shouldLoadPickedAllocation =
+ canPrefill &&
!!material?.id &&
- hasPickingAllocation &&
(trackingType === "Batch" || trackingType === "Serial");
const { data: pickedAllocation, resolved: pickedAllocationResolved } =
usePickedAllocation(
@@ -362,36 +414,66 @@ export function IssueMaterialModal({
useEffect(() => {
if (hasSeededSuggestionRef.current) return;
if (!seedAllocation.length) return;
+ // Intersect the seed with what is actually still available before
+ // applying it. The picked allocation is NOT netted by consumption
+ // (pickingListLineTrackedEntity keeps the original picked qty, and a
+ // partial consumption splits the entity into a new id), so re-opening
+ // the modal after a partial issue would otherwise re-suggest lots that
+ // were already consumed. Consumed/unavailable entities drop out of the
+ // options lists, so waiting for those to resolve and filtering against
+ // them nets the seed correctly.
if (trackingType === "Batch") {
+ if (batchNumbers?.data === undefined) return;
// Don't clobber a selection the operator already started if the (async)
// suggestion arrives after they picked.
if (selectedBatchNumbers.some((b) => b.id)) return;
+ const availableById = new Map(
+ batchOptions.map((o) => [o.value, o.availableQuantity])
+ );
+ const lots = seedAllocation
+ .map((lot) => ({
+ ...lot,
+ quantity: Math.min(
+ lot.quantity,
+ availableById.get(lot.trackedEntityId) ?? 0
+ )
+ }))
+ .filter((lot) => lot.quantity > 0);
+ hasSeededSuggestionRef.current = true;
+ if (!lots.length) return;
setSelectedBatchNumbers(
- seedAllocation.map((lot, index) => ({
+ lots.map((lot, index) => ({
index,
id: lot.trackedEntityId,
quantity: lot.quantity
}))
);
setActiveTab("select");
- hasSeededSuggestionRef.current = true;
} else if (trackingType === "Serial") {
+ if (serialNumbers?.data === undefined) return;
if (selectedSerialNumbers.some((s) => s.id)) return;
+ const availableIds = new Set(serialOptions.map((o) => o.value));
+ const lots = seedAllocation.filter((lot) =>
+ availableIds.has(lot.trackedEntityId)
+ );
+ hasSeededSuggestionRef.current = true;
+ if (!lots.length) return;
setSelectedSerialNumbers((prev) =>
prev.map((row, i) =>
- seedAllocation[i]
- ? { ...row, id: seedAllocation[i].trackedEntityId }
- : row
+ lots[i] ? { ...row, id: lots[i].trackedEntityId } : row
)
);
setActiveTab("select");
- hasSeededSuggestionRef.current = true;
}
}, [
seedAllocation,
trackingType,
selectedBatchNumbers,
- selectedSerialNumbers
+ selectedSerialNumbers,
+ batchNumbers,
+ serialNumbers,
+ batchOptions,
+ serialOptions
]);
// Expiry override state. Surfaced when a selected serial/batch is expired.
@@ -528,10 +610,15 @@ export function IssueMaterialModal({
const addSerialNumber = useCallback(() => {
setSelectedSerialNumbers((prev) => {
- // Pre-fill the new row with the next unused serial. Prefer the remaining
- // pick-method-ordered suggestion (FEFO/FIFO/LIFO), so added rows stay
- // consistent with the seeded ones; only fall back to the picker's default
- // FEFO/FIFO order once the suggestion is exhausted. Editable either way.
+ // When prefill is allowed, seed the new row with the next unused serial.
+ // Prefer the remaining pick-method-ordered suggestion (FEFO/FIFO/LIFO),
+ // so added rows stay consistent with the seeded ones; only fall back to
+ // the picker's default FEFO/FIFO order once the suggestion is exhausted.
+ // When prefill is off, the row starts empty — auto-picking a tracked
+ // entity the operator never chose is a traceability hazard.
+ if (!canPrefill) {
+ return [...prev, { index: prev.length, id: "" }];
+ }
const used = new Set(prev.map((s) => s.id).filter(Boolean));
const fromSuggestion = seedAllocation.find(
(lot) => !used.has(lot.trackedEntityId)
@@ -541,7 +628,7 @@ export function IssueMaterialModal({
: serialOptions.find((o) => !used.has(o.value) && !o.isExpired);
return [...prev, { index: prev.length, id: next?.value ?? "" }];
});
- }, [serialOptions, seedAllocation]);
+ }, [serialOptions, seedAllocation, canPrefill]);
const removeSerialNumber = useCallback((indexToRemove: number) => {
setSelectedSerialNumbers((prev) => {
@@ -578,10 +665,15 @@ export function IssueMaterialModal({
const addBatchNumber = useCallback(() => {
setSelectedBatchNumbers((prev) => {
- // Pre-fill the new row with the next unused batch. Prefer the remaining
- // pick-method-ordered suggestion (FEFO/FIFO/LIFO) so added rows match the
- // seeded ones; fall back to the picker's default FEFO/FIFO order once the
- // suggestion is exhausted. Default qty is clamped to the lot's on-hand.
+ // When prefill is allowed, seed the new row with the next unused batch.
+ // Prefer the remaining pick-method-ordered suggestion (FEFO/FIFO/LIFO) so
+ // added rows match the seeded ones; fall back to the picker's default
+ // FEFO/FIFO order once the suggestion is exhausted. Default qty is
+ // clamped to the lot's on-hand. When prefill is off, the row starts
+ // empty — auto-picking a tracked entity is a traceability hazard.
+ if (!canPrefill) {
+ return [...prev, { index: prev.length, id: "", quantity: 1 }];
+ }
const used = new Set(prev.map((b) => b.id).filter(Boolean));
const fromSuggestion = seedAllocation.find(
(lot) => !used.has(lot.trackedEntityId)
@@ -598,7 +690,7 @@ export function IssueMaterialModal({
}
];
});
- }, [batchOptions, seedAllocation]);
+ }, [batchOptions, seedAllocation, canPrefill]);
const removeBatchNumber = useCallback((indexToRemove: number) => {
setSelectedBatchNumbers((prev) => {
@@ -725,6 +817,11 @@ export function IssueMaterialModal({
overrideReason: expiryOverrideReason.trim()
}
: {};
+ // Per-unit/per-step attribution context (assembly view only).
+ const contextFields = {
+ ...(jobOperationStepId ? { jobOperationStepId } : {}),
+ ...(unitNumber !== undefined ? { unitNumber } : {})
+ };
const payload = material?.id
? {
materialId: material.id,
@@ -733,6 +830,7 @@ export function IssueMaterialModal({
trackedEntityId: sn.id,
quantity: 1
})),
+ ...contextFields,
...overrideFields
}
: {
@@ -743,6 +841,7 @@ export function IssueMaterialModal({
trackedEntityId: sn.id,
quantity: 1
})),
+ ...contextFields,
...overrideFields
};
@@ -761,7 +860,9 @@ export function IssueMaterialModal({
selectedItemId,
fetcher,
hasExpiredSelection,
- expiryOverrideReason
+ expiryOverrideReason,
+ jobOperationStepId,
+ unitNumber
]);
const handleSubmitBatch = useCallback(() => {
@@ -797,6 +898,11 @@ export function IssueMaterialModal({
overrideReason: expiryOverrideReason.trim()
}
: {};
+ // Per-unit/per-step attribution context (assembly view only).
+ const contextFields = {
+ ...(jobOperationStepId ? { jobOperationStepId } : {}),
+ ...(unitNumber !== undefined ? { unitNumber } : {})
+ };
const payload = material?.id
? {
materialId: material.id,
@@ -805,6 +911,7 @@ export function IssueMaterialModal({
trackedEntityId: bn.id,
quantity: bn.quantity
})),
+ ...contextFields,
...overrideFields
}
: {
@@ -815,6 +922,7 @@ export function IssueMaterialModal({
trackedEntityId: bn.id,
quantity: bn.quantity
})),
+ ...contextFields,
...overrideFields
};
@@ -833,7 +941,9 @@ export function IssueMaterialModal({
selectedItemId,
fetcher,
hasExpiredSelection,
- expiryOverrideReason
+ expiryOverrideReason,
+ jobOperationStepId,
+ unitNumber
]);
const handleUnconsumeSerial = useCallback(() => {
@@ -1061,14 +1171,17 @@ export function IssueMaterialModal({
materialId: material?.id ?? "",
jobOperationId: operationId,
itemId: selectedItemId,
- // Default to the remaining qty, but never submit zero/negative
- // — that's how this modal ends up posting an invalid form and
- // the server bouncing it silently when a material has been
- // fully issued already.
+ // Default to the remaining qty (or one unit's worth in the
+ // assembly view's one-at-a-time flow), but never submit
+ // zero/negative — that's how this modal ends up posting an
+ // invalid form and the server bouncing it silently when a
+ // material has been fully issued already.
quantity: Math.max(
1,
- (material?.estimatedQuantity ?? 0) -
- (material?.quantityIssued ?? 0)
+ issuePerUnit
+ ? (material?.quantity ?? material?.estimatedQuantity ?? 1)
+ : (material?.estimatedQuantity ?? 0) -
+ (material?.quantityIssued ?? 0)
),
adjustmentType: "Negative Adjmt."
}}
@@ -1077,6 +1190,14 @@ export function IssueMaterialModal({
<ModalBody>
<Hidden name="jobOperationId" />
<Hidden name="materialId" />
+ {/* Scope an unplanned part (no materialId) to the step it's
+ issued on so the assembly view shows it on that step. */}
+ {!material?.id && jobOperationStepId && (
+ <Hidden
+ name="jobOperationStepId"
+ value={jobOperationStepId}
+ />
+ )}
{material?.id && (
<Hidden name="adjustmentType" value="Negative Adjmt." />
)}
@@ -1236,6 +1357,7 @@ export function IssueMaterialModal({
<div className="flex-1">
<InputGroup>
<Input
+ autoFocus={index === 0}
placeholder={`Serial Number ${index + 1}`}
value={sn.id}
onChange={(e) => {
@@ -1251,6 +1373,15 @@ export function IssueMaterialModal({
newSerialNumbers
);
}}
+ onKeyDown={(e) => {
+ // Barcode scanners emit the code then an
+ // Enter keystroke — submit the issue on
+ // Enter, same as clicking Issue.
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSubmitSerial();
+ }
+ }}
onBlur={(e) => {
const newValue = e.target.value;
const error = validateSerialNumber(
@@ -1476,6 +1607,7 @@ export function IssueMaterialModal({
<div className="flex-1">
<InputGroup>
<Input
+ autoFocus={index === 0}
value={batch.id}
onChange={(e) => {
const newValue = e.target.value;
@@ -1484,6 +1616,15 @@ export function IssueMaterialModal({
id: newValue
});
}}
+ onKeyDown={(e) => {
+ // Barcode scanners emit the code then an
+ // Enter keystroke — submit the issue on
+ // Enter, same as clicking Issue.
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSubmitBatch();
+ }
+ }}
onBlur={(e) => {
validateBatchInput(
e.target.value,
diff --git a/apps/mes/app/entry.client.tsx b/apps/mes/app/entry.client.tsx
index 9e6b456ed4..bae67cb270 100644
--- a/apps/mes/app/entry.client.tsx
+++ b/apps/mes/app/entry.client.tsx
@@ -1,3 +1,8 @@
+import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";
+import { pdfjs } from "react-pdf";
+
+pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
+
import { ensureLoggingConfigured } from "@carbon/logger/config.client";
import { Fragment, startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index a83ab903e5..96463391da 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -216,7 +216,7 @@ function Document({
}}
/>
) : null}
- <Toaster position="bottom-right" visibleToasts={5} />
+ <Toaster position="bottom-left" visibleToasts={5} />
<ScrollRestoration />
<Scripts />
{!CONTROLLED_ENVIRONMENT && import.meta.env.PROD && <Analytics />}
diff --git a/apps/mes/app/routes/x+/assembly.$operationId.tsx b/apps/mes/app/routes/x+/assembly.$operationId.tsx
new file mode 100644
index 0000000000..1c4dafc771
--- /dev/null
+++ b/apps/mes/app/routes/x+/assembly.$operationId.tsx
@@ -0,0 +1,273 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { getUserClaims } from "@carbon/auth/users.server";
+import type { ComponentProps } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useParams } from "react-router";
+import { AssemblyView } from "~/components/AssemblyView";
+import { getCompanySettings } from "~/services/inventory.service";
+import {
+ getAssemblyPlaybackByOperationId,
+ getJobByOperationId,
+ getJobMakeMethod,
+ getJobMaterialsByOperationId,
+ getJobOperationById,
+ getJobOperationProcedure,
+ getKanbanByJobId,
+ getModelUploadsByIds,
+ getNcrsByJobOperationId,
+ getNonConformanceActions,
+ getProductionEventsForJobOperation,
+ getProductionQuantitiesForJobOperation,
+ getThumbnailPathByItemId,
+ getToolsByOperationId,
+ getTrackedEntitiesByMakeMethodId,
+ getWorkCenter
+} from "~/services/operations.service";
+import type { OperationWithDetails } from "~/services/types";
+import { makeDurations } from "~/utils/durations";
+import { resolveOperationView } from "~/utils/operationView";
+import { path } from "~/utils/path";
+
+type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { userId, companyId } = await requirePermissions(request, {});
+
+ // Manager-only "complete all steps" override is gated on the Production DELETE permission:
+ // operators hold view/create/update (they record steps) but not delete, so delete cleanly
+ // separates managers from operators regardless of how a company names its employee types.
+ const claims = await getUserClaims(userId, companyId);
+ const canOverrideComplete =
+ claims?.permissions?.production?.delete?.some(
+ (c) => c === "0" || c === companyId
+ ) ?? false;
+
+ const { operationId } = params;
+ if (!operationId) throw new Error("Operation ID is required");
+
+ const url = new URL(request.url);
+ const trackedEntityId = url.searchParams.get("trackedEntityId");
+
+ const serviceRole = await getCarbonServiceRole();
+
+ const [job, operation] = await Promise.all([
+ getJobByOperationId(serviceRole, operationId),
+ getJobOperationById(serviceRole, operationId)
+ ]);
+
+ if (job.error)
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(job.error, "Failed to fetch job"))
+ );
+ if (operation.error)
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(operation.error, "Failed to fetch operation"))
+ );
+
+ const op = operation.data?.[0];
+ if (!op) throw redirect(path.to.operations);
+
+ // Redirect guard (ADR-0005): only Assembly operations render here. Anything else goes
+ // back to the operation route (which renders its own view, or redirects again). Guards
+ // only redirect kinds they don't serve, so no loop.
+ if (resolveOperationView(op.operationType) !== "assembly") {
+ throw redirect(path.to.operation(operationId) + url.search);
+ }
+
+ const [
+ thumbnailPath,
+ trackedEntities,
+ jobMakeMethod,
+ procedure,
+ tools,
+ ncrs,
+ events,
+ nonConformanceActions,
+ assemblyPlayback
+ ] = await Promise.all([
+ getThumbnailPathByItemId(serviceRole, op.itemId),
+ getTrackedEntitiesByMakeMethodId(serviceRole, op.jobMakeMethodId),
+ getJobMakeMethod(serviceRole, op.jobMakeMethodId),
+ getJobOperationProcedure(serviceRole, operationId),
+ getToolsByOperationId(serviceRole, operationId),
+ getNcrsByJobOperationId(serviceRole, operationId),
+ getProductionEventsForJobOperation(serviceRole, { operationId, userId }),
+ getNonConformanceActions(serviceRole, {
+ itemId: op.itemId,
+ processId: op.processId,
+ companyId
+ }),
+ getAssemblyPlaybackByOperationId(serviceRole, operationId)
+ ]);
+
+ // 3D model slides reference modelUpload rows; resolve their render metadata
+ // (glbPath / modelPath / thumbnail) in one query.
+ const slideModelIds = Array.from(
+ new Set(
+ procedure.attributes.flatMap((step) =>
+ (step.jobOperationStepSlide ?? []).map((slide) => slide.modelUploadId)
+ )
+ )
+ ).filter((id): id is string => !!id);
+
+ const [quantities, workCenter, kanban, slideModelUploads] = await Promise.all(
+ [
+ getProductionQuantitiesForJobOperation(serviceRole, operationId),
+ getWorkCenter(serviceRole, op.workCenterId),
+ job.data.id ? getKanbanByJobId(serviceRole, job.data.id) : null,
+ slideModelIds.length > 0
+ ? getModelUploadsByIds(serviceRole, slideModelIds)
+ : null
+ ]
+ );
+
+ const productionQuantities = (quantities.data ?? []).reduce(
+ (acc, curr) => {
+ if (curr.type === "Scrap") acc.scrap += curr.quantity;
+ else if (curr.type === "Production") acc.production += curr.quantity;
+ else if (curr.type === "Rework") acc.rework += curr.quantity;
+ return acc;
+ },
+ { scrap: 0, production: 0, rework: 0 }
+ );
+
+ // Expiry policy for the issue-material modal — same source as the operation view.
+ const companySettings = await getCompanySettings(serviceRole, companyId);
+ const inventoryShelfLife = (companySettings.data?.inventoryShelfLife ??
+ null) as { expiredEntityPolicy?: ExpiredEntityPolicy } | null;
+ const expiredEntityPolicy: ExpiredEntityPolicy =
+ inventoryShelfLife?.expiredEntityPolicy ?? "Block";
+
+ // Passive operation timer (opt-in). When on, the assembly view auto-starts the operator's
+ // timer on open (see AutoTimer in AssemblyView). It never auto-ends a timer.
+ const autoStartOperationTimer =
+ companySettings.data?.autoStartOperationTimer ?? false;
+
+ // Resolve the unit the materials/consume target key off. Only serial/batch parents
+ // bind per-unit tracked entities; inventory/non-inventory parents page purely by index,
+ // so their stray inventory entities must NOT seed the unit axis. Navigable units are
+ // capped to the operation quantity (a job can pre-generate extra serials). An explicit
+ // ?trackedEntityId wins; otherwise honor the ?unit index, so client navigation to an
+ // untracked unit isn't snapped back to unit 0.
+ const allEntities = trackedEntities.data ?? [];
+ const opQty = Math.max(
+ 1,
+ Math.round((op.operationQuantity as number) ?? allEntities.length)
+ );
+ const isParentTracked =
+ (jobMakeMethod.data?.requiresSerialTracking ?? false) ||
+ (jobMakeMethod.data?.requiresBatchTracking ?? false);
+ const navEntities = isParentTracked ? allEntities.slice(0, opQty) : [];
+ const unitParam = Number.parseInt(url.searchParams.get("unit") ?? "", 10);
+ const entityIndex = trackedEntityId
+ ? navEntities.findIndex((te) => te.id === trackedEntityId)
+ : -1;
+ // Must match AssemblyView.currentUnitIndex: with no explicit ?unit/?trackedEntityId,
+ // land on the NEXT unit still to build (quantityComplete), not unit 0 — for EVERY
+ // tracking type. A serial parent seeds trackedEntityId to this unit's entity below,
+ // so a fresh load resumes on the in-progress unit instead of a finished unit 1. The
+ // component deletes ?unit after completing a unit and rolls forward on quantityComplete;
+ // material issue attribution also keys off this unit, so a stale 0 would mis-credit it.
+ const quantityComplete = Math.max(
+ 0,
+ Math.round((op.quantityComplete as number) ?? 0)
+ );
+ const defaultUnitIndex = Math.min(quantityComplete, Math.max(0, opQty - 1));
+ const unitIndex =
+ entityIndex >= 0
+ ? entityIndex
+ : Number.isInteger(unitParam) && unitParam >= 0 && unitParam < opQty
+ ? unitParam
+ : defaultUnitIndex;
+ // A batch parent shares ONE lot across every unit, so its lot entity binds to all
+ // units regardless of the unit index; a serial parent binds a distinct entity per
+ // unit (navEntities[unitIndex]).
+ const effectiveEntityId =
+ (jobMakeMethod.data?.requiresBatchTracking ?? false)
+ ? navEntities[0]?.id
+ : navEntities[unitIndex]?.id;
+
+ const [materials, openEvent] = await Promise.all([
+ getJobMaterialsByOperationId(serviceRole, {
+ operation: op,
+ trackedEntityId: effectiveEntityId,
+ requiresSerialTracking:
+ jobMakeMethod.data?.requiresSerialTracking ?? false,
+ requiresBatchTracking: jobMakeMethod.data?.requiresBatchTracking ?? false,
+ unitIndex
+ }),
+ // Open Labor production event for this operator+operation drives the timer.
+ serviceRole
+ .from("productionEvent")
+ .select("id, startTime")
+ .eq("jobOperationId", op.id)
+ .eq("employeeId", userId)
+ .eq("type", "Labor")
+ .is("endTime", null)
+ .order("startTime", { ascending: false })
+ .limit(1)
+ .maybeSingle()
+ ]);
+
+ return {
+ job: job.data,
+ operation: makeDurations(op) as OperationWithDetails,
+ thumbnailPath,
+ trackedEntities: trackedEntities.data ?? [],
+ // The resolved entity for the current unit, or null for untracked units, so the
+ // component falls back to the ?unit index instead of snapping back to unit 0.
+ trackedEntityId: effectiveEntityId ?? null,
+ materials,
+ procedure,
+ tools: tools.data ?? [],
+ ncrs: ncrs.data ?? [],
+ requiresSerialTracking: jobMakeMethod.data?.requiresSerialTracking ?? false,
+ requiresBatchTracking: jobMakeMethod.data?.requiresBatchTracking ?? false,
+ openEvent: openEvent.data ?? null,
+ events: events.data ?? [],
+ nonConformanceActions,
+ expiredEntityPolicy,
+ autoStartOperationTimer,
+ productionQuantities,
+ workCenter:
+ (workCenter.data as {
+ id: string;
+ name: string;
+ isBlocked: boolean | null;
+ blockingDispatchId: string | null;
+ blockingDispatchReadableId: string | null;
+ } | null) ?? null,
+ kanban: kanban?.data ?? null,
+ jobId: job.data.id ?? null,
+ canOverrideComplete,
+ modelPath:
+ (op as { itemModelPath?: string | null }).itemModelPath ??
+ (job.data as { modelPath?: string | null }).modelPath ??
+ null,
+ slideModels: Object.fromEntries(
+ (slideModelUploads?.data ?? []).map((model) => [model.id, model])
+ ),
+ assemblyPlayback
+ };
+}
+
+export default function AssemblyRoute() {
+ const { operationId } = useParams();
+ if (!operationId) throw new Error("Operation ID is required");
+
+ const data = useLoaderData<typeof loader>();
+ // The generated DB types leave JSONB columns as `Json`; the slide annotations
+ // are written exclusively by the ERP editors through slideAnnotationValidator,
+ // so the view's narrowed pin type is the real runtime shape.
+ const procedure = data.procedure as unknown as ComponentProps<
+ typeof AssemblyView
+ >["procedure"];
+ return (
+ <AssemblyView {...data} procedure={procedure} operationId={operationId} />
+ );
+}
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index 053c7df38e..3cf243ce4b 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -30,10 +30,40 @@ export async function action({ request }: ActionFunctionArgs) {
action: productionAction,
timezone,
trackedEntityId,
+ unitIndex,
+ exclusive,
...d
} = validation.data;
if (productionAction === "Start") {
+ // Single-phase (assembly) clocking: end any other open work type for this
+ // operator on this operation before starting, so Setup and Labor can never
+ // run simultaneously. Post each ended event so its cost still books.
+ if (exclusive === "true") {
+ const openOthers = await client
+ .from("productionEvent")
+ .select("id")
+ .eq("jobOperationId", d.jobOperationId)
+ .eq("employeeId", userId)
+ .is("endTime", null)
+ .neq("type", d.type);
+ if (openOthers.data && openOthers.data.length > 0) {
+ const serviceRole = await getCarbonServiceRole();
+ const endTime = now(timezone ?? getLocalTimeZone()).toAbsoluteString();
+ for (const ev of openOthers.data) {
+ const ended = await endProductionEvent(client, {
+ id: ev.id,
+ endTime,
+ employeeId: userId
+ });
+ if (ended.data && ended.data.length > 0) {
+ await serviceRole.functions.invoke("post-production-event", {
+ body: { productionEventId: ended.data[0].id, userId, companyId }
+ });
+ }
+ }
+ }
+ }
const startEvent = await startProductionEvent(
client,
{
@@ -43,7 +73,8 @@ export async function action({ request }: ActionFunctionArgs) {
companyId,
createdBy: userId
},
- trackedEntityId
+ trackedEntityId,
+ unitIndex
);
if (startEvent.error) {
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
new file mode 100644
index 0000000000..4ab8fa1c29
--- /dev/null
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
@@ -0,0 +1,136 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { inspectionCompletePassedValidator } from "~/services/models";
+import {
+ getInspectionOutcomeState,
+ getSerialCompletionCandidates,
+ postBulkCompletion,
+ postSerialCompletions
+} from "~/services/quality.server";
+import { path } from "~/utils/path";
+
+// Progressive completion while the lot stays open: any unit that passed
+// inspection can move on immediately, without waiting for the disposition.
+// Explicit (a button, not auto-on-pass) so a verdict typo doesn't need a
+// compensating transaction — un-posted verdicts stay editable.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "quality"
+ });
+ const { id } = params;
+ if (!id) throw new Error("id is required");
+
+ const formData = await request.formData();
+ const validation = await validator(
+ inspectionCompletePassedValidator
+ ).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const {
+ operationId,
+ setupProductionEventId,
+ laborProductionEventId,
+ machineProductionEventId
+ } = validation.data;
+ const eventIds = {
+ setupProductionEventId,
+ laborProductionEventId,
+ machineProductionEventId
+ };
+ const returnTo = path.to.inspection(operationId);
+ const fail = async (err: unknown, message: string): Promise<never> => {
+ throw redirect(returnTo, await flash(request, error(err, message)));
+ };
+
+ const serviceRole = await getCarbonServiceRole();
+ const stateResult = await getInspectionOutcomeState(serviceRole, {
+ inspectionId: id,
+ companyId
+ });
+ if (stateResult.error !== null || !stateResult.data) {
+ return fail(stateResult.error, stateResult.message ?? "Failed to load lot");
+ }
+ const state = stateResult.data;
+ if (state.jobOperationId !== operationId) {
+ return fail(null, "Operation does not match the inspection lot");
+ }
+ if (["Passed", "Failed", "Partial"].includes(state.inspection.status)) {
+ return fail(null, "Inspection is closed — the disposition already ran");
+ }
+
+ if (state.requiresSerialTracking) {
+ const candidates = getSerialCompletionCandidates(state, {
+ includePending: false,
+ includeSampleless: false
+ });
+ if (candidates.length === 0) {
+ return fail(null, "No passed units to complete");
+ }
+ if (candidates.length > state.opRemaining) {
+ return fail(
+ null,
+ `Passed units (${candidates.length}) exceed the operation's remaining quantity (${state.opRemaining}) — quantities were already recorded from the actions menu`
+ );
+ }
+ const completions = await postSerialCompletions(serviceRole, {
+ candidates,
+ jobOperationId: state.jobOperationId,
+ inspectionId: id,
+ eventIds,
+ companyId,
+ userId
+ });
+ if (completions.error) {
+ return fail(
+ completions.error,
+ `Completing units failed after ${completions.completed} of ${candidates.length}`
+ );
+ }
+ throw redirect(
+ returnTo,
+ await flash(
+ request,
+ success(
+ `${completions.completed} unit${completions.completed === 1 ? "" : "s"} completed`
+ )
+ )
+ );
+ }
+
+ const passedCount = state.samples.filter((s) => s.status === "Passed").length;
+ const quantity = Math.min(
+ Math.max(0, passedCount - state.linkedProductionQuantity),
+ state.opRemaining
+ );
+ if (quantity <= 0) {
+ return fail(null, "No passed units to complete");
+ }
+
+ const completion = await postBulkCompletion(serviceRole, client, state, {
+ quantity,
+ eventIds,
+ companyId,
+ userId
+ });
+ if (completion.error) {
+ return fail(
+ completion.error,
+ completion.message ?? "Failed to complete units"
+ );
+ }
+
+ throw redirect(
+ returnTo,
+ await flash(
+ request,
+ success(`${quantity} unit${quantity === 1 ? "" : "s"} completed`)
+ )
+ );
+}
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
new file mode 100644
index 0000000000..c66f148c56
--- /dev/null
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
@@ -0,0 +1,403 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { dispositionInspection } from "@carbon/database/quality";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
+import { inspectionDispositionValidator } from "~/services/models";
+import {
+ finishJobOperation,
+ insertScrapQuantity
+} from "~/services/operations.service";
+import {
+ createInspectionRejectionIssue,
+ getInspectionOutcomeState,
+ getSerialCompletionCandidates,
+ postBulkCompletion,
+ postSerialCompletions
+} from "~/services/quality.server";
+import { path } from "~/utils/path";
+
+// One decision surface: the quality verdict carries its physical outcome.
+// Accept completes the remaining lot; Reject/Partial split the failed set
+// between Scrap (reason) and Rework (upstream target via trigger-rework's
+// routing clone — the cloned Inspection op re-inspects for free) — or record
+// only. The disposition is one-shot (requireOpen): postings can never re-run.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "quality"
+ });
+ const { id } = params;
+ if (!id) throw new Error("id is required");
+
+ const formData = await request.formData();
+ const validation = await validator(inspectionDispositionValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const {
+ decision,
+ operationId,
+ scrapReasonId,
+ targetOperationId,
+ reworkReason,
+ createNcr,
+ nonConformanceTypeId,
+ setupProductionEventId,
+ laborProductionEventId,
+ machineProductionEventId
+ } = validation.data;
+ const eventIds = {
+ setupProductionEventId,
+ laborProductionEventId,
+ machineProductionEventId
+ };
+ const returnTo = path.to.inspection(operationId);
+ const fail = async (err: unknown, message: string): Promise<never> => {
+ throw redirect(returnTo, await flash(request, error(err, message)));
+ };
+
+ const parseIds = (json: string | undefined): string[] => {
+ if (!json) return [];
+ try {
+ const parsed = JSON.parse(json);
+ return Array.isArray(parsed) ? parsed.filter(Boolean) : [];
+ } catch {
+ return [];
+ }
+ };
+ const scrapEntityIds = parseIds(validation.data.scrapEntityIds);
+ const reworkEntityIds = parseIds(validation.data.reworkEntityIds);
+
+ const serviceRole = await getCarbonServiceRole();
+
+ // ---------------------------------------------------------------
+ // 1. Recompute every bucket fresh from the DB (form fields are
+ // operator intent, not trusted arithmetic) and validate.
+ // ---------------------------------------------------------------
+ const stateResult = await getInspectionOutcomeState(serviceRole, {
+ inspectionId: id,
+ companyId
+ });
+ if (stateResult.error !== null || !stateResult.data) {
+ return fail(stateResult.error, stateResult.message ?? "Failed to load lot");
+ }
+ const state = stateResult.data;
+ if (state.jobOperationId !== operationId) {
+ return fail(null, "Operation does not match the inspection lot");
+ }
+
+ const inspectedCount = state.samples.filter(
+ (s) => s.status !== "Pending"
+ ).length;
+ const passedCount = state.samples.filter((s) => s.status === "Passed").length;
+ const failedCount = state.samples.filter((s) => s.status === "Failed").length;
+ const failedEntityIds = new Set(
+ state.samples
+ .filter((s) => s.status === "Failed")
+ .map((s) => s.trackedEntityId)
+ .filter((entityId): entityId is string => Boolean(entityId))
+ );
+
+ // Partial is the terminal mixed close — only meaningful when every unit has
+ // its own verdict (the operational meaning of "inspect all").
+ if (decision === "Partial") {
+ if (
+ inspectedCount < state.lotSize ||
+ passedCount === 0 ||
+ failedCount === 0
+ ) {
+ return fail(
+ null,
+ "Partial disposition requires every unit inspected with both passes and failures"
+ );
+ }
+ }
+
+ // Serial allocation checks: ids must be this lot's WIP, still open at this
+ // operation, and each unit allocated to exactly one outcome.
+ let completionCandidates: {
+ trackedEntityId: string;
+ inspectionSampleId: string | null;
+ }[] = [];
+ let completionQuantity = 0;
+ const scrapTotal = state.requiresSerialTracking
+ ? scrapEntityIds.length
+ : (validation.data.scrapQuantity ?? 0);
+ const reworkTotal = state.requiresSerialTracking
+ ? reworkEntityIds.length
+ : (validation.data.reworkQuantity ?? 0);
+
+ if (decision === "Accept" && scrapTotal + reworkTotal > 0) {
+ return fail(null, "Accept cannot scrap or rework units");
+ }
+
+ if (state.requiresSerialTracking) {
+ const allocated = new Set([...scrapEntityIds, ...reworkEntityIds]);
+ if (allocated.size < scrapEntityIds.length + reworkEntityIds.length) {
+ return fail(null, "A unit cannot be both scrapped and reworked");
+ }
+ for (const entityId of allocated) {
+ if (!state.entityEligible(entityId)) {
+ return fail(
+ null,
+ "An allocated unit is no longer open at this operation — reload and retry"
+ );
+ }
+ if (decision === "Partial" && !failedEntityIds.has(entityId)) {
+ return fail(null, "Partial can only scrap or rework failed units");
+ }
+ }
+ if (decision === "Accept") {
+ completionCandidates = getSerialCompletionCandidates(state, {
+ includePending: true,
+ includeSampleless: true,
+ excludeEntityIds: failedEntityIds
+ });
+ } else if (decision === "Partial") {
+ completionCandidates = getSerialCompletionCandidates(state, {
+ includePending: false,
+ includeSampleless: false,
+ excludeEntityIds: allocated
+ });
+ }
+ completionQuantity = completionCandidates.length;
+ } else {
+ if (decision === "Partial" && scrapTotal + reworkTotal > failedCount) {
+ return fail(null, "Allocation exceeds the failed unit count");
+ }
+ if (decision === "Accept") {
+ completionQuantity = state.opRemaining;
+ } else if (decision === "Partial") {
+ completionQuantity = Math.max(
+ 0,
+ passedCount - state.linkedProductionQuantity
+ );
+ }
+ }
+
+ // Clamp to the operation column's remaining quantity — escape-hatch menu
+ // postings already recorded there can never be double-counted. Serial
+ // divergence blocks (silently dropping identified units would lie).
+ const postedTotal = completionQuantity + scrapTotal + reworkTotal;
+ if (postedTotal > state.opRemaining) {
+ if (state.requiresSerialTracking) {
+ return fail(
+ null,
+ `Allocated units (${postedTotal}) exceed the operation's remaining quantity (${state.opRemaining}) — quantities were already recorded from the actions menu`
+ );
+ }
+ return fail(
+ null,
+ `Allocation (${postedTotal}) exceeds the operation's remaining quantity (${state.opRemaining})`
+ );
+ }
+
+ // ---------------------------------------------------------------
+ // 2. Close the lot FIRST — the one-shot requireOpen update is the
+ // serialization point; a concurrent second POST dies here before
+ // any posting can re-run.
+ // ---------------------------------------------------------------
+ const dispositionResult = await dispositionInspection(getDatabaseClient(), {
+ id,
+ decision,
+ companyId,
+ dispositionedBy: userId,
+ requireOpen: true
+ });
+ if (dispositionResult.error) {
+ return fail(dispositionResult.error, "Failed to disposition lot");
+ }
+
+ // ---------------------------------------------------------------
+ // 3. Physical postings. Failures past this point leave the lot
+ // closed with partial postings — surfaced loudly; the ERP's
+ // productionQuantity records (and their links) self-heal the
+ // arithmetic for whatever is re-posted manually.
+ // ---------------------------------------------------------------
+ const warnings: string[] = [];
+
+ if (completionQuantity > 0) {
+ if (state.requiresSerialTracking) {
+ const completions = await postSerialCompletions(serviceRole, {
+ candidates: completionCandidates,
+ jobOperationId: state.jobOperationId,
+ inspectionId: id,
+ eventIds,
+ companyId,
+ userId
+ });
+ if (completions.error) {
+ return fail(
+ completions.error,
+ `Lot dispositioned, but completing units failed after ${completions.completed} of ${completionQuantity}`
+ );
+ }
+ } else {
+ const completion = await postBulkCompletion(serviceRole, client, state, {
+ quantity: completionQuantity,
+ eventIds,
+ companyId,
+ userId
+ });
+ if (completion.error) {
+ return fail(
+ completion.error,
+ `Lot dispositioned, but ${completion.message ?? "completing units failed"}`
+ );
+ }
+ }
+ }
+
+ if (scrapTotal > 0 && scrapReasonId) {
+ const scrapResult = await insertScrapQuantity(client, {
+ jobOperationId: state.jobOperationId,
+ quantity: scrapTotal,
+ scrapReasonId,
+ inspectionId: id,
+ ...eventIds,
+ companyId,
+ createdBy: userId
+ });
+ if (scrapResult.error) {
+ return fail(
+ scrapResult.error,
+ "Lot dispositioned, but recording scrap failed"
+ );
+ }
+
+ // Scrapped WIP serials leave the flow for good: Rejected keeps them out
+ // of inventory and out of complete_job_to_inventory's release at the
+ // last operation. Reworked units are NOT flipped — they continue through
+ // the cloned branch.
+ if (state.requiresSerialTracking && scrapEntityIds.length > 0) {
+ const flip = await serviceRole
+ .from("trackedEntity")
+ .update({ status: "Rejected" })
+ .in("id", scrapEntityIds)
+ .eq("companyId", companyId);
+ if (flip.error) {
+ warnings.push("failed to mark scrapped units Rejected");
+ }
+ }
+
+ const backflush = await serviceRole.functions.invoke("issue", {
+ body: {
+ id: state.jobOperationId,
+ type: "jobOperation",
+ quantity: scrapTotal,
+ companyId,
+ userId
+ }
+ });
+ if (backflush.error) {
+ warnings.push("failed to issue materials for scrap");
+ }
+ }
+
+ if (reworkTotal > 0 && targetOperationId && reworkReason) {
+ const rework = await serviceRole.functions.invoke("trigger-rework", {
+ body: {
+ jobId: state.jobId,
+ triggeredAtJobOperationId: state.jobOperationId,
+ targetJobOperationId: targetOperationId,
+ reason: reworkReason,
+ quantity: reworkTotal,
+ trackedEntityIds: state.requiresSerialTracking
+ ? reworkEntityIds
+ : undefined,
+ inspectionId: id,
+ companyId,
+ userId
+ }
+ });
+ if (rework.error) {
+ return fail(
+ rework.error,
+ "Lot dispositioned, but triggering rework failed"
+ );
+ }
+
+ const recalculate = await serviceRole.functions.invoke("recalculate", {
+ body: {
+ type: "jobRequirements",
+ id: state.jobId,
+ companyId,
+ userId
+ }
+ });
+ if (recalculate.error) {
+ warnings.push("failed to recalculate job requirements");
+ }
+ }
+
+ // NCR is optional documentation — never required for scrap or rework.
+ if (decision !== "Accept" && createNcr === "true") {
+ const issue = await createInspectionRejectionIssue(serviceRole, {
+ inspectionId: id,
+ companyId,
+ userId,
+ nonConformanceTypeId
+ });
+ if (issue.error || issue.message) {
+ warnings.push(issue.message ?? "failed to create quality issue");
+ }
+ }
+
+ // Mirror complete.tsx: the quantity interceptor auto-flips Done when the
+ // column sum reaches a positive target; the explicit finish covers
+ // targetQuantity = 0 operations.
+ const willBeFinished =
+ (postedTotal > 0 || decision === "Accept") &&
+ state.opAccounted + postedTotal >=
+ (state.operation.targetQuantity ??
+ state.operation.operationQuantity ??
+ 0);
+ if (willBeFinished) {
+ const finishResult = await finishJobOperation(serviceRole, {
+ jobOperationId: state.jobOperationId,
+ userId,
+ companyId
+ });
+ if (finishResult.error) {
+ warnings.push("failed to finish the operation");
+ }
+ }
+
+ const outcomes = [
+ completionQuantity > 0 &&
+ `${completionQuantity} unit${completionQuantity === 1 ? "" : "s"} completed`,
+ scrapTotal > 0 && `${scrapTotal} scrapped`,
+ reworkTotal > 0 && `${reworkTotal} sent to rework`
+ ]
+ .filter(Boolean)
+ .join(", ");
+ const headline =
+ decision === "Accept"
+ ? "Lot accepted"
+ : decision === "Reject"
+ ? "Lot rejected"
+ : "Lot partially accepted";
+ const message = outcomes ? `${headline} — ${outcomes}` : headline;
+
+ if (warnings.length > 0) {
+ throw redirect(
+ willBeFinished ? path.to.operations : returnTo,
+ await flash(
+ request,
+ error(null, `${message}, but ${warnings.join("; ")}`)
+ )
+ );
+ }
+
+ throw redirect(
+ willBeFinished ? path.to.operations : returnTo,
+ await flash(request, success(message))
+ );
+}
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.measurement.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.measurement.tsx
new file mode 100644
index 0000000000..ba0109a8df
--- /dev/null
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.measurement.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { upsertInspectionMeasurement } from "@carbon/database/quality";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
+import { inspectionMeasurementValidator } from "~/services/models";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "quality"
+ });
+ const { id } = params;
+ if (!id) throw new Error("id is required");
+
+ const formData = await request.formData();
+ const validation = await validator(inspectionMeasurementValidator).validate(
+ formData
+ );
+ if (validation.error) return validationError(validation.error);
+
+ if (validation.data.inspectionId !== id) {
+ return data(
+ { error: { message: "Inspection id mismatch" } },
+ await flash(request, error(null, "Inspection id mismatch"))
+ );
+ }
+
+ const result = await upsertInspectionMeasurement(getDatabaseClient(), {
+ ...validation.data,
+ companyId,
+ userId
+ });
+
+ if (result.error) {
+ return data(
+ { error: result.error },
+ await flash(request, error(result.error, "Failed to save measurement"))
+ );
+ }
+
+ // No success flash — per-cell saves must be quiet; the matrix consumes the
+ // returned ids/statuses to update itself.
+ return data(result);
+}
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx
new file mode 100644
index 0000000000..e679a72562
--- /dev/null
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx
@@ -0,0 +1,57 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { upsertInspectionSample } from "@carbon/database/quality";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
+import { inspectionSampleValidator } from "~/services/models";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "quality"
+ });
+ const { id } = params;
+ if (!id) throw new Error("id is required");
+
+ const formData = await request.formData();
+ // Quiet saves come from the measurement matrix's "Overall result" cells via
+ // a raw fetch (no revalidation), so a flash cookie would surface as a stray
+ // toast on the next navigation — suppress it and just return the sample id.
+ const quiet = formData.get("quiet") === "true";
+ const validation = await validator(inspectionSampleValidator).validate(
+ formData
+ );
+ if (validation.error) return validationError(validation.error);
+
+ if (validation.data.inspectionId !== id) {
+ return data(
+ { error: { message: "Inspection id mismatch" } },
+ await flash(request, error(null, "Inspection id mismatch"))
+ );
+ }
+
+ const result = await upsertInspectionSample(getDatabaseClient(), {
+ ...validation.data,
+ companyId,
+ inspectedBy: userId
+ });
+
+ if (result.error) {
+ return data(
+ { error: result.error },
+ await flash(request, error(result.error, "Failed to save sample"))
+ );
+ }
+
+ if (quiet) {
+ return data({ success: true, sampleId: result.data.id });
+ }
+
+ return data(
+ { success: true, sampleId: result.data.id },
+ await flash(request, success("Sample recorded"))
+ );
+}
diff --git a/apps/mes/app/routes/x+/inspection.$operationId.tsx b/apps/mes/app/routes/x+/inspection.$operationId.tsx
new file mode 100644
index 0000000000..04a089aec5
--- /dev/null
+++ b/apps/mes/app/routes/x+/inspection.$operationId.tsx
@@ -0,0 +1,194 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ getOrCreateJobOperationInspection,
+ reconcileInspectionSamplingPlans
+} from "@carbon/database/quality";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useParams } from "react-router";
+import { InspectionView } from "~/components/Inspection/InspectionView";
+import { getDatabaseClient } from "~/services/database.server";
+import {
+ getJobByOperationId,
+ getJobMakeMethod,
+ getJobOperationById,
+ getProductionEventsForJobOperation,
+ getProductionQuantitiesForJobOperation,
+ getTrackedEntitiesByMakeMethodId
+} from "~/services/operations.service";
+import {
+ getInspection,
+ getInspectionDocumentWithBalloons,
+ getInspectionMeasurements,
+ getInspectionSamplingPlans,
+ getIssueTypesList
+} from "~/services/quality.service";
+import type { InspectionSample, OperationWithDetails } from "~/services/types";
+import { makeDurations } from "~/utils/durations";
+import { resolveOperationView } from "~/utils/operationView";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { userId, companyId } = await requirePermissions(request, {});
+
+ const { operationId } = params;
+ if (!operationId) throw new Error("Operation ID is required");
+
+ const url = new URL(request.url);
+ const serviceRole = await getCarbonServiceRole();
+
+ const [job, operation] = await Promise.all([
+ getJobByOperationId(serviceRole, operationId),
+ getJobOperationById(serviceRole, operationId)
+ ]);
+
+ if (job.error)
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(job.error, "Failed to fetch job"))
+ );
+ if (operation.error)
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(operation.error, "Failed to fetch operation"))
+ );
+
+ const op = operation.data?.[0];
+ if (!op) throw redirect(path.to.operations);
+
+ // Redirect guard (ADR-0005): only Inspection operations render here.
+ // Guards only redirect kinds they don't serve, so no loop.
+ if (resolveOperationView(op.operationType) !== "inspection") {
+ throw redirect(path.to.operation(operationId) + url.search);
+ }
+
+ // Lazy find-or-create of the inspection lot for this operation — mirrors
+ // post-receipt lot creation (plan snapshot + per-feature plans from the
+ // operation's inspectionDocumentId FK). Idempotent per (sourceDocument,
+ // sourceDocumentLineId).
+ const lot = await getOrCreateJobOperationInspection(getDatabaseClient(), {
+ jobOperationId: operationId,
+ companyId,
+ userId
+ });
+ if (lot.error || !lot.data) {
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(lot.error, "Failed to create inspection"))
+ );
+ }
+
+ const inspectionResult = await getInspection(serviceRole, lot.data.id);
+ if (inspectionResult.error || !inspectionResult.data) {
+ throw redirect(
+ path.to.operations,
+ await flash(
+ request,
+ error(inspectionResult.error, "Failed to fetch inspection")
+ )
+ );
+ }
+ const inspection = inspectionResult.data as any;
+
+ // The lot references its document live: features added to the document
+ // after lot creation get their per-lot plan rows resolved lazily.
+ if (inspection.inspectionDocumentId) {
+ await reconcileInspectionSamplingPlans(
+ getDatabaseClient(),
+ lot.data.id,
+ companyId
+ );
+ }
+
+ const [
+ features,
+ measurements,
+ issueTypes,
+ trackedEntities,
+ jobMakeMethod,
+ events,
+ quantities,
+ linkedQuantities,
+ document
+ ] = await Promise.all([
+ getInspectionSamplingPlans(serviceRole, lot.data.id, companyId),
+ getInspectionMeasurements(serviceRole, lot.data.id, companyId),
+ getIssueTypesList(serviceRole, companyId),
+ getTrackedEntitiesByMakeMethodId(serviceRole, op.jobMakeMethodId),
+ getJobMakeMethod(serviceRole, op.jobMakeMethodId),
+ getProductionEventsForJobOperation(serviceRole, { operationId, userId }),
+ getProductionQuantitiesForJobOperation(serviceRole, operationId),
+ // Verdict-driven postings link back to their sample — the UI derives
+ // "Complete passed (n)" from what is passed but not yet posted.
+ serviceRole
+ .from("productionQuantity")
+ .select("id, type, quantity, inspectionSampleId")
+ .eq("inspectionId", lot.data.id),
+ inspection.inspectionDocumentId
+ ? getInspectionDocumentWithBalloons(
+ serviceRole,
+ inspection.inspectionDocumentId
+ )
+ : Promise.resolve(null)
+ ]);
+
+ const linkedProductionRows = (linkedQuantities.data ?? []).filter(
+ (row) => row.type === "Production"
+ );
+
+ const productionQuantities = (quantities.data ?? []).reduce(
+ (acc, curr) => {
+ if (curr.type === "Scrap") acc.scrap += curr.quantity;
+ else if (curr.type === "Production") acc.production += curr.quantity;
+ else if (curr.type === "Rework") acc.rework += curr.quantity;
+ return acc;
+ },
+ { scrap: 0, production: 0, rework: 0 }
+ );
+
+ // Sample column order must match the engine's required-feature derivation
+ // (createdAt asc, id asc).
+ const samples = (
+ [...(inspection.inspectionSample ?? [])] as InspectionSample[]
+ ).sort(
+ (a, b) =>
+ (a.createdAt ?? "").localeCompare(b.createdAt ?? "") ||
+ a.id.localeCompare(b.id)
+ );
+
+ return {
+ job: job.data,
+ operation: makeDurations(op) as OperationWithDetails,
+ inspection,
+ samples,
+ features: features.data ?? [],
+ measurements: measurements.data ?? [],
+ issueTypes: issueTypes.data ?? [],
+ trackedEntities: trackedEntities.data ?? [],
+ requiresSerialTracking: jobMakeMethod.data?.requiresSerialTracking ?? false,
+ requiresBatchTracking: jobMakeMethod.data?.requiresBatchTracking ?? false,
+ events: events.data ?? [],
+ productionQuantities,
+ linkedSampleIds: linkedProductionRows
+ .map((row) => row.inspectionSampleId)
+ .filter((sampleId): sampleId is string => Boolean(sampleId)),
+ linkedProductionQuantity: linkedProductionRows.reduce(
+ (sum, row) => sum + (row.quantity ?? 0),
+ 0
+ ),
+ jobId: job.data.id ?? null,
+ balloons: document?.data?.balloons ?? [],
+ documentName: document?.data?.name ?? null,
+ pdfUrl: document?.data?.pdfUrl ?? null
+ };
+}
+
+export default function InspectionRoute() {
+ const { operationId } = useParams();
+ if (!operationId) throw new Error("Operation ID is required");
+
+ const data = useLoaderData<typeof loader>();
+ return <InspectionView {...data} operationId={operationId} />;
+}
diff --git a/apps/mes/app/routes/x+/issue-tracked-entity.tsx b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
index c7a3a8c1bf..c516b95bae 100644
--- a/apps/mes/app/routes/x+/issue-tracked-entity.tsx
+++ b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
@@ -29,6 +29,8 @@ export async function action({ request }: ActionFunctionArgs) {
itemId,
parentTrackedEntityId,
children,
+ jobOperationStepId,
+ unitNumber,
overrideExpired,
overrideReason
} = validation.data;
@@ -42,6 +44,8 @@ export async function action({ request }: ActionFunctionArgs) {
itemId,
parentTrackedEntityId,
children,
+ jobOperationStepId,
+ unitNumber,
overrideExpired,
overrideReason,
companyId,
diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsx
index 14be06f03d..7703a48fd6 100644
--- a/apps/mes/app/routes/x+/issue.tsx
+++ b/apps/mes/app/routes/x+/issue.tsx
@@ -23,8 +23,14 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { jobOperationId, materialId, itemId, quantity, adjustmentType } =
- validation.data;
+ const {
+ jobOperationId,
+ materialId,
+ jobOperationStepId,
+ itemId,
+ quantity,
+ adjustmentType
+ } = validation.data;
const serviceRole = await getCarbonServiceRole();
const acknowledged = formData.get("acknowledged") === "true";
@@ -83,6 +89,7 @@ export async function action({ request }: ActionFunctionArgs) {
type: "partToOperation",
itemId,
materialId,
+ jobOperationStepId,
quantity,
adjustmentType,
companyId,
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index b136b3afca..f12e89bf3f 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -27,6 +27,7 @@ import type { OperationWithDetails } from "~/services/types";
type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
import { makeDurations } from "~/utils/durations";
+import { resolveOperationView } from "~/utils/operationView";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -71,6 +72,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ const op = operation.data?.[0];
+
+ // Redirect guard (ADR-0005): each view has its own route. Guards only
+ // redirect kinds they don't serve, so no loop.
+ if (resolveOperationView(op?.operationType) === "assembly") {
+ throw redirect(path.to.assembly(operationId) + url.search);
+ }
+ if (resolveOperationView(op?.operationType) === "inspection") {
+ throw redirect(path.to.inspection(operationId) + url.search);
+ }
+
const [
thumbnailPath,
trackedEntities,
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
index 5b421f8913..191cb3dc9d 100644
--- a/apps/mes/app/routes/x+/operations.tsx
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -7,12 +7,12 @@ import {
ClientOnly,
Heading,
HStack,
+ LoadingBars,
Popover,
PopoverContent,
PopoverTrigger,
Separator,
SidebarTrigger,
- Spinner,
Switch,
toast,
useInterval,
@@ -289,7 +289,7 @@ export default function ScheduleRoute() {
<ClientOnly
fallback={
<div className="flex h-screen w-[calc(100dvw-var(--sidebar-width-icon))] items-center justify-center">
- <Spinner className="h-8 w-8" />
+ <LoadingBars />
</div>
}
>
diff --git a/apps/mes/app/routes/x+/quality-issue.new.tsx b/apps/mes/app/routes/x+/quality-issue.new.tsx
index 20c536bc19..290c6c68ba 100644
--- a/apps/mes/app/routes/x+/quality-issue.new.tsx
+++ b/apps/mes/app/routes/x+/quality-issue.new.tsx
@@ -2,32 +2,11 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import type { Database } from "@carbon/database";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
+import { createQualityIssue } from "~/services/quality.server";
import { path, requestReferrer } from "~/utils/path";
-type ServiceRole = Awaited<ReturnType<typeof getCarbonServiceRole>>;
-type IssueContext =
- | {
- ok: true;
- jobOperationId: string;
- operationOrder: string | null;
- jobId: string;
- jobReadableId: string;
- jobMakeMethodId: string | null;
- itemId: string | null;
- itemReadableId: string | null;
- locationId: string;
- issueTypeId: string;
- assignee: string | null;
- }
- | {
- ok: false;
- error: unknown;
- message: string;
- };
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {
@@ -60,123 +39,25 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const context = await getIssueContext(serviceRole, {
+ const result = await createQualityIssue(serviceRole, {
companyId,
userId,
- jobOperationId
- });
-
- if (!context.ok) {
- throw redirect(
- requestReferrer(request) ?? path.to.active,
- await flash(request, error(context.error, context.message))
- );
- }
-
- const nextSequence = await serviceRole.rpc("get_next_sequence", {
- sequence_name: "nonConformance",
- company_id: companyId
- });
-
- if (nextSequence.error || !nextSequence.data) {
- throw redirect(
- requestReferrer(request) ?? path.to.active,
- await flash(
- request,
- error(nextSequence.error, "Failed to get quality issue sequence")
- )
- );
- }
-
- const name =
- userDescription ??
- `MES quality issue: ${context.itemReadableId ?? context.jobReadableId}`;
-
- const issue = await serviceRole
- .from("nonConformance")
- .insert({
- nonConformanceId: nextSequence.data,
- name,
- description: "",
- priority: priority ?? "Medium",
- source: "Internal",
- locationId: context.locationId,
- nonConformanceTypeId: nonConformanceTypeId ?? context.issueTypeId,
- nonConformanceWorkflowId: null,
- openDate: new Date().toISOString().slice(0, 10),
- quantity,
- assignee: context.assignee,
- requiredActionIds: [],
- approvalRequirements: [],
- companyId,
- createdBy: userId
- } satisfies Database["public"]["Tables"]["nonConformance"]["Insert"])
- .select("id")
- .single();
-
- if (issue.error || !issue.data?.id) {
- throw redirect(
- requestReferrer(request) ?? path.to.active,
- await flash(request, error(issue.error, "Failed to create quality issue"))
- );
- }
-
- const nonConformanceId = issue.data.id;
-
- const [jobOperationAssociation, dispositionAssociation] = await Promise.all([
- serviceRole.from("nonConformanceJobOperation").insert({
- nonConformanceId,
- jobOperationId: context.jobOperationId,
- jobId: context.jobId,
- jobReadableId: context.jobReadableId,
- companyId,
- createdBy: userId
- }),
- linkIssueDispositionContext(serviceRole, {
- nonConformanceId,
- companyId,
- userId,
- itemId: context.itemId,
- jobMakeMethodId: context.jobMakeMethodId,
- trackedEntityId,
- quantity
- })
- ]);
- const associationError =
- jobOperationAssociation.error ?? dispositionAssociation.error;
- if (associationError) {
- await serviceRole
- .from("nonConformance")
- .delete()
- .eq("id", nonConformanceId);
- throw redirect(
- requestReferrer(request) ?? path.to.active,
- await flash(
- request,
- error(associationError, "Failed to link quality issue to MES context")
- )
- );
- }
-
- const tasks = await serviceRole.functions.invoke("create", {
- body: {
- type: "nonConformanceTasks",
- id: nonConformanceId,
- companyId,
- userId
- }
+ jobOperationId,
+ trackedEntityId,
+ // The operator's free-text description doubles as the issue name (the
+ // original MES behavior — the description body stays empty).
+ name: userDescription,
+ nonConformanceTypeId,
+ priority,
+ quantity
});
- if (tasks.error) {
- await serviceRole
- .from("nonConformance")
- .delete()
- .eq("id", nonConformanceId);
+ if (result.error || !result.data) {
throw redirect(
requestReferrer(request) ?? path.to.active,
await flash(
request,
- error(tasks.error, "Failed to create quality issue tasks")
+ error(result.error, result.message ?? "Failed to create quality issue")
)
);
}
@@ -196,234 +77,3 @@ function normalizeQuantity(value: string | undefined) {
const quantity = Number(value ?? "1");
return Number.isFinite(quantity) && quantity > 0 ? quantity : 1;
}
-
-async function getIssueContext(
- client: ServiceRole,
- args: {
- companyId: string;
- userId: string;
- jobOperationId: string;
- }
-): Promise<IssueContext> {
- const operation = await client
- .from("jobOperation")
- .select("id, companyId, jobId, jobMakeMethodId, operationOrder")
- .eq("id", args.jobOperationId)
- .maybeSingle();
-
- if (operation.error || !operation.data) {
- return {
- ok: false,
- error: operation.error,
- message: "Failed to load job operation"
- };
- }
-
- if (operation.data.companyId !== args.companyId) {
- return {
- ok: false,
- error: null,
- message: "Job operation is not in this company"
- };
- }
-
- const [job, defaults, issueType] = await Promise.all([
- client
- .from("job")
- .select("id, jobId, itemId, locationId, assignee")
- .eq("id", operation.data.jobId)
- .maybeSingle(),
- client
- .from("userDefaults")
- .select("locationId")
- .eq("userId", args.userId)
- .eq("companyId", args.companyId)
- .maybeSingle(),
- client
- .from("nonConformanceType")
- .select("id")
- .eq("companyId", args.companyId)
- .order("name", { ascending: true })
- .limit(1)
- .maybeSingle()
- ]);
-
- if (job.error || !job.data) {
- return {
- ok: false,
- error: job.error,
- message: "Failed to load job context"
- };
- }
-
- if (issueType.error || !issueType.data?.id) {
- return {
- ok: false,
- error: issueType.error,
- message:
- "Configure at least one quality issue type before creating MES issues"
- };
- }
-
- const locationId = defaults.data?.locationId ?? job.data.locationId;
- if (!locationId) {
- return {
- ok: false,
- error: defaults.error,
- message: "A location is required to create a quality issue"
- };
- }
-
- const item = job.data.itemId
- ? await client
- .from("item")
- .select("readableId, name")
- .eq("id", job.data.itemId)
- .maybeSingle()
- : null;
-
- return {
- ok: true,
- jobOperationId: operation.data.id,
- operationOrder: operation.data.operationOrder,
- jobId: job.data.id,
- jobReadableId: job.data.jobId,
- jobMakeMethodId: operation.data.jobMakeMethodId,
- itemId: job.data.itemId,
- itemReadableId:
- item?.data?.readableId ?? item?.data?.name ?? job.data.itemId ?? null,
- locationId,
- issueTypeId: issueType.data.id,
- assignee: job.data.assignee
- };
-}
-
-async function linkIssueDispositionContext(
- client: ServiceRole,
- args: {
- nonConformanceId: string;
- companyId: string;
- userId: string;
- itemId: string | null;
- jobMakeMethodId: string | null;
- trackedEntityId?: string;
- quantity: number;
- }
-): Promise<{ error: unknown | null }> {
- const {
- nonConformanceId,
- companyId,
- userId,
- itemId,
- jobMakeMethodId,
- trackedEntityId,
- quantity
- } = args;
-
- if (!itemId) return { error: null };
-
- const trackedEntities = await getTrackedEntitiesForIssue(client, {
- companyId,
- jobMakeMethodId,
- trackedEntityId
- });
-
- if (trackedEntities.error) {
- return { error: trackedEntities.error };
- }
-
- const itemQuantity =
- trackedEntities.data.length > 0
- ? trackedEntities.data.reduce(
- (total, entity) => total + Number(entity.quantity ?? quantity),
- 0
- )
- : quantity;
-
- const item = await client
- .from("nonConformanceItem")
- .insert({
- nonConformanceId,
- itemId,
- quantity: itemQuantity,
- disposition: "Pending",
- companyId,
- createdBy: userId
- })
- .select("id")
- .single();
-
- if (item.error || !item.data?.id) {
- return { error: item.error ?? new Error("Failed to create issue item") };
- }
-
- if (trackedEntities.data.length === 0) {
- return { error: null };
- }
-
- const trackedEntityLinks = await client
- .from("nonConformanceTrackedEntity")
- .insert(
- trackedEntities.data.map((entity) => ({
- nonConformanceId,
- trackedEntityId: entity.id,
- companyId,
- createdBy: userId
- }))
- );
-
- if (trackedEntityLinks.error) {
- return { error: trackedEntityLinks.error };
- }
-
- const dispositionLinks = await client
- .from("nonConformanceItemTrackedEntity")
- .insert(
- trackedEntities.data.map((entity) => ({
- nonConformanceItemId: item.data.id,
- nonConformanceId,
- trackedEntityId: entity.id,
- quantity: Number(entity.quantity ?? quantity),
- companyId,
- createdBy: userId
- }))
- );
-
- return { error: dispositionLinks.error };
-}
-
-async function getTrackedEntitiesForIssue(
- client: ServiceRole,
- args: {
- companyId: string;
- jobMakeMethodId: string | null;
- trackedEntityId?: string;
- }
-): Promise<{
- data: { id: string; quantity: number | null }[];
- error: unknown | null;
-}> {
- if (!args.trackedEntityId) {
- return { data: [], error: null };
- }
-
- const entity = await client
- .from("trackedEntity")
- .select("id, quantity")
- .eq("id", args.trackedEntityId)
- .eq("companyId", args.companyId)
- .maybeSingle();
-
- if (entity.error) {
- return { data: [], error: entity.error };
- }
-
- if (!entity.data) {
- return {
- data: [],
- error: new Error("Tracked entity is not in this company")
- };
- }
-
- return { data: [entity.data], error: null };
-}
diff --git a/apps/mes/app/routes/x+/record.tsx b/apps/mes/app/routes/x+/record.tsx
index c71c9bf495..b694d180b0 100644
--- a/apps/mes/app/routes/x+/record.tsx
+++ b/apps/mes/app/routes/x+/record.tsx
@@ -3,10 +3,16 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { stepRecordValidator } from "~/services/models";
-import { insertAttributeRecord } from "~/services/operations.service";
+import {
+ backflushUntrackedMaterialsOnStepRecord,
+ insertAttributeRecord
+} from "~/services/operations.service";
+
+const log = getLogger("mes");
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -36,6 +42,23 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // Recording a step auto-issues one unit's worth of the untracked materials that
+ // step owns — a step-assigned part when its step is recorded, or a loose part
+ // (unassigned) on the operation's first step. The operator builds unit by unit
+ // and never scans these. A backflush failure (e.g. insufficient stock) never
+ // blocks the record; the part just stays manually issuable.
+ const backflush = await backflushUntrackedMaterialsOnStepRecord(serviceRole, {
+ jobOperationStepId: validation.data.jobOperationStepId,
+ companyId,
+ userId
+ });
+ if (backflush.error) {
+ log.error("Backflush on step record failed", {
+ error: backflush.error,
+ jobOperationStepId: validation.data.jobOperationStepId
+ });
+ }
+
return data(
{ success: true },
await flash(request, success("Attribute recorded successfully"))
diff --git a/apps/mes/app/routes/x+/steps.complete-all.tsx b/apps/mes/app/routes/x+/steps.complete-all.tsx
new file mode 100644
index 0000000000..573ba87b5e
--- /dev/null
+++ b/apps/mes/app/routes/x+/steps.complete-all.tsx
@@ -0,0 +1,60 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { completeAllStepsForUnit } from "~/services/operations.service";
+
+const log = getLogger("mes");
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ // Manager override — gated on the Production DELETE permission (operators lack it).
+ const { companyId, userId } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const formData = await request.formData();
+ const operationId = formData.get("operationId")?.toString();
+ const index = Number.parseInt(formData.get("index")?.toString() ?? "", 10);
+
+ if (!operationId || Number.isNaN(index)) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Missing operation or unit"))
+ );
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+ const result = await completeAllStepsForUnit(serviceRole, {
+ operationId,
+ index,
+ companyId,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ return data(
+ { success: false },
+ await flash(request, error(result.error, "Failed to complete all steps"))
+ );
+ }
+
+ if (result.data?.backflushError) {
+ log.error("Backflush on complete-all override failed", {
+ error: result.data.backflushError,
+ operationId,
+ index
+ });
+ }
+
+ return data(
+ { success: true },
+ await flash(
+ request,
+ success(`Completed ${result.data?.count ?? 0} remaining step(s)`)
+ )
+ );
+}
diff --git a/apps/mes/app/services/database.server.ts b/apps/mes/app/services/database.server.ts
new file mode 100644
index 0000000000..a68103d40d
--- /dev/null
+++ b/apps/mes/app/services/database.server.ts
@@ -0,0 +1,29 @@
+/**
+ * Database client singleton for server-side usage.
+ * Similar to Prisma client singleton. from https://www.prisma.io/docs/guides/react-router-7
+ * Polluting the global namespace like this is usually discouraged, but it's okay as we're just caching connections during development.
+ * In production, this code path is not hit multiple times as ESM modules are only singletons by default.
+ */
+import {
+ getPostgresClient,
+ getPostgresConnectionPool
+} from "@carbon/database/client";
+import { PostgresDriver } from "kysely";
+
+const init = () => {
+ const pool = getPostgresConnectionPool(10);
+ // We use the PostgresDriver from Kysely here as this code only runs in Node environment
+ return getPostgresClient(pool, PostgresDriver);
+};
+
+type ClientSingleton = ReturnType<typeof init>;
+
+const globalForKysely = globalThis as unknown as {
+ kysely: ClientSingleton | undefined;
+};
+
+const database = globalForKysely.kysely ?? init();
+
+if (process.env.NODE_ENV !== "production") globalForKysely.kysely = database;
+
+export const getDatabaseClient = () => database;
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index ab32f68fa7..cb7dc059e7 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -112,6 +112,9 @@ export const issueValidator = z.object({
itemId: z.string().min(1, { message: "Item is required" }),
jobOperationId: z.string().min(1, { message: "Job Operation is required" }),
materialId: zfd.text(z.string().optional()),
+ // When issuing an unplanned part from the shop floor (no materialId), scope the
+ // newly-created jobMaterial to the step it was issued on so it shows on that step.
+ jobOperationStepId: zfd.text(z.string().optional()),
quantity: zfd.numeric(z.number()),
adjustmentType: z.enum(["Set Quantity", "Positive Adjmt.", "Negative Adjmt."])
});
@@ -148,7 +151,16 @@ export const productionEventValidator = z.object({
})
}),
workCenterId: zfd.text(z.string().optional()),
- trackedEntityId: zfd.text(z.string().optional())
+ trackedEntityId: zfd.text(z.string().optional()),
+ // The 0-based unit-axis position this event is building — identical to the key
+ // written to jobOperationStepRecord.index. Recorded on the tracked activity so
+ // traceability can isolate this unit's step records from the operation's other
+ // units. Omitted by the operation view (no unit paging).
+ unitIndex: zfd.numeric(z.number().optional()),
+ // Assembly clocking is single-phase: when set, starting this work type ends
+ // any other open work type for the operator on this operation (so Setup and
+ // Labor can never run at once). Omitted by the operation view.
+ exclusive: zfd.text(z.string().optional())
});
export const finishValidator = z.object({
@@ -169,6 +181,11 @@ export const issueTrackedEntityValidator = z.object({
quantity: z.number()
})
),
+ // Assembly view only: the step + unit the operator was on when scanning, so the
+ // consume can be attributed per-unit (and per-step) even for a batch parent where
+ // every unit shares one lot entity. `unitNumber` is 1-based (currentUnitIndex + 1).
+ jobOperationStepId: z.string().optional(),
+ unitNumber: z.number().int().positive().optional(),
// Set when policy is BlockWithOverride and operator typed a reason.
overrideExpired: z.boolean().optional(),
overrideReason: z.string().optional()
@@ -198,7 +215,10 @@ export const triggerReworkValidator = z.object({
quantity: zfd.numeric(
z.number().positive({ message: "Quantity must be greater than 0" })
),
- trackedEntityIds: zfd.text(z.string().optional())
+ trackedEntityIds: zfd.text(z.string().optional()),
+ // Provenance link when the rework was triggered by an inspection
+ // disposition (stamped on the Rework productionQuantity row).
+ inspectionId: zfd.text(z.string().optional())
});
export const maintenanceDispatchValidator = z.object({
@@ -255,3 +275,112 @@ export const maintenanceDispatchIssueTrackedEntityValidator = z.object({
})
)
});
+
+// Inspection execution (mirrors the ERP quality module's validators — the
+// shared engine in @carbon/database/quality consumes these shapes).
+export const inspectionSampleValidator = z.object({
+ inspectionId: z.string().min(1, { message: "Inspection is required" }),
+ // Optional: update an existing sample in place (the grid's "Overall result"
+ // row re-toggles an anonymous non-serial column). Serial parts upsert by the
+ // tracked entity instead, so they don't need it.
+ sampleId: zfd.text(z.string().optional()),
+ // Optional: serial parts scan a discrete tracked entity; batch / inventory /
+ // non-inventory parts record pass/fail without one.
+ trackedEntityId: zfd.text(z.string().optional()),
+ // "Pending" registers a sample without a verdict (identify-only scan when an
+ // inspection document drives per-feature measurements).
+ status: z.enum(["Pending", "Passed", "Failed"], {
+ errorMap: () => ({ message: "Status is required" })
+ }),
+ notes: zfd.text(z.string().optional())
+});
+
+// One decision surface for closing an inspection lot: the verdict carries its
+// physical outcome. Accept completes the remaining lot; Reject/Partial split
+// the failed set between Scrap (reason) and Rework (upstream target op) — or
+// record only. Serial lots allocate per entity (two disjoint JSON id arrays);
+// non-serial lots allocate by quantity. The route recomputes every bucket from
+// the DB and clamps to the operation's remaining quantity — these fields are
+// operator intent, not trusted arithmetic.
+export const inspectionDispositionValidator = z
+ .object({
+ decision: z.enum(["Accept", "Reject", "Partial"], {
+ errorMap: () => ({ message: "Decision is required" })
+ }),
+ // The job operation, for postings + redirect back to the inspection view.
+ operationId: z.string().min(1, { message: "Operation is required" }),
+ setupProductionEventId: zfd.text(z.string().optional()),
+ laborProductionEventId: zfd.text(z.string().optional()),
+ machineProductionEventId: zfd.text(z.string().optional()),
+ // Serial allocation: JSON string[] of tracked entity ids per outcome.
+ scrapEntityIds: zfd.text(z.string().optional()),
+ reworkEntityIds: zfd.text(z.string().optional()),
+ // Non-serial allocation: quantities out of the failed/remainder count.
+ scrapQuantity: zfd.numeric(z.number().min(0).optional()),
+ reworkQuantity: zfd.numeric(z.number().min(0).optional()),
+ // Shared outcome params.
+ scrapReasonId: zfd.text(z.string().optional()),
+ targetOperationId: zfd.text(z.string().optional()),
+ reworkReason: zfd.text(z.string().optional()),
+ // NCR is optional documentation — never required for scrap or rework.
+ createNcr: zfd.text(z.enum(["true", "false"]).optional()),
+ nonConformanceTypeId: zfd.text(z.string().optional())
+ })
+ .superRefine((data, ctx) => {
+ const parseIds = (json: string | undefined): string[] => {
+ if (!json) return [];
+ try {
+ const parsed = JSON.parse(json);
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+ };
+ const scrapCount = parseIds(data.scrapEntityIds).length;
+ const reworkCount = parseIds(data.reworkEntityIds).length;
+ const hasScrap = scrapCount > 0 || (data.scrapQuantity ?? 0) > 0;
+ const hasRework = reworkCount > 0 || (data.reworkQuantity ?? 0) > 0;
+ if (hasScrap && !data.scrapReasonId) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["scrapReasonId"],
+ message: "Scrap reason is required"
+ });
+ }
+ if (hasRework && !data.targetOperationId) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["targetOperationId"],
+ message: "Target operation is required"
+ });
+ }
+ if (hasRework && !data.reworkReason) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["reworkReason"],
+ message: "Rework reason is required"
+ });
+ }
+ });
+
+// Progressive completion of passed units while the lot stays open — posts a
+// Production row per passed serial sample (or one linked bulk row for
+// non-serial counts) with sample-level provenance links.
+export const inspectionCompletePassedValidator = z.object({
+ operationId: z.string().min(1, { message: "Operation is required" }),
+ setupProductionEventId: zfd.text(z.string().optional()),
+ laborProductionEventId: zfd.text(z.string().optional()),
+ machineProductionEventId: zfd.text(z.string().optional())
+});
+
+export const inspectionMeasurementValidator = z.object({
+ inspectionId: z.string().min(1, { message: "Inspection is required" }),
+ // Absent = create an anonymous sample (non-serial grid columns).
+ sampleId: zfd.text(z.string().optional()),
+ inspectionFeatureId: z.string().min(1, { message: "Feature is required" }),
+ // Numeric string for Measurement features; empty clears the reading.
+ value: zfd.text(z.string().optional()),
+ // Attribute (non-numeric) features toggle pass/fail instead of a value.
+ passed: zfd.text(z.enum(["true", "false"]).optional()),
+ notes: zfd.text(z.string().optional())
+});
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 015c4f7b64..c5a6e3d1a1 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -8,7 +8,7 @@ import {
type TrackedActivityAttributes
} from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import { sanitize } from "~/utils/supabase";
@@ -395,7 +395,7 @@ export async function getJobOperationProcedure(
const [attributes, parameters] = await Promise.all([
client
.from("jobOperationStep")
- .select("*, jobOperationStepRecord(*)")
+ .select("*, jobOperationStepRecord(*), jobOperationStepSlide(*)")
.eq("operationId", operationId),
client
.from("jobOperationParameter")
@@ -409,6 +409,64 @@ export async function getJobOperationProcedure(
};
}
+// Render/display metadata for 3D model slides: glbPath when the assembler service
+// has converted a STEP source (fast to load), modelPath as the raw fallback the
+// viewer parses client-side, thumbnailPath for the carousel.
+export async function getModelUploadsByIds(
+ client: SupabaseClient<Database>,
+ ids: string[]
+) {
+ return client
+ .from("modelUpload")
+ .select("id, name, modelPath, thumbnailPath, glbPath, processingStatus")
+ .in("id", ids);
+}
+
+// Step-aware 3D playback for the assembly view: when the operation is linked to a
+// (synced) assembly instruction whose model has converted artifacts, return the
+// GLB + graph paths and the instruction's animated steps. The view maps the
+// operator's current BOP step to its instruction step via the
+// assemblyInstructionStepId provenance marker and drives the AssemblyPlayer to it.
+// Null when there's no link or no converted artifacts (the static slides remain).
+export async function getAssemblyPlaybackByOperationId(
+ client: SupabaseClient<Database>,
+ operationId: string
+) {
+ const operation = await client
+ .from("jobOperation")
+ .select("assemblyInstructionId")
+ .eq("id", operationId)
+ .single();
+ const instructionId = operation.data?.assemblyInstructionId;
+ if (!instructionId) return null;
+
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("id, modelUpload(glbPath, graphPath)")
+ .eq("id", instructionId)
+ .single();
+ const model = instruction.data?.modelUpload as {
+ glbPath: string | null;
+ graphPath: string | null;
+ } | null;
+ if (!model?.glbPath || !model?.graphPath) return null;
+
+ const steps = await client
+ .from("assemblyInstructionStep")
+ .select(
+ "id, title, instructionText, componentNodeIds, motion, camera, fastener, durationSeconds, warnings"
+ )
+ .eq("assemblyInstructionId", instructionId)
+ .order("sortOrder", { ascending: true });
+
+ if (!steps.data || steps.data.length === 0) return null;
+ return {
+ glbPath: model.glbPath,
+ graphPath: model.graphPath,
+ steps: steps.data
+ };
+}
+
export async function getJobAttributesByOperationId(
client: SupabaseClient<Database>,
operationId: string
@@ -510,9 +568,22 @@ export async function getJobMaterialsByOperationId(
operation: BaseOperationWithDetails;
trackedEntityId: string | undefined;
requiresSerialTracking: boolean;
+ // Batch parents share ONE lot entity across every unit, so consumed inputs
+ // can't be attributed per-unit by the parent entity alone. When the operator
+ // scanned from the assembly view we stamped the 1-based unit onto the Consume
+ // activity ("Unit" attribute); pass the 0-based unit being viewed so we can
+ // attribute issued quantities to it. Defaults keep the operation view unchanged.
+ requiresBatchTracking?: boolean;
+ unitIndex?: number;
}
) {
- const { operation, trackedEntityId, requiresSerialTracking } = args;
+ const {
+ operation,
+ trackedEntityId,
+ requiresSerialTracking,
+ requiresBatchTracking = false,
+ unitIndex = 0
+ } = args;
const [materials, trackedInputs] = await Promise.all([
client
@@ -558,6 +629,30 @@ export async function getJobMaterialsByOperationId(
materials.data = [...(materials.data ?? []), ...processedKittedMaterials];
}
+ // Step assignment (Phase 2: part ↔ step, many-to-many). The make-method view doesn't carry
+ // the join rows, so look them up from jobMaterialStep and attach an array. No rows = the
+ // material applies to the whole operation (shown on every step); 1+ rows scope it to those
+ // steps so the MES shows only the parts involved in the current step.
+ const stepLinks = await client
+ .from("jobMaterialStep")
+ .select("jobMaterialId, jobOperationStepId")
+ .in(
+ "jobMaterialId",
+ (materials.data ?? []).map((m) => m.id ?? "")
+ );
+ const stepIdsByMaterialId = new Map<string, string[]>();
+ for (const r of stepLinks.data ?? []) {
+ const list = stepIdsByMaterialId.get(r.jobMaterialId) ?? [];
+ list.push(r.jobOperationStepId);
+ stepIdsByMaterialId.set(r.jobMaterialId, list);
+ }
+ if (materials.data) {
+ materials.data = materials.data.map((m) => ({
+ ...m,
+ jobOperationStepIds: stepIdsByMaterialId.get(m.id ?? "") ?? []
+ }));
+ }
+
// The descendant rpc doesn't return expirationDate, so look it up from
// trackedEntity for the consumed inputs in one batched call. This lets
// us flag materials whose CONSUMED stock is now past expiry — useful
@@ -638,6 +733,58 @@ export async function getJobMaterialsByOperationId(
}) ?? [],
trackedInputs: trackedInputs.data ?? []
};
+ } else if (requiresBatchTracking) {
+ // Batch parent: every unit shares one lot entity, so trackedInputs are ALL the
+ // serials/batches consumed into that lot across every unit. Attribute the current
+ // unit's issued quantity from the "Unit" attribute we stamp at issue time (1-based).
+ // Consumes made before that stamp existed carry no "Unit" — fall back to the
+ // job-wide-minus-earlier-units heuristic for those only. The returned quantityIssued
+ // is per-unit (the component renders it directly, no clamp).
+ const currentUnitNumber = unitIndex + 1;
+ return {
+ materials:
+ materials.data?.map((material) => {
+ const hasExpiredConsumed = consumedExpiredFor(material.id);
+ const picked = pickedFor(material.id);
+ if (
+ !material.requiresSerialTracking &&
+ !material.requiresBatchTracking
+ )
+ return { ...material, hasExpiredConsumed, ...picked };
+
+ const forMaterial = (trackedInputs.data ?? []).filter(
+ (input) =>
+ (input.activityAttributes as TrackedActivityAttributes)?.[
+ "Job Material"
+ ] === material.id
+ );
+ const unitAttr = (input: (typeof forMaterial)[number]) =>
+ (input.activityAttributes as TrackedActivityAttributes)?.Unit;
+
+ const issuedThisUnit = forMaterial
+ .filter((input) => Number(unitAttr(input)) === currentUnitNumber)
+ .reduce((acc, input) => acc + input.quantity, 0);
+
+ // Legacy (unstamped) consumes → distribute with the old per-unit heuristic.
+ const legacyTotal = forMaterial
+ .filter((input) => unitAttr(input) == null)
+ .reduce((acc, input) => acc + input.quantity, 0);
+ const requiredPerUnit =
+ material.quantity ?? material.estimatedQuantity ?? 0;
+ const legacyShare = Math.min(
+ requiredPerUnit,
+ Math.max(0, legacyTotal - unitIndex * requiredPerUnit)
+ );
+
+ return {
+ ...material,
+ quantityIssued: issuedThisUnit + legacyShare,
+ hasExpiredConsumed,
+ ...picked
+ };
+ }) ?? [],
+ trackedInputs: trackedInputs.data ?? []
+ };
} else {
return {
materials: (materials.data ?? []).map((material) => ({
@@ -650,6 +797,144 @@ export async function getJobMaterialsByOperationId(
}
}
+/**
+ * Backflush untracked materials when a job operation STEP is recorded. Units are
+ * built one at a time; an untracked (not serial/batch) part is consumed as the
+ * step that "owns" it is recorded, so recording that step issues one unit's worth
+ * automatically instead of making the operator issue it by hand (tracked parts
+ * still require a scan). Step ownership:
+ * • A step-assigned part (jobMaterialStep) is owned by its assigned step(s) and
+ * issues when any of those steps is recorded for a unit.
+ * • A loose part (no step assignment) is owned by the operation's FIRST step —
+ * that's where the operator sees it — matching the prior behavior.
+ * Idempotent by construction: per material the target is
+ * (distinct units that recorded an owning step) × per-unit quantity, and only the
+ * shortfall vs quantityIssued is issued — re-records, undo/redo, manual issues,
+ * and the completion-time backflush (backflush_job_materials, which tops up to
+ * completed × per-unit) can all overlap without double-issuing. A part assigned to
+ * several steps is still counted once per unit, so its requirement never
+ * multiplies. Eligibility mirrors backflush_job_materials (Material/Part/Consumable,
+ * not Make to Order, untracked). Issue failures (e.g. insufficient stock) are
+ * collected, not thrown — the part simply stays unissued and manually issuable.
+ */
+export async function backflushUntrackedMaterialsOnStepRecord(
+ client: SupabaseClient<Database>,
+ args: { jobOperationStepId: string; companyId: string; userId: string }
+) {
+ const step = await client
+ .from("jobOperationStep")
+ .select("id, operationId")
+ .eq("id", args.jobOperationStepId)
+ .single();
+ if (step.error || !step.data.operationId) return { error: step.error };
+ const operationId = step.data.operationId;
+
+ const [steps, operation] = await Promise.all([
+ client
+ .from("jobOperationStep")
+ .select("id")
+ .eq("operationId", operationId)
+ .order("sortOrder", { ascending: true })
+ .order("id", { ascending: true }),
+ client
+ .from("jobOperation")
+ .select("id, jobMakeMethodId")
+ .eq("id", operationId)
+ .single()
+ ]);
+ const firstStepId = steps.data?.[0]?.id;
+ if (steps.error || !firstStepId) return { error: steps.error };
+ if (operation.error || !operation.data?.jobMakeMethodId) {
+ return { error: operation.error };
+ }
+ const stepIds = steps.data.map((s) => s.id);
+
+ const materials = await client
+ .from("jobMaterial")
+ .select("id, itemId, quantity, quantityIssued, methodType")
+ .eq("jobMakeMethodId", operation.data.jobMakeMethodId)
+ .eq("companyId", args.companyId)
+ .in("itemType", ["Material", "Part", "Consumable"])
+ .neq("methodType", "Make to Order")
+ .eq("requiresSerialTracking", false)
+ .eq("requiresBatchTracking", false);
+ if (materials.error || !materials.data?.length) {
+ return { error: materials.error };
+ }
+
+ // Step ownership: materialId → the step ids it's assigned to (empty = loose).
+ const stepLinks = await client
+ .from("jobMaterialStep")
+ .select("jobMaterialId, jobOperationStepId")
+ .in(
+ "jobMaterialId",
+ materials.data.map((m) => m.id)
+ );
+ if (stepLinks.error) return { error: stepLinks.error };
+ const ownedSteps = new Map<string, Set<string>>();
+ for (const link of stepLinks.data ?? []) {
+ const set = ownedSteps.get(link.jobMaterialId) ?? new Set<string>();
+ set.add(link.jobOperationStepId);
+ ownedSteps.set(link.jobMaterialId, set);
+ }
+
+ // Units (index) that have recorded each of the operation's steps, so we can
+ // count distinct started units per material from its owning step(s).
+ const records = await client
+ .from("jobOperationStepRecord")
+ .select("jobOperationStepId, index")
+ .in("jobOperationStepId", stepIds);
+ if (records.error) return { error: records.error };
+ const unitsByStep = new Map<string, Set<number>>();
+ for (const r of records.data ?? []) {
+ const set = unitsByStep.get(r.jobOperationStepId) ?? new Set<number>();
+ set.add(r.index);
+ unitsByStep.set(r.jobOperationStepId, set);
+ }
+
+ const failures: string[] = [];
+ for (const material of materials.data) {
+ const perUnit = material.quantity ?? 0;
+ if (perUnit <= 0) continue;
+ // Owning steps: the material's assigned steps (scoped to this operation), or
+ // the first step when it's loose (unassigned).
+ const owning = ownedSteps.get(material.id);
+ const triggerStepIds =
+ owning && owning.size > 0
+ ? stepIds.filter((id) => owning.has(id))
+ : [firstStepId];
+ // Distinct units that recorded at least one owning step — a unit that
+ // recorded several owning steps of the same material still counts once.
+ const units = new Set<number>();
+ for (const id of triggerStepIds) {
+ for (const idx of unitsByStep.get(id) ?? []) units.add(idx);
+ }
+ const delta = units.size * perUnit - (material.quantityIssued ?? 0);
+ if (delta <= 0) continue;
+ const issue = await client.functions.invoke("issue", {
+ body: {
+ id: operationId,
+ type: "partToOperation",
+ itemId: material.itemId,
+ materialId: material.id,
+ quantity: delta,
+ adjustmentType: "Negative Adjmt.",
+ companyId: args.companyId,
+ userId: args.userId
+ }
+ });
+ if (issue.error) failures.push(material.itemId);
+ }
+
+ return {
+ error: failures.length
+ ? new Error(
+ `Backflush failed for ${failures.length} material(s): ${failures.join(", ")}`
+ )
+ : null
+ };
+}
+
export async function getJobOperationsAssignedToEmployee(
client: SupabaseClient<Database>,
employeeId: string,
@@ -766,6 +1051,85 @@ export async function getProductionQuantitiesForJobOperation(
.eq("jobOperationId", operationId);
}
+export async function getToolsByOperationId(
+ client: SupabaseClient<Database>,
+ operationId: string
+) {
+ type Tool = {
+ quantity: number;
+ jobOperationStepIds: string[];
+ item: {
+ id: string;
+ name: string;
+ type: string;
+ readableId: string | null;
+ } | null;
+ };
+
+ // Read the job's OWN tools (jobOperationTool), not the method template. This carries the
+ // tool ↔ step links (Phase 2, many-to-many) via jobOperationToolStep, copied from the
+ // method by get-method, so the assembly view can show only the tools relevant to the
+ // current step. No links = the tool applies to the whole operation (shown on every step).
+ // Mirrors the per-step material filter.
+ const result = await client
+ .from("jobOperationTool")
+ .select(
+ "quantity, item:toolId(id, name, type, readableId), jobOperationToolStep(jobOperationStepId)"
+ )
+ .eq("operationId", operationId);
+
+ const tools = (result.data ?? []).map((t) => ({
+ quantity: (t as { quantity: number }).quantity,
+ item: (t as { item: Tool["item"] }).item,
+ jobOperationStepIds: (
+ (t as { jobOperationToolStep?: { jobOperationStepId: string }[] })
+ .jobOperationToolStep ?? []
+ ).map((s) => s.jobOperationStepId)
+ })) as Tool[];
+
+ // Merge duplicate rows for the same tool (union step links, max quantity).
+ // Older get-method copies inserted assembly-instruction tools AND method
+ // tools separately, leaving e.g. one step-linked row plus one unlinked row —
+ // which the MES would show on every step AND twice on the linked step.
+ const merged = new Map<string, Tool>();
+ for (const tool of tools) {
+ const key = tool.item?.id;
+ if (!key) {
+ merged.set(`__no_item_${merged.size}`, tool);
+ continue;
+ }
+ const existing = merged.get(key);
+ if (!existing) {
+ merged.set(key, tool);
+ } else {
+ existing.quantity = Math.max(existing.quantity, tool.quantity);
+ existing.jobOperationStepIds = [
+ ...new Set([
+ ...existing.jobOperationStepIds,
+ ...tool.jobOperationStepIds
+ ])
+ ];
+ }
+ }
+
+ return {
+ data: [...merged.values()],
+ error: result.error
+ };
+}
+
+export async function getNcrsByJobOperationId(
+ client: SupabaseClient<Database>,
+ jobOperationId: string
+) {
+ return client
+ .from("nonConformanceJobOperation")
+ .select(
+ "nonConformanceId, nonConformance(id, nonConformanceId, status, priority)"
+ )
+ .eq("jobOperationId", jobOperationId);
+}
+
export async function getRecentJobOperationsByEmployee(
client: SupabaseClient<Database>,
args: {
@@ -991,6 +1355,70 @@ export async function insertAttributeRecord(
});
}
+// Manager override: record every step of an operation that has no record yet for this unit
+// index, in one write. Records carry no captured value (booleanValue/numericValue/etc. left
+// null) — the override marks steps done without their data capture, which is the point of an
+// override. Already-recorded steps are skipped (ignoreDuplicates) so it never overwrites real
+// operator data. Gated at the route on the Production DELETE permission.
+export async function completeAllStepsForUnit(
+ client: SupabaseClient<Database>,
+ args: {
+ operationId: string;
+ index: number;
+ companyId: string;
+ createdBy: string;
+ }
+): Promise<{
+ data: { count: number; backflushError: Error | null } | null;
+ error: PostgrestError | null;
+}> {
+ // Scope by companyId: this runs with the service-role client (RLS bypassed) and
+ // operationId comes from the request, so the tenant filter is the only guard against
+ // reading or stamping another company's steps.
+ const steps = await client
+ .from("jobOperationStep")
+ .select("id, jobOperationStepRecord(index)")
+ .eq("operationId", args.operationId)
+ .eq("companyId", args.companyId);
+ if (steps.error) return { data: null, error: steps.error };
+
+ const missing = (steps.data ?? []).filter(
+ (s) => !(s.jobOperationStepRecord ?? []).some((r) => r.index === args.index)
+ );
+ if (missing.length === 0) {
+ return { data: { count: 0, backflushError: null }, error: null };
+ }
+
+ const insert = await client.from("jobOperationStepRecord").upsert(
+ missing.map((s) => ({
+ jobOperationStepId: s.id,
+ index: args.index,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ })),
+ { onConflict: "jobOperationStepId, index", ignoreDuplicates: true }
+ );
+ if (insert.error) return { data: null, error: insert.error };
+
+ // The override marks steps done without their per-step data capture, so it
+ // must still consume the untracked materials those steps own for this unit —
+ // otherwise recording via the override under-issues vs. recording step by step
+ // (which backflushes on every record). The backflush is idempotent and
+ // operation-wide, so one call after the inserts tops up this unit's shortfall.
+ // Non-blocking: a failure (e.g. insufficient stock) leaves parts manually
+ // issuable, matching the per-step record path.
+ const backflush = await backflushUntrackedMaterialsOnStepRecord(client, {
+ jobOperationStepId: missing[0].id,
+ companyId: args.companyId,
+ userId: args.createdBy
+ });
+
+ return {
+ data: { count: missing.length, backflushError: backflush.error ?? null },
+ error: null
+ };
+}
+
export async function insertReworkQuantity(
client: SupabaseClient<Database>,
data: z.infer<typeof nonScrapQuantityValidator> & {
@@ -1020,6 +1448,10 @@ export async function insertProductionQuantity(
data: z.infer<typeof nonScrapQuantityValidator> & {
companyId: string;
createdBy: string;
+ // Provenance links for inspection-driven completions (the partial UNIQUE
+ // index on inspectionSampleId is the double-count guard).
+ inspectionId?: string;
+ inspectionSampleId?: string;
}
) {
return client
@@ -1038,6 +1470,8 @@ export async function insertScrapQuantity(
data: z.infer<typeof scrapQuantityValidator> & {
companyId: string;
createdBy: string;
+ inspectionId?: string;
+ inspectionSampleId?: string;
}
) {
return client
@@ -1111,18 +1545,56 @@ export async function endProductionEventsByWorkCenter(
.eq("companyId", args.companyId);
}
+// Phase 3 (auto-start): when an operator starts a production event, flip a not-yet-started
+// job + operation to "In Progress" so the shop floor doesn't have to mark it manually. Status
+// guards make re-starts and already-running jobs no-ops. Best-effort — a failure here must not
+// block the production event that already succeeded.
+async function autoStartJobAndOperation(
+ client: SupabaseClient<Database>,
+ args: { jobOperationId: string; userId: string }
+) {
+ const op = await client
+ .from("jobOperation")
+ .select("jobId, status")
+ .eq("id", args.jobOperationId)
+ .maybeSingle();
+ if (op.error || !op.data) return;
+
+ const updates: PromiseLike<unknown>[] = [];
+ if (["Todo", "Ready", "Waiting"].includes(op.data.status ?? "")) {
+ updates.push(
+ client
+ .from("jobOperation")
+ .update({ status: "In Progress", updatedBy: args.userId })
+ .eq("id", args.jobOperationId)
+ .in("status", ["Todo", "Ready", "Waiting"])
+ );
+ }
+ if (op.data.jobId) {
+ updates.push(
+ client
+ .from("job")
+ .update({ status: "In Progress", updatedBy: args.userId })
+ .eq("id", op.data.jobId)
+ .in("status", ["Draft", "Planned", "Ready"])
+ );
+ }
+ await Promise.all(updates);
+}
+
export async function startProductionEvent(
client: SupabaseClient<Database>,
data: Omit<
z.infer<typeof productionEventValidator>,
- "id" | "action" | "timezone" | "hasActiveEvents"
+ "id" | "action" | "timezone" | "hasActiveEvents" | "unitIndex"
> & {
startTime: string;
employeeId: string;
companyId: string;
createdBy: string;
},
- trackedEntityId: string | undefined
+ trackedEntityId: string | undefined,
+ unitIndex?: number
) {
if (trackedEntityId) {
const activityId = nanoid();
@@ -1151,7 +1623,10 @@ export async function startProductionEvent(
"Job Operation": data.jobOperationId,
"Production Event": eventInsert.data?.id,
"Work Center": data.workCenterId,
- Employee: data.employeeId
+ Employee: data.employeeId,
+ // The unit this event built, so traceability can scope this activity's
+ // step records to just this unit (see get_job_operation_step_records).
+ ...(typeof unitIndex === "number" ? { Unit: unitIndex } : {})
},
companyId: data.companyId,
createdBy: data.createdBy
@@ -1183,10 +1658,27 @@ export async function startProductionEvent(
return trackedActivityOutputInsert;
}
+ await autoStartJobAndOperation(client, {
+ jobOperationId: data.jobOperationId,
+ userId: data.createdBy
+ });
+
return eventInsert;
}
- return client.from("productionEvent").insert(data).select("*");
+ const eventInsert = await client
+ .from("productionEvent")
+ .insert(data)
+ .select("*");
+
+ if (!eventInsert.error) {
+ await autoStartJobAndOperation(client, {
+ jobOperationId: data.jobOperationId,
+ userId: data.createdBy
+ });
+ }
+
+ return eventInsert;
}
type JobMethod = {
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
new file mode 100644
index 0000000000..d3cd319cd9
--- /dev/null
+++ b/apps/mes/app/services/quality.server.ts
@@ -0,0 +1,884 @@
+import type { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ getJobMakeMethod,
+ getTrackedEntitiesByMakeMethodId,
+ insertProductionQuantity
+} from "~/services/operations.service";
+import {
+ getInspection,
+ getInspectionMeasurements,
+ getInspectionSamplingPlans
+} from "~/services/quality.service";
+
+type ServiceRole = Awaited<ReturnType<typeof getCarbonServiceRole>>;
+
+export type ProductionEventIds = {
+ setupProductionEventId?: string;
+ laborProductionEventId?: string;
+ machineProductionEventId?: string;
+};
+
+type IssueContext =
+ | {
+ ok: true;
+ jobOperationId: string;
+ operationOrder: string | null;
+ jobId: string;
+ jobReadableId: string;
+ jobMakeMethodId: string | null;
+ itemId: string | null;
+ itemReadableId: string | null;
+ locationId: string;
+ issueTypeId: string;
+ assignee: string | null;
+ }
+ | {
+ ok: false;
+ error: unknown;
+ message: string;
+ };
+
+export type CreateQualityIssueArgs = {
+ companyId: string;
+ userId: string;
+ jobOperationId: string;
+ trackedEntityId?: string;
+ // Falls back to "MES quality issue: {item}" when absent.
+ name?: string;
+ description?: string;
+ // Falls back to the company's first issue type when absent.
+ nonConformanceTypeId?: string;
+ priority?: "Low" | "Medium" | "High" | "Critical";
+ quantity?: number;
+};
+
+// MES-owned NCR creation for a job operation: sequence, nonConformance insert,
+// the nonConformanceJobOperation / item / tracked-entity links, and the
+// follow-up tasks edge function — with compensating deletes on failure.
+// Extracted from the quality-issue.new route so the inspection reject route
+// can create the same job-operation-aware issue.
+export async function createQualityIssue(
+ serviceRole: ServiceRole,
+ args: CreateQualityIssueArgs
+): Promise<
+ | { data: { id: string }; error: null; message: null }
+ | { data: null; error: unknown; message: string }
+> {
+ const { companyId, userId, jobOperationId } = args;
+ const quantity =
+ Number.isFinite(args.quantity) && (args.quantity ?? 0) > 0
+ ? (args.quantity as number)
+ : 1;
+
+ const context = await getIssueContext(serviceRole, {
+ companyId,
+ userId,
+ jobOperationId
+ });
+
+ if (!context.ok) {
+ return { data: null, error: context.error, message: context.message };
+ }
+
+ const nextSequence = await serviceRole.rpc("get_next_sequence", {
+ sequence_name: "nonConformance",
+ company_id: companyId
+ });
+
+ if (nextSequence.error || !nextSequence.data) {
+ return {
+ data: null,
+ error: nextSequence.error,
+ message: "Failed to get quality issue sequence"
+ };
+ }
+
+ const name =
+ args.name ??
+ `MES quality issue: ${context.itemReadableId ?? context.jobReadableId}`;
+
+ const issue = await serviceRole
+ .from("nonConformance")
+ .insert({
+ nonConformanceId: nextSequence.data,
+ name,
+ description: args.description ?? "",
+ priority: args.priority ?? "Medium",
+ source: "Internal",
+ locationId: context.locationId,
+ nonConformanceTypeId: args.nonConformanceTypeId ?? context.issueTypeId,
+ nonConformanceWorkflowId: null,
+ openDate: new Date().toISOString().slice(0, 10),
+ quantity,
+ assignee: context.assignee,
+ requiredActionIds: [],
+ approvalRequirements: [],
+ companyId,
+ createdBy: userId
+ } satisfies Database["public"]["Tables"]["nonConformance"]["Insert"])
+ .select("id")
+ .single();
+
+ if (issue.error || !issue.data?.id) {
+ return {
+ data: null,
+ error: issue.error,
+ message: "Failed to create quality issue"
+ };
+ }
+
+ const nonConformanceId = issue.data.id;
+
+ const [jobOperationAssociation, dispositionAssociation] = await Promise.all([
+ serviceRole.from("nonConformanceJobOperation").insert({
+ nonConformanceId,
+ jobOperationId: context.jobOperationId,
+ jobId: context.jobId,
+ jobReadableId: context.jobReadableId,
+ companyId,
+ createdBy: userId
+ }),
+ linkIssueDispositionContext(serviceRole, {
+ nonConformanceId,
+ companyId,
+ userId,
+ itemId: context.itemId,
+ jobMakeMethodId: context.jobMakeMethodId,
+ trackedEntityId: args.trackedEntityId,
+ quantity
+ })
+ ]);
+ const associationError =
+ jobOperationAssociation.error ?? dispositionAssociation.error;
+ if (associationError) {
+ await serviceRole
+ .from("nonConformance")
+ .delete()
+ .eq("id", nonConformanceId);
+ return {
+ data: null,
+ error: associationError,
+ message: "Failed to link quality issue to MES context"
+ };
+ }
+
+ const tasks = await serviceRole.functions.invoke("create", {
+ body: {
+ type: "nonConformanceTasks",
+ id: nonConformanceId,
+ companyId,
+ userId
+ }
+ });
+
+ if (tasks.error) {
+ await serviceRole
+ .from("nonConformance")
+ .delete()
+ .eq("id", nonConformanceId);
+ return {
+ data: null,
+ error: tasks.error,
+ message: "Failed to create quality issue tasks"
+ };
+ }
+
+ return { data: { id: nonConformanceId }, error: null, message: null };
+}
+
+export type InspectionOutcomeSample = {
+ id: string;
+ trackedEntityId: string | null;
+ status: string;
+};
+
+// Everything the disposition / complete-passed routes need to turn a verdict
+// into physical postings, recomputed fresh from the DB on every POST (client
+// form fields are operator intent, never trusted arithmetic).
+export type InspectionOutcomeState = {
+ inspection: any;
+ jobOperationId: string;
+ operation: Database["public"]["Tables"]["jobOperation"]["Row"];
+ jobId: string;
+ requiresSerialTracking: boolean;
+ requiresBatchTracking: boolean;
+ // The make method's batch WIP entity (batch-tracked completions accumulate
+ // onto it via jobOperationBatchComplete).
+ batchTrackedEntityId: string | null;
+ // Ascending (createdAt, id) — the grid's column order and the completion
+ // processing order.
+ samples: InspectionOutcomeSample[];
+ lotSize: number;
+ // Production rows already linked to this inspection: per-sample links are
+ // the serial double-count guard; the quantity sum is the non-serial one.
+ linkedSampleIds: Set<string>;
+ linkedProductionQuantity: number;
+ // Operation quantity column bookkeeping. `opRemaining` nets out EVERY
+ // posting — complete, scrapped, reworked, linked or not — so escape-hatch
+ // menu postings can never be double-counted by the orchestration.
+ opTarget: number;
+ opAccounted: number;
+ opRemaining: number;
+ // Serial only: the make method's WIP entities and the eligibility test
+ // (not Consumed, not Rejected, not already completed at this operation).
+ entities: { id: string; status: string | null; attributes: unknown }[];
+ entityEligible: (entityId: string) => boolean;
+};
+
+export async function getInspectionOutcomeState(
+ serviceRole: ServiceRole,
+ args: { inspectionId: string; companyId: string }
+): Promise<
+ | { data: InspectionOutcomeState; error: null; message: null }
+ | { data: null; error: unknown; message: string }
+> {
+ const inspectionResult = await getInspection(serviceRole, args.inspectionId);
+ if (inspectionResult.error || !inspectionResult.data) {
+ return {
+ data: null,
+ error: inspectionResult.error,
+ message: "Failed to load inspection"
+ };
+ }
+ const inspection = inspectionResult.data as any;
+ const jobOperationId = inspection.sourceDocumentLineId as string | null;
+ if (inspection.sourceDocument !== "Job Operation" || !jobOperationId) {
+ return {
+ data: null,
+ error: null,
+ message: "Inspection is not a job operation lot"
+ };
+ }
+
+ const [operationResult, linkedRows] = await Promise.all([
+ serviceRole
+ .from("jobOperation")
+ .select("*")
+ .eq("id", jobOperationId)
+ .single(),
+ serviceRole
+ .from("productionQuantity")
+ .select("id, type, quantity, inspectionSampleId")
+ .eq("inspectionId", args.inspectionId)
+ ]);
+ if (operationResult.error || !operationResult.data) {
+ return {
+ data: null,
+ error: operationResult.error,
+ message: "Failed to load job operation"
+ };
+ }
+ const operation = operationResult.data;
+ if (operation.companyId !== args.companyId) {
+ return {
+ data: null,
+ error: null,
+ message: "Job operation is not in this company"
+ };
+ }
+
+ const jobMakeMethod = operation.jobMakeMethodId
+ ? await getJobMakeMethod(serviceRole, operation.jobMakeMethodId)
+ : null;
+ const requiresSerialTracking =
+ jobMakeMethod?.data?.requiresSerialTracking ?? false;
+ const requiresBatchTracking =
+ jobMakeMethod?.data?.requiresBatchTracking ?? false;
+
+ const trackedEntities =
+ requiresSerialTracking && operation.jobMakeMethodId
+ ? await getTrackedEntitiesByMakeMethodId(
+ serviceRole,
+ operation.jobMakeMethodId
+ )
+ : null;
+
+ const samples: InspectionOutcomeSample[] = [
+ ...((inspection.inspectionSample ?? []) as any[])
+ ]
+ .sort(
+ (a, b) =>
+ (a.createdAt ?? "").localeCompare(b.createdAt ?? "") ||
+ a.id.localeCompare(b.id)
+ )
+ .map((s) => ({
+ id: s.id,
+ trackedEntityId: s.trackedEntityId ?? null,
+ status: s.status
+ }));
+
+ const productionRows = (linkedRows.data ?? []).filter(
+ (r) => r.type === "Production"
+ );
+ const linkedSampleIds = new Set(
+ productionRows
+ .map((r) => r.inspectionSampleId)
+ .filter((id): id is string => Boolean(id))
+ );
+ const linkedProductionQuantity = productionRows.reduce(
+ (sum, r) => sum + (r.quantity ?? 0),
+ 0
+ );
+
+ const opTarget = operation.targetQuantity ?? operation.operationQuantity ?? 0;
+ const opAccounted =
+ (operation.quantityComplete ?? 0) +
+ (operation.quantityScrapped ?? 0) +
+ (operation.quantityReworked ?? 0);
+ const opRemaining = Math.max(0, opTarget - opAccounted);
+
+ const entities = (trackedEntities?.data ?? []).map((e) => ({
+ id: e.id,
+ status: e.status,
+ attributes: e.attributes
+ }));
+ const opAttrKey = `Operation ${jobOperationId}`;
+ const entityById = new Map(entities.map((e) => [e.id, e]));
+ const entityEligible = (entityId: string) => {
+ const entity = entityById.get(entityId);
+ if (!entity) return false;
+ if (entity.status === "Consumed" || entity.status === "Rejected") {
+ return false;
+ }
+ const attributes = (entity.attributes ?? {}) as Record<string, unknown>;
+ return !attributes[opAttrKey];
+ };
+
+ return {
+ data: {
+ inspection,
+ jobOperationId,
+ operation,
+ jobId: operation.jobId,
+ requiresSerialTracking,
+ requiresBatchTracking,
+ batchTrackedEntityId: jobMakeMethod?.data?.trackedEntityId ?? null,
+ samples,
+ lotSize: Number(inspection.lotSize ?? 0),
+ linkedSampleIds,
+ linkedProductionQuantity,
+ opTarget,
+ opAccounted,
+ opRemaining,
+ entities,
+ entityEligible
+ },
+ error: null,
+ message: null
+ };
+}
+
+// The serial units a completion pass may post, in ascending sample order:
+// sampled units whose sample isn't linked yet, then (optionally) sample-less
+// eligible units. Verdict-driven double-posting is impossible — the sample
+// link's partial UNIQUE index guards sampled units, and the `Operation <opId>`
+// entity attribute (via entityEligible) guards sample-less ones.
+export function getSerialCompletionCandidates(
+ state: InspectionOutcomeState,
+ opts: {
+ // Accept completes Pending-sampled units too (identify-only scans that
+ // never failed); progressive complete-passed takes Passed only.
+ includePending: boolean;
+ // Accept sweeps un-sampled eligible units; Partial/complete-passed don't.
+ includeSampleless: boolean;
+ excludeEntityIds?: Set<string>;
+ }
+): { trackedEntityId: string; inspectionSampleId: string | null }[] {
+ const candidates: {
+ trackedEntityId: string;
+ inspectionSampleId: string | null;
+ }[] = [];
+ const sampledEntityIds = new Set<string>();
+ for (const sample of state.samples) {
+ if (sample.trackedEntityId) sampledEntityIds.add(sample.trackedEntityId);
+ const statusOk =
+ sample.status === "Passed" ||
+ (opts.includePending && sample.status === "Pending");
+ if (!statusOk) continue;
+ if (!sample.trackedEntityId) continue;
+ if (state.linkedSampleIds.has(sample.id)) continue;
+ if (!state.entityEligible(sample.trackedEntityId)) continue;
+ if (opts.excludeEntityIds?.has(sample.trackedEntityId)) continue;
+ candidates.push({
+ trackedEntityId: sample.trackedEntityId,
+ inspectionSampleId: sample.id
+ });
+ }
+ if (opts.includeSampleless) {
+ for (const entity of state.entities) {
+ if (sampledEntityIds.has(entity.id)) continue;
+ if (!state.entityEligible(entity.id)) continue;
+ if (opts.excludeEntityIds?.has(entity.id)) continue;
+ candidates.push({ trackedEntityId: entity.id, inspectionSampleId: null });
+ }
+ }
+ return candidates;
+}
+
+// One `issue` serial-complete per unit (quantity 1), carrying the provenance
+// links. Sequential on purpose: each complete mints the next Reserved entity
+// and backflushes; stops at the first failure and reports how far it got.
+export async function postSerialCompletions(
+ serviceRole: ServiceRole,
+ args: {
+ candidates: {
+ trackedEntityId: string;
+ inspectionSampleId: string | null;
+ }[];
+ jobOperationId: string;
+ inspectionId: string;
+ eventIds: ProductionEventIds;
+ companyId: string;
+ userId: string;
+ }
+): Promise<{ completed: number; error: unknown | null }> {
+ let completed = 0;
+ for (const candidate of args.candidates) {
+ const response = await serviceRole.functions.invoke("issue", {
+ body: {
+ type: "jobOperationSerialComplete",
+ trackedEntityId: candidate.trackedEntityId,
+ quantity: 1,
+ jobOperationId: args.jobOperationId,
+ inspectionId: args.inspectionId,
+ ...(candidate.inspectionSampleId
+ ? { inspectionSampleId: candidate.inspectionSampleId }
+ : {}),
+ ...args.eventIds,
+ companyId: args.companyId,
+ userId: args.userId
+ }
+ });
+ if (response.error) return { completed, error: response.error };
+ completed += 1;
+ }
+ return { completed, error: null };
+}
+
+// Non-serial completion: one bulk Production posting (batch entities
+// accumulate via the issue edge fn; untracked inserts + backflushes here).
+// The row links the inspection plus the lowest unlinked passed sample as a
+// serializing representative — concurrent posts collide on the sample link's
+// UNIQUE index instead of double-counting.
+export async function postBulkCompletion(
+ serviceRole: ServiceRole,
+ client: SupabaseClient<Database>,
+ state: InspectionOutcomeState,
+ args: {
+ quantity: number;
+ eventIds: ProductionEventIds;
+ companyId: string;
+ userId: string;
+ }
+): Promise<{ error: unknown | null; message: string | null }> {
+ const watermark = state.samples.find(
+ (s) => s.status === "Passed" && !state.linkedSampleIds.has(s.id)
+ );
+
+ if (state.requiresBatchTracking && state.batchTrackedEntityId) {
+ const response = await serviceRole.functions.invoke("issue", {
+ body: {
+ type: "jobOperationBatchComplete",
+ trackedEntityId: state.batchTrackedEntityId,
+ quantity: args.quantity,
+ jobOperationId: state.jobOperationId,
+ inspectionId: state.inspection.id,
+ ...(watermark ? { inspectionSampleId: watermark.id } : {}),
+ ...args.eventIds,
+ companyId: args.companyId,
+ userId: args.userId
+ }
+ });
+ if (response.error) {
+ return { error: response.error, message: "Failed to complete units" };
+ }
+ return { error: null, message: null };
+ }
+
+ const insertResult = await insertProductionQuantity(client, {
+ jobOperationId: state.jobOperationId,
+ quantity: args.quantity,
+ inspectionId: state.inspection.id,
+ ...(watermark ? { inspectionSampleId: watermark.id } : {}),
+ ...args.eventIds,
+ companyId: args.companyId,
+ createdBy: args.userId
+ });
+ if (insertResult.error) {
+ return {
+ error: insertResult.error,
+ message: "Failed to record production quantity"
+ };
+ }
+
+ const issue = await serviceRole.functions.invoke("issue", {
+ body: {
+ id: state.jobOperationId,
+ type: "jobOperation",
+ quantity: args.quantity,
+ companyId: args.companyId,
+ userId: args.userId
+ }
+ });
+ if (issue.error) {
+ return {
+ error: issue.error,
+ message: "Units completed, but failed to issue materials"
+ };
+ }
+
+ return { error: null, message: null };
+}
+
+// Auto-creates the optional NCR documenting a rejected (or partially rejected)
+// inspection lot — failed features (measured values vs. spec) + sampling
+// summary in the description — and links it back via nonConformanceInspection.
+// Purely documentation: the physical outcome (scrap/rework/complete) is
+// orchestrated by the disposition route, never by the NCR. Lifted from the
+// retired inspection-lot reject route.
+export async function createInspectionRejectionIssue(
+ serviceRole: ServiceRole,
+ args: {
+ inspectionId: string;
+ companyId: string;
+ userId: string;
+ nonConformanceTypeId?: string;
+ }
+): Promise<{ error: unknown | null; message: string | null }> {
+ const { inspectionId, companyId, userId } = args;
+
+ const inspection = await getInspection(serviceRole, inspectionId);
+ if (inspection.error || !inspection.data) {
+ return {
+ error: inspection.error,
+ message: "Failed to load the lot for the quality issue"
+ };
+ }
+ const insp = inspection.data as any;
+ const jobOperationId = insp.sourceDocumentLineId as string | null;
+ if (!jobOperationId) {
+ return { error: null, message: "Lot has no job operation to link" };
+ }
+
+ const inspectionReadableId = insp.inspectionId ?? "";
+ const itemReadableId =
+ insp.item?.readableId ?? insp.itemReadableId ?? insp.itemId;
+
+ const issueTitle = [
+ "Rejected lot",
+ inspectionReadableId,
+ itemReadableId && `— ${itemReadableId}`,
+ insp.sourceDocumentReadableId && `on ${insp.sourceDocumentReadableId}`
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ // Document-driven lots: attach the failed features (measured values
+ // vs. spec) so MRB sees what failed and by how much without re-measuring.
+ const [lotFeatures, lotMeasurements] = await Promise.all([
+ getInspectionSamplingPlans(serviceRole, inspectionId, companyId),
+ getInspectionMeasurements(serviceRole, inspectionId, companyId)
+ ]);
+ const failedFeatureLines: string[] = [];
+ for (const lotFeature of lotFeatures.data ?? []) {
+ const feature = lotFeature.inspectionFeature;
+ if (!feature) continue;
+ const featureMeasurements = (lotMeasurements.data ?? []).filter(
+ (m) => m.inspectionFeatureId === feature.id
+ );
+ const recorded = featureMeasurements.filter(
+ (m) => m.status !== "Pending"
+ ).length;
+ const failed = featureMeasurements.filter((m) => m.status === "Failed");
+ if (failed.length === 0) continue;
+ const failedValues = failed
+ .map((m) => (m.value == null ? "F" : String(m.value)))
+ .join(", ");
+ const spec = [
+ feature.nominalValue,
+ feature.tolerancePlus != null || feature.toleranceMinus != null
+ ? `+${feature.tolerancePlus ?? "0"}/−${feature.toleranceMinus ?? "0"}`
+ : null,
+ feature.unit
+ ]
+ .filter(Boolean)
+ .join(" ");
+ failedFeatureLines.push(
+ spec
+ ? `- ${feature.label}: nominal ${spec} — failed values: ${failedValues} (${failed.length}/${recorded} failed, n=${lotFeature.sampleSize}, Ac=${lotFeature.acceptanceNumber})`
+ : `- ${feature.label}: ${failed.length}/${recorded} failed (n=${lotFeature.sampleSize}, Ac=${lotFeature.acceptanceNumber})`
+ );
+ }
+ const failedFeaturesBlock =
+ failedFeatureLines.length > 0
+ ? `\n\nFailed features:\n${failedFeatureLines.join("\n")}`
+ : "";
+
+ const issue = await createQualityIssue(serviceRole, {
+ companyId,
+ userId,
+ jobOperationId,
+ nonConformanceTypeId: args.nonConformanceTypeId,
+ name: issueTitle,
+ description: `Auto-created from inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}.${failedFeaturesBlock}`,
+ priority: "Medium",
+ quantity: Number(insp.lotSize ?? 1)
+ });
+
+ if (issue.error || !issue.data) {
+ return {
+ error: issue.error,
+ message: issue.message ?? "Failed to create quality issue"
+ };
+ }
+
+ // Link the source inspection to the issue so the ERP issue explorer can
+ // surface the origin and deep-link back to the inspection lot.
+ const link = await serviceRole.from("nonConformanceInspection").insert({
+ nonConformanceId: issue.data.id,
+ inspectionId,
+ companyId,
+ createdBy: userId
+ });
+ if (link.error) {
+ return {
+ error: link.error,
+ message: "Quality issue created, but failed to link the inspection"
+ };
+ }
+
+ return { error: null, message: null };
+}
+
+async function getIssueContext(
+ client: ServiceRole,
+ args: {
+ companyId: string;
+ userId: string;
+ jobOperationId: string;
+ }
+): Promise<IssueContext> {
+ const operation = await client
+ .from("jobOperation")
+ .select("id, companyId, jobId, jobMakeMethodId, operationOrder")
+ .eq("id", args.jobOperationId)
+ .maybeSingle();
+
+ if (operation.error || !operation.data) {
+ return {
+ ok: false,
+ error: operation.error,
+ message: "Failed to load job operation"
+ };
+ }
+
+ if (operation.data.companyId !== args.companyId) {
+ return {
+ ok: false,
+ error: null,
+ message: "Job operation is not in this company"
+ };
+ }
+
+ const [job, defaults, issueType] = await Promise.all([
+ client
+ .from("job")
+ .select("id, jobId, itemId, locationId, assignee")
+ .eq("id", operation.data.jobId)
+ .maybeSingle(),
+ client
+ .from("userDefaults")
+ .select("locationId")
+ .eq("userId", args.userId)
+ .eq("companyId", args.companyId)
+ .maybeSingle(),
+ client
+ .from("nonConformanceType")
+ .select("id")
+ .eq("companyId", args.companyId)
+ .order("name", { ascending: true })
+ .limit(1)
+ .maybeSingle()
+ ]);
+
+ if (job.error || !job.data) {
+ return {
+ ok: false,
+ error: job.error,
+ message: "Failed to load job context"
+ };
+ }
+
+ if (issueType.error || !issueType.data?.id) {
+ return {
+ ok: false,
+ error: issueType.error,
+ message:
+ "Configure at least one quality issue type before creating MES issues"
+ };
+ }
+
+ const locationId = defaults.data?.locationId ?? job.data.locationId;
+ if (!locationId) {
+ return {
+ ok: false,
+ error: defaults.error,
+ message: "A location is required to create a quality issue"
+ };
+ }
+
+ const item = job.data.itemId
+ ? await client
+ .from("item")
+ .select("readableId, name")
+ .eq("id", job.data.itemId)
+ .maybeSingle()
+ : null;
+
+ return {
+ ok: true,
+ jobOperationId: operation.data.id,
+ operationOrder: operation.data.operationOrder,
+ jobId: job.data.id,
+ jobReadableId: job.data.jobId,
+ jobMakeMethodId: operation.data.jobMakeMethodId,
+ itemId: job.data.itemId,
+ itemReadableId:
+ item?.data?.readableId ?? item?.data?.name ?? job.data.itemId ?? null,
+ locationId,
+ issueTypeId: issueType.data.id,
+ assignee: job.data.assignee
+ };
+}
+
+async function linkIssueDispositionContext(
+ client: ServiceRole,
+ args: {
+ nonConformanceId: string;
+ companyId: string;
+ userId: string;
+ itemId: string | null;
+ jobMakeMethodId: string | null;
+ trackedEntityId?: string;
+ quantity: number;
+ }
+): Promise<{ error: unknown | null }> {
+ const {
+ nonConformanceId,
+ companyId,
+ userId,
+ itemId,
+ jobMakeMethodId,
+ trackedEntityId,
+ quantity
+ } = args;
+
+ if (!itemId) return { error: null };
+
+ const trackedEntities = await getTrackedEntitiesForIssue(client, {
+ companyId,
+ jobMakeMethodId,
+ trackedEntityId
+ });
+
+ if (trackedEntities.error) {
+ return { error: trackedEntities.error };
+ }
+
+ const itemQuantity =
+ trackedEntities.data.length > 0
+ ? trackedEntities.data.reduce(
+ (total, entity) => total + Number(entity.quantity ?? quantity),
+ 0
+ )
+ : quantity;
+
+ const item = await client
+ .from("nonConformanceItem")
+ .insert({
+ nonConformanceId,
+ itemId,
+ quantity: itemQuantity,
+ disposition: "Pending",
+ companyId,
+ createdBy: userId
+ })
+ .select("id")
+ .single();
+
+ if (item.error || !item.data?.id) {
+ return { error: item.error ?? new Error("Failed to create issue item") };
+ }
+
+ if (trackedEntities.data.length === 0) {
+ return { error: null };
+ }
+
+ const trackedEntityLinks = await client
+ .from("nonConformanceTrackedEntity")
+ .insert(
+ trackedEntities.data.map((entity) => ({
+ nonConformanceId,
+ trackedEntityId: entity.id,
+ companyId,
+ createdBy: userId
+ }))
+ );
+
+ if (trackedEntityLinks.error) {
+ return { error: trackedEntityLinks.error };
+ }
+
+ const dispositionLinks = await client
+ .from("nonConformanceItemTrackedEntity")
+ .insert(
+ trackedEntities.data.map((entity) => ({
+ nonConformanceItemId: item.data.id,
+ nonConformanceId,
+ trackedEntityId: entity.id,
+ quantity: Number(entity.quantity ?? quantity),
+ companyId,
+ createdBy: userId
+ }))
+ );
+
+ return { error: dispositionLinks.error };
+}
+
+async function getTrackedEntitiesForIssue(
+ client: ServiceRole,
+ args: {
+ companyId: string;
+ jobMakeMethodId: string | null;
+ trackedEntityId?: string;
+ }
+): Promise<{
+ data: { id: string; quantity: number | null }[];
+ error: unknown | null;
+}> {
+ if (!args.trackedEntityId) {
+ return { data: [], error: null };
+ }
+
+ const entity = await client
+ .from("trackedEntity")
+ .select("id, quantity")
+ .eq("id", args.trackedEntityId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+
+ if (entity.error) {
+ return { data: [], error: entity.error };
+ }
+
+ if (!entity.data) {
+ return {
+ data: [],
+ error: new Error("Tracked entity is not in this company")
+ };
+ }
+
+ return { data: [entity.data], error: null };
+}
diff --git a/apps/mes/app/services/quality.service.ts b/apps/mes/app/services/quality.service.ts
new file mode 100644
index 0000000000..b02f5a2661
--- /dev/null
+++ b/apps/mes/app/services/quality.service.ts
@@ -0,0 +1,99 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+// Reads for the MES inspection execution view. Copied from the ERP quality
+// module's service reads (apps/erp/app/modules/quality/quality.service.ts) —
+// MES cannot import ERP app code, and reads stay supabase-js by convention.
+
+export async function getInspection(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return (client as any)
+ .from("inspection")
+ .select(
+ "*, item(readableId, name, type, itemTrackingType), inspectionSample(*, trackedEntity(id, readableId, attributes, status, sourceDocumentReadableId))"
+ )
+ .eq("id", id)
+ .single();
+}
+
+export async function getInspectionSamplingPlans(
+ client: SupabaseClient<Database>,
+ inspectionId: string,
+ companyId: string
+) {
+ // Embed by target table name, never alias:fkColumn — composite-FK embeds
+ // break with the alias form.
+ return client
+ .from("inspectionSamplingPlan")
+ .select(
+ "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit)"
+ )
+ .eq("inspectionId", inspectionId)
+ .eq("companyId", companyId);
+}
+
+export async function getInspectionMeasurements(
+ client: SupabaseClient<Database>,
+ inspectionId: string,
+ companyId: string
+) {
+ return client
+ .from("inspectionMeasurement")
+ .select("*")
+ .eq("inspectionId", inspectionId)
+ .eq("companyId", companyId);
+}
+
+export async function getIssueTypesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("nonConformanceType")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .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
+// production module assembles via mapInspectionDocument/mapBalloon.
+export async function getInspectionDocumentWithBalloons(
+ client: SupabaseClient<Database>,
+ inspectionDocumentId: string
+) {
+ const [document, balloons] = await Promise.all([
+ client
+ .from("inspectionDocument")
+ .select("id, drawingNumber, fileName, storagePath")
+ .eq("id", inspectionDocumentId)
+ .single(),
+ client
+ .from("balloon")
+ .select("id, inspectionFeatureId, pageNumber, xCoordinate, yCoordinate")
+ .eq("inspectionDocumentId", inspectionDocumentId)
+ ]);
+
+ if (document.error) {
+ return { data: null, error: document.error };
+ }
+
+ const storagePath = document.data?.storagePath ?? null;
+ return {
+ data: {
+ name:
+ document.data?.drawingNumber ??
+ document.data?.fileName ??
+ "Untitled Diagram",
+ pdfUrl: storagePath
+ ? storagePath.startsWith("/file/preview/private/")
+ ? storagePath
+ : `/file/preview/private/${storagePath}`
+ : null,
+ balloons: balloons.data ?? []
+ },
+ error: null
+ };
+}
diff --git a/apps/mes/app/services/types.ts b/apps/mes/app/services/types.ts
index 82bd18a61c..e929fb267b 100644
--- a/apps/mes/app/services/types.ts
+++ b/apps/mes/app/services/types.ts
@@ -1,3 +1,4 @@
+import type { Database } from "@carbon/database";
import type { FileObject } from "@supabase/storage-js";
import type {
getJobByOperationId,
@@ -14,6 +15,11 @@ import type {
getTrackedEntitiesByMakeMethodId,
getTrackedInputs
} from "./operations.service";
+import type {
+ getInspectionMeasurements,
+ getInspectionSamplingPlans,
+ getIssueTypesList
+} from "./quality.service";
export type BaseOperation = NonNullable<
Awaited<ReturnType<typeof getRecentJobOperationsByEmployee>>["data"]
@@ -97,3 +103,30 @@ export type TrackedInput = NonNullable<
export type WorkCenter = NonNullable<
Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
>[number];
+
+export type Inspection = Database["public"]["Tables"]["inspection"]["Row"];
+
+export type InspectionStatus =
+ Database["public"]["Enums"]["inspectionStatusType"];
+
+export type InspectionTrackedEntity = Pick<
+ Database["public"]["Tables"]["trackedEntity"]["Row"],
+ "id" | "readableId" | "attributes" | "status" | "sourceDocumentReadableId"
+>;
+
+export type InspectionSample =
+ Database["public"]["Tables"]["inspectionSample"]["Row"] & {
+ trackedEntity: InspectionTrackedEntity | null;
+ };
+
+export type InspectionSamplingPlan = NonNullable<
+ Awaited<ReturnType<typeof getInspectionSamplingPlans>>["data"]
+>[number];
+
+export type InspectionMeasurement = NonNullable<
+ Awaited<ReturnType<typeof getInspectionMeasurements>>["data"]
+>[number];
+
+export type IssueTypeListItem = NonNullable<
+ Awaited<ReturnType<typeof getIssueTypesList>>["data"]
+>[number];
diff --git a/apps/mes/app/ssr-shims/canvas-stub.cjs b/apps/mes/app/ssr-shims/canvas-stub.cjs
new file mode 100644
index 0000000000..ec941e6557
--- /dev/null
+++ b/apps/mes/app/ssr-shims/canvas-stub.cjs
@@ -0,0 +1,62 @@
+/**
+ * Stub for Node's `canvas` package. Konva's `lib/index-node.js` requires it
+ * when Vite SSR evaluates `konva`; we avoid installing native `canvas`.
+ * SSR does not render Konva output; this only needs to load without throwing.
+ */
+"use strict";
+
+class ImageStub {
+ constructor() {
+ this.src = "";
+ this.onload = null;
+ this.onerror = null;
+ }
+}
+
+function createCanvas() {
+ return {
+ width: 300,
+ height: 300,
+ style: {},
+ getContext() {
+ return {
+ canvas: null,
+ fillRect() {},
+ clearRect() {},
+ drawImage() {},
+ fill() {},
+ stroke() {},
+ beginPath() {},
+ closePath() {},
+ moveTo() {},
+ lineTo() {},
+ rect() {},
+ clip() {},
+ save() {},
+ restore() {},
+ translate() {},
+ scale() {},
+ rotate() {},
+ measureText() {
+ return { width: 0 };
+ }
+ };
+ }
+ };
+}
+
+const DOMMatrixStub =
+ typeof globalThis.DOMMatrix !== "undefined"
+ ? globalThis.DOMMatrix
+ : class DOMMatrixStubInner {
+ constructor() {}
+ };
+
+const api = {
+ createCanvas,
+ Image: ImageStub,
+ DOMMatrix: DOMMatrixStub
+};
+
+module.exports = api;
+module.exports.default = api;
diff --git a/apps/mes/app/utils/operationView.ts b/apps/mes/app/utils/operationView.ts
new file mode 100644
index 0000000000..a6a67485cf
--- /dev/null
+++ b/apps/mes/app/utils/operationView.ts
@@ -0,0 +1,36 @@
+/**
+ * The view resolver (Workstream C). A pure mapping from an operation's classification
+ * (`operationType`) to the execution view the operator should land on. The MES operation
+ * route calls this and renders the matching component, so a single route + deep link
+ * survives a type change. See .ai/specs/2026-07-20-operation-type-consolidation.md and
+ * .ai/specs/2026-07-14-mes-execution-views.md §5.1.
+ *
+ * Tracking type is orthogonal — it decides per-unit vs. batch cadence *inside* a view,
+ * never which view.
+ */
+export type OperationType =
+ | "Process"
+ | "Assembly"
+ | "Inspection"
+ | "Outside Processing";
+
+export type OperationView = "operation" | "assembly" | "inspection";
+
+/**
+ * Resolve the view for an operation type. Anything unrecognized — including
+ * `null`/`undefined`, the default `Process`, and `Outside Processing` (subcontracted
+ * work has no execution view of its own) — falls back to the Operation view, so the
+ * route is always safe to open (ADR-0001).
+ */
+export function resolveOperationView(
+ type: OperationType | null | undefined
+): OperationView {
+ switch (type) {
+ case "Assembly":
+ return "assembly";
+ case "Inspection":
+ return "inspection";
+ default:
+ return "operation";
+ }
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index f2cc8b303f..c879498122 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -39,12 +39,14 @@ export const path = {
`${api}/suggested-allocation?itemId=${itemId}&locationId=${locationId}&quantity=${quantity}`
)
},
+ assembly: (id: string) => generatePath(`${x}/assembly/${id}`),
assigned: `${x}/assigned`,
authenticatedRoot: x,
callback: "/callback",
companySwitch: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
complete: `${x}/complete`,
+ completeAllSteps: `${x}/steps/complete-all`,
consolePinIn: `${x}/console/pin-in`,
consolePinOut: `${x}/console/pin-out`,
consoleToggle: `${x}/console/toggle`,
@@ -123,6 +125,16 @@ export const path = {
},
finish: `${x}/finish`,
health: "/health",
+ inspection: (operationId: string) =>
+ generatePath(`${x}/inspection/${operationId}`),
+ inspectionCompletePassed: (id: string) =>
+ generatePath(`${x}/inspection-lot/${id}/complete-passed`),
+ inspectionDisposition: (id: string) =>
+ generatePath(`${x}/inspection-lot/${id}/disposition`),
+ inspectionMeasurement: (id: string) =>
+ generatePath(`${x}/inspection-lot/${id}/measurement`),
+ inspectionSample: (id: string) =>
+ generatePath(`${x}/inspection-lot/${id}/sample`),
inspectionSteps: `${x}/steps/inspection`,
inventoryAdjustment: `${x}/adjustment`,
issue: `${x}/issue`,
diff --git a/apps/mes/app/utils/units.ts b/apps/mes/app/utils/units.ts
new file mode 100644
index 0000000000..0ffb24ce9a
--- /dev/null
+++ b/apps/mes/app/utils/units.ts
@@ -0,0 +1,42 @@
+/**
+ * The unit axis (FIX-1) — the list of units an operator pages through ("Unit X of N").
+ *
+ * Quantity-centric, so it works for *every* tracking type:
+ * - Serial: `count` entities → unit i bound to entities[i]
+ * - Batch: 1 lot entity → unit 0 bound to the lot, units 1..N-1 bound to null
+ * - Inventory: 0 entities → every unit bound to null
+ *
+ * `index` is the 0-based axis position and is the key written to
+ * `jobOperationStepRecord.index` / the inspection result record, identical to the
+ * convention the Operation view already uses. This is what isolates unit i's
+ * step records from every other unit. See .ai/specs/2026-07-14-mes-execution-views.md
+ * §2 ("unit axis").
+ */
+export type Unit<E> = {
+ index: number;
+ entity: E | null;
+};
+
+/**
+ * Derive the unit axis from a unit count and an optional list of tracked entities.
+ *
+ * @param count How many units to page — `operationQuantity` for Assembly, or the
+ * derived sample size for Inspection. Rounded and clamped to >= 1 so a
+ * missing/zero/NaN quantity still yields a single shared unit (mirrors the
+ * existing `Math.max(1, Math.round(operationQuantity))` behavior).
+ * @param entities The tracked entities, in their stable loader order. Entities beyond
+ * `count` are ignored (a job may pre-generate more serials than it builds);
+ * a `count` longer than the list binds the surplus units to `null`.
+ */
+export function deriveUnits<E>(
+ count: number,
+ entities?: readonly E[] | null
+): Unit<E>[] {
+ const total = Math.max(1, Math.round(Number.isFinite(count) ? count : 1));
+ const list = entities ?? [];
+
+ return Array.from({ length: total }, (_, index) => ({
+ index,
+ entity: list[index] ?? null
+ }));
+}
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 24d5176283..58d76163c4 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -62,16 +62,20 @@
"dompurify": "catalog:",
"framer-motion": "catalog:",
"isbot": "catalog:",
+ "konva": "^9.3.22",
+ "kysely": "catalog:",
"localforage": "1.10.0",
"nanoid": "catalog:",
"nanostores": "catalog:",
"non.geist": "catalog:",
+ "pdfjs-dist": "5.4.296",
"posthog-js": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-dropzone": "catalog:",
"react-hotkeys-hook": "catalog:",
"react-icons": "catalog:",
+ "react-konva": "^18.2.10",
"react-pdf": "catalog:",
"react-resizable-panels": "catalog:",
"react-router": "catalog:",
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index a56589ebe3..c00dfaa6bd 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -56,6 +56,12 @@ export default defineConfig(({ mode, isSsrBuild }) => {
resolve: {
tsconfigPaths: true,
alias: {
+ /**
+ * Konva's Node entry (`index-node.js`) requires native `canvas`. Vite SSR
+ * can still load that graph; alias `canvas` to a stub (do not alias the
+ * konva entry itself — the drawing pane needs the real browser build).
+ */
+ canvas: path.resolve(__dirname, "app/ssr-shims/canvas-stub.cjs"),
// Directory (not index.ts) so subpath imports like
// `@carbon/utils/favicon` resolve to `src/favicon.ts`.
"@carbon/utils": path.resolve(__dirname, "../../packages/utils/src"),
diff --git a/docs/content/docs/reference/jobs.mdx b/docs/content/docs/reference/jobs.mdx
index aa67ec42c1..acccc80c50 100644
--- a/docs/content/docs/reference/jobs.mdx
+++ b/docs/content/docs/reference/jobs.mdx
@@ -61,12 +61,12 @@ The job's <Term id="routing">routing</Term> is copied into job-specific **operat
<Status name="Canceled" terminal>Won't run.</Status>
</StatusFlow>
-### Inside and outside
+### Operation type
-Each operation is **Inside** or **Outside**. An Inside operation runs on one of your work centers and prices against its rates. An **<Term id="outside-operation">outside</Term>** operation is subcontracted: instead of a work center it points at a supplier process, copies that supplier's cost and lead time, and drives an outside-processing <Term id="purchase-order">purchase order</Term>.
+Each operation carries an <Term id="operation-type">operation type</Term>: **Process**, **Assembly**, **Inspection**, or **Outside Processing**. The first three run in-house on one of your work centers and price against its rates, and the type decides which execution view the operator sees on the shop floor. A plain **Process** operation runs the standard operation view. An **Assembly** operation opens a guided, step-by-step build view: 3D animated work instructions play each step's insertion motion, with the parts, tools, and reference images scoped to the step in front of the operator. An **Inspection** operation runs a quality check, recording measured features against a ballooned drawing (the same execution screen the quality module uses for received goods). An **<Term id="outside-operation">Outside Processing</Term>** operation is subcontracted: instead of a work center it points at a supplier process, copies that supplier's cost and lead time, and drives an outside-processing <Term id="purchase-order">purchase order</Term>. The process you pick carries the same type and defaults it on new operations.
<Callout type="warn">
-An outside operation's cost and lead time are copied when you set the supplier process, not linked live. If the supplier's pricing changes, re-select the supplier process to refresh it.
+An Outside Processing operation's cost and lead time are copied when you set the supplier process, not linked live. If the supplier's pricing changes, re-select the supplier process to refresh it.
</Callout>
### Sequencing
@@ -79,7 +79,7 @@ The floor reports two separate things against an operation. A <Term id="producti
### Procedures
-Each operation can attach a <Term id="procedure">procedure</Term>: a reusable set of work instructions keyed to a process. A procedure carries an ordered list of typed **steps** the operator completes (a value, a measurement with a min/max range, a checkbox, a list choice, a timestamp, a person, or a file), any of which can be marked required. It also carries **parameters**, the process settings the work runs at, such as a temperature or speed. Separately, the operation lists the **tools** it requires.
+Each operation can attach a <Term id="procedure">procedure</Term>: a reusable set of work instructions keyed to a process. A procedure carries an ordered list of typed **steps** the operator completes (a value, a measurement with a min/max range, a checkbox, a list choice, a timestamp, a person, or a file), any of which can be marked required. It also carries **parameters**, the process settings the work runs at, such as a temperature or speed. Separately, the operation lists the **tools** it requires. A material or tool can be assigned to a single step, or left to apply across the whole operation — so an assembly view shows the operator exactly the parts and tools each step needs as they advance.
Because a procedure is keyed by process, you author it once and every operation running that process can attach it. It's versioned, moving through **Draft** while it's written, **Active** once ready for live work, and **Archived** when retired.
@@ -128,5 +128,5 @@ Creating the job needs a location and the company has none (or no default). Add
Completing the job to inventory referenced a serial or batch that no longer exists — usually consumed or deleted since the job's output was recorded. Re-check the job's tracked outputs and materials before completing again.
### "Failed to schedule job"
-The scheduling engine errored while placing the job's operations. Check that every operation has a work center (inside operations) or supplier process (outside operations) and that the job has a due date, then retry from the job's status menu.
+The scheduling engine errored while placing the job's operations. Check that every operation has a work center (in-house Process, Assembly, and Inspection operations) or a supplier process (Outside Processing operations) and that the job has a due date, then retry from the job's status menu.
</AgentContext>
diff --git a/docs/content/docs/reference/quality.mdx b/docs/content/docs/reference/quality.mdx
index 0d916b7d67..890964b309 100644
--- a/docs/content/docs/reference/quality.mdx
+++ b/docs/content/docs/reference/quality.mdx
@@ -15,6 +15,8 @@ Issues open from several places: by hand, from the shop floor in MES, from Slack
An issue can run a configurable workflow, often an **<Term id="8d">8D</Term>**. The workflow attaches **required actions** and **approvals** as tasks; each task advances *Pending → In Progress → Completed* as the team works it. Adding a **Material Review Board** approval gates closing the issue: it can't close until a **disposition** is chosen for the affected material. The five options are *Pending* (not yet decided), *Return to Supplier*, *<Term>Rework</Term>*, *<Term>Scrap</Term>*, and *Use As Is*.
+When accounting is enabled, closing the issue posts each disposition's stock movement to the general ledger. *Scrap* and *Return to Supplier* write the material off — relieving its inventory cost layers and posting **debit Scrap / Cost of Quality, credit Inventory** — so scrapped and returned value lands on a dedicated cost-of-quality account rather than distorting on-hand inventory. *Use As Is* and *Rework* keep the material as stock, restoring any value an earlier rejection had written off. Once an issue has posted these entries it can no longer be reopened; a correction is booked forward as a new adjustment, never by unwinding the original.
+
<Callout type="note">
There's no dedicated supplier scorecard in Carbon. **Supplier quality is a derived metric**, counted from the issues linked to each supplier. The data comes from the issues themselves, not a separate record.
</Callout>
@@ -29,9 +31,13 @@ An inspection moves through **Pending**, **In Progress**, and one of three outco
Inbound inspection only fires on **purchase-order receipts** of items flagged to require it. Until a lot is dispositioned, its units sit On Hold: received, but not yet stock you can sell or consume.
</Callout>
+### Executing an inspection
+
+Whatever raised it, an inspection is worked on one screen: a features × samples grid laid over the item's ballooned drawing. Each column is a sample (scanned serials and batches label their own column); each row is a feature to measure, recording a value or a pass/fail. Sample and lot status are derived from those readings against tolerance. The same screen serves an inbound lot held off a receipt and an in-house **Inspection** <Term id="job-operation">job operation</Term> — an Inspection operation resolves the part's inspection document and runs this grid on the shop floor.
+
## Also in quality
-The module also covers [**gauges and calibration**](/docs/reference/calibration) (with calibration-due tracking), **controlled documents** (versioned procedures and work instructions, with one active version at a time), **inspection documents** (ballooned FAI drawings and their characteristics), and a **risk register**.
+The module also covers [**gauges and calibration**](/docs/reference/calibration) (with calibration-due tracking), **controlled documents** (versioned procedures and work instructions, with one active version at a time), **inspection documents** (ballooned FAI drawings and their features), and a **risk register**.
## Related
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 9543924f6f..e89b418eb7 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -37,7 +37,9 @@ pnpm --filter @carbon/database typecheck
| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords`, `fetchRecordsInBatches` |
| `./client` | `Kysely`, `KyselyDatabase`, Postgres pool factories (`getPostgresClient`, `getPostgresConnectionPool`) |
| `./event` | `QueueMessage`, `EventSchema`, `createEventSystemSubscription`, `deleteEventSystemSubscription` |
-| `./audit` | `auditConfig`, entity/table lookup helpers, `AuditEntityType` |
+| `./quality` | Inspection execution engine shared by ERP + MES (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection` — optional one-shot `requireOpen`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `getOrCreateJobOperationInspection`, pure `valuateMeasurement`); Passed/Failed/Partial are all hard-terminal and samples linked from `productionQuantity.inspectionSampleId` are locked; every fn takes a `Kysely<KyselyDatabase>` first arg — authorize at the route, see `.claude/rules/inspection-system.md` |
+| `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) |
+| `./audit` | Audit-log functions (`getEntityAuditLog`, `enableAuditLog`, `syncAuditSubscriptions`, …); `auditConfig` + `AuditEntityType` come from the separate `./audit.config` subpath |
| `./ratelimit` | `checkApiKeyRateLimit` (Postgres RPC wrapper) |
## Cross-References
diff --git a/packages/database/package.json b/packages/database/package.json
index c30ea42ac7..08e32a6606 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -19,7 +19,9 @@
".": "./src/index.ts",
"./client": "./src/client.ts",
"./event": "./src/event.ts",
+ "./quality": "./src/quality.ts",
"./ratelimit": "./src/ratelimit.ts",
+ "./sampling": "./src/sampling.ts",
"./audit": "./src/audit.ts",
"./audit.config": "./src/audit.config.ts",
"./audit.types": "./src/audit.types.ts",
diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.ts
new file mode 100644
index 0000000000..3a5d6cf72e
--- /dev/null
+++ b/packages/database/src/quality.ts
@@ -0,0 +1,1348 @@
+/**
+ * Inspection execution engine — the transactional core of the quality
+ * inspection system, shared by the ERP routes (`x+/inspection+/*`) and the MES
+ * routes (`x+/inspection-lot.$id.*`). Moved here from
+ * `apps/erp/app/modules/quality/quality.server.ts` so both apps run one engine.
+ *
+ * Every function takes a Kysely client as its first argument (each app passes
+ * its own `getDatabaseClient()` singleton). Kysely bypasses RLS — the calling
+ * route's `requirePermissions` is the auth gate.
+ */
+import type { Transaction } from "kysely";
+import { sql } from "kysely";
+
+import { getNextSequence } from "../supabase/functions/shared/get-next-sequence.ts";
+import type { Kysely, KyselyDatabase } from "./client.ts";
+import type { SamplingPlanInput, SamplingStandard } from "./sampling.ts";
+import { resolveFeatureSamplingPlan, resolveSamplingPlan } from "./sampling.ts";
+
+type Ok<T> = { data: T; error: null };
+type Err = { data: null; error: { message: string; blockers?: unknown } };
+export type Result<T> = Ok<T> | Err;
+
+export function errResult(message: string, blockers?: unknown): Err {
+ return { data: null, error: { message, ...(blockers ? { blockers } : {}) } };
+}
+
+// Plain input shapes (structurally assignable from the apps' zod-inferred
+// validator types — zod stays app-side, the engine takes data).
+export type InspectionSampleInput = {
+ inspectionId: string;
+ // Optional: update an existing sample in place (the grid's "Overall result"
+ // row re-toggles an anonymous non-serial column). Serial parts upsert by the
+ // tracked entity instead, so they don't need it.
+ sampleId?: string;
+ // Optional: serial parts scan a discrete tracked entity; batch / inventory /
+ // non-inventory parts record pass/fail without one.
+ trackedEntityId?: string;
+ // "Pending" registers a sample without a verdict (identify-only scan when an
+ // inspection document drives per-feature measurements).
+ status: "Pending" | "Passed" | "Failed";
+ notes?: string;
+ companyId: string;
+ inspectedBy: string;
+};
+
+export type InspectionDispositionInput = {
+ id: string;
+ decision: "Accept" | "Reject" | "Partial";
+ notes?: string;
+ companyId: string;
+ dispositionedBy: string;
+ // One-shot mode: refuse to disposition a lot that is already terminal
+ // (Passed/Failed/Partial). The MES disposition route passes this because its
+ // dispositions drive physical postings (scrap/rework/complete) that must not
+ // re-run; ERP receipt lots keep re-disposition (write-off retry semantics).
+ requireOpen?: boolean;
+ // Restrict the disposition to lots of this source. The ERP Accept/Reject/Partial
+ // routes pass "Receipt" because their verdicts carry NO physical production
+ // posting — accepting a Job Operation lot here would hard-terminate it with no
+ // complete/scrap/rework and wedge the operation (whose outcome the MES
+ // disposition route owns). The MES route omits this so it can disposition
+ // Job Operation lots.
+ requireSource?: "Receipt" | "Job Operation";
+};
+
+export type InspectionMeasurementInput = {
+ inspectionId: string;
+ // Absent = create an anonymous sample (non-serial grid columns).
+ sampleId?: string;
+ inspectionFeatureId: string;
+ // Numeric string for Measurement features; empty clears the reading.
+ value?: string;
+ // Attribute (non-numeric) features toggle pass/fail instead of a value.
+ passed?: "true" | "false";
+ notes?: string;
+ companyId: string;
+ userId: string;
+};
+
+// The sampling hierarchy is: feature rule -> document default -> All. This
+// maps an inspectionDocument row's default-rule columns into the engine's
+// plan shape (NUMERIC columns come back from pg as strings — coerce).
+function toSamplingPlanInput(
+ row:
+ | {
+ samplingPlanType: SamplingPlanInput["type"] | null;
+ samplingSampleSize: number | null;
+ samplingPercentage: string | number | null;
+ samplingAql: string | number | null;
+ samplingInspectionLevel: SamplingPlanInput["inspectionLevel"];
+ samplingSeverity: SamplingPlanInput["severity"];
+ }
+ | null
+ | undefined
+): SamplingPlanInput | null {
+ if (!row?.samplingPlanType) return null;
+ return {
+ type: row.samplingPlanType,
+ sampleSize: row.samplingSampleSize,
+ percentage:
+ row.samplingPercentage == null ? null : Number(row.samplingPercentage),
+ aql: row.samplingAql == null ? null : Number(row.samplingAql),
+ inspectionLevel: row.samplingInspectionLevel,
+ severity: row.samplingSeverity
+ };
+}
+
+// Terminal lot statuses. Passed/Failed/Partial are all hard-terminal: once
+// dispositioned, samples and measurements are immutable (Partial is the mixed
+// close — some units passed, some failed, each already routed to its outcome).
+const INSPECTION_CLOSED_STATUSES = ["Passed", "Failed", "Partial"] as const;
+
+function isInspectionClosed(status: string): boolean {
+ return (INSPECTION_CLOSED_STATUSES as readonly string[]).includes(status);
+}
+
+// A sample whose verdict already drove a production posting (MES verdict-driven
+// completion links productionQuantity.inspectionSampleId) is locked — changing
+// it would desync the posted quantity. Deleting the productionQuantity row in
+// the ERP unlocks it (the completion arithmetic self-heals from the links).
+async function assertSampleNotLinked(
+ trx: Transaction<KyselyDatabase>,
+ sampleId: string
+) {
+ const linked = await trx
+ .selectFrom("productionQuantity")
+ .select(["id"])
+ .where("inspectionSampleId", "=", sampleId)
+ .executeTakeFirst();
+ if (linked) {
+ throw new Error(
+ "Sample is locked: its unit was already completed from this verdict"
+ );
+ }
+}
+
+// Mirrors the old in-service helper. Terminal states (Passed/Failed/Partial)
+// are owned by the disposition path, so the per-sample recompute only flips
+// between Pending and In Progress.
+function computeLotStatus(
+ samples: { status: string }[]
+): "Pending" | "In Progress" {
+ const inspected = samples.filter((s) => s.status !== "Pending").length;
+ return inspected > 0 ? "In Progress" : "Pending";
+}
+
+// Entity-level side effects of a sample verdict (serial parts only): flip the
+// tracked entity's status and record the Inspect activity. Shared by the
+// pass/fail sample path and the derived-status measurement path. Only invoked
+// for Receipt-sourced lots — Job Operation inspections act on WIP entities
+// whose lifecycle belongs to the job, so sampling never flips them.
+async function applySampleEntityStatus(
+ trx: Transaction<KyselyDatabase>,
+ args: {
+ trackedEntityId: string;
+ status: "Passed" | "Failed";
+ inspectionId: string;
+ // Receipt-sourced lots pass the receipt id for the activity's Receipt
+ // attribute; other sources pass null.
+ receiptId: string | null;
+ notes: string | null;
+ userId: string;
+ companyId: string;
+ }
+) {
+ const trackedEntityStatus =
+ args.status === "Passed" ? "Available" : "Rejected";
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: trackedEntityStatus })
+ .where("id", "=", args.trackedEntityId)
+ .where("companyId", "=", args.companyId)
+ .execute();
+
+ const activity = await trx
+ .insertInto("trackedActivity")
+ .values({
+ type: "Inspect",
+ sourceDocument: "Inbound Inspection",
+ sourceDocumentId: args.inspectionId,
+ attributes: {
+ Result: args.status,
+ ...(args.receiptId ? { Receipt: args.receiptId } : {}),
+ Inspector: args.userId,
+ ...(args.notes ? { Notes: args.notes } : {})
+ },
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .insertInto("trackedActivityInput")
+ .values({
+ trackedActivityId: activity.id,
+ trackedEntityId: args.trackedEntityId,
+ quantity: 0,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .execute();
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activity.id,
+ trackedEntityId: args.trackedEntityId,
+ quantity: 0,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .execute();
+}
+
+// -------------------------------------------------------------
+// 1. upsertInspectionSample
+// -------------------------------------------------------------
+// Writes that must stay consistent:
+// - inspectionSample (insert or update)
+// - trackedEntity.status (flip to Available or Rejected; Receipt source only)
+// - trackedActivity + trackedActivityInput + trackedActivityOutput
+// - inspection.status (recompute if non-terminal)
+
+export async function upsertInspectionSample(
+ db: Kysely<KyselyDatabase>,
+ sample: InspectionSampleInput
+): Promise<Result<{ id: string }>> {
+ const nowIso = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const inspection = await trx
+ .selectFrom("inspection")
+ .select(["id", "status", "sourceDocument", "sourceDocumentId"])
+ .where("id", "=", sample.inspectionId)
+ .where("companyId", "=", sample.companyId)
+ .executeTakeFirst();
+ if (!inspection) throw new Error("Inspection not found");
+ if (isInspectionClosed(inspection.status)) {
+ throw new Error("Inspection is closed");
+ }
+
+ // Serial parts carry a tracked entity that may only be sampled once, so we
+ // upsert by it. Anonymous (batch / inventory / non-inventory) columns have
+ // no entity: the caller passes the column's sampleId to update it in place
+ // (idempotent re-toggle of the "Overall result" cell), otherwise each call
+ // is a fresh anonymous sample.
+ const trackedEntityId = sample.trackedEntityId || null;
+ let existing: { id: string } | undefined;
+ if (trackedEntityId) {
+ existing = await trx
+ .selectFrom("inspectionSample")
+ .select(["id"])
+ .where("trackedEntityId", "=", trackedEntityId)
+ .where("inspectionId", "=", sample.inspectionId)
+ .where("companyId", "=", sample.companyId)
+ .executeTakeFirst();
+ } else if (sample.sampleId) {
+ existing = await trx
+ .selectFrom("inspectionSample")
+ .select(["id"])
+ .where("id", "=", sample.sampleId)
+ .where("inspectionId", "=", sample.inspectionId)
+ .where("companyId", "=", sample.companyId)
+ .executeTakeFirst();
+ if (!existing) throw new Error("Sample not found");
+ }
+
+ const samplePayload = {
+ inspectionId: sample.inspectionId,
+ trackedEntityId,
+ status: sample.status,
+ notes: sample.notes ?? null,
+ inspectedBy: sample.inspectedBy,
+ inspectedAt: nowIso,
+ companyId: sample.companyId
+ };
+
+ let sampleId: string;
+ if (existing) {
+ await assertSampleNotLinked(trx, existing.id);
+ const updated = await trx
+ .updateTable("inspectionSample")
+ .set({
+ ...samplePayload,
+ updatedBy: sample.inspectedBy,
+ updatedAt: nowIso
+ })
+ .where("id", "=", existing.id)
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ sampleId = updated.id;
+ } else {
+ const inserted = await trx
+ .insertInto("inspectionSample")
+ .values({ ...samplePayload, createdBy: sample.inspectedBy })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ sampleId = inserted.id;
+ }
+
+ // Entity-level side effects only apply when a tracked entity is present
+ // (serial parts) and a verdict was recorded. Identify-only scans
+ // (status "Pending") leave the entity On Hold until measurements derive
+ // a verdict; anonymous samples are handled by the lot's disposition.
+ // Job Operation lots sample WIP entities and never flip their status.
+ if (
+ inspection.sourceDocument === "Receipt" &&
+ trackedEntityId &&
+ sample.status !== "Pending"
+ ) {
+ await applySampleEntityStatus(trx, {
+ trackedEntityId,
+ status: sample.status,
+ inspectionId: sample.inspectionId,
+ receiptId: inspection.sourceDocumentId,
+ notes: sample.notes ?? null,
+ userId: sample.inspectedBy,
+ companyId: sample.companyId
+ });
+ }
+
+ const isTerminal =
+ inspection.status === "Passed" ||
+ inspection.status === "Failed" ||
+ inspection.status === "Partial";
+ if (!isTerminal) {
+ const samples = await trx
+ .selectFrom("inspectionSample")
+ .select(["status"])
+ .where("inspectionId", "=", sample.inspectionId)
+ .execute();
+ const nextStatus = computeLotStatus(samples);
+ if (nextStatus !== inspection.status) {
+ await trx
+ .updateTable("inspection")
+ .set({
+ status: nextStatus,
+ updatedBy: sample.inspectedBy,
+ updatedAt: nowIso
+ })
+ .where("id", "=", sample.inspectionId)
+ .execute();
+ }
+ }
+
+ return { id: sampleId };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to save sample"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// 2. dispositionInspection
+// -------------------------------------------------------------
+// Writes:
+// - trackedEntity.status (bulk flip for Accept/Reject; nothing for Partial)
+// - inspection (status, dispositionedBy/At, notes)
+// - inspectionHistory (1 row for future plan auto-switching)
+
+export async function dispositionInspection(
+ db: Kysely<KyselyDatabase>,
+ args: InspectionDispositionInput
+): Promise<
+ Result<{
+ id: string;
+ status: string;
+ // Non-tracked Inventory reject: the inventory write-off the route must post
+ // through post-nonconformance (itemLedger + cost relief + GL). Null when the
+ // decision/tracking type needs no compensating ledger movement.
+ writeOff: {
+ itemId: string;
+ quantity: number;
+ locationId: string | null;
+ } | null;
+ }>
+> {
+ const nowIso = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const inspection = await trx
+ .selectFrom("inspection")
+ .select([
+ "id",
+ "sourceDocument",
+ "sourceDocumentId",
+ "sourceDocumentLineId",
+ "itemId",
+ "status",
+ "supplierId",
+ "samplingStandard",
+ "severity",
+ "inspectionLevel",
+ "aql",
+ "lotSize",
+ "sampleSize"
+ ])
+ .where("id", "=", args.id)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!inspection) throw new Error("Inspection not found");
+ if (
+ args.requireSource &&
+ inspection.sourceDocument !== args.requireSource
+ ) {
+ throw new Error(
+ `This disposition is only available for ${args.requireSource} inspections`
+ );
+ }
+ if (args.requireOpen && isInspectionClosed(inspection.status)) {
+ throw new Error("Inspection is already dispositioned");
+ }
+ const isReceiptSource = inspection.sourceDocument === "Receipt";
+
+ const item = await trx
+ .selectFrom("item")
+ .select(["itemTrackingType"])
+ .where("id", "=", inspection.itemId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+
+ // Receipt-sourced lots: the received tracked entities and the receiving
+ // location hang off the receipt line. Other sources have no lot entities
+ // to flip (e.g. Job Operation inspections act on WIP, not received stock).
+ const receiptLine =
+ isReceiptSource && inspection.sourceDocumentLineId
+ ? await trx
+ .selectFrom("receiptLine")
+ .select(["locationId"])
+ .where("id", "=", inspection.sourceDocumentLineId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst()
+ : undefined;
+
+ const lotEntities =
+ isReceiptSource && inspection.sourceDocumentLineId
+ ? await trx
+ .selectFrom("trackedEntity")
+ .select(["id"])
+ .where(
+ sql<string>`attributes ->> 'Receipt Line'`,
+ "=",
+ inspection.sourceDocumentLineId
+ )
+ .where("companyId", "=", args.companyId)
+ .execute()
+ : [];
+
+ const existingSamples = await trx
+ .selectFrom("inspectionSample")
+ .select(["trackedEntityId", "status"])
+ .where("inspectionId", "=", args.id)
+ .execute();
+
+ const failedEntityIds = new Set(
+ existingSamples
+ .filter((s) => s.status === "Failed")
+ .map((s) => s.trackedEntityId)
+ .filter(Boolean)
+ );
+ const allLotIds = lotEntities.map((e) => e.id);
+ const failures = existingSamples.filter(
+ (s) => s.status === "Failed"
+ ).length;
+
+ // Per-feature gating (document-driven lots). Each feature must meet its
+ // own resolved sample size and acceptance number before Accept; Reject
+ // requires a feature past its rejection number or a failed sample. Lots
+ // without features keep the caller-side lot-level gating untouched.
+ const lotFeatures = await trx
+ .selectFrom("inspectionSamplingPlan")
+ .select([
+ "inspectionFeatureId",
+ "sampleSize",
+ "acceptanceNumber",
+ "rejectionNumber"
+ ])
+ .where("inspectionId", "=", args.id)
+ .execute();
+
+ if (lotFeatures.length > 0) {
+ const measurements = await trx
+ .selectFrom("inspectionMeasurement")
+ .select(["inspectionFeatureId", "status"])
+ .where("inspectionId", "=", args.id)
+ .execute();
+ const countsByFeature = new Map<
+ string,
+ { recorded: number; failed: number }
+ >();
+ for (const m of measurements) {
+ const counts = countsByFeature.get(m.inspectionFeatureId) ?? {
+ recorded: 0,
+ failed: 0
+ };
+ if (m.status !== "Pending") counts.recorded += 1;
+ if (m.status === "Failed") counts.failed += 1;
+ countsByFeature.set(m.inspectionFeatureId, counts);
+ }
+
+ if (args.decision === "Accept") {
+ const blocking = lotFeatures.filter((f) => {
+ const counts = countsByFeature.get(f.inspectionFeatureId) ?? {
+ recorded: 0,
+ failed: 0
+ };
+ return (
+ counts.recorded < f.sampleSize ||
+ counts.failed > f.acceptanceNumber
+ );
+ });
+ if (blocking.length > 0) {
+ throw new Error(
+ "Cannot accept: sampling incomplete or acceptance number exceeded for one or more features"
+ );
+ }
+ }
+
+ if (args.decision === "Reject") {
+ const rejectable =
+ lotFeatures.some((f) => {
+ const counts = countsByFeature.get(f.inspectionFeatureId);
+ return counts != null && counts.failed >= f.rejectionNumber;
+ }) || existingSamples.some((s) => s.status === "Failed");
+ if (!rejectable) {
+ throw new Error(
+ "Cannot reject: no feature has reached its rejection number and no sample has failed"
+ );
+ }
+ }
+ }
+
+ // Reject = entire lot non-conforming (ISO 9001:2015 §8.7). Accept
+ // releases every lot entity that didn't fail a sample — un-sampled and
+ // partially-inspected (Pending) units included; failed units stay
+ // Rejected. Partial leaves un-sampled entities On Hold.
+ let lotStatus: "Passed" | "Failed" | "Partial";
+ let idsToFlip: string[] = [];
+ let flipStatus: "Available" | "Rejected" | null = null;
+ switch (args.decision) {
+ case "Accept":
+ lotStatus = "Passed";
+ idsToFlip = allLotIds.filter((id) => !failedEntityIds.has(id));
+ flipStatus = "Available";
+ break;
+ case "Reject":
+ lotStatus = "Failed";
+ idsToFlip = allLotIds;
+ flipStatus = "Rejected";
+ break;
+ case "Partial":
+ lotStatus = "Partial";
+ idsToFlip = [];
+ flipStatus = null;
+ break;
+ }
+
+ if (flipStatus && idsToFlip.length > 0) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: flipStatus })
+ .where("id", "in", idsToFlip)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ }
+
+ // Non-tracked (Inventory) items have no tracked entities to flip, so the
+ // received quantity sits in itemLedger with no per-row status to exclude
+ // it from on-hand. Rejecting the lot posts a compensating write-off —
+ // itemLedger Negative Adjmt. + cost relief + GL — through the
+ // post-nonconformance edge function, which the route invokes AFTER this
+ // transaction commits (cost/GL logic is Deno-only). The `inspection.status
+ // !== "Failed"` guard is intentionally dropped: post-nonconformance is
+ // idempotent per (documentType, documentId), so a re-reject / retry is
+ // safe. Tracked items are handled by the status flip above; Non-Inventory
+ // never posted a receipt ledger entry, so neither needs a write-off.
+ const writeOff =
+ args.decision === "Reject" &&
+ isReceiptSource &&
+ item?.itemTrackingType === "Inventory" &&
+ inspection.lotSize > 0
+ ? {
+ itemId: inspection.itemId,
+ quantity: -inspection.lotSize,
+ locationId: receiptLine?.locationId ?? null
+ }
+ : null;
+
+ const updated = await trx
+ .updateTable("inspection")
+ .set({
+ status: lotStatus,
+ notes: args.notes ?? null,
+ dispositionedBy: args.dispositionedBy,
+ dispositionedAt: nowIso,
+ updatedBy: args.dispositionedBy,
+ updatedAt: nowIso
+ })
+ .where("id", "=", args.id)
+ .where("companyId", "=", args.companyId)
+ // One-shot under concurrency: a second disposition blocks on the row
+ // lock, re-evaluates this predicate against the committed terminal
+ // status, matches zero rows, and throws below — the early read check
+ // alone can't see an uncommitted concurrent disposition.
+ .$if(args.requireOpen === true, (qb) =>
+ qb.where("status", "not in", [...INSPECTION_CLOSED_STATUSES])
+ )
+ .returning(["id", "status"])
+ .executeTakeFirst();
+ if (!updated) {
+ throw new Error("Inspection is already dispositioned");
+ }
+
+ await trx
+ .insertInto("inspectionHistory")
+ .values({
+ inspectionId: args.id,
+ itemId: inspection.itemId,
+ supplierId: inspection.supplierId ?? null,
+ samplingStandard: inspection.samplingStandard,
+ severity: inspection.severity ?? "Normal",
+ inspectionLevel: inspection.inspectionLevel ?? null,
+ aql: inspection.aql ?? null,
+ lotSize: inspection.lotSize,
+ sampleSize: inspection.sampleSize,
+ defectsFound: failures,
+ outcome:
+ args.decision === "Accept"
+ ? "Accepted"
+ : args.decision === "Reject"
+ ? "Rejected"
+ : "Partial",
+ companyId: args.companyId,
+ createdBy: args.dispositionedBy
+ })
+ .execute();
+
+ return { id: updated.id, status: updated.status, writeOff };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to disposition inspection"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// 3. Measurements (document-driven lots)
+// -------------------------------------------------------------
+
+function parseSpecNumber(value: string | null | undefined): number | null {
+ if (value == null) return null;
+ const trimmed = value.trim();
+ if (trimmed === "") return null;
+ const parsed = Number(trimmed.replace(/^\+/, ""));
+ return Number.isNaN(parsed) ? null : parsed;
+}
+
+// Pure valuation of one reading against the live feature spec. Measurement
+// features with a parseable nominal are judged numerically inside
+// [nominal - |tol-|, nominal + |tol+|]; everything else (attribute features,
+// GD&T strings that don't parse) is a pass/fail toggle.
+export function valuateMeasurement(
+ feature: {
+ type: string;
+ nominalValue: string | null;
+ tolerancePlus: string | null;
+ toleranceMinus: string | null;
+ },
+ value: number | null,
+ passed?: boolean | null
+): "Pending" | "Passed" | "Failed" {
+ const nominal =
+ feature.type === "Measurement"
+ ? parseSpecNumber(feature.nominalValue)
+ : null;
+
+ if (feature.type === "Measurement" && nominal !== null) {
+ if (value == null) return "Pending";
+ const tolPlus = Math.abs(parseSpecNumber(feature.tolerancePlus) ?? 0);
+ const tolMinus = Math.abs(parseSpecNumber(feature.toleranceMinus) ?? 0);
+ return value >= nominal - tolMinus && value <= nominal + tolPlus
+ ? "Passed"
+ : "Failed";
+ }
+
+ if (passed == null) return "Pending";
+ return passed ? "Passed" : "Failed";
+}
+
+// Records one cell of the features x samples grid. Valuates the reading,
+// upserts the measurement, derives the sample's status from its required
+// measurements (strict: no override), applies serial-entity side effects on
+// status transitions (Receipt source only), and recomputes the non-terminal
+// lot status.
+export async function upsertInspectionMeasurement(
+ db: Kysely<KyselyDatabase>,
+ args: InspectionMeasurementInput
+): Promise<
+ Result<{
+ sampleId: string;
+ measurementId: string;
+ measurementStatus: string;
+ sampleStatus: string;
+ }>
+> {
+ const nowIso = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const inspection = await trx
+ .selectFrom("inspection")
+ .select(["id", "status", "sourceDocument", "sourceDocumentId"])
+ .where("id", "=", args.inspectionId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!inspection) throw new Error("Inspection not found");
+ if (isInspectionClosed(inspection.status)) {
+ throw new Error("Inspection is closed");
+ }
+
+ const feature = await trx
+ .selectFrom("inspectionFeature")
+ .select([
+ "id",
+ "type",
+ "nominalValue",
+ "tolerancePlus",
+ "toleranceMinus"
+ ])
+ .where("id", "=", args.inspectionFeatureId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!feature) throw new Error("Inspection feature not found");
+
+ // Resolve or create the sample (anonymous columns are created on the
+ // first measurement recorded against them).
+ let sample: {
+ id: string;
+ trackedEntityId: string | null;
+ status: string;
+ };
+ if (args.sampleId) {
+ const existing = await trx
+ .selectFrom("inspectionSample")
+ .select(["id", "trackedEntityId", "status", "inspectionId"])
+ .where("id", "=", args.sampleId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!existing || existing.inspectionId !== args.inspectionId) {
+ throw new Error("Sample not found");
+ }
+ await assertSampleNotLinked(trx, existing.id);
+ sample = existing;
+ } else {
+ const inserted = await trx
+ .insertInto("inspectionSample")
+ .values({
+ inspectionId: args.inspectionId,
+ trackedEntityId: null,
+ status: "Pending",
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .returning(["id", "trackedEntityId", "status"])
+ .executeTakeFirstOrThrow();
+ sample = inserted;
+ }
+
+ const numericValue =
+ args.value != null && args.value !== "" ? Number(args.value) : null;
+ if (numericValue != null && Number.isNaN(numericValue)) {
+ throw new Error("Value must be a number");
+ }
+ const passed = args.passed != null ? args.passed === "true" : null;
+
+ const measurementStatus = valuateMeasurement(
+ feature,
+ numericValue,
+ passed
+ );
+
+ const existingMeasurement = await trx
+ .selectFrom("inspectionMeasurement")
+ .select(["id"])
+ .where("inspectionSampleId", "=", sample.id)
+ .where("inspectionFeatureId", "=", feature.id)
+ .executeTakeFirst();
+
+ const measurementPayload = {
+ value: numericValue,
+ status: measurementStatus,
+ notes: args.notes ?? null,
+ inspectedBy: measurementStatus !== "Pending" ? args.userId : null,
+ inspectedAt: measurementStatus !== "Pending" ? nowIso : null
+ };
+
+ let measurementId: string;
+ if (existingMeasurement) {
+ const updated = await trx
+ .updateTable("inspectionMeasurement")
+ .set({
+ ...measurementPayload,
+ updatedBy: args.userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", existingMeasurement.id)
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ measurementId = updated.id;
+ } else {
+ const inserted = await trx
+ .insertInto("inspectionMeasurement")
+ .values({
+ ...measurementPayload,
+ inspectionId: args.inspectionId,
+ inspectionSampleId: sample.id,
+ inspectionFeatureId: feature.id,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ measurementId = inserted.id;
+ }
+
+ // Derive the sample's status. Sampling is count-based, not positional —
+ // a feature's n is the minimum number of readings across ANY samples
+ // (per-feature gating at disposition enforces the counts), so a sample's
+ // own verdict is: Failed the moment any of its readings fails, Passed
+ // once every plan feature has a passing reading on it (a fully-inspected
+ // unit), otherwise Pending (partially inspected).
+ const lotFeatures = await trx
+ .selectFrom("inspectionSamplingPlan")
+ .select(["inspectionFeatureId", "sampleSize"])
+ .where("inspectionId", "=", args.inspectionId)
+ .execute();
+ const sampleMeasurements = await trx
+ .selectFrom("inspectionMeasurement")
+ .select(["inspectionFeatureId", "status"])
+ .where("inspectionSampleId", "=", sample.id)
+ .execute();
+
+ const anyFailed = sampleMeasurements.some((m) => m.status === "Failed");
+ const allFeaturesPassed =
+ lotFeatures.length > 0 &&
+ lotFeatures.every(
+ (f) =>
+ sampleMeasurements.find(
+ (m) => m.inspectionFeatureId === f.inspectionFeatureId
+ )?.status === "Passed"
+ );
+ const derivedStatus: "Pending" | "Passed" | "Failed" = anyFailed
+ ? "Failed"
+ : allFeaturesPassed
+ ? "Passed"
+ : "Pending";
+
+ if (derivedStatus !== sample.status) {
+ await trx
+ .updateTable("inspectionSample")
+ .set({
+ status: derivedStatus,
+ inspectedBy: derivedStatus !== "Pending" ? args.userId : null,
+ inspectedAt: derivedStatus !== "Pending" ? nowIso : null,
+ updatedBy: args.userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", sample.id)
+ .execute();
+
+ // WIP entities on Job Operation lots keep their job-owned status; only
+ // Receipt-sourced entities ride the sample verdict.
+ if (inspection.sourceDocument === "Receipt" && sample.trackedEntityId) {
+ if (derivedStatus === "Pending") {
+ // Revert (e.g. corrected typo): back On Hold, no activity row.
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: "On Hold" })
+ .where("id", "=", sample.trackedEntityId)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ } else {
+ await applySampleEntityStatus(trx, {
+ trackedEntityId: sample.trackedEntityId,
+ status: derivedStatus,
+ inspectionId: args.inspectionId,
+ receiptId: inspection.sourceDocumentId,
+ notes: args.notes ?? null,
+ userId: args.userId,
+ companyId: args.companyId
+ });
+ }
+ }
+ }
+
+ // Passed/Failed already threw above, so Partial is the only terminal
+ // status left to guard against.
+ const isTerminal = inspection.status === "Partial";
+ if (!isTerminal) {
+ const samples = await trx
+ .selectFrom("inspectionSample")
+ .select(["status"])
+ .where("inspectionId", "=", args.inspectionId)
+ .execute();
+ const nextStatus = computeLotStatus(samples);
+ if (nextStatus !== inspection.status) {
+ await trx
+ .updateTable("inspection")
+ .set({
+ status: nextStatus,
+ updatedBy: args.userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", args.inspectionId)
+ .execute();
+ }
+ }
+
+ return {
+ sampleId: sample.id,
+ measurementId,
+ measurementStatus,
+ sampleStatus: derivedStatus
+ };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to save measurement"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// 4. reconcileInspectionSamplingPlans
+// -------------------------------------------------------------
+// The lot references its inspection document live, so features added to the
+// document after lot creation need per-lot plan rows resolved lazily. Rows
+// whose live feature was deleted are left in place (the grid ignores them).
+
+export async function reconcileInspectionSamplingPlans(
+ db: Kysely<KyselyDatabase>,
+ inspectionId: string,
+ companyId: string
+): Promise<Result<{ added: number }>> {
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const inspection = await trx
+ .selectFrom("inspection")
+ .select([
+ "id",
+ "inspectionDocumentId",
+ "lotSize",
+ "samplingStandard",
+ "createdBy"
+ ])
+ .where("id", "=", inspectionId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!inspection) throw new Error("Inspection not found");
+ if (!inspection.inspectionDocumentId) return { added: 0 };
+
+ const documentFeatures = await trx
+ .selectFrom("inspectionFeature")
+ .select([
+ "id",
+ "samplingPlanType",
+ "samplingSampleSize",
+ "samplingPercentage",
+ "samplingAql",
+ "samplingInspectionLevel",
+ "samplingSeverity"
+ ])
+ .where("inspectionDocumentId", "=", inspection.inspectionDocumentId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ const existingRows = await trx
+ .selectFrom("inspectionSamplingPlan")
+ .select(["inspectionFeatureId"])
+ .where("inspectionId", "=", inspectionId)
+ .execute();
+ const existingIds = new Set(
+ existingRows.map((r) => r.inspectionFeatureId)
+ );
+ const missing = documentFeatures.filter((f) => !existingIds.has(f.id));
+ if (missing.length === 0) return { added: 0 };
+
+ // The document's own default rule is the fallback for features without
+ // a rule (feature rule -> document default -> All).
+ const documentDefault = await trx
+ .selectFrom("inspectionDocument")
+ .select([
+ "samplingPlanType",
+ "samplingSampleSize",
+ "samplingPercentage",
+ "samplingAql",
+ "samplingInspectionLevel",
+ "samplingSeverity"
+ ])
+ .where("id", "=", inspection.inspectionDocumentId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ const defaultPlan = toSamplingPlanInput(documentDefault);
+
+ const inserts = missing.map((feature) => {
+ const resolved = resolveFeatureSamplingPlan(
+ feature,
+ defaultPlan,
+ Number(inspection.lotSize),
+ inspection.samplingStandard as SamplingStandard
+ );
+ return {
+ inspectionId,
+ inspectionFeatureId: feature.id,
+ sampleSize: resolved.sampleSize,
+ acceptanceNumber: resolved.acceptance,
+ rejectionNumber: resolved.rejection,
+ codeLetter: resolved.codeLetter,
+ companyId,
+ // Never NULL into a NOT NULL audit column: fall back to the lot's
+ // creator (the creating flow's userId).
+ createdBy: inspection.createdBy
+ };
+ });
+
+ await trx.insertInto("inspectionSamplingPlan").values(inserts).execute();
+ return { added: inserts.length };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to reconcile features"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// 5. changeInspectionDocument
+// -------------------------------------------------------------
+// Swaps (or clears) the document assigned to an open lot. Only allowed while
+// the lot is non-terminal and no measurements have been recorded — recorded
+// readings belong to the old document's features. The per-lot plan rows are
+// wiped; the next loader pass reconciles rows for the new document.
+
+export async function changeInspectionDocument(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ inspectionId: string;
+ inspectionDocumentId: string | null;
+ companyId: string;
+ userId: string;
+ }
+): Promise<Result<{ id: string }>> {
+ const nowIso = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const inspection = await trx
+ .selectFrom("inspection")
+ .select(["id", "status"])
+ .where("id", "=", args.inspectionId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!inspection) throw new Error("Inspection not found");
+ if (isInspectionClosed(inspection.status)) {
+ throw new Error("Inspection is closed");
+ }
+
+ const measurement = await trx
+ .selectFrom("inspectionMeasurement")
+ .select(["id"])
+ .where("inspectionId", "=", args.inspectionId)
+ .limit(1)
+ .executeTakeFirst();
+ if (measurement) {
+ throw new Error(
+ "Cannot change document after measurements are recorded"
+ );
+ }
+
+ await trx
+ .updateTable("inspection")
+ .set({
+ inspectionDocumentId: args.inspectionDocumentId,
+ updatedBy: args.userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", args.inspectionId)
+ .execute();
+
+ await trx
+ .deleteFrom("inspectionSamplingPlan")
+ .where("inspectionId", "=", args.inspectionId)
+ .execute();
+
+ return { id: inspection.id };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to change document"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// 6. getOrCreateJobOperationInspection
+// -------------------------------------------------------------
+// Lazy find-or-create of the inspection lot for a jobOperation with
+// operationType = 'Inspection', called by the MES inspection loader on first
+// open. Mirrors the post-receipt lot creation: snapshots the resolved sampling
+// plan (item plan -> "All"), resolves per-feature plans from the operation's
+// explicit inspectionDocumentId FK, and allocates the human-readable id from
+// the "inspection" sequence. Idempotent against the partial unique index on
+// (sourceDocument, sourceDocumentLineId): a concurrent creation loses with a
+// 23505, which we resolve by re-selecting the winner's lot.
+
+export async function getOrCreateJobOperationInspection(
+ db: Kysely<KyselyDatabase>,
+ args: { jobOperationId: string; companyId: string; userId: string }
+): Promise<Result<{ id: string; created: boolean }>> {
+ const selectExisting = () =>
+ db
+ .selectFrom("inspection")
+ .select(["id"])
+ .where("sourceDocument", "=", "Job Operation")
+ .where("sourceDocumentLineId", "=", args.jobOperationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const existing = await trx
+ .selectFrom("inspection")
+ .select(["id"])
+ .where("sourceDocument", "=", "Job Operation")
+ .where("sourceDocumentLineId", "=", args.jobOperationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (existing) return { id: existing.id, created: false };
+
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .select([
+ "id",
+ "jobId",
+ "jobMakeMethodId",
+ "operationQuantity",
+ "inspectionDocumentId"
+ ])
+ .where("id", "=", args.jobOperationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!operation) throw new Error("Job operation not found");
+
+ const job = await trx
+ .selectFrom("job")
+ .select(["id", "jobId", "itemId", "quantity"])
+ .where("id", "=", operation.jobId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!job) throw new Error("Job not found");
+
+ // The make method's item is the assembly actually produced at this level
+ // of the job (subassembly operations inspect the subassembly, not the
+ // top-level part).
+ const makeMethod = operation.jobMakeMethodId
+ ? await trx
+ .selectFrom("jobMakeMethod")
+ .select(["itemId"])
+ .where("id", "=", operation.jobMakeMethodId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst()
+ : undefined;
+ const itemId = makeMethod?.itemId ?? job.itemId;
+ if (!itemId) throw new Error("Job has no item to inspect");
+
+ const item = await trx
+ .selectFrom("item")
+ .select(["readableIdWithRevision"])
+ .where("id", "=", itemId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+
+ const settings = await trx
+ .selectFrom("companySettings")
+ .select(["samplingStandard"])
+ .where("id", "=", args.companyId)
+ .executeTakeFirst();
+ const samplingStandard = (settings?.samplingStandard ??
+ "ANSI_Z1_4") as SamplingStandard;
+
+ // The document's default sampling rule is both the lot-level plan base
+ // and the fallback for features without their own rule. No document (or
+ // no default set) means 100% inspection.
+ const documentDefault = operation.inspectionDocumentId
+ ? await trx
+ .selectFrom("inspectionDocument")
+ .select([
+ "samplingPlanType",
+ "samplingSampleSize",
+ "samplingPercentage",
+ "samplingAql",
+ "samplingInspectionLevel",
+ "samplingSeverity"
+ ])
+ .where("id", "=", operation.inspectionDocumentId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst()
+ : undefined;
+ const defaultPlan = toSamplingPlanInput(documentDefault);
+
+ const plan: SamplingPlanInput = defaultPlan ?? {
+ type: "All",
+ sampleSize: null,
+ percentage: null,
+ aql: null,
+ inspectionLevel: "II",
+ severity: "Normal"
+ };
+
+ const lotSize = Math.max(
+ 1,
+ Math.floor(Number(operation.operationQuantity ?? job.quantity ?? 1))
+ );
+
+ const snapshot = resolveSamplingPlan(plan, lotSize, samplingStandard);
+
+ const documentFeatures = operation.inspectionDocumentId
+ ? await trx
+ .selectFrom("inspectionFeature")
+ .select([
+ "id",
+ "samplingPlanType",
+ "samplingSampleSize",
+ "samplingPercentage",
+ "samplingAql",
+ "samplingInspectionLevel",
+ "samplingSeverity"
+ ])
+ .where("inspectionDocumentId", "=", operation.inspectionDocumentId)
+ .where("companyId", "=", args.companyId)
+ .execute()
+ : [];
+ const featurePlans = documentFeatures.map((feature) => ({
+ inspectionFeatureId: feature.id,
+ resolved: resolveFeatureSamplingPlan(
+ feature,
+ defaultPlan,
+ lotSize,
+ samplingStandard
+ )
+ }));
+
+ const readableInspectionId = await getNextSequence(
+ trx,
+ "inspection",
+ args.companyId
+ );
+
+ const inserted = await trx
+ .insertInto("inspection")
+ .values({
+ inspectionId: readableInspectionId,
+ sourceDocument: "Job Operation",
+ sourceDocumentId: operation.jobId,
+ sourceDocumentLineId: operation.id,
+ sourceDocumentReadableId: job.jobId,
+ itemId,
+ itemReadableId: item?.readableIdWithRevision ?? null,
+ supplierId: null,
+ lotSize,
+ samplingStandard,
+ samplingPlanType: plan.type,
+ // With a document attached, the lot-level sample size is the max
+ // across the per-feature plans (SAP-style); Ac/Re remain the
+ // item-plan fallback numbers used by the no-document flow.
+ sampleSize:
+ featurePlans.length > 0
+ ? Math.max(...featurePlans.map((p) => p.resolved.sampleSize))
+ : snapshot.sampleSize,
+ acceptanceNumber: snapshot.acceptance,
+ rejectionNumber: snapshot.rejection,
+ aql: plan.aql ?? null,
+ inspectionLevel: plan.inspectionLevel ?? null,
+ severity: plan.severity ?? null,
+ codeLetter: snapshot.codeLetter,
+ // The operation FK is the explicit plan link ("the FK is the truth").
+ // Unlike post-receipt's assignment slots, a drawing-only document
+ // (zero features yet) still renders its PDF, and features added to it
+ // later reconcile in lazily.
+ inspectionDocumentId: operation.inspectionDocumentId ?? null,
+ status: "Pending",
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (featurePlans.length > 0) {
+ await trx
+ .insertInto("inspectionSamplingPlan")
+ .values(
+ featurePlans.map((p) => ({
+ inspectionId: inserted.id,
+ inspectionFeatureId: p.inspectionFeatureId,
+ sampleSize: p.resolved.sampleSize,
+ acceptanceNumber: p.resolved.acceptance,
+ rejectionNumber: p.resolved.rejection,
+ codeLetter: p.resolved.codeLetter,
+ companyId: args.companyId,
+ createdBy: args.userId
+ }))
+ )
+ .execute();
+ }
+
+ return { id: inserted.id, created: true };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ // Concurrent first-open race: the partial unique index on
+ // (sourceDocument, sourceDocumentLineId) rejects the second insert with a
+ // unique violation. The winner's lot is the lot.
+ if ((err as { code?: string })?.code === "23505") {
+ const existing = await selectExisting();
+ if (existing)
+ return { data: { id: existing.id, created: false }, error: null };
+ }
+ return errResult(
+ err instanceof Error ? err.message : "Failed to create inspection"
+ );
+ }
+}
diff --git a/packages/database/src/sampling.ts b/packages/database/src/sampling.ts
new file mode 100644
index 0000000000..f01b236691
--- /dev/null
+++ b/packages/database/src/sampling.ts
@@ -0,0 +1,5 @@
+// Node-side re-export of the edge-runtime sampling engine (same pattern as
+// client.ts). The engine is pure TS (Z1.4 / ISO 2859-1 tables + resolvers), so
+// ERP, MES, and edge functions can all share the single copy that post-receipt
+// already uses.
+export * from "../supabase/functions/shared/sampling-engine.ts";
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 3044c99a22..09cb62b1e6 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -219,6 +219,114 @@ export default {
tags: ["procedures"]
}
},
+ "/jobOperationToolStep": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/jobOperationToolStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["jobOperationToolStep"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobOperationToolStep"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["jobOperationToolStep"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["jobOperationToolStep"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationToolStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/body.jobOperationToolStep"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["jobOperationToolStep"]
+ }
+ },
"/purchasingRfqLines": {
get: {
parameters: [
@@ -1293,6 +1401,114 @@ export default {
tags: ["documentLabels"]
}
},
+ "/jobMaterialStep": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/jobMaterialStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["jobMaterialStep"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobMaterialStep"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["jobMaterialStep"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["jobMaterialStep"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialStep.jobOperationStepId"
+ },
+ {
+ $ref: "#/parameters/body.jobMaterialStep"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["jobMaterialStep"]
+ }
+ },
"/consumables": {
get: {
parameters: [
@@ -1869,29 +2085,47 @@ export default {
tags: ["employeeSummary"]
}
},
- "/changeOrderType": {
+ "/assemblyInstructionStepSlide": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.changeOrderType.id"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.name"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.companyId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.createdAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.modelUploadId"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.createdBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.updatedAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.updatedBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedAt"
},
{
$ref: "#/parameters/select"
@@ -1920,7 +2154,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/changeOrderType"
+ $ref: "#/definitions/assemblyInstructionStepSlide"
},
type: "array"
}
@@ -1929,12 +2163,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["changeOrderType"]
+ tags: ["assemblyInstructionStepSlide"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.changeOrderType"
+ $ref: "#/parameters/body.assemblyInstructionStepSlide"
},
{
$ref: "#/parameters/select"
@@ -1948,30 +2182,48 @@ export default {
description: "Created"
}
},
- tags: ["changeOrderType"]
+ tags: ["assemblyInstructionStepSlide"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.changeOrderType.id"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.name"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.companyId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.createdAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.modelUploadId"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.createdBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.updatedAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.changeOrderType.updatedBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedAt"
},
{
$ref: "#/parameters/preferReturn"
@@ -1982,7 +2234,178 @@ export default {
description: "No Content"
}
},
- tags: ["changeOrderType"]
+ tags: ["assemblyInstructionStepSlide"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.stepId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.imagePath"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.caption"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.sortOrder"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepSlide.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.assemblyInstructionStepSlide"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["assemblyInstructionStepSlide"]
+ }
+ },
+ "/changeOrderType": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.updatedBy"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/changeOrderType"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["changeOrderType"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.changeOrderType"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["changeOrderType"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.changeOrderType.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["changeOrderType"]
},
patch: {
parameters: [
@@ -2763,188 +3186,422 @@ export default {
tags: ["quoteShipment"]
}
},
- "/customerLocation": {
+ "/inspectionHistory": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.customerLocation.id"
+ $ref: "#/parameters/rowFilter.inspectionHistory.id"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.customerId"
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionId"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.addressId"
+ $ref: "#/parameters/rowFilter.inspectionHistory.itemId"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.customFields"
+ $ref: "#/parameters/rowFilter.inspectionHistory.supplierId"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.name"
+ $ref: "#/parameters/rowFilter.inspectionHistory.samplingStandard"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.tags"
+ $ref: "#/parameters/rowFilter.inspectionHistory.severity"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.companyId"
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionLevel"
},
{
- $ref: "#/parameters/select"
+ $ref: "#/parameters/rowFilter.inspectionHistory.aql"
},
{
- $ref: "#/parameters/order"
+ $ref: "#/parameters/rowFilter.inspectionHistory.lotSize"
},
{
- $ref: "#/parameters/range"
+ $ref: "#/parameters/rowFilter.inspectionHistory.sampleSize"
},
{
- $ref: "#/parameters/rangeUnit"
+ $ref: "#/parameters/rowFilter.inspectionHistory.defectsFound"
},
{
- $ref: "#/parameters/offset"
+ $ref: "#/parameters/rowFilter.inspectionHistory.outcome"
},
{
- $ref: "#/parameters/limit"
+ $ref: "#/parameters/rowFilter.inspectionHistory.companyId"
},
{
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/customerLocation"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["customerLocation"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.customerLocation"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["customerLocation"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.customerLocation.id"
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdAt"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.customerId"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.addressId"
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdBy"
},
{
- $ref: "#/parameters/rowFilter.customerLocation.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.name"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.tags"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.companyId"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["customerLocation"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.customerLocation.id"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.customerId"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.addressId"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.name"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.tags"
- },
- {
- $ref: "#/parameters/rowFilter.customerLocation.companyId"
- },
- {
- $ref: "#/parameters/body.customerLocation"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["customerLocation"]
- }
- },
- "/oauthToken": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.oauthToken.id"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.accessToken"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.refreshToken"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.clientId"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.userId"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.expiresAt"
- },
- {
- $ref: "#/parameters/rowFilter.oauthToken.scope"
+ $ref: "#/parameters/rowFilter.inspectionHistory.updatedBy"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspectionHistory"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspectionHistory"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspectionHistory"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspectionHistory"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.supplierId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.samplingStandard"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.severity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.aql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.lotSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.defectsFound"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.outcome"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionHistory"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.supplierId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.samplingStandard"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.severity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.inspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.aql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.lotSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.defectsFound"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.outcome"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionHistory.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.inspectionHistory"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionHistory"]
+ }
+ },
+ "/customerLocation": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customerId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.addressId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.companyId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/customerLocation"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["customerLocation"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.customerLocation"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["customerLocation"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customerId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.addressId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.companyId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["customerLocation"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customerId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.addressId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.customerLocation.companyId"
+ },
+ {
+ $ref: "#/parameters/body.customerLocation"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["customerLocation"]
+ }
+ },
+ "/oauthToken": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.accessToken"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.refreshToken"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.clientId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.expiresAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.oauthToken.scope"
},
{
$ref: "#/parameters/select"
@@ -3579,38 +4236,47 @@ export default {
tags: ["qualityActions"]
}
},
- "/nonConformanceSalesOrderLine": {
+ "/jobOperationStepSlide": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.modelUploadId"
},
{
$ref: "#/parameters/select"
@@ -3639,7 +4305,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/nonConformanceSalesOrderLine"
+ $ref: "#/definitions/jobOperationStepSlide"
},
type: "array"
}
@@ -3648,12 +4314,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["nonConformanceSalesOrderLine"]
+ tags: ["jobOperationStepSlide"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.nonConformanceSalesOrderLine"
+ $ref: "#/parameters/body.jobOperationStepSlide"
},
{
$ref: "#/parameters/select"
@@ -3667,39 +4333,48 @@ export default {
description: "Created"
}
},
- tags: ["nonConformanceSalesOrderLine"]
+ tags: ["jobOperationStepSlide"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.modelUploadId"
},
{
$ref: "#/parameters/preferReturn"
@@ -3710,42 +4385,51 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceSalesOrderLine"]
+ tags: ["jobOperationStepSlide"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/body.nonConformanceSalesOrderLine"
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStepSlide.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/body.jobOperationStepSlide"
},
{
$ref: "#/parameters/preferReturn"
@@ -3756,50 +4440,230 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceSalesOrderLine"]
+ tags: ["jobOperationStepSlide"]
}
},
- "/companyAccountsPayableBillingAddress": {
+ "/nonConformanceSalesOrderLine": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.id"
- },
- {
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.name"
- },
- {
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.addressLine1"
- },
- {
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.addressLine2"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.city"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.state"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.postalCode"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.countryCode"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.phone"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.fax"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.email"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.updatedAt"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.updatedBy"
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/nonConformanceSalesOrderLine"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["nonConformanceSalesOrderLine"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.nonConformanceSalesOrderLine"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["nonConformanceSalesOrderLine"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["nonConformanceSalesOrderLine"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.salesOrderReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceSalesOrderLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.nonConformanceSalesOrderLine"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["nonConformanceSalesOrderLine"]
+ }
+ },
+ "/companyAccountsPayableBillingAddress": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.addressLine1"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.addressLine2"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.city"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.state"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.postalCode"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.countryCode"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.phone"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.fax"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.email"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.companyAccountsPayableBillingAddress.updatedBy"
},
{
$ref: "#/parameters/select"
@@ -5691,35 +6555,44 @@ export default {
tags: ["purchaseInvoicePriceChange"]
}
},
- "/assemblyStandardNote": {
+ "/makeMethod": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.id"
+ $ref: "#/parameters/rowFilter.makeMethod.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.makeMethod.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.makeMethod.companyId"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.name"
+ $ref: "#/parameters/rowFilter.makeMethod.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.makeMethod.createdBy"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.content"
+ $ref: "#/parameters/rowFilter.makeMethod.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.severity"
+ $ref: "#/parameters/rowFilter.makeMethod.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.companyId"
+ $ref: "#/parameters/rowFilter.makeMethod.customFields"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdBy"
+ $ref: "#/parameters/rowFilter.makeMethod.tags"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdAt"
+ $ref: "#/parameters/rowFilter.makeMethod.version"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedBy"
+ $ref: "#/parameters/rowFilter.makeMethod.status"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedAt"
+ $ref: "#/parameters/rowFilter.makeMethod.changeOrderId"
},
{
$ref: "#/parameters/select"
@@ -5748,7 +6621,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/assemblyStandardNote"
+ $ref: "#/definitions/makeMethod"
},
type: "array"
}
@@ -5757,12 +6630,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["assemblyStandardNote"]
+ tags: ["makeMethod"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.assemblyStandardNote"
+ $ref: "#/parameters/body.makeMethod"
},
{
$ref: "#/parameters/select"
@@ -5776,79 +6649,45 @@ export default {
description: "Created"
}
},
- tags: ["assemblyStandardNote"]
+ tags: ["makeMethod"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.name"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.content"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.severity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedBy"
+ $ref: "#/parameters/rowFilter.makeMethod.id"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedAt"
+ $ref: "#/parameters/rowFilter.makeMethod.itemId"
},
{
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["assemblyStandardNote"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyStandardNote.id"
+ $ref: "#/parameters/rowFilter.makeMethod.companyId"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.name"
+ $ref: "#/parameters/rowFilter.makeMethod.createdAt"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.content"
+ $ref: "#/parameters/rowFilter.makeMethod.createdBy"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.severity"
+ $ref: "#/parameters/rowFilter.makeMethod.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.companyId"
+ $ref: "#/parameters/rowFilter.makeMethod.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdBy"
+ $ref: "#/parameters/rowFilter.makeMethod.customFields"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.createdAt"
+ $ref: "#/parameters/rowFilter.makeMethod.tags"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedBy"
+ $ref: "#/parameters/rowFilter.makeMethod.version"
},
{
- $ref: "#/parameters/rowFilter.assemblyStandardNote.updatedAt"
+ $ref: "#/parameters/rowFilter.makeMethod.status"
},
{
- $ref: "#/parameters/body.assemblyStandardNote"
+ $ref: "#/parameters/rowFilter.makeMethod.changeOrderId"
},
{
$ref: "#/parameters/preferReturn"
@@ -5859,155 +6698,9 @@ export default {
description: "No Content"
}
},
- tags: ["assemblyStandardNote"]
- }
- },
- "/makeMethod": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.makeMethod.id"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.tags"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.version"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.status"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.changeOrderId"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/makeMethod"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["makeMethod"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.makeMethod"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["makeMethod"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.makeMethod.id"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.tags"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.version"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.status"
- },
- {
- $ref: "#/parameters/rowFilter.makeMethod.changeOrderId"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["makeMethod"]
- },
- patch: {
+ tags: ["makeMethod"]
+ },
+ patch: {
parameters: [
{
$ref: "#/parameters/rowFilter.makeMethod.id"
@@ -7209,204 +7902,6 @@ export default {
tags: ["receipts"]
}
},
- "/itemSamplingPlan": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.type"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.percentage"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.aql"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.inspectionLevel"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.severity"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedBy"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/itemSamplingPlan"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["itemSamplingPlan"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.itemSamplingPlan"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["itemSamplingPlan"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.type"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.percentage"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.aql"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.inspectionLevel"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.severity"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedBy"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["itemSamplingPlan"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.type"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.percentage"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.aql"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.inspectionLevel"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.severity"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.itemSamplingPlan.updatedBy"
- },
- {
- $ref: "#/parameters/body.itemSamplingPlan"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["itemSamplingPlan"]
- }
- },
"/purchaseOrderLocations": {
get: {
parameters: [
@@ -8376,6 +8871,12 @@ export default {
{
$ref: "#/parameters/rowFilter.productionQuantity.scrapReasonId"
},
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionSampleId"
+ },
{
$ref: "#/parameters/select"
},
@@ -8477,6 +8978,12 @@ export default {
{
$ref: "#/parameters/rowFilter.productionQuantity.scrapReasonId"
},
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionSampleId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -8532,6 +9039,12 @@ export default {
{
$ref: "#/parameters/rowFilter.productionQuantity.scrapReasonId"
},
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.inspectionSampleId"
+ },
{
$ref: "#/parameters/body.productionQuantity"
},
@@ -8916,6 +9429,312 @@ export default {
tags: ["auditLogArchive"]
}
},
+ "/methodMaterialStep": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/methodMaterialStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["methodMaterialStep"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.methodMaterialStep"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["methodMaterialStep"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["methodMaterialStep"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodMaterialStep.methodOperationStepId"
+ },
+ {
+ $ref: "#/parameters/body.methodMaterialStep"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["methodMaterialStep"]
+ }
+ },
+ "/inspectionSample": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.trackedEntityId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedBy"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspectionSample"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspectionSample"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspectionSample"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspectionSample"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.trackedEntityId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionSample"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.trackedEntityId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSample.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.inspectionSample"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionSample"]
+ }
+ },
"/nonConformanceActionTask": {
get: {
parameters: [
@@ -8994,7 +9813,232 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/nonConformanceActionTask"
+ $ref: "#/definitions/nonConformanceActionTask"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["nonConformanceActionTask"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.nonConformanceActionTask"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["nonConformanceActionTask"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.dueDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.completedDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.assignee"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.sortOrder"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.actionTypeId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["nonConformanceActionTask"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.dueDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.completedDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.assignee"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.sortOrder"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.actionTypeId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId"
+ },
+ {
+ $ref: "#/parameters/body.nonConformanceActionTask"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["nonConformanceActionTask"]
+ }
+ },
+ "/quoteOperationStepSlide": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.stepId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.imagePath"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.caption"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.sortOrder"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/quoteOperationStepSlide"
},
type: "array"
}
@@ -9003,12 +10047,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["nonConformanceActionTask"]
+ tags: ["quoteOperationStepSlide"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.nonConformanceActionTask"
+ $ref: "#/parameters/body.quoteOperationStepSlide"
},
{
$ref: "#/parameters/select"
@@ -9022,57 +10066,48 @@ export default {
description: "Created"
}
},
- tags: ["nonConformanceActionTask"]
+ tags: ["quoteOperationStepSlide"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.id"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.nonConformanceId"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.status"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.dueDate"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.completedDate"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.assignee"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.notes"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.sortOrder"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.tags"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.companyId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdAt"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdBy"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedAt"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedBy"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.size"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.actionTypeId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.annotations"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.modelUploadId"
},
{
$ref: "#/parameters/preferReturn"
@@ -9083,60 +10118,51 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceActionTask"]
+ tags: ["quoteOperationStepSlide"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.id"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.nonConformanceId"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.status"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.dueDate"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.completedDate"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.assignee"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.notes"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.sortOrder"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.tags"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.companyId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdAt"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.createdBy"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedAt"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.updatedBy"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.size"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.actionTypeId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.annotations"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId"
+ $ref: "#/parameters/rowFilter.quoteOperationStepSlide.modelUploadId"
},
{
- $ref: "#/parameters/body.nonConformanceActionTask"
+ $ref: "#/parameters/body.quoteOperationStepSlide"
},
{
$ref: "#/parameters/preferReturn"
@@ -9147,7 +10173,7 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceActionTask"]
+ tags: ["quoteOperationStepSlide"]
}
},
"/supplierInteraction": {
@@ -10320,6 +11346,12 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteOperation.procedureId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.assemblyInstructionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/select"
},
@@ -10475,6 +11507,12 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteOperation.procedureId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.assemblyInstructionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -10584,6 +11622,12 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteOperation.procedureId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.assemblyInstructionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/body.quoteOperation"
},
@@ -14739,6 +15783,168 @@ export default {
tags: ["openPurchaseOrderLines"]
}
},
+ "/itemInspectionDocumentAssignment": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.usage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/itemInspectionDocumentAssignment"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["itemInspectionDocumentAssignment"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.itemInspectionDocumentAssignment"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["itemInspectionDocumentAssignment"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.usage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["itemInspectionDocumentAssignment"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.usage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemInspectionDocumentAssignment.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.itemInspectionDocumentAssignment"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["itemInspectionDocumentAssignment"]
+ }
+ },
"/fixedAssetClass": {
get: {
parameters: [
@@ -19911,6 +21117,114 @@ export default {
tags: ["assemblyComponentMapping"]
}
},
+ "/quoteOperationToolStep": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/quoteOperationToolStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["quoteOperationToolStep"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.quoteOperationToolStep"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["quoteOperationToolStep"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["quoteOperationToolStep"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationToolStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/body.quoteOperationToolStep"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["quoteOperationToolStep"]
+ }
+ },
"/salesOrderPayment": {
get: {
parameters: [
@@ -25824,382 +27138,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/methodOperationParameter"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["methodOperationParameter"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.methodOperationParameter"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["methodOperationParameter"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.id"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.key"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.value"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.operationId"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.updatedBy"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["methodOperationParameter"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.id"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.key"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.value"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.operationId"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.methodOperationParameter.updatedBy"
- },
- {
- $ref: "#/parameters/body.methodOperationParameter"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["methodOperationParameter"]
- }
- },
- "/assemblyPlanJob": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/assemblyPlanJob"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["assemblyPlanJob"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.assemblyPlanJob"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["assemblyPlanJob"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["assemblyPlanJob"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
- },
- {
- $ref: "#/parameters/body.assemblyPlanJob"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["assemblyPlanJob"]
- }
- },
- "/openJobMaterialLines": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.id"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.jobId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.parentMaterialId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.jobMakeMethodId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.jobReadableId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.quantityToIssue"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.unitOfMeasureCode"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.replenishmentSystem"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.itemTrackingType"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.leadTime"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.locationId"
- },
- {
- $ref: "#/parameters/rowFilter.openJobMaterialLines.dueDate"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/openJobMaterialLines"
+ $ref: "#/definitions/methodOperationParameter"
},
type: "array"
}
@@ -26208,59 +27147,146 @@ export default {
description: "Partial Content"
}
},
- tags: ["openJobMaterialLines"]
- }
- },
- "/inboundInspectionHistory": {
- get: {
+ tags: ["methodOperationParameter"]
+ },
+ post: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.id"
+ $ref: "#/parameters/body.methodOperationParameter"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inboundInspectionId"
+ $ref: "#/parameters/select"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.itemId"
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["methodOperationParameter"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.supplierId"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.key"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.samplingStandard"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.value"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.severity"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.operationId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inspectionLevel"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.companyId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.aql"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.createdAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.lotSize"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.createdBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.sampleSize"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.defectsFound"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.outcome"
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["methodOperationParameter"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.companyId"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.key"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdAt"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.value"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdBy"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.operationId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.updatedBy"
+ $ref: "#/parameters/rowFilter.methodOperationParameter.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationParameter.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.methodOperationParameter"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["methodOperationParameter"]
+ }
+ },
+ "/assemblyPlanJob": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
},
{
$ref: "#/parameters/select"
@@ -26289,7 +27315,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/inboundInspectionHistory"
+ $ref: "#/definitions/assemblyPlanJob"
},
type: "array"
}
@@ -26298,12 +27324,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["inboundInspectionHistory"]
+ tags: ["assemblyPlanJob"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.inboundInspectionHistory"
+ $ref: "#/parameters/body.assemblyPlanJob"
},
{
$ref: "#/parameters/select"
@@ -26317,57 +27343,91 @@ export default {
description: "Created"
}
},
- tags: ["inboundInspectionHistory"]
+ tags: ["assemblyPlanJob"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.id"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inboundInspectionId"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.itemId"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.supplierId"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.samplingStandard"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.severity"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inspectionLevel"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.aql"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.lotSize"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.sampleSize"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.defectsFound"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.outcome"
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["assemblyPlanJob"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.modelUploadId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.companyId"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.kind"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.status"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdAt"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.planPath"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.stats"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.error"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.createdAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdBy"
+ $ref: "#/parameters/rowFilter.assemblyPlanJob.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.updatedBy"
+ $ref: "#/parameters/body.assemblyPlanJob"
},
{
$ref: "#/parameters/preferReturn"
@@ -26378,71 +27438,91 @@ export default {
description: "No Content"
}
},
- tags: ["inboundInspectionHistory"]
- },
- patch: {
+ tags: ["assemblyPlanJob"]
+ }
+ },
+ "/openJobMaterialLines": {
+ get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.id"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inboundInspectionId"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.jobId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.itemId"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.parentMaterialId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.supplierId"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.jobMakeMethodId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.samplingStandard"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.jobReadableId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.severity"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.itemId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.inspectionLevel"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.quantityToIssue"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.aql"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.unitOfMeasureCode"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.lotSize"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.replenishmentSystem"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.sampleSize"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.itemTrackingType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.leadTime"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.defectsFound"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.locationId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.outcome"
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.dueDate"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.companyId"
+ $ref: "#/parameters/select"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdAt"
+ $ref: "#/parameters/order"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.createdBy"
+ $ref: "#/parameters/range"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionHistory.updatedBy"
+ $ref: "#/parameters/rangeUnit"
},
{
- $ref: "#/parameters/body.inboundInspectionHistory"
+ $ref: "#/parameters/offset"
},
{
- $ref: "#/parameters/preferReturn"
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
}
],
responses: {
- "204": {
- description: "No Content"
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/openJobMaterialLines"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
}
},
- tags: ["inboundInspectionHistory"]
+ tags: ["openJobMaterialLines"]
}
},
"/externalIntegrationMapping": {
@@ -33051,55 +34131,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/purchasingRfqs"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["purchasingRfqs"]
- }
- },
- "/salesOrderFavorite": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
- },
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/salesOrderFavorite"
+ $ref: "#/definitions/purchasingRfqs"
},
type: "array"
}
@@ -33108,107 +34140,17 @@ export default {
description: "Partial Content"
}
},
- tags: ["salesOrderFavorite"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.salesOrderFavorite"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["salesOrderFavorite"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
- },
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["salesOrderFavorite"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
- },
- {
- $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
- },
- {
- $ref: "#/parameters/body.salesOrderFavorite"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["salesOrderFavorite"]
+ tags: ["purchasingRfqs"]
}
},
- "/inboundInspectionSample": {
+ "/salesOrderFavorite": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.trackedEntityId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.status"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.notes"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedAt"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedBy"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
},
{
$ref: "#/parameters/select"
@@ -33237,7 +34179,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/inboundInspectionSample"
+ $ref: "#/definitions/salesOrderFavorite"
},
type: "array"
}
@@ -33246,12 +34188,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["inboundInspectionSample"]
+ tags: ["salesOrderFavorite"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.inboundInspectionSample"
+ $ref: "#/parameters/body.salesOrderFavorite"
},
{
$ref: "#/parameters/select"
@@ -33265,45 +34207,15 @@ export default {
description: "Created"
}
},
- tags: ["inboundInspectionSample"]
+ tags: ["salesOrderFavorite"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.trackedEntityId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.status"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.notes"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedAt"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedBy"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
},
{
$ref: "#/parameters/preferReturn"
@@ -33314,48 +34226,18 @@ export default {
description: "No Content"
}
},
- tags: ["inboundInspectionSample"]
+ tags: ["salesOrderFavorite"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.trackedEntityId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.status"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.notes"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.inspectedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedAt"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.salesOrderId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspectionSample.updatedBy"
+ $ref: "#/parameters/rowFilter.salesOrderFavorite.userId"
},
{
- $ref: "#/parameters/body.inboundInspectionSample"
+ $ref: "#/parameters/body.salesOrderFavorite"
},
{
$ref: "#/parameters/preferReturn"
@@ -33366,7 +34248,7 @@ export default {
description: "No Content"
}
},
- tags: ["inboundInspectionSample"]
+ tags: ["salesOrderFavorite"]
}
},
"/exchangeRateHistory": {
@@ -34521,9 +35403,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.companyId"
},
@@ -34733,9 +35612,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.companyId"
},
@@ -34899,9 +35775,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.purchaseOrderLine.companyId"
},
@@ -35286,6 +36159,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.assetLossOnDisposalAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.scrapAccount"
+ },
{
$ref: "#/parameters/select"
},
@@ -35498,6 +36374,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.assetLossOnDisposalAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.scrapAccount"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -35664,6 +36543,9 @@ export default {
{
$ref: "#/parameters/rowFilter.accountDefault.assetLossOnDisposalAccount"
},
+ {
+ $ref: "#/parameters/rowFilter.accountDefault.scrapAccount"
+ },
{
$ref: "#/parameters/body.accountDefault"
},
@@ -36309,7 +37191,148 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/documentFavorite"
+ $ref: "#/definitions/documentFavorite"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["documentFavorite"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.documentFavorite"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["documentFavorite"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.documentFavorite.documentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.documentFavorite.userId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["documentFavorite"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.documentFavorite.documentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.documentFavorite.userId"
+ },
+ {
+ $ref: "#/parameters/body.documentFavorite"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["documentFavorite"]
+ }
+ },
+ "/currencies": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.currencies.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.code"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.exchangeRate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.decimalPlaces"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.active"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.tags"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.companyGroupId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.currencies.name"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/currencies"
},
type: "array"
}
@@ -36318,56 +37341,82 @@ export default {
description: "Partial Content"
}
},
- tags: ["documentFavorite"]
- },
- post: {
+ tags: ["currencies"]
+ }
+ },
+ "/methodOperationToolStep": {
+ get: {
parameters: [
{
- $ref: "#/parameters/body.documentFavorite"
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationToolId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationStepId"
},
{
$ref: "#/parameters/select"
},
{
- $ref: "#/parameters/preferPost"
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
}
],
responses: {
- "201": {
- description: "Created"
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/methodOperationToolStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
}
},
- tags: ["documentFavorite"]
+ tags: ["methodOperationToolStep"]
},
- delete: {
+ post: {
parameters: [
{
- $ref: "#/parameters/rowFilter.documentFavorite.documentId"
+ $ref: "#/parameters/body.methodOperationToolStep"
},
{
- $ref: "#/parameters/rowFilter.documentFavorite.userId"
+ $ref: "#/parameters/select"
},
{
- $ref: "#/parameters/preferReturn"
+ $ref: "#/parameters/preferPost"
}
],
responses: {
- "204": {
- description: "No Content"
+ "201": {
+ description: "Created"
}
},
- tags: ["documentFavorite"]
+ tags: ["methodOperationToolStep"]
},
- patch: {
+ delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.documentFavorite.documentId"
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationToolId"
},
{
- $ref: "#/parameters/rowFilter.documentFavorite.userId"
- },
- {
- $ref: "#/parameters/body.documentFavorite"
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationStepId"
},
{
$ref: "#/parameters/preferReturn"
@@ -36378,88 +37427,29 @@ export default {
description: "No Content"
}
},
- tags: ["documentFavorite"]
- }
- },
- "/currencies": {
- get: {
+ tags: ["methodOperationToolStep"]
+ },
+ patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.currencies.id"
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationToolId"
},
{
- $ref: "#/parameters/rowFilter.currencies.code"
+ $ref: "#/parameters/rowFilter.methodOperationToolStep.methodOperationStepId"
},
{
- $ref: "#/parameters/rowFilter.currencies.exchangeRate"
+ $ref: "#/parameters/body.methodOperationToolStep"
},
{
- $ref: "#/parameters/rowFilter.currencies.decimalPlaces"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.active"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.tags"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.companyGroupId"
- },
- {
- $ref: "#/parameters/rowFilter.currencies.name"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
+ $ref: "#/parameters/preferReturn"
}
],
responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/currencies"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
+ "204": {
+ description: "No Content"
}
},
- tags: ["currencies"]
+ tags: ["methodOperationToolStep"]
}
},
"/shippingMethod": {
@@ -38661,6 +39651,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/select"
},
@@ -38858,6 +39851,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -39009,6 +40005,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/body.jobOperation"
},
@@ -45294,247 +46293,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/fixture"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["fixture"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.fixture"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["fixture"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.fixture.id"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.customerId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.approved"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.approvedBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.tags"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["fixture"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.fixture.id"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.customerId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.approved"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.approvedBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.fixture.tags"
- },
- {
- $ref: "#/parameters/body.fixture"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["fixture"]
- }
- },
- "/inboundInspection": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.inboundInspection.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptLineId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemReadableId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.supplierId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.lotSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingStandard"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingPlanType"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.acceptanceNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.rejectionNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.aql"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inspectionLevel"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.severity"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.codeLetter"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.status"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.notes"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.updatedBy"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/inboundInspection"
+ $ref: "#/definitions/fixture"
},
type: "array"
}
@@ -45543,12 +46302,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["inboundInspection"]
+ tags: ["fixture"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.inboundInspection"
+ $ref: "#/parameters/body.fixture"
},
{
$ref: "#/parameters/select"
@@ -45562,87 +46321,45 @@ export default {
description: "Created"
}
},
- tags: ["inboundInspection"]
+ tags: ["fixture"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspection.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptLineId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemReadableId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.supplierId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.lotSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingStandard"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingPlanType"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.acceptanceNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.rejectionNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.aql"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inspectionLevel"
+ $ref: "#/parameters/rowFilter.fixture.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.severity"
+ $ref: "#/parameters/rowFilter.fixture.itemId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.codeLetter"
+ $ref: "#/parameters/rowFilter.fixture.customerId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.status"
+ $ref: "#/parameters/rowFilter.fixture.approved"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.notes"
+ $ref: "#/parameters/rowFilter.fixture.approvedBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedBy"
+ $ref: "#/parameters/rowFilter.fixture.customFields"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedAt"
+ $ref: "#/parameters/rowFilter.fixture.companyId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.companyId"
+ $ref: "#/parameters/rowFilter.fixture.createdBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.createdAt"
+ $ref: "#/parameters/rowFilter.fixture.createdAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.createdBy"
+ $ref: "#/parameters/rowFilter.fixture.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.updatedAt"
+ $ref: "#/parameters/rowFilter.fixture.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.updatedBy"
+ $ref: "#/parameters/rowFilter.fixture.tags"
},
{
$ref: "#/parameters/preferReturn"
@@ -45653,90 +46370,48 @@ export default {
description: "No Content"
}
},
- tags: ["inboundInspection"]
+ tags: ["fixture"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.inboundInspection.id"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptLineId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.receiptId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.itemReadableId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.supplierId"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.lotSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingStandard"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.samplingPlanType"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.sampleSize"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.acceptanceNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.rejectionNumber"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.aql"
- },
- {
- $ref: "#/parameters/rowFilter.inboundInspection.inspectionLevel"
+ $ref: "#/parameters/rowFilter.fixture.id"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.severity"
+ $ref: "#/parameters/rowFilter.fixture.itemId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.codeLetter"
+ $ref: "#/parameters/rowFilter.fixture.customerId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.status"
+ $ref: "#/parameters/rowFilter.fixture.approved"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.notes"
+ $ref: "#/parameters/rowFilter.fixture.approvedBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedBy"
+ $ref: "#/parameters/rowFilter.fixture.customFields"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.dispositionedAt"
+ $ref: "#/parameters/rowFilter.fixture.companyId"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.companyId"
+ $ref: "#/parameters/rowFilter.fixture.createdBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.createdAt"
+ $ref: "#/parameters/rowFilter.fixture.createdAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.createdBy"
+ $ref: "#/parameters/rowFilter.fixture.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.updatedAt"
+ $ref: "#/parameters/rowFilter.fixture.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.inboundInspection.updatedBy"
+ $ref: "#/parameters/rowFilter.fixture.tags"
},
{
- $ref: "#/parameters/body.inboundInspection"
+ $ref: "#/parameters/body.fixture"
},
{
$ref: "#/parameters/preferReturn"
@@ -45747,7 +46422,7 @@ export default {
description: "No Content"
}
},
- tags: ["inboundInspection"]
+ tags: ["fixture"]
}
},
"/userPermission": {
@@ -46377,6 +47052,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationStep.nonConformanceInvestigationId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/select"
},
@@ -46493,6 +47171,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationStep.nonConformanceInvestigationId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -46563,6 +47244,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationStep.nonConformanceInvestigationId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/body.jobOperationStep"
},
@@ -47365,63 +48049,157 @@ export default {
$ref: "#/parameters/rowFilter.inspectionFeature.type"
},
{
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPercentage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingAql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingInspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSeverity"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspectionFeature"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspectionFeature"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspectionFeature"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspectionFeature"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.pageNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.label"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.description"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.nominalValue"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.tolerancePlus"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.toleranceMinus"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.unit"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.type"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPlanType"
},
{
- $ref: "#/parameters/offset"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSampleSize"
},
{
- $ref: "#/parameters/limit"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPercentage"
},
{
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/inspectionFeature"
- },
- type: "array"
- }
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingAql"
},
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["inspectionFeature"]
- },
- post: {
- parameters: [
{
- $ref: "#/parameters/body.inspectionFeature"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingInspectionLevel"
},
{
- $ref: "#/parameters/select"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSeverity"
},
{
- $ref: "#/parameters/preferPost"
+ $ref: "#/parameters/preferReturn"
}
],
responses: {
- "201": {
- description: "Created"
+ "204": {
+ description: "No Content"
}
},
tags: ["inspectionFeature"]
},
- delete: {
+ patch: {
parameters: [
{
$ref: "#/parameters/rowFilter.inspectionFeature.id"
@@ -47469,62 +48247,22 @@ export default {
$ref: "#/parameters/rowFilter.inspectionFeature.type"
},
{
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["inspectionFeature"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.id"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.inspectionDocumentId"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.pageNumber"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPlanType"
},
{
- $ref: "#/parameters/rowFilter.inspectionFeature.label"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSampleSize"
},
{
- $ref: "#/parameters/rowFilter.inspectionFeature.description"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingPercentage"
},
{
- $ref: "#/parameters/rowFilter.inspectionFeature.nominalValue"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingAql"
},
{
- $ref: "#/parameters/rowFilter.inspectionFeature.tolerancePlus"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingInspectionLevel"
},
{
- $ref: "#/parameters/rowFilter.inspectionFeature.toleranceMinus"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.unit"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.inspectionFeature.type"
+ $ref: "#/parameters/rowFilter.inspectionFeature.samplingSeverity"
},
{
$ref: "#/parameters/body.inspectionFeature"
@@ -48732,6 +49470,24 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPercentage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingAql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingInspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
+ },
{
$ref: "#/parameters/select"
},
@@ -48836,6 +49592,24 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPercentage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingAql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingInspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -48894,6 +49668,24 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingPercentage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingAql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingInspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
+ },
{
$ref: "#/parameters/body.inspectionDocument"
},
@@ -49623,7 +50415,169 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/configurationRule"
+ $ref: "#/definitions/configurationRule"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["configurationRule"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.configurationRule"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["configurationRule"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.field"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.code"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["configurationRule"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.field"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.code"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.configurationRule.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.configurationRule"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["configurationRule"]
+ }
+ },
+ "/nonConformanceReviewer": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/nonConformanceReviewer"
},
type: "array"
}
@@ -49632,12 +50586,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["configurationRule"]
+ tags: ["nonConformanceReviewer"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.configurationRule"
+ $ref: "#/parameters/body.nonConformanceReviewer"
},
{
$ref: "#/parameters/select"
@@ -49651,27 +50605,45 @@ export default {
description: "Created"
}
},
- tags: ["configurationRule"]
+ tags: ["nonConformanceReviewer"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.configurationRule.itemId"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.field"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.code"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.companyId"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.updatedAt"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.updatedBy"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
},
{
$ref: "#/parameters/preferReturn"
@@ -49682,30 +50654,48 @@ export default {
description: "No Content"
}
},
- tags: ["configurationRule"]
+ tags: ["nonConformanceReviewer"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.configurationRule.itemId"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.field"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.code"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.companyId"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.updatedAt"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
},
{
- $ref: "#/parameters/rowFilter.configurationRule.updatedBy"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
},
{
- $ref: "#/parameters/body.configurationRule"
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
+ },
+ {
+ $ref: "#/parameters/body.nonConformanceReviewer"
},
{
$ref: "#/parameters/preferReturn"
@@ -49716,47 +50706,50 @@ export default {
description: "No Content"
}
},
- tags: ["configurationRule"]
+ tags: ["nonConformanceReviewer"]
}
},
- "/nonConformanceReviewer": {
+ "/methodOperationStepSlide": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.size"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.modelUploadId"
},
{
$ref: "#/parameters/select"
@@ -49785,7 +50778,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/nonConformanceReviewer"
+ $ref: "#/definitions/methodOperationStepSlide"
},
type: "array"
}
@@ -49794,12 +50787,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["nonConformanceReviewer"]
+ tags: ["methodOperationStepSlide"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.nonConformanceReviewer"
+ $ref: "#/parameters/body.methodOperationStepSlide"
},
{
$ref: "#/parameters/select"
@@ -49813,45 +50806,48 @@ export default {
description: "Created"
}
},
- tags: ["nonConformanceReviewer"]
+ tags: ["methodOperationStepSlide"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.size"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.annotations"
+ },
+ {
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.modelUploadId"
},
{
$ref: "#/parameters/preferReturn"
@@ -49862,48 +50858,51 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceReviewer"]
+ tags: ["methodOperationStepSlide"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.id"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.id"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.title"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.stepId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.status"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.imagePath"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.nonConformanceId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.caption"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.notes"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.assignee"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.companyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.companyId"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.createdAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.createdBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedAt"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.size"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.annotations"
},
{
- $ref: "#/parameters/body.nonConformanceReviewer"
+ $ref: "#/parameters/rowFilter.methodOperationStepSlide.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/body.methodOperationStepSlide"
},
{
$ref: "#/parameters/preferReturn"
@@ -49914,7 +50913,7 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceReviewer"]
+ tags: ["methodOperationStepSlide"]
}
},
"/employee": {
@@ -52356,9 +53355,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLines.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.salesOrderLines.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.salesOrderLines.companyId"
},
@@ -52725,7 +53721,211 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/trackedEntity"
+ $ref: "#/definitions/trackedEntity"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["trackedEntity"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.trackedEntity"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["trackedEntity"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.attributes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.readableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.expirationDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.updatedBy"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["trackedEntity"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.attributes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.readableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.expirationDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedEntity.updatedBy"
+ },
+ {
+ $ref: "#/parameters/body.trackedEntity"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["trackedEntity"]
+ }
+ },
+ "/assemblyInstructionStepTool": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.stepId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.sortOrder"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/assemblyInstructionStepTool"
},
type: "array"
}
@@ -52734,12 +53934,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["trackedEntity"]
+ tags: ["assemblyInstructionStepTool"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.trackedEntity"
+ $ref: "#/parameters/body.assemblyInstructionStepTool"
},
{
$ref: "#/parameters/select"
@@ -52753,51 +53953,39 @@ export default {
description: "Created"
}
},
- tags: ["trackedEntity"]
+ tags: ["assemblyInstructionStepTool"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.trackedEntity.id"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.id"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.quantity"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.stepId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.status"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.itemId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocument"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.quantity"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentReadableId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.companyId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.attributes"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdBy"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.companyId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdAt"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.createdAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.readableId"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.expirationDate"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.updatedBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedAt"
},
{
$ref: "#/parameters/preferReturn"
@@ -52808,54 +53996,42 @@ export default {
description: "No Content"
}
},
- tags: ["trackedEntity"]
+ tags: ["assemblyInstructionStepTool"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.trackedEntity.id"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.id"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.quantity"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.stepId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.status"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.itemId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocument"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.quantity"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.sourceDocumentReadableId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.companyId"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.attributes"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdBy"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.companyId"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.createdAt"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.createdAt"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.createdBy"
+ $ref: "#/parameters/rowFilter.assemblyInstructionStepTool.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.trackedEntity.readableId"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.expirationDate"
- },
- {
- $ref: "#/parameters/rowFilter.trackedEntity.updatedBy"
- },
- {
- $ref: "#/parameters/body.trackedEntity"
+ $ref: "#/parameters/body.assemblyInstructionStepTool"
},
{
$ref: "#/parameters/preferReturn"
@@ -52866,7 +54042,7 @@ export default {
description: "No Content"
}
},
- tags: ["trackedEntity"]
+ tags: ["assemblyInstructionStepTool"]
}
},
"/companyPlan": {
@@ -54072,231 +55248,6 @@ export default {
tags: ["parts"]
}
},
- "/assemblyInstructionStepRequirement": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.stepId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.type"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.name"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.text"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.severity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.filePath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.quantity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.sortOrder"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedAt"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/assemblyInstructionStepRequirement"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["assemblyInstructionStepRequirement"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.assemblyInstructionStepRequirement"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["assemblyInstructionStepRequirement"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.stepId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.type"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.name"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.text"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.severity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.filePath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.quantity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.sortOrder"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedAt"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["assemblyInstructionStepRequirement"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.id"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.stepId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.type"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.name"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.text"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.severity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.filePath"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.quantity"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.sortOrder"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.assemblyInstructionStepRequirement.updatedAt"
- },
- {
- $ref: "#/parameters/body.assemblyInstructionStepRequirement"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["assemblyInstructionStepRequirement"]
- }
- },
"/currency": {
get: {
parameters: [
@@ -60135,6 +61086,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/select"
},
@@ -60278,6 +61232,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -60375,6 +61332,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperation.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperation.inspectionDocumentId"
+ },
{
$ref: "#/parameters/body.methodOperation"
},
@@ -61971,6 +62931,357 @@ export default {
tags: ["nonConformancePurchaseOrderLine"]
}
},
+ "/inspection": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspection.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.supplierId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.lotSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingStandard"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.aql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.severity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspection"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspection"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspection"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspection"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspection.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.supplierId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.lotSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingStandard"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.aql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.severity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspection"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspection.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.itemReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.supplierId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.lotSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingStandard"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.aql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.severity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.dispositionedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.inspectionDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspection.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/body.inspection"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspection"]
+ }
+ },
"/processes": {
get: {
parameters: [
@@ -62889,9 +64200,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.salesOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.salesOrderLine.companyId"
},
@@ -63083,9 +64391,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.salesOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.salesOrderLine.companyId"
},
@@ -63231,9 +64536,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.salesOrderLine.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.salesOrderLine.companyId"
},
@@ -64965,6 +66267,222 @@ export default {
tags: ["implementationRow"]
}
},
+ "/inspectionMeasurement": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionSampleId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.value"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspectionMeasurement"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspectionMeasurement"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspectionMeasurement"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspectionMeasurement"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionSampleId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.value"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionMeasurement"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionSampleId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.value"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.inspectedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionMeasurement.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.inspectionMeasurement"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionMeasurement"]
+ }
+ },
"/externalLink": {
get: {
parameters: [
@@ -65436,6 +66954,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperationStep.description"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/select"
},
@@ -65546,6 +67067,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperationStep.description"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -65610,6 +67134,9 @@ export default {
{
$ref: "#/parameters/rowFilter.methodOperationStep.description"
},
+ {
+ $ref: "#/parameters/rowFilter.methodOperationStep.assemblyInstructionStepId"
+ },
{
$ref: "#/parameters/body.methodOperationStep"
},
@@ -67092,6 +68619,114 @@ export default {
tags: ["companyGroup"]
}
},
+ "/quoteMaterialStep": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/quoteMaterialStep"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["quoteMaterialStep"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.quoteMaterialStep"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["quoteMaterialStep"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["quoteMaterialStep"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialStep.quoteOperationStepId"
+ },
+ {
+ $ref: "#/parameters/body.quoteMaterialStep"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["quoteMaterialStep"]
+ }
+ },
"/nonConformanceSupplier": {
get: {
parameters: [
@@ -68160,6 +69795,204 @@ export default {
tags: ["gaugeCalibrationRecord"]
}
},
+ "/inspectionSamplingPlan": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/inspectionSamplingPlan"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["inspectionSamplingPlan"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.inspectionSamplingPlan"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["inspectionSamplingPlan"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionSamplingPlan"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.inspectionFeatureId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.sampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.acceptanceNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.rejectionNumber"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.codeLetter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionSamplingPlan.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.inspectionSamplingPlan"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["inspectionSamplingPlan"]
+ }
+ },
"/customerTax": {
get: {
parameters: [
@@ -68583,9 +70416,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrderLines.invoicedComplete"
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrderLines.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.purchaseOrderLines.companyId"
},
@@ -72384,121 +74214,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/openSalesOrderLines"
- },
- type: "array"
- }
- },
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["openSalesOrderLines"]
- }
- },
- "/supplier": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.supplier.id"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.name"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.supplierTypeId"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.accountManagerId"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.logo"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.assignee"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.currencyCode"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.phone"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.fax"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.website"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.tags"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.taxPercent"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.embedding"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.purchasingContactId"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.defaultCc"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.supplierStatus"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.intercompanyCompanyId"
- },
- {
- $ref: "#/parameters/rowFilter.supplier.readableId"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/order"
- },
- {
- $ref: "#/parameters/range"
- },
- {
- $ref: "#/parameters/rangeUnit"
- },
- {
- $ref: "#/parameters/offset"
- },
- {
- $ref: "#/parameters/limit"
- },
- {
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/supplier"
+ $ref: "#/definitions/openSalesOrderLines"
},
type: "array"
}
@@ -72507,28 +74223,11 @@ export default {
description: "Partial Content"
}
},
- tags: ["supplier"]
- },
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.supplier"
- },
- {
- $ref: "#/parameters/select"
- },
- {
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["supplier"]
- },
- delete: {
+ tags: ["openSalesOrderLines"]
+ }
+ },
+ "/supplier": {
+ get: {
parameters: [
{
$ref: "#/parameters/rowFilter.supplier.id"
@@ -72603,17 +74302,63 @@ export default {
$ref: "#/parameters/rowFilter.supplier.readableId"
},
{
- $ref: "#/parameters/preferReturn"
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
}
],
responses: {
- "204": {
- description: "No Content"
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/supplier"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
}
},
tags: ["supplier"]
},
- patch: {
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.supplier"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["supplier"]
+ },
+ delete: {
parameters: [
{
$ref: "#/parameters/rowFilter.supplier.id"
@@ -72687,9 +74432,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.readableId"
},
- {
- $ref: "#/parameters/body.supplier"
- },
{
$ref: "#/parameters/preferReturn"
}
@@ -72700,148 +74442,83 @@ export default {
}
},
tags: ["supplier"]
- }
- },
- "/nonConformanceInboundInspection": {
- get: {
+ },
+ patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.id"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.nonConformanceId"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.inboundInspectionId"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.updatedBy"
+ $ref: "#/parameters/rowFilter.supplier.id"
},
{
- $ref: "#/parameters/select"
+ $ref: "#/parameters/rowFilter.supplier.name"
},
{
- $ref: "#/parameters/order"
+ $ref: "#/parameters/rowFilter.supplier.supplierTypeId"
},
{
- $ref: "#/parameters/range"
+ $ref: "#/parameters/rowFilter.supplier.accountManagerId"
},
{
- $ref: "#/parameters/rangeUnit"
+ $ref: "#/parameters/rowFilter.supplier.logo"
},
{
- $ref: "#/parameters/offset"
+ $ref: "#/parameters/rowFilter.supplier.assignee"
},
{
- $ref: "#/parameters/limit"
+ $ref: "#/parameters/rowFilter.supplier.companyId"
},
{
- $ref: "#/parameters/preferCount"
- }
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/nonConformanceInboundInspection"
- },
- type: "array"
- }
+ $ref: "#/parameters/rowFilter.supplier.createdAt"
},
- "206": {
- description: "Partial Content"
- }
- },
- tags: ["nonConformanceInboundInspection"]
- },
- post: {
- parameters: [
{
- $ref: "#/parameters/body.nonConformanceInboundInspection"
+ $ref: "#/parameters/rowFilter.supplier.createdBy"
},
{
- $ref: "#/parameters/select"
+ $ref: "#/parameters/rowFilter.supplier.updatedAt"
},
{
- $ref: "#/parameters/preferPost"
- }
- ],
- responses: {
- "201": {
- description: "Created"
- }
- },
- tags: ["nonConformanceInboundInspection"]
- },
- delete: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.id"
+ $ref: "#/parameters/rowFilter.supplier.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.nonConformanceId"
+ $ref: "#/parameters/rowFilter.supplier.customFields"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.inboundInspectionId"
+ $ref: "#/parameters/rowFilter.supplier.currencyCode"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.companyId"
+ $ref: "#/parameters/rowFilter.supplier.phone"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdAt"
+ $ref: "#/parameters/rowFilter.supplier.fax"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdBy"
+ $ref: "#/parameters/rowFilter.supplier.website"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.updatedBy"
+ $ref: "#/parameters/rowFilter.supplier.tags"
},
{
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["nonConformanceInboundInspection"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.id"
+ $ref: "#/parameters/rowFilter.supplier.taxPercent"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.nonConformanceId"
+ $ref: "#/parameters/rowFilter.supplier.embedding"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.inboundInspectionId"
+ $ref: "#/parameters/rowFilter.supplier.purchasingContactId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.companyId"
+ $ref: "#/parameters/rowFilter.supplier.defaultCc"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdAt"
+ $ref: "#/parameters/rowFilter.supplier.supplierStatus"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.createdBy"
+ $ref: "#/parameters/rowFilter.supplier.intercompanyCompanyId"
},
{
- $ref: "#/parameters/rowFilter.nonConformanceInboundInspection.updatedBy"
+ $ref: "#/parameters/rowFilter.supplier.readableId"
},
{
- $ref: "#/parameters/body.nonConformanceInboundInspection"
+ $ref: "#/parameters/body.supplier"
},
{
$ref: "#/parameters/preferReturn"
@@ -72852,7 +74529,7 @@ export default {
description: "No Content"
}
},
- tags: ["nonConformanceInboundInspection"]
+ tags: ["supplier"]
}
},
"/timeCardEntry": {
@@ -73866,9 +75543,6 @@ export default {
{
$ref: "#/parameters/rowFilter.item.readableIdWithRevision"
},
- {
- $ref: "#/parameters/rowFilter.item.requiresInspection"
- },
{
$ref: "#/parameters/rowFilter.item.sourcingType"
},
@@ -74010,104 +75684,98 @@ export default {
$ref: "#/parameters/rowFilter.item.readableIdWithRevision"
},
{
- $ref: "#/parameters/rowFilter.item.requiresInspection"
- },
- {
- $ref: "#/parameters/rowFilter.item.sourcingType"
- },
- {
- $ref: "#/parameters/rowFilter.item.mpn"
- },
- {
- $ref: "#/parameters/rowFilter.item.revisionStatus"
- },
- {
- $ref: "#/parameters/rowFilter.item.changeOrderId"
- },
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["item"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.item.id"
- },
- {
- $ref: "#/parameters/rowFilter.item.readableId"
- },
- {
- $ref: "#/parameters/rowFilter.item.name"
- },
- {
- $ref: "#/parameters/rowFilter.item.description"
- },
- {
- $ref: "#/parameters/rowFilter.item.type"
- },
- {
- $ref: "#/parameters/rowFilter.item.replenishmentSystem"
- },
- {
- $ref: "#/parameters/rowFilter.item.defaultMethodType"
- },
- {
- $ref: "#/parameters/rowFilter.item.itemTrackingType"
- },
- {
- $ref: "#/parameters/rowFilter.item.unitOfMeasureCode"
- },
- {
- $ref: "#/parameters/rowFilter.item.active"
- },
- {
- $ref: "#/parameters/rowFilter.item.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.item.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.item.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.item.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.item.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.item.assignee"
- },
- {
- $ref: "#/parameters/rowFilter.item.modelUploadId"
- },
- {
- $ref: "#/parameters/rowFilter.item.thumbnailPath"
- },
- {
- $ref: "#/parameters/rowFilter.item.notes"
- },
- {
- $ref: "#/parameters/rowFilter.item.trackingMethod"
- },
- {
- $ref: "#/parameters/rowFilter.item.embedding"
- },
- {
- $ref: "#/parameters/rowFilter.item.revision"
- },
- {
- $ref: "#/parameters/rowFilter.item.readableIdWithRevision"
- },
- {
- $ref: "#/parameters/rowFilter.item.requiresInspection"
+ $ref: "#/parameters/rowFilter.item.sourcingType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.mpn"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.revisionStatus"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.changeOrderId"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["item"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.item.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.readableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.description"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.type"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.replenishmentSystem"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.defaultMethodType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.itemTrackingType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.unitOfMeasureCode"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.active"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.assignee"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.modelUploadId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.thumbnailPath"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.trackingMethod"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.embedding"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.revision"
+ },
+ {
+ $ref: "#/parameters/rowFilter.item.readableIdWithRevision"
},
{
$ref: "#/parameters/rowFilter.item.sourcingType"
@@ -77967,7 +79635,190 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/demandProjection"
+ $ref: "#/definitions/demandProjection"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["demandProjection"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.demandProjection"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["demandProjection"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.locationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.periodId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastMethod"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.confidence"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.id"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["demandProjection"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.locationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.periodId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastMethod"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.confidence"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.id"
+ },
+ {
+ $ref: "#/parameters/body.demandProjection"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["demandProjection"]
+ }
+ },
+ "/pickingListLineTrackedEntity": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/pickingListLineTrackedEntity"
},
type: "array"
}
@@ -77976,12 +79827,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["demandProjection"]
+ tags: ["pickingListLineTrackedEntity"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.demandProjection"
+ $ref: "#/parameters/body.pickingListLineTrackedEntity"
},
{
$ref: "#/parameters/select"
@@ -77995,48 +79846,24 @@ export default {
description: "Created"
}
},
- tags: ["demandProjection"]
+ tags: ["pickingListLineTrackedEntity"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.demandProjection.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.locationId"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.periodId"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.forecastMethod"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.confidence"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.notes"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.demandProjection.createdBy"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.createdAt"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedAt"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedBy"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.id"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
},
{
$ref: "#/parameters/preferReturn"
@@ -78047,81 +79874,78 @@ export default {
description: "No Content"
}
},
- tags: ["demandProjection"]
+ tags: ["pickingListLineTrackedEntity"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.demandProjection.itemId"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.locationId"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.periodId"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.forecastMethod"
+ $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.confidence"
+ $ref: "#/parameters/body.pickingListLineTrackedEntity"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.notes"
- },
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["pickingListLineTrackedEntity"]
+ }
+ },
+ "/supplierProcess": {
+ get: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.demandProjection.companyId"
+ $ref: "#/parameters/rowFilter.supplierProcess.id"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.createdBy"
+ $ref: "#/parameters/rowFilter.supplierProcess.supplierId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.createdAt"
+ $ref: "#/parameters/rowFilter.supplierProcess.processId"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedAt"
+ $ref: "#/parameters/rowFilter.supplierProcess.minimumCost"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedBy"
+ $ref: "#/parameters/rowFilter.supplierProcess.leadTime"
},
{
- $ref: "#/parameters/rowFilter.demandProjection.id"
+ $ref: "#/parameters/rowFilter.supplierProcess.companyId"
},
{
- $ref: "#/parameters/body.demandProjection"
+ $ref: "#/parameters/rowFilter.supplierProcess.customFields"
},
{
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["demandProjection"]
- }
- },
- "/pickingListLineTrackedEntity": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
+ $ref: "#/parameters/rowFilter.supplierProcess.createdBy"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
+ $ref: "#/parameters/rowFilter.supplierProcess.createdAt"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
+ $ref: "#/parameters/rowFilter.supplierProcess.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
+ $ref: "#/parameters/rowFilter.supplierProcess.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
+ $ref: "#/parameters/rowFilter.supplierProcess.tags"
},
{
$ref: "#/parameters/select"
@@ -78150,7 +79974,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/pickingListLineTrackedEntity"
+ $ref: "#/definitions/supplierProcess"
},
type: "array"
}
@@ -78159,12 +79983,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["pickingListLineTrackedEntity"]
+ tags: ["supplierProcess"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.pickingListLineTrackedEntity"
+ $ref: "#/parameters/body.supplierProcess"
},
{
$ref: "#/parameters/select"
@@ -78178,55 +80002,45 @@ export default {
description: "Created"
}
},
- tags: ["pickingListLineTrackedEntity"]
+ tags: ["supplierProcess"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
+ $ref: "#/parameters/rowFilter.supplierProcess.id"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
+ $ref: "#/parameters/rowFilter.supplierProcess.supplierId"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
+ $ref: "#/parameters/rowFilter.supplierProcess.processId"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
+ $ref: "#/parameters/rowFilter.supplierProcess.minimumCost"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
+ $ref: "#/parameters/rowFilter.supplierProcess.leadTime"
},
{
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["pickingListLineTrackedEntity"]
- },
- patch: {
- parameters: [
+ $ref: "#/parameters/rowFilter.supplierProcess.companyId"
+ },
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.pickingListLineId"
+ $ref: "#/parameters/rowFilter.supplierProcess.customFields"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.trackedEntityId"
+ $ref: "#/parameters/rowFilter.supplierProcess.createdBy"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantity"
+ $ref: "#/parameters/rowFilter.supplierProcess.createdAt"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.quantityPicked"
+ $ref: "#/parameters/rowFilter.supplierProcess.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.pickingListLineTrackedEntity.companyId"
+ $ref: "#/parameters/rowFilter.supplierProcess.updatedAt"
},
{
- $ref: "#/parameters/body.pickingListLineTrackedEntity"
+ $ref: "#/parameters/rowFilter.supplierProcess.tags"
},
{
$ref: "#/parameters/preferReturn"
@@ -78237,11 +80051,9 @@ export default {
description: "No Content"
}
},
- tags: ["pickingListLineTrackedEntity"]
- }
- },
- "/supplierProcess": {
- get: {
+ tags: ["supplierProcess"]
+ },
+ patch: {
parameters: [
{
$ref: "#/parameters/rowFilter.supplierProcess.id"
@@ -78279,6 +80091,45 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierProcess.tags"
},
+ {
+ $ref: "#/parameters/body.supplierProcess"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["supplierProcess"]
+ }
+ },
+ "/nonConformanceInspection": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.nonConformanceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.inspectionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.updatedBy"
+ },
{
$ref: "#/parameters/select"
},
@@ -78306,7 +80157,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/supplierProcess"
+ $ref: "#/definitions/nonConformanceInspection"
},
type: "array"
}
@@ -78315,12 +80166,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["supplierProcess"]
+ tags: ["nonConformanceInspection"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.supplierProcess"
+ $ref: "#/parameters/body.nonConformanceInspection"
},
{
$ref: "#/parameters/select"
@@ -78334,45 +80185,30 @@ export default {
description: "Created"
}
},
- tags: ["supplierProcess"]
+ tags: ["nonConformanceInspection"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.supplierProcess.id"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.id"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.supplierId"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.nonConformanceId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.processId"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.inspectionId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.minimumCost"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.companyId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.leadTime"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdAt"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.companyId"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdBy"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.tags"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.updatedBy"
},
{
$ref: "#/parameters/preferReturn"
@@ -78383,48 +80219,33 @@ export default {
description: "No Content"
}
},
- tags: ["supplierProcess"]
+ tags: ["nonConformanceInspection"]
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.supplierProcess.id"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.supplierId"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.processId"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.minimumCost"
- },
- {
- $ref: "#/parameters/rowFilter.supplierProcess.leadTime"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.id"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.companyId"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.nonConformanceId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.customFields"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.inspectionId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.createdBy"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.companyId"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.createdAt"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdAt"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.updatedBy"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.createdBy"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.updatedAt"
+ $ref: "#/parameters/rowFilter.nonConformanceInspection.updatedBy"
},
{
- $ref: "#/parameters/rowFilter.supplierProcess.tags"
- },
- {
- $ref: "#/parameters/body.supplierProcess"
+ $ref: "#/parameters/body.nonConformanceInspection"
},
{
$ref: "#/parameters/preferReturn"
@@ -78435,7 +80256,7 @@ export default {
description: "No Content"
}
},
- tags: ["supplierProcess"]
+ tags: ["nonConformanceInspection"]
}
},
"/maintenanceScheduleItem": {
@@ -80739,6 +82560,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.showCustomerReadableId"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.autoStartOperationTimer"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
@@ -80924,6 +82748,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.showCustomerReadableId"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.autoStartOperationTimer"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
@@ -81063,6 +82890,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.showCustomerReadableId"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.autoStartOperationTimer"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
@@ -92623,6 +94453,24 @@ export default {
},
type: "object"
},
+ jobOperationToolStep: {
+ required: ["jobOperationToolId", "jobOperationStepId"],
+ properties: {
+ jobOperationToolId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperationTool.id`.<fk table='jobOperationTool' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ jobOperationStepId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperationStep.id`.<fk table='jobOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
purchasingRfqLines: {
properties: {
id: {
@@ -93120,6 +94968,24 @@ export default {
},
type: "object"
},
+ jobMaterialStep: {
+ required: ["jobMaterialId", "jobOperationStepId"],
+ properties: {
+ jobMaterialId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobMaterial.id`.<fk table='jobMaterial' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ jobOperationStepId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperationStep.id`.<fk table='jobOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
consumables: {
properties: {
active: {
@@ -93486,6 +95352,87 @@ export default {
},
type: "object"
},
+ assemblyInstructionStepSlide: {
+ required: [
+ "id",
+ "stepId",
+ "sortOrder",
+ "size",
+ "annotations",
+ "companyId",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ stepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstructionStep.id`.<fk table='assemblyInstructionStep' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ imagePath: {
+ format: "text",
+ type: "string"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ caption: {
+ format: "text",
+ type: "string"
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number"
+ },
+ size: {
+ default: "medium",
+ format: "text",
+ type: "string"
+ },
+ annotations: {
+ format: "jsonb"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
changeOrderType: {
required: ["id", "name", "companyId", "createdAt", "createdBy"],
properties: {
@@ -93810,6 +95757,105 @@ export default {
},
type: "object"
},
+ inspectionHistory: {
+ required: [
+ "id",
+ "inspectionId",
+ "itemId",
+ "samplingStandard",
+ "severity",
+ "lotSize",
+ "sampleSize",
+ "defectsFound",
+ "outcome",
+ "companyId",
+ "createdAt",
+ "createdBy"
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ supplierId: {
+ format: "text",
+ type: "string"
+ },
+ samplingStandard: {
+ enum: ["ANSI_Z1_4", "ISO_2859_1"],
+ format: 'public."samplingStandard"',
+ type: "string"
+ },
+ severity: {
+ enum: ["Normal", "Tightened", "Reduced"],
+ format: 'public."inspectionSeverity"',
+ type: "string"
+ },
+ inspectionLevel: {
+ enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
+ format: 'public."inspectionLevel"',
+ type: "string"
+ },
+ aql: {
+ format: "numeric",
+ type: "number"
+ },
+ lotSize: {
+ format: "numeric",
+ type: "number"
+ },
+ sampleSize: {
+ format: "integer",
+ type: "integer"
+ },
+ defectsFound: {
+ format: "integer",
+ type: "integer"
+ },
+ outcome: {
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
customerLocation: {
required: ["id", "customerId", "addressId", "name", "companyId"],
properties: {
@@ -94169,6 +96215,87 @@ export default {
},
type: "object"
},
+ jobOperationStepSlide: {
+ required: [
+ "id",
+ "stepId",
+ "sortOrder",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "size",
+ "annotations"
+ ],
+ properties: {
+ id: {
+ default: "public.id('slide'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ stepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobOperationStep.id`.<fk table='jobOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ imagePath: {
+ format: "text",
+ type: "string"
+ },
+ caption: {
+ format: "text",
+ type: "string"
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ size: {
+ default: "medium",
+ format: "text",
+ type: "string"
+ },
+ annotations: {
+ format: "jsonb"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
nonConformanceSalesOrderLine: {
required: [
"id",
@@ -94843,7 +96970,7 @@ export default {
type: "number"
},
operationType: {
- enum: ["Inside", "Outside"],
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -95057,67 +97184,6 @@ export default {
},
type: "object"
},
- assemblyStandardNote: {
- required: [
- "id",
- "name",
- "content",
- "severity",
- "companyId",
- "createdBy",
- "createdAt"
- ],
- properties: {
- id: {
- default: "public.xid()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- name: {
- format: "text",
- type: "string"
- },
- content: {
- format: "text",
- type: "string"
- },
- severity: {
- default: "Info",
- enum: ["Info", "Caution", "Warning"],
- format: 'public."assemblyNoteSeverity"',
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- }
- },
- type: "object"
- },
makeMethod: {
required: [
"id",
@@ -95854,83 +97920,6 @@ export default {
},
type: "object"
},
- itemSamplingPlan: {
- required: [
- "itemId",
- "type",
- "inspectionLevel",
- "severity",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- itemId: {
- description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
- format: "text",
- type: "string"
- },
- type: {
- default: "All",
- enum: ["All", "First", "Percentage", "AQL"],
- format: 'public."samplingPlanType"',
- type: "string"
- },
- sampleSize: {
- format: "integer",
- type: "integer"
- },
- percentage: {
- format: "numeric",
- type: "number"
- },
- aql: {
- format: "numeric",
- type: "number"
- },
- inspectionLevel: {
- default: "II",
- enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
- format: 'public."inspectionLevel"',
- type: "string"
- },
- severity: {
- default: "Normal",
- enum: ["Normal", "Tightened", "Reduced"],
- format: 'public."inspectionSeverity"',
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- }
- },
- type: "object"
- },
purchaseOrderLocations: {
properties: {
id: {
@@ -96155,7 +98144,9 @@ export default {
"Asset Disposal",
"Payment",
"Credit Memo",
- "Debit Memo"
+ "Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -96390,153 +98381,306 @@ export default {
},
type: "object"
},
- productionQuantity: {
+ productionQuantity: {
+ required: [
+ "id",
+ "jobOperationId",
+ "type",
+ "quantity",
+ "companyId",
+ "createdAt",
+ "createdBy"
+ ],
+ properties: {
+ id: {
+ default: "public.id('pq'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ jobOperationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ type: {
+ default: "Production",
+ enum: ["Rework", "Scrap", "Production"],
+ format: 'public."productionQuantityType"',
+ type: "string"
+ },
+ quantity: {
+ format: "numeric",
+ type: "number"
+ },
+ setupProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ laborProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ machineProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ notes: {
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ format: "text",
+ type: "string"
+ },
+ scrapReasonId: {
+ description:
+ "Note:\nThis is a Foreign Key to `scrapReason.id`.<fk table='scrapReason' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionSampleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionSample.id`.<fk table='inspectionSample' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
+ implementationHub: {
+ required: [
+ "id",
+ "templateKey",
+ "templateVersion",
+ "tier",
+ "status",
+ "exclusions",
+ "contacts",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ templateKey: {
+ default: "standard",
+ format: "text",
+ type: "string"
+ },
+ templateVersion: {
+ default: 1,
+ format: "integer",
+ type: "integer"
+ },
+ tier: {
+ default: "self_serve",
+ enum: ["self_serve", "guided", "enterprise"],
+ format: 'public."implementationTier"',
+ type: "string"
+ },
+ status: {
+ default: "tailoring",
+ enum: ["tailoring", "shared", "active", "complete", "archived"],
+ format: 'public."implementationStatus"',
+ type: "string"
+ },
+ exclusions: {
+ format: "jsonb"
+ },
+ contacts: {
+ format: "jsonb"
+ },
+ signedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ signedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
+ auditLogArchive: {
required: [
"id",
- "jobOperationId",
- "type",
- "quantity",
"companyId",
- "createdAt",
- "createdBy"
+ "archivePath",
+ "startDate",
+ "endDate",
+ "rowCount",
+ "createdAt"
],
properties: {
id: {
- default: "public.id('pq'::text)",
+ default: "public.id('arc'::text)",
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string"
},
- jobOperationId: {
+ companyId: {
description:
- "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
format: "text",
type: "string"
},
- type: {
- default: "Production",
- enum: ["Rework", "Scrap", "Production"],
- format: 'public."productionQuantityType"',
- type: "string"
- },
- quantity: {
- format: "numeric",
- type: "number"
- },
- setupProductionEventId: {
- description:
- "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ archivePath: {
format: "text",
type: "string"
},
- laborProductionEventId: {
- description:
- "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
- format: "text",
+ startDate: {
+ format: "date",
type: "string"
},
- machineProductionEventId: {
- description:
- "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
- format: "text",
+ endDate: {
+ format: "date",
type: "string"
},
- notes: {
- format: "text",
- type: "string"
+ rowCount: {
+ format: "integer",
+ type: "integer"
},
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
+ sizeBytes: {
+ format: "bigint",
+ type: "integer"
},
createdAt: {
default: "now()",
format: "timestamp with time zone",
type: "string"
- },
- createdBy: {
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
+ }
+ },
+ type: "object"
+ },
+ methodMaterialStep: {
+ required: ["methodMaterialId", "methodOperationStepId"],
+ properties: {
+ methodMaterialId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `methodMaterial.id`.<fk table='methodMaterial' column='id'/>",
format: "text",
type: "string"
},
- scrapReasonId: {
+ methodOperationStepId: {
description:
- "Note:\nThis is a Foreign Key to `scrapReason.id`.<fk table='scrapReason' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `methodOperationStep.id`.<fk table='methodOperationStep' column='id'/>",
format: "text",
type: "string"
}
},
type: "object"
},
- implementationHub: {
+ inspectionSample: {
required: [
"id",
- "templateKey",
- "templateVersion",
- "tier",
+ "inspectionId",
"status",
- "exclusions",
- "contacts",
- "createdBy",
- "createdAt"
+ "companyId",
+ "createdAt",
+ "createdBy"
],
properties: {
id: {
- description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string"
},
- templateKey: {
- default: "standard",
+ inspectionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
format: "text",
type: "string"
},
- templateVersion: {
- default: 1,
- format: "integer",
- type: "integer"
- },
- tier: {
- default: "self_serve",
- enum: ["self_serve", "guided", "enterprise"],
- format: 'public."implementationTier"',
+ trackedEntityId: {
+ description:
+ "Note:\nThis is a Foreign Key to `trackedEntity.id`.<fk table='trackedEntity' column='id'/>",
+ format: "text",
type: "string"
},
status: {
- default: "tailoring",
- enum: ["tailoring", "shared", "active", "complete", "archived"],
- format: 'public."implementationStatus"',
+ default: "Pending",
+ enum: ["Pending", "Passed", "Failed"],
+ format: 'public."inspectionSampleStatusType"',
type: "string"
},
- exclusions: {
- format: "jsonb"
- },
- contacts: {
- format: "jsonb"
- },
- signedAt: {
- format: "timestamp with time zone",
+ notes: {
+ format: "text",
type: "string"
},
- signedBy: {
+ inspectedBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
},
- createdBy: {
+ inspectedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ companyId: {
description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
format: "text",
type: "string"
},
@@ -96545,7 +98689,7 @@ export default {
format: "timestamp with time zone",
type: "string"
},
- updatedBy: {
+ createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
@@ -96554,57 +98698,12 @@ export default {
updatedAt: {
format: "timestamp with time zone",
type: "string"
- }
- },
- type: "object"
- },
- auditLogArchive: {
- required: [
- "id",
- "companyId",
- "archivePath",
- "startDate",
- "endDate",
- "rowCount",
- "createdAt"
- ],
- properties: {
- id: {
- default: "public.id('arc'::text)",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
},
- companyId: {
+ updatedBy: {
description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- archivePath: {
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
- },
- startDate: {
- format: "date",
- type: "string"
- },
- endDate: {
- format: "date",
- type: "string"
- },
- rowCount: {
- format: "integer",
- type: "integer"
- },
- sizeBytes: {
- format: "bigint",
- type: "integer"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
}
},
type: "object"
@@ -96708,6 +98807,87 @@ export default {
},
type: "object"
},
+ quoteOperationStepSlide: {
+ required: [
+ "id",
+ "stepId",
+ "sortOrder",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "size",
+ "annotations"
+ ],
+ properties: {
+ id: {
+ default: "public.id('slide'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ stepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `quoteOperationStep.id`.<fk table='quoteOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ imagePath: {
+ format: "text",
+ type: "string"
+ },
+ caption: {
+ format: "text",
+ type: "string"
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ size: {
+ default: "medium",
+ format: "text",
+ type: "string"
+ },
+ annotations: {
+ format: "jsonb"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
supplierInteraction: {
required: ["id", "companyId", "supplierId"],
properties: {
@@ -97330,8 +99510,8 @@ export default {
type: "number"
},
operationType: {
- default: "Inside",
- enum: ["Inside", "Outside"],
+ default: "Process",
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -97371,6 +99551,18 @@ export default {
"Note:\nThis is a Foreign Key to `procedure.id`.<fk table='procedure' column='id'/>",
format: "text",
type: "string"
+ },
+ assemblyInstructionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstruction.id`.<fk table='assemblyInstruction' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -97725,7 +99917,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -97774,7 +99966,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -99488,6 +101680,64 @@ export default {
},
type: "object"
},
+ itemInspectionDocumentAssignment: {
+ required: [
+ "itemId",
+ "usage",
+ "inspectionDocumentId",
+ "companyId",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ itemId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ usage: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ enum: ["Receipt"],
+ format: 'public."inspectionDocumentUsage"',
+ type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
fixedAssetClass: {
required: [
"id",
@@ -102068,6 +104318,24 @@ export default {
},
type: "object"
},
+ quoteOperationToolStep: {
+ required: ["quoteOperationToolId", "quoteOperationStepId"],
+ properties: {
+ quoteOperationToolId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `quoteOperationTool.id`.<fk table='quoteOperationTool' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ quoteOperationStepId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `quoteOperationStep.id`.<fk table='quoteOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
salesOrderPayment: {
required: ["id", "paymentComplete", "companyId"],
properties: {
@@ -103021,9 +105289,9 @@ export default {
type: "string"
},
processType: {
- default: "Inside",
- enum: ["Inside", "Outside", "Inside and Outside"],
- format: 'public."processType"',
+ default: "Process",
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
+ format: 'public."operationType"',
type: "string"
},
tags: {
@@ -105188,105 +107456,6 @@ export default {
},
type: "object"
},
- inboundInspectionHistory: {
- required: [
- "id",
- "inboundInspectionId",
- "itemId",
- "samplingStandard",
- "severity",
- "lotSize",
- "sampleSize",
- "defectsFound",
- "outcome",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- id: {
- default: "public.id()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- inboundInspectionId: {
- description:
- "Note:\nThis is a Foreign Key to `inboundInspection.id`.<fk table='inboundInspection' column='id'/>",
- format: "text",
- type: "string"
- },
- itemId: {
- description:
- "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
- format: "text",
- type: "string"
- },
- supplierId: {
- format: "text",
- type: "string"
- },
- samplingStandard: {
- enum: ["ANSI_Z1_4", "ISO_2859_1"],
- format: 'public."samplingStandard"',
- type: "string"
- },
- severity: {
- enum: ["Normal", "Tightened", "Reduced"],
- format: 'public."inspectionSeverity"',
- type: "string"
- },
- inspectionLevel: {
- enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
- format: 'public."inspectionLevel"',
- type: "string"
- },
- aql: {
- format: "numeric",
- type: "number"
- },
- lotSize: {
- format: "numeric",
- type: "number"
- },
- sampleSize: {
- format: "integer",
- type: "integer"
- },
- defectsFound: {
- format: "integer",
- type: "integer"
- },
- outcome: {
- format: "text",
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- }
- },
- type: "object"
- },
externalIntegrationMapping: {
required: [
"id",
@@ -106620,7 +108789,9 @@ export default {
"Payment",
"Memo",
"Inventory Adjustment",
- "Inventory Count"
+ "Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalLineDocumentType"',
type: "string"
@@ -107183,7 +109354,9 @@ export default {
"Asset Disposal",
"Payment",
"Credit Memo",
- "Debit Memo"
+ "Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -108247,84 +110420,6 @@ export default {
},
type: "object"
},
- inboundInspectionSample: {
- required: [
- "id",
- "inboundInspectionId",
- "status",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- id: {
- default: "public.id()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- inboundInspectionId: {
- description:
- "Note:\nThis is a Foreign Key to `inboundInspection.id`.<fk table='inboundInspection' column='id'/>",
- format: "text",
- type: "string"
- },
- trackedEntityId: {
- description:
- "Note:\nThis is a Foreign Key to `trackedEntity.id`.<fk table='trackedEntity' column='id'/>",
- format: "text",
- type: "string"
- },
- status: {
- default: "Pending",
- enum: ["Pending", "Passed", "Failed"],
- format: 'public."inboundInspectionSampleStatus"',
- type: "string"
- },
- notes: {
- format: "text",
- type: "string"
- },
- inspectedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- inspectedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- }
- },
- type: "object"
- },
exchangeRateHistory: {
required: [
"id",
@@ -108790,7 +110885,6 @@ export default {
"purchaseOrderLineType",
"receivedComplete",
"invoicedComplete",
- "requiresInspection",
"companyId",
"createdAt",
"createdBy",
@@ -108894,11 +110988,6 @@ export default {
format: "boolean",
type: "boolean"
},
- requiresInspection: {
- default: false,
- format: "boolean",
- type: "boolean"
- },
companyId: {
format: "text",
type: "string"
@@ -109530,6 +111619,12 @@ export default {
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
format: "text",
type: "string"
+ },
+ scrapAccount: {
+ description:
+ "Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -109905,6 +112000,24 @@ export default {
},
type: "object"
},
+ methodOperationToolStep: {
+ required: ["methodOperationToolId", "methodOperationStepId"],
+ properties: {
+ methodOperationToolId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `methodOperationTool.id`.<fk table='methodOperationTool' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ methodOperationStepId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `methodOperationStep.id`.<fk table='methodOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
shippingMethod: {
required: [
"id",
@@ -111049,8 +113162,8 @@ export default {
type: "number"
},
operationType: {
- default: "Inside",
- enum: ["Inside", "Outside"],
+ default: "Process",
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -111207,6 +113320,12 @@ export default {
"Note:\nThis is a Foreign Key to `assemblyInstruction.id`.<fk table='assemblyInstruction' column='id'/>",
format: "text",
type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -114253,155 +116372,6 @@ export default {
},
type: "object"
},
- inboundInspection: {
- required: [
- "id",
- "inboundInspectionId",
- "receiptLineId",
- "receiptId",
- "itemId",
- "lotSize",
- "samplingStandard",
- "samplingPlanType",
- "sampleSize",
- "acceptanceNumber",
- "rejectionNumber",
- "status",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- id: {
- default: "public.id()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- inboundInspectionId: {
- format: "text",
- type: "string"
- },
- receiptLineId: {
- description:
- "Note:\nThis is a Foreign Key to `receiptLine.id`.<fk table='receiptLine' column='id'/>",
- format: "text",
- type: "string"
- },
- receiptId: {
- description:
- "Note:\nThis is a Foreign Key to `receipt.id`.<fk table='receipt' column='id'/>",
- format: "text",
- type: "string"
- },
- itemId: {
- description:
- "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
- format: "text",
- type: "string"
- },
- itemReadableId: {
- format: "text",
- type: "string"
- },
- supplierId: {
- format: "text",
- type: "string"
- },
- lotSize: {
- format: "numeric",
- type: "number"
- },
- samplingStandard: {
- enum: ["ANSI_Z1_4", "ISO_2859_1"],
- format: 'public."samplingStandard"',
- type: "string"
- },
- samplingPlanType: {
- enum: ["All", "First", "Percentage", "AQL"],
- format: 'public."samplingPlanType"',
- type: "string"
- },
- sampleSize: {
- format: "integer",
- type: "integer"
- },
- acceptanceNumber: {
- format: "integer",
- type: "integer"
- },
- rejectionNumber: {
- format: "integer",
- type: "integer"
- },
- aql: {
- format: "numeric",
- type: "number"
- },
- inspectionLevel: {
- enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
- format: 'public."inspectionLevel"',
- type: "string"
- },
- severity: {
- enum: ["Normal", "Tightened", "Reduced"],
- format: 'public."inspectionSeverity"',
- type: "string"
- },
- codeLetter: {
- format: "text",
- type: "string"
- },
- status: {
- default: "Pending",
- enum: ["Pending", "In Progress", "Passed", "Failed", "Partial"],
- format: 'public."inboundInspectionStatus"',
- type: "string"
- },
- notes: {
- format: "text",
- type: "string"
- },
- dispositionedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- dispositionedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- }
- },
- type: "object"
- },
userPermission: {
required: ["id"],
properties: {
@@ -114667,6 +116637,12 @@ export default {
nonConformanceInvestigationId: {
format: "text",
type: "string"
+ },
+ assemblyInstructionStepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstructionStep.id`.<fk table='assemblyInstructionStep' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -115073,6 +117049,33 @@ export default {
],
format: 'public."procedureStepType"',
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"
}
},
type: "object"
@@ -115586,6 +117589,33 @@ export default {
updatedAt: {
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"
}
},
type: "object"
@@ -115988,6 +118018,87 @@ export default {
},
type: "object"
},
+ methodOperationStepSlide: {
+ required: [
+ "id",
+ "stepId",
+ "sortOrder",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "size",
+ "annotations"
+ ],
+ properties: {
+ id: {
+ default: "public.id('slide'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ stepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `methodOperationStep.id`.<fk table='methodOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ imagePath: {
+ format: "text",
+ type: "string"
+ },
+ caption: {
+ format: "text",
+ type: "string"
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ size: {
+ default: "medium",
+ format: "text",
+ type: "string"
+ },
+ annotations: {
+ format: "jsonb"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
employee: {
required: ["id", "companyId", "employeeTypeId", "active"],
properties: {
@@ -117081,10 +119192,6 @@ export default {
format: "boolean",
type: "boolean"
},
- requiresInspection: {
- format: "boolean",
- type: "boolean"
- },
companyId: {
format: "text",
type: "string"
@@ -117377,6 +119484,76 @@ export default {
},
type: "object"
},
+ assemblyInstructionStepTool: {
+ required: [
+ "id",
+ "stepId",
+ "itemId",
+ "quantity",
+ "sortOrder",
+ "companyId",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ stepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstructionStep.id`.<fk table='assemblyInstructionStep' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ quantity: {
+ default: 1,
+ format: "integer",
+ type: "integer"
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
companyPlan: {
required: [
"id",
@@ -118053,98 +120230,6 @@ export default {
},
type: "object"
},
- assemblyInstructionStepRequirement: {
- required: [
- "id",
- "stepId",
- "type",
- "quantity",
- "sortOrder",
- "companyId",
- "createdBy",
- "createdAt"
- ],
- properties: {
- id: {
- default: "public.xid()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- stepId: {
- description:
- "Note:\nThis is a Foreign Key to `assemblyInstructionStep.id`.<fk table='assemblyInstructionStep' column='id'/>",
- format: "text",
- type: "string"
- },
- type: {
- enum: ["Tool", "Fixture", "Consumable", "Note", "Media"],
- format: 'public."assemblyRequirementType"',
- type: "string"
- },
- itemId: {
- description:
- "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
- format: "text",
- type: "string"
- },
- name: {
- format: "text",
- type: "string"
- },
- text: {
- format: "text",
- type: "string"
- },
- severity: {
- enum: ["Info", "Caution", "Warning"],
- format: 'public."assemblyNoteSeverity"',
- type: "string"
- },
- filePath: {
- format: "text",
- type: "string"
- },
- quantity: {
- default: 1,
- format: "integer",
- type: "integer"
- },
- sortOrder: {
- default: 1,
- format: "double precision",
- type: "number"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedAt: {
- format: "timestamp with time zone",
- type: "string"
- }
- },
- type: "object"
- },
currency: {
required: [
"id",
@@ -119026,7 +121111,9 @@ export default {
"Payment",
"Memo",
"Inventory Adjustment",
- "Inventory Count"
+ "Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalLineDocumentType"',
type: "string"
@@ -119132,7 +121219,9 @@ export default {
"Asset Disposal",
"Payment",
"Credit Memo",
- "Debit Memo"
+ "Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -119201,7 +121290,9 @@ export default {
"Payment",
"Memo",
"Inventory Adjustment",
- "Inventory Count"
+ "Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection"
],
format: 'public."journalLineDocumentType"',
type: "string"
@@ -121218,8 +123309,8 @@ export default {
type: "string"
},
operationType: {
- default: "Inside",
- enum: ["Inside", "Outside"],
+ default: "Process",
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -121265,6 +123356,12 @@ export default {
"Note:\nThis is a Foreign Key to `assemblyInstruction.id`.<fk table='assemblyInstruction' column='id'/>",
format: "text",
type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -121778,112 +123875,249 @@ export default {
},
type: "object"
},
- employeeJob: {
- required: ["id", "companyId"],
+ employeeJob: {
+ required: ["id", "companyId"],
+ properties: {
+ id: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ locationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ shiftId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shift.id`.<fk table='shift' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ managerId: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ title: {
+ format: "text",
+ type: "string"
+ },
+ startDate: {
+ format: "date",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp without time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ customFields: {
+ format: "jsonb"
+ },
+ departmentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `department.id`.<fk table='department' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ tags: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ }
+ },
+ type: "object"
+ },
+ nonConformancePurchaseOrderLine: {
+ required: [
+ "id",
+ "nonConformanceId",
+ "purchaseOrderLineId",
+ "companyId",
+ "createdAt",
+ "createdBy"
+ ],
+ properties: {
+ id: {
+ default: "public.id('ncpol'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ nonConformanceId: {
+ description:
+ "Note:\nThis is a Foreign Key to `nonConformance.id`.<fk table='nonConformance' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ purchaseOrderLineId: {
+ description:
+ "Note:\nThis is a Foreign Key to `purchaseOrderLine.id`.<fk table='purchaseOrderLine' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ purchaseOrderId: {
+ description:
+ "Note:\nThis is a Foreign Key to `purchaseOrder.id`.<fk table='purchaseOrder' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ purchaseOrderReadableId: {
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
+ inspection: {
+ required: [
+ "id",
+ "inspectionId",
+ "itemId",
+ "lotSize",
+ "samplingStandard",
+ "samplingPlanType",
+ "sampleSize",
+ "acceptanceNumber",
+ "rejectionNumber",
+ "status",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "sourceDocument",
+ "sourceDocumentId"
+ ],
properties: {
id: {
- description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string"
},
- locationId: {
- description:
- "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ inspectionId: {
format: "text",
type: "string"
},
- shiftId: {
+ itemId: {
description:
- "Note:\nThis is a Foreign Key to `shift.id`.<fk table='shift' column='id'/>",
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
format: "text",
type: "string"
},
- managerId: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ itemReadableId: {
format: "text",
type: "string"
},
- title: {
+ supplierId: {
format: "text",
type: "string"
},
- startDate: {
- format: "date",
- type: "string"
+ lotSize: {
+ format: "numeric",
+ type: "number"
},
- companyId: {
- description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
+ samplingStandard: {
+ enum: ["ANSI_Z1_4", "ISO_2859_1"],
+ format: 'public."samplingStandard"',
type: "string"
},
- updatedAt: {
- format: "timestamp without time zone",
+ samplingPlanType: {
+ enum: ["All", "First", "Percentage", "AQL"],
+ format: 'public."samplingPlanType"',
type: "string"
},
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
+ sampleSize: {
+ format: "integer",
+ type: "integer"
},
- customFields: {
- format: "jsonb"
+ acceptanceNumber: {
+ format: "integer",
+ type: "integer"
},
- departmentId: {
- description:
- "Note:\nThis is a Foreign Key to `department.id`.<fk table='department' column='id'/>",
- format: "text",
+ rejectionNumber: {
+ format: "integer",
+ type: "integer"
+ },
+ aql: {
+ format: "numeric",
+ type: "number"
+ },
+ inspectionLevel: {
+ enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
+ format: 'public."inspectionLevel"',
type: "string"
},
- tags: {
- format: "text[]",
- items: {
- type: "string"
- },
- type: "array"
- }
- },
- type: "object"
- },
- nonConformancePurchaseOrderLine: {
- required: [
- "id",
- "nonConformanceId",
- "purchaseOrderLineId",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- id: {
- default: "public.id('ncpol'::text)",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
+ severity: {
+ enum: ["Normal", "Tightened", "Reduced"],
+ format: 'public."inspectionSeverity"',
type: "string"
},
- nonConformanceId: {
- description:
- "Note:\nThis is a Foreign Key to `nonConformance.id`.<fk table='nonConformance' column='id'/>",
+ codeLetter: {
format: "text",
type: "string"
},
- purchaseOrderLineId: {
- description:
- "Note:\nThis is a Foreign Key to `purchaseOrderLine.id`.<fk table='purchaseOrderLine' column='id'/>",
+ status: {
+ default: "Pending",
+ enum: ["Pending", "In Progress", "Passed", "Failed", "Partial"],
+ format: 'public."inspectionStatusType"',
+ type: "string"
+ },
+ notes: {
format: "text",
type: "string"
},
- purchaseOrderId: {
+ dispositionedBy: {
description:
- "Note:\nThis is a Foreign Key to `purchaseOrder.id`.<fk table='purchaseOrder' column='id'/>",
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
},
- purchaseOrderReadableId: {
- format: "text",
+ dispositionedAt: {
+ format: "timestamp with time zone",
type: "string"
},
companyId: {
@@ -121912,6 +124146,29 @@ export default {
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ sourceDocument: {
+ enum: ["Receipt", "Job Operation"],
+ format: 'public."inspectionSourceDocument"',
+ type: "string"
+ },
+ sourceDocumentId: {
+ format: "text",
+ type: "string"
+ },
+ sourceDocumentLineId: {
+ format: "text",
+ type: "string"
+ },
+ sourceDocumentReadableId: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -121974,8 +124231,8 @@ export default {
type: "string"
},
processType: {
- enum: ["Inside", "Outside", "Inside and Outside"],
- format: 'public."processType"',
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
+ format: 'public."operationType"',
type: "string"
},
tags: {
@@ -122433,7 +124690,7 @@ export default {
type: "number"
},
operationType: {
- enum: ["Inside", "Outside"],
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -122501,7 +124758,6 @@ export default {
"salesOrderLineType",
"sentComplete",
"invoicedComplete",
- "requiresInspection",
"companyId",
"createdAt",
"createdBy",
@@ -122603,11 +124859,6 @@ export default {
format: "boolean",
type: "boolean"
},
- requiresInspection: {
- default: false,
- format: "boolean",
- type: "boolean"
- },
companyId: {
format: "text",
type: "string"
@@ -123389,6 +125640,96 @@ export default {
},
type: "object"
},
+ inspectionMeasurement: {
+ required: [
+ "id",
+ "inspectionId",
+ "inspectionSampleId",
+ "inspectionFeatureId",
+ "status",
+ "companyId",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('iim'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionSampleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionSample.id`.<fk table='inspectionSample' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionFeatureId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionFeature.id`.<fk table='inspectionFeature' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ value: {
+ format: "numeric",
+ type: "number"
+ },
+ status: {
+ default: "Pending",
+ enum: ["Pending", "Passed", "Failed"],
+ format: 'public."inspectionSampleStatusType"',
+ type: "string"
+ },
+ notes: {
+ format: "text",
+ type: "string"
+ },
+ inspectedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
externalLink: {
required: ["id", "documentType", "documentId", "createdAt", "companyId"],
properties: {
@@ -123719,6 +126060,12 @@ export default {
},
description: {
format: "json"
+ },
+ assemblyInstructionStepId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstructionStep.id`.<fk table='assemblyInstructionStep' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -124256,6 +126603,24 @@ export default {
},
type: "object"
},
+ quoteMaterialStep: {
+ required: ["quoteMaterialId", "quoteOperationStepId"],
+ properties: {
+ quoteMaterialId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `quoteMaterial.id`.<fk table='quoteMaterial' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ quoteOperationStepId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `quoteOperationStep.id`.<fk table='quoteOperationStep' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
nonConformanceSupplier: {
required: [
"id",
@@ -124746,72 +127111,174 @@ export default {
format: "text",
type: "string"
},
- requiredActionIds: {
- format: "text[]",
- items: {
- type: "string"
- },
- type: "array"
+ requiredActionIds: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ }
+ },
+ type: "object"
+ },
+ gaugeCalibrationRecord: {
+ required: [
+ "id",
+ "gaugeId",
+ "dateCalibrated",
+ "inspectionStatus",
+ "requiresAction",
+ "requiresAdjustment",
+ "requiresRepair",
+ "notes",
+ "customFields",
+ "createdAt",
+ "createdBy"
+ ],
+ properties: {
+ id: {
+ default: "public.id('gcr'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ gaugeId: {
+ description:
+ "Note:\nThis is a Foreign Key to `gauge.id`.<fk table='gauge' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ dateCalibrated: {
+ format: "date",
+ type: "string"
+ },
+ inspectionStatus: {
+ enum: ["Pass", "Fail"],
+ format: 'public."inspectionStatus"',
+ type: "string"
+ },
+ requiresAction: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ requiresAdjustment: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ requiresRepair: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ notes: {
+ format: "json"
+ },
+ customFields: {
+ format: "json"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ supplierId: {
+ format: "text",
+ type: "string"
+ },
+ temperature: {
+ format: "real",
+ type: "number"
+ },
+ humidity: {
+ format: "real",
+ type: "number"
+ },
+ approvedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ measurementStandard: {
+ format: "text",
+ type: "string"
+ },
+ calibrationAttempts: {
+ format: "jsonb"
}
},
type: "object"
},
- gaugeCalibrationRecord: {
+ inspectionSamplingPlan: {
required: [
"id",
- "gaugeId",
- "dateCalibrated",
- "inspectionStatus",
- "requiresAction",
- "requiresAdjustment",
- "requiresRepair",
- "notes",
- "customFields",
- "createdAt",
- "createdBy"
+ "inspectionId",
+ "inspectionFeatureId",
+ "sampleSize",
+ "acceptanceNumber",
+ "rejectionNumber",
+ "companyId",
+ "createdBy",
+ "createdAt"
],
properties: {
id: {
- default: "public.id('gcr'::text)",
+ default: "public.id('iif'::text)",
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string"
},
- gaugeId: {
+ inspectionId: {
description:
- "Note:\nThis is a Foreign Key to `gauge.id`.<fk table='gauge' column='id'/>",
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
format: "text",
type: "string"
},
- dateCalibrated: {
- format: "date",
- type: "string"
- },
- inspectionStatus: {
- enum: ["Pass", "Fail"],
- format: 'public."inspectionStatus"',
+ inspectionFeatureId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionFeature.id`.<fk table='inspectionFeature' column='id'/>",
+ format: "text",
type: "string"
},
- requiresAction: {
- default: false,
- format: "boolean",
- type: "boolean"
- },
- requiresAdjustment: {
- default: false,
- format: "boolean",
- type: "boolean"
+ sampleSize: {
+ format: "integer",
+ type: "integer"
},
- requiresRepair: {
- default: false,
- format: "boolean",
- type: "boolean"
+ acceptanceNumber: {
+ format: "integer",
+ type: "integer"
},
- notes: {
- format: "json"
+ rejectionNumber: {
+ format: "integer",
+ type: "integer"
},
- customFields: {
- format: "json"
+ codeLetter: {
+ format: "text",
+ type: "string"
},
companyId: {
description:
@@ -124819,18 +127286,14 @@ export default {
format: "text",
type: "string"
},
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
format: "text",
type: "string"
},
- updatedAt: {
+ createdAt: {
+ default: "now()",
format: "timestamp with time zone",
type: "string"
},
@@ -124840,30 +127303,9 @@ export default {
format: "text",
type: "string"
},
- supplierId: {
- format: "text",
- type: "string"
- },
- temperature: {
- format: "real",
- type: "number"
- },
- humidity: {
- format: "real",
- type: "number"
- },
- approvedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- measurementStandard: {
- format: "text",
+ updatedAt: {
+ format: "timestamp with time zone",
type: "string"
- },
- calibrationAttempts: {
- format: "jsonb"
}
},
type: "object"
@@ -125090,10 +127532,6 @@ export default {
format: "boolean",
type: "boolean"
},
- requiresInspection: {
- format: "boolean",
- type: "boolean"
- },
companyId: {
format: "text",
type: "string"
@@ -127224,60 +129662,6 @@ export default {
},
type: "object"
},
- nonConformanceInboundInspection: {
- required: [
- "id",
- "nonConformanceId",
- "inboundInspectionId",
- "companyId",
- "createdAt",
- "createdBy"
- ],
- properties: {
- id: {
- default: "public.id()",
- description: "Note:\nThis is a Primary Key.<pk/>",
- format: "text",
- type: "string"
- },
- nonConformanceId: {
- description:
- "Note:\nThis is a Foreign Key to `nonConformance.id`.<fk table='nonConformance' column='id'/>",
- format: "text",
- type: "string"
- },
- inboundInspectionId: {
- description:
- "Note:\nThis is a Foreign Key to `inboundInspection.id`.<fk table='inboundInspection' column='id'/>",
- format: "text",
- type: "string"
- },
- companyId: {
- description:
- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
- format: "text",
- type: "string"
- },
- createdAt: {
- default: "now()",
- format: "timestamp with time zone",
- type: "string"
- },
- createdBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- },
- updatedBy: {
- description:
- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
- format: "text",
- type: "string"
- }
- },
- type: "object"
- },
timeCardEntry: {
required: [
"id",
@@ -127560,7 +129944,7 @@ export default {
type: "number"
},
operationType: {
- enum: ["Inside", "Outside"],
+ enum: ["Process", "Assembly", "Inspection", "Outside Processing"],
format: 'public."operationType"',
type: "string"
},
@@ -127841,7 +130225,6 @@ export default {
"active",
"createdBy",
"createdAt",
- "requiresInspection",
"sourcingType",
"revisionStatus"
],
@@ -127965,11 +130348,6 @@ export default {
format: "text",
type: "string"
},
- requiresInspection: {
- default: false,
- format: "boolean",
- type: "boolean"
- },
sourcingType: {
default: "Specified",
enum: ["Specified", "Drop Ship", "Ship from Inventory"],
@@ -130134,6 +132512,60 @@ export default {
},
type: "object"
},
+ nonConformanceInspection: {
+ required: [
+ "id",
+ "nonConformanceId",
+ "inspectionId",
+ "companyId",
+ "createdAt",
+ "createdBy"
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ nonConformanceId: {
+ description:
+ "Note:\nThis is a Foreign Key to `nonConformance.id`.<fk table='nonConformance' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspection.id`.<fk table='inspection' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
maintenanceScheduleItem: {
required: [
"id",
@@ -131092,6 +133524,7 @@ export default {
"assetTaxDepreciationEnabled",
"showSupplierReadableId",
"showCustomerReadableId",
+ "autoStartOperationTimer",
"plmReleaseControl"
],
properties: {
@@ -131319,6 +133752,11 @@ export default {
format: "boolean",
type: "boolean"
},
+ autoStartOperationTimer: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
plmReleaseControl: {
default: "enforce",
format: "text",
@@ -132028,6 +134466,27 @@ export default {
in: "query",
type: "string"
},
+ "body.jobOperationToolStep": {
+ name: "jobOperationToolStep",
+ description: "jobOperationToolStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobOperationToolStep"
+ }
+ },
+ "rowFilter.jobOperationToolStep.jobOperationToolId": {
+ name: "jobOperationToolId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationToolStep.jobOperationStepId": {
+ name: "jobOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.purchasingRfqLines": {
name: "purchasingRfqLines",
description: "purchasingRfqLines",
@@ -132598,6 +135057,27 @@ export default {
in: "query",
type: "string"
},
+ "body.jobMaterialStep": {
+ name: "jobMaterialStep",
+ description: "jobMaterialStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobMaterialStep"
+ }
+ },
+ "rowFilter.jobMaterialStep.jobMaterialId": {
+ name: "jobMaterialId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobMaterialStep.jobOperationStepId": {
+ name: "jobOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.consumables": {
name: "consumables",
description: "consumables",
@@ -133057,6 +135537,93 @@ export default {
in: "query",
type: "string"
},
+ "body.assemblyInstructionStepSlide": {
+ name: "assemblyInstructionStepSlide",
+ description: "assemblyInstructionStepSlide",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/assemblyInstructionStepSlide"
+ }
+ },
+ "rowFilter.assemblyInstructionStepSlide.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.stepId": {
+ name: "stepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.imagePath": {
+ name: "imagePath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.caption": {
+ name: "caption",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.annotations": {
+ name: "annotations",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepSlide.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.changeOrderType": {
name: "changeOrderType",
description: "changeOrderType",
@@ -133399,6 +135966,111 @@ export default {
in: "query",
type: "string"
},
+ "body.inspectionHistory": {
+ name: "inspectionHistory",
+ description: "inspectionHistory",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/inspectionHistory"
+ }
+ },
+ "rowFilter.inspectionHistory.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.supplierId": {
+ name: "supplierId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.samplingStandard": {
+ name: "samplingStandard",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.severity": {
+ name: "severity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.inspectionLevel": {
+ name: "inspectionLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.aql": {
+ name: "aql",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.lotSize": {
+ name: "lotSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.sampleSize": {
+ name: "sampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.defectsFound": {
+ name: "defectsFound",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.outcome": {
+ name: "outcome",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionHistory.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.customerLocation": {
name: "customerLocation",
description: "customerLocation",
@@ -133837,6 +136509,93 @@ export default {
in: "query",
type: "string"
},
+ "body.jobOperationStepSlide": {
+ name: "jobOperationStepSlide",
+ description: "jobOperationStepSlide",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobOperationStepSlide"
+ }
+ },
+ "rowFilter.jobOperationStepSlide.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.stepId": {
+ name: "stepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.imagePath": {
+ name: "imagePath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.caption": {
+ name: "caption",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.annotations": {
+ name: "annotations",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationStepSlide.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.nonConformanceSalesOrderLine": {
name: "nonConformanceSalesOrderLine",
description: "nonConformanceSalesOrderLine",
@@ -134848,69 +137607,6 @@ export default {
in: "query",
type: "string"
},
- "body.assemblyStandardNote": {
- name: "assemblyStandardNote",
- description: "assemblyStandardNote",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/assemblyStandardNote"
- }
- },
- "rowFilter.assemblyStandardNote.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.name": {
- name: "name",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.content": {
- name: "content",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.severity": {
- name: "severity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyStandardNote.updatedAt": {
- name: "updatedAt",
- required: false,
- in: "query",
- type: "string"
- },
"body.makeMethod": {
name: "makeMethod",
description: "makeMethod",
@@ -135697,87 +138393,6 @@ export default {
in: "query",
type: "string"
},
- "body.itemSamplingPlan": {
- name: "itemSamplingPlan",
- description: "itemSamplingPlan",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/itemSamplingPlan"
- }
- },
- "rowFilter.itemSamplingPlan.itemId": {
- name: "itemId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.type": {
- name: "type",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.sampleSize": {
- name: "sampleSize",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.percentage": {
- name: "percentage",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.aql": {
- name: "aql",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.inspectionLevel": {
- name: "inspectionLevel",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.severity": {
- name: "severity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.updatedAt": {
- name: "updatedAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.itemSamplingPlan.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
"body.purchaseOrderLocations": {
name: "purchaseOrderLocations",
description: "purchaseOrderLocations",
@@ -136396,6 +139011,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.productionQuantity.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.productionQuantity.inspectionSampleId": {
+ name: "inspectionSampleId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.implementationHub": {
name: "implementationHub",
description: "implementationHub",
@@ -136540,6 +139167,108 @@ export default {
in: "query",
type: "string"
},
+ "body.methodMaterialStep": {
+ name: "methodMaterialStep",
+ description: "methodMaterialStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/methodMaterialStep"
+ }
+ },
+ "rowFilter.methodMaterialStep.methodMaterialId": {
+ name: "methodMaterialId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodMaterialStep.methodOperationStepId": {
+ name: "methodOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "body.inspectionSample": {
+ name: "inspectionSample",
+ description: "inspectionSample",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/inspectionSample"
+ }
+ },
+ "rowFilter.inspectionSample.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.trackedEntityId": {
+ name: "trackedEntityId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.notes": {
+ name: "notes",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.inspectedBy": {
+ name: "inspectedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.inspectedAt": {
+ name: "inspectedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSample.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.nonConformanceActionTask": {
name: "nonConformanceActionTask",
description: "nonConformanceActionTask",
@@ -136645,6 +139374,93 @@ export default {
in: "query",
type: "string"
},
+ "body.quoteOperationStepSlide": {
+ name: "quoteOperationStepSlide",
+ description: "quoteOperationStepSlide",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/quoteOperationStepSlide"
+ }
+ },
+ "rowFilter.quoteOperationStepSlide.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.stepId": {
+ name: "stepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.imagePath": {
+ name: "imagePath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.caption": {
+ name: "caption",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.annotations": {
+ name: "annotations",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationStepSlide.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.supplierInteraction": {
name: "supplierInteraction",
description: "supplierInteraction",
@@ -137305,6 +140121,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteOperation.assemblyInstructionId": {
+ name: "assemblyInstructionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperation.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.notification": {
name: "notification",
description: "notification",
@@ -139813,6 +142641,63 @@ export default {
in: "query",
type: "string"
},
+ "body.itemInspectionDocumentAssignment": {
+ name: "itemInspectionDocumentAssignment",
+ description: "itemInspectionDocumentAssignment",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/itemInspectionDocumentAssignment"
+ }
+ },
+ "rowFilter.itemInspectionDocumentAssignment.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.usage": {
+ name: "usage",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemInspectionDocumentAssignment.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.fixedAssetClass": {
name: "fixedAssetClass",
description: "fixedAssetClass",
@@ -142699,6 +145584,27 @@ export default {
in: "query",
type: "string"
},
+ "body.quoteOperationToolStep": {
+ name: "quoteOperationToolStep",
+ description: "quoteOperationToolStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/quoteOperationToolStep"
+ }
+ },
+ "rowFilter.quoteOperationToolStep.quoteOperationToolId": {
+ name: "quoteOperationToolId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationToolStep.quoteOperationStepId": {
+ name: "quoteOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.salesOrderPayment": {
name: "salesOrderPayment",
description: "salesOrderPayment",
@@ -146220,111 +149126,6 @@ export default {
in: "query",
type: "string"
},
- "body.inboundInspectionHistory": {
- name: "inboundInspectionHistory",
- description: "inboundInspectionHistory",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/inboundInspectionHistory"
- }
- },
- "rowFilter.inboundInspectionHistory.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.inboundInspectionId": {
- name: "inboundInspectionId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.itemId": {
- name: "itemId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.supplierId": {
- name: "supplierId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.samplingStandard": {
- name: "samplingStandard",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.severity": {
- name: "severity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.inspectionLevel": {
- name: "inspectionLevel",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.aql": {
- name: "aql",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.lotSize": {
- name: "lotSize",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.sampleSize": {
- name: "sampleSize",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.defectsFound": {
- name: "defectsFound",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.outcome": {
- name: "outcome",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionHistory.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
"body.externalIntegrationMapping": {
name: "externalIntegrationMapping",
description: "externalIntegrationMapping",
@@ -149605,87 +152406,6 @@ export default {
in: "query",
type: "string"
},
- "body.inboundInspectionSample": {
- name: "inboundInspectionSample",
- description: "inboundInspectionSample",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/inboundInspectionSample"
- }
- },
- "rowFilter.inboundInspectionSample.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.inboundInspectionId": {
- name: "inboundInspectionId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.trackedEntityId": {
- name: "trackedEntityId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.status": {
- name: "status",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.notes": {
- name: "notes",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.inspectedBy": {
- name: "inspectedBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.inspectedAt": {
- name: "inspectedAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.updatedAt": {
- name: "updatedAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspectionSample.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
"body.exchangeRateHistory": {
name: "exchangeRateHistory",
description: "exchangeRateHistory",
@@ -150304,12 +153024,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.requiresInspection": {
- name: "requiresInspection",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.purchaseOrderLine.companyId": {
name: "companyId",
required: false,
@@ -150976,6 +153690,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.accountDefault.scrapAccount": {
+ name: "scrapAccount",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.warehouse": {
name: "warehouse",
description: "warehouse",
@@ -151408,6 +154128,27 @@ export default {
in: "query",
type: "string"
},
+ "body.methodOperationToolStep": {
+ name: "methodOperationToolStep",
+ description: "methodOperationToolStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/methodOperationToolStep"
+ }
+ },
+ "rowFilter.methodOperationToolStep.methodOperationToolId": {
+ name: "methodOperationToolId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationToolStep.methodOperationStepId": {
+ name: "methodOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.shippingMethod": {
name: "shippingMethod",
description: "shippingMethod",
@@ -152712,6 +155453,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobOperation.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.userAttributeCategory": {
name: "userAttributeCategory",
description: "userAttributeCategory",
@@ -156228,171 +158975,6 @@ export default {
in: "query",
type: "string"
},
- "body.inboundInspection": {
- name: "inboundInspection",
- description: "inboundInspection",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/inboundInspection"
- }
- },
- "rowFilter.inboundInspection.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.inboundInspectionId": {
- name: "inboundInspectionId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.receiptLineId": {
- name: "receiptLineId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.receiptId": {
- name: "receiptId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.itemId": {
- name: "itemId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.itemReadableId": {
- name: "itemReadableId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.supplierId": {
- name: "supplierId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.lotSize": {
- name: "lotSize",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.samplingStandard": {
- name: "samplingStandard",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.samplingPlanType": {
- name: "samplingPlanType",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.sampleSize": {
- name: "sampleSize",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.acceptanceNumber": {
- name: "acceptanceNumber",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.rejectionNumber": {
- name: "rejectionNumber",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.aql": {
- name: "aql",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.inspectionLevel": {
- name: "inspectionLevel",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.severity": {
- name: "severity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.codeLetter": {
- name: "codeLetter",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.status": {
- name: "status",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.notes": {
- name: "notes",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.dispositionedBy": {
- name: "dispositionedBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.dispositionedAt": {
- name: "dispositionedAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.updatedAt": {
- name: "updatedAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.inboundInspection.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
"body.userPermission": {
name: "userPermission",
description: "userPermission",
@@ -156690,6 +159272,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobOperationStep.assemblyInstructionStepId": {
+ name: "assemblyInstructionStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.purchasingRfqToSupplierQuote": {
name: "purchasingRfqToSupplierQuote",
description: "purchasingRfqToSupplierQuote",
@@ -157128,6 +159716,42 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.inspectionFeature.samplingPlanType": {
+ name: "samplingPlanType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionFeature.samplingSampleSize": {
+ name: "samplingSampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionFeature.samplingPercentage": {
+ name: "samplingPercentage",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionFeature.samplingAql": {
+ name: "samplingAql",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionFeature.samplingInspectionLevel": {
+ name: "samplingInspectionLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionFeature.samplingSeverity": {
+ name: "samplingSeverity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.warehouseTransfer": {
name: "warehouseTransfer",
description: "warehouseTransfer",
@@ -157683,6 +160307,42 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.inspectionDocument.samplingPlanType": {
+ name: "samplingPlanType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocument.samplingSampleSize": {
+ name: "samplingSampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocument.samplingPercentage": {
+ name: "samplingPercentage",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocument.samplingAql": {
+ name: "samplingAql",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocument.samplingInspectionLevel": {
+ name: "samplingInspectionLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocument.samplingSeverity": {
+ name: "samplingSeverity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.supplierQuote": {
name: "supplierQuote",
description: "supplierQuote",
@@ -158100,6 +160760,93 @@ export default {
in: "query",
type: "string"
},
+ "body.methodOperationStepSlide": {
+ name: "methodOperationStepSlide",
+ description: "methodOperationStepSlide",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/methodOperationStepSlide"
+ }
+ },
+ "rowFilter.methodOperationStepSlide.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.stepId": {
+ name: "stepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.imagePath": {
+ name: "imagePath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.caption": {
+ name: "caption",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.annotations": {
+ name: "annotations",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.methodOperationStepSlide.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.employee": {
name: "employee",
description: "employee",
@@ -159295,12 +162042,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.requiresInspection": {
- name: "requiresInspection",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.salesOrderLines.companyId": {
name: "companyId",
required: false,
@@ -159685,6 +162426,75 @@ export default {
in: "query",
type: "string"
},
+ "body.assemblyInstructionStepTool": {
+ name: "assemblyInstructionStepTool",
+ description: "assemblyInstructionStepTool",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/assemblyInstructionStepTool"
+ }
+ },
+ "rowFilter.assemblyInstructionStepTool.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.stepId": {
+ name: "stepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.assemblyInstructionStepTool.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.companyPlan": {
name: "companyPlan",
description: "companyPlan",
@@ -160489,105 +163299,6 @@ export default {
in: "query",
type: "string"
},
- "body.assemblyInstructionStepRequirement": {
- name: "assemblyInstructionStepRequirement",
- description: "assemblyInstructionStepRequirement",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/assemblyInstructionStepRequirement"
- }
- },
- "rowFilter.assemblyInstructionStepRequirement.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.stepId": {
- name: "stepId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.type": {
- name: "type",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.itemId": {
- name: "itemId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.name": {
- name: "name",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.text": {
- name: "text",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.severity": {
- name: "severity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.filePath": {
- name: "filePath",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.quantity": {
- name: "quantity",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.sortOrder": {
- name: "sortOrder",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.assemblyInstructionStepRequirement.updatedAt": {
- name: "updatedAt",
- required: false,
- in: "query",
- type: "string"
- },
"body.currency": {
name: "currency",
description: "currency",
@@ -164055,6 +166766,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.methodOperation.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.jobMaterial": {
name: "jobMaterial",
description: "jobMaterial",
@@ -164747,6 +167464,189 @@ export default {
in: "query",
type: "string"
},
+ "body.inspection": {
+ name: "inspection",
+ description: "inspection",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/inspection"
+ }
+ },
+ "rowFilter.inspection.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.itemReadableId": {
+ name: "itemReadableId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.supplierId": {
+ name: "supplierId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.lotSize": {
+ name: "lotSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.samplingStandard": {
+ name: "samplingStandard",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.samplingPlanType": {
+ name: "samplingPlanType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.sampleSize": {
+ name: "sampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.acceptanceNumber": {
+ name: "acceptanceNumber",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.rejectionNumber": {
+ name: "rejectionNumber",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.aql": {
+ name: "aql",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.inspectionLevel": {
+ name: "inspectionLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.severity": {
+ name: "severity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.codeLetter": {
+ name: "codeLetter",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.notes": {
+ name: "notes",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.dispositionedBy": {
+ name: "dispositionedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.dispositionedAt": {
+ name: "dispositionedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.sourceDocument": {
+ name: "sourceDocument",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.sourceDocumentId": {
+ name: "sourceDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.sourceDocumentLineId": {
+ name: "sourceDocumentLineId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspection.sourceDocumentReadableId": {
+ name: "sourceDocumentReadableId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.processes": {
name: "processes",
description: "processes",
@@ -165500,12 +168400,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.requiresInspection": {
- name: "requiresInspection",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.salesOrderLine.companyId": {
name: "companyId",
required: false,
@@ -166475,6 +169369,99 @@ export default {
in: "query",
type: "string"
},
+ "body.inspectionMeasurement": {
+ name: "inspectionMeasurement",
+ description: "inspectionMeasurement",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/inspectionMeasurement"
+ }
+ },
+ "rowFilter.inspectionMeasurement.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.inspectionSampleId": {
+ name: "inspectionSampleId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.inspectionFeatureId": {
+ name: "inspectionFeatureId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.value": {
+ name: "value",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.notes": {
+ name: "notes",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.inspectedBy": {
+ name: "inspectedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.inspectedAt": {
+ name: "inspectedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionMeasurement.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.externalLink": {
name: "externalLink",
description: "externalLink",
@@ -166823,6 +169810,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.methodOperationStep.assemblyInstructionStepId": {
+ name: "assemblyInstructionStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.tag": {
name: "tag",
description: "tag",
@@ -167378,6 +170371,27 @@ export default {
in: "query",
type: "string"
},
+ "body.quoteMaterialStep": {
+ name: "quoteMaterialStep",
+ description: "quoteMaterialStep",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/quoteMaterialStep"
+ }
+ },
+ "rowFilter.quoteMaterialStep.quoteMaterialId": {
+ name: "quoteMaterialId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteMaterialStep.quoteOperationStepId": {
+ name: "quoteOperationStepId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.nonConformanceSupplier": {
name: "nonConformanceSupplier",
description: "nonConformanceSupplier",
@@ -168047,6 +171061,87 @@ export default {
in: "query",
type: "string"
},
+ "body.inspectionSamplingPlan": {
+ name: "inspectionSamplingPlan",
+ description: "inspectionSamplingPlan",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/inspectionSamplingPlan"
+ }
+ },
+ "rowFilter.inspectionSamplingPlan.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.inspectionFeatureId": {
+ name: "inspectionFeatureId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.sampleSize": {
+ name: "sampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.acceptanceNumber": {
+ name: "acceptanceNumber",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.rejectionNumber": {
+ name: "rejectionNumber",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.codeLetter": {
+ name: "codeLetter",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionSamplingPlan.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.customerTax": {
name: "customerTax",
description: "customerTax",
@@ -168302,12 +171397,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.requiresInspection": {
- name: "requiresInspection",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.purchaseOrderLines.companyId": {
name: "companyId",
required: false,
@@ -170750,57 +173839,6 @@ export default {
in: "query",
type: "string"
},
- "body.nonConformanceInboundInspection": {
- name: "nonConformanceInboundInspection",
- description: "nonConformanceInboundInspection",
- required: false,
- in: "body",
- schema: {
- $ref: "#/definitions/nonConformanceInboundInspection"
- }
- },
- "rowFilter.nonConformanceInboundInspection.id": {
- name: "id",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.nonConformanceId": {
- name: "nonConformanceId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.inboundInspectionId": {
- name: "inboundInspectionId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.createdAt": {
- name: "createdAt",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.createdBy": {
- name: "createdBy",
- required: false,
- in: "query",
- type: "string"
- },
- "rowFilter.nonConformanceInboundInspection.updatedBy": {
- name: "updatedBy",
- required: false,
- in: "query",
- type: "string"
- },
"body.timeCardEntry": {
name: "timeCardEntry",
description: "timeCardEntry",
@@ -171539,12 +174577,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.item.requiresInspection": {
- name: "requiresInspection",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.item.sourcingType": {
name: "sourcingType",
required: false,
@@ -173972,6 +177004,57 @@ export default {
in: "query",
type: "string"
},
+ "body.nonConformanceInspection": {
+ name: "nonConformanceInspection",
+ description: "nonConformanceInspection",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/nonConformanceInspection"
+ }
+ },
+ "rowFilter.nonConformanceInspection.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.nonConformanceId": {
+ name: "nonConformanceId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.inspectionId": {
+ name: "inspectionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.nonConformanceInspection.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.maintenanceScheduleItem": {
name: "maintenanceScheduleItem",
description: "maintenanceScheduleItem",
@@ -175244,6 +178327,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.autoStartOperationTimer": {
+ name: "autoStartOperationTimer",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.plmReleaseControl": {
name: "plmReleaseControl",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 0ce13ad464..2b30aea54f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -373,6 +373,7 @@ export type Database = {
salesAccount: string
salesDiscountAccount: string
salesTaxPayableAccount: string
+ scrapAccount: string | null
serviceChargeAccount: string
subcontractingVarianceAccount: string
supplierPaymentDiscountAccount: string
@@ -426,6 +427,7 @@ export type Database = {
salesAccount: string
salesDiscountAccount: string
salesTaxPayableAccount: string
+ scrapAccount?: string | null
serviceChargeAccount: string
subcontractingVarianceAccount: string
supplierPaymentDiscountAccount: string
@@ -479,6 +481,7 @@ export type Database = {
salesAccount?: string
salesDiscountAccount?: string
salesTaxPayableAccount?: string
+ scrapAccount?: string | null
serviceChargeAccount?: string
subcontractingVarianceAccount?: string
supplierPaymentDiscountAccount?: string
@@ -1118,6 +1121,20 @@ export type Database = {
referencedRelation: "accounts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "accountDefault_scrapAccount_fkey"
+ columns: ["scrapAccount"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountDefault_scrapAccount_fkey"
+ columns: ["scrapAccount"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "accountDefault_serviceChargeAccount_fkey"
columns: ["serviceChargeAccount"]
@@ -3550,201 +3567,174 @@ export type Database = {
},
]
}
- assemblyInstructionStepRequirement: {
+ assemblyInstructionStepSlide: {
Row: {
+ annotations: Json
+ caption: string | null
companyId: string
createdAt: string
createdBy: string
- filePath: string | null
id: string
- itemId: string | null
- name: string | null
- quantity: number
- severity: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
sortOrder: number
stepId: string
- text: string | null
- type: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt: string | null
updatedBy: string | null
}
Insert: {
+ annotations?: Json
+ caption?: string | null
companyId: string
createdAt?: string
createdBy: string
- filePath?: string | null
id?: string
- itemId?: string | null
- name?: string | null
- quantity?: number
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
sortOrder?: number
stepId: string
- text?: string | null
- type: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
+ annotations?: Json
+ caption?: string | null
companyId?: string
createdAt?: string
createdBy?: string
- filePath?: string | null
id?: string
- itemId?: string | null
- name?: string | null
- quantity?: number
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
sortOrder?: number
stepId?: string
- text?: string | null
- type?: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "services"
+ referencedRelation: "modelUpload"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_stepId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_stepId_fkey"
columns: ["stepId"]
isOneToOne: false
referencedRelation: "assemblyInstructionStep"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -3752,265 +3742,317 @@ export type Database = {
},
]
}
- assemblyPlanJob: {
+ assemblyInstructionStepTool: {
Row: {
companyId: string
createdAt: string
createdBy: string
- error: string | null
id: string
- kind: string
- modelUploadId: string
- planPath: string | null
- stats: Json | null
- status: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId: string
+ quantity: number
+ sortOrder: number
+ stepId: string
updatedAt: string | null
+ updatedBy: string | null
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
- error?: string | null
id?: string
- kind: string
- modelUploadId: string
- planPath?: string | null
- stats?: Json | null
- status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId: string
+ quantity?: number
+ sortOrder?: number
+ stepId: string
updatedAt?: string | null
+ updatedBy?: string | null
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
- error?: string | null
id?: string
- kind?: string
- modelUploadId?: string
- planPath?: string | null
- stats?: Json | null
- status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId?: string
+ quantity?: number
+ sortOrder?: number
+ stepId?: string
updatedAt?: string | null
+ updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["modelId"]
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "modelUpload"
+ referencedRelation: "item"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "salesRfqLines"
- referencedColumns: ["modelId"]
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
},
]
}
- assemblyStandardNote: {
+ assemblyPlanJob: {
Row: {
companyId: string
- content: string
createdAt: string
createdBy: string
+ error: string | null
id: string
- name: string
- severity: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind: string
+ modelUploadId: string
+ planPath: string | null
+ stats: Json | null
+ status: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt: string | null
- updatedBy: string | null
}
Insert: {
companyId: string
- content: string
createdAt?: string
createdBy: string
+ error?: string | null
id?: string
- name: string
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind: string
+ modelUploadId: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt?: string | null
- updatedBy?: string | null
}
Update: {
companyId?: string
- content?: string
createdAt?: string
createdBy?: string
+ error?: string | null
id?: string
- name?: string
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind?: string
+ modelUploadId?: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt?: string | null
- updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "user"
+ referencedRelation: "modelUpload"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
},
]
}
@@ -6659,6 +6701,7 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
+ autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -6703,6 +6746,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -6747,6 +6791,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -16204,7 +16249,40 @@ export type Database = {
},
]
}
- inboundInspection: {
+ industry: {
+ Row: {
+ active: boolean
+ createdAt: string
+ description: string | null
+ iconName: string | null
+ id: string
+ name: string
+ sortOrder: number
+ updatedAt: string | null
+ }
+ Insert: {
+ active?: boolean
+ createdAt?: string
+ description?: string | null
+ iconName?: string | null
+ id: string
+ name: string
+ sortOrder?: number
+ updatedAt?: string | null
+ }
+ Update: {
+ active?: boolean
+ createdAt?: string
+ description?: string | null
+ iconName?: string | null
+ id?: string
+ name?: string
+ sortOrder?: number
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
+ inspection: {
Row: {
acceptanceNumber: number
aql: number | null
@@ -16215,20 +16293,23 @@ export type Database = {
dispositionedAt: string | null
dispositionedBy: string | null
id: string
- inboundInspectionId: string
+ inspectionDocumentId: string | null
+ inspectionId: string
inspectionLevel: Database["public"]["Enums"]["inspectionLevel"] | null
itemId: string
itemReadableId: string | null
lotSize: number
notes: string | null
- receiptId: string
- receiptLineId: string
rejectionNumber: number
sampleSize: number
samplingPlanType: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
severity: Database["public"]["Enums"]["inspectionSeverity"] | null
- status: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId: string
+ sourceDocumentLineId: string | null
+ sourceDocumentReadableId: string | null
+ status: Database["public"]["Enums"]["inspectionStatusType"]
supplierId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -16243,7 +16324,8 @@ export type Database = {
dispositionedAt?: string | null
dispositionedBy?: string | null
id?: string
- inboundInspectionId: string
+ inspectionDocumentId?: string | null
+ inspectionId: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16251,14 +16333,16 @@ export type Database = {
itemReadableId?: string | null
lotSize: number
notes?: string | null
- receiptId: string
- receiptLineId: string
rejectionNumber: number
sampleSize: number
samplingPlanType: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
severity?: Database["public"]["Enums"]["inspectionSeverity"] | null
- status?: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId: string
+ sourceDocumentLineId?: string | null
+ sourceDocumentReadableId?: string | null
+ status?: Database["public"]["Enums"]["inspectionStatusType"]
supplierId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -16273,7 +16357,8 @@ export type Database = {
dispositionedAt?: string | null
dispositionedBy?: string | null
id?: string
- inboundInspectionId?: string
+ inspectionDocumentId?: string | null
+ inspectionId?: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16281,14 +16366,16 @@ export type Database = {
itemReadableId?: string | null
lotSize?: number
notes?: string | null
- receiptId?: string
- receiptLineId?: string
rejectionNumber?: number
sampleSize?: number
samplingPlanType?: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
severity?: Database["public"]["Enums"]["inspectionSeverity"] | null
- status?: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument?: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId?: string
+ sourceDocumentLineId?: string | null
+ sourceDocumentReadableId?: string | null
+ status?: Database["public"]["Enums"]["inspectionStatusType"]
supplierId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -16392,6 +16479,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "inboundInspection_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspection_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "inboundInspection_itemId_fkey"
columns: ["itemId"]
@@ -16434,34 +16535,6 @@ export type Database = {
referencedRelation: "tools"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "inboundInspection_receiptId_fkey"
- columns: ["receiptId"]
- isOneToOne: false
- referencedRelation: "receipt"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptId_fkey"
- columns: ["receiptId"]
- isOneToOne: false
- referencedRelation: "receipts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptLineId_fkey"
- columns: ["receiptLineId"]
- isOneToOne: true
- referencedRelation: "receiptLine"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptLineId_fkey"
- columns: ["receiptLineId"]
- isOneToOne: true
- referencedRelation: "receiptLines"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "inboundInspection_supplierId_fkey"
columns: ["supplierId", "companyId"]
@@ -16520,7 +16593,476 @@ export type Database = {
},
]
}
- inboundInspectionHistory: {
+ inspectionDocument: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ defaultPageHeight: number | null
+ defaultPageWidth: number | null
+ drawingNumber: string | null
+ fileName: string | null
+ id: string
+ pageCount: number | null
+ partId: string
+ 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
+ uploadedBy: string | null
+ version: number
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ defaultPageHeight?: number | null
+ defaultPageWidth?: number | null
+ drawingNumber?: string | null
+ fileName?: string | null
+ id?: string
+ pageCount?: number | null
+ partId: string
+ 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
+ uploadedBy?: string | null
+ version?: number
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ defaultPageHeight?: number | null
+ defaultPageWidth?: number | null
+ drawingNumber?: string | null
+ fileName?: string | null
+ id?: string
+ pageCount?: number | null
+ partId?: string
+ 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
+ uploadedBy?: string | null
+ version?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ inspectionFeature: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: string | null
+ id: string
+ inspectionDocumentId: string
+ label: string
+ nominalValue: string | null
+ pageNumber: number
+ 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
+ toleranceMinus: string | null
+ tolerancePlus: string | null
+ type: Database["public"]["Enums"]["procedureStepType"]
+ unit: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: string | null
+ id?: string
+ inspectionDocumentId: string
+ label: string
+ nominalValue?: string | null
+ pageNumber: number
+ 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
+ toleranceMinus?: string | null
+ tolerancePlus?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unit?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: string | null
+ id?: string
+ inspectionDocumentId?: string
+ label?: string
+ nominalValue?: string | null
+ pageNumber?: number
+ 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
+ toleranceMinus?: string | null
+ tolerancePlus?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unit?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_document_company_fkey"
+ columns: ["inspectionDocumentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_document_company_fkey"
+ columns: ["inspectionDocumentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ inspectionHistory: {
Row: {
aql: number | null
companyId: string
@@ -16528,7 +17070,7 @@ export type Database = {
createdBy: string
defectsFound: number
id: string
- inboundInspectionId: string
+ inspectionId: string
inspectionLevel: Database["public"]["Enums"]["inspectionLevel"] | null
itemId: string
lotSize: number
@@ -16546,7 +17088,7 @@ export type Database = {
createdBy: string
defectsFound: number
id?: string
- inboundInspectionId: string
+ inspectionId: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16566,7 +17108,7 @@ export type Database = {
createdBy?: string
defectsFound?: number
id?: string
- inboundInspectionId?: string
+ inspectionId?: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16645,9 +17187,9 @@ export type Database = {
},
{
foreignKeyName: "inboundInspectionHistory_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
@@ -16750,192 +17292,205 @@ export type Database = {
},
]
}
- inboundInspectionSample: {
+ inspectionMeasurement: {
Row: {
companyId: string
createdAt: string
createdBy: string
id: string
- inboundInspectionId: string
inspectedAt: string | null
inspectedBy: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ inspectionSampleId: string
notes: string | null
- status: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId: string | null
+ status: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt: string | null
updatedBy: string | null
+ value: number | null
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
id?: string
- inboundInspectionId: string
inspectedAt?: string | null
inspectedBy?: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ inspectionSampleId: string
notes?: string | null
- status?: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt?: string | null
updatedBy?: string | null
+ value?: number | null
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
id?: string
- inboundInspectionId?: string
inspectedAt?: string | null
inspectedBy?: string | null
+ inspectionFeatureId?: string
+ inspectionId?: string
+ inspectionSampleId?: string
notes?: string | null
- status?: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt?: string | null
updatedBy?: string | null
+ value?: number | null
}
Relationships: [
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inboundInspectionSample_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ foreignKeyName: "inboundInspectionMeasurement_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inboundInspectionSample_trackedEntityId_fkey"
- columns: ["trackedEntityId"]
+ foreignKeyName: "inboundInspectionMeasurement_inspectionFeatureId_fkey"
+ columns: ["inspectionFeatureId"]
isOneToOne: false
- referencedRelation: "trackedEntity"
+ referencedRelation: "inspectionFeature"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_sampleId_fkey"
+ columns: ["inspectionSampleId"]
+ isOneToOne: false
+ referencedRelation: "inspectionSample"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -16943,429 +17498,350 @@ export type Database = {
},
]
}
- industry: {
- Row: {
- active: boolean
- createdAt: string
- description: string | null
- iconName: string | null
- id: string
- name: string
- sortOrder: number
- updatedAt: string | null
- }
- Insert: {
- active?: boolean
- createdAt?: string
- description?: string | null
- iconName?: string | null
- id: string
- name: string
- sortOrder?: number
- updatedAt?: string | null
- }
- Update: {
- active?: boolean
- createdAt?: string
- description?: string | null
- iconName?: string | null
- id?: string
- name?: string
- sortOrder?: number
- updatedAt?: string | null
- }
- Relationships: []
- }
- inspectionDocument: {
+ inspectionSample: {
Row: {
companyId: string
createdAt: string
createdBy: string
- defaultPageHeight: number | null
- defaultPageWidth: number | null
- drawingNumber: string | null
- fileName: string | null
id: string
- pageCount: number | null
- partId: string
- storagePath: string | null
+ inspectedAt: string | null
+ inspectedBy: string | null
+ inspectionId: string
+ notes: string | null
+ status: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId: string | null
updatedAt: string | null
updatedBy: string | null
- uploadedBy: string | null
- version: number
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
- defaultPageHeight?: number | null
- defaultPageWidth?: number | null
- drawingNumber?: string | null
- fileName?: string | null
id?: string
- pageCount?: number | null
- partId: string
- storagePath?: string | null
+ inspectedAt?: string | null
+ inspectedBy?: string | null
+ inspectionId: string
+ notes?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
- uploadedBy?: string | null
- version?: number
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
- defaultPageHeight?: number | null
- defaultPageWidth?: number | null
- drawingNumber?: string | null
- fileName?: string | null
id?: string
- pageCount?: number | null
- partId?: string
- storagePath?: string | null
+ inspectedAt?: string | null
+ inspectedBy?: string | null
+ inspectionId?: string
+ notes?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
- uploadedBy?: string | null
- version?: number
}
Relationships: [
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
+ foreignKeyName: "inboundInspectionSample_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "tools"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_trackedEntityId_fkey"
+ columns: ["trackedEntityId"]
+ isOneToOne: false
+ referencedRelation: "trackedEntity"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
]
}
- inspectionFeature: {
+ inspectionSamplingPlan: {
Row: {
+ acceptanceNumber: number
+ codeLetter: string | null
companyId: string
createdAt: string
createdBy: string
- description: string | null
id: string
- inspectionDocumentId: string
- label: string
- nominalValue: string | null
- pageNumber: number
- toleranceMinus: string | null
- tolerancePlus: string | null
- type: Database["public"]["Enums"]["procedureStepType"]
- unit: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ rejectionNumber: number
+ sampleSize: number
updatedAt: string | null
updatedBy: string | null
}
Insert: {
+ acceptanceNumber: number
+ codeLetter?: string | null
companyId: string
createdAt?: string
createdBy: string
- description?: string | null
id?: string
- inspectionDocumentId: string
- label: string
- nominalValue?: string | null
- pageNumber: number
- toleranceMinus?: string | null
- tolerancePlus?: string | null
- type?: Database["public"]["Enums"]["procedureStepType"]
- unit?: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ rejectionNumber: number
+ sampleSize: number
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
+ acceptanceNumber?: number
+ codeLetter?: string | null
companyId?: string
createdAt?: string
createdBy?: string
- description?: string | null
id?: string
- inspectionDocumentId?: string
- label?: string
- nominalValue?: string | null
- pageNumber?: number
- toleranceMinus?: string | null
- tolerancePlus?: string | null
- type?: Database["public"]["Enums"]["procedureStepType"]
- unit?: string | null
+ inspectionFeatureId?: string
+ inspectionId?: string
+ rejectionNumber?: number
+ sampleSize?: number
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionFeature_document_company_fkey"
- columns: ["inspectionDocumentId", "companyId"]
+ foreignKeyName: "inboundInspectionFeature_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inspectionDocument"
- referencedColumns: ["id", "companyId"]
+ referencedRelation: "inspection"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_document_company_fkey"
- columns: ["inspectionDocumentId", "companyId"]
+ foreignKeyName: "inboundInspectionFeature_inspectionFeatureId_fkey"
+ columns: ["inspectionFeatureId"]
isOneToOne: false
- referencedRelation: "inspectionDocuments"
- referencedColumns: ["id", "companyId"]
+ referencedRelation: "inspectionFeature"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -18387,7 +18863,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string | null
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string | null
revisionStatus: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -18417,7 +18892,6 @@ export type Database = {
readableId: string
readableIdWithRevision?: string | null
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection?: boolean
revision?: string | null
revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType?: Database["public"]["Enums"]["sourcingType"]
@@ -18447,7 +18921,6 @@ export type Database = {
readableId?: string
readableIdWithRevision?: string | null
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection?: boolean
revision?: string | null
revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType?: Database["public"]["Enums"]["sourcingType"]
@@ -18832,6 +19305,194 @@ export type Database = {
},
]
}
+ itemInspectionDocumentAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ inspectionDocumentId: string
+ itemId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ usage: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ inspectionDocumentId: string
+ itemId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ usage: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ inspectionDocumentId?: string
+ itemId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ usage?: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemLedger: {
Row: {
comment: string | null
@@ -19665,192 +20326,6 @@ export type Database = {
},
]
}
- itemSamplingPlan: {
- Row: {
- aql: number | null
- companyId: string
- createdAt: string
- createdBy: string
- inspectionLevel: Database["public"]["Enums"]["inspectionLevel"]
- itemId: string
- percentage: number | null
- sampleSize: number | null
- severity: Database["public"]["Enums"]["inspectionSeverity"]
- type: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- aql?: number | null
- companyId: string
- createdAt?: string
- createdBy: string
- inspectionLevel?: Database["public"]["Enums"]["inspectionLevel"]
- itemId: string
- percentage?: number | null
- sampleSize?: number | null
- severity?: Database["public"]["Enums"]["inspectionSeverity"]
- type?: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- aql?: number | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- inspectionLevel?: Database["public"]["Enums"]["inspectionLevel"]
- itemId?: string
- percentage?: number | null
- sampleSize?: number | null
- severity?: Database["public"]["Enums"]["inspectionSeverity"]
- type?: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
itemShelfLife: {
Row: {
calculateFromBom: boolean
@@ -21522,6 +21997,50 @@ export type Database = {
},
]
}
+ jobMaterialStep: {
+ Row: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Insert: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Update: {
+ jobMaterialId?: string
+ jobOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -21535,6 +22054,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string
+ inspectionDocumentId: string | null
jobId: string
jobMakeMethodId: string | null
laborRate: number
@@ -21583,6 +22103,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string
+ inspectionDocumentId?: string | null
jobId: string
jobMakeMethodId?: string | null
laborRate?: number
@@ -21631,6 +22152,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string
+ inspectionDocumentId?: string | null
jobId?: string
jobMakeMethodId?: string | null
laborRate?: number
@@ -21773,6 +22295,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -22303,6 +22839,7 @@ export type Database = {
}
jobOperationStep: {
Row: {
+ assemblyInstructionStepId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -22324,6 +22861,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ assemblyInstructionStepId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -22345,6 +22883,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ assemblyInstructionStepId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -22457,6 +22996,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperationStep_assemblyInstructionStepId_fkey"
+ columns: ["assemblyInstructionStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperationStep_nonConformanceActionId_fkey"
columns: ["nonConformanceActionId"]
@@ -22659,6 +23205,181 @@ export type Database = {
},
]
}
+ jobOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobOperationTool: {
Row: {
companyId: string
@@ -22857,6 +23578,36 @@ export type Database = {
},
]
}
+ jobOperationToolStep: {
+ Row: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Insert: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Update: {
+ jobOperationStepId?: string
+ jobOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
+ columns: ["jobOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
journal: {
Row: {
accountingPeriodId: string | null
@@ -27224,6 +27975,36 @@ export type Database = {
},
]
}
+ methodMaterialStep: {
+ Row: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Insert: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Update: {
+ methodMaterialId?: string
+ methodOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
+ columns: ["methodMaterialId"]
+ isOneToOne: false
+ referencedRelation: "methodMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -27233,6 +28014,7 @@ export type Database = {
customFields: Json | null
description: string
id: string
+ inspectionDocumentId: string | null
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
machineTime: number
@@ -27263,6 +28045,7 @@ export type Database = {
customFields?: Json | null
description: string
id?: string
+ inspectionDocumentId?: string | null
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
@@ -27293,6 +28076,7 @@ export type Database = {
customFields?: Json | null
description?: string
id?: string
+ inspectionDocumentId?: string | null
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
@@ -27386,6 +28170,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "methodOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperation_methodId_fkey"
columns: ["makeMethodId"]
@@ -27637,6 +28435,7 @@ export type Database = {
}
methodOperationStep: {
Row: {
+ assemblyInstructionStepId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -27656,6 +28455,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ assemblyInstructionStepId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -27675,6 +28475,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ assemblyInstructionStepId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -27771,6 +28572,188 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "methodOperationStep_assemblyInstructionStepId_fkey"
+ columns: ["assemblyInstructionStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ methodOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
methodOperationTool: {
@@ -27957,6 +28940,36 @@ export type Database = {
},
]
}
+ methodOperationToolStep: {
+ Row: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Insert: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Update: {
+ methodOperationStepId?: string
+ methodOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
+ columns: ["methodOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -29154,13 +30167,13 @@ export type Database = {
},
]
}
- nonConformanceInboundInspection: {
+ nonConformanceInspection: {
Row: {
companyId: string
createdAt: string
createdBy: string
id: string
- inboundInspectionId: string
+ inspectionId: string
nonConformanceId: string
updatedBy: string | null
}
@@ -29169,7 +30182,7 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
- inboundInspectionId: string
+ inspectionId: string
nonConformanceId: string
updatedBy?: string | null
}
@@ -29178,7 +30191,7 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
- inboundInspectionId?: string
+ inspectionId?: string
nonConformanceId?: string
updatedBy?: string | null
}
@@ -29248,9 +30261,9 @@ export type Database = {
},
{
foreignKeyName: "nonConformanceInboundInspection_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
@@ -35531,7 +36544,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id: string
name: string
- processType: Database["public"]["Enums"]["processType"]
+ processType: Database["public"]["Enums"]["operationType"]
tags: string[] | null
updatedAt: string | null
updatedBy: string | null
@@ -35546,7 +36559,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id?: string
name: string
- processType?: Database["public"]["Enums"]["processType"]
+ processType?: Database["public"]["Enums"]["operationType"]
tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
@@ -35561,7 +36574,7 @@ export type Database = {
defaultStandardFactor?: Database["public"]["Enums"]["factor"]
id?: string
name?: string
- processType?: Database["public"]["Enums"]["processType"]
+ processType?: Database["public"]["Enums"]["operationType"]
tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
@@ -35910,6 +36923,8 @@ export type Database = {
createdAt: string
createdBy: string
id: string
+ inspectionId: string | null
+ inspectionSampleId: string | null
jobOperationId: string
laborProductionEventId: string | null
machineProductionEventId: string | null
@@ -35926,6 +36941,8 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
+ inspectionId?: string | null
+ inspectionSampleId?: string | null
jobOperationId: string
laborProductionEventId?: string | null
machineProductionEventId?: string | null
@@ -35942,6 +36959,8 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
+ inspectionId?: string | null
+ inspectionSampleId?: string | null
jobOperationId?: string
laborProductionEventId?: string | null
machineProductionEventId?: string | null
@@ -35982,6 +37001,20 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "productionQuantity_inspectionId_fkey"
+ columns: ["inspectionId"]
+ isOneToOne: false
+ referencedRelation: "inspection"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_inspectionSampleId_fkey"
+ columns: ["inspectionSampleId"]
+ isOneToOne: false
+ referencedRelation: "inspectionSample"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "productionQuantity_jobOperationId_fkey"
columns: ["jobOperationId"]
@@ -37676,7 +38709,6 @@ export type Database = {
receivedComplete: boolean
receivedDate: string | null
requiredDate: string | null
- requiresInspection: boolean
setupPrice: number | null
shippingCost: number | null
sortOrder: number
@@ -37729,7 +38761,6 @@ export type Database = {
receivedComplete?: boolean
receivedDate?: string | null
requiredDate?: string | null
- requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
sortOrder?: number
@@ -37782,7 +38813,6 @@ export type Database = {
receivedComplete?: boolean
receivedDate?: string | null
requiredDate?: string | null
- requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
sortOrder?: number
@@ -41144,14 +42174,53 @@ export type Database = {
},
]
}
+ quoteMaterialStep: {
+ Row: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Insert: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Update: {
+ quoteMaterialId?: string
+ quoteOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quoteOperation: {
Row: {
+ assemblyInstructionId: string | null
companyId: string
createdAt: string
createdBy: string
customFields: Json | null
description: string | null
id: string
+ inspectionDocumentId: string | null
laborRate: number
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
@@ -41180,12 +42249,14 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
companyId: string
createdAt?: string
createdBy: string
customFields?: Json | null
description?: string | null
id?: string
+ inspectionDocumentId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
@@ -41214,12 +42285,14 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
customFields?: Json | null
description?: string | null
id?: string
+ inspectionDocumentId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
@@ -41248,6 +42321,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_companyId_fkey"
columns: ["companyId"]
@@ -41311,6 +42391,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
columns: ["operationSupplierProcessId"]
@@ -41740,6 +42834,181 @@ export type Database = {
},
]
}
+ quoteOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
quoteOperationTool: {
Row: {
companyId: string
@@ -41931,6 +43200,36 @@ export type Database = {
},
]
}
+ quoteOperationToolStep: {
+ Row: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Insert: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Update: {
+ quoteOperationStepId?: string
+ quoteOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
+ columns: ["quoteOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quotePayment: {
Row: {
companyId: string
@@ -44526,7 +45825,6 @@ export type Database = {
quantitySent: number | null
quantityToInvoice: number | null
quantityToSend: number | null
- requiresInspection: boolean
saleQuantity: number | null
salesOrderId: string
salesOrderLineType: Database["public"]["Enums"]["salesOrderLineType"]
@@ -44573,7 +45871,6 @@ export type Database = {
quantitySent?: number | null
quantityToInvoice?: number | null
quantityToSend?: number | null
- requiresInspection?: boolean
saleQuantity?: number | null
salesOrderId: string
salesOrderLineType: Database["public"]["Enums"]["salesOrderLineType"]
@@ -44620,7 +45917,6 @@ export type Database = {
quantitySent?: number | null
quantityToInvoice?: number | null
quantityToSend?: number | null
- requiresInspection?: boolean
saleQuantity?: number | null
salesOrderId?: string
salesOrderLineType?: Database["public"]["Enums"]["salesOrderLineType"]
@@ -63692,7 +64988,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"] | null
id: string | null
name: string | null
- processType: Database["public"]["Enums"]["processType"] | null
+ processType: Database["public"]["Enums"]["operationType"] | null
suppliers: Json | null
tags: string[] | null
updatedAt: string | null
@@ -64490,7 +65786,6 @@ export type Database = {
receivedComplete: boolean | null
receivedDate: string | null
requiredDate: string | null
- requiresInspection: boolean | null
setupPrice: number | null
shippingCost: number | null
sortOrder: number | null
@@ -64832,14 +66127,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -68225,14 +69520,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -68554,7 +69849,6 @@ export type Database = {
quantitySent: number | null
quantityToInvoice: number | null
quantityToSend: number | null
- requiresInspection: boolean | null
saleQuantity: number | null
salesOrderId: string | null
salesOrderLineType:
@@ -68780,14 +70074,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72598,7 +73892,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
supplierIds: string
@@ -72958,6 +74251,7 @@ export type Database = {
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationType: Database["public"]["Enums"]["operationType"]
parentMaterialId: string
processId: string
quantityComplete: number
@@ -73183,7 +74477,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
supplierIds: string
@@ -73225,6 +74518,7 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
+ methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -73304,7 +74598,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -73821,7 +75114,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -73873,7 +75165,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -74578,13 +75869,6 @@ export type Database = {
approvalDocumentType: "purchaseOrder" | "qualityDocument" | "supplier"
approvalStatus: "Pending" | "Approved" | "Rejected" | "Cancelled"
assemblyInstructionStatus: "Draft" | "Published" | "Archived"
- assemblyNoteSeverity: "Info" | "Caution" | "Warning"
- assemblyRequirementType:
- | "Tool"
- | "Fixture"
- | "Consumable"
- | "Note"
- | "Media"
assemblyStepStatus: "Todo" | "Review" | "Done"
changeOrderChangeType:
| "Version"
@@ -74751,13 +76035,6 @@ export type Database = {
| "complete"
| "archived"
implementationTier: "self_serve" | "guided" | "enterprise"
- inboundInspectionSampleStatus: "Pending" | "Passed" | "Failed"
- inboundInspectionStatus:
- | "Pending"
- | "In Progress"
- | "Passed"
- | "Failed"
- | "Partial"
incoterm:
| "EXW"
| "FCA"
@@ -74770,9 +76047,18 @@ export type Database = {
| "DAP"
| "DPU"
| "DDP"
+ inspectionDocumentUsage: "Receipt"
inspectionLevel: "I" | "II" | "III" | "S1" | "S2" | "S3" | "S4"
+ inspectionSampleStatusType: "Pending" | "Passed" | "Failed"
inspectionSeverity: "Normal" | "Tightened" | "Reduced"
+ inspectionSourceDocument: "Receipt" | "Job Operation"
inspectionStatus: "Pass" | "Fail"
+ inspectionStatusType:
+ | "Pending"
+ | "In Progress"
+ | "Passed"
+ | "Failed"
+ | "Partial"
inventoryCountStatus: "Draft" | "Pending" | "Posted"
itemCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO"
itemLedgerDocumentType:
@@ -74870,6 +76156,8 @@ export type Database = {
| "Payment"
| "Credit Memo"
| "Debit Memo"
+ | "Non-Conformance"
+ | "Inbound Inspection"
journalEntryStatus: "Draft" | "Posted" | "Reversed"
journalLineDocumentType:
| "Receipt"
@@ -74891,6 +76179,8 @@ export type Database = {
| "Memo"
| "Inventory Adjustment"
| "Inventory Count"
+ | "Non-Conformance"
+ | "Inbound Inspection"
kanbanOutput: "label" | "qrcode" | "url"
macrsConvention: "Half-Year" | "Mid-Quarter"
macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"
@@ -74975,7 +76265,11 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
- operationType: "Inside" | "Outside"
+ operationType:
+ | "Process"
+ | "Assembly"
+ | "Inspection"
+ | "Outside Processing"
payableLineType:
| "Comment"
| "G/L Account"
@@ -75007,7 +76301,6 @@ export type Database = {
| "File"
| "Task"
| "Inspection"
- processType: "Inside" | "Outside" | "Inside and Outside"
productionEventType: "Setup" | "Labor" | "Machine"
productionQuantityType: "Rework" | "Scrap" | "Production"
purchaseInvoiceStatus:
@@ -75925,14 +77218,6 @@ export const Constants = {
approvalDocumentType: ["purchaseOrder", "qualityDocument", "supplier"],
approvalStatus: ["Pending", "Approved", "Rejected", "Cancelled"],
assemblyInstructionStatus: ["Draft", "Published", "Archived"],
- assemblyNoteSeverity: ["Info", "Caution", "Warning"],
- assemblyRequirementType: [
- "Tool",
- "Fixture",
- "Consumable",
- "Note",
- "Media",
- ],
assemblyStepStatus: ["Todo", "Review", "Done"],
changeOrderChangeType: [
"Version",
@@ -76117,14 +77402,6 @@ export const Constants = {
"archived",
],
implementationTier: ["self_serve", "guided", "enterprise"],
- inboundInspectionSampleStatus: ["Pending", "Passed", "Failed"],
- inboundInspectionStatus: [
- "Pending",
- "In Progress",
- "Passed",
- "Failed",
- "Partial",
- ],
incoterm: [
"EXW",
"FCA",
@@ -76138,9 +77415,19 @@ export const Constants = {
"DPU",
"DDP",
],
+ inspectionDocumentUsage: ["Receipt"],
inspectionLevel: ["I", "II", "III", "S1", "S2", "S3", "S4"],
+ inspectionSampleStatusType: ["Pending", "Passed", "Failed"],
inspectionSeverity: ["Normal", "Tightened", "Reduced"],
+ inspectionSourceDocument: ["Receipt", "Job Operation"],
inspectionStatus: ["Pass", "Fail"],
+ inspectionStatusType: [
+ "Pending",
+ "In Progress",
+ "Passed",
+ "Failed",
+ "Partial",
+ ],
inventoryCountStatus: ["Draft", "Pending", "Posted"],
itemCostingMethod: ["Standard", "Average", "LIFO", "FIFO"],
itemLedgerDocumentType: [
@@ -76245,6 +77532,8 @@ export const Constants = {
"Payment",
"Credit Memo",
"Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection",
],
journalEntryStatus: ["Draft", "Posted", "Reversed"],
journalLineDocumentType: [
@@ -76267,6 +77556,8 @@ export const Constants = {
"Memo",
"Inventory Adjustment",
"Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection",
],
kanbanOutput: ["label", "qrcode", "url"],
macrsConvention: ["Half-Year", "Mid-Quarter"],
@@ -76361,7 +77652,12 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
- operationType: ["Inside", "Outside"],
+ operationType: [
+ "Process",
+ "Assembly",
+ "Inspection",
+ "Outside Processing",
+ ],
payableLineType: [
"Comment",
"G/L Account",
@@ -76395,7 +77691,6 @@ export const Constants = {
"Task",
"Inspection",
],
- processType: ["Inside", "Outside", "Inside and Outside"],
productionEventType: ["Setup", "Labor", "Machine"],
productionQuantityType: ["Rework", "Scrap", "Production"],
purchaseInvoiceStatus: [
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 7369856755..cc9e1be8fa 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -201,6 +201,11 @@ enabled = true
verify_jwt = true
entrypoint = "./functions/post-inventory-adjustment/index.ts"
+[functions.post-nonconformance]
+enabled = true
+verify_jwt = true
+entrypoint = "./functions/post-nonconformance/index.ts"
+
[functions.transcription]
enabled = true
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index f78189dbe5..3ae4ac0133 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -419,7 +419,7 @@ serve(async (req: Request) => {
if (jobOperations.error) throw new Error(jobOperations.error.message);
const outsideOperations = jobOperations.data?.filter(
- (d) => d.operationType === "Outside"
+ (d) => d.operationType === "Outside Processing"
);
if (outsideOperations.length > 0) {
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index ce3cb1b3e1..b974f7fe5c 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -42,6 +42,82 @@ import {
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
+// Stored configurator rules are user-authored JS that may still return legacy "Inside"/"Outside" operationType values.
+const normalizeOperationType = (value: unknown) =>
+ (value === "Inside"
+ ? "Process"
+ : value === "Outside"
+ ? "Outside Processing"
+ : value) as Database["public"]["Enums"]["operationType"];
+
+// Copy an operation step's reference slides (grandchild) when a method/job/quote is
+// copied. Source slides are queried by their (old) step ids and remapped onto the freshly
+// inserted step ids — a bulk insert preserves order, so insertedStepIds[i] ↔ sourceSteps[i].
+// Guarded: a no-op when there are no slides, so it can never break step copying.
+// See .ai/specs/2026-07-14-mes-execution-views.md §4.
+async function copyStepSlides(
+ trx: Transaction<DB>,
+ client: SupabaseClient<Database>,
+ sourceSteps: Array<{ id?: string | null }>,
+ insertedStepIds: Array<{ id: string }>,
+ sourceTable:
+ | "methodOperationStepSlide"
+ | "jobOperationStepSlide"
+ | "quoteOperationStepSlide",
+ targetTable:
+ | "methodOperationStepSlide"
+ | "jobOperationStepSlide"
+ | "quoteOperationStepSlide",
+ companyId: string,
+ userId: string,
+) {
+ const sourceStepIds = sourceSteps
+ .map((s) => s.id)
+ .filter((id): id is string => !!id);
+ if (sourceStepIds.length === 0) return;
+
+ const { data: srcSlides } = await client
+ .from(sourceTable)
+ .select(
+ "stepId, imagePath, modelUploadId, caption, sortOrder, size, annotations",
+ )
+ .in("stepId", sourceStepIds);
+
+ const inserts = (srcSlides ?? []).flatMap((sl) => {
+ const idx = sourceSteps.findIndex((s) => s.id === sl.stepId);
+ const newStepId = insertedStepIds[idx]?.id;
+ if (!newStepId) return [];
+ return [{
+ stepId: newStepId,
+ imagePath: sl.imagePath,
+ modelUploadId: sl.modelUploadId,
+ caption: sl.caption,
+ sortOrder: sl.sortOrder,
+ size: sl.size,
+ annotations: sl.annotations,
+ companyId,
+ createdBy: userId,
+ }];
+ });
+
+ if (inserts.length > 0) {
+ // deno-lint-ignore no-explicit-any
+ await trx.insertInto(targetTable as any).values(inserts as any).execute();
+ }
+}
+
+// Many-to-many step links (Phase 2): remap a parent's OLD operation-step ids onto the freshly
+// inserted step ids via stepMap, dropping any that don't map. Empty in = the parent applies to
+// the whole operation (no join rows, shown on every step in the MES).
+function remapStepIds(
+ oldIds: Array<string | null | undefined> | null | undefined,
+ stepMap: Record<string, string>,
+): string[] {
+ return (oldIds ?? []).flatMap((id) =>
+ id && stepMap[id] ? [stepMap[id]] : []
+ );
+}
+
const partsValidator = z.object({
billOfMaterial: z.boolean().default(true),
billOfProcess: z.boolean().default(true),
@@ -279,10 +355,13 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops inherit steps from the linked instruction —
+ // never copy (possibly stale) template steps alongside it.
+ !operation.assemblyInstructionId &&
Array.isArray(methodOperationStep) &&
methodOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("methodOperationStep")
.values(
methodOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -293,7 +372,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "methodOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -309,6 +400,13 @@ serve(async (req: Request) => {
}
const itemId = sourceId;
const isConfigured = !!configuration;
+ // Assembly ops whose steps were materialized from an instruction —
+ // their material ↔ step links are flushed after the traversal has
+ // inserted every node's jobMaterial rows.
+ const assemblyOperationsToLink: Array<{
+ operationId: string;
+ assemblyInstructionId: string;
+ }> = [];
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses, job] =
await Promise.all([
@@ -538,13 +636,15 @@ serve(async (req: Request) => {
}:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
let methodOperationsToJobOperations: Record<string, string> = {};
+ // method step id -> new job step id, for copying the part ↔ step link (Phase 2)
+ const methodStepsToJobSteps: Record<string, string> = {};
// For child nodes, always include operations regardless of parts flags
if (!node.data.isRoot || parts.billOfProcess) {
const relatedOperations = await client
.from("methodOperation")
.select(
- "*, methodOperationTool(*), methodOperationParameter(*), methodOperationStep(*)"
+ "*, methodOperationTool(*, methodOperationToolStep(*)), methodOperationParameter(*), methodOperationStep(*)"
)
.eq("makeMethodId", node.data.materialMakeMethodId);
@@ -645,7 +745,11 @@ serve(async (req: Request) => {
...getLaborAndOverheadRates(processId, op.workCenterId),
order: op.order,
operationOrder,
- operationType,
+ operationType: normalizeOperationType(operationType),
+ // Carry the Assembly → BOP sync link so the MES can drive the
+ // animated instruction player on jobs made from a synced method.
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
operationSupplierProcessId: op.operationSupplierProcessId,
...getOutsideOperationRates(
processId,
@@ -707,24 +811,11 @@ serve(async (req: Request) => {
procedureId,
} = operation;
- if (
- (!node.data.isRoot || parts.tools) &&
- Array.isArray(methodOperationTool) &&
- methodOperationTool.length > 0
- ) {
- await trx
- .insertInto("jobOperationTool")
- .values(
- methodOperationTool.map((tool) => ({
- toolId: tool.toolId,
- quantity: tool.quantity,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ // Tool ids already inserted by the assembly-instruction
+ // copy — the method tool copy below must skip these or the
+ // job gets the same tool twice (once step-linked, once
+ // unlinked → the MES shows it on every step AND its step).
+ let assemblyToolIds: Set<string> = new Set();
if (procedureId) {
await insertProcedureDataForJobOperation(trx, client, {
@@ -759,7 +850,27 @@ serve(async (req: Request) => {
.execute();
}
- if (
+ if (operation.assemblyInstructionId) {
+ // Assembly ops inherit their steps from the linked
+ // instruction (the method only carries the pointer);
+ // material ↔ step links are flushed after the
+ // jobMaterial rows exist.
+ assemblyToolIds = await insertAssemblyDataForJobOperation(
+ trx,
+ client,
+ {
+ operationId,
+ assemblyInstructionId:
+ operation.assemblyInstructionId,
+ companyId,
+ userId,
+ }
+ );
+ assemblyOperationsToLink.push({
+ operationId,
+ assemblyInstructionId: operation.assemblyInstructionId,
+ });
+ } else if (
(!node.data.isRoot || parts.steps) &&
Array.isArray(methodOperationStep) &&
methodOperationStep.length > 0
@@ -786,9 +897,82 @@ serve(async (req: Request) => {
)
);
- await trx
+ const insertedSteps = await trx
.insertInto("jobOperationStep")
.values(attributes)
+ .returning(["id"])
+ .execute();
+
+ // Bulk insert preserves order, so insertedSteps[i] ↔
+ // methodOperationStep[i]: record each method step -> new job step so
+ // materials can carry the part ↔ step link onto the job (Phase 2).
+ (methodOperationStep as Array<{ id?: string }>).forEach(
+ (s, i) => {
+ const newStepId = insertedSteps[i]?.id;
+ if (s?.id && newStepId)
+ methodStepsToJobSteps[s.id] = newStepId;
+ }
+ );
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "jobOperationStepSlide",
+ companyId,
+ userId,
+ );
+ }
+ }
+
+ // Tools after steps (Phase 2): the method-step -> job-step map is now
+ // populated, so a tool scoped to steps carries those links onto the job via
+ // jobOperationToolStep. Mirrors the material part ↔ step copy above. Tools
+ // the assembly-instruction copy already inserted are skipped (see above).
+ const toolsToCopy = (
+ Array.isArray(methodOperationTool) ? methodOperationTool : []
+ ).filter((tool: { toolId: string }) => !assemblyToolIds.has(tool.toolId));
+ if (
+ (!node.data.isRoot || parts.tools) &&
+ toolsToCopy.length > 0
+ ) {
+ const insertedTools = await trx
+ .insertInto("jobOperationTool")
+ .values(
+ toolsToCopy.map((tool) => ({
+ toolId: tool.toolId,
+ quantity: tool.quantity,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .returning(["id"])
+ .execute();
+
+ // Tool ↔ step links (Phase 2, many-to-many). Bulk insert preserves order,
+ // so insertedTools[i] ↔ toolsToCopy[i]. A tool with no links applies
+ // to the whole operation (shown on every step in the MES).
+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {
+ const jobOperationToolId = insertedTools[i]?.id;
+ if (!jobOperationToolId) return [];
+ const oldStepIds = (
+ (tool.methodOperationToolStep ?? []) as Array<{
+ methodOperationStepId: string | null;
+ }>
+ ).map((l) => l.methodOperationStepId);
+ return remapStepIds(oldStepIds, methodStepsToJobSteps).map(
+ (jobOperationStepId) => ({
+ jobOperationToolId,
+ jobOperationStepId,
+ })
+ );
+ });
+ if (toolStepRows.length > 0) {
+ await trx
+ .insertInto("jobOperationToolStep")
+ .values(toolStepRows)
.execute();
}
}
@@ -926,6 +1110,13 @@ serve(async (req: Request) => {
jobMakeMethodId: parentJobMakeMethodId!,
jobOperationId:
methodOperationsToJobOperations[child.data.operationId],
+ // Transient (Phase 2, many-to-many): the part ↔ step links, remapped onto the
+ // job's steps. Stripped before insert; used to build jobMaterialStep rows.
+ __stepIds: remapStepIds(
+ (child.data as { methodOperationStepIds?: string[] | null })
+ .methodOperationStepIds,
+ methodStepsToJobSteps
+ ),
itemId,
itemType,
kit: child.data.kit,
@@ -1024,9 +1215,34 @@ serve(async (req: Request) => {
await trx
.insertInto("jobMaterial")
- .values(madeMaterialsWithIds)
+ .values(
+ madeMaterialsWithIds.map((m) => {
+ const { __stepIds, ...rest } = m as typeof m & {
+ __stepIds?: string[];
+ };
+ return rest;
+ })
+ )
.execute();
+ // Part ↔ step links (Phase 2, many-to-many): the transient __stepIds carried the
+ // remapped job step ids; write them to jobMaterialStep now that the material id
+ // exists. No links = whole operation (shown on every step in the MES).
+ const madeStepRows = madeMaterialsWithIds.flatMap((m) =>
+ ((m as { __stepIds?: string[] }).__stepIds ?? []).map(
+ (jobOperationStepId) => ({
+ jobMaterialId: m.id,
+ jobOperationStepId,
+ })
+ )
+ );
+ if (madeStepRows.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(madeStepRows)
+ .execute();
+ }
+
for (const [index, child] of madeChildren.entries()) {
const materialId = madeMaterialsWithIds[index].id;
const newMakeMethodId = nanoid();
@@ -1084,10 +1300,38 @@ serve(async (req: Request) => {
}
if (pickedOrBoughtMaterials.length > 0) {
+ // Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference
+ // each row; strip the transient __stepIds before inserting the material.
+ const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({
+ ...m,
+ id: (m as { id?: string }).id ?? nanoid(),
+ }));
await trx
.insertInto("jobMaterial")
- .values(pickedOrBoughtMaterials)
+ .values(
+ pickedWithIds.map((m) => {
+ const { __stepIds, ...rest } = m as typeof m & {
+ __stepIds?: string[];
+ };
+ return rest;
+ })
+ )
.execute();
+
+ const pickedStepRows = pickedWithIds.flatMap((m) =>
+ ((m as { __stepIds?: string[] }).__stepIds ?? []).map(
+ (jobOperationStepId) => ({
+ jobMaterialId: m.id,
+ jobOperationStepId,
+ })
+ )
+ );
+ if (pickedStepRows.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(pickedStepRows)
+ .execute();
+ }
}
} // end if (parts.billOfMaterial)
}
@@ -1106,6 +1350,13 @@ serve(async (req: Request) => {
jobMakeMethod.data.id,
job.data?.quantity ?? 1
);
+
+ await linkAssemblyStepMaterialsForJobOperations(
+ trx,
+ client,
+ assemblyOperationsToLink,
+ companyId
+ );
});
break;
@@ -1118,6 +1369,13 @@ serve(async (req: Request) => {
}
const itemId = sourceId;
const isConfigured = !!configuration;
+ // Assembly ops whose steps were materialized from an instruction —
+ // material ↔ step links flush after the traversal inserts the
+ // jobMaterial rows.
+ const assemblyOperationsToLink: Array<{
+ operationId: string;
+ assemblyInstructionId: string;
+ }> = [];
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
@@ -1281,7 +1539,7 @@ serve(async (req: Request) => {
const relatedOperations = await client
.from("methodOperation")
.select(
- "*, methodOperationTool(*), methodOperationParameter(*), methodOperationStep(*)"
+ "*, methodOperationTool(*, methodOperationToolStep(*)), methodOperationParameter(*), methodOperationStep(*)"
)
.eq("makeMethodId", node.data.materialMakeMethodId);
@@ -1303,6 +1561,10 @@ serve(async (req: Request) => {
order: op.order,
operationOrder: op.operationOrder,
operationType: op.operationType,
+ // Carry the Assembly → BOP sync link so the MES can drive the
+ // animated instruction player on jobs made from a synced method.
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
operationUnitCost: op.operationUnitCost ?? 0,
operationSupplierProcessId: op.operationSupplierProcessId,
...getOutsideOperationRates(
@@ -1319,6 +1581,8 @@ serve(async (req: Request) => {
})) ?? [];
let methodOperationsToJobOperations: Record<string, string> = {};
+ // method step id -> new job step id, for copying the part ↔ step link (Phase 2)
+ const methodStepsToJobSteps: Record<string, string> = {};
if (parts.billOfProcess) {
if (jobOperationsInserts?.length > 0) {
@@ -1341,24 +1605,11 @@ serve(async (req: Request) => {
procedureId,
} = operation;
- if (
- parts.tools &&
- Array.isArray(methodOperationTool) &&
- methodOperationTool.length > 0
- ) {
- await trx
- .insertInto("jobOperationTool")
- .values(
- methodOperationTool.map((tool) => ({
- toolId: tool.toolId,
- quantity: tool.quantity,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ // Tool ids already inserted by the assembly-instruction
+ // copy — the method tool copy below must skip these or the
+ // job gets the same tool twice (once step-linked, once
+ // unlinked → the MES shows it on every step AND its step).
+ let assemblyToolIds: Set<string> = new Set();
if (procedureId) {
await insertProcedureDataForJobOperation(trx, client, {
@@ -1387,12 +1638,32 @@ serve(async (req: Request) => {
.execute();
}
- if (
+ if (operation.assemblyInstructionId) {
+ // Assembly ops inherit their steps from the linked
+ // instruction (the method only carries the pointer);
+ // material ↔ step links are flushed after the
+ // jobMaterial rows exist.
+ assemblyToolIds = await insertAssemblyDataForJobOperation(
+ trx,
+ client,
+ {
+ operationId,
+ assemblyInstructionId:
+ operation.assemblyInstructionId,
+ companyId,
+ userId,
+ }
+ );
+ assemblyOperationsToLink.push({
+ operationId,
+ assemblyInstructionId: operation.assemblyInstructionId,
+ });
+ } else if (
parts.steps &&
Array.isArray(methodOperationStep) &&
methodOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("jobOperationStep")
.values(
methodOperationStep.map(
@@ -1405,6 +1676,76 @@ serve(async (req: Request) => {
})
)
)
+ .returning(["id"])
+ .execute();
+
+ // Bulk insert preserves order, so insertedSteps[i] ↔
+ // methodOperationStep[i]: record each method step -> new job step so
+ // materials can carry the part ↔ step link onto the job (Phase 2).
+ (methodOperationStep as Array<{ id?: string }>).forEach(
+ (s, i) => {
+ const newStepId = insertedSteps[i]?.id;
+ if (s?.id && newStepId)
+ methodStepsToJobSteps[s.id] = newStepId;
+ }
+ );
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "jobOperationStepSlide",
+ companyId,
+ userId,
+ );
+ }
+ }
+
+ // Tools after steps (Phase 2): the method-step -> job-step map is now
+ // populated, so a tool scoped to steps carries those links onto the job via
+ // jobOperationToolStep. Mirrors the material part ↔ step copy above. Tools
+ // the assembly-instruction copy already inserted are skipped (see above).
+ const toolsToCopy = (
+ Array.isArray(methodOperationTool) ? methodOperationTool : []
+ ).filter((tool: { toolId: string }) => !assemblyToolIds.has(tool.toolId));
+ if (parts.tools && toolsToCopy.length > 0) {
+ const insertedTools = await trx
+ .insertInto("jobOperationTool")
+ .values(
+ toolsToCopy.map((tool) => ({
+ toolId: tool.toolId,
+ quantity: tool.quantity,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .returning(["id"])
+ .execute();
+
+ // Tool ↔ step links (Phase 2, many-to-many). Bulk insert preserves order,
+ // so insertedTools[i] ↔ toolsToCopy[i]. A tool with no links applies
+ // to the whole operation (shown on every step in the MES).
+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {
+ const jobOperationToolId = insertedTools[i]?.id;
+ if (!jobOperationToolId) return [];
+ const oldStepIds = (
+ (tool.methodOperationToolStep ?? []) as Array<{
+ methodOperationStepId: string | null;
+ }>
+ ).map((l) => l.methodOperationStepId);
+ return remapStepIds(oldStepIds, methodStepsToJobSteps).map(
+ (jobOperationStepId) => ({
+ jobOperationToolId,
+ jobOperationStepId,
+ })
+ );
+ });
+ if (toolStepRows.length > 0) {
+ await trx
+ .insertInto("jobOperationToolStep")
+ .values(toolStepRows)
.execute();
}
}
@@ -1459,6 +1800,13 @@ serve(async (req: Request) => {
jobMakeMethodId: parentJobMakeMethodId!,
jobOperationId:
methodOperationsToJobOperations[child.data.operationId],
+ // Transient (Phase 2, many-to-many): the part ↔ step links, remapped onto the
+ // job's steps. Stripped before insert; used to build jobMaterialStep rows.
+ __stepIds: remapStepIds(
+ (child.data as { methodOperationStepIds?: string[] | null })
+ .methodOperationStepIds,
+ methodStepsToJobSteps
+ ),
itemId: child.data.itemId,
kit: child.data.kit,
itemType: child.data.itemType,
@@ -1538,9 +1886,34 @@ serve(async (req: Request) => {
await trx
.insertInto("jobMaterial")
- .values(madeMaterialsWithIds)
+ .values(
+ madeMaterialsWithIds.map((m) => {
+ const { __stepIds, ...rest } = m as typeof m & {
+ __stepIds?: string[];
+ };
+ return rest;
+ })
+ )
.execute();
+ // Part ↔ step links (Phase 2, many-to-many): the transient __stepIds carried the
+ // remapped job step ids; write them to jobMaterialStep now that the material id
+ // exists. No links = whole operation (shown on every step in the MES).
+ const madeStepRows = madeMaterialsWithIds.flatMap((m) =>
+ ((m as { __stepIds?: string[] }).__stepIds ?? []).map(
+ (jobOperationStepId) => ({
+ jobMaterialId: m.id,
+ jobOperationStepId,
+ })
+ )
+ );
+ if (madeStepRows.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(madeStepRows)
+ .execute();
+ }
+
const madeChildren = node.children.filter(
(child) => child.data.methodType === "Make to Order"
);
@@ -1591,10 +1964,38 @@ serve(async (req: Request) => {
}
if (pickedOrBoughtMaterials.length > 0) {
+ // Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference
+ // each row; strip the transient __stepIds before inserting the material.
+ const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({
+ ...m,
+ id: (m as { id?: string }).id ?? nanoid(),
+ }));
await trx
.insertInto("jobMaterial")
- .values(pickedOrBoughtMaterials)
+ .values(
+ pickedWithIds.map((m) => {
+ const { __stepIds, ...rest } = m as typeof m & {
+ __stepIds?: string[];
+ };
+ return rest;
+ })
+ )
.execute();
+
+ const pickedStepRows = pickedWithIds.flatMap((m) =>
+ ((m as { __stepIds?: string[] }).__stepIds ?? []).map(
+ (jobOperationStepId) => ({
+ jobMaterialId: m.id,
+ jobOperationStepId,
+ })
+ )
+ );
+ if (pickedStepRows.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(pickedStepRows)
+ .execute();
+ }
}
} // end if (parts.billOfMaterial)
}
@@ -1605,6 +2006,13 @@ serve(async (req: Request) => {
jobMakeMethod.data.id,
parentEstimatedQuantity
);
+
+ await linkAssemblyStepMaterialsForJobOperations(
+ trx,
+ client,
+ assemblyOperationsToLink,
+ companyId
+ );
});
break;
}
@@ -1933,6 +2341,8 @@ serve(async (req: Request) => {
quoteMakeMethodId: parentQuoteMakeMethodId!,
processId,
procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId,
description,
setupTime,
@@ -1944,7 +2354,7 @@ serve(async (req: Request) => {
...getLaborAndOverheadRates(processId, op.workCenterId),
order: op.order,
operationOrder,
- operationType,
+ operationType: normalizeOperationType(operationType),
operationSupplierProcessId: op.operationSupplierProcessId,
operationUnitCost: op.operationUnitCost ?? 0,
...getOutsideOperationRates(
@@ -2079,10 +2489,22 @@ serve(async (req: Request) => {
)
);
- await trx
+ const insertedSteps = await trx
.insertInto("quoteOperationStep")
.values(attributes)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "quoteOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -2474,6 +2896,8 @@ serve(async (req: Request) => {
quoteMakeMethodId: parentQuoteMakeMethodId!,
processId: op.processId,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -2563,10 +2987,13 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops inherit steps from the linked instruction —
+ // never copy (possibly stale) template steps alongside it.
+ !operation.assemblyInstructionId &&
Array.isArray(methodOperationStep) &&
methodOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("quoteOperationStep")
.values(
methodOperationStep.map(
@@ -2579,7 +3006,19 @@ serve(async (req: Request) => {
})
)
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "quoteOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -2863,6 +3302,8 @@ serve(async (req: Request) => {
makeMethodId: op.makeMethodId!,
processId: op.processId!,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -2873,7 +3314,7 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
- operationType: op.operationType ?? "Inside",
+ operationType: op.operationType ?? "Process",
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -2954,10 +3395,15 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops and inspection ops inherit their steps from
+ // the linked instruction/document — never copy materialized
+ // steps back onto a template.
+ !operation.assemblyInstructionId &&
+ !operation.inspectionDocumentId &&
Array.isArray(jobOperationStep) &&
jobOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("jobOperationStep")
.values(
jobOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -2968,7 +3414,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ jobOperationStep,
+ insertedSteps,
+ "jobOperationStepSlide",
+ "jobOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -3164,6 +3622,8 @@ serve(async (req: Request) => {
makeMethodId: op.makeMethodId!,
processId: op.processId!,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
// workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -3174,7 +3634,7 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
- operationType: op.operationType ?? "Inside",
+ operationType: op.operationType ?? "Process",
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -3256,10 +3716,15 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops and inspection ops inherit their steps from
+ // the linked instruction/document — never copy materialized
+ // steps back onto a template.
+ !operation.assemblyInstructionId &&
+ !operation.inspectionDocumentId &&
Array.isArray(jobOperationStep) &&
jobOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("methodOperationStep")
.values(
jobOperationStep.map((step) => ({
@@ -3278,7 +3743,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ jobOperationStep,
+ insertedSteps,
+ "jobOperationStepSlide",
+ "methodOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -3446,10 +3923,13 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops inherit steps from the linked instruction —
+ // never copy (possibly stale) template steps alongside it.
+ !operation.assemblyInstructionId &&
Array.isArray(methodOperationStep) &&
methodOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("methodOperationStep")
.values(
methodOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -3460,7 +3940,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "methodOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -3787,6 +4279,8 @@ serve(async (req: Request) => {
makeMethodId: op.makeMethodId!,
processId: op.processId!,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -3797,7 +4291,7 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
- operationType: op.operationType ?? "Inside",
+ operationType: op.operationType ?? "Process",
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -3878,10 +4372,13 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops inherit steps from the linked instruction —
+ // never copy (possibly stale) quote steps alongside it.
+ !operation.assemblyInstructionId &&
Array.isArray(quoteOperationStep) &&
quoteOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("methodOperationStep")
.values(
quoteOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -3892,7 +4389,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ quoteOperationStep,
+ insertedSteps,
+ "quoteOperationStepSlide",
+ "methodOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -4087,6 +4596,8 @@ serve(async (req: Request) => {
makeMethodId: op.makeMethodId!,
processId: op.processId!,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -4097,7 +4608,7 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
- operationType: op.operationType ?? "Inside",
+ operationType: op.operationType ?? "Process",
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -4178,10 +4689,13 @@ serve(async (req: Request) => {
if (
parts.steps &&
+ // Assembly ops inherit steps from the linked instruction —
+ // never copy (possibly stale) quote steps alongside it.
+ !operation.assemblyInstructionId &&
Array.isArray(quoteOperationStep) &&
quoteOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("methodOperationStep")
.values(
quoteOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -4192,7 +4706,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ quoteOperationStep,
+ insertedSteps,
+ "quoteOperationStepSlide",
+ "methodOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -4213,6 +4739,12 @@ serve(async (req: Request) => {
if (!quoteId || !quoteLineId) {
throw new Error("Invalid sourceId");
}
+ // Assembly ops whose steps were materialized from an instruction —
+ // material ↔ step links flush after the jobMaterial rows exist.
+ const assemblyOperationsToLink: Array<{
+ operationId: string;
+ assemblyInstructionId: string;
+ }> = [];
const [
job,
@@ -4555,6 +5087,10 @@ serve(async (req: Request) => {
order: op.order,
operationOrder: op.operationOrder,
operationType: op.operationType,
+ // Carry the Assembly → BOP sync link so the MES can drive the
+ // animated instruction player on jobs made from a synced method.
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
operationSupplierProcessId: op.operationSupplierProcessId,
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
@@ -4634,12 +5170,27 @@ serve(async (req: Request) => {
.execute();
}
- if (
+ if (operation.assemblyInstructionId) {
+ // Assembly ops inherit their steps from the linked
+ // instruction (the quote only carries the pointer);
+ // material ↔ step links are flushed after the jobMaterial
+ // rows exist.
+ await insertAssemblyDataForJobOperation(trx, client, {
+ operationId,
+ assemblyInstructionId: operation.assemblyInstructionId,
+ companyId,
+ userId,
+ });
+ assemblyOperationsToLink.push({
+ operationId,
+ assemblyInstructionId: operation.assemblyInstructionId,
+ });
+ } else if (
parts.steps &&
Array.isArray(quoteOperationStep) &&
quoteOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("jobOperationStep")
.values(
quoteOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -4650,13 +5201,34 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ quoteOperationStep,
+ insertedSteps,
+ "quoteOperationStepSlide",
+ "jobOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
}
}
} // end if (parts.billOfProcess)
+
+ // Materials were inserted before operations in this direction, so the
+ // assembly material ↔ step links can flush immediately.
+ await linkAssemblyStepMaterialsForJobOperations(
+ trx,
+ client,
+ assemblyOperationsToLink,
+ companyId
+ );
});
break;
@@ -4855,6 +5427,8 @@ serve(async (req: Request) => {
: quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],
processId: op.processId,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -4941,7 +5515,7 @@ serve(async (req: Request) => {
Array.isArray(quoteOperationStep) &&
quoteOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("quoteOperationStep")
.values(
quoteOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -4952,7 +5526,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ quoteOperationStep,
+ insertedSteps,
+ "quoteOperationStepSlide",
+ "quoteOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -5344,6 +5930,8 @@ serve(async (req: Request) => {
],
processId: op.processId,
procedureId: op.procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -5427,7 +6015,7 @@ serve(async (req: Request) => {
Array.isArray(quoteOperationStep) &&
quoteOperationStep.length > 0
) {
- await trx
+ const insertedSteps = await trx
.insertInto("quoteOperationStep")
.values(
quoteOperationStep.map(({ id: _id, ...attribute }) => ({
@@ -5438,7 +6026,19 @@ serve(async (req: Request) => {
createdBy: userId,
}))
)
+ .returning(["id"])
.execute();
+
+ await copyStepSlides(
+ trx,
+ client,
+ quoteOperationStep,
+ insertedSteps,
+ "quoteOperationStepSlide",
+ "quoteOperationStepSlide",
+ companyId,
+ userId,
+ );
}
}
}
@@ -5798,6 +6398,300 @@ async function insertProcedureDataForJobOperation(
.execute();
}
+// Assembly analog of insertProcedureDataForJobOperation: an Assembly operation
+// inherits its steps from the linked assembly instruction at job-creation time
+// (the method/quote only carry the pointer). Mirrors the payload of
+// syncAssemblyInstructionToOperation (production.service.ts) — including the
+// assemblyInstructionStepId provenance marker, so the job-side re-sync
+// reconciles these rows instead of duplicating them — and attaches the
+// instruction's 3D model as a model slide on every step.
+// Material ↔ step links are flushed separately by
+// linkAssemblyStepMaterialsForJobOperations AFTER the direction's jobMaterial
+// rows exist (operations are inserted before materials in every direction).
+async function insertAssemblyDataForJobOperation(
+ trx: Transaction<DB>,
+ client: SupabaseClient<Database>,
+ args: {
+ operationId: string;
+ assemblyInstructionId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { operationId, assemblyInstructionId, companyId, userId } = args;
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("id, modelUploadId, assemblyInstructionStep(*)")
+ .eq("id", assemblyInstructionId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (instruction.error) return new Set<string>();
+
+ const sourceSteps = (instruction.data?.assemblyInstructionStep ?? []).sort(
+ (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)
+ );
+ if (sourceSteps.length === 0) return new Set<string>();
+
+ const sourceStepIds = sourceSteps.map((step) => step.id);
+ const [sourceSlides, sourceTools] = await Promise.all([
+ client
+ .from("assemblyInstructionStepSlide")
+ .select(
+ "stepId, imagePath, modelUploadId, caption, sortOrder, size, annotations"
+ )
+ .in("stepId", sourceStepIds)
+ .eq("companyId", companyId)
+ .order("sortOrder", { ascending: true }),
+ client
+ .from("assemblyInstructionStepTool")
+ .select("stepId, itemId, quantity")
+ .in("stepId", sourceStepIds)
+ .eq("companyId", companyId),
+ ]);
+ const slidesByStep = new Map<
+ string,
+ NonNullable<typeof sourceSlides.data>
+ >();
+ for (const slide of sourceSlides.data ?? []) {
+ const list = slidesByStep.get(slide.stepId) ?? [];
+ list.push(slide);
+ slidesByStep.set(slide.stepId, list);
+ }
+ const toolsByStep = new Map<string, { itemId: string; quantity: number }[]>();
+ for (const tool of sourceTools.data ?? []) {
+ const list = toolsByStep.get(tool.stepId) ?? [];
+ list.push({ itemId: tool.itemId, quantity: tool.quantity ?? 1 });
+ toolsByStep.set(tool.stepId, list);
+ }
+
+ // Correlate inserted job steps back to their source steps via the provenance
+ // column, not row order.
+ const insertedSteps = await trx
+ .insertInto("jobOperationStep")
+ .values(
+ sourceSteps.map((source, index) => ({
+ operationId,
+ name: source.title || `Step ${index + 1}`,
+ type: source.type ?? "Task",
+ description: toTiptapDoc(source.description ?? source.instructionText),
+ required: source.required ?? false,
+ unitOfMeasureCode: source.unitOfMeasureCode,
+ minValue: source.minValue,
+ maxValue: source.maxValue,
+ listValues: source.listValues,
+ fileTypes: source.fileTypes,
+ sortOrder: source.sortOrder ?? index + 1,
+ assemblyInstructionStepId: source.id,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .returning(["id", "assemblyInstructionStepId"])
+ .execute();
+ const targetIdBySource = new Map(
+ insertedSteps.map((step) => [step.assemblyInstructionStepId, step.id])
+ );
+
+ // Per-step slides: the instruction's 3D model leads as a model slide,
+ // followed by the step's authored slides (image XOR model, with captions,
+ // sizes, and annotation pins).
+ const slideRows: {
+ stepId: string;
+ imagePath: string | null;
+ modelUploadId: string | null;
+ caption: string | null;
+ sortOrder: number;
+ size: string;
+ annotations: string;
+ companyId: string;
+ createdBy: string;
+ }[] = [];
+ for (const source of sourceSteps) {
+ const targetStepId = targetIdBySource.get(source.id);
+ if (!targetStepId) continue;
+ const authored = slidesByStep.get(source.id) ?? [];
+ const modelUploadId = instruction.data?.modelUploadId;
+ if (
+ modelUploadId &&
+ !authored.some((slide) => slide.modelUploadId === modelUploadId)
+ ) {
+ slideRows.push({
+ stepId: targetStepId,
+ imagePath: null,
+ modelUploadId,
+ caption: null,
+ sortOrder: 0,
+ size: "medium",
+ annotations: JSON.stringify([]),
+ companyId,
+ createdBy: userId,
+ });
+ }
+ for (const slide of authored) {
+ slideRows.push({
+ stepId: targetStepId,
+ imagePath: slide.imagePath,
+ modelUploadId: slide.modelUploadId,
+ caption: slide.caption,
+ sortOrder: slide.sortOrder ?? 1,
+ size: slide.size ?? "medium",
+ annotations: JSON.stringify(slide.annotations ?? []),
+ companyId,
+ createdBy: userId,
+ });
+ }
+ }
+ if (slideRows.length > 0) {
+ await trx.insertInto("jobOperationStepSlide").values(slideRows).execute();
+ }
+
+ // Per-step tools: one jobOperationTool row per distinct tool item (quantity =
+ // max across steps) plus the tool ↔ step scope links.
+ const maxQuantityByItemId = new Map<string, number>();
+ for (const tools of toolsByStep.values()) {
+ for (const tool of tools) {
+ maxQuantityByItemId.set(
+ tool.itemId,
+ Math.max(maxQuantityByItemId.get(tool.itemId) ?? 0, tool.quantity)
+ );
+ }
+ }
+ if (maxQuantityByItemId.size > 0) {
+ // The operation may already carry rows for these tools (the quote → job
+ // direction copies quoteOperationTool BEFORE this runs). Link steps to the
+ // existing row instead of inserting a duplicate the MES would list twice.
+ const existingTools = await trx
+ .selectFrom("jobOperationTool")
+ .select(["id", "toolId"])
+ .where("operationId", "=", operationId)
+ .execute();
+ const toolRowIdByItemId = new Map(
+ existingTools.map((tool) => [tool.toolId, tool.id])
+ );
+ const missingTools = [...maxQuantityByItemId.entries()].filter(
+ ([itemId]) => !toolRowIdByItemId.has(itemId)
+ );
+ if (missingTools.length > 0) {
+ const insertedTools = await trx
+ .insertInto("jobOperationTool")
+ .values(
+ missingTools.map(([itemId, quantity]) => ({
+ operationId,
+ toolId: itemId,
+ quantity,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .returning(["id", "toolId"])
+ .execute();
+ for (const tool of insertedTools) {
+ toolRowIdByItemId.set(tool.toolId, tool.id);
+ }
+ }
+ const toolLinkRows: {
+ jobOperationToolId: string;
+ jobOperationStepId: string;
+ }[] = [];
+ for (const source of sourceSteps) {
+ const targetStepId = targetIdBySource.get(source.id);
+ if (!targetStepId) continue;
+ for (const tool of toolsByStep.get(source.id) ?? []) {
+ const jobOperationToolId = toolRowIdByItemId.get(tool.itemId);
+ if (jobOperationToolId) {
+ toolLinkRows.push({
+ jobOperationToolId,
+ jobOperationStepId: targetStepId,
+ });
+ }
+ }
+ }
+ if (toolLinkRows.length > 0) {
+ await trx
+ .insertInto("jobOperationToolStep")
+ .values(toolLinkRows)
+ .execute();
+ }
+ }
+ // Tool ids the instruction accounts for — the method → job copy paths filter
+ // methodOperationTool by this set so the same tool isn't inserted a second
+ // time (unlinked, so the MES would show it on every step AND on its step).
+ return new Set(maxQuantityByItemId.keys());
+}
+
+// Post-materials pass: link the assembly-materialized job steps to the job's
+// materials, resolving the instruction's per-step itemIds against the
+// operation's own make method (same resolution the app-side sync performs).
+// Must read jobOperation/jobOperationStep/jobMaterial through the TRANSACTION —
+// those rows are uncommitted at this point.
+async function linkAssemblyStepMaterialsForJobOperations(
+ trx: Transaction<DB>,
+ client: SupabaseClient<Database>,
+ operations: Array<{ operationId: string; assemblyInstructionId: string }>,
+ companyId: string
+) {
+ for (const { operationId } of operations) {
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .select(["jobMakeMethodId"])
+ .where("id", "=", operationId)
+ .executeTakeFirst();
+ if (!operation?.jobMakeMethodId) continue;
+
+ const steps = await trx
+ .selectFrom("jobOperationStep")
+ .select(["id", "assemblyInstructionStepId"])
+ .where("operationId", "=", operationId)
+ .where("assemblyInstructionStepId", "is not", null)
+ .execute();
+ if (steps.length === 0) continue;
+
+ const sourceStepIds = steps.map(
+ (step) => step.assemblyInstructionStepId as string
+ );
+ const stepMaterials = await client
+ .from("assemblyInstructionStepMaterial")
+ .select("stepId, itemId")
+ .in("stepId", sourceStepIds)
+ .eq("companyId", companyId);
+ if (stepMaterials.error || (stepMaterials.data ?? []).length === 0) {
+ continue;
+ }
+
+ const jobMaterials = await trx
+ .selectFrom("jobMaterial")
+ .select(["id", "itemId"])
+ .where("jobMakeMethodId", "=", operation.jobMakeMethodId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const materialIdByItemId = new Map(
+ jobMaterials.map((material) => [material.itemId, material.id])
+ );
+ const jobStepBySourceStep = new Map(
+ steps.map((step) => [step.assemblyInstructionStepId as string, step.id])
+ );
+
+ const linkRows = (stepMaterials.data ?? []).flatMap((link) => {
+ const jobOperationStepId = jobStepBySourceStep.get(link.stepId);
+ const jobMaterialId = link.itemId
+ ? materialIdByItemId.get(link.itemId)
+ : undefined;
+ return jobOperationStepId && jobMaterialId
+ ? [{ jobMaterialId, jobOperationStepId }]
+ : [];
+ });
+
+ if (linkRows.length > 0) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values(linkRows)
+ .onConflict((oc) => oc.doNothing())
+ .execute();
+ }
+ }
+}
+
async function hydrateConfiguration(
client: SupabaseClient<Database>,
configuration: Record<string, unknown> | undefined,
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 72b4e46b55..760ba75eda 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -2194,6 +2194,21 @@ serve(async (req: Request) => {
data: Database["public"]["Tables"]["process"]["Update"];
}[] = [];
+ // Legacy CSV templates may still use the old Inside/Outside process types.
+ const normalizeProcessType = (value: string) =>
+ (value === "Inside"
+ ? "Process"
+ : value === "Outside" || value === "Inside and Outside"
+ ? "Outside Processing"
+ : value) as Database["public"]["Enums"]["processType"];
+
+ const validProcessTypes = [
+ "Process",
+ "Assembly",
+ "Inspection",
+ "Outside Processing",
+ ];
+
const isProcessValid = (
record: Record<string, string>
): record is { name: string; processType: string } => {
@@ -2201,8 +2216,9 @@ serve(async (req: Request) => {
typeof record.name === "string" &&
record.name.trim() !== "" &&
typeof record.processType === "string" &&
- (record.processType === "Inside" ||
- record.processType === "Outside")
+ validProcessTypes.includes(
+ normalizeProcessType(record.processType)
+ )
);
};
@@ -2216,6 +2232,7 @@ serve(async (req: Request) => {
id: existingEntityId,
data: {
...rest,
+ processType: normalizeProcessType(rest.processType),
completeAllOnScan:
rest.completeAllOnScan?.toLowerCase() === "true" ?? false,
updatedAt: new Date().toISOString(),
@@ -2227,6 +2244,7 @@ serve(async (req: Request) => {
processIds.add(id);
processInserts.push({
...rest,
+ processType: normalizeProcessType(rest.processType),
completeAllOnScan:
rest.completeAllOnScan?.toLowerCase() === "true" ?? false,
companyId,
diff --git a/packages/database/supabase/functions/import-csv/method-import.ts b/packages/database/supabase/functions/import-csv/method-import.ts
index 0935e97691..ab5f16918e 100644
--- a/packages/database/supabase/functions/import-csv/method-import.ts
+++ b/packages/database/supabase/functions/import-csv/method-import.ts
@@ -75,6 +75,14 @@ const bool = (s: string | undefined): boolean =>
const text = (s: string | undefined): string => (s ?? "").trim();
+// Legacy CSV templates may still use the old "Inside"/"Outside" operation types.
+const normalizeOperationType = (value: string): string =>
+ value === "Inside"
+ ? "Process"
+ : value === "Outside"
+ ? "Outside Processing"
+ : value;
+
// The `row` reported on each error: the 0-based index of the data row. This must
// match how the results modal keys errors to rows (by array index into the parsed
// rows) and the standard importer in index.ts — NOT a human CSV line number.
@@ -429,13 +437,13 @@ function validateGroup(
}
}
- // Inside operations need time units.
- const opType = text(e.record.operationType) || "Inside";
- if (opType === "Inside") {
+ // In-house operations need time units.
+ const opType = normalizeOperationType(text(e.record.operationType)) || "Process";
+ if (opType !== "Outside Processing") {
if (!text(e.record.setupUnit) || !text(e.record.laborUnit) || !text(e.record.machineUnit)) {
errors.push({
row: rowOf(e.index),
- reason: `Op ${opNo}: Inside operations require Setup, Labor, and Machine units`,
+ reason: `Op ${opNo}: In-house operations require Setup, Labor, and Machine units`,
});
}
}
@@ -668,14 +676,14 @@ async function writeGroup(
for (const e of bucket.bop) {
const r = e.record;
const opNo = text(r.opNo);
- const opType = text(r.operationType) || "Inside";
+ const opType = normalizeOperationType(text(r.operationType)) || "Process";
const processId = ctx.processMap.get(text(r.process).toLowerCase())!;
const workCenterId = text(r.workCenter)
? ctx.workCenterMap.get(text(r.workCenter).toLowerCase())
: undefined;
let operationSupplierProcessId: string | undefined;
- if (opType === "Outside" && text(r.supplier)) {
+ if (opType === "Outside Processing" && text(r.supplier)) {
operationSupplierProcessId = await resolveSupplierProcess(
trx,
companyId,
@@ -921,7 +929,7 @@ async function seedStorageUnitIds(
return current;
}
-// Optional supplier-process link for an Outside operation (by supplier + process).
+// Optional supplier-process link for an Outside Processing operation (by supplier + process).
async function resolveSupplierProcess(
trx: Transaction<DB>,
companyId: string,
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index c9cb75818e..051c0547e6 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -810,6 +810,11 @@ const payloadValidator = z.discriminatedUnion("type", [
laborProductionEventId: z.string().optional(),
machineProductionEventId: z.string().optional(),
setupProductionEventId: z.string().optional(),
+ // Provenance links for inspection-driven completions. The partial UNIQUE
+ // index on productionQuantity.inspectionSampleId makes a re-post of the
+ // same verdict fail instead of double-counting.
+ inspectionId: z.string().optional(),
+ inspectionSampleId: z.string().optional(),
}),
z.object({
type: z.literal("jobOperationSerialComplete"),
@@ -822,6 +827,8 @@ const payloadValidator = z.discriminatedUnion("type", [
laborProductionEventId: z.string().optional(),
machineProductionEventId: z.string().optional(),
setupProductionEventId: z.string().optional(),
+ inspectionId: z.string().optional(),
+ inspectionSampleId: z.string().optional(),
}),
z.object({
type: z.literal("partToOperation"),
@@ -834,6 +841,9 @@ const payloadValidator = z.discriminatedUnion("type", [
"Negative Adjmt.",
]),
materialId: z.string().optional(),
+ // Assembly view: when issuing an unplanned part (no materialId), scope the new
+ // jobMaterial to this step so it surfaces on that step in the operator view.
+ jobOperationStepId: z.string().optional(),
companyId: z.string(),
userId: z.string(),
}),
@@ -857,6 +867,11 @@ const payloadValidator = z.discriminatedUnion("type", [
quantity: z.number(),
})
),
+ // Assembly view: the step + 1-based unit the operator was on, stamped onto the
+ // Consume activity so issued quantities can be attributed per-unit/per-step even
+ // for a batch parent (all units share one lot entity).
+ jobOperationStepId: z.string().optional(),
+ unitNumber: z.number().int().positive().optional(),
overrideExpired: z.boolean().optional(),
overrideReason: z.string().optional(),
companyId: z.string(),
@@ -1326,6 +1341,7 @@ serve(async (req: Request) => {
itemId,
quantity,
materialId,
+ jobOperationStepId,
adjustmentType,
} = validatedPayload;
@@ -1520,7 +1536,7 @@ serve(async (req: Request) => {
.select("unitCost")
.executeTakeFirst();
- await trx
+ const newJobMaterial = await trx
.insertInto("jobMaterial")
.values({
companyId,
@@ -1538,8 +1554,22 @@ serve(async (req: Request) => {
quantityIssued: Number(quantity ?? 0),
unitCost: itemCost?.unitCost ?? 0,
})
+ .returning("id")
.executeTakeFirst();
+ // Scope this unplanned part to the step it was issued on (assembly
+ // view), so it shows on that step rather than as a General material.
+ if (jobOperationStepId && newJobMaterial?.id) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values({
+ jobMaterialId: newJobMaterial.id,
+ jobOperationStepId,
+ })
+ .onConflict((oc) => oc.doNothing())
+ .execute();
+ }
+
if (itemLedgerInserts.length > 0) {
await trx
.insertInto("itemLedger")
@@ -1802,6 +1832,8 @@ serve(async (req: Request) => {
itemId,
parentTrackedEntityId,
children,
+ jobOperationStepId,
+ unitNumber,
overrideExpired,
overrideReason,
companyId,
@@ -2026,6 +2058,19 @@ serve(async (req: Request) => {
actualMaterialId = newJobMaterial.id!;
+ // Scope this unplanned tracked part to the step it was issued on
+ // (assembly view), so it shows on that step rather than as General.
+ if (jobOperationStepId) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values({
+ jobMaterialId: actualMaterialId,
+ jobOperationStepId,
+ })
+ .onConflict((oc) => oc.doNothing())
+ .execute();
+ }
+
// Fetch the newly created jobMaterial
jobMaterial = await trx
.selectFrom("jobMaterial")
@@ -2084,6 +2129,13 @@ serve(async (req: Request) => {
"Job Make Method": jobMaterial?.jobMakeMethodId!,
"Job Material": jobMaterial?.id!,
Employee: userId,
+ // Assembly view: which step + 1-based unit this consume was for, so
+ // the MES can attribute issued quantities per-unit even for a batch
+ // parent (where all units share one lot entity).
+ ...(jobOperationStepId
+ ? { "Job Operation Step": jobOperationStepId }
+ : {}),
+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {}),
},
companyId,
createdBy: userId,
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
index 2f11d9b372..732468e823 100644
--- a/packages/database/supabase/functions/lib/methods.ts
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -664,7 +664,7 @@ export async function calculateQuoteLinePrices(
}
for (const operation of node.operations) {
- if (operation.operationType === "Inside") {
+ if (operation.operationType !== "Outside Processing") {
if (operation.setupTime) {
const { fixedHours, hoursPerUnit } = normalizeTimeToHours(
operation.setupTime,
@@ -745,7 +745,7 @@ export async function calculateQuoteLinePrices(
return fixedHours * (operation.overheadRate ?? 0);
}
});
- } else if (operation.operationType === "Outside") {
+ } else if (operation.operationType === "Outside Processing") {
effects.outsideCost.push((quantity) => {
const unitCost =
operation.operationUnitCost * node.quantity * quantity;
diff --git a/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts b/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts
index e42eb92602..ebc40d9f7a 100644
--- a/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts
+++ b/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts
@@ -263,7 +263,7 @@ export class WorkCenterSelector {
for (const op of sorted) {
// Skip outside operations (they don't need work center assignment)
- if (op.operationType === "Outside") {
+ if (op.operationType === "Outside Processing") {
continue;
}
diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.ts
index 40230a73fe..fe5e510bef 100644
--- a/packages/database/supabase/functions/lib/seed.data.ts
+++ b/packages/database/supabase/functions/lib/seed.data.ts
@@ -248,9 +248,11 @@ export const sequences = [
step: 1
},
{
- table: "inboundInspection",
- name: "Inbound Inspection",
- prefix: "II",
+ // Existing companies keep their re-keyed II sequence (20260722132135);
+ // only new companies seed the INS prefix.
+ table: "inspection",
+ name: "Inspection",
+ prefix: "INS",
suffix: null,
next: 0,
size: 6,
@@ -723,6 +725,7 @@ export const accounts = [
// Inventory Adjustments
{ key: "inventory-adjustments", number: null, name: "Inventory Adjustments", isGroup: true, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },
{ key: "5310", number: "5310", name: "Inventory Adjustment", isGroup: false, parentKey: "inventory-adjustments", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },
+ { key: "5320", number: "5320", name: "Scrap / Cost of Quality", isGroup: false, parentKey: "inventory-adjustments", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },
// ─── 6000-6999: OPERATING EXPENSES ───
{ key: "operating-expenses", number: null, name: "Operating Expenses", isGroup: true, parentKey: "income-statement", accountType: "Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },
@@ -762,6 +765,7 @@ export const accountDefaults = {
costOfGoodsSoldAccount: "5010",
purchaseVarianceAccount: "5210",
inventoryAdjustmentVarianceAccount: "5310",
+ scrapAccount: "5320",
materialVarianceAccount: "5220",
laborAndMachineVarianceAccount: "5230",
overheadVarianceAccount: "5240",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 0ce13ad464..2b30aea54f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -373,6 +373,7 @@ export type Database = {
salesAccount: string
salesDiscountAccount: string
salesTaxPayableAccount: string
+ scrapAccount: string | null
serviceChargeAccount: string
subcontractingVarianceAccount: string
supplierPaymentDiscountAccount: string
@@ -426,6 +427,7 @@ export type Database = {
salesAccount: string
salesDiscountAccount: string
salesTaxPayableAccount: string
+ scrapAccount?: string | null
serviceChargeAccount: string
subcontractingVarianceAccount: string
supplierPaymentDiscountAccount: string
@@ -479,6 +481,7 @@ export type Database = {
salesAccount?: string
salesDiscountAccount?: string
salesTaxPayableAccount?: string
+ scrapAccount?: string | null
serviceChargeAccount?: string
subcontractingVarianceAccount?: string
supplierPaymentDiscountAccount?: string
@@ -1118,6 +1121,20 @@ export type Database = {
referencedRelation: "accounts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "accountDefault_scrapAccount_fkey"
+ columns: ["scrapAccount"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountDefault_scrapAccount_fkey"
+ columns: ["scrapAccount"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "accountDefault_serviceChargeAccount_fkey"
columns: ["serviceChargeAccount"]
@@ -3550,201 +3567,174 @@ export type Database = {
},
]
}
- assemblyInstructionStepRequirement: {
+ assemblyInstructionStepSlide: {
Row: {
+ annotations: Json
+ caption: string | null
companyId: string
createdAt: string
createdBy: string
- filePath: string | null
id: string
- itemId: string | null
- name: string | null
- quantity: number
- severity: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
sortOrder: number
stepId: string
- text: string | null
- type: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt: string | null
updatedBy: string | null
}
Insert: {
+ annotations?: Json
+ caption?: string | null
companyId: string
createdAt?: string
createdBy: string
- filePath?: string | null
id?: string
- itemId?: string | null
- name?: string | null
- quantity?: number
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
sortOrder?: number
stepId: string
- text?: string | null
- type: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
+ annotations?: Json
+ caption?: string | null
companyId?: string
createdAt?: string
createdBy?: string
- filePath?: string | null
id?: string
- itemId?: string | null
- name?: string | null
- quantity?: number
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
sortOrder?: number
stepId?: string
- text?: string | null
- type?: Database["public"]["Enums"]["assemblyRequirementType"]
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "services"
+ referencedRelation: "modelUpload"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
- columns: ["itemId"]
+ foreignKeyName: "assemblyInstructionStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_stepId_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_stepId_fkey"
columns: ["stepId"]
isOneToOne: false
referencedRelation: "assemblyInstructionStep"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ foreignKeyName: "assemblyInstructionStepSlide_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -3752,265 +3742,317 @@ export type Database = {
},
]
}
- assemblyPlanJob: {
+ assemblyInstructionStepTool: {
Row: {
companyId: string
createdAt: string
createdBy: string
- error: string | null
id: string
- kind: string
- modelUploadId: string
- planPath: string | null
- stats: Json | null
- status: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId: string
+ quantity: number
+ sortOrder: number
+ stepId: string
updatedAt: string | null
+ updatedBy: string | null
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
- error?: string | null
id?: string
- kind: string
- modelUploadId: string
- planPath?: string | null
- stats?: Json | null
- status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId: string
+ quantity?: number
+ sortOrder?: number
+ stepId: string
updatedAt?: string | null
+ updatedBy?: string | null
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
- error?: string | null
id?: string
- kind?: string
- modelUploadId?: string
- planPath?: string | null
- stats?: Json | null
- status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ itemId?: string
+ quantity?: number
+ sortOrder?: number
+ stepId?: string
updatedAt?: string | null
+ updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ foreignKeyName: "assemblyInstructionStepTool_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["modelId"]
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "modelUpload"
+ referencedRelation: "item"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
- columns: ["modelUploadId"]
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
isOneToOne: false
- referencedRelation: "salesRfqLines"
- referencedColumns: ["modelId"]
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepTool_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
},
]
}
- assemblyStandardNote: {
+ assemblyPlanJob: {
Row: {
companyId: string
- content: string
createdAt: string
createdBy: string
+ error: string | null
id: string
- name: string
- severity: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind: string
+ modelUploadId: string
+ planPath: string | null
+ stats: Json | null
+ status: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt: string | null
- updatedBy: string | null
}
Insert: {
companyId: string
- content: string
createdAt?: string
createdBy: string
+ error?: string | null
id?: string
- name: string
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind: string
+ modelUploadId: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt?: string | null
- updatedBy?: string | null
}
Update: {
companyId?: string
- content?: string
createdAt?: string
createdBy?: string
+ error?: string | null
id?: string
- name?: string
- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ kind?: string
+ modelUploadId?: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
updatedAt?: string | null
- updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "user"
+ referencedRelation: "modelUpload"
referencedColumns: ["id"]
},
{
- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
},
]
}
@@ -6659,6 +6701,7 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
+ autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -6703,6 +6746,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -6747,6 +6791,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -16204,7 +16249,40 @@ export type Database = {
},
]
}
- inboundInspection: {
+ industry: {
+ Row: {
+ active: boolean
+ createdAt: string
+ description: string | null
+ iconName: string | null
+ id: string
+ name: string
+ sortOrder: number
+ updatedAt: string | null
+ }
+ Insert: {
+ active?: boolean
+ createdAt?: string
+ description?: string | null
+ iconName?: string | null
+ id: string
+ name: string
+ sortOrder?: number
+ updatedAt?: string | null
+ }
+ Update: {
+ active?: boolean
+ createdAt?: string
+ description?: string | null
+ iconName?: string | null
+ id?: string
+ name?: string
+ sortOrder?: number
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
+ inspection: {
Row: {
acceptanceNumber: number
aql: number | null
@@ -16215,20 +16293,23 @@ export type Database = {
dispositionedAt: string | null
dispositionedBy: string | null
id: string
- inboundInspectionId: string
+ inspectionDocumentId: string | null
+ inspectionId: string
inspectionLevel: Database["public"]["Enums"]["inspectionLevel"] | null
itemId: string
itemReadableId: string | null
lotSize: number
notes: string | null
- receiptId: string
- receiptLineId: string
rejectionNumber: number
sampleSize: number
samplingPlanType: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
severity: Database["public"]["Enums"]["inspectionSeverity"] | null
- status: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId: string
+ sourceDocumentLineId: string | null
+ sourceDocumentReadableId: string | null
+ status: Database["public"]["Enums"]["inspectionStatusType"]
supplierId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -16243,7 +16324,8 @@ export type Database = {
dispositionedAt?: string | null
dispositionedBy?: string | null
id?: string
- inboundInspectionId: string
+ inspectionDocumentId?: string | null
+ inspectionId: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16251,14 +16333,16 @@ export type Database = {
itemReadableId?: string | null
lotSize: number
notes?: string | null
- receiptId: string
- receiptLineId: string
rejectionNumber: number
sampleSize: number
samplingPlanType: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
severity?: Database["public"]["Enums"]["inspectionSeverity"] | null
- status?: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId: string
+ sourceDocumentLineId?: string | null
+ sourceDocumentReadableId?: string | null
+ status?: Database["public"]["Enums"]["inspectionStatusType"]
supplierId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -16273,7 +16357,8 @@ export type Database = {
dispositionedAt?: string | null
dispositionedBy?: string | null
id?: string
- inboundInspectionId?: string
+ inspectionDocumentId?: string | null
+ inspectionId?: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16281,14 +16366,16 @@ export type Database = {
itemReadableId?: string | null
lotSize?: number
notes?: string | null
- receiptId?: string
- receiptLineId?: string
rejectionNumber?: number
sampleSize?: number
samplingPlanType?: Database["public"]["Enums"]["samplingPlanType"]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
severity?: Database["public"]["Enums"]["inspectionSeverity"] | null
- status?: Database["public"]["Enums"]["inboundInspectionStatus"]
+ sourceDocument?: Database["public"]["Enums"]["inspectionSourceDocument"]
+ sourceDocumentId?: string
+ sourceDocumentLineId?: string | null
+ sourceDocumentReadableId?: string | null
+ status?: Database["public"]["Enums"]["inspectionStatusType"]
supplierId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -16392,6 +16479,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "inboundInspection_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspection_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "inboundInspection_itemId_fkey"
columns: ["itemId"]
@@ -16434,34 +16535,6 @@ export type Database = {
referencedRelation: "tools"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "inboundInspection_receiptId_fkey"
- columns: ["receiptId"]
- isOneToOne: false
- referencedRelation: "receipt"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptId_fkey"
- columns: ["receiptId"]
- isOneToOne: false
- referencedRelation: "receipts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptLineId_fkey"
- columns: ["receiptLineId"]
- isOneToOne: true
- referencedRelation: "receiptLine"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inboundInspection_receiptLineId_fkey"
- columns: ["receiptLineId"]
- isOneToOne: true
- referencedRelation: "receiptLines"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "inboundInspection_supplierId_fkey"
columns: ["supplierId", "companyId"]
@@ -16520,7 +16593,476 @@ export type Database = {
},
]
}
- inboundInspectionHistory: {
+ inspectionDocument: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ defaultPageHeight: number | null
+ defaultPageWidth: number | null
+ drawingNumber: string | null
+ fileName: string | null
+ id: string
+ pageCount: number | null
+ partId: string
+ 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
+ uploadedBy: string | null
+ version: number
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ defaultPageHeight?: number | null
+ defaultPageWidth?: number | null
+ drawingNumber?: string | null
+ fileName?: string | null
+ id?: string
+ pageCount?: number | null
+ partId: string
+ 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
+ uploadedBy?: string | null
+ version?: number
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ defaultPageHeight?: number | null
+ defaultPageWidth?: number | null
+ drawingNumber?: string | null
+ fileName?: string | null
+ id?: string
+ pageCount?: number | null
+ partId?: string
+ 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
+ uploadedBy?: string | null
+ version?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_partId_fkey"
+ columns: ["partId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_uploadedBy_fkey"
+ columns: ["uploadedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ inspectionFeature: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: string | null
+ id: string
+ inspectionDocumentId: string
+ label: string
+ nominalValue: string | null
+ pageNumber: number
+ 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
+ toleranceMinus: string | null
+ tolerancePlus: string | null
+ type: Database["public"]["Enums"]["procedureStepType"]
+ unit: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: string | null
+ id?: string
+ inspectionDocumentId: string
+ label: string
+ nominalValue?: string | null
+ pageNumber: number
+ 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
+ toleranceMinus?: string | null
+ tolerancePlus?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unit?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: string | null
+ id?: string
+ inspectionDocumentId?: string
+ label?: string
+ nominalValue?: string | null
+ pageNumber?: number
+ 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
+ toleranceMinus?: string | null
+ tolerancePlus?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unit?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_document_company_fkey"
+ columns: ["inspectionDocumentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_document_company_fkey"
+ columns: ["inspectionDocumentId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ inspectionHistory: {
Row: {
aql: number | null
companyId: string
@@ -16528,7 +17070,7 @@ export type Database = {
createdBy: string
defectsFound: number
id: string
- inboundInspectionId: string
+ inspectionId: string
inspectionLevel: Database["public"]["Enums"]["inspectionLevel"] | null
itemId: string
lotSize: number
@@ -16546,7 +17088,7 @@ export type Database = {
createdBy: string
defectsFound: number
id?: string
- inboundInspectionId: string
+ inspectionId: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16566,7 +17108,7 @@ export type Database = {
createdBy?: string
defectsFound?: number
id?: string
- inboundInspectionId?: string
+ inspectionId?: string
inspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
| null
@@ -16645,9 +17187,9 @@ export type Database = {
},
{
foreignKeyName: "inboundInspectionHistory_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
@@ -16750,192 +17292,205 @@ export type Database = {
},
]
}
- inboundInspectionSample: {
+ inspectionMeasurement: {
Row: {
companyId: string
createdAt: string
createdBy: string
id: string
- inboundInspectionId: string
inspectedAt: string | null
inspectedBy: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ inspectionSampleId: string
notes: string | null
- status: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId: string | null
+ status: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt: string | null
updatedBy: string | null
+ value: number | null
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
id?: string
- inboundInspectionId: string
inspectedAt?: string | null
inspectedBy?: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ inspectionSampleId: string
notes?: string | null
- status?: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt?: string | null
updatedBy?: string | null
+ value?: number | null
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
id?: string
- inboundInspectionId?: string
inspectedAt?: string | null
inspectedBy?: string | null
+ inspectionFeatureId?: string
+ inspectionId?: string
+ inspectionSampleId?: string
notes?: string | null
- status?: Database["public"]["Enums"]["inboundInspectionSampleStatus"]
- trackedEntityId?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
updatedAt?: string | null
updatedBy?: string | null
+ value?: number | null
}
Relationships: [
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inboundInspectionSample_companyId_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_createdBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inboundInspectionSample_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ foreignKeyName: "inboundInspectionMeasurement_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_inspectedBy_fkey"
columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inboundInspectionSample_trackedEntityId_fkey"
- columns: ["trackedEntityId"]
+ foreignKeyName: "inboundInspectionMeasurement_inspectionFeatureId_fkey"
+ columns: ["inspectionFeatureId"]
isOneToOne: false
- referencedRelation: "trackedEntity"
+ referencedRelation: "inspectionFeature"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_sampleId_fkey"
+ columns: ["inspectionSampleId"]
+ isOneToOne: false
+ referencedRelation: "inspectionSample"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionMeasurement_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -16943,429 +17498,350 @@ export type Database = {
},
]
}
- industry: {
- Row: {
- active: boolean
- createdAt: string
- description: string | null
- iconName: string | null
- id: string
- name: string
- sortOrder: number
- updatedAt: string | null
- }
- Insert: {
- active?: boolean
- createdAt?: string
- description?: string | null
- iconName?: string | null
- id: string
- name: string
- sortOrder?: number
- updatedAt?: string | null
- }
- Update: {
- active?: boolean
- createdAt?: string
- description?: string | null
- iconName?: string | null
- id?: string
- name?: string
- sortOrder?: number
- updatedAt?: string | null
- }
- Relationships: []
- }
- inspectionDocument: {
+ inspectionSample: {
Row: {
companyId: string
createdAt: string
createdBy: string
- defaultPageHeight: number | null
- defaultPageWidth: number | null
- drawingNumber: string | null
- fileName: string | null
id: string
- pageCount: number | null
- partId: string
- storagePath: string | null
+ inspectedAt: string | null
+ inspectedBy: string | null
+ inspectionId: string
+ notes: string | null
+ status: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId: string | null
updatedAt: string | null
updatedBy: string | null
- uploadedBy: string | null
- version: number
}
Insert: {
companyId: string
createdAt?: string
createdBy: string
- defaultPageHeight?: number | null
- defaultPageWidth?: number | null
- drawingNumber?: string | null
- fileName?: string | null
id?: string
- pageCount?: number | null
- partId: string
- storagePath?: string | null
+ inspectedAt?: string | null
+ inspectedBy?: string | null
+ inspectionId: string
+ notes?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
- uploadedBy?: string | null
- version?: number
}
Update: {
companyId?: string
createdAt?: string
createdBy?: string
- defaultPageHeight?: number | null
- defaultPageWidth?: number | null
- drawingNumber?: string | null
- fileName?: string | null
id?: string
- pageCount?: number | null
- partId?: string
- storagePath?: string | null
+ inspectedAt?: string | null
+ inspectedBy?: string | null
+ inspectionId?: string
+ notes?: string | null
+ status?: Database["public"]["Enums"]["inspectionSampleStatusType"]
+ trackedEntityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
- uploadedBy?: string | null
- version?: number
}
Relationships: [
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionDocument_companyId_fkey"
+ foreignKeyName: "inboundInspectionSample_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_createdBy_fkey"
+ foreignKeyName: "inboundInspectionSample_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "inspectionDocument_partId_fkey"
- columns: ["partId"]
+ foreignKeyName: "inboundInspectionSample_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "tools"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "inboundInspectionSample_inspectedBy_fkey"
+ columns: ["inspectedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_trackedEntityId_fkey"
+ columns: ["trackedEntityId"]
+ isOneToOne: false
+ referencedRelation: "trackedEntity"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionDocument_uploadedBy_fkey"
- columns: ["uploadedBy"]
+ foreignKeyName: "inboundInspectionSample_updatedBy_fkey"
+ columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
]
}
- inspectionFeature: {
+ inspectionSamplingPlan: {
Row: {
+ acceptanceNumber: number
+ codeLetter: string | null
companyId: string
createdAt: string
createdBy: string
- description: string | null
id: string
- inspectionDocumentId: string
- label: string
- nominalValue: string | null
- pageNumber: number
- toleranceMinus: string | null
- tolerancePlus: string | null
- type: Database["public"]["Enums"]["procedureStepType"]
- unit: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ rejectionNumber: number
+ sampleSize: number
updatedAt: string | null
updatedBy: string | null
}
Insert: {
+ acceptanceNumber: number
+ codeLetter?: string | null
companyId: string
createdAt?: string
createdBy: string
- description?: string | null
id?: string
- inspectionDocumentId: string
- label: string
- nominalValue?: string | null
- pageNumber: number
- toleranceMinus?: string | null
- tolerancePlus?: string | null
- type?: Database["public"]["Enums"]["procedureStepType"]
- unit?: string | null
+ inspectionFeatureId: string
+ inspectionId: string
+ rejectionNumber: number
+ sampleSize: number
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
+ acceptanceNumber?: number
+ codeLetter?: string | null
companyId?: string
createdAt?: string
createdBy?: string
- description?: string | null
id?: string
- inspectionDocumentId?: string
- label?: string
- nominalValue?: string | null
- pageNumber?: number
- toleranceMinus?: string | null
- tolerancePlus?: string | null
- type?: Database["public"]["Enums"]["procedureStepType"]
- unit?: string | null
+ inspectionFeatureId?: string
+ inspectionId?: string
+ rejectionNumber?: number
+ sampleSize?: number
updatedAt?: string | null
updatedBy?: string | null
}
Relationships: [
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "companies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "company"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "customFieldTables"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionFeature_companyId_fkey"
+ foreignKeyName: "inboundInspectionFeature_companyId_fkey"
columns: ["companyId"]
isOneToOne: false
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_createdBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_createdBy_fkey"
columns: ["createdBy"]
isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
{
- foreignKeyName: "inspectionFeature_document_company_fkey"
- columns: ["inspectionDocumentId", "companyId"]
+ foreignKeyName: "inboundInspectionFeature_inboundInspectionId_fkey"
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inspectionDocument"
- referencedColumns: ["id", "companyId"]
+ referencedRelation: "inspection"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_document_company_fkey"
- columns: ["inspectionDocumentId", "companyId"]
+ foreignKeyName: "inboundInspectionFeature_inspectionFeatureId_fkey"
+ columns: ["inspectionFeatureId"]
isOneToOne: false
- referencedRelation: "inspectionDocuments"
- referencedColumns: ["id", "companyId"]
+ referencedRelation: "inspectionFeature"
+ referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeesAcrossCompanies"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
- foreignKeyName: "inspectionFeature_updatedBy_fkey"
+ foreignKeyName: "inboundInspectionFeature_updatedBy_fkey"
columns: ["updatedBy"]
isOneToOne: false
referencedRelation: "userDefaults"
@@ -18387,7 +18863,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string | null
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string | null
revisionStatus: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -18417,7 +18892,6 @@ export type Database = {
readableId: string
readableIdWithRevision?: string | null
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection?: boolean
revision?: string | null
revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType?: Database["public"]["Enums"]["sourcingType"]
@@ -18447,7 +18921,6 @@ export type Database = {
readableId?: string
readableIdWithRevision?: string | null
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection?: boolean
revision?: string | null
revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]
sourcingType?: Database["public"]["Enums"]["sourcingType"]
@@ -18832,6 +19305,194 @@ export type Database = {
},
]
}
+ itemInspectionDocumentAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ inspectionDocumentId: string
+ itemId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ usage: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ inspectionDocumentId: string
+ itemId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ usage: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ inspectionDocumentId?: string
+ itemId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ usage?: Database["public"]["Enums"]["inspectionDocumentUsage"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemInspectionDocumentAssignment_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemLedger: {
Row: {
comment: string | null
@@ -19665,192 +20326,6 @@ export type Database = {
},
]
}
- itemSamplingPlan: {
- Row: {
- aql: number | null
- companyId: string
- createdAt: string
- createdBy: string
- inspectionLevel: Database["public"]["Enums"]["inspectionLevel"]
- itemId: string
- percentage: number | null
- sampleSize: number | null
- severity: Database["public"]["Enums"]["inspectionSeverity"]
- type: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- aql?: number | null
- companyId: string
- createdAt?: string
- createdBy: string
- inspectionLevel?: Database["public"]["Enums"]["inspectionLevel"]
- itemId: string
- percentage?: number | null
- sampleSize?: number | null
- severity?: Database["public"]["Enums"]["inspectionSeverity"]
- type?: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- aql?: number | null
- companyId?: string
- createdAt?: string
- createdBy?: string
- inspectionLevel?: Database["public"]["Enums"]["inspectionLevel"]
- itemId?: string
- percentage?: number | null
- sampleSize?: number | null
- severity?: Database["public"]["Enums"]["inspectionSeverity"]
- type?: Database["public"]["Enums"]["samplingPlanType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: true
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "itemSamplingPlan_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
itemShelfLife: {
Row: {
calculateFromBom: boolean
@@ -21522,6 +21997,50 @@ export type Database = {
},
]
}
+ jobMaterialStep: {
+ Row: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Insert: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Update: {
+ jobMaterialId?: string
+ jobOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -21535,6 +22054,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string
+ inspectionDocumentId: string | null
jobId: string
jobMakeMethodId: string | null
laborRate: number
@@ -21583,6 +22103,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string
+ inspectionDocumentId?: string | null
jobId: string
jobMakeMethodId?: string | null
laborRate?: number
@@ -21631,6 +22152,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string
+ inspectionDocumentId?: string | null
jobId?: string
jobMakeMethodId?: string | null
laborRate?: number
@@ -21773,6 +22295,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -22303,6 +22839,7 @@ export type Database = {
}
jobOperationStep: {
Row: {
+ assemblyInstructionStepId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -22324,6 +22861,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ assemblyInstructionStepId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -22345,6 +22883,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ assemblyInstructionStepId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -22457,6 +22996,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperationStep_assemblyInstructionStepId_fkey"
+ columns: ["assemblyInstructionStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperationStep_nonConformanceActionId_fkey"
columns: ["nonConformanceActionId"]
@@ -22659,6 +23205,181 @@ export type Database = {
},
]
}
+ jobOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobOperationTool: {
Row: {
companyId: string
@@ -22857,6 +23578,36 @@ export type Database = {
},
]
}
+ jobOperationToolStep: {
+ Row: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Insert: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Update: {
+ jobOperationStepId?: string
+ jobOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
+ columns: ["jobOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
journal: {
Row: {
accountingPeriodId: string | null
@@ -27224,6 +27975,36 @@ export type Database = {
},
]
}
+ methodMaterialStep: {
+ Row: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Insert: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Update: {
+ methodMaterialId?: string
+ methodOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
+ columns: ["methodMaterialId"]
+ isOneToOne: false
+ referencedRelation: "methodMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -27233,6 +28014,7 @@ export type Database = {
customFields: Json | null
description: string
id: string
+ inspectionDocumentId: string | null
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
machineTime: number
@@ -27263,6 +28045,7 @@ export type Database = {
customFields?: Json | null
description: string
id?: string
+ inspectionDocumentId?: string | null
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
@@ -27293,6 +28076,7 @@ export type Database = {
customFields?: Json | null
description?: string
id?: string
+ inspectionDocumentId?: string | null
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
@@ -27386,6 +28170,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "methodOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperation_methodId_fkey"
columns: ["makeMethodId"]
@@ -27637,6 +28435,7 @@ export type Database = {
}
methodOperationStep: {
Row: {
+ assemblyInstructionStepId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -27656,6 +28455,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ assemblyInstructionStepId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -27675,6 +28475,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ assemblyInstructionStepId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -27771,6 +28572,188 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "methodOperationStep_assemblyInstructionStepId_fkey"
+ columns: ["assemblyInstructionStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ methodOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
methodOperationTool: {
@@ -27957,6 +28940,36 @@ export type Database = {
},
]
}
+ methodOperationToolStep: {
+ Row: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Insert: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Update: {
+ methodOperationStepId?: string
+ methodOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
+ columns: ["methodOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -29154,13 +30167,13 @@ export type Database = {
},
]
}
- nonConformanceInboundInspection: {
+ nonConformanceInspection: {
Row: {
companyId: string
createdAt: string
createdBy: string
id: string
- inboundInspectionId: string
+ inspectionId: string
nonConformanceId: string
updatedBy: string | null
}
@@ -29169,7 +30182,7 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
- inboundInspectionId: string
+ inspectionId: string
nonConformanceId: string
updatedBy?: string | null
}
@@ -29178,7 +30191,7 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
- inboundInspectionId?: string
+ inspectionId?: string
nonConformanceId?: string
updatedBy?: string | null
}
@@ -29248,9 +30261,9 @@ export type Database = {
},
{
foreignKeyName: "nonConformanceInboundInspection_inboundInspectionId_fkey"
- columns: ["inboundInspectionId"]
+ columns: ["inspectionId"]
isOneToOne: false
- referencedRelation: "inboundInspection"
+ referencedRelation: "inspection"
referencedColumns: ["id"]
},
{
@@ -35531,7 +36544,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id: string
name: string
- processType: Database["public"]["Enums"]["processType"]
+ processType: Database["public"]["Enums"]["operationType"]
tags: string[] | null
updatedAt: string | null
updatedBy: string | null
@@ -35546,7 +36559,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id?: string
name: string
- processType?: Database["public"]["Enums"]["processType"]
+ processType?: Database["public"]["Enums"]["operationType"]
tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
@@ -35561,7 +36574,7 @@ export type Database = {
defaultStandardFactor?: Database["public"]["Enums"]["factor"]
id?: string
name?: string
- processType?: Database["public"]["Enums"]["processType"]
+ processType?: Database["public"]["Enums"]["operationType"]
tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
@@ -35910,6 +36923,8 @@ export type Database = {
createdAt: string
createdBy: string
id: string
+ inspectionId: string | null
+ inspectionSampleId: string | null
jobOperationId: string
laborProductionEventId: string | null
machineProductionEventId: string | null
@@ -35926,6 +36941,8 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
+ inspectionId?: string | null
+ inspectionSampleId?: string | null
jobOperationId: string
laborProductionEventId?: string | null
machineProductionEventId?: string | null
@@ -35942,6 +36959,8 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
+ inspectionId?: string | null
+ inspectionSampleId?: string | null
jobOperationId?: string
laborProductionEventId?: string | null
machineProductionEventId?: string | null
@@ -35982,6 +37001,20 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "productionQuantity_inspectionId_fkey"
+ columns: ["inspectionId"]
+ isOneToOne: false
+ referencedRelation: "inspection"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_inspectionSampleId_fkey"
+ columns: ["inspectionSampleId"]
+ isOneToOne: false
+ referencedRelation: "inspectionSample"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "productionQuantity_jobOperationId_fkey"
columns: ["jobOperationId"]
@@ -37676,7 +38709,6 @@ export type Database = {
receivedComplete: boolean
receivedDate: string | null
requiredDate: string | null
- requiresInspection: boolean
setupPrice: number | null
shippingCost: number | null
sortOrder: number
@@ -37729,7 +38761,6 @@ export type Database = {
receivedComplete?: boolean
receivedDate?: string | null
requiredDate?: string | null
- requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
sortOrder?: number
@@ -37782,7 +38813,6 @@ export type Database = {
receivedComplete?: boolean
receivedDate?: string | null
requiredDate?: string | null
- requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
sortOrder?: number
@@ -41144,14 +42174,53 @@ export type Database = {
},
]
}
+ quoteMaterialStep: {
+ Row: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Insert: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Update: {
+ quoteMaterialId?: string
+ quoteOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quoteOperation: {
Row: {
+ assemblyInstructionId: string | null
companyId: string
createdAt: string
createdBy: string
customFields: Json | null
description: string | null
id: string
+ inspectionDocumentId: string | null
laborRate: number
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
@@ -41180,12 +42249,14 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
companyId: string
createdAt?: string
createdBy: string
customFields?: Json | null
description?: string | null
id?: string
+ inspectionDocumentId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
@@ -41214,12 +42285,14 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
customFields?: Json | null
description?: string | null
id?: string
+ inspectionDocumentId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
@@ -41248,6 +42321,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_companyId_fkey"
columns: ["companyId"]
@@ -41311,6 +42391,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
columns: ["operationSupplierProcessId"]
@@ -41740,6 +42834,181 @@ export type Database = {
},
]
}
+ quoteOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string | null
+ modelUploadId: string | null
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string | null
+ modelUploadId?: string | null
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
quoteOperationTool: {
Row: {
companyId: string
@@ -41931,6 +43200,36 @@ export type Database = {
},
]
}
+ quoteOperationToolStep: {
+ Row: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Insert: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Update: {
+ quoteOperationStepId?: string
+ quoteOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
+ columns: ["quoteOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quotePayment: {
Row: {
companyId: string
@@ -44526,7 +45825,6 @@ export type Database = {
quantitySent: number | null
quantityToInvoice: number | null
quantityToSend: number | null
- requiresInspection: boolean
saleQuantity: number | null
salesOrderId: string
salesOrderLineType: Database["public"]["Enums"]["salesOrderLineType"]
@@ -44573,7 +45871,6 @@ export type Database = {
quantitySent?: number | null
quantityToInvoice?: number | null
quantityToSend?: number | null
- requiresInspection?: boolean
saleQuantity?: number | null
salesOrderId: string
salesOrderLineType: Database["public"]["Enums"]["salesOrderLineType"]
@@ -44620,7 +45917,6 @@ export type Database = {
quantitySent?: number | null
quantityToInvoice?: number | null
quantityToSend?: number | null
- requiresInspection?: boolean
saleQuantity?: number | null
salesOrderId?: string
salesOrderLineType?: Database["public"]["Enums"]["salesOrderLineType"]
@@ -63692,7 +64988,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"] | null
id: string | null
name: string | null
- processType: Database["public"]["Enums"]["processType"] | null
+ processType: Database["public"]["Enums"]["operationType"] | null
suppliers: Json | null
tags: string[] | null
updatedAt: string | null
@@ -64490,7 +65786,6 @@ export type Database = {
receivedComplete: boolean | null
receivedDate: string | null
requiredDate: string | null
- requiresInspection: boolean | null
setupPrice: number | null
shippingCost: number | null
sortOrder: number | null
@@ -64832,14 +66127,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -68225,14 +69520,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -68554,7 +69849,6 @@ export type Database = {
quantitySent: number | null
quantityToInvoice: number | null
quantityToSend: number | null
- requiresInspection: boolean | null
saleQuantity: number | null
salesOrderId: string | null
salesOrderLineType:
@@ -68780,14 +70074,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -72598,7 +73892,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
supplierIds: string
@@ -72958,6 +74251,7 @@ export type Database = {
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationType: Database["public"]["Enums"]["operationType"]
parentMaterialId: string
processId: string
quantityComplete: number
@@ -73183,7 +74477,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
supplierIds: string
@@ -73225,6 +74518,7 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
+ methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -73304,7 +74598,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -73821,7 +75114,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -73873,7 +75165,6 @@ export type Database = {
readableId: string
readableIdWithRevision: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
- requiresInspection: boolean
revision: string
revisions: Json
sourcingType: Database["public"]["Enums"]["sourcingType"]
@@ -74578,13 +75869,6 @@ export type Database = {
approvalDocumentType: "purchaseOrder" | "qualityDocument" | "supplier"
approvalStatus: "Pending" | "Approved" | "Rejected" | "Cancelled"
assemblyInstructionStatus: "Draft" | "Published" | "Archived"
- assemblyNoteSeverity: "Info" | "Caution" | "Warning"
- assemblyRequirementType:
- | "Tool"
- | "Fixture"
- | "Consumable"
- | "Note"
- | "Media"
assemblyStepStatus: "Todo" | "Review" | "Done"
changeOrderChangeType:
| "Version"
@@ -74751,13 +76035,6 @@ export type Database = {
| "complete"
| "archived"
implementationTier: "self_serve" | "guided" | "enterprise"
- inboundInspectionSampleStatus: "Pending" | "Passed" | "Failed"
- inboundInspectionStatus:
- | "Pending"
- | "In Progress"
- | "Passed"
- | "Failed"
- | "Partial"
incoterm:
| "EXW"
| "FCA"
@@ -74770,9 +76047,18 @@ export type Database = {
| "DAP"
| "DPU"
| "DDP"
+ inspectionDocumentUsage: "Receipt"
inspectionLevel: "I" | "II" | "III" | "S1" | "S2" | "S3" | "S4"
+ inspectionSampleStatusType: "Pending" | "Passed" | "Failed"
inspectionSeverity: "Normal" | "Tightened" | "Reduced"
+ inspectionSourceDocument: "Receipt" | "Job Operation"
inspectionStatus: "Pass" | "Fail"
+ inspectionStatusType:
+ | "Pending"
+ | "In Progress"
+ | "Passed"
+ | "Failed"
+ | "Partial"
inventoryCountStatus: "Draft" | "Pending" | "Posted"
itemCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO"
itemLedgerDocumentType:
@@ -74870,6 +76156,8 @@ export type Database = {
| "Payment"
| "Credit Memo"
| "Debit Memo"
+ | "Non-Conformance"
+ | "Inbound Inspection"
journalEntryStatus: "Draft" | "Posted" | "Reversed"
journalLineDocumentType:
| "Receipt"
@@ -74891,6 +76179,8 @@ export type Database = {
| "Memo"
| "Inventory Adjustment"
| "Inventory Count"
+ | "Non-Conformance"
+ | "Inbound Inspection"
kanbanOutput: "label" | "qrcode" | "url"
macrsConvention: "Half-Year" | "Mid-Quarter"
macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"
@@ -74975,7 +76265,11 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
- operationType: "Inside" | "Outside"
+ operationType:
+ | "Process"
+ | "Assembly"
+ | "Inspection"
+ | "Outside Processing"
payableLineType:
| "Comment"
| "G/L Account"
@@ -75007,7 +76301,6 @@ export type Database = {
| "File"
| "Task"
| "Inspection"
- processType: "Inside" | "Outside" | "Inside and Outside"
productionEventType: "Setup" | "Labor" | "Machine"
productionQuantityType: "Rework" | "Scrap" | "Production"
purchaseInvoiceStatus:
@@ -75925,14 +77218,6 @@ export const Constants = {
approvalDocumentType: ["purchaseOrder", "qualityDocument", "supplier"],
approvalStatus: ["Pending", "Approved", "Rejected", "Cancelled"],
assemblyInstructionStatus: ["Draft", "Published", "Archived"],
- assemblyNoteSeverity: ["Info", "Caution", "Warning"],
- assemblyRequirementType: [
- "Tool",
- "Fixture",
- "Consumable",
- "Note",
- "Media",
- ],
assemblyStepStatus: ["Todo", "Review", "Done"],
changeOrderChangeType: [
"Version",
@@ -76117,14 +77402,6 @@ export const Constants = {
"archived",
],
implementationTier: ["self_serve", "guided", "enterprise"],
- inboundInspectionSampleStatus: ["Pending", "Passed", "Failed"],
- inboundInspectionStatus: [
- "Pending",
- "In Progress",
- "Passed",
- "Failed",
- "Partial",
- ],
incoterm: [
"EXW",
"FCA",
@@ -76138,9 +77415,19 @@ export const Constants = {
"DPU",
"DDP",
],
+ inspectionDocumentUsage: ["Receipt"],
inspectionLevel: ["I", "II", "III", "S1", "S2", "S3", "S4"],
+ inspectionSampleStatusType: ["Pending", "Passed", "Failed"],
inspectionSeverity: ["Normal", "Tightened", "Reduced"],
+ inspectionSourceDocument: ["Receipt", "Job Operation"],
inspectionStatus: ["Pass", "Fail"],
+ inspectionStatusType: [
+ "Pending",
+ "In Progress",
+ "Passed",
+ "Failed",
+ "Partial",
+ ],
inventoryCountStatus: ["Draft", "Pending", "Posted"],
itemCostingMethod: ["Standard", "Average", "LIFO", "FIFO"],
itemLedgerDocumentType: [
@@ -76245,6 +77532,8 @@ export const Constants = {
"Payment",
"Credit Memo",
"Debit Memo",
+ "Non-Conformance",
+ "Inbound Inspection",
],
journalEntryStatus: ["Draft", "Posted", "Reversed"],
journalLineDocumentType: [
@@ -76267,6 +77556,8 @@ export const Constants = {
"Memo",
"Inventory Adjustment",
"Inventory Count",
+ "Non-Conformance",
+ "Inbound Inspection",
],
kanbanOutput: ["label", "qrcode", "url"],
macrsConvention: ["Half-Year", "Mid-Quarter"],
@@ -76361,7 +77652,12 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
- operationType: ["Inside", "Outside"],
+ operationType: [
+ "Process",
+ "Assembly",
+ "Inspection",
+ "Outside Processing",
+ ],
payableLineType: [
"Comment",
"G/L Account",
@@ -76395,7 +77691,6 @@ export const Constants = {
"Task",
"Inspection",
],
- processType: ["Inside", "Outside", "Inside and Outside"],
productionEventType: ["Setup", "Labor", "Machine"],
productionQuantityType: ["Rework", "Scrap", "Production"],
purchaseInvoiceStatus: [
diff --git a/packages/database/supabase/functions/post-nonconformance/.npmrc b/packages/database/supabase/functions/post-nonconformance/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/post-nonconformance/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.ts
new file mode 100644
index 0000000000..7d1ebc294d
--- /dev/null
+++ b/packages/database/supabase/functions/post-nonconformance/index.ts
@@ -0,0 +1,299 @@
+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { z } from "https://deno.land/x/[email protected]/mod.ts";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getFunctionLogger } from "../lib/logging.ts";
+import { requirePermissions } from "../lib/supabase.ts";
+import { Database } from "../lib/types.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import {
+ AdjustmentItemCost,
+ bookAdjustment,
+ createAdjustmentJournal,
+} from "../shared/post-adjustment.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+const logger = getFunctionLogger("post-nonconformance");
+
+// The GL/cost posting path for inspection-reject and NCR-disposition inventory
+// write-offs. The caller (inspection reject route / closeIssue) owns the
+// physical/status side — tracked-entity flips, nonConformance.status — and hands
+// this function a batch of explicit SIGNED movements. In ONE transaction each
+// movement books through the shared core: item ledger + cost layers + (when
+// companySettings.accountingEnabled) a balanced journal against the company's
+// scrapAccount (offset), one shared journal per call. Scrap / Return post a
+// Negative Adjmt. (Dr Scrap / Cr Inventory + relieve layers); a kept lot's
+// restore posts a Positive Adjmt. (Dr Inventory / Cr Scrap + create a layer).
+const payloadValidator = z.object({
+ companyId: z.string(),
+ userId: z.string(),
+ // Drives both the itemLedger/costLedger documentType and the journal
+ // sourceType — 'Non-Conformance' for a disposition close, 'Inbound Inspection'
+ // for an inspection reject.
+ documentType: z.enum(["Non-Conformance", "Inbound Inspection"]),
+ documentId: z.string(),
+ description: z.string().optional().nullable(),
+ postingDate: z.string().optional().nullable(),
+ movements: z
+ .array(
+ z.object({
+ itemId: z.string(),
+ locationId: z.string().optional().nullable(),
+ trackedEntityId: z.string().optional().nullable(),
+ // SIGNED: < 0 removes value (scrap/return), > 0 restores value (kept).
+ quantity: z.number(),
+ comment: z.string().optional().nullable(),
+ })
+ )
+ .min(1),
+});
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ const payload = await req.json();
+ const {
+ companyId,
+ userId,
+ documentType,
+ documentId,
+ description,
+ postingDate: providedPostingDate,
+ movements,
+ } = payloadValidator.parse(payload);
+
+ const client = await requirePermissions(req, companyId, userId, {
+ update: "quality",
+ });
+
+ const postingDate = providedPostingDate || format(new Date(), "yyyy-MM-dd");
+
+ // Only movements that actually move stock post anything.
+ const effectiveMovements = movements.filter((m) => m.quantity !== 0);
+ if (effectiveMovements.length === 0) {
+ return new Response(JSON.stringify({ success: true, journalId: null }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ });
+ }
+
+ const itemIds = [...new Set(effectiveMovements.map((m) => m.itemId))];
+
+ const [itemsResult, itemCostsResult, accountingSettings] =
+ await Promise.all([
+ client
+ .from("item")
+ .select("id, itemTrackingType, replenishmentSystem")
+ .in("id", itemIds)
+ .eq("companyId", companyId),
+ client
+ .from("itemCost")
+ .select("itemId, costingMethod, unitCost, standardCost, itemPostingGroupId")
+ .in("itemId", itemIds)
+ .eq("companyId", companyId),
+ client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single(),
+ ]);
+
+ if (itemsResult.error) throw new Error("Failed to fetch items");
+ if (itemCostsResult.error) throw new Error("Failed to fetch item costs");
+ if (accountingSettings.error) {
+ throw new Error("Failed to fetch company settings");
+ }
+
+ // The generated types are deep enough that a multi-row .select() infers as
+ // {} here; type the projected rows explicitly (the reference sidesteps this
+ // via .single()).
+ type NcItemRow = {
+ id: string;
+ itemTrackingType: string | null;
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null;
+ };
+ type NcItemCostRow = {
+ itemId: string;
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];
+ unitCost: number | null;
+ standardCost: number | null;
+ itemPostingGroupId: string | null;
+ };
+ const itemById = new Map<string, NcItemRow>(
+ ((itemsResult.data ?? []) as NcItemRow[]).map((row) => [row.id, row])
+ );
+ const costByItem = new Map<string, NcItemCostRow>(
+ ((itemCostsResult.data ?? []) as NcItemCostRow[]).map((row) => [
+ row.itemId,
+ row,
+ ])
+ );
+
+ // The accountingEnabled flag gates ALL journal writes: when false the posting
+ // core still moves the ledger + cost layers, just no journal. Fail closed —
+ // a failed settings read must not silently post without GL.
+ const accountingEnabled =
+ accountingSettings.data?.accountingEnabled ?? false;
+ const accountDefaults = accountingEnabled
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (
+ accountingEnabled &&
+ (accountDefaults?.error || !accountDefaults?.data)
+ ) {
+ throw new Error("Error getting account defaults");
+ }
+
+ // Active dimensions for the company group — journal lines get
+ // Item / ItemPostingGroup / Location tags (post-adjustment precedent).
+ const dimensionMap: Record<string, string> = {};
+ if (accountingEnabled) {
+ const companyRecord = await client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single();
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const dimensions = await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["Item", "ItemPostingGroup", "Location"]);
+ if (dimensions.error) throw new Error("Failed to fetch dimensions");
+ for (const dim of dimensions.data ?? []) {
+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;
+ }
+ }
+
+ // Resolve the accounting period BEFORE opening the transaction —
+ // getCurrentAccountingPeriod uses the REST client and calling it
+ // mid-transaction parks the (size 1) pool in idle-in-transaction.
+ const accountingPeriodId = accountingEnabled
+ ? await getCurrentAccountingPeriod(client, companyId, db)
+ : null;
+
+ const journalDescription =
+ description?.trim() ||
+ (documentType === "Inbound Inspection"
+ ? "Inbound Inspection write-off"
+ : "Non-Conformance disposition");
+
+ let journalId: string | null = null;
+
+ await db.transaction().execute(async (trx) => {
+ // Idempotent per (documentType, documentId): a reject posts one write-off
+ // per inspection, a disposition close posts once per NCR (reopen is blocked
+ // after posting). A retry after a partial route failure — e.g. the caller's
+ // status/NCR step failed after this already committed — must not double-post.
+ const alreadyPosted = await trx
+ .selectFrom("itemLedger")
+ .select("id")
+ .where("companyId", "=", companyId)
+ .where("documentType", "=", documentType)
+ .where("documentId", "=", documentId)
+ .limit(1)
+ .executeTakeFirst();
+ if (alreadyPosted) return;
+
+ // One shared journal per call (per reject / per disposition close), a line
+ // pair per movement — created lazily so an all-zero-value run posts none.
+ const accounting =
+ accountingEnabled && accountDefaults?.data && accountingPeriodId
+ ? {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount,
+ },
+ // Cost of quality: offset to scrapAccount, falling back to the
+ // variance account for companies whose scrapAccount is unset.
+ offsetAccount:
+ accountDefaults.data.scrapAccount ??
+ accountDefaults.data.inventoryAdjustmentVarianceAccount,
+ offsetDescription: "Scrap / Cost of Quality",
+ sourceType: documentType,
+ description: journalDescription,
+ userId,
+ dimensions: dimensionMap,
+ getJournalId: async () => {
+ if (!journalId) {
+ journalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId,
+ description: journalDescription,
+ postingDate,
+ userId,
+ sourceType: documentType,
+ });
+ }
+ return journalId;
+ },
+ }
+ : null;
+
+ for (const movement of effectiveMovements) {
+ const itemRow = itemById.get(movement.itemId);
+ if (!itemRow) throw new Error(`Item ${movement.itemId} not found`);
+ const costRow = costByItem.get(movement.itemId);
+ // Missing itemCost (rare) — post the ledger movement at zero value so a
+ // disposition is never blocked; no journal results from a zero cost.
+ const itemCost: AdjustmentItemCost = costRow
+ ? {
+ costingMethod: costRow.costingMethod,
+ unitCost: costRow.unitCost,
+ standardCost: costRow.standardCost,
+ }
+ : { costingMethod: "Average", unitCost: 0, standardCost: 0 };
+
+ await bookAdjustment(trx, {
+ ledger: {
+ postingDate,
+ itemId: movement.itemId,
+ quantity: movement.quantity,
+ locationId: movement.locationId ?? null,
+ storageUnitId: null,
+ trackedEntityId: movement.trackedEntityId ?? null,
+ entryType:
+ movement.quantity < 0 ? "Negative Adjmt." : "Positive Adjmt.",
+ documentType,
+ documentId,
+ comment: movement.comment ?? null,
+ companyId,
+ createdBy: userId,
+ },
+ item: {
+ itemTrackingType: itemRow.itemTrackingType,
+ replenishmentSystem: itemRow.replenishmentSystem,
+ itemPostingGroupId: costRow?.itemPostingGroupId ?? null,
+ },
+ itemCost,
+ accounting,
+ });
+ }
+ });
+
+ return new Response(JSON.stringify({ success: true, journalId }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ });
+ } catch (err) {
+ logger.error("post-nonconformance failed", {
+ error: String((err as Error).stack ?? err),
+ });
+ return new Response(JSON.stringify({ error: (err as Error).message }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 97f3ad0927..564377af1e 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -20,6 +20,7 @@ import {
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
import {
+ resolveFeatureSamplingPlan,
resolveSamplingPlan,
type SamplingStandard,
} from "../shared/sampling-engine.ts";
@@ -105,30 +106,22 @@ serve(async (req: Request) => {
}
return acc;
}, []);
- const [items, itemCosts, companySettings, itemSamplingPlans] =
- await Promise.all([
- client
- .from("item")
- .select("id, itemTrackingType, replenishmentSystem, requiresInspection")
- .in("id", itemIds)
- .eq("companyId", companyId),
- client
- .from("itemCost")
- .select("itemId, itemPostingGroupId")
- .in("itemId", itemIds),
- client
- .from("companySettings")
- .select("samplingStandard")
- .eq("id", companyId)
- .single(),
- (client as any)
- .from("itemSamplingPlan")
- .select(
- "itemId, type, sampleSize, percentage, aql, inspectionLevel, severity"
- )
- .in("itemId", itemIds)
- .eq("companyId", companyId),
- ]);
+ const [items, itemCosts, companySettings] = await Promise.all([
+ client
+ .from("item")
+ .select("id, itemTrackingType, replenishmentSystem")
+ .in("id", itemIds)
+ .eq("companyId", companyId),
+ client
+ .from("itemCost")
+ .select("itemId, itemPostingGroupId")
+ .in("itemId", itemIds),
+ client
+ .from("companySettings")
+ .select("samplingStandard")
+ .eq("id", companyId)
+ .single(),
+ ]);
if (items.error) {
throw new Error("Failed to fetch items");
}
@@ -138,10 +131,68 @@ serve(async (req: Request) => {
const samplingStandard: SamplingStandard =
(companySettings.data as any)?.samplingStandard ?? "ANSI_Z1_4";
- const samplingPlansByItemId = new Map<string, any>(
- ((itemSamplingPlans.data as any[]) ?? []).map((p) => [p.itemId, p])
+
+ // Receipt-usage inspection document assignments drive per-feature
+ // measurement plans on the created lots.
+ const inspectionDocumentAssignments = await (client as any)
+ .from("itemInspectionDocumentAssignment")
+ .select("itemId, inspectionDocumentId")
+ .eq("companyId", companyId)
+ .eq("usage", "Receipt")
+ .in("itemId", itemIds);
+ const assignmentByItemId = new Map<string, string>(
+ ((inspectionDocumentAssignments.data as any[]) ?? []).map((a) => [
+ a.itemId,
+ a.inspectionDocumentId,
+ ])
);
-
+ const assignedDocumentIds = [...new Set(assignmentByItemId.values())];
+ const inspectionFeaturesByDocumentId = new Map<string, any[]>();
+ if (assignedDocumentIds.length > 0) {
+ const inspectionFeatures = await (client as any)
+ .from("inspectionFeature")
+ .select(
+ "id, inspectionDocumentId, type, samplingPlanType, samplingSampleSize, samplingPercentage, samplingAql, samplingInspectionLevel, samplingSeverity"
+ )
+ .in("inspectionDocumentId", assignedDocumentIds)
+ .eq("companyId", companyId);
+ for (const feature of (inspectionFeatures.data as any[]) ?? []) {
+ const list =
+ inspectionFeaturesByDocumentId.get(feature.inspectionDocumentId) ??
+ [];
+ list.push(feature);
+ inspectionFeaturesByDocumentId.set(feature.inspectionDocumentId, list);
+ }
+ }
+
+ // The document's default sampling rule is the lot-level plan base and the
+ // fallback for features without their own rule (feature rule -> document
+ // default -> All).
+ const documentDefaultByDocumentId = new Map<string, any>();
+ if (assignedDocumentIds.length > 0) {
+ const assignedDocuments = await (client as any)
+ .from("inspectionDocument")
+ .select(
+ "id, samplingPlanType, samplingSampleSize, samplingPercentage, samplingAql, samplingInspectionLevel, samplingSeverity"
+ )
+ .in("id", assignedDocumentIds)
+ .eq("companyId", companyId);
+ for (const doc of (assignedDocuments.data as any[]) ?? []) {
+ if (!doc.samplingPlanType) continue;
+ documentDefaultByDocumentId.set(doc.id, {
+ type: doc.samplingPlanType,
+ sampleSize: doc.samplingSampleSize,
+ percentage:
+ doc.samplingPercentage == null
+ ? null
+ : Number(doc.samplingPercentage),
+ aql: doc.samplingAql == null ? null : Number(doc.samplingAql),
+ inspectionLevel: doc.samplingInspectionLevel,
+ severity: doc.samplingSeverity,
+ });
+ }
+ }
+
if (type === "void") {
if (receipt.data?.status !== "Posted") {
throw new Error("Can only void posted receipts");
@@ -656,16 +707,36 @@ serve(async (req: Request) => {
return acc;
}, {});
- // Build one inspection lot per receiptLine that belongs to an item
- // with requiresInspection = true. Compute the sampling plan snapshot
- // from the company's chosen standard and the item's plan (or default
- // to "Inspect All" if no plan is configured).
- const inboundInspectionInserts: Array<Record<string, any>> = [];
+ // Build one inspection lot per receiptLine whose item has a Receipt-usage
+ // inspection plan (a document assignment). The assigned document is the
+ // plan for the receipt; without one, no lot is created. Compute the
+ // sampling plan snapshot from the company's chosen standard and the
+ // document's default plan (or "Inspect All" when the document has none).
+ const inspectionInserts: Array<Record<string, any>> = [];
+ // Per-feature resolved plans, keyed by receiptLineId until the lot ids
+ // exist (they are joined after the insert returns ids).
+ type InspectionSamplingPlanInsert = {
+ inspectionFeatureId: string;
+ sampleSize: number;
+ acceptanceNumber: number;
+ rejectionNumber: number;
+ codeLetter: string | null;
+ companyId: string;
+ createdBy: string;
+ };
+ const samplingPlanInsertsByReceiptLineId = new Map<
+ string,
+ Array<InspectionSamplingPlanInsert>
+ >();
for (const receiptLine of receiptLines.data ?? []) {
- const item = items.data?.find((i) => i.id === receiptLine.itemId);
- if (!item?.requiresInspection) continue;
if (!receiptLine.itemId) continue;
+ // An item is inspected at receipt when it has a Receipt-usage
+ // inspection plan (document assignment); without one, no lot.
+ const assignedDocumentId =
+ assignmentByItemId.get(receiptLine.itemId) ?? null;
+ if (!assignedDocumentId) continue;
+
const safeReceivedQuantity =
isNaN(receiptLine.receivedQuantity as any) ||
receiptLine.receivedQuantity == null
@@ -673,7 +744,11 @@ serve(async (req: Request) => {
: receiptLine.receivedQuantity;
if (safeReceivedQuantity <= 0) continue;
- const plan = samplingPlansByItemId.get(receiptLine.itemId) ?? {
+ const documentDefault = assignedDocumentId
+ ? (documentDefaultByDocumentId.get(assignedDocumentId) ?? null)
+ : null;
+
+ const plan = documentDefault ?? {
type: "All",
sampleSize: null,
percentage: null,
@@ -688,31 +763,68 @@ serve(async (req: Request) => {
samplingStandard
);
- inboundInspectionInserts.push({
- receiptLineId: receiptLine.id,
- receiptId,
+ const documentFeatures = assignedDocumentId
+ ? (inspectionFeaturesByDocumentId.get(assignedDocumentId) ?? [])
+ : [];
+ const featurePlans = documentFeatures.map((feature) => ({
+ inspectionFeatureId: feature.id,
+ resolved: resolveFeatureSamplingPlan(
+ feature,
+ documentDefault,
+ safeReceivedQuantity,
+ samplingStandard
+ ),
+ }));
+ if (featurePlans.length > 0) {
+ samplingPlanInsertsByReceiptLineId.set(
+ receiptLine.id,
+ featurePlans.map((p) => ({
+ inspectionFeatureId: p.inspectionFeatureId,
+ sampleSize: p.resolved.sampleSize,
+ acceptanceNumber: p.resolved.acceptance,
+ rejectionNumber: p.resolved.rejection,
+ codeLetter: p.resolved.codeLetter,
+ companyId,
+ createdBy: userId,
+ }))
+ );
+ }
+
+ inspectionInserts.push({
+ sourceDocument: "Receipt",
+ sourceDocumentId: receiptId,
+ sourceDocumentLineId: receiptLine.id,
+ sourceDocumentReadableId: receipt.data.receiptId ?? null,
itemId: receiptLine.itemId,
itemReadableId: receiptLine.itemReadableId,
supplierId: purchaseOrder.data.supplierId ?? null,
lotSize: safeReceivedQuantity,
samplingStandard,
samplingPlanType: plan.type,
- sampleSize: snapshot.sampleSize,
+ // With a document attached, the lot-level sample size is the max
+ // across the per-feature plans (SAP-style); Ac/Re remain the
+ // item-plan fallback numbers used by the no-document flow.
+ sampleSize:
+ featurePlans.length > 0
+ ? Math.max(...featurePlans.map((p) => p.resolved.sampleSize))
+ : snapshot.sampleSize,
acceptanceNumber: snapshot.acceptance,
rejectionNumber: snapshot.rejection,
aql: plan.aql ?? null,
inspectionLevel: plan.inspectionLevel ?? null,
severity: plan.severity ?? null,
codeLetter: snapshot.codeLetter,
+ inspectionDocumentId: assignedDocumentId,
status: "Pending",
companyId,
createdBy: userId,
});
}
- // Tracked entities for items requiring inspection stay On Hold after
- // posting (they are released individually by the sample inspection or
- // en masse by lot disposition). Everything else flips to Available.
+ // Tracked entities for items with a Receipt-usage inspection plan stay
+ // On Hold after posting (they are released individually by the sample
+ // inspection or en masse by lot disposition). Everything else flips to
+ // Available.
const trackedEntityUpdates =
receiptLineTracking.data?.reduce<
Record<
@@ -738,10 +850,9 @@ serve(async (req: Request) => {
? 1
: safeReceivedQuantity || itemTracking.quantity;
- const item = items.data?.find(
- (item) => item.id === receiptLine?.itemId
- );
- const requiresInspection = item?.requiresInspection === true;
+ const requiresInspection = receiptLine?.itemId
+ ? assignmentByItemId.has(receiptLine.itemId)
+ : false;
acc[itemTracking.id] = {
status: requiresInspection ? "On Hold" : "Available",
@@ -1812,18 +1923,43 @@ serve(async (req: Request) => {
}
}
- if (inboundInspectionInserts.length > 0) {
- for (const row of inboundInspectionInserts) {
- row.inboundInspectionId = await getNextSequence(
+ if (inspectionInserts.length > 0) {
+ for (const row of inspectionInserts) {
+ row.inspectionId = await getNextSequence(
trx,
- "inboundInspection",
+ "inspection",
companyId
);
}
- await trx
- .insertInto("inboundInspection")
- .values(inboundInspectionInserts)
+ const insertedInspections = await trx
+ .insertInto("inspection")
+ .values(inspectionInserts)
+ .returning(["id", "sourceDocumentLineId"])
.execute();
+
+ const samplingPlanInserts: Array<
+ InspectionSamplingPlanInsert & { inspectionId: string }
+ > = [];
+ for (const inspection of insertedInspections) {
+ const featureRows = inspection.sourceDocumentLineId
+ ? samplingPlanInsertsByReceiptLineId.get(
+ inspection.sourceDocumentLineId
+ )
+ : undefined;
+ if (!featureRows) continue;
+ for (const featureRow of featureRows) {
+ samplingPlanInserts.push({
+ ...featureRow,
+ inspectionId: inspection.id,
+ });
+ }
+ }
+ if (samplingPlanInserts.length > 0) {
+ await trx
+ .insertInto("inspectionSamplingPlan")
+ .values(samplingPlanInserts)
+ .execute();
+ }
}
});
break;
diff --git a/packages/database/supabase/functions/shared/get-next-sequence.ts b/packages/database/supabase/functions/shared/get-next-sequence.ts
index f053b8be40..377c8b28b4 100644
--- a/packages/database/supabase/functions/shared/get-next-sequence.ts
+++ b/packages/database/supabase/functions/shared/get-next-sequence.ts
@@ -1,5 +1,8 @@
import { Transaction } from "kysely";
-import { DB } from "../lib/database.ts";
+// Type-only import from postgres/index.ts (not lib/database.ts) keeps the
+// Deno-only driver out of the graph so this file is also importable from the
+// node-side @carbon/database/quality engine.
+import type { KyselyDatabase as DB } from "../lib/postgres/index.ts";
import { interpolateSequenceDate } from "../lib/utils.ts";
export async function getNextSequence(
diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.ts
index 73be2649f5..aebccfaf26 100644
--- a/packages/database/supabase/functions/shared/post-adjustment.ts
+++ b/packages/database/supabase/functions/shared/post-adjustment.ts
@@ -28,8 +28,14 @@ export interface BookAdjustmentArgs {
trackedEntityId: string | null;
entryType: "Positive Adjmt." | "Negative Adjmt.";
// itemLedgerDocumentType — manual adjustments stay NULL (ledger rows keep
- // today's shape; 'Inventory Adjustment' exists only on journalLineDocumentType)
- documentType?: "Inventory Count" | null;
+ // today's shape; 'Inventory Adjustment' exists only on journalLineDocumentType).
+ // Non-Conformance / Inbound Inspection tag NCR-disposition & inspection-reject
+ // write-offs (these also flow to the journal line's documentType).
+ documentType?:
+ | "Inventory Count"
+ | "Non-Conformance"
+ | "Inbound Inspection"
+ | null;
documentId?: string | null;
correctionOfItemLedgerId?: string | null;
comment?: string | null;
@@ -52,6 +58,15 @@ export interface BookAdjustmentArgs {
finishedGoodsAccount: string;
inventoryAdjustmentVarianceAccount: string;
};
+ // Offset (non-inventory) side of the balanced pair. Defaults to
+ // inventoryAdjustmentVarianceAccount; NCR-disposition / inspection-reject
+ // write-offs pass the company's scrapAccount so cost of quality is separable
+ // on the P&L.
+ offsetAccount?: string | null;
+ offsetDescription?: string;
+ // journal.sourceType for a header this call creates (default
+ // 'Inventory Adjustment'). Ignored when getJournalId supplies a shared journal.
+ sourceType?: Database["public"]["Enums"]["journalEntrySourceType"];
description: string;
userId: string;
// active dimensions for the company group, entityType → dimension id
@@ -82,6 +97,7 @@ export interface CreateAdjustmentJournalArgs {
description: string;
postingDate: string;
userId: string;
+ sourceType?: Database["public"]["Enums"]["journalEntrySourceType"];
}
// One journal header for adjustment postings ('Inventory Adjustment' source,
@@ -104,7 +120,7 @@ export async function createAdjustmentJournal(
description: args.description,
postingDate: args.postingDate,
companyId: args.companyId,
- sourceType: "Inventory Adjustment",
+ sourceType: args.sourceType ?? "Inventory Adjustment",
status: "Posted",
postedAt: new Date().toISOString(),
postedBy: args.userId,
@@ -267,6 +283,7 @@ export async function bookAdjustment(
description: accounting.description,
postingDate: ledger.postingDate,
userId: accounting.userId,
+ sourceType: accounting.sourceType,
});
const inventoryAccount = resolveInventoryAccount(
@@ -293,8 +310,10 @@ export async function bookAdjustment(
},
{
journalId,
- accountId: accounting.accountDefaults.inventoryAdjustmentVarianceAccount,
- description: "Inventory Adjustment",
+ accountId:
+ accounting.offsetAccount ??
+ accounting.accountDefaults.inventoryAdjustmentVarianceAccount,
+ description: accounting.offsetDescription ?? "Inventory Adjustment",
amount: isGain ? credit("expense", cost) : debit("expense", cost),
quantity: absQuantity,
documentType: journalLineDocumentType,
diff --git a/packages/database/supabase/functions/shared/sampling-engine.ts b/packages/database/supabase/functions/shared/sampling-engine.ts
index 422aaf85e8..40b4e8db0e 100644
--- a/packages/database/supabase/functions/shared/sampling-engine.ts
+++ b/packages/database/supabase/functions/shared/sampling-engine.ts
@@ -173,3 +173,34 @@ export function resolveSamplingPlan(
}
return { sampleSize: cell.n, acceptance: cell.Ac, rejection: cell.Re, codeLetter: letter, standard };
}
+
+export type FeatureSamplingRule = {
+ samplingPlanType?: SamplingPlanType | null;
+ samplingSampleSize?: number | null;
+ samplingPercentage?: number | null;
+ samplingAql?: number | null;
+ samplingInspectionLevel?: InspectionLevel | null;
+ samplingSeverity?: InspectionSeverity | null;
+};
+
+// Per-feature resolution: a feature's own rule wins, else the inspection
+// document's default rule, else 100% inspection. Mirrors samplingStandards.ts
+// — keep in sync.
+export function resolveFeatureSamplingPlan(
+ feature: FeatureSamplingRule | null | undefined,
+ defaultPlan: SamplingPlanInput | null | undefined,
+ lotSize: number,
+ standard: SamplingStandard
+): SamplingResult {
+ const plan: SamplingPlanInput = feature?.samplingPlanType
+ ? {
+ type: feature.samplingPlanType,
+ sampleSize: feature.samplingSampleSize ?? undefined,
+ percentage: feature.samplingPercentage ?? undefined,
+ aql: feature.samplingAql ?? undefined,
+ inspectionLevel: feature.samplingInspectionLevel ?? undefined,
+ severity: feature.samplingSeverity ?? undefined
+ }
+ : (defaultPlan ?? { type: "All" });
+ return resolveSamplingPlan(plan, lotSize, standard);
+}
diff --git a/packages/database/supabase/functions/trigger-rework/index.ts b/packages/database/supabase/functions/trigger-rework/index.ts
index fcf1b14430..b1ac87091d 100644
--- a/packages/database/supabase/functions/trigger-rework/index.ts
+++ b/packages/database/supabase/functions/trigger-rework/index.ts
@@ -16,6 +16,9 @@ interface TriggerReworkRequest {
reason: string;
quantity: number;
trackedEntityIds?: string[];
+ // Provenance link when an inspection disposition triggered the rework —
+ // stamped on the Rework productionQuantity row.
+ inspectionId?: string;
companyId: string;
userId: string;
}
@@ -93,6 +96,7 @@ async function triggerRework(
reason,
quantity,
trackedEntityIds,
+ inspectionId,
companyId,
userId,
} = body;
@@ -233,6 +237,11 @@ async function triggerRework(
operationSupplierProcessId: sourceOp.operationSupplierProcessId,
workInstruction: sourceOp.workInstruction,
procedureId: sourceOp.procedureId,
+ // A cloned Inspection op must re-inspect against the SAME plan — its
+ // lazily-created lot resolves features/sampling from this document.
+ // Assembly ops likewise keep their instruction link for 3D playback.
+ inspectionDocumentId: sourceOp.inspectionDocumentId,
+ assemblyInstructionId: sourceOp.assemblyInstructionId,
operationQuantity: quantity,
targetQuantity: quantity,
tags: sourceOp.tags,
@@ -373,6 +382,7 @@ async function triggerRework(
jobOperationId: triggeredAtJobOperationId,
type: "Rework",
quantity,
+ inspectionId: inspectionId ?? null,
companyId,
createdBy: userId,
})
@@ -401,6 +411,7 @@ serve(async (req) => {
reason: z.string().min(1),
quantity: z.number().positive(),
trackedEntityIds: z.array(z.string()).optional(),
+ inspectionId: z.string().optional(),
companyId: z.string().min(1),
userId: z.string().min(1),
})
diff --git a/packages/database/supabase/migrations/20260705143722_mes-assembly-view.sql b/packages/database/supabase/migrations/20260705143722_mes-assembly-view.sql
new file mode 100644
index 0000000000..33b393967e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260705143722_mes-assembly-view.sql
@@ -0,0 +1,561 @@
+-- ===== 20260616132744_operation-view-rpc.sql =====
+-- Surface the operation's classification (operationType) through the MES operation
+-- RPC so the execution-view router can read it. See
+-- .ai/specs/2026-07-20-operation-type-consolidation.md and
+-- .ai/specs/2026-07-14-mes-execution-views.md (§5.1 view routing). At this point in
+-- history operationType is still the legacy Inside/Outside enum; the
+-- operation-type-consolidation migration converts it to
+-- Process/Assembly/Inspection/Outside Processing and re-binds this function to the
+-- new type. Tracking type stays orthogonal. NOTE: the inspection-plan link
+-- (inspectionDocumentId) is deliberately deferred to the Inspection workstream
+-- (Phase 3) so this keystone migration does not depend on the inspection tables —
+-- see §5.4 of the execution-views spec.
+
+-- Mirrors 20260531084723_rework-serial-flow.sql; only the trailing column is new.
+DROP FUNCTION IF EXISTS get_job_operation_by_id(TEXT);
+CREATE OR REPLACE FUNCTION get_job_operation_by_id(operation_id TEXT)
+RETURNS TABLE (
+ id TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ description TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "itemUnitOfMeasure" TEXT,
+ "itemModelPath" TEXT,
+ "itemModelId" TEXT,
+ "itemModelName" TEXT,
+ "itemModelSize" BIGINT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "workInstruction" JSON,
+ "operationDueDate" DATE,
+ "reworkId" TEXT,
+ "operationType" "operationType"
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate"::DATE AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."id" as "itemId",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."name" as "itemDescription",
+ uom."name" as "itemUnitOfMeasure",
+ m."modelPath" as "itemModelPath",
+ m."id" as "itemModelId",
+ m."name" as "itemModelName",
+ m."size" as "itemModelSize",
+ jo."status" AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."workInstruction",
+ jo."dueDate" AS "operationDueDate",
+ jo."reworkId",
+ jo."operationType"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "unitOfMeasure" uom ON i."unitOfMeasureCode" = uom."code" AND i."companyId" = uom."companyId"
+ LEFT JOIN "modelUpload" m ON i."modelUploadId" = m.id
+ WHERE jo.id = operation_id
+ LIMIT 1;
+END;
+$$ LANGUAGE plpgsql;
+
+-- ===== 20260621154233_operation-step-slides.sql =====
+-- Step reference images ("slides"). A first-class child of an operation step holding a
+-- single reference image (+ optional caption + order), authored on the method (template)
+-- and copied to the job/quote by get-method, exactly like steps/tools/parameters.
+-- See .ai/specs/2026-07-14-mes-execution-views.md §4. Mirrors the *OperationStep tables
+-- (single TEXT id PK,
+-- companyId column, stepId FK ON DELETE CASCADE, production_* RLS).
+
+-- 1. Template slides (authored in the BOP editor)
+-- IF NOT EXISTS / drop-before-create so a re-run (shared dev volume whose bookkeeping
+-- was pruned by the branch-switch migration repair) is a no-op instead of a hard failure.
+CREATE TABLE IF NOT EXISTS "methodOperationStepSlide" (
+ "id" TEXT NOT NULL DEFAULT id('slide'),
+ "stepId" TEXT NOT NULL,
+ "imagePath" TEXT NOT NULL,
+ "caption" TEXT,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "methodOperationStepSlide_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "methodOperationStepSlide_stepId_fkey" FOREIGN KEY ("stepId") REFERENCES "methodOperationStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "methodOperationStepSlide_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "methodOperationStepSlide_stepId_idx" ON "methodOperationStepSlide" ("stepId");
+CREATE INDEX IF NOT EXISTS "methodOperationStepSlide_companyId_idx" ON "methodOperationStepSlide" ("companyId");
+
+-- 2. Job slides (copied from the template by get-method)
+CREATE TABLE IF NOT EXISTS "jobOperationStepSlide" (
+ "id" TEXT NOT NULL DEFAULT id('slide'),
+ "stepId" TEXT NOT NULL,
+ "imagePath" TEXT NOT NULL,
+ "caption" TEXT,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "jobOperationStepSlide_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "jobOperationStepSlide_stepId_fkey" FOREIGN KEY ("stepId") REFERENCES "jobOperationStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobOperationStepSlide_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "jobOperationStepSlide_stepId_idx" ON "jobOperationStepSlide" ("stepId");
+CREATE INDEX IF NOT EXISTS "jobOperationStepSlide_companyId_idx" ON "jobOperationStepSlide" ("companyId");
+
+-- 3. Quote slides (copied from the template by get-method)
+CREATE TABLE IF NOT EXISTS "quoteOperationStepSlide" (
+ "id" TEXT NOT NULL DEFAULT id('slide'),
+ "stepId" TEXT NOT NULL,
+ "imagePath" TEXT NOT NULL,
+ "caption" TEXT,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "quoteOperationStepSlide_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "quoteOperationStepSlide_stepId_fkey" FOREIGN KEY ("stepId") REFERENCES "quoteOperationStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "quoteOperationStepSlide_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "quoteOperationStepSlide_stepId_idx" ON "quoteOperationStepSlide" ("stepId");
+CREATE INDEX IF NOT EXISTS "quoteOperationStepSlide_companyId_idx" ON "quoteOperationStepSlide" ("companyId");
+
+-- RLS — same shape as the *OperationStep parents (any employee reads; production perms write).
+ALTER TABLE "public"."methodOperationStepSlide" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "public"."jobOperationStepSlide" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "public"."quoteOperationStepSlide" ENABLE ROW LEVEL SECURITY;
+
+-- methodOperationStepSlide
+DROP POLICY IF EXISTS "SELECT" ON "public"."methodOperationStepSlide";
+CREATE POLICY "SELECT" ON "public"."methodOperationStepSlide"
+FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+DROP POLICY IF EXISTS "INSERT" ON "public"."methodOperationStepSlide";
+CREATE POLICY "INSERT" ON "public"."methodOperationStepSlide"
+FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]));
+DROP POLICY IF EXISTS "UPDATE" ON "public"."methodOperationStepSlide";
+CREATE POLICY "UPDATE" ON "public"."methodOperationStepSlide"
+FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]));
+DROP POLICY IF EXISTS "DELETE" ON "public"."methodOperationStepSlide";
+CREATE POLICY "DELETE" ON "public"."methodOperationStepSlide"
+FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]));
+
+-- jobOperationStepSlide
+DROP POLICY IF EXISTS "SELECT" ON "public"."jobOperationStepSlide";
+CREATE POLICY "SELECT" ON "public"."jobOperationStepSlide"
+FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+DROP POLICY IF EXISTS "INSERT" ON "public"."jobOperationStepSlide";
+CREATE POLICY "INSERT" ON "public"."jobOperationStepSlide"
+FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]));
+DROP POLICY IF EXISTS "UPDATE" ON "public"."jobOperationStepSlide";
+CREATE POLICY "UPDATE" ON "public"."jobOperationStepSlide"
+FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]));
+DROP POLICY IF EXISTS "DELETE" ON "public"."jobOperationStepSlide";
+CREATE POLICY "DELETE" ON "public"."jobOperationStepSlide"
+FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]));
+
+-- quoteOperationStepSlide
+DROP POLICY IF EXISTS "SELECT" ON "public"."quoteOperationStepSlide";
+CREATE POLICY "SELECT" ON "public"."quoteOperationStepSlide"
+FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+DROP POLICY IF EXISTS "INSERT" ON "public"."quoteOperationStepSlide";
+CREATE POLICY "INSERT" ON "public"."quoteOperationStepSlide"
+FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]));
+DROP POLICY IF EXISTS "UPDATE" ON "public"."quoteOperationStepSlide";
+CREATE POLICY "UPDATE" ON "public"."quoteOperationStepSlide"
+FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]));
+DROP POLICY IF EXISTS "DELETE" ON "public"."quoteOperationStepSlide";
+CREATE POLICY "DELETE" ON "public"."quoteOperationStepSlide"
+FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]));
+
+-- ===== 20260628145000_operation-step-part-tool-link.sql =====
+-- Associate a material (part/consumable) and a tool with a specific operation STEP, so the
+-- MES can show only the parts/tools relevant to the step the operator is on — and scan a
+-- serial/batch part at the step where it's actually used.
+--
+-- Nullable FK = backward compatible: every existing row stays operation-level (NULL = "applies
+-- to the whole operation"). Authored on the method template and copied to job/quote by
+-- get-method, exactly like steps/slides/tools/parameters. ON DELETE SET NULL because a
+-- material/tool is owned by the OPERATION and only *assigned* to a step — deleting the step
+-- must not delete the material; it just reverts to operation-level. Mirrors the stepId pattern
+-- from 20260621154233_operation-step-slides.sql (which FKs the *OperationStep "id").
+
+-- Materials ---------------------------------------------------------------------------------
+-- IF NOT EXISTS so a re-run (shared dev volume whose bookkeeping was pruned by the
+-- branch-switch migration repair) is a no-op instead of a hard failure.
+ALTER TABLE "methodMaterial"
+ ADD COLUMN IF NOT EXISTS "methodOperationStepId" TEXT
+ REFERENCES "methodOperationStep"("id") ON DELETE SET NULL;
+ALTER TABLE "jobMaterial"
+ ADD COLUMN IF NOT EXISTS "jobOperationStepId" TEXT
+ REFERENCES "jobOperationStep"("id") ON DELETE SET NULL;
+ALTER TABLE "quoteMaterial"
+ ADD COLUMN IF NOT EXISTS "quoteOperationStepId" TEXT
+ REFERENCES "quoteOperationStep"("id") ON DELETE SET NULL;
+
+-- Tools -------------------------------------------------------------------------------------
+ALTER TABLE "methodOperationTool"
+ ADD COLUMN IF NOT EXISTS "methodOperationStepId" TEXT
+ REFERENCES "methodOperationStep"("id") ON DELETE SET NULL;
+ALTER TABLE "jobOperationTool"
+ ADD COLUMN IF NOT EXISTS "jobOperationStepId" TEXT
+ REFERENCES "jobOperationStep"("id") ON DELETE SET NULL;
+ALTER TABLE "quoteOperationTool"
+ ADD COLUMN IF NOT EXISTS "quoteOperationStepId" TEXT
+ REFERENCES "quoteOperationStep"("id") ON DELETE SET NULL;
+
+-- Index every new FK (per conventions: index companyId and every FK).
+CREATE INDEX IF NOT EXISTS "methodMaterial_methodOperationStepId_idx" ON "methodMaterial" ("methodOperationStepId");
+CREATE INDEX IF NOT EXISTS "jobMaterial_jobOperationStepId_idx" ON "jobMaterial" ("jobOperationStepId");
+CREATE INDEX IF NOT EXISTS "quoteMaterial_quoteOperationStepId_idx" ON "quoteMaterial" ("quoteOperationStepId");
+CREATE INDEX IF NOT EXISTS "methodOperationTool_methodOperationStepId_idx" ON "methodOperationTool" ("methodOperationStepId");
+CREATE INDEX IF NOT EXISTS "jobOperationTool_jobOperationStepId_idx" ON "jobOperationTool" ("jobOperationStepId");
+CREATE INDEX IF NOT EXISTS "quoteOperationTool_quoteOperationStepId_idx" ON "quoteOperationTool" ("quoteOperationStepId");
+
+-- ===== 20260628161500_method-tree-step-link.sql / 20260628163000_method-tree-step-base.sql =====
+-- (definitions removed in the operation-type consolidation)
+-- These sub-migrations redefined get_method_tree to surface the scalar
+-- methodMaterial.methodOperationStepId. The defs were LANGUAGE sql (bodies are
+-- validated at CREATE) and referenced the effectivity columns that main's
+-- 20260714084035_remove-bom-line-effectivity.sql drops — on any remote that has
+-- already applied that migration, re-creating those bodies hard-fails. Since this
+-- file is a squash, the intermediate definitions are transient anyway: the final
+-- get_method_tree (join-table step links, no effectivity) is landed once, in
+-- 20260721004140_operation-type-consolidation.sql, which is timestamped after
+-- every definition on main.
+
+-- ===== 20260701151200_auto-start-operation-timer.sql =====
+-- Passive operation timer (MES): opt-in per company. When ON, the MES assembly view
+-- auto-starts the operator's production event on open (so the timer isn't forgotten).
+-- It never auto-ends a timer — stopping is always a manual action.
+-- Additive + defaulted, no backfill.
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "autoStartOperationTimer" BOOLEAN NOT NULL DEFAULT false;
+
+-- ===== 20260701171540_operation-step-slide-annotations.sql =====
+-- Per-slide display size + image annotations (numbered pins) for step reference images.
+-- Extends the *OperationStepSlide tables from 20260621154233_operation-step-slides.sql.
+--
+-- size — display size in the BOP editor grid and the MES operator view.
+-- 'small' | 'medium' | 'large'; defaults to 'medium' (backward compatible:
+-- every existing slide keeps today's medium look).
+-- annotations — JSONB array of numbered pins overlaid on the image, shape:
+-- [{ "id": text, "x": 0..1, "y": 0..1, "label"?: text, "color"?: text }, ...].
+-- x/y are fractions of the image box so they survive any rendered size.
+-- Defaults to '[]' (no annotations).
+--
+-- Authored on the method template and copied to job/quote by get-method (copyStepSlides),
+-- exactly like the caption/order columns. IF NOT EXISTS so a re-run on a shared dev volume
+-- is a no-op instead of a hard failure (mirrors the parent slides migration).
+
+-- methodOperationStepSlide -------------------------------------------------------------------
+ALTER TABLE "methodOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "size" TEXT NOT NULL DEFAULT 'medium',
+ ADD COLUMN IF NOT EXISTS "annotations" JSONB NOT NULL DEFAULT '[]';
+
+-- jobOperationStepSlide ----------------------------------------------------------------------
+ALTER TABLE "jobOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "size" TEXT NOT NULL DEFAULT 'medium',
+ ADD COLUMN IF NOT EXISTS "annotations" JSONB NOT NULL DEFAULT '[]';
+
+-- quoteOperationStepSlide --------------------------------------------------------------------
+ALTER TABLE "quoteOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "size" TEXT NOT NULL DEFAULT 'medium',
+ ADD COLUMN IF NOT EXISTS "annotations" JSONB NOT NULL DEFAULT '[]';
+
+-- Constrain size to the three allowed values (guard against bad writes; NOT VALID-free since
+-- every existing row is the default 'medium'). DROP-before-ADD keeps a re-run idempotent.
+ALTER TABLE "methodOperationStepSlide" DROP CONSTRAINT IF EXISTS "methodOperationStepSlide_size_check";
+ALTER TABLE "methodOperationStepSlide"
+ ADD CONSTRAINT "methodOperationStepSlide_size_check" CHECK ("size" IN ('small', 'medium', 'large'));
+
+ALTER TABLE "jobOperationStepSlide" DROP CONSTRAINT IF EXISTS "jobOperationStepSlide_size_check";
+ALTER TABLE "jobOperationStepSlide"
+ ADD CONSTRAINT "jobOperationStepSlide_size_check" CHECK ("size" IN ('small', 'medium', 'large'));
+
+ALTER TABLE "quoteOperationStepSlide" DROP CONSTRAINT IF EXISTS "quoteOperationStepSlide_size_check";
+ALTER TABLE "quoteOperationStepSlide"
+ ADD CONSTRAINT "quoteOperationStepSlide_size_check" CHECK ("size" IN ('small', 'medium', 'large'));
+
+-- ===== 20260702143000_operation-step-link-many-to-many.sql =====
+-- Many-to-many tool<->step and part<->step.
+--
+-- Replaces the single nullable FK *OperationStepId (added in
+-- 20260628145000_operation-step-part-tool-link.sql) with six join tables so a tool/material
+-- can be scoped to ANY SUBSET of an operation's steps — not just one step, and not only "all".
+-- Semantics: NO join rows = operation-level (shown on every step, backward compatible);
+-- 1+ rows = shown only on those steps.
+--
+-- Join tables carry no companyId (like pickingListLineTrackedEntity) — they reach the company
+-- through the parent via EXISTS in RLS. Both FKs are ON DELETE CASCADE: deleting the tool/
+-- material OR the step removes the link row (a link is meaningless without either side).
+--
+-- The old scalar columns are backfilled here and dropped in the paired migration
+-- 20260702143500 (below).
+
+-- Materials ---------------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS "methodMaterialStep" (
+ "methodMaterialId" TEXT NOT NULL REFERENCES "methodMaterial"("id") ON DELETE CASCADE,
+ "methodOperationStepId" TEXT NOT NULL REFERENCES "methodOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("methodMaterialId", "methodOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "methodMaterialStep_methodOperationStepId_idx" ON "methodMaterialStep" ("methodOperationStepId");
+
+CREATE TABLE IF NOT EXISTS "jobMaterialStep" (
+ "jobMaterialId" TEXT NOT NULL REFERENCES "jobMaterial"("id") ON DELETE CASCADE,
+ "jobOperationStepId" TEXT NOT NULL REFERENCES "jobOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("jobMaterialId", "jobOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "jobMaterialStep_jobOperationStepId_idx" ON "jobMaterialStep" ("jobOperationStepId");
+
+CREATE TABLE IF NOT EXISTS "quoteMaterialStep" (
+ "quoteMaterialId" TEXT NOT NULL REFERENCES "quoteMaterial"("id") ON DELETE CASCADE,
+ "quoteOperationStepId" TEXT NOT NULL REFERENCES "quoteOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("quoteMaterialId", "quoteOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "quoteMaterialStep_quoteOperationStepId_idx" ON "quoteMaterialStep" ("quoteOperationStepId");
+
+-- Tools -------------------------------------------------------------------------------------
+CREATE TABLE IF NOT EXISTS "methodOperationToolStep" (
+ "methodOperationToolId" TEXT NOT NULL REFERENCES "methodOperationTool"("id") ON DELETE CASCADE,
+ "methodOperationStepId" TEXT NOT NULL REFERENCES "methodOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("methodOperationToolId", "methodOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "methodOperationToolStep_methodOperationStepId_idx" ON "methodOperationToolStep" ("methodOperationStepId");
+
+CREATE TABLE IF NOT EXISTS "jobOperationToolStep" (
+ "jobOperationToolId" TEXT NOT NULL REFERENCES "jobOperationTool"("id") ON DELETE CASCADE,
+ "jobOperationStepId" TEXT NOT NULL REFERENCES "jobOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("jobOperationToolId", "jobOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "jobOperationToolStep_jobOperationStepId_idx" ON "jobOperationToolStep" ("jobOperationStepId");
+
+CREATE TABLE IF NOT EXISTS "quoteOperationToolStep" (
+ "quoteOperationToolId" TEXT NOT NULL REFERENCES "quoteOperationTool"("id") ON DELETE CASCADE,
+ "quoteOperationStepId" TEXT NOT NULL REFERENCES "quoteOperationStep"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("quoteOperationToolId", "quoteOperationStepId")
+);
+CREATE INDEX IF NOT EXISTS "quoteOperationToolStep_quoteOperationStepId_idx" ON "quoteOperationToolStep" ("quoteOperationStepId");
+
+-- RLS -- reach companyId through the parent (tool/material). SELECT: any employee of the
+-- parent's company. Writes: the parent's module permission (job->production, method->parts,
+-- quote->sales), matching the parent tables' own policies.
+
+-- methodMaterialStep (parts)
+ALTER TABLE "public"."methodMaterialStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."methodMaterialStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."methodMaterialStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."methodMaterialStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."methodMaterialStep";
+CREATE POLICY "SELECT" ON "public"."methodMaterialStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "methodMaterial" p WHERE p."id" = "methodMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."methodMaterialStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "methodMaterial" p WHERE p."id" = "methodMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."methodMaterialStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "methodMaterial" p WHERE p."id" = "methodMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."methodMaterialStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "methodMaterial" p WHERE p."id" = "methodMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])));
+
+-- jobMaterialStep (production)
+ALTER TABLE "public"."jobMaterialStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."jobMaterialStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."jobMaterialStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."jobMaterialStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."jobMaterialStep";
+CREATE POLICY "SELECT" ON "public"."jobMaterialStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "jobMaterial" p WHERE p."id" = "jobMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."jobMaterialStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "jobMaterial" p WHERE p."id" = "jobMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."jobMaterialStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "jobMaterial" p WHERE p."id" = "jobMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."jobMaterialStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "jobMaterial" p WHERE p."id" = "jobMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[])));
+
+-- quoteMaterialStep (sales)
+ALTER TABLE "public"."quoteMaterialStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."quoteMaterialStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."quoteMaterialStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."quoteMaterialStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."quoteMaterialStep";
+CREATE POLICY "SELECT" ON "public"."quoteMaterialStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "quoteMaterial" p WHERE p."id" = "quoteMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."quoteMaterialStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "quoteMaterial" p WHERE p."id" = "quoteMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."quoteMaterialStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "quoteMaterial" p WHERE p."id" = "quoteMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."quoteMaterialStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "quoteMaterial" p WHERE p."id" = "quoteMaterialId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[])));
+
+-- methodOperationToolStep (parts)
+ALTER TABLE "public"."methodOperationToolStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."methodOperationToolStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."methodOperationToolStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."methodOperationToolStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."methodOperationToolStep";
+CREATE POLICY "SELECT" ON "public"."methodOperationToolStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "methodOperationTool" p WHERE p."id" = "methodOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."methodOperationToolStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "methodOperationTool" p WHERE p."id" = "methodOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."methodOperationToolStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "methodOperationTool" p WHERE p."id" = "methodOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."methodOperationToolStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "methodOperationTool" p WHERE p."id" = "methodOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])));
+
+-- jobOperationToolStep (production)
+ALTER TABLE "public"."jobOperationToolStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."jobOperationToolStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."jobOperationToolStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."jobOperationToolStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."jobOperationToolStep";
+CREATE POLICY "SELECT" ON "public"."jobOperationToolStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "jobOperationTool" p WHERE p."id" = "jobOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."jobOperationToolStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "jobOperationTool" p WHERE p."id" = "jobOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."jobOperationToolStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "jobOperationTool" p WHERE p."id" = "jobOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."jobOperationToolStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "jobOperationTool" p WHERE p."id" = "jobOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[])));
+
+-- quoteOperationToolStep (sales)
+ALTER TABLE "public"."quoteOperationToolStep" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."quoteOperationToolStep";
+DROP POLICY IF EXISTS "INSERT" ON "public"."quoteOperationToolStep";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."quoteOperationToolStep";
+DROP POLICY IF EXISTS "DELETE" ON "public"."quoteOperationToolStep";
+CREATE POLICY "SELECT" ON "public"."quoteOperationToolStep" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "quoteOperationTool" p WHERE p."id" = "quoteOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])));
+CREATE POLICY "INSERT" ON "public"."quoteOperationToolStep" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "quoteOperationTool" p WHERE p."id" = "quoteOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[])));
+CREATE POLICY "UPDATE" ON "public"."quoteOperationToolStep" FOR UPDATE USING (
+ EXISTS (SELECT 1 FROM "quoteOperationTool" p WHERE p."id" = "quoteOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[])));
+CREATE POLICY "DELETE" ON "public"."quoteOperationToolStep" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "quoteOperationTool" p WHERE p."id" = "quoteOperationToolId"
+ AND p."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[])));
+
+-- Backfill existing single-FK assignments into the join tables (no data loss).
+-- Guarded on the scalar columns still existing: on a re-run after 20260702143500
+-- (below) has dropped them, the backfill is a no-op instead of a hard failure.
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'methodMaterial'
+ AND column_name = 'methodOperationStepId'
+ ) THEN
+ INSERT INTO "methodMaterialStep" ("methodMaterialId", "methodOperationStepId")
+ SELECT "id", "methodOperationStepId" FROM "methodMaterial" WHERE "methodOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ INSERT INTO "jobMaterialStep" ("jobMaterialId", "jobOperationStepId")
+ SELECT "id", "jobOperationStepId" FROM "jobMaterial" WHERE "jobOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ INSERT INTO "quoteMaterialStep" ("quoteMaterialId", "quoteOperationStepId")
+ SELECT "id", "quoteOperationStepId" FROM "quoteMaterial" WHERE "quoteOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ INSERT INTO "methodOperationToolStep" ("methodOperationToolId", "methodOperationStepId")
+ SELECT "id", "methodOperationStepId" FROM "methodOperationTool" WHERE "methodOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ INSERT INTO "jobOperationToolStep" ("jobOperationToolId", "jobOperationStepId")
+ SELECT "id", "jobOperationStepId" FROM "jobOperationTool" WHERE "jobOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ INSERT INTO "quoteOperationToolStep" ("quoteOperationToolId", "quoteOperationStepId")
+ SELECT "id", "quoteOperationStepId" FROM "quoteOperationTool" WHERE "quoteOperationStepId" IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ END IF;
+END $$;
+
+-- ===== 20260702143500_method-tree-step-many-drop-scalar.sql =====
+-- Paired with 20260702143000. Now that methodMaterialStep exists and is backfilled,
+-- drop the six scalar columns. The matching get_method_tree redefinition (surfacing
+-- methodOperationStepIds JSONB aggregated from the join tables) lives in
+-- 20260721004140_operation-type-consolidation.sql — see the note at 20260628161500
+-- above for why no definition is created here. The pre-existing definition does not
+-- reference these scalar columns (they were added by this branch), so dropping them
+-- with that definition still in place is safe.
+
+-- Drop the now-superseded scalar columns (data already backfilled into the join tables).
+ALTER TABLE "methodMaterial" DROP COLUMN IF EXISTS "methodOperationStepId";
+ALTER TABLE "jobMaterial" DROP COLUMN IF EXISTS "jobOperationStepId";
+ALTER TABLE "quoteMaterial" DROP COLUMN IF EXISTS "quoteOperationStepId";
+ALTER TABLE "methodOperationTool" DROP COLUMN IF EXISTS "methodOperationStepId";
+ALTER TABLE "jobOperationTool" DROP COLUMN IF EXISTS "jobOperationStepId";
+ALTER TABLE "quoteOperationTool" DROP COLUMN IF EXISTS "quoteOperationStepId";
+
+-- ===== 20260705143722_drop-operation-timer-idle-minutes.sql =====
+-- The idle auto clock-out was removed from the operation timer: it now only auto-starts
+-- (auto clock-in) and never auto-ends, so the company-configurable idle threshold is dead.
+-- Drop the column. IF EXISTS so this is a no-op on DBs that never got the column.
+ALTER TABLE "companySettings"
+ DROP COLUMN IF EXISTS "operationTimerIdleMinutes";
+
diff --git a/packages/database/supabase/migrations/20260719221229_step-model-slides.sql b/packages/database/supabase/migrations/20260719221229_step-model-slides.sql
new file mode 100644
index 0000000000..c65f141ed5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260719221229_step-model-slides.sql
@@ -0,0 +1,50 @@
+-- Model slides: a BOP step slide can be a 3D model (modelUpload) instead of a picture.
+-- A slide is image XOR model — "imagePath" is relaxed to nullable and a CHECK enforces
+-- that at least one of "imagePath" / "modelUploadId" is set. The FK cascades: a model
+-- slide without its model is meaningless (image slides are unaffected — their
+-- "modelUploadId" is NULL). STEP uploads are converted to GLB by the assembler service
+-- via the existing assembly-convert pipeline; other viewer-supported formats render
+-- directly from "modelUpload"."modelPath".
+-- See .ai/specs/2026-07-14-mes-execution-views.md §4 (this consciously supersedes the
+-- "no 3D model slides" non-goal) and .ai/plans/2026-07-19-step-model-slides.md.
+-- IF EXISTS / IF NOT EXISTS guards mirror the mes-assembly-view migration so a re-run
+-- on a shared dev volume is a no-op.
+
+-- 1. Template slides
+ALTER TABLE "methodOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "modelUploadId" TEXT REFERENCES "modelUpload"("id") ON DELETE CASCADE;
+ALTER TABLE "methodOperationStepSlide"
+ ALTER COLUMN "imagePath" DROP NOT NULL;
+ALTER TABLE "methodOperationStepSlide"
+ DROP CONSTRAINT IF EXISTS "methodOperationStepSlide_content_check";
+ALTER TABLE "methodOperationStepSlide"
+ ADD CONSTRAINT "methodOperationStepSlide_content_check"
+ CHECK ("imagePath" IS NOT NULL OR "modelUploadId" IS NOT NULL);
+CREATE INDEX IF NOT EXISTS "methodOperationStepSlide_modelUploadId_idx"
+ ON "methodOperationStepSlide" ("modelUploadId");
+
+-- 2. Job slides
+ALTER TABLE "jobOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "modelUploadId" TEXT REFERENCES "modelUpload"("id") ON DELETE CASCADE;
+ALTER TABLE "jobOperationStepSlide"
+ ALTER COLUMN "imagePath" DROP NOT NULL;
+ALTER TABLE "jobOperationStepSlide"
+ DROP CONSTRAINT IF EXISTS "jobOperationStepSlide_content_check";
+ALTER TABLE "jobOperationStepSlide"
+ ADD CONSTRAINT "jobOperationStepSlide_content_check"
+ CHECK ("imagePath" IS NOT NULL OR "modelUploadId" IS NOT NULL);
+CREATE INDEX IF NOT EXISTS "jobOperationStepSlide_modelUploadId_idx"
+ ON "jobOperationStepSlide" ("modelUploadId");
+
+-- 3. Quote slides
+ALTER TABLE "quoteOperationStepSlide"
+ ADD COLUMN IF NOT EXISTS "modelUploadId" TEXT REFERENCES "modelUpload"("id") ON DELETE CASCADE;
+ALTER TABLE "quoteOperationStepSlide"
+ ALTER COLUMN "imagePath" DROP NOT NULL;
+ALTER TABLE "quoteOperationStepSlide"
+ DROP CONSTRAINT IF EXISTS "quoteOperationStepSlide_content_check";
+ALTER TABLE "quoteOperationStepSlide"
+ ADD CONSTRAINT "quoteOperationStepSlide_content_check"
+ CHECK ("imagePath" IS NOT NULL OR "modelUploadId" IS NOT NULL);
+CREATE INDEX IF NOT EXISTS "quoteOperationStepSlide_modelUploadId_idx"
+ ON "quoteOperationStepSlide" ("modelUploadId");
diff --git a/packages/database/supabase/migrations/20260720025847_assembly-bop-sync.sql b/packages/database/supabase/migrations/20260720025847_assembly-bop-sync.sql
new file mode 100644
index 0000000000..9b6149e5dc
--- /dev/null
+++ b/packages/database/supabase/migrations/20260720025847_assembly-bop-sync.sql
@@ -0,0 +1,19 @@
+-- Assembly → BOP sync: provenance marker linking a BOP step to the
+-- assemblyInstructionStep it was synced from. Re-sync uses it to update/delete only
+-- the steps it created, leaving hand-authored steps (NULL marker) untouched. ON DELETE
+-- SET NULL: deleting the instruction (or a step of it) demotes synced BOP steps to
+-- hand-authored rather than deleting the operator's work instructions.
+-- See .ai/plans/2026-07-19-step-model-slides.md (Status → follow-up) and
+-- .ai/specs/2026-07-14-mes-execution-views.md §4.
+
+ALTER TABLE "methodOperationStep"
+ ADD COLUMN IF NOT EXISTS "assemblyInstructionStepId" TEXT
+ REFERENCES "assemblyInstructionStep"("id") ON DELETE SET NULL;
+CREATE INDEX IF NOT EXISTS "methodOperationStep_assemblyInstructionStepId_idx"
+ ON "methodOperationStep" ("assemblyInstructionStepId");
+
+ALTER TABLE "jobOperationStep"
+ ADD COLUMN IF NOT EXISTS "assemblyInstructionStepId" TEXT
+ REFERENCES "assemblyInstructionStep"("id") ON DELETE SET NULL;
+CREATE INDEX IF NOT EXISTS "jobOperationStep_assemblyInstructionStepId_idx"
+ ON "jobOperationStep" ("assemblyInstructionStepId");
diff --git a/packages/database/supabase/migrations/20260721004140_operation-type-consolidation.sql b/packages/database/supabase/migrations/20260721004140_operation-type-consolidation.sql
new file mode 100644
index 0000000000..47866587cb
--- /dev/null
+++ b/packages/database/supabase/migrations/20260721004140_operation-type-consolidation.sql
@@ -0,0 +1,437 @@
+-- Operation Type Consolidation
+-- Spec: .ai/specs/2026-07-20-operation-type-consolidation.md
+--
+-- Replaces the legacy 2-value "operationType" enum (Inside/Outside) with a 4-value
+-- enum (Process/Assembly/Inspection/Outside Processing) on methodOperation,
+-- quoteOperation and jobOperation, and converts process."processType" to the SAME
+-- enum type so the two can never drift (the 3-value "processType" enum is dropped).
+--
+-- Data mapping:
+-- operations: 'Inside' -> 'Process', 'Outside' -> 'Outside Processing'
+-- process: 'Inside' -> 'Process', 'Outside' and 'Inside and Outside' -> 'Outside Processing'
+--
+-- Business-logic invariant downstream: subcontract behavior keys on
+-- operationType = 'Outside Processing'; in-house behavior keys on
+-- operationType <> 'Outside Processing' (never an enumeration of in-house values),
+-- so future in-house types inherit costing/scheduling/PO behavior unchanged.
+--
+-- Every step is guarded so a deploy-runner retry over partially-committed state is
+-- a no-op for the parts that already ran.
+
+-- 1. Swap the enum: rename the legacy type aside and create the new 4-value type
+-- under the same name. Skipped when the new type already exists (retry).
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON e.enumtypid = t.oid
+ WHERE t.typname = 'operationType' AND e.enumlabel = 'Process'
+ ) THEN
+ ALTER TYPE "operationType" RENAME TO "operationType__old";
+ CREATE TYPE "operationType" AS ENUM ('Process', 'Assembly', 'Inspection', 'Outside Processing');
+ END IF;
+END $$;
+
+-- 2. Drop the views that project these columns (all recreated below, forked from
+-- their newest definitions).
+DROP VIEW IF EXISTS "jobOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "jobOperationsWithDependencies";
+DROP VIEW IF EXISTS "quoteOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "processes";
+
+-- 3. Convert the three operation tables. Each block is guarded on the column still
+-- being the legacy type, so a retry skips already-converted tables.
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'methodOperation'
+ AND column_name = 'operationType' AND udt_name = 'operationType__old'
+ ) THEN
+ ALTER TABLE "methodOperation" ALTER COLUMN "operationType" DROP DEFAULT;
+ ALTER TABLE "methodOperation" ALTER COLUMN "operationType" TYPE "operationType"
+ USING (CASE WHEN "operationType"::text = 'Outside' THEN 'Outside Processing' ELSE 'Process' END)::"operationType";
+ ALTER TABLE "methodOperation" ALTER COLUMN "operationType" SET DEFAULT 'Process';
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'quoteOperation'
+ AND column_name = 'operationType' AND udt_name = 'operationType__old'
+ ) THEN
+ ALTER TABLE "quoteOperation" ALTER COLUMN "operationType" DROP DEFAULT;
+ ALTER TABLE "quoteOperation" ALTER COLUMN "operationType" TYPE "operationType"
+ USING (CASE WHEN "operationType"::text = 'Outside' THEN 'Outside Processing' ELSE 'Process' END)::"operationType";
+ ALTER TABLE "quoteOperation" ALTER COLUMN "operationType" SET DEFAULT 'Process';
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'jobOperation'
+ AND column_name = 'operationType' AND udt_name = 'operationType__old'
+ ) THEN
+ ALTER TABLE "jobOperation" ALTER COLUMN "operationType" DROP DEFAULT;
+ ALTER TABLE "jobOperation" ALTER COLUMN "operationType" TYPE "operationType"
+ USING (CASE WHEN "operationType"::text = 'Outside' THEN 'Outside Processing' ELSE 'Process' END)::"operationType";
+ ALTER TABLE "jobOperation" ALTER COLUMN "operationType" SET DEFAULT 'Process';
+ END IF;
+END $$;
+
+-- 4. Convert process."processType" to the same enum. A process's type is the
+-- default operationType for operations that use it; capability ("Inside and
+-- Outside") now lives in workCenterProcess / supplierProcess rows, not the enum.
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'process'
+ AND column_name = 'processType' AND udt_name = 'processType'
+ ) THEN
+ ALTER TABLE "process" ALTER COLUMN "processType" DROP DEFAULT;
+ ALTER TABLE "process" ALTER COLUMN "processType" TYPE "operationType"
+ USING (CASE WHEN "processType"::text = 'Inside' THEN 'Process' ELSE 'Outside Processing' END)::"operationType";
+ ALTER TABLE "process" ALTER COLUMN "processType" SET DEFAULT 'Process';
+ END IF;
+END $$;
+
+-- 5. Re-bind get_job_operation_by_id to the new enum. The prior definition's
+-- RETURNS TABLE references the legacy type, which would block DROP TYPE below.
+DROP FUNCTION IF EXISTS get_job_operation_by_id(TEXT);
+CREATE OR REPLACE FUNCTION get_job_operation_by_id(operation_id TEXT)
+RETURNS TABLE (
+ id TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ description TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "itemUnitOfMeasure" TEXT,
+ "itemModelPath" TEXT,
+ "itemModelId" TEXT,
+ "itemModelName" TEXT,
+ "itemModelSize" BIGINT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "workInstruction" JSON,
+ "operationDueDate" DATE,
+ "reworkId" TEXT,
+ "operationType" "operationType"
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate"::DATE AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."id" as "itemId",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."name" as "itemDescription",
+ uom."name" as "itemUnitOfMeasure",
+ m."modelPath" as "itemModelPath",
+ m."id" as "itemModelId",
+ m."name" as "itemModelName",
+ m."size" as "itemModelSize",
+ jo."status" AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."workInstruction",
+ jo."dueDate" AS "operationDueDate",
+ jo."reworkId",
+ jo."operationType"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "unitOfMeasure" uom ON i."unitOfMeasureCode" = uom."code" AND i."companyId" = uom."companyId"
+ LEFT JOIN "modelUpload" m ON i."modelUploadId" = m.id
+ WHERE jo.id = operation_id
+ LIMIT 1;
+END;
+$$ LANGUAGE plpgsql;
+
+-- 6. Drop the retired types. Nothing references them anymore: columns are
+-- converted and the RPC above was recreated against the new type.
+DROP TYPE IF EXISTS "operationType__old";
+DROP TYPE IF EXISTS "processType";
+
+-- 7. Recreate the dropped views, forked verbatim from their newest definitions
+-- (20260610151942_assembly-instructions.sql for the two job views,
+-- 20250603011801_make-method-version.sql for the quote view,
+-- 20260120171236_process-active-column.sql for processes).
+CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ jo.*
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm
+ ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "makeMethod" mm
+ ON jmm."itemId" = mm."itemId" AND jmm."version" = mm."version";
+
+CREATE OR REPLACE VIEW "jobOperationsWithDependencies"
+WITH (security_invoker = true)
+AS
+SELECT
+ jo.*,
+ COALESCE(
+ (
+ SELECT array_agg(jod."dependsOnId")
+ FROM "jobOperationDependency" jod
+ WHERE jod."operationId" = jo.id
+ ),
+ '{}'::text[]
+ ) AS "dependencies"
+FROM "jobOperation" jo;
+
+CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ qo.*
+ FROM "quoteOperation" qo
+ INNER JOIN "quoteMakeMethod" qmm
+ ON qo."quoteMakeMethodId" = qmm.id
+ LEFT JOIN "makeMethod" mm
+ ON qmm."itemId" = mm."itemId" AND qmm."version" = mm."version";
+
+CREATE OR REPLACE VIEW "processes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ p.*,
+ wcp."workCenters",
+ sp."suppliers"
+ FROM "process" p
+ LEFT JOIN (
+ SELECT
+ "processId",
+ array_agg("workCenterId"::text) as "workCenters"
+ FROM "workCenterProcess" wcp
+ INNER JOIN "workCenter" wc ON wcp."workCenterId" = wc.id
+ GROUP BY "processId"
+ ) wcp ON p.id = wcp."processId"
+ LEFT JOIN (
+ SELECT
+ "processId",
+ jsonb_agg(jsonb_build_object('id', sp."id", 'name', s.name)) as "suppliers"
+ FROM "supplierProcess" sp
+ INNER JOIN "supplier" s ON sp."supplierId" = s.id
+ GROUP BY "processId"
+ ) sp ON p.id = sp."processId";
+
+-- 8. Re-land get_method_tree. Main's 20260714084035_remove-bom-line-effectivity.sql
+-- redefined it NEWER than this branch's squashed 20260705143722 (which added the
+-- methodOperationStepIds step links), so in timestamp order the step links would
+-- be silently reverted on deploy. This definition is main's newest body (no BOM
+-- line effectivity) merged with the branch's methodOperationStepIds additions.
+DROP FUNCTION IF EXISTS get_method_tree(TEXT);
+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)
+RETURNS TABLE (
+ "methodMaterialId" TEXT,
+ "makeMethodId" TEXT,
+ "materialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemType" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "unitCost" NUMERIC,
+ "quantity" NUMERIC,
+ "methodType" "methodType",
+ "itemTrackingType" TEXT,
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "operationId" TEXT,
+ "methodOperationStepIds" JSONB,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC,
+ "storageUnitIds" JSONB,
+ "isPickDescendant" BOOLEAN,
+ "replenishmentSystem" "itemReplenishmentSystem"
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "id",
+ "makeMethodId",
+ "methodType",
+ COALESCE(
+ "materialMakeMethodId",
+ CASE WHEN "methodType" = 'Pull from Inventory' THEN (
+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = "methodMaterial"."itemId" LIMIT 1
+ ) END
+ ) AS "materialMakeMethodId",
+ "itemId",
+ "itemType",
+ "quantity",
+ "makeMethodId" AS "parentMaterialId",
+ NULL AS "operationId",
+ COALESCE("order", 1) AS "order",
+ "kit",
+ "storageUnitIds",
+ false AS "isPickDescendant"
+ FROM
+ "methodMaterial"
+ WHERE
+ "makeMethodId" = uid
+ UNION
+ SELECT
+ child."id",
+ child."makeMethodId",
+ child."methodType",
+ COALESCE(
+ child."materialMakeMethodId",
+ CASE WHEN child."methodType" = 'Pull from Inventory' THEN (
+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = child."itemId" LIMIT 1
+ ) END
+ ) AS "materialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ parent."id" AS "parentMaterialId",
+ child."methodOperationId" AS "operationId",
+ child."order",
+ child."kit",
+ child."storageUnitIds",
+ (parent."methodType" = 'Pull from Inventory' OR parent."isPickDescendant") AS "isPickDescendant"
+ FROM
+ "methodMaterial" child
+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"
+)
+SELECT
+ material.id as "methodMaterialId",
+ material."makeMethodId",
+ material."materialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ material."itemType",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ material."quantity",
+ material."methodType",
+ item."itemTrackingType",
+ material."parentMaterialId",
+ material."order",
+ material."operationId",
+ (
+ SELECT COALESCE(jsonb_agg(mms."methodOperationStepId"), '[]'::jsonb)
+ FROM "methodMaterialStep" mms
+ WHERE mms."methodMaterialId" = material.id
+ ) AS "methodOperationStepIds",
+ false AS "isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm2."version",
+ material."storageUnitIds",
+ material."isPickDescendant",
+ item."replenishmentSystem"
+FROM material
+INNER JOIN item
+ ON material."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+INNER JOIN "makeMethod" mm
+ ON material."makeMethodId" = mm.id
+LEFT JOIN "makeMethod" mm2
+ ON material."materialMakeMethodId" = mm2.id
+UNION
+SELECT
+ mm."id" AS "methodMaterialId",
+ NULL AS "makeMethodId",
+ mm.id AS "materialMakeMethodId",
+ mm."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."type"::text,
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ 1 AS "quantity",
+ 'Make to Order' AS "methodType",
+ item."itemTrackingType",
+ NULL AS "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ NULL AS "operationId",
+ '[]'::jsonb AS "methodOperationStepIds",
+ true AS "isRoot",
+ false AS "kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm."version",
+ '{}'::JSONB AS "storageUnitIds",
+ false AS "isPickDescendant",
+ item."replenishmentSystem"
+FROM "makeMethod" mm
+INNER JOIN item
+ ON mm."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+WHERE mm.id = uid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
diff --git a/packages/database/supabase/migrations/20260721014248_assembly-select-employee-role.sql b/packages/database/supabase/migrations/20260721014248_assembly-select-employee-role.sql
new file mode 100644
index 0000000000..74ed5add3c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260721014248_assembly-select-employee-role.sql
@@ -0,0 +1,54 @@
+-- Normalize assembly* SELECT policies from the `production_view` permission to
+-- get_companies_with_employee_role(), so any employee of the company can read
+-- assembly instructions. This matches the `procedure` table and the feature's
+-- own newer MES step/slide tables (which already SELECT via employee role).
+-- INSERT/UPDATE/DELETE stay on production_create/update/delete (unchanged).
+-- Idempotent: DROP POLICY IF EXISTS before each CREATE.
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyPlanJob";
+CREATE POLICY "SELECT" ON "public"."assemblyPlanJob"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstruction";
+CREATE POLICY "SELECT" ON "public"."assemblyInstruction"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstructionStep";
+CREATE POLICY "SELECT" ON "public"."assemblyInstructionStep"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstructionStepRequirement";
+CREATE POLICY "SELECT" ON "public"."assemblyInstructionStepRequirement"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyStandardNote";
+CREATE POLICY "SELECT" ON "public"."assemblyStandardNote"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstructionStepMaterial";
+CREATE POLICY "SELECT" ON "public"."assemblyInstructionStepMaterial"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyUnit";
+CREATE POLICY "SELECT" ON "public"."assemblyUnit"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyComponentMapping";
+CREATE POLICY "SELECT" ON "public"."assemblyComponentMapping"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ );
diff --git a/packages/database/supabase/migrations/20260721022847_operation-instruction-sources.sql b/packages/database/supabase/migrations/20260721022847_operation-instruction-sources.sql
new file mode 100644
index 0000000000..c09e4ad28e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260721022847_operation-instruction-sources.sql
@@ -0,0 +1,61 @@
+-- Operation Instruction Sources
+-- Spec: .ai/specs/2026-07-21-operation-instruction-sources.md
+--
+-- Per-operation instruction-source pointers, keyed on operationType:
+-- Process -> procedureId (existing, all three tables)
+-- Assembly -> assemblyInstructionId (existing on methodOperation/jobOperation;
+-- added to quoteOperation here)
+-- Inspection -> inspectionDocumentId (new on all three tables — the explicit
+-- plan link accepted in the MES execution
+-- views PRD §5.4; resolve-by-item only
+-- scopes the picker, the FK is the truth)
+--
+-- All FKs are ON DELETE SET NULL (deleting a source never deletes operations),
+-- matching the assemblyInstructionId precedent. Guarded so a deploy-runner retry
+-- over partially-committed state is a no-op.
+
+-- 1. Assembly pointer for quote operations
+ALTER TABLE "quoteOperation" ADD COLUMN IF NOT EXISTS "assemblyInstructionId" TEXT;
+DO $$ BEGIN
+ ALTER TABLE "quoteOperation"
+ ADD CONSTRAINT "quoteOperation_assemblyInstructionId_fkey"
+ FOREIGN KEY ("assemblyInstructionId") REFERENCES "assemblyInstruction"("id") ON DELETE SET NULL;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+CREATE INDEX IF NOT EXISTS "quoteOperation_assemblyInstructionId_idx"
+ ON "quoteOperation"("assemblyInstructionId");
+
+-- 2. Inspection plan link on all three operation tables
+ALTER TABLE "methodOperation" ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+DO $$ BEGIN
+ ALTER TABLE "methodOperation"
+ ADD CONSTRAINT "methodOperation_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+CREATE INDEX IF NOT EXISTS "methodOperation_inspectionDocumentId_idx"
+ ON "methodOperation"("inspectionDocumentId");
+
+ALTER TABLE "quoteOperation" ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+DO $$ BEGIN
+ ALTER TABLE "quoteOperation"
+ ADD CONSTRAINT "quoteOperation_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+CREATE INDEX IF NOT EXISTS "quoteOperation_inspectionDocumentId_idx"
+ ON "quoteOperation"("inspectionDocumentId");
+
+ALTER TABLE "jobOperation" ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+DO $$ BEGIN
+ ALTER TABLE "jobOperation"
+ ADD CONSTRAINT "jobOperation_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+CREATE INDEX IF NOT EXISTS "jobOperation_inspectionDocumentId_idx"
+ ON "jobOperation"("inspectionDocumentId");
diff --git a/packages/database/supabase/migrations/20260721170301_assembly-step-slides-and-tools.sql b/packages/database/supabase/migrations/20260721170301_assembly-step-slides-and-tools.sql
new file mode 100644
index 0000000000..da4e75c2e6
--- /dev/null
+++ b/packages/database/supabase/migrations/20260721170301_assembly-step-slides-and-tools.sql
@@ -0,0 +1,195 @@
+-- Assembly step parity with the BOP step definition: a step supports parts,
+-- tools, and slides. Adds per-step slides (image XOR 3D model, mirroring
+-- methodOperationStepSlide) and per-step tools (tool-type items + quantity,
+-- mirroring assemblyInstructionStepMaterial), salvages catalog-linked Tool
+-- requirements into the new tools table, then retires the requirements /
+-- standard-notes surface entirely (fixtures, consumables, notes, and media
+-- have no step-definition equivalent and are dropped by design).
+-- All DDL is idempotent: guarded creates first, ON CONFLICT salvage, IF EXISTS
+-- drops last — a retried run over committed partial state is a no-op.
+
+-- 1. Per-step slides (image XOR model), mirroring methodOperationStepSlide +
+-- the model/size/annotations columns it gained later.
+CREATE TABLE IF NOT EXISTS "assemblyInstructionStepSlide" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "stepId" TEXT NOT NULL,
+ "imagePath" TEXT,
+ "modelUploadId" TEXT,
+ "caption" TEXT,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "size" TEXT NOT NULL DEFAULT 'medium',
+ "annotations" JSONB NOT NULL DEFAULT '[]',
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstructionStepSlide_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstructionStepSlide_stepId_fkey"
+ FOREIGN KEY ("stepId") REFERENCES "assemblyInstructionStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepSlide_modelUploadId_fkey"
+ FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepSlide_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepSlide_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepSlide_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ -- A slide is an image or a 3D model, never neither
+ CONSTRAINT "assemblyInstructionStepSlide_content_check"
+ CHECK ("imagePath" IS NOT NULL OR "modelUploadId" IS NOT NULL),
+ CONSTRAINT "assemblyInstructionStepSlide_size_check"
+ CHECK ("size" IN ('small', 'medium', 'large'))
+);
+
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepSlide_stepId_idx"
+ ON "assemblyInstructionStepSlide" ("stepId");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepSlide_stepId_sortOrder_idx"
+ ON "assemblyInstructionStepSlide" ("stepId", "sortOrder");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepSlide_companyId_idx"
+ ON "assemblyInstructionStepSlide" ("companyId");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepSlide_modelUploadId_idx"
+ ON "assemblyInstructionStepSlide" ("modelUploadId");
+
+ALTER TABLE "public"."assemblyInstructionStepSlide" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstructionStepSlide";
+CREATE POLICY "SELECT" ON "public"."assemblyInstructionStepSlide"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_view'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "INSERT" ON "public"."assemblyInstructionStepSlide";
+CREATE POLICY "INSERT" ON "public"."assemblyInstructionStepSlide"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "UPDATE" ON "public"."assemblyInstructionStepSlide";
+CREATE POLICY "UPDATE" ON "public"."assemblyInstructionStepSlide"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "DELETE" ON "public"."assemblyInstructionStepSlide";
+CREATE POLICY "DELETE" ON "public"."assemblyInstructionStepSlide"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+ );
+
+-- 2. Per-step tools, mirroring assemblyInstructionStepMaterial. itemId is a
+-- tool-type item — the same target jobOperationTool.toolId references, so
+-- the BOP sync maps rows 1:1. Quantity is INTEGER DEFAULT 1 to match
+-- jobOperationTool.quantity.
+CREATE TABLE IF NOT EXISTS "assemblyInstructionStepTool" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "stepId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "quantity" INTEGER NOT NULL DEFAULT 1,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstructionStepTool_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstructionStepTool_stepId_fkey"
+ FOREIGN KEY ("stepId") REFERENCES "assemblyInstructionStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepTool_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepTool_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepTool_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepTool_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepTool_stepId_itemId_key"
+ UNIQUE ("stepId", "itemId")
+);
+
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepTool_stepId_idx"
+ ON "assemblyInstructionStepTool" ("stepId");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepTool_stepId_sortOrder_idx"
+ ON "assemblyInstructionStepTool" ("stepId", "sortOrder");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepTool_companyId_idx"
+ ON "assemblyInstructionStepTool" ("companyId");
+CREATE INDEX IF NOT EXISTS "assemblyInstructionStepTool_itemId_idx"
+ ON "assemblyInstructionStepTool" ("itemId");
+
+ALTER TABLE "public"."assemblyInstructionStepTool" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."assemblyInstructionStepTool";
+CREATE POLICY "SELECT" ON "public"."assemblyInstructionStepTool"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_view'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "INSERT" ON "public"."assemblyInstructionStepTool";
+CREATE POLICY "INSERT" ON "public"."assemblyInstructionStepTool"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_create'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "UPDATE" ON "public"."assemblyInstructionStepTool";
+CREATE POLICY "UPDATE" ON "public"."assemblyInstructionStepTool"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_update'))::text[]
+ )
+ );
+
+DROP POLICY IF EXISTS "DELETE" ON "public"."assemblyInstructionStepTool";
+CREATE POLICY "DELETE" ON "public"."assemblyInstructionStepTool"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('production_delete'))::text[]
+ )
+ );
+
+-- 3. Salvage catalog-linked Tool requirements into the new tools table before
+-- the requirements surface is dropped. Guarded so a retry after the drop
+-- (committed partial state) is a no-op.
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name = 'assemblyInstructionStepRequirement'
+ ) THEN
+ INSERT INTO "assemblyInstructionStepTool"
+ ("stepId", "itemId", "quantity", "sortOrder", "companyId", "createdBy", "createdAt")
+ SELECT
+ r."stepId",
+ r."itemId",
+ GREATEST(COALESCE(r."quantity", 1), 1),
+ r."sortOrder",
+ r."companyId",
+ r."createdBy",
+ r."createdAt"
+ FROM "assemblyInstructionStepRequirement" r
+ WHERE r."type" = 'Tool' AND r."itemId" IS NOT NULL
+ ON CONFLICT ("stepId", "itemId") DO NOTHING;
+ END IF;
+END $$;
+
+-- 4. Retire the requirements / standard-notes surface. Fixtures, consumables,
+-- notes, and media cannot be expressed on a step definition and are
+-- eliminated by design (internal-only feature).
+DROP TABLE IF EXISTS "assemblyInstructionStepRequirement";
+DROP TABLE IF EXISTS "assemblyStandardNote";
+DROP TYPE IF EXISTS "assemblyRequirementType";
+DROP TYPE IF EXISTS "assemblyNoteSeverity";
diff --git a/packages/database/supabase/migrations/20260722040401_inbound-inspection-execution.sql b/packages/database/supabase/migrations/20260722040401_inbound-inspection-execution.sql
new file mode 100644
index 0000000000..e05803b76f
--- /dev/null
+++ b/packages/database/supabase/migrations/20260722040401_inbound-inspection-execution.sql
@@ -0,0 +1,548 @@
+-- Inbound inspection execution: document assignment, per-feature sampling,
+-- per-lot feature plans, per-sample measurements.
+-- Spec: .ai/specs/2026-07-21-inbound-inspection-execution.md
+
+-- 1) Usage enum (extensible: 'FAI', 'Production' later)
+DO $$ BEGIN
+ CREATE TYPE "inspectionDocumentUsage" AS ENUM ('Receipt');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 2) Item-level document assignment per usage slot
+CREATE TABLE IF NOT EXISTS "itemInspectionDocumentAssignment" (
+ "itemId" TEXT NOT NULL,
+ "usage" "inspectionDocumentUsage" NOT NULL,
+ "inspectionDocumentId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "itemInspectionDocumentAssignment_pkey" PRIMARY KEY ("itemId", "usage"),
+ CONSTRAINT "itemInspectionDocumentAssignment_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_inspectionDocumentId_fkey" FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemInspectionDocumentAssignment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "itemInspectionDocumentAssignment_companyId_idx" ON "itemInspectionDocumentAssignment" ("companyId");
+CREATE INDEX IF NOT EXISTS "itemInspectionDocumentAssignment_inspectionDocumentId_idx" ON "itemInspectionDocumentAssignment" ("inspectionDocumentId");
+CREATE INDEX IF NOT EXISTS "itemInspectionDocumentAssignment_createdBy_idx" ON "itemInspectionDocumentAssignment" ("createdBy");
+
+ALTER TABLE "public"."itemInspectionDocumentAssignment" ENABLE ROW LEVEL SECURITY;
+
+DO $$ BEGIN
+ CREATE POLICY "SELECT" ON "public"."itemInspectionDocumentAssignment"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_view'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "INSERT" ON "public"."itemInspectionDocumentAssignment"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_create'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "UPDATE" ON "public"."itemInspectionDocumentAssignment"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_update'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "DELETE" ON "public"."itemInspectionDocumentAssignment"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_delete'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 3) Per-feature sampling rule (nullable = inherit itemSamplingPlan)
+ALTER TABLE "inspectionFeature"
+ ADD COLUMN IF NOT EXISTS "samplingPlanType" "samplingPlanType",
+ ADD COLUMN IF NOT EXISTS "samplingSampleSize" INTEGER,
+ ADD COLUMN IF NOT EXISTS "samplingPercentage" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingAql" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingInspectionLevel" "inspectionLevel",
+ ADD COLUMN IF NOT EXISTS "samplingSeverity" "inspectionSeverity";
+
+-- 4) Lot -> document live reference
+ALTER TABLE "inboundInspection"
+ ADD COLUMN IF NOT EXISTS "inspectionDocumentId" TEXT;
+
+DO $$ BEGIN
+ ALTER TABLE "inboundInspection"
+ ADD CONSTRAINT "inboundInspection_inspectionDocumentId_fkey"
+ FOREIGN KEY ("inspectionDocumentId") REFERENCES "inspectionDocument"("id") ON DELETE SET NULL;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+CREATE INDEX IF NOT EXISTS "inboundInspection_inspectionDocumentId_idx" ON "inboundInspection" ("inspectionDocumentId");
+
+-- 5) Per-lot per-feature resolved sampling plan
+CREATE TABLE IF NOT EXISTS "inboundInspectionFeature" (
+ "id" TEXT NOT NULL DEFAULT id('iif'),
+ "inboundInspectionId" TEXT NOT NULL,
+ "inspectionFeatureId" TEXT NOT NULL,
+ "sampleSize" INTEGER NOT NULL,
+ "acceptanceNumber" INTEGER NOT NULL,
+ "rejectionNumber" INTEGER NOT NULL,
+ "codeLetter" TEXT,
+ "companyId" TEXT NOT NULL,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "inboundInspectionFeature_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionFeature_unique" UNIQUE ("inboundInspectionId", "inspectionFeatureId"),
+ CONSTRAINT "inboundInspectionFeature_inboundInspectionId_fkey" FOREIGN KEY ("inboundInspectionId") REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionFeature_inspectionFeatureId_fkey" FOREIGN KEY ("inspectionFeatureId") REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionFeature_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_companyId_idx" ON "inboundInspectionFeature" ("companyId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_inboundInspectionId_idx" ON "inboundInspectionFeature" ("inboundInspectionId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_inspectionFeatureId_idx" ON "inboundInspectionFeature" ("inspectionFeatureId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionFeature_createdBy_idx" ON "inboundInspectionFeature" ("createdBy");
+
+ALTER TABLE "public"."inboundInspectionFeature" ENABLE ROW LEVEL SECURITY;
+
+DO $$ BEGIN
+ CREATE POLICY "SELECT" ON "public"."inboundInspectionFeature"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_view'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "INSERT" ON "public"."inboundInspectionFeature"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_create'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "UPDATE" ON "public"."inboundInspectionFeature"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_update'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "DELETE" ON "public"."inboundInspectionFeature"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_delete'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 6) Per sample x feature measurement
+CREATE TABLE IF NOT EXISTS "inboundInspectionMeasurement" (
+ "id" TEXT NOT NULL DEFAULT id('iim'),
+ "inboundInspectionId" TEXT NOT NULL,
+ "inboundInspectionSampleId" TEXT NOT NULL,
+ "inspectionFeatureId" TEXT NOT NULL,
+ "value" NUMERIC,
+ "status" "inboundInspectionSampleStatus" NOT NULL DEFAULT 'Pending',
+ "notes" TEXT,
+ "inspectedBy" TEXT,
+ "inspectedAt" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "inboundInspectionMeasurement_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "inboundInspectionMeasurement_unique" UNIQUE ("inboundInspectionSampleId", "inspectionFeatureId"),
+ CONSTRAINT "inboundInspectionMeasurement_inboundInspectionId_fkey" FOREIGN KEY ("inboundInspectionId") REFERENCES "inboundInspection"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_sampleId_fkey" FOREIGN KEY ("inboundInspectionSampleId") REFERENCES "inboundInspectionSample"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_inspectionFeatureId_fkey" FOREIGN KEY ("inspectionFeatureId") REFERENCES "inspectionFeature"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "inboundInspectionMeasurement_inspectedBy_fkey" FOREIGN KEY ("inspectedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_companyId_idx" ON "inboundInspectionMeasurement" ("companyId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_inboundInspectionId_idx" ON "inboundInspectionMeasurement" ("inboundInspectionId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_sampleId_idx" ON "inboundInspectionMeasurement" ("inboundInspectionSampleId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_inspectionFeatureId_idx" ON "inboundInspectionMeasurement" ("inspectionFeatureId");
+CREATE INDEX IF NOT EXISTS "inboundInspectionMeasurement_createdBy_idx" ON "inboundInspectionMeasurement" ("createdBy");
+
+ALTER TABLE "public"."inboundInspectionMeasurement" ENABLE ROW LEVEL SECURITY;
+
+DO $$ BEGIN
+ CREATE POLICY "SELECT" ON "public"."inboundInspectionMeasurement"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_view'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "INSERT" ON "public"."inboundInspectionMeasurement"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_create'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "UPDATE" ON "public"."inboundInspectionMeasurement"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_update'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE POLICY "DELETE" ON "public"."inboundInspectionMeasurement"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('quality_delete'))::text[]
+ )
+ );
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 7) Fork save_inspection_document_atomic (newest prior definition:
+-- 20260526142837_inspection-feature-type.sql) to persist the six per-feature
+-- sampling columns. Signature is unchanged, so CREATE OR REPLACE suffices (no
+-- DROP; the supabase CLI statement splitter also mis-chunks DROP+CREATE here).
+-- Body preserved verbatim apart from: the six columns added to the feature
+-- create INSERT, the feature update SET, and the returned features payload.
+CREATE OR REPLACE FUNCTION save_inspection_document_atomic(
+ p_inspection_document_id TEXT,
+ p_company_id TEXT,
+ p_user_id TEXT,
+ p_pdf_url TEXT DEFAULT NULL,
+ p_page_count INTEGER DEFAULT NULL,
+ p_default_page_width DOUBLE PRECISION DEFAULT NULL,
+ p_default_page_height DOUBLE PRECISION DEFAULT NULL,
+ p_features JSONB DEFAULT '{}'::jsonb,
+ p_balloons JSONB DEFAULT '{}'::jsonb
+)
+RETURNS JSONB
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_document RECORD;
+ v_storage_path TEXT;
+ v_features_create JSONB := COALESCE(p_features->'create', '[]'::jsonb);
+ v_features_update JSONB := COALESCE(p_features->'update', '[]'::jsonb);
+ v_features_delete JSONB := COALESCE(p_features->'delete', '[]'::jsonb);
+ v_balloons_create JSONB := COALESCE(p_balloons->'create', '[]'::jsonb);
+ v_balloons_update JSONB := COALESCE(p_balloons->'update', '[]'::jsonb);
+ v_balloons_delete JSONB := COALESCE(p_balloons->'delete', '[]'::jsonb);
+ v_item JSONB;
+ v_temp_id TEXT;
+ v_feature_id TEXT;
+ v_balloon_id TEXT;
+ v_feature_id_map JSONB := '{}'::jsonb;
+ v_balloon_anchor_id_map JSONB := '{}'::jsonb;
+BEGIN
+ SELECT *
+ INTO v_document
+ FROM "inspectionDocument"
+ WHERE "id" = p_inspection_document_id
+ FOR UPDATE;
+
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Inspection document not found';
+ END IF;
+
+ IF v_document."companyId" <> p_company_id THEN
+ RAISE EXCEPTION 'Inspection document does not belong to this company';
+ END IF;
+
+ v_storage_path := NULLIF(
+ regexp_replace(COALESCE(p_pdf_url, ''), '^/file/preview/private/', ''),
+ ''
+ );
+
+ UPDATE "inspectionDocument"
+ SET
+ "storagePath" = CASE
+ WHEN v_storage_path IS NOT NULL THEN v_storage_path
+ ELSE "storagePath"
+ END,
+ "fileName" = CASE
+ WHEN v_storage_path IS NOT NULL THEN split_part(v_storage_path, '/', array_length(string_to_array(v_storage_path, '/'), 1))
+ ELSE "fileName"
+ END,
+ "uploadedBy" = CASE
+ WHEN v_storage_path IS NOT NULL THEN p_user_id
+ ELSE "uploadedBy"
+ END,
+ "pageCount" = CASE
+ WHEN p_page_count IS NOT NULL AND p_page_count > 0 THEN p_page_count
+ ELSE "pageCount"
+ END,
+ "defaultPageWidth" = CASE
+ WHEN p_default_page_width IS NOT NULL AND p_default_page_width > 0 THEN p_default_page_width
+ ELSE "defaultPageWidth"
+ END,
+ "defaultPageHeight" = CASE
+ WHEN p_default_page_height IS NOT NULL AND p_default_page_height > 0 THEN p_default_page_height
+ ELSE "defaultPageHeight"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "id" = p_inspection_document_id
+ AND "companyId" = p_company_id;
+
+ IF jsonb_array_length(v_features_delete) > 0 THEN
+ DELETE FROM "inspectionFeature"
+ WHERE "id" = ANY (
+ SELECT jsonb_array_elements_text(v_features_delete)
+ )
+ AND "inspectionDocumentId" = p_inspection_document_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ IF jsonb_array_length(v_balloons_delete) > 0 THEN
+ DELETE FROM "balloon"
+ WHERE "id" = ANY (
+ SELECT jsonb_array_elements_text(v_balloons_delete)
+ )
+ AND "inspectionDocumentId" = p_inspection_document_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ FOR v_item IN SELECT value FROM jsonb_array_elements(v_features_create)
+ LOOP
+ INSERT INTO "inspectionFeature" (
+ "inspectionDocumentId",
+ "companyId",
+ "pageNumber",
+ "label",
+ "description",
+ "nominalValue",
+ "tolerancePlus",
+ "toleranceMinus",
+ "unit",
+ "type",
+ "samplingPlanType",
+ "samplingSampleSize",
+ "samplingPercentage",
+ "samplingAql",
+ "samplingInspectionLevel",
+ "samplingSeverity",
+ "createdBy",
+ "updatedBy"
+ ) VALUES (
+ p_inspection_document_id,
+ p_company_id,
+ COALESCE((v_item->>'pageNumber')::INTEGER, 1),
+ COALESCE(v_item->>'label', ''),
+ CASE WHEN v_item ? 'description' THEN v_item->>'description' ELSE NULL END,
+ CASE WHEN v_item ? 'nominalValue' THEN v_item->>'nominalValue' ELSE NULL END,
+ CASE WHEN v_item ? 'tolerancePlus' THEN v_item->>'tolerancePlus' ELSE NULL END,
+ CASE WHEN v_item ? 'toleranceMinus' THEN v_item->>'toleranceMinus' ELSE NULL END,
+ CASE WHEN v_item ? 'unit' THEN v_item->>'unit' ELSE NULL END,
+ COALESCE((v_item->>'type')::"procedureStepType", 'Measurement'::"procedureStepType"),
+ CASE WHEN v_item ? 'samplingPlanType' THEN NULLIF(v_item->>'samplingPlanType', '')::"samplingPlanType" ELSE NULL END,
+ CASE WHEN v_item ? 'samplingSampleSize' THEN (v_item->>'samplingSampleSize')::INTEGER ELSE NULL END,
+ CASE WHEN v_item ? 'samplingPercentage' THEN (v_item->>'samplingPercentage')::NUMERIC ELSE NULL END,
+ CASE WHEN v_item ? 'samplingAql' THEN (v_item->>'samplingAql')::NUMERIC ELSE NULL END,
+ CASE WHEN v_item ? 'samplingInspectionLevel' THEN NULLIF(v_item->>'samplingInspectionLevel', '')::"inspectionLevel" ELSE NULL END,
+ CASE WHEN v_item ? 'samplingSeverity' THEN NULLIF(v_item->>'samplingSeverity', '')::"inspectionSeverity" ELSE NULL END,
+ p_user_id,
+ p_user_id
+ )
+ RETURNING "id" INTO v_feature_id;
+
+ v_temp_id := v_item->>'tempId';
+ IF v_temp_id IS NOT NULL AND length(v_temp_id) > 0 THEN
+ v_feature_id_map := v_feature_id_map || jsonb_build_object(v_temp_id, v_feature_id);
+ END IF;
+ END LOOP;
+
+ FOR v_item IN SELECT value FROM jsonb_array_elements(v_balloons_create)
+ LOOP
+ v_feature_id := NULL;
+ IF v_item ? 'inspectionFeatureId' THEN
+ v_feature_id := v_item->>'inspectionFeatureId';
+ ELSIF v_item ? 'tempInspectionFeatureId' THEN
+ v_temp_id := v_item->>'tempInspectionFeatureId';
+ IF v_feature_id_map ? v_temp_id THEN
+ v_feature_id := v_feature_id_map->>v_temp_id;
+ END IF;
+ END IF;
+
+ IF v_feature_id IS NULL OR length(v_feature_id) = 0 THEN
+ RAISE EXCEPTION 'balloon create requires inspectionFeatureId or tempInspectionFeatureId';
+ END IF;
+
+ INSERT INTO "balloon" (
+ "inspectionDocumentId",
+ "companyId",
+ "inspectionFeatureId",
+ "pageNumber",
+ "regionX",
+ "regionY",
+ "regionWidth",
+ "regionHeight",
+ "xCoordinate",
+ "yCoordinate",
+ "createdBy",
+ "updatedBy"
+ ) VALUES (
+ p_inspection_document_id,
+ p_company_id,
+ v_feature_id,
+ COALESCE((v_item->>'pageNumber')::INTEGER, 1),
+ COALESCE((v_item->>'regionX')::DOUBLE PRECISION, 0),
+ COALESCE((v_item->>'regionY')::DOUBLE PRECISION, 0),
+ COALESCE((v_item->>'regionWidth')::DOUBLE PRECISION, 0.1),
+ COALESCE((v_item->>'regionHeight')::DOUBLE PRECISION, 0.1),
+ COALESCE((v_item->>'xCoordinate')::DOUBLE PRECISION, 0),
+ COALESCE((v_item->>'yCoordinate')::DOUBLE PRECISION, 0),
+ p_user_id,
+ p_user_id
+ )
+ RETURNING "id" INTO v_balloon_id;
+
+ v_temp_id := v_item->>'tempBalloonAnchorId';
+ IF v_temp_id IS NOT NULL AND length(v_temp_id) > 0 THEN
+ v_balloon_anchor_id_map := v_balloon_anchor_id_map || jsonb_build_object(v_temp_id, v_balloon_id);
+ END IF;
+ END LOOP;
+
+ FOR v_item IN SELECT value FROM jsonb_array_elements(v_features_update)
+ LOOP
+ UPDATE "inspectionFeature"
+ SET
+ "pageNumber" = CASE WHEN v_item ? 'pageNumber' THEN (v_item->>'pageNumber')::INTEGER ELSE "pageNumber" END,
+ "label" = CASE WHEN v_item ? 'label' THEN v_item->>'label' ELSE "label" END,
+ "description" = CASE WHEN v_item ? 'description' THEN v_item->>'description' ELSE "description" END,
+ "nominalValue" = CASE WHEN v_item ? 'nominalValue' THEN v_item->>'nominalValue' ELSE "nominalValue" END,
+ "tolerancePlus" = CASE WHEN v_item ? 'tolerancePlus' THEN v_item->>'tolerancePlus' ELSE "tolerancePlus" END,
+ "toleranceMinus" = CASE WHEN v_item ? 'toleranceMinus' THEN v_item->>'toleranceMinus' ELSE "toleranceMinus" END,
+ "unit" = CASE WHEN v_item ? 'unit' THEN v_item->>'unit' ELSE "unit" END,
+ "type" = CASE WHEN v_item ? 'type' THEN (v_item->>'type')::"procedureStepType" ELSE "type" END,
+ "samplingPlanType" = CASE WHEN v_item ? 'samplingPlanType' THEN NULLIF(v_item->>'samplingPlanType', '')::"samplingPlanType" ELSE "samplingPlanType" END,
+ "samplingSampleSize" = CASE WHEN v_item ? 'samplingSampleSize' THEN (v_item->>'samplingSampleSize')::INTEGER ELSE "samplingSampleSize" END,
+ "samplingPercentage" = CASE WHEN v_item ? 'samplingPercentage' THEN (v_item->>'samplingPercentage')::NUMERIC ELSE "samplingPercentage" END,
+ "samplingAql" = CASE WHEN v_item ? 'samplingAql' THEN (v_item->>'samplingAql')::NUMERIC ELSE "samplingAql" END,
+ "samplingInspectionLevel" = CASE WHEN v_item ? 'samplingInspectionLevel' THEN NULLIF(v_item->>'samplingInspectionLevel', '')::"inspectionLevel" ELSE "samplingInspectionLevel" END,
+ "samplingSeverity" = CASE WHEN v_item ? 'samplingSeverity' THEN NULLIF(v_item->>'samplingSeverity', '')::"inspectionSeverity" ELSE "samplingSeverity" END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "id" = v_item->>'id'
+ AND "inspectionDocumentId" = p_inspection_document_id
+ AND "companyId" = p_company_id;
+ END LOOP;
+
+ FOR v_item IN SELECT value FROM jsonb_array_elements(v_balloons_update)
+ LOOP
+ UPDATE "balloon"
+ SET
+ "pageNumber" = CASE WHEN v_item ? 'pageNumber' THEN (v_item->>'pageNumber')::INTEGER ELSE "pageNumber" END,
+ "regionX" = CASE WHEN v_item ? 'regionX' THEN (v_item->>'regionX')::DOUBLE PRECISION ELSE "regionX" END,
+ "regionY" = CASE WHEN v_item ? 'regionY' THEN (v_item->>'regionY')::DOUBLE PRECISION ELSE "regionY" END,
+ "regionWidth" = CASE WHEN v_item ? 'regionWidth' THEN (v_item->>'regionWidth')::DOUBLE PRECISION ELSE "regionWidth" END,
+ "regionHeight" = CASE WHEN v_item ? 'regionHeight' THEN (v_item->>'regionHeight')::DOUBLE PRECISION ELSE "regionHeight" END,
+ "xCoordinate" = CASE WHEN v_item ? 'xCoordinate' THEN (v_item->>'xCoordinate')::DOUBLE PRECISION ELSE "xCoordinate" END,
+ "yCoordinate" = CASE WHEN v_item ? 'yCoordinate' THEN (v_item->>'yCoordinate')::DOUBLE PRECISION ELSE "yCoordinate" END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "id" = v_item->>'id'
+ AND "inspectionDocumentId" = p_inspection_document_id
+ AND "companyId" = p_company_id;
+ END LOOP;
+
+ RETURN jsonb_build_object(
+ 'success', true,
+ 'featureIdMap', v_feature_id_map,
+ 'balloonAnchorIdMap', v_balloon_anchor_id_map,
+ 'features', COALESCE((
+ SELECT jsonb_agg(jsonb_build_object(
+ 'id', f."id",
+ 'inspectionDocumentId', f."inspectionDocumentId",
+ 'companyId', f."companyId",
+ 'pageNumber', f."pageNumber",
+ 'label', f."label",
+ 'description', f."description",
+ 'nominalValue', f."nominalValue",
+ 'tolerancePlus', f."tolerancePlus",
+ 'toleranceMinus', f."toleranceMinus",
+ 'unit', f."unit",
+ 'type', f."type",
+ 'samplingPlanType', f."samplingPlanType",
+ 'samplingSampleSize', f."samplingSampleSize",
+ 'samplingPercentage', f."samplingPercentage",
+ 'samplingAql', f."samplingAql",
+ 'samplingInspectionLevel', f."samplingInspectionLevel",
+ 'samplingSeverity', f."samplingSeverity",
+ 'balloonId', b."id",
+ 'createdBy', f."createdBy",
+ 'updatedBy', f."updatedBy",
+ 'createdAt', f."createdAt",
+ 'updatedAt', f."updatedAt"
+ ) ORDER BY f."createdAt" ASC)
+ FROM "inspectionFeature" f
+ LEFT JOIN "balloon" b
+ ON b."inspectionFeatureId" = f."id"
+ AND b."companyId" = f."companyId"
+ WHERE f."inspectionDocumentId" = p_inspection_document_id
+ AND f."companyId" = p_company_id
+ ), '[]'::jsonb),
+ 'balloons', COALESCE((
+ SELECT jsonb_agg(jsonb_build_object(
+ 'id', b."id",
+ 'inspectionDocumentId', b."inspectionDocumentId",
+ 'companyId', b."companyId",
+ 'inspectionFeatureId', b."inspectionFeatureId",
+ 'pageNumber', b."pageNumber",
+ 'regionX', b."regionX",
+ 'regionY', b."regionY",
+ 'regionWidth', b."regionWidth",
+ 'regionHeight', b."regionHeight",
+ 'xCoordinate', b."xCoordinate",
+ 'yCoordinate', b."yCoordinate",
+ 'createdBy', b."createdBy",
+ 'updatedBy', b."updatedBy",
+ 'createdAt', b."createdAt",
+ 'updatedAt', b."updatedAt"
+ ) ORDER BY b."createdAt" ASC)
+ FROM "balloon" b
+ WHERE b."inspectionDocumentId" = p_inspection_document_id
+ AND b."companyId" = p_company_id
+ ), '[]'::jsonb),
+ 'anchors', COALESCE((
+ SELECT jsonb_agg(jsonb_build_object(
+ 'id', b."id",
+ 'pageNumber', b."pageNumber",
+ 'xCoordinate', b."regionX",
+ 'yCoordinate', b."regionY",
+ 'width', b."regionWidth",
+ 'height', b."regionHeight"
+ ) ORDER BY b."createdAt" ASC)
+ FROM "balloon" b
+ WHERE b."inspectionDocumentId" = p_inspection_document_id
+ AND b."companyId" = p_company_id
+ ), '[]'::jsonb)
+ );
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260722132135_inspections-refactor.sql b/packages/database/supabase/migrations/20260722132135_inspections-refactor.sql
new file mode 100644
index 0000000000..cc50bc3bb4
--- /dev/null
+++ b/packages/database/supabase/migrations/20260722132135_inspections-refactor.sql
@@ -0,0 +1,144 @@
+-- Inspections refactor: generalize the inbound inspection family to a
+-- source-document model and rename the tables to the `inspection` family.
+-- Spec: .ai/specs/2026-07-21-inbound-inspection-execution.md (2026-07-22 entry)
+--
+-- Naming constraints: `inspectionFeature` (document characteristics) and the
+-- Pass/Fail enum `inspectionStatus` already exist, so the per-lot plan table
+-- becomes `inspectionSamplingPlan` and the status enums take the *StatusType
+-- suffix (supplierStatusType precedent). Old constraint/index NAMES keep their
+-- `inboundInspection` strings — renaming them is cosmetic churn.
+
+-- 1) Table renames (RLS policies follow the table)
+DO $$ BEGIN
+ IF to_regclass('public."inboundInspection"') IS NOT NULL THEN
+ ALTER TABLE "inboundInspection" RENAME TO "inspection";
+ END IF;
+ IF to_regclass('public."inboundInspectionSample"') IS NOT NULL THEN
+ ALTER TABLE "inboundInspectionSample" RENAME TO "inspectionSample";
+ END IF;
+ IF to_regclass('public."inboundInspectionFeature"') IS NOT NULL THEN
+ ALTER TABLE "inboundInspectionFeature" RENAME TO "inspectionSamplingPlan";
+ END IF;
+ IF to_regclass('public."inboundInspectionMeasurement"') IS NOT NULL THEN
+ ALTER TABLE "inboundInspectionMeasurement" RENAME TO "inspectionMeasurement";
+ END IF;
+ IF to_regclass('public."inboundInspectionHistory"') IS NOT NULL THEN
+ ALTER TABLE "inboundInspectionHistory" RENAME TO "inspectionHistory";
+ END IF;
+ IF to_regclass('public."nonConformanceInboundInspection"') IS NOT NULL THEN
+ ALTER TABLE "nonConformanceInboundInspection" RENAME TO "nonConformanceInspection";
+ END IF;
+END $$;
+
+-- 2) Enum renames
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inboundInspectionStatus') THEN
+ ALTER TYPE "inboundInspectionStatus" RENAME TO "inspectionStatusType";
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inboundInspectionSampleStatus') THEN
+ ALTER TYPE "inboundInspectionSampleStatus" RENAME TO "inspectionSampleStatusType";
+ END IF;
+END $$;
+
+-- 3) Column renames. Parent readable id follows the nonConformance precedent
+-- (readable `inspectionId` on the parent; child FK columns share the name but
+-- reference inspection.id).
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspection'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "inspection" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspectionSample'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "inspectionSample" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspectionSamplingPlan'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "inspectionSamplingPlan" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspectionMeasurement'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "inspectionMeasurement" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspectionMeasurement'
+ AND column_name = 'inboundInspectionSampleId') THEN
+ ALTER TABLE "inspectionMeasurement" RENAME COLUMN "inboundInspectionSampleId" TO "inspectionSampleId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspectionHistory'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "inspectionHistory" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'nonConformanceInspection'
+ AND column_name = 'inboundInspectionId') THEN
+ ALTER TABLE "nonConformanceInspection" RENAME COLUMN "inboundInspectionId" TO "inspectionId";
+ END IF;
+END $$;
+
+-- 4) Generic source-document model
+DO $$ BEGIN
+ CREATE TYPE "inspectionSourceDocument" AS ENUM ('Receipt', 'Job Operation');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ALTER TABLE "inspection"
+ ADD COLUMN IF NOT EXISTS "sourceDocument" "inspectionSourceDocument",
+ ADD COLUMN IF NOT EXISTS "sourceDocumentId" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceDocumentLineId" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceDocumentReadableId" TEXT;
+
+-- Backfill from the receipt-specific columns, then drop them. Gated on the old
+-- columns still existing so a retry over committed partial state is a no-op.
+-- Dropping the columns also drops their FK and unique constraints.
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'inspection'
+ AND column_name = 'receiptLineId') THEN
+ UPDATE "inspection" i
+ SET
+ "sourceDocument" = 'Receipt',
+ "sourceDocumentId" = i."receiptId",
+ "sourceDocumentLineId" = i."receiptLineId",
+ "sourceDocumentReadableId" = r."receiptId"
+ FROM "receipt" r
+ WHERE r."id" = i."receiptId"
+ AND i."sourceDocument" IS NULL;
+
+ -- Safety net for rows whose receipt no longer resolves (should not exist;
+ -- the FK was ON DELETE CASCADE).
+ UPDATE "inspection"
+ SET
+ "sourceDocument" = 'Receipt',
+ "sourceDocumentId" = "receiptId",
+ "sourceDocumentLineId" = "receiptLineId"
+ WHERE "sourceDocument" IS NULL;
+
+ ALTER TABLE "inspection" DROP COLUMN "receiptId";
+ ALTER TABLE "inspection" DROP COLUMN "receiptLineId";
+ END IF;
+END $$;
+
+ALTER TABLE "inspection"
+ ALTER COLUMN "sourceDocument" SET NOT NULL,
+ ALTER COLUMN "sourceDocumentId" SET NOT NULL;
+
+-- One inspection per source line (was: unique receiptLineId). No FKs on the
+-- generic ids — same as receipt."sourceDocumentId".
+CREATE UNIQUE INDEX IF NOT EXISTS "inspection_sourceDocumentLineId_key"
+ ON "inspection" ("sourceDocument", "sourceDocumentLineId")
+ WHERE "sourceDocumentLineId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "inspection_sourceDocumentId_idx"
+ ON "inspection" ("sourceDocumentId");
+CREATE INDEX IF NOT EXISTS "inspection_sourceDocument_idx"
+ ON "inspection" ("sourceDocument");
+
+-- 5) Sequence re-key: existing companies keep their prefix (II) and counter;
+-- only NEW companies seed the INS prefix (lib/seed.data.ts).
+UPDATE "sequence"
+SET "table" = 'inspection', "name" = 'Inspection'
+WHERE "table" = 'inboundInspection';
diff --git a/packages/database/supabase/migrations/20260726012013_add_scrap_account.sql b/packages/database/supabase/migrations/20260726012013_add_scrap_account.sql
new file mode 100644
index 0000000000..003c2f05e8
--- /dev/null
+++ b/packages/database/supabase/migrations/20260726012013_add_scrap_account.sql
@@ -0,0 +1,25 @@
+-- Scrap / cost-of-quality write-off account for inspection rejects and NCR
+-- dispositions (Scrap / Return to Supplier). Kept distinct from the physical
+-- inventory-count offset (inventoryAdjustmentVarianceAccount) so cost of quality
+-- is separable on the P&L. Flat company-level default (no posting-group matrix).
+
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "scrapAccount" TEXT;
+
+-- RESTRICT (not SET NULL): deleting the account must not silently disable scrap
+-- posting. Drop-and-recreate so a re-run over a partial apply is corrected.
+ALTER TABLE "accountDefault"
+ DROP CONSTRAINT IF EXISTS "accountDefault_scrapAccount_fkey";
+ALTER TABLE "accountDefault"
+ ADD CONSTRAINT "accountDefault_scrapAccount_fkey"
+ FOREIGN KEY ("scrapAccount") REFERENCES "account"("id")
+ ON UPDATE CASCADE ON DELETE RESTRICT;
+
+-- Backfill existing companies to their inventory-adjustment variance account so
+-- none is left null (both are account.id FKs). Idempotent (guarded on NULL);
+-- a company whose variance account is itself null keeps NULL and relies on the
+-- edge function's runtime fallback (scrapAccount ?? inventoryAdjustmentVarianceAccount).
+UPDATE "accountDefault"
+SET "scrapAccount" = "inventoryAdjustmentVarianceAccount"
+WHERE "scrapAccount" IS NULL
+ AND "inventoryAdjustmentVarianceAccount" IS NOT NULL;
diff --git a/packages/database/supabase/migrations/20260726013204_add_nonconformance_journal_doctypes.sql b/packages/database/supabase/migrations/20260726013204_add_nonconformance_journal_doctypes.sql
new file mode 100644
index 0000000000..0d3cff374d
--- /dev/null
+++ b/packages/database/supabase/migrations/20260726013204_add_nonconformance_journal_doctypes.sql
@@ -0,0 +1,12 @@
+-- Make inspection-reject and NCR-disposition write-offs first-class GL entries.
+-- itemLedgerDocumentType already carries 'Non-Conformance' + 'Inbound Inspection';
+-- add the matching journal source type and journal-line document type so the
+-- posted journal is traceable to its origin (mirrors 'Asset Disposal' /
+-- 'Asset Depreciation' on journalEntrySourceType). ADD VALUE only — no usage in
+-- this migration, so it is transaction-safe.
+
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Non-Conformance';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Inbound Inspection';
+
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Non-Conformance';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Inbound Inspection';
diff --git a/packages/database/supabase/migrations/20260726231401_document-sampling-default.sql b/packages/database/supabase/migrations/20260726231401_document-sampling-default.sql
new file mode 100644
index 0000000000..c6045b893c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260726231401_document-sampling-default.sql
@@ -0,0 +1,46 @@
+-- Sampling configuration moves entirely into the inspection plan:
+-- feature rule -> document default -> All
+-- The inspection document gains a default sampling rule (the fallback for
+-- features without their own rule, and the lot-level plan base), replacing the
+-- per-item itemSamplingPlan tier. Existing item plans are preserved by copying
+-- them onto the item's documents' default slots before the table is dropped;
+-- items with a plan but no document fall back to All (100% inspection), which
+-- is the intended behavior for document-less inspections.
+
+-- 1) Document-level default sampling rule (same column set/types as the
+-- per-feature rule columns on inspectionFeature).
+ALTER TABLE "inspectionDocument"
+ ADD COLUMN IF NOT EXISTS "samplingPlanType" "samplingPlanType",
+ ADD COLUMN IF NOT EXISTS "samplingSampleSize" INTEGER,
+ ADD COLUMN IF NOT EXISTS "samplingPercentage" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingAql" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "samplingInspectionLevel" "inspectionLevel",
+ ADD COLUMN IF NOT EXISTS "samplingSeverity" "inspectionSeverity";
+
+-- 2) Backfill: each item plan becomes the default rule on that item's
+-- documents (inspectionDocument.partId = itemSamplingPlan.itemId). Guarded
+-- so a retry over committed partial state is safe (the table may already be
+-- gone; already-backfilled documents are skipped via samplingPlanType IS NULL).
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name = 'itemSamplingPlan'
+ ) THEN
+ UPDATE "inspectionDocument" d
+ SET
+ "samplingPlanType" = p."type",
+ "samplingSampleSize" = p."sampleSize",
+ "samplingPercentage" = p."percentage",
+ "samplingAql" = p."aql",
+ "samplingInspectionLevel" = p."inspectionLevel",
+ "samplingSeverity" = p."severity"
+ FROM "itemSamplingPlan" p
+ WHERE d."partId" = p."itemId"
+ AND d."companyId" = p."companyId"
+ AND d."samplingPlanType" IS NULL;
+ END IF;
+END $$;
+
+-- 3) Retire the per-item tier.
+DROP TABLE IF EXISTS "itemSamplingPlan";
diff --git a/packages/database/supabase/migrations/20260726234512_drop-requires-inspection.sql b/packages/database/supabase/migrations/20260726234512_drop-requires-inspection.sql
new file mode 100644
index 0000000000..e76e104475
--- /dev/null
+++ b/packages/database/supabase/migrations/20260726234512_drop-requires-inspection.sql
@@ -0,0 +1,1202 @@
+-- Drop the vestigial `requiresInspection` columns from `item`, `purchaseOrderLine`,
+-- and `salesOrderLine`. Inbound (receipt) inspection is now gated entirely by the
+-- item's Receipt-usage inspection-document assignment (`itemInspectionDocumentAssignment`),
+-- not a per-item boolean. See `.claude/rules/inspection-system.md`.
+--
+-- The `item` column is referenced by the item-detail RPCs and by the
+-- `parts`/`tools`/`materials`/`consumables`/`services` views; the line columns are
+-- referenced (transitively, via `pl.*` / `sl.*`) by `purchaseOrderLines` /
+-- `salesOrderLines`. Views hard-block a column drop, so we drop them first, drop the
+-- columns, then recreate the views (and the RPCs) without the column.
+--
+-- Idempotent: guarded with IF EXISTS / IF NOT EXISTS so a partial re-run over
+-- committed state re-converges. No downstream object depends on these views, so no
+-- CASCADE is needed; grants are re-acquired via Supabase default privileges (same
+-- pattern as `20260711011724_exclude-draft-journals.sql`).
+
+-- 1. Drop the views that reference the columns.
+DROP VIEW IF EXISTS "parts";
+DROP VIEW IF EXISTS "tools";
+DROP VIEW IF EXISTS "materials";
+DROP VIEW IF EXISTS "consumables";
+DROP VIEW IF EXISTS "services";
+DROP VIEW IF EXISTS "purchaseOrderLines";
+DROP VIEW IF EXISTS "salesOrderLines";
+
+-- 2. Drop the item-detail RPCs (recreated below without the column; the RETURNS
+-- TABLE row type changes, so DROP + recreate rather than CREATE OR REPLACE).
+DROP FUNCTION IF EXISTS get_part_details(TEXT);
+DROP FUNCTION IF EXISTS get_tool_details(TEXT);
+DROP FUNCTION IF EXISTS get_material_details(TEXT);
+DROP FUNCTION IF EXISTS get_consumable_details(TEXT);
+DROP FUNCTION IF EXISTS get_service_details(TEXT);
+
+-- 3. Drop the columns.
+ALTER TABLE "item" DROP COLUMN IF EXISTS "requiresInspection";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "requiresInspection";
+ALTER TABLE "salesOrderLine" DROP COLUMN IF EXISTS "requiresInspection";
+
+-- 4. Recreate the views (verbatim from the newest prior definitions, with every
+-- `requiresInspection` reference removed). The `*`-expansion views (`parts`,
+-- `purchaseOrderLines`, `salesOrderLines`) are recreated as-is — the dropped
+-- column simply no longer expands.
+
+CREATE VIEW "parts" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ mu.id as "modelUploadId",
+
+ mu."modelPath",
+ mu."thumbnailPath" as "modelThumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize"
+ FROM "item" i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE i."type" = 'Part'
+ ORDER BY i."readableId", i."companyId",
+ i."active" DESC,
+ CASE WHEN i."revision" = '0' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END DESC,
+ i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'name', i."name",
+ 'description', i."description",
+ 'active', i."active",
+ 'createdAt', i."createdAt"
+ ) ORDER BY
+ CASE WHEN i."revision" = '0' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END,
+ i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."type" = 'Part'
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ li."active",
+ li."assignee",
+ li."defaultMethodType",
+ li."sourcingType",
+ li."description",
+ li."itemTrackingType",
+ li."name",
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li."notes",
+ li."revision",
+ li."readableId",
+ li."readableIdWithRevision",
+ li."id",
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END as "thumbnailPath",
+
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ p."customFields",
+ p."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL OR eim."metadata" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt",
+ ss."supersessionMode",
+ li."mpn"
+FROM "part" p
+INNER JOIN latest_items li ON li."readableId" = p."id" AND li."companyId" = p."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = p."id" AND ir."companyId" = p."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "companyId"
+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"
+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id
+LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";
+
+CREATE VIEW "tools" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,
+ i."readableId",
+ i.name,
+ i.description,
+ i.type,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."companyId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i.assignee,
+ i."modelUploadId",
+ i."thumbnailPath",
+ i.notes,
+ i."trackingMethod",
+ i.embedding,
+ i.revision,
+ i."readableIdWithRevision",
+ i."sourcingType",
+ mu.id AS "modelUploadId",
+ mu."modelPath",
+ mu."thumbnailPath" AS "modelThumbnailPath",
+ mu.name AS "modelName",
+ mu.size AS "modelSize",
+ i."mpn"
+ FROM item i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE i.type = 'Tool'::"itemType"
+ ORDER BY i."readableId", i."companyId", i.active DESC, (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i."readableId",
+ i."companyId",
+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END), i."createdAt") AS revisions
+ FROM item i
+ WHERE i.type = 'Tool'::"itemType"
+ GROUP BY i."readableId", i."companyId"
+ )
+ SELECT li.active,
+ li.assignee,
+ li."defaultMethodType",
+ li."sourcingType",
+ li.description,
+ li."itemTrackingType",
+ li.name,
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li.notes,
+ li.revision,
+ li."readableId",
+ li."readableIdWithRevision",
+ li.id,
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END AS "thumbnailPath",
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ t."customFields",
+ t.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt",
+ ss."supersessionMode",
+ li."mpn"
+ FROM tool t
+ JOIN latest_items li(id, "readableId", name, description, type, "replenishmentSystem", "defaultMethodType", "itemTrackingType", "unitOfMeasureCode", active, "companyId", "createdBy", "createdAt", "updatedBy", "updatedAt", assignee, "modelUploadId", "thumbnailPath", notes, "trackingMethod", embedding, revision, "readableIdWithRevision", "sourcingType", "modelUploadId_1", "modelPath", "modelThumbnailPath", "modelName", "modelSize", "mpn") ON li."readableId" = t.id AND li."companyId" = t."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = t.id AND ir."companyId" = li."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";
+
+CREATE VIEW "materials" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i_1."readableId", i_1."companyId") i_1.id,
+ i_1."readableId",
+ i_1.name,
+ i_1.description,
+ i_1.type,
+ i_1."replenishmentSystem",
+ i_1."defaultMethodType",
+ i_1."itemTrackingType",
+ i_1."unitOfMeasureCode",
+ i_1.active,
+ i_1."companyId",
+ i_1."createdBy",
+ i_1."createdAt",
+ i_1."updatedBy",
+ i_1."updatedAt",
+ i_1.assignee,
+ i_1."modelUploadId",
+ i_1."thumbnailPath",
+ i_1.notes,
+ i_1."trackingMethod",
+ i_1.embedding,
+ i_1.revision,
+ i_1."readableIdWithRevision",
+ i_1.mpn,
+ mu_1."modelPath",
+ mu_1."thumbnailPath" AS "modelThumbnailPath",
+ mu_1.name AS "modelName",
+ mu_1.size AS "modelSize"
+ FROM item i_1
+ LEFT JOIN "modelUpload" mu_1 ON mu_1.id = i_1."modelUploadId"
+ WHERE i_1.type = 'Material'::"itemType"
+ ORDER BY i_1."readableId", i_1."companyId", i_1.active DESC, (
+ CASE
+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i_1."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i_1."readableId",
+ i_1."companyId",
+ json_agg(json_build_object('id', i_1.id, 'revision', i_1.revision, 'methodType', i_1."defaultMethodType", 'type', i_1.type) ORDER BY (
+ CASE
+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0
+ ELSE 1
+ END), i_1."createdAt") AS revisions
+ FROM item i_1
+ WHERE i_1.type = 'Material'::"itemType"
+ GROUP BY i_1."readableId", i_1."companyId"
+ )
+ SELECT i.active,
+ i.assignee,
+ i."defaultMethodType",
+ i.description,
+ i."itemTrackingType",
+ i.name,
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i.notes,
+ i.revision,
+ i."readableId",
+ i."readableIdWithRevision",
+ i.id,
+ i."companyId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND i."modelThumbnailPath" IS NOT NULL THEN i."modelThumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."modelUploadId",
+ i."modelPath",
+ i."modelName",
+ i."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ mf.name AS "materialForm",
+ ms.name AS "materialSubstance",
+ md.name AS dimensions,
+ mfin.name AS finish,
+ mg.name AS grade,
+ mt.name AS "materialType",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."customFields",
+ m.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = i.id) AS "externalId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ ss."supersessionMode",
+ i.mpn
+ FROM material m
+ JOIN latest_items i ON i."readableId" = m.id AND i."companyId" = m."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = m.id AND ir."companyId" = i."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = i.id AND ps."companyId" = i."companyId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "materialForm" mf ON mf.id = m."materialFormId"
+ LEFT JOIN "materialSubstance" ms ON ms.id = m."materialSubstanceId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md.id
+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin.id
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg.id
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt.id
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = i.id AND ss."companyId" = i."companyId";
+
+CREATE VIEW "consumables" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,
+ i."readableId",
+ i.name,
+ i.description,
+ i.type,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."companyId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i.assignee,
+ i."modelUploadId",
+ i."thumbnailPath",
+ i.notes,
+ i."trackingMethod",
+ i.embedding,
+ i.revision,
+ i."readableIdWithRevision",
+ i.mpn,
+ mu."modelPath",
+ mu."thumbnailPath" AS "modelThumbnailPath",
+ mu.name AS "modelName",
+ mu.size AS "modelSize"
+ FROM item i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE i.type = 'Consumable'::"itemType"
+ ORDER BY i."readableId", i."companyId", i.active DESC, (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i."readableId",
+ i."companyId",
+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END), i."createdAt") AS revisions
+ FROM item i
+ WHERE i.type = 'Consumable'::"itemType"
+ GROUP BY i."readableId", i."companyId"
+ )
+ SELECT li.active,
+ li.assignee,
+ li."defaultMethodType",
+ li.description,
+ li."itemTrackingType",
+ li.name,
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li.notes,
+ li.revision,
+ li."readableId",
+ li."readableIdWithRevision",
+ li.id,
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END AS "thumbnailPath",
+ li."modelUploadId",
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ c."customFields",
+ c.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt",
+ ss."supersessionMode",
+ li.mpn
+ FROM consumable c
+ JOIN latest_items li ON li."readableId" = c.id AND li."companyId" = c."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = c.id AND ir."companyId" = li."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";
+
+CREATE VIEW "services" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,
+ i."readableId",
+ i.name,
+ i.description,
+ i.type,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."companyId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i.assignee,
+ i."modelUploadId",
+ i."thumbnailPath",
+ i.notes,
+ i."trackingMethod",
+ i.embedding,
+ i.revision,
+ i."readableIdWithRevision"
+ FROM item i
+ WHERE i.type = 'Service'::"itemType"
+ ORDER BY i."readableId", i."companyId", i.active DESC, (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i."readableId",
+ i."companyId",
+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END), i."createdAt") AS revisions
+ FROM item i
+ WHERE i.type = 'Service'::"itemType"
+ GROUP BY i."readableId", i."companyId"
+ )
+ SELECT li.active,
+ li.assignee,
+ li."defaultMethodType",
+ li.description,
+ li."itemTrackingType",
+ li.name,
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li.notes,
+ li.revision,
+ li."readableId",
+ li."readableIdWithRevision",
+ li.id,
+ li."companyId",
+ li."thumbnailPath",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ s."customFields",
+ s.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+ FROM service s
+ JOIN latest_items li ON li."readableId" = s.id AND li."companyId" = s."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = s.id AND ir."companyId" = li."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;
+
+CREATE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT DISTINCT ON (pl.id)
+ pl.*,
+ sp."supplierPartId" as "supplierPartIdFromSupplier",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i.name as "itemName",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.description as "itemDescription",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ jo."description" as "jobOperationDescription",
+ a."name" as "accountName",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "purchaseOrderLine" pl
+ INNER JOIN "purchaseOrder" so ON so.id = pl."purchaseOrderId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "jobOperation" jo ON jo."id" = pl."jobOperationId"
+ LEFT JOIN "account" a ON a.id = pl."accountId"
+ LEFT JOIN "fixedAsset" fa ON fa.id = pl."assetId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = so."supplierId" AND sp."itemId" = i.id
+);
+
+CREATE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ sl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ cp."customerPartId",
+ cp."customerPartRevision",
+ so."orderDate",
+ so."customerId",
+ so."salesOrderId" as "salesOrderReadableId",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "salesOrderLine" sl
+ INNER JOIN "salesOrder" so ON so.id = sl."salesOrderId"
+ LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = sl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "customerPartToItem" cp ON cp."customerId" = so."customerId" AND cp."itemId" = i.id
+ LEFT JOIN "fixedAsset" fa ON fa.id = sl."assetId"
+);
+
+-- 5. Recreate the item-detail RPCs without the `requiresInspection` column
+-- (removed from both RETURNS TABLE and the SELECT list).
+
+CREATE OR REPLACE FUNCTION get_part_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "sourcingType" "sourcingType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "unitOfMeasure" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "revisions" JSON,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt" DESC
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Part'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."sourcingType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ uom.name as "unitOfMeasure",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ir."revisions",
+ p."customFields",
+ p."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "part" p
+ LEFT JOIN "item" i ON i."readableId" = p."id" AND i."companyId" = p."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_tool_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "sourcingType" "sourcingType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "unitOfMeasure" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "revisions" JSON,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt" DESC
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Tool'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."sourcingType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ uom.name as "unitOfMeasure",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ir."revisions",
+ t."customFields",
+ t."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "tool" t
+ LEFT JOIN "item" i ON i."readableId" = t."id" AND i."companyId" = t."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_material_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelUploadId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "supplierIds" TEXT,
+ "unitOfMeasure" TEXT,
+ "revisions" JSON,
+ "materialForm" TEXT,
+ "materialSubstance" TEXT,
+ "finish" TEXT,
+ "grade" TEXT,
+ "dimensions" TEXT,
+ "materialType" TEXT,
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "materialTypeId" TEXT,
+ "dimensionId" TEXT,
+ "gradeId" TEXT,
+ "finishId" TEXT,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Material'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelUploadId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ mf."name" AS "materialForm",
+ ms."name" AS "materialSubstance",
+ mfin."name" AS "finish",
+ mg."name" AS "grade",
+ md."name" AS "dimensions",
+ mt."name" AS "materialType",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."materialTypeId",
+ m."dimensionId",
+ m."gradeId",
+ m."finishId",
+ m."customFields",
+ m."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "material" m
+ LEFT JOIN "item" i ON i."readableId" = m."id" AND i."companyId" = m."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "materialForm" mf ON mf."id" = m."materialFormId"
+ LEFT JOIN "materialSubstance" ms ON ms."id" = m."materialSubstanceId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql STABLE;
+
+CREATE OR REPLACE FUNCTION get_consumable_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelUploadId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "supplierIds" TEXT,
+ "unitOfMeasure" TEXT,
+ "revisions" JSON,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Consumable'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelUploadId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ c."customFields",
+ c."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "consumable" c
+ LEFT JOIN "item" i ON i."readableId" = c."id" AND i."companyId" = c."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql STABLE;
+
+CREATE OR REPLACE FUNCTION get_service_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "sourcingType" "sourcingType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "unitOfMeasure" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "revisions" JSON,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt" DESC
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Service'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."sourcingType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ uom.name as "unitOfMeasure",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ir."revisions",
+ s."customFields",
+ s."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "service" s
+ LEFT JOIN "item" i ON i."readableId" = s."id" AND i."companyId" = s."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/database/supabase/migrations/20260727031247_inspection-production-links.sql b/packages/database/supabase/migrations/20260727031247_inspection-production-links.sql
new file mode 100644
index 0000000000..45ac4aa06b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260727031247_inspection-production-links.sql
@@ -0,0 +1,833 @@
+-- Unify inspection dispositions with production outcomes.
+--
+-- 1) Provenance/idempotency links: a productionQuantity row can record which
+-- inspection (and which sample) drove it. The partial UNIQUE index on
+-- inspectionSampleId is the double-count guard for verdict-driven postings
+-- (a sample can produce at most one posting); inspectionId links lot-level
+-- bulk rows.
+ALTER TABLE "productionQuantity"
+ ADD COLUMN IF NOT EXISTS "inspectionId" TEXT REFERENCES "inspection"("id") ON DELETE SET NULL,
+ ADD COLUMN IF NOT EXISTS "inspectionSampleId" TEXT REFERENCES "inspectionSample"("id") ON DELETE SET NULL;
+
+CREATE INDEX IF NOT EXISTS "productionQuantity_inspectionId_idx"
+ ON "productionQuantity" ("inspectionId");
+CREATE UNIQUE INDEX IF NOT EXISTS "productionQuantity_inspectionSampleId_key"
+ ON "productionQuantity" ("inspectionSampleId")
+ WHERE "inspectionSampleId" IS NOT NULL;
+
+-- 2) sync_finish_job_operation (fork of 20260706181125): the zero-completions
+-- fallback to the full job quantity now applies ONLY when the job recorded
+-- no scrap/rework — a fully-scrapped job closes without receiving stock.
+CREATE OR REPLACE FUNCTION sync_finish_job_operation(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_location_id TEXT;
+ v_job_storage_unit_id TEXT;
+ v_job_quantity NUMERIC;
+ v_sales_order_id TEXT;
+ v_quantity_complete NUMERIC;
+ v_quantity_lost NUMERIC;
+ v_job_status TEXT;
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;
+
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "endTime" IS NULL;
+
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = p_new->>'id'
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2.status != 'Done'
+ AND jo2.id != p_new->>'id'
+ );
+
+ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN
+ RETURN;
+ END IF;
+
+ IF is_last_job_operation(p_new->>'id') THEN
+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId"
+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id
+ FROM "job"
+ WHERE id = p_new->>'jobId';
+
+ v_quantity_complete := (
+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)
+ FROM "jobOperation" terminal_jo
+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"
+ WHERE terminal_jo."jobId" = p_new->>'jobId'
+ AND terminal_jmm."parentMaterialId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
+ WHERE dep."dependsOnId" = terminal_jo.id
+ AND child_jmm."parentMaterialId" IS NULL
+ )
+ );
+
+ IF COALESCE(v_quantity_complete, 0) = 0 THEN
+ -- The zero fallback exists for the quantity-less Finish flow (no
+ -- productionQuantity ever recorded). When the job DID record scrap or
+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped
+ -- lot) — falling back would receive scrapped units into stock.
+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)
+ INTO v_quantity_lost
+ FROM "jobOperation"
+ WHERE "jobId" = p_new->>'jobId';
+
+ IF v_quantity_lost = 0 THEN
+ v_quantity_complete := v_job_quantity;
+ ELSE
+ -- Nothing to receive: close the job without posting Assembly Output.
+ -- Materials were already consumed by the scrap/complete flows; WIP
+ -- cost disposition for fully-scrapped jobs is a costing follow-up.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = 0,
+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),
+ "updatedAt" = NOW()
+ WHERE id = p_new->>'jobId';
+ RETURN;
+ END IF;
+ END IF;
+
+ PERFORM complete_job_to_inventory(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_storage_unit_id := v_job_storage_unit_id,
+ p_location_id := v_job_location_id,
+ p_company_id := p_new->>'companyId',
+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')
+ );
+ END IF;
+END;
+$$;
+
+-- 3) complete_job_to_inventory (fork of 20260714043017): the serial branch
+-- excludes 'Rejected' entities (scrapped at inspection) from both the
+-- Assembly Output ledger loop and the Available release.
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN CURRENT_DATE
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ -- Rejected units (scrapped at inspection) must not be received.
+ AND status NOT IN ('Consumed', 'Rejected')
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ -- Rejected units (scrapped at inspection) stay Rejected, out of stock.
+ AND status NOT IN ('Consumed', 'Rejected');
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+ END IF;
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
diff --git a/packages/database/supabase/migrations/20260727183030_model-original-path.sql b/packages/database/supabase/migrations/20260727183030_model-original-path.sql
index 53fb669c48..afe396c04d 100644
--- a/packages/database/supabase/migrations/20260727183030_model-original-path.sql
+++ b/packages/database/supabase/migrations/20260727183030_model-original-path.sql
@@ -3,4 +3,4 @@
-- The original is what customers download; ".xbf" is not openable by CAD tools.
-- Null = original not available (legacy rows compacted before this column, or
-- mesh rows whose ".zst" modelPath decompresses to the identical original bytes).
-ALTER TABLE "modelUpload" ADD COLUMN "originalPath" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN IF NOT EXISTS "originalPath" TEXT;
diff --git a/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx b/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx
index 130f6e761b..746717927f 100644
--- a/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx
@@ -57,7 +57,7 @@ export function OperationsBlock({
{jobOperations
.sort((a, b) => a.order - b.order)
.map((operation, index) => {
- const isInside = operation.operationType === "Inside";
+ const isInside = operation.operationType !== "Outside Processing";
const setupQrCode =
operation.setupTime > 0
? generateQRCode(`${getStartPath(operation.id)}?type=Setup`, 10)
diff --git a/packages/documents/src/pdf/jobTraveler.samples.ts b/packages/documents/src/pdf/jobTraveler.samples.ts
index 06342f6d15..8234182b59 100644
--- a/packages/documents/src/pdf/jobTraveler.samples.ts
+++ b/packages/documents/src/pdf/jobTraveler.samples.ts
@@ -47,7 +47,7 @@ export const SAMPLE_JOB_TRAVELER = {
order: 1,
operationOrder: "After Previous",
description: "CNC Mill — rough + finish",
- operationType: "Inside",
+ operationType: "Process",
setupTime: 0.5,
setupUnit: "Hours",
laborTime: 2,
@@ -63,7 +63,7 @@ export const SAMPLE_JOB_TRAVELER = {
order: 2,
operationOrder: "After Previous",
description: "Deburr & inspect",
- operationType: "Inside",
+ operationType: "Process",
setupTime: 0,
setupUnit: "Hours",
laborTime: 0.75,
@@ -79,7 +79,7 @@ export const SAMPLE_JOB_TRAVELER = {
order: 3,
operationOrder: "After Previous",
description: "Anodize (outside vendor)",
- operationType: "Outside",
+ operationType: "Outside Processing",
setupTime: 0,
setupUnit: "Hours",
laborTime: 0,
diff --git a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
index 9dcd1fcfff..64fbd18123 100644
--- a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
@@ -96,6 +96,21 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<
"Positive Adjmt.",
"Negative Adjmt."
])
+ // Only genuine inventory adjustments push as Xero ManualJournals against the
+ // variance account. Exclude Non-Conformance / Inbound Inspection (these post
+ // their own local journals against the scrap account) and Batch Split
+ // (value-neutral). NULL documentType (manual adjustment) must stay included,
+ // so `NOT IN` alone won't do — it drops NULLs.
+ .where((eb) =>
+ eb.or([
+ eb("itemLedger.documentType", "is", null),
+ eb("itemLedger.documentType", "not in", [
+ "Non-Conformance",
+ "Inbound Inspection",
+ "Batch Split"
+ ])
+ ])
+ )
.execute();
return this.transformRows(rows as unknown as InventoryAdjustmentRow[]);
diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
index 099b311c27..f858882ea7 100644
--- a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
@@ -567,8 +567,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<
purchaseOrderLineType: itemId ? "Part" : "G/L Account",
supplierShippingCost: 0,
invoicedComplete: false,
- receivedComplete: false,
- requiresInspection: false
+ receivedComplete: false
})
.execute();
}
diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.ts
index d7847b9df7..f03b269c46 100644
--- a/packages/ee/src/paperless-parts/lib/lib.ts
+++ b/packages/ee/src/paperless-parts/lib/lib.ts
@@ -2111,8 +2111,7 @@ export async function createPartFromComponent(
operations.push({
order: operation.position ?? index + 1,
operationOrder: "After Previous",
- operationType:
- process.processType === "Inside" ? "Inside" : "Outside",
+ operationType: process.processType,
description:
operation.operation_definition_name ??
operation.name ??
@@ -2588,7 +2587,10 @@ async function getOrCreateProcess(
.from("process")
.insert({
name: operationName,
- processType: operation.is_outside_service === true ? "Outside" : "Inside",
+ processType:
+ operation.is_outside_service === true
+ ? "Outside Processing"
+ : "Process",
companyId,
createdBy,
defaultStandardFactor: "Minutes/Piece"
@@ -3122,8 +3124,7 @@ export async function insertQuoteLines(
quoteMakeMethodId,
processId: process.id,
order: operation.position ?? operationOrder++,
- operationType:
- process.processType === "Inside" ? "Inside" : "Outside",
+ operationType: process.processType,
description:
operationName ?? `Operation ${operationOrder}`,
setupTime: (operation.setup_time ?? 0) * 60,
diff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.ts
index a85386a06f..1657ad4cc8 100644
--- a/packages/glossary/src/terms.ts
+++ b/packages/glossary/src/terms.ts
@@ -69,6 +69,10 @@ export const terms = {
definition: msg`Called a method in Carbon — the components plus operations that produce a part.`,
href: "/docs/reference/methods"
},
+ "operation-type": {
+ term: msg`Operation Type`,
+ definition: msg`Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations.`
+ },
"change-order": {
term: msg`Change order`,
definition: msg`An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace.`
@@ -1188,7 +1192,7 @@ export const terms = {
// ── Quality: Inspection document (InspectionDocumentForm) ───────────────
"inspection-document-drawing-number": {
term: msg`Drawing Number`,
- definition: msg`The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing.`
+ definition: msg`The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing.`
},
// ── Quality: Issue (IssueForm + IssueProperties) ────────────────────────
@@ -1678,7 +1682,7 @@ export const terms = {
// ── Resources: Processes (ProcessForm) ──────────────────────────────────
"process-type": {
term: msg`Process Type`,
- definition: msg`Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process.`
+ definition: msg`Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations.`
},
"process-default-unit": {
term: msg`Default Unit`,
@@ -1868,7 +1872,7 @@ export const terms = {
// ── Config: sequences, custom fields, dimensions ────────────────────────
"numbering-sequence": {
term: msg`Numbering sequence`,
- definition: msg`The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created.`,
+ definition: msg`The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created.`,
href: "/docs/reference/sequences",
aliases: ["sequence"]
},
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 452cb80b20..eb7e7ebfd1 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -725,6 +725,9 @@ msgstr "Parameter hinzufügen"
msgid "Add Partner"
msgstr "Partner hinzufügen"
+msgid "Add parts"
+msgstr "Teile hinzufügen"
+
msgid "Add Permissions"
msgstr "Berechtigungen hinzufügen"
@@ -749,6 +752,9 @@ msgstr "Risiko hinzufügen"
msgid "Add rule"
msgstr "Regel hinzufügen"
+msgid "Add Sample"
+msgstr "Beispiel hinzufügen"
+
msgid "Add Selector"
msgstr "Selektor hinzufügen"
@@ -764,6 +770,9 @@ msgstr "Ersatzteil hinzufügen"
msgid "Add Step"
msgstr "Schritt hinzufügen"
+msgid "Add steps to preview the operator view."
+msgstr "Schritte hinzufügen, um die Bedieneransicht in der Vorschau anzuzeigen."
+
msgid "Add Supplier"
msgstr "Lieferant hinzufügen"
@@ -776,6 +785,9 @@ msgstr "Zeitkarte hinzufügen"
msgid "Add to stock for future use"
msgstr "Zum zukünftigen Gebrauch in den Bestand aufnehmen"
+msgid "Add tools"
+msgstr "Werkzeuge hinzufügen"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Fügen Sie Ihren ersten {0} hinzu"
@@ -1041,6 +1053,9 @@ msgstr "Gilt für alle"
msgid "Applies to all work centers"
msgstr "Gilt für alle Arbeitszentren"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Gilt für Funktionen ohne eigene Regel und für die Charge, wenn dieser Plan eine Inspektion auslöst."
+
msgid "Apply"
msgstr "Anwenden"
@@ -1401,8 +1416,11 @@ msgstr "Möchten Sie diese Änderungsanweisung wirklich löschen?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Sind Sie sicher, dass Sie dieses Messinstrument löschen möchten?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Sind Sie sicher, dass Sie dieses Inspektionsdokument löschen möchten?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Sind Sie sicher, dass Sie diesen Inspektionsplan löschen möchten?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie diesen Inspektionsplan löschen möchten? Dies kann nicht rückgängig gemacht werden."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Sind Sie sicher, dass Sie diesen Issue-Workflow löschen möchten?"
@@ -1534,6 +1552,9 @@ msgstr "Bitten Sie einen Admin mit {0}-Berechtigung, das erste {1} hinzuzufügen
msgid "Assemblies"
msgstr "Montagen"
+msgid "Assembly Instruction"
+msgstr "Montageanleitungen"
+
msgid "Assembly Instructions"
msgstr "Montageanleitungen"
@@ -1678,6 +1699,12 @@ msgstr "Automatisch generierter QR-Code"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Automatische Nummerierungsformate für Bestellungen, Aufträge, Teile und mehr"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Startet automatisch den Timer des Bedieners, wenn dieser eine Operation in der MES öffnet, damit Zeitprotokolle von Anfang an erfasst werden."
+
+msgid "Auto-start timer on open"
+msgstr "Timer beim Öffnen automatisch starten"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Käufe automatisch basierend auf Bedarf und Bestellpunkten vorschlagen"
@@ -1741,6 +1768,9 @@ msgstr "Ausgeglichen"
msgid "Balloon"
msgstr "Ballon"
+msgid "Ballooned drawings with inspection features."
+msgstr "Aufgeblähte Zeichnungen mit Inspektionsmerkmalen."
+
msgid "Bank - Cash"
msgstr "Bank - Bargeld"
@@ -2094,6 +2124,9 @@ msgstr "Hochladen nicht möglich — Lieferanteninteraktion noch nicht erstellt"
msgid "Cannot upload to parts bucket without item ID"
msgstr "Kann nicht in den Teile-Bucket ohne Element-ID hochgeladen werden"
+msgid "Caption"
+msgstr "Beschriftung"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Fachleute"
msgid "Change"
msgstr "Ändern"
+msgid "Change Document"
+msgstr "Dokument ändern"
+
+msgid "Change Inspection Plan"
+msgstr "Inspektionsplan ändern"
+
msgid "Change order"
msgstr "Änderungsauftrag"
@@ -2283,6 +2322,9 @@ msgstr "Klasse"
msgid "Class (inherited)"
msgstr "Klasse (geerbt)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Klassifiziert eine Routingoperation: Prozess-, Montage- und Inspektionsoperationen laufen auf Ihrer eigenen Werkstattebene in der MES – Montage erhält die geführte Montageansicht und Inspektion eine Qualitätsprüfung – während eine Fremdfertigungsoperation an einen Lieferanten vergeben wird und eine Bestellung erstellt; der Prozess trägt den gleichen Typ und nimmt ihn als Standard bei neuen Operationen an."
+
msgid "Clean and approve the migrated data"
msgstr "Bereinigen und genehmigen Sie die migrierten Daten"
@@ -2747,6 +2789,9 @@ msgstr "Konvertieren Sie MRP-Vorschläge in Bestellungen und Aufträge."
msgid "Convert to Quote"
msgstr "In Angebot umwandeln"
+msgid "Converting…"
+msgstr "Wird konvertiert …"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Konvertiert die Kaufeinheit eines Lieferanten in Ihre Bestandseinheit in einer Bestellung, Quittung oder Rechnungszeile — kaufen in Kartons von 12, lagern in Stücken."
@@ -3055,9 +3100,6 @@ msgstr "Änderungsanweisung erstellen"
msgid "Create Issue"
msgstr "Problem erstellen"
-msgid "Create Issue from Inspection"
-msgstr "Problem aus Inspektion erstellen"
-
msgid "Create Jobs"
msgstr "Aufträge erstellen"
@@ -3699,6 +3741,9 @@ msgstr "Standardpriorität"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Standard-Einnahmen-GL-Konto, das gutgeschrieben wird, wenn eine Verkaufsrechnung gebucht wird."
+msgid "Default Sampling"
+msgstr "Standard-Stichprobenprüfung"
+
msgid "Default shelf-life duration (days)"
msgstr "Standarddauer der Haltbarkeit (Tage)"
@@ -3741,9 +3786,6 @@ msgstr "Definieren Sie zunächst einen Herstellungsbetrieb."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definieren Sie mehrstufige Stücklisten und Bill of Process (Herstellungsmethoden)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Definiert, wie viele nachverfolgten Entitäten pro Charge inspiziert werden und wie viele Fehler toleriert werden, bevor die Charge abgelehnt wird."
-
msgid "Delete"
msgstr "Löschen"
@@ -3837,6 +3879,9 @@ msgstr "Gruppe löschen"
msgid "Delete Holiday"
msgstr "Feiertag löschen"
+msgid "Delete Inspection Plan"
+msgstr "Inspektionsplan löschen"
+
msgid "Delete Issue"
msgstr "Problem löschen"
@@ -4329,6 +4374,9 @@ msgstr "Zum Neuordnen ziehen"
msgid "Drag to resize diagram and features"
msgstr "Ziehen Sie, um das Diagramm und die Funktionen zu ändern"
+msgid "Drag to resize drawing and features"
+msgstr "Zum Vergrößern von Zeichnung und Funktionen ziehen"
+
msgid "Drag to zoom"
msgstr "Zum Zoomen ziehen"
@@ -4549,8 +4597,8 @@ msgstr "Gruppe bearbeiten"
msgid "Edit Holiday"
msgstr "Feiertag bearbeiten"
-msgid "Edit Inspection Document"
-msgstr "Inspektionsdokument bearbeiten"
+msgid "Edit Inspection Plan"
+msgstr "Inspektionsplan bearbeiten"
msgid "Edit Item Group"
msgstr "Artikelgruppe bearbeiten"
@@ -5236,6 +5284,9 @@ msgstr "Zusätzliche Tags zum Aufteilen Ihrer GL-Berichte"
msgid "Fail"
msgstr "Fehlgeschlagen"
+msgid "Failed features"
+msgstr "Fehlgeschlagene Merkmale"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (First-Expiry-First-Out)"
@@ -5479,6 +5530,21 @@ msgstr "Fehler beim Speichern der Konfigurationsregel"
msgid "Failed to save diagram"
msgstr "Fehler beim Speichern des Diagramms"
+msgid "Failed to save measurement"
+msgstr "Messung konnte nicht gespeichert werden"
+
+msgid "Failed to save parts"
+msgstr "Teile konnten nicht gespeichert werden"
+
+msgid "Failed to save result"
+msgstr "Ergebnis konnte nicht gespeichert werden"
+
+msgid "Failed to save slides"
+msgstr "Folien konnten nicht gespeichert werden"
+
+msgid "Failed to save tools"
+msgstr "Werkzeuge konnten nicht gespeichert werden"
+
msgid "Failed to update batch property"
msgstr "Fehler beim Aktualisieren der Batch-Eigenschaft"
@@ -6400,15 +6466,6 @@ msgstr "Inaktive Aktionen werden nicht in Auswahlisten angezeigt"
msgid "Inbound inspection"
msgstr "Wareneingangsprüfung"
-msgid "Inbound Inspection"
-msgstr "Eingangsinspektion"
-
-msgid "Inbound Inspections"
-msgstr "Eingehende Inspektionen"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Wareneingangsprüfungen: Unterschiedliche Inspektoren erforderlich"
-
msgid "Inbox"
msgstr "Posteingang"
@@ -6454,6 +6511,12 @@ msgstr "Indirekte Materialien & Dienstleistungen (Standard)"
msgid "Infrastructure"
msgstr "Infrastruktur"
+msgid "Inherit"
+msgstr "Erben"
+
+msgid "Inherit document default"
+msgstr "Dokumentstandard erben"
+
msgid "Inherit From Materials"
msgstr "Von Materialien erben"
@@ -6490,32 +6553,35 @@ msgstr "Erste N inspizieren"
msgid "Inspect Item"
msgstr "Artikel überprüfen"
-msgid "Inspect Next Item"
-msgstr "Nächstes Element prüfen"
-
msgid "Inspection"
msgstr "Inspektion"
-msgid "Inspection Document"
-msgstr "Inspektionsdokument"
-
-msgid "Inspection Documents"
-msgstr "Inspektionsdokumente"
-
msgid "Inspection Level"
msgstr "Inspektionsstufe"
+msgid "Inspection Plan"
+msgstr "Inspektionsplan"
+
+msgid "Inspection Plan Assignments"
+msgstr "Inspektionsplan-Zuweisungen"
+
+msgid "Inspection Plans"
+msgstr "Inspektionspläne"
+
msgid "Inspection Status"
msgstr "Inspektionsstatus"
+msgid "Inspections"
+msgstr "Inspektionen"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspektionen, Nichtkonformität und CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspektionen, Nichtkonformität, CAPA"
-msgid "Inspector"
-msgstr "Inspekteur"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspektionen: Unterschiedlichen Inspektor erforderlich"
msgid "Install"
msgstr "Installieren"
@@ -7439,15 +7505,9 @@ msgstr "Erledigt markieren"
msgid "Mark Light Mode"
msgstr "Marke Hellmodus"
-msgid "Mark lot as partial?"
-msgstr "Lot als teilweise markieren?"
-
msgid "Mark not done"
msgstr "Als nicht erledigt markieren"
-msgid "Mark Partial"
-msgstr "Teilweise markieren"
-
msgid "Mark scope as agreed"
msgstr "Umfang als vereinbart markieren"
@@ -7960,8 +8020,8 @@ msgstr "Neuer Feiertag"
msgid "New IC Transaction"
msgstr "Neue IC-Transaktion"
-msgid "New Inspection Document"
-msgstr "Neues Inspektionsdokument"
+msgid "New Inspection Plan"
+msgstr "Neuer Inspektionsplan"
msgid "New Inventory Count"
msgstr "Neue Bestandszählung"
@@ -8332,6 +8392,9 @@ msgstr "Keine Gruppen zugewiesen"
msgid "No image"
msgstr "Kein Bild"
+msgid "No inspection plans"
+msgstr "Keine Inspektionspläne"
+
msgid "No issue types configured"
msgstr "Keine Problemtypen konfiguriert"
@@ -8392,6 +8455,9 @@ msgstr "Noch keine übergeordneten Quellen aufgezeichnet. Klicken Sie auf der Pl
msgid "No part ID"
msgstr "Keine Teile-ID"
+msgid "No parts"
+msgstr "Keine Teile"
+
msgid "No payables"
msgstr "Keine Verbindlichkeiten"
@@ -8428,6 +8494,9 @@ msgstr "Keine Angebotsgründe"
msgid "No receivables"
msgstr "Keine Forderungen"
+msgid "No reference image"
+msgstr "Kein Referenzbild"
+
msgid "No remaining entities to inspect."
msgstr "Keine verbleibenden Entitäten zur Überprüfung."
@@ -8443,9 +8512,6 @@ msgstr "Hier sind keine Zeilen."
msgid "No rules assigned"
msgstr "Keine Regeln zugewiesen"
-msgid "No samples inspected yet."
-msgstr "Noch keine Muster inspiziert."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Keine einzige, vertrauenswürdige Zahl für Bestand oder Auftragsstatus"
@@ -8464,6 +8530,12 @@ msgstr "Noch keine Lieferanten"
msgid "No time entries for this week"
msgstr "Keine Zeiteinträge für diese Woche"
+msgid "No tools"
+msgstr "Keine Werkzeuge"
+
+msgid "No tools for this step"
+msgstr "Keine Werkzeuge für diesen Schritt"
+
msgid "No transactions in this period"
msgstr "Keine Transaktionen in diesem Zeitraum"
@@ -8773,6 +8845,9 @@ msgstr "Betrieb"
msgid "Operation Order"
msgstr "Operationsreihenfolge"
+msgid "Operation Timer"
+msgstr "Operationstimer"
+
msgid "Operation Type"
msgstr "Operationstyp"
@@ -8900,6 +8975,9 @@ msgstr "Gemeinkostenabweichung"
msgid "Over-applied by"
msgstr "Überangewendet um"
+msgid "Overall result"
+msgstr "Gesamtergebnis"
+
msgid "Overdue"
msgstr "Überfällig"
@@ -9027,9 +9105,6 @@ msgstr "Teilenummer"
msgid "Part Supersession"
msgstr "Teilersatz"
-msgid "Partial"
-msgstr "Teilweise"
-
msgid "Partner"
msgstr "Partner"
@@ -9246,6 +9321,9 @@ msgstr "Stück/Stunde"
msgid "Pieces/Minute"
msgstr "Stück/Minute"
+msgid "Pin"
+msgstr "Anheften"
+
msgid "Pinned"
msgstr "Angeheftet"
@@ -9447,6 +9525,9 @@ msgstr "Vorheriges Datum"
msgid "Previous page"
msgstr "Vorherige Seite"
+msgid "Previous step"
+msgstr "Vorheriger Schritt"
+
msgid "Price break actions"
msgstr "Aktionen für Preisabstufung"
@@ -10138,9 +10219,6 @@ msgstr "Datensatz gelöscht"
msgid "Record inspections tied to a part and a job"
msgstr "Inspektionen aufzeichnen, die an ein Teil und einen Auftrag gebunden sind"
-msgid "Record the inspection result for this sample."
-msgstr "Inspektionsergebnis für diese Stichprobe aufzeichnen."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Bei einer Kalibrierung vermerkt, dass das Messinstrument repariert werden muss, bevor seinen Messwerte vertraut werden kann."
@@ -10265,9 +10343,6 @@ msgstr "Entfernen {label}"
msgid "Remove condition"
msgstr "Bedingung entfernen"
-msgid "Remove feature"
-msgstr "Feature entfernen"
-
msgid "Remove filter"
msgstr "Filter entfernen"
@@ -10286,12 +10361,21 @@ msgstr "Bestellung entfernen"
msgid "Remove pair"
msgstr "Paar entfernen"
+msgid "Remove part"
+msgstr "Teil entfernen"
+
+msgid "Remove slide"
+msgstr "Folie entfernen"
+
msgid "Remove sort by column"
msgstr "Sortierung nach Spalte entfernen"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Entfernen Sie diesen Speichertyp aus allen referenzierenden Speichereinheiten und löschen Sie ihn. Dies kann nicht rückgängig gemacht werden."
+msgid "Remove tool"
+msgstr "Werkzeug entfernen"
+
msgid "Removed"
msgstr "Entfernt"
@@ -10421,9 +10505,6 @@ msgstr "Erfordert Maßnahmen"
msgid "Requires Adjustment"
msgstr "Erfordert Anpassung"
-msgid "Requires Inspection"
-msgstr "Inspektionspflicht erforderlich"
-
msgid "Requires Repair"
msgstr "Reparatur erforderlich"
@@ -10444,7 +10525,7 @@ msgstr "PIN zurücksetzen"
msgid "Reset PIN for {0} {1}"
msgstr "PIN zurücksetzen für {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Ansicht zurücksetzen"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Gleich wie Buch"
msgid "Sample"
msgstr "Probe"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Muster {0}"
-
msgid "Sample Size"
msgstr "Stichprobengröße"
-msgid "Sampling Plan"
-msgstr "Stichprobenplan"
+msgid "Sampling"
+msgstr "Stichprobenprüfung"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Stichprobenprüfung — Funktion {featureLabel}"
msgid "Sampling Standard"
msgstr "Stichprobenstandard"
@@ -10852,8 +10932,8 @@ msgstr "Scannen oder Verfolgungsnummer eingeben"
msgid "Scan or search..."
msgstr "Scannen oder suchen..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Scannen oder wählen Sie eine nachverfölgte Entität aus diesem Los aus und erfassen Sie das Inspektionsergebnis."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scannen Sie eine verfolgbare Entität aus dieser Charge oder wählen Sie eine aus, um sie als Beispielspalte hinzuzufügen, und erfassen Sie dann ihr Ergebnis in der Tabelle."
msgid "Scan the tracking ID for this line"
msgstr "Scannen Sie die Tracking-ID für diese Zeile"
@@ -10900,6 +10980,9 @@ msgstr "Bereiche"
msgid "Scrap"
msgstr "Verschrottung"
+msgid "Scrap / Cost of Quality"
+msgstr "Verschrott / Qualitätskosten"
+
msgid "Scrap Percent"
msgstr "Ausschussquote"
@@ -10960,6 +11043,9 @@ msgstr "Job durchsuchen"
msgid "Search operators..."
msgstr "Operatoren durchsuchen..."
+msgid "Search parts..."
+msgstr "Teile durchsuchen..."
+
msgid "Search processes..."
msgstr "Prozesse durchsuchen..."
@@ -10969,6 +11055,9 @@ msgstr "Nach verwandten Elementen suchen..."
msgid "Search suppliers..."
msgstr "Lieferanten durchsuchen..."
+msgid "Search tools..."
+msgstr "Werkzeuge durchsuchen..."
+
msgid "Search..."
msgstr "Suchen..."
@@ -10990,6 +11079,9 @@ msgstr "Wählen Sie einen Bevollmächtigten"
msgid "Select a default approver"
msgstr "Wählen Sie einen Standard-Genehmiger"
+msgid "Select a document"
+msgstr "Dokument auswählen"
+
msgid "Select a new owner"
msgstr "Wählen Sie einen neuen Eigentümer"
@@ -11647,6 +11739,9 @@ msgstr "Ersatzteilverbrauch"
msgid "Spare Part Cost"
msgstr "Ersatzteilkosten"
+msgid "Spec"
+msgstr "Spezifikation"
+
msgid "Specific Customer"
msgstr "Bestimmter Kunde"
@@ -11777,6 +11872,12 @@ msgstr "Schritte"
msgid "Steps"
msgstr "Schritte"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Die Schritte werden von der Montageanleitungen geerbt."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Schritte werden vom Inspektionsplan geerbt."
+
msgid "Stock Transfer ID"
msgstr "Lagerbestandstransfer-ID"
@@ -12470,8 +12571,8 @@ msgstr "Der durchgängige Geschäflauf vom Angebot an einen Kunden bis zur Zahlu
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Der Endpunkt, der eine POST-Anfrage mit den aktualisierten Daten empfängt, wenn die Tabelle aktualisiert wird"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Die technische Zeichnung, an die dieses Inspektionsdokument gebunden ist; gegen diesen Teilbezug aufgezeichnete Inspektionen verweisen auf diese Zeichnung."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Die technische Zeichnung, mit der dieser Inspektionsplan verknüpft ist; Inspektionen, die gegen dieses Teil aufgezeichnet werden, verweisen auf diese Zeichnung."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "Der erwartete Prozentsatz der Produktion dieses Teils, der während der Produktion verloren geht; die Planung multipliziert die Nachfrage mit 1 / (1 − Ausschuss) zur Kompensation."
@@ -12620,15 +12721,15 @@ msgstr "Die Logos, die auf Ihren gedruckten und per E-Mail versendeten Dokumente
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "Der Los-Identifikation für diesen Bestand; eine Zeile pro Charge, die Menge ist die Hand für diesen Los."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Die Charge bleibt offen, damit Sie weiterhin inspizieren und später disponieren können. Inspektionsergebnisse werden beibehalten."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Das Los wird als Bestanden markiert. {fails} erfasste Fehler werden für Ihre Unterlagen aufgezeichnet."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Das Los wird immer noch abgelehnt, aber ein NCR kann nicht erstellt werden, bis mindestens ein Problemtyp konfiguriert ist."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "Der Stichprobenplan pro Merkmal des Loses wird aus dem ausgewählten Dokument neu aufgelöst."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Der niedrigste Betrag, den dieser Lieferant für diesen Prozess berechnet, unabhängig von der Menge; Aufträge unter dem Gewinnschwellen-Volumen kosten immer noch mindestens diesen Betrag."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "Die geordnete Abfolge von Operationen, die ein Auftrag durchläuft, kopiert aus der Prozeßliste des Verfahrens."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Die ursprüngliche Modelldatei ist nicht mehr verfügbar"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Das ausgehende Buchungsdokument, das Waren aus dem Lager zu einem Kunden herausnimmt und dabei COGS bucht."
@@ -12719,8 +12820,8 @@ msgstr "Die Personen auf der Carbon-Seite, die Ihre Implementierung durchführen
msgid "The people on your team and their access to Carbon"
msgstr "Die Personen in Ihrem Team und deren Zugriff auf Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Der unternehmensabhängige Zähler hinter der lesbaren Nummer eines Dokumenttyps, assembling {prefix}{next+step, zero-padded}{suffix} und vorrückend wenn jedes Dokument erstellt wird."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Der Zähler pro Unternehmen hinter der lesbaren Nummer eines Dokumenttyps, der das Präfix, den nullen-aufgefüllten nächsten Wert und das Suffix zusammensetzt und mit der Erstellung jedes Dokuments voranschreitet."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "Das artikelweise Ergebnis, das auf dem betroffenen Material einer Nichtkonformität aufgezeichnet wird — Ausstehend, Rückkehr zum Lieferanten, Nachbearbeitung, Ausschuss oder Wie-Ist-Verwendung — für jede betroffene Charge oder Seriennummer separat entschieden."
@@ -13011,6 +13112,9 @@ msgstr "Diese Informationen werden in Dokumentkopfzeilen verwendet"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Diese Informationen sind für alle Benutzer sichtbar, daher seien Sie vorsichtig, was Sie teilen."
+msgid "this inspection plan"
+msgstr "dieser Inspektionsplan"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Dies ist ein gekauftes Element – es hat keine Stückliste/Arbeitspläne; nur seine Attribute und Dokumente können sich ändern."
@@ -13459,9 +13563,6 @@ msgstr "Typ:"
msgid "Types"
msgstr "Typen"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Nicht beprobte Entitäten bleiben in Warteschleife, damit Sie weiterhin inspizieren und später dispositieren können. Beprobte Ergebnisse bleiben erhalten."
-
msgid "Unapplied"
msgstr "Nicht angewendet"
@@ -14311,6 +14412,9 @@ msgstr "Wenn aktiviert, erscheinen Attribute in dieser Kategorie im öffentliche
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Wenn aktiviert, können Mitarbeiter den Wert dieses Attributs in ihrem eigenen Profil bearbeiten; andernfalls können nur Administratoren dies tun."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Wenn aktiviert, startet das Öffnen einer Operation automatisch ihren Timer."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Wenn aktiviert, gelten Preisregeln (Volumenrabatte, Promotionen) weiterhin auf dieser Außerkraftsetzung; wenn deaktiviert, ist diese Außerkraftsetzung der endgültige Preis."
@@ -14437,8 +14541,8 @@ msgstr "Ob die Uhr startet, wenn der gewählte Prozess beginnt oder wenn er abge
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Ob dieses Los/diese Seriennummer die Prüfung besteht (Pass) oder nicht besteht (Fail); ein Fail verhindert, dass der Bestand in den verfügbaren Bestand aufgenommen wird."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Ob dieser Prozess auf internen Arbeitsplätzen (Inside), bei externen Lieferanten (Outside) oder bei beiden (Both) ausgeführt wird; zeigt unterschiedliche nachgelagerte Felder an und ändert, wie die Planung die Arbeitsgänge für diesen Prozess leitet."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Ob dieser Prozess in internen Arbeitszentren (Prozess, Montage oder Inspektion) oder bei externen Lieferanten (Fremdbearbeitung) abläuft; zeigt verschiedene nachgelagerte Felder an, ändert die Funktionsweise von Planungsrouten für diesen Prozess und legt den Standardoperationstyp für neue Operationen fest."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Ob diese Arbeit die Produktion blockiert (Ausfall), sie beeinträchtigt (Auswirkung), in einem geplanten Ausfallzeitfenster stattfindet (Geplant) oder keine Produktionsauswirkung hat (Keine Auswirkung); informiert die Planung und die kundenorientierte Ausfallzeitkommunikation."
@@ -14446,6 +14550,9 @@ msgstr "Ob diese Arbeit die Produktion blockiert (Ausfall), sie beeinträchtigt
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Ob die ausgewählten Berechtigungen auf das hinzugefügt werden, was jeder Benutzer bereits hat, oder Aktualisierung durch Ersetzen des Berechtigungssatzes jedes Benutzers mit der folgenden Auswahl."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Welches Dokument bestimmt jeden Inspektionsfluss für diesen Artikel."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Welches Fertigungsereignis die Lagerfrist-Uhr startet — z. B. Füllen, Versiegeln oder endgültiges QS."
@@ -14608,6 +14715,9 @@ msgstr "Abschreibungskonto"
msgid "Write-off for {0}"
msgstr "Abschreibung für {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Abschreibung von Lagern, die durch Inspektionsablehnungen und NCR-Verfügungen verschrottet oder zurückgegeben wurden"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Den Wert eines Vermögenswerts über seine Lebensdauer abschreiben — ein monatlicher Batch, den Sie erstellen, als Entwurf überprüfen und dann buchen."
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index ad3bd3a525..f780818dbf 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} von {1} abgeschlossen"
msgid "{0} Scrapped"
msgstr "{0} Ausschuss"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} bestandene Einheit(en) werden abgeschlossen."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} erfasste Fehler werden NICHT abgeschlossen – beheben Sie diese über das Aktionsmenü."
+
msgid "About"
msgstr "Über"
+msgid "Accept"
+msgstr "Annehmen"
+
+msgid "Accept Lot"
+msgstr "Charge annehmen"
+
+msgid "Accept lot?"
+msgstr "Charge annehmen?"
+
msgid "Account Settings"
msgstr "Kontoeinstellungen"
@@ -66,12 +81,27 @@ msgstr "Fügen Sie einen Drucker in den Druckeinstellungen hinzu, um Etiketten d
msgid "Add Inventory"
msgstr "Bestand hinzufügen"
+msgid "Add Sample"
+msgstr "Probe hinzufügen"
+
msgid "Add Spare Part"
msgstr "Ersatzteil hinzufügen"
msgid "All"
msgstr "Alle"
+msgid "All rework"
+msgstr "Alle Überarbeitungen"
+
+msgid "All scrap"
+msgstr "Alles Ausschuss"
+
+msgid "Allocate failed units"
+msgstr "Fehlerhafte Einheiten zuordnen"
+
+msgid "Allocate units"
+msgstr "Einheiten zuordnen"
+
msgid "Are you sure you want to delete this step?"
msgstr "Möchten Sie diesen Schritt wirklich löschen?"
@@ -165,6 +195,12 @@ msgstr "Ausstempeln"
msgid "Clocked in since {0}"
msgstr "Eingestempelt seit {0}"
+msgid "Close"
+msgstr "Schließen"
+
+msgid "Collapse features table"
+msgstr "Merkmalstabelle ausblenden"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Abschließen"
msgid "Complete All"
msgstr "Alles abschließen"
+msgid "Complete passed"
+msgstr "Bestandene abgeschlossen"
+
msgid "Completed"
msgstr "Abgeschlossen"
@@ -281,6 +320,9 @@ msgstr "Entwurf"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Datei hierher ziehen oder klicken, um eine Datei auszuwählen"
+msgid "Drag to resize drawing and features"
+msgstr "Zeichnung und Funktionen durch Ziehen vergrößern/verkleinern"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Ziehen von {0} abgebrochen."
@@ -325,6 +367,12 @@ msgstr "Fehler"
msgid "Estimated"
msgstr "Soll"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Jede Einheit hat ein Urteil: {passes} bestanden und {fails} fehlgeschlagen. Das Los wird geschlossen, wobei jede Einheit zu ihrem eigenen Ergebnis weitergeleitet wird."
+
+msgid "Expand features table"
+msgstr "Funktionstabelle erweitern"
+
msgid "Expired"
msgstr "Abgelaufen"
@@ -337,6 +385,12 @@ msgstr "Verfällt am {date}"
msgid "Expiring first"
msgstr "Verfällt zuerst"
+msgid "Failed"
+msgstr "Fehlgeschlagen"
+
+msgid "Failed features"
+msgstr "Fehlgeschlagene Funktionen"
+
msgid "Failed to complete inventory adjustment"
msgstr "Bestandskorrektur konnte nicht abgeschlossen werden"
@@ -349,6 +403,12 @@ msgstr "Aktive Arbeitsgänge konnten nicht abgerufen werden"
msgid "Failed to fetch storageUnits"
msgstr "Fehler beim Abrufen von Lagerbereichen"
+msgid "Failed to save measurement"
+msgstr "Messung konnte nicht gespeichert werden"
+
+msgid "Failed to save result"
+msgstr "Ergebnis konnte nicht gespeichert werden"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Datei konnte nicht hochgeladen werden: {0}"
@@ -356,6 +416,12 @@ msgstr "Datei konnte nicht hochgeladen werden: {0}"
msgid "Failed to upload image"
msgstr "Bild konnte nicht hochgeladen werden"
+msgid "Feature"
+msgstr "Funktion"
+
+msgid "Features"
+msgstr "Merkmale"
+
msgid "File size exceeds 10MB limit"
msgstr "Dateigröße überschreitet das Limit von 10 MB"
@@ -405,6 +471,12 @@ msgstr "Imperiale"
msgid "In Progress"
msgstr "In Bearbeitung"
+msgid "Inspect Item"
+msgstr "Artikel prüfen"
+
+msgid "inspected"
+msgstr "geprüft"
+
msgid "Insufficient quantity"
msgstr "Unzureichende Menge"
@@ -498,6 +570,9 @@ msgstr "Ausschuss erfassen für {0}"
msgid "Login"
msgstr "Anmelden"
+msgid "Lot"
+msgstr "Charge"
+
msgid "Machine"
msgstr "Maschine"
@@ -531,6 +606,9 @@ msgstr "Metrisch"
msgid "Model"
msgstr "Modell"
+msgid "More actions"
+msgstr "Weitere Aktionen"
+
msgid "More Actions"
msgstr "Weitere Aktionen"
@@ -595,6 +673,9 @@ msgstr "Keine Dateien"
msgid "No Impact"
msgstr "Keine Auswirkung"
+msgid "No issue types configured"
+msgstr "Keine Problemtypen konfiguriert"
+
msgid "No maintenance scheduled for today"
msgstr "Keine Instandhaltung für heute geplant"
@@ -607,6 +688,9 @@ msgstr "Keine Materialien"
msgid "No open jobs"
msgstr "Keine offenen Aufträge"
+msgid "No open units to allocate"
+msgstr "Keine offenen Einheiten zum Zuordnen"
+
msgid "No operators"
msgstr "Keine Bediener"
@@ -625,6 +709,9 @@ msgstr "Kein Drucker konfiguriert"
msgid "No recent operations"
msgstr "Keine kürzlichen Arbeitsgänge"
+msgid "No remaining entities to inspect."
+msgstr "Keine verbleibenden Einheiten zu prüfen."
+
msgid "No results"
msgstr "Keine Ergebnisse"
@@ -634,6 +721,9 @@ msgstr "Keine Ergebnisse vorhanden"
msgid "No results found"
msgstr "Keine Ergebnisse gefunden"
+msgid "No samples required."
+msgstr "Keine Proben erforderlich."
+
msgid "No scheduled time"
msgstr "Keine geplante Zeit"
@@ -683,6 +773,9 @@ msgstr "Hoppla. Diese Seite sollten Sie nicht sehen. Sie wird künftig eine Star
msgid "Open"
msgstr "Offen"
+msgid "Open an NCR for MRB disposition"
+msgstr "NCR für MRB-Disposition öffnen"
+
msgid "Open Jobs"
msgstr "Offene Aufträge"
@@ -698,12 +791,21 @@ msgstr "Vom Bediener durchgeführt"
msgid "Optional"
msgstr "Optional"
+msgid "Overall result"
+msgstr "Gesamtergebnis"
+
msgid "Parameters"
msgstr "Parameter"
msgid "Part"
msgstr "Teil"
+msgid "Partial"
+msgstr "Teilweise"
+
+msgid "Partial Disposition"
+msgstr "Teilweise Disposition"
+
msgid "Passed Inspection"
msgstr "Prüfung bestanden"
@@ -749,9 +851,6 @@ msgstr "Zurück"
msgid "Preventive"
msgstr "Vorbeugend"
-msgid "Previous"
-msgstr "Zurück"
-
msgid "Print"
msgstr "Drucken"
@@ -801,6 +900,18 @@ msgstr "Erfassen"
msgid "Record {0}"
msgstr "Datensatz {0}"
+msgid "Record only"
+msgstr "Nur aufzeichnen"
+
+msgid "Record Partial"
+msgstr "Teilweise aufzeichnen"
+
+msgid "Reject"
+msgstr "Ablehnen"
+
+msgid "Reject Lot"
+msgstr "Charge ablehnen"
+
msgid "Remove"
msgstr "Entfernen"
@@ -813,12 +924,18 @@ msgstr "Bestand entfernen"
msgid "Remove part"
msgstr "Teil entfernen"
+msgid "Result"
+msgstr "Ergebnis"
+
msgid "Rework"
msgstr "Überarbeitung"
msgid "Rework created successfully"
msgstr "Überarbeitung erfolgreich erstellt"
+msgid "Rework quantity"
+msgstr "Rework-Menge"
+
msgid "Sales Order"
msgstr "Kundenauftrag"
@@ -828,21 +945,33 @@ msgstr "Speichern"
msgid "Scan"
msgstr "Scannen"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Verfolgtes Objekt scannen, um die erste Beispielspalte hinzuzufügen."
+
msgid "Scan or enter serial number"
msgstr "Seriennummer scannen oder eingeben"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Verfolgtes Objekt mit ID, Seriennummer oder Batch scannen oder eingeben"
+
msgid "Scan or enter tracking number"
msgstr "Scannen oder Verfolgungsnummer eingeben"
msgid "Scan or search serial number..."
msgstr "Seriennummer scannen oder suchen..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scannen oder wählen Sie aus dieser Charge ein verfolgtes Objekt aus, um es als Beispielspalte hinzuzufügen, und notieren Sie dann das Ergebnis im Raster."
+
msgid "Schedule"
msgstr "Zeitplan"
msgid "Scrap"
msgstr "Ausschuss"
+msgid "Scrap quantity"
+msgstr "Verschrottungsmenge"
+
msgid "Scrap Reason"
msgstr "Ausschussgrund"
@@ -876,6 +1005,9 @@ msgstr "Ausschussmenge und Grund auswählen"
msgid "Select a serial number to continue with this operation"
msgstr "Wählen Sie eine Seriennummer, um mit diesem Arbeitsgang fortzufahren"
+msgid "Select an issue type"
+msgstr "Problemtyp wählen"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Wählen Sie einen Artikel und geben Sie die auszugebende Menge an"
@@ -899,6 +1031,9 @@ msgstr "Seriennummer auswählen"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Wählen Sie den Vorgang aus, zu dem Sie zurückkehren möchten. Alle Vorgänge von diesem Punkt bis zum aktuellen Vorgang werden wiederholt."
+msgid "Selected"
+msgstr "Ausgewählt"
+
msgid "Send"
msgstr "Senden"
@@ -978,6 +1113,10 @@ msgstr "Stationsbenutzer"
msgid "Station: {stationName}"
msgstr "Station: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "Statistische Annahme fehlgeschlagen, daher wird die gesamte Charge von {0} als nicht konform betrachtet (ISO 9001:2015 §8.7) — {passes} Stichproben bestanden und {fails} Fehler. Leiten Sie die Einheiten unten zum Verschrott oder zur Nachbearbeitung weiter, oder erfassen Sie nur das Ergebnis."
+
msgid "Status"
msgstr "Status"
@@ -1015,6 +1154,12 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "Die abgeschlossene Menge für diesen Arbeitsgang ist geringer als die erforderliche Menge von {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Das Los wird als Bestanden markiert und {remaining} verbleibende Einheit(en) werden bei diesem Arbeitsgang abgeschlossen."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Das Los wird weiterhin dispositioniert, aber ein NCR kann nicht erstellt werden, bis mindestens ein Problemtyp konfiguriert ist."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Es gibt serien- oder chargenverfolgte Materialien in der Stückliste, die noch nicht vollständig ausgegeben wurden. Ein Abschluss ohne Ausgabe kann zu fehlerhaften Rückverfolgbarkeitsdaten führen."
@@ -1048,6 +1193,9 @@ msgstr "Gesamtzeit: {0}"
msgid "Total: {0}"
msgstr "Gesamt: {0}"
+msgid "Tracked Entity"
+msgstr "Verfolgtes Objekt"
+
msgid "Tracking"
msgstr "Verfolgung"
@@ -1070,6 +1218,9 @@ msgstr "Entfernen {0}"
msgid "Unsaved changes"
msgstr "Nicht gespeicherte Änderungen"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Bis zu {maxAllocatable} Einheit(en) können zugeordnet werden; der Rest wird ohne Buchung erfasst."
+
msgid "Update"
msgstr "Aktualisieren"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 26ec41905a..cd5ade6396 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -725,6 +725,9 @@ msgstr "Add Parameter"
msgid "Add Partner"
msgstr "Add Partner"
+msgid "Add parts"
+msgstr "Add parts"
+
msgid "Add Permissions"
msgstr "Add Permissions"
@@ -749,6 +752,9 @@ msgstr "Add Risk"
msgid "Add rule"
msgstr "Add rule"
+msgid "Add Sample"
+msgstr "Add Sample"
+
msgid "Add Selector"
msgstr "Add Selector"
@@ -764,6 +770,9 @@ msgstr "Add Spare Part"
msgid "Add Step"
msgstr "Add Step"
+msgid "Add steps to preview the operator view."
+msgstr "Add steps to preview the operator view."
+
msgid "Add Supplier"
msgstr "Add Supplier"
@@ -776,6 +785,9 @@ msgstr "Add Timecard"
msgid "Add to stock for future use"
msgstr "Add to stock for future use"
+msgid "Add tools"
+msgstr "Add tools"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Add your first {0}"
@@ -1041,6 +1053,9 @@ msgstr "Applies to all"
msgid "Applies to all work centers"
msgstr "Applies to all work centers"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+
msgid "Apply"
msgstr "Apply"
@@ -1401,8 +1416,11 @@ msgstr "Are you sure you want to delete this change order?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Are you sure you want to delete this gauge?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Are you sure you want to delete this inspection document?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Are you sure you want to delete this inspection plan?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Are you sure you want to delete this inspection plan? This cannot be undone."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Are you sure you want to delete this issue workflow?"
@@ -1534,6 +1552,9 @@ msgstr "Ask an admin with {0} permission to add the first {1}."
msgid "Assemblies"
msgstr "Assemblies"
+msgid "Assembly Instruction"
+msgstr "Assembly Instruction"
+
msgid "Assembly Instructions"
msgstr "Assembly Instructions"
@@ -1678,6 +1699,12 @@ msgstr "Auto-generated QR Code"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Auto-numbering formats for orders, jobs, parts, and more"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+
+msgid "Auto-start timer on open"
+msgstr "Auto-start timer on open"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Auto-suggest purchases from demand and reorder points"
@@ -1741,6 +1768,9 @@ msgstr "Balanced"
msgid "Balloon"
msgstr "Balloon"
+msgid "Ballooned drawings with inspection features."
+msgstr "Ballooned drawings with inspection features."
+
msgid "Bank - Cash"
msgstr "Bank - Cash"
@@ -2094,6 +2124,9 @@ msgstr "Cannot upload — supplier interaction not yet created"
msgid "Cannot upload to parts bucket without item ID"
msgstr "Cannot upload to parts bucket without item ID"
+msgid "Caption"
+msgstr "Caption"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Champions"
msgid "Change"
msgstr "Change"
+msgid "Change Document"
+msgstr "Change Document"
+
+msgid "Change Inspection Plan"
+msgstr "Change Inspection Plan"
+
msgid "Change order"
msgstr "Change order"
@@ -2283,6 +2322,9 @@ msgstr "Class"
msgid "Class (inherited)"
msgstr "Class (inherited)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+
msgid "Clean and approve the migrated data"
msgstr "Clean and approve the migrated data"
@@ -2747,6 +2789,9 @@ msgstr "Convert MRP suggestions into purchase orders and jobs."
msgid "Convert to Quote"
msgstr "Convert to Quote"
+msgid "Converting…"
+msgstr "Converting…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
@@ -3055,9 +3100,6 @@ msgstr "Create Change Order"
msgid "Create Issue"
msgstr "Create Issue"
-msgid "Create Issue from Inspection"
-msgstr "Create Issue from Inspection"
-
msgid "Create Jobs"
msgstr "Create Jobs"
@@ -3699,6 +3741,9 @@ msgstr "Default Priority"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Default revenue GL account credited when a sales invoice posts."
+msgid "Default Sampling"
+msgstr "Default Sampling"
+
msgid "Default shelf-life duration (days)"
msgstr "Default shelf-life duration (days)"
@@ -3741,9 +3786,6 @@ msgstr "Define a manufacturing operation first."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Define multi-level BOMs and Bill of Process (make methods)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-
msgid "Delete"
msgstr "Delete"
@@ -3837,6 +3879,9 @@ msgstr "Delete Group"
msgid "Delete Holiday"
msgstr "Delete Holiday"
+msgid "Delete Inspection Plan"
+msgstr "Delete Inspection Plan"
+
msgid "Delete Issue"
msgstr "Delete Issue"
@@ -4329,6 +4374,9 @@ msgstr "Drag to reorder"
msgid "Drag to resize diagram and features"
msgstr "Drag to resize diagram and features"
+msgid "Drag to resize drawing and features"
+msgstr "Drag to resize drawing and features"
+
msgid "Drag to zoom"
msgstr "Drag to zoom"
@@ -4549,8 +4597,8 @@ msgstr "Edit Group"
msgid "Edit Holiday"
msgstr "Edit Holiday"
-msgid "Edit Inspection Document"
-msgstr "Edit Inspection Document"
+msgid "Edit Inspection Plan"
+msgstr "Edit Inspection Plan"
msgid "Edit Item Group"
msgstr "Edit Item Group"
@@ -5236,6 +5284,9 @@ msgstr "Extra tags for slicing your GL reporting"
msgid "Fail"
msgstr "Fail"
+msgid "Failed features"
+msgstr "Failed features"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "Failed to create asset class: {0}"
@@ -5479,6 +5530,21 @@ msgstr "Failed to save configuration rule"
msgid "Failed to save diagram"
msgstr "Failed to save diagram"
+msgid "Failed to save measurement"
+msgstr "Failed to save measurement"
+
+msgid "Failed to save parts"
+msgstr "Failed to save parts"
+
+msgid "Failed to save result"
+msgstr "Failed to save result"
+
+msgid "Failed to save slides"
+msgstr "Failed to save slides"
+
+msgid "Failed to save tools"
+msgstr "Failed to save tools"
+
msgid "Failed to update batch property"
msgstr "Failed to update batch property"
@@ -6400,15 +6466,6 @@ msgstr "Inactive actions will not appear in selection lists"
msgid "Inbound inspection"
msgstr "Inbound inspection"
-msgid "Inbound Inspection"
-msgstr "Inbound Inspection"
-
-msgid "Inbound Inspections"
-msgstr "Inbound Inspections"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Inbound Inspections: Require Different Inspector"
-
msgid "Inbox"
msgstr "Inbox"
@@ -6454,6 +6511,12 @@ msgstr "Indirect Materials & Services (default)"
msgid "Infrastructure"
msgstr "Infrastructure"
+msgid "Inherit"
+msgstr "Inherit"
+
+msgid "Inherit document default"
+msgstr "Inherit document default"
+
msgid "Inherit From Materials"
msgstr "Inherit From Materials"
@@ -6490,32 +6553,35 @@ msgstr "Inspect First N"
msgid "Inspect Item"
msgstr "Inspect Item"
-msgid "Inspect Next Item"
-msgstr "Inspect Next Item"
-
msgid "Inspection"
msgstr "Inspection"
-msgid "Inspection Document"
-msgstr "Inspection Document"
-
-msgid "Inspection Documents"
-msgstr "Inspection Documents"
-
msgid "Inspection Level"
msgstr "Inspection Level"
+msgid "Inspection Plan"
+msgstr "Inspection Plan"
+
+msgid "Inspection Plan Assignments"
+msgstr "Inspection Plan Assignments"
+
+msgid "Inspection Plans"
+msgstr "Inspection Plans"
+
msgid "Inspection Status"
msgstr "Inspection Status"
+msgid "Inspections"
+msgstr "Inspections"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspections, nonconformance, and CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspections, Nonconformance, CAPA"
-msgid "Inspector"
-msgstr "Inspector"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspections: Require Different Inspector"
msgid "Install"
msgstr "Install"
@@ -7439,15 +7505,9 @@ msgstr "Mark Done"
msgid "Mark Light Mode"
msgstr "Mark Light Mode"
-msgid "Mark lot as partial?"
-msgstr "Mark lot as partial?"
-
msgid "Mark not done"
msgstr "Mark not done"
-msgid "Mark Partial"
-msgstr "Mark Partial"
-
msgid "Mark scope as agreed"
msgstr "Mark scope as agreed"
@@ -7960,8 +8020,8 @@ msgstr "New Holiday"
msgid "New IC Transaction"
msgstr "New IC Transaction"
-msgid "New Inspection Document"
-msgstr "New Inspection Document"
+msgid "New Inspection Plan"
+msgstr "New Inspection Plan"
msgid "New Inventory Count"
msgstr "New Inventory Count"
@@ -8332,6 +8392,9 @@ msgstr "No groups assigned"
msgid "No image"
msgstr "No image"
+msgid "No inspection plans"
+msgstr "No inspection plans"
+
msgid "No issue types configured"
msgstr "No issue types configured"
@@ -8392,6 +8455,9 @@ msgstr "No parent sources recorded yet. Click Recalculate on the planning page t
msgid "No part ID"
msgstr "No part ID"
+msgid "No parts"
+msgstr "No parts"
+
msgid "No payables"
msgstr "No payables"
@@ -8428,6 +8494,9 @@ msgstr "No Quote Reasons"
msgid "No receivables"
msgstr "No receivables"
+msgid "No reference image"
+msgstr "No reference image"
+
msgid "No remaining entities to inspect."
msgstr "No remaining entities to inspect."
@@ -8443,9 +8512,6 @@ msgstr "No rows here."
msgid "No rules assigned"
msgstr "No rules assigned"
-msgid "No samples inspected yet."
-msgstr "No samples inspected yet."
-
msgid "No single, trusted number for inventory or job status"
msgstr "No single, trusted number for inventory or job status"
@@ -8464,6 +8530,12 @@ msgstr "No suppliers yet"
msgid "No time entries for this week"
msgstr "No time entries for this week"
+msgid "No tools"
+msgstr "No tools"
+
+msgid "No tools for this step"
+msgstr "No tools for this step"
+
msgid "No transactions in this period"
msgstr "No transactions in this period"
@@ -8773,6 +8845,9 @@ msgstr "Operation"
msgid "Operation Order"
msgstr "Operation Order"
+msgid "Operation Timer"
+msgstr "Operation Timer"
+
msgid "Operation Type"
msgstr "Operation Type"
@@ -8900,6 +8975,9 @@ msgstr "Outside operation"
msgid "Over-applied by"
msgstr "Over-applied by"
+msgid "Overall result"
+msgstr "Overall result"
+
msgid "Overdue"
msgstr "Overdue"
@@ -9027,9 +9105,6 @@ msgstr "Part Number"
msgid "Part Supersession"
msgstr "Part Supersession"
-msgid "Partial"
-msgstr "Partial"
-
msgid "Partner"
msgstr "Partner"
@@ -9246,6 +9321,9 @@ msgstr "Pieces/Hour"
msgid "Pieces/Minute"
msgstr "Pieces/Minute"
+msgid "Pin"
+msgstr "Pin"
+
msgid "Pinned"
msgstr "Pinned"
@@ -9447,6 +9525,9 @@ msgstr "Previous Date"
msgid "Previous page"
msgstr "Previous page"
+msgid "Previous step"
+msgstr "Previous step"
+
msgid "Price break actions"
msgstr "Price break actions"
@@ -10138,9 +10219,6 @@ msgstr "Record deleted"
msgid "Record inspections tied to a part and a job"
msgstr "Record inspections tied to a part and a job"
-msgid "Record the inspection result for this sample."
-msgstr "Record the inspection result for this sample."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
@@ -10265,9 +10343,6 @@ msgstr "Remove {label}"
msgid "Remove condition"
msgstr "Remove condition"
-msgid "Remove feature"
-msgstr "Remove feature"
-
msgid "Remove filter"
msgstr "Remove filter"
@@ -10286,12 +10361,21 @@ msgstr "Remove order"
msgid "Remove pair"
msgstr "Remove pair"
+msgid "Remove part"
+msgstr "Remove part"
+
+msgid "Remove slide"
+msgstr "Remove slide"
+
msgid "Remove sort by column"
msgstr "Remove sort by column"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
+msgid "Remove tool"
+msgstr "Remove tool"
+
msgid "Removed"
msgstr "Removed"
@@ -10421,9 +10505,6 @@ msgstr "Requires Action"
msgid "Requires Adjustment"
msgstr "Requires Adjustment"
-msgid "Requires Inspection"
-msgstr "Requires Inspection"
-
msgid "Requires Repair"
msgstr "Requires Repair"
@@ -10444,8 +10525,8 @@ msgstr "Reset PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Reset PIN for {0} {1}"
-msgid "Reset View"
-msgstr "Reset View"
+msgid "Reset view"
+msgstr "Reset view"
msgid "Residual value"
msgstr "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Same as Book"
msgid "Sample"
msgstr "Sample"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Sample {0}"
-
msgid "Sample Size"
msgstr "Sample Size"
-msgid "Sampling Plan"
-msgstr "Sampling Plan"
+msgid "Sampling"
+msgstr "Sampling"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Sampling — Feature {featureLabel}"
msgid "Sampling Standard"
msgstr "Sampling Standard"
@@ -10852,8 +10932,8 @@ msgstr "Scan or enter tracking number"
msgid "Scan or search..."
msgstr "Scan or search..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Scan or select a tracked entity from this lot and record the inspection result."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgid "Scan the tracking ID for this line"
msgstr "Scan the tracking ID for this line"
@@ -10900,6 +10980,9 @@ msgstr "Scopes"
msgid "Scrap"
msgstr "Scrap"
+msgid "Scrap / Cost of Quality"
+msgstr "Scrap / Cost of Quality"
+
msgid "Scrap Percent"
msgstr "Scrap Percent"
@@ -10960,6 +11043,9 @@ msgstr "Search Job"
msgid "Search operators..."
msgstr "Search operators..."
+msgid "Search parts..."
+msgstr "Search parts..."
+
msgid "Search processes..."
msgstr "Search processes..."
@@ -10969,6 +11055,9 @@ msgstr "Search related items..."
msgid "Search suppliers..."
msgstr "Search suppliers..."
+msgid "Search tools..."
+msgstr "Search tools..."
+
msgid "Search..."
msgstr "Search..."
@@ -10990,6 +11079,9 @@ msgstr "Select a assignee"
msgid "Select a default approver"
msgstr "Select a default approver"
+msgid "Select a document"
+msgstr "Select a document"
+
msgid "Select a new owner"
msgstr "Select a new owner"
@@ -11647,6 +11739,9 @@ msgstr "Spare Part Consumption"
msgid "Spare Part Cost"
msgstr "Spare Part Cost"
+msgid "Spec"
+msgstr "Spec"
+
msgid "Specific Customer"
msgstr "Specific Customer"
@@ -11777,6 +11872,12 @@ msgstr "steps"
msgid "Steps"
msgstr "Steps"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Steps are inherited from the assembly instruction."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Steps are inherited from the inspection plan."
+
msgid "Stock Transfer ID"
msgstr "Stock Transfer ID"
@@ -12470,8 +12571,8 @@ msgstr "The end-to-end commercial flow from quoting a customer to collecting pay
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "The endpoint that receives a POST request with the updated data when the table is updated"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
@@ -12620,15 +12721,15 @@ msgstr "The logos shown on your printed and emailed documents"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "The lot's per-feature sampling plan will be re-resolved from the selected document."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
@@ -12719,8 +12820,8 @@ msgstr "The people on the Carbon side who will run your implementation, and how
msgid "The people on your team and their access to Carbon"
msgstr "The people on your team and their access to Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
@@ -13011,6 +13112,9 @@ msgstr "This information will be used on document headers"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "This information will be visible to all users, so be careful what you share."
+msgid "this inspection plan"
+msgstr "this inspection plan"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
@@ -13459,9 +13563,6 @@ msgstr "Type:"
msgid "Types"
msgstr "Types"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-
msgid "Unapplied"
msgstr "Unapplied"
@@ -14311,6 +14412,9 @@ msgstr "When on, attributes in this category show up on a person's public profil
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "When on, opening an operation starts its timer automatically."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
@@ -14437,8 +14541,8 @@ msgstr "Whether the clock starts when the chosen process begins or when it compl
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
@@ -14446,6 +14550,9 @@ msgstr "Whether this work blocks production (Down), degrades it (Impact), is on
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Which document drives each inspection flow for this item."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
@@ -14608,6 +14715,9 @@ msgstr "Write-Off Account"
msgid "Write-off for {0}"
msgstr "Write-off for {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index e59379dafb..1d0d2a1bba 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} of {1} completed"
msgid "{0} Scrapped"
msgstr "{0} Scrapped"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} passed unit(s) will be completed."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+
msgid "About"
msgstr "About"
+msgid "Accept"
+msgstr "Accept"
+
+msgid "Accept Lot"
+msgstr "Accept Lot"
+
+msgid "Accept lot?"
+msgstr "Accept lot?"
+
msgid "Account Settings"
msgstr "Account Settings"
@@ -66,12 +81,27 @@ msgstr "Add a printer in the printing settings to print labels directly."
msgid "Add Inventory"
msgstr "Add Inventory"
+msgid "Add Sample"
+msgstr "Add Sample"
+
msgid "Add Spare Part"
msgstr "Add Spare Part"
msgid "All"
msgstr "All"
+msgid "All rework"
+msgstr "All rework"
+
+msgid "All scrap"
+msgstr "All scrap"
+
+msgid "Allocate failed units"
+msgstr "Allocate failed units"
+
+msgid "Allocate units"
+msgstr "Allocate units"
+
msgid "Are you sure you want to delete this step?"
msgstr "Are you sure you want to delete this step?"
@@ -165,6 +195,12 @@ msgstr "Clock Out"
msgid "Clocked in since {0}"
msgstr "Clocked in since {0}"
+msgid "Close"
+msgstr "Close"
+
+msgid "Collapse features table"
+msgstr "Collapse features table"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Complete"
msgid "Complete All"
msgstr "Complete All"
+msgid "Complete passed"
+msgstr "Complete passed"
+
msgid "Completed"
msgstr "Completed"
@@ -281,6 +320,9 @@ msgstr "Draft"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Drag and drop a file here, or click to select a file"
+msgid "Drag to resize drawing and features"
+msgstr "Drag to resize drawing and features"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Dragging {0} cancelled."
@@ -325,6 +367,12 @@ msgstr "Error"
msgid "Estimated"
msgstr "Estimated"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+
+msgid "Expand features table"
+msgstr "Expand features table"
+
msgid "Expired"
msgstr "Expired"
@@ -337,6 +385,12 @@ msgstr "Expires {date}"
msgid "Expiring first"
msgstr "Expiring first"
+msgid "Failed"
+msgstr "Failed"
+
+msgid "Failed features"
+msgstr "Failed features"
+
msgid "Failed to complete inventory adjustment"
msgstr "Failed to complete inventory adjustment"
@@ -349,6 +403,12 @@ msgstr "Failed to fetch active operations"
msgid "Failed to fetch storageUnits"
msgstr "Failed to fetch storageUnits"
+msgid "Failed to save measurement"
+msgstr "Failed to save measurement"
+
+msgid "Failed to save result"
+msgstr "Failed to save result"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Failed to upload file: {0}"
@@ -356,6 +416,12 @@ msgstr "Failed to upload file: {0}"
msgid "Failed to upload image"
msgstr "Failed to upload image"
+msgid "Feature"
+msgstr "Feature"
+
+msgid "Features"
+msgstr "Features"
+
msgid "File size exceeds 10MB limit"
msgstr "File size exceeds 10MB limit"
@@ -405,6 +471,12 @@ msgstr "Imperial"
msgid "In Progress"
msgstr "In Progress"
+msgid "Inspect Item"
+msgstr "Inspect Item"
+
+msgid "inspected"
+msgstr "inspected"
+
msgid "Insufficient quantity"
msgstr "Insufficient quantity"
@@ -498,6 +570,9 @@ msgstr "Log scrap for {0}"
msgid "Login"
msgstr "Login"
+msgid "Lot"
+msgstr "Lot"
+
msgid "Machine"
msgstr "Machine"
@@ -531,6 +606,9 @@ msgstr "Metric"
msgid "Model"
msgstr "Model"
+msgid "More actions"
+msgstr "More actions"
+
msgid "More Actions"
msgstr "More Actions"
@@ -595,6 +673,9 @@ msgstr "No files"
msgid "No Impact"
msgstr "No Impact"
+msgid "No issue types configured"
+msgstr "No issue types configured"
+
msgid "No maintenance scheduled for today"
msgstr "No maintenance scheduled for today"
@@ -607,6 +688,9 @@ msgstr "No materials"
msgid "No open jobs"
msgstr "No open jobs"
+msgid "No open units to allocate"
+msgstr "No open units to allocate"
+
msgid "No operators"
msgstr "No operators"
@@ -625,6 +709,9 @@ msgstr "No printer configured"
msgid "No recent operations"
msgstr "No recent operations"
+msgid "No remaining entities to inspect."
+msgstr "No remaining entities to inspect."
+
msgid "No results"
msgstr "No results"
@@ -634,6 +721,9 @@ msgstr "No results exist"
msgid "No results found"
msgstr "No results found"
+msgid "No samples required."
+msgstr "No samples required."
+
msgid "No scheduled time"
msgstr "No scheduled time"
@@ -683,6 +773,9 @@ msgstr "Oops. You shouldn't see this page. Eventually it will be a landing page.
msgid "Open"
msgstr "Open"
+msgid "Open an NCR for MRB disposition"
+msgstr "Open an NCR for MRB disposition"
+
msgid "Open Jobs"
msgstr "Open Jobs"
@@ -698,12 +791,21 @@ msgstr "Operator Performed"
msgid "Optional"
msgstr "Optional"
+msgid "Overall result"
+msgstr "Overall result"
+
msgid "Parameters"
msgstr "Parameters"
msgid "Part"
msgstr "Part"
+msgid "Partial"
+msgstr "Partial"
+
+msgid "Partial Disposition"
+msgstr "Partial Disposition"
+
msgid "Passed Inspection"
msgstr "Passed Inspection"
@@ -749,9 +851,6 @@ msgstr "Prev"
msgid "Preventive"
msgstr "Preventive"
-msgid "Previous"
-msgstr "Previous"
-
msgid "Print"
msgstr "Print"
@@ -801,6 +900,18 @@ msgstr "Record"
msgid "Record {0}"
msgstr "Record {0}"
+msgid "Record only"
+msgstr "Record only"
+
+msgid "Record Partial"
+msgstr "Record Partial"
+
+msgid "Reject"
+msgstr "Reject"
+
+msgid "Reject Lot"
+msgstr "Reject Lot"
+
msgid "Remove"
msgstr "Remove"
@@ -813,12 +924,18 @@ msgstr "Remove Inventory"
msgid "Remove part"
msgstr "Remove part"
+msgid "Result"
+msgstr "Result"
+
msgid "Rework"
msgstr "Rework"
msgid "Rework created successfully"
msgstr "Rework created successfully"
+msgid "Rework quantity"
+msgstr "Rework quantity"
+
msgid "Sales Order"
msgstr "Sales Order"
@@ -828,21 +945,33 @@ msgstr "Save"
msgid "Scan"
msgstr "Scan"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Scan a tracked entity to add the first sample column."
+
msgid "Scan or enter serial number"
msgstr "Scan or enter serial number"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Scan or enter tracked entity ID, serial, or batch"
+
msgid "Scan or enter tracking number"
msgstr "Scan or enter tracking number"
msgid "Scan or search serial number..."
msgstr "Scan or search serial number..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+
msgid "Schedule"
msgstr "Schedule"
msgid "Scrap"
msgstr "Scrap"
+msgid "Scrap quantity"
+msgstr "Scrap quantity"
+
msgid "Scrap Reason"
msgstr "Scrap Reason"
@@ -876,6 +1005,9 @@ msgstr "Select a scrap quantity and reason"
msgid "Select a serial number to continue with this operation"
msgstr "Select a serial number to continue with this operation"
+msgid "Select an issue type"
+msgstr "Select an issue type"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Select an item and specify the quantity to issue"
@@ -899,6 +1031,9 @@ msgstr "Select Serial Number"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Select the operation to go back to. All operations from that point to the current operation will be redone."
+msgid "Selected"
+msgstr "Selected"
+
msgid "Send"
msgstr "Send"
@@ -978,6 +1113,10 @@ msgstr "Station User"
msgid "Station: {stationName}"
msgstr "Station: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+
msgid "Status"
msgstr "Status"
@@ -1015,6 +1154,12 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "The completed quantity for this operation is less than the required quantity of {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
@@ -1048,6 +1193,9 @@ msgstr "Total time: {0}"
msgid "Total: {0}"
msgstr "Total: {0}"
+msgid "Tracked Entity"
+msgstr "Tracked Entity"
+
msgid "Tracking"
msgstr "Tracking"
@@ -1070,6 +1218,9 @@ msgstr "Unpick {0}"
msgid "Unsaved changes"
msgstr "Unsaved changes"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+
msgid "Update"
msgstr "Update"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 99d28dec51..8cb8854031 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -725,6 +725,9 @@ msgstr "Agregar Parámetro"
msgid "Add Partner"
msgstr "Agregar Socio"
+msgid "Add parts"
+msgstr "Agregar piezas"
+
msgid "Add Permissions"
msgstr "Agregar Permisos"
@@ -749,6 +752,9 @@ msgstr "Agregar Riesgo"
msgid "Add rule"
msgstr "Agregar regla"
+msgid "Add Sample"
+msgstr "Añadir Muestra"
+
msgid "Add Selector"
msgstr "Agregar selector"
@@ -764,6 +770,9 @@ msgstr "Agregar Pieza de Repuesto"
msgid "Add Step"
msgstr "Agregar paso"
+msgid "Add steps to preview the operator view."
+msgstr "Agregar pasos para obtener una vista previa de la vista del operador."
+
msgid "Add Supplier"
msgstr "Agregar Proveedor"
@@ -776,6 +785,9 @@ msgstr "Agregar Tarjeta de Tiempo"
msgid "Add to stock for future use"
msgstr "Agregar al inventario para uso futuro"
+msgid "Add tools"
+msgstr "Agregar herramientas"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Agregue su primer {0}"
@@ -1041,6 +1053,9 @@ msgstr "Se aplica a todos"
msgid "Applies to all work centers"
msgstr "Se aplica a todos los centros de trabajo"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Se aplica a características sin su propia regla, y al lote cuando este plan impulsa una inspección."
+
msgid "Apply"
msgstr "Aplicar"
@@ -1401,8 +1416,11 @@ msgstr "¿Está seguro de que desea eliminar esta orden de cambio?"
msgid "Are you sure you want to delete this gauge?"
msgstr "¿Estás seguro de que deseas eliminar este calibrador?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "¿Estás seguro de que deseas eliminar este documento de inspección?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "¿Está seguro de que desea eliminar este plan de inspección?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "¿Estás seguro de que deseas eliminar este plan de inspección? Esto no se puede deshacer."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "¿Estás seguro de que deseas eliminar este flujo de trabajo de problemas?"
@@ -1534,6 +1552,9 @@ msgstr "Pida a un administrador con permiso {0} que agregue el primer {1}."
msgid "Assemblies"
msgstr "Asambleas"
+msgid "Assembly Instruction"
+msgstr "Instrucción de Montaje"
+
msgid "Assembly Instructions"
msgstr "Instrucciones de Montaje"
@@ -1678,6 +1699,12 @@ msgstr "Código QR generado automáticamente"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Formatos de numeración automática para pedidos, trabajos, piezas y más"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Iniciar automáticamente el cronómetro del operario cuando abra una operación en el MES para que se capturen registros de tiempo desde el inicio."
+
+msgid "Auto-start timer on open"
+msgstr "Iniciar cronómetro automáticamente al abrir"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Sugerir automáticamente compras según la demanda y puntos de reorden"
@@ -1741,6 +1768,9 @@ msgstr "Equilibrado"
msgid "Balloon"
msgstr "Globo"
+msgid "Ballooned drawings with inspection features."
+msgstr "Planos con características de inspección indicadas."
+
msgid "Bank - Cash"
msgstr "Banco - Efectivo"
@@ -2094,6 +2124,9 @@ msgstr "No se puede cargar — la interacción con el proveedor aún no se ha cr
msgid "Cannot upload to parts bucket without item ID"
msgstr "No se puede cargar en el depósito de piezas sin ID de artículo"
+msgid "Caption"
+msgstr "Leyenda"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Campeones"
msgid "Change"
msgstr "Cambiar"
+msgid "Change Document"
+msgstr "Cambiar Documento"
+
+msgid "Change Inspection Plan"
+msgstr "Cambiar plan de inspección"
+
msgid "Change order"
msgstr "Orden de cambio"
@@ -2283,6 +2322,9 @@ msgstr "Clase"
msgid "Class (inherited)"
msgstr "Clase (heredada)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Clasifica una operación de enrutamiento: Las operaciones de Proceso, Montaje e Inspección se ejecutan en su propio piso de taller en el MES — El Montaje obtiene la vista de montaje guiado e Inspección una verificación de calidad — mientras que una operación de Procesamiento Externo se subcontrata a un proveedor y crea una orden de compra; el proceso lleva el mismo tipo y lo establece como predeterminado en nuevas operaciones."
+
msgid "Clean and approve the migrated data"
msgstr "Limpiar y aprobar los datos migrados"
@@ -2747,6 +2789,9 @@ msgstr "Convierte sugerencias de MRP en órdenes de compra y trabajos."
msgid "Convert to Quote"
msgstr "Convertir a Cotización"
+msgid "Converting…"
+msgstr "Convirtiendo…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Convierte la unidad de compra de un proveedor a su unidad de inventario en una línea de pedido, recepción o factura — compre en cajas de 12, reserve en individuos."
@@ -3055,9 +3100,6 @@ msgstr "Crear Orden de Cambio"
msgid "Create Issue"
msgstr "Crear Problema"
-msgid "Create Issue from Inspection"
-msgstr "Crear incidencia desde inspección"
-
msgid "Create Jobs"
msgstr "Crear Trabajos"
@@ -3699,6 +3741,9 @@ msgstr "Prioridad Predeterminada"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Cuenta GL de ingresos predeterminada acreditada cuando se contabiliza una factura de venta."
+msgid "Default Sampling"
+msgstr "Muestreo Predeterminado"
+
msgid "Default shelf-life duration (days)"
msgstr "Duración predeterminada de vida útil (días)"
@@ -3741,9 +3786,6 @@ msgstr "Defina primero una operación de fabricación."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definir BOMs multinivel y Bill of Process (métodos de fabricación)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Define cuántas entidades rastreadas se inspeccionan por lote y cuántas fallas se toleran antes de que el lote sea rechazado."
-
msgid "Delete"
msgstr "Eliminar"
@@ -3837,6 +3879,9 @@ msgstr "Eliminar Grupo"
msgid "Delete Holiday"
msgstr "Eliminar Día Festivo"
+msgid "Delete Inspection Plan"
+msgstr "Eliminar Plan de Inspección"
+
msgid "Delete Issue"
msgstr "Eliminar Problema"
@@ -4329,6 +4374,9 @@ msgstr "Arrastra para reordenar"
msgid "Drag to resize diagram and features"
msgstr "Arrastra para redimensionar el diagrama y las características"
+msgid "Drag to resize drawing and features"
+msgstr "Arrastra para redimensionar el dibujo y las características"
+
msgid "Drag to zoom"
msgstr "Arrastra para ampliar"
@@ -4549,8 +4597,8 @@ msgstr "Editar Grupo"
msgid "Edit Holiday"
msgstr "Editar Festivo"
-msgid "Edit Inspection Document"
-msgstr "Editar Documento de Inspección"
+msgid "Edit Inspection Plan"
+msgstr "Editar plan de inspección"
msgid "Edit Item Group"
msgstr "Editar Grupo de Artículos"
@@ -5236,6 +5284,9 @@ msgstr "Etiquetas adicionales para segmentar tu informe de GL"
msgid "Fail"
msgstr "Fallar"
+msgid "Failed features"
+msgstr "Características fallidas"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (primero que vence, primero que sale)"
@@ -5479,6 +5530,21 @@ msgstr "Error al guardar la regla de configuración"
msgid "Failed to save diagram"
msgstr "No se pudo guardar el diagrama"
+msgid "Failed to save measurement"
+msgstr "Error al guardar la medición"
+
+msgid "Failed to save parts"
+msgstr "Error al guardar piezas"
+
+msgid "Failed to save result"
+msgstr "Error al guardar resultado"
+
+msgid "Failed to save slides"
+msgstr "Error al guardar diapositivas"
+
+msgid "Failed to save tools"
+msgstr "Error al guardar herramientas"
+
msgid "Failed to update batch property"
msgstr "Error al actualizar la propiedad de lote"
@@ -6400,15 +6466,6 @@ msgstr "Las acciones inactivas no aparecerán en las listas de selección"
msgid "Inbound inspection"
msgstr "Inspección de entrada"
-msgid "Inbound Inspection"
-msgstr "Inspección de Entrada"
-
-msgid "Inbound Inspections"
-msgstr "Inspecciones de Entrada"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Inspecciones de Entrada: Requerir Inspector Diferente"
-
msgid "Inbox"
msgstr "Bandeja de entrada"
@@ -6454,6 +6511,12 @@ msgstr "Materiales Indirectos y Servicios (predeterminado)"
msgid "Infrastructure"
msgstr "Infraestructura"
+msgid "Inherit"
+msgstr "Heredar"
+
+msgid "Inherit document default"
+msgstr "Heredar valor predeterminado del documento"
+
msgid "Inherit From Materials"
msgstr "Heredar de Materiales"
@@ -6490,32 +6553,35 @@ msgstr "Inspeccionar los Primeros N"
msgid "Inspect Item"
msgstr "Inspeccionar Artículo"
-msgid "Inspect Next Item"
-msgstr "Inspeccionar Siguiente Artículo"
-
msgid "Inspection"
msgstr "Inspección"
-msgid "Inspection Document"
-msgstr "Documento de Inspección"
-
-msgid "Inspection Documents"
-msgstr "Documentos de Inspección"
-
msgid "Inspection Level"
msgstr "Nivel de Inspección"
+msgid "Inspection Plan"
+msgstr "Plan de inspección"
+
+msgid "Inspection Plan Assignments"
+msgstr "Asignaciones de plan de inspección"
+
+msgid "Inspection Plans"
+msgstr "Planes de inspección"
+
msgid "Inspection Status"
msgstr "Estado de Inspección"
+msgid "Inspections"
+msgstr "Inspecciones"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspecciones, incumplimiento y CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspecciones, Incumplimiento, CAPA"
-msgid "Inspector"
-msgstr "Inspector"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspecciones: Requerir Inspector Diferente"
msgid "Install"
msgstr "Instalar"
@@ -7439,15 +7505,9 @@ msgstr "Marcar como Completado"
msgid "Mark Light Mode"
msgstr "Marca Modo Claro"
-msgid "Mark lot as partial?"
-msgstr "¿Marcar lote como parcial?"
-
msgid "Mark not done"
msgstr "Marcar como no realizado"
-msgid "Mark Partial"
-msgstr "Marcar como Parcial"
-
msgid "Mark scope as agreed"
msgstr "Marcar alcance como acordado"
@@ -7960,8 +8020,8 @@ msgstr "Nuevo Día Festivo"
msgid "New IC Transaction"
msgstr "Nueva Transacción IC"
-msgid "New Inspection Document"
-msgstr "Nuevo Documento de Inspección"
+msgid "New Inspection Plan"
+msgstr "Nuevo plan de inspección"
msgid "New Inventory Count"
msgstr "Nuevo Conteo de Inventario"
@@ -8332,6 +8392,9 @@ msgstr "No hay grupos asignados"
msgid "No image"
msgstr "Sin imagen"
+msgid "No inspection plans"
+msgstr "Sin planes de inspección"
+
msgid "No issue types configured"
msgstr "No hay tipos de problemas configurados"
@@ -8392,6 +8455,9 @@ msgstr "No hay fuentes principales registradas aún. Haz clic en Recalcular en l
msgid "No part ID"
msgstr "Sin ID de pieza"
+msgid "No parts"
+msgstr "Sin piezas"
+
msgid "No payables"
msgstr "Sin cuentas por pagar"
@@ -8428,6 +8494,9 @@ msgstr "Razones sin cotización"
msgid "No receivables"
msgstr "Sin cuentas por cobrar"
+msgid "No reference image"
+msgstr "Sin imagen de referencia"
+
msgid "No remaining entities to inspect."
msgstr "No hay entidades restantes para inspeccionar."
@@ -8443,9 +8512,6 @@ msgstr "No hay filas aquí."
msgid "No rules assigned"
msgstr "Sin reglas asignadas"
-msgid "No samples inspected yet."
-msgstr "No hay muestras inspeccionadas aún."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Sin un único número confiable para inventario o estado del trabajo"
@@ -8464,6 +8530,12 @@ msgstr "Sin proveedores aún"
msgid "No time entries for this week"
msgstr "No hay entradas de tiempo para esta semana"
+msgid "No tools"
+msgstr "Sin herramientas"
+
+msgid "No tools for this step"
+msgstr "Sin herramientas para este paso"
+
msgid "No transactions in this period"
msgstr "No hay transacciones en este período"
@@ -8773,6 +8845,9 @@ msgstr "Operación"
msgid "Operation Order"
msgstr "Orden de Operación"
+msgid "Operation Timer"
+msgstr "Cronómetro de Operación"
+
msgid "Operation Type"
msgstr "Tipo de Operación"
@@ -8900,6 +8975,9 @@ msgstr "Varianza de Gastos Indirectos"
msgid "Over-applied by"
msgstr "Aplicado en exceso por"
+msgid "Overall result"
+msgstr "Resultado general"
+
msgid "Overdue"
msgstr "Vencido"
@@ -9027,9 +9105,6 @@ msgstr "Número de pieza"
msgid "Part Supersession"
msgstr "Sustitución de Pieza"
-msgid "Partial"
-msgstr "Parcial"
-
msgid "Partner"
msgstr "Socio"
@@ -9246,6 +9321,9 @@ msgstr "Piezas/Hora"
msgid "Pieces/Minute"
msgstr "Piezas/Minuto"
+msgid "Pin"
+msgstr "Anclar"
+
msgid "Pinned"
msgstr "Fijado"
@@ -9447,6 +9525,9 @@ msgstr "Fecha Anterior"
msgid "Previous page"
msgstr "Página anterior"
+msgid "Previous step"
+msgstr "Paso anterior"
+
msgid "Price break actions"
msgstr "Acciones de desglose de precios"
@@ -10138,9 +10219,6 @@ msgstr "Registro eliminado"
msgid "Record inspections tied to a part and a job"
msgstr "Registrar inspecciones vinculadas a una parte y un trabajo"
-msgid "Record the inspection result for this sample."
-msgstr "Registre el resultado de la inspección para esta muestra."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Registrado en una calibración que la galga necesita reparación antes de que sus lecturas puedan ser confiables."
@@ -10265,9 +10343,6 @@ msgstr "Eliminar {label}"
msgid "Remove condition"
msgstr "Eliminar condición"
-msgid "Remove feature"
-msgstr "Eliminar característica"
-
msgid "Remove filter"
msgstr "Eliminar filtro"
@@ -10286,12 +10361,21 @@ msgstr "Eliminar orden"
msgid "Remove pair"
msgstr "Eliminar par"
+msgid "Remove part"
+msgstr "Eliminar pieza"
+
+msgid "Remove slide"
+msgstr "Eliminar diapositiva"
+
msgid "Remove sort by column"
msgstr "Eliminar ordenamiento por columna"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Elimina este tipo de almacenamiento de todas las unidades de almacenamiento que lo referencian y elimínalo. Esto no se puede deshacer."
+msgid "Remove tool"
+msgstr "Eliminar herramienta"
+
msgid "Removed"
msgstr "Eliminado"
@@ -10421,9 +10505,6 @@ msgstr "Requiere Acción"
msgid "Requires Adjustment"
msgstr "Requiere Ajuste"
-msgid "Requires Inspection"
-msgstr "Requiere Inspección"
-
msgid "Requires Repair"
msgstr "Requiere Reparación"
@@ -10444,7 +10525,7 @@ msgstr "Restablecer PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Restablecer PIN para {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Restablecer vista"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Igual que el libro"
msgid "Sample"
msgstr "Muestra"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Muestra {0}"
-
msgid "Sample Size"
msgstr "Tamaño de Muestra"
-msgid "Sampling Plan"
-msgstr "Plan de Muestreo"
+msgid "Sampling"
+msgstr "Muestreo"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Muestreo — Característica {featureLabel}"
msgid "Sampling Standard"
msgstr "Estándar de Muestreo"
@@ -10852,8 +10932,8 @@ msgstr "Escanear o ingresar número de seguimiento"
msgid "Scan or search..."
msgstr "Escanear o buscar..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Escanea o selecciona una entidad rastreada de este lote y registra el resultado de la inspección."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Escanee o seleccione una entidad rastreada de este lote para agregarla como una columna de muestra, luego registre su resultado en la cuadrícula."
msgid "Scan the tracking ID for this line"
msgstr "Escanea el ID de seguimiento para esta línea"
@@ -10900,6 +10980,9 @@ msgstr "Alcances"
msgid "Scrap"
msgstr "Desecho"
+msgid "Scrap / Cost of Quality"
+msgstr "Rechazo / Costo de Calidad"
+
msgid "Scrap Percent"
msgstr "Porcentaje de Rechazo"
@@ -10960,6 +11043,9 @@ msgstr "Buscar trabajo"
msgid "Search operators..."
msgstr "Buscar operadores..."
+msgid "Search parts..."
+msgstr "Buscar piezas..."
+
msgid "Search processes..."
msgstr "Buscar procesos..."
@@ -10969,6 +11055,9 @@ msgstr "Buscar elementos relacionados..."
msgid "Search suppliers..."
msgstr "Buscar proveedores..."
+msgid "Search tools..."
+msgstr "Buscar herramientas..."
+
msgid "Search..."
msgstr "Buscar..."
@@ -10990,6 +11079,9 @@ msgstr "Seleccionar un asignado"
msgid "Select a default approver"
msgstr "Selecciona un aprobador predeterminado"
+msgid "Select a document"
+msgstr "Selecciona un documento"
+
msgid "Select a new owner"
msgstr "Selecciona un nuevo propietario"
@@ -11647,6 +11739,9 @@ msgstr "Consumo de Piezas de Repuesto"
msgid "Spare Part Cost"
msgstr "Costo de Piezas de Repuesto"
+msgid "Spec"
+msgstr "Especificación"
+
msgid "Specific Customer"
msgstr "Cliente Específico"
@@ -11777,6 +11872,12 @@ msgstr "pasos"
msgid "Steps"
msgstr "Pasos"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Los pasos se heredan de la instrucción de montaje."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Los pasos se heredan del plan de inspección."
+
msgid "Stock Transfer ID"
msgstr "ID de Transferencia de Inventario"
@@ -12470,8 +12571,8 @@ msgstr "El flujo comercial de extremo a extremo desde la cotización de un clien
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "El endpoint que recibe una solicitud POST con los datos actualizados cuando la tabla se actualiza"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "El dibujo de ingeniería al que está vinculado este documento de inspección; las inspecciones registradas contra esta referencia de parte hacen referencia a este dibujo."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "El dibujo de ingeniería al que está vinculado este plan de inspección; las inspecciones registradas para esta pieza hacen referencia a este dibujo."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "El porcentaje esperado de la producción de este artículo perdido durante la fabricación; la planificación multiplica la demanda por 1 / (1 − desperdicio) para compensar."
@@ -12620,15 +12721,15 @@ msgstr "Los logotipos que aparecen en tus documentos impresos y enviados por cor
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "El identificador de lote para este inventario; una fila por lote, la cantidad es la en mano para ese lote."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "El lote permanece abierto para que puedas seguir inspeccionando y disponer más tarde. Los resultados muestreados se conservan."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "El lote será marcado como Aprobado. {fails} fallo(s) muestreado(s) se registran para sus registros."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "El lote seguirá siendo rechazado, pero no se puede crear un NCR hasta que se configure al menos un tipo de problema."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "El plan de muestreo por característica del lote se volverá a resolver desde el documento seleccionado."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "La cantidad mínima que este proveedor cobrará por este proceso, independientemente de la cantidad; los trabajos por debajo del volumen de equilibrio aún cuestan al menos esta cantidad."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "La secuencia ordenada de operaciones que ejecuta un trabajo, copiada de la lista de procesos del método."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "El archivo de modelo original ya no está disponible"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "El documento de contabilización de salida que saca bienes del inventario a un cliente, contabilizando COGS en el camino."
@@ -12719,8 +12820,8 @@ msgstr "Las personas del lado de Carbon que ejecutarán tu implementación y có
msgid "The people on your team and their access to Carbon"
msgstr "Las personas en tu equipo y su acceso a Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "El contador por empresa detrás del número legible de un tipo de documento, ensamblando {prefix}{next+step, zero-padded}{suffix} y avanzando a medida que se crea cada documento."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "El contador por empresa detrás del número legible de un tipo de documento, ensamblando el prefijo, el siguiente valor relleno de ceros, y el sufijo, y avanzando a medida que se crea cada documento."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "El resultado por artículo registrado en el material afectado por una no conformidad — Pendiente, Devolver al Proveedor, Reproceso, Rechazo o Usar Como Está — decidido para cada lote o número de serie afectado de forma independiente."
@@ -13011,6 +13112,9 @@ msgstr "Esta información se utilizará en los encabezados de documentos"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Esta información será visible para todos los usuarios, así que ten cuidado con lo que compartes."
+msgid "this inspection plan"
+msgstr "este plan de inspección"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Este es un artículo comprado — no tiene BoM/BoP; solo sus atributos y documentos pueden cambiar."
@@ -13459,9 +13563,6 @@ msgstr "Tipo:"
msgid "Types"
msgstr "Tipos"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Las entidades no muestreadas permanecerán En Espera para que puedas seguir inspeccionando y disponer más tarde. Los resultados muestreados se conservan."
-
msgid "Unapplied"
msgstr "No aplicado"
@@ -14311,6 +14412,9 @@ msgstr "Cuando está activado, los atributos en esta categoría aparecen en el p
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Cuando está activado, los empleados pueden editar el valor de este atributo en su propio perfil; de lo contrario, solo los administradores pueden hacerlo."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Cuando está activado, abrir una operación inicia su cronómetro automáticamente."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Cuando está activado, las reglas de precios (descuentos por volumen, promociones) aún se aplican además de esta invalidación; cuando está desactivado, esta invalidación es el precio final."
@@ -14437,8 +14541,8 @@ msgstr "Si el reloj comienza cuando el proceso elegido empieza o cuando se compl
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Si este lote/número de serie pasa la inspección (Pass) o falla (Fail); un Fail impide que el stock se reciba en el inventario disponible."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Si este proceso se ejecuta en centros de trabajo internos (Inside), proveedores externos (Outside) o ambos (Both); muestra diferentes campos posteriores y cambia cómo la planificación enruta este proceso."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Si este proceso se ejecuta en centros de trabajo internos (Proceso, Montaje o Inspección) o en proveedores externos (Procesamiento Externo); revela diferentes campos posteriores, cambia cómo funcionan las rutas de planificación para este proceso y establece el tipo de operación predeterminado en nuevas operaciones."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Si este trabajo bloquea la producción (Inactivo), la degrada (Impacto), se encuentra en una ventana de tiempo de inactividad planificada (Planificada) o no tiene impacto de producción (Sin Impacto); informa la programación y la comunicación de tiempo de inactividad orientada al cliente."
@@ -14446,6 +14550,9 @@ msgstr "Si este trabajo bloquea la producción (Inactivo), la degrada (Impacto),
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Si se Agregan los permisos seleccionados además de lo que cada usuario ya tiene, o se Actualizan reemplazando el conjunto de permisos de cada usuario con la selección a continuación."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Qué documento conduce cada flujo de inspección para este artículo."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Qué evento de fabricación inicia el reloj de vida útil — por ejemplo, rellenado, sellado o QC final."
@@ -14608,6 +14715,9 @@ msgstr "Cuenta de Cancelación"
msgid "Write-off for {0}"
msgstr "Cancelación para {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Baja de inventario descartado o devuelto a través de rechazos de inspección y disposiciones de NCR"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Reducir el valor de un activo a lo largo de su vida útil — un lote mensual que crea, revisa como borrador y luego contabiliza."
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 815e896eea..81cf979f3a 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} de {1} completados"
msgid "{0} Scrapped"
msgstr "{0} Descartados"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} unidad(es) aprobada(s) se completará(n)."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} fallo(s) muestreado(s) registrado(s) y NO serán completado(s) — resuélvalo(s) desde el menú de acciones."
+
msgid "About"
msgstr "Acerca de"
+msgid "Accept"
+msgstr "Aceptar"
+
+msgid "Accept Lot"
+msgstr "Aceptar lote"
+
+msgid "Accept lot?"
+msgstr "¿Aceptar lote?"
+
msgid "Account Settings"
msgstr "Configuración de cuenta"
@@ -66,12 +81,27 @@ msgstr "Añade una impresora en la configuración de impresión para imprimir et
msgid "Add Inventory"
msgstr "Agregar inventario"
+msgid "Add Sample"
+msgstr "Agregar muestra"
+
msgid "Add Spare Part"
msgstr "Agregar repuesto"
msgid "All"
msgstr "Todos"
+msgid "All rework"
+msgstr "Todo reproceso"
+
+msgid "All scrap"
+msgstr "Todo chatarra"
+
+msgid "Allocate failed units"
+msgstr "Asignar unidades fallidas"
+
+msgid "Allocate units"
+msgstr "Asignar unidades"
+
msgid "Are you sure you want to delete this step?"
msgstr "¿Está seguro de que desea eliminar este paso?"
@@ -165,6 +195,12 @@ msgstr "Registrar salida"
msgid "Clocked in since {0}"
msgstr "Registrado desde {0}"
+msgid "Close"
+msgstr "Cerrar"
+
+msgid "Collapse features table"
+msgstr "Contraer tabla de características"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Completar"
msgid "Complete All"
msgstr "Completar todo"
+msgid "Complete passed"
+msgstr "Completar aprobados"
+
msgid "Completed"
msgstr "Completado"
@@ -281,6 +320,9 @@ msgstr "Borrador"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Arrastre y suelte un archivo aquí, o haga clic para seleccionar un archivo"
+msgid "Drag to resize drawing and features"
+msgstr "Arrastra para redimensionar el dibujo y las características"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Se canceló el arrastre de {0}."
@@ -325,6 +367,12 @@ msgstr "Error"
msgid "Estimated"
msgstr "Estimado"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Cada unidad tiene un veredicto: {passes} aprobadas y {fails} rechazadas. El lote se cierra con cada unidad dirigida a su propio resultado."
+
+msgid "Expand features table"
+msgstr "Expandir tabla de características"
+
msgid "Expired"
msgstr "Vencido"
@@ -337,6 +385,12 @@ msgstr "Vence {date}"
msgid "Expiring first"
msgstr "Vencimiento próximo"
+msgid "Failed"
+msgstr "Fallido"
+
+msgid "Failed features"
+msgstr "Características fallidas"
+
msgid "Failed to complete inventory adjustment"
msgstr "Error al completar el ajuste de inventario"
@@ -349,6 +403,12 @@ msgstr "Error al obtener las operaciones activas"
msgid "Failed to fetch storageUnits"
msgstr "Error al obtener unidades de almacenamiento"
+msgid "Failed to save measurement"
+msgstr "Error al guardar la medición"
+
+msgid "Failed to save result"
+msgstr "Error al guardar el resultado"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Error al subir el archivo: {0}"
@@ -356,6 +416,12 @@ msgstr "Error al subir el archivo: {0}"
msgid "Failed to upload image"
msgstr "Error al subir la imagen"
+msgid "Feature"
+msgstr "Característica"
+
+msgid "Features"
+msgstr "Características"
+
msgid "File size exceeds 10MB limit"
msgstr "El tamaño del archivo excede el límite de 10MB"
@@ -405,6 +471,12 @@ msgstr "Imperial"
msgid "In Progress"
msgstr "En progreso"
+msgid "Inspect Item"
+msgstr "Inspeccionar artículo"
+
+msgid "inspected"
+msgstr "inspeccionado"
+
msgid "Insufficient quantity"
msgstr "Cantidad insuficiente"
@@ -498,6 +570,9 @@ msgstr "Registrar desperdicio para {0}"
msgid "Login"
msgstr "Iniciar sesión"
+msgid "Lot"
+msgstr "Lote"
+
msgid "Machine"
msgstr "Máquina"
@@ -531,6 +606,9 @@ msgstr "Métrico"
msgid "Model"
msgstr "Modelo"
+msgid "More actions"
+msgstr "Más acciones"
+
msgid "More Actions"
msgstr "Más acciones"
@@ -595,6 +673,9 @@ msgstr "Sin archivos"
msgid "No Impact"
msgstr "Sin impacto"
+msgid "No issue types configured"
+msgstr "No hay tipos de problema configurados"
+
msgid "No maintenance scheduled for today"
msgstr "No hay mantenimiento programado para hoy"
@@ -607,6 +688,9 @@ msgstr "Sin materiales"
msgid "No open jobs"
msgstr "Sin trabajos abiertos"
+msgid "No open units to allocate"
+msgstr "No hay unidades abiertas para asignar"
+
msgid "No operators"
msgstr "Sin operadores"
@@ -625,6 +709,9 @@ msgstr "Sin impresora configurada"
msgid "No recent operations"
msgstr "No hay operaciones recientes"
+msgid "No remaining entities to inspect."
+msgstr "No hay entidades restantes para inspeccionar."
+
msgid "No results"
msgstr "Sin resultados"
@@ -634,6 +721,9 @@ msgstr "No existen resultados"
msgid "No results found"
msgstr "No se encontraron resultados"
+msgid "No samples required."
+msgstr "No se requieren muestras."
+
msgid "No scheduled time"
msgstr "Sin tiempo programado"
@@ -683,6 +773,9 @@ msgstr "Ups. No debería ver esta página. Eventualmente será una página de in
msgid "Open"
msgstr "Abierto"
+msgid "Open an NCR for MRB disposition"
+msgstr "Abrir un NCR para la disposición de MRB"
+
msgid "Open Jobs"
msgstr "Trabajos Abiertos"
@@ -698,12 +791,21 @@ msgstr "Realizado por operador"
msgid "Optional"
msgstr "Opcional"
+msgid "Overall result"
+msgstr "Resultado general"
+
msgid "Parameters"
msgstr "Parámetros"
msgid "Part"
msgstr "Pieza"
+msgid "Partial"
+msgstr "Parcial"
+
+msgid "Partial Disposition"
+msgstr "Disposición Parcial"
+
msgid "Passed Inspection"
msgstr "Inspección aprobada"
@@ -749,9 +851,6 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventivo"
-msgid "Previous"
-msgstr "Anterior"
-
msgid "Print"
msgstr "Imprimir"
@@ -801,6 +900,18 @@ msgstr "Registrar"
msgid "Record {0}"
msgstr "Registro {0}"
+msgid "Record only"
+msgstr "Solo registrar"
+
+msgid "Record Partial"
+msgstr "Registrar Parcial"
+
+msgid "Reject"
+msgstr "Rechazar"
+
+msgid "Reject Lot"
+msgstr "Rechazar lote"
+
msgid "Remove"
msgstr "Eliminar"
@@ -813,12 +924,18 @@ msgstr "Eliminar inventario"
msgid "Remove part"
msgstr "Eliminar pieza"
+msgid "Result"
+msgstr "Resultado"
+
msgid "Rework"
msgstr "Reelaboración"
msgid "Rework created successfully"
msgstr "Rework creado exitosamente"
+msgid "Rework quantity"
+msgstr "Cantidad de reproceso"
+
msgid "Sales Order"
msgstr "Orden de venta"
@@ -828,21 +945,33 @@ msgstr "Guardar"
msgid "Scan"
msgstr "Escanear"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Escanee una entidad rastreada para agregar la primera columna de muestra."
+
msgid "Scan or enter serial number"
msgstr "Escanee o ingrese el número de serie"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Escanee o ingrese ID de entidad rastreada, serie o lote"
+
msgid "Scan or enter tracking number"
msgstr "Escanear o ingresar número de seguimiento"
msgid "Scan or search serial number..."
msgstr "Escanear o buscar número de serie..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Escanee o seleccione una entidad rastreada de este lote para agregarla como columna de muestra, luego registre su resultado en la cuadrícula."
+
msgid "Schedule"
msgstr "Programación"
msgid "Scrap"
msgstr "Descartar"
+msgid "Scrap quantity"
+msgstr "Cantidad de desecho"
+
msgid "Scrap Reason"
msgstr "Motivo de desperdicio"
@@ -876,6 +1005,9 @@ msgstr "Seleccione una cantidad de desperdicio y un motivo"
msgid "Select a serial number to continue with this operation"
msgstr "Seleccione un número de serie para continuar con esta operación"
+msgid "Select an issue type"
+msgstr "Seleccione un tipo de problema"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Seleccione un artículo y especifique la cantidad a emitir"
@@ -899,6 +1031,9 @@ msgstr "Seleccionar número de serie"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Selecciona la operación a la que volver. Todas las operaciones desde ese punto hasta la operación actual se repetirán."
+msgid "Selected"
+msgstr "Seleccionado"
+
msgid "Send"
msgstr "Enviar"
@@ -978,6 +1113,10 @@ msgstr "Usuario de estación"
msgid "Station: {stationName}"
msgstr "Estación: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "La aceptación estadística falló, por lo que el lote completo de {0} se considera no conforme (ISO 9001:2015 §8.7) — {passes} aprobación(es) muestreada(s) y {fails} fallo(s). Dirija las unidades a continuación a desecho o reproceso, o registre solo el veredicto."
+
msgid "Status"
msgstr "Estado"
@@ -1015,6 +1154,12 @@ msgstr "Etiqueta"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "La cantidad completada para esta operación es menor que la cantidad requerida de {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "El lote se marcará como Aprobado y {remaining} unidad(es) restante(s) se completarán en esta operación."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "El lote seguirá siendo disposicionado, pero no se puede crear un NCR hasta que se configure al menos un tipo de problema."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Hay materiales con seguimiento de serie o lote en la lista de materiales que no se han emitido completamente. Completar sin emitir puede generar registros de trazabilidad incorrectos."
@@ -1048,6 +1193,9 @@ msgstr "Tiempo total: {0}"
msgid "Total: {0}"
msgstr "Total: {0}"
+msgid "Tracked Entity"
+msgstr "Entidad rastreada"
+
msgid "Tracking"
msgstr "Seguimiento"
@@ -1070,6 +1218,9 @@ msgstr "Descartar {0}"
msgid "Unsaved changes"
msgstr "Cambios no guardados"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Hasta {maxAllocatable} unidad(es) pueden asignarse; el resto se registra sin una publicación."
+
msgid "Update"
msgstr "Actualizar"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 2a7242adb1..10f0eb61df 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -725,6 +725,9 @@ msgstr "Ajouter un paramètre"
msgid "Add Partner"
msgstr "Ajouter un partenaire"
+msgid "Add parts"
+msgstr "Ajouter des pièces"
+
msgid "Add Permissions"
msgstr "Ajouter des autorisations"
@@ -749,6 +752,9 @@ msgstr "Ajouter un risque"
msgid "Add rule"
msgstr "Ajouter une règle"
+msgid "Add Sample"
+msgstr "Ajouter un échantillon"
+
msgid "Add Selector"
msgstr "Ajouter un sélecteur"
@@ -764,6 +770,9 @@ msgstr "Ajouter une pièce de rechange"
msgid "Add Step"
msgstr "Ajouter une étape"
+msgid "Add steps to preview the operator view."
+msgstr "Ajouter des étapes pour prévisualiser la vue de l'opérateur."
+
msgid "Add Supplier"
msgstr "Ajouter un fournisseur"
@@ -776,6 +785,9 @@ msgstr "Ajouter une feuille de temps"
msgid "Add to stock for future use"
msgstr "Ajouter au stock pour utilisation future"
+msgid "Add tools"
+msgstr "Ajouter des outils"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Ajoutez votre premier {0}"
@@ -1041,6 +1053,9 @@ msgstr "S'applique à tous"
msgid "Applies to all work centers"
msgstr "S'applique à tous les centres de travail"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "S'applique aux fonctionnalités sans leur propre règle, et au lot lorsque ce plan détermine une inspection."
+
msgid "Apply"
msgstr "Appliquer"
@@ -1401,8 +1416,11 @@ msgstr "Êtes-vous sûr de vouloir supprimer cet ordre de modification ?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Êtes-vous sûr de vouloir supprimer ce jauge ?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Êtes-vous sûr de vouloir supprimer ce document d'inspection ?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Êtes-vous sûr de vouloir supprimer ce plan d'inspection ?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir supprimer ce plan d'inspection ? Cette action ne peut pas être annulée."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Êtes-vous sûr de vouloir supprimer ce flux de travail de problème ?"
@@ -1534,6 +1552,9 @@ msgstr "Demandez à un administrador disposant de la permission {0} d'ajouter le
msgid "Assemblies"
msgstr "Assemblages"
+msgid "Assembly Instruction"
+msgstr "Instruction d'assemblage"
+
msgid "Assembly Instructions"
msgstr "Instructions d'assemblage"
@@ -1678,6 +1699,12 @@ msgstr "Code QR généré automatiquement"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Formats de numérotation automatique pour les commandes, les travaux, les pièces, et plus"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Démarrage automatique du chronomètre de l'opérateur lors de l'ouverture d'une opération en MES pour que les journaux de temps soient capturés dès le départ."
+
+msgid "Auto-start timer on open"
+msgstr "Démarrage automatique du chronomètre à l'ouverture"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Suggérer automatiquement les achats en fonction de la demande et des points de réapprovisionnement"
@@ -1741,6 +1768,9 @@ msgstr "Équilibré"
msgid "Balloon"
msgstr "Ballon"
+msgid "Ballooned drawings with inspection features."
+msgstr "Dessins avec annotations et caractéristiques d'inspection."
+
msgid "Bank - Cash"
msgstr "Banque - Espèces"
@@ -2094,6 +2124,9 @@ msgstr "Impossible de télécharger — l'interaction fournisseur n'a pas encore
msgid "Cannot upload to parts bucket without item ID"
msgstr "Impossible de télécharger vers le compartiment des pièces sans ID d'article"
+msgid "Caption"
+msgstr "Légende"
+
msgid "Carbon"
msgstr "Carbone"
@@ -2193,6 +2226,12 @@ msgstr "Champions"
msgid "Change"
msgstr "Modifier"
+msgid "Change Document"
+msgstr "Modifier le document"
+
+msgid "Change Inspection Plan"
+msgstr "Modifier le plan d'inspection"
+
msgid "Change order"
msgstr "Ordre de modification"
@@ -2283,6 +2322,9 @@ msgstr "Classe"
msgid "Class (inherited)"
msgstr "Classe (héritée)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Classe une opération de routage : les opérations de Processus, Assemblage et Inspection s'exécutent sur votre propre atelier en MES — Assemblage obtient la vue d'assemblage guidée et Inspection un contrôle de qualité — tandis qu'une opération Traitement extérieur est sous-traitée à un fournisseur et crée une commande d'achat ; le processus porte le même type et l'applique par défaut sur les nouvelles opérations."
+
msgid "Clean and approve the migrated data"
msgstr "Nettoyer et approuver les données migrées"
@@ -2747,6 +2789,9 @@ msgstr "Convertir les suggestions MRP en commandes d'achat et en travaux."
msgid "Convert to Quote"
msgstr "Convertir en devis"
+msgid "Converting…"
+msgstr "Conversion en cours…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Convertit l'unité d'achat d'un fournisseur en votre unité d'inventaire sur une ligne de commande, reçu ou facture — acheter en cartons de 12, stocker en unités."
@@ -3055,9 +3100,6 @@ msgstr "Créer un ordre de modification"
msgid "Create Issue"
msgstr "Créer un problème"
-msgid "Create Issue from Inspection"
-msgstr "Créer un problème à partir de l'inspection"
-
msgid "Create Jobs"
msgstr "Créer des tâches"
@@ -3699,6 +3741,9 @@ msgstr "Priorité par défaut"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Compte GL de revenu par défaut crédité lors de l'enregistrement d'une facture de vente."
+msgid "Default Sampling"
+msgstr "Échantillonnage par défaut"
+
msgid "Default shelf-life duration (days)"
msgstr "Durée de vie par défaut (jours)"
@@ -3741,9 +3786,6 @@ msgstr "Définissez d'abord une opération de fabrication."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Définir les nomenclatures multi-niveaux et la gamme de fabrication (méthodes de fabrication)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Définit le nombre d'entités suivies inspectées par lot et le nombre de défaillances tolérées avant le rejet du lot."
-
msgid "Delete"
msgstr "Supprimer"
@@ -3837,6 +3879,9 @@ msgstr "Supprimer le groupe"
msgid "Delete Holiday"
msgstr "Supprimer le jour férié"
+msgid "Delete Inspection Plan"
+msgstr "Supprimer le plan d'inspection"
+
msgid "Delete Issue"
msgstr "Supprimer le problème"
@@ -4329,6 +4374,9 @@ msgstr "Glisser pour réorganiser"
msgid "Drag to resize diagram and features"
msgstr "Faites glisser pour redimensionner le diagramme et les fonctionnalités"
+msgid "Drag to resize drawing and features"
+msgstr "Faites glisser pour redimensionner le dessin et les fonctionnalités"
+
msgid "Drag to zoom"
msgstr "Glisser pour zoomer"
@@ -4549,8 +4597,8 @@ msgstr "Modifier le groupe"
msgid "Edit Holiday"
msgstr "Modifier le congé"
-msgid "Edit Inspection Document"
-msgstr "Modifier le document d'inspection"
+msgid "Edit Inspection Plan"
+msgstr "Éditer le plan d'inspection"
msgid "Edit Item Group"
msgstr "Modifier le groupe d'articles"
@@ -5236,6 +5284,9 @@ msgstr "Balises supplémentaires pour segmenter vos rapports GL"
msgid "Fail"
msgstr "Échouer"
+msgid "Failed features"
+msgstr "Caractéristiques échouées"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (premier à expirer, premier à sortir)"
@@ -5479,6 +5530,21 @@ msgstr "Échec de l'enregistrement de la règle de configuration"
msgid "Failed to save diagram"
msgstr "Impossible d'enregistrer le diagramme"
+msgid "Failed to save measurement"
+msgstr "Impossible d'enregistrer la mesure"
+
+msgid "Failed to save parts"
+msgstr "Échec de l'enregistrement des pièces"
+
+msgid "Failed to save result"
+msgstr "Impossible d'enregistrer le résultat"
+
+msgid "Failed to save slides"
+msgstr "Échec de l'enregistrement des diapositives"
+
+msgid "Failed to save tools"
+msgstr "Échec de l'enregistrement des outils"
+
msgid "Failed to update batch property"
msgstr "Échec de la mise à jour de la propriété de lot"
@@ -6400,15 +6466,6 @@ msgstr "Les actions inactives n'apparaîtront pas dans les listes de sélection"
msgid "Inbound inspection"
msgstr "Inspection entrante"
-msgid "Inbound Inspection"
-msgstr "Inspection entrante"
-
-msgid "Inbound Inspections"
-msgstr "Inspections entrantes"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Inspections entrantes : Exiger un inspecteur différent"
-
msgid "Inbox"
msgstr "Boîte de réception"
@@ -6454,6 +6511,12 @@ msgstr "Matériaux Indirects et Services (par défaut)"
msgid "Infrastructure"
msgstr "Infrastructure"
+msgid "Inherit"
+msgstr "Hériter"
+
+msgid "Inherit document default"
+msgstr "Hériter du paramètre par défaut du document"
+
msgid "Inherit From Materials"
msgstr "Hériter des matériaux"
@@ -6490,32 +6553,35 @@ msgstr "Inspecter les Premiers N"
msgid "Inspect Item"
msgstr "Inspecter l'article"
-msgid "Inspect Next Item"
-msgstr "Inspecter l'article suivant"
-
msgid "Inspection"
msgstr "Inspection"
-msgid "Inspection Document"
-msgstr "Document d'inspection"
-
-msgid "Inspection Documents"
-msgstr "Documents d'inspection"
-
msgid "Inspection Level"
msgstr "Niveau d'inspection"
+msgid "Inspection Plan"
+msgstr "Plan d'inspection"
+
+msgid "Inspection Plan Assignments"
+msgstr "Attributions du plan d'inspection"
+
+msgid "Inspection Plans"
+msgstr "Plans d'inspection"
+
msgid "Inspection Status"
msgstr "Statut d'inspection"
+msgid "Inspections"
+msgstr "Inspections"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspections, non-conformité et CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspections, Non-conformité, CAPA"
-msgid "Inspector"
-msgstr "Inspecteur"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspections : Exiger un inspecteur différent"
msgid "Install"
msgstr "Installer"
@@ -7439,15 +7505,9 @@ msgstr "Marquer comme terminé"
msgid "Mark Light Mode"
msgstr "Marque Mode Clair"
-msgid "Mark lot as partial?"
-msgstr "Marquer le lot comme partiel ?"
-
msgid "Mark not done"
msgstr "Marquer comme non fait"
-msgid "Mark Partial"
-msgstr "Marquer comme partiel"
-
msgid "Mark scope as agreed"
msgstr "Marquer le périmètre comme convenu"
@@ -7960,8 +8020,8 @@ msgstr "Nouveau Congé"
msgid "New IC Transaction"
msgstr "Nouvelle Transaction IC"
-msgid "New Inspection Document"
-msgstr "Nouveau Document d'Inspection"
+msgid "New Inspection Plan"
+msgstr "Nouveau plan d'inspection"
msgid "New Inventory Count"
msgstr "Nouveau Décompte d'Inventaire"
@@ -8332,6 +8392,9 @@ msgstr "Aucun groupe assigné"
msgid "No image"
msgstr "Aucune image"
+msgid "No inspection plans"
+msgstr "Aucun plan d'inspection"
+
msgid "No issue types configured"
msgstr "Aucun type de problème configuré"
@@ -8392,6 +8455,9 @@ msgstr "Aucune source parent enregistrée pour le moment. Cliquez sur Recalculer
msgid "No part ID"
msgstr "Aucun ID de pièce"
+msgid "No parts"
+msgstr "Pas de pièces"
+
msgid "No payables"
msgstr "Aucun compte créditeur"
@@ -8428,6 +8494,9 @@ msgstr "Aucune raison de devis"
msgid "No receivables"
msgstr "Aucune créance"
+msgid "No reference image"
+msgstr "Pas d'image de référence"
+
msgid "No remaining entities to inspect."
msgstr "Aucune entité restante à inspecter."
@@ -8443,9 +8512,6 @@ msgstr "Pas de lignes ici."
msgid "No rules assigned"
msgstr "Aucune règle assignée"
-msgid "No samples inspected yet."
-msgstr "Aucun échantillon inspecté pour le moment."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Pas de chiffre unique et fiable pour l'inventaire ou le statut du travail"
@@ -8464,6 +8530,12 @@ msgstr "Aucun fournisseur pour le moment"
msgid "No time entries for this week"
msgstr "Aucune entrée de temps pour cette semaine"
+msgid "No tools"
+msgstr "Pas d'outils"
+
+msgid "No tools for this step"
+msgstr "Pas d'outils pour cette étape"
+
msgid "No transactions in this period"
msgstr "Aucune transaction au cours de cette période"
@@ -8773,6 +8845,9 @@ msgstr "Opération"
msgid "Operation Order"
msgstr "Ordre d'opération"
+msgid "Operation Timer"
+msgstr "Chronomètre d'opération"
+
msgid "Operation Type"
msgstr "Type d'opération"
@@ -8900,6 +8975,9 @@ msgstr "Écart de Frais Généraux"
msgid "Over-applied by"
msgstr "Appliqué en excédent de"
+msgid "Overall result"
+msgstr "Résultat global"
+
msgid "Overdue"
msgstr "En retard"
@@ -9027,9 +9105,6 @@ msgstr "Numéro de pièce"
msgid "Part Supersession"
msgstr "Remplacement de pièce"
-msgid "Partial"
-msgstr "Partiel"
-
msgid "Partner"
msgstr "Partenaire"
@@ -9246,6 +9321,9 @@ msgstr "Pièces/Heure"
msgid "Pieces/Minute"
msgstr "Pièces/Minute"
+msgid "Pin"
+msgstr "Épingler"
+
msgid "Pinned"
msgstr "Épinglé"
@@ -9447,6 +9525,9 @@ msgstr "Date précédente"
msgid "Previous page"
msgstr "Page précédente"
+msgid "Previous step"
+msgstr "Étape précédente"
+
msgid "Price break actions"
msgstr "Actions de rupture de prix"
@@ -10138,9 +10219,6 @@ msgstr "Enregistrement supprimé"
msgid "Record inspections tied to a part and a job"
msgstr "Enregistrer les inspections liées à une pièce et à un travail"
-msgid "Record the inspection result for this sample."
-msgstr "Enregistrez le résultat de l'inspection pour cet échantillon."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Enregistré lors d'un étalonnage indiquant que la jauge nécessite une réparation avant que ses lectures ne puissent être fiables."
@@ -10265,9 +10343,6 @@ msgstr "Supprimer {label}"
msgid "Remove condition"
msgstr "Supprimer la condition"
-msgid "Remove feature"
-msgstr "Supprimer la fonctionnalité"
-
msgid "Remove filter"
msgstr "Supprimer le filtre"
@@ -10286,12 +10361,21 @@ msgstr "Supprimer la commande"
msgid "Remove pair"
msgstr "Supprimer la paire"
+msgid "Remove part"
+msgstr "Supprimer la pièce"
+
+msgid "Remove slide"
+msgstr "Supprimer la diapositive"
+
msgid "Remove sort by column"
msgstr "Supprimer le tri par colonne"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Supprimez ce type de stockage de toutes les unités de stockage qui le référencent et supprimez-le. Cette action ne peut pas être annulée."
+msgid "Remove tool"
+msgstr "Supprimer l'outil"
+
msgid "Removed"
msgstr "Supprimé"
@@ -10421,9 +10505,6 @@ msgstr "Nécessite une action"
msgid "Requires Adjustment"
msgstr "Nécessite un ajustement"
-msgid "Requires Inspection"
-msgstr "Nécessite une inspection"
-
msgid "Requires Repair"
msgstr "Nécessite une réparation"
@@ -10444,7 +10525,7 @@ msgstr "Réinitialiser le PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Réinitialiser le PIN pour {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Réinitialiser la vue"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Identique à la comptabilité"
msgid "Sample"
msgstr "Échantillon"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Échantillon {0}"
-
msgid "Sample Size"
msgstr "Taille de l'échantillon"
-msgid "Sampling Plan"
-msgstr "Plan d'échantillonnage"
+msgid "Sampling"
+msgstr "Échantillonnage"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Échantillonnage — Fonctionnalité {featureLabel}"
msgid "Sampling Standard"
msgstr "Norme d'échantillonnage"
@@ -10852,8 +10932,8 @@ msgstr "Scannez ou entrez le numéro de suivi"
msgid "Scan or search..."
msgstr "Scannez ou recherchez..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Scannez ou sélectionnez une entité suivie de ce lot et enregistrez le résultat de l'inspection."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scannez ou sélectionnez une entité suivie de ce lot pour l'ajouter comme colonne d'échantillon, puis enregistrez son résultat dans la grille."
msgid "Scan the tracking ID for this line"
msgstr "Scannez l'ID de suivi pour cette ligne"
@@ -10900,6 +10980,9 @@ msgstr "Portées"
msgid "Scrap"
msgstr "Déchet"
+msgid "Scrap / Cost of Quality"
+msgstr "Rebut / Coût de la qualité"
+
msgid "Scrap Percent"
msgstr "Pourcentage de rebut"
@@ -10960,6 +11043,9 @@ msgstr "Rechercher un travail"
msgid "Search operators..."
msgstr "Rechercher des opérateurs..."
+msgid "Search parts..."
+msgstr "Rechercher des pièces..."
+
msgid "Search processes..."
msgstr "Rechercher des processus..."
@@ -10969,6 +11055,9 @@ msgstr "Rechercher les articles associés..."
msgid "Search suppliers..."
msgstr "Rechercher des fournisseurs..."
+msgid "Search tools..."
+msgstr "Rechercher des outils..."
+
msgid "Search..."
msgstr "Rechercher..."
@@ -10990,6 +11079,9 @@ msgstr "Sélectionner un assigné"
msgid "Select a default approver"
msgstr "Sélectionner un approbateur par défaut"
+msgid "Select a document"
+msgstr "Sélectionner un document"
+
msgid "Select a new owner"
msgstr "Sélectionner un nouveau propriétaire"
@@ -11647,6 +11739,9 @@ msgstr "Consommation de pièces de rechange"
msgid "Spare Part Cost"
msgstr "Coût des pièces de rechange"
+msgid "Spec"
+msgstr "Spec"
+
msgid "Specific Customer"
msgstr "Client spécifique"
@@ -11777,6 +11872,12 @@ msgstr "étapes"
msgid "Steps"
msgstr "Étapes"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Les étapes sont héritées de l'instruction d'assemblage."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Les étapes sont héritées du plan d'inspection."
+
msgid "Stock Transfer ID"
msgstr "ID de transfert de stock"
@@ -12470,8 +12571,8 @@ msgstr "Le flux commercial de bout en bout allant de la citation d'un client à
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Le point de terminaison qui reçoit une requête POST avec les données mises à jour lorsque la table est mise à jour"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Le dessin technique auquel ce document d'inspection est lié; les inspections enregistrées par rapport à cette référence de pièce font référence à ce dessin."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Le dessin d'ingénierie auquel ce plan d'inspection est lié ; les inspections enregistrées pour cette pièce font référence à ce dessin."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "Le pourcentage attendu de la production de cet article perdu pendant la fabrication; la planification multiplie la demande par 1 / (1 − ferraille) pour compenser."
@@ -12620,15 +12721,15 @@ msgstr "Les logos affichés sur vos documents imprimés et envoyés par e-mail"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "L'identifiant de lot pour ce stock; une ligne par lot, la quantité est celle en main pour ce lot."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Le lot reste ouvert pour que vous puissiez continuer l'inspection et disposer plus tard. Les résultats d'échantillonnage sont conservés."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Le lot sera marqué comme Accepté. {fails} défaut(s) échantillonné(s) sont enregistrés pour vos dossiers."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Le lot sera toujours rejeté, mais un NCR ne peut pas être créé tant qu'au moins un type de problème n'est pas configuré."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "Le plan d'échantillonnage par caractéristique du lot sera re-résolu à partir du document sélectionné."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Le montant minimum que ce fournisseur facturera pour ce processus, quel que soit la quantité; les travaux en dessous du volume de seuil de rentabilité coûtent toujours au moins ce montant."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "La séquence ordonnée des opérations qu'une tâche exécute, copiée de la liste des processus de la méthode."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Le fichier de modèle original n'est plus disponible"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Le document de comptabilisation sortante qui sort les marchandises du stock vers un client, en comptabilisant le COGS en cours de route."
@@ -12719,8 +12820,8 @@ msgstr "Les personnes du côté Carbon qui géreront votre implémentation et co
msgid "The people on your team and their access to Carbon"
msgstr "Les personnes de votre équipe et leur accès à Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Le compteur par entreprise derrière le numéro lisible d'un type de document, assemblant {prefix}{next+step, zero-padded}{suffix} et progressant à chaque création de document."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Le compteur par entreprise qui génère le numéro lisible d'un type de document, en assemblant le préfixe, la valeur suivante avec zéro initial, et le suffixe, et qui s'incrémente à la création de chaque document."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "Le résultat par article enregistré sur le matériel affecté d'une non-conformité — En attente, Retour au fournisseur, Retravail, Rebut ou Utiliser en l'état — décidé pour chaque lot ou numéro de série affecté individuellement."
@@ -13011,6 +13112,9 @@ msgstr "Ces informations seront utilisées dans les en-têtes de document"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Ces informations seront visibles par tous les utilisateurs, soyez donc prudent dans ce que vous partagez."
+msgid "this inspection plan"
+msgstr "ce plan d'inspection"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Ceci est un article acheté — il n'a pas de BoM/BoP ; seuls ses attributs et documents peuvent changer."
@@ -13459,9 +13563,6 @@ msgstr "Type :"
msgid "Types"
msgstr "Types"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Les entités non échantillonnées resteront En attente pour que vous puissiez continuer l'inspection et disposer ultérieurement. Les résultats échantillonnés sont conservés."
-
msgid "Unapplied"
msgstr "Non appliqué"
@@ -14311,6 +14412,9 @@ msgstr "Quand il est activé, les attributs de cette catégorie s'affichent dans
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Quand il est activé, les employés peuvent modifier la valeur de cet attribut dans leur propre profil ; sinon, seuls les administrateurs peuvent le faire."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Lorsqu'il est activé, l'ouverture d'une opération démarre automatiquement son chronomètre."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Quand il est activé, les règles de tarification (remises en volume, promotions) s'appliquent toujours en plus de ce remplacement ; quand il est désactivé, ce remplacement est le prix final."
@@ -14437,8 +14541,8 @@ msgstr "Si le chronomètre démarre lorsque le processus choisi commence ou lors
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Si ce lot/numéro de série réussit l'inspection (Pass) ou échoue (Fail) ; un Fail empêche la réception du stock dans l'inventaire disponible."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Si ce processus s'exécute sur des postes de travail internes (Inside), des fournisseurs externes (Outside) ou les deux (Both) ; affiche différents champs en aval et modifie la manière dont la planification achemine ce processus."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Que ce processus s'exécute sur des centres de travail internes (Processus, Assemblage ou Inspection) ou chez des fournisseurs externes (Traitement extérieur) ; révèle différents champs en aval, change le fonctionnement des itinéraires de planification pour ce processus et définit par défaut le type d'opération sur les nouvelles opérations."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Si ce travail bloque la production (Baisse), la dégrade (Impact), se situe dans une fenêtre de temps d'arrêt planifiée (Planifié) ou n'a aucun impact de production (Pas d'Impact) ; informe la planification et la communication d'arrêt orientée client."
@@ -14446,6 +14550,9 @@ msgstr "Si ce travail bloque la production (Baisse), la dégrade (Impact), se si
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Si les autorisations sélectionnées sont Ajoutées au-dessus de ce que chaque utilisateur possède déjà, ou Mises à Jour en remplaçant l'ensemble des autorisations de chaque utilisateur par la sélection ci-dessous."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Quel document pilote chaque flux d'inspection pour cet article."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Quel événement de fabrication démarre l'horloge de durée de conservation — par exemple, remplissage, scellement ou CQ final."
@@ -14608,6 +14715,9 @@ msgstr "Compte de Radiation"
msgid "Write-off for {0}"
msgstr "Radiation pour {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Radiation du stock mis au rebut ou retourné via les rejets d'inspection et les dispositions des rapports de non-conformité"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Réduire la valeur d'un actif au cours de sa vie utile — un lot mensuel que vous créez, vérifiez en tant que brouillon, puis comptabilisez."
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index d5f35ce147..1448a57469 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} sur {1} terminé(s)"
msgid "{0} Scrapped"
msgstr "{0} Rebuté(s)"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} unité(s) acceptée(s) sera/seront complétée(s)."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} défaut(s) échantillonné(s) enregistré(s) et ne seront PAS complété(s) — résolvez-les à partir du menu des actions."
+
msgid "About"
msgstr "À propos"
+msgid "Accept"
+msgstr "Accepter"
+
+msgid "Accept Lot"
+msgstr "Accepter lot"
+
+msgid "Accept lot?"
+msgstr "Accepter lot ?"
+
msgid "Account Settings"
msgstr "Paramètres du compte"
@@ -66,12 +81,27 @@ msgstr "Ajoutez une imprimante dans les paramètres d'impression pour imprimer l
msgid "Add Inventory"
msgstr "Ajouter au stock"
+msgid "Add Sample"
+msgstr "Ajouter échantillon"
+
msgid "Add Spare Part"
msgstr "Ajouter une pièce de rechange"
msgid "All"
msgstr "Tout"
+msgid "All rework"
+msgstr "Tous les retouches"
+
+msgid "All scrap"
+msgstr "Tout rebut"
+
+msgid "Allocate failed units"
+msgstr "Allouer les unités défaillantes"
+
+msgid "Allocate units"
+msgstr "Allouer les unités"
+
msgid "Are you sure you want to delete this step?"
msgstr "Êtes-vous sûr de vouloir supprimer cette étape ?"
@@ -165,6 +195,12 @@ msgstr "Pointer la sortie"
msgid "Clocked in since {0}"
msgstr "Pointé depuis {0}"
+msgid "Close"
+msgstr "Fermer"
+
+msgid "Collapse features table"
+msgstr "Réduire le tableau des caractéristiques"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Terminé"
msgid "Complete All"
msgstr "Tout compléter"
+msgid "Complete passed"
+msgstr "Terminer les réussis"
+
msgid "Completed"
msgstr "Terminé"
@@ -281,6 +320,9 @@ msgstr "Brouillon"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Glissez-déposez un fichier ici, ou cliquez pour sélectionner un fichier"
+msgid "Drag to resize drawing and features"
+msgstr "Faites glisser pour redimensionner le dessin et les caractéristiques"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Déplacement de {0} annulé."
@@ -325,6 +367,12 @@ msgstr "Erreur"
msgid "Estimated"
msgstr "Estimé"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Chaque unité a un verdict : {passes} réussie(s) et {fails} échouée(s). Le lot se ferme avec chaque unité acheminée vers son propre résultat."
+
+msgid "Expand features table"
+msgstr "Développer le tableau des caractéristiques"
+
msgid "Expired"
msgstr "Expiré"
@@ -337,6 +385,12 @@ msgstr "Expire le {date}"
msgid "Expiring first"
msgstr "Expiration en premier"
+msgid "Failed"
+msgstr "Échoué"
+
+msgid "Failed features"
+msgstr "Fonctionnalités échouées"
+
msgid "Failed to complete inventory adjustment"
msgstr "Échec de l'ajustement de stock"
@@ -349,6 +403,12 @@ msgstr "Échec de la récupération des opérations actives"
msgid "Failed to fetch storageUnits"
msgstr "Échec de la récupération des unités de stockage"
+msgid "Failed to save measurement"
+msgstr "Échec de l'enregistrement de la mesure"
+
+msgid "Failed to save result"
+msgstr "Échec de l'enregistrement du résultat"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Échec du téléversement du fichier : {0}"
@@ -356,6 +416,12 @@ msgstr "Échec du téléversement du fichier : {0}"
msgid "Failed to upload image"
msgstr "Échec du téléversement de l'image"
+msgid "Feature"
+msgstr "Fonctionnalité"
+
+msgid "Features"
+msgstr "Caractéristiques"
+
msgid "File size exceeds 10MB limit"
msgstr "La taille du fichier dépasse la limite de 10 Mo"
@@ -405,6 +471,12 @@ msgstr "Impérial"
msgid "In Progress"
msgstr "En cours"
+msgid "Inspect Item"
+msgstr "Inspecter l'article"
+
+msgid "inspected"
+msgstr "inspecté"
+
msgid "Insufficient quantity"
msgstr "Quantité insuffisante"
@@ -498,6 +570,9 @@ msgstr "Enregistrer le rebut pour {0}"
msgid "Login"
msgstr "Connexion"
+msgid "Lot"
+msgstr "Lot"
+
msgid "Machine"
msgstr "Machine"
@@ -531,6 +606,9 @@ msgstr "Métrique"
msgid "Model"
msgstr "Modèle"
+msgid "More actions"
+msgstr "Plus d'actions"
+
msgid "More Actions"
msgstr "Plus d'actions"
@@ -595,6 +673,9 @@ msgstr "Aucun fichier"
msgid "No Impact"
msgstr "Aucun impact"
+msgid "No issue types configured"
+msgstr "Aucun type de problème configuré"
+
msgid "No maintenance scheduled for today"
msgstr "Aucune maintenance planifiée pour aujourd'hui"
@@ -607,6 +688,9 @@ msgstr "Aucun matériau"
msgid "No open jobs"
msgstr "Aucun travail ouvert"
+msgid "No open units to allocate"
+msgstr "Aucune unité ouverte à allouer"
+
msgid "No operators"
msgstr "Aucun opérateur"
@@ -625,6 +709,9 @@ msgstr "Aucune imprimante configurée"
msgid "No recent operations"
msgstr "Aucune opération récente"
+msgid "No remaining entities to inspect."
+msgstr "Aucune entité restante à inspecter."
+
msgid "No results"
msgstr "Aucun résultat"
@@ -634,6 +721,9 @@ msgstr "Aucun résultat trouvé"
msgid "No results found"
msgstr "Aucun résultat trouvé"
+msgid "No samples required."
+msgstr "Aucun échantillon requis."
+
msgid "No scheduled time"
msgstr "Aucun horaire planifié"
@@ -683,6 +773,9 @@ msgstr "Oups. Vous ne devriez pas voir cette page. Elle deviendra éventuellemen
msgid "Open"
msgstr "Ouvert"
+msgid "Open an NCR for MRB disposition"
+msgstr "Ouvrir un NCR pour la disposition MRB"
+
msgid "Open Jobs"
msgstr "Emplois ouverts"
@@ -698,12 +791,21 @@ msgstr "Effectué par l'opérateur"
msgid "Optional"
msgstr "Optionnel"
+msgid "Overall result"
+msgstr "Résultat global"
+
msgid "Parameters"
msgstr "Paramètres"
msgid "Part"
msgstr "Pièce"
+msgid "Partial"
+msgstr "Partiel"
+
+msgid "Partial Disposition"
+msgstr "Disposition partielle"
+
msgid "Passed Inspection"
msgstr "Inspection réussie"
@@ -749,9 +851,6 @@ msgstr "Précédent"
msgid "Preventive"
msgstr "Préventif"
-msgid "Previous"
-msgstr "Précédent"
-
msgid "Print"
msgstr "Imprimer"
@@ -801,6 +900,18 @@ msgstr "Enregistrer"
msgid "Record {0}"
msgstr "Enregistrement {0}"
+msgid "Record only"
+msgstr "Enregistrer uniquement"
+
+msgid "Record Partial"
+msgstr "Enregistrer partiellement"
+
+msgid "Reject"
+msgstr "Rejeter"
+
+msgid "Reject Lot"
+msgstr "Rejeter lot"
+
msgid "Remove"
msgstr "Retirer"
@@ -813,12 +924,18 @@ msgstr "Retirer du stock"
msgid "Remove part"
msgstr "Retirer la pièce"
+msgid "Result"
+msgstr "Résultat"
+
msgid "Rework"
msgstr "Retouche"
msgid "Rework created successfully"
msgstr "Rework créé avec succès"
+msgid "Rework quantity"
+msgstr "Quantité de retouche"
+
msgid "Sales Order"
msgstr "Commande client"
@@ -828,21 +945,33 @@ msgstr "Enregistrer"
msgid "Scan"
msgstr "Scanner"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Scannez une entité suivie pour ajouter la première colonne d'échantillon."
+
msgid "Scan or enter serial number"
msgstr "Scanner ou saisir le numéro de série"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Scannez ou entrez l'ID d'entité suivie, le numéro de série ou le lot"
+
msgid "Scan or enter tracking number"
msgstr "Scannez ou entrez le numéro de suivi"
msgid "Scan or search serial number..."
msgstr "Scannez ou recherchez un numéro de série..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scannez ou sélectionnez une entité suivie de ce lot pour l'ajouter en tant que colonne d'échantillon, puis enregistrez son résultat dans la grille."
+
msgid "Schedule"
msgstr "Planification"
msgid "Scrap"
msgstr "Rebut"
+msgid "Scrap quantity"
+msgstr "Quantité de rebut"
+
msgid "Scrap Reason"
msgstr "Motif de rebut"
@@ -876,6 +1005,9 @@ msgstr "Sélectionner une quantité de rebut et un motif"
msgid "Select a serial number to continue with this operation"
msgstr "Sélectionner un numéro de série pour continuer cette opération"
+msgid "Select an issue type"
+msgstr "Sélectionnez un type de problème"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Sélectionner un article et préciser la quantité à distribuer"
@@ -899,6 +1031,9 @@ msgstr "Sélectionner le numéro de série"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Sélectionnez l'opération à laquelle revenir. Toutes les opérations à partir de ce point jusqu'à l'opération actuelle seront refaites."
+msgid "Selected"
+msgstr "Sélectionné"
+
msgid "Send"
msgstr "Envoyer"
@@ -978,6 +1113,10 @@ msgstr "Utilisateur du poste"
msgid "Station: {stationName}"
msgstr "Poste : {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "L'acceptation statistique a échoué, de sorte que l'ensemble du lot de {0} est considéré comme non-conforme (ISO 9001:2015 §8.7) — {passes} passage(s) échantillonné(s) et {fails} défaillance(s). Acheminez les unités ci-dessous vers la rebut ou le retravail, ou enregistrez uniquement le verdict."
+
msgid "Status"
msgstr "Statut"
@@ -1015,6 +1154,12 @@ msgstr "Étiquette"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "La quantité produite pour cette opération est inférieure à la quantité requise de {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Le lot sera marqué comme Réussi et {remaining} unité(s) restante(s) seront complétées à cette opération."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Le lot sera toujours dispositionné, mais un NCR ne peut pas être créé tant qu'au moins un type de problème n'est pas configuré."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Il existe des matériaux suivis par numéro de série ou par lot dans la nomenclature qui n'ont pas été entièrement distribués. Terminer sans distribuer peut entraîner des enregistrements de traçabilité incorrects."
@@ -1048,6 +1193,9 @@ msgstr "Temps total : {0}"
msgid "Total: {0}"
msgstr "Total : {0}"
+msgid "Tracked Entity"
+msgstr "Entité suivie"
+
msgid "Tracking"
msgstr "Suivi"
@@ -1070,6 +1218,9 @@ msgstr "Dépicker {0}"
msgid "Unsaved changes"
msgstr "Modifications non enregistrées"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Jusqu'à {maxAllocatable} unité(s) peut/peuvent être allouée(s) ; le reste est enregistré sans comptabilisation."
+
msgid "Update"
msgstr "Mettre à jour"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index c5e3aa0789..30cef6d143 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -725,6 +725,9 @@ msgstr "पैरामीटर जोड़ें"
msgid "Add Partner"
msgstr "पार्टनर जोड़ें"
+msgid "Add parts"
+msgstr "पुर्जे जोड़ें"
+
msgid "Add Permissions"
msgstr "अनुमतियां जोड़ें"
@@ -749,6 +752,9 @@ msgstr "जोखिम जोड़ें"
msgid "Add rule"
msgstr "नियम जोड़ें"
+msgid "Add Sample"
+msgstr "नमूना जोड़ें"
+
msgid "Add Selector"
msgstr "सिलेक्टर जोड़ें"
@@ -764,6 +770,9 @@ msgstr "स्पेयर पार्ट जोड़ें"
msgid "Add Step"
msgstr "स्टेप जोड़ें"
+msgid "Add steps to preview the operator view."
+msgstr "ऑपरेटर व्यू की प्रीव्यू के लिए कदम जोड़ें।"
+
msgid "Add Supplier"
msgstr "आपूर्तिकर्ता जोड़ें"
@@ -776,6 +785,9 @@ msgstr "टाइमकार्ड जोड़ें"
msgid "Add to stock for future use"
msgstr "भविष्य के उपयोग के लिए स्टॉक में जोड़ें"
+msgid "Add tools"
+msgstr "उपकरण जोड़ें"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "अपना पहला {0} जोड़ें"
@@ -1041,6 +1053,9 @@ msgstr "सभी पर लागू होता है"
msgid "Applies to all work centers"
msgstr "सभी कार्य केंद्रों पर लागू होता है"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "उन सुविधाओं पर लागू होता है जिनके अपने नियम नहीं हैं, और जब यह योजना निरीक्षण चलाती है तो लॉट पर लागू होता है।"
+
msgid "Apply"
msgstr "लागू करें"
@@ -1401,8 +1416,11 @@ msgstr "क्या आप इस परिवर्तन आदेश को
msgid "Are you sure you want to delete this gauge?"
msgstr "क्या आप सुनिश्चित हैं कि आप इस गेज को हटाना चाहते हैं?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "क्या आप सुनिश्चित हैं कि आप इस निरीक्षण दस्तावेज़ को हटाना चाहते हैं?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "क्या आप निश्चित हैं कि आप इस निरीक्षण योजना को हटाना चाहते हैं?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "क्या आप सुनिश्चित हैं कि आप इस निरीक्षण योजना को हटाना चाहते हैं? यह पूर्ववत नहीं किया जा सकता।"
msgid "Are you sure you want to delete this issue workflow?"
msgstr "क्या आप सुनिश्चित हैं कि आप इस समस्या वर्कफ़्लो को हटाना चाहते हैं?"
@@ -1534,6 +1552,9 @@ msgstr "{0} अनुमति वाले व्यवस्थापक स
msgid "Assemblies"
msgstr "असेंबलीज"
+msgid "Assembly Instruction"
+msgstr "विधानसभा निर्देश"
+
msgid "Assembly Instructions"
msgstr "असेंबली निर्देश"
@@ -1678,6 +1699,12 @@ msgstr "स्वचालित रूप से उत्पन्न QR क
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "ऑर्डर, जॉब, पार्ट्स और अन्य के लिए ऑटो-नंबरिंग फॉर्मेट"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "जब ऑपरेटर MES में एक ऑपरेशन खोलते हैं तो उनके टाइमर को स्वचालित रूप से शुरू करें ताकि समय लॉग शुरू से ही कैप्चर किए जाएं।"
+
+msgid "Auto-start timer on open"
+msgstr "खोलने पर टाइमर को स्वचालित रूप से शुरू करें"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "मांग और पुनः ऑर्डर बिंदुओं से स्वचालित रूप से खरीद सुझाएं"
@@ -1741,6 +1768,9 @@ msgstr "संतुलित"
msgid "Balloon"
msgstr "गुब्बारा"
+msgid "Ballooned drawings with inspection features."
+msgstr "निरीक्षण विशेषताओं वाले विस्तृत चित्र।"
+
msgid "Bank - Cash"
msgstr "बैंक - नकद"
@@ -2094,6 +2124,9 @@ msgstr "अपलोड नहीं कर सकते — आपूर्त
msgid "Cannot upload to parts bucket without item ID"
msgstr "आइटम आईडी के बिना पार्ट्स बकेट में अपलोड नहीं कर सकते"
+msgid "Caption"
+msgstr "कैप्शन"
+
msgid "Carbon"
msgstr "कार्बन"
@@ -2193,6 +2226,12 @@ msgstr "चैंपियन"
msgid "Change"
msgstr "बदलें"
+msgid "Change Document"
+msgstr "परिवर्तन दस्तावेज़"
+
+msgid "Change Inspection Plan"
+msgstr "निरीक्षण योजना बदलें"
+
msgid "Change order"
msgstr "परिवर्तन आदेश"
@@ -2283,6 +2322,9 @@ msgstr "वर्ग"
msgid "Class (inherited)"
msgstr "वर्ग (विरासत में मिला)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "एक रूटिंग ऑपरेशन को वर्गीकृत करता है: प्रक्रिया, असेंबली, और निरीक्षण ऑपरेशन MES में आपके खुद के शॉप फ्लोर पर चलते हैं - असेंबली को निर्देशित असेंबली दृश्य मिलता है और निरीक्षण को गुणवत्ता जांच - जबकि एक बाहरी प्रसंस्करण ऑपरेशन एक आपूर्तिकर्ता को आउटसोर्स किया जाता है और एक खरीद आदेश बनाता है; प्रक्रिया समान प्रकार को लागू करती है और इसे नए ऑपरेशन पर डिफ़ॉल्ट करती है।"
+
msgid "Clean and approve the migrated data"
msgstr "माइग्रेट किए गए डेटा को साफ करें और मंजूरी दें"
@@ -2747,6 +2789,9 @@ msgstr "MRP सुझावों को खरीद आदेशों और
msgid "Convert to Quote"
msgstr "उद्धरण में परिवर्तित करें"
+msgid "Converting…"
+msgstr "परिवर्तित कर रहे हैं…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "एक आपूर्तिकर्ता की खरीद इकाई को PO, प्राप्ति, या बिल लाइन पर आपकी इन्वेंटरी इकाई में परिवर्तित करता है — 12 के कार्टन में खरीदें, व्यक्तिगत में स्टॉक करें।"
@@ -3055,9 +3100,6 @@ msgstr "परिवर्तन आदेश बनाएं"
msgid "Create Issue"
msgstr "समस्या बनाएं"
-msgid "Create Issue from Inspection"
-msgstr "निरीक्षण से समस्या बनाएं"
-
msgid "Create Jobs"
msgstr "नौकरियां बनाएं"
@@ -3699,6 +3741,9 @@ msgstr "डिफ़ॉल्ट प्राथमिकता"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "डिफ़ॉल्ट राजस्व GL खाता जब बिक्री चालान पोस्ट किया जाता है तो क्रेडिट किया जाता है।"
+msgid "Default Sampling"
+msgstr "डिफ़ॉल्ट नमूनाकरण"
+
msgid "Default shelf-life duration (days)"
msgstr "डिफ़ॉल्ट शेल्फ-लाइफ अवधि (दिन)"
@@ -3741,9 +3786,6 @@ msgstr "पहले एक विनिर्माण ऑपरेशन क
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "बहु-स्तरीय BOMs और Bill of Process (make methods) को परिभाषित करें"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "परिभाषित करता है कि प्रति लॉट कितनी ट्रैक की गई संस्थाओं का निरीक्षण किया जाता है, और लॉट को अस्वीकार करने से पहले कितनी विफलताओं को सहन किया जाता है।"
-
msgid "Delete"
msgstr "हटाएं"
@@ -3837,6 +3879,9 @@ msgstr "समूह हटाएं"
msgid "Delete Holiday"
msgstr "छुट्टी हटाएं"
+msgid "Delete Inspection Plan"
+msgstr "निरीक्षण योजना हटाएं"
+
msgid "Delete Issue"
msgstr "समस्या हटाएं"
@@ -4329,6 +4374,9 @@ msgstr "पुनः व्यवस्थित करने के लिए
msgid "Drag to resize diagram and features"
msgstr "आरेख और सुविधाओं को पुनः आकार देने के लिए खींचें"
+msgid "Drag to resize drawing and features"
+msgstr "ड्राइंग और विशेषताओं को आकार बदलने के लिए खींचें"
+
msgid "Drag to zoom"
msgstr "ज़ूम करने के लिए ड्रैग करें"
@@ -4549,8 +4597,8 @@ msgstr "समूह संपादित करें"
msgid "Edit Holiday"
msgstr "छुट्टी संपादित करें"
-msgid "Edit Inspection Document"
-msgstr "निरीक्षण दस्तावेज़ संपादित करें"
+msgid "Edit Inspection Plan"
+msgstr "निरीक्षण योजना संपादित करें"
msgid "Edit Item Group"
msgstr "आइटम ग्रुप संपादित करें"
@@ -5236,6 +5284,9 @@ msgstr "आपकी GL रिपोर्टिंग को स्लाइस
msgid "Fail"
msgstr "विफल"
+msgid "Failed features"
+msgstr "विफल विशेषताएँ"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (पहले समाप्त होने वाले को पहले बाहर करना)"
@@ -5479,6 +5530,21 @@ msgstr "कॉन्फ़िगरेशन नियम सहेजने म
msgid "Failed to save diagram"
msgstr "आरेख सहेजने में विफल"
+msgid "Failed to save measurement"
+msgstr "माप को सहेजने में विफल"
+
+msgid "Failed to save parts"
+msgstr "पुर्जों को सहेजने में विफल"
+
+msgid "Failed to save result"
+msgstr "परिणाम को सहेजने में विफल रहा"
+
+msgid "Failed to save slides"
+msgstr "स्लाइड्स को सहेजने में विफल"
+
+msgid "Failed to save tools"
+msgstr "उपकरणों को सहेजने में विफल"
+
msgid "Failed to update batch property"
msgstr "बैच प्रॉपर्टी अपडेट करने में विफल"
@@ -6400,15 +6466,6 @@ msgstr "निष्क्रिय क्रियाएं चयन सूच
msgid "Inbound inspection"
msgstr "इनबाउंड निरीक्षण"
-msgid "Inbound Inspection"
-msgstr "इनबाउंड निरीक्षण"
-
-msgid "Inbound Inspections"
-msgstr "इनबाउंड निरीक्षण"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "इनबाउंड निरीक्षण: विभिन्न निरीक्षक की आवश्यकता"
-
msgid "Inbox"
msgstr "इनबॉक्स"
@@ -6454,6 +6511,12 @@ msgstr "अप्रत्यक्ष सामग्री और सेवा
msgid "Infrastructure"
msgstr "बुनियादी ढांचा"
+msgid "Inherit"
+msgstr "विरासत"
+
+msgid "Inherit document default"
+msgstr "दस्तावेज़ डिफ़ॉल्ट को विरासत में लें"
+
msgid "Inherit From Materials"
msgstr "सामग्री से विरासत में प्राप्त करें"
@@ -6490,32 +6553,35 @@ msgstr "पहले N निरीक्षण करें"
msgid "Inspect Item"
msgstr "आइटम का निरीक्षण करें"
-msgid "Inspect Next Item"
-msgstr "अगली वस्तु का निरीक्षण करें"
-
msgid "Inspection"
msgstr "निरीक्षण"
-msgid "Inspection Document"
-msgstr "निरीक्षण दस्तावेज़"
-
-msgid "Inspection Documents"
-msgstr "निरीक्षण दस्तावेज़"
-
msgid "Inspection Level"
msgstr "निरीक्षण स्तर"
+msgid "Inspection Plan"
+msgstr "निरीक्षण योजना"
+
+msgid "Inspection Plan Assignments"
+msgstr "निरीक्षण योजना असाइनमेंट"
+
+msgid "Inspection Plans"
+msgstr "निरीक्षण योजनाएं"
+
msgid "Inspection Status"
msgstr "निरीक्षण स्थिति"
+msgid "Inspections"
+msgstr "निरीक्षण"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "निरीक्षण, असंगति, और CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "निरीक्षण, असंगति, CAPA"
-msgid "Inspector"
-msgstr "निरीक्षक"
+msgid "Inspections: Require Different Inspector"
+msgstr "निरीक्षण: विभिन्न निरीक्षक की आवश्यकता है"
msgid "Install"
msgstr "इंस्टॉल करें"
@@ -7439,15 +7505,9 @@ msgstr "पूर्ण के रूप में चिह्नित कर
msgid "Mark Light Mode"
msgstr "मार्क लाइट मोड"
-msgid "Mark lot as partial?"
-msgstr "लॉट को आंशिक के रूप में चिह्नित करें?"
-
msgid "Mark not done"
msgstr "पूर्ण नहीं किया गया चिह्नित करें"
-msgid "Mark Partial"
-msgstr "आंशिक रूप से चिह्नित करें"
-
msgid "Mark scope as agreed"
msgstr "स्कोप को सहमत के रूप में चिह्नित करें"
@@ -7960,8 +8020,8 @@ msgstr "नई छुट्टी"
msgid "New IC Transaction"
msgstr "नया IC लेनदेन"
-msgid "New Inspection Document"
-msgstr "नया निरीक्षण दस्तावेज़"
+msgid "New Inspection Plan"
+msgstr "नई निरीक्षण योजना"
msgid "New Inventory Count"
msgstr "नई इन्वेंटरी गणना"
@@ -8332,6 +8392,9 @@ msgstr "कोई समूह असाइन नहीं किया गय
msgid "No image"
msgstr "कोई छवि नहीं"
+msgid "No inspection plans"
+msgstr "कोई निरीक्षण योजनाएं नहीं"
+
msgid "No issue types configured"
msgstr "कोई समस्या प्रकार कॉन्फ़िगर नहीं किया गया"
@@ -8392,6 +8455,9 @@ msgstr "अभी तक कोई मूल स्रोत दर्ज नह
msgid "No part ID"
msgstr "कोई भाग ID नहीं"
+msgid "No parts"
+msgstr "कोई पुर्जे नहीं"
+
msgid "No payables"
msgstr "कोई देय नहीं"
@@ -8428,6 +8494,9 @@ msgstr "कोई उद्धरण कारण नहीं"
msgid "No receivables"
msgstr "कोई प्राप्य नहीं"
+msgid "No reference image"
+msgstr "कोई संदर्भ छवि नहीं"
+
msgid "No remaining entities to inspect."
msgstr "निरीक्षण के लिए कोई शेष इकाई नहीं है।"
@@ -8443,9 +8512,6 @@ msgstr "यहाँ कोई पंक्तियाँ नहीं है
msgid "No rules assigned"
msgstr "कोई नियम असाइन नहीं किया गया"
-msgid "No samples inspected yet."
-msgstr "अभी तक कोई नमूना निरीक्षण नहीं किया गया है।"
-
msgid "No single, trusted number for inventory or job status"
msgstr "इन्वेंटरी या जॉब स्थिति के लिए कोई एकल, विश्वसनीय संख्या नहीं"
@@ -8464,6 +8530,12 @@ msgstr "अभी तक कोई आपूर्तिकर्ता नह
msgid "No time entries for this week"
msgstr "इस सप्ताह के लिए कोई समय प्रविष्टि नहीं"
+msgid "No tools"
+msgstr "कोई उपकरण नहीं"
+
+msgid "No tools for this step"
+msgstr "इस कदम के लिए कोई उपकरण नहीं"
+
msgid "No transactions in this period"
msgstr "इस अवधि में कोई लेनदेन नहीं"
@@ -8773,6 +8845,9 @@ msgstr "ऑपरेशन"
msgid "Operation Order"
msgstr "ऑपरेशन क्रम"
+msgid "Operation Timer"
+msgstr "ऑपरेशन टाइमर"
+
msgid "Operation Type"
msgstr "ऑपरेशन प्रकार"
@@ -8900,6 +8975,9 @@ msgstr "ओवरहेड विचरण"
msgid "Over-applied by"
msgstr "अत्यधिक लागू किया गया"
+msgid "Overall result"
+msgstr "समग्र परिणाम"
+
msgid "Overdue"
msgstr "अतिदेय"
@@ -9027,9 +9105,6 @@ msgstr "भाग संख्या"
msgid "Part Supersession"
msgstr "भाग प्रतिस्थापन"
-msgid "Partial"
-msgstr "आंशिक"
-
msgid "Partner"
msgstr "साथी"
@@ -9246,6 +9321,9 @@ msgstr "Pieces/Hour"
msgid "Pieces/Minute"
msgstr "Pieces/Minute"
+msgid "Pin"
+msgstr "पिन"
+
msgid "Pinned"
msgstr "पिन किया गया"
@@ -9447,6 +9525,9 @@ msgstr "पिछली तारीख"
msgid "Previous page"
msgstr "पिछला पृष्ठ"
+msgid "Previous step"
+msgstr "पिछला कदम"
+
msgid "Price break actions"
msgstr "मूल्य विराम क्रियाएं"
@@ -10138,9 +10219,6 @@ msgstr "रिकॉर्ड हटाया गया"
msgid "Record inspections tied to a part and a job"
msgstr "एक भाग और एक कार्य से जुड़े निरीक्षण रिकॉर्ड करें"
-msgid "Record the inspection result for this sample."
-msgstr "इस नमूने के लिए निरीक्षण परिणाम दर्ज करें।"
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "कैलिब्रेशन पर दर्ज किया गया है कि गेज को मरम्मत की आवश्यकता है इससे पहले कि इसकी रीडिंग पर विश्वास किया जा सके।"
@@ -10265,9 +10343,6 @@ msgstr "हटाएँ {label}"
msgid "Remove condition"
msgstr "शर्त हटाएं"
-msgid "Remove feature"
-msgstr "सुविधा हटाएं"
-
msgid "Remove filter"
msgstr "फ़िल्टर हटाएं"
@@ -10286,12 +10361,21 @@ msgstr "ऑर्डर हटाएं"
msgid "Remove pair"
msgstr "जोड़ी हटाएं"
+msgid "Remove part"
+msgstr "पुर्जा हटाएँ"
+
+msgid "Remove slide"
+msgstr "स्लाइड हटाएँ"
+
msgid "Remove sort by column"
msgstr "कॉलम द्वारा सॉर्ट हटाएं"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "इस स्टोरेज प्रकार को सभी संदर्भित स्टोरेज इकाइयों से हटाएं और इसे हटाएं। यह पूर्ववत नहीं किया जा सकता।"
+msgid "Remove tool"
+msgstr "उपकरण हटाएँ"
+
msgid "Removed"
msgstr "हटाया गया"
@@ -10421,9 +10505,6 @@ msgstr "कार्रवाई आवश्यक है"
msgid "Requires Adjustment"
msgstr "समायोजन आवश्यक है"
-msgid "Requires Inspection"
-msgstr "निरीक्षण आवश्यक है"
-
msgid "Requires Repair"
msgstr "मरम्मत की आवश्यकता है"
@@ -10444,7 +10525,7 @@ msgstr "PIN रीसेट करें"
msgid "Reset PIN for {0} {1}"
msgstr "{0} {1} के लिए PIN रीसेट करें"
-msgid "Reset View"
+msgid "Reset view"
msgstr "दृश्य रीसेट करें"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "किताब के समान"
msgid "Sample"
msgstr "नमूना"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "नमूना {0}"
-
msgid "Sample Size"
msgstr "नमूना आकार"
-msgid "Sampling Plan"
-msgstr "सैंपलिंग प्लान"
+msgid "Sampling"
+msgstr "नमूनाकरण"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "नमूनाकरण — सुविधा {featureLabel}"
msgid "Sampling Standard"
msgstr "नमूना मानक"
@@ -10852,8 +10932,8 @@ msgstr "स्कैन करें या ट्रैकिंग नंब
msgid "Scan or search..."
msgstr "स्कैन या खोजें..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "इस लॉट से एक ट्रैक किए गए इकाई को स्कैन या चुनें और निरीक्षण परिणाम रिकॉर्ड करें।"
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "इस लॉट से एक ट्रैक की गई इकाई को स्कैन या चुनें इसे एक नमूना कॉलम के रूप में जोड़ने के लिए, फिर ग्रिड में इसके परिणाम को रिकॉर्ड करें।"
msgid "Scan the tracking ID for this line"
msgstr "इस लाइन के लिए ट्रैकिंग आईडी स्कैन करें"
@@ -10900,6 +10980,9 @@ msgstr "स्कोप"
msgid "Scrap"
msgstr "स्क्रैप"
+msgid "Scrap / Cost of Quality"
+msgstr "स्क्रैप / गुणवत्ता की लागत"
+
msgid "Scrap Percent"
msgstr "स्क्रैप प्रतिशत"
@@ -10960,6 +11043,9 @@ msgstr "Job खोजें"
msgid "Search operators..."
msgstr "ऑपरेटर खोजें..."
+msgid "Search parts..."
+msgstr "पुर्जे खोजें..."
+
msgid "Search processes..."
msgstr "प्रक्रियाओं को खोजें..."
@@ -10969,6 +11055,9 @@ msgstr "संबंधित आइटम खोजें..."
msgid "Search suppliers..."
msgstr "आपूर्तिकर्ताओं को खोजें..."
+msgid "Search tools..."
+msgstr "उपकरण खोजें..."
+
msgid "Search..."
msgstr "खोजें..."
@@ -10990,6 +11079,9 @@ msgstr "एक असाइनी चुनें"
msgid "Select a default approver"
msgstr "एक डिफ़ॉल्ट अनुमोदक चुनें"
+msgid "Select a document"
+msgstr "एक दस्तावेज़ चुनें"
+
msgid "Select a new owner"
msgstr "एक नया मालिक चुनें"
@@ -11647,6 +11739,9 @@ msgstr "स्पेयर पार्ट खपत"
msgid "Spare Part Cost"
msgstr "स्पेयर पार्ट लागत"
+msgid "Spec"
+msgstr "विनिर्देश"
+
msgid "Specific Customer"
msgstr "विशिष्ट ग्राहक"
@@ -11777,6 +11872,12 @@ msgstr "कदम"
msgid "Steps"
msgstr "चरण"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "चरण विधानसभा निर्देश से विरासत में मिले हैं।"
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "चरण निरीक्षण योजना से विरासत में मिले हैं।"
+
msgid "Stock Transfer ID"
msgstr "स्टॉक ट्रांसफर आईडी"
@@ -12470,8 +12571,8 @@ msgstr "ग्राहक को उद्धृत करने से भु
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "वह एंडपॉइंट जो तालिका अपडेट होने पर अपडेट किए गए डेटा के साथ POST अनुरोध प्राप्त करता है"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "इंजीनियरिंग ड्राइंग जिससे यह निरीक्षण दस्तावेज़ जुड़ा है; इस भाग संदर्भ के विरुद्ध दर्ज किए गए निरीक्षण इस ड्राइंग को संदर्भित करते हैं।"
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "इंजीनियरिंग ड्राइंग जिसे यह निरीक्षण योजना बंधी है; इस हिस्से के विरुद्ध दर्ज निरीक्षण इस ड्राइंग को वापस संदर्भित करते हैं।"
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "उत्पादन के दौरान इस आइटम के उत्पादन का अपेक्षित प्रतिशत खो गया; योजना नुकसान की भरपाई के लिए मांग को 1 / (1 - स्क्रैप) से गुणा करता है।"
@@ -12620,15 +12721,15 @@ msgstr "आपके मुद्रित और ईमेल किए गए
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "इस स्टॉक के लिए लॉट पहचानकर्ता; प्रति बैच एक पंक्ति, मात्रा उस लॉट के लिए हाथ पर है।"
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "लॉट खुला रहता है ताकि आप निरीक्षण जारी रख सकें और बाद में निपटान कर सकें। नमूने के परिणाम संरक्षित रहते हैं।"
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "लॉट को पास के रूप में चिह्नित किया जाएगा। {fails} नमूना विफलता(एं) आपके रिकॉर्ड के लिए दर्ज की गई हैं।"
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "लॉट अभी भी अस्वीकृत कर दिया जाएगा, लेकिन कम से कम एक Issue Type कॉन्फ़िगर होने तक NCR नहीं बनाया जा सकता।"
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "चयनित दस्तावेज़ से लॉट की प्रति-विशेषता नमूनाकरण योजना को पुनः निर्धारित किया जाएगा।"
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "सबसे कम राशि जो यह आपूर्तिकर्ता इस प्रक्रिया के लिए चार्ज करेगा, मात्रा की परवाह किए बिना; संतुलन मात्रा के नीचे नौकरियां अभी भी कम से कम इतनी अधिक लागत करती हैं।"
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "संचालन का क्रमित क्रम जो एक काम चलाता है, विधि के बिल ऑफ प्रोसेस से कॉपी किया गया।"
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "मूल मॉडल फ़ाइल अब उपलब्ध नहीं है"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "बाहरी पोस्टिंग दस्तावेज़ जो स्टॉक से माल को ग्राहक के पास ले जाता है, रास्ते में COGS पोस्ट करता है।"
@@ -12719,8 +12820,8 @@ msgstr "कार्बन की ओर से वे लोग जो आप
msgid "The people on your team and their access to Carbon"
msgstr "आपकी टीम के लोग और Carbon तक उनकी पहुंच"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "दस्तावेज़ प्रकार की पठनीय संख्या के पीछे प्रति-कंपनी काउंटर, {prefix}{next+step, zero-padded}{suffix} को असेम्बल करता है और प्रत्येक दस्तावेज़ बनाए जाने पर आगे बढ़ता है।"
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "प्रति-कंपनी काउंटर जो एक दस्तावेज़ प्रकार की पठनीय संख्या के अंतर्गत काम करता है, जो उपसर्ग, शून्य-पैडित अगली मान, और प्रत्यय को एकत्रित करता है, और हर नए दस्तावेज़ के निर्माण के साथ आगे बढ़ता है।"
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "प्रत्येक आइटम का परिणाम एक गैर-अनुरूपता की प्रभावित सामग्री पर दर्ज किया गया — प्रतीक्षित, आपूर्तिकर्ता को वापस, पुनः कार्य, स्क्रैप, या जैसा है वैसा उपयोग करें — प्रत्येक प्रभावित लॉट या सीरियल के लिए अपने आप पर निर्णय लिया गया।"
@@ -13011,6 +13112,9 @@ msgstr "यह जानकारी दस्तावेज़ शीर्ष
msgid "This information will be visible to all users, so be careful what you share."
msgstr "यह जानकारी सभी उपयोगकर्ताओं को दिखाई देगी, इसलिए सावधान रहें कि आप क्या साझा करते हैं।"
+msgid "this inspection plan"
+msgstr "इस निरीक्षण योजना"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "यह एक खरीदा गया आइटम है — इसके पास कोई BoM/BoP नहीं है; केवल इसकी विशेषताओं और दस्तावेजों को बदला जा सकता है।"
@@ -13459,9 +13563,6 @@ msgstr "प्रकार:"
msgid "Types"
msgstr "प्रकार"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "नमूना न लिए गए इकाइयां On Hold पर रहेंगी ताकि आप निरीक्षण जारी रख सकें और बाद में निपटान कर सकें। नमूना किए गए परिणाम संरक्षित रहते हैं।"
-
msgid "Unapplied"
msgstr "अप्रयुक्त"
@@ -14311,6 +14412,9 @@ msgstr "जब सक्षम हो, तो इस श्रेणी की
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "जब सक्षम हो, तो कर्मचारी अपनी स्वयं की प्रोफ़ाइल पर इस विशेषता का मान संपादित कर सकते हैं; अन्यथा केवल व्यवस्थापक ऐसा कर सकते हैं।"
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "जब चालू हो, तो एक ऑपरेशन खोलने से इसका टाइमर स्वचालित रूप से शुरू हो जाता है।"
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "जब सक्षम हो, तो मूल्य निर्धारण नियम (वॉल्यूम डिस्काउंट, प्रचार) इस ओवरराइड के शीर्ष पर लागू होते रहते हैं; जब अक्षम हो, तो यह ओवरराइड अंतिम मूल्य है।"
@@ -14437,8 +14541,8 @@ msgstr "क्या घड़ी तब शुरू होती है जब
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "क्या यह लॉट/सीरियल निरीक्षण पास करता है (Pass) या विफल होता है (Fail); एक Fail स्टॉक को उपलब्ध इन्वेंट्री में प्राप्त होने से रोकता है।"
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "क्या यह प्रक्रिया आंतरिक कार्य केंद्रों (Inside), बाहरी आपूर्तिकर्ताओं (Outside), या दोनों (Both) पर चलती है; विभिन्न डाउनस्ट्रीम फ़ील्ड दिखाती है और बदलती है कि इस प्रक्रिया के लिए योजना रूटिंग कैसे काम करती है।"
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "क्या यह प्रक्रिया आंतरिक कार्य केंद्रों (प्रक्रिया, असेंबली, या निरीक्षण) पर चलती है या बाहरी आपूर्तिकर्ताओं (बाहरी प्रसंस्करण) पर; विभिन्न डाउनस्ट्रीम फ़ील्ड्स को प्रकट करता है, इस प्रक्रिया के लिए योजना मार्गों का काम करने का तरीका बदलता है, और नए ऑपरेशन पर ऑपरेशन प्रकार को डिफ़ॉल्ट करता है।"
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "यह कार्य उत्पादन को अवरुद्ध करता है (डाउन), इसे नीचा दिखाता है (प्रभाव), एक नियोजित डाउनटाइम विंडो (योजनाबद्ध) में है, या कोई उत्पादन प्रभाव नहीं है (कोई प्रभाव नहीं); शेड्यूलिंग और ग्राहक-सामना डाउनटाइम संचार को सूचित करता है।"
@@ -14446,6 +14550,9 @@ msgstr "यह कार्य उत्पादन को अवरुद्
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "चाहे चयनित अनुमतियां जोड़ी जाएं कि प्रत्येक उपयोगकर्ता के पास पहले से क्या है, या अपडेट द्वारा नीचे दिए गए चयन के साथ प्रत्येक उपयोगकर्ता की अनुमति सेट को प्रतिस्थापित करें।"
+msgid "Which document drives each inspection flow for this item."
+msgstr "कौन सा दस्तावेज़ इस आइटम के लिए प्रत्येक निरीक्षण प्रवाह को चलाता है।"
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "कौन सी विनिर्माण घटना शेल्फ-जीवन घड़ी शुरू करती है — उदाहरण के लिए, भरना, सील करना, या अंतिम क्यूसी।"
@@ -14608,6 +14715,9 @@ msgstr "बट्टे खाता"
msgid "Write-off for {0}"
msgstr "{0} के लिए राइट-ऑफ"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "निरीक्षण अस्वीकृतियों और एनसीआर निपटान के माध्यम से स्टॉक को स्क्रैप या वापस किए जाने की राइट-ऑफ"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "किसी संपत्ति के मूल्य को उसके जीवन काल में कम करना — एक मासिक बैच जो आप बनाते हैं, ड्राफ्ट के रूप में समीक्षा करते हैं, फिर पोस्ट करते हैं।"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 34f945748d..31843251f6 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} में से {1} पूर्ण"
msgid "{0} Scrapped"
msgstr "{0} स्क्रैप किया गया"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} पास किए गए यूनिट(यूनिट्स) पूरी की जाएंगी।"
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} नमूना विफलता(एं) दर्ज की गई है और पूर्ण नहीं की जाएगी — उन्हें क्रियाएं मेनू से हल करें।"
+
msgid "About"
msgstr "के बारे में"
+msgid "Accept"
+msgstr "स्वीकार करें"
+
+msgid "Accept Lot"
+msgstr "लॉट स्वीकार करें"
+
+msgid "Accept lot?"
+msgstr "लॉट स्वीकार करें?"
+
msgid "Account Settings"
msgstr "खाता सेटिंग्स"
@@ -66,12 +81,27 @@ msgstr "प्रिंटिंग सेटिंग्स में एक
msgid "Add Inventory"
msgstr "इन्वेंटरी जोड़ें"
+msgid "Add Sample"
+msgstr "नमूना जोड़ें"
+
msgid "Add Spare Part"
msgstr "स्पेयर पार्ट जोड़ें"
msgid "All"
msgstr "सभी"
+msgid "All rework"
+msgstr "सभी रीवर्क"
+
+msgid "All scrap"
+msgstr "सभी स्क्रैप"
+
+msgid "Allocate failed units"
+msgstr "विफल इकाइयों को आवंटित करें"
+
+msgid "Allocate units"
+msgstr "इकाइयों को आवंटित करें"
+
msgid "Are you sure you want to delete this step?"
msgstr "क्या आप सुनिश्चित हैं कि आप इस चरण को हटाना चाहते हैं?"
@@ -165,6 +195,12 @@ msgstr "घड़ी बंद करें"
msgid "Clocked in since {0}"
msgstr "Clocked in since {0}"
+msgid "Close"
+msgstr "बंद करें"
+
+msgid "Collapse features table"
+msgstr "फीचर्स टेबल को संक्षिप्त करें"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "पूर्ण करें"
msgid "Complete All"
msgstr "सभी को पूर्ण करें"
+msgid "Complete passed"
+msgstr "पूर्ण पास"
+
msgid "Completed"
msgstr "पूर्ण"
@@ -281,6 +320,9 @@ msgstr "ड्राफ्ट"
msgid "Drag and drop a file here, or click to select a file"
msgstr "यहाँ एक फ़ाइल को ड्रैग और ड्रॉप करें, या फ़ाइल चुनने के लिए क्लिक करें"
+msgid "Drag to resize drawing and features"
+msgstr "ड्राइंग और फीचर्स को रिसाइज़ करने के लिए ड्रैग करें"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "\"{0}\" को ड्रैग करना रद्द किया गया।"
@@ -325,6 +367,12 @@ msgstr "त्रुटि"
msgid "Estimated"
msgstr "अनुमानित"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "हर इकाई का एक निर्णय है: {passes} पास और {fails} विफल। लॉट बंद हो जाता है और प्रत्येक इकाई अपने परिणाम के लिए रूट की जाती है।"
+
+msgid "Expand features table"
+msgstr "फीचर्स टेबल को विस्तृत करें"
+
msgid "Expired"
msgstr "समाप्त"
@@ -337,6 +385,12 @@ msgstr "समाप्त होता है {date}"
msgid "Expiring first"
msgstr "पहले समाप्त होने वाले"
+msgid "Failed"
+msgstr "विफल"
+
+msgid "Failed features"
+msgstr "विफल सुविधाएँ"
+
msgid "Failed to complete inventory adjustment"
msgstr "इन्वेंटरी समायोजन पूरा करने में विफल"
@@ -349,6 +403,12 @@ msgstr "सक्रिय संचालन प्राप्त करने
msgid "Failed to fetch storageUnits"
msgstr "storageUnits को प्राप्त करने में विफल"
+msgid "Failed to save measurement"
+msgstr "माप को सहेजने में विफल"
+
+msgid "Failed to save result"
+msgstr "परिणाम को सहेजने में विफल"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "फ़ाइल अपलोड करने में विफल: {0}"
@@ -356,6 +416,12 @@ msgstr "फ़ाइल अपलोड करने में विफल: {0}
msgid "Failed to upload image"
msgstr "छवि अपलोड करने में विफल"
+msgid "Feature"
+msgstr "सुविधा"
+
+msgid "Features"
+msgstr "विशेषताएं"
+
msgid "File size exceeds 10MB limit"
msgstr "फ़ाइल का आकार 10MB की सीमा से अधिक है"
@@ -405,6 +471,12 @@ msgstr "इंपीरियल"
msgid "In Progress"
msgstr "प्रगति में"
+msgid "Inspect Item"
+msgstr "आइटम का निरीक्षण करें"
+
+msgid "inspected"
+msgstr "निरीक्षण किया गया"
+
msgid "Insufficient quantity"
msgstr "अपर्याप्त मात्रा"
@@ -498,6 +570,9 @@ msgstr "{0} के लिए स्क्रैप लॉग करें"
msgid "Login"
msgstr "लॉगिन"
+msgid "Lot"
+msgstr "लॉट"
+
msgid "Machine"
msgstr "मशीन"
@@ -531,6 +606,9 @@ msgstr "मीट्रिक"
msgid "Model"
msgstr "मॉडल"
+msgid "More actions"
+msgstr "अधिक क्रियाएं"
+
msgid "More Actions"
msgstr "अधिक क्रियाएं"
@@ -595,6 +673,9 @@ msgstr "कोई फ़ाइलें नहीं"
msgid "No Impact"
msgstr "कोई प्रभाव नहीं"
+msgid "No issue types configured"
+msgstr "कोई समस्या प्रकार कॉन्फ़िगर नहीं किया गया"
+
msgid "No maintenance scheduled for today"
msgstr "आज के लिए कोई रखरखाव निर्धारित नहीं है"
@@ -607,6 +688,9 @@ msgstr "कोई सामग्री नहीं"
msgid "No open jobs"
msgstr "कोई खुली नौकरी नहीं"
+msgid "No open units to allocate"
+msgstr "आवंटित करने के लिए कोई खुली इकाई नहीं"
+
msgid "No operators"
msgstr "कोई ऑपरेटर नहीं"
@@ -625,6 +709,9 @@ msgstr "कोई प्रिंटर कॉन्फ़िगर नहीं
msgid "No recent operations"
msgstr "कोई हाल के संचालन नहीं"
+msgid "No remaining entities to inspect."
+msgstr "निरीक्षण करने के लिए कोई शेष इकाई नहीं है।"
+
msgid "No results"
msgstr "कोई परिणाम नहीं"
@@ -634,6 +721,9 @@ msgstr "कोई परिणाम मौजूद नहीं है"
msgid "No results found"
msgstr "कोई परिणाम नहीं मिला"
+msgid "No samples required."
+msgstr "कोई नमूना आवश्यक नहीं है।"
+
msgid "No scheduled time"
msgstr "कोई निर्धारित समय नहीं"
@@ -683,6 +773,9 @@ msgstr "अरे। आपको यह पृष्ठ नहीं देख
msgid "Open"
msgstr "खुला"
+msgid "Open an NCR for MRB disposition"
+msgstr "एमआरबी डिस्पोजिशन के लिए एनसीआर खोलें"
+
msgid "Open Jobs"
msgstr "खुली नौकरियां"
@@ -698,12 +791,21 @@ msgstr "ऑपरेटर द्वारा निष्पादित"
msgid "Optional"
msgstr "वैकल्पिक"
+msgid "Overall result"
+msgstr "समग्र परिणाम"
+
msgid "Parameters"
msgstr "पैरामीटर"
msgid "Part"
msgstr "भाग"
+msgid "Partial"
+msgstr "आंशिक"
+
+msgid "Partial Disposition"
+msgstr "आंशिक निपटान"
+
msgid "Passed Inspection"
msgstr "निरीक्षण पास किया"
@@ -749,9 +851,6 @@ msgstr "पिछला"
msgid "Preventive"
msgstr "निवारक"
-msgid "Previous"
-msgstr "पिछला"
-
msgid "Print"
msgstr "प्रिंट करें"
@@ -801,6 +900,18 @@ msgstr "रिकॉर्ड"
msgid "Record {0}"
msgstr "रिकॉर्ड {0}"
+msgid "Record only"
+msgstr "केवल रिकॉर्ड करें"
+
+msgid "Record Partial"
+msgstr "आंशिक रिकॉर्ड करें"
+
+msgid "Reject"
+msgstr "अस्वीकार करें"
+
+msgid "Reject Lot"
+msgstr "लॉट अस्वीकार करें"
+
msgid "Remove"
msgstr "हटाएं"
@@ -813,12 +924,18 @@ msgstr "इन्वेंटरी हटाएं"
msgid "Remove part"
msgstr "भाग हटाएं"
+msgid "Result"
+msgstr "परिणाम"
+
msgid "Rework"
msgstr "रीवर्क"
msgid "Rework created successfully"
msgstr "रीवर्क सफलतापूर्वक बनाया गया"
+msgid "Rework quantity"
+msgstr "रीवर्क मात्रा"
+
msgid "Sales Order"
msgstr "बिक्रय आदेश"
@@ -828,21 +945,33 @@ msgstr "सहेजें"
msgid "Scan"
msgstr "स्कैन करें"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "पहले नमूना कॉलम जोड़ने के लिए ट्रैक की गई इकाई को स्कैन करें।"
+
msgid "Scan or enter serial number"
msgstr "स्कैन करें या सीरियल नंबर दर्ज करें"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "ट्रैक की गई इकाई आईडी, सीरियल, या बैच को स्कैन या दर्ज करें"
+
msgid "Scan or enter tracking number"
msgstr "स्कैन करें या ट्रैकिंग नंबर दर्ज करें"
msgid "Scan or search serial number..."
msgstr "सीरियल नंबर स्कैन या खोजें..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "इस लॉट से ट्रैक की गई इकाई को स्कैन या चुनें इसे नमूना कॉलम के रूप में जोड़ने के लिए, फिर ग्रिड में इसके परिणाम को रिकॉर्ड करें।"
+
msgid "Schedule"
msgstr "शेड्यूल"
msgid "Scrap"
msgstr "स्क्रैप"
+msgid "Scrap quantity"
+msgstr "स्क्रैप मात्रा"
+
msgid "Scrap Reason"
msgstr "स्क्रैप कारण"
@@ -876,6 +1005,9 @@ msgstr "स्क्रैप मात्रा और कारण चुन
msgid "Select a serial number to continue with this operation"
msgstr "इस ऑपरेशन को जारी रखने के लिए एक सीरियल नंबर चुनें"
+msgid "Select an issue type"
+msgstr "समस्या प्रकार चुनें"
+
msgid "Select an item and specify the quantity to issue"
msgstr "एक आइटम चुनें और जारी करने के लिए मात्रा निर्दिष्ट करें"
@@ -899,6 +1031,9 @@ msgstr "सीरियल नंबर चुनें"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "उस ऑपरेशन को चुनें जिस पर वापस जाना है। उस बिंदु से वर्तमान ऑपरेशन तक के सभी ऑपरेशन फिर से किए जाएंगे।"
+msgid "Selected"
+msgstr "चयनित"
+
msgid "Send"
msgstr "भेजें"
@@ -978,6 +1113,10 @@ msgstr "स्टेशन उपयोगकर्ता"
msgid "Station: {stationName}"
msgstr "स्टेशन: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "सांख्यिकीय स्वीकृति विफल हुई, इसलिए {0} का पूरा लॉट गैर-अनुरूप माना जाता है (ISO 9001:2015 §8.7) — {passes} नमूना पास और {fails} विफलता(एं)। नीचे दी गई इकाइयों को स्क्रैप या रीवर्क के लिए रूट करें, या केवल निर्णय रिकॉर्ड करें।"
+
msgid "Status"
msgstr "स्थिति"
@@ -1015,6 +1154,12 @@ msgstr "टैग"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "इस ऑपरेशन के लिए पूर्ण मात्रा आवश्यक मात्रा {0} से कम है।"
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "लॉट को पास के रूप में चिह्नित किया जाएगा और {remaining} शेष इकाई(यों) को इस ऑपरेशन पर पूरा किया जाएगा।"
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "लॉट को अभी भी डिस्पोज़ किया जाएगा, लेकिन कम से कम एक Issue Type कॉन्फ़िगर होने तक NCR नहीं बनाया जा सकता।"
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "बिल ऑफ मेटेरियल पर सीरियल या बैच ट्रैक किए गए मेटेरियल हैं जो पूरी तरह से जारी नहीं किए गए हैं। जारी किए बिना पूरा करने से गलत ट्रेसेबिलिटी रिकॉर्ड हो सकते हैं।"
@@ -1048,6 +1193,9 @@ msgstr "कुल समय: {0}"
msgid "Total: {0}"
msgstr "कुल: {0}"
+msgid "Tracked Entity"
+msgstr "ट्रैक की गई इकाई"
+
msgid "Tracking"
msgstr "ट्रैकिंग"
@@ -1070,6 +1218,9 @@ msgstr "अनपिक {0}"
msgid "Unsaved changes"
msgstr "असहेजे परिवर्तन"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "अधिकतम {maxAllocatable} इकाई(यों) को आवंटित किया जा सकता है; शेष को पोस्टिंग के बिना दर्ज किया जाता है।"
+
msgid "Update"
msgstr "अपडेट करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 74a2df5927..a5127a91c2 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -725,6 +725,9 @@ msgstr "Aggiungi Parametro"
msgid "Add Partner"
msgstr "Aggiungi Partner"
+msgid "Add parts"
+msgstr "Aggiungi parti"
+
msgid "Add Permissions"
msgstr "Aggiungi Autorizzazioni"
@@ -749,6 +752,9 @@ msgstr "Aggiungi Rischio"
msgid "Add rule"
msgstr "Aggiungi regola"
+msgid "Add Sample"
+msgstr "Aggiungi Campione"
+
msgid "Add Selector"
msgstr "Aggiungi selettore"
@@ -764,6 +770,9 @@ msgstr "Aggiungi Pezzo di Ricambio"
msgid "Add Step"
msgstr "Aggiungi Passaggio"
+msgid "Add steps to preview the operator view."
+msgstr "Aggiungi passaggi per visualizzare in anteprima la vista operatore."
+
msgid "Add Supplier"
msgstr "Aggiungi Fornitore"
@@ -776,6 +785,9 @@ msgstr "Aggiungi Scheda Orario"
msgid "Add to stock for future use"
msgstr "Aggiungi alle scorte per uso futuro"
+msgid "Add tools"
+msgstr "Aggiungi strumenti"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Aggiungi il tuo primo {0}"
@@ -1041,6 +1053,9 @@ msgstr "Si applica a tutti"
msgid "Applies to all work centers"
msgstr "Si applica a tutti i centri di lavoro"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Si applica alle funzionalità senza una propria regola e al lotto quando questo piano determina un'ispezione."
+
msgid "Apply"
msgstr "Applica"
@@ -1401,8 +1416,11 @@ msgstr "Sei sicuro di voler eliminare questo ordine di modifica?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Sei sicuro di voler eliminare questo calibro?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Sei sicuro di voler eliminare questo documento di ispezione?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Sei sicuro che desideri eliminare questo piano di ispezione?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Sei sicuro di voler eliminare questo piano di ispezione? Questa azione non può essere annullata."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Sei sicuro di voler eliminare questo flusso di lavoro dei problemi?"
@@ -1534,6 +1552,9 @@ msgstr "Chiedi a un amministratore con autorizzazione {0} di aggiungere il primo
msgid "Assemblies"
msgstr "Assiemi"
+msgid "Assembly Instruction"
+msgstr "Istruzioni di Montaggio"
+
msgid "Assembly Instructions"
msgstr "Istruzioni di Montaggio"
@@ -1678,6 +1699,12 @@ msgstr "Codice QR generato automaticamente"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Formati di numerazione automatica per ordini, lavori, parti e altro"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Avvia automaticamente il timer dell'operatore quando apre un'operazione nel MES in modo che i registri dei tempi siano acquisiti dall'inizio."
+
+msgid "Auto-start timer on open"
+msgstr "Avvia automaticamente il timer all'apertura"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Suggerisci automaticamente acquisti da domanda e punti di riordino"
@@ -1741,6 +1768,9 @@ msgstr "Equilibrato"
msgid "Balloon"
msgstr "Palloncino"
+msgid "Ballooned drawings with inspection features."
+msgstr "Disegni con palloncini con caratteristiche di ispezione."
+
msgid "Bank - Cash"
msgstr "Banca - Contanti"
@@ -2094,6 +2124,9 @@ msgstr "Impossibile caricare — interazione fornitore non ancora creata"
msgid "Cannot upload to parts bucket without item ID"
msgstr "Impossibile caricare nel bucket delle parti senza ID elemento"
+msgid "Caption"
+msgstr "Didascalia"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Campioni"
msgid "Change"
msgstr "Cambia"
+msgid "Change Document"
+msgstr "Modifica Documento"
+
+msgid "Change Inspection Plan"
+msgstr "Modifica Piano di Ispezione"
+
msgid "Change order"
msgstr "Ordine di modifica"
@@ -2283,6 +2322,9 @@ msgstr "Classe"
msgid "Class (inherited)"
msgstr "Classe (ereditata)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Classifica un'operazione di routing: le operazioni di Processo, Assemblaggio e Ispezione vengono eseguite nel tuo shop floor nel MES — Assemblaggio ottiene la vista di assemblaggio guidata e Ispezione un controllo qualità — mentre un'operazione di Lavorazione Esterna è subappaltata a un fornitore e crea un ordine di acquisto; il processo riporta lo stesso tipo e lo imposta di default sulle nuove operazioni."
+
msgid "Clean and approve the migrated data"
msgstr "Pulisci e approva i dati migrati"
@@ -2747,6 +2789,9 @@ msgstr "Converti i suggerimenti MRP in ordini di acquisto e commesse."
msgid "Convert to Quote"
msgstr "Converti in Preventivo"
+msgid "Converting…"
+msgstr "Conversione in corso…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converte l'unità di acquisto di un fornitore nella tua unità di inventario su una linea di ordine, ricevuta o fattura — acquista in scatole di 12, stoccaggio in unità singole."
@@ -3055,9 +3100,6 @@ msgstr "Crea Ordine di Modifica"
msgid "Create Issue"
msgstr "Crea Problema"
-msgid "Create Issue from Inspection"
-msgstr "Crea problema da ispezione"
-
msgid "Create Jobs"
msgstr "Crea Lavori"
@@ -3699,6 +3741,9 @@ msgstr "Priorità predefinita"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Conto GL di ricavo predefinito accreditato quando una fattura di vendita viene registrata."
+msgid "Default Sampling"
+msgstr "Campionamento predefinito"
+
msgid "Default shelf-life duration (days)"
msgstr "Durata predefinita della shelf-life (giorni)"
@@ -3741,9 +3786,6 @@ msgstr "Definisci prima un'operazione di produzione."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definire distinte base multi-livello e Bill of Process (metodi di produzione)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Definisce quante entità tracciate vengono ispezionate per lotto e quanti difetti sono tollerati prima che il lotto venga rifiutato."
-
msgid "Delete"
msgstr "Elimina"
@@ -3837,6 +3879,9 @@ msgstr "Elimina Gruppo"
msgid "Delete Holiday"
msgstr "Elimina Festività"
+msgid "Delete Inspection Plan"
+msgstr "Elimina Piano di Ispezione"
+
msgid "Delete Issue"
msgstr "Elimina Problema"
@@ -4329,6 +4374,9 @@ msgstr "Trascina per riordinare"
msgid "Drag to resize diagram and features"
msgstr "Trascinare per ridimensionare il diagramma e le funzioni"
+msgid "Drag to resize drawing and features"
+msgstr "Trascina per ridimensionare il disegno e le funzionalità"
+
msgid "Drag to zoom"
msgstr "Trascina per ingrandire"
@@ -4549,8 +4597,8 @@ msgstr "Modifica Gruppo"
msgid "Edit Holiday"
msgstr "Modifica Festività"
-msgid "Edit Inspection Document"
-msgstr "Modifica Documento di Ispezione"
+msgid "Edit Inspection Plan"
+msgstr "Modifica Piano di Ispezione"
msgid "Edit Item Group"
msgstr "Modifica Gruppo Articoli"
@@ -5236,6 +5284,9 @@ msgstr "Tag aggiuntivi per suddividere i tuoi report GL"
msgid "Fail"
msgstr "Non superato"
+msgid "Failed features"
+msgstr "Caratteristiche fallite"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (prima scadenza, prima uscita)"
@@ -5479,6 +5530,21 @@ msgstr "Impossibile salvare la regola di configurazione"
msgid "Failed to save diagram"
msgstr "Impossibile salvare il diagramma"
+msgid "Failed to save measurement"
+msgstr "Impossibile salvare la misurazione"
+
+msgid "Failed to save parts"
+msgstr "Errore nel salvataggio delle parti"
+
+msgid "Failed to save result"
+msgstr "Impossibile salvare il risultato"
+
+msgid "Failed to save slides"
+msgstr "Errore nel salvataggio delle diapositive"
+
+msgid "Failed to save tools"
+msgstr "Errore nel salvataggio degli strumenti"
+
msgid "Failed to update batch property"
msgstr "Impossibile aggiornare la proprietà batch"
@@ -6400,15 +6466,6 @@ msgstr "Le azioni inattive non appariranno negli elenchi di selezione"
msgid "Inbound inspection"
msgstr "Ispezione in entrata"
-msgid "Inbound Inspection"
-msgstr "Ispezione in ingresso"
-
-msgid "Inbound Inspections"
-msgstr "Ispezioni in Entrata"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Ispezioni in Entrata: Richiedi Ispettore Diverso"
-
msgid "Inbox"
msgstr "Posta in arrivo"
@@ -6454,6 +6511,12 @@ msgstr "Materiali e Servizi Indiretti (predefinito)"
msgid "Infrastructure"
msgstr "Infrastruttura"
+msgid "Inherit"
+msgstr "Eredita"
+
+msgid "Inherit document default"
+msgstr "Eredita il valore predefinito del documento"
+
msgid "Inherit From Materials"
msgstr "Eredita dai Materiali"
@@ -6490,32 +6553,35 @@ msgstr "Ispeziona i Primi N"
msgid "Inspect Item"
msgstr "Ispeziona Articolo"
-msgid "Inspect Next Item"
-msgstr "Ispeziona Elemento Successivo"
-
msgid "Inspection"
msgstr "Ispezione"
-msgid "Inspection Document"
-msgstr "Documento di Ispezione"
-
-msgid "Inspection Documents"
-msgstr "Documenti di Ispezione"
-
msgid "Inspection Level"
msgstr "Livello di Ispezione"
+msgid "Inspection Plan"
+msgstr "Piano di Ispezione"
+
+msgid "Inspection Plan Assignments"
+msgstr "Assegnazioni Piano di Ispezione"
+
+msgid "Inspection Plans"
+msgstr "Piani di Ispezione"
+
msgid "Inspection Status"
msgstr "Stato di Ispezione"
+msgid "Inspections"
+msgstr "Ispezioni"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Ispezioni, non conformità e CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Ispezioni, Non conformità, CAPA"
-msgid "Inspector"
-msgstr "Ispettore"
+msgid "Inspections: Require Different Inspector"
+msgstr "Ispezioni: Richiedi un Ispettore Diverso"
msgid "Install"
msgstr "Installa"
@@ -7439,15 +7505,9 @@ msgstr "Segna Come Completato"
msgid "Mark Light Mode"
msgstr "Marchio Modalità Chiara"
-msgid "Mark lot as partial?"
-msgstr "Contrassegnare il lotto come parziale?"
-
msgid "Mark not done"
msgstr "Segna come non completato"
-msgid "Mark Partial"
-msgstr "Contrassegna come parziale"
-
msgid "Mark scope as agreed"
msgstr "Contrassegna ambito come concordato"
@@ -7960,8 +8020,8 @@ msgstr "Nuova Festività"
msgid "New IC Transaction"
msgstr "Nuova Transazione IC"
-msgid "New Inspection Document"
-msgstr "Nuovo Documento di Ispezione"
+msgid "New Inspection Plan"
+msgstr "Nuovo Piano di Ispezione"
msgid "New Inventory Count"
msgstr "Nuovo Conteggio Inventario"
@@ -8332,6 +8392,9 @@ msgstr "Nessun gruppo assegnato"
msgid "No image"
msgstr "Nessuna immagine"
+msgid "No inspection plans"
+msgstr "Nessun piano di ispezione"
+
msgid "No issue types configured"
msgstr "Nessun tipo di problema configurato"
@@ -8392,6 +8455,9 @@ msgstr "Nessuna fonte padre registrata ancora. Fai clic su Ricalcola nella pagin
msgid "No part ID"
msgstr "Nessun ID parte"
+msgid "No parts"
+msgstr "Nessuna parte"
+
msgid "No payables"
msgstr "Nessun debito"
@@ -8428,6 +8494,9 @@ msgstr "Nessun motivo di mancata offerta"
msgid "No receivables"
msgstr "Nessun credito"
+msgid "No reference image"
+msgstr "Nessuna immagine di riferimento"
+
msgid "No remaining entities to inspect."
msgstr "Nessuna entità rimanente da ispezionare."
@@ -8443,9 +8512,6 @@ msgstr "Nessuna riga qui."
msgid "No rules assigned"
msgstr "Nessuna regola assegnata"
-msgid "No samples inspected yet."
-msgstr "Nessun campione ispezionato ancora."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Nessun numero unico e affidabile per l'inventario o lo stato del lavoro"
@@ -8464,6 +8530,12 @@ msgstr "Nessun fornitore ancora"
msgid "No time entries for this week"
msgstr "Nessuna registrazione oraria per questa settimana"
+msgid "No tools"
+msgstr "Nessuno strumento"
+
+msgid "No tools for this step"
+msgstr "Nessuno strumento per questo passaggio"
+
msgid "No transactions in this period"
msgstr "Nessuna transazione in questo periodo"
@@ -8773,6 +8845,9 @@ msgstr "Operazione"
msgid "Operation Order"
msgstr "Ordine Operazione"
+msgid "Operation Timer"
+msgstr "Timer operazione"
+
msgid "Operation Type"
msgstr "Tipo di operazione"
@@ -8900,6 +8975,9 @@ msgstr "Varianza Indiretta"
msgid "Over-applied by"
msgstr "Applicato in eccesso di"
+msgid "Overall result"
+msgstr "Risultato complessivo"
+
msgid "Overdue"
msgstr "Scaduto"
@@ -9027,9 +9105,6 @@ msgstr "Numero componente"
msgid "Part Supersession"
msgstr "Sostituzione Pezzo"
-msgid "Partial"
-msgstr "Parziale"
-
msgid "Partner"
msgstr "Partner"
@@ -9246,6 +9321,9 @@ msgstr "Pezzi/Ora"
msgid "Pieces/Minute"
msgstr "Pezzi/Minuto"
+msgid "Pin"
+msgstr "Fissa"
+
msgid "Pinned"
msgstr "Fissato"
@@ -9447,6 +9525,9 @@ msgstr "Data precedente"
msgid "Previous page"
msgstr "Pagina precedente"
+msgid "Previous step"
+msgstr "Passaggio precedente"
+
msgid "Price break actions"
msgstr "Azioni di scaglione di prezzo"
@@ -10138,9 +10219,6 @@ msgstr "Record eliminato"
msgid "Record inspections tied to a part and a job"
msgstr "Registra ispezioni collegate a una parte e a un lavoro"
-msgid "Record the inspection result for this sample."
-msgstr "Registra il risultato dell'ispezione per questo campione."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Registrato in una taratura che l'indicatore ha bisogno di riparazione prima che le sue letture possano essere affidabili."
@@ -10265,9 +10343,6 @@ msgstr "Rimuovi {label}"
msgid "Remove condition"
msgstr "Rimuovi condizione"
-msgid "Remove feature"
-msgstr "Rimuovi funzione"
-
msgid "Remove filter"
msgstr "Rimuovi filtro"
@@ -10286,12 +10361,21 @@ msgstr "Rimuovi ordine"
msgid "Remove pair"
msgstr "Rimuovi coppia"
+msgid "Remove part"
+msgstr "Rimuovi parte"
+
+msgid "Remove slide"
+msgstr "Rimuovi diapositiva"
+
msgid "Remove sort by column"
msgstr "Rimuovi ordinamento per colonna"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Rimuovi questo tipo di archiviazione da tutte le unità di archiviazione che lo referenziano ed eliminalo. Questa azione non può essere annullata."
+msgid "Remove tool"
+msgstr "Rimuovi strumento"
+
msgid "Removed"
msgstr "Rimosso"
@@ -10421,9 +10505,6 @@ msgstr "Richiede Azione"
msgid "Requires Adjustment"
msgstr "Richiede Regolazione"
-msgid "Requires Inspection"
-msgstr "Richiede Ispezione"
-
msgid "Requires Repair"
msgstr "Richiede Riparazione"
@@ -10444,7 +10525,7 @@ msgstr "Ripristina PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Reimposta PIN per {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Ripristina visualizzazione"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Uguale al registro"
msgid "Sample"
msgstr "Campione"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Campione {0}"
-
msgid "Sample Size"
msgstr "Dimensione del Campione"
-msgid "Sampling Plan"
-msgstr "Piano di Campionamento"
+msgid "Sampling"
+msgstr "Campionamento"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Campionamento — Funzionalità {featureLabel}"
msgid "Sampling Standard"
msgstr "Standard di Campionamento"
@@ -10852,8 +10932,8 @@ msgstr "Scansiona o inserisci numero di tracciamento"
msgid "Scan or search..."
msgstr "Scansiona o cerca..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Scansiona o seleziona un'entità tracciata da questo lotto e registra il risultato dell'ispezione."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scansiona o seleziona un'entità tracciata da questo lotto per aggiungerla come colonna di esempio, quindi registra il suo risultato nella griglia."
msgid "Scan the tracking ID for this line"
msgstr "Scansiona l'ID di tracciamento per questa riga"
@@ -10900,6 +10980,9 @@ msgstr "Ambiti"
msgid "Scrap"
msgstr "Scarto"
+msgid "Scrap / Cost of Quality"
+msgstr "Scarto / Costo della Qualità"
+
msgid "Scrap Percent"
msgstr "Percentuale di Scarto"
@@ -10960,6 +11043,9 @@ msgstr "Cerca Job"
msgid "Search operators..."
msgstr "Cerca operatori..."
+msgid "Search parts..."
+msgstr "Cerca parti…"
+
msgid "Search processes..."
msgstr "Cerca processi..."
@@ -10969,6 +11055,9 @@ msgstr "Cerca elementi correlati..."
msgid "Search suppliers..."
msgstr "Cerca fornitori..."
+msgid "Search tools..."
+msgstr "Cerca strumenti…"
+
msgid "Search..."
msgstr "Cerca..."
@@ -10990,6 +11079,9 @@ msgstr "Seleziona un assegnatario"
msgid "Select a default approver"
msgstr "Seleziona un approvatore predefinito"
+msgid "Select a document"
+msgstr "Seleziona un documento"
+
msgid "Select a new owner"
msgstr "Seleziona un nuovo proprietario"
@@ -11647,6 +11739,9 @@ msgstr "Consumo di Ricambi"
msgid "Spare Part Cost"
msgstr "Costo dei Ricambi"
+msgid "Spec"
+msgstr "Specifica"
+
msgid "Specific Customer"
msgstr "Cliente Specifico"
@@ -11777,6 +11872,12 @@ msgstr "passaggi"
msgid "Steps"
msgstr "Passaggi"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "I passaggi vengono ereditati dalle istruzioni di montaggio."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "I passaggi sono ereditati dal piano di ispezione."
+
msgid "Stock Transfer ID"
msgstr "ID Trasferimento Magazzino"
@@ -12470,8 +12571,8 @@ msgstr "Il flusso commerciale end-to-end dal preventivo del cliente alla riscoss
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "L'endpoint che riceve una richiesta POST con i dati aggiornati quando la tabella viene aggiornata"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Il disegno tecnico a cui è legato questo documento di ispezione; le ispezioni registrate rispetto a questo riferimento pezzo fanno riferimento a questo disegno."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Il disegno tecnico a cui è associato questo piano di ispezione; le ispezioni registrate rispetto a questa parte fanno riferimento a questo disegno."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "La percentuale attesa della produzione di questo articolo persa durante la produzione; la pianificazione moltiplica la domanda per 1 / (1 − scarto) per compensare."
@@ -12620,15 +12721,15 @@ msgstr "I loghi mostrati sui tuoi documenti stampati e inviati per email"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "L'identificatore di lotto per questo stock; una riga per lotto, la quantità è quella in mano per quel lotto."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Il lotto rimane aperto in modo da poter continuare l'ispezione e la disposizione in seguito. I risultati campionati vengono conservati."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Il lotto sarà contrassegnato come Superato. {fails} errore(i) campionato(i) sono registrati per i tuoi registri."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Il lotto sarà comunque rifiutato, ma non è possibile creare un NCR finché non è configurato almeno un tipo di problema."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "Il piano di campionamento per caratteristica del lotto sarà ri-risolto dal documento selezionato."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "L'importo minimo che questo fornitore addebiterà per questo processo, indipendentemente dalla quantità; i lavori al di sotto del volume di pareggio costano comunque almeno questo importo."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "La sequenza ordinata delle operazioni che un lavoro esegue, copiata dal distinta base dei processi del metodo."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Il file del modello originale non è più disponibile"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Il documento di contabilizzazione in uscita che estrae i beni da magazzino a un cliente, contabilizzando COGS mentre procede."
@@ -12719,8 +12820,8 @@ msgstr "Le persone del team Carbon che gestiranno la tua implementazione e come
msgid "The people on your team and their access to Carbon"
msgstr "Le persone del tuo team e il loro accesso a Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Il contatore per azienda dietro il numero leggibile di un tipo di documento, assemblando {prefix}{next+step, zero-padded}{suffix} e avanzando man mano che ogni documento viene creato."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Il contatore per azienda dietro il numero leggibile di un tipo di documento, che assembla il prefisso, il valore successivo riempito di zeri e il suffisso, e avanza quando ogni documento viene creato."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "L'esito per articolo registrato sul materiale interessato da una non-conformità — In sospeso, Reso al fornitore, Rielaborazione, Scarto o Usa così com'è — deciso per ogni lotto o seriale interessato individualmente."
@@ -13011,6 +13112,9 @@ msgstr "Queste informazioni verranno utilizzate nelle intestazioni dei documenti
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Queste informazioni saranno visibili a tutti gli utenti, quindi fai attenzione a ciò che condividi."
+msgid "this inspection plan"
+msgstr "questo piano di ispezione"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Questo è un elemento acquistato — non ha BoM/BoP; solo i suoi attributi e documenti possono cambiare."
@@ -13459,9 +13563,6 @@ msgstr "Tipo:"
msgid "Types"
msgstr "Tipi"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Le entità non campionate rimarranno In Sospeso in modo che tu possa continuare a ispezionare e disporre in seguito. I risultati campionati vengono conservati."
-
msgid "Unapplied"
msgstr "Non applicato"
@@ -14311,6 +14412,9 @@ msgstr "Se abilitato, gli attributi in questa categoria vengono visualizzati nel
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Se abilitato, i dipendenti possono modificare il valore di questo attributo nel proprio profilo; in caso contrario, solo gli amministratori possono farlo."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Se attivato, l'apertura di un'operazione avvia automaticamente il suo timer."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Se abilitato, le regole di prezzo (sconti in volume, promozioni) vengono comunque applicate in cima a questo override; se disabilitato, questo override è il prezzo finale."
@@ -14437,8 +14541,8 @@ msgstr "Se il conteggio del tempo inizia quando il processo scelto comincia o qu
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Se questo lotto/seriale supera l'ispezione (Pass) o non la supera (Fail); un Fail impedisce che la merce venga ricevuta nell'inventario disponibile."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Se questo processo viene eseguito su centri di lavoro interni (Inside), fornitori esterni (Outside) o entrambi (Both); mostra diversi campi a valle e modifica il modo in cui la pianificazione instrada questo processo."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Se questo processo viene eseguito su centri di lavoro interni (Processo, Assemblaggio o Ispezione) o presso fornitori esterni (Lavorazione Esterna); rivela diversi campi a valle, modifica il modo in cui i percorsi di pianificazione funzionano per questo processo, e imposta il tipo di operazione di default sulle nuove operazioni."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Se questo lavoro blocca la produzione (Inattivo), la degrada (Impatto), si trova in una finestra di tempo di inattività pianificata (Pianificato) o non ha impatto sulla produzione (Nessun Impatto); informa la pianificazione e la comunicazione dei tempi di inattività orientata al cliente."
@@ -14446,6 +14550,9 @@ msgstr "Se questo lavoro blocca la produzione (Inattivo), la degrada (Impatto),
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Se le autorizzazioni selezionate vengono Aggiunte sopra ciò che ogni utente ha già, o Aggiornate sostituendo il set di autorizzazioni di ogni utente con la selezione di seguito."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Quale documento gestisce ogni flusso di ispezione per questo articolo."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Quale evento di produzione avvia l'orologio della vita di magazzino — ad esempio, riempimento, sigillatura o QC finale."
@@ -14608,6 +14715,9 @@ msgstr "Conto di Cancellazione"
msgid "Write-off for {0}"
msgstr "Cancellazione per {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Eliminazione dei scorte scartate o restituite tramite rifiuti di ispezione e disposizioni NCR"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Ridurre il valore di un bene nel corso della sua vita utile — un batch mensile che crei, rivedi come bozza, quindi contabilizzi."
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 94655f03af..8ac1d20aef 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} di {1} completati"
msgid "{0} Scrapped"
msgstr "{0} Scartati"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} unità passate saranno completate."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} errore(i) campionato(i) registrato(i) e NON sarà(sarranno) completato(i) — risolvere(li) dal menu azioni."
+
msgid "About"
msgstr "Informazioni"
+msgid "Accept"
+msgstr "Accetta"
+
+msgid "Accept Lot"
+msgstr "Accetta Lotto"
+
+msgid "Accept lot?"
+msgstr "Accettare il lotto?"
+
msgid "Account Settings"
msgstr "Impostazioni Account"
@@ -66,12 +81,27 @@ msgstr "Aggiungi una stampante nelle impostazioni di stampa per stampare le etic
msgid "Add Inventory"
msgstr "Aggiungi Inventario"
+msgid "Add Sample"
+msgstr "Aggiungi Campione"
+
msgid "Add Spare Part"
msgstr "Aggiungi Ricambio"
msgid "All"
msgstr "Tutti"
+msgid "All rework"
+msgstr "Tutto rilavorazione"
+
+msgid "All scrap"
+msgstr "Tutto scarto"
+
+msgid "Allocate failed units"
+msgstr "Allocare unità non conformi"
+
+msgid "Allocate units"
+msgstr "Assegna unità"
+
msgid "Are you sure you want to delete this step?"
msgstr "Sei sicuro di voler eliminare questa fase?"
@@ -165,6 +195,12 @@ msgstr "Timbratura Uscita"
msgid "Clocked in since {0}"
msgstr "Timbrato in ingresso dalle {0}"
+msgid "Close"
+msgstr "Chiudi"
+
+msgid "Collapse features table"
+msgstr "Comprimi tabella funzionalità"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Completa"
msgid "Complete All"
msgstr "Completa tutto"
+msgid "Complete passed"
+msgstr "Completa passati"
+
msgid "Completed"
msgstr "Completato"
@@ -281,6 +320,9 @@ msgstr "Bozza"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Trascina e rilascia un file qui, o clicca per selezionare un file"
+msgid "Drag to resize drawing and features"
+msgstr "Trascinare per ridimensionare il disegno e le caratteristiche"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Trascinamento di {0} annullato."
@@ -325,6 +367,12 @@ msgstr "Errore"
msgid "Estimated"
msgstr "Stimato"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Ogni unità ha un verdetto: {passes} approvate e {fails} non approvate. Il lotto si chiude con ogni unità instradata al suo risultato."
+
+msgid "Expand features table"
+msgstr "Espandi tabella funzionalità"
+
msgid "Expired"
msgstr "Scaduto"
@@ -337,6 +385,12 @@ msgstr "Scade {date}"
msgid "Expiring first"
msgstr "Scadenza prima"
+msgid "Failed"
+msgstr "Non riuscito"
+
+msgid "Failed features"
+msgstr "Funzionalità non riuscite"
+
msgid "Failed to complete inventory adjustment"
msgstr "Impossibile completare la rettifica dell'inventario"
@@ -349,6 +403,12 @@ msgstr "Impossibile recuperare le operazioni attive"
msgid "Failed to fetch storageUnits"
msgstr "Impossibile recuperare le unità di archiviazione"
+msgid "Failed to save measurement"
+msgstr "Errore durante il salvataggio della misurazione"
+
+msgid "Failed to save result"
+msgstr "Errore durante il salvataggio del risultato"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Impossibile caricare il file: {0}"
@@ -356,6 +416,12 @@ msgstr "Impossibile caricare il file: {0}"
msgid "Failed to upload image"
msgstr "Impossibile caricare l'immagine"
+msgid "Feature"
+msgstr "Funzionalità"
+
+msgid "Features"
+msgstr "Caratteristiche"
+
msgid "File size exceeds 10MB limit"
msgstr "La dimensione del file supera il limite di 10MB"
@@ -405,6 +471,12 @@ msgstr "Imperiale"
msgid "In Progress"
msgstr "In Corso"
+msgid "Inspect Item"
+msgstr "Ispeziona Articolo"
+
+msgid "inspected"
+msgstr "ispezionato"
+
msgid "Insufficient quantity"
msgstr "Quantità insufficiente"
@@ -498,6 +570,9 @@ msgstr "Registra scarti per {0}"
msgid "Login"
msgstr "Accedi"
+msgid "Lot"
+msgstr "Lotto"
+
msgid "Machine"
msgstr "Macchina"
@@ -531,6 +606,9 @@ msgstr "Metrico"
msgid "Model"
msgstr "Modello"
+msgid "More actions"
+msgstr "Altre azioni"
+
msgid "More Actions"
msgstr "Altre azioni"
@@ -595,6 +673,9 @@ msgstr "Nessun file"
msgid "No Impact"
msgstr "Nessun Impatto"
+msgid "No issue types configured"
+msgstr "Nessun tipo di problema configurato"
+
msgid "No maintenance scheduled for today"
msgstr "Nessuna manutenzione programmata per oggi"
@@ -607,6 +688,9 @@ msgstr "Nessun materiale"
msgid "No open jobs"
msgstr "Nessun lavoro aperto"
+msgid "No open units to allocate"
+msgstr "Nessuna unità aperta da allocare"
+
msgid "No operators"
msgstr "Nessun operatore"
@@ -625,6 +709,9 @@ msgstr "Nessuna stampante configurata"
msgid "No recent operations"
msgstr "Nessuna operazione recente"
+msgid "No remaining entities to inspect."
+msgstr "Nessuna entità rimanente da ispezionare."
+
msgid "No results"
msgstr "Nessun risultato"
@@ -634,6 +721,9 @@ msgstr "Nessun risultato esistente"
msgid "No results found"
msgstr "Nessun risultato trovato"
+msgid "No samples required."
+msgstr "Nessun campione richiesto."
+
msgid "No scheduled time"
msgstr "Nessun orario programmato"
@@ -683,6 +773,9 @@ msgstr "Ops. Non dovresti vedere questa pagina. In futuro sarà una pagina di de
msgid "Open"
msgstr "Aperto"
+msgid "Open an NCR for MRB disposition"
+msgstr "Apri un NCR per la disposizione MRB"
+
msgid "Open Jobs"
msgstr "Lavori Aperti"
@@ -698,12 +791,21 @@ msgstr "Eseguito dall'Operatore"
msgid "Optional"
msgstr "Facoltativo"
+msgid "Overall result"
+msgstr "Risultato complessivo"
+
msgid "Parameters"
msgstr "Parametri"
msgid "Part"
msgstr "Componente"
+msgid "Partial"
+msgstr "Parziale"
+
+msgid "Partial Disposition"
+msgstr "Disposizione Parziale"
+
msgid "Passed Inspection"
msgstr "Ispezione Superata"
@@ -749,9 +851,6 @@ msgstr "Precedente"
msgid "Preventive"
msgstr "Preventivo"
-msgid "Previous"
-msgstr "Precedente"
-
msgid "Print"
msgstr "Stampa"
@@ -801,6 +900,18 @@ msgstr "Registra"
msgid "Record {0}"
msgstr "Registrazione {0}"
+msgid "Record only"
+msgstr "Solo registrazione"
+
+msgid "Record Partial"
+msgstr "Registra Parziale"
+
+msgid "Reject"
+msgstr "Rifiuta"
+
+msgid "Reject Lot"
+msgstr "Rifiuta Lotto"
+
msgid "Remove"
msgstr "Rimuovi"
@@ -813,12 +924,18 @@ msgstr "Rimuovi Inventario"
msgid "Remove part"
msgstr "Rimuovi componente"
+msgid "Result"
+msgstr "Risultato"
+
msgid "Rework"
msgstr "Rielaborazione"
msgid "Rework created successfully"
msgstr "Rework creato con successo"
+msgid "Rework quantity"
+msgstr "Quantità di rilavorazione"
+
msgid "Sales Order"
msgstr "Ordine di Vendita"
@@ -828,21 +945,33 @@ msgstr "Salva"
msgid "Scan"
msgstr "Scansiona"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Scansiona un'entità tracciata per aggiungere la prima colonna campione."
+
msgid "Scan or enter serial number"
msgstr "Scansiona o inserisci il numero di serie"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Scansiona o inserisci ID entità tracciata, numero di serie o lotto"
+
msgid "Scan or enter tracking number"
msgstr "Scansiona o inserisci numero di tracciamento"
msgid "Scan or search serial number..."
msgstr "Scansiona o cerca numero di serie..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Scansiona o seleziona un'entità tracciata da questo lotto per aggiungerla come colonna campione, quindi registra il suo risultato nella griglia."
+
msgid "Schedule"
msgstr "Pianificazione"
msgid "Scrap"
msgstr "Scarto"
+msgid "Scrap quantity"
+msgstr "Quantità di scarto"
+
msgid "Scrap Reason"
msgstr "Motivo Scarto"
@@ -876,6 +1005,9 @@ msgstr "Seleziona una quantità di scarto e il motivo"
msgid "Select a serial number to continue with this operation"
msgstr "Seleziona un numero di serie per continuare con questa operazione"
+msgid "Select an issue type"
+msgstr "Seleziona un tipo di problema"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Seleziona un articolo e specifica la quantità da prelevare"
@@ -899,6 +1031,9 @@ msgstr "Seleziona Numero di Serie"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Seleziona l'operazione a cui tornare. Tutte le operazioni da quel punto all'operazione corrente verranno ripetute."
+msgid "Selected"
+msgstr "Selezionato"
+
msgid "Send"
msgstr "Invia"
@@ -978,6 +1113,10 @@ msgstr "Utente Stazione"
msgid "Station: {stationName}"
msgstr "Stazione: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "L'accettazione statistica è fallita, quindi l'intero lotto di {0} è considerato non conforme (ISO 9001:2015 §8.7) — {passes} campione(i) superato(i) e {fails} guasto(i). Instradare le unità di seguito a scarto o rilavorazione, oppure registrare solo il verdetto."
+
msgid "Status"
msgstr "Stato"
@@ -1015,6 +1154,12 @@ msgstr "Etichetta"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "La quantità completata per questa operazione è inferiore alla quantità richiesta di {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Il lotto sarà contrassegnato come Superato e {remaining} unità/unità rimanente/i saranno completate in questa operazione."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Il lotto sarà comunque disposizionato, ma non è possibile creare un NCR finché non è configurato almeno un tipo di problema."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Ci sono materiali tracciati per numero di serie o lotto nella distinta base che non sono stati completamente prelevati. Completare senza prelevare potrebbe causare registrazioni di tracciabilità errate."
@@ -1048,6 +1193,9 @@ msgstr "Tempo totale: {0}"
msgid "Total: {0}"
msgstr "Totale: {0}"
+msgid "Tracked Entity"
+msgstr "Entità Tracciata"
+
msgid "Tracking"
msgstr "Tracciamento"
@@ -1070,6 +1218,9 @@ msgstr "Annulla prelievo {0}"
msgid "Unsaved changes"
msgstr "Modifiche non salvate"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Fino a {maxAllocatable} unità possono essere allocate; il resto viene registrato senza una registrazione."
+
msgid "Update"
msgstr "Aggiorna"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 3ecb7bf80c..1b429a4abe 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -725,6 +725,9 @@ msgstr "パラメータを追加"
msgid "Add Partner"
msgstr "パートナーを追加"
+msgid "Add parts"
+msgstr "部品を追加"
+
msgid "Add Permissions"
msgstr "権限を追加"
@@ -749,6 +752,9 @@ msgstr "リスクを追加"
msgid "Add rule"
msgstr "ルールを追加"
+msgid "Add Sample"
+msgstr "サンプルを追加"
+
msgid "Add Selector"
msgstr "セレクターを追加"
@@ -764,6 +770,9 @@ msgstr "スペアパーツを追加"
msgid "Add Step"
msgstr "ステップを追加"
+msgid "Add steps to preview the operator view."
+msgstr "オペレータビューをプレビューするステップを追加してください。"
+
msgid "Add Supplier"
msgstr "サプライヤーを追加"
@@ -776,6 +785,9 @@ msgstr "タイムカードを追加"
msgid "Add to stock for future use"
msgstr "将来の使用のためにストックに追加"
+msgid "Add tools"
+msgstr "ツールを追加"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "最初の{0}を追加"
@@ -1041,6 +1053,9 @@ msgstr "すべてに適用"
msgid "Applies to all work centers"
msgstr "すべてのワークセンターに適用"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "独自のルールがない機能に適用され、このプランが検査を実施する場合、ロットに適用されます。"
+
msgid "Apply"
msgstr "適用"
@@ -1401,8 +1416,11 @@ msgstr "この変更指示を削除してもよろしいですか?"
msgid "Are you sure you want to delete this gauge?"
msgstr "このゲージを削除してもよろしいですか?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "このインスペクションドキュメントを削除してもよろしいですか?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "この検査計画を削除しますか?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "このインスペクションプランを削除してもよろしいですか?この操作は取り消せません。"
msgid "Are you sure you want to delete this issue workflow?"
msgstr "このイシューワークフローを削除してもよろしいですか?"
@@ -1534,6 +1552,9 @@ msgstr "{0}権限を持つ管理者に最初の{1}を追加するよう依頼し
msgid "Assemblies"
msgstr "アセンブリ"
+msgid "Assembly Instruction"
+msgstr "組立指示"
+
msgid "Assembly Instructions"
msgstr "組立指示"
@@ -1678,6 +1699,12 @@ msgstr "自動生成されたQRコード"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "注文、ジョブ、部品などの自動採番形式"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "オペレータがMESの操作を開くときに自動的にタイマーを開始し、時間ログが最初からキャプチャされるようにします。"
+
+msgid "Auto-start timer on open"
+msgstr "開くときにタイマーを自動開始"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "需要に基づいて購買を自動提案し、再注文ポイントを設定"
@@ -1741,6 +1768,9 @@ msgstr "バランスが取れています"
msgid "Balloon"
msgstr "バルーン"
+msgid "Ballooned drawings with inspection features."
+msgstr "検査機能を持つ拡大図"
+
msgid "Bank - Cash"
msgstr "銀行-現金"
@@ -2094,6 +2124,9 @@ msgstr "アップロードできません — サプライヤーインタラク
msgid "Cannot upload to parts bucket without item ID"
msgstr "アイテムIDなしでパーツバケットにアップロードできません"
+msgid "Caption"
+msgstr "キャプション"
+
msgid "Carbon"
msgstr "カーボン"
@@ -2193,6 +2226,12 @@ msgstr "チャンピオン"
msgid "Change"
msgstr "変更"
+msgid "Change Document"
+msgstr "ドキュメント変更"
+
+msgid "Change Inspection Plan"
+msgstr "検査計画を変更"
+
msgid "Change order"
msgstr "変更オーダー"
@@ -2283,6 +2322,9 @@ msgstr "クラス"
msgid "Class (inherited)"
msgstr "クラス(継承)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "ルーティング操作を分類します:Process、Assembly、およびInspection操作はMESの自分のショップフロアで実行されます—Assemblyはガイド付きアセンブリビューを取得し、Inspectionは品質チェック—一方、Outside Processing操作はサプライヤーに下請けに出され、購買注文を作成します。プロセスは同じタイプを持ち、新しい操作のデフォルトになります。"
+
msgid "Clean and approve the migrated data"
msgstr "移行されたデータをクリーンアップして承認する"
@@ -2747,6 +2789,9 @@ msgstr "MRP提案を発注書とジョブに変換します。"
msgid "Convert to Quote"
msgstr "見積に変換"
+msgid "Converting…"
+msgstr "変換中…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "サプライヤーの購入単位をPO、領収書、または請求書行のインベントリ単位に変換します — 12個の箱で購入、個別にストック。"
@@ -3055,9 +3100,6 @@ msgstr "変更指示を作成"
msgid "Create Issue"
msgstr "問題を作成"
-msgid "Create Issue from Inspection"
-msgstr "検査から問題を作成"
-
msgid "Create Jobs"
msgstr "ジョブを作成"
@@ -3699,6 +3741,9 @@ msgstr "デフォルト優先度"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "売上請求書が転記されるときにクレジットされるデフォルト収益GLアカウント。"
+msgid "Default Sampling"
+msgstr "デフォルトサンプリング"
+
msgid "Default shelf-life duration (days)"
msgstr "デフォルト保管期間(日数)"
@@ -3741,9 +3786,6 @@ msgstr "最初に製造作業を定義します。"
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "複数レベルのBOMおよびプロセス表(製造方法)を定義する"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "ロットごとに検査される追跡対象エンティティの数と、ロットが却下される前に許容される失敗の数を定義します。"
-
msgid "Delete"
msgstr "削除"
@@ -3837,6 +3879,9 @@ msgstr "グループを削除"
msgid "Delete Holiday"
msgstr "休日を削除"
+msgid "Delete Inspection Plan"
+msgstr "検査計画を削除"
+
msgid "Delete Issue"
msgstr "問題を削除"
@@ -4329,6 +4374,9 @@ msgstr "ドラッグして並べ替え"
msgid "Drag to resize diagram and features"
msgstr "図と機能をリサイズするにはドラッグしてください"
+msgid "Drag to resize drawing and features"
+msgstr "ドラッグして図面と機能のサイズを変更してください"
+
msgid "Drag to zoom"
msgstr "ズームするにはドラッグしてください"
@@ -4549,8 +4597,8 @@ msgstr "グループを編集"
msgid "Edit Holiday"
msgstr "休日を編集"
-msgid "Edit Inspection Document"
-msgstr "検査文書を編集"
+msgid "Edit Inspection Plan"
+msgstr "検査計画を編集"
msgid "Edit Item Group"
msgstr "アイテムグループを編集"
@@ -5236,6 +5284,9 @@ msgstr "GL レポートをスライスするための追加タグ"
msgid "Fail"
msgstr "不合格"
+msgid "Failed features"
+msgstr "失敗した機能"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO(最先期限切れ先出法)"
@@ -5479,6 +5530,21 @@ msgstr "設定ルールの保存に失敗しました"
msgid "Failed to save diagram"
msgstr "図の保存に失敗しました"
+msgid "Failed to save measurement"
+msgstr "測定値の保存に失敗しました"
+
+msgid "Failed to save parts"
+msgstr "部品の保存に失敗しました"
+
+msgid "Failed to save result"
+msgstr "結果の保存に失敗しました"
+
+msgid "Failed to save slides"
+msgstr "スライドの保存に失敗しました"
+
+msgid "Failed to save tools"
+msgstr "ツールの保存に失敗しました"
+
msgid "Failed to update batch property"
msgstr "バッチプロパティの更新に失敗しました"
@@ -6400,15 +6466,6 @@ msgstr "非アクティブなアクションは選択リストに表示されま
msgid "Inbound inspection"
msgstr "受入検査"
-msgid "Inbound Inspection"
-msgstr "受け入れ検査"
-
-msgid "Inbound Inspections"
-msgstr "受け入れ検査"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "受入検査:異なる検査官が必要"
-
msgid "Inbox"
msgstr "受信トレイ"
@@ -6454,6 +6511,12 @@ msgstr "間接材料とサービス(デフォルト)"
msgid "Infrastructure"
msgstr "インフラストラクチャ"
+msgid "Inherit"
+msgstr "継承"
+
+msgid "Inherit document default"
+msgstr "ドキュメントのデフォルトを継承"
+
msgid "Inherit From Materials"
msgstr "材料から継承"
@@ -6490,32 +6553,35 @@ msgstr "最初のNを検査"
msgid "Inspect Item"
msgstr "検査項目"
-msgid "Inspect Next Item"
-msgstr "次のアイテムを検査"
-
msgid "Inspection"
msgstr "検査"
-msgid "Inspection Document"
-msgstr "検査ドキュメント"
-
-msgid "Inspection Documents"
-msgstr "検査ドキュメント"
-
msgid "Inspection Level"
msgstr "検査レベル"
+msgid "Inspection Plan"
+msgstr "検査計画"
+
+msgid "Inspection Plan Assignments"
+msgstr "検査計画の割り当て"
+
+msgid "Inspection Plans"
+msgstr "検査計画"
+
msgid "Inspection Status"
msgstr "検査ステータス"
+msgid "Inspections"
+msgstr "検査"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "検査、不適合、および是正予防措置"
msgid "Inspections, Nonconformance, CAPA"
msgstr "検査、不適合、CAPA"
-msgid "Inspector"
-msgstr "検査官"
+msgid "Inspections: Require Different Inspector"
+msgstr "検査:別の検査官が必要です"
msgid "Install"
msgstr "インストール"
@@ -7439,15 +7505,9 @@ msgstr "完了としてマーク"
msgid "Mark Light Mode"
msgstr "マークライトモード"
-msgid "Mark lot as partial?"
-msgstr "ロットを部分的にマークしますか?"
-
msgid "Mark not done"
msgstr "完了を取り消す"
-msgid "Mark Partial"
-msgstr "部分的にマーク"
-
msgid "Mark scope as agreed"
msgstr "スコープを合意済みとしてマーク"
@@ -7960,8 +8020,8 @@ msgstr "新しい休日"
msgid "New IC Transaction"
msgstr "新しいIC取引"
-msgid "New Inspection Document"
-msgstr "新しい検査文書"
+msgid "New Inspection Plan"
+msgstr "新しい検査計画"
msgid "New Inventory Count"
msgstr "新しい在庫数"
@@ -8332,6 +8392,9 @@ msgstr "グループが割り当てられていません"
msgid "No image"
msgstr "画像なし"
+msgid "No inspection plans"
+msgstr "検査計画がありません"
+
msgid "No issue types configured"
msgstr "問題タイプが設定されていません"
@@ -8392,6 +8455,9 @@ msgstr "親ソースはまだ記録されていません。計画ページの「
msgid "No part ID"
msgstr "パーツIDなし"
+msgid "No parts"
+msgstr "部品がありません"
+
msgid "No payables"
msgstr "支払い義務なし"
@@ -8428,6 +8494,9 @@ msgstr "見積なし理由"
msgid "No receivables"
msgstr "売掛金がありません"
+msgid "No reference image"
+msgstr "参照画像がありません"
+
msgid "No remaining entities to inspect."
msgstr "検査する残りのエンティティはありません。"
@@ -8443,9 +8512,6 @@ msgstr "ここに行はありません。"
msgid "No rules assigned"
msgstr "ルールが割り当てられていません"
-msgid "No samples inspected yet."
-msgstr "まだサンプルが検査されていません。"
-
msgid "No single, trusted number for inventory or job status"
msgstr "在庫またはジョブステータスの単一の信頼できる数値がない"
@@ -8464,6 +8530,12 @@ msgstr "まだサプライヤーがありません"
msgid "No time entries for this week"
msgstr "今週のタイムエントリがありません"
+msgid "No tools"
+msgstr "ツールがありません"
+
+msgid "No tools for this step"
+msgstr "このステップのツールがありません"
+
msgid "No transactions in this period"
msgstr "この期間に取引がありません"
@@ -8773,6 +8845,9 @@ msgstr "操作"
msgid "Operation Order"
msgstr "操作順序"
+msgid "Operation Timer"
+msgstr "操作タイマー"
+
msgid "Operation Type"
msgstr "操作タイプ"
@@ -8900,6 +8975,9 @@ msgstr "間接費差異"
msgid "Over-applied by"
msgstr "超過適用額"
+msgid "Overall result"
+msgstr "総合結果"
+
msgid "Overdue"
msgstr "期限超過"
@@ -9027,9 +9105,6 @@ msgstr "部品番号"
msgid "Part Supersession"
msgstr "パーツの廃止予定"
-msgid "Partial"
-msgstr "部分的"
-
msgid "Partner"
msgstr "パートナー"
@@ -9246,6 +9321,9 @@ msgstr "個/時間"
msgid "Pieces/Minute"
msgstr "個/分"
+msgid "Pin"
+msgstr "ピン"
+
msgid "Pinned"
msgstr "ピン留め"
@@ -9447,6 +9525,9 @@ msgstr "前の日付"
msgid "Previous page"
msgstr "前のページ"
+msgid "Previous step"
+msgstr "前のステップ"
+
msgid "Price break actions"
msgstr "価格ブレークアクション"
@@ -10138,9 +10219,6 @@ msgstr "レコード削除済み"
msgid "Record inspections tied to a part and a job"
msgstr "部品とジョブに関連付けられた検査を記録する"
-msgid "Record the inspection result for this sample."
-msgstr "このサンプルの検査結果を記録してください。"
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "キャリブレーション時に、ゲージの読み値を信頼できるようになる前に修理が必要であることが記録されました。"
@@ -10265,9 +10343,6 @@ msgstr "{label}を削除"
msgid "Remove condition"
msgstr "条件を削除"
-msgid "Remove feature"
-msgstr "機能を削除"
-
msgid "Remove filter"
msgstr "フィルターを削除"
@@ -10286,12 +10361,21 @@ msgstr "注文を削除"
msgid "Remove pair"
msgstr "ペアを削除"
+msgid "Remove part"
+msgstr "部品を削除"
+
+msgid "Remove slide"
+msgstr "スライドを削除"
+
msgid "Remove sort by column"
msgstr "列でソートを削除"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "このストレージタイプをすべての参照ストレージユニットから削除し、削除します。これは元に戻すことはできません。"
+msgid "Remove tool"
+msgstr "ツールを削除"
+
msgid "Removed"
msgstr "削除済み"
@@ -10421,9 +10505,6 @@ msgstr "対応が必要"
msgid "Requires Adjustment"
msgstr "調整が必要"
-msgid "Requires Inspection"
-msgstr "検査が必要"
-
msgid "Requires Repair"
msgstr "修理が必要"
@@ -10444,7 +10525,7 @@ msgstr "PINをリセット"
msgid "Reset PIN for {0} {1}"
msgstr "{0} {1}のPINをリセット"
-msgid "Reset View"
+msgid "Reset view"
msgstr "ビューをリセット"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "簿価と同じ"
msgid "Sample"
msgstr "サンプル"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "サンプル {0}"
-
msgid "Sample Size"
msgstr "サンプルサイズ"
-msgid "Sampling Plan"
-msgstr "サンプリング計画"
+msgid "Sampling"
+msgstr "サンプリング"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "サンプリング — 機能 {featureLabel}"
msgid "Sampling Standard"
msgstr "サンプリング標準"
@@ -10852,8 +10932,8 @@ msgstr "スキャンまたは追跡番号を入力"
msgid "Scan or search..."
msgstr "スキャンまたは検索..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "このロットから追跡対象エンティティをスキャンまたは選択し、検査結果を記録してください。"
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "このロットから追跡対象エンティティをスキャンまたは選択してサンプル列として追加し、グリッドにその結果を記録します。"
msgid "Scan the tracking ID for this line"
msgstr "このラインのトラッキングIDをスキャンしてください"
@@ -10900,6 +10980,9 @@ msgstr "スコープ"
msgid "Scrap"
msgstr "スクラップ"
+msgid "Scrap / Cost of Quality"
+msgstr "スクラップ / 品質コスト"
+
msgid "Scrap Percent"
msgstr "スクラップ率"
@@ -10960,6 +11043,9 @@ msgstr "ジョブを検索"
msgid "Search operators..."
msgstr "オペレーターを検索..."
+msgid "Search parts..."
+msgstr "部品を検索..."
+
msgid "Search processes..."
msgstr "プロセスを検索..."
@@ -10969,6 +11055,9 @@ msgstr "関連アイテムを検索..."
msgid "Search suppliers..."
msgstr "サプライヤーを検索..."
+msgid "Search tools..."
+msgstr "ツールを検索..."
+
msgid "Search..."
msgstr "検索..."
@@ -10990,6 +11079,9 @@ msgstr "担当者を選択"
msgid "Select a default approver"
msgstr "デフォルト承認者を選択"
+msgid "Select a document"
+msgstr "ドキュメントを選択"
+
msgid "Select a new owner"
msgstr "新しい所有者を選択"
@@ -11647,6 +11739,9 @@ msgstr "予備部品消費"
msgid "Spare Part Cost"
msgstr "スペアパーツコスト"
+msgid "Spec"
+msgstr "仕様"
+
msgid "Specific Customer"
msgstr "特定の顧客"
@@ -11777,6 +11872,12 @@ msgstr "ステップ"
msgid "Steps"
msgstr "ステップ"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "ステップは組立指示から継承されます。"
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "ステップは検査計画から継承されます。"
+
msgid "Stock Transfer ID"
msgstr "在庫移動ID"
@@ -12470,8 +12571,8 @@ msgstr "顧客への見積もりから支払い回収までのエンドツーエ
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "テーブルが更新されたときに、更新されたデータを含むPOSTリクエストを受け取るエンドポイント"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "このインスペクションドキュメントが結合されているエンジニアリング図面。この部品参照に対して記録された検査は、この図面を参照します。"
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "この検査計画が関連付けられているエンジニアリング図面。このパーツに対して記録された検査はこの図面を参照します。"
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "生産中に失われるこのアイテムの出力の予想パーセンテージ。計画は補償するために需要に1 / (1 −スクラップ)を乗じます。"
@@ -12620,15 +12721,15 @@ msgstr "印刷およびメール送信されたドキュメントに表示され
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "このストックのロット識別子。ロットごとに1行、数量はそのロットのオンハンドです。"
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "ロットは開いたままなので、検査を続けて後で処分できます。サンプリングされた結果は保持されます。"
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "ロットは合格とマークされます。{fails}件のサンプル不良が記録されます。"
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "ロットは引き続き却下されますが、少なくとも1つの問題タイプが設定されるまでNCRを作成することはできません。"
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "ロットの機能ごとのサンプリング計画は、選択されたドキュメントから再度解決されます。"
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "このサプライヤーがこのプロセスに対して請求する最低額(数量に関係なく)。損益分岐点以下のジョブもこの金額以上の費用がかかります。"
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "メソッドのプロセス一覧から コピーされた、ジョブが実行される操作の順序付きシーケンス。"
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "元のモデルファイルは利用できなくなりました"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "在庫から顧客に商品を取り出す発信転記文書。転記時にCOGSを転記します。"
@@ -12719,8 +12820,8 @@ msgstr "Carbonチーム側の実装を担当する人たちと、彼らへの連
msgid "The people on your team and their access to Carbon"
msgstr "チームのメンバーと Carbon へのアクセス権"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "ドキュメントタイプの判読可能な番号の背後にある会社ごとのカウンター、{prefix}{next+step, zero-padded}{suffix}を組み立て、各ドキュメントが作成されるたびに進みます。"
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "ドキュメント タイプの可読番号を生成する会社単位のカウンター。プレフィックス、ゼロパディングされた次の値、およびサフィックスを組み合わせて構成され、ドキュメントが作成されるたびに進行します。"
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "不適合の影響を受けた材料に記録される項目ごとの結果 — 保留中、サプライヤーへの返品、再加工、スクラップ、またはそのまま使用 — 影響を受けた各ロットまたはシリアルに対して個別に決定されます。"
@@ -13011,6 +13112,9 @@ msgstr "この情報はドキュメントヘッダーで使用されます"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "この情報はすべてのユーザーに表示されるため、共有する内容に注意してください。"
+msgid "this inspection plan"
+msgstr "この検査計画"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "これは購入アイテムです。BoM/BoP はありません。属性と文書のみ変更できます。"
@@ -13459,9 +13563,6 @@ msgstr "タイプ:"
msgid "Types"
msgstr "タイプ"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "未サンプリングされたエンティティは保留中のままになるため、検査を続けて後で処分できます。サンプリングされた結果は保持されます。"
-
msgid "Unapplied"
msgstr "未適用"
@@ -14311,6 +14412,9 @@ msgstr "有効にすると、このカテゴリーの属性がユーザーの公
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "有効にすると、従業員は自分のプロフィールでこのアトリビュートの値を編集できます。そうでない場合は、管理者のみが編集できます。"
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "有効の場合、操作を開くとそのタイマーが自動的に開始されます。"
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "有効にすると、価格設定ルール(ボリュームディスカウント、プロモーション)がこのオーバーライドの上に引き続き適用されます。無効にすると、このオーバーライドが最終価格です。"
@@ -14437,8 +14541,8 @@ msgstr "選択したプロセスの開始時にカウントを開始するか、
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "このロット/シリアルが検査に合格(Pass)するか不合格(Fail)になるか。Fail の場合、在庫が利用可能在庫として受け入れられなくなります。"
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "このプロセスを内部ワークセンター(Inside)、外部サプライヤー(Outside)、またはその両方(Both)のいずれで実行するか。下流の異なるフィールドが表示され、このプロセスの計画ルーティング方法が変わります。"
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "このプロセスが内部ワークセンター(Process、Assembly、またはInspection)で実行されるか、外部サプライヤー(Outside Processing)で実行されるか。異なるダウンストリームフィールドを表示し、このプロセスの計画ルートの動作方法を変更し、新しい操作のデフォルト操作タイプを設定します。"
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "この作業が生産をブロックするか(ダウン)、それを低下させるか(影響)、計画されたダウンタイムウィンドウ(計画)にあるか、または生産への影響がない(影響なし)。スケジューリングとカスタマーフェーシングダウンタイム通信に通知します。"
@@ -14446,6 +14550,9 @@ msgstr "この作業が生産をブロックするか(ダウン)、それを低
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "選択されたアクセス許可が各ユーザーが既に持っているものに追加されるか、または以下の選択で各ユーザーのアクセス許可セットを置き換えることで更新されるか。"
+msgid "Which document drives each inspection flow for this item."
+msgstr "このアイテムの各検査フローを駆動するドキュメント。"
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "どの製造イベントが保存期間時計を開始するか — たとえば、塗りつぶし、シール、または最終QC。"
@@ -14608,6 +14715,9 @@ msgstr "償却勘定"
msgid "Write-off for {0}"
msgstr "{0}の償却"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "検査不合格とNCR処置によってスクラップまたは返品された在庫の償却"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "資産の価値をその耐用年数にわたって削減する — 作成、ドラフトとしてレビュー、その後ポストするメンバッチ。"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index d9893790d6..f442381e53 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} / {1} 完了済み"
msgid "{0} Scrapped"
msgstr "{0} スクラップ"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions}個の合格ユニットが完了します。"
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails}件のサンプル不良が記録されており、完了されません — アクションメニューから対応してください。"
+
msgid "About"
msgstr "バージョン情報"
+msgid "Accept"
+msgstr "受け入れ"
+
+msgid "Accept Lot"
+msgstr "ロットを受け入れ"
+
+msgid "Accept lot?"
+msgstr "ロットを受け入れますか?"
+
msgid "Account Settings"
msgstr "アカウント設定"
@@ -66,12 +81,27 @@ msgstr "印刷設定でプリンターを追加して、ラベルを直接印刷
msgid "Add Inventory"
msgstr "在庫追加"
+msgid "Add Sample"
+msgstr "サンプルを追加"
+
msgid "Add Spare Part"
msgstr "スペアパーツを追加"
msgid "All"
msgstr "すべて"
+msgid "All rework"
+msgstr "すべて再加工"
+
+msgid "All scrap"
+msgstr "すべてスクラップ"
+
+msgid "Allocate failed units"
+msgstr "不合格ユニットを割り当てる"
+
+msgid "Allocate units"
+msgstr "ユニットを割り当てる"
+
msgid "Are you sure you want to delete this step?"
msgstr "このステップを削除してもよろしいですか?"
@@ -165,6 +195,12 @@ msgstr "退勤打刻"
msgid "Clocked in since {0}"
msgstr "{0} から出勤中"
+msgid "Close"
+msgstr "閉じる"
+
+msgid "Collapse features table"
+msgstr "機能テーブルを折りたたむ"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "完了"
msgid "Complete All"
msgstr "すべて完了"
+msgid "Complete passed"
+msgstr "完了済みを完了"
+
msgid "Completed"
msgstr "完了済み"
@@ -281,6 +320,9 @@ msgstr "下書き"
msgid "Drag and drop a file here, or click to select a file"
msgstr "ファイルをここにドラッグ&ドロップするか、クリックしてファイルを選択してください"
+msgid "Drag to resize drawing and features"
+msgstr "描画と機能をリサイズするためにドラッグします"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "{0} のドラッグがキャンセルされました。"
@@ -325,6 +367,12 @@ msgstr "エラー"
msgid "Estimated"
msgstr "見積"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "すべてのユニットに判定があります: {passes}件が合格し、{fails}件が不合格です。ロットは各ユニットが独自の結果にルーティングされて終了します。"
+
+msgid "Expand features table"
+msgstr "機能テーブルを展開"
+
msgid "Expired"
msgstr "期限切れ"
@@ -337,6 +385,12 @@ msgstr "有効期限 {date}"
msgid "Expiring first"
msgstr "最初に期限切れ"
+msgid "Failed"
+msgstr "失敗"
+
+msgid "Failed features"
+msgstr "失敗した機能"
+
msgid "Failed to complete inventory adjustment"
msgstr "在庫調整の完了に失敗しました"
@@ -349,6 +403,12 @@ msgstr "アクティブな工程の取得に失敗しました"
msgid "Failed to fetch storageUnits"
msgstr "storageUnitsの取得に失敗しました"
+msgid "Failed to save measurement"
+msgstr "測定の保存に失敗しました"
+
+msgid "Failed to save result"
+msgstr "結果の保存に失敗しました"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "ファイルのアップロードに失敗しました: {0}"
@@ -356,6 +416,12 @@ msgstr "ファイルのアップロードに失敗しました: {0}"
msgid "Failed to upload image"
msgstr "画像のアップロードに失敗しました"
+msgid "Feature"
+msgstr "機能"
+
+msgid "Features"
+msgstr "機能"
+
msgid "File size exceeds 10MB limit"
msgstr "ファイルサイズが10MBの制限を超えています"
@@ -405,6 +471,12 @@ msgstr "インペリアル"
msgid "In Progress"
msgstr "進行中"
+msgid "Inspect Item"
+msgstr "アイテムを検査"
+
+msgid "inspected"
+msgstr "検査済み"
+
msgid "Insufficient quantity"
msgstr "数量が不足しています"
@@ -498,6 +570,9 @@ msgstr "{0} のスクラップを記録"
msgid "Login"
msgstr "ログイン"
+msgid "Lot"
+msgstr "ロット"
+
msgid "Machine"
msgstr "機械"
@@ -531,6 +606,9 @@ msgstr "メートル法"
msgid "Model"
msgstr "モデル"
+msgid "More actions"
+msgstr "その他のアクション"
+
msgid "More Actions"
msgstr "その他のアクション"
@@ -595,6 +673,9 @@ msgstr "ファイルなし"
msgid "No Impact"
msgstr "影響なし"
+msgid "No issue types configured"
+msgstr "構成されたイシュータイプがありません"
+
msgid "No maintenance scheduled for today"
msgstr "本日のメンテナンス予定はありません"
@@ -607,6 +688,9 @@ msgstr "材料なし"
msgid "No open jobs"
msgstr "オープンなジョブはありません"
+msgid "No open units to allocate"
+msgstr "割り当てるオープンユニットがありません"
+
msgid "No operators"
msgstr "オペレーターなし"
@@ -625,6 +709,9 @@ msgstr "プリンターが設定されていません"
msgid "No recent operations"
msgstr "最近の工程はありません"
+msgid "No remaining entities to inspect."
+msgstr "検査するエンティティが残っていません。"
+
msgid "No results"
msgstr "結果なし"
@@ -634,6 +721,9 @@ msgstr "結果がありません"
msgid "No results found"
msgstr "結果が見つかりません"
+msgid "No samples required."
+msgstr "サンプルは必要ありません。"
+
msgid "No scheduled time"
msgstr "予定時間なし"
@@ -683,6 +773,9 @@ msgstr "このページは表示されないはずです。最終的にはラン
msgid "Open"
msgstr "未対応"
+msgid "Open an NCR for MRB disposition"
+msgstr "MRB処分用のNCRを開く"
+
msgid "Open Jobs"
msgstr "オープンジョブ"
@@ -698,12 +791,21 @@ msgstr "オペレーター実施"
msgid "Optional"
msgstr "オプション"
+msgid "Overall result"
+msgstr "全体的な結果"
+
msgid "Parameters"
msgstr "パラメーター"
msgid "Part"
msgstr "パーツ"
+msgid "Partial"
+msgstr "部分的"
+
+msgid "Partial Disposition"
+msgstr "部分的な処分"
+
msgid "Passed Inspection"
msgstr "検査合格"
@@ -749,9 +851,6 @@ msgstr "前へ"
msgid "Preventive"
msgstr "予防保全"
-msgid "Previous"
-msgstr "前へ"
-
msgid "Print"
msgstr "印刷"
@@ -801,6 +900,18 @@ msgstr "記録"
msgid "Record {0}"
msgstr "レコード {0}"
+msgid "Record only"
+msgstr "記録のみ"
+
+msgid "Record Partial"
+msgstr "部分的に記録"
+
+msgid "Reject"
+msgstr "却下"
+
+msgid "Reject Lot"
+msgstr "ロットを却下"
+
msgid "Remove"
msgstr "削除"
@@ -813,12 +924,18 @@ msgstr "在庫削除"
msgid "Remove part"
msgstr "パーツを削除"
+msgid "Result"
+msgstr "結果"
+
msgid "Rework"
msgstr "リワーク"
msgid "Rework created successfully"
msgstr "リワーク作成に成功しました"
+msgid "Rework quantity"
+msgstr "リワーク数量"
+
msgid "Sales Order"
msgstr "受注"
@@ -828,21 +945,33 @@ msgstr "保存"
msgid "Scan"
msgstr "スキャン"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "スキャンして追跡エンティティを追加し、最初のサンプル列を追加してください。"
+
msgid "Scan or enter serial number"
msgstr "シリアル番号をスキャンまたは入力"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "追跡エンティティID、シリアル番号、またはバッチをスキャンまたは入力してください"
+
msgid "Scan or enter tracking number"
msgstr "スキャンまたは追跡番号を入力"
msgid "Scan or search serial number..."
msgstr "シリアル番号をスキャンまたは検索..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "このロットから追跡エンティティをスキャンまたは選択してサンプル列として追加し、グリッドにその結果を記録してください。"
+
msgid "Schedule"
msgstr "スケジュール"
msgid "Scrap"
msgstr "廃棄"
+msgid "Scrap quantity"
+msgstr "スクラップ数量"
+
msgid "Scrap Reason"
msgstr "スクラップ理由"
@@ -876,6 +1005,9 @@ msgstr "スクラップ数量と理由を選択"
msgid "Select a serial number to continue with this operation"
msgstr "この工程を続行するシリアル番号を選択してください"
+msgid "Select an issue type"
+msgstr "イシュータイプを選択"
+
msgid "Select an item and specify the quantity to issue"
msgstr "品目を選択し、払出数量を指定してください"
@@ -899,6 +1031,9 @@ msgstr "シリアル番号を選択"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "戻る操作を選択してください。その時点から現在の操作までのすべての操作が再度実行されます。"
+msgid "Selected"
+msgstr "選択済み"
+
msgid "Send"
msgstr "送信"
@@ -978,6 +1113,10 @@ msgstr "ステーションユーザー"
msgid "Station: {stationName}"
msgstr "ステーション: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "統計的受け入れに失敗したため、{0}の全ロットは不適合と見なされます(ISO 9001:2015 §8.7) — {passes}件のサンプル合格と{fails}件の不合格。以下のユニットをスクラップまたは再加工にルーティングするか、判定のみを記録してください。"
+
msgid "Status"
msgstr "ステータス"
@@ -1015,6 +1154,12 @@ msgstr "タグ"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "この工程の完了数量が必要数量 {0} を下回っています。"
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "ロットは「合格」とマークされ、{remaining}個の残りユニットがこの工程で完了します。"
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "ロットは引き続き処分されますが、少なくとも1つの問題タイプが設定されるまでNCRを作成することはできません。"
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "部品表にシリアルまたはバッチ追跡対象の材料が完全に払い出されていません。払出なしで完了すると、トレーサビリティ記録が不正確になる可能性があります。"
@@ -1048,6 +1193,9 @@ msgstr "合計時間: {0}"
msgid "Total: {0}"
msgstr "合計: {0}"
+msgid "Tracked Entity"
+msgstr "追跡エンティティ"
+
msgid "Tracking"
msgstr "追跡"
@@ -1070,6 +1218,9 @@ msgstr "ピック解除 {0}"
msgid "Unsaved changes"
msgstr "未保存の変更"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "最大 {maxAllocatable} 個のユニットを割り当てることができます。残りは転記なしで記録されます。"
+
msgid "Update"
msgstr "更新"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 87f1dd9ef7..002880d097 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -725,6 +725,9 @@ msgstr "파라미터 추가"
msgid "Add Partner"
msgstr "파트너 추가"
+msgid "Add parts"
+msgstr "부품 추가"
+
msgid "Add Permissions"
msgstr "권한 추가"
@@ -749,6 +752,9 @@ msgstr "리스크 추가"
msgid "Add rule"
msgstr "규칙 추가"
+msgid "Add Sample"
+msgstr "샘플 추가"
+
msgid "Add Selector"
msgstr "선택자 추가"
@@ -764,6 +770,9 @@ msgstr "예비 부품 추가"
msgid "Add Step"
msgstr "단계 추가"
+msgid "Add steps to preview the operator view."
+msgstr "운영자 보기를 미리 보기 위해 단계를 추가하세요."
+
msgid "Add Supplier"
msgstr "공급업체 추가"
@@ -776,6 +785,9 @@ msgstr "근무기록 추가"
msgid "Add to stock for future use"
msgstr "향후 사용을 위해 재고에 추가"
+msgid "Add tools"
+msgstr "도구 추가"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "첫 {0}을(를) 추가하세요"
@@ -1041,6 +1053,9 @@ msgstr "전체에 적용"
msgid "Applies to all work centers"
msgstr "모든 작업장에 적용"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "자신의 규칙이 없는 기능과 이 계획이 검사를 실행할 때의 로트에 적용됩니다."
+
msgid "Apply"
msgstr "적용"
@@ -1401,8 +1416,11 @@ msgstr "이 변경주문을 삭제하시겠습니까?"
msgid "Are you sure you want to delete this gauge?"
msgstr "이 측정기를 삭제하시겠습니까?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "이 검사 문서를 삭제하시겠습니까?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "이 검사 계획을 삭제하시겠습니까?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "이 검사 계획을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "이 이슈 워크플로를 삭제하시겠습니까?"
@@ -1534,6 +1552,9 @@ msgstr "{0} 권한이 있는 관리자에게 첫 {1} 추가를 요청하세요."
msgid "Assemblies"
msgstr "조립품"
+msgid "Assembly Instruction"
+msgstr "조립 지시사항"
+
msgid "Assembly Instructions"
msgstr "조립 지침"
@@ -1678,6 +1699,12 @@ msgstr "자동 생성된 QR 코드"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "주문, 작업, 품목 등에 대한 자동 번호 매기기 형식"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "운영자가 MES에서 작업을 열 때 타이머를 자동으로 시작하여 시간 로그가 처음부터 기록되도록 합니다."
+
+msgid "Auto-start timer on open"
+msgstr "열 때 타이머 자동 시작"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "수요와 재주문점을 기반으로 구매를 자동 제안"
@@ -1741,6 +1768,9 @@ msgstr "균형"
msgid "Balloon"
msgstr "말풍선"
+msgid "Ballooned drawings with inspection features."
+msgstr "검사 기능이 표시된 주석 도면."
+
msgid "Bank - Cash"
msgstr "은행 - 현금"
@@ -2094,6 +2124,9 @@ msgstr "업로드할 수 없습니다 — 공급업체 상호작용이 아직
msgid "Cannot upload to parts bucket without item ID"
msgstr "품목 ID 없이는 품목 버킷에 업로드할 수 없습니다"
+msgid "Caption"
+msgstr "캡션"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "챔피언"
msgid "Change"
msgstr "변경"
+msgid "Change Document"
+msgstr "문서 변경"
+
+msgid "Change Inspection Plan"
+msgstr "검사 계획 변경"
+
msgid "Change order"
msgstr "변경 주문"
@@ -2283,6 +2322,9 @@ msgstr "클래스"
msgid "Class (inherited)"
msgstr "클래스(상속됨)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "라우팅 작업을 분류합니다: 프로세스, 어셈블리, 검사 작업은 MES의 자체 작업장에서 실행됩니다 — 어셈블리는 안내식 어셈블리 보기를 받고 검사는 품질 확인을 수행합니다 — 외부 처리 작업은 공급업체에 외주되며 구매 주문을 생성합니다; 프로세스는 동일한 유형을 가지며 새 작업에 기본값을 설정합니다."
+
msgid "Clean and approve the migrated data"
msgstr "마이그레이션된 데이터를 정리하고 승인하세요"
@@ -2747,6 +2789,9 @@ msgstr "MRP 제안을 구매주문 및 작업으로 전환합니다."
msgid "Convert to Quote"
msgstr "견적으로 전환"
+msgid "Converting…"
+msgstr "변환 중…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "구매주문, 입고, 청구서 라인에서 공급업체의 구매 단위를 귀사의 재고 단위로 변환합니다 — 12개들이 카톤으로 구매하고 낱개로 재고 관리."
@@ -3055,9 +3100,6 @@ msgstr "변경주문 생성"
msgid "Create Issue"
msgstr "이슈 생성"
-msgid "Create Issue from Inspection"
-msgstr "검사에서 이슈 생성"
-
msgid "Create Jobs"
msgstr "작업 생성"
@@ -3699,6 +3741,9 @@ msgstr "기본 우선순위"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "판매 인보이스가 전기될 때 대변에 기록되는 기본 수익 총계정원장 계정입니다."
+msgid "Default Sampling"
+msgstr "기본 샘플링"
+
msgid "Default shelf-life duration (days)"
msgstr "기본 유통기한(일)"
@@ -3741,9 +3786,6 @@ msgstr "먼저 제조 공정작업을 정의하세요."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "다단계 자재명세서(BOM)와 공정(BOP)을 정의하세요(제작 방법)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "로트당 검사할 추적 개체 수와, 로트가 반려되기 전 허용되는 불합격 수를 정의합니다."
-
msgid "Delete"
msgstr "삭제"
@@ -3837,6 +3879,9 @@ msgstr "그룹 삭제"
msgid "Delete Holiday"
msgstr "휴일 삭제"
+msgid "Delete Inspection Plan"
+msgstr "검사 계획 삭제"
+
msgid "Delete Issue"
msgstr "이슈 삭제"
@@ -4329,6 +4374,9 @@ msgstr "드래그하여 순서 변경"
msgid "Drag to resize diagram and features"
msgstr "드래그하여 다이어그램과 피처 크기 조정"
+msgid "Drag to resize drawing and features"
+msgstr "드래그하여 드로잉 및 기능의 크기를 조정"
+
msgid "Drag to zoom"
msgstr "드래그하여 확대/축소"
@@ -4549,8 +4597,8 @@ msgstr "그룹 수정"
msgid "Edit Holiday"
msgstr "휴일 수정"
-msgid "Edit Inspection Document"
-msgstr "검사 문서 수정"
+msgid "Edit Inspection Plan"
+msgstr "검사 계획 편집"
msgid "Edit Item Group"
msgstr "품목 그룹 수정"
@@ -5236,6 +5284,9 @@ msgstr "총계정원장 보고를 세분화하기 위한 추가 태그"
msgid "Fail"
msgstr "실패"
+msgid "Failed features"
+msgstr "부적합 특성"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "자산 클래스 생성 실패: {0}"
@@ -5479,6 +5530,21 @@ msgstr "설정 규칙을 저장하지 못했습니다"
msgid "Failed to save diagram"
msgstr "다이어그램을 저장하지 못했습니다"
+msgid "Failed to save measurement"
+msgstr "측정값 저장 실패"
+
+msgid "Failed to save parts"
+msgstr "부품 저장 실패"
+
+msgid "Failed to save result"
+msgstr "결과 저장 실패"
+
+msgid "Failed to save slides"
+msgstr "슬라이드 저장 실패"
+
+msgid "Failed to save tools"
+msgstr "도구 저장 실패"
+
msgid "Failed to update batch property"
msgstr "배치 속성을 업데이트하지 못했습니다"
@@ -6400,15 +6466,6 @@ msgstr "비활성 조치는 선택 목록에 표시되지 않습니다"
msgid "Inbound inspection"
msgstr "입고 검사"
-msgid "Inbound Inspection"
-msgstr "입고 검사"
-
-msgid "Inbound Inspections"
-msgstr "입고 검사"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "입고 검사: 다른 검사자 필요"
-
msgid "Inbox"
msgstr "받은함"
@@ -6454,6 +6511,12 @@ msgstr "간접 자재 및 서비스(기본값)"
msgid "Infrastructure"
msgstr "인프라"
+msgid "Inherit"
+msgstr "상속"
+
+msgid "Inherit document default"
+msgstr "문서 기본값 상속"
+
msgid "Inherit From Materials"
msgstr "자재로부터 상속"
@@ -6490,32 +6553,35 @@ msgstr "처음 N개 검사"
msgid "Inspect Item"
msgstr "품목 검사"
-msgid "Inspect Next Item"
-msgstr "다음 품목 검사"
-
msgid "Inspection"
msgstr "검사"
-msgid "Inspection Document"
-msgstr "검사 문서"
-
-msgid "Inspection Documents"
-msgstr "검사 문서"
-
msgid "Inspection Level"
msgstr "검사 수준"
+msgid "Inspection Plan"
+msgstr "검사 계획"
+
+msgid "Inspection Plan Assignments"
+msgstr "검사 계획 배정"
+
+msgid "Inspection Plans"
+msgstr "검사 계획"
+
msgid "Inspection Status"
msgstr "검사 상태"
+msgid "Inspections"
+msgstr "검사"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "검사, 부적합, CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "검사, 부적합, CAPA"
-msgid "Inspector"
-msgstr "검사자"
+msgid "Inspections: Require Different Inspector"
+msgstr "검사: 다른 검사자 필요"
msgid "Install"
msgstr "설치"
@@ -7439,15 +7505,9 @@ msgstr "완료 표시"
msgid "Mark Light Mode"
msgstr "라이트 모드로 표시"
-msgid "Mark lot as partial?"
-msgstr "로트를 부분 처리로 표시하시겠습니까?"
-
msgid "Mark not done"
msgstr "미완료로 표시"
-msgid "Mark Partial"
-msgstr "부분으로 표시"
-
msgid "Mark scope as agreed"
msgstr "범위를 합의됨으로 표시"
@@ -7960,8 +8020,8 @@ msgstr "신규 휴일"
msgid "New IC Transaction"
msgstr "신규 IC 거래"
-msgid "New Inspection Document"
-msgstr "신규 검사 문서"
+msgid "New Inspection Plan"
+msgstr "새 검사 계획"
msgid "New Inventory Count"
msgstr "신규 재고 실사"
@@ -8332,6 +8392,9 @@ msgstr "배정된 그룹이 없습니다"
msgid "No image"
msgstr "이미지 없음"
+msgid "No inspection plans"
+msgstr "검사 계획 없음"
+
msgid "No issue types configured"
msgstr "설정된 이슈 유형이 없습니다"
@@ -8392,6 +8455,9 @@ msgstr "아직 기록된 상위 소스가 없습니다. 계획 페이지에서
msgid "No part ID"
msgstr "품목 ID 없음"
+msgid "No parts"
+msgstr "부품 없음"
+
msgid "No payables"
msgstr "매입채무가 없습니다"
@@ -8428,6 +8494,9 @@ msgstr "견적 불가 사유"
msgid "No receivables"
msgstr "매출채권이 없습니다"
+msgid "No reference image"
+msgstr "참조 이미지 없음"
+
msgid "No remaining entities to inspect."
msgstr "검사할 개체가 남아 있지 않습니다."
@@ -8443,9 +8512,6 @@ msgstr "행이 없습니다."
msgid "No rules assigned"
msgstr "배정된 규칙이 없습니다"
-msgid "No samples inspected yet."
-msgstr "아직 검사된 샘플이 없습니다."
-
msgid "No single, trusted number for inventory or job status"
msgstr "재고나 작업 상태를 나타내는 신뢰할 수 있는 단일 수치가 없음"
@@ -8464,6 +8530,12 @@ msgstr "아직 공급업체가 없습니다"
msgid "No time entries for this week"
msgstr "이번 주 시간 기록이 없습니다"
+msgid "No tools"
+msgstr "도구 없음"
+
+msgid "No tools for this step"
+msgstr "이 단계에 도구 없음"
+
msgid "No transactions in this period"
msgstr "이 기간에 거래가 없습니다"
@@ -8773,6 +8845,9 @@ msgstr "공정작업"
msgid "Operation Order"
msgstr "공정작업 순서"
+msgid "Operation Timer"
+msgstr "작업 타이머"
+
msgid "Operation Type"
msgstr "공정작업 유형"
@@ -8900,6 +8975,9 @@ msgstr "외주 공정작업"
msgid "Over-applied by"
msgstr "초과 적용액"
+msgid "Overall result"
+msgstr "전체 결과"
+
msgid "Overdue"
msgstr "연체"
@@ -9027,9 +9105,6 @@ msgstr "부품 번호"
msgid "Part Supersession"
msgstr "부품 대체"
-msgid "Partial"
-msgstr "부분"
-
msgid "Partner"
msgstr "파트너"
@@ -9246,6 +9321,9 @@ msgstr "개/시간"
msgid "Pieces/Minute"
msgstr "개/분"
+msgid "Pin"
+msgstr "핀"
+
msgid "Pinned"
msgstr "고정됨"
@@ -9447,6 +9525,9 @@ msgstr "이전 날짜"
msgid "Previous page"
msgstr "이전 페이지"
+msgid "Previous step"
+msgstr "이전 단계"
+
msgid "Price break actions"
msgstr "가격 구간 작업"
@@ -10138,9 +10219,6 @@ msgstr "레코드가 삭제됨"
msgid "Record inspections tied to a part and a job"
msgstr "품목과 작업에 연결된 검사를 기록"
-msgid "Record the inspection result for this sample."
-msgstr "이 샘플의 검사 결과를 기록하세요."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "게이지의 읽음값을 신뢰하기 전에 수리가 필요하다는 것이 교정에 기록됨."
@@ -10265,9 +10343,6 @@ msgstr "제거 {label}"
msgid "Remove condition"
msgstr "조건 제거"
-msgid "Remove feature"
-msgstr "기능 제거"
-
msgid "Remove filter"
msgstr "필터 제거"
@@ -10286,12 +10361,21 @@ msgstr "주문 제거"
msgid "Remove pair"
msgstr "쌍 제거"
+msgid "Remove part"
+msgstr "부품 제거"
+
+msgid "Remove slide"
+msgstr "슬라이드 제거"
+
msgid "Remove sort by column"
msgstr "열 정렬 제거"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "이 저장 유형을 참조하는 모든 저장 단위에서 제거하고 삭제합니다. 이 작업은 되돌릴 수 없습니다."
+msgid "Remove tool"
+msgstr "도구 제거"
+
msgid "Removed"
msgstr "제거됨"
@@ -10421,9 +10505,6 @@ msgstr "조치 필요"
msgid "Requires Adjustment"
msgstr "조정 필요"
-msgid "Requires Inspection"
-msgstr "검사 필요"
-
msgid "Requires Repair"
msgstr "수리 필요"
@@ -10444,7 +10525,7 @@ msgstr "PIN 재설정"
msgid "Reset PIN for {0} {1}"
msgstr "{0} {1}의 PIN 재설정"
-msgid "Reset View"
+msgid "Reset view"
msgstr "보기 초기화"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "장부와 동일"
msgid "Sample"
msgstr "샘플"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "샘플 {0}"
-
msgid "Sample Size"
msgstr "샘플 크기"
-msgid "Sampling Plan"
-msgstr "샘플링 계획"
+msgid "Sampling"
+msgstr "샘플링"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "샘플링 — 기능 {featureLabel}"
msgid "Sampling Standard"
msgstr "샘플링 표준"
@@ -10852,8 +10932,8 @@ msgstr "추적 번호를 스캔하거나 입력하세요"
msgid "Scan or search..."
msgstr "스캔 또는 검색..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "이 로트에서 추적 개체를 스캔하거나 선택하고 검사 결과를 기록하세요."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "이 로트에서 추적 엔티티를 스캔하거나 선택하여 샘플 열로 추가한 후 그리드에 결과를 기록하세요."
msgid "Scan the tracking ID for this line"
msgstr "이 라인의 추적 ID를 스캔하세요"
@@ -10900,6 +10980,9 @@ msgstr "범위"
msgid "Scrap"
msgstr "스크랩"
+msgid "Scrap / Cost of Quality"
+msgstr "스크랩 / 품질 원가"
+
msgid "Scrap Percent"
msgstr "스크랩 비율"
@@ -10960,6 +11043,9 @@ msgstr "작업 검색"
msgid "Search operators..."
msgstr "작업자 검색..."
+msgid "Search parts..."
+msgstr "부품 검색..."
+
msgid "Search processes..."
msgstr "공정 검색..."
@@ -10969,6 +11055,9 @@ msgstr "관련 품목 검색..."
msgid "Search suppliers..."
msgstr "공급업체 검색..."
+msgid "Search tools..."
+msgstr "도구 검색..."
+
msgid "Search..."
msgstr "검색..."
@@ -10990,6 +11079,9 @@ msgstr "담당자 선택"
msgid "Select a default approver"
msgstr "기본 승인자 선택"
+msgid "Select a document"
+msgstr "문서 선택"
+
msgid "Select a new owner"
msgstr "새 소유자 선택"
@@ -11647,6 +11739,9 @@ msgstr "예비 부품 소모"
msgid "Spare Part Cost"
msgstr "예비 부품 비용"
+msgid "Spec"
+msgstr "사양"
+
msgid "Specific Customer"
msgstr "특정 고객"
@@ -11777,6 +11872,12 @@ msgstr "단계"
msgid "Steps"
msgstr "단계"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "단계는 조립 지시사항에서 상속됩니다."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "단계는 검사 계획에서 상속됩니다."
+
msgid "Stock Transfer ID"
msgstr "재고 이동 ID"
@@ -12470,8 +12571,8 @@ msgstr "고객 견적부터 대금 회수까지 이어지는 전체 상거래
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "테이블이 업데이트될 때 변경된 데이터를 담은 POST 요청을 수신하는 엔드포인트"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "이 검사 문서가 연결된 설계 도면입니다. 이 품목에 대해 기록되는 검사는 이 도면을 참조합니다."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "이 검사 계획이 연결된 엔지니어링 드로잉입니다. 이 부품에 대해 기록된 검사는 이 드로잉을 참조합니다."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "생산 중 손실될 것으로 예상되는 이 품목 산출물의 비율입니다. 계획은 이를 보정하기 위해 수요에 1 / (1 − 스크랩율)을 곱합니다."
@@ -12620,15 +12721,15 @@ msgstr "인쇄물 및 이메일 문서에 표시되는 로고"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "이 재고의 로트 식별자입니다. 배치당 한 행이며, 수량은 해당 로트의 보유 수량입니다."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "로트는 열린 상태로 유지되어 나중에 계속 검사하고 처리할 수 있습니다. 샘플링 결과는 그대로 보존됩니다."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "로트가 합격으로 표시됩니다. 기록을 위해 샘플링 불합격 {fails}건이 기록됩니다."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "로트는 그대로 반려되지만, 이슈 유형이 하나 이상 설정되기 전까지는 NCR을 생성할 수 없습니다."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "로트의 특성별 샘플링 계획이 선택된 문서에서 다시 결정됩니다."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "수량과 관계없이 이 공급업체가 이 공정에 청구하는 최소 금액입니다. 손익분기 수량 미만인 작업도 최소한 이 금액만큼 비용이 발생합니다."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "작업이 거쳐가는 공정작업의 순서로, 방법의 공정(BOP)에서 복사됩니다."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "원본 모델 파일을 더 이상 사용할 수 없습니다"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "재화를 재고에서 고객에게 출고시키는 출고 전표로, 진행되면서 매출원가(COGS)를 계상합니다."
@@ -12719,8 +12820,8 @@ msgstr "귀사의 도입을 진행할 Carbon 측 담당자와 연락 방법입
msgid "The people on your team and their access to Carbon"
msgstr "팀 구성원과 Carbon 접근 권한"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "문서 유형의 읽을 수 있는 번호 뒤의 회사별 카운터로, {prefix}{next+step, zero-padded}{suffix}를 조립하고 각 문서가 생성될 때마다 증가함."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "문서 유형의 식별 번호를 생성하는 회사별 카운터로, 접두사, 0으로 채워진 다음 번호, 그리고 접미사를 결합하여 번호를 만들고, 각 문서가 생성될 때마다 증가합니다."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "부적합에 영향을 받은 자재에 기록되는 항목별 결과 — 대기 중, 공급자에게 반환, 재작업, 폐기 또는 있는 그대로 사용 — 각 영향을 받은 로트 또는 시리얼에 대해 개별적으로 결정됨."
@@ -13011,6 +13112,9 @@ msgstr "이 정보는 문서 헤더에 사용됩니다"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "이 정보는 모든 사용자에게 표시되므로 공유하는 내용에 유의하세요."
+msgid "this inspection plan"
+msgstr "이 검사 계획"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "이것은 구매 항목입니다 — BoM/BoP가 없습니다. 해당 속성과 문서만 변경할 수 있습니다."
@@ -13459,9 +13563,6 @@ msgstr "유형:"
msgid "Types"
msgstr "유형"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "샘플링되지 않은 개체는 보류 상태로 유지되어 이후에도 계속 검사하고 처분을 결정할 수 있습니다. 샘플링된 결과는 그대로 유지됩니다."
-
msgid "Unapplied"
msgstr "미적용"
@@ -14311,6 +14412,9 @@ msgstr "켜면 이 카테고리의 속성이 사용자의 공개 프로필에
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "켜면 직원이 자신의 프로필에서 이 속성 값을 직접 수정할 수 있습니다. 끄면 관리자만 수정할 수 있습니다."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "켜져 있을 때, 작업을 열면 타이머가 자동으로 시작됩니다."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "켜면 가격 규칙(수량 할인, 프로모션)이 이 재정의 위에 계속 적용됩니다. 끄면 이 재정의가 최종 가격이 됩니다."
@@ -14437,8 +14541,8 @@ msgstr "선택한 공정이 시작될 때 시간을 측정할지, 완료될 때
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "이 로트/일련번호가 검사를 통과(합격)했는지 불합격했는지 여부로, 불합격 시 해당 재고는 사용 가능 재고로 입고되지 못합니다."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "이 공정이 내부 작업장(내부), 외부 공급업체(외부), 또는 둘 다(둘 다)에서 실행되는지 여부로, 이에 따라 하위 필드가 달라지고 계획에서 이 공정의 라우팅 방식이 변경됩니다."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "이 프로세스가 내부 작업 센터(프로세스, 어셈블리 또는 검사)에서 실행되는지 외부 공급업체(외부 처리)에서 실행되는지 여부; 다양한 다운스트림 필드를 표시하고, 이 프로세스에 대해 계획 경로가 작동하는 방식을 변경하며, 새 작업에서 작업 유형의 기본값을 설정합니다."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "이 작업이 생산을 중단시키는지(가동중단), 저하시키는지(영향), 계획된 가동중단 구간에 해당하는지(계획됨), 또는 생산에 영향이 없는지(영향 없음) 여부로, 일정 계획 및 고객 대상 가동중단 커뮤니케이션에 활용됩니다."
@@ -14446,6 +14550,9 @@ msgstr "이 작업이 생산을 중단시키는지(가동중단), 저하시키
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "선택한 권한을 각 사용자가 이미 가진 권한에 추가할지(추가), 아래 선택 항목으로 각 사용자의 권한 세트를 완전히 교체할지(업데이트) 여부입니다."
+msgid "Which document drives each inspection flow for this item."
+msgstr "이 항목에 대한 각 검사 흐름을 운영하는 문서입니다."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "유효기간 계산이 시작되는 제조 이벤트 — 예를 들어 충전, 밀봉, 또는 최종 품질검사."
@@ -14608,6 +14715,9 @@ msgstr "대손상각 계정"
msgid "Write-off for {0}"
msgstr "{0}에 대한 대손상각"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "검사 거부 및 NCR 처리를 통해 폐기되거나 반품된 재고의 상각"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "자산의 가치를 내용연수에 걸쳐 상각하는 것 — 매월 생성하여 초안으로 검토한 후 전기하는 배치 작업입니다."
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index 916ff27b8c..e45ce5e002 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -42,9 +42,24 @@ msgstr "{1} 중 {0} 완료됨"
msgid "{0} Scrapped"
msgstr "{0} 스크랩됨"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions}개의 합격 단위가 완료됩니다."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails}개의 샘플 불량이 기록되었으며 완료되지 않습니다 — 작업 메뉴에서 해결하세요."
+
msgid "About"
msgstr "정보"
+msgid "Accept"
+msgstr "수락"
+
+msgid "Accept Lot"
+msgstr "로트 수락"
+
+msgid "Accept lot?"
+msgstr "로트를 수락하시겠습니까?"
+
msgid "Account Settings"
msgstr "계정 설정"
@@ -66,12 +81,27 @@ msgstr "라벨을 직접 출력하려면 인쇄 설정에서 프린터를 추가
msgid "Add Inventory"
msgstr "재고 추가"
+msgid "Add Sample"
+msgstr "샘플 추가"
+
msgid "Add Spare Part"
msgstr "예비 부품 추가"
msgid "All"
msgstr "전체"
+msgid "All rework"
+msgstr "모두 재작업"
+
+msgid "All scrap"
+msgstr "모두 폐기"
+
+msgid "Allocate failed units"
+msgstr "실패한 단위 할당"
+
+msgid "Allocate units"
+msgstr "단위 할당"
+
msgid "Are you sure you want to delete this step?"
msgstr "이 단계를 삭제하시겠습니까?"
@@ -165,6 +195,12 @@ msgstr "퇴근"
msgid "Clocked in since {0}"
msgstr "{0}부터 출근 중"
+msgid "Close"
+msgstr "닫기"
+
+msgid "Collapse features table"
+msgstr "기능 테이블 축소"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "완료"
msgid "Complete All"
msgstr "모두 완료"
+msgid "Complete passed"
+msgstr "완료된 합격"
+
msgid "Completed"
msgstr "완료됨"
@@ -281,6 +320,9 @@ msgstr "초안"
msgid "Drag and drop a file here, or click to select a file"
msgstr "파일을 여기로 끌어다 놓거나 클릭하여 선택하세요"
+msgid "Drag to resize drawing and features"
+msgstr "그리기 및 기능 크기 조정하려면 드래그하세요"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "{0} 끌기가 취소되었습니다."
@@ -325,6 +367,12 @@ msgstr "오류"
msgid "Estimated"
msgstr "예상"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "모든 단위에 판정이 있습니다: {passes}개 합격 및 {fails}개 불합격. 로트는 각 단위가 자신의 결과로 라우팅되면서 종료됩니다."
+
+msgid "Expand features table"
+msgstr "기능 테이블 확장"
+
msgid "Expired"
msgstr "만료됨"
@@ -337,6 +385,12 @@ msgstr "{date}에 만료"
msgid "Expiring first"
msgstr "먼저 만료되는 순"
+msgid "Failed"
+msgstr "실패"
+
+msgid "Failed features"
+msgstr "실패한 기능"
+
msgid "Failed to complete inventory adjustment"
msgstr "재고 조정을 완료하지 못했습니다"
@@ -349,6 +403,12 @@ msgstr "진행 중인 공정작업을 불러오지 못했습니다"
msgid "Failed to fetch storageUnits"
msgstr "저장 단위를 불러오지 못했습니다"
+msgid "Failed to save measurement"
+msgstr "측정값 저장 실패"
+
+msgid "Failed to save result"
+msgstr "결과 저장 실패"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "파일을 업로드하지 못했습니다: {0}"
@@ -356,6 +416,12 @@ msgstr "파일을 업로드하지 못했습니다: {0}"
msgid "Failed to upload image"
msgstr "이미지를 업로드하지 못했습니다"
+msgid "Feature"
+msgstr "기능"
+
+msgid "Features"
+msgstr "기능"
+
msgid "File size exceeds 10MB limit"
msgstr "파일 크기가 10MB 제한을 초과했습니다"
@@ -405,6 +471,12 @@ msgstr "야드파운드법"
msgid "In Progress"
msgstr "진행 중"
+msgid "Inspect Item"
+msgstr "항목 검사"
+
+msgid "inspected"
+msgstr "검사됨"
+
msgid "Insufficient quantity"
msgstr "수량 부족"
@@ -498,6 +570,9 @@ msgstr "{0} 스크랩 기록"
msgid "Login"
msgstr "로그인"
+msgid "Lot"
+msgstr "로트"
+
msgid "Machine"
msgstr "기계"
@@ -531,6 +606,9 @@ msgstr "미터법"
msgid "Model"
msgstr "모델"
+msgid "More actions"
+msgstr "더 많은 작업"
+
msgid "More Actions"
msgstr "추가 작업"
@@ -595,6 +673,9 @@ msgstr "파일 없음"
msgid "No Impact"
msgstr "영향 없음"
+msgid "No issue types configured"
+msgstr "구성된 문제 유형이 없음"
+
msgid "No maintenance scheduled for today"
msgstr "오늘 예정된 유지보수가 없습니다"
@@ -607,6 +688,9 @@ msgstr "자재 없음"
msgid "No open jobs"
msgstr "진행 중인 작업이 없습니다"
+msgid "No open units to allocate"
+msgstr "할당할 열린 단위가 없습니다"
+
msgid "No operators"
msgstr "작업자 없음"
@@ -625,6 +709,9 @@ msgstr "설정된 프린터가 없습니다"
msgid "No recent operations"
msgstr "최근 공정작업이 없습니다"
+msgid "No remaining entities to inspect."
+msgstr "검사할 나머지 엔터티가 없습니다."
+
msgid "No results"
msgstr "결과 없음"
@@ -634,6 +721,9 @@ msgstr "결과가 없습니다"
msgid "No results found"
msgstr "결과가 없습니다"
+msgid "No samples required."
+msgstr "필요한 샘플이 없습니다."
+
msgid "No scheduled time"
msgstr "예정된 시간 없음"
@@ -683,6 +773,9 @@ msgstr "이런. 이 페이지가 보이면 안 됩니다. 나중에 랜딩 페
msgid "Open"
msgstr "열림"
+msgid "Open an NCR for MRB disposition"
+msgstr "MRB 처리를 위한 NCR 열기"
+
msgid "Open Jobs"
msgstr "진행 중인 작업"
@@ -698,12 +791,21 @@ msgstr "작업자 수행"
msgid "Optional"
msgstr "선택 사항"
+msgid "Overall result"
+msgstr "전체 결과"
+
msgid "Parameters"
msgstr "파라미터"
msgid "Part"
msgstr "품목"
+msgid "Partial"
+msgstr "부분"
+
+msgid "Partial Disposition"
+msgstr "부분 처리"
+
msgid "Passed Inspection"
msgstr "검사 합격"
@@ -749,9 +851,6 @@ msgstr "이전"
msgid "Preventive"
msgstr "예방"
-msgid "Previous"
-msgstr "이전"
-
msgid "Print"
msgstr "인쇄"
@@ -801,6 +900,18 @@ msgstr "기록"
msgid "Record {0}"
msgstr "{0} 기록"
+msgid "Record only"
+msgstr "기록만"
+
+msgid "Record Partial"
+msgstr "부분 기록"
+
+msgid "Reject"
+msgstr "거부"
+
+msgid "Reject Lot"
+msgstr "로트 거부"
+
msgid "Remove"
msgstr "제거"
@@ -813,12 +924,18 @@ msgstr "재고 제거"
msgid "Remove part"
msgstr "품목 제거"
+msgid "Result"
+msgstr "결과"
+
msgid "Rework"
msgstr "재작업"
msgid "Rework created successfully"
msgstr "재작업이 생성되었습니다"
+msgid "Rework quantity"
+msgstr "재작업 수량"
+
msgid "Sales Order"
msgstr "판매주문"
@@ -828,21 +945,33 @@ msgstr "저장"
msgid "Scan"
msgstr "스캔"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "추적된 엔터티를 스캔하여 첫 번째 샘플 열을 추가하세요."
+
msgid "Scan or enter serial number"
msgstr "일련번호를 스캔하거나 입력하세요"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "추적된 엔터티 ID, 일련번호 또는 배치를 스캔하거나 입력하세요"
+
msgid "Scan or enter tracking number"
msgstr "추적 번호를 스캔하거나 입력하세요"
msgid "Scan or search serial number..."
msgstr "일련번호를 스캔하거나 검색하세요..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "이 로트에서 추적된 엔터티를 스캔하거나 선택하여 샘플 열로 추가한 다음 그리드에 그 결과를 기록하세요."
+
msgid "Schedule"
msgstr "일정"
msgid "Scrap"
msgstr "스크랩"
+msgid "Scrap quantity"
+msgstr "폐기 수량"
+
msgid "Scrap Reason"
msgstr "스크랩 사유"
@@ -876,6 +1005,9 @@ msgstr "스크랩 수량과 사유를 선택하세요"
msgid "Select a serial number to continue with this operation"
msgstr "이 공정작업을 계속하려면 일련번호를 선택하세요"
+msgid "Select an issue type"
+msgstr "문제 유형 선택"
+
msgid "Select an item and specify the quantity to issue"
msgstr "품목을 선택하고 출고할 수량을 지정하세요"
@@ -899,6 +1031,9 @@ msgstr "일련번호 선택"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "되돌아갈 공정작업을 선택하세요. 해당 시점부터 현재 공정작업까지 모두 다시 진행됩니다."
+msgid "Selected"
+msgstr "선택됨"
+
msgid "Send"
msgstr "전송"
@@ -978,6 +1113,10 @@ msgstr "스테이션 사용자"
msgid "Station: {stationName}"
msgstr "스테이션: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "통계적 수용이 실패했으므로 {0}의 전체 로트는 부적합으로 간주됩니다(ISO 9001:2015 §8.7) — {passes}개의 샘플 합격 및 {fails}개의 불합격. 아래 단위를 스크랩 또는 재작업으로 라우팅하거나 판정만 기록하세요."
+
msgid "Status"
msgstr "상태"
@@ -1015,6 +1154,12 @@ msgstr "태그"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "이 공정작업의 완료 수량이 필요 수량 {0}보다 적습니다."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "로트가 합격으로 표시되고 {remaining}개의 남은 단위가 이 작업에서 완료됩니다."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "로트는 여전히 처리되지만 최소한 하나의 Issue Type이 구성될 때까지 NCR을 생성할 수 없습니다."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "자재명세서(BOM)에 아직 완전히 출고되지 않은 일련번호 또는 배치 추적 자재가 있습니다. 출고하지 않고 완료하면 이력추적 기록이 부정확해질 수 있습니다."
@@ -1048,6 +1193,9 @@ msgstr "총 시간: {0}"
msgid "Total: {0}"
msgstr "합계: {0}"
+msgid "Tracked Entity"
+msgstr "추적된 엔터티"
+
msgid "Tracking"
msgstr "추적"
@@ -1070,6 +1218,9 @@ msgstr "{0} 피킹 취소"
msgid "Unsaved changes"
msgstr "저장되지 않은 변경 사항"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "최대 {maxAllocatable}개 단위까지 할당할 수 있으며, 나머지는 전기 없이 기록됩니다."
+
msgid "Update"
msgstr "업데이트"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index f298b6d8d2..0e41a8c4fa 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -725,6 +725,9 @@ msgstr "Dodaj parametr"
msgid "Add Partner"
msgstr "Dodaj partnera"
+msgid "Add parts"
+msgstr "Dodaj części"
+
msgid "Add Permissions"
msgstr "Dodaj uprawnienia"
@@ -749,6 +752,9 @@ msgstr "Dodaj ryzyko"
msgid "Add rule"
msgstr "Dodaj regułę"
+msgid "Add Sample"
+msgstr "Dodaj próbkę"
+
msgid "Add Selector"
msgstr "Dodaj selektor"
@@ -764,6 +770,9 @@ msgstr "Dodaj część zamienną"
msgid "Add Step"
msgstr "Dodaj krok"
+msgid "Add steps to preview the operator view."
+msgstr "Dodaj kroki, aby wyświetlić podgląd widoku operatora."
+
msgid "Add Supplier"
msgstr "Dodaj dostawcę"
@@ -776,6 +785,9 @@ msgstr "Dodaj kartę czasu pracy"
msgid "Add to stock for future use"
msgstr "Dodaj do zapasów do przyszłego użytku"
+msgid "Add tools"
+msgstr "Dodaj narzędzia"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Dodaj swój pierwszy {0}"
@@ -1041,6 +1053,9 @@ msgstr "Dotyczy wszystkich"
msgid "Applies to all work centers"
msgstr "Dotyczy wszystkich centrów pracy"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Dotyczy funkcji bez własnej reguły oraz partii, gdy ten plan prowadzi inspekcję."
+
msgid "Apply"
msgstr "Zastosuj"
@@ -1401,8 +1416,11 @@ msgstr "Czy na pewno chcesz usunąć to zlecenie zmian?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Czy na pewno chcesz usunąć ten miernik?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Czy na pewno chcesz usunąć ten dokument inspekcji?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Czy na pewno chcesz usunąć ten plan inspekcji?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Czy na pewno chcesz usunąć ten plan inspekcji? Tej operacji nie można cofnąć."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Czy na pewno chcesz usunąć ten przepływ pracy problemu?"
@@ -1534,6 +1552,9 @@ msgstr "Poproś administratora z uprawnieniami {0} o dodanie pierwszego {1}."
msgid "Assemblies"
msgstr "Zespoły"
+msgid "Assembly Instruction"
+msgstr "Instrukcja montażu"
+
msgid "Assembly Instructions"
msgstr "Instrukcje montażu"
@@ -1678,6 +1699,12 @@ msgstr "Automatycznie generowany kod QR"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Formaty automatycznego numerowania dla zamówień, zadań, części i nie tylko"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Automatycznie uruchom timer operatora po otwarciu operacji w MES, aby dzienniki czasu były rejestrowane od początku."
+
+msgid "Auto-start timer on open"
+msgstr "Automatycznie uruchom timer przy otwarciu"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Automatycznie sugeruj zakupy na podstawie popytu i punktów ponownego zamówienia"
@@ -1741,6 +1768,9 @@ msgstr "Zrównoważone"
msgid "Balloon"
msgstr "Balon"
+msgid "Ballooned drawings with inspection features."
+msgstr "Rysunki z zaznaczeniami cech inspekcji."
+
msgid "Bank - Cash"
msgstr "Bank - Gotówka"
@@ -2094,6 +2124,9 @@ msgstr "Nie można przesłać — interakcja z dostawcą nie została jeszcze ut
msgid "Cannot upload to parts bucket without item ID"
msgstr "Nie można przesłać do zasobnika części bez identyfikatora elementu"
+msgid "Caption"
+msgstr "Podpis"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Mistrzowie"
msgid "Change"
msgstr "Zmień"
+msgid "Change Document"
+msgstr "Zmień dokument"
+
+msgid "Change Inspection Plan"
+msgstr "Zmień plan inspekcji"
+
msgid "Change order"
msgstr "Zmiana zamówienia"
@@ -2283,6 +2322,9 @@ msgstr "Klasa"
msgid "Class (inherited)"
msgstr "Klasa (odziedziczona)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Klasyfikuje operację routingu: operacje Proces, Montaż i Inspeksja działają na Twojej hali produkcyjnej w MES — Montaż wyświetla widok montażu z przewodnikiem, a Inspeksja sprawdzenie jakości — natomiast operacja Obróbka na zewnątrz jest zlecana dostawcy i tworzy zamówienie zakupu; proces nosi ten sam typ i ustawia go domyślnie dla nowych operacji."
+
msgid "Clean and approve the migrated data"
msgstr "Wyczyść i zatwierdź migrowane dane"
@@ -2747,6 +2789,9 @@ msgstr "Konwertuj sugestie MRP na zamówienia zakupu i zadania."
msgid "Convert to Quote"
msgstr "Konwertuj na Ofertę"
+msgid "Converting…"
+msgstr "Konwertowanie…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Konwertuje jednostkę zakupu dostawcy na jednostkę zapasów w wierszu zamówienia, paragonu lub faktury — kup w kartonach po 12 sztuk, magazyn w jednostkach."
@@ -3055,9 +3100,6 @@ msgstr "Utwórz Zlecenie Zmian"
msgid "Create Issue"
msgstr "Utwórz problem"
-msgid "Create Issue from Inspection"
-msgstr "Utwórz problem z inspekcji"
-
msgid "Create Jobs"
msgstr "Utwórz zadania"
@@ -3699,6 +3741,9 @@ msgstr "Priorytet domyślny"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Domyślne konto GL przychodu kredytowane po zaksięgowaniu faktury sprzedaży."
+msgid "Default Sampling"
+msgstr "Domyślne pobieranie próbek"
+
msgid "Default shelf-life duration (days)"
msgstr "Domyślny czas trwania przydatności (dni)"
@@ -3741,9 +3786,6 @@ msgstr "Najpierw zdefiniuj operację produkcyjną."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definiuj wielopoziomowe BOM i Bill of Process (metody produkcji)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Określa, ile śledzonych jednostek jest sprawdzanych na partię i ile błędów jest tolerowanych przed odrzuceniem partii."
-
msgid "Delete"
msgstr "Usuń"
@@ -3837,6 +3879,9 @@ msgstr "Usuń grupę"
msgid "Delete Holiday"
msgstr "Usuń Święto"
+msgid "Delete Inspection Plan"
+msgstr "Usuń plan inspekcji"
+
msgid "Delete Issue"
msgstr "Usuń Problem"
@@ -4329,6 +4374,9 @@ msgstr "Przeciągnij, aby zmienić kolejność"
msgid "Drag to resize diagram and features"
msgstr "Przeciągnij, aby zmienić rozmiar diagramu i funkcji"
+msgid "Drag to resize drawing and features"
+msgstr "Przeciągnij, aby zmienić rozmiar rysunku i funkcji"
+
msgid "Drag to zoom"
msgstr "Przeciągnij, aby powiększyć"
@@ -4549,8 +4597,8 @@ msgstr "Edytuj grupę"
msgid "Edit Holiday"
msgstr "Edytuj Święto"
-msgid "Edit Inspection Document"
-msgstr "Edytuj dokument inspekcji"
+msgid "Edit Inspection Plan"
+msgstr "Edytuj plan inspekcji"
msgid "Edit Item Group"
msgstr "Edytuj grupę pozycji"
@@ -5236,6 +5284,9 @@ msgstr "Dodatkowe tagi do dzielenia raportów GL"
msgid "Fail"
msgstr "Nie powiodło się"
+msgid "Failed features"
+msgstr "Cechy nie powiodły się"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (pierwsza data ważności, pierwsza wychodzi)"
@@ -5479,6 +5530,21 @@ msgstr "Nie udało się zapisać reguły konfiguracji"
msgid "Failed to save diagram"
msgstr "Nie udało się zapisać diagramu"
+msgid "Failed to save measurement"
+msgstr "Nie udało się zapisać pomiaru"
+
+msgid "Failed to save parts"
+msgstr "Nie udało się zapisać części"
+
+msgid "Failed to save result"
+msgstr "Nie udało się zapisać wyniku"
+
+msgid "Failed to save slides"
+msgstr "Nie udało się zapisać slajdów"
+
+msgid "Failed to save tools"
+msgstr "Nie udało się zapisać narzędzi"
+
msgid "Failed to update batch property"
msgstr "Nie udało się zaktualizować właściwości partii"
@@ -6400,15 +6466,6 @@ msgstr "Nieaktywne akcje nie będą wyświetlane na listach wyboru"
msgid "Inbound inspection"
msgstr "Inspekcja przychodząca"
-msgid "Inbound Inspection"
-msgstr "Inspekcja przychodząca"
-
-msgid "Inbound Inspections"
-msgstr "Inspekcje przychodzące"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Inspekcje przychodzące: Wymagaj innego inspektora"
-
msgid "Inbox"
msgstr "Skrzynka odbiorcza"
@@ -6454,6 +6511,12 @@ msgstr "Materiały Pośrednie i Usługi (domyślne)"
msgid "Infrastructure"
msgstr "Infrastruktura"
+msgid "Inherit"
+msgstr "Odziedzicz"
+
+msgid "Inherit document default"
+msgstr "Odziedzicz domyślne ustawienie dokumentu"
+
msgid "Inherit From Materials"
msgstr "Dziedzicz z Materiałów"
@@ -6490,32 +6553,35 @@ msgstr "Zbadaj Pierwsze N"
msgid "Inspect Item"
msgstr "Sprawdź element"
-msgid "Inspect Next Item"
-msgstr "Sprawdź następny element"
-
msgid "Inspection"
msgstr "Inspekcja"
-msgid "Inspection Document"
-msgstr "Dokument Inspekcji"
-
-msgid "Inspection Documents"
-msgstr "Dokumenty inspekcji"
-
msgid "Inspection Level"
msgstr "Poziom kontroli"
+msgid "Inspection Plan"
+msgstr "Plan inspekcji"
+
+msgid "Inspection Plan Assignments"
+msgstr "Przypisania planu inspekcji"
+
+msgid "Inspection Plans"
+msgstr "Plany inspekcji"
+
msgid "Inspection Status"
msgstr "Stan kontroli"
+msgid "Inspections"
+msgstr "Inspekcje"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspekcje, niezgodności i CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspekcje, Niezgodności, CAPA"
-msgid "Inspector"
-msgstr "Inspektor"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspekcje: Wymagaj innego inspektora"
msgid "Install"
msgstr "Zainstaluj"
@@ -7439,15 +7505,9 @@ msgstr "Oznacz jako Wykonane"
msgid "Mark Light Mode"
msgstr "Znak w trybie jasnym"
-msgid "Mark lot as partial?"
-msgstr "Oznaczyć partię jako częściową?"
-
msgid "Mark not done"
msgstr "Oznacz jako niezrobione"
-msgid "Mark Partial"
-msgstr "Oznacz jako częściowe"
-
msgid "Mark scope as agreed"
msgstr "Oznacz zakres jako uzgodniony"
@@ -7960,8 +8020,8 @@ msgstr "Nowe Święto"
msgid "New IC Transaction"
msgstr "Nowa Transakcja IC"
-msgid "New Inspection Document"
-msgstr "Nowy dokument inspekcji"
+msgid "New Inspection Plan"
+msgstr "Nowy plan inspekcji"
msgid "New Inventory Count"
msgstr "Nowa inwentaryzacja"
@@ -8332,6 +8392,9 @@ msgstr "Brak przypisanych grup"
msgid "No image"
msgstr "Brak obrazu"
+msgid "No inspection plans"
+msgstr "Brak planów inspekcji"
+
msgid "No issue types configured"
msgstr "Brak skonfigurowanych typów problemów"
@@ -8392,6 +8455,9 @@ msgstr "Brak zarejestrowanych źródeł nadrzędnych. Kliknij Przelicz na stroni
msgid "No part ID"
msgstr "Brak identyfikatora części"
+msgid "No parts"
+msgstr "Brak części"
+
msgid "No payables"
msgstr "Brak zobowiązań"
@@ -8428,6 +8494,9 @@ msgstr "Brak powodów oferty"
msgid "No receivables"
msgstr "Brak należności"
+msgid "No reference image"
+msgstr "Brak obrazu referencyjnego"
+
msgid "No remaining entities to inspect."
msgstr "Brak pozostałych jednostek do sprawdzenia."
@@ -8443,9 +8512,6 @@ msgstr "Brak wierszy tutaj."
msgid "No rules assigned"
msgstr "Brak przypisanych reguł"
-msgid "No samples inspected yet."
-msgstr "Brak próbek do sprawdzenia."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Brak jednej, zaufanej liczby dla zapasów lub statusu zadania"
@@ -8464,6 +8530,12 @@ msgstr "Brak dostawców"
msgid "No time entries for this week"
msgstr "Brak wpisów czasu pracy w tym tygodniu"
+msgid "No tools"
+msgstr "Brak narzędzi"
+
+msgid "No tools for this step"
+msgstr "Brak narzędzi dla tego kroku"
+
msgid "No transactions in this period"
msgstr "Brak transakcji w tym okresie"
@@ -8773,6 +8845,9 @@ msgstr "Operacja"
msgid "Operation Order"
msgstr "Kolejność operacji"
+msgid "Operation Timer"
+msgstr "Timer operacji"
+
msgid "Operation Type"
msgstr "Typ operacji"
@@ -8900,6 +8975,9 @@ msgstr "Odchylenie Kosztów Pośrednich"
msgid "Over-applied by"
msgstr "Przekroczone o"
+msgid "Overall result"
+msgstr "Ogólny wynik"
+
msgid "Overdue"
msgstr "Zaległy"
@@ -9027,9 +9105,6 @@ msgstr "Numer części"
msgid "Part Supersession"
msgstr "Zastąpienie części"
-msgid "Partial"
-msgstr "Częściowo"
-
msgid "Partner"
msgstr "Partner"
@@ -9246,6 +9321,9 @@ msgstr "Sztuk/Godzina"
msgid "Pieces/Minute"
msgstr "Sztuk/Minutę"
+msgid "Pin"
+msgstr "Przypnij"
+
msgid "Pinned"
msgstr "Przypięte"
@@ -9447,6 +9525,9 @@ msgstr "Poprzednia data"
msgid "Previous page"
msgstr "Poprzednia strona"
+msgid "Previous step"
+msgstr "Poprzedni krok"
+
msgid "Price break actions"
msgstr "Akcje podziału ceny"
@@ -10138,9 +10219,6 @@ msgstr "Rekord usunięty"
msgid "Record inspections tied to a part and a job"
msgstr "Rejestruj inspekcje powiązane z częścią i zadaniem"
-msgid "Record the inspection result for this sample."
-msgstr "Zarejestruj wynik inspekcji dla tej próbki."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Zanotowano podczas kalibracji, że przyrząd potrzebuje naprawy, zanim jego odczyty będą godne zaufania."
@@ -10178,7 +10256,7 @@ msgid "Refresh exchange rate"
msgstr "Odśwież kurs wymiany"
msgid "Regenerate"
-msgstr "Ponownie wygeneruj"
+msgstr "Regeneruj"
msgid "Regenerating thumbnail…"
msgstr "Ponownie generowanie miniatury…"
@@ -10265,9 +10343,6 @@ msgstr "Usuń {label}"
msgid "Remove condition"
msgstr "Usuń warunek"
-msgid "Remove feature"
-msgstr "Usuń funkcję"
-
msgid "Remove filter"
msgstr "Usuń filtr"
@@ -10286,12 +10361,21 @@ msgstr "Usuń zamówienie"
msgid "Remove pair"
msgstr "Usuń parę"
+msgid "Remove part"
+msgstr "Usuń część"
+
+msgid "Remove slide"
+msgstr "Usuń slajd"
+
msgid "Remove sort by column"
msgstr "Usuń sortowanie według kolumny"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Usuń ten typ magazynu ze wszystkich jednostek magazynowych, które się do niego odwołują, i usuń go. Tej operacji nie można cofnąć."
+msgid "Remove tool"
+msgstr "Usuń narzędzie"
+
msgid "Removed"
msgstr "Usunięte"
@@ -10421,9 +10505,6 @@ msgstr "Wymaga działania"
msgid "Requires Adjustment"
msgstr "Wymaga regulacji"
-msgid "Requires Inspection"
-msgstr "Wymaga inspekcji"
-
msgid "Requires Repair"
msgstr "Wymaga naprawy"
@@ -10444,7 +10525,7 @@ msgstr "Resetuj PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Resetuj PIN dla {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Resetuj widok"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Taki sam jak w księdze"
msgid "Sample"
msgstr "Próbka"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Próbka {0}"
-
msgid "Sample Size"
msgstr "Rozmiar próbki"
-msgid "Sampling Plan"
-msgstr "Plan próbkowania"
+msgid "Sampling"
+msgstr "Pobieranie próbek"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Pobieranie próbek — Funkcja {featureLabel}"
msgid "Sampling Standard"
msgstr "Standard pobierania próbek"
@@ -10852,8 +10932,8 @@ msgstr "Skanuj lub wpisz numer śledzenia"
msgid "Scan or search..."
msgstr "Skanuj lub wyszukaj..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Skanuj lub wybierz śledzony element z tej partii i zapisz wynik inspekcji."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Skanuj lub wybierz śledzoną jednostkę z tej partii, aby dodać ją jako kolumnę próbną, a następnie zanotuj jej wynik w siatce."
msgid "Scan the tracking ID for this line"
msgstr "Skanuj identyfikator śledzenia dla tej linii"
@@ -10900,6 +10980,9 @@ msgstr "Zakresy"
msgid "Scrap"
msgstr "Złom"
+msgid "Scrap / Cost of Quality"
+msgstr "Złom / Koszt jakości"
+
msgid "Scrap Percent"
msgstr "Procent odpadów"
@@ -10960,6 +11043,9 @@ msgstr "Szukaj zadania"
msgid "Search operators..."
msgstr "Wyszukaj operatory..."
+msgid "Search parts..."
+msgstr "Wyszukaj części..."
+
msgid "Search processes..."
msgstr "Szukaj procesów..."
@@ -10969,6 +11055,9 @@ msgstr "Szukaj powiązanych elementów..."
msgid "Search suppliers..."
msgstr "Szukaj dostawców..."
+msgid "Search tools..."
+msgstr "Wyszukaj narzędzia..."
+
msgid "Search..."
msgstr "Szukaj..."
@@ -10990,6 +11079,9 @@ msgstr "Wybierz osobę przydzieloną"
msgid "Select a default approver"
msgstr "Wybierz domyślnego zatwierdzającego"
+msgid "Select a document"
+msgstr "Wybierz dokument"
+
msgid "Select a new owner"
msgstr "Wybierz nowego właściciela"
@@ -11647,6 +11739,9 @@ msgstr "Zużycie części zamiennych"
msgid "Spare Part Cost"
msgstr "Koszt części zamiennych"
+msgid "Spec"
+msgstr "Specyfikacja"
+
msgid "Specific Customer"
msgstr "Konkretny klient"
@@ -11777,6 +11872,12 @@ msgstr "kroki"
msgid "Steps"
msgstr "Kroki"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Kroki są dziedziczone z instrukcji montażu."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Kroki są dziedziczone z planu inspekcji."
+
msgid "Stock Transfer ID"
msgstr "Identyfikator Transferu Zapasów"
@@ -12470,8 +12571,8 @@ msgstr "Przepływ handlowy end-to-end od wyceny klienta do zbierania płatności
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Punkt końcowy, który odbiera żądanie POST z zaktualizowanymi danymi, gdy tabela jest aktualizowana"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Rysunek techniczny, do którego powiązany jest ten dokument inspekcji; sprawdzenia zarejestrowane dla tego odwołania części odwołują się do tego rysunku."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Rysunek techniczny, do którego powiązany jest ten plan inspekcji; kontrole zarejestrowane dla tej części odnoszą się do tego rysunku."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "Oczekiwany procent produkcji tego artykułu utraconej podczas produkcji; planowanie mnoży zapotrzebowanie przez 1 / (1 − złom), aby skompensować."
@@ -12620,15 +12721,15 @@ msgstr "Logotypy wyświetlane na drukowanych i wysyłanych pocztą dokumentach"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "Identyfikator lotu dla tego magazynu; jeden wiersz na partię, ilość to wręcz dla tego lotu."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Partia pozostaje otwarta, aby można było kontynuować inspekcję i podjąć decyzję później. Wyniki próbek są zachowywane."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Lot zostanie oznaczony jako Zaakceptowany. {fails} próbkowanych niepowodzeń zostało zarejestrowanych dla Twoich rejestrów."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Partia będzie nadal odrzucona, ale nie można utworzyć NCR, dopóki nie zostanie skonfigurowany co najmniej jeden typ problemu."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "Plan pobierania próbek dla każdej cechy będzie ponownie ustalony na podstawie wybranego dokumentu."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Najniższa kwota, którą ten dostawca pobierze za ten proces, niezależnie od ilości; zadania poniżej wolumenu progu rentowności nadal kosztują co najmniej tę kwotę."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "Uporządkowana sekwencja operacji, przez którą przechodzi zadanie, skopiowana z listy procesów metody."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Oryginalny plik modelu nie jest już dostępny"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Dokument buchowania wychodzącego, który wyjmuje towary z magazynu do klienta, księgując COGS w drodze."
@@ -12719,8 +12820,8 @@ msgstr "Osoby ze strony Carbon, które będą prowadzić Twoją implementację,
msgid "The people on your team and their access to Carbon"
msgstr "Osoby w Twojej drużynie i ich dostęp do Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Licznik dla każdej firmy za czytelnym numerem typu dokumentu, montujący {prefix}{next+step, zero-padded}{suffix} i przesuwający się przy tworzeniu każdego dokumentu."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Licznik dedykowany każdej firmie, stanowiący podstawę czytelnego numeru typu dokumentu, łączący prefiks, zerami uzupełnioną następną wartość i sufiks, zwiększający się przy każdym utworzeniu dokumentu."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "Wynik na każdą pozycję zarejestrowany na zagrożonym materiale niezgodności — Oczekujące, Zwrot do dostawcy, Przeróbka, Złom lub Użyj tak, jak jest — ustalany dla każdej zagrożonej partii lub numeru seryjnego indywidualnie."
@@ -13011,6 +13112,9 @@ msgstr "Te informacje będą używane w nagłówkach dokumentów"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Te informacje będą widoczne dla wszystkich użytkowników, więc uważaj na to, co udostępniasz."
+msgid "this inspection plan"
+msgstr "ten plan inspekcji"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "To jest element nabywany — nie ma BoM/BoP; mogą zmieniać się tylko jego atrybuty i dokumenty."
@@ -13459,9 +13563,6 @@ msgstr "Typ:"
msgid "Types"
msgstr "Typy"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Nieprzetestowane jednostki pozostaną w stanie Wstrzymane, aby można było kontynuować inspekcję i podjąć decyzję później. Wyniki testowanych jednostek są zachowywane."
-
msgid "Unapplied"
msgstr "Niezastosowane"
@@ -14311,6 +14412,9 @@ msgstr "Gdy włączone, atrybuty w tej kategorii pojawiają się w profilu publi
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Gdy włączone, pracownicy mogą edytować wartość tego atrybutu w swoim własnym profilu; w przeciwnym razie mogą to zrobić tylko administratorzy."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Po włączeniu otwarcie operacji automatycznie uruchamia jej timer."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Gdy włączone, zasady ustalania cen (rabaty objętościowe, promocje) nadal mają zastosowanie na podstawie tego zastąpienia; gdy wyłączone, to zastąpienie jest ceną ostateczną."
@@ -14437,8 +14541,8 @@ msgstr "Czy licznik czasu rozpoczyna się, gdy wybrany proces się zaczyna, czy
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Czy ta partia/numer seryjny przechodzi kontrolę (Pass), czy ją oblewa (Fail); Fail blokuje przyjęcie zapasów do dostępnego magazynu."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Czy ten proces jest wykonywany w wewnętrznych gniazdach roboczych (Inside), u zewnętrznych dostawców (Outside) czy w obu (Both); ujawnia różne pola podrzędne i zmienia sposób, w jaki planowanie wyznacza marszruty dla tego procesu."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Czy ten proces odbywa się w wewnętrznych centrach pracy (Proces, Montaż lub Inspeksja) czy u zewnętrznych dostawców (Obróbka na zewnątrz); ujawnia różne pola podrzędne, zmienia sposób działania tras planowania dla tego procesu i ustawia domyślnie typ operacji dla nowych operacji."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Czy ta praca blokuje produkcję (W dół), ją degraduje (Wpływ), znajduje się w planowanym oknie czasu przestoju (Zaplanowane) lub nie ma wpływu na produkcję (Brak Wpływu); informuje planowanie i komunikację o przestojach skierowaną do klientów."
@@ -14446,6 +14550,9 @@ msgstr "Czy ta praca blokuje produkcję (W dół), ją degraduje (Wpływ), znajd
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Czy wybrane uprawnienia są Dodawane do tego, co każdy użytkownik już ma, czy Aktualizowane poprzez zastąpienie zestawu uprawnień każdego użytkownika poniższą selekcją."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Który dokument kieruje każdym przepływem kontroli dla tego produktu."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Które zdarzenie produkcyjne uruchamia zegar czasu przechowywania — na przykład napełnianie, uszczelnianie lub ostateczną kontrolę jakości."
@@ -14608,6 +14715,9 @@ msgstr "Konto Odpisu"
msgid "Write-off for {0}"
msgstr "Odpis dla {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Odpis zapasów złomowanych lub zwróconych przez odrzucenia kontroli i dyspozycje NCR"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Zmniejszanie wartości składnika aktywów w trakcie jego użyteczności — monta miesięczny, który tworzysz, przeglądam jako wersję roboczą, a następnie księgujesz."
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 30f750c6fc..c296335d19 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} z {1} ukończonych"
msgid "{0} Scrapped"
msgstr "{0} Odrzuconych"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} jednostka(e) przebiegła(y) zostanie(ą) ukończona(e)."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} zarejestrowanych niepowodzeń będzie NIEUKOŃCZONYCH — rozwiąż je z menu akcji."
+
msgid "About"
msgstr "O programie"
+msgid "Accept"
+msgstr "Akceptuj"
+
+msgid "Accept Lot"
+msgstr "Zaakceptuj partię"
+
+msgid "Accept lot?"
+msgstr "Zaakceptuj partię?"
+
msgid "Account Settings"
msgstr "Ustawienia konta"
@@ -66,12 +81,27 @@ msgstr "Dodaj drukarkę w ustawieniach drukowania, aby drukować etykiety bezpo
msgid "Add Inventory"
msgstr "Dodaj zapasy"
+msgid "Add Sample"
+msgstr "Dodaj próbkę"
+
msgid "Add Spare Part"
msgstr "Dodaj część zamienną"
msgid "All"
msgstr "Wszystkie"
+msgid "All rework"
+msgstr "Wszystkie przeróbki"
+
+msgid "All scrap"
+msgstr "Wszystko do złomu"
+
+msgid "Allocate failed units"
+msgstr "Przydziel jednostki z błędami"
+
+msgid "Allocate units"
+msgstr "Przydziel jednostki"
+
msgid "Are you sure you want to delete this step?"
msgstr "Czy na pewno chcesz usunąć ten krok?"
@@ -165,6 +195,12 @@ msgstr "Zakończ zmianę"
msgid "Clocked in since {0}"
msgstr "Zalogowany od {0}"
+msgid "Close"
+msgstr "Zamknij"
+
+msgid "Collapse features table"
+msgstr "Zwiń tabelę funkcji"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Ukończ"
msgid "Complete All"
msgstr "Uzupełnij wszystko"
+msgid "Complete passed"
+msgstr "Ukończ przebieg"
+
msgid "Completed"
msgstr "Ukończone"
@@ -281,6 +320,9 @@ msgstr "Szkic"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Przeciągnij i upuść plik tutaj lub kliknij, aby wybrać plik"
+msgid "Drag to resize drawing and features"
+msgstr "Przeciągnij, aby zmienić rozmiar rysunku i funkcji"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Przeciąganie {0} anulowane."
@@ -325,6 +367,12 @@ msgstr "Błąd"
msgid "Estimated"
msgstr "Szacowane"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Każda jednostka ma werdykt: {passes} zdane i {fails} niezdane. Partia zamyka się, a każda jednostka trafia do swojego wyniku."
+
+msgid "Expand features table"
+msgstr "Rozwiń tabelę funkcji"
+
msgid "Expired"
msgstr "Wygasło"
@@ -337,6 +385,12 @@ msgstr "Wygasa {date}"
msgid "Expiring first"
msgstr "Wygasające pierwsze"
+msgid "Failed"
+msgstr "Nieudane"
+
+msgid "Failed features"
+msgstr "Funkcje nie powiodły się"
+
msgid "Failed to complete inventory adjustment"
msgstr "Nie udało się zakończyć korekty zapasów"
@@ -349,6 +403,12 @@ msgstr "Nie udało się pobrać aktywnych operacji"
msgid "Failed to fetch storageUnits"
msgstr "Nie udało się pobrać jednostek magazynowych"
+msgid "Failed to save measurement"
+msgstr "Nie udało się zapisać pomiaru"
+
+msgid "Failed to save result"
+msgstr "Nie udało się zapisać wyniku"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Nie udało się przesłać pliku: {0}"
@@ -356,6 +416,12 @@ msgstr "Nie udało się przesłać pliku: {0}"
msgid "Failed to upload image"
msgstr "Nie udało się przesłać obrazu"
+msgid "Feature"
+msgstr "Funkcja"
+
+msgid "Features"
+msgstr "Cechy"
+
msgid "File size exceeds 10MB limit"
msgstr "Rozmiar pliku przekracza limit 10 MB"
@@ -405,6 +471,12 @@ msgstr "Imperialny"
msgid "In Progress"
msgstr "W toku"
+msgid "Inspect Item"
+msgstr "Zbadaj artykuł"
+
+msgid "inspected"
+msgstr "zbadane"
+
msgid "Insufficient quantity"
msgstr "Niewystarczająca ilość"
@@ -498,6 +570,9 @@ msgstr "Rejestruj odpad dla {0}"
msgid "Login"
msgstr "Zaloguj się"
+msgid "Lot"
+msgstr "Partia"
+
msgid "Machine"
msgstr "Maszyna"
@@ -531,6 +606,9 @@ msgstr "Metryczny"
msgid "Model"
msgstr "Model"
+msgid "More actions"
+msgstr "Więcej akcji"
+
msgid "More Actions"
msgstr "Więcej akcji"
@@ -595,6 +673,9 @@ msgstr "Brak plików"
msgid "No Impact"
msgstr "Brak wpływu"
+msgid "No issue types configured"
+msgstr "Nie skonfigurowano żadnych typów problemów"
+
msgid "No maintenance scheduled for today"
msgstr "Brak zaplanowanego utrzymania ruchu na dziś"
@@ -607,6 +688,9 @@ msgstr "Brak materiałów"
msgid "No open jobs"
msgstr "Brak otwartych zadań"
+msgid "No open units to allocate"
+msgstr "Brak otwartych jednostek do przydzielenia"
+
msgid "No operators"
msgstr "Brak operatorów"
@@ -625,6 +709,9 @@ msgstr "Brak skonfigurowanej drukarki"
msgid "No recent operations"
msgstr "Brak ostatnich operacji"
+msgid "No remaining entities to inspect."
+msgstr "Brak pozostałych encji do przebadania."
+
msgid "No results"
msgstr "Brak wyników"
@@ -634,6 +721,9 @@ msgstr "Brak wyników"
msgid "No results found"
msgstr "Nie znaleziono wyników"
+msgid "No samples required."
+msgstr "Nie wymagane żadne próbki."
+
msgid "No scheduled time"
msgstr "Brak zaplanowanego czasu"
@@ -683,6 +773,9 @@ msgstr "Ups. Nie powinieneś widzieć tej strony. Docelowo będzie to strona gł
msgid "Open"
msgstr "Otwarte"
+msgid "Open an NCR for MRB disposition"
+msgstr "Otwórz NCR dla dyspozycji MRB"
+
msgid "Open Jobs"
msgstr "Otwarte Zadania"
@@ -698,12 +791,21 @@ msgstr "Wykonane przez operatora"
msgid "Optional"
msgstr "Opcjonalnie"
+msgid "Overall result"
+msgstr "Wynik ogólny"
+
msgid "Parameters"
msgstr "Parametry"
msgid "Part"
msgstr "Część"
+msgid "Partial"
+msgstr "Częściowo"
+
+msgid "Partial Disposition"
+msgstr "Częściowa dyspozycja"
+
msgid "Passed Inspection"
msgstr "Inspekcja zaliczona"
@@ -749,9 +851,6 @@ msgstr "Poprzedni"
msgid "Preventive"
msgstr "Prewencyjne"
-msgid "Previous"
-msgstr "Poprzedni"
-
msgid "Print"
msgstr "Drukuj"
@@ -801,6 +900,18 @@ msgstr "Rejestruj"
msgid "Record {0}"
msgstr "Rekord {0}"
+msgid "Record only"
+msgstr "Tylko zarejestruj"
+
+msgid "Record Partial"
+msgstr "Zapisz częściowo"
+
+msgid "Reject"
+msgstr "Odrzuć"
+
+msgid "Reject Lot"
+msgstr "Odrzuć partię"
+
msgid "Remove"
msgstr "Usuń"
@@ -813,12 +924,18 @@ msgstr "Usuń zapasy"
msgid "Remove part"
msgstr "Usuń część"
+msgid "Result"
+msgstr "Wynik"
+
msgid "Rework"
msgstr "Przeróbka"
msgid "Rework created successfully"
msgstr "Przeróbka utworzona pomyślnie"
+msgid "Rework quantity"
+msgstr "Ilość do przeróbki"
+
msgid "Sales Order"
msgstr "Zamówienie sprzedaży"
@@ -828,21 +945,33 @@ msgstr "Zapisz"
msgid "Scan"
msgstr "Skanuj"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Zeskanuj śledzony element, aby dodać pierwszą kolumnę próbki."
+
msgid "Scan or enter serial number"
msgstr "Skanuj lub wprowadź numer seryjny"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Zeskanuj lub wprowadź ID elementu, numer seryjny lub numer partii"
+
msgid "Scan or enter tracking number"
msgstr "Skanuj lub wpisz numer śledzenia"
msgid "Scan or search serial number..."
msgstr "Skanuj lub wyszukaj numer seryjny..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Zeskanuj lub wybierz śledzony element z tej partii, aby dodać go jako kolumnę próbki, a następnie zaznacz jego wynik w siatce."
+
msgid "Schedule"
msgstr "Harmonogram"
msgid "Scrap"
msgstr "Złom"
+msgid "Scrap quantity"
+msgstr "Ilość złomu"
+
msgid "Scrap Reason"
msgstr "Przyczyna odrzutu"
@@ -876,6 +1005,9 @@ msgstr "Wybierz ilość odrzutu i przyczynę"
msgid "Select a serial number to continue with this operation"
msgstr "Wybierz numer seryjny, aby kontynuować tę operację"
+msgid "Select an issue type"
+msgstr "Wybierz typ problemu"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Wybierz pozycję i określ ilość do wydania"
@@ -899,6 +1031,9 @@ msgstr "Wybierz numer seryjny"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Wybierz operację, do której chcesz wrócić. Wszystkie operacje od tego punktu do bieżącej operacji będą powtórzone."
+msgid "Selected"
+msgstr "Wybrane"
+
msgid "Send"
msgstr "Wyślij"
@@ -978,6 +1113,10 @@ msgstr "Użytkownik stacji"
msgid "Station: {stationName}"
msgstr "Stacja: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "Statystyczna akceptacja nie powiodła się, dlatego cała partia {0} jest uważana za niezgodną (ISO 9001:2015 §8.7) — {passes} próbkowanych przejść i {fails} niepowodzenia. Skieruj jednostki poniżej do złomu lub przeróbki, lub tylko zarejestruj werdykt."
+
msgid "Status"
msgstr "Status"
@@ -1015,6 +1154,12 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "Ukończona ilość dla tej operacji jest mniejsza niż wymagana ilość {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Partia zostanie oznaczona jako Zaakceptowana i {remaining} pozostałych jednostek zostanie ukończonych w tej operacji."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Partia będzie nadal dyspozycjonowana, ale nie można utworzyć NCR, dopóki nie zostanie skonfigurowany co najmniej jeden typ problemu."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Na liście materiałowej znajdują się materiały śledzone seryjnie lub partiami, które nie zostały w pełni wydane. Ukończenie bez wydania może skutkować nieprawidłowymi rekordami śledzenia."
@@ -1048,6 +1193,9 @@ msgstr "Czas całkowity: {0}"
msgid "Total: {0}"
msgstr "Razem: {0}"
+msgid "Tracked Entity"
+msgstr "Śledzony element"
+
msgid "Tracking"
msgstr "Śledzenie"
@@ -1070,6 +1218,9 @@ msgstr "Cofnij {0}"
msgid "Unsaved changes"
msgstr "Niezapisane zmiany"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Do {maxAllocatable} jednostek(i) można przydzielić; reszta jest rejestrowana bez księgowania."
+
msgid "Update"
msgstr "Aktualizuj"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 29ba75418f..a1f54de7cc 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -725,6 +725,9 @@ msgstr "Adicionar Parâmetro"
msgid "Add Partner"
msgstr "Adicionar Parceiro"
+msgid "Add parts"
+msgstr "Adicionar peças"
+
msgid "Add Permissions"
msgstr "Adicionar Permissões"
@@ -749,6 +752,9 @@ msgstr "Adicionar Risco"
msgid "Add rule"
msgstr "Adicionar regra"
+msgid "Add Sample"
+msgstr "Adicionar Amostra"
+
msgid "Add Selector"
msgstr "Adicionar Seletor"
@@ -764,6 +770,9 @@ msgstr "Adicionar Peça de Reposição"
msgid "Add Step"
msgstr "Adicionar Etapa"
+msgid "Add steps to preview the operator view."
+msgstr "Adicione etapas para visualizar a visualização do operador."
+
msgid "Add Supplier"
msgstr "Adicionar Fornecedor"
@@ -776,6 +785,9 @@ msgstr "Adicionar Cartão de Ponto"
msgid "Add to stock for future use"
msgstr "Adicionar ao estoque para uso futuro"
+msgid "Add tools"
+msgstr "Adicionar ferramentas"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Adicione seu primeiro {0}"
@@ -1041,6 +1053,9 @@ msgstr "Aplica-se a todos"
msgid "Applies to all work centers"
msgstr "Aplica-se a todos os centros de trabalho"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Aplica-se a recursos sem sua própria regra e ao lote quando este plano conduz a uma inspeção."
+
msgid "Apply"
msgstr "Aplicar"
@@ -1401,8 +1416,11 @@ msgstr "Tem certeza que deseja deletar esta ordem de alteração?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Tem certeza de que deseja excluir este medidor?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Tem a certeza de que deseja eliminar este documento de inspeção?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Tem certeza que deseja excluir este plano de inspeção?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Tem a certeza de que deseja eliminar este plano de inspeção? Esta ação não pode ser desfeita."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Tem certeza de que deseja excluir este fluxo de trabalho de problema?"
@@ -1534,6 +1552,9 @@ msgstr "Peça a um administrador com permissão {0} para adicionar o primeiro {1
msgid "Assemblies"
msgstr "Montagens"
+msgid "Assembly Instruction"
+msgstr "Instrução de Montagem"
+
msgid "Assembly Instructions"
msgstr "Instruções de Montagem"
@@ -1678,6 +1699,12 @@ msgstr "Código QR gerado automaticamente"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Formatos de numeração automática para pedidos, trabalhos, peças e muito mais"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Auto-iniciar o cronômetro do operador quando ele abrir uma operação no MES para que os registros de tempo sejam capturados desde o início."
+
+msgid "Auto-start timer on open"
+msgstr "Auto-iniciar cronômetro ao abrir"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Sugerir automaticamente compras a partir da demanda e pontos de reabastecimento"
@@ -1741,6 +1768,9 @@ msgstr "Equilibrado"
msgid "Balloon"
msgstr "Balão"
+msgid "Ballooned drawings with inspection features."
+msgstr "Desenhos ampliados com recursos de inspeção."
+
msgid "Bank - Cash"
msgstr "Banco - Dinheiro"
@@ -2094,6 +2124,9 @@ msgstr "Não é possível fazer upload — interação com fornecedor ainda não
msgid "Cannot upload to parts bucket without item ID"
msgstr "Não é possível fazer upload para o bucket de peças sem ID do item"
+msgid "Caption"
+msgstr "Legenda"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "Campeões"
msgid "Change"
msgstr "Alterar"
+msgid "Change Document"
+msgstr "Alterar Documento"
+
+msgid "Change Inspection Plan"
+msgstr "Alterar Plano de Inspeção"
+
msgid "Change order"
msgstr "Ordem de mudança"
@@ -2283,6 +2322,9 @@ msgstr "Classe"
msgid "Class (inherited)"
msgstr "Classe (herdada)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Classifica uma operação de roteamento: operações de Processo, Montagem e Inspeção são executadas em seu próprio chão de fábrica no MES — Montagem obtém a visualização de montagem orientada e Inspeção uma verificação de qualidade — enquanto uma operação de Processamento Externo é subcontratada para um fornecedor e cria uma ordem de compra; o processo carrega o mesmo tipo e o define como padrão em novas operações."
+
msgid "Clean and approve the migrated data"
msgstr "Limpar e aprovar os dados migrados"
@@ -2747,6 +2789,9 @@ msgstr "Converta sugestões de MRP em pedidos de compra e tarefas."
msgid "Convert to Quote"
msgstr "Converter para Cotação"
+msgid "Converting…"
+msgstr "Convertendo…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converte a unidade de compra de um fornecedor para sua unidade de inventário em uma linha de pedido, recebimento ou fatura — compre em caixas de 12, estoque em unidades."
@@ -3055,9 +3100,6 @@ msgstr "Criar Ordem de Alteração"
msgid "Create Issue"
msgstr "Criar Problema"
-msgid "Create Issue from Inspection"
-msgstr "Criar Problema a partir da Inspeção"
-
msgid "Create Jobs"
msgstr "Criar Trabalhos"
@@ -3699,6 +3741,9 @@ msgstr "Prioridade Padrão"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Conta GL de receita padrão creditada quando uma fatura de venda é lançada."
+msgid "Default Sampling"
+msgstr "Amostragem Padrão"
+
msgid "Default shelf-life duration (days)"
msgstr "Duração padrão da vida útil (dias)"
@@ -3741,9 +3786,6 @@ msgstr "Defina primeiro uma operação de manufatura."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definir BOMs multi-nível e Bill of Process (métodos de fabricação)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Define quantas entidades rastreadas são inspecionadas por lote e quantas falhas são toleradas antes que o lote seja rejeitado."
-
msgid "Delete"
msgstr "Eliminar"
@@ -3837,6 +3879,9 @@ msgstr "Eliminar Grupo"
msgid "Delete Holiday"
msgstr "Excluir Feriado"
+msgid "Delete Inspection Plan"
+msgstr "Eliminar Plano de Inspeção"
+
msgid "Delete Issue"
msgstr "Eliminar Problema"
@@ -4329,6 +4374,9 @@ msgstr "Arrastar para reordenar"
msgid "Drag to resize diagram and features"
msgstr "Arraste para redimensionar diagrama e recursos"
+msgid "Drag to resize drawing and features"
+msgstr "Arraste para redimensionar desenho e recursos"
+
msgid "Drag to zoom"
msgstr "Arrastar para ampliar"
@@ -4549,8 +4597,8 @@ msgstr "Editar Grupo"
msgid "Edit Holiday"
msgstr "Editar Feriado"
-msgid "Edit Inspection Document"
-msgstr "Editar Documento de Inspeção"
+msgid "Edit Inspection Plan"
+msgstr "Editar Plano de Inspeção"
msgid "Edit Item Group"
msgstr "Editar Grupo de Itens"
@@ -5236,6 +5284,9 @@ msgstr "Tags extras para segmentar seus relatórios GL"
msgid "Fail"
msgstr "Falhar"
+msgid "Failed features"
+msgstr "Recursos com falha"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (primeiro a expirar, primeiro a sair)"
@@ -5479,6 +5530,21 @@ msgstr "Falha ao salvar regra de configuração"
msgid "Failed to save diagram"
msgstr "Falha ao salvar diagrama"
+msgid "Failed to save measurement"
+msgstr "Falha ao salvar medição"
+
+msgid "Failed to save parts"
+msgstr "Falha ao salvar peças"
+
+msgid "Failed to save result"
+msgstr "Falha ao salvar resultado"
+
+msgid "Failed to save slides"
+msgstr "Falha ao salvar slides"
+
+msgid "Failed to save tools"
+msgstr "Falha ao salvar ferramentas"
+
msgid "Failed to update batch property"
msgstr "Falha ao atualizar propriedade de lote"
@@ -6400,15 +6466,6 @@ msgstr "Ações inativas não aparecerão nas listas de seleção"
msgid "Inbound inspection"
msgstr "Inspeção de entrada"
-msgid "Inbound Inspection"
-msgstr "Inspeção de Entrada"
-
-msgid "Inbound Inspections"
-msgstr "Inspeções de Entrada"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Inspeções de Entrada: Exigir Inspetor Diferente"
-
msgid "Inbox"
msgstr "Caixa de entrada"
@@ -6454,6 +6511,12 @@ msgstr "Materiais Indiretos e Serviços (padrão)"
msgid "Infrastructure"
msgstr "Infraestrutura"
+msgid "Inherit"
+msgstr "Herdar"
+
+msgid "Inherit document default"
+msgstr "Herdar padrão do documento"
+
msgid "Inherit From Materials"
msgstr "Herdar de Materiais"
@@ -6490,32 +6553,35 @@ msgstr "Inspecionar o Primeiro N"
msgid "Inspect Item"
msgstr "Inspecionar Item"
-msgid "Inspect Next Item"
-msgstr "Inspecionar Próximo Item"
-
msgid "Inspection"
msgstr "Inspeção"
-msgid "Inspection Document"
-msgstr "Documento de Inspeção"
-
-msgid "Inspection Documents"
-msgstr "Documentos de Inspeção"
-
msgid "Inspection Level"
msgstr "Nível de Inspeção"
+msgid "Inspection Plan"
+msgstr "Plano de Inspeção"
+
+msgid "Inspection Plan Assignments"
+msgstr "Atribuições de Plano de Inspeção"
+
+msgid "Inspection Plans"
+msgstr "Planos de Inspeção"
+
msgid "Inspection Status"
msgstr "Status de Inspeção"
+msgid "Inspections"
+msgstr "Inspeções"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Inspeções, não conformidade e CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Inspeções, Não Conformidade, CAPA"
-msgid "Inspector"
-msgstr "Inspetor"
+msgid "Inspections: Require Different Inspector"
+msgstr "Inspeções: Exigir Inspetor Diferente"
msgid "Install"
msgstr "Instalar"
@@ -7439,15 +7505,9 @@ msgstr "Marcar Como Concluído"
msgid "Mark Light Mode"
msgstr "Marca Modo Claro"
-msgid "Mark lot as partial?"
-msgstr "Marcar lote como parcial?"
-
msgid "Mark not done"
msgstr "Marcar como não concluído"
-msgid "Mark Partial"
-msgstr "Marcar como Parcial"
-
msgid "Mark scope as agreed"
msgstr "Marcar escopo como acordado"
@@ -7960,8 +8020,8 @@ msgstr "Novo Feriado"
msgid "New IC Transaction"
msgstr "Nova Transação IC"
-msgid "New Inspection Document"
-msgstr "Novo Documento de Inspeção"
+msgid "New Inspection Plan"
+msgstr "Novo Plano de Inspeção"
msgid "New Inventory Count"
msgstr "Novo Inventário"
@@ -8332,6 +8392,9 @@ msgstr "Nenhum grupo atribuído"
msgid "No image"
msgstr "Sem imagem"
+msgid "No inspection plans"
+msgstr "Nenhum plano de inspeção"
+
msgid "No issue types configured"
msgstr "Nenhum tipo de problema configurado"
@@ -8392,6 +8455,9 @@ msgstr "Nenhuma fonte pai registrada ainda. Clique em Recalcular na página de p
msgid "No part ID"
msgstr "Sem ID de peça"
+msgid "No parts"
+msgstr "Nenhuma peça"
+
msgid "No payables"
msgstr "Sem contas a pagar"
@@ -8428,6 +8494,9 @@ msgstr "Sem Motivos de Cotação"
msgid "No receivables"
msgstr "Sem recebíveis"
+msgid "No reference image"
+msgstr "Nenhuma imagem de referência"
+
msgid "No remaining entities to inspect."
msgstr "Nenhuma entidade restante para inspecionar."
@@ -8443,9 +8512,6 @@ msgstr "Nenhuma linha aqui."
msgid "No rules assigned"
msgstr "Nenhuma regra atribuída"
-msgid "No samples inspected yet."
-msgstr "Nenhuma amostra inspecionada ainda."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Nenhum número único e confiável para inventário ou status do trabalho"
@@ -8464,6 +8530,12 @@ msgstr "Nenhum fornecedor ainda"
msgid "No time entries for this week"
msgstr "Sem registros de tempo para esta semana"
+msgid "No tools"
+msgstr "Nenhuma ferramenta"
+
+msgid "No tools for this step"
+msgstr "Nenhuma ferramenta para esta etapa"
+
msgid "No transactions in this period"
msgstr "Nenhuma transação neste período"
@@ -8773,6 +8845,9 @@ msgstr "Operação"
msgid "Operation Order"
msgstr "Ordem da Operação"
+msgid "Operation Timer"
+msgstr "Cronômetro de Operação"
+
msgid "Operation Type"
msgstr "Tipo de Operação"
@@ -8900,6 +8975,9 @@ msgstr "Variação de Despesas Gerais"
msgid "Over-applied by"
msgstr "Aplicado em excesso por"
+msgid "Overall result"
+msgstr "Resultado geral"
+
msgid "Overdue"
msgstr "Vencido"
@@ -9027,9 +9105,6 @@ msgstr "Número da Peça"
msgid "Part Supersession"
msgstr "Substituição de Peça"
-msgid "Partial"
-msgstr "Parcial"
-
msgid "Partner"
msgstr "Parceiro"
@@ -9246,6 +9321,9 @@ msgstr "Peças/Hora"
msgid "Pieces/Minute"
msgstr "Peças/Minuto"
+msgid "Pin"
+msgstr "Fixar"
+
msgid "Pinned"
msgstr "Fixado"
@@ -9447,6 +9525,9 @@ msgstr "Data Anterior"
msgid "Previous page"
msgstr "Página anterior"
+msgid "Previous step"
+msgstr "Etapa anterior"
+
msgid "Price break actions"
msgstr "Ações de quebra de preço"
@@ -10138,9 +10219,6 @@ msgstr "Registro eliminado"
msgid "Record inspections tied to a part and a job"
msgstr "Registar inspeções vinculadas a uma peça e um trabalho"
-msgid "Record the inspection result for this sample."
-msgstr "Registre o resultado da inspeção para esta amostra."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Registrado em uma calibração que o medidor precisa de reparo antes de suas leituras poderem ser confiáveis."
@@ -10265,9 +10343,6 @@ msgstr "Remover {label}"
msgid "Remove condition"
msgstr "Remover condição"
-msgid "Remove feature"
-msgstr "Remover recurso"
-
msgid "Remove filter"
msgstr "Remover filtro"
@@ -10286,12 +10361,21 @@ msgstr "Remover pedido"
msgid "Remove pair"
msgstr "Remover par"
+msgid "Remove part"
+msgstr "Remover peça"
+
+msgid "Remove slide"
+msgstr "Remover slide"
+
msgid "Remove sort by column"
msgstr "Remover ordenação por coluna"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Remova este tipo de armazenamento de todas as unidades de armazenamento que o referenciam e o delete. Isto não pode ser desfeito."
+msgid "Remove tool"
+msgstr "Remover ferramenta"
+
msgid "Removed"
msgstr "Removido"
@@ -10421,9 +10505,6 @@ msgstr "Requer Ação"
msgid "Requires Adjustment"
msgstr "Requer Ajuste"
-msgid "Requires Inspection"
-msgstr "Requer Inspeção"
-
msgid "Requires Repair"
msgstr "Requer Reparo"
@@ -10444,8 +10525,8 @@ msgstr "Redefinir PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Redefinir PIN para {0} {1}"
-msgid "Reset View"
-msgstr "Redefinir Visualização"
+msgid "Reset view"
+msgstr "Repor vista"
msgid "Residual value"
msgstr "Valor residual"
@@ -10797,15 +10878,14 @@ msgstr "Igual ao livro"
msgid "Sample"
msgstr "Amostra"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Amostra {0}"
-
msgid "Sample Size"
msgstr "Tamanho da Amostra"
-msgid "Sampling Plan"
-msgstr "Plano de Amostragem"
+msgid "Sampling"
+msgstr "Amostragem"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Amostragem — Recurso {featureLabel}"
msgid "Sampling Standard"
msgstr "Padrão de Amostragem"
@@ -10852,8 +10932,8 @@ msgstr "Digitalize ou insira o número de rastreamento"
msgid "Scan or search..."
msgstr "Digitalize ou pesquise..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Digitalize ou selecione uma entidade rastreada deste lote e registre o resultado da inspeção."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Digitalize ou selecione uma entidade rastreada deste lote para adicioná-la como coluna de amostra e, em seguida, registre seu resultado na grade."
msgid "Scan the tracking ID for this line"
msgstr "Digitalize o ID de rastreamento para esta linha"
@@ -10900,6 +10980,9 @@ msgstr "Escopos"
msgid "Scrap"
msgstr "Sucata"
+msgid "Scrap / Cost of Quality"
+msgstr "Sucata / Custo de Qualidade"
+
msgid "Scrap Percent"
msgstr "Percentual de Sucata"
@@ -10960,6 +11043,9 @@ msgstr "Pesquisar Trabalho"
msgid "Search operators..."
msgstr "Pesquisar operadores..."
+msgid "Search parts..."
+msgstr "Pesquisar peças..."
+
msgid "Search processes..."
msgstr "Pesquisar processos..."
@@ -10969,6 +11055,9 @@ msgstr "Pesquisar itens relacionados..."
msgid "Search suppliers..."
msgstr "Pesquisar fornecedores..."
+msgid "Search tools..."
+msgstr "Pesquisar ferramentas..."
+
msgid "Search..."
msgstr "Pesquisar..."
@@ -10990,6 +11079,9 @@ msgstr "Selecione um responsável"
msgid "Select a default approver"
msgstr "Selecione um aprovador padrão"
+msgid "Select a document"
+msgstr "Selecione um documento"
+
msgid "Select a new owner"
msgstr "Selecione um novo proprietário"
@@ -11647,6 +11739,9 @@ msgstr "Consumo de Peças de Reposição"
msgid "Spare Part Cost"
msgstr "Custo de Peça de Reposição"
+msgid "Spec"
+msgstr "Especificação"
+
msgid "Specific Customer"
msgstr "Cliente Específico"
@@ -11777,6 +11872,12 @@ msgstr "passos"
msgid "Steps"
msgstr "Etapas"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Os passos são herdados da instrução de montagem."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "As etapas são herdadas do plano de inspeção."
+
msgid "Stock Transfer ID"
msgstr "ID de Transferência de Estoque"
@@ -12470,8 +12571,8 @@ msgstr "O fluxo comercial de ponta a ponta, desde a cotação de um cliente até
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "O endpoint que recebe uma solicitação POST com os dados atualizados quando a tabela é atualizada"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "O desenho técnico ao qual este documento de inspeção está vinculado; as inspeções registradas em relação a esta referência de parte fazem referência a este desenho."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "O desenho de engenharia ao qual este plano de inspeção está vinculado; as inspeções registradas nesta peça referenciam este desenho."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "O percentual esperado da produção deste item perdido durante a fabricação; o planejamento multiplica a demanda por 1 / (1 − sucata) para compensar."
@@ -12620,15 +12721,15 @@ msgstr "Os logotipos mostrados em seus documentos impressos e enviados por email
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "O identificador de lote para este estoque; uma linha por lote, a quantidade é a em mão para esse lote."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "O lote permanece aberto para que você possa continuar inspecionando e disposicionando posteriormente. Os resultados das amostras são preservados."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "O lote será marcado como Aprovado. {fails} falha(s) amostrada(s) são registradas para seus registros."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "O lote ainda será rejeitado, mas um NCR não pode ser criado até que pelo menos um Tipo de Problema seja configurado."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "O plano de amostragem por recurso do lote será resolvido novamente a partir do documento selecionado."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "O valor mínimo que este fornecedor cobrará por esse processo, independentemente da quantidade; os trabalhos abaixo do volume de equilíbrio ainda custam pelo menos esse valor."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "A sequência ordenada de operações que um trabalho executa, copiada da lista de processos do método."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "O arquivo do modelo original não está mais disponível"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "O documento de contabilização de saída que remove bens do estoque para um cliente, contabilizando o COGS no processo."
@@ -12719,8 +12820,8 @@ msgstr "As pessoas do lado da Carbon que executarão sua implementação e como
msgid "The people on your team and their access to Carbon"
msgstr "As pessoas da sua equipe e seu acesso ao Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "O contador por empresa por trás do número legível de um tipo de documento, montando {prefix}{next+step, zero-padded}{suffix} e avançando conforme cada documento é criado."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "O contador por empresa por trás do número legível de um tipo de documento, montando o prefixo, o próximo valor preenchido com zeros, e o sufixo, e avançando conforme cada documento é criado."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "O resultado por item registrado no material afetado de uma não-conformidade — Pendente, Devolução ao Fornecedor, Retrabalho, Sucata ou Usar Como Está — decidido para cada lote ou serial afetado individualmente."
@@ -13011,6 +13112,9 @@ msgstr "Esta informação será usada nos cabeçalhos de documentos"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Esta informação será visível para todos os usuários, portanto, tenha cuidado com o que você compartilha."
+msgid "this inspection plan"
+msgstr "este plano de inspeção"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Este é um item comprado — não tem BOM/BOP; apenas seus atributos e documentos podem mudar."
@@ -13459,9 +13563,6 @@ msgstr "Tipo:"
msgid "Types"
msgstr "Tipos"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Entidades não amostradas permanecerão Em Espera para que você possa continuar inspecionando e fazer a disposição posteriormente. Os resultados das amostras são preservados."
-
msgid "Unapplied"
msgstr "Não aplicado"
@@ -14311,6 +14412,9 @@ msgstr "Quando ativado, os atributos nesta categoria aparecem no perfil público
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Quando ativado, os funcionários podem editar o valor deste atributo em seu próprio perfil; caso contrário, apenas os administradores podem fazê-lo."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Quando ativado, abrir uma operação inicia seu cronômetro automaticamente."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Quando ativado, as regras de preço (descontos por volume, promoções) ainda se aplicam sobre esta substituição; quando desativado, esta substituição é o preço final."
@@ -14437,8 +14541,8 @@ msgstr "Se o cronômetro inicia quando o processo escolhido começa ou quando el
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Se este lote/série passa na inspeção (Pass) ou falha (Fail); um Fail impede que o estoque seja recebido no inventário disponível."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Se este processo é executado em centros de trabalho internos (Inside), fornecedores externos (Outside) ou ambos (Both); revela diferentes campos posteriores e altera como o planejamento roteia este processo."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Se este processo é executado em centros de trabalho internos (Processo, Montagem ou Inspeção) ou em fornecedores externos (Processamento Externo); revela diferentes campos subsequentes, muda como as rotas de planejamento funcionam para este processo e define o tipo de operação padrão em novas operações."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Se este trabalho bloqueia a produção (Inativo), a degrada (Impacto), fica em uma janela de tempo de inatividade planejada (Planejado) ou não tem impacto na produção (Sem Impacto); informa o agendamento e a comunicação de inatividade orientada ao cliente."
@@ -14446,6 +14550,9 @@ msgstr "Se este trabalho bloqueia a produção (Inativo), a degrada (Impacto), f
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Se as permissões selecionadas forem Adicionadas ao que cada usuário já possui, ou Atualizadas substituindo o conjunto de permissões de cada usuário pela seleção abaixo."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Qual documento conduz cada fluxo de inspeção para este item."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Qual evento de fabricação inicia o relógio da vida útil — por exemplo, preenchimento, selagem ou QC final."
@@ -14608,6 +14715,9 @@ msgstr "Conta de Cancelamento"
msgid "Write-off for {0}"
msgstr "Cancelamento para {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Baixa de estoque sucatado ou devolvido por rejeições de inspeção e disposições de NCR"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Reduzir o valor de um ativo ao longo de sua vida útil — um lote mensal que você cria, revisa como rascunho e depois contabiliza."
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index c08bdfe773..cce564a964 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} de {1} concluído(s)"
msgid "{0} Scrapped"
msgstr "{0} Refugado(s)"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} unidade(s) aprovada(s) será(ão) concluída(s)."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} falha(s) amostrada(s) registrada(s) e NÃO será(ão) concluída(s) — resolva-as no menu de ações."
+
msgid "About"
msgstr "Sobre"
+msgid "Accept"
+msgstr "Aceitar"
+
+msgid "Accept Lot"
+msgstr "Aceitar Lote"
+
+msgid "Accept lot?"
+msgstr "Aceitar lote?"
+
msgid "Account Settings"
msgstr "Configurações da Conta"
@@ -66,12 +81,27 @@ msgstr "Adicione uma impressora nas configurações de impressão para imprimir
msgid "Add Inventory"
msgstr "Adicionar Estoque"
+msgid "Add Sample"
+msgstr "Adicionar Amostra"
+
msgid "Add Spare Part"
msgstr "Adicionar Peça Sobressalente"
msgid "All"
msgstr "Todos"
+msgid "All rework"
+msgstr "Todos para retrabalho"
+
+msgid "All scrap"
+msgstr "Tudo sucata"
+
+msgid "Allocate failed units"
+msgstr "Alocar unidades com falha"
+
+msgid "Allocate units"
+msgstr "Alocar unidades"
+
msgid "Are you sure you want to delete this step?"
msgstr "Tem certeza de que deseja excluir esta etapa?"
@@ -165,6 +195,12 @@ msgstr "Registrar Saída"
msgid "Clocked in since {0}"
msgstr "Registrado desde {0}"
+msgid "Close"
+msgstr "Fechar"
+
+msgid "Collapse features table"
+msgstr "Recolher tabela de recursos"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Concluir"
msgid "Complete All"
msgstr "Completar Tudo"
+msgid "Complete passed"
+msgstr "Completar aprovados"
+
msgid "Completed"
msgstr "Concluído"
@@ -281,6 +320,9 @@ msgstr "Rascunho"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Arraste e solte um arquivo aqui ou clique para selecionar um arquivo"
+msgid "Drag to resize drawing and features"
+msgstr "Arraste para redimensionar desenho e recursos"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Arraste de {0} cancelado."
@@ -325,6 +367,12 @@ msgstr "Erro"
msgid "Estimated"
msgstr "Estimado"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Cada unidade tem um veredicto: {passes} aprovada(s) e {fails} reprovada(s). O lote fecha com cada unidade encaminhada para seu próprio resultado."
+
+msgid "Expand features table"
+msgstr "Expandir tabela de recursos"
+
msgid "Expired"
msgstr "Expirado"
@@ -337,6 +385,12 @@ msgstr "Expira {date}"
msgid "Expiring first"
msgstr "Expirando primeiro"
+msgid "Failed"
+msgstr "Falhou"
+
+msgid "Failed features"
+msgstr "Recursos com falha"
+
msgid "Failed to complete inventory adjustment"
msgstr "Falha ao concluir ajuste de estoque"
@@ -349,6 +403,12 @@ msgstr "Falha ao buscar operações ativas"
msgid "Failed to fetch storageUnits"
msgstr "Falha ao buscar unidades de armazenamento"
+msgid "Failed to save measurement"
+msgstr "Falha ao salvar medição"
+
+msgid "Failed to save result"
+msgstr "Falha ao salvar resultado"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Falha ao enviar arquivo: {0}"
@@ -356,6 +416,12 @@ msgstr "Falha ao enviar arquivo: {0}"
msgid "Failed to upload image"
msgstr "Falha ao enviar imagem"
+msgid "Feature"
+msgstr "Recurso"
+
+msgid "Features"
+msgstr "Características"
+
msgid "File size exceeds 10MB limit"
msgstr "O tamanho do arquivo excede o limite de 10MB"
@@ -405,6 +471,12 @@ msgstr "Imperial"
msgid "In Progress"
msgstr "Em Andamento"
+msgid "Inspect Item"
+msgstr "Inspecionar Item"
+
+msgid "inspected"
+msgstr "inspecionado"
+
msgid "Insufficient quantity"
msgstr "Quantidade insuficiente"
@@ -498,6 +570,9 @@ msgstr "Registrar refugo para {0}"
msgid "Login"
msgstr "Entrar"
+msgid "Lot"
+msgstr "Lote"
+
msgid "Machine"
msgstr "Máquina"
@@ -531,6 +606,9 @@ msgstr "Métrico"
msgid "Model"
msgstr "Modelo"
+msgid "More actions"
+msgstr "Mais ações"
+
msgid "More Actions"
msgstr "Mais Ações"
@@ -595,6 +673,9 @@ msgstr "Nenhum arquivo"
msgid "No Impact"
msgstr "Sem Impacto"
+msgid "No issue types configured"
+msgstr "Nenhum tipo de problema configurado"
+
msgid "No maintenance scheduled for today"
msgstr "Nenhuma manutenção programada para hoje"
@@ -607,6 +688,9 @@ msgstr "Nenhum material"
msgid "No open jobs"
msgstr "Nenhum trabalho aberto"
+msgid "No open units to allocate"
+msgstr "Nenhuma unidade aberta para alocar"
+
msgid "No operators"
msgstr "Nenhum operador"
@@ -625,6 +709,9 @@ msgstr "Nenhuma impressora configurada"
msgid "No recent operations"
msgstr "Nenhuma operação recente"
+msgid "No remaining entities to inspect."
+msgstr "Nenhuma entidade restante para inspecionar."
+
msgid "No results"
msgstr "Nenhum resultado"
@@ -634,6 +721,9 @@ msgstr "Nenhum resultado encontrado"
msgid "No results found"
msgstr "Nenhum resultado encontrado"
+msgid "No samples required."
+msgstr "Nenhuma amostra necessária."
+
msgid "No scheduled time"
msgstr "Nenhum horário programado"
@@ -683,6 +773,9 @@ msgstr "Ops. Você não deveria ver esta página. Eventualmente será uma págin
msgid "Open"
msgstr "Aberto"
+msgid "Open an NCR for MRB disposition"
+msgstr "Abrir um NCR para disposição MRB"
+
msgid "Open Jobs"
msgstr "Trabalhos Abertos"
@@ -698,12 +791,21 @@ msgstr "Realizado pelo Operador"
msgid "Optional"
msgstr "Opcional"
+msgid "Overall result"
+msgstr "Resultado geral"
+
msgid "Parameters"
msgstr "Parâmetros"
msgid "Part"
msgstr "Peça"
+msgid "Partial"
+msgstr "Parcial"
+
+msgid "Partial Disposition"
+msgstr "Disposição Parcial"
+
msgid "Passed Inspection"
msgstr "Aprovado na Inspeção"
@@ -749,9 +851,6 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventiva"
-msgid "Previous"
-msgstr "Anterior"
-
msgid "Print"
msgstr "Imprimir"
@@ -801,6 +900,18 @@ msgstr "Registrar"
msgid "Record {0}"
msgstr "Registro {0}"
+msgid "Record only"
+msgstr "Apenas registrar"
+
+msgid "Record Partial"
+msgstr "Registrar Parcial"
+
+msgid "Reject"
+msgstr "Rejeitar"
+
+msgid "Reject Lot"
+msgstr "Rejeitar Lote"
+
msgid "Remove"
msgstr "Remover"
@@ -813,12 +924,18 @@ msgstr "Remover Estoque"
msgid "Remove part"
msgstr "Remover peça"
+msgid "Result"
+msgstr "Resultado"
+
msgid "Rework"
msgstr "Retrabalho"
msgid "Rework created successfully"
msgstr "Rework criado com sucesso"
+msgid "Rework quantity"
+msgstr "Quantidade de retrabalho"
+
msgid "Sales Order"
msgstr "Pedido de Venda"
@@ -828,21 +945,33 @@ msgstr "Salvar"
msgid "Scan"
msgstr "Escanear"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Digitalizar uma entidade rastreada para adicionar a primeira coluna de amostra."
+
msgid "Scan or enter serial number"
msgstr "Escanear ou inserir número de série"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Digitalizar ou inserir ID da entidade rastreada, serial ou lote"
+
msgid "Scan or enter tracking number"
msgstr "Digitalize ou insira o número de rastreamento"
msgid "Scan or search serial number..."
msgstr "Digitalize ou procure número de série..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Digitalizar ou selecionar uma entidade rastreada deste lote para adicioná-la como uma coluna de amostra, depois registre seu resultado na grade."
+
msgid "Schedule"
msgstr "Cronograma"
msgid "Scrap"
msgstr "Sucata"
+msgid "Scrap quantity"
+msgstr "Quantidade de sucata"
+
msgid "Scrap Reason"
msgstr "Motivo do Refugo"
@@ -876,6 +1005,9 @@ msgstr "Selecione uma quantidade de refugo e motivo"
msgid "Select a serial number to continue with this operation"
msgstr "Selecione um número de série para continuar com esta operação"
+msgid "Select an issue type"
+msgstr "Selecionar um tipo de problema"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Selecione um item e especifique a quantidade a emitir"
@@ -899,6 +1031,9 @@ msgstr "Selecionar Número de Série"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Selecione a operação para voltar. Todas as operações desse ponto até a operação atual serão refeitas."
+msgid "Selected"
+msgstr "Selecionado"
+
msgid "Send"
msgstr "Enviar"
@@ -978,6 +1113,10 @@ msgstr "Usuário da Estação"
msgid "Station: {stationName}"
msgstr "Estação: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "A aceitação estatística falhou, portanto o lote inteiro de {0} é considerado não-conforme (ISO 9001:2015 §8.7) — {passes} amostra(s) aprovada(s) e {fails} falha(s). Encaminhe as unidades abaixo para sucata ou retrabalho, ou registre apenas o veredicto."
+
msgid "Status"
msgstr "Status"
@@ -1015,6 +1154,12 @@ msgstr "Etiqueta"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "A quantidade concluída para esta operação é menor que a quantidade requerida de {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "O lote será marcado como Aprovado e {remaining} unidade(s) restante(s) será(ão) concluída(s) nesta operação."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "O lote ainda será disposicionado, mas um NCR não pode ser criado até que pelo menos um Tipo de Problema seja configurado."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Existem materiais rastreados por série ou lote na lista de materiais que não foram totalmente emitidos. Concluir sem emitir pode resultar em registros de rastreabilidade incorretos."
@@ -1048,6 +1193,9 @@ msgstr "Tempo total: {0}"
msgid "Total: {0}"
msgstr "Total: {0}"
+msgid "Tracked Entity"
+msgstr "Entidade Rastreada"
+
msgid "Tracking"
msgstr "Rastreamento"
@@ -1070,6 +1218,9 @@ msgstr "Desmarcar {0}"
msgid "Unsaved changes"
msgstr "Alterações não salvas"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "Até {maxAllocatable} unidade(s) pode(m) ser alocada(s); o restante é registrado sem uma postagem."
+
msgid "Update"
msgstr "Atualizar"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index cf3a78cd04..83d57cc6cd 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -725,6 +725,9 @@ msgstr "Добавить параметр"
msgid "Add Partner"
msgstr "Добавить партнера"
+msgid "Add parts"
+msgstr "Добавить детали"
+
msgid "Add Permissions"
msgstr "Добавить разрешения"
@@ -749,6 +752,9 @@ msgstr "Добавить риск"
msgid "Add rule"
msgstr "Добавить правило"
+msgid "Add Sample"
+msgstr "Добавить образец"
+
msgid "Add Selector"
msgstr "Добавить селектор"
@@ -764,6 +770,9 @@ msgstr "Добавить запасную часть"
msgid "Add Step"
msgstr "Добавить шаг"
+msgid "Add steps to preview the operator view."
+msgstr "Добавьте шаги для предварительного просмотра представления оператора."
+
msgid "Add Supplier"
msgstr "Добавить поставщика"
@@ -776,6 +785,9 @@ msgstr "Добавить табель учета рабочего времени
msgid "Add to stock for future use"
msgstr "Добавить в запас для будущего использования"
+msgid "Add tools"
+msgstr "Добавить инструменты"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "Добавьте свой первый {0}"
@@ -1041,6 +1053,9 @@ msgstr "Применяется ко всем"
msgid "Applies to all work centers"
msgstr "Применяется ко всем рабочим центрам"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Применяется к функциям без собственного правила и к партии, когда этот план инициирует проверку."
+
msgid "Apply"
msgstr "Применить"
@@ -1401,8 +1416,11 @@ msgstr "Вы уверены, что хотите удалить этот при
msgid "Are you sure you want to delete this gauge?"
msgstr "Вы уверены, что хотите удалить этот манометр?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Вы уверены, что хотите удалить этот документ проверки?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Вы уверены, что хотите удалить этот план контроля?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Вы уверены, что хотите удалить этот план проверки? Это действие невозможно отменить."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Вы уверены, что хотите удалить этот рабочий процесс проблемы?"
@@ -1534,6 +1552,9 @@ msgstr "Попросите администратора с разрешение
msgid "Assemblies"
msgstr "Сборки"
+msgid "Assembly Instruction"
+msgstr "Инструкция по сборке"
+
msgid "Assembly Instructions"
msgstr "Инструкции по сборке"
@@ -1678,6 +1699,12 @@ msgstr "Автоматически созданный QR-код"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Форматы автонумерации для заказов, работ, деталей и многого другого"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Автоматически запускать таймер оператора при открытии операции в MES, чтобы логи времени записывались с начала."
+
+msgid "Auto-start timer on open"
+msgstr "Автоматически запустить таймер при открытии"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Автоматически предлагать покупки на основе спроса и точек переупорядочения"
@@ -1741,6 +1768,9 @@ msgstr "Сбалансировано"
msgid "Balloon"
msgstr "Выноска"
+msgid "Ballooned drawings with inspection features."
+msgstr "Аннотированные чертежи с элементами проверки."
+
msgid "Bank - Cash"
msgstr "Банк - Денежные средства"
@@ -2094,6 +2124,9 @@ msgstr "Невозможно загрузить — взаимодействие
msgid "Cannot upload to parts bucket without item ID"
msgstr "Невозможно загрузить в корзину деталей без ID элемента"
+msgid "Caption"
+msgstr "Заголовок"
+
msgid "Carbon"
msgstr "Углерод"
@@ -2193,6 +2226,12 @@ msgstr "Чемпионы"
msgid "Change"
msgstr "Изменить"
+msgid "Change Document"
+msgstr "Изменить документ"
+
+msgid "Change Inspection Plan"
+msgstr "Изменить план контроля"
+
msgid "Change order"
msgstr "Приказ об изменении"
@@ -2283,6 +2322,9 @@ msgstr "Класс"
msgid "Class (inherited)"
msgstr "Класс (унаследованный)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Классифицирует операцию маршрута: операции Process, Assembly и Inspection выполняются на собственном производстве в MES — Assembly получает управляемое представление сборки, а Inspection выполняет проверку качества — в то время как операция Outside Processing субподряжается поставщику и создает заказ на покупку; процесс имеет тот же тип и использует его по умолчанию для новых операций."
+
msgid "Clean and approve the migrated data"
msgstr "Очистить и утвердить перенесенные данные"
@@ -2747,6 +2789,9 @@ msgstr "Преобразуйте предложения MRP в заказы на
msgid "Convert to Quote"
msgstr "Преобразовать в предложение"
+msgid "Converting…"
+msgstr "Преобразование…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Преобразует единицу покупки поставщика в единицу инвентаря в строке заказа на покупку, квитанции или счета — покупайте в картонах по 12 штук, запасайте в единицах."
@@ -3055,9 +3100,6 @@ msgstr "Создать приказ об изменении"
msgid "Create Issue"
msgstr "Создать проблему"
-msgid "Create Issue from Inspection"
-msgstr "Создать проблему из проверки"
-
msgid "Create Jobs"
msgstr "Создать задания"
@@ -3699,6 +3741,9 @@ msgstr "Приоритет по умолчанию"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Счет GL по умолчанию, который кредитуется при проведении счета-фактуры продажи."
+msgid "Default Sampling"
+msgstr "Выборка по умолчанию"
+
msgid "Default shelf-life duration (days)"
msgstr "Продолжительность срока годности по умолчанию (дни)"
@@ -3741,9 +3786,6 @@ msgstr "Сначала определите производственную о
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Определите многоуровневые спецификации материалов и Лист процесса (методы производства)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Определяет, сколько отслеживаемых объектов проверяется на партию и сколько отказов допускается перед отклонением партии."
-
msgid "Delete"
msgstr "Удалить"
@@ -3837,6 +3879,9 @@ msgstr "Удалить группу"
msgid "Delete Holiday"
msgstr "Удалить праздник"
+msgid "Delete Inspection Plan"
+msgstr "Удалить план проверки"
+
msgid "Delete Issue"
msgstr "Удалить проблему"
@@ -4329,6 +4374,9 @@ msgstr "Перетащите для переупорядочивания"
msgid "Drag to resize diagram and features"
msgstr "Перетащите, чтобы изменить размер диаграммы и функций"
+msgid "Drag to resize drawing and features"
+msgstr "Перетащите, чтобы изменить размер рисунка и функций"
+
msgid "Drag to zoom"
msgstr "Перетащите для масштабирования"
@@ -4549,8 +4597,8 @@ msgstr "Редактировать группу"
msgid "Edit Holiday"
msgstr "Редактировать праздник"
-msgid "Edit Inspection Document"
-msgstr "Редактировать документ проверки"
+msgid "Edit Inspection Plan"
+msgstr "Отредактировать план контроля"
msgid "Edit Item Group"
msgstr "Редактировать группу товаров"
@@ -5236,6 +5284,9 @@ msgstr "Дополнительные теги для разбора отчетн
msgid "Fail"
msgstr "Не пройти"
+msgid "Failed features"
+msgstr "Отказавшие элементы"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (первый истекший - первый выходит)"
@@ -5479,6 +5530,21 @@ msgstr "Ошибка при сохранении правила конфигур
msgid "Failed to save diagram"
msgstr "Не удалось сохранить диаграмму"
+msgid "Failed to save measurement"
+msgstr "Не удалось сохранить измерение"
+
+msgid "Failed to save parts"
+msgstr "Ошибка при сохранении деталей"
+
+msgid "Failed to save result"
+msgstr "Не удалось сохранить результат"
+
+msgid "Failed to save slides"
+msgstr "Ошибка при сохранении слайдов"
+
+msgid "Failed to save tools"
+msgstr "Ошибка при сохранении инструментов"
+
msgid "Failed to update batch property"
msgstr "Не удалось обновить свойство партии"
@@ -6400,15 +6466,6 @@ msgstr "Неактивные действия не будут отображат
msgid "Inbound inspection"
msgstr "Входящая проверка"
-msgid "Inbound Inspection"
-msgstr "Входящая проверка"
-
-msgid "Inbound Inspections"
-msgstr "Входящие проверки"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Входящие проверки: требовать другого инспектора"
-
msgid "Inbox"
msgstr "Входящие"
@@ -6454,6 +6511,12 @@ msgstr "Косвенные материалы и услуги (по умолча
msgid "Infrastructure"
msgstr "Инфраструктура"
+msgid "Inherit"
+msgstr "Наследовать"
+
+msgid "Inherit document default"
+msgstr "Наследовать документ по умолчанию"
+
msgid "Inherit From Materials"
msgstr "Наследовать от материалов"
@@ -6490,32 +6553,35 @@ msgstr "Проверить первые N"
msgid "Inspect Item"
msgstr "Проверить товар"
-msgid "Inspect Next Item"
-msgstr "Проверить следующий элемент"
-
msgid "Inspection"
msgstr "Проверка"
-msgid "Inspection Document"
-msgstr "Документ проверки"
-
-msgid "Inspection Documents"
-msgstr "Документы проверки"
-
msgid "Inspection Level"
msgstr "Уровень проверки"
+msgid "Inspection Plan"
+msgstr "План контроля"
+
+msgid "Inspection Plan Assignments"
+msgstr "Назначения плана контроля"
+
+msgid "Inspection Plans"
+msgstr "Планы контроля"
+
msgid "Inspection Status"
msgstr "Статус проверки"
+msgid "Inspections"
+msgstr "Проверки"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Проверки, несоответствия и CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Проверки, несоответствия, CAPA"
-msgid "Inspector"
-msgstr "Инспектор"
+msgid "Inspections: Require Different Inspector"
+msgstr "Проверки: Требуется другой инспектор"
msgid "Install"
msgstr "Установить"
@@ -7439,15 +7505,9 @@ msgstr "Отметить как выполнено"
msgid "Mark Light Mode"
msgstr "Логотип в светлом режиме"
-msgid "Mark lot as partial?"
-msgstr "Отметить партию как частичную?"
-
msgid "Mark not done"
msgstr "Отметить как невыполненное"
-msgid "Mark Partial"
-msgstr "Отметить как частичное"
-
msgid "Mark scope as agreed"
msgstr "Отметить область как согласованную"
@@ -7960,8 +8020,8 @@ msgstr "Новый праздник"
msgid "New IC Transaction"
msgstr "Новая транзакция IC"
-msgid "New Inspection Document"
-msgstr "Новый документ проверки"
+msgid "New Inspection Plan"
+msgstr "Новый план контроля"
msgid "New Inventory Count"
msgstr "Новый подсчет инвентаря"
@@ -8332,6 +8392,9 @@ msgstr "Нет назначенных групп"
msgid "No image"
msgstr "Нет изображения"
+msgid "No inspection plans"
+msgstr "Нет планов контроля"
+
msgid "No issue types configured"
msgstr "Типы проблем не настроены"
@@ -8392,6 +8455,9 @@ msgstr "Родительские источники еще не записаны
msgid "No part ID"
msgstr "Нет ID детали"
+msgid "No parts"
+msgstr "Нет деталей"
+
msgid "No payables"
msgstr "Нет кредиторской задолженности"
@@ -8428,6 +8494,9 @@ msgstr "Причины отсутствия предложения"
msgid "No receivables"
msgstr "Нет дебиторской задолженности"
+msgid "No reference image"
+msgstr "Нет эталонного изображения"
+
msgid "No remaining entities to inspect."
msgstr "Нет оставшихся объектов для проверки."
@@ -8443,9 +8512,6 @@ msgstr "Нет строк здесь."
msgid "No rules assigned"
msgstr "Нет назначенных правил"
-msgid "No samples inspected yet."
-msgstr "Пока нет проверенных образцов."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Нет единого надежного показателя для инвентаря или статуса работы"
@@ -8464,6 +8530,12 @@ msgstr "Поставщиков еще нет"
msgid "No time entries for this week"
msgstr "Нет записей о времени на эту неделю"
+msgid "No tools"
+msgstr "Нет инструментов"
+
+msgid "No tools for this step"
+msgstr "Нет инструментов для этого шага"
+
msgid "No transactions in this period"
msgstr "Нет транзакций в этом периоде"
@@ -8773,6 +8845,9 @@ msgstr "Операция"
msgid "Operation Order"
msgstr "Порядок операции"
+msgid "Operation Timer"
+msgstr "Таймер операции"
+
msgid "Operation Type"
msgstr "Тип операции"
@@ -8900,6 +8975,9 @@ msgstr "Отклонение косвенных затрат"
msgid "Over-applied by"
msgstr "Переприменено на"
+msgid "Overall result"
+msgstr "Общий результат"
+
msgid "Overdue"
msgstr "Просрочено"
@@ -9027,9 +9105,6 @@ msgstr "Номер детали"
msgid "Part Supersession"
msgstr "Замена детали"
-msgid "Partial"
-msgstr "Частичный"
-
msgid "Partner"
msgstr "Партнер"
@@ -9246,6 +9321,9 @@ msgstr "Штук/час"
msgid "Pieces/Minute"
msgstr "Деталей/Минуту"
+msgid "Pin"
+msgstr "Закрепить"
+
msgid "Pinned"
msgstr "Закреплено"
@@ -9447,6 +9525,9 @@ msgstr "Предыдущая дата"
msgid "Previous page"
msgstr "Предыдущая страница"
+msgid "Previous step"
+msgstr "Предыдущий шаг"
+
msgid "Price break actions"
msgstr "Действия ценовой скидки"
@@ -10138,9 +10219,6 @@ msgstr "Запись удалена"
msgid "Record inspections tied to a part and a job"
msgstr "Записывать проверки, связанные с деталью и заказом"
-msgid "Record the inspection result for this sample."
-msgstr "Запишите результат проверки для этого образца."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Записано при калибровке, что калибр нужно отремонтировать перед тем, как можно доверять его показаниям."
@@ -10265,9 +10343,6 @@ msgstr "Удалить {label}"
msgid "Remove condition"
msgstr "Удалить условие"
-msgid "Remove feature"
-msgstr "Удалить функцию"
-
msgid "Remove filter"
msgstr "Удалить фильтр"
@@ -10286,12 +10361,21 @@ msgstr "Удалить заказ"
msgid "Remove pair"
msgstr "Удалить пару"
+msgid "Remove part"
+msgstr "Удалить деталь"
+
+msgid "Remove slide"
+msgstr "Удалить слайд"
+
msgid "Remove sort by column"
msgstr "Удалить сортировку по столбцу"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Удалите этот тип хранилища из всех ссылающихся на него единиц хранения и удалите его. Это невозможно отменить."
+msgid "Remove tool"
+msgstr "Удалить инструмент"
+
msgid "Removed"
msgstr "Удалено"
@@ -10421,9 +10505,6 @@ msgstr "Требует действия"
msgid "Requires Adjustment"
msgstr "Требует регулировки"
-msgid "Requires Inspection"
-msgstr "Требует проверки"
-
msgid "Requires Repair"
msgstr "Требует ремонта"
@@ -10444,7 +10525,7 @@ msgstr "Сброс PIN"
msgid "Reset PIN for {0} {1}"
msgstr "Сброс PIN для {0} {1}"
-msgid "Reset View"
+msgid "Reset view"
msgstr "Сбросить вид"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "Как в книге"
msgid "Sample"
msgstr "Образец"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Образец {0}"
-
msgid "Sample Size"
msgstr "Размер выборки"
-msgid "Sampling Plan"
-msgstr "План выборочного контроля"
+msgid "Sampling"
+msgstr "Выборка"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Выборка — Функция {featureLabel}"
msgid "Sampling Standard"
msgstr "Стандарт выборки"
@@ -10852,8 +10932,8 @@ msgstr "Отсканируйте или введите номер отслежи
msgid "Scan or search..."
msgstr "Сканировать или искать..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Отсканируйте или выберите отслеживаемый объект из этой партии и запишите результат проверки."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Отсканируйте или выберите отслеживаемую сущность из этой партии, чтобы добавить её в качестве столбца образца, затем запишите её результат в сетку."
msgid "Scan the tracking ID for this line"
msgstr "Отсканируйте идентификатор отслеживания для этой строки"
@@ -10900,6 +10980,9 @@ msgstr "Области"
msgid "Scrap"
msgstr "Брак"
+msgid "Scrap / Cost of Quality"
+msgstr "Брак / Стоимость качества"
+
msgid "Scrap Percent"
msgstr "Процент брака"
@@ -10960,6 +11043,9 @@ msgstr "Поиск задания"
msgid "Search operators..."
msgstr "Поиск операторов..."
+msgid "Search parts..."
+msgstr "Поиск деталей..."
+
msgid "Search processes..."
msgstr "Поиск процессов..."
@@ -10969,6 +11055,9 @@ msgstr "Поиск связанных элементов..."
msgid "Search suppliers..."
msgstr "Поиск поставщиков..."
+msgid "Search tools..."
+msgstr "Поиск инструментов..."
+
msgid "Search..."
msgstr "Поиск..."
@@ -10990,6 +11079,9 @@ msgstr "Выберите исполнителя"
msgid "Select a default approver"
msgstr "Выберите утверждающего по умолчанию"
+msgid "Select a document"
+msgstr "Выберите документ"
+
msgid "Select a new owner"
msgstr "Выберите нового владельца"
@@ -11647,6 +11739,9 @@ msgstr "Потребление запасных частей"
msgid "Spare Part Cost"
msgstr "Стоимость запасных частей"
+msgid "Spec"
+msgstr "Тех. условия"
+
msgid "Specific Customer"
msgstr "Конкретный клиент"
@@ -11777,6 +11872,12 @@ msgstr "шаги"
msgid "Steps"
msgstr "Шаги"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Этапы наследуются из инструкции по сборке."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Этапы наследуются из плана контроля."
+
msgid "Stock Transfer ID"
msgstr "ID передачи запасов"
@@ -12470,8 +12571,8 @@ msgstr "Сквозной коммерческий процесс от предл
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Конечная точка, которая получает POST-запрос с обновленными данными при обновлении таблицы"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Технический чертеж, к которому привязан этот документ проверки; проверки, записанные в отношении этого обозначения детали, ссылаются на этот чертеж."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Техническая схема, к которой привязан данный план контроля; проверки, записанные для этой детали, ссылаются на эту схему."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "Ожидаемый процент выпуска этого товара, потерянный во время производства; планирование умножает спрос на 1 / (1 − отход) для компенсации."
@@ -12620,15 +12721,15 @@ msgstr "Логотипы, отображаемые в ваших печатны
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "Идентификатор партии для этого запаса; одна строка на партию, количество - это количество на руках для этой партии."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Партия остается открытой, чтобы вы могли продолжить проверку и принять решение позже. Результаты выборки сохраняются."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Партия будет отмечена как принята. {fails} образец(ов) с дефектом(и) записан(ы) для ваших записей."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Партия все еще будет отклонена, но NCR не может быть создана до тех пор, пока не будет настроен хотя бы один тип проблемы."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "План выборочной проверки партии по элементам будет переопределен из выбранного документа."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Минимальная сумма, которую этот поставщик взимает за этот процесс, независимо от количества; работы ниже объема безубыточности все еще стоят как минимум эту сумму."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "Упорядоченная последовательность операций, которые выполняет задание, скопированная из расчета процессов метода."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Исходный файл модели больше недоступен"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Документ исходящего учета, который выводит товары со склада к клиенту, осуществляя учет себестоимости проданных товаров."
@@ -12719,8 +12820,8 @@ msgstr "Люди со стороны Carbon, которые будут упра
msgid "The people on your team and their access to Carbon"
msgstr "Люди в вашей команде и их доступ к Carbon"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Счётчик для каждой компании, лежащий в основе читаемого номера документа, собирающий {prefix}{next+step, zero-padded}{suffix} и увеличивающийся при создании каждого документа."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Счётчик на уровне компании, формирующий читаемый номер документа путём объединения префикса, дополняемого нулями числового значения и суффикса, и увеличивающийся при создании каждого документа."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "Исход для каждого элемента, записанный для затронутого материала несоответствия — В ожидании, Вернуть поставщику, Переработка, Брак или Использовать как есть — решается для каждой затронутой партии или серии отдельно."
@@ -13011,6 +13112,9 @@ msgstr "Эта информация будет использована в за
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Эта информация будет видна всем пользователям, поэтому будьте осторожны с тем, что вы делитесь."
+msgid "this inspection plan"
+msgstr "этот план проверки"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Это купленный элемент — у него нет BoM/BoP; могут изменяться только его атрибуты и документы."
@@ -13459,9 +13563,6 @@ msgstr "Тип:"
msgid "Types"
msgstr "Типы"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Необработанные сущности останутся в статусе \"На удержании\", чтобы вы могли продолжить проверку и принять решение позже. Результаты проверенных образцов сохраняются."
-
msgid "Unapplied"
msgstr "Неприменённые"
@@ -14311,6 +14412,9 @@ msgstr "Когда включено, атрибуты в этой категор
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Когда включено, сотрудники могут редактировать значение этого атрибута в своем профиле; в противном случае это могут делать только администраторы."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Когда включено, открытие операции автоматически запускает ее таймер."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Когда включено, правила цены (скидки по объемам, акции) по-прежнему применяются сверх этого переопределения; когда отключено, это переопределение — финальная цена."
@@ -14437,8 +14541,8 @@ msgstr "Запускается ли отсчёт времени в начале
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Проходит ли эта партия/серийный номер проверку (Pass) или не проходит (Fail); Fail блокирует приём запасов в доступные складские остатки."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Выполняется ли этот процесс на внутренних рабочих центрах (Inside), у внешних поставщиков (Outside) или и там, и там (Both); открывает разные последующие поля и меняет, как планирование строит маршруты для этого процесса."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Определяет, выполняется ли этот процесс на внутренних рабочих центрах (Process, Assembly или Inspection) или у внешних поставщиков (Outside Processing); раскрывает различные нижестоящие поля, изменяет способ работы планирования маршрутов для этого процесса и устанавливает тип операции по умолчанию для новых операций."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Блокирует ли эта работа производство (Вниз), его деградирует (Воздействие), находится в окне планового простоя (Плановое) или не оказывает влияния на производство (Без воздействия); информирует планирование и общение об простое, обращенное к клиентам."
@@ -14446,6 +14550,9 @@ msgstr "Блокирует ли эта работа производство (В
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Если выбранные разрешения Добавляются к тому, что каждый пользователь уже имеет, или Обновляются путем замены набора разрешений каждого пользователя на выбранные ниже."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Какой документ определяет каждый процесс контроля для этого элемента."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Какое производственное событие запускает часы срока хранения — например, заполнение, уплотнение или окончательный контроль качества."
@@ -14608,6 +14715,9 @@ msgstr "Счет списания"
msgid "Write-off for {0}"
msgstr "Списание для {0}"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Списание запасов, забракованных или возвращённых через отклонения проверки и решения NCR"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Снижение стоимости актива в течение его полезного использования — ежемесячный пакет, который вы создаете, проверяете как черновик, затем контируете."
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index c4d79d3ca9..d21c8b0c87 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} из {1} завершено"
msgid "{0} Scrapped"
msgstr "{0} Списано"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} прошедших единиц будут завершены."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} записанных отказов будут НЕ завершены — разрешите их из меню действий."
+
msgid "About"
msgstr "О системе"
+msgid "Accept"
+msgstr "Принять"
+
+msgid "Accept Lot"
+msgstr "Принять партию"
+
+msgid "Accept lot?"
+msgstr "Принять партию?"
+
msgid "Account Settings"
msgstr "Настройки аккаунта"
@@ -66,12 +81,27 @@ msgstr "Добавьте принтер в параметры печати, чт
msgid "Add Inventory"
msgstr "Добавить запас"
+msgid "Add Sample"
+msgstr "Добавить образец"
+
msgid "Add Spare Part"
msgstr "Добавить запасную часть"
msgid "All"
msgstr "Все"
+msgid "All rework"
+msgstr "Все переработки"
+
+msgid "All scrap"
+msgstr "Весь брак"
+
+msgid "Allocate failed units"
+msgstr "Распределить неудачные единицы"
+
+msgid "Allocate units"
+msgstr "Распределить единицы"
+
msgid "Are you sure you want to delete this step?"
msgstr "Вы уверены, что хотите удалить этот шаг?"
@@ -165,6 +195,12 @@ msgstr "Отметить уход"
msgid "Clocked in since {0}"
msgstr "На смене с {0}"
+msgid "Close"
+msgstr "Закрыть"
+
+msgid "Collapse features table"
+msgstr "Свернуть таблицу функций"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Завершить"
msgid "Complete All"
msgstr "Завершить все"
+msgid "Complete passed"
+msgstr "Завершить прошедшие"
+
msgid "Completed"
msgstr "Завершено"
@@ -281,6 +320,9 @@ msgstr "Черновик"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Перетащите файл сюда или нажмите для выбора файла"
+msgid "Drag to resize drawing and features"
+msgstr "Перетащите, чтобы изменить размер чертежа и функций"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Перетаскивание {0} отменено."
@@ -325,6 +367,12 @@ msgstr "Ошибка"
msgid "Estimated"
msgstr "План"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Каждый блок имеет вердикт: {passes} прошли и {fails} не прошли. Партия закрывается с маршрутизацией каждого блока к его собственному результату."
+
+msgid "Expand features table"
+msgstr "Развернуть таблицу функций"
+
msgid "Expired"
msgstr "Истекло"
@@ -337,6 +385,12 @@ msgstr "Истекает {date}"
msgid "Expiring first"
msgstr "Истекает первым"
+msgid "Failed"
+msgstr "Не пройдено"
+
+msgid "Failed features"
+msgstr "Неудачные функции"
+
msgid "Failed to complete inventory adjustment"
msgstr "Не удалось выполнить корректировку запасов"
@@ -349,6 +403,12 @@ msgstr "Не удалось загрузить активные операции
msgid "Failed to fetch storageUnits"
msgstr "Не удалось получить единицы хранения"
+msgid "Failed to save measurement"
+msgstr "Не удалось сохранить измерение"
+
+msgid "Failed to save result"
+msgstr "Не удалось сохранить результат"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Не удалось загрузить файл: {0}"
@@ -356,6 +416,12 @@ msgstr "Не удалось загрузить файл: {0}"
msgid "Failed to upload image"
msgstr "Не удалось загрузить изображение"
+msgid "Feature"
+msgstr "Функция"
+
+msgid "Features"
+msgstr "Характеристики"
+
msgid "File size exceeds 10MB limit"
msgstr "Размер файла превышает ограничение в 10 МБ"
@@ -405,6 +471,12 @@ msgstr "Имперская"
msgid "In Progress"
msgstr "В работе"
+msgid "Inspect Item"
+msgstr "Проверить элемент"
+
+msgid "inspected"
+msgstr "проверенный"
+
msgid "Insufficient quantity"
msgstr "Недостаточное количество"
@@ -498,6 +570,9 @@ msgstr "Записать брак для {0}"
msgid "Login"
msgstr "Вход"
+msgid "Lot"
+msgstr "Партия"
+
msgid "Machine"
msgstr "Станок"
@@ -531,6 +606,9 @@ msgstr "Метрическая"
msgid "Model"
msgstr "Модель"
+msgid "More actions"
+msgstr "Дополнительные действия"
+
msgid "More Actions"
msgstr "Дополнительные действия"
@@ -595,6 +673,9 @@ msgstr "Нет файлов"
msgid "No Impact"
msgstr "Без влияния"
+msgid "No issue types configured"
+msgstr "Типы проблем не настроены"
+
msgid "No maintenance scheduled for today"
msgstr "На сегодня обслуживание не запланировано"
@@ -607,6 +688,9 @@ msgstr "Нет материалов"
msgid "No open jobs"
msgstr "Нет открытых заданий"
+msgid "No open units to allocate"
+msgstr "Нет открытых единиц для распределения"
+
msgid "No operators"
msgstr "Нет операторов"
@@ -625,6 +709,9 @@ msgstr "Принтер не настроен"
msgid "No recent operations"
msgstr "Нет недавних операций"
+msgid "No remaining entities to inspect."
+msgstr "Нет оставшихся объектов для проверки."
+
msgid "No results"
msgstr "Нет результатов"
@@ -634,6 +721,9 @@ msgstr "Результаты отсутствуют"
msgid "No results found"
msgstr "Ничего не найдено"
+msgid "No samples required."
+msgstr "Образцы не требуются."
+
msgid "No scheduled time"
msgstr "Нет запланированного времени"
@@ -683,6 +773,9 @@ msgstr "Ой. Вы не должны видеть эту страницу. Со
msgid "Open"
msgstr "Открытые"
+msgid "Open an NCR for MRB disposition"
+msgstr "Открыть NCR для решения MRB"
+
msgid "Open Jobs"
msgstr "Открытые задания"
@@ -698,12 +791,21 @@ msgstr "Выполнено оператором"
msgid "Optional"
msgstr "Опционально"
+msgid "Overall result"
+msgstr "Общий результат"
+
msgid "Parameters"
msgstr "Параметры"
msgid "Part"
msgstr "Деталь"
+msgid "Partial"
+msgstr "Частичный"
+
+msgid "Partial Disposition"
+msgstr "Частичное распределение"
+
msgid "Passed Inspection"
msgstr "Контроль пройден"
@@ -749,9 +851,6 @@ msgstr "Назад"
msgid "Preventive"
msgstr "Профилактическое"
-msgid "Previous"
-msgstr "Предыдущий"
-
msgid "Print"
msgstr "Печать"
@@ -801,6 +900,18 @@ msgstr "Записать"
msgid "Record {0}"
msgstr "Запись {0}"
+msgid "Record only"
+msgstr "Только записать"
+
+msgid "Record Partial"
+msgstr "Записать частичный результат"
+
+msgid "Reject"
+msgstr "Отклонить"
+
+msgid "Reject Lot"
+msgstr "Отклонить партию"
+
msgid "Remove"
msgstr "Удалить"
@@ -813,12 +924,18 @@ msgstr "Списать запас"
msgid "Remove part"
msgstr "Удалить деталь"
+msgid "Result"
+msgstr "Результат"
+
msgid "Rework"
msgstr "Переделка"
msgid "Rework created successfully"
msgstr "Переработка успешно создана"
+msgid "Rework quantity"
+msgstr "Количество переработки"
+
msgid "Sales Order"
msgstr "Заказ на продажу"
@@ -828,21 +945,33 @@ msgstr "Сохранить"
msgid "Scan"
msgstr "Сканировать"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "Отсканируйте отслеживаемый объект, чтобы добавить первый столбец образца."
+
msgid "Scan or enter serial number"
msgstr "Сканируйте или введите серийный номер"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "Отсканируйте или введите ID отслеживаемого объекта, серийный номер или партию"
+
msgid "Scan or enter tracking number"
msgstr "Отсканируйте или введите номер отслеживания"
msgid "Scan or search serial number..."
msgstr "Сканируйте или ищите серийный номер..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Отсканируйте или выберите отслеживаемый объект из этой партии, чтобы добавить его в качестве столбца образца, затем запишите его результат в сетку."
+
msgid "Schedule"
msgstr "Расписание"
msgid "Scrap"
msgstr "Брак"
+msgid "Scrap quantity"
+msgstr "Количество брака"
+
msgid "Scrap Reason"
msgstr "Причина брака"
@@ -876,6 +1005,9 @@ msgstr "Выберите количество брака и причину"
msgid "Select a serial number to continue with this operation"
msgstr "Выберите серийный номер для продолжения операции"
+msgid "Select an issue type"
+msgstr "Выберите тип проблемы"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Выберите номенклатуру и укажите количество для выдачи"
@@ -899,6 +1031,9 @@ msgstr "Выберите серийный номер"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Выберите операцию, к которой нужно вернуться. Все операции от этой точки до текущей операции будут повторены."
+msgid "Selected"
+msgstr "Выбрано"
+
msgid "Send"
msgstr "Отправить"
@@ -978,6 +1113,10 @@ msgstr "Пользователь станции"
msgid "Station: {stationName}"
msgstr "Станция: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "Статистическая приемка не пройдена, поэтому вся партия из {0} считается несоответствующей (ISO 9001:2015 §8.7) — {passes} прошедших образцов и {fails} отказов. Направьте единицы ниже в брак или переработку, или только зафиксируйте результат."
+
msgid "Status"
msgstr "Статус"
@@ -1015,6 +1154,12 @@ msgstr "Тег"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "Количество готовой продукции по этой операции меньше требуемого количества {0}."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Партия будет отмечена как Пройдена, и {remaining} оставшихся единиц будут завершены в этой операции."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Партия все еще будет распределена, но NCR не может быть создана до тех пор, пока не будет настроен хотя бы один тип проблемы."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "В спецификации есть материалы с серийным или партионным учётом, которые не были полностью выданы. Завершение без выдачи может привести к некорректным записям прослеживаемости."
@@ -1048,6 +1193,9 @@ msgstr "Общее время: {0}"
msgid "Total: {0}"
msgstr "Итого: {0}"
+msgid "Tracked Entity"
+msgstr "Отслеживаемый объект"
+
msgid "Tracking"
msgstr "Отслеживание"
@@ -1070,6 +1218,9 @@ msgstr "Отменить выбор {0}"
msgid "Unsaved changes"
msgstr "Несохранённые изменения"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "До {maxAllocatable} единиц могут быть распределены; остальное записывается без проводки."
+
msgid "Update"
msgstr "Обновить"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index a571b10528..d129cb46cb 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -725,6 +725,9 @@ msgstr "Parametre Ekle"
msgid "Add Partner"
msgstr "Ortak Ekle"
+msgid "Add parts"
+msgstr "Parça ekle"
+
msgid "Add Permissions"
msgstr "İzin Ekle"
@@ -749,6 +752,9 @@ msgstr "Risk Ekle"
msgid "Add rule"
msgstr "Kural ekle"
+msgid "Add Sample"
+msgstr "Örnek Ekle"
+
msgid "Add Selector"
msgstr "Seçici Ekle"
@@ -764,6 +770,9 @@ msgstr "Yedek Parça Ekle"
msgid "Add Step"
msgstr "Adım Ekle"
+msgid "Add steps to preview the operator view."
+msgstr "Operatör görünümünü önizlemek için adımlar ekleyin."
+
msgid "Add Supplier"
msgstr "Tedarikçi Ekle"
@@ -776,6 +785,9 @@ msgstr "Zaman Kartı Ekle"
msgid "Add to stock for future use"
msgstr "Gelecekteki kullanım için stoğa ekle"
+msgid "Add tools"
+msgstr "Araç ekle"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "İlk {0}inizi ekleyin"
@@ -1041,6 +1053,9 @@ msgstr "Tümüne uygulanır"
msgid "Applies to all work centers"
msgstr "Tüm iş merkezlerine uygulanır"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "Kendi kuralı olmayan özelliklere ve bu plan bir muayene yaptırdığında lota uygulanır."
+
msgid "Apply"
msgstr "Uygula"
@@ -1401,8 +1416,11 @@ msgstr "Bu değişiklik emrini silmek istediğinizden emin misiniz?"
msgid "Are you sure you want to delete this gauge?"
msgstr "Bu kalibratörü silmek istediğinizden emin misiniz?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "Bu muayene belgesini silmek istediğinizden emin misiniz?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "Bu muayene planını silmek istediğinizden emin misiniz?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "Bu muayene planını silmek istediğinizden emin misiniz? Bu işlem geri alınamaz."
msgid "Are you sure you want to delete this issue workflow?"
msgstr "Bu iş akışını silmek istediğinizden emin misiniz?"
@@ -1534,6 +1552,9 @@ msgstr "{0} izni olan bir yöneticiye ilk {1}i eklemesini isteyin."
msgid "Assemblies"
msgstr "Montajlar"
+msgid "Assembly Instruction"
+msgstr "Montaj Talimatı"
+
msgid "Assembly Instructions"
msgstr "Montaj Talimatları"
@@ -1678,6 +1699,12 @@ msgstr "Otomatik oluşturulan QR kodu"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "Siparişler, işler, parçalar ve daha fazlası için otomatik numaralandırma formatları"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "Operatörün bir işlemi MES'te açtığında zamanlayıcıyı otomatik olarak başlat, böylece zaman günlükleri baştan itibaren kaydedilsin."
+
+msgid "Auto-start timer on open"
+msgstr "Açıldığında zamanlayıcıyı otomatik olarak başlat"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "Talep ve yeniden sipariş noktalarından otomatik satın alma önerileri"
@@ -1741,6 +1768,9 @@ msgstr "Dengeli"
msgid "Balloon"
msgstr "Balon"
+msgid "Ballooned drawings with inspection features."
+msgstr "İnceleme özellikleriyle balona alınmış çizimler."
+
msgid "Bank - Cash"
msgstr "Banka - Nakit"
@@ -2094,6 +2124,9 @@ msgstr "Yüklenemiyor — tedarikçi etkileşimi henüz oluşturulmadı"
msgid "Cannot upload to parts bucket without item ID"
msgstr "Öğe kimliği olmadan parçalar klasörüne yüklenemez"
+msgid "Caption"
+msgstr "Başlık"
+
msgid "Carbon"
msgstr "Karbon"
@@ -2193,6 +2226,12 @@ msgstr "Şampiyonlar"
msgid "Change"
msgstr "Değiştir"
+msgid "Change Document"
+msgstr "Belgeyi Değiştir"
+
+msgid "Change Inspection Plan"
+msgstr "Muayene Planını Değiştir"
+
msgid "Change order"
msgstr "Değişiklik emri"
@@ -2283,6 +2322,9 @@ msgstr "Sınıf"
msgid "Class (inherited)"
msgstr "Sınıf (Devralınan)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "Bir rota işlemini sınıflandırır: Proses, Montaj ve Muayene işlemleri MES'te kendi atölyenizde çalışır — Montaj kılavuzlu montaj görünümü ve Muayene kalite kontrolü alır — Dış İşleme işlemi ise bir tedarikçiye yaptırılır ve satın alma siparişi oluşturur; işlem aynı türü taşır ve yeni işlemlerde bunu varsayılan olarak ayarlar."
+
msgid "Clean and approve the migrated data"
msgstr "Geçirilen verileri temizleyin ve onaylayın"
@@ -2747,6 +2789,9 @@ msgstr "MRP önerilerini satın alma siparişlerine ve işlere dönüştürün."
msgid "Convert to Quote"
msgstr "Teklif Oluştur"
+msgid "Converting…"
+msgstr "Dönüştürülüyor…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Bir tedarikçinin satın alma birimini bir PO, makbuz veya fatura satırında envanter biriminize dönüştürür — 12'lik kutularda satın alın, birimlerde stok yapın."
@@ -3055,9 +3100,6 @@ msgstr "Değişiklik Emri Oluştur"
msgid "Create Issue"
msgstr "Sorun Oluştur"
-msgid "Create Issue from Inspection"
-msgstr "Muayeneeden Hata Oluştur"
-
msgid "Create Jobs"
msgstr "İş Oluştur"
@@ -3699,6 +3741,9 @@ msgstr "Varsayılan Öncelik"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "Bir satış faturası nakledildiğinde alacaklandırılan varsayılan gelir GL hesabı."
+msgid "Default Sampling"
+msgstr "Varsayılan Örnekleme"
+
msgid "Default shelf-life duration (days)"
msgstr "Varsayılan raf ömrü süresi (gün)"
@@ -3741,9 +3786,6 @@ msgstr "Önce bir üretim işlemini tanımlayın."
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Çok seviyeli BOM'ları ve Bill of Process'i (üretim yöntemlerini) tanımlayın"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "Lot başına kaç izlenen varlığın denetlendiğini ve parti reddedilmeden önce kaç hatanın tolere edildiğini tanımlar."
-
msgid "Delete"
msgstr "Sil"
@@ -3837,6 +3879,9 @@ msgstr "Grubu Sil"
msgid "Delete Holiday"
msgstr "Tatili Sil"
+msgid "Delete Inspection Plan"
+msgstr "Muayene Planını Sil"
+
msgid "Delete Issue"
msgstr "Sorunu Sil"
@@ -4329,6 +4374,9 @@ msgstr "Yeniden sıralamak için sürükleyin"
msgid "Drag to resize diagram and features"
msgstr "Şemayı ve özellikleri yeniden boyutlandırmak için sürükleyin"
+msgid "Drag to resize drawing and features"
+msgstr "Çizim ve özellikleri yeniden boyutlandırmak için sürükleyin"
+
msgid "Drag to zoom"
msgstr "Yakınlaştırmak için sürükleyin"
@@ -4549,8 +4597,8 @@ msgstr "Grubu Düzenle"
msgid "Edit Holiday"
msgstr "Tatil Düzenle"
-msgid "Edit Inspection Document"
-msgstr "Muayene Belgesini Düzenle"
+msgid "Edit Inspection Plan"
+msgstr "Muayene Planını Düzenle"
msgid "Edit Item Group"
msgstr "Ürün Grubunu Düzenle"
@@ -5236,6 +5284,9 @@ msgstr "GL raporlamanızı dilimlemek için ekstra etiketler"
msgid "Fail"
msgstr "Başarısız"
+msgid "Failed features"
+msgstr "Başarısız özellikler"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO (ilk son kullanma tarihi, ilk çıkış)"
@@ -5479,6 +5530,21 @@ msgstr "Yapılandırma kuralını kaydetme başarısız oldu"
msgid "Failed to save diagram"
msgstr "Şemayı kaydetme başarısız oldu"
+msgid "Failed to save measurement"
+msgstr "Ölçüm kaydedilemedi"
+
+msgid "Failed to save parts"
+msgstr "Parça kaydedilemedi"
+
+msgid "Failed to save result"
+msgstr "Sonuç kaydedilemedi"
+
+msgid "Failed to save slides"
+msgstr "Slayt kaydedilemedi"
+
+msgid "Failed to save tools"
+msgstr "Araç kaydedilemedi"
+
msgid "Failed to update batch property"
msgstr "Toplu özelliği güncelleme başarısız oldu"
@@ -6400,15 +6466,6 @@ msgstr "Etkin olmayan eylemler seçim listelerinde görünmeyecektir"
msgid "Inbound inspection"
msgstr "Gelen Muhasebesi"
-msgid "Inbound Inspection"
-msgstr "Gelen Muayene"
-
-msgid "Inbound Inspections"
-msgstr "Gelen Muayeneler"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "Gelen Muayeneler: Farklı Denetçi Gerektirir"
-
msgid "Inbox"
msgstr "Gelen Kutusu"
@@ -6454,6 +6511,12 @@ msgstr "Dolaylı Malzemeler ve Hizmetler (varsayılan)"
msgid "Infrastructure"
msgstr "Altyapı"
+msgid "Inherit"
+msgstr "Devral"
+
+msgid "Inherit document default"
+msgstr "Belge varsayılanını devral"
+
msgid "Inherit From Materials"
msgstr "Malzemelerden Devral"
@@ -6490,32 +6553,35 @@ msgstr "İlk N'yi İncele"
msgid "Inspect Item"
msgstr "Ürünü İncele"
-msgid "Inspect Next Item"
-msgstr "Sonraki Öğeyi İncele"
-
msgid "Inspection"
msgstr "Kontrol"
-msgid "Inspection Document"
-msgstr "Muayene Belgesi"
-
-msgid "Inspection Documents"
-msgstr "Muayene Belgeleri"
-
msgid "Inspection Level"
msgstr "Muayene Seviyesi"
+msgid "Inspection Plan"
+msgstr "Muayene Planı"
+
+msgid "Inspection Plan Assignments"
+msgstr "Muayene Planı Atamalar"
+
+msgid "Inspection Plans"
+msgstr "Muayene Planları"
+
msgid "Inspection Status"
msgstr "Kontrol Durumu"
+msgid "Inspections"
+msgstr "Muayeneler"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "Muayeneler, uygunsuzluk ve CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "Muayeneler, Uygunsuzluk, CAPA"
-msgid "Inspector"
-msgstr "Denetçi"
+msgid "Inspections: Require Different Inspector"
+msgstr "Muayeneler: Farklı Müfettiş Gereklidir"
msgid "Install"
msgstr "Yükle"
@@ -7439,15 +7505,9 @@ msgstr "Tamamlandı Olarak İşaretle"
msgid "Mark Light Mode"
msgstr "Aydınlık Mod Markası"
-msgid "Mark lot as partial?"
-msgstr "Lotu kısmi olarak işaretlemek mi?"
-
msgid "Mark not done"
msgstr "Yapılmadı olarak işaretle"
-msgid "Mark Partial"
-msgstr "Kısmi Olarak İşaretle"
-
msgid "Mark scope as agreed"
msgstr "Kapsamı kabul edildi olarak işaretle"
@@ -7960,8 +8020,8 @@ msgstr "Yeni Tatil"
msgid "New IC Transaction"
msgstr "Yeni IC İşlemi"
-msgid "New Inspection Document"
-msgstr "Yeni Muayene Belgesi"
+msgid "New Inspection Plan"
+msgstr "Yeni Muayene Planı"
msgid "New Inventory Count"
msgstr "Yeni Envanter Sayımı"
@@ -8332,6 +8392,9 @@ msgstr "Atanmış grup yok"
msgid "No image"
msgstr "Resim yok"
+msgid "No inspection plans"
+msgstr "Muayene planı yok"
+
msgid "No issue types configured"
msgstr "Hiçbir sorun türü yapılandırılmamış"
@@ -8392,6 +8455,9 @@ msgstr "Henüz üst kaynaklar kaydedilmedi. Atıfı yenilemek için planlama say
msgid "No part ID"
msgstr "Parça kimliği yok"
+msgid "No parts"
+msgstr "Parça yok"
+
msgid "No payables"
msgstr "Ödeme yükümlülüğü yok"
@@ -8428,6 +8494,9 @@ msgstr "Teklif Nedeni Yok"
msgid "No receivables"
msgstr "Alacak yok"
+msgid "No reference image"
+msgstr "Referans resim yok"
+
msgid "No remaining entities to inspect."
msgstr "İncelenecek kalan varlık yok."
@@ -8443,9 +8512,6 @@ msgstr "Burada satır yok."
msgid "No rules assigned"
msgstr "Atanmış kural yok"
-msgid "No samples inspected yet."
-msgstr "Henüz örnek incelenmedi."
-
msgid "No single, trusted number for inventory or job status"
msgstr "Envanter veya iş durumu için tek bir güvenilir sayı yok"
@@ -8464,6 +8530,12 @@ msgstr "Henüz tedarikçi yok"
msgid "No time entries for this week"
msgstr "Bu hafta için zaman girişi yok"
+msgid "No tools"
+msgstr "Araç yok"
+
+msgid "No tools for this step"
+msgstr "Bu adım için araç yok"
+
msgid "No transactions in this period"
msgstr "Bu dönemde işlem yok"
@@ -8773,6 +8845,9 @@ msgstr "Operasyon"
msgid "Operation Order"
msgstr "Operasyon Sırası"
+msgid "Operation Timer"
+msgstr "İşlem Zamanlayıcısı"
+
msgid "Operation Type"
msgstr "Operasyon Türü"
@@ -8900,6 +8975,9 @@ msgstr "Genel Gider Sapması"
msgid "Over-applied by"
msgstr "Fazla uygulandı"
+msgid "Overall result"
+msgstr "Genel sonuç"
+
msgid "Overdue"
msgstr "Geçmiş"
@@ -9027,9 +9105,6 @@ msgstr "Parça Numarası"
msgid "Part Supersession"
msgstr "Parça Yerini Alma"
-msgid "Partial"
-msgstr "Kısmi"
-
msgid "Partner"
msgstr "İş Ortağı"
@@ -9246,6 +9321,9 @@ msgstr "Adet/Saat"
msgid "Pieces/Minute"
msgstr "Parça/Dakika"
+msgid "Pin"
+msgstr "Sabitle"
+
msgid "Pinned"
msgstr "Sabitlenmiş"
@@ -9447,6 +9525,9 @@ msgstr "Önceki Tarih"
msgid "Previous page"
msgstr "Önceki sayfa"
+msgid "Previous step"
+msgstr "Önceki adım"
+
msgid "Price break actions"
msgstr "Fiyat kırılımı işlemleri"
@@ -10138,9 +10219,6 @@ msgstr "Kayıt silindi"
msgid "Record inspections tied to a part and a job"
msgstr "Bir parça ve bir işe bağlı muayeneleri kaydedin"
-msgid "Record the inspection result for this sample."
-msgstr "Bu numune için muayene sonucunu kaydedin."
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "Ölçü aletiyle ilgili kalibrasyonda, okumaları güvenilir olması için aletin onarılması gerektiği kaydedilmiştir."
@@ -10178,7 +10256,7 @@ msgid "Refresh exchange rate"
msgstr "Döviz kurunu yenile"
msgid "Regenerate"
-msgstr "Yenile"
+msgstr "Yeniden Oluştur"
msgid "Regenerating thumbnail…"
msgstr "Küçük resim yenileniyor…"
@@ -10265,9 +10343,6 @@ msgstr "{label}'i Kaldır"
msgid "Remove condition"
msgstr "Koşulu kaldır"
-msgid "Remove feature"
-msgstr "Özelliği kaldır"
-
msgid "Remove filter"
msgstr "Filtreyi kaldır"
@@ -10286,12 +10361,21 @@ msgstr "Siparişi kaldır"
msgid "Remove pair"
msgstr "Çifti kaldır"
+msgid "Remove part"
+msgstr "Parçayı kaldır"
+
+msgid "Remove slide"
+msgstr "Slaytı kaldır"
+
msgid "Remove sort by column"
msgstr "Sıralamayı kaldır"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "Bu depolama türünü tüm referans veren depolama birimlerinden kaldırır ve siler. Bu geri alınamaz."
+msgid "Remove tool"
+msgstr "Aracı kaldır"
+
msgid "Removed"
msgstr "Kaldırıldı"
@@ -10421,9 +10505,6 @@ msgstr "Eylem Gerektirir"
msgid "Requires Adjustment"
msgstr "Ayarlama Gerektirir"
-msgid "Requires Inspection"
-msgstr "Kontrol Gerektirir"
-
msgid "Requires Repair"
msgstr "Onarım Gerektirir"
@@ -10444,8 +10525,8 @@ msgstr "PIN'i Sıfırla"
msgid "Reset PIN for {0} {1}"
msgstr "PIN'i sıfırla {0} {1}"
-msgid "Reset View"
-msgstr "Görünümü Sıfırla"
+msgid "Reset view"
+msgstr "Görünümü sıfırla"
msgid "Residual value"
msgstr "Artık değer"
@@ -10797,15 +10878,14 @@ msgstr "Kitapta aynı"
msgid "Sample"
msgstr "Örnek"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "Örnek {0}"
-
msgid "Sample Size"
msgstr "Örnek Boyutu"
-msgid "Sampling Plan"
-msgstr "Numune Alma Planı"
+msgid "Sampling"
+msgstr "Örnekleme"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "Örnekleme — Özellik {featureLabel}"
msgid "Sampling Standard"
msgstr "Örnekleme Standardı"
@@ -10852,8 +10932,8 @@ msgstr "Takip numarasını tarayın veya girin"
msgid "Scan or search..."
msgstr "Tarama veya arayın..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "Bu partiden izlenen bir varlığı tarayın veya seçin ve muayene sonucunu kaydedin."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Bu lottan izlenen bir varlığı taramak veya seçmek için bunu örnek sütun olarak ekleyin, ardından sonucunu ızgarada kaydedin."
msgid "Scan the tracking ID for this line"
msgstr "Bu satır için takip kimliğini tarayın"
@@ -10900,6 +10980,9 @@ msgstr "Kapsamlar"
msgid "Scrap"
msgstr "Hurda"
+msgid "Scrap / Cost of Quality"
+msgstr "Atık / Kalite Maliyeti"
+
msgid "Scrap Percent"
msgstr "Hurda Yüzdesi"
@@ -10960,6 +11043,9 @@ msgstr "İş Ara"
msgid "Search operators..."
msgstr "Operatörleri ara..."
+msgid "Search parts..."
+msgstr "Parça ara..."
+
msgid "Search processes..."
msgstr "Süreçleri ara..."
@@ -10969,6 +11055,9 @@ msgstr "İlgili öğeleri ara..."
msgid "Search suppliers..."
msgstr "Tedarikçileri ara..."
+msgid "Search tools..."
+msgstr "Araç ara..."
+
msgid "Search..."
msgstr "Ara..."
@@ -10990,6 +11079,9 @@ msgstr "Bir atanan seçin"
msgid "Select a default approver"
msgstr "Varsayılan onaylayıcı seçin"
+msgid "Select a document"
+msgstr "Belge seçin"
+
msgid "Select a new owner"
msgstr "Yeni bir sahip seç"
@@ -11647,6 +11739,9 @@ msgstr "Yedek Parça Tüketimi"
msgid "Spare Part Cost"
msgstr "Yedek Parça Maliyeti"
+msgid "Spec"
+msgstr "Spesifikasyon"
+
msgid "Specific Customer"
msgstr "Belirli Müşteri"
@@ -11777,6 +11872,12 @@ msgstr "adımlar"
msgid "Steps"
msgstr "Adımlar"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "Adımlar montaj talimatından devralınır."
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "Adımlar muayene planından devralınır."
+
msgid "Stock Transfer ID"
msgstr "Stok Transfer Kimliği"
@@ -12470,8 +12571,8 @@ msgstr "Müşteriye fiyat teklifi vermekten ödeme tahsilatına kadar uçtan uca
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Tablo güncellendiğinde güncellenmiş verilerle bir POST isteği alan uç nokta"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "Bu denetim belgesinin bağlı olduğu mühendislik çizimi; bu parça referansına karşı kaydedilen denetimler bu çizime başvur."
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "Bu muayene planının bağlı olduğu mühendislik çizimi; bu parça için kaydedilen muayeneler bu çizime geri başvurur."
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "Bu öğenin üretim sırasında kaybedilen çıkışının beklenen yüzdesi; planlama telafi etmek için talebi 1 / (1 - hurda) ile çarpar."
@@ -12620,15 +12721,15 @@ msgstr "Yazdırılan ve e-postayla gönderilen belgelerinizde gösterilen logola
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "Bu stok için lot tanımlayıcısı; lot başına bir satır, miktar o lot için eldedir."
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Lot açık kalır böylece daha sonra incelemeye ve elden çıkarmaya devam edebilirsiniz. Örneklenmiş sonuçlar korunur."
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "Lot bu olarak işaretlenecektir. Kayıtlarınız için {fails} örnek başarısızlığı kaydedilmiştir."
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Lot yine de reddedilecek, ancak en az bir Hata Türü yapılandırılana kadar Bir Uygunluk Raporu (NCR) oluşturulamaz."
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "Lot'un her özellik başına örnekleme planı seçilen belgeden yeniden çözülecektir."
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Bu tedarikçinin miktar ne olursa olsun bu işlem için tahsil edeceği minimum tutar; kâr-zarar noktası hacmi altındaki işler hala en az bu tutarına mal olur."
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "Bir işin çalıştırılmış olduğu işlemlerin sıralanmış sırası, yöntemin süreç faturasından kopyalanmıştır."
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "Orijinal model dosyası artık kullanılamıyor"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Malları envanterten bir müşteriye çıkaran ve yol boyunca COGS'yi deftere geçiren giden deftere nakil belgesi."
@@ -12719,8 +12820,8 @@ msgstr "Carbon tarafındaki uygulamanızı yönetecek ve onlara nasıl ulaşaca
msgid "The people on your team and their access to Carbon"
msgstr "Ekibinizdeki kişiler ve Carbon'a erişimleri"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "Belge türünün okunabilir sayısının arkasındaki şirket başına sayaç, {prefix}{next+step, zero-padded}{suffix} öğesini bir araya getiriyor ve her belge oluşturulduğunda ilerlemiştir."
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "Belge türünün okunabilir numarasını oluşturan, şirket başına sayaç; ön ek, sıfırla dolgulu sonraki değer ve son eki birleştirerek, her belge oluşturulduğunda ilerler."
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "Uyumsuzluğun etkilenen malzemesine kaydedilen ürün başına sonuç — Beklemede, Tedarikçiye İade, Yeniden İşleme, Hurdaya Çıkarma veya Olduğu Gibi Kullan — her etkilenen partiye veya seriye kendi başına karar verilir."
@@ -13011,6 +13112,9 @@ msgstr "Bu bilgiler belge başlıklarında kullanılacaktır"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "Bu bilgiler tüm kullanıcılar tarafından görülecektir, bu yüzden ne paylaştığınıza dikkat edin."
+msgid "this inspection plan"
+msgstr "bu muayene planı"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "Bu satın alınan bir üründür — BoM/BoP'si yoktur; yalnızca öznitelikleri ve belgeleri değişebilir."
@@ -13459,9 +13563,6 @@ msgstr "Tip:"
msgid "Types"
msgstr "Tipler"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "Örneklenmeyen varlıklar daha sonra incelemeye ve elden çıkarmaya devam edebilmeniz için Beklemede kalacaktır. Örneklenen sonuçlar korunur."
-
msgid "Unapplied"
msgstr "Uygulanmamış"
@@ -14311,6 +14412,9 @@ msgstr "Etkinleştirildiğinde, bu kategorideki öznitelikler bir kişinin genel
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "Etkinleştirildiğinde, çalışanlar bu özniteliğin değerini kendi profillerinde düzenleyebilir; aksi takdirde yalnızca yöneticiler bunu yapabilir."
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "Açık olduğunda, bir işlemi açmak zamanlayıcıyı otomatik olarak başlatır."
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "Etkinleştirildiğinde, fiyatlandırma kuralları (hacim indirimler, promosyonlar) hala bu geçersiz kılmanın üstüne uygulanır; devre dışı bırakıldığında, bu geçersiz kılma nihai fiyattır."
@@ -14437,8 +14541,8 @@ msgstr "Sayacın, seçilen süreç başladığında mı yoksa tamamlandığında
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "Bu lotun/serinin muayeneyi geçip geçmediği (Pass) veya geçemediği (Fail); bir Fail, stoğun kullanılabilir envantere alınmasını engeller."
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "Bu sürecin dahili iş merkezlerinde (Inside), dış tedarikçilerde (Outside) veya her ikisinde (Both) mi çalıştığı; farklı alt akış alanlarını gösterir ve planlamanın bu süreç için rotaları nasıl oluşturduğunu değiştirir."
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "Bu işlemin dahili iş merkezlerinde (Proses, Montaj veya Muayene) mı yoksa dış tedarikçilerde (Dış İşleme) mi çalışıp çalışmadığı; farklı aşağı yönlü alanları ortaya koymakta, bu işlem için planlama rotalarının nasıl çalıştığını değiştirmekte ve yeni işlemlerde işlem türünü varsayılan olarak ayarlamaktadır."
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "Bu işin üretimi bloklayıp (Aşağı), onu bozultuyor (Etki), planlanmış bir kapalı kalma penceresinde (Planlanmış) bulunuyor veya hiçbir üretim etkisi yok (Etki Yok); zamanlama ve müşteriye yönelik kapalı kalma iletişimini bilgilendirir."
@@ -14446,6 +14550,9 @@ msgstr "Bu işin üretimi bloklayıp (Aşağı), onu bozultuyor (Etki), planlanm
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "Seçilen izinlerin her kullanıcının zaten sahip olduğu şeylerin üstüne Eklenip Eklenmediği veya her kullanıcının izin setinin aşağıda seçilen kişilerle değiştirilmesi suretiyle Güncelleştirilmesi."
+msgid "Which document drives each inspection flow for this item."
+msgstr "Bu öğe için her inceleme akışını hangi belge yönlendirir."
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Hangi üretim olayı raf ömrü saatini başlatır — örneğin, doldurma, mühürleme veya nihai QC."
@@ -14608,6 +14715,9 @@ msgstr "Silme Hesabı"
msgid "Write-off for {0}"
msgstr "{0} için silme"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "Muayene reddiyelerinden ve NCR (Uygunluk Dışı Raporları) kararlarıyla atılan veya iade edilen stokun silinmesi"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Bir varlığın değerini faydalı kullanım süresi boyunca azaltma — oluşturduğunuz, taslak olarak gözden geçirdiğiniz ve deftere naklettiyiniz aylık batch."
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 6dc0a4c28f..cda5dfedd3 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} adet tamamlandı"
msgid "{0} Scrapped"
msgstr "{0} Hurdaya Çıkarılmış"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} geçen birim(ler) tamamlanacaktır."
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} örnek hata(ları) kaydedildi ve tamamlanmayacak — bunları işlemler menüsünden çözün."
+
msgid "About"
msgstr "Hakkında"
+msgid "Accept"
+msgstr "Kabul Et"
+
+msgid "Accept Lot"
+msgstr "Lotu Kabul Et"
+
+msgid "Accept lot?"
+msgstr "Lotu kabul et?"
+
msgid "Account Settings"
msgstr "Hesap Ayarları"
@@ -66,12 +81,27 @@ msgstr "Etiketleri doğrudan yazdırmak için yazdırma ayarlarında bir yazıc
msgid "Add Inventory"
msgstr "Envantere Ekle"
+msgid "Add Sample"
+msgstr "Örnek Ekle"
+
msgid "Add Spare Part"
msgstr "Yedek Parça Ekle"
msgid "All"
msgstr "Tümü"
+msgid "All rework"
+msgstr "Tümünü yeniden işle"
+
+msgid "All scrap"
+msgstr "Tümünü hurdaya çıkar"
+
+msgid "Allocate failed units"
+msgstr "Başarısız birimleri tahsis et"
+
+msgid "Allocate units"
+msgstr "Birimleri tahsis et"
+
msgid "Are you sure you want to delete this step?"
msgstr "Bu adımı silmek istediğinizden emin misiniz?"
@@ -165,6 +195,12 @@ msgstr "Çıkış Yap"
msgid "Clocked in since {0}"
msgstr "Giriş yapıldı: {0}"
+msgid "Close"
+msgstr "Kapat"
+
+msgid "Collapse features table"
+msgstr "Özellikler tablosunu daralt"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "Tamamla"
msgid "Complete All"
msgstr "Tümünü Tamamla"
+msgid "Complete passed"
+msgstr "Tamamlanan geçti"
+
msgid "Completed"
msgstr "Tamamlandı"
@@ -281,6 +320,9 @@ msgstr "Taslak"
msgid "Drag and drop a file here, or click to select a file"
msgstr "Dosyayı buraya sürükleyip bırakın veya bir dosya seçmek için tıklayın"
+msgid "Drag to resize drawing and features"
+msgstr "Çizimi ve özellikleri yeniden boyutlandırmak için sürükleyin"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "Taşıma {0} iptal edildi."
@@ -325,6 +367,12 @@ msgstr "Hata"
msgid "Estimated"
msgstr "Tahmini"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "Her birim için bir karar verildi: {passes} geçti ve {fails} başarısız oldu. Lot, her birim kendi sonucuna yönlendirilmek üzere kapanır."
+
+msgid "Expand features table"
+msgstr "Özellikler tablosunu genişlet"
+
msgid "Expired"
msgstr "Süresi Dolmuş"
@@ -337,6 +385,12 @@ msgstr "Son kullanma tarihi {date}'de"
msgid "Expiring first"
msgstr "İlk süresi dolacak"
+msgid "Failed"
+msgstr "Başarısız"
+
+msgid "Failed features"
+msgstr "Başarısız özellikler"
+
msgid "Failed to complete inventory adjustment"
msgstr "Envanter ayarlaması tamamlanamadı"
@@ -349,6 +403,12 @@ msgstr "Aktif operasyonlar alınamadı"
msgid "Failed to fetch storageUnits"
msgstr "Depolama birimlerini almak başarısız oldu"
+msgid "Failed to save measurement"
+msgstr "Ölçüm kaydedilemedi"
+
+msgid "Failed to save result"
+msgstr "Sonuç kaydedilemedi"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Dosyayı yüklemede başarısız oldu: {0}"
@@ -356,6 +416,12 @@ msgstr "Dosyayı yüklemede başarısız oldu: {0}"
msgid "Failed to upload image"
msgstr "Görsel yüklenemedi"
+msgid "Feature"
+msgstr "Özellik"
+
+msgid "Features"
+msgstr "Özellikler"
+
msgid "File size exceeds 10MB limit"
msgstr "Dosya boyutu 10MB sınırını aşıyor"
@@ -405,6 +471,12 @@ msgstr "İmparatorluk"
msgid "In Progress"
msgstr "Devam Ediyor"
+msgid "Inspect Item"
+msgstr "Ürünü İncele"
+
+msgid "inspected"
+msgstr "incelendi"
+
msgid "Insufficient quantity"
msgstr "Yetersiz miktar"
@@ -498,6 +570,9 @@ msgstr "Hata için kayıt yap {0}"
msgid "Login"
msgstr "Giriş Yap"
+msgid "Lot"
+msgstr "Lot"
+
msgid "Machine"
msgstr "Makine"
@@ -531,6 +606,9 @@ msgstr "Metrik"
msgid "Model"
msgstr "Model"
+msgid "More actions"
+msgstr "Daha fazla işlem"
+
msgid "More Actions"
msgstr "Daha Fazla İşlem"
@@ -595,6 +673,9 @@ msgstr "Dosya yok"
msgid "No Impact"
msgstr "Etki Yok"
+msgid "No issue types configured"
+msgstr "Sorun türü yapılandırılmadı"
+
msgid "No maintenance scheduled for today"
msgstr "Bugün planlanmış bakım yok"
@@ -607,6 +688,9 @@ msgstr "Malzeme yok"
msgid "No open jobs"
msgstr "Açık iş yok"
+msgid "No open units to allocate"
+msgstr "Tahsis edilecek açık birim yok"
+
msgid "No operators"
msgstr "Operatör bulunamadı"
@@ -625,6 +709,9 @@ msgstr "Yazıcı yapılandırılmadı"
msgid "No recent operations"
msgstr "Son yakın işlemler yok"
+msgid "No remaining entities to inspect."
+msgstr "İncelenecek kalan varlık yok."
+
msgid "No results"
msgstr "Sonuç bulunamadı"
@@ -634,6 +721,9 @@ msgstr "Sonuç bulunamadı"
msgid "No results found"
msgstr "Sonuç bulunamadı"
+msgid "No samples required."
+msgstr "Örnek gerekli değil."
+
msgid "No scheduled time"
msgstr "Planlanmış zaman yok"
@@ -683,6 +773,9 @@ msgstr "Üzgünüz. Bu sayfayı görmemelisiniz. Sonunda bir açılış sayfası
msgid "Open"
msgstr "Açık"
+msgid "Open an NCR for MRB disposition"
+msgstr "MRB kararı için NCR aç"
+
msgid "Open Jobs"
msgstr "Açık İşler"
@@ -698,12 +791,21 @@ msgstr "Operatör Tarafından Yapıldı"
msgid "Optional"
msgstr "İsteğe bağlı"
+msgid "Overall result"
+msgstr "Genel sonuç"
+
msgid "Parameters"
msgstr "Parametreler"
msgid "Part"
msgstr "Parça"
+msgid "Partial"
+msgstr "Kısmi"
+
+msgid "Partial Disposition"
+msgstr "Kısmi Disposition"
+
msgid "Passed Inspection"
msgstr "Kontrolden Geçti"
@@ -749,9 +851,6 @@ msgstr "Önceki"
msgid "Preventive"
msgstr "Önleyici"
-msgid "Previous"
-msgstr "Önceki"
-
msgid "Print"
msgstr "Yazdır"
@@ -801,6 +900,18 @@ msgstr "Kaydet"
msgid "Record {0}"
msgstr "Kayıt {0}"
+msgid "Record only"
+msgstr "Yalnızca kaydet"
+
+msgid "Record Partial"
+msgstr "Kısmi Kaydı"
+
+msgid "Reject"
+msgstr "Reddet"
+
+msgid "Reject Lot"
+msgstr "Lotu Reddet"
+
msgid "Remove"
msgstr "Kaldır"
@@ -813,12 +924,18 @@ msgstr "Stoktan Çıkar"
msgid "Remove part"
msgstr "Parçayı kaldır"
+msgid "Result"
+msgstr "Sonuç"
+
msgid "Rework"
msgstr "Revizyon"
msgid "Rework created successfully"
msgstr "Yeniden işleme başarıyla oluşturuldu"
+msgid "Rework quantity"
+msgstr "Yeniden işleme miktarı"
+
msgid "Sales Order"
msgstr "Satış Siparişi"
@@ -828,21 +945,33 @@ msgstr "Kaydet"
msgid "Scan"
msgstr "Tarama"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "İlk örnek sütununu eklemek için izlenen bir varlığı tarayın."
+
msgid "Scan or enter serial number"
msgstr "Seri numarası tarayın veya girin"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "İzlenen varlık kimliğini, seri numarasını veya grubunu tarayın veya girin"
+
msgid "Scan or enter tracking number"
msgstr "Takip numarasını tarayın veya girin"
msgid "Scan or search serial number..."
msgstr "Seri numaras tarayın veya arayın..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "Bu lottan izlenen bir varlığı tarayın veya seçin, onu bir örnek sütunu olarak ekleyin ve sonucunu ızgarada kaydedin."
+
msgid "Schedule"
msgstr "Planlama"
msgid "Scrap"
msgstr "Hurda"
+msgid "Scrap quantity"
+msgstr "Hurda miktarı"
+
msgid "Scrap Reason"
msgstr "Hurda Nedeni"
@@ -876,6 +1005,9 @@ msgstr "Bir hurda miktarı ve nedeni seçin"
msgid "Select a serial number to continue with this operation"
msgstr "Bu işlemle devam etmek için bir seri numarası seçin"
+msgid "Select an issue type"
+msgstr "Bir sorun türü seçin"
+
msgid "Select an item and specify the quantity to issue"
msgstr "Bir parça seçin ve çıkarılacak miktarı belirtin"
@@ -899,6 +1031,9 @@ msgstr "Seri Numarası Seçin"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "Geri dönülecek işlemi seçin. O noktadan mevcut işleme kadar olan tüm işlemler yeniden yapılacaktır."
+msgid "Selected"
+msgstr "Seçildi"
+
msgid "Send"
msgstr "Gönder"
@@ -978,6 +1113,10 @@ msgstr "İstasyon Kullanıcısı"
msgid "Station: {stationName}"
msgstr "İstasyon: {stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "İstatistiksel kabul başarısız oldu, bu nedenle {0} birimlik tüm lot uygunsuz olarak kabul edilir (ISO 9001:2015 §8.7) — {passes} örnek geçti ve {fails} hata(lar). Aşağıdaki birimleri hurda veya yeniden işlemeye yönlendirin veya yalnızca kararı kaydedin."
+
msgid "Status"
msgstr "Durum"
@@ -1015,6 +1154,12 @@ msgstr "Etiket"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "Bu işlem için tamamlanan miktar, gerekli miktar olan {0}'dan azdır."
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "Lot Passed olarak işaretlenecek ve {remaining} kalan birim(ler) bu operasyonda tamamlanacaktır."
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "Lot yine de işleme tabi tutulacak, ancak en az bir Sorun Türü yapılandırılana kadar bir NCR oluşturulamaz."
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "Malzeme listesindeki seri veya parti takipli malzemeler tam olarak verilmemiş. Vermeden tamamlamak, yanlış izlenebilirlik kayıtlarına neden olabilir."
@@ -1048,6 +1193,9 @@ msgstr "Toplam süre: {0}"
msgid "Total: {0}"
msgstr "Toplam: {0}"
+msgid "Tracked Entity"
+msgstr "İzlenen Varlık"
+
msgid "Tracking"
msgstr "Takip"
@@ -1070,6 +1218,9 @@ msgstr "Çıkart {0}"
msgid "Unsaved changes"
msgstr "Kaydedilmemiş değişiklikler"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "En fazla {maxAllocatable} birim ayrılabilir; geri kalanı deftere kaydedilmeden kaydedilir."
+
msgid "Update"
msgstr "Güncelle"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index c461f015ac..9cd08ae66f 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -725,6 +725,9 @@ msgstr "添加参数"
msgid "Add Partner"
msgstr "添加合作伙伴"
+msgid "Add parts"
+msgstr "添加零件"
+
msgid "Add Permissions"
msgstr "添加权限"
@@ -749,6 +752,9 @@ msgstr "添加风险"
msgid "Add rule"
msgstr "添加规则"
+msgid "Add Sample"
+msgstr "添加样品"
+
msgid "Add Selector"
msgstr "添加选择器"
@@ -764,6 +770,9 @@ msgstr "添加备件"
msgid "Add Step"
msgstr "添加步骤"
+msgid "Add steps to preview the operator view."
+msgstr "添加步骤以预览操作员视图。"
+
msgid "Add Supplier"
msgstr "添加供应商"
@@ -776,6 +785,9 @@ msgstr "添加工时卡"
msgid "Add to stock for future use"
msgstr "添加到库存以供将来使用"
+msgid "Add tools"
+msgstr "添加工具"
+
#. placeholder {0}: copy.noun
msgid "Add your first {0}"
msgstr "添加您的第一个{0}"
@@ -1041,6 +1053,9 @@ msgstr "适用于全部"
msgid "Applies to all work centers"
msgstr "适用于所有工作中心"
+msgid "Applies to features without their own rule, and to the lot when this plan drives an inspection."
+msgstr "适用于没有自己规则的功能,以及当该计划驱动检验时的批次。"
+
msgid "Apply"
msgstr "应用"
@@ -1401,8 +1416,11 @@ msgstr "您确定要删除此变更单吗?"
msgid "Are you sure you want to delete this gauge?"
msgstr "你确定要删除此量规吗?"
-msgid "Are you sure you want to delete this inspection document?"
-msgstr "你确定要删除此检验文件吗?"
+msgid "Are you sure you want to delete this inspection plan?"
+msgstr "你确定要删除此检验计划吗?"
+
+msgid "Are you sure you want to delete this inspection plan? This cannot be undone."
+msgstr "你确定要删除此检验计划吗?此操作无法撤销。"
msgid "Are you sure you want to delete this issue workflow?"
msgstr "你确定要删除此问题工作流吗?"
@@ -1534,6 +1552,9 @@ msgstr "请求具有{0}权限的管理员添加第一个{1}。"
msgid "Assemblies"
msgstr "装配件"
+msgid "Assembly Instruction"
+msgstr "装配说明"
+
msgid "Assembly Instructions"
msgstr "装配说明"
@@ -1678,6 +1699,12 @@ msgstr "自动生成的二维码"
msgid "Auto-numbering formats for orders, jobs, parts, and more"
msgstr "订单、工作、零件等的自动编号格式"
+msgid "Auto-start the operator's timer when they open an operation in the MES so time logs are captured from the start."
+msgstr "当操作员在MES中打开操作时自动启动计时器,以便从一开始就捕获时间日志。"
+
+msgid "Auto-start timer on open"
+msgstr "打开时自动启动计时器"
+
msgid "Auto-suggest purchases from demand and reorder points"
msgstr "根据需求和重新订购点自动建议采购"
@@ -1741,6 +1768,9 @@ msgstr "平衡"
msgid "Balloon"
msgstr "气球"
+msgid "Ballooned drawings with inspection features."
+msgstr "带有检验特性的标注图纸。"
+
msgid "Bank - Cash"
msgstr "银行-现金"
@@ -2094,6 +2124,9 @@ msgstr "无法上传 — 供应商互动尚未创建"
msgid "Cannot upload to parts bucket without item ID"
msgstr "无法在没有项目ID的情况下上传到零件存储桶"
+msgid "Caption"
+msgstr "标题"
+
msgid "Carbon"
msgstr "Carbon"
@@ -2193,6 +2226,12 @@ msgstr "冠军"
msgid "Change"
msgstr "更改"
+msgid "Change Document"
+msgstr "变更文档"
+
+msgid "Change Inspection Plan"
+msgstr "更改检验计划"
+
msgid "Change order"
msgstr "变更单"
@@ -2283,6 +2322,9 @@ msgstr "类别"
msgid "Class (inherited)"
msgstr "类(继承)"
+msgid "Classifies a routing operation: Process, Assembly, and Inspection operations run on your own shop floor in the MES — Assembly gets the guided assembly view and Inspection a quality check — while an Outside Processing operation is subcontracted to a supplier and creates a purchase order; the process carries the same type and defaults it on new operations."
+msgstr "对工艺操作进行分类:流程、组装和检测操作在MES中的您自己的车间运行——组装获得引导的组装视图,检测获得质量检查——而外部加工操作则分包给供应商并创建采购订单;流程承载相同的类型,并在新操作上默认设置该类型。"
+
msgid "Clean and approve the migrated data"
msgstr "清理并批准迁移的数据"
@@ -2747,6 +2789,9 @@ msgstr "将MRP建议转换为采购订单和工作单。"
msgid "Convert to Quote"
msgstr "转换为报价"
+msgid "Converting…"
+msgstr "转换中…"
+
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "将供应商的采购单位转换为采购订单、收据或发票行中的库存单位 — 以12个纸箱购买,以单位储存。"
@@ -3055,9 +3100,6 @@ msgstr "创建变更单"
msgid "Create Issue"
msgstr "创建问题"
-msgid "Create Issue from Inspection"
-msgstr "从检验创建问题"
-
msgid "Create Jobs"
msgstr "创建工作"
@@ -3699,6 +3741,9 @@ msgstr "默认优先级"
msgid "Default revenue GL account credited when a sales invoice posts."
msgstr "销售发票过帐时贷记的默认收入GL账户。"
+msgid "Default Sampling"
+msgstr "默认抽样"
+
msgid "Default shelf-life duration (days)"
msgstr "默认保质期时长(天)"
@@ -3741,9 +3786,6 @@ msgstr "首先定义制造操作。"
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "定义多级物料清单和工艺流程(制造方法)"
-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."
-msgstr "定义每批检查多少个跟踪实体,以及在批次被拒绝前允许多少个失败。"
-
msgid "Delete"
msgstr "删除"
@@ -3837,6 +3879,9 @@ msgstr "删除群组"
msgid "Delete Holiday"
msgstr "删除假期"
+msgid "Delete Inspection Plan"
+msgstr "删除检验计划"
+
msgid "Delete Issue"
msgstr "删除问题"
@@ -4329,6 +4374,9 @@ msgstr "拖动以重新排序"
msgid "Drag to resize diagram and features"
msgstr "拖动以调整图表和功能的大小"
+msgid "Drag to resize drawing and features"
+msgstr "拖动以调整绘图和功能的大小"
+
msgid "Drag to zoom"
msgstr "拖动以缩放"
@@ -4549,8 +4597,8 @@ msgstr "编辑组"
msgid "Edit Holiday"
msgstr "编辑假期"
-msgid "Edit Inspection Document"
-msgstr "编辑检验文件"
+msgid "Edit Inspection Plan"
+msgstr "编辑检验计划"
msgid "Edit Item Group"
msgstr "编辑项目组"
@@ -5236,6 +5284,9 @@ msgstr "用于切分总账报告的额外标签"
msgid "Fail"
msgstr "失败"
+msgid "Failed features"
+msgstr "失效特性"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create asset class: {0}"
msgstr "FEFO(先到期先出)"
@@ -5479,6 +5530,21 @@ msgstr "保存配置规则失败"
msgid "Failed to save diagram"
msgstr "保存图表失败"
+msgid "Failed to save measurement"
+msgstr "保存测量值失败"
+
+msgid "Failed to save parts"
+msgstr "保存零件失败"
+
+msgid "Failed to save result"
+msgstr "未能保存结果"
+
+msgid "Failed to save slides"
+msgstr "保存幻灯片失败"
+
+msgid "Failed to save tools"
+msgstr "保存工具失败"
+
msgid "Failed to update batch property"
msgstr "批处理属性更新失败"
@@ -6400,15 +6466,6 @@ msgstr "不活跃的操作将不会出现在选择列表中"
msgid "Inbound inspection"
msgstr "入站检验"
-msgid "Inbound Inspection"
-msgstr "入站检验"
-
-msgid "Inbound Inspections"
-msgstr "入站检验"
-
-msgid "Inbound Inspections: Require Different Inspector"
-msgstr "入库检验:需要不同的检验员"
-
msgid "Inbox"
msgstr "收件箱"
@@ -6454,6 +6511,12 @@ msgstr "间接材料和服务(默认)"
msgid "Infrastructure"
msgstr "基础设施"
+msgid "Inherit"
+msgstr "继承"
+
+msgid "Inherit document default"
+msgstr "继承文档默认值"
+
msgid "Inherit From Materials"
msgstr "从材料继承"
@@ -6490,32 +6553,35 @@ msgstr "检查前N个"
msgid "Inspect Item"
msgstr "检查项目"
-msgid "Inspect Next Item"
-msgstr "检查下一项"
-
msgid "Inspection"
msgstr "检验"
-msgid "Inspection Document"
-msgstr "检验文件"
-
-msgid "Inspection Documents"
-msgstr "检验文件"
-
msgid "Inspection Level"
msgstr "检验水平"
+msgid "Inspection Plan"
+msgstr "检验计划"
+
+msgid "Inspection Plan Assignments"
+msgstr "检验计划分配"
+
+msgid "Inspection Plans"
+msgstr "检验计划"
+
msgid "Inspection Status"
msgstr "检验状态"
+msgid "Inspections"
+msgstr "检验"
+
msgid "Inspections, nonconformance, and CAPA"
msgstr "检验、不符合和CAPA"
msgid "Inspections, Nonconformance, CAPA"
msgstr "检验、不符合、纠正预防措施"
-msgid "Inspector"
-msgstr "检查员"
+msgid "Inspections: Require Different Inspector"
+msgstr "检验:需要不同的检验员"
msgid "Install"
msgstr "安装"
@@ -7439,15 +7505,9 @@ msgstr "标记为完成"
msgid "Mark Light Mode"
msgstr "标记浅色模式"
-msgid "Mark lot as partial?"
-msgstr "将批次标记为部分?"
-
msgid "Mark not done"
msgstr "标记为未完成"
-msgid "Mark Partial"
-msgstr "标记为部分"
-
msgid "Mark scope as agreed"
msgstr "将范围标记为已同意"
@@ -7960,8 +8020,8 @@ msgstr "新假期"
msgid "New IC Transaction"
msgstr "新IC事务"
-msgid "New Inspection Document"
-msgstr "新检验文件"
+msgid "New Inspection Plan"
+msgstr "新检验计划"
msgid "New Inventory Count"
msgstr "新库存盘点"
@@ -8332,6 +8392,9 @@ msgstr "未分配任何组"
msgid "No image"
msgstr "没有图像"
+msgid "No inspection plans"
+msgstr "无检验计划"
+
msgid "No issue types configured"
msgstr "未配置问题类型"
@@ -8392,6 +8455,9 @@ msgstr "尚未记录任何父源。点击计划页面上的\"重新计算\"以
msgid "No part ID"
msgstr "无零件ID"
+msgid "No parts"
+msgstr "没有零件"
+
msgid "No payables"
msgstr "无应付款"
@@ -8428,6 +8494,9 @@ msgstr "无报价原因"
msgid "No receivables"
msgstr "无应收账款"
+msgid "No reference image"
+msgstr "没有参考图像"
+
msgid "No remaining entities to inspect."
msgstr "没有剩余的实体可检查。"
@@ -8443,9 +8512,6 @@ msgstr "这里没有行。"
msgid "No rules assigned"
msgstr "未分配规则"
-msgid "No samples inspected yet."
-msgstr "还没有检查任何样品。"
-
msgid "No single, trusted number for inventory or job status"
msgstr "没有单一的、可信的库存或工作状态数字"
@@ -8464,6 +8530,12 @@ msgstr "还没有供应商"
msgid "No time entries for this week"
msgstr "本周没有时间条目"
+msgid "No tools"
+msgstr "没有工具"
+
+msgid "No tools for this step"
+msgstr "此步骤没有工具"
+
msgid "No transactions in this period"
msgstr "此期间无交易"
@@ -8773,6 +8845,9 @@ msgstr "操作"
msgid "Operation Order"
msgstr "操作顺序"
+msgid "Operation Timer"
+msgstr "操作计时器"
+
msgid "Operation Type"
msgstr "操作类型"
@@ -8900,6 +8975,9 @@ msgstr "间接费用差异"
msgid "Over-applied by"
msgstr "超额应用"
+msgid "Overall result"
+msgstr "总体结果"
+
msgid "Overdue"
msgstr "逾期"
@@ -9027,9 +9105,6 @@ msgstr "零件编号"
msgid "Part Supersession"
msgstr "零件取代"
-msgid "Partial"
-msgstr "部分"
-
msgid "Partner"
msgstr "合作伙伴"
@@ -9246,6 +9321,9 @@ msgstr "件/小时"
msgid "Pieces/Minute"
msgstr "件/分钟"
+msgid "Pin"
+msgstr "固定"
+
msgid "Pinned"
msgstr "已固定"
@@ -9447,6 +9525,9 @@ msgstr "上一个日期"
msgid "Previous page"
msgstr "上一页"
+msgid "Previous step"
+msgstr "上一步"
+
msgid "Price break actions"
msgstr "价格阶梯操作"
@@ -10138,9 +10219,6 @@ msgstr "记录已删除"
msgid "Record inspections tied to a part and a job"
msgstr "记录与零件和工作相关的检验"
-msgid "Record the inspection result for this sample."
-msgstr "记录此样本的检验结果。"
-
msgid "Recorded on a calibration that the gauge needs repair before its readings can be trusted."
msgstr "在校准记录中标记该量具需要修理才能使其读数可信。"
@@ -10265,9 +10343,6 @@ msgstr "移除 {label}"
msgid "Remove condition"
msgstr "移除条件"
-msgid "Remove feature"
-msgstr "删除功能"
-
msgid "Remove filter"
msgstr "移除筛选"
@@ -10286,12 +10361,21 @@ msgstr "删除订单"
msgid "Remove pair"
msgstr "移除配对"
+msgid "Remove part"
+msgstr "移除零件"
+
+msgid "Remove slide"
+msgstr "移除幻灯片"
+
msgid "Remove sort by column"
msgstr "删除按列排序"
msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."
msgstr "从所有引用此存储类型的存储单元中移除它并将其删除。此操作无法撤销。"
+msgid "Remove tool"
+msgstr "移除工具"
+
msgid "Removed"
msgstr "已移除"
@@ -10421,9 +10505,6 @@ msgstr "需要采取行动"
msgid "Requires Adjustment"
msgstr "需要调整"
-msgid "Requires Inspection"
-msgstr "需要检查"
-
msgid "Requires Repair"
msgstr "需要维修"
@@ -10444,7 +10525,7 @@ msgstr "重置PIN"
msgid "Reset PIN for {0} {1}"
msgstr "重置 {0} {1} 的 PIN"
-msgid "Reset View"
+msgid "Reset view"
msgstr "重置视图"
msgid "Residual value"
@@ -10797,15 +10878,14 @@ msgstr "与账面相同"
msgid "Sample"
msgstr "样本"
-#. placeholder {0}: idx + 1
-msgid "Sample {0}"
-msgstr "样本 {0}"
-
msgid "Sample Size"
msgstr "样本量"
-msgid "Sampling Plan"
-msgstr "抽样计划"
+msgid "Sampling"
+msgstr "抽样"
+
+msgid "Sampling — Feature {featureLabel}"
+msgstr "抽样 — 功能 {featureLabel}"
msgid "Sampling Standard"
msgstr "抽样标准"
@@ -10852,8 +10932,8 @@ msgstr "扫描或输入追踪号"
msgid "Scan or search..."
msgstr "扫描或搜索..."
-msgid "Scan or select a tracked entity from this lot and record the inspection result."
-msgstr "扫描或从此批次中选择一个追踪实体并记录检验结果。"
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "从此批次扫描或选择被追踪的实体以将其作为样本列添加,然后在网格中记录其结果。"
msgid "Scan the tracking ID for this line"
msgstr "扫描此行的跟踪ID"
@@ -10900,6 +10980,9 @@ msgstr "范围"
msgid "Scrap"
msgstr "报废"
+msgid "Scrap / Cost of Quality"
+msgstr "废品 / 质量成本"
+
msgid "Scrap Percent"
msgstr "废料百分比"
@@ -10960,6 +11043,9 @@ msgstr "搜索任务"
msgid "Search operators..."
msgstr "搜索运算符..."
+msgid "Search parts..."
+msgstr "搜索零件..."
+
msgid "Search processes..."
msgstr "搜索流程..."
@@ -10969,6 +11055,9 @@ msgstr "搜索相关项目..."
msgid "Search suppliers..."
msgstr "搜索供应商..."
+msgid "Search tools..."
+msgstr "搜索工具..."
+
msgid "Search..."
msgstr "搜索..."
@@ -10990,6 +11079,9 @@ msgstr "选择受理人"
msgid "Select a default approver"
msgstr "选择默认审批人"
+msgid "Select a document"
+msgstr "选择文件"
+
msgid "Select a new owner"
msgstr "选择新的所有者"
@@ -11647,6 +11739,9 @@ msgstr "备件消耗"
msgid "Spare Part Cost"
msgstr "备件成本"
+msgid "Spec"
+msgstr "规范"
+
msgid "Specific Customer"
msgstr "特定客户"
@@ -11777,6 +11872,12 @@ msgstr "步骤"
msgid "Steps"
msgstr "步骤"
+msgid "Steps are inherited from the assembly instruction."
+msgstr "步骤继承自装配说明。"
+
+msgid "Steps are inherited from the inspection plan."
+msgstr "步骤继承自检验计划。"
+
msgid "Stock Transfer ID"
msgstr "库存转移ID"
@@ -12470,8 +12571,8 @@ msgstr "从客户报价到收款的端到端商业流程:询价到报价到销
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "接收表格更新时包含更新数据的POST请求的端点"
-msgid "The engineering drawing this inspection document is tied to; inspections recorded against this part reference back to this drawing."
-msgstr "该检查文件链接到的工程图纸;针对此零件参考记录的检查会引用此图纸。"
+msgid "The engineering drawing this inspection plan is tied to; inspections recorded against this part reference back to this drawing."
+msgstr "此检验计划关联的工程图纸;针对此零件记录的检验将引用此图纸。"
msgid "The expected percentage of this item's output lost during production; planning multiplies demand by 1 / (1 − scrap) to compensate."
msgstr "生产期间此项目的预期产出百分比丢失;规划将需求乘以1 / (1 −废料)来补偿。"
@@ -12620,15 +12721,15 @@ msgstr "显示在您打印和电子邮件文档上的徽标"
msgid "The lot identifier for this stock; one row per batch, quantity is the on-hand for that lot."
msgstr "此库存的批号标识符;每批一行,数量是该批的库存。"
-msgid "The lot stays open so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "该批次保持开放状态,您可以继续检验并稍后进行处置。已取样的结果将被保留。"
-
msgid "The lot will be marked Passed. {fails} sampled failure(s) are recorded for your records."
msgstr "该批次将被标记为通过。{fails} 个抽样失败已记录在案。"
msgid "The lot will still be rejected, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "该批次仍将被拒收,但在至少配置一个问题类型之前,无法创建NCR。"
+msgid "The lot's per-feature sampling plan will be re-resolved from the selected document."
+msgstr "该批次的按特性抽样计划将从选定的文件中重新解析。"
+
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "此供应商无论数量如何为此流程收费的最低金额;低于损益平衡点的工作仍至少花费此金额。"
@@ -12696,7 +12797,7 @@ msgid "The ordered sequence of operations a job runs through, copied from the me
msgstr "工作执行的操作的有序序列,从方法的流程清单中复制。"
msgid "The original model file is no longer available"
-msgstr ""
+msgstr "原始模型文件不再可用"
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "将商品从库存中取出给客户的出账凭证,沿途过账销售成本。"
@@ -12719,8 +12820,8 @@ msgstr "Carbon 方面将运行您的实施的人员,以及如何联系他们
msgid "The people on your team and their access to Carbon"
msgstr "您团队中的人员及其对 Carbon 的访问权限"
-msgid "The per-company counter behind a document type's readable number, assembling {prefix}{next+step, zero-padded}{suffix} and advancing as each document is created."
-msgstr "文档类型可读编号背后的按公司计数器,组合{prefix}{next+step, zero-padded}{suffix},每创建一个文档就增加。"
+msgid "The per-company counter behind a document type's readable number, assembling the prefix, the zero-padded next value, and the suffix, and advancing as each document is created."
+msgstr "按公司分别维护的计数器,用于生成文档类型的可读编号,将前缀、零填充的序列号和后缀组合在一起,每创建一个文档时自动递增。"
msgid "The per-item outcome recorded on a non-conformance's affected material — Pending, Return to Supplier, Rework, Scrap, or Use As Is — decided for each affected lot or serial on its own."
msgstr "在不符合项的受影响物料上记录的逐项结果——待处理、退回供应商、返工、报废或照原样使用——针对每个受影响的批次或序列号单独决定。"
@@ -13011,6 +13112,9 @@ msgstr "此信息将用于文档标题"
msgid "This information will be visible to all users, so be careful what you share."
msgstr "此信息将对所有用户可见,请谨慎分享。"
+msgid "this inspection plan"
+msgstr "这个检验计划"
+
msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."
msgstr "这是一个采购项目 — 它没有BoM/BoP;只有其属性和文档可以更改。"
@@ -13459,9 +13563,6 @@ msgstr "类型:"
msgid "Types"
msgstr "类型"
-msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."
-msgstr "未采样的实体将保持\"待处理\"状态,以便您可以继续检验并稍后进行处置。已采样的结果将被保留。"
-
msgid "Unapplied"
msgstr "未应用"
@@ -14311,6 +14412,9 @@ msgstr "启用后,此类别中的属性会显示在人员的公开个人资料
msgid "When on, employees can edit this attribute's value on their own profile; otherwise only admins can."
msgstr "启用后,员工可以在自己的个人资料中编辑此属性的值;否则,仅管理员可以这样做。"
+msgid "When on, opening an operation starts its timer automatically."
+msgstr "打开时,打开操作会自动启动其计时器。"
+
msgid "When on, pricing rules (volume discounts, promotions) still apply on top of this override; when off, this override is the final price."
msgstr "启用后,定价规则(批量折扣、促销)仍适用于此覆盖;禁用时,此覆盖是最终价格。"
@@ -14437,8 +14541,8 @@ msgstr "计时是在所选工序开始时启动,还是在其完成时启动。
msgid "Whether this lot/serial passes inspection (Pass) or fails (Fail); a Fail blocks the stock from being received into available inventory."
msgstr "此批次/序列是否通过检验 (Pass) 或未通过 (Fail);Fail 会阻止库存被收入可用库存。"
-msgid "Whether this process runs on internal work centers (Inside), outside suppliers (Outside), or both (Both); reveals different downstream fields and changes how planning routes work for this process."
-msgstr "此工序是在内部工作中心 (Inside)、外部供应商 (Outside) 还是两者 (Both) 上运行;会显示不同的下游字段,并改变计划如何为此工序安排路线。"
+msgid "Whether this process runs on internal work centers (Process, Assembly, or Inspection) or at outside suppliers (Outside Processing); reveals different downstream fields, changes how planning routes work for this process, and defaults the operation type on new operations."
+msgstr "该流程是在内部工作中心(流程、组装或检测)还是在外部供应商处运行(外部加工);显示不同的下游字段,更改此流程的规划路由工作方式,并默认设置新操作的操作类型。"
msgid "Whether this work blocks production (Down), degrades it (Impact), is on a planned downtime window (Planned), or has no production impact (No Impact); informs scheduling and customer-facing downtime communication."
msgstr "此工作是否阻止生产(关闭)、降低生产(影响)、处于计划停机时间窗口(计划)或没有生产影响(无影响);告知计划和面向客户的停机通信。"
@@ -14446,6 +14550,9 @@ msgstr "此工作是否阻止生产(关闭)、降低生产(影响)、处于计
msgid "Whether to Add the selected permissions on top of what each user already has, or Update by replacing each user's permission set wholesale with the selection below."
msgstr "是否将选定的权限添加到每个用户已有的权限之上,或通过将每个用户的权限集替换为下面的选择来更新。"
+msgid "Which document drives each inspection flow for this item."
+msgstr "哪份文件驱动此物料的每个检验流程。"
+
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "哪个制造事件启动保质期时钟 — 例如填充、密封或最终QC。"
@@ -14608,6 +14715,9 @@ msgstr "核销账户"
msgid "Write-off for {0}"
msgstr "{0}的核销"
+msgid "Write-off of stock scrapped or returned via inspection rejects and NCR dispositions"
+msgstr "通过检验拒绝和不符合项处置报废或退回的库存的报销"
+
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "在资产的使用寿命期间降低其价值 — 您创建、作为草稿审阅然后过账的月度批次。"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 1a537982a2..fdcfdc7f2e 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -42,9 +42,24 @@ msgstr "{0} / {1} 已完成"
msgid "{0} Scrapped"
msgstr "{0} 已报废"
+msgid "{completions} passed unit(s) will be completed."
+msgstr "{completions} 个合格单位将被完成。"
+
+msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+msgstr "{fails} 个抽样失败已记录,将不会完成 — 请从操作菜单中解决。"
+
msgid "About"
msgstr "关于"
+msgid "Accept"
+msgstr "接收"
+
+msgid "Accept Lot"
+msgstr "接收批次"
+
+msgid "Accept lot?"
+msgstr "接收批次?"
+
msgid "Account Settings"
msgstr "账户设置"
@@ -66,12 +81,27 @@ msgstr "在打印设置中添加打印机以直接打印标签。"
msgid "Add Inventory"
msgstr "添加库存"
+msgid "Add Sample"
+msgstr "添加样本"
+
msgid "Add Spare Part"
msgstr "添加备件"
msgid "All"
msgstr "全部"
+msgid "All rework"
+msgstr "全部返工"
+
+msgid "All scrap"
+msgstr "全部报废"
+
+msgid "Allocate failed units"
+msgstr "分配不合格单位"
+
+msgid "Allocate units"
+msgstr "分配单位"
+
msgid "Are you sure you want to delete this step?"
msgstr "确定要删除此步骤吗?"
@@ -165,6 +195,12 @@ msgstr "下班打卡"
msgid "Clocked in since {0}"
msgstr "自 {0} 起已打卡上班"
+msgid "Close"
+msgstr "关闭"
+
+msgid "Collapse features table"
+msgstr "折叠功能表"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -194,6 +230,9 @@ msgstr "完成"
msgid "Complete All"
msgstr "全部完成"
+msgid "Complete passed"
+msgstr "完成已通过"
+
msgid "Completed"
msgstr "已完成"
@@ -281,6 +320,9 @@ msgstr "草稿"
msgid "Drag and drop a file here, or click to select a file"
msgstr "拖放文件到此处,或点击选择文件"
+msgid "Drag to resize drawing and features"
+msgstr "拖动以调整绘图和功能的大小"
+
#. placeholder {0}: active.data.current?.type
msgid "Dragging {0} cancelled."
msgstr "拖拽 {0} 已取消。"
@@ -325,6 +367,12 @@ msgstr "错误"
msgid "Estimated"
msgstr "估计"
+msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
+msgstr "每个单位都有判定结果:{passes} 个合格,{fails} 个不合格。批次关闭,每个单位按其各自的结果进行处理。"
+
+msgid "Expand features table"
+msgstr "展开功能表"
+
msgid "Expired"
msgstr "已过期"
@@ -337,6 +385,12 @@ msgstr "过期时间 {date}"
msgid "Expiring first"
msgstr "即将过期优先"
+msgid "Failed"
+msgstr "失败"
+
+msgid "Failed features"
+msgstr "失败的功能"
+
msgid "Failed to complete inventory adjustment"
msgstr "库存调整失败"
@@ -349,6 +403,12 @@ msgstr "获取活跃工序失败"
msgid "Failed to fetch storageUnits"
msgstr "获取存储单位失败"
+msgid "Failed to save measurement"
+msgstr "无法保存测量"
+
+msgid "Failed to save result"
+msgstr "无法保存结果"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "文件上传失败:{0}"
@@ -356,6 +416,12 @@ msgstr "文件上传失败:{0}"
msgid "Failed to upload image"
msgstr "图片上传失败"
+msgid "Feature"
+msgstr "功能"
+
+msgid "Features"
+msgstr "特性"
+
msgid "File size exceeds 10MB limit"
msgstr "文件大小超过 10MB 限制"
@@ -405,6 +471,12 @@ msgstr "英制"
msgid "In Progress"
msgstr "进行中"
+msgid "Inspect Item"
+msgstr "检验物品"
+
+msgid "inspected"
+msgstr "已检验"
+
msgid "Insufficient quantity"
msgstr "数量不足"
@@ -498,6 +570,9 @@ msgstr "记录 {0} 的报废"
msgid "Login"
msgstr "登录"
+msgid "Lot"
+msgstr "批次"
+
msgid "Machine"
msgstr "机器"
@@ -531,6 +606,9 @@ msgstr "公制"
msgid "Model"
msgstr "模型"
+msgid "More actions"
+msgstr "更多操作"
+
msgid "More Actions"
msgstr "更多操作"
@@ -595,6 +673,9 @@ msgstr "无文件"
msgid "No Impact"
msgstr "无影响"
+msgid "No issue types configured"
+msgstr "未配置问题类型"
+
msgid "No maintenance scheduled for today"
msgstr "今天没有计划的维护"
@@ -607,6 +688,9 @@ msgstr "无物料"
msgid "No open jobs"
msgstr "没有开放的工作"
+msgid "No open units to allocate"
+msgstr "没有可分配的开放单位"
+
msgid "No operators"
msgstr "无操作员"
@@ -625,6 +709,9 @@ msgstr "未配置打印机"
msgid "No recent operations"
msgstr "无近期工序"
+msgid "No remaining entities to inspect."
+msgstr "没有剩余实体要检验。"
+
msgid "No results"
msgstr "无结果"
@@ -634,6 +721,9 @@ msgstr "无结果"
msgid "No results found"
msgstr "未找到结果"
+msgid "No samples required."
+msgstr "不需要样本。"
+
msgid "No scheduled time"
msgstr "无排定时间"
@@ -683,6 +773,9 @@ msgstr "抱歉,您不应该看到此页面。此页面最终将成为首页。
msgid "Open"
msgstr "打开"
+msgid "Open an NCR for MRB disposition"
+msgstr "为 MRB 处置打开 NCR"
+
msgid "Open Jobs"
msgstr "开放工作"
@@ -698,12 +791,21 @@ msgstr "操作员执行"
msgid "Optional"
msgstr "可选"
+msgid "Overall result"
+msgstr "总体结果"
+
msgid "Parameters"
msgstr "参数"
msgid "Part"
msgstr "零件"
+msgid "Partial"
+msgstr "部分"
+
+msgid "Partial Disposition"
+msgstr "部分处置"
+
msgid "Passed Inspection"
msgstr "检验通过"
@@ -749,9 +851,6 @@ msgstr "上一个"
msgid "Preventive"
msgstr "预防性"
-msgid "Previous"
-msgstr "上一步"
-
msgid "Print"
msgstr "打印"
@@ -801,6 +900,18 @@ msgstr "记录"
msgid "Record {0}"
msgstr "记录 {0}"
+msgid "Record only"
+msgstr "仅记录"
+
+msgid "Record Partial"
+msgstr "记录部分"
+
+msgid "Reject"
+msgstr "退收"
+
+msgid "Reject Lot"
+msgstr "退收批次"
+
msgid "Remove"
msgstr "移除"
@@ -813,12 +924,18 @@ msgstr "移除库存"
msgid "Remove part"
msgstr "移除零件"
+msgid "Result"
+msgstr "结果"
+
msgid "Rework"
msgstr "返工"
msgid "Rework created successfully"
msgstr "返工创建成功"
+msgid "Rework quantity"
+msgstr "返工数量"
+
msgid "Sales Order"
msgstr "销售订单"
@@ -828,21 +945,33 @@ msgstr "保存"
msgid "Scan"
msgstr "扫描"
+msgid "Scan a tracked entity to add the first sample column."
+msgstr "扫描跟踪实体以添加第一个样本列。"
+
msgid "Scan or enter serial number"
msgstr "扫描或输入序列号"
+msgid "Scan or enter tracked entity ID, serial, or batch"
+msgstr "扫描或输入跟踪实体 ID、序列号或批次"
+
msgid "Scan or enter tracking number"
msgstr "扫描或输入追踪号"
msgid "Scan or search serial number..."
msgstr "扫描或搜索序列号..."
+msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgstr "从此批次扫描或选择跟踪实体以将其添加为样本列,然后在网格中记录其结果。"
+
msgid "Schedule"
msgstr "排程"
msgid "Scrap"
msgstr "报废"
+msgid "Scrap quantity"
+msgstr "报废数量"
+
msgid "Scrap Reason"
msgstr "报废原因"
@@ -876,6 +1005,9 @@ msgstr "选择报废数量和原因"
msgid "Select a serial number to continue with this operation"
msgstr "选择一个序列号以继续此工序"
+msgid "Select an issue type"
+msgstr "选择问题类型"
+
msgid "Select an item and specify the quantity to issue"
msgstr "选择物料并指定发放数量"
@@ -899,6 +1031,9 @@ msgstr "选择序列号"
msgid "Select the operation to go back to. All operations from that point to the current operation will be redone."
msgstr "选择要返回的操作。从该点到当前操作的所有操作都将重新进行。"
+msgid "Selected"
+msgstr "已选择"
+
msgid "Send"
msgstr "发送"
@@ -978,6 +1113,10 @@ msgstr "工位用户"
msgid "Station: {stationName}"
msgstr "工位:{stationName}"
+#. placeholder {0}: inspection.lotSize
+msgid "Statistical acceptance failed, so the entire lot of {0} is considered non-conforming (ISO 9001:2015 §8.7) — {passes} sampled pass(es) and {fails} failure(s). Route the units below to scrap or rework, or record the verdict only."
+msgstr "统计验收失败,因此整个批次 {0} 被视为不符合要求 (ISO 9001:2015 §8.7) — {passes} 个样品合格和 {fails} 个失败。将下面的单位路由到报废或返工,或仅记录判定结果。"
+
msgid "Status"
msgstr "状态"
@@ -1015,6 +1154,12 @@ msgstr "标签"
msgid "The completed quantity for this operation is less than the required quantity of {0}."
msgstr "此工序的完成数量小于所需数量 {0}。"
+msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
+msgstr "该批次将被标记为\"通过\",{remaining} 个剩余单位将在此操作中完成。"
+
+msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+msgstr "该批次仍将进行处置,但在至少配置一个问题类型之前,无法创建NCR。"
+
msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."
msgstr "物料清单中有序列号或批次追踪的物料尚未完全发放。不发放即完成可能导致追溯记录不正确。"
@@ -1048,6 +1193,9 @@ msgstr "总时间:{0}"
msgid "Total: {0}"
msgstr "合计:{0}"
+msgid "Tracked Entity"
+msgstr "跟踪实体"
+
msgid "Tracking"
msgstr "追踪"
@@ -1070,6 +1218,9 @@ msgstr "取消拣选 {0}"
msgid "Unsaved changes"
msgstr "未保存的更改"
+msgid "Up to {maxAllocatable} unit(s) can be allocated; the rest is recorded without a posting."
+msgstr "最多可分配 {maxAllocatable} 个单位;其余的将被记录而不进行过账。"
+
msgid "Update"
msgstr "更新"
diff --git a/packages/onboarding/src/ui/GuidedUpsellCard.tsx b/packages/onboarding/src/ui/GuidedUpsellCard.tsx
index 50017ddf82..f2e86e7049 100644
--- a/packages/onboarding/src/ui/GuidedUpsellCard.tsx
+++ b/packages/onboarding/src/ui/GuidedUpsellCard.tsx
@@ -13,7 +13,7 @@ export function GuidedUpsellCard({
}) {
const { i18n } = useLingui();
return (
- <section className="rounded-2xl border border-border p-6 flex items-start gap-4">
+ <section className="rounded-2xl border border-border bg-card p-6 flex items-start gap-4">
<div className="shrink-0 size-11 rounded-2xl bg-primary/15 flex items-center justify-center text-primary">
<LuSparkles className="text-xl" />
</div>
diff --git a/packages/onboarding/src/ui/OnboardingHub.tsx b/packages/onboarding/src/ui/OnboardingHub.tsx
index ee2c05e3c3..d3ad1363bd 100644
--- a/packages/onboarding/src/ui/OnboardingHub.tsx
+++ b/packages/onboarding/src/ui/OnboardingHub.tsx
@@ -244,7 +244,7 @@ function NextStepCard({
: undefined;
return (
- <div className="rounded-2xl border border-border p-5 flex items-start gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300">
+ <div className="rounded-2xl border border-border bg-card p-5 flex items-start gap-4 motion-safe:animate-in motion-safe:fade-in-50 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300">
<div className="shrink-0 size-9 rounded-xl bg-primary/15 flex items-center justify-center text-sm font-medium tabular-nums text-primary">
{action.gateNumber}
</div>
diff --git a/packages/printing/src/ui/PrintButton.tsx b/packages/printing/src/ui/PrintButton.tsx
index fa6869efe6..e10b9b7ee0 100644
--- a/packages/printing/src/ui/PrintButton.tsx
+++ b/packages/printing/src/ui/PrintButton.tsx
@@ -1,5 +1,6 @@
import {
Button,
+ IconButton,
Modal,
ModalBody,
ModalContent,
@@ -32,7 +33,8 @@ export function PrintButton({
fileRoutes,
disabled,
variant = "secondary",
- size
+ size,
+ isIcon = false
}: {
sourceDocument: string;
sourceDocumentId: string;
@@ -43,6 +45,9 @@ export function PrintButton({
disabled?: boolean;
variant?: ComponentProps<typeof Button>["variant"];
size?: ComponentProps<typeof Button>["size"];
+ // Render as an icon-only button (printer glyph, no label) instead of the
+ // default labeled button. Same print/download flow either way.
+ isIcon?: boolean;
}) {
const { printerRoutes, resolvePrinterRoute, printPath } = usePrinting();
const modal = useDisclosure();
@@ -96,15 +101,26 @@ export function PrintButton({
return (
<>
- <Button
- leftIcon={<LuPrinter />}
- variant={variant}
- size={size}
- disabled={disabled}
- onClick={handleClick}
- >
- <Trans>Print</Trans>
- </Button>
+ {isIcon ? (
+ <IconButton
+ aria-label="Print label"
+ icon={<LuPrinter />}
+ variant={variant}
+ size={size}
+ isDisabled={disabled}
+ onClick={handleClick}
+ />
+ ) : (
+ <Button
+ leftIcon={<LuPrinter />}
+ variant={variant}
+ size={size}
+ disabled={disabled}
+ onClick={handleClick}
+ >
+ <Trans>Print</Trans>
+ </Button>
+ )}
{modal.isOpen && (
<Modal open onOpenChange={(open) => !open && modal.onClose()}>
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index ccfb9f5d32..4aa30eda4c 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -5,15 +5,12 @@ import type { ComponentPropsWithoutRef, ReactNode } from "react";
import { forwardRef, useId, useMemo, useRef, useState } from "react";
import { FaRegSquare, FaSquareCheck } from "react-icons/fa6";
import { LuCirclePlus, LuSettings2 } from "react-icons/lu";
-import { RxMagnifyingGlass } from "react-icons/rx";
-import { Badge, BadgeCloseButton } from "./Badge";
-import { Button } from "./Button";
import {
Command,
CommandGroup,
CommandInput,
CommandItem,
- multiSelectTriggerVariants
+ CommandTrigger
} from "./Command";
import { HStack } from "./HStack";
import { IconButton } from "./IconButton";
@@ -85,12 +82,13 @@ const CreatableMultiSelect = forwardRef<
const id = useId();
- const handleUnselect = (item: string) => {
- onChange(value.filter((i) => i !== item));
- };
-
const hasSelections = value.length > 0;
const isInlinePreview = !!inline;
+
+ const selectedLabels = value
+ .map((item) => options.find((option) => option.value === item)?.label)
+ .filter((label): label is string => Boolean(label));
+ const selectedLabelText = selectedLabels.join(", ");
const dropdownContentWidthCh = useMemo(() => {
if (options.length === 0) return undefined;
@@ -140,49 +138,31 @@ const CreatableMultiSelect = forwardRef<
onClick={() => setOpen(true)}
/>
) : (
- <Button
+ <CommandTrigger
aria-controls={id}
aria-expanded={open}
role="combobox"
- tabIndex={0}
- variant="secondary"
- className={cn(
- multiSelectTriggerVariants({ size, hasSelections }),
- "bg-transparent px-2",
- className
- )}
- isDisabled={isReadOnly}
+ size={size}
+ className={cn("min-w-[160px]", className)}
+ ref={ref}
+ disabled={isReadOnly}
onClick={() => {
if (!isReadOnly) setOpen(!open);
}}
- onKeyDown={(e) => {
- if ((e.key === "Enter" || e.key === " ") && !isReadOnly) {
- setOpen(!open);
- }
- }}
- asChild
>
- <div>
- {hasSelections ? (
- <div className="flex gap-1 flex-wrap">
- {value.map((item) => (
- <SelectedOption
- key={item.toString()}
- item={item}
- options={options}
- onUnselect={handleUnselect}
- />
- ))}
- </div>
- ) : (
- <span className="text-muted-foreground">
- {placeholder ?? t`Search...`}
- </span>
- )}
-
- <RxMagnifyingGlass className="h-4 w-4 shrink-0 opacity-50" />
- </div>
- </Button>
+ {hasSelections ? (
+ <TruncatedTooltipText
+ className="block min-w-0 flex-1 truncate text-left"
+ tooltip={selectedLabelText}
+ >
+ {selectedLabelText}
+ </TruncatedTooltipText>
+ ) : (
+ <span className="!text-muted-foreground">
+ {placeholder ?? t`Search...`}
+ </span>
+ )}
+ </CommandTrigger>
)}
</PopoverTrigger>
<PopoverContent
@@ -403,40 +383,3 @@ function VirtualizedCommand({
</Command>
);
}
-
-function SelectedOption({
- isReadOnly,
- item,
- options,
- onUnselect
-}: {
- isReadOnly?: boolean;
- item: string;
- options: CreatableMultiSelectProps["options"];
- onUnselect: (item: string) => void;
-}) {
- return (
- <Badge key={item} variant="secondary" className="border border-card">
- {options.find((option) => option.value === item)?.label}
- <BadgeCloseButton
- disabled={isReadOnly}
- tabIndex={-1}
- type="button"
- onKeyDown={(e) => {
- if (e.key === "Enter" && !isReadOnly) {
- onUnselect(item);
- }
- }}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (!isReadOnly) onUnselect(item);
- }}
- />
- </Badge>
- );
-}
diff --git a/packages/react/src/MultiSelect.tsx b/packages/react/src/MultiSelect.tsx
index bee10d1601..42aa05db08 100644
--- a/packages/react/src/MultiSelect.tsx
+++ b/packages/react/src/MultiSelect.tsx
@@ -4,20 +4,18 @@ import type { ComponentPropsWithoutRef, ReactNode } from "react";
import { forwardRef, useId, useMemo, useRef, useState } from "react";
import { FaRegSquare, FaSquareCheck } from "react-icons/fa6";
import { LuCirclePlus, LuSettings2, LuX } from "react-icons/lu";
-import { RxMagnifyingGlass } from "react-icons/rx";
-import { Badge, BadgeCloseButton } from "./Badge";
-import { Button } from "./Button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
- multiSelectTriggerVariants
+ CommandTrigger
} from "./Command";
import { HStack } from "./HStack";
import { IconButton } from "./IconButton";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
+import { TruncatedTooltipText } from "./TruncatedTooltipText";
import { cn } from "./utils/cn";
import { reactNodeToString } from "./utils/react";
@@ -73,13 +71,14 @@ const MultiSelect = forwardRef<HTMLButtonElement, MultiSelectProps>(
const id = useId();
- const handleUnselect = (item: string) => {
- onChange(value.filter((i) => i !== item));
- };
-
const hasSelections = value.length > 0;
const isInlinePreview = !!inline;
+ const selectedLabels = value
+ .map((item) => options.find((option) => option.value === item)?.label)
+ .filter((label): label is string => Boolean(label));
+ const selectedLabelText = selectedLabels.join(", ");
+
return (
<HStack
className={cn(isInlinePreview ? "w-full" : "min-w-0 flex-grow")}
@@ -118,72 +117,31 @@ const MultiSelect = forwardRef<HTMLButtonElement, MultiSelectProps>(
onClick={() => setOpen(true)}
/>
) : (
- <Button
+ <CommandTrigger
aria-controls={id}
aria-expanded={open}
role="combobox"
- tabIndex={0}
- variant="secondary"
- className={cn(
- multiSelectTriggerVariants({ size, hasSelections }),
- "bg-transparent px-2 hover:scale-100 focus-visible:scale-100",
- className
- )}
- isDisabled={isReadOnly}
+ size={size}
+ className={cn("min-w-[160px]", className)}
+ ref={ref}
+ disabled={isReadOnly}
onClick={() => {
if (!isReadOnly) setOpen(!open);
}}
- onKeyDown={(e) => {
- if ((e.key === "Enter" || e.key === " ") && !isReadOnly) {
- setOpen(!open);
- }
- }}
- asChild
>
- <div>
- {hasSelections ? (
- <div className="flex gap-1 flex-wrap">
- {value.map((item) => (
- <Badge
- key={item}
- variant="secondary"
- className="border border-card"
- >
- {
- options.find((option) => option.value === item)
- ?.label
- }
- <BadgeCloseButton
- disabled={isReadOnly}
- type="button"
- tabIndex={-1}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !isReadOnly) {
- handleUnselect(item);
- }
- }}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (!isReadOnly) handleUnselect(item);
- }}
- />
- </Badge>
- ))}
- </div>
- ) : (
- <span className="text-muted-foreground">
- {placeholder ?? t`Select`}
- </span>
- )}
-
- <RxMagnifyingGlass className="h-4 w-4 shrink-0 opacity-50" />
- </div>
- </Button>
+ {hasSelections ? (
+ <TruncatedTooltipText
+ className="block min-w-0 flex-1 truncate text-left"
+ tooltip={selectedLabelText}
+ >
+ {selectedLabelText}
+ </TruncatedTooltipText>
+ ) : (
+ <span className="!text-muted-foreground">
+ {placeholder ?? t`Select`}
+ </span>
+ )}
+ </CommandTrigger>
)}
</PopoverTrigger>
<PopoverContent
diff --git a/packages/react/src/Sidebar.tsx b/packages/react/src/Sidebar.tsx
index 8b3d851607..1d16687beb 100644
--- a/packages/react/src/Sidebar.tsx
+++ b/packages/react/src/Sidebar.tsx
@@ -163,7 +163,7 @@ const SidebarProvider = React.forwardRef<
} as React.CSSProperties
}
className={cn(
- "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
+ "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-card",
className
)}
ref={ref}
@@ -203,7 +203,7 @@ const Sidebar = React.forwardRef<
return (
<div
className={cn(
- "flex h-full w-[var(--sidebar-width)] flex-col bg-sidebar text-sidebar-foreground",
+ "flex h-full w-[var(--sidebar-width)] flex-col bg-card text-foreground",
className
)}
ref={ref}
@@ -220,7 +220,7 @@ const Sidebar = React.forwardRef<
<DrawerContent
data-sidebar="sidebar"
data-mobile="true"
- className="w-[var(--sidebar-width)] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
+ className="w-[var(--sidebar-width)] bg-card p-0 text-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE
@@ -236,7 +236,7 @@ const Sidebar = React.forwardRef<
return (
<div
ref={ref}
- className="group peer hidden md:block text-sidebar-foreground"
+ className="group peer hidden md:block text-foreground"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
@@ -271,7 +271,7 @@ const Sidebar = React.forwardRef<
>
<div
data-sidebar="sidebar"
- className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
+ className="flex h-full w-full flex-col bg-card group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
>
{children}
</div>
@@ -324,7 +324,7 @@ const SidebarRail = React.forwardRef<
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-opacity duration-150 ease-out motion-reduce:transition-none after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
- "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
+ "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-card",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
@@ -466,7 +466,7 @@ const SidebarGroupLabel = React.forwardRef<
className={cn(
// Vercel style: very muted, uppercase, smaller text
// ease-out-quint for consistent spring-like feel with sidebar expansion
- "flex h-7 shrink-0 items-center rounded-md px-2 text-[11px] font-medium uppercase tracking-wider text-sidebar-foreground/50 outline-none ring-sidebar-ring transition-[margin,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none focus-visible:ring-2 [&>svg]:size-3.5 [&>svg]:shrink-0",
+ "flex h-7 shrink-0 items-center rounded-md px-2 text-[11px] font-medium uppercase tracking-wider text-foreground/50 outline-none ring-sidebar-ring transition-[margin,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none focus-visible:ring-2 [&>svg]:size-3.5 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
@@ -488,7 +488,7 @@ const SidebarGroupAction = React.forwardRef<
data-sidebar="group-action"
className={cn(
// Muted by default, brightens on hover (Vercel style)
- "absolute right-3 top-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground/50 outline-none ring-sidebar-ring transition-[background-color,color] duration-100 ease-out hover:bg-sidebar-accent/50 hover:text-sidebar-foreground focus-visible:ring-2 motion-reduce:transition-none [&>svg]:size-3.5 [&>svg]:shrink-0",
+ "absolute right-3 top-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-foreground/50 outline-none ring-sidebar-ring transition-[background-color,color] duration-100 ease-out hover:bg-sidebar-accent/50 hover:text-foreground focus-visible:ring-2 motion-reduce:transition-none [&>svg]:size-3.5 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
@@ -552,26 +552,26 @@ const sidebarMenuButtonVariants = cva(
// Layout - tighter padding for Vercel-style compact feel
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md px-2 py-1.5 text-left text-sm outline-none",
// Default: muted text color (Vercel style - text is subdued until interaction)
- "text-sidebar-foreground/70",
+ "text-foreground/70",
// Icons inherit the muted color (size is applied per touch/non-touch mode below)
- "[&>svg]:shrink-0 [&>svg]:text-sidebar-foreground/70",
+ "[&>svg]:shrink-0 [&>svg]:text-foreground/70",
// Focus ring
"ring-sidebar-ring focus-visible:ring-2",
// Transitions - fast and smooth
"transition-[background-color,color,border-color] duration-100 ease-out motion-reduce:transition-none",
// Hover: subtle background tint + brighten text
- "hover:bg-sidebar-accent/50 hover:text-sidebar-foreground [&:hover>svg]:text-sidebar-foreground",
+ "hover:bg-sidebar-accent/50 hover:text-foreground [&:hover>svg]:text-foreground",
// Active (pressed): same as hover
- "active:bg-sidebar-accent/50 active:text-sidebar-foreground",
+ "active:bg-sidebar-accent/50 active:text-foreground",
// Disabled states
"disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50",
// Menu action padding adjustment
"group-has-[[data-sidebar=menu-action]]/menu-item:pr-8",
// Active/selected state - Vercel style: subtle left border accent + bright text
- "data-[active=true]:bg-sidebar-accent/50 data-[active=true]:text-sidebar-foreground data-[active=true]:font-medium",
- "[&[data-active=true]>svg]:text-sidebar-foreground",
+ "data-[active=true]:bg-sidebar-accent/50 data-[active=true]:text-foreground data-[active=true]:font-medium",
+ "[&[data-active=true]>svg]:text-foreground",
// Open state (for collapsible menus)
- "data-[state=open]:bg-sidebar-accent/50 data-[state=open]:text-sidebar-foreground",
+ "data-[state=open]:bg-sidebar-accent/50 data-[state=open]:text-foreground",
// Text truncation
"[&>span:last-child]:truncate"
].join(" "),
@@ -625,11 +625,12 @@ const SidebarMenuButton = React.forwardRef<
// so the !important collapsed sizing never conflicts between modes.
const sizing = touch
? cn(
- // Expanded / mobile sheet: taller rows + bigger icons
- "min-h-11 [&>svg]:size-5",
+ // Expanded / mobile sheet: taller rows; icons kept compact for a
+ // lighter feel (button size unchanged).
+ "min-h-11 [&>svg]:size-4",
// Collapsed icon rail: a roomy centered square showing only the
// leading icon/avatar (labels, counts, chevron clip away cleanly)
- "group-data-[collapsible=icon]:!size-12 group-data-[collapsible=icon]:!p-0 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:[&>svg]:size-6 group-data-[collapsible=icon]:[&>:not(:first-child)]:hidden"
+ "group-data-[collapsible=icon]:!size-12 group-data-[collapsible=icon]:!p-0 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:[&>svg]:size-5 group-data-[collapsible=icon]:[&>:not(:first-child)]:hidden"
)
: cn(
"[&>svg]:size-4",
@@ -691,7 +692,7 @@ const SidebarMenuAction = React.forwardRef<
data-sidebar="menu-action"
className={cn(
// Muted by default (Vercel style)
- "absolute right-1 top-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground/50 outline-none ring-sidebar-ring transition-[background-color,color,opacity] duration-100 ease-out hover:bg-sidebar-accent/50 hover:text-sidebar-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-foreground motion-reduce:transition-none [&>svg]:size-3.5 [&>svg]:shrink-0",
+ "absolute right-1 top-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-foreground/50 outline-none ring-sidebar-ring transition-[background-color,color,opacity] duration-100 ease-out hover:bg-sidebar-accent/50 hover:text-foreground focus-visible:ring-2 peer-hover/menu-button:text-foreground motion-reduce:transition-none [&>svg]:size-3.5 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"peer-data-[size=sm]/menu-button:top-0.5",
@@ -699,7 +700,7 @@ const SidebarMenuAction = React.forwardRef<
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
- "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-foreground md:opacity-0",
+ "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-foreground md:opacity-0",
className
)}
{...props}
@@ -717,8 +718,8 @@ const SidebarMenuBadge = React.forwardRef<
data-sidebar="menu-badge"
className={cn(
// Muted by default, brightens with parent (Vercel style)
- "absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground/50 select-none pointer-events-none transition-colors duration-100 ease-out",
- "peer-hover/menu-button:text-sidebar-foreground peer-data-[active=true]/menu-button:text-sidebar-foreground",
+ "absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-foreground/50 select-none pointer-events-none transition-colors duration-100 ease-out",
+ "peer-hover/menu-button:text-foreground peer-data-[active=true]/menu-button:text-foreground",
"peer-data-[size=sm]/menu-button:top-0.5",
"peer-data-[size=default]/menu-button:top-1",
"peer-data-[size=lg]/menu-button:top-2.5",
@@ -817,23 +818,23 @@ const SidebarMenuSubButton = React.forwardRef<
// Layout - compact
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2",
// Default: muted text (Vercel style)
- "text-sidebar-foreground/70",
+ "text-foreground/70",
// Focus ring
"outline-none ring-sidebar-ring focus-visible:ring-2",
// Transitions
"transition-[background-color,color] duration-100 ease-out motion-reduce:transition-none",
// Hover: subtle tint + brighten
- "hover:bg-sidebar-accent/50 hover:text-sidebar-foreground",
+ "hover:bg-sidebar-accent/50 hover:text-foreground",
// Active (pressed)
- "active:bg-sidebar-accent/50 active:text-sidebar-foreground",
+ "active:bg-sidebar-accent/50 active:text-foreground",
// Disabled
"disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50",
// Icons
- "[&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-foreground/70",
- "[&:hover>svg]:text-sidebar-foreground",
+ "[&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-foreground/70",
+ "[&:hover>svg]:text-foreground",
// Selected state
- "data-[active=true]:bg-sidebar-accent/50 data-[active=true]:text-sidebar-foreground data-[active=true]:font-medium",
- "[&[data-active=true]>svg]:text-sidebar-foreground",
+ "data-[active=true]:bg-sidebar-accent/50 data-[active=true]:text-foreground data-[active=true]:font-medium",
+ "[&[data-active=true]>svg]:text-foreground",
// Size variants
size === "sm" && "text-xs",
size === "md" && "text-sm",
diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.ts
index 38cd880c1e..f6217b9063 100644
--- a/packages/utils/src/themes.ts
+++ b/packages/utils/src/themes.ts
@@ -216,8 +216,8 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "20 14.3% 6.1%",
- foreground: "60 9.1% 97.8%",
+ background: "20 14.3% 3.1%",
+ foreground: "20 9.1% 97.8%",
card: "20 14.3% 5%",
"card-foreground": "60 9.1% 97.8%",
popover: "20 14.3% 8.9%",
@@ -276,11 +276,11 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "20 14.3% 6.1%",
+ background: "61 14.3% 3.1%",
foreground: "61 9.1% 97.8%",
- card: "20 14.3% 5%",
+ card: "61 14.3% 5%",
"card-foreground": "61 9.1% 97.8%",
- popover: "20 14.3% 4.1%",
+ popover: "61 14.3% 4.1%",
"popover-foreground": "61 9.1% 97.8%",
primary: "61 100% 53.1%",
"primary-foreground": "61 83.3% 14.1%",
@@ -338,7 +338,7 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "20 14.3% 6.1%",
+ background: "151 14.3% 3.1%",
foreground: "0 0% 95%",
popover: "151 0% 9%",
"popover-foreground": "151 0% 95%",
@@ -398,7 +398,7 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "220 14.3% 6.1%",
+ background: "220 14.3% 3.1%",
foreground: "220 0% 95%",
popover: "216 0% 9%",
"popover-foreground": "220 0% 95%",
@@ -458,7 +458,7 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "263 41.4 6.1%",
+ background: "263 41.4 3.1%",
foreground: "263 20% 98%",
card: "263 41.4 5%",
"card-foreground": "210 20% 98%",
diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts
index b8ab395169..35f6c4b49f 100644
--- a/packages/utils/src/types.ts
+++ b/packages/utils/src/types.ts
@@ -59,6 +59,10 @@ export interface TrackedActivityAttributes {
"Job Make Method"?: string;
"Job Material"?: string;
"Job Operation"?: string;
+ "Job Operation Step"?: string;
+ // 1-based unit the consume was for (assembly view), so batch-parent issues can be
+ // attributed per-unit even though every unit shares one lot entity.
+ Unit?: number;
"Original Quantity"?: number;
"Production Event"?: string;
"Receipt Line"?: string;
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
new file mode 100644
index 0000000000..f5ec2a81bc
--- /dev/null
+++ b/packages/viewer/AGENTS.md
@@ -0,0 +1,58 @@
+# @carbon/viewer
+
+3D model + animated assembly-instruction rendering (three.js / react-three-fiber). Backs the ERP assembly editor and the MES shop-floor player.
+
+## Key Domain Concepts
+
+- **graph.json** (`AssemblyGraph`) — assembly tree written by the geometry service `/convert`; leaf nodes carry a stable `nodeId` (also baked into GLB node extras as `userData.nodeId`). All joins between steps, plans, and scene objects are by `nodeId`.
+- **plan.json** (`AssemblyPlan`) — per-component insertion `Motion`, sequence, subassembly `groups`, and body-level `contacts`, written by the geometry service `/plan`. `CURRENT_PLAN_VERSION` (currently `3`) — stored plans below it are STALE and must be treated as absent so the pipeline re-plans.
+- **Step** (`AssemblyStep`) — one build instruction: `componentNodeIds`, a `Motion`, optional `camera`, `fastener`, and subassembly `phase`. Built from a plan by `buildAssemblyStepGroups`.
+- **Motion** — discriminated union `linear | L | helix | path | none`. 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.
+
+## Always
+
+- MUST key everything by `nodeId` — scene objects (`useAssembly` `nodesById`), plan components, and steps all join on it. Stale/unknown nodeIds (post re-upload) are skipped, never assumed.
+- MUST keep the three-free import path clean: server/Inngest code imports plan logic from `@carbon/viewer/steps` (re-exports `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`), NOT the barrel `.` — the barrel pulls in three.js/R3F.
+- MUST treat plans below `CURRENT_PLAN_VERSION` as absent (re-plan), never resurrect their motions.
+- MUST keep this package free of `@carbon/react` router/i18n peers in the pure/motion/plan modules — `cn` is re-implemented locally in `utils.ts` for that reason. (`ModelPreview.tsx` is the one component that does import `@carbon/react`.)
+- MUST prefer server artifacts over the raw tier — the raw WASM fallback renders only when there is no server GLB.
+
+## Ask First
+
+- Changing `types.ts` (`Motion`, `AssemblyGraph`, `AssemblyPlan`, `AssemblyStep`) — these are a shared contract with the geometry service and the ERP/Inngest layer; change all three together (see the header comment in `types.ts`).
+- Bumping `CURRENT_PLAN_VERSION` — it invalidates every stored plan and forces a re-plan across the fleet; coordinate with the geometry service's `PLAN_VERSION`. (Note: the heuristic step-building in `plan.ts` is tuned freely and is NOT a version event.)
+
+## Never
+
+- Never fabricate a motion for a `flagged`/`blockedBy` component — it must stay `none` and fade in at the seated pose.
+- Never add ordering assumptions between components sharing a `wave` — they are parallel-buildable by definition.
+- Never let a step animate two components whose swept `motionCorridor`s overlap simultaneously — they must take separate steps (subassembly `groupId` members are the one exempt rigid-body case).
+
+## Validation Commands
+
+```bash
+pnpm --filter @carbon/viewer test # vitest — camera, fallback, graph, motion, plan, visibility
+pnpm --filter @carbon/viewer typecheck # tsgo --noEmit
+```
+
+## Key Exports
+
+| Subpath | Provides |
+|---------|----------|
+| `.` | `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` |
+| `./canvas` | `ModelCanvas` — standalone static GLB viewer (orbit + view, no steps) |
+| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view |
+| `./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) |
+
+Key non-exported building blocks: `useAssembly` (loads meshopt GLB + graph.json, indexes nodes by nodeId), `motion.ts` (`buildStepClip`, `motionToKeyframes`, `naturalizeMotion`), `fallback.ts` (`synthesizeFallbackMotion` — AABB escape for legacy `none` motions), `camera.ts` (`fitFraming` — live frustum fit around the planner's baked view direction), `raw/` (WASM fallback tier: `loadRawModel` via occt-import-js).
+
+## Cross-References
+
+- **Consumers**: ERP `apps/erp/app/components/CadModel.tsx`, `apps/erp/app/modules/production/ui/Assemblies/*`, route `apps/erp/app/routes/x+/assembly+/$id.tsx`; MES `apps/mes/app/components/AssemblyView.tsx` + `JobOperation`; Inngest `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts` (imports `@carbon/viewer/steps`).
+- **Contracts**: `docs/specs/animated-work-instructions-contracts.md` (mirrored by `types.ts`).
+- **Model paths / raw limits**: `@carbon/utils` (`modelPathOptimizeFormat`, `MODEL_RAW_KEEP_MAX_BYTES`).
+</content>
+</invoke>
diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsx
index 450a82d8f2..b7ca880709 100644
--- a/packages/viewer/src/AssemblyPlayer.tsx
+++ b/packages/viewer/src/AssemblyPlayer.tsx
@@ -60,6 +60,12 @@ export type { FutureComponentsMode } from "./visibility";
/** Marquee rectangle in canvas-local CSS pixels while box-selecting. */
type BoxRect = { left: number; top: number; width: number; height: number };
+/**
+ * Loop mode (MES) holds the seated pose for this long at the end of each cycle
+ * before replaying the insertion — a calmer cadence than a seamless repeat.
+ */
+const LOOP_END_PAUSE_SECONDS = 2;
+
export type AssemblyPlayerProps = {
glbUrl: string;
graphUrl: string;
@@ -112,6 +118,12 @@ export type AssemblyPlayerProps = {
* just that step, and it only continues through the rest once Play is pressed.
*/
autoPlay?: boolean;
+ /**
+ * Loops the active step's insertion animation continuously instead of playing
+ * it once and holding the seated pose. Used by MES playback, where the operator
+ * stays on one step and the motion should keep replaying.
+ */
+ loop?: boolean;
/**
* Named subassembly units (authored "plan as one component" groups). A step whose
* components are exactly one of these is titled by the unit's name rather than by
@@ -125,6 +137,12 @@ export type AssemblyPlayerProps = {
* path would be misleading.
*/
suppressFallbackMotions?: boolean;
+ /**
+ * Hides the footer caption (the active step's title + instructionText). Shop-floor
+ * (MES) playback shows the step name/description in its own panel, so the in-player
+ * caption is redundant there.
+ */
+ hideCaption?: boolean;
mode?: "dark" | "light";
className?: string;
};
@@ -171,8 +189,10 @@ export const AssemblyPlayer = forwardRef<
defaultFutureMode = "ghost",
componentPickerActive = false,
autoPlay = true,
+ loop = false,
units,
suppressFallbackMotions = false,
+ hideCaption = false,
mode = "dark",
className
},
@@ -466,6 +486,7 @@ export const AssemblyPlayer = forwardRef<
steps={displaySteps}
activeStepIndex={clampedIndex}
isPlaying={isPlaying}
+ loop={loop}
futureMode={futureMode}
highlightedNodeIds={highlightedNodeIds}
hiddenNodeIds={hiddenNodeIds}
@@ -670,20 +691,22 @@ export const AssemblyPlayer = forwardRef<
</div>
</div>
- {activeStep && (activeStepTitle || activeStep.instructionText) && (
- <div className="border-t border-border bg-background px-3 py-2">
- {activeStepTitle && (
- <p className="text-sm font-medium text-foreground">
- {activeStepTitle}
- </p>
- )}
- {activeStep.instructionText && (
- <p className="text-sm text-muted-foreground">
- {activeStep.instructionText}
- </p>
- )}
- </div>
- )}
+ {!hideCaption &&
+ activeStep &&
+ (activeStepTitle || activeStep.instructionText) && (
+ <div className="border-t border-border bg-background px-3 py-2">
+ {activeStepTitle && (
+ <p className="text-sm font-medium text-foreground">
+ {activeStepTitle}
+ </p>
+ )}
+ {activeStep.instructionText && (
+ <p className="text-sm text-muted-foreground">
+ {activeStep.instructionText}
+ </p>
+ )}
+ </div>
+ )}
</div>
);
});
@@ -796,6 +819,7 @@ function AssemblyScene({
steps,
activeStepIndex,
isPlaying,
+ loop,
futureMode,
highlightedNodeIds,
hiddenNodeIds,
@@ -824,6 +848,8 @@ function AssemblyScene({
steps: AssemblyStep[];
activeStepIndex: number;
isPlaying: boolean;
+ /** Loop the active step's animation continuously (MES playback) */
+ loop: boolean;
futureMode: FutureComponentsMode;
highlightedNodeIds?: string[];
hiddenNodeIds?: string[];
@@ -1248,6 +1274,9 @@ function AssemblyScene({
}));
const action = mixer.clipAction(clip);
+ // Play the insertion once and hold the seated pose. The editor keeps it seated;
+ // MES loop mode replays it from the frame loop after LOOP_END_PAUSE_SECONDS, so
+ // each cycle ends on a brief settled pause instead of a seamless repeat.
action.setLoop(LoopOnce, 1);
action.clampWhenFinished = true;
action.play();
@@ -1281,6 +1310,7 @@ function AssemblyScene({
clipKey,
activeStepIndex,
isEditingActive,
+ loop,
seekRef,
playheadRef
]);
@@ -1396,21 +1426,31 @@ function AssemblyScene({
});
useFrame((_, delta) => {
- if (isPlaying) {
+ // MES loop: freeze the animation while the operator manipulates the model
+ // (orbit/zoom/pan), so they can inspect it without the parts moving; it
+ // resumes the moment they let go. Only in loop mode — the editor is unaffected.
+ const advancing = isPlaying && !(loop && orbitingRef.current);
+ if (advancing) {
mixer.update(delta);
localElapsedRef.current += delta;
}
const segment = segments[activeStepIndex] ?? 0;
const clamped = Math.min(localElapsedRef.current, segment);
playheadRef.current = (startTimes[activeStepIndex] ?? 0) + clamped;
- if (
- isPlaying &&
- !finishedRef.current &&
- segment > 0 &&
- localElapsedRef.current >= segment
- ) {
- finishedRef.current = true;
- onStepFinished?.();
+ if (advancing && segment > 0 && localElapsedRef.current >= segment) {
+ if (loop) {
+ // Hold the seated pose for LOOP_END_PAUSE_SECONDS (the action is
+ // LoopOnce+clamp, so the mesh stays put), then replay the insertion from
+ // the start — the seated fade re-runs when localElapsed wraps to 0.
+ if (localElapsedRef.current >= segment + LOOP_END_PAUSE_SECONDS) {
+ localElapsedRef.current = 0;
+ finishedRef.current = false;
+ actionRef.current?.reset().play();
+ }
+ } else if (!finishedRef.current) {
+ finishedRef.current = true;
+ onStepFinished?.();
+ }
}
});
diff --git a/packages/viewer/src/AssemblyViewer.tsx b/packages/viewer/src/AssemblyViewer.tsx
index a161873a9b..a344e91469 100644
--- a/packages/viewer/src/AssemblyViewer.tsx
+++ b/packages/viewer/src/AssemblyViewer.tsx
@@ -30,13 +30,7 @@ export function AssemblyViewer({
const isDarkMode = mode === "dark";
return (
- <div
- className={cn(
- "relative h-full w-full",
- isDarkMode ? "bg-[#141619]" : "bg-white",
- className
- )}
- >
+ <div className={cn("relative h-full w-full bg-card", className)}>
<Canvas
// Logarithmic depth buffer: distributes depth precision across a huge
// CAD scale range (metre-scale body, mm-scale parts) so coplanar faces
@@ -60,10 +54,12 @@ export function AssemblyViewer({
// Explicit CSS background on the canvas element: with alpha:true the
// canvas layer is otherwise transparent, and Chrome's recomposite
// during page unload/reload flashes such layers white in dark mode.
+ // Use the theme's card token so the viewer matches the surrounding cards
+ // in every theme instead of a hardcoded color.
style={{
position: "absolute",
inset: 0,
- background: isDarkMode ? "#141619" : "#ffffff"
+ background: "hsl(var(--card))"
}}
>
<ambientLight intensity={isDarkMode ? 0.6 : 0.8} />
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 03b44256ea..3cee2a1ace 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1233,6 +1233,12 @@ importers:
isbot:
specifier: 'catalog:'
version: 5.1.37
+ konva:
+ specifier: ^9.3.22
+ version: 9.3.22
+ kysely:
+ specifier: 'catalog:'
+ version: 0.28.15
localforage:
specifier: 1.10.0
version: 1.10.0
@@ -1245,6 +1251,9 @@ importers:
non.geist:
specifier: 'catalog:'
version: 1.0.4
+ pdfjs-dist:
+ specifier: 5.4.296
+ version: 5.4.296
posthog-js:
specifier: 'catalog:'
version: 1.367.0
@@ -1263,6 +1272,9 @@ importers:
react-icons:
specifier: 'catalog:'
version: 5.6.0([email protected])
+ react-konva:
+ specifier: ^18.2.10
react-pdf:
specifier: 'catalog:'
diff --git a/setup.sh b/setup.sh
index beda11d5eb..47d08ba7dc 100755
--- a/setup.sh
+++ b/setup.sh
@@ -353,6 +353,38 @@ uninstall_proxy_daemon() {
ok "LaunchDaemon removed"
}
+# Install Draco (mesh compression) for the optional `assembler` geometry
+# service. The `draco-bridge` crate compiles a C++ shim against Draco's headers
+# and `build.rs` expects the Homebrew keg at /opt/homebrew/opt/draco on macOS.
+# Idempotent — skips when already installed. Best-effort: the rest of the stack
+# runs without the assembler, so a failure here only warns.
+install_draco() {
+ hdr "Installing Draco (assembler build dep)"
+ case "$(uname -s)" in
+ Darwin*)
+ if [[ -d "$(brew --prefix 2>/dev/null)/opt/draco/include/draco" ]]; then
+ info "draco already installed"
+ return 0
+ fi
+ if ! command -v brew >/dev/null 2>&1; then
+ warn "Homebrew not found — install draco manually (\`brew install draco\`) if you need the assembler."
+ return 0
+ fi
+ if brew install draco; then
+ ok "draco installed via brew"
+ else
+ warn "\`brew install draco\` failed — the assembler won't build until it's installed."
+ fi
+ ;;
+ Linux*)
+ info "On Linux install draco via your package manager (e.g. \`apt install libdraco-dev\`) if you need the assembler."
+ ;;
+ *)
+ info "skipping draco install on this platform"
+ ;;
+ esac
+}
+
install() {
case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*|Linux*|Darwin*) ;;
@@ -408,6 +440,8 @@ install() {
install_proxy_daemon || true
+ install_draco || true
+
hdr "Activate"
printf ' Open a new shell, or run:\n\n'
printf ' %s\n\n' "$(kbd "source $rc")"