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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(api): declared MCP tools, no `_operation`, audit-column and wasm fixes, serial order, turbo caching (#1777)
Sid22c9b9850849
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex cf60f1e01e..e50ec78e21 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2648,6 +2648,37 @@ tiebreak (a label, a sort order, then the id). Never rely on insertion order sur**Applies to:** any list ordered by `createdAt` whose rows are written together — RPCs,Kysely transactions, `insertInto(...).values([...])`, seeds.+## `scripts/one-off/` is executed in production++**Context:** A codemod that added `@mcp` tags to service files was saved as+`scripts/one-off/tag-mcp-exposure.ts` — "a script run once".++**Problem:** That folder is a registry, not a scratch area. `ci/src/migrations.ts` runs+every `.ts` file in it against every workspace database on the next deploy and records it+in `scriptRun`. A source-rewriting codemod there would have been executed by the deploy+workflow.++**Rule:** `scripts/one-off/` is only for one-time DATA migrations (see its README). A+codemod is run locally and deleted, or lives in `scripts/` if it is worth keeping.++**Applies to:** anything added under `scripts/one-off/`.++## A lookup table keyed by source text must be a `Map`++**Context:** The MCP generator decided "is this call a database write" with+`WRITES[memberName]` over an object literal.++**Problem:** `memberName` comes from the code being analysed, so `x.toString()` looked up+`WRITES["toString"]`, found `Object.prototype.toString`, and counted as a write. Five read+tools silently left the manifest until the digest diff showed them missing.++**Rule:** When the key is arbitrary input (an identifier from parsed source, a column name,+a user string), use a `Map`/`Set` or `Object.hasOwn`, never `obj[key]` truthiness. And diff+the generated manifest against the previous one before trusting a generator change.++**Applies to:** `scripts/lib/service-ast.ts`, and any analyser or dispatcher that indexes a+record by a name it did not choose.+## A JS array bound for a jsonb column must be stringified on the Kysely path**Context:** `quoteLinePrice.priceTrace` (a `PriceTraceStep[]`) is written both through@@ -2706,3 +2737,53 @@ awaited.drawer (`foo.tsx` + `foo.new.tsx`). A list loader reads the whole query string, so it passes`search: "all"`. A loader that reads the pathname, a cookie or a header must not use thehelper.++## A cached generator's inputs are everything it executes, not everything it parses++**Context:** The MCP manifest generator was made a cached Turborepo task with `inputs`+listing the service, models and `types.ts` files it parses.++**Problem:** It also EXECUTES every `*.models.ts` to convert the zod validators, so the+schemas depend on whatever those files import: `sales.utils.ts`, `accounting.utils.ts`,+`samplingStandards`, `@carbon/utils`. A change to one of those was a cache hit; turbo+restored the old manifest (and the old committed digest) over the working tree, and the+build bundled it. Uncached, this could not happen.++**Rule:** Before caching a task, list what it loads and runs, not only what it reads on+purpose, and pin that list with a test against the task's real imports. If the true set+cannot be named, leave the task uncached.++**Applies to:** `//#generate:mcp` in `turbo.json` (pinned by+`apps/erp/test/mcp-manifest-cache-inputs.test.ts`), and any task given `inputs`.++## A key looked up "anywhere in the payload" finds the wrong one++**Context:** The API dispatcher decides whether an upsert creates or updates from the+record's `id`. It looked for `id` at the top level and then inside any nested object, to+support `{ job: { id } }`.++**Problem:** `{ name: "x", customFields: { id: "z" } }` matched the nested `id`, so a+create was stamped as an update and went down the service's update branch.++**Rule:** Read a record's key only where the record can be: the body itself or the wrapper+named by the service's payload parameter. A search that descends into arbitrary objects+will eventually match user data.++**Applies to:** `resolveUpsertOperation` / `recordField` in+`apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts`.++## A git merge can move a doc comment onto a different function++**Context:** Every API tool is declared by an `@mcp` line in its function's doc comment.+Main inserted a new function directly under an existing doc block.++**Problem:** The merge was clean, but the doc block (and its `@mcp` line) now sat above+the NEW function, and the function it described had none. That function silently stopped+being a tool. Nothing fails: an untagged export is simply not exposed.++**Rule:** After merging into a branch that touches service files, regenerate the manifest+and diff the tool NAMES against the pre-merge list. A name that disappears is a displaced+tag until proven otherwise.++**Applies to:** `apps/erp/app/modules/*/*.service.ts`, `pnpm run generate:mcp`.+diff --git a/.ai/specs/2026-10-01-mcp-generator-ts-morph.md b/.ai/specs/2026-10-01-mcp-generator-ts-morph.mdnew file mode 100644index 0000000000..034a833634--- /dev/null+++ b/.ai/specs/2026-10-01-mcp-generator-ts-morph.md@@ -0,0 +1,410 @@+# MCP generator: replace hand-rolled TypeScript parsing with ts-morph++> Status: in progress — Phase 1, the structural half of Phase 2 and the ts-morph bump implemented; the rest of Phase 0 (scripts/ typecheck and lint coverage), 2b, 2c and 3 open+> Author: Sidwebworks+> Date: 2026-10-01++## TLDR++`scripts/lib/service-metadata.ts` derives the entire MCP / v1-API operation+manifest (1557 tools) by parsing TypeScript as **text** — 105 regexes, a+hand-rolled type parser, a brace/comment scanner, and body substring scans.+The robust tool for this is already a dependency of the same generator:+`scripts/lib/response-schema.ts` builds a real ts-morph `Project` off the ERP+tsconfig and reflects return types through the actual TypeChecker. This spec+migrates the textual half onto that same `Project`, in four phases, deleting+~750 lines while keeping `buildAllToolMetadata` synchronous and pure. Phases 0–2+are digest-neutral by construction; Phase 3 (type resolution) is expected to+refine ~531 param schemas and is reviewed by spot-check per category.++## Problem Statement++The generator has two halves that answer the same question with different+machinery, in the same run, over the same files.++`response-schema.ts:17` imports ts-morph, and at `:271-280` it builds a+`Project` from `apps/erp/tsconfig.json`, adds exactly the three files per module+(`{mod}.service.ts`, `{mod}.ee.service.ts`, `{mod}.mcp.server.ts`), calls+`project.resolveSourceFileDependencies()`, and iterates+`source.getFunctions().filter(f => f.isExported())`. It reflects 1493/1574+return types in ~4s.++`service-metadata.ts` re-derives the same file list with `fs.existsSync` and the+same function list with `/export\s+(?:async\s+)?function\s+(\w+)\s*\(/g`, then+hand-parses types, JSDoc, and function bodies from strings.++Measured against the current file (1675 lines, i.e. after the fallback deletion+in `5c90a8df30`), 752 lines (44%) are work the compiler in the same process has+already done:++| Lines | Layer | Functions |+|---|---|---|+| 199 | text scaffolding | `skipComment`, `findMatchingBrace`, `splitAtTopLevel`, `isArrowClose`, `findTopLevel`, `stripComments`, `extractFunctionBody`, `precedingJsdoc`, `parseExportedFunctions`, `destructuredParamName`, `inferTypeFromDefaultLiteral` |+| 498 | TS type parser | `typeToJsonSchema`, `genericInner`, `wrapsWholeType`, `resolveNestedInferType`, `resolveInferExpression`, `parseInlineObjectType`, `splitObjectFields`, `resolveTypeAlias`, `lookupValidatorSchema` |+| 55 | body substring scans | `classifyFunction`, `functionBodyDeletes`, `functionBodyPaginates`, `functionBodyTables`, `usesOperationDiscriminator` |++Concrete defects this shape causes today:++1. **`extractFunctionBody` resolves the wrong body for a shadowed function.** It+ regex-matches the first `export function <name>(` in `service + "\n" ++ mcpServer` concatenated content, so a `mcp.server.ts` wrapper's classification,+ pagination and table scans are taken from the *service* body it shadows. The+ file's own comment admits this. One function is affected today+ (`production.upsertJobMaterial`).+2. **An exported arrow function is invisible.** `production.getPartDocuments` is+ `export const … = async (…) =>`, which the regex never matches, so it is+ absent from the manifest with no diagnostic. It is the only one today.+3. **Body scans are substring matches, not call sites.** "Does `.delete(` appear+ in this text" cannot distinguish a real call from a comment, a string, or a+ nested closure. `no-missing-audit-column` in `@carbon/checks` had two+ false-positive classes from exactly this style of matching (PR #1777 review),+ which is the same bug shape one layer out.+4. **No safety net.** Nothing typechecks or lints `scripts/`: root+ `tsconfig.json` is `{}` and biome's `files.includes` is+ `(apps|packages|docs)/**`, so `biome check scripts/…` reports "Checked 0+ files". That is how this file reached 105 regexes unnoticed.++What is **not** wrong, and bounds the ambition here: the type parser is+currently producing good output. 1434 of 1557 tools (92%) have a non-empty param+schema, and the single non-READ tool with an empty one legitimately takes zero+user params. This is a maintainability and robustness change, not a bug fix.++### Prior work already landed++Commit `5c90a8df30` deleted the source-text zod fallback+(`parseValidatorFields`, `extractValidatorRhs`, `parseFirstZObject`,+`zodExprToJsonSchema`, 160 lines) after instrumentation showed all 342 `z.infer`+params resolve `native` and the fallback fired zero times, and made a module+load failure refuse to write rather than publish a lossy manifest. That is the+precedent this spec follows: measure the route, delete what never runs, fail+loudly instead of degrading.++### What landed after this spec was written, and what it changed++Two commits moved the ground under Phase 2, so the design below is not the one+originally written here.++**Exposure is now opt-in** (`a961578699`). A WRITE/DESTRUCTIVE function reaches+the API only with an `@mcp` JSDoc tag, gated by `MCP_MODULE_ALLOWLIST`+(`apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.ts`). The surface went 1557 →+1468. That matters here for one reason: **`classifyFunction` is now+load-bearing.** It was a name-verb heuristic feeding a metadata field; it now+decides whether a function needs a tag at all, so its errors change what is+published. Three reads are already misclassified WRITE and had to be tagged to+stay exposed — `items_diffMethod`, `items_lookupBuyPrice`,+`shared_lookupPriceFromBreaks` (also `items_matchItemIdByText`,+`production_maxToolQuantityByItem`, `shared_lookupBuyPriceFromMap`,+`shared_resolveSupplierPrice`). `@mcp` means "expose", not "this writes", so+they are harmless today, but the inaccuracy now leaks into exposure decisions.++**The audit-column analysis was measured against a ts-morph prototype**, and the+result was not the expected one. Over the pre-fix baseline: 58 of 77 drops+agreed, ts-morph found **0** breakage the string version missed (including across+the 36 multi-table functions the string version skips entirely), the 19+string-only drops are writes built from an explicit literal where the field+never reaches the row either way, and the prototype produced **one false+positive** of its own (`purchasing_upsertPurchaseOrder`, from misattributing a+receiver chain). So Phase 2 is not a correctness upgrade for that rule — it is a+maintainability one, plus the ability to express cases the regex cannot.++Two constraints came out of that measurement and both belong in the design:++- **Removal must be asymmetric.** 292 tables declare `createdBy TEXT NOT NULL`,+ so wrongly REMOVING an injection trades a PGRST204 for a NOT NULL violation.+ Only a provable break justifies a removal; "looks unnecessary" never does. A+ symmetric "is it needed?" rule disagreed with the baseline 244 times.+- **The signature is a hard constraint.** `insertDepreciationRun` and+ `upsertReimbursementLines` declare `createdBy: string` in their parameter type+ and read it explicitly. Any rule must consult+ `param.getType().getProperty("createdBy")` and keep it.++**And both analyses share a blind spot neither can close: they are+intra-procedural.** 24 audit-injecting tools hand their payload to an edge+function (`get-method`, `recalculate`, `post-picking`, `batch-operations`), three+of them by spread (`body: { type: "create", ...args }`). Those turn out to be+safe only because every one of those functions re-validates its body with a zod+schema and `z.object()` strips unknown keys — a property of the RECEIVING code+that the generator knows nothing about. That is the real lesson from the+production incident: the analysis was never wrong, it was never asked.++## Proposed Solution++Hoist one shared ts-morph `Project`, hand it to both halves of the generator as+data, and replace each textual layer with the equivalent AST/TypeChecker query.++`buildAllToolMetadata` stays **synchronous and pure** — the property its design+comment deliberately protects. ts-morph's API is synchronous, so the `Project`+is passed in exactly as `validators` and `responses` already are.++### Phases++Each phase is its own commit with its own digest verdict, so a churn diff is+never mixed with a refactor diff.++**Phase 0 — floor.** Add `scripts/tsconfig.json` extending the repo base, add+`scripts/**` to biome's `files.includes`, and add both to the CI `Typecheck` and+`Lint` jobs. Fix the pre-existing errors this surfaces (measured: 33 across ~10+files with an ad-hoc `tsc` invocation; a real tsconfig extending the base should+resolve the subset that came from `packages/database` being pulled in with the+wrong module resolution). Also bump `ts-morph` 22.0.0 → 28.0.0 in this phase, on+its own commit: ts-morph carries its own TypeScript (22 bundles+`@ts-morph/[email protected]`, ≈ TS 5.4) while the repo compiles on 5.8.3, so+`response-schema.ts` currently reflects types with an older compiler than the+one that typechecks the tree. Any digest movement from the bump must be+attributable to the bump alone. Digest verdict: **must be unchanged**.++**Phase 1 — discovery and JSDoc.** Replace `parseExportedFunctions`,+`precedingJsdoc`, `destructuredParamName` and `inferTypeFromDefaultLiteral` with+`source.getFunctions()`, `fn.getJsDocs()`, `param.getName()` and+`param.getInitializer()`, reading from the shared `Project`. Shadowing becomes+explicit: the `mcp.server.ts` declaration wins, and its OWN body is the one+scanned. Additionally collect exported arrow functions+(`getVariableStatements()` whose initializer is a function), and add+`production_getPartDocuments` to `MCP_BLOCKED_TOOL_NAMES` with the rest-param+reason (below). Digest verdict: **must be unchanged** — verified below.++**Phase 2 — body scans.** Replace the five substring scans with+`fn.getDescendantsOfKind(SyntaxKind.CallExpression)` queries: a `.delete()` /+`.deleteFrom()` call for `classifyFunction`, `setGenericQueryFilters` / `.range`+for `functionBodyPaginates`, `.from("t")` / `insertInto("t")` /+`updateTable("t")` string-literal arguments for `functionBodyTables`, and the+`_operation` discriminator for `usesOperationDiscriminator`. Digest verdict:+**must be unchanged** for pagination and `_operation`; `classification` and+`injectAuth` may move, and each move is justified below.++Phase 2 carries three sub-goals the original draft did not have:++**2a — `classifyFunction` becomes structural, because exposure now depends on+it.** A `.delete(` substring cannot tell a call from a comment, a string, or a+nested closure, and it is the reason seven read helpers are classified WRITE and+need an `@mcp` tag to stay exposed. On the AST the question is exact: does the+function contain a `CallExpression` whose callee is a `.delete` / `.deleteFrom`+member, and does it contain any write call at all. Expect `classification` to+change for those seven; each is a read gaining its correct label, and each drops+its now-unnecessary tag in the same commit.++**2b — the audit-column rule keeps its asymmetry and gains conflict+reporting.** Per write call site, resolve that site's OWN table (so the 36+multi-table functions stop being skipped), decide payload flow by symbol+identity rather than a spread regex, and consult the parameter TYPE for a+declared `createdBy`/`updatedBy`. Remove a field only when every write receiving+the payload targets a table lacking it; when some targets have it and some do+not, that is a genuine conflict in the service — **report it and keep the+field**, never silently pick.++**2c — refuse rather than assume when the payload escapes analysis.** If the+payload object is passed to `functions.invoke`, an `.rpc`, or another function,+the generator cannot see where it lands and must say so instead of quietly+continuing to inject. This is the sub-goal that addresses the production+incident's actual cause, and it is the opposite of what both the string version+and the first ts-morph prototype do today. The report is advisory at first (the+24 known handoffs are all zod-guarded, so failing hard would block the build for+no live defect) and becomes a refusal once the list is known-empty.++**Phase 3 — type resolution.** Replace the 498-line type parser with+`param.getType()` plus the `typeToJsonSchema` walker `response-schema.ts`+already owns, extracted so both the param side and the return side share one+implementation. The zod path is untouched: a `z.infer<typeof v>` param keeps+resolving through the loaded validator and `z.toJSONSchema`. Digest verdict:+**churn expected and accepted** — see Risks.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Parser technology | ts-morph, already a dependency | `response-schema.ts` already builds a `Project` over the same files in the same run. This is deduplication, not a new dependency. Rejected `ts-json-schema-generator` (duplicates the walker we own, and cannot see supabase-js's select-string inference the checker already resolves) and swc/oxc/tree-sitter (fast parsers, no type resolution — every type bug would survive) |+| `Project` lifetime | One, built once, passed into both halves | Removes a second ~4s parse; `resolveSourceFileDependencies()` is the expensive step and is already paid once |+| `buildAllToolMetadata` shape | Stays sync + pure | ts-morph is synchronous, so the existing "hoist the expensive work, pass results in as data" design survives unchanged. This is the property that makes the builder testable |+| Phase ordering | Floor → discovery → body scans → types | Puts all three digest-neutral phases before the one that churns, so a reviewer never reads a mixed diff |+| ts-morph version | Bump 22.0.0 → 28.0.0 in Phase 0, separate commit | ts-morph bundles its own TypeScript; 22 is ≈ TS 5.4 against the repo's 5.8.3. Bumping inside a later phase would make a compiler-version digest change indistinguishable from a refactor bug |+| Arrow-function exports | Collect them; block `production_getPartDocuments` | Closes the discovery blind spot structurally for every future arrow export. That one function is variadic (`...items: Array<{itemId: string}>`) and the MCP dispatcher builds a named-key JSON payload, so publishing it would ship a tool that can never validate — the same reason `production_returnPickedRemainders*` are already blocked |+| Digest churn review (Phase 3) | Accept the compiler's output; spot-check per category | ~531 params sit in the two shapes where the string parser is weakest. Justifying all of them individually would stall the phase; requiring zero churn would make it unlandable. Spot-check one sample per category (inline object, generic, bare alias) and record the counts in the PR |+| Heuristic 1–6 (multi-tenancy, service shape, RLS, permissions, forms, module layout) | N/A | No database, service, route, form or module change. This touches build tooling under `scripts/` only |+| Heuristic 7 (backward compatibility) | Tool schemas are not a listed contract surface; treat Phase 3 as additive-in-spirit | `BACKWARD_COMPATIBILITY.md` lists Database Schema, Permission Scope Strings, RLS Policy Names, Service Function Signatures, Route Paths, Edge Function Names, Event Types, Component Props, Import Paths and Model Validators. The generated manifest is none of them, and it is regenerated from source on every `postinstall`. Phase 3 must still not *remove* a published field: a param that has a schema today keeps one |+| Audit-column removal | Asymmetric — remove only on proven breakage | 292 tables declare `createdBy TEXT NOT NULL`, so a wrong removal trades PGRST204 for a NOT NULL violation. A symmetric "is it needed?" rule disagreed with the baseline 244 times |+| Declared parameter fields | Always injected | `insertDepreciationRun` / `upsertReimbursementLines` declare `createdBy: string` and read it explicitly; `param.getType().getProperty()` is the only reliable way to see that, and string matching cannot |+| Multi-table conflict | Report and KEEP | A function writing one table that has the column and one that lacks it is at fault; guessing either way breaks a write. One exists today after false positives are discounted |+| Payload escaping the function | Report, then refuse | Both the string version and the ts-morph prototype are intra-procedural; 24 tools hand the payload to an edge function. Advisory first because all 24 are zod-guarded today |+| `classifyFunction` | Structural, in Phase 2a | It stopped being a metadata field and became an exposure gate when `@mcp` landed; seven reads are misclassified WRITE today |+| Competitor research (`/research`) | N/A | This is internal build tooling with no ERP domain logic. The skill's research gate exists so domain behaviour is not invented; there is no domain behaviour here |++## Data Model Changes++None. No migration, no table, no column. This spec changes only+`scripts/**`, `apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts`,+`biome.jsonc` and `.github/workflows/check.yml`.++## API / Service Changes++No service function changes. The generator's internal contract changes:++- `BuildOptions` gains `project: Project` (the shared ts-morph project).+- `ParsedFunction` is replaced by, or backed by, a ts-morph+ `FunctionDeclaration` / `VariableDeclaration`, so `params` carries real `Type`+ objects instead of `typeStr` strings.+- `buildAllToolMetadataWithValidators` builds the `Project` alongside the+ validator registry and the response index, and passes all three in.+- `MCP_BLOCKED_TOOL_NAMES` gains `production_getPartDocuments`.++The published artifacts (`tool-metadata.json`, `tool-manifest.digest.json`) keep+their exact shape. `manifest-digest.ts` is untouched, so `check:manifest`+remains the oracle throughout.++## UI Changes++None.++## Acceptance Criteria++- [ ] `pnpm run generate:mcp` after Phase 0, 1 and 2 leaves+ `tool-manifest.digest.json` byte-identical — `sha256` matches+ `48b51bb5116e583aae5ca3490fcdf010b29833ba4553173961807ff97f47d624` and+ `git diff` on the file is empty+- [ ] `pnpm run check:manifest` prints `digest current` after every phase+- [ ] `production_upsertJobMaterial` is derived from the `mcp.server.ts`+ wrapper's own body after Phase 1, and its digest entry is unchanged+ (verified: the wrapper and the service body yield identical scan results —+ 0 `.delete(`, 0 pagination, 0 `_operation`; the wrapper names two tables so+ the audit-column drop stays inapplicable either way)+- [ ] `production_getPartDocuments` is discovered by the generator and excluded+ by `MCP_BLOCKED_TOOL_NAMES`, so `totalTools` stays 1557+- [ ] A new exported arrow function in a service file appears as a tool without+ any generator edit (add one in a scratch commit, confirm, revert)+- [ ] A new exported function with a rest parameter is reported by name at+ generate time rather than published as an uncallable tool+- [ ] Phase 3: every tool that has a non-empty param schema today still has one+ (no field loss); the PR body records changed-entry counts per category+ with one spot-checked example each+- [ ] `scripts/**` is covered by `pnpm run typecheck` and `pnpm run lint`, both+ green, and CI runs them+- [ ] `pnpm exec turbo run typecheck --filter='*' --concurrency=1` is 33/33 and+ `pnpm run test` is green after each phase+- [ ] The seven reads currently classified WRITE (`items_diffMethod`,+ `items_lookupBuyPrice`, `items_matchItemIdByText`,+ `production_maxToolQuantityByItem`, `shared_lookupBuyPriceFromMap`,+ `shared_lookupPriceFromBreaks`, `shared_resolveSupplierPrice`) are+ classified READ after 2a, and their `@mcp` tags are removed in the same+ commit+- [ ] A function whose payload reaches `functions.invoke` / `.rpc` / another+ function is listed by name in the generator output, with a count+- [ ] A multi-table conflict is reported and the field KEPT — verified by+ constructing one in a fixture+- [ ] A parameter type declaring `createdBy` keeps the injection regardless of+ which tables the function writes+- [ ] `service-metadata.ts` is under 950 lines with no `findMatchingBrace`,+ `stripComments`, `extractFunctionBody` or `splitAtTopLevel`++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Phase 3 silently drops a param schema, publishing `{}` where a real schema belonged — an MCP client then guesses field names and the guess reaches an insert (the PGRST204 shape) | High | Assert per-tool that a non-empty schema never becomes empty, as a generate-time refusal, not a review step. `generate:mcp` already refuses to write on unresolved validators; extend the same gate |+| Phase 3 churn is large enough to be unreviewable | Medium | Bounded by measurement: 531 of 2338 user params (23%) sit in the two weak shapes; 67% are primitives the compiler treats identically. Spot-check per category, record counts. If churn exceeds ~200 entries, split Phase 3 by shape (generics first, inline objects second) |+| ts-morph 28 resolves types differently from 22, moving the digest for reasons unrelated to the refactor | Medium | Phase 0 bumps it alone, with the digest as the verdict. A change there is investigated before any refactor lands on top |+| Sharing one `Project` couples the two halves, so a failure in one takes out both | Low | It already is one program in practice; a file that will not parse breaks return-type reflection today. `generate:mcp` refuses to write on failure |+| Phase 0 surfaces pre-existing `scripts/` errors that balloon the change | Medium | 33 measured with ad-hoc flags; a real `scripts/tsconfig.json` extending the repo base should drop the ones caused by wrong module resolution. If the genuine remainder is large, fix them in a dedicated commit before the tsconfig is wired into CI, so the gate lands green |+| Peak memory: one `Project` over every service file plus `resolveSourceFileDependencies` | Low | Already paid by `response-schema.ts` today (~4s, no OOM). Whole-repo `tsgo` is the known memory hazard, not this |+| Behaviour change hides in a "digest-neutral" phase because the digest hashes schemas rather than storing them | Low | The digest stores `schema` and `response` as hashes, so any schema change does move it. Field-level drift cannot hide behind an unchanged hash |++## Open Questions++> HARD STOP: Do not proceed with implementation until these are answered.++All resolved with the user on 2026-10-01 before this spec was written.++- [x] Does Phase 3 (the 498-line type parser) happen at all, given the parser+ currently works — 92% of tools have real schemas and the only non-READ+ tool with an empty one legitimately takes zero params — so the change is+ maintainability against churn on a generated public contract?+ — **Answer:** Both phases. Do the digest-neutral work first, then the type+ parser. The duplication and fragility are worth removing even without a+ forcing bug; the phase split keeps the churn isolated and reviewable.+- [x] `production.getPartDocuments` is an exported arrow function and is+ invisible to the manifest today. Preserve the omission, or collect arrow+ functions?+ — **Answer (after re-ask):** Collect them structurally, and block this one.+ The first answer was "include it", which conflicts with the code: the+ function is variadic (`...items: Array<{itemId: string}>`) and the MCP+ dispatcher builds a named-key JSON payload, so publishing it would ship a+ tool that can never validate — exactly why+ `production_returnPickedRemaindersForOperation/ForJob` are already on+ `MCP_BLOCKED_TOOL_NAMES`. It is also the only rest-param export in the+ tree, so the generator has no precedent for handling one. Resolution:+ collect arrow functions, add `production_getPartDocuments` to the blocked+ list with that reason, and report any future rest-param export by name at+ generate time.+- [x] How is the Phase 3 digest diff reviewed — justify every changed entry,+ accept and spot-check, or require zero churn?+ — **Answer:** Accept the compiler's output as authoritative, spot-check a+ sample per category (inline object, generic, bare alias), and record the+ counts. Justifying each entry would stall the phase; requiring zero churn+ would make it unlandable. Paired with the hard generate-time assertion+ that no tool loses a schema it already had.+- [x] `scripts/` has no typecheck or lint coverage — fold that into this spec or+ raise it separately?+ — **Answer:** Fold it in, as Phase 0, so the migration lands on a floor+ that catches drift. Cost acknowledged: 33 pre-existing errors measured+ across ~10 files, some of which are artifacts of ad-hoc `tsc` flags rather+ than real defects.++## Changelog++- 2026-10-02: `ts-morph` bumped 22.0.0 → 28.0.0 (the Phase 0 bump, on its own+ commit). Its bundled TypeScript goes from 5.4.2 to 6.0.2. Digest verdict:+ byte-identical, so no schema, response or classification moved. Uncached+ generation is about 5s slower (~25s from ~20s); a cache hit is unaffected.+- 2026-10-02: The name stopped deciding anything. Every exposed function now+ declares `@mcp <verb> [destructive]` (`read`, `create`, `update`, `upsert`,+ `delete`, `action`), and classification, permission actions and audit fields+ come from that verb (`MCP_VERBS` in `mcp-exposure.ts`). `inferClassification`,+ `permissionActionsFor`, `computeInjectAuth` and the `INJECT_AUTH_OVERRIDES` /+ `PERMISSION_OVERRIDES` tables are gone; the two override tables became+ `@mcp audit` / `@mcp permission` tags on the functions. Reads are opt-in too: an+ untagged export is not a tool. All 1476 tags were written from the manifest of+ the day and the regenerated digest is byte-identical, so no tool changed. This+ supersedes 2a (structural classification): there is no inferred classification+ left to make structural, only a declared one checked against the body.+ `_operation` was removed in the same pass (`upsert` rule + `@mcp key`).+- 2026-10-01: Phase 1 and Phase 2 (scans + 2a) implemented in+ `scripts/lib/service-ast.ts`. One ts-morph project is shared with+ `response-schema.ts`; discovery, parameters, doc tags and every body question+ come from the AST, and `parseExportedFunctions`, `precedingJsdoc`,+ `extractFunctionBody`, `stripComments` and the regex tag readers are gone.+ Digest verdict against the pre-change manifest (1476 tools): 10 entries moved,+ all explained —+ - `accounting_getOrCreateAccountingPeriod` and+ `accounting_getPeriodCloseChecklist` READ → WRITE (`accounting:view` →+ `accounting:update`). Both insert rows; the name-first rule had published+ them as reads with no `@mcp` opt-in. Both are now tagged.+ - 8 schemas (plus the first of the two above) where a parameter has both a+ type and a default (`sortDescending: boolean = false`): the text parser read+ the type as `"boolean = false"` and published an untyped REQUIRED field;+ they are now typed and optional. So Phase 1 was not digest-neutral, in the+ direction of being correct.+ Divergences from the design above:+ - 2a does NOT turn the seven non-read-named pure functions into READs. A body+ with no write of its own is indistinguishable from one that delegates its+ write (`issueMaterial` → edge function), so the name still breaks that tie+ and those seven keep their `@mcp read` declaration.+ - A write is anchored on a `.from(…)` receiver chain rather than on the member+ name alone; `members.delete(id)` on a Set no longer reads as a row delete.+ - `scripts/one-off/tag-mcp-exposure.ts` was deleted rather than ported: that+ folder is executed against every production database on deploy.+ Not done: Phase 0 (`scripts/` has no tsconfig or lint coverage; ts-morph is+ still 22), 2b (per-call-site table resolution), 2c (escape reporting), and+ Phase 3 (the type parser and its text helpers are still in+ `service-metadata.ts`, now ~1530 lines).+- 2026-10-01: Phase 2 redesigned after measurement, and after opt-in exposure+ landed (`a961578699`). The original draft treated Phase 2 as a drop-in+ ts-morph swap; measuring it showed 58/77 agreement, zero extra breakage found,+ and one false positive of its own, so the phase gained three sub-goals+ (structural `classifyFunction`, the asymmetric audit rule with conflict+ reporting, and escape refusal) and two hard constraints (NOT NULL asymmetry,+ declared-parameter fields). Recorded that both analyses are intra-procedural+ and that 24 edge-function handoffs are safe only through zod stripping in the+ receiving code.+- 2026-10-01: Created. Open questions resolved with the user before writing+ (four asked, one re-asked after the answer contradicted the variadic signature+ in `production.service.ts`). Measurements taken against commit `5c90a8df30`:+ 1557 tools, 1675 lines in `service-metadata.ts`, 752 replaceable, 2338 user+ params by shape, digest `sha256 48b51bb5…`.diff --git a/.claude/rules/conventions-services.md b/.claude/rules/conventions-services.mdindex 80ea236a21..2fdfa1e191 100644--- a/.claude/rules/conventions-services.md+++ b/.claude/rules/conventions-services.md@@ -204,6 +204,40 @@ route-wiring example is in [database-patterns.md](database-patterns.md#transacti- **RPCs**: heavy/aggregate logic is `client.rpc("fn_name", { ... })`; the function isdefined in a migration. See database-patterns.md.+## Exposing a service function as an API tool++An exported function of an ERP `{module}.service.ts` becomes an MCP / v1-API+tool only when its doc comment declares it (`pnpm run generate:mcp` reads the+tags; the function's name decides nothing but the tool's name):++```ts+/**+ * Creates or updates a customer.+ * @mcp upsert+ */+export async function upsertCustomer(…)+```++- **Verb**: `read`, `create`, `update`, `upsert`, `delete`, or `action` (a state+ change that is not a row edit). It sets the permission the caller needs and the+ audit fields the payload is handed. Add `destructive` after a write verb when+ the call can remove rows the caller did not name.+- Leave the tag off unless the function is safe to call with nothing but its+ payload — whatever gate or orchestration its route performs does not run for+ an API caller.+- The first sentence of the doc comment is the tool's description. Write one.+- An upsert that branches on `"createdBy" in payload` must let the API tell+ create from update without being told: give the update shape an `id` the create+ shape does not require, or declare the row it updates with+ `@mcp key <table> <column>`.+- Don't spread a payload into a write on a table the payload has extra keys for;+ build the row. The dispatcher stamps `createdBy`/`updatedBy` onto the payload.+- Generation fails, naming the function, when a declaration contradicts the body+ (a `read` that writes, a delete without `destructive`).++Full vocabulary: [mcp-tools-reference.md](mcp-tools-reference.md) and+`apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.ts`.+## Naming conventions| Operation | Name | First arg |diff --git a/.claude/rules/material-tables.md b/.claude/rules/material-tables.mdindex b36fcda0e1..11f89cb736 100644--- a/.claude/rules/material-tables.md+++ b/.claude/rules/material-tables.md@@ -113,7 +113,8 @@ the service loads the rows they read and writes what they decide.failure there leaves the transaction's writes in place. An update by readable id is refused whenthe material has several revisions (sizes are revisions); pass the item id.- `materialDimension`, `materialFinish`, `materialGrade` and `materialType` have no audit columns,- so their MCP tools inject only `companyId` (`INJECT_AUTH_OVERRIDES` in+ so their MCP tools inject only `companyId` (the generator drops an audit field the+ tool's one table has no column for — `withoutAbsentAuditColumns` in`scripts/lib/service-metadata.ts`). Their update branch filters by `companyId` when given andnever writes it, so an update cannot move a row to another company.diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex d53dc477d2..aeb3d50fa9 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -24,15 +24,30 @@ catalogSearch, toolMetadata }`.> `describe_tool` / `search_tools` read from it at runtime.>> That manifest is **gitignored build output** (1.9 MB, rewritten wholesale on every-> run — it churned 250+ commits). It is produced by `pnpm generate:mcp`, which runs-> from `postinstall` and as the turbo root task `//#generate:mcp` that `typecheck`,-> `build` and `test` depend on — so a fresh clone regenerates it before anything-> imports it. The committed record of the published contract is its small companion+> run — it churned 250+ commits). It is produced by `pnpm generate:mcp`, as the turbo+> root task `//#generate:mcp`. `postinstall` runs that task, and the `typecheck`,+> `build` and `test` of the two packages that read the manifest — `erp` and `docs`+> (`apps/erp/turbo.json`, `docs/turbo.json`) — depend on it, so a fresh clone+> regenerates it before anything imports it. The task is CACHED: its `inputs` in+> `turbo.json` are every `.ts` file under `apps/erp/app/modules`, the app's+> `types` and `utils`, the generated DB types, the two `mcp-*` lib files,+> `scripts/lib`, and the `src` of each package a `*.models.ts` imports. With none+> of those changed turbo restores both output files in milliseconds instead of+> spending ~20s. The validators are why the list is that wide: the generator+> EXECUTES every models file, so an enum array in `sales.utils.ts` or a helper in+> `@carbon/utils` can change a schema. Listing only service/models files made such+> a change a cache hit that restored a STALE manifest, which the build then+> bundled. `apps/erp/test/mcp-manifest-cache-inputs.test.ts` fails when a models+> file imports something the inputs do not cover; the manifest trigger in+> `.husky/pre-commit` names the same set. Types reached only through the compiler+> (a return type declared in a package no models file imports) are still not+> inputs.+> The committed record of the published contract is its small companion> `tool-manifest.digest.json`: one line per operation carrying classification,> permission, injectAuth, argument count and a hash of the schema, so a contract-> change is still one visible line in review. `pnpm check:manifest` regenerates and-> fails if the digest is stale; pre-commit runs it when a service, models or-> generator file is staged.+> change is still one visible line in review. `pnpm check:manifest` regenerates+> WITHOUT the cache and fails if the digest is stale; pre-commit runs it when a+> service, models or generator file is staged.## Endpoint & transport@@ -162,10 +177,10 @@ HTTP/agent/workflow callers of `callOperation` are untouched:"… N more rows omitted" marker — the backstop for the unpaginated `get*List`(fetchAll) operations. A paginated read short of its total appends`(showing R of C rows)` from the envelope's `count`.-- **List paging splits on the manifest's `paginates` flag** (generator body- scan for `setGenericQueryFilters(`/`.range(`, same mechanism as- `functionBodyDeletes`; in `ManifestEntry` AND the committed digest, so a flip- is review-visible). Of ~536 list-shaped ops, only ~127 page natively.+- **List paging splits on the manifest's `paginates` flag** (the generator asks+ the function's AST whether it calls `setGenericQueryFilters` or `.range` —+ `paginates` in `scripts/lib/service-ast.ts`; in `ManifestEntry` AND the+ committed digest, so a flip is review-visible). Of ~536 list-shaped ops, only ~127 page natively.- `paginates: true` (search-style `get*`): `call_tool` INJECTS the paginationPAIR — `limit: MCP_DEFAULT_LIMIT` (25) AND `offset: 0` — for whichever ofthe two the caller omits (flat body, `{ args: {...} }` wrapper, and the@@ -282,8 +297,8 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separatethere handed the service the note STRING instead of the record. The schemadecides: a wrapper op declares one property named for the param, so read it; anop listing the param's own fields is describing it, so pass the whole body.- `_operation` and any property that is itself another serviceParam (`args`, and- scalar siblings like `locationId`) don't count toward that, since each is+ A property that is itself another serviceParam (`args`, and+ scalar siblings like `locationId`) does not count toward that, since each isaddressed on its own pass. When a payload param is an **array** of rows,`enrichWithAuthContext` stamps `createdBy` into each element (insert only) —the top-level stamp never reached inside, so a NOT NULL `createdBy` on the row@@ -383,7 +398,7 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate## Tool metadata & the generator (`scripts/generate-mcp.ts`)`tool-metadata.json` is **generated**, never hand-edited. Run-`npx tsx scripts/generate-mcp.ts`; it parses every `apps/erp/app/modules/*/*.service.ts`+`pnpm run generate:mcp`; it parses every `apps/erp/app/modules/*/*.service.ts`(falling back to the `.ee`-licensed `<module>.ee.service.ts` — e.g. `accounting`),plus an optional server-only companion `<module>.mcp.server.ts` when present (for MCPfunctions that must import `*.server` modules — see the gotcha below — e.g.@@ -392,14 +407,70 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc(`{ generated, totalTools, modules, tools }`). Each tool entry:`{ name, module, classification, description, paramCount, serviceParams, injectAuth, schema }`.-- **Classification** (`classifyFunction`): `delete*` → `DESTRUCTIVE`;- `get|list|fetch|search|find|count|check|is|has*` → `READ`; a WRITE whose- **body issues a delete** (`.delete(` / `.deleteFrom(`, detected by- `functionBodyDeletes`) → `DESTRUCTIVE` too — a delete-and-reinsert `upsert*`- (e.g. `upsertQuoteLinePrices`, `replace*Steps`, favourite toggles) is- destructive-by-omission and the client must treat it as such; everything else →- `WRITE`. Drives the MCP annotations (`READ_ONLY_/WRITE_/DESTRUCTIVE_ANNOTATIONS`- in `packages/ee/src/mcp/types.ts`).+- **How the service files are read** (`scripts/lib/service-ast.ts`): ONE ts-morph+ project, shared with the response-schema reflection. Which functions exist+ (exported declarations AND exported arrow consts), their parameters, their doc+ tags and what their bodies do all come from the AST. The only thing still read+ as text is a parameter's declared TYPE, which `typeToJsonSchema` turns into a+ JSON Schema. A `mcp.server.ts` export that shadows a service function replaces+ it entirely — params, doc and body.+- **A function is a tool because its doc comment says so** (`lib/mcp-exposure.ts`+ is the whole vocabulary). Nothing about a tool is read off the function's name+ except the published name itself (`{module}_{functionName}`):++ ```ts+ /**+ * Creates or updates a customer.+ * @mcp upsert+ */+ export async function upsertCustomer(…)+ ```++ There is one tag, `@mcp`, always lowercase; each line says one thing:++ | Line | Meaning |+ |---|---|+ | `@mcp <verb> [destructive]` | Required, exactly once. No such line → not a tool, reads included. Text after it is a note. |+ | `@mcp permission <module>:<action>[+<action>]` | Only when the gate is not the tool's own module + its verb's action (`getApiKeys` → `users:update`). |+ | `@mcp audit <field>[, <field>]` | Only when the verb's audit fields are wrong for intent the schema cannot express (a ledger insert takes `createdBy` alone). Stated in full; `companyId` is always added. |+ | `@mcp key <table> <column>[=<field>], …` | The row an upsert updates when it exists (below). Several lines are alternatives. |++ The verb decides classification, permission actions and audit fields+ (`MCP_VERBS`), pinned by `apps/erp/test/mcp-tool-permissions.test.ts`:++ | Verb | Classification | Permission | Stamped besides `companyId` |+ |---|---|---|---|+ | `read` | READ | view | — |+ | `create` | WRITE | create | createdBy, updatedBy |+ | `update` | WRITE | update | updatedBy |+ | `upsert` | WRITE | create + update | createdBy, updatedBy |+ | `delete` | DESTRUCTIVE | delete | — |+ | `action` | WRITE | update | — |++ `action` is a state change that is not a row edit (lock a period, complete an+ operation). `destructive` after a write verb relabels it DESTRUCTIVE for the+ client — a delete-then-reinsert `upsert` drops whatever the caller left out —+ without changing its permission or audit fields. Classification drives the MCP+ annotations (`READ_ONLY_/WRITE_/DESTRUCTIVE_ANNOTATIONS` in+ `packages/ee/src/mcp/types.ts`).+- **The declaration is checked against the body** (`declarationOf`), in the one+ direction that can be: `read` on a body that writes, or a write verb whose+ body deletes rows without `destructive`, fails generation; so do an unknown+ verb, a setting given twice, and a rest parameter. A write is a supabase+ `.insert/.upsert/.update/.delete` whose receiver chain is rooted in `.from(…)`+ — through `(… as any)`, parentheses, `await` and one local variable;+ `client.storage.from(…)` does not count — or Kysely+ `insertInto/updateTable/deleteFrom`. `members.delete(id)` on a Set is not a+ write. The reverse cannot be checked: a body with no write of its own may hand+ the work to a helper, an RPC or an edge function, which is why the verb is+ declared rather than inferred. `MCP_MODULE_ALLOWLIST` is the coarse gate (a+ module absent from it exposes nothing), and the generator prints how many+ exported functions carry no tag.+- **Why it is declared.** Every exported function used to be a tool and its name+ decided the rest: `get*` was a READ whatever it did+ (`accounting_getOrCreateAccountingPeriod` inserted a period and was published on+ `accounting:view`), `upsert*` meant "stamp createdBy and updatedBy" whatever the+ table had, and a pure function named `diffMethod` demanded `parts:update`.- **Description** precedence: a function-level **JSDoc** on the service export(first sentence, `@tag`s stripped, trailing period removed, leading letterlowercased unless it starts an acronym, capped ~160 chars —@@ -410,39 +481,50 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mcappend a period — hence the normalization), and are NOT part of the digest,so a description change is invisible in review by design. Pinned by`apps/erp/test/mcp-jsdoc-description.test.ts`.-- **injectAuth** (`computeInjectAuth`): keyed off the **name verb, not the- classification** — only `READ` takes `["companyId"]`. `upsert|create|insert|- add|new|copy|duplicate|generate*` → `["companyId","createdBy","updatedBy"]`;- `update|set|sync|run|…*` → `["companyId","updatedBy"]`; anything else (incl. a- genuine `delete*`) → `["companyId"]`. A DESTRUCTIVE-classified `upsert*` still- inserts rows, so it keeps its `createdBy` — the label is only a caller hint.--- **`_operation`** (`usesOperationDiscriminator`): a tool whose service picks- insert-vs-update by testing for an audit field on the payload gets a **required**- `_operation: "create" | "update"` in its schema — the schema is the only marker,- there is no parallel metadata flag. **BOTH discriminator directions count**:- `if ("createdBy" in …)` (create-branch first, e.g. `upsertQuoteOperation`) AND- `if ("updatedBy" in …)` (update-branch first, e.g. `upsertQuoteMaterial`,- `upsertJobMaterial`, `upsertJob`, `upsertProductionQuantity`, `upsertPartner`,- `upsertPeriodCloseTaskDefinition`). The generator only matched `"createdBy" in`- until it was broadened — so the inverted ones shipped WITHOUT `_operation`, and- since `enrichWithAuthContext` always stamped `updatedBy`, their `"updatedBy" in`- test was always true: every create was forced down the UPDATE branch, matched- zero rows for a fresh id, and returned **PGRST116** — a silent no-op the customer- hit trying to add quote/job materials over the connector. (A few — `upsertJobOperation`,- `upsertContractor`, `upsertGaugeCalibrationRecord` — got `_operation` anyway from- a secondary `"createdBy" in` in the body, but were broken the same way until the- dispatch fix below, because their PRIMARY branch is `"updatedBy" in`.)- The dispatch (`api+/v1+/lib/dispatch.server.ts`) strips `_operation` from the args- (top level *and* the `{ args: {...} }` wrapper) before building the payload, then- stamps audit fields **symmetrically**: on `"create"` it stamps `createdBy` and- **suppresses `updatedBy`**; on `"update"` it stamps `updatedBy` and **suppresses- `createdBy`** — so either convention lands on the branch the caller asked for, and- the create path matches the create-variant service type / UI insert (createdBy, no- updatedBy). With no `_operation` (operation `undefined`) both audit fields are- stamped, as before. Missing/invalid `_operation` on such a tool is rejected before- the service is called; `call_tool.arguments` is `z.any()`, so the dispatch is the gate.- Pinned by `dispatch-parity.test.ts` (cases o/p/q) and `mcp-tool-metadata.test.ts`.+- **injectAuth** starts from the verb's audit fields (table above) plus+ `companyId`, then is checked against the schema (`withoutAbsentAuditColumns`):+ when the function names exactly ONE relation and that relation has no+ `createdBy`/`updatedBy` column, the field is dropped — dispatch stamps these+ onto the payload object, and a service that spreads its argument into the write+ would otherwise send a column that does not exist (PGRST204, how+ `items_upsertItemCustomerPart` failed). Zero or several relations leaves the+ set alone. `userId` is added when the payload's own type declares one+ (`withPayloadUserId`). `@mcp audit` replaces all of that for intent the schema+ cannot express.++- **Create vs update on an upsert is never the caller's question.** A service+ that picks insert-vs-update by testing for an audit field on the payload+ (`branchesOnKeyPresence`: `"createdBy" in …` create-branch first, e.g.+ `upsertQuoteOperation`, or `"updatedBy" in …` update-branch first, e.g.+ `upsertQuoteMaterial`, `upsertJobMaterial`, `upsertJob`) needs exactly ONE of+ the two stamped — stamp both and an `"updatedBy" in` service takes its UPDATE+ branch on every create, matches zero rows and returns PGRST116. The generator+ records how to decide in the manifest entry's `upsert` (also in the digest), and+ fails generation for a branching upsert it cannot give a rule to:+ - **By `id`** (`{ keys: ["id"] }`, most upserts) — read off the parameter's TYPE+ (`idDistinguishesUpdate`, `service-ast.ts`): every union member that requires+ `updatedBy` has an `id`, and no other member requires one. Sending `id` means+ update; omitting it means create.+ - **By lookup** (`lookups: [{ table, match }]`, the rest) — declared on the+ function with `@mcp key <table> <column>[=<field>], …` when the payload+ cannot say: a part's `id` is its part number on create and its item id (or+ part number) on update, so `upsertPart` carries `@mcp key item id` and+ `@mcp key item readableId=id` (alternatives); a pick method has no id, only+ `itemId, locationId`. The dispatcher looks the row up with the caller's+ client, scoped to the caller's company (the table must have `companyId`), and+ updates when it exists.+ `resolveUpsertOperation` (`api+/v1+/lib/dispatch.server.ts`) applies the rule —+ a missing or empty key is a create without asking the database. The key is+ read from the RECORD only: the body's top level, the payload parameter's+ wrapper (`{ job: { id } }`), or a lone unnamed wrapper. Never from any other+ nested object — `{ name, customFields: { id } }` was once read as an update.+ It then stamps+ `createdBy` and suppresses `updatedBy` on create, the reverse on update. The+ key field's schema `description` says what sending it does. These tools used+ to require `_operation: "create" | "update"`; no schema publishes it now, but+ a caller that still sends it is obeyed (and a value other than those two is+ refused). Pinned by `dispatch-parity.test.ts` (f, f2, f3, o–t) and+ `mcp-tool-metadata.test.ts`.## The 15 modules (current `tool-metadata.json`)@@ -484,8 +566,12 @@ the model context or the MCP dispatch.## Gotchas-- The generator reads a service's **parameter list textually**, but resolves more- shapes than it used to. An **inline** array-of-objects+- The generator takes a service's parameters from the AST (name, optionality,+ rest, the `/** doc */` above the parameter, and the type's text with comments+ removed), then resolves that TYPE text — and it resolves more shapes than it+ used to. A parameter with a default is optional and keeps its declared type+ (`sortDescending: boolean = false` used to publish as an untyped, required+ field). An **inline** array-of-objects(`prices: { quantity: number; ... }[]`) now publishes as a typed`{"type":"array","items":{...}}`; a `z.infer<typeof V>` validator param resolves`V.merge(z.object({...}))` / `applyX(...)` wrappers / referenced `*Validator`s@@ -509,8 +595,6 @@ the model context or the MCP dispatch.`apps/erp/test/mcp-tool-metadata.test.ts`). Still opaque, deliberately:compiler-derived types (`ReturnType`/`Awaited`), aliases imported from otherpackages, `Map<...>` params, and genuine `Json`/`unknown`/rich-text fields.- Keep `//` comments above the function, not inside the parameter list (a- comment there is parsed as a property name).- A service whose first parameter is `db` (a Kysely transaction client) is served`getDatabaseClient()` by `dispatch.server.ts`, the same way `client` is servedthe supabase one. A first parameter named anything else falls through to the@@ -521,8 +605,11 @@ the model context or the MCP dispatch.- "Shelf" was renamed to **storage unit**: use `inventory_*StorageUnit*`, not`getShelf` (which no longer exists). "Shelf life" (`*ShelfLife*`) is a*different*, still-current concept — don't conflate them.-- To block a tool from MCP, add its `<module>_<func>` name to- `MCP_BLOCKED_TOOL_NAMES` and regenerate metadata.+- To expose a service function, put `@mcp <verb>` in its doc comment and+ regenerate; without the tag it is not a tool, whatever it is called. To keep an+ exposed-looking function internal on purpose (and say why), also add its+ `<module>_<func>` name to `MCP_BLOCKED_TOOL_NAMES` — that list is enforced at+ run time too.- **Moving a service function to another module RENAMES its published tool**(`production_getInspectionDocument` → `quality_getInspectionDocument`). Add theold name to `OPERATION_ALIASES` (`api+/v1+/lib/operations.server.ts`) in the same@@ -552,8 +639,9 @@ the model context or the MCP dispatch.estimatedQuantity 0 and issue/picking pulled nothing. The wrapper mirrors bothroutes' orchestration (MTO method pull on transition, recalc released creates /all updates) and keeps the exact service payload type so the published schema- hash is unchanged. Body scans (classification, `_operation`) read the FIRST- match in the concatenated content — the service body — so a wrapper must keep- the same discriminator convention as the function it shadows. Pinned by+ hash is unchanged. Classification, the upsert rule and the audit-column rule are+ read from the WRAPPER's own body (it replaces the service function in the AST),+ and it is the wrapper that carries the `@mcp` tags; the service function it+ shadows carries none. Pinned by`mcp-upsert-job-material.test.ts` and the "registers a shadowed mcp.serverfunction exactly once" case in `mcp-tool-metadata.test.ts`.diff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlindex f1a90f7717..8e41eda1c3 100644--- a/.github/workflows/check.yml+++ b/.github/workflows/check.yml@@ -32,6 +32,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfile@@ -57,6 +68,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfile@@ -89,6 +111,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfile@@ -117,6 +150,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfile@@ -144,6 +188,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfile@@ -171,6 +226,17 @@ jobs:packages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+ # Turborepo's local cache, carried between runs: the postinstall+ # (fonts, MCP manifest), typecheck and test restore instead of re-running+ # for packages whose inputs did not change. Keyed per job so each job+ # saves its own tasks; it only ever grows, so bump the prefix to reset it.+ - uses: actions/cache@v4+ with:+ path: .turbo/cache+ key: turbo-v1-${{ github.job }}-${{ github.sha }}+ restore-keys: |+ turbo-v1-${{ github.job }}-+# Always install so the postinstall generates the gitignored font data.- run: pnpm install --frozen-lockfilediff --git a/.husky/pre-commit b/.husky/pre-commitindex bb7877f133..6a29d94ce9 100755--- a/.husky/pre-commit+++ b/.husky/pre-commit@@ -70,10 +70,11 @@ if [ -z "$CARBON_SKIP_BACKUP_CHECK" ] && git diff --cached --name-only | grep -qfi# The published operation contract lives in a GITIGNORED manifest, so its committed# digest is the only record a reviewer can see. Regenerate and refuse the commit if-# a service or validator change did not update it — a stale digest is worse than-# none, since it reads as "nothing changed".+# a change to anything the generator reads did not update it — a stale digest is+# worse than none, since it reads as "nothing changed". The file set is the+# //#generate:mcp inputs in turbo.json; keep the two in step.# Set CARBON_SKIP_MANIFEST_CHECK=1 to skip.-if [ -z "$CARBON_SKIP_MANIFEST_CHECK" ] && git diff --cached --name-only | grep -qE '^(apps/erp/app/modules/[^/]+/[^/]+\.(service|models|mcp\.server)\.ts|apps/erp/app/routes/api\+/mcp\+/lib/mcp-blocked-tools\.ts|scripts/(generate-mcp|lib/.*)\.ts)$'; then+if [ -z "$CARBON_SKIP_MANIFEST_CHECK" ] && git diff --cached --name-only | grep -qE '^(apps/erp/app/modules/.*\.ts|apps/erp/app/(types|utils)/.*|apps/erp/app/routes/api\+/mcp\+/lib/mcp-(blocked-tools|exposure)\.ts|packages/(api|database|documents|files|locale|logger|notifications|printing|utils)/src/.*|packages/database/supabase/functions/shared/.*|scripts/(generate-mcp|lib/.*)\.ts)$'; thenecho "Checking the API operation manifest digest..."if ! pnpm --silent check:manifest; thenecho ""diff --git a/AGENTS.md b/AGENTS.mdindex 480fc8ddf3..2b626d7993 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -53,6 +53,14 @@ pnpm db:check:datasets # Do the demo datasets still apply? (pre-commit gatpnpm db:check:backups # Would existing customer backups still restore? (pre-commit gate)```+`typecheck`, `test`, `lint` and `build` are cached by Turborepo: a package re-runs+only when its own files, a workspace dependency's files, or the lockfile changed+(`--force` re-runs regardless). That is only correct while a task reads nothing+outside that set. A package whose task reads other paths declares them in its own+`turbo.json` — as `inputs`, or `"cache": false` when it scans the repo+(`packages/checks`, `docs/content`) — and a package that needs a generated root+artifact depends on the task that makes it (`apps/erp/turbo.json`).+Both `db:check:*` commands read your live local schema. They run from`.husky/pre-commit`, so run `pnpm db:migrate` before either — a stale database makesthe dataset check fail for the wrong reason and makes the backup check refuse to givediff --git a/apps/academy/package.json b/apps/academy/package.jsonindex f440f1c303..3351eea8bd 100644--- a/apps/academy/package.json+++ b/apps/academy/package.json@@ -59,7 +59,7 @@"dev": "NODE_EXTRA_CA_CERTS=$HOME/.portless/ca.pem react-router dev","lint": "biome lint --write","start": "react-router-serve ./build/server/index.js",- "typecheck": "tsgo --noEmit",+ "typecheck": "react-router typegen && tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/erp/app/components/MapExtractedLinesModal.tsx b/apps/erp/app/components/MapExtractedLinesModal.tsxindex f8e0da157a..2890b710b0 100644--- a/apps/erp/app/components/MapExtractedLinesModal.tsx+++ b/apps/erp/app/components/MapExtractedLinesModal.tsx@@ -19,7 +19,8 @@ import {SelectContent,SelectItem,SelectTrigger,- SelectValue+ SelectValue,+ toast} from "@carbon/react";import { Trans } from "@lingui/react/macro";import type { ReactNode } from "react";@@ -117,6 +118,10 @@ export default function MapExtractedLinesModal({useEffect(() => {if (fetcher.data?.success) {onClose();+ } else if (fetcher.data?.success === false && fetcher.data.error) {+ // The endpoints answer `{ success: false, error }`; without this the+ // modal just sat there and the failure was invisible.+ toast.error(fetcher.data.error);}}, [fetcher.data, onClose]);diff --git a/apps/erp/app/modules/account/account.service.ts b/apps/erp/app/modules/account/account.service.tsindex ff44a53df1..b65bd7f960 100644--- a/apps/erp/app/modules/account/account.service.ts+++ b/apps/erp/app/modules/account/account.service.ts@@ -35,6 +35,7 @@ export async function getChangelogPanelEntry(};}+/** @mcp read */export async function getNotificationPreferences(client: SupabaseClient<Database>,userId: string,@@ -47,6 +48,7 @@ export async function getNotificationPreferences(.eq("companyId", companyId);}+/** @mcp upsert */export async function upsertNotificationPreference(client: SupabaseClient<Database>,preference: {@@ -66,6 +68,7 @@ export async function upsertNotificationPreference();}+/** @mcp delete */export async function deleteUserAttributeValue(client: SupabaseClient<Database>,args: {@@ -82,6 +85,7 @@ export async function deleteUserAttributeValue(.eq("userId", args.userId);}+/** @mcp read */export async function getAccount(client: SupabaseClient<Database>, id: string) {return client.from("user").select("*").eq("id", id).single();}@@ -91,6 +95,7 @@ export async function getAccount(client: SupabaseClient<Database>, id: string) {* executor from the OAuth token, so this always resolves to the caller — it is the identity source* an OS deployment can use for sign-in (a user who completed Carbon's OAuth has proven control of* this account, so its email is a verified sign-in identity).+ * @mcp read*/export async function getCurrentUser(client: SupabaseClient<Database>,@@ -103,6 +108,7 @@ export async function getCurrentUser(.single();}+/** @mcp read */export async function getAttributes(client: SupabaseClient<Database>,userId: string,@@ -128,6 +134,7 @@ export async function getAttributes(.order("sortOrder", { foreignTable: "userAttribute", ascending: true });}+/** @mcp read */export async function getPrivateAttributes(client: SupabaseClient<Database>,userId: string,@@ -136,6 +143,7 @@ export async function getPrivateAttributes(return getAttributes(client, userId, companyId, false);}+/** @mcp read */export async function getPublicAttributes(client: SupabaseClient<Database>,userId: string,@@ -144,6 +152,7 @@ export async function getPublicAttributes(return getAttributes(client, userId, companyId, true);}+/** @mcp read */export async function getAllAttributeCategories(client: SupabaseClient<Database>,userId: string,@@ -167,6 +176,7 @@ export async function getAllAttributeCategories(.order("sortOrder", { foreignTable: "userAttribute", ascending: true });}+/** @mcp read */export async function getAttributeCategoryWithValues(client: SupabaseClient<Database>,categoryId: string,@@ -193,6 +203,7 @@ export async function getAttributeCategoryWithValues(.single();}+/** @mcp update */export async function updateAvatar(client: SupabaseClient<Database>,userId: string,@@ -208,6 +219,7 @@ export async function updateAvatar(.eq("id", userId);}+/** @mcp update */export async function updatePublicAccount(client: SupabaseClient<Database>,account: {@@ -221,6 +233,7 @@ export async function updatePublicAccount(return client.from("user").update(sanitize(account)).eq("id", account.id);}+/** @mcp upsert */export async function upsertUserAttributeValue(client: SupabaseClient<Database>,update: {diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex 1098e38356..2643393176 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -145,6 +145,7 @@ function applyRootSignCorrection<});}+/** @mcp read */export async function getTrialBalance(client: SupabaseClient<Database>,companyGroupId: string,@@ -163,6 +164,7 @@ export async function getTrialBalance(});}+/** @mcp read */export async function getAccountLedger(client: SupabaseClient<Database>,args: {@@ -212,6 +214,7 @@ export async function getAccountLedger(};}+/** @mcp read */export async function getAccountLedgerSummary(client: SupabaseClient<Database>,companyGroupId: string,@@ -249,6 +252,7 @@ export async function getAccountLedgerSummary(};}+/** @mcp read */export async function getFinancialStatementBalances(client: SupabaseClient<Database>,companyGroupId: string,@@ -367,6 +371,7 @@ export async function getFinancialStatementBalances(};}+/** @mcp read */export async function getAccountPeriodSeries(client: SupabaseClient<Database>,companyGroupId: string,@@ -779,6 +784,7 @@ export async function translateCompanyPeriodSeries(* the accountTreeBalancePeriodSeries RPC (snapshot-based, single journal scan).* The multi-period sibling of getFinancialStatementBalances — same accounts* view, same Net Income injection (per bucket), same root sign correction.+ * @mcp read*/export async function getFinancialStatementPeriodSeries(client: SupabaseClient<Database>,@@ -967,6 +973,7 @@ export async function getFinancialStatementPeriodSeries(* getConsolidatedBalances: per-company series (including auto-resolved* elimination entities) summed per account and bucket, with per-bucket* currency translation and CTA.+ * @mcp read*/export async function getConsolidatedPeriodSeries(client: SupabaseClient<Database>,@@ -1232,6 +1239,7 @@ export async function getConsolidatedPeriodSeries(// Per-user pin overrides for the reports hub. Absent row = the report's// default pin state (the core financial statements default to pinned).+/** @mcp read */export async function getReportPins(client: SupabaseClient<Database>,userId: string,@@ -1244,6 +1252,7 @@ export async function getReportPins(.eq("companyId", companyId);}+/** @mcp upsert */export async function upsertReportPin(client: SupabaseClient<Database>,args: {@@ -1317,6 +1326,7 @@ function pivotAccountScopeParams(* the matching active, non-group accounts; the scrap scope resolves to the* scrapAccount ids the loader already fetched. Returns the raw supabase* response so callers keep the `{ data, error }` convention.+ * @mcp read*/export async function getAccountsInScope(client: SupabaseClient<Database>,@@ -1342,6 +1352,7 @@ export async function getAccountsInScope(return query.order("number", { ascending: true });}+/** @mcp read */export async function getDimensionPivot(client: SupabaseClient<Database>,args: {@@ -1509,6 +1520,7 @@ type DimensionPivotLineRow =* tag for that dimension) — so `rowValue1IsNull` maps to "send* p_row_dimension_1, omit p_row_value_1". A period column narrows postingDate* via p_column_period_start/end instead of a dimension match.+ * @mcp read*/export async function getDimensionPivotLines(client: SupabaseClient<Database>,@@ -1599,6 +1611,7 @@ const PURCHASE_FIELD_ENTITY_TYPE: Record<string, string> = {costCenter: "CostCenter"};+/** @mcp read */export async function getPurchaseLinePivot(client: SupabaseClient<Database>,args: {@@ -1717,6 +1730,7 @@ export async function getPurchaseLinePivot(type PurchaseLinePivotRow =Database["public"]["Functions"]["purchaseLinePivotLines"]["Returns"][number];+/** @mcp read */export async function getPurchaseLinePivotLines(client: SupabaseClient<Database>,args: {@@ -1809,6 +1823,7 @@ async function resolveDimensionValueNames(// Named, shareable saved pivot views for the analytics reports. RLS handles// visibility (Company rows are readable by every employee; Private rows only// by their creator; writes stay owner-only).+/** @mcp read */export async function getReportViews(client: SupabaseClient<Database>,args: { companyId: string; reportKey?: string }@@ -1825,6 +1840,7 @@ export async function getReportViews(return query.order("name", { ascending: true });}+/** @mcp upsert */export async function upsertReportView(client: SupabaseClient<Database>,view:@@ -1859,6 +1875,7 @@ export async function upsertReportView(return client.from("reportView").insert([view]).select("*").single();}+/** @mcp delete */export async function deleteReportView(client: SupabaseClient<Database>,id: string,@@ -1871,6 +1888,7 @@ export async function deleteReportView(.eq("companyId", companyId);}+/** @mcp read */export async function getCompaniesInGroup(client: SupabaseClient<Database>,companyGroupId: string@@ -1886,6 +1904,7 @@ export async function getCompaniesInGroup(.order("name", { ascending: true });}+/** @mcp delete */export async function deleteAccount(client: SupabaseClient<Database>,accountId: string@@ -1893,6 +1912,7 @@ export async function deleteAccount(return client.from("account").delete().eq("id", accountId);}+/** @mcp delete */export async function deletePaymentTerm(client: SupabaseClient<Database>,paymentTermId: string@@ -1903,6 +1923,7 @@ export async function deletePaymentTerm(.eq("id", paymentTermId);}+/** @mcp read */export async function getAccount(client: SupabaseClient<Database>,accountId: string@@ -1910,6 +1931,7 @@ export async function getAccount(return client.from("account").select("*").eq("id", accountId).single();}+/** @mcp read */export async function getAccounts(client: SupabaseClient<Database>,companyGroupId: string,@@ -1935,6 +1957,7 @@ export async function getAccounts(return query;}+/** @mcp read */export async function getAccountsList(client: SupabaseClient<Database>,companyGroupId: string,@@ -1966,6 +1989,7 @@ export async function getAccountsList(return query;}+/** @mcp read */export async function getGroupAccounts(client: SupabaseClient<Database>,companyGroupId: string@@ -1979,6 +2003,7 @@ export async function getGroupAccounts(.order("name", { ascending: true });}+/** @mcp read */export async function getBaseCurrency(client: SupabaseClient<Database>,companyId: string@@ -2005,6 +2030,7 @@ export async function getBaseCurrency(.single();}+/** @mcp read */export async function getChartOfAccounts(client: SupabaseClient<Database>,companyGroupId: string,@@ -2067,6 +2093,7 @@ export async function getChartOfAccounts(};}+/** @mcp read */export async function getCurrency(client: SupabaseClient<Database>,currencyId: string@@ -2082,6 +2109,7 @@ export async function getCurrency(* Settlement decimals for the company's base currency. Fixed-asset and GL* amounts are booked in base currency, so this is the scale their rounding must* use. Falls back to 2 only when the currency row is unreachable.+ * @mcp read*/export async function getBaseCurrencyDecimalPlaces(client: SupabaseClient<Database>,@@ -2106,6 +2134,7 @@ export async function getBaseCurrencyDecimalPlaces(return currency.data?.decimalPlaces ?? 2;}+/** @mcp read */export async function getCurrencyByCode(client: SupabaseClient<Database>,companyGroupId: string,@@ -2124,6 +2153,7 @@ export async function getCurrencyByCode(* THIS company's base currency, right now". Base currency resolves to 1 by* definition; a user override wins next; otherwise the ratio of the two* USD-anchored market rates. A missing rate is an ERROR — never 1.+ * @mcp read*/export async function getExchangeRate(client: SupabaseClient<Database>,@@ -2140,6 +2170,7 @@ export async function getExchangeRate(* Every active currency of the company's group, resolved for THIS company,* with provenance: 'base' | 'override' | 'market' | 'missing'. Backs the* exchange-rates settings page.+ * @mcp read*/export async function getExchangeRates(client: SupabaseClient<Database>,@@ -2150,6 +2181,7 @@ export async function getExchangeRates(});}+/** @mcp upsert */export async function upsertExchangeRateOverride(client: SupabaseClient<Database>,override: {@@ -2209,6 +2241,7 @@ export async function upsertExchangeRateOverride(return insert;}+/** @mcp delete */export async function deleteExchangeRateOverride(client: SupabaseClient<Database>,companyId: string,@@ -2221,6 +2254,7 @@ export async function deleteExchangeRateOverride(.eq("currencyCode", currencyCode);}+/** @mcp read */export async function getCurrencies(client: SupabaseClient<Database>,companyGroupId: string,@@ -2249,6 +2283,7 @@ export async function getCurrencies(* format or round money need the settlement scale alongside the code — the DB* column is authoritative over Intl/CLDR, so it has to travel with the option.* `decimalPlaces` is null for an ISO currency the group has not configured.+ * @mcp read*/export async function getCurrenciesList(client: SupabaseClient<Database>,@@ -2279,6 +2314,7 @@ export async function getCurrenciesList(};}+/** @mcp read */export async function getCurrentAccountingPeriod(client: SupabaseClient<Database>,companyId: string,@@ -2302,6 +2338,7 @@ type AccountingPeriodCloseColumns = {periodNumber?: number | null;};+/** @mcp action */export async function getOrCreateAccountingPeriod(client: SupabaseClient<Database>,companyId: string,@@ -2410,6 +2447,7 @@ type AccountingPeriodRow = {closedBy: string | null;};+/** @mcp read */export async function getAccountingPeriods(client: SupabaseClient<Database>,companyId: string@@ -2455,6 +2493,7 @@ async function getAccountingPeriodById(// referencing the period (journal.accountingPeriodId, FK ON DELETE RESTRICT)// means it has postings; Locked/Closed periods are structurally frozen.// periodCloseTask rows cascade on delete, so they never block.+/** @mcp read */export async function getAccountingPeriodDeletability(client: SupabaseClient<Database>,periodId: string,@@ -2497,6 +2536,7 @@ export async function getAccountingPeriodDeletability(};}+/** @mcp delete */export async function deleteAccountingPeriod(client: SupabaseClient<Database>,args: { periodId: string; companyId: string }@@ -2531,6 +2571,7 @@ export async function deleteAccountingPeriod(// retroactively rewrite already-reported fiscal years (and needs a short-year// bridge, not an edit), so the setting locks. Open, empty periods stay freely// changeable via delete + regenerate.+/** @mcp read */export async function getFiscalCalendarCommitted(client: SupabaseClient<Database>,companyId: string@@ -2555,6 +2596,7 @@ export async function getFiscalCalendarCommitted(};}+/** @mcp action */export async function lockAccountingPeriod(client: SupabaseClient<Database>,args: { periodId: string; companyId: string; userId: string }@@ -2590,6 +2632,7 @@ export async function lockAccountingPeriod(.single();}+/** @mcp action */export async function unlockAccountingPeriod(client: SupabaseClient<Database>,args: { periodId: string; companyId: string; userId: string }@@ -2775,6 +2818,7 @@ export async function closeAccountingPeriod(// checklist-aware close is exactly that call with the argument shape the route// action passes. Kept as a distinct named export so the route imports intent,// not the lower-level lifecycle primitive.+/** @mcp update */export async function closePeriodWithChecklist(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -2854,6 +2898,7 @@ export async function reopenAccountingPeriod(.single();}+/** @mcp create */export async function createFiscalYearPeriods(client: SupabaseClient<Database>,args: { companyId: string; fiscalYear: number; userId: string }@@ -2975,6 +3020,7 @@ const TERMINAL_SYNC_OPERATION_STATUSES = new Set([* journal (reversalOfId set) is delivered through the ORIGINAL journal's* "<id>:reversal" operation — the reversal row never gets its own ledger* entry (see getJournalSyncCompleteness).+ * @mcp read*/export async function getPeriodExternalGlSyncReadiness(client: SupabaseClient<Database>,@@ -3324,6 +3370,7 @@ async function computePeriodReadiness(return { checks, blockers, warnings };}+/** @mcp read */export async function getPeriodCloseReadiness(client: SupabaseClient<Database>,companyId: string,@@ -3494,8 +3541,12 @@ export function evaluateCloseChecklist(return { tasks: views, canClose, blockingReason, autoTaskStates };}-// Idempotently instantiate the checklist for a period from active definitions,-// then overlay live readiness. Returns the evaluated tasks plus the close gate.+/**+ * Idempotently instantiate the checklist for a period from active definitions,+ * then overlay live readiness. Returns the evaluated tasks plus the close gate.+ *+ * @mcp action+ */export async function getPeriodCloseChecklist(client: SupabaseClient<Database>,companyId: string,@@ -3606,6 +3657,7 @@ async function getPeriodCloseTaskById(}>;}+/** @mcp action */export async function completeCloseTask(client: SupabaseClient<Database>,args: { taskId: string; companyId: string; userId: string; notes?: string }@@ -3646,6 +3698,7 @@ export async function completeCloseTask(.single();}+/** @mcp action */export async function skipCloseTask(client: SupabaseClient<Database>,args: {@@ -3739,6 +3792,7 @@ export async function addCloseTask(.single();}+/** @mcp read */export async function getPeriodCloseTaskDefinitions(client: SupabaseClient<Database>,companyId: string@@ -3822,6 +3876,7 @@ export async function deletePeriodCloseTaskDefinition(.eq("companyId", args.companyId);}+/** @mcp read */export async function getDefaultAccounts(client: SupabaseClient<Database>,companyId: string@@ -3838,6 +3893,7 @@ export async function getDefaultAccounts(* report's account scope (accountScope.source === "scrapAccounts"). Empty* when no scrap account is configured — getDimensionPivot short-circuits to* an empty pivot in that case.+ * @mcp read*/export async function getScrapAccountIds(client: SupabaseClient<Database>,@@ -3857,6 +3913,7 @@ export async function getScrapAccountIds(};}+/** @mcp read */export async function getFiscalYearSettings(client: SupabaseClient<Database>,companyId: string@@ -3868,6 +3925,7 @@ export async function getFiscalYearSettings(.single();}+/** @mcp read */export async function getPaymentTerm(client: SupabaseClient<Database>,paymentTermId: string@@ -3879,6 +3937,7 @@ export async function getPaymentTerm(.single();}+/** @mcp read */export async function getPaymentTerms(client: SupabaseClient<Database>,companyId: string,@@ -3904,6 +3963,7 @@ export async function getPaymentTerms(return query;}+/** @mcp read */export async function getPaymentTermsList(client: SupabaseClient<Database>,companyId: string@@ -3916,7 +3976,10 @@ export async function getPaymentTermsList(.order("name", { ascending: true });}-/** Save both defaults sections atomically after validating the effective mapping. */+/**+ * Save both defaults sections atomically after validating the effective mapping.+ * @mcp update+ */export async function updateDefaultAccounts(client: SupabaseClient<Database>,defaultAccounts: z.infer<typeof defaultAccountValidator> & {@@ -3991,6 +4054,7 @@ export async function validateDefaultIncomeAccounts(return { error: null };}+/** @mcp update */export async function updateFiscalYearSettings(client: SupabaseClient<Database>,fiscalYearSettings: z.infer<typeof fiscalYearSettingsValidator> & {@@ -4004,6 +4068,7 @@ export async function updateFiscalYearSettings(.eq("companyId", fiscalYearSettings.companyId);}+/** @mcp upsert */export async function upsertAccount(client: SupabaseClient<Database>,account:@@ -4029,6 +4094,7 @@ export async function upsertAccount(.single();}+/** @mcp upsert */export async function upsertCurrency(client: SupabaseClient<Database>,currency:@@ -4055,6 +4121,7 @@ export async function upsertCurrency(.single();}+/** @mcp upsert */export async function upsertPaymentTerm(client: SupabaseClient<Database>,paymentTerm:@@ -4084,6 +4151,7 @@ export async function upsertPaymentTerm(.single();}+/** @mcp delete */export async function deleteCostCenter(client: SupabaseClient<Database>,costCenterId: string@@ -4091,6 +4159,7 @@ export async function deleteCostCenter(return client.from("costCenter").delete().eq("id", costCenterId);}+/** @mcp read */export async function getCostCenter(client: SupabaseClient<Database>,costCenterId: string@@ -4098,6 +4167,7 @@ export async function getCostCenter(return client.from("costCenter").select("*").eq("id", costCenterId).single();}+/** @mcp read */export async function getCostCenters(client: SupabaseClient<Database>,companyId: string,@@ -4121,6 +4191,7 @@ export async function getCostCenters(return query;}+/** @mcp read */export async function getCostCentersList(client: SupabaseClient<Database>,companyId: string@@ -4132,6 +4203,7 @@ export async function getCostCentersList(.order("name");}+/** @mcp read */export async function getCostCentersTree(client: SupabaseClient<Database>,companyId: string@@ -4145,6 +4217,7 @@ export async function getCostCentersTree(.order("name");}+/** @mcp upsert */export async function upsertCostCenter(client: SupabaseClient<Database>,costCenter:@@ -4170,6 +4243,7 @@ export async function upsertCostCenter(.single();}+/** @mcp delete */export async function deleteProject(client: SupabaseClient<Database>,companyId: string,@@ -4189,6 +4263,7 @@ export async function deleteProject(.single();}+/** @mcp read */export async function getProject(client: SupabaseClient<Database>,companyId: string,@@ -4202,6 +4277,7 @@ export async function getProject(.single();}+/** @mcp read */export async function getProjects(client: SupabaseClient<Database>,companyId: string,@@ -4226,6 +4302,7 @@ export async function getProjects(return query;}+/** @mcp upsert */export async function upsertProject(client: SupabaseClient<Database>,project:@@ -4257,6 +4334,7 @@ export async function upsertProject(.single();}+/** @mcp read */export async function getDimensions(client: SupabaseClient<Database>,companyGroupId: string,@@ -4282,6 +4360,7 @@ export async function getDimensions(return query;}+/** @mcp read */export async function getDimension(client: SupabaseClient<Database>,dimensionId: string@@ -4293,6 +4372,7 @@ export async function getDimension(.single();}+/** @mcp upsert destructive */export async function upsertDimension(client: SupabaseClient<Database>,dimension:@@ -4370,6 +4450,7 @@ export async function upsertDimension(return dimensionResult;}+/** @mcp delete */export async function deleteDimension(client: SupabaseClient<Database>,dimensionId: string@@ -4380,6 +4461,7 @@ export async function deleteDimension(.eq("id", dimensionId);}+/** @mcp read */export async function getActiveDimensionsWithValues(client: SupabaseClient<Database>,companyGroupId: string,@@ -4540,6 +4622,7 @@ function getEntityDimensionValues(}}+/** @mcp read */export async function getJournalLineDimensions(client: SupabaseClient<Database>,journalLineIds: string[]@@ -4674,6 +4757,7 @@ function getEntityValuesByIds(}}+/** @mcp action destructive */export async function saveJournalLineDimensions(client: SupabaseClient<Database>,journalLineId: string,@@ -4699,6 +4783,7 @@ export async function saveJournalLineDimensions();}+/** @mcp action */export async function translateCompanyBalances(client: SupabaseClient<Database>,companyGroupId: string,@@ -4905,6 +4990,7 @@ async function resolveConsolidationCompanyIds(return [...companyIds, ...eliminationIds];}+/** @mcp read */export async function getConsolidatedBalances(client: SupabaseClient<Database>,companyGroupId: string,@@ -5074,6 +5160,7 @@ export async function getConsolidatedBalances(// -- Intercompany --+/** @mcp read */export async function getIntercompanyTransactions(client: SupabaseClient<Database>,companyGroupId: string,@@ -5097,6 +5184,7 @@ export async function getIntercompanyTransactions(return query;}+/** @mcp create */export async function createIntercompanyTransaction(client: SupabaseClient<Database>,input: z.infer<typeof intercompanyTransactionValidator> & {@@ -5194,6 +5282,7 @@ export async function createIntercompanyTransaction(return intercompanyTransaction;}+/** @mcp read */export async function getIntercompanyEliminationLines(client: SupabaseClient<Database>,transactionIds: string[]@@ -5207,6 +5296,7 @@ export async function getIntercompanyEliminationLines(.in("intercompanyTransactionId", transactionIds);}+/** @mcp update */export async function runIntercompanyMatching(client: SupabaseClient<Database>,companyGroupId: string@@ -5216,6 +5306,7 @@ export async function runIntercompanyMatching(});}+/** @mcp create */export async function generateEliminations(client: SupabaseClient<Database>,companyGroupId: string,@@ -5229,6 +5320,7 @@ export async function generateEliminations(});}+/** @mcp read */export async function getIntercompanyBalance(client: SupabaseClient<Database>,companyGroupId: string@@ -5242,6 +5334,7 @@ export async function getIntercompanyBalance(* Market-rate history for the chart on the exchange-rates page. Reads the* platform-global "exchangeRate" store (USD-anchored), newest ~6 months of* daily rows, ascending for the chart.+ * @mcp read*/export async function getExchangeRateHistory(client: SupabaseClient<Database>,@@ -5265,6 +5358,7 @@ export async function getExchangeRateHistory(// Manual JEs start as Draft and are posted by flipping status to Posted.// amount > 0 = debit, amount < 0 = credit.+/** @mcp read */export async function getJournalEntries(client: SupabaseClient<Database>,companyId: string,@@ -5292,6 +5386,7 @@ export async function getJournalEntries(return query;}+/** @mcp read */export async function getJournalEntry(client: SupabaseClient<Database>,id: string@@ -5303,6 +5398,7 @@ export async function getJournalEntry(.single();}+/** @mcp create */export async function createJournalEntry(client: SupabaseClient<Database>,data: z.infer<typeof journalEntryValidator> & {@@ -5338,6 +5434,7 @@ export async function updateJournalEntry(.eq("status", "Draft");}+/** @mcp delete */export async function deleteJournalEntry(client: SupabaseClient<Database>,id: string@@ -5412,6 +5509,7 @@ export async function deleteJournalEntryLine(return client.from("journalLine").delete().eq("id", id);}+/** @mcp action destructive */export async function saveJournalEntryWithLines(client: SupabaseClient<Database>,data: {@@ -5523,6 +5621,7 @@ export async function saveJournalEntryWithLines(return insertResult;}+/** @mcp action */export async function postJournalEntry(client: SupabaseClient<Database>,id: string,@@ -5614,6 +5713,7 @@ export async function postJournalEntry(// entry, or null. Callers only need existence — this is the re-entry gate. Only// status='Posted' blocks a new set; a Reversed entry lets the user enter a fresh// one.+/** @mcp read */export async function getExistingOpeningBalanceEntry(client: SupabaseClient<Database>,companyId: string@@ -5638,6 +5738,7 @@ export async function getExistingOpeningBalanceEntry(// the Retained Earnings default account so debits equal credits. Reuses the// manual-JE stack: createJournalEntry (Draft) → saveJournalEntryWithLines →// postJournalEntry (which validates the balance and resolves the period).+/** @mcp create destructive */export async function createOpeningBalanceJournal(client: SupabaseClient<Database>,args: {@@ -5803,6 +5904,7 @@ export async function createOpeningBalanceJournal(return { data: { id }, error: null };}+/** @mcp action */export async function reverseJournalEntry(client: SupabaseClient<Database>,id: string,@@ -5911,6 +6013,7 @@ export async function reverseJournalEntry(// -- Asset Classes --+/** @mcp read */export async function getFixedAssetClasses(client: SupabaseClient<Database>,companyId: string,@@ -5934,6 +6037,7 @@ export async function getFixedAssetClasses(return query;}+/** @mcp read */export async function getFixedAssetClass(client: SupabaseClient<Database>,id: string@@ -5941,6 +6045,7 @@ export async function getFixedAssetClass(return client.from("fixedAssetClass").select("*").eq("id", id).single();}+/** @mcp read */export async function getFixedAssetClassesList(client: SupabaseClient<Database>,companyId: string@@ -5954,6 +6059,7 @@ export async function getFixedAssetClassesList(.order("name");}+/** @mcp upsert */export async function upsertFixedAssetClass(client: SupabaseClient<Database>,data:@@ -5976,6 +6082,7 @@ export async function upsertFixedAssetClass(.single();}+/** @mcp delete */export async function deleteFixedAssetClass(client: SupabaseClient<Database>,id: string@@ -5985,6 +6092,7 @@ export async function deleteFixedAssetClass(// -- Fixed Assets --+/** @mcp read */export async function getFixedAssets(client: SupabaseClient<Database>,companyId: string,@@ -6017,6 +6125,7 @@ export async function getFixedAssets(return query;}+/** @mcp read */export async function getFixedAsset(client: SupabaseClient<Database>,id: string@@ -6030,6 +6139,7 @@ export async function getFixedAsset(.single();}+/** @mcp read */export async function getFixedAssetsList(client: SupabaseClient<Database>,companyId: string@@ -6042,6 +6152,7 @@ export async function getFixedAssetsList(.order("fixedAssetId");}+/** @mcp read */export async function getFixedAssetsListForSale(client: SupabaseClient<Database>,companyId: string@@ -6054,6 +6165,7 @@ export async function getFixedAssetsListForSale(.order("fixedAssetId");}+/** @mcp create */export async function insertFixedAsset(client: SupabaseClient<Database>,input: {@@ -6137,6 +6249,7 @@ export async function insertFixedAsset(};}+/** @mcp update */export async function updateFixedAsset(client: SupabaseClient<Database>,input: {@@ -6201,6 +6314,7 @@ export async function upsertFixedAsset(.single();}+/** @mcp delete */export async function deleteFixedAsset(client: SupabaseClient<Database>,id: string@@ -6208,6 +6322,7 @@ export async function deleteFixedAsset(return client.from("fixedAsset").delete().eq("id", id).eq("status", "Draft");}+/** @mcp create destructive */export async function insertDepreciationRun(client: SupabaseClient<Database>,input: {@@ -6288,6 +6403,7 @@ export async function insertDepreciationRun(};}+/** @mcp delete */export async function deleteDepreciationRun(client: SupabaseClient<Database>,id: string@@ -6301,6 +6417,7 @@ export async function deleteDepreciationRun(// -- Depreciation --+/** @mcp read */export async function getDepreciationRuns(client: SupabaseClient<Database>,companyId: string,@@ -6323,6 +6440,7 @@ export async function getDepreciationRuns(return query;}+/** @mcp read */export async function getDepreciationRun(client: SupabaseClient<Database>,id: string@@ -6330,6 +6448,7 @@ export async function getDepreciationRun(return client.from("depreciationRun").select("*").eq("id", id).single();}+/** @mcp read */export async function getDepreciationRunLines(client: SupabaseClient<Database>,depreciationRunId: string@@ -6344,6 +6463,7 @@ export async function getDepreciationRunLines(// -- Depreciation History for a single asset --+/** @mcp read */export async function getAssetDepreciationHistory(client: SupabaseClient<Database>,fixedAssetId: string@@ -6359,6 +6479,7 @@ export async function getAssetDepreciationHistory(// -- Disposals --+/** @mcp read */export async function getFixedAssetDisposal(client: SupabaseClient<Database>,fixedAssetId: string@@ -6372,6 +6493,7 @@ export async function getFixedAssetDisposal(// -- Usage Logs --+/** @mcp read */export async function getFixedAssetUsageLogs(client: SupabaseClient<Database>,fixedAssetId: string@@ -6383,6 +6505,11 @@ export async function getFixedAssetUsageLogs(.order("periodEnd", { ascending: false });}+/**+ * A usage log is a ledger: an "edit" is a new offsetting row, never an in-place+ * change, so `updatedBy` must stay NULL even though the column exists. If this+ * is ever exposed, declare `@mcp audit createdBy` alongside its verb.+ */export async function upsertFixedAssetUsageLog(client: SupabaseClient<Database>,data: Record<string, any> & { companyId: string; createdBy: string }@@ -6432,6 +6559,7 @@ export type JournalSyncCompleteness = {* (this module deliberately does not import @carbon/ee/accounting — see the* TS2589 notes in the settings Integrations components) and passes* syncFromDate explicitly.+ * @mcp read*/export async function getJournalSyncCompleteness(client: SupabaseClient<Database>,@@ -6725,6 +6853,7 @@ async function joinTieOutCells(* The tie-out grid: every persisted cell for the company, joined with* account and period identity, newest period first. Optional filters narrow* to one integration and/or one accounting period.+ * @mcp read*/export async function getAccountingSyncTieOut(client: SupabaseClient<Database>,@@ -6811,6 +6940,7 @@ const TIE_OUT_CELL_JOURNAL_LIMIT = 200;* integration. A reversal journal's disposition lives under the original* journal's "<id>:reversal" entity id (see getJournalSyncCompleteness).* Bounded to the newest TIE_OUT_CELL_JOURNAL_LIMIT journals.+ * @mcp read*/export async function getAccountingSyncTieOutCell(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.tsindex ea08bdbb4d..14035b6006 100644--- a/apps/erp/app/modules/documents/documents.service.ts+++ b/apps/erp/app/modules/documents/documents.service.ts@@ -23,6 +23,7 @@ import {parseStagedUploadPath} from "./documents.models";+/** @mcp delete */export async function deleteDocument(client: SupabaseClient<Database>,id: string@@ -54,6 +55,7 @@ export async function deleteDocumentLabel(.eq("label", label);}+/** @mcp read */export async function getDocument(client: SupabaseClient<Database>,documentId: string@@ -61,6 +63,7 @@ export async function getDocument(return client.from("documents").select("*").eq("id", documentId).single();}+/** @mcp read */export async function getDocuments(client: SupabaseClient<Database>,companyId: string,@@ -101,10 +104,12 @@ export async function getDocuments(return query;}+/** @mcp read */export async function getDocumentExtensions(client: SupabaseClient<Database>) {return client.from("documentExtensions").select("extension");}+/** @mcp read */export async function getDocumentLabels(client: SupabaseClient<Database>,userId: string@@ -132,6 +137,7 @@ export async function insertDocumentLabel(.insert({ documentId: id, label, companyId, userId });}+/** @mcp update */export async function moveDocumentToTrash(client: SupabaseClient<Database>,id: string,@@ -147,6 +153,7 @@ export async function moveDocumentToTrash(.eq("id", id);}+/** @mcp action */export async function restoreDocument(client: SupabaseClient<Database>,id: string,@@ -167,6 +174,7 @@ type SourceDocumentData = {sourceDocumentId?: string;};+/** @mcp upsert */export async function upsertDocument(client: SupabaseClient<Database>,document:@@ -220,6 +228,9 @@ export async function upsertDocument(* bytes to JPEG at the real path. The caller's flow is unchanged: PUT to the* signed URL, register the returned `path`, receive a `.jpg` document row.* Abandoned staged uploads are swept nightly.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createDocumentUploadUrl(client: SupabaseClient<Database>,@@ -246,6 +257,9 @@ export async function createDocumentUploadUrl(* `document.size` column and the browser upload hooks. A path minted for a* HEIC name is a staged upload: the bytes are converted to JPEG and moved to* the real document path here, so the registered row is never HEIC.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function insertUploadedDocument(client: SupabaseClient<Database>,@@ -328,6 +342,7 @@ export async function insertUploadedDocument(});}+/** @mcp update destructive */export async function updateDocumentFavorite(client: SupabaseClient<Database>,args: {@@ -350,6 +365,7 @@ export async function updateDocumentFavorite(}}+/** @mcp update destructive */export async function updateDocumentLabels(client: SupabaseClient<Database>,document: z.infer<typeof documentLabelsValidator> & {@@ -377,6 +393,7 @@ export async function updateDocumentLabels(});}+/** @mcp create */export async function insertDocumentExtraction(client: SupabaseClient<Database>,data: {diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex c0cf05514a..1aad8ee762 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -58,6 +58,7 @@ import {splitConsumeFirstPick} from "./supersession-pick";+/** @mcp delete */export async function deleteBatchProperty(client: SupabaseClient<Database>,id: string@@ -65,6 +66,7 @@ export async function deleteBatchProperty(return client.from("batchProperty").delete().eq("id", id);}+/** @mcp delete */export async function deleteKanban(client: SupabaseClient<Database>,kanbanId: string@@ -72,6 +74,7 @@ export async function deleteKanban(return client.from("kanban").delete().eq("id", kanbanId);}+/** @mcp delete */export async function deleteReceipt(client: SupabaseClient<Database>,receiptId: string@@ -79,6 +82,7 @@ export async function deleteReceipt(return client.from("receipt").delete().eq("id", receiptId);}+/** @mcp delete */export async function deleteReceiptLine(client: SupabaseClient<Database>,receiptLineId: string@@ -86,6 +90,7 @@ export async function deleteReceiptLine(return client.from("receiptLine").delete().eq("id", receiptLineId);}+/** @mcp delete */export async function deleteStorageUnit(client: SupabaseClient<Database>,storageUnitId: string@@ -104,6 +109,7 @@ export async function deleteStorageUnit(** We fetch the subtree via `storageUnits_recursive` (which already returns* self + descendants thanks to `ancestorPath @> ARRAY[id]`).+ * @mcp delete*/export async function deleteStorageUnitCascade(client: SupabaseClient<Database>,@@ -127,6 +133,7 @@ export async function deleteStorageUnitCascade(return client.from("storageUnit").delete().in("id", ids);}+/** @mcp delete */export async function deleteShipment(client: SupabaseClient<Database>,shipmentId: string@@ -134,6 +141,7 @@ export async function deleteShipment(return client.from("shipment").delete().eq("id", shipmentId);}+/** @mcp delete */export async function deleteShipmentLine(client: SupabaseClient<Database>,shipmentLineId: string@@ -141,6 +149,7 @@ export async function deleteShipmentLine(return client.from("shipmentLine").delete().eq("id", shipmentLineId);}+/** @mcp delete */export async function deleteShippingMethod(client: SupabaseClient<Database>,shippingMethodId: string@@ -151,6 +160,7 @@ export async function deleteShippingMethod(.eq("id", shippingMethodId);}+/** @mcp delete */export async function deleteStockTransfer(client: SupabaseClient<Database>,stockTransferId: string@@ -158,6 +168,7 @@ export async function deleteStockTransfer(return client.from("stockTransfer").delete().eq("id", stockTransferId);}+/** @mcp delete */export async function deleteStockTransferLine(client: SupabaseClient<Database>,stockTransferLineId: string@@ -168,6 +179,7 @@ export async function deleteStockTransferLine(.eq("id", stockTransferLineId);}+/** @mcp delete */export async function deleteWarehouseTransfer(client: SupabaseClient<Database>,transferId: string@@ -175,6 +187,7 @@ export async function deleteWarehouseTransfer(return client.from("warehouseTransfer").delete().eq("id", transferId);}+/** @mcp delete */export async function deleteWarehouseTransferLine(client: SupabaseClient<Database>,transferLineId: string@@ -182,6 +195,7 @@ export async function deleteWarehouseTransferLine(return client.from("warehouseTransferLine").delete().eq("id", transferLineId);}+/** @mcp read */export async function getItemLedgerPage(client: SupabaseClient<Database>,itemId: string,@@ -230,6 +244,7 @@ export async function getItemLedgerPage(** Returns rows newest→oldest regardless of direction. No `count` — `hasMore` is* inferred from a full page, so there's no whole-table count per request.+ * @mcp read*/export async function getItemLedgerActivity(client: SupabaseClient<Database>,@@ -279,6 +294,7 @@ export async function getItemLedgerActivity(return { data: rows, hasMore: (data?.length ?? 0) === pageSize, error };}+/** @mcp read */export async function getBatchProperties(client: SupabaseClient<Database>,itemIds: string[],@@ -292,6 +308,7 @@ export async function getBatchProperties(.order("sortOrder");}+/** @mcp read */export async function getInventoryItems(client: SupabaseClient<Database>,locationId: string,@@ -323,6 +340,7 @@ export async function getInventoryItems(return query;}+/** @mcp read */export async function getInventoryItemsCount(client: SupabaseClient<Database>,locationId: string,@@ -349,6 +367,7 @@ export async function getInventoryItemsCount(return query;}+/** @mcp read */export async function getInventoryValuation(client: SupabaseClient<Database>,companyId: string,@@ -361,6 +380,7 @@ export async function getInventoryValuation(});}+/** @mcp read */export async function getInventoryValuationTieOut(client: SupabaseClient<Database>,companyId: string,@@ -382,6 +402,7 @@ export async function getInventoryValuationTieOut(// Posted on the tie-out's as-of date — the tie-out only counts journals with// postingDate <= asOfDate, so a today-dated journal could never resolve a// backdated variance. Posting may still be rejected if that period is Closed.+/** @mcp create */export async function createInventoryReconciliationJournal(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -476,6 +497,7 @@ export async function createInventoryReconciliationJournal(}}+/** @mcp read */export async function getKanbans(client: SupabaseClient<Database>,locationId: string,@@ -504,6 +526,7 @@ export async function getKanbans(return query;}+/** @mcp read */export async function getKanban(client: SupabaseClient<Database>,kanbanId: string,@@ -519,6 +542,7 @@ export async function getKanban(.single();}+/** @mcp read */export async function getStockTransfer(client: SupabaseClient<Database>,stockTransferId: string@@ -530,6 +554,7 @@ export async function getStockTransfer(.single();}+/** @mcp read */export async function getStockTransferLine(client: SupabaseClient<Database>,stockTransferLineId: string@@ -541,6 +566,7 @@ export async function getStockTransferLine(.single();}+/** @mcp read */export async function getStockTransferLines(client: SupabaseClient<Database>,stockTransferId: string@@ -553,6 +579,7 @@ export async function getStockTransferLines(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getStockTransferTracking(client: SupabaseClient<Database>,stockTransferId: string,@@ -566,6 +593,7 @@ export async function getStockTransferTracking(.eq("companyId", companyId);}+/** @mcp read */export async function getStockTransfers(client: SupabaseClient<Database>,companyId: string,@@ -595,6 +623,7 @@ export async function getStockTransfers(return query;}+/** @mcp read */export async function getDefaultStorageUnitOrStorageUnitWithHighestQuantity(client: SupabaseClient<Database>,itemId: string,@@ -631,6 +660,7 @@ export async function getDefaultStorageUnitOrStorageUnitWithHighestQuantity(return storageUnitWithHighestQuantity?.storageUnitId ?? null;}+/** @mcp read */export async function getReceipts(client: SupabaseClient<Database>,companyId: string,@@ -658,6 +688,7 @@ export async function getReceipts(return query;}+/** @mcp read */export async function getReceipt(client: SupabaseClient<Database>,receiptId: string@@ -665,6 +696,7 @@ export async function getReceipt(return client.from("receipt").select("*").eq("id", receiptId).single();}+/** @mcp read */export async function getReceiptLines(client: SupabaseClient<Database>,receiptId: string@@ -672,6 +704,7 @@ export async function getReceiptLines(return client.from("receiptLines").select("*").eq("receiptId", receiptId);}+/** @mcp read */export async function getReceiptTracking(client: SupabaseClient<Database>,receiptId: string,@@ -684,6 +717,7 @@ export async function getReceiptTracking(.eq("companyId", companyId);}+/** @mcp read */export async function getReceiptLineTracking(client: SupabaseClient<Database>,receiptLineId: string,@@ -703,6 +737,7 @@ export async function getReceiptLineTracking(* (edited serial) entities would otherwise become phantom Available serials.* The keep/delete decision is owned by `reconcileReceiptLineSerials` so it* stays in lockstep with the post-time validation in ReceiptPostModal.+ * @mcp action destructive*/export async function reconcileReceiptSerialEntities(client: SupabaseClient<Database>,@@ -755,6 +790,7 @@ export async function reconcileReceiptSerialEntities(}}+/** @mcp read */export async function getReceiptFiles(client: SupabaseClient<Database>,companyId: string,@@ -789,6 +825,7 @@ export async function getReceiptFiles(};}+/** @mcp read */export async function getSerialNumbersForItem(client: SupabaseClient<Database>,args: {@@ -819,6 +856,7 @@ export async function getSerialNumbersForItem(* warehouse). `excludeAllocated` nets out quantities already allocated to other* non-cancelled picking lines so the same lot is never recommended twice;* `excludeLineId` keeps the current line's own allocation visible.+ * @mcp read*/export async function getAvailableTrackedEntities(client: SupabaseClient<Database>,@@ -844,6 +882,7 @@ export async function getAvailableTrackedEntities(/*** The configured tracked-entity pick order for an item at a location, used as* the picker's default sort. Falls back to "Default" (smart) when unset.+ * @mcp read*/export async function getPickOrder(client: SupabaseClient<Database>,@@ -859,6 +898,7 @@ export async function getPickOrder(return data?.sortMethod ?? "Default";}+/** @mcp read */export async function getBatchNumbersForItem(client: SupabaseClient<Database>,args: {@@ -878,6 +918,7 @@ export async function getBatchNumbersForItem(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getStorageUnitsList(client: SupabaseClient<Database>,companyId: string@@ -890,6 +931,7 @@ export async function getStorageUnitsList();}+/** @mcp read */export async function getStorageUnitsListForLocation(client: SupabaseClient<Database>,companyId: string,@@ -910,6 +952,7 @@ export async function getStorageUnitsListForLocation(// Tree shape from storageUnits_recursive view: each row has its 1-based depth// and the full ancestorPath (root → node ids). Sort by ancestorPath so the// caller can render a flat list that visually nests by depth.+/** @mcp read */export async function getStorageUnitsTreeForLocation(client: SupabaseClient<Database>,companyId: string,@@ -933,6 +976,7 @@ export async function getStorageUnitsTreeForLocation();}+/** @mcp read */export async function getStorageUnits(client: SupabaseClient<Database>,locationId: string,@@ -962,6 +1006,7 @@ export async function getStorageUnits(return query;}+/** @mcp read */export async function getStorageUnit(client: SupabaseClient<Database>,storageUnitId: string@@ -973,6 +1018,7 @@ export async function getStorageUnit(.single();}+/** @mcp read */export async function getEffectiveWorkCenterId(client: SupabaseClient<Database>,storageUnitId: string@@ -984,6 +1030,7 @@ export async function getEffectiveWorkCenterId(// Roots only (depth = 1). Honors search/filter/pagination so the table can// paginate top-level storage units while children load lazily on demand.+/** @mcp read */export async function getStorageUnitRoots(client: SupabaseClient<Database>,companyId: string,@@ -1010,6 +1057,7 @@ export async function getStorageUnitRoots(// Immediate children of a single parent (one level deep). Used by the lazy// expand handler in the StorageUnits table.+/** @mcp read */export async function getStorageUnitChildren(client: SupabaseClient<Database>,parentId: string@@ -1027,6 +1075,7 @@ export async function getStorageUnitChildren(// subtrees in one round trip. Used to render the tree expanded by default;// the depth cap keeps very deep trees from loading their entire subtree// eagerly — anything below `maxDepth` still lazy-loads on demand.+/** @mcp read */export async function getStorageUnitSubtrees(client: SupabaseClient<Database>,companyId: string,@@ -1050,6 +1099,7 @@ export async function getStorageUnitSubtrees(// Set of storageUnit ids that have at least one child in the given location.// Drives whether the table renders an expand chevron on a row.+/** @mcp read */export async function getStorageUnitParentIdsWithChildren(client: SupabaseClient<Database>,companyId: string,@@ -1075,6 +1125,7 @@ export async function getStorageUnitParentIdsWithChildren(// every ancestor of each match, so the tree path renders intact. Returns the// flat ordered row set + the parentIds that should be pre-expanded so that// matches are visible to the user.+/** @mcp read */export async function searchStorageUnitsWithAncestors(client: SupabaseClient<Database>,companyId: string,@@ -1125,6 +1176,7 @@ export async function searchStorageUnitsWithAncestors(};}+/** @mcp read */export async function getStockMovements(client: SupabaseClient<Database>,companyId: string,@@ -1156,6 +1208,7 @@ export async function getStockMovements(return query;}+/** @mcp read */export async function getShipments(client: SupabaseClient<Database>,companyId: string,@@ -1183,6 +1236,7 @@ export async function getShipments(return query;}+/** @mcp read */export async function getShipment(client: SupabaseClient<Database>,shipmentId: string@@ -1190,6 +1244,7 @@ export async function getShipment(return client.from("shipment").select("*").eq("id", shipmentId).single();}+/** @mcp read */export async function getShipmentLines(client: SupabaseClient<Database>,shipmentId: string@@ -1200,6 +1255,7 @@ export async function getShipmentLines(.eq("shipmentId", shipmentId);}+/** @mcp read */export async function getShipmentLinesWithDetails(client: SupabaseClient<Database>,shipmentId: string@@ -1207,6 +1263,7 @@ export async function getShipmentLinesWithDetails(return client.from("shipmentLines").select("*").eq("shipmentId", shipmentId);}+/** @mcp read */export async function getShipmentFiles(client: SupabaseClient<Database>,companyId: string,@@ -1241,6 +1298,7 @@ export async function getShipmentFiles(};}+/** @mcp read */export async function getShipmentRelatedItems(client: SupabaseClient<Database>,shipmentId: string,@@ -1266,6 +1324,7 @@ export async function getShipmentRelatedItems(};}+/** @mcp read */export async function getShipmentTracking(client: SupabaseClient<Database>,shipmentId: string,@@ -1278,6 +1337,7 @@ export async function getShipmentTracking(.eq("companyId", companyId);}+/** @mcp read */export async function getShipmentLineTracking(client: SupabaseClient<Database>,shipmentLineId: string,@@ -1290,6 +1350,7 @@ export async function getShipmentLineTracking(.eq("companyId", companyId);}+/** @mcp read */export async function getShippingMethod(client: SupabaseClient<Database>,shippingMethodId: string@@ -1301,6 +1362,7 @@ export async function getShippingMethod(.single();}+/** @mcp read */export async function getShippingMethods(client: SupabaseClient<Database>,companyId: string,@@ -1328,6 +1390,7 @@ export async function getShippingMethods(return query;}+/** @mcp read */export async function getShippingMethodsList(client: SupabaseClient<Database>,companyId: string@@ -1340,6 +1403,7 @@ export async function getShippingMethodsList(.order("name", { ascending: true });}+/** @mcp read */export async function getShippingTermsList(client: SupabaseClient<Database>,companyId: string@@ -1355,6 +1419,7 @@ export async function getShippingTermsList(// Merge >=2 same-item Available lots into ONE new entity (fresh id, summed// quantity, earliest expiry) with genealogy back to every parent. The issue// edge fn owns the writes; see shared/batch-merge.ts.+/** @mcp action */export async function mergeTrackedEntities(client: SupabaseClient<Database>,args: {@@ -1376,6 +1441,7 @@ export async function mergeTrackedEntities(});}+/** @mcp read */export async function getTrackedEntities(client: SupabaseClient<Database>,companyId: string,@@ -1403,19 +1469,28 @@ export async function getTrackedEntities(return query;}+/** @mcp read */export async function getTrackedEntitiesByMakeMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string,companyId: string) {+ // Unit-axis order: position here is the `index` step records are stored+ // under, so it must be a pure function of immutable columns. `createdAt`+ // alone ties for bulk-minted serials and Postgres breaks the tie by physical+ // row order, which any UPDATE changes. Full reasoning on the MES copy+ // (`apps/mes/app/services/operations.service.ts`); keep the two identical.return client.from("trackedEntity").select("*").eq("attributes->>Job Make Method", jobMakeMethodId).eq("companyId", companyId)- .order("createdAt", { ascending: true });+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });}+/** @mcp read */export async function getTrackedEntity(client: SupabaseClient<Database>,trackedEntityId: string@@ -1443,6 +1518,7 @@ export async function getTrackedEntity(* },* ...* ]+ * @mcp update*/export async function updateTrackedEntityExpiry(client: SupabaseClient<Database>,@@ -1500,6 +1576,7 @@ export async function updateTrackedEntityExpiry(.eq("id", args.trackedEntityId);}+/** @mcp read */export async function getTrackedEntitiesByOperationId(client: SupabaseClient<Database>,operationId: string,@@ -1525,6 +1602,7 @@ export async function getTrackedEntitiesByOperationId();}+/** @mcp read */export async function getWarehouseTransfers(client: SupabaseClient<Database>,companyId: string,@@ -1554,6 +1632,7 @@ export async function getWarehouseTransfers(return query;}+/** @mcp read */export async function getWarehouseTransfer(client: SupabaseClient<Database>,transferId: string@@ -1567,6 +1646,7 @@ export async function getWarehouseTransfer(.single();}+/** @mcp read */export async function getWarehouseTransferLine(client: SupabaseClient<Database>,transferId: string,@@ -1582,6 +1662,7 @@ export async function getWarehouseTransferLine(.single();}+/** @mcp read */export async function getWarehouseTransferLines(client: SupabaseClient<Database>,transferId: string@@ -1599,6 +1680,10 @@ export async function getWarehouseTransferLines(// Set Quantity resolution, storage-unit transfers, serial/batch stock-target// resolution, tracked-entity updates, cost layers, and GL posting (only when// companySettings.accountingEnabled) in one transaction.+/**+ * @mcp create+ * @mcp audit createdBy+ */export async function insertManualInventoryAdjustment(client: SupabaseClient<Database>,// `requiresSerialTracking` is a form-only flag for the validator's serial@@ -1641,6 +1726,7 @@ export async function insertManualInventoryAdjustment(// fix→fix). Mirrors the walk inside the correct-stock-movement edge function;// the modal pre-fills from this so the user never submits a value derived from// an incomplete page of movements.+/** @mcp read */export async function getStockMovementEffectiveQuantity(client: SupabaseClient<Database>,companyId: string,@@ -1695,6 +1781,7 @@ export async function getStockMovementEffectiveQuantity(// opposite (delta) movement linked to the corrected movement via// correctionOfItemLedgerId, dated with the original's postingDate and posted// into the original's accounting period.+/** @mcp action */export async function correctStockMovement(client: SupabaseClient<Database>,correction: z.infer<typeof stockMovementCorrectionValidator> & {@@ -1729,6 +1816,7 @@ export async function correctStockMovement(// Inventory Count / Cycle Count// ===========================================================================+/** @mcp read */export async function getInventoryCounts(client: SupabaseClient<Database>,companyId: string,@@ -1749,6 +1837,7 @@ export async function getInventoryCounts(return query;}+/** @mcp read */export async function getInventoryCount(client: SupabaseClient<Database>,id: string,@@ -1762,6 +1851,7 @@ export async function getInventoryCount(.single();}+/** @mcp read */export async function getInventoryCountLines(client: SupabaseClient<Database>,inventoryCountId: string,@@ -1800,6 +1890,7 @@ export async function getInventoryCountLines(// Aggregate counts for the confirm dialog. Computed server-side so the warnings// stay accurate regardless of which page of lines is currently loaded.+/** @mcp read */export async function getInventoryCountLineSummary(client: SupabaseClient<Database>,inventoryCountId: string,@@ -1827,6 +1918,7 @@ export async function getInventoryCountLineSummary(// corrections, which copy the count's documentType/documentId), found via the// movement's `documentType`/`documentId` back-reference. Used to show a posted// count what it actually did to inventory. Chronological.+/** @mcp read */export async function getInventoryCountMovements(client: SupabaseClient<Database>,companyId: string,@@ -1844,6 +1936,7 @@ export async function getInventoryCountMovements(// Counts are created once and never edited as a header (only their lines and// status change), so this is insert-only — no upsert/update branch.+/** @mcp create */export async function insertInventoryCount(client: SupabaseClient<Database>,inventoryCount: {@@ -1864,6 +1957,7 @@ export async function insertInventoryCount(.single();}+/** @mcp delete */export async function deleteInventoryCount(client: SupabaseClient<Database>,id: string,@@ -1882,6 +1976,7 @@ export async function deleteInventoryCount(// empty bins and correct discrepancies. On-hand is summed from `itemLedger`// (status-aware: excludes Rejected, matching `get_inventory_quantities`).// Idempotent: safe to re-run to re-snapshot while the count is Draft.+/** @mcp create destructive */export async function generateInventoryCountLines(db: Kysely<KyselyDatabase>,args: {@@ -2015,6 +2110,7 @@ export async function generateInventoryCountLines(// read-then-update would leave open (a concurrent Confirm can't slip in between).// Returns the updated row id, or undefined when the line doesn't exist or the// count is no longer Draft. Kysely bypasses RLS — authorize at the route first.+/** @mcp update */export async function updateInventoryCountLine(db: Kysely<KyselyDatabase>,args: z.infer<typeof inventoryCountLineValidator> & {@@ -2058,6 +2154,7 @@ export async function updateInventoryCountLine(.executeTakeFirst();}+/** @mcp update */export async function updateInventoryCountStatus(client: SupabaseClient<Database>,args: {@@ -2082,6 +2179,7 @@ export async function updateInventoryCountStatus(return query.select("id").single();}+/** @mcp update */export async function updateBatchPropertyOrder(client: SupabaseClient<Database>,data: Omit<@@ -2095,6 +2193,7 @@ export async function updateBatchPropertyOrder(return client.from("batchProperty").update(sanitize(data)).eq("id", data.id);}+/** @mcp update */export async function updateStockTransferStatus(client: SupabaseClient<Database>,args: {@@ -2117,6 +2216,7 @@ export async function updateStockTransferStatus(.eq("id", id);}+/** @mcp upsert */export async function upsertBatchProperty(client: SupabaseClient<Database>,batchProperty: z.infer<typeof batchPropertyValidator> & {@@ -2144,6 +2244,7 @@ export async function upsertBatchProperty(});}+/** @mcp upsert */export async function upsertKanban(client: SupabaseClient<Database>,kanban:@@ -2178,6 +2279,7 @@ export async function upsertKanban(.single();}+/** @mcp upsert */export async function upsertReceipt(client: SupabaseClient<Database>,receipt:@@ -2208,6 +2310,7 @@ export async function upsertReceipt(.single();}+/** @mcp upsert */export async function upsertStorageUnit(client: SupabaseClient<Database>,storageUnit:@@ -2243,6 +2346,7 @@ export async function upsertStorageUnit(.single();}+/** @mcp upsert */export async function upsertShippingMethod(client: SupabaseClient<Database>,shippingMethod:@@ -2272,6 +2376,7 @@ export async function upsertShippingMethod(.single();}+/** @mcp upsert */export async function upsertShipment(client: SupabaseClient<Database>,shipment:@@ -2339,6 +2444,7 @@ export async function upsertStockTransfer(.single();}+/** @mcp upsert */export async function upsertStockTransferLine(client: SupabaseClient<Database>,stockTransferLine:@@ -2420,6 +2526,7 @@ export async function upsertWarehouseTransfer(.single();}+/** @mcp update */export async function updateWarehouseTransferStatus(client: SupabaseClient<Database>,transferId: string,@@ -2436,6 +2543,7 @@ export async function updateWarehouseTransferStatus(.eq("id", transferId);}+/** @mcp upsert */export async function upsertWarehouseTransferLine(client: SupabaseClient<Database>,line:@@ -2467,6 +2575,7 @@ export async function upsertWarehouseTransferLine(}}+/** @mcp read */export async function getDefaultStorageUnitForJob(client: SupabaseClient<Database>,itemId: string,@@ -2510,6 +2619,7 @@ export async function getDefaultStorageUnitForJob(// defined in 20260417000200_storage-unit-nesting-and-type.sql)// ----------------------------------------------------------------------------+/** @mcp read */export async function getStorageUnitTree(client: SupabaseClient<Database>,companyId: string,@@ -2525,6 +2635,7 @@ export async function getStorageUnitTree(.order("ancestorPath");}+/** @mcp read */export async function getStorageUnitDescendants(client: SupabaseClient<Database>,storageUnitId: string@@ -2537,6 +2648,7 @@ export async function getStorageUnitDescendants(.contains("ancestorPath", [storageUnitId]);}+/** @mcp action */export async function expandStorageUnitIdsWithDescendants(client: SupabaseClient<Database>,storageUnitIds: string[]@@ -2557,6 +2669,7 @@ export async function expandStorageUnitIdsWithDescendants(// storageType CRUD (mirrors materialType in items.service.ts)// ----------------------------------------------------------------------------+/** @mcp read */export async function getStorageTypeUsage(client: SupabaseClient<Database>,id: string,@@ -2570,6 +2683,7 @@ export async function getStorageTypeUsage(.limit(5);}+/** @mcp delete */export async function deleteStorageTypeWithCascade(client: SupabaseClient<Database>,id: string,@@ -2595,6 +2709,7 @@ export async function deleteStorageTypeWithCascade(return client.from("storageType").delete().eq("id", id);}+/** @mcp read */export async function getStorageTypes(client: SupabaseClient<Database>,companyId: string,@@ -2615,6 +2730,7 @@ export async function getStorageTypes(return query;}+/** @mcp read */export async function getStorageType(client: SupabaseClient<Database>,id: string@@ -2622,6 +2738,7 @@ export async function getStorageType(return client.from("storageType").select("*").eq("id", id).single();}+/** @mcp read */export async function getStorageTypesList(client: SupabaseClient<Database>,companyId: string@@ -2634,6 +2751,7 @@ export async function getStorageTypesList();}+/** @mcp upsert */export async function upsertStorageType(client: SupabaseClient<Database>,storageType:@@ -2666,6 +2784,7 @@ export async function upsertStorageType(.single();}+/** @mcp read */export async function getShelfLifeForItems(client: SupabaseClient<Database>,itemIds: string[]@@ -2681,6 +2800,7 @@ export async function getShelfLifeForItems(* Map of trackedEntityId → expirationDate (or null) for a set of ids.* Used by the inventory adjustment modal to prefill the date picker when* editing an existing batch / serial.+ * @mcp read*/export async function getTrackedEntityExpirations(client: SupabaseClient<Database>,@@ -2704,6 +2824,7 @@ export async function getTrackedEntityExpirations(// Picking List CRUD// ----------------------------------------------------------------------------+/** @mcp read */export async function getPickingLists(client: SupabaseClient<Database>,companyId: string,@@ -2746,6 +2867,7 @@ export async function getPickingLists(return query;}+/** @mcp read */export async function getPickingList(client: SupabaseClient<Database>,pickingListId: string@@ -2759,6 +2881,7 @@ export async function getPickingList(.single();}+/** @mcp read */export async function getPicksByJobMaterial(client: SupabaseClient<Database>,jobId: string,@@ -2813,6 +2936,7 @@ export type JobMaterialPick = {pickingListStatus: string;};+/** @mcp read */export async function getPickingListLines(client: SupabaseClient<Database>,pickingListId: string@@ -2831,6 +2955,7 @@ export async function getPickingListLines(* Per-line WAREHOUSE (non-lineside, incl. the unassigned/null bin) on-hand for* a picking list's items — drives the "No Stock" warning. Returns a map of* pickingListLineId → availableQuantity.+ * @mcp read*/export async function getPickingListAvailability(client: SupabaseClient<Database>,@@ -2863,6 +2988,7 @@ export type PickingListRecommendation = {* greedily assign distinct lots to lines in pick order so the same serial is never* recommended to two lines, and a batch lot is split across lines by remaining qty.* Returns a map of pickingListLineId → recommended lots (empty/partial if short).+ * @mcp read*/export async function getPickingListRecommendations(client: SupabaseClient<Database>,@@ -2931,6 +3057,7 @@ export async function getPickingListRecommendations(return recommendations;}+/** @mcp read */export async function getPickingListLine(client: SupabaseClient<Database>,lineId: string@@ -2944,6 +3071,7 @@ export async function getPickingListLine(.single();}+/** @mcp read */export async function getPickingListLineTrackedEntities(client: SupabaseClient<Database>,lineId: string@@ -2959,6 +3087,7 @@ export async function getPickingListLineTrackedEntities(* MOVES the chosen lot from its warehouse bin to the line's lineside shelf via* the `post-picking` edge function (serial/batch), records it on the line, and* points the job material at lineside. `unpick` reverses it.+ * @mcp update*/export async function setPickingListLineTrackedEntity(client: SupabaseClient<Database>,@@ -3059,6 +3188,7 @@ export async function setPickingListLineTrackedEntity(return { data: { id: args.pickingListLineId }, error: null };}+/** @mcp upsert */export async function upsertPickingList(client: SupabaseClient<Database>,pickingList:@@ -3102,6 +3232,7 @@ export type UnresolvedPickingListLine = {// operator neither fully picked, cancelled, nor explicitly marked Short — i.e.// silently left behind. `hasShort` reports whether any acknowledged shortfall// exists, which forces the final header status to Partial rather than Completed.+/** @mcp read */export async function getUnresolvedPickingListLines(client: SupabaseClient<Database>,pickingListId: string,@@ -3147,6 +3278,7 @@ export async function getUnresolvedPickingListLines(return { unresolved, hasShort, error: null };}+/** @mcp action */export async function cancelOpenPickingListsForJob(db: Kysely<KyselyDatabase>,args: { jobId: string; companyId: string; userId: string }@@ -3203,6 +3335,7 @@ export async function cancelOpenPickingListsForJob(}}+/** @mcp update */export async function updatePickingListStatus(client: SupabaseClient<Database>,pickingListId: string,@@ -3245,6 +3378,7 @@ export async function upsertPickingListLine(.single();}+/** @mcp delete */export async function deletePickingList(client: SupabaseClient<Database>,pickingListId: string@@ -3263,6 +3397,7 @@ export async function deletePickingListLine(// Picking List Business Logic// ----------------------------------------------------------------------------+/** @mcp read */export async function getPickingSchedule(client: SupabaseClient<Database>,args: {@@ -3430,6 +3565,7 @@ class PickingReadError extends Error {}}+/** @mcp create destructive */export async function generatePickingList(client: SupabaseClient<Database>,args: {@@ -3959,6 +4095,7 @@ export async function generatePickingList(* - Unpick: quantity = 0* - Short: quantity = whatever was actually picked, markShort = true* Tracked items go through the scan flow and are rejected here.+ * @mcp action*/export async function pickPickingListLine(client: SupabaseClient<Database>,@@ -4083,6 +4220,7 @@ export async function pickPickingListLine(return { data: { id: line.id }, error: null };}+/** @mcp create destructive */export async function insertStockTransfer(client: SupabaseClient<Database>,input: {@@ -4181,6 +4319,7 @@ export async function insertStockTransfer(};}+/** @mcp create */export async function insertWarehouseTransfer(client: SupabaseClient<Database>,input: {@@ -4285,6 +4424,7 @@ export async function updateStockTransfer(.single();}+/** @mcp update */export async function updateWarehouseTransfer(client: SupabaseClient<Database>,input: {diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex b704fa0101..480cb62ca9 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -108,6 +108,7 @@ export const DEFAULT_PAYMENT_TERM: {* Mirrors calculateDueDate in* packages/database/supabase/functions/shared/calculate-due-date.ts (used when* posting invoices) — keep the two in sync.+ * @mcp read*/export async function computeInvoiceDateDue(client: SupabaseClient<Database>,@@ -173,6 +174,7 @@ export async function computeInvoiceDateDue(* The deadline uses the same calculationMethod anchoring as the due date (see* computeInvoiceDateDue) but with `daysDiscount` instead of `daysDue`. Terms are* batch-loaded in one query — never per invoice (N+1).+ * @mcp read*/export async function computeEarlyPaymentDiscounts(client: SupabaseClient<Database>,@@ -263,6 +265,7 @@ export async function computeEarlyPaymentDiscounts(return result;}+/** @mcp create */export async function createPurchaseInvoiceFromPurchaseOrder(client: SupabaseClient<Database>,purchaseOrderId: string,@@ -279,6 +282,7 @@ export async function createPurchaseInvoiceFromPurchaseOrder(});}+/** @mcp create */export async function createSalesInvoiceFromSalesOrder(client: SupabaseClient<Database>,salesOrderId: string,@@ -295,6 +299,7 @@ export async function createSalesInvoiceFromSalesOrder(});}+/** @mcp create */export async function createSalesInvoiceFromShipment(client: SupabaseClient<Database>,shipmentId: string,@@ -311,6 +316,7 @@ export async function createSalesInvoiceFromShipment(});}+/** @mcp delete */export async function deletePurchaseInvoice(client: SupabaseClient<Database>,purchaseInvoiceId: string@@ -339,6 +345,7 @@ export async function deletePurchaseInvoice(return client.from("purchaseInvoice").delete().eq("id", purchaseInvoiceId);}+/** @mcp delete */export async function deletePurchaseInvoiceLine(client: SupabaseClient<Database>,purchaseInvoiceLineId: string@@ -349,6 +356,7 @@ export async function deletePurchaseInvoiceLine(.eq("id", purchaseInvoiceLineId);}+/** @mcp delete */export async function deleteSalesInvoice(client: SupabaseClient<Database>,salesInvoiceId: string@@ -377,6 +385,7 @@ export async function deleteSalesInvoice(return client.from("salesInvoice").delete().eq("id", salesInvoiceId);}+/** @mcp delete */export async function deleteSalesInvoiceLine(client: SupabaseClient<Database>,salesInvoiceLineId: string@@ -384,6 +393,7 @@ export async function deleteSalesInvoiceLine(return client.from("salesInvoiceLine").delete().eq("id", salesInvoiceLineId);}+/** @mcp read */export async function getPurchaseInvoice(client: SupabaseClient<Database>,purchaseInvoiceId: string@@ -395,6 +405,7 @@ export async function getPurchaseInvoice(.single();}+/** @mcp read */export async function getPurchaseInvoices(client: SupabaseClient<Database>,companyId: string,@@ -422,6 +433,7 @@ export async function getPurchaseInvoices(return query;}+/** @mcp read */export async function getPurchaseInvoiceDelivery(client: SupabaseClient<Database>,purchaseInvoiceId: string@@ -433,6 +445,7 @@ export async function getPurchaseInvoiceDelivery(.single();}+/** @mcp read */export async function getPurchaseInvoiceLines(client: SupabaseClient<Database>,purchaseInvoiceId: string@@ -445,6 +458,7 @@ export async function getPurchaseInvoiceLines(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getPurchaseInvoiceLine(client: SupabaseClient<Database>,purchaseInvoiceLineId: string@@ -456,6 +470,7 @@ export async function getPurchaseInvoiceLine(.single();}+/** @mcp read */export async function getSalesInvoice(client: SupabaseClient<Database>,salesInvoiceId: string@@ -467,6 +482,7 @@ export async function getSalesInvoice(.single();}+/** @mcp read */export async function getSalesInvoiceCustomerDetails(client: SupabaseClient<Database>,salesInvoiceId: string@@ -478,6 +494,7 @@ export async function getSalesInvoiceCustomerDetails(.single();}+/** @mcp read */export async function getSalesInvoices(client: SupabaseClient<Database>,companyId: string,@@ -505,6 +522,7 @@ export async function getSalesInvoices(return query;}+/** @mcp read */export async function getSalesInvoiceShipment(client: SupabaseClient<Database>,salesInvoiceId: string@@ -516,6 +534,7 @@ export async function getSalesInvoiceShipment(.single();}+/** @mcp read */export async function getSalesInvoiceLines(client: SupabaseClient<Database>,salesInvoiceId: string@@ -528,6 +547,7 @@ export async function getSalesInvoiceLines(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getSalesInvoiceLine(client: SupabaseClient<Database>,salesInvoiceLineId: string@@ -539,6 +559,7 @@ export async function getSalesInvoiceLine(.single();}+/** @mcp update */export async function updatePurchaseInvoiceExchangeRate(client: SupabaseClient<Database>,data: {@@ -558,6 +579,7 @@ export async function updatePurchaseInvoiceExchangeRate(return client.from("purchaseInvoice").update(update).eq("id", update.id);}+/** @mcp update */export async function updatePurchaseInvoiceStatus(client: SupabaseClient<Database>,update: {@@ -584,6 +606,7 @@ export async function updatePurchaseInvoiceStatus(return client.from("purchaseInvoice").update(update).eq("id", update.id);}+/** @mcp update */export async function updateSalesInvoiceExchangeRate(client: SupabaseClient<Database>,data: {@@ -603,6 +626,7 @@ export async function updateSalesInvoiceExchangeRate(return client.from("salesInvoice").update(update).eq("id", update.id);}+/** @mcp update */export async function updateSalesInvoiceStatus(client: SupabaseClient<Database>,update: {@@ -629,6 +653,7 @@ export async function updateSalesInvoiceStatus(return client.from("salesInvoice").update(update).eq("id", update.id);}+/** @mcp create destructive */export async function insertPurchaseInvoice(client: SupabaseClient<Database>,input: {@@ -766,6 +791,7 @@ export async function insertPurchaseInvoice(};}+/** @mcp update */export async function updatePurchaseInvoice(client: SupabaseClient<Database>,input: {@@ -916,6 +942,7 @@ export async function upsertPurchaseInvoice(return invoice;}+/** @mcp upsert */export async function upsertPurchaseInvoiceDelivery(client: SupabaseClient<Database>,purchaseInvoiceDelivery:@@ -945,6 +972,7 @@ export async function upsertPurchaseInvoiceDelivery(.single();}+/** @mcp upsert */export async function upsertPurchaseInvoiceLine(client: SupabaseClient<Database>,purchaseInvoiceLine:@@ -985,6 +1013,7 @@ export async function upsertPurchaseInvoiceLine(.single();}+/** @mcp update */export async function updatePurchaseInvoiceLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -1002,6 +1031,7 @@ export async function updatePurchaseInvoiceLineOrder(});}+/** @mcp create destructive */export async function insertSalesInvoice(client: SupabaseClient<Database>,input: {@@ -1144,6 +1174,7 @@ export async function insertSalesInvoice(};}+/** @mcp update */export async function updateSalesInvoice(client: SupabaseClient<Database>,input: {@@ -1294,6 +1325,7 @@ export async function upsertSalesInvoice(return invoice;}+/** @mcp upsert */export async function upsertSalesInvoiceShipment(client: SupabaseClient<Database>,salesInvoiceShipment:@@ -1323,6 +1355,7 @@ export async function upsertSalesInvoiceShipment(.single();}+/** @mcp upsert */export async function upsertSalesInvoiceLine(client: SupabaseClient<Database>,salesInvoiceLine:@@ -1363,6 +1396,7 @@ export async function upsertSalesInvoiceLine(.single();}+/** @mcp update */export async function updateSalesInvoiceLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -1384,6 +1418,7 @@ export async function updateSalesInvoiceLineOrder(// Payments (AR receipts + AP disbursements + applications)// ======================================================================+/** @mcp read */export async function getPayment(client: SupabaseClient<Database>,id: string,@@ -1394,6 +1429,7 @@ export async function getPayment(return query.single();}+/** @mcp read */export async function getPayments(client: SupabaseClient<Database>,companyId: string,@@ -1444,6 +1480,7 @@ export async function getPayments(return query;}+/** @mcp read */export async function getCharge(client: SupabaseClient<Database>,companyId: string,@@ -1457,6 +1494,7 @@ export async function getCharge(.single();}+/** @mcp read */export async function getCharges(client: SupabaseClient<Database>,companyId: string,@@ -1491,6 +1529,7 @@ export async function getCharges(return query;}+/** @mcp read */export async function getReimbursement(client: SupabaseClient<Database>,companyId: string,@@ -1506,6 +1545,7 @@ export async function getReimbursement(.single();}+/** @mcp read */export async function getReimbursements(client: SupabaseClient<Database>,companyId: string,@@ -1546,6 +1586,7 @@ export async function getReimbursements(* document is immutable, and a caller that tries gets zero rows rather than* a silent partial write. There is deliberately no insert branch: the Ramp* sync is the only thing that creates a reimbursement.+ * @mcp update*/export async function updateReimbursement(client: SupabaseClient<Database>,@@ -1579,6 +1620,7 @@ export async function updateReimbursement(** Delete-all-then-reinsert rather than a diff: the editor submits the whole* line set as one field, so a diff would be more code for the same result.+ * @mcp upsert destructive*/export async function upsertReimbursementLines(db: Kysely<KyselyDatabase>,@@ -1659,6 +1701,7 @@ export async function upsertReimbursementLines(});}+/** @mcp read */export async function getInvoiceSettlements(client: SupabaseClient<Database>,companyId: string,@@ -1722,6 +1765,7 @@ export type InvoiceSettlementForInvoice = {// credit/debit memos. Used by the "Applied" panel on the sales/purchase invoice// detail page. Page the embedded parents with their applications so large histories// retain every source without oversized ID lookups.+/** @mcp read */export async function getInvoiceSettlementsForInvoice(client: SupabaseClient<Database>,companyId: string,@@ -1876,6 +1920,7 @@ export type MemoApplication = {| { type: "reimbursement"; id: string; readableId: string };};+/** @mcp read */export async function getMemoApplications(client: SupabaseClient<Database>,companyId: string,@@ -1995,6 +2040,7 @@ export async function getMemoApplications(// Open sales invoices for a customer (active status and a positive// balance). Drives the apply table on the AR payment detail.+/** @mcp read */export async function getOpenSalesInvoicesForCustomer(client: SupabaseClient<Database>,companyId: string,@@ -2009,6 +2055,7 @@ export async function getOpenSalesInvoicesForCustomer(currencyCode);}+/** @mcp read */export async function getOpenPurchaseInvoicesForSupplier(client: SupabaseClient<Database>,companyId: string,@@ -2210,6 +2257,7 @@ async function getOpenInvoicesForParty(* `reimbursement.amount` is DOCUMENT currency (there is no base-currency total* column), so it is converted once here; `invoiceRemainingAmounts` wants a base* total and converts back itself.+ * @mcp read*/export async function getOpenReimbursementsForEmployee(client: SupabaseClient<Database>,@@ -2398,6 +2446,7 @@ function requireCurrencyDecimals(return value;}+/** @mcp read */export async function getPaymentCurrencyConfiguration(client: SupabaseClient<Database>,companyId: string,@@ -2507,6 +2556,7 @@ async function loadOnAccountSources(};}+/** @mcp read */export async function getAvailableOnAccountCreditSources(client: SupabaseClient<Database>,companyId: string,@@ -2554,7 +2604,10 @@ export async function getAvailableOnAccountCreditSources(}}-/** Base-total contract for other readers; the composer uses typed document sources. */+/**+ * Base-total contract for other readers; the composer uses typed document sources.+ * @mcp read+ */export async function getAvailableOnAccountCredit(client: SupabaseClient<Database>,companyId: string,@@ -2568,6 +2621,7 @@ export async function getAvailableOnAccountCredit(}}+/** @mcp upsert */export async function upsertPayment(client: SupabaseClient<Database>,payment:@@ -2614,6 +2668,7 @@ export async function upsertPayment(}// RLS DELETE policy on payment restricts to status='Draft'.+/** @mcp delete */export async function deletePayment(client: SupabaseClient<Database>,id: string@@ -3015,6 +3070,10 @@ async function loadTransactionMemoConsumption(.execute();}+/**+ * @mcp action destructive+ * @mcp audit createdBy+ */export async function replaceInvoiceSettlements(db: Kysely<KyselyDatabase>,args: {@@ -3575,10 +3634,12 @@ export async function replaceInvoiceSettlements(// creditMemo / debitMemo sequences. Posting is handled by the post-memo edge// function; the apply table is editable only while the memo is Draft.+/** @mcp read */export async function getMemo(client: SupabaseClient<Database>, id: string) {return client.from("memo").select("*").eq("id", id).single();}+/** @mcp read */export async function getMemos(client: SupabaseClient<Database>,companyId: string,@@ -3628,6 +3689,7 @@ export async function getMemos(return query;}+/** @mcp upsert */export async function upsertMemo(client: SupabaseClient<Database>,memo:@@ -3659,6 +3721,7 @@ export async function upsertMemo(}// RLS DELETE policy on memo restricts to status='Draft'.+/** @mcp delete */export async function deleteMemo(client: SupabaseClient<Database>, id: string) {return client.from("memo").delete().eq("id", id);}@@ -3843,6 +3906,7 @@ async function loadAvailableMemoCredits(});}+/** @mcp read */export async function getAvailableCreditsForParty(client: SupabaseClient<Database>,companyId: string,@@ -3869,6 +3933,7 @@ export async function getAvailableCreditsForParty(}}+/** @mcp read */export async function getCompanyHasOpenCredits(client: SupabaseClient<Database>,companyId: string,@@ -3890,6 +3955,7 @@ export async function getCompanyHasOpenCredits(// The credit applications currently staged on a (Draft) payment — drives the// composer's pre-fill so a staged credit stays visible and editable instead of// silently vanishing from the available list.+/** @mcp read */export async function getStagedCreditsForPayment(client: SupabaseClient<Database>,paymentId: string,@@ -3936,6 +4002,10 @@ export async function getStagedCreditsForPayment(return { data, error: null };}+/**+ * @mcp action destructive+ * @mcp audit createdBy+ */export async function applyCreditsToInvoices(db: Kysely<KyselyDatabase>,args: {@@ -4142,6 +4212,7 @@ export async function applyCreditsToInvoices(// Tie-out RPCs (migration 20260519140000_ar-ap-tie-out)+/** @mcp read */export async function getArTieOut(client: SupabaseClient<Database>,companyId: string,@@ -4155,6 +4226,7 @@ export async function getArTieOut(.single();}+/** @mcp read */export async function getApTieOut(client: SupabaseClient<Database>,companyId: string,@@ -4168,6 +4240,7 @@ export async function getApTieOut(.single();}+/** @mcp read */export async function getArOpenByCustomer(client: SupabaseClient<Database>,companyId: string,@@ -4179,6 +4252,7 @@ export async function getArOpenByCustomer(});}+/** @mcp read */export async function getApOpenBySupplier(client: SupabaseClient<Database>,companyId: string,@@ -4197,6 +4271,7 @@ export type AgingOptions = {bucketDays?: [number, number, number];};+/** @mcp read */export async function getArAging(client: SupabaseClient<Database>,companyId: string,@@ -4214,6 +4289,7 @@ export async function getArAging(});}+/** @mcp read */export async function getApAging(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex a3853b7016..333501e2ee 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -123,6 +123,7 @@ const SERVICES_LIST_COLUMNS =const logger = getLogger("erp", "items");+/** @mcp action */export async function activateMethodVersion(client: SupabaseClient<Database>,payload: {@@ -139,6 +140,7 @@ export async function activateMethodVersion(});}+/** @mcp create */export async function copyItem(client: SupabaseClient<Database>,args: z.infer<typeof getMethodValidator> & {@@ -165,6 +167,7 @@ export async function copyItem(});}+/** @mcp create */export async function copyMakeMethod(client: SupabaseClient<Database>,args: z.infer<typeof getMethodValidator> & {@@ -214,6 +217,7 @@ export async function copyItemPostingGroup(.eq("companyId", args.companyId);}+/** @mcp create */export async function createRevision(client: SupabaseClient<Database>,args: {@@ -280,6 +284,7 @@ export async function createRevision(}// getNextRevision — numeric → +1, A → …→ Z → AA, AA → AB, etc.+/** @mcp read */export function getNextRevision(maxRevision: string): string {if (/^\d+$/.test(maxRevision)) {return (parseInt(maxRevision) + 1).toString();@@ -299,6 +304,7 @@ export function getNextRevision(maxRevision: string): string {return maxRevision;}+/** @mcp delete */export async function deleteConfigurationParameter(client: SupabaseClient<Database>,id: string@@ -306,6 +312,7 @@ export async function deleteConfigurationParameter(return client.from("configurationParameter").delete().eq("id", id);}+/** @mcp delete */export async function deleteConfigurationRule(client: SupabaseClient<Database>,field: string,@@ -318,6 +325,7 @@ export async function deleteConfigurationRule(.eq("itemId", itemId);}+/** @mcp delete */export async function deleteItemCustomerPart(client: SupabaseClient<Database>,id: string,@@ -330,6 +338,7 @@ export async function deleteItemCustomerPart(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteSupplierPart(client: SupabaseClient<Database>,id: string,@@ -342,6 +351,7 @@ export async function deleteSupplierPart(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteConfigurationParameterGroup(client: SupabaseClient<Database>,id: string@@ -371,10 +381,12 @@ export async function deleteConfigurationParameterGroup(return client.from("configurationParameterGroup").delete().eq("id", id);}+/** @mcp delete */export async function deleteItem(client: SupabaseClient<Database>, id: string) {return client.from("item").delete().eq("id", id);}+/** @mcp delete */export async function deleteItemPostingGroup(client: SupabaseClient<Database>,id: string@@ -382,6 +394,7 @@ export async function deleteItemPostingGroup(return client.from("itemPostingGroup").delete().eq("id", id);}+/** @mcp delete */export async function deleteMaterialDimension(client: SupabaseClient<Database>,id: string@@ -389,6 +402,7 @@ export async function deleteMaterialDimension(return client.from("materialDimension").delete().eq("id", id);}+/** @mcp delete */export async function deleteMaterialFinish(client: SupabaseClient<Database>,id: string@@ -396,6 +410,7 @@ export async function deleteMaterialFinish(return client.from("materialFinish").delete().eq("id", id);}+/** @mcp delete */export async function deleteMaterialForm(client: SupabaseClient<Database>,id: string@@ -403,6 +418,7 @@ export async function deleteMaterialForm(return client.from("materialForm").delete().eq("id", id);}+/** @mcp delete */export async function deleteMaterialGrade(client: SupabaseClient<Database>,id: string@@ -410,6 +426,7 @@ export async function deleteMaterialGrade(return client.from("materialGrade").delete().eq("id", id);}+/** @mcp delete */export async function deleteMaterialSubstance(client: SupabaseClient<Database>,id: string@@ -417,6 +434,7 @@ export async function deleteMaterialSubstance(return client.from("materialSubstance").delete().eq("id", id);}+/** @mcp delete */export async function deleteMethodMaterial(client: SupabaseClient<Database>,id: string@@ -424,6 +442,7 @@ export async function deleteMethodMaterial(return client.from("methodMaterial").delete().eq("id", id);}+/** @mcp action */export async function assertMethodOperationIsDraft(client: SupabaseClient<Database>,operationId: string@@ -453,6 +472,7 @@ export async function deleteMethodOperation(return client.from("methodOperation").delete().eq("id", methodOperationId);}+/** @mcp delete */export async function deleteMethodOperationStep(client: SupabaseClient<Database>,id: string@@ -460,6 +480,7 @@ export async function deleteMethodOperationStep(return client.from("methodOperationStep").delete().eq("id", id);}+/** @mcp delete */export async function deleteMethodOperationStepSlide(client: SupabaseClient<Database>,id: string@@ -467,6 +488,7 @@ export async function deleteMethodOperationStepSlide(return client.from("methodOperationStepSlide").delete().eq("id", id);}+/** @mcp delete */export async function deleteMethodOperationParameter(client: SupabaseClient<Database>,id: string@@ -474,6 +496,7 @@ export async function deleteMethodOperationParameter(return client.from("methodOperationParameter").delete().eq("id", id);}+/** @mcp delete */export async function deleteMethodOperationTool(client: SupabaseClient<Database>,id: string@@ -481,6 +504,7 @@ export async function deleteMethodOperationTool(return client.from("methodOperationTool").delete().eq("id", id);}+/** @mcp delete */export async function deleteUnitOfMeasure(client: SupabaseClient<Database>,id: string@@ -488,6 +512,7 @@ export async function deleteUnitOfMeasure(return client.from("unitOfMeasure").delete().eq("id", id);}+/** @mcp read */export async function getConfigurationParameters(client: SupabaseClient<Database>,itemId: string,@@ -523,6 +548,7 @@ export async function getConfigurationParameters(return { groups: groups.data ?? [], parameters: parameters.data ?? [] };}+/** @mcp read */export async function getConfigurationRules(client: SupabaseClient<Database>,itemId: string,@@ -540,6 +566,7 @@ export async function getConfigurationRules(return result.data ?? [];}+/** @mcp read */export async function getConsumable(client: SupabaseClient<Database>,itemId: string,@@ -552,6 +579,7 @@ export async function getConsumable(.single();}+/** @mcp read */export async function getConsumables(client: SupabaseClient<Database>,companyId: string,@@ -585,6 +613,7 @@ export async function getConsumables(return query;}+/** @mcp read */export async function getConsumablesList(client: SupabaseClient<Database>,companyId: string@@ -602,10 +631,12 @@ export async function getConsumablesList();}+/** @mcp read */export async function getItem(client: SupabaseClient<Database>, id: string) {return client.from("item").select("*").eq("id", id).single();}+/** @mcp read */export async function getItemCost(client: SupabaseClient<Database>,itemId: string,@@ -619,6 +650,7 @@ export async function getItemCost(.single();}+/** @mcp read */export async function getItemCostHistory(client: SupabaseClient<Database>,itemId: string,@@ -639,6 +671,7 @@ export async function getItemCostHistory(.limit(500);}+/** @mcp read */export async function getItemCustomerPart(client: SupabaseClient<Database>,id: string,@@ -652,6 +685,7 @@ export async function getItemCustomerPart(.single();}+/** @mcp read */export async function getItemCustomerParts(client: SupabaseClient<Database>,itemId: string,@@ -664,6 +698,7 @@ export async function getItemCustomerParts(.eq("companyId", companyId);}+/** @mcp read */export async function getItemDemand(client: SupabaseClient<Database>,{@@ -750,6 +785,7 @@ export type DemandForecastSourceRow = {} | null;};+/** @mcp read */export async function getDemandForecastSources(client: SupabaseClient<Database>,{@@ -810,6 +846,7 @@ export async function getDemandForecastSources(};}+/** @mcp read */export async function getItemFiles(client: SupabaseClient<Database>,itemId: string,@@ -821,6 +858,7 @@ export async function getItemFiles(return result.data ?? [];}+/** @mcp read */export async function getItemPostingGroup(client: SupabaseClient<Database>,id: string@@ -828,6 +866,7 @@ export async function getItemPostingGroup(return client.from("itemPostingGroup").select("*").eq("id", id).single();}+/** @mcp read */export async function getItemPostingGroups(client: SupabaseClient<Database>,companyId: string,@@ -853,6 +892,7 @@ export async function getItemPostingGroups(return query;}+/** @mcp read */export async function getItemPostingGroupsList(client: SupabaseClient<Database>,companyId: string@@ -864,6 +904,7 @@ export async function getItemPostingGroupsList(.order("name");}+/** @mcp read */export async function getItemManufacturing(client: SupabaseClient<Database>,id: string,@@ -877,6 +918,7 @@ export async function getItemManufacturing(.single();}+/** @mcp read */export async function getItemPlanning(client: SupabaseClient<Database>,itemId: string,@@ -892,6 +934,7 @@ export async function getItemPlanning(.maybeSingle();}+/** @mcp read */export async function getItemQuantities(client: SupabaseClient<Database>,itemId: string,@@ -920,6 +963,7 @@ export async function getItemQuantities(* location is in play. Zero rows are dropped — the picker renders no badge for* an item it has no row for, so they carry no information and are the bulk of* the table on a tenant with history.+ * @mcp read*/export async function getItemStockQuantitiesByLocation(client: SupabaseClient<Database>,@@ -953,6 +997,7 @@ export async function getItemStockQuantitiesByLocation(return { data: quantities, error: null };}+/** @mcp read */export async function getItemReplenishment(client: SupabaseClient<Database>,itemId: string,@@ -966,6 +1011,7 @@ export async function getItemReplenishment(.single();}+/** @mcp read */export async function getItemSupersession(client: SupabaseClient<Database>,itemId: string,@@ -982,6 +1028,7 @@ export async function getItemSupersession(.maybeSingle();}+/** @mcp read */export async function getItemSupersessionsForItems(client: SupabaseClient<Database>,itemIds: string[],@@ -998,6 +1045,7 @@ export async function getItemSupersessionsForItems(}// Parts that point to this item as their successor (the "Supersedes" back-ref).+/** @mcp read */export async function getItemSupersededBy(client: SupabaseClient<Database>,itemId: string,@@ -1012,6 +1060,7 @@ export async function getItemSupersededBy(.eq("companyId", companyId);}+/** @mcp read */export async function getSupersessionChain(client: SupabaseClient<Database>,itemId: string,@@ -1053,6 +1102,7 @@ export async function getSupersessionChain(return { chain, supersededBy: supersededBy.data ?? [] };}+/** @mcp read */export async function getItemStorageUnitQuantities(client: SupabaseClient<Database>,itemId: string,@@ -1066,6 +1116,7 @@ export async function getItemStorageUnitQuantities(});}+/** @mcp read */export async function getItemSupply(client: SupabaseClient<Database>,{@@ -1105,6 +1156,7 @@ export async function getItemSupply(};}+/** @mcp read */export async function getItemUnitSalePrice(client: SupabaseClient<Database>,id: string,@@ -1118,6 +1170,7 @@ export async function getItemUnitSalePrice(.single();}+/** @mcp read */export async function getJobMaterialUsageForItem(client: SupabaseClient<Database>,{ itemId, companyId }: { itemId: string; companyId: string }@@ -1151,6 +1204,7 @@ export async function getJobMaterialUsageForItem(return { byMaterialId, byJobId };}+/** @mcp read */export async function getMaterialUsedIn(client: SupabaseClient<Database>,itemId: string,@@ -1277,6 +1331,7 @@ export async function getMaterialUsedIn(};}+/** @mcp read */export async function getMakeMethods(client: SupabaseClient<Database>,itemId: string,@@ -1289,6 +1344,7 @@ export async function getMakeMethods(.eq("companyId", companyId);}+/** @mcp read */export async function getMakeMethodById(client: SupabaseClient<Database>,makeMethodId: string,@@ -1302,6 +1358,7 @@ export async function getMakeMethodById(.single();}+/** @mcp read */export async function getMaterial(client: SupabaseClient<Database>,itemId: string,@@ -1314,6 +1371,7 @@ export async function getMaterial(.single();}+/** @mcp read */export async function getMaterials(client: SupabaseClient<Database>,companyId: string,@@ -1347,6 +1405,7 @@ export async function getMaterials(return query;}+/** @mcp read */export async function getMaterialsList(client: SupabaseClient<Database>,companyId: string@@ -1369,6 +1428,7 @@ function buildSearchFilter(search: string, columns: string[]) {return columns.map((column) => `${column}.ilike.${value}`).join(",");}+/** @mcp read */export async function getMaterialDimension(client: SupabaseClient<Database>,id: string@@ -1376,6 +1436,7 @@ export async function getMaterialDimension(return client.from("materialDimension").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialDimensions(client: SupabaseClient<Database>,companyId: string,@@ -1405,6 +1466,7 @@ export async function getMaterialDimensions(return query;}+/** @mcp read */export async function getMaterialDimensionList(client: SupabaseClient<Database>,materialFormId: string,@@ -1419,6 +1481,7 @@ export async function getMaterialDimensionList(.or(`companyId.eq.${companyId},companyId.is.null`);}+/** @mcp read */export async function getMaterialFinish(client: SupabaseClient<Database>,id: string@@ -1426,6 +1489,7 @@ export async function getMaterialFinish(return client.from("materialFinish").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialFinishes(client: SupabaseClient<Database>,companyId: string,@@ -1454,6 +1518,7 @@ export async function getMaterialFinishes(return query;}+/** @mcp read */export async function getMaterialFinishList(client: SupabaseClient<Database>,materialSubstanceId: string,@@ -1466,6 +1531,7 @@ export async function getMaterialFinishList(.or(`companyId.eq.${companyId},companyId.is.null`);}+/** @mcp read */export async function getMaterialForm(client: SupabaseClient<Database>,id: string@@ -1473,6 +1539,7 @@ export async function getMaterialForm(return client.from("materialForm").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialForms(client: SupabaseClient<Database>,companyId: string,@@ -1498,6 +1565,7 @@ export async function getMaterialForms(return query;}+/** @mcp read */export async function getMaterialFormsList(client: SupabaseClient<Database>,companyId: string@@ -1509,6 +1577,7 @@ export async function getMaterialFormsList(.order("name");}+/** @mcp read */export async function getMaterialGrades(client: SupabaseClient<Database>,companyId: string,@@ -1537,6 +1606,7 @@ export async function getMaterialGrades(return query;}+/** @mcp read */export async function getMaterialGrade(client: SupabaseClient<Database>,id: string@@ -1544,6 +1614,7 @@ export async function getMaterialGrade(return client.from("materialGrade").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialGradeList(client: SupabaseClient<Database>,materialSubstanceId: string,@@ -1556,6 +1627,7 @@ export async function getMaterialGradeList(.or(`companyId.eq.${companyId},companyId.is.null`);}+/** @mcp read */export async function getMaterialSubstance(client: SupabaseClient<Database>,id: string@@ -1563,6 +1635,7 @@ export async function getMaterialSubstance(return client.from("materialSubstance").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialSubstances(client: SupabaseClient<Database>,companyId: string,@@ -1588,6 +1661,7 @@ export async function getMaterialSubstances(return query;}+/** @mcp read */export async function getMaterialSubstancesList(client: SupabaseClient<Database>,companyId: string@@ -1599,6 +1673,7 @@ export async function getMaterialSubstancesList(.order("name");}+/** @mcp read */export async function getMethodMaterial(client: SupabaseClient<Database>,materialId: string@@ -1610,6 +1685,7 @@ export async function getMethodMaterial(.single();}+/** @mcp read */export async function getMethodMaterials(client: SupabaseClient<Database>,companyId: string,@@ -1648,6 +1724,7 @@ function isMissingQuantityColumn(return error?.code === "42703" || error?.code === "PGRST204";}+/** @mcp read */export async function getMethodMaterialsByMakeMethod(client: SupabaseClient<Database>,makeMethodId: string@@ -1671,6 +1748,7 @@ export async function getMethodMaterialsByMakeMethod(return result;}+/** @mcp read */export async function getMethodOperations(client: SupabaseClient<Database>,companyId: string,@@ -1699,6 +1777,7 @@ export async function getMethodOperations(return query;}+/** @mcp read */export async function getMethodOperationsByMakeMethodId(client: SupabaseClient<Database>,makeMethodId: string@@ -1721,6 +1800,7 @@ type MethodTreeItem = {children: MethodTreeItem[];};+/** @mcp read */export async function getMethodTree(client: SupabaseClient<Database>,makeMethodId: string@@ -1736,6 +1816,7 @@ export async function getMethodTree(};}+/** @mcp read */export async function getMethodTreeArray(client: SupabaseClient<Database>,makeMethodId: string@@ -1796,6 +1877,7 @@ export type BomItemAttributes = {leadTime: number | null;};+/** @mcp read */export async function getBomItemAttributes(client: SupabaseClient<Database>,companyId: string,@@ -1847,6 +1929,7 @@ export async function getBomItemAttributes(return { data, error: null };}+/** @mcp read */export async function getOpenJobMaterials(client: SupabaseClient<Database>,{@@ -1865,6 +1948,7 @@ export async function getOpenJobMaterials(.eq("companyId", companyId);}+/** @mcp read */export async function getOpenProductionOrders(client: SupabaseClient<Database>,{@@ -1883,6 +1967,7 @@ export async function getOpenProductionOrders(.eq("companyId", companyId);}+/** @mcp read */export async function getOpenPurchaseOrderLines(client: SupabaseClient<Database>,{@@ -1901,6 +1986,7 @@ export async function getOpenPurchaseOrderLines(.eq("companyId", companyId);}+/** @mcp read */export async function getOpenSalesOrderLines(client: SupabaseClient<Database>,{@@ -1919,6 +2005,7 @@ export async function getOpenSalesOrderLines(.eq("locationId", locationId);}+/** @mcp read */export async function getPart(client: SupabaseClient<Database>,itemId: string,@@ -1931,6 +2018,7 @@ export async function getPart(.single();}+/** @mcp read */export async function getParts(client: SupabaseClient<Database>,companyId: string,@@ -1966,6 +2054,7 @@ export async function getParts(// Distinct manufacturer part numbers for the company, used to populate the MPN// column filter in the item list tables. Deduping happens in the route loader.+/** @mcp read */export async function getItemMpnsList(client: SupabaseClient<Database>,companyId: string@@ -1979,6 +2068,7 @@ export async function getItemMpnsList();}+/** @mcp read */export async function getPartsList(client: SupabaseClient<Database>,companyId: string@@ -1996,6 +2086,7 @@ export async function getPartsList();}+/** @mcp read */export async function getPartUsedIn(client: SupabaseClient<Database>,itemId: string,@@ -2153,6 +2244,7 @@ export async function getPartUsedIn(};}+/** @mcp read */export async function getPickMethod(client: SupabaseClient<Database>,itemId: string,@@ -2168,6 +2260,7 @@ export async function getPickMethod(.maybeSingle();}+/** @mcp read */export async function getPickMethods(client: SupabaseClient<Database>,itemId: string,@@ -2180,6 +2273,7 @@ export async function getPickMethods(.eq("companyId", companyId);}+/** @mcp read */export async function getServices(client: SupabaseClient<Database>,companyId: string,@@ -2217,6 +2311,7 @@ export async function getServices(return query;}+/** @mcp read */export async function getService(client: SupabaseClient<Database>,itemId: string,@@ -2233,6 +2328,7 @@ export async function getService(.single();}+/** @mcp read */export async function getServicesList(client: SupabaseClient<Database>,companyId: string@@ -2250,6 +2346,7 @@ export async function getServicesList();}+/** @mcp read */export async function getSupplierParts(client: SupabaseClient<Database>,id: string,@@ -2263,6 +2360,7 @@ export async function getSupplierParts(.eq("companyId", companyId);}+/** @mcp read */export async function getTool(client: SupabaseClient<Database>,itemId: string,@@ -2275,6 +2373,7 @@ export async function getTool(.single();}+/** @mcp read */export async function getTools(client: SupabaseClient<Database>,companyId: string,@@ -2308,6 +2407,7 @@ export async function getTools(return query;}+/** @mcp read */export async function getToolsList(client: SupabaseClient<Database>,companyId: string@@ -2325,6 +2425,7 @@ export async function getToolsList();}+/** @mcp read */export async function getUnitOfMeasure(client: SupabaseClient<Database>,id: string,@@ -2342,6 +2443,7 @@ export async function getUnitOfMeasure(* Which tables still reference a unit of measure, and how many rows each;* empty means safe to delete (or id not visible to the caller). RPC-backed so* the answer doesn't depend on the caller's module permissions.+ * @mcp read*/export async function getUnitOfMeasureUsage(client: SupabaseClient<Database>,@@ -2350,6 +2452,7 @@ export async function getUnitOfMeasureUsage(return client.rpc("get_unit_of_measure_usage", { p_id: id });}+/** @mcp read */export async function getUnitOfMeasures(client: SupabaseClient<Database>,companyId: string,@@ -2372,6 +2475,7 @@ export async function getUnitOfMeasures(return query;}+/** @mcp read */export async function getUnitOfMeasuresList(client: SupabaseClient<Database>,companyId: string@@ -2383,6 +2487,7 @@ export async function getUnitOfMeasuresList(.order("name");}+/** @mcp update */export async function updateConfigurationParameterGroupOrder(client: SupabaseClient<Database>,data: z.infer<typeof configurationParameterGroupOrderValidator>@@ -2393,6 +2498,7 @@ export async function updateConfigurationParameterGroupOrder(.eq("id", data.id);}+/** @mcp update */export async function updateDefaultRevision(client: SupabaseClient<Database>,data: {@@ -2433,6 +2539,7 @@ export async function updateDefaultRevision(.in("itemId", itemIds);}+/** @mcp update */export async function updateConfigurationParameterOrder(client: SupabaseClient<Database>,data: Omit<@@ -2449,6 +2556,7 @@ export async function updateConfigurationParameterOrder(.eq("id", data.id);}+/** @mcp update */export async function updateItemCost(client: SupabaseClient<Database>,itemId: string,@@ -2468,6 +2576,7 @@ export async function updateItemCost(.single();}+/** @mcp update */export async function updateMaterialOrder(client: SupabaseClient<Database>,updates: {@@ -2482,6 +2591,7 @@ export async function updateMaterialOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateOperationOrder(client: SupabaseClient<Database>,updates: {@@ -2496,6 +2606,7 @@ export async function updateOperationOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateRevision(client: SupabaseClient<Database>,revision: {@@ -2513,6 +2624,7 @@ export async function updateRevision(.eq("id", revision.id);}+/** @mcp upsert */export async function upsertConfigurationParameter(client: SupabaseClient<Database>,configurationParameter: z.infer<typeof configurationParameterValidator> & {@@ -2575,6 +2687,7 @@ export async function upsertConfigurationParameter(});}+/** @mcp upsert */export async function upsertConfigurationParameterGroup(client: SupabaseClient<Database>,configurationParameterGroup: z.infer<@@ -2613,6 +2726,7 @@ export async function upsertConfigurationParameterGroup(});}+/** @mcp upsert */export async function upsertConfigurationRule(client: SupabaseClient<Database>,configurationRule: z.infer<typeof configurationRuleValidator> & {@@ -2705,6 +2819,7 @@ export async function upsertItemDefaultPickMethod(* picker to processes the recipe will actually run, so users can't pick a* process the trigger never matches against (the set-shelf-life helper short-circuits* on processId mismatch). Empty array when the item has no active recipe.+ * @mcp read*/export async function getRecipeProcessIdsForItem(client: SupabaseClient<Database>,@@ -2739,6 +2854,7 @@ export async function getRecipeProcessIdsForItem(* Fetch the shelf-life policy for an item. Returns `data: null` (without* an error) when the item has no row, since absence = "not managed" and* that's a valid state we don't want to treat as an error path.+ * @mcp read*/export async function getItemShelfLife(client: SupabaseClient<Database>,@@ -2761,6 +2877,7 @@ export async function getItemShelfLife(* Returns false when there is no make-method, no materials, or every* material has shelf-life NotManaged. Errors are coerced to false — this* is a UI hint, not a correctness gate.+ * @mcp read*/export async function getBomHasShelfLifeManagedInput(client: SupabaseClient<Database>,@@ -2905,6 +3022,7 @@ export async function upsertItemShelfLife(* two independent Supabase calls means a failure between the two leaves a* partial update committed. This helper runs both writes inside a single* Postgres transaction via Kysely.+ * @mcp upsert destructive*/export async function upsertPickMethodWithShelfLife(db: Kysely<KyselyDatabase>,@@ -3054,6 +3172,7 @@ export async function upsertPickMethodWithShelfLife(* Without this, snapshot flags drift from the live item value and leave the* UI reading stale (often sticky-true) tracking flags after an item is* flipped back to Inventory / Non-Inventory.+ * @mcp action*/export async function cascadeItemTrackingType(db: Kysely<KyselyDatabase>,@@ -3196,6 +3315,7 @@ export async function cascadeItemTrackingType(* sourcingType and defaultMethodType are item-level properties; method* materials are read-only mirrors. Only mirrors on Draft make methods are* touched — Active and Archived methods are frozen.+ * @mcp update*/export async function updateItemMethodAndSourcing(db: Kysely<KyselyDatabase>,@@ -3467,6 +3587,9 @@ const typedItemTables = {* Creates a consumable (item row and consumable row) or updates one; on update* `id` is the item id (uuid) or the consumable's readable id and the write is* a full replace, so omitted optional fields are cleared.+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id*/export async function upsertConsumable(client: SupabaseClient<Database>,@@ -3606,6 +3729,7 @@ export async function upsertConsumable(** Callers that also have a customer/supplier part mapping should try that* first; this covers the readableId/name half of the match.+ * @mcp read*/export async function matchItemIdByText(client: SupabaseClient<Database>,@@ -3700,6 +3824,7 @@ export async function matchItemIdByText(* Resolve extracted document line text to an item id: first through the* party's part mapping (customerPartToItem / supplierPart), then by exact* readableId/name match. Returns null when nothing matches directly.+ * @mcp action*/export async function resolveItemIdFromExtractedText(client: SupabaseClient<Database>,@@ -3743,6 +3868,9 @@ export async function resolveItemIdFromExtractedText(* Creates a part (item row and part row) or updates one; on update `id` is the* item id (uuid) or the part's readable id and the write is a full replace, so* omitted optional fields are cleared.+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id*/export async function upsertPart(client: SupabaseClient<Database>,@@ -3888,6 +4016,7 @@ export async function upsertPart(return updated;}+/** @mcp update */export async function updateItem(client: SupabaseClient<Database>,item: z.infer<typeof itemValidator> & {@@ -3902,6 +4031,7 @@ export async function updateItem(.eq("companyId", item.companyId);}+/** @mcp upsert */export async function upsertItemCost(client: SupabaseClient<Database>,itemCost: z.infer<typeof itemCostValidator> & {@@ -3915,6 +4045,10 @@ export async function upsertItemCost(.eq("itemId", itemCost.itemId);}+/**+ * @mcp upsert+ * @mcp key pickMethod itemId, locationId+ */export async function upsertPickMethod(client: SupabaseClient<Database>,pickMethod:@@ -3941,6 +4075,7 @@ export async function upsertPickMethod(.eq("locationId", pickMethod.locationId);}+/** @mcp upsert */export async function upsertItemManufacturing(client: SupabaseClient<Database>,partManufacturing: z.infer<typeof itemManufacturingValidator> & {@@ -3954,6 +4089,10 @@ export async function upsertItemManufacturing(.eq("itemId", partManufacturing.itemId);}+/**+ * @mcp upsert+ * @mcp key itemPlanning itemId, locationId+ */export async function upsertItemPlanning(client: SupabaseClient<Database>,partPlanning:@@ -3978,6 +4117,7 @@ export async function upsertItemPlanning(.eq("locationId", partPlanning.locationId);}+/** @mcp upsert */export async function upsertItemPurchasing(client: SupabaseClient<Database>,itemPurchasing: z.infer<typeof itemPurchasingValidator> & {@@ -4069,6 +4209,7 @@ async function findSupersessionCycle(return { kind: "cycle", path: path.map((id) => readable.get(id) ?? id) };}+/** @mcp upsert destructive */export async function upsertItemSupersession(client: SupabaseClient<Database>,itemSupersession: z.infer<typeof itemSupersessionValidator> & {@@ -4173,6 +4314,7 @@ export async function upsertItemSupersession(.insert({ ...row, itemId, companyId, createdBy });}+/** @mcp upsert */export async function upsertItemPostingGroup(client: SupabaseClient<Database>,itemPostingGroup:@@ -4205,6 +4347,7 @@ export async function upsertItemPostingGroup();}+/** @mcp upsert */export async function upsertSupplierPart(client: SupabaseClient<Database>,supplierPart:@@ -4236,6 +4379,7 @@ export async function upsertSupplierPart(.single();}+/** @mcp upsert */export async function upsertItemCustomerPart(client: SupabaseClient<Database>,customerPart:@@ -4261,6 +4405,7 @@ export async function upsertItemCustomerPart(.single();}+/** @mcp upsert */export async function upsertItemUnitSalePrice(client: SupabaseClient<Database>,itemUnitSalePrice: z.infer<typeof itemUnitSalePriceValidator> & {@@ -4274,6 +4419,7 @@ export async function upsertItemUnitSalePrice(.eq("itemId", itemUnitSalePrice.itemId);}+/** @mcp upsert */export async function upsertMakeMethodVersion(client: SupabaseClient<Database>,makeMethodVersion: z.infer<typeof makeMethodVersionValidator> & {@@ -4391,6 +4537,10 @@ async function resolveMethodMaterialStorageUnitIds(return current;}+/**+ * @mcp upsert+ * @mcp key methodMaterial id+ */export async function upsertMethodMaterial(client: SupabaseClient<Database>,@@ -4496,6 +4646,10 @@ export async function upsertMethodMaterial(.single();}+/**+ * @mcp upsert+ * @mcp key methodOperation id+ */export async function upsertMethodOperation(client: SupabaseClient<Database>,@@ -4531,6 +4685,7 @@ export async function upsertMethodOperation(.single();}+/** @mcp upsert */export async function upsertMethodOperationStep(client: SupabaseClient<Database>,methodOperationStep:@@ -4569,6 +4724,7 @@ export async function upsertMethodOperationStep(// 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.+/** @mcp create */export async function duplicateMethodOperationStep(client: SupabaseClient<Database>,args: { id: string; companyId: string; createdBy: string }@@ -4699,6 +4855,7 @@ export async function duplicateMethodOperationStep(return { data: { id: newStepId }, error: null };}+/** @mcp upsert */export async function upsertMethodOperationStepSlide(client: SupabaseClient<Database>,slide:@@ -4740,6 +4897,7 @@ export async function upsertMethodOperationStepSlide(.single();}+/** @mcp upsert */export async function upsertMethodOperationParameter(client: SupabaseClient<Database>,methodOperationParameter:@@ -4769,6 +4927,7 @@ export async function upsertMethodOperationParameter(.single();}+/** @mcp upsert */export async function upsertMethodOperationTool(client: SupabaseClient<Database>,methodOperationTool:@@ -4844,6 +5003,7 @@ export async function replaceMethodMaterialSteps(// `linked` true = link the material to the step, false = unlink. Idempotent on link.// `quantity` is the per-step share of the BOM line (NULL = the full line quantity);// re-linking an existing link updates the quantity, so the same call edits a split.+/** @mcp update destructive */export async function setMethodMaterialStepLink(client: SupabaseClient<Database>,args: {@@ -4882,6 +5042,7 @@ export async function setMethodMaterialStepLink(// row the operation's Tools tab would create) before linking it to the step. Unlink// removes only the step link; the operation tool row stays (the Tools tab owns it).// Twin of setMethodMaterialStepLink.+/** @mcp update destructive */export async function setMethodOperationToolStepLink(client: SupabaseClient<Database>,args: {@@ -5278,6 +5439,9 @@ async function getNewMaterialSizes(* IDs are typed by hand. An update's material, item and item cost writes land* together or not at all; the pick method, shelf life and new sizes are* written after them.+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id*/export async function upsertMaterial(client: SupabaseClient<Database>,@@ -5624,6 +5788,7 @@ export async function upsertMaterial(* the substance, dimension to the shape, and type to both. With generated* material IDs on, every revision's readable id and name are regenerated once* the material has a substance and a shape.+ * @mcp update*/export async function updateMaterialProperties(client: SupabaseClient<Database>,@@ -5703,6 +5868,7 @@ export async function updateMaterialProperties(/*** Creates a dimension (a named size) for a material shape, or updates the one* whose `id` is sent; a new dimension's id is generated.+ * @mcp upsert*/export async function upsertMaterialDimension(client: SupabaseClient<Database>,@@ -5737,6 +5903,7 @@ export async function upsertMaterialDimension(/*** Creates a finish for a material substance, or updates the one whose `id` is* sent; a new finish's id is generated.+ * @mcp upsert*/export async function upsertMaterialFinish(client: SupabaseClient<Database>,@@ -5766,6 +5933,7 @@ export async function upsertMaterialFinish(.single();}+/** @mcp upsert */export async function upsertMaterialForm(client: SupabaseClient<Database>,materialForm:@@ -5801,6 +5969,7 @@ export async function upsertMaterialForm(/*** Creates a grade for a material substance, or updates the one whose `id` is* sent; a new grade's id is generated.+ * @mcp upsert*/export async function upsertMaterialGrade(client: SupabaseClient<Database>,@@ -5830,6 +5999,7 @@ export async function upsertMaterialGrade(.single();}+/** @mcp delete */export async function deleteMaterialType(client: SupabaseClient<Database>,id: string@@ -5837,6 +6007,7 @@ export async function deleteMaterialType(return client.from("materialType").delete().eq("id", id);}+/** @mcp read */export async function getMaterialTypes(client: SupabaseClient<Database>,companyId: string,@@ -5862,6 +6033,7 @@ export async function getMaterialTypes(return query;}+/** @mcp read */export async function getMaterialType(client: SupabaseClient<Database>,id: string@@ -5869,6 +6041,7 @@ export async function getMaterialType(return client.from("materialType").select("*").eq("id", id).single();}+/** @mcp read */export async function getMaterialTypeList(client: SupabaseClient<Database>,materialSubstanceId: string,@@ -5886,6 +6059,7 @@ export async function getMaterialTypeList(/*** Creates a material type for a substance and shape pair, or updates the one* whose `id` is sent; a new type's id is generated.+ * @mcp upsert*/export async function upsertMaterialType(client: SupabaseClient<Database>,@@ -5915,6 +6089,7 @@ export async function upsertMaterialType(.single();}+/** @mcp upsert */export async function upsertMaterialSubstance(client: SupabaseClient<Database>,materialSubstance:@@ -5951,6 +6126,9 @@ export async function upsertMaterialSubstance(* Creates a service (item row and service row) or updates one; on update `id`* is the item id (uuid) or the service's readable id and the write is a full* replace, so omitted optional fields are cleared.+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id*/export async function upsertService(client: SupabaseClient<Database>,@@ -6043,6 +6221,7 @@ export async function upsertService(return updated;}+/** @mcp upsert */export async function upsertUnitOfMeasure(client: SupabaseClient<Database>,unitOfMeasure:@@ -6077,6 +6256,9 @@ export async function upsertUnitOfMeasure(* Creates a tool (item row and tool row) or updates one; on update `id` is the* item id (uuid) or the tool's readable id and the write is a full replace, so* omitted optional fields are cleared.+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id*/export async function upsertTool(client: SupabaseClient<Database>,@@ -6214,6 +6396,7 @@ export async function upsertTool(* tiers from ALL suppliers for each item.** Used by the quote loader to pre-load pricing data for BOM costing.+ * @mcp read*/export async function getSupplierPriceBreaksForItems(client: SupabaseClient<Database>,@@ -6274,6 +6457,7 @@ export async function getSupplierPriceBreaksForItems(* Delegates to getSupplierPriceBreaksForItems + lookupBuyPriceFromMap.** Used in quote creation where the specific supplier isn't known.+ * @mcp read*/export async function lookupBuyPrice(client: SupabaseClient<Database>,@@ -6288,6 +6472,7 @@ export async function lookupBuyPrice(/*** Fetch price breaks array for a specific supplier part.* Used by PO and Invoice forms to cache breaks in state.+ * @mcp read*/export async function getSupplierPartPriceBreaks(client: SupabaseClient<Database>,@@ -6311,6 +6496,7 @@ export async function getSupplierPartPriceBreaks(// -----------------------------------------------------------------------------// Reads// -----------------------------------------------------------------------------+/** @mcp read */export async function getChangeNotice(client: SupabaseClient<Database>,changeNoticeId: string,@@ -6324,6 +6510,7 @@ export async function getChangeNotice(.single();}+/** @mcp read */export async function getChangeNotices(client: SupabaseClient<Database>,companyId: string,@@ -6352,6 +6539,7 @@ export async function getChangeNotices(// -----------------------------------------------------------------------------// Header CRUD// -----------------------------------------------------------------------------+/** @mcp create */export async function insertChangeNotice(client: SupabaseClient<Database>,input: {@@ -6428,6 +6616,7 @@ export async function insertChangeNotice(};}+/** @mcp update */export async function updateChangeNotice(client: SupabaseClient<Database>,input: {@@ -6462,6 +6651,7 @@ export async function updateChangeNotice(return { data: { id: result.data.id }, error: null };}+/** @mcp delete */export async function deleteChangeNotice(client: SupabaseClient<Database>,changeNoticeId: string,@@ -6495,6 +6685,7 @@ export async function deleteChangeNotice(// Stage transition — the single guarded writer (G8), a compare-and-swap (G2).// Forward-only (isAllowedChangeNoticeTransition).// -----------------------------------------------------------------------------+/** @mcp update */export async function updateChangeNoticeStatus(client: SupabaseClient<Database>,update: {@@ -6556,6 +6747,7 @@ export async function updateChangeNoticeStatus(// -----------------------------------------------------------------------------// Change Notice Types (the "Category" lookup — configured like Issue Types)// -----------------------------------------------------------------------------+/** @mcp read */export async function getChangeNoticeTypes(client: SupabaseClient<Database>,companyId: string,@@ -6579,6 +6771,7 @@ export async function getChangeNoticeTypes(return query;}+/** @mcp read */export async function getChangeNoticeTypesList(client: SupabaseClient<Database>,companyId: string@@ -6590,6 +6783,7 @@ export async function getChangeNoticeTypesList(.order("name", { ascending: true });}+/** @mcp read */export async function getChangeNoticeType(client: SupabaseClient<Database>,id: string,@@ -6603,6 +6797,7 @@ export async function getChangeNoticeType(.single();}+/** @mcp upsert */export async function upsertChangeNoticeType(client: SupabaseClient<Database>,changeNoticeType:@@ -6638,6 +6833,7 @@ export async function upsertChangeNoticeType(.single();}+/** @mcp delete */export async function deleteChangeNoticeType(client: SupabaseClient<Database>,id: string,@@ -6667,6 +6863,7 @@ export async function deleteChangeNoticeType(// embeds — TS2589 budget); a per-item origin set that only grows drives a fixpoint,// so a corrupt/cyclic BOM can't loop forever and provenance fully propagates.// `nodeBudget` is a pure infinite-loop backstop, not a depth limit.+/** @mcp read */export async function getTopLevelProductsForItems(client: SupabaseClient<Database>,itemIds: string[],@@ -7247,6 +7444,7 @@ async function discardChangeNoticeDraft(// Add an affected item to a CO: insert the row, then spin its CO-owned Draft// make method per the change type and write the draft refs back. Rolls the row// back if draft creation fails (edge-fn calls can't share one txn — G2).+/** @mcp create destructive */export async function addChangeNoticeAffectedItem(client: SupabaseClient<Database>,input: {@@ -7410,6 +7608,7 @@ export async function addChangeNoticeAffectedItem(// Switch an affected item's change type: discard its current draft and rebuild// for the new type (Q2 — the editable surface differs per type, so edits reset).+/** @mcp update */export async function updateChangeNoticeAffectedItemChangeType(client: SupabaseClient<Database>,input: {@@ -7485,6 +7684,7 @@ export async function updateChangeNoticeAffectedItemChangeType(// Update the per-item revision cutover config (mode + dates). The existence of// the oldRev→newRev supersession is automatic at release; this only tunes it.+/** @mcp update */export async function updateChangeNoticeAffectedItemCutover(client: SupabaseClient<Database>,input: {@@ -7562,6 +7762,7 @@ async function stitchItemLabels(}// The affected items of a CO, each stitched to a minimal item label.+/** @mcp read */export async function getChangeNoticeAffectedItems(client: SupabaseClient<Database>,changeNoticeId: string,@@ -7597,6 +7798,7 @@ export async function getChangeNoticeAffectedItems(// Remove an affected item + discard its CO-owned Draft (delete the new item for// Revision/New Part, or the Draft method for Version) so no orphan draft leaks.+/** @mcp action destructive */export async function removeChangeNoticeAffectedItem(client: SupabaseClient<Database>,id: string,@@ -7642,6 +7844,7 @@ export type ChangeNoticeForItem = {createdAt: string;};+/** @mcp read */export async function findChangeNoticesForItem(client: SupabaseClient<Database>,args: {@@ -7751,6 +7954,7 @@ export async function findChangeNoticesForItem(// Reverse of the Linked-NCR cross-link (4a): every change notice that references// a given non-conformance. Read-only, minimal columns; rendered on the Issue// detail. Flat select (no embeds — TS2589 budget).+/** @mcp read */export async function getChangeNoticesForNonConformance(client: SupabaseClient<Database>,nonConformanceId: string,@@ -7769,6 +7973,7 @@ export async function getChangeNoticesForNonConformance(// Reuses the canonical G6 query at the open-status filter. A non-empty result// means adding the part here would create a parallel open CO — the routes (and// the staging service) reject it.+/** @mcp read */export async function findOtherOpenChangeNoticesForItem(client: SupabaseClient<Database>,args: { itemId: string; companyId: string; excludeChangeNoticeId: string }@@ -7785,6 +7990,7 @@ export async function findOtherOpenChangeNoticesForItem(// item detail page (part/tool/material) — the CO history for the item plus the// type lookup used to label rows. One shared source so the detail routes don't// each re-implement the pair of reads.+/** @mcp read */export async function getItemChangeNoticeData(client: SupabaseClient<Database>,itemId: string,@@ -7805,6 +8011,7 @@ export async function getItemChangeNoticeData(// user, any stage; non-gating. Kept as its own section of items.service.ts to// keep each area focused and under the module's 1000-line budget (G4).// =============================================================================+/** @mcp read */export async function getChangeNoticeActions(client: SupabaseClient<Database>,changeNoticeId: string,@@ -7862,6 +8069,7 @@ export async function getChangeNoticeActions(};}+/** @mcp update */export async function updateChangeNoticeActionStatus(client: SupabaseClient<Database>,input: {@@ -7883,6 +8091,7 @@ export async function updateChangeNoticeActionStatus(.single();}+/** @mcp delete */export async function deleteChangeNoticeAction(client: SupabaseClient<Database>,id: string@@ -7890,6 +8099,7 @@ export async function deleteChangeNoticeAction(return client.from("changeOrderActionTask").delete().eq("id", id);}+/** @mcp update */export async function updateChangeNoticeActionOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -7911,6 +8121,7 @@ export async function updateChangeNoticeActionOrder(// Change Notice Required Actions (the configurable default-action templates the// config CRUD page manages, and the source new change notices are seeded from).// =============================================================================+/** @mcp read */export async function getChangeNoticeRequiredActions(client: SupabaseClient<Database>,companyId: string,@@ -7934,6 +8145,7 @@ export async function getChangeNoticeRequiredActions(return query;}+/** @mcp read */export async function getChangeNoticeRequiredActionsList(client: SupabaseClient<Database>,companyId: string@@ -7946,6 +8158,7 @@ export async function getChangeNoticeRequiredActionsList(.order("name", { ascending: true });}+/** @mcp read */export async function getChangeNoticeRequiredAction(client: SupabaseClient<Database>,id: string,@@ -7959,6 +8172,7 @@ export async function getChangeNoticeRequiredAction(.single();}+/** @mcp upsert */export async function upsertChangeNoticeRequiredAction(client: SupabaseClient<Database>,input: {@@ -7995,6 +8209,7 @@ export async function upsertChangeNoticeRequiredAction(.single();}+/** @mcp delete */export async function deleteChangeNoticeRequiredAction(client: SupabaseClient<Database>,id: string,@@ -8012,6 +8227,7 @@ export async function deleteChangeNoticeRequiredAction(// Quality's requiredActionIds field). Templates newly selected are instantiated// (appended); templates deselected have their task removed. Tasks with no// template link (actionTypeId IS NULL) are left untouched.+/** @mcp update destructive */export async function setChangeNoticeActionTasks(client: SupabaseClient<Database>,input: {@@ -8400,6 +8616,9 @@ export type DiffMethodResult = {// PURE. Compares two method snapshots. No DB access — the caller supplies plain// rows (live method rows as `base`, CO-staged rows as `target`), and optionally// the per-operation child buckets to also diff steps/parameters/tools.+/**+ * @mcp read+ */export function diffMethod(input: DiffMethodInput): DiffMethodResult {return {materials: diffRows(@@ -8820,6 +9039,7 @@ async function stampOperationRefNames(// CO-owned Draft method as `target` (both REAL method tables), correlate by// natural keys, run the pure `diffMethod`, and collect. Also returns the manual// supersession declarations. Flat selects scoped by companyId (no embeds).+/** @mcp read */export async function getChangeNoticeDiff(client: SupabaseClient<Database>,changeNoticeId: string,@@ -8988,6 +9208,9 @@ export async function getChangeNoticeDiff(* returned `signedUrl`, then call `documents_insertUploadedDocument` with the* returned `path`, the item's type as `sourceDocument`, and* `sourceDocumentId: itemId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createItemDocumentUploadUrl(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.tsindex 3e7ea95ce5..1123259a45 100644--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@ -22,6 +22,7 @@ import type {shiftValidator} from "./people.models";+/** @mcp delete */export async function deleteAttribute(client: SupabaseClient<Database>,attributeId: string@@ -32,6 +33,7 @@ export async function deleteAttribute(.eq("id", attributeId);}+/** @mcp delete */export async function deleteAttributeCategory(client: SupabaseClient<Database>,attributeCategoryId: string@@ -42,6 +44,7 @@ export async function deleteAttributeCategory(.eq("id", attributeCategoryId);}+/** @mcp delete */export async function deleteDepartment(client: SupabaseClient<Database>,departmentId: string@@ -49,6 +52,7 @@ export async function deleteDepartment(return client.from("department").delete().eq("id", departmentId);}+/** @mcp delete */export async function deleteHoliday(client: SupabaseClient<Database>,holidayId: string@@ -56,6 +60,7 @@ export async function deleteHoliday(return client.from("holiday").delete().eq("id", holidayId);}+/** @mcp delete */export async function deleteShift(client: SupabaseClient<Database>,shiftId: string@@ -64,6 +69,7 @@ export async function deleteShift(return client.from("shift").update({ active: false }).eq("id", shiftId);}+/** @mcp read */export async function getAttribute(client: SupabaseClient<Database>,attributeId: string@@ -98,6 +104,7 @@ async function getAttributes(.order("sortOrder", { foreignTable: "userAttribute", ascending: true });}+/** @mcp read */export async function getAttributeCategories(client: SupabaseClient<Database>,companyId: string,@@ -125,6 +132,7 @@ export async function getAttributeCategories(return query;}+/** @mcp read */export async function getAttributeCategory(client: SupabaseClient<Database>,id: string@@ -147,10 +155,12 @@ export async function getAttributeCategory(.single();}+/** @mcp read */export async function getAttributeDataTypes(client: SupabaseClient<Database>) {return client.from("attributeDataType").select("*");}+/** @mcp read */export async function getDepartment(client: SupabaseClient<Database>,departmentId: string@@ -158,6 +168,7 @@ export async function getDepartment(return client.from("department").select("*").eq("id", departmentId).single();}+/** @mcp read */export async function getDepartments(client: SupabaseClient<Database>,companyId: string,@@ -183,6 +194,7 @@ export async function getDepartments(return query;}+/** @mcp read */export async function getDepartmentsList(client: SupabaseClient<Database>,companyId: string@@ -194,6 +206,7 @@ export async function getDepartmentsList(.order("name");}+/** @mcp read */export async function getDepartmentsTree(client: SupabaseClient<Database>,companyId: string@@ -205,6 +218,7 @@ export async function getDepartmentsTree(.order("name");}+/** @mcp read */export async function getEmployeeJob(client: SupabaseClient<Database>,employeeId: string,@@ -218,6 +232,7 @@ export async function getEmployeeJob(.single();}+/** @mcp read */export async function getEmployeeSummary(client: SupabaseClient<Database>,employeeId: string,@@ -231,6 +246,7 @@ export async function getEmployeeSummary(.single();}+/** @mcp read */export async function getHoliday(client: SupabaseClient<Database>,holidayId: string@@ -238,6 +254,7 @@ export async function getHoliday(return client.from("holiday").select("*").eq("id", holidayId).single();}+/** @mcp read */export async function getHolidays(client: SupabaseClient<Database>,companyId: string,@@ -263,6 +280,7 @@ export async function getHolidays(return query;}+/** @mcp read */export function getHolidayYears(client: SupabaseClient<Database>,companyId: string@@ -289,6 +307,7 @@ type Person = Employee & {attributes: PersonAttributes;};+/** @mcp read */export async function getPeople(client: SupabaseClient<Database>,companyId: string,@@ -368,6 +387,7 @@ export async function getPeople(};}+/** @mcp read */export async function getContacts(client: SupabaseClient<Database>,companyId: string,@@ -400,6 +420,7 @@ export async function getContacts(error: null};}+/** @mcp read */export async function getShift(client: SupabaseClient<Database>,shiftId: string@@ -412,6 +433,7 @@ export async function getShift(.single();}+/** @mcp read */export async function getShifts(client: SupabaseClient<Database>,companyId: string,@@ -435,6 +457,7 @@ export async function getShifts(return query;}+/** @mcp read */export async function getShiftsList(client: SupabaseClient<Database>,companyId: string,@@ -453,6 +476,7 @@ export async function getShiftsList(return query.order("name");}+/** @mcp read */export async function getEmployeeShifts(client: SupabaseClient<Database>,companyId: string@@ -463,6 +487,7 @@ export async function getEmployeeShifts(.eq("companyId", companyId);}+/** @mcp read */export async function getEmployeeDepartments(client: SupabaseClient<Database>,companyId: string@@ -473,6 +498,7 @@ export async function getEmployeeDepartments(.eq("companyId", companyId);}+/** @mcp read */export async function getShiftsWithTimes(client: SupabaseClient<Database>,companyId: string,@@ -489,6 +515,7 @@ export async function getShiftsWithTimes(.order("name");}+/** @mcp create */export async function insertAttribute(client: SupabaseClient<Database>,attribute: {@@ -518,6 +545,7 @@ export async function insertAttribute(.single();}+/** @mcp create */export async function insertAttributeCategory(client: SupabaseClient<Database>,attributeCategory: {@@ -535,6 +563,7 @@ export async function insertAttributeCategory(.single();}+/** @mcp create */export async function insertEmployeeJob(client: SupabaseClient<Database>,job: {@@ -546,6 +575,7 @@ export async function insertEmployeeJob(return client.from("employeeJob").insert(job).select("*").single();}+/** @mcp update */export async function updateAttribute(client: SupabaseClient<Database>,attribute: {@@ -570,6 +600,7 @@ export async function updateAttribute(.eq("id", attribute.id);}+/** @mcp update */export async function updateAttributeCategory(client: SupabaseClient<Database>,attributeCategory: {@@ -587,6 +618,7 @@ export async function updateAttributeCategory(.eq("id", id);}+/** @mcp update */export async function updateAttributeSortOrder(client: SupabaseClient<Database>,updates: {@@ -601,6 +633,7 @@ export async function updateAttributeSortOrder(return Promise.all(updatePromises);}+/** @mcp update destructive */export async function updateEmployeeJob(db: Kysely<KyselyDatabase>,employeeId: string,@@ -734,6 +767,7 @@ export async function updateEmployeeJob(}}+/** @mcp upsert */export async function upsertDepartment(client: SupabaseClient<Database>,department:@@ -757,6 +791,7 @@ export async function upsertDepartment(return client.from("department").insert(department).select("*").single();}+/** @mcp upsert */export async function upsertHoliday(client: SupabaseClient<Database>,holiday:@@ -777,6 +812,7 @@ export async function upsertHoliday(return client.from("holiday").update(sanitize(holiday)).eq("id", holiday.id);}+/** @mcp upsert */export async function upsertShift(client: SupabaseClient<Database>,shift:@@ -797,6 +833,7 @@ export async function upsertShift(return client.from("shift").update(sanitize(shift)).eq("id", shift.id);}+/** @mcp action */export async function clockIn(client: SupabaseClient<Database>,args: {@@ -821,6 +858,7 @@ export async function clockIn(});}+/** @mcp action */export async function clockOut(client: SupabaseClient<Database>,args: {@@ -849,6 +887,7 @@ export async function clockOut(.eq("id", open.data.id);}+/** @mcp create */export async function createTimeCardEntry(client: SupabaseClient<Database>,entry: {@@ -867,6 +906,7 @@ export async function createTimeCardEntry(.single();}+/** @mcp delete */export async function deleteTimeCardEntry(client: SupabaseClient<Database>,entryId: string@@ -874,6 +914,7 @@ export async function deleteTimeCardEntry(return client.from("timeCardEntry").delete().eq("id", entryId);}+/** @mcp read */export async function getClockedInEmployees(client: SupabaseClient<Database>,companyId: string@@ -886,6 +927,7 @@ export async function getClockedInEmployees(.order("clockIn", { ascending: true });}+/** @mcp read */export async function getOpenClockEntry(client: SupabaseClient<Database>,employeeId: string,@@ -900,6 +942,7 @@ export async function getOpenClockEntry(.maybeSingle();}+/** @mcp read */export async function getRecentTimecards(client: SupabaseClient<Database>,companyId: string@@ -912,6 +955,7 @@ export async function getRecentTimecards(.limit(100);}+/** @mcp read */export async function getScheduledEmployeesToday(client: SupabaseClient<Database>,companyId: string@@ -946,6 +990,7 @@ export async function getScheduledEmployeesToday(});}+/** @mcp read */export async function getTimeCardEntry(client: SupabaseClient<Database>,entryId: string@@ -953,6 +998,7 @@ export async function getTimeCardEntry(return client.from("timeCardEntry").select("*").eq("id", entryId).single();}+/** @mcp read */export async function getTimeCardEntries(client: SupabaseClient<Database>,args: {@@ -979,6 +1025,7 @@ export async function getTimeCardEntries(return query;}+/** @mcp read */export async function getTimecardEntries(client: SupabaseClient<Database>,companyId: string,@@ -1002,6 +1049,7 @@ export async function getTimecardEntries(return query;}+/** @mcp read */export async function getWeeklyHoursForEmployees(client: SupabaseClient<Database>,companyId: string,@@ -1031,6 +1079,7 @@ export async function getWeeklyHoursForEmployees(return weeklyMs;}+/** @mcp update */export async function updateTimeCardEntry(client: SupabaseClient<Database>,args: {diff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.tsindex 0403df355f..44c86470f3 100644--- a/apps/erp/app/modules/production/production.mcp.server.ts+++ b/apps/erp/app/modules/production/production.mcp.server.ts@@ -162,6 +162,7 @@ export async function completeJob(* `production` update gate is re-applied here (the MCP executor performs no* per-tool check). `client` MUST stay named `client` and first — the MCP executor* injects it positionally by that exact name; renaming breaks the tool.+ * @mcp action*/export async function scheduleJob(client: SupabaseClient<Database>,@@ -204,6 +205,8 @@ export async function scheduleJob(* creates match the UI: estimates fill at release).* - Update recalcs requirements ALWAYS; dependencies when the material is* Make to Order and tied to an operation.+ * @mcp upsert+ * @mcp key jobMaterial id*/export async function upsertJobMaterial(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 5e420d698d..ea20bef088 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -115,6 +115,7 @@ import {const logger = getLogger("erp", "production");+/** @mcp update */export async function convertSalesOrderLinesToJobs(client: SupabaseClient<Database>,{@@ -441,6 +442,7 @@ export async function convertSalesOrderLinesToJobs(* @param client - Supabase client* @param params - Job details* @returns The calculated priority number+ * @mcp action*/export async function calculateJobPriority(client: SupabaseClient<Database>,@@ -526,6 +528,7 @@ export async function calculateJobPriority(return newPriority;}+/** @mcp delete */export async function deleteJob(client: SupabaseClient<Database>,jobId: string@@ -533,6 +536,7 @@ export async function deleteJob(return client.from("job").delete().eq("id", jobId);}+/** @mcp delete */export async function deleteJobMaterial(client: SupabaseClient<Database>,jobMaterialId: string@@ -547,6 +551,7 @@ export async function deleteJobOperation(return client.from("jobOperation").delete().eq("id", jobOperationId);}+/** @mcp delete */export async function deleteJobOperationStep(client: SupabaseClient<Database>,id: string@@ -554,6 +559,7 @@ export async function deleteJobOperationStep(return client.from("jobOperationStep").delete().eq("id", id);}+/** @mcp delete */export async function deleteJobOperationStepSlide(client: SupabaseClient<Database>,id: string@@ -561,6 +567,7 @@ export async function deleteJobOperationStepSlide(return client.from("jobOperationStepSlide").delete().eq("id", id);}+/** @mcp delete */export async function deleteJobOperationParameter(client: SupabaseClient<Database>,id: string@@ -568,6 +575,7 @@ export async function deleteJobOperationParameter(return client.from("jobOperationParameter").delete().eq("id", id);}+/** @mcp delete */export async function deleteJobOperationTool(client: SupabaseClient<Database>,id: string@@ -575,6 +583,7 @@ export async function deleteJobOperationTool(return client.from("jobOperationTool").delete().eq("id", id);}+/** @mcp delete */export async function deleteProcedure(client: SupabaseClient<Database>,procedureId: string@@ -582,6 +591,7 @@ export async function deleteProcedure(return client.from("procedure").delete().eq("id", procedureId);}+/** @mcp delete */export async function deleteProcedureStep(client: SupabaseClient<Database>,procedureStepId: string,@@ -594,6 +604,7 @@ export async function deleteProcedureStep(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteProcedureParameter(client: SupabaseClient<Database>,procedureParameterId: string,@@ -606,6 +617,7 @@ export async function deleteProcedureParameter(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteProductionEvent(client: SupabaseClient<Database>,productionEventId: string,@@ -659,6 +671,7 @@ export async function deleteProductionEvent(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteProductionQuantity(client: SupabaseClient<Database>,productionQuantityId: string@@ -669,6 +682,7 @@ export async function deleteProductionQuantity(.eq("id", productionQuantityId);}+/** @mcp read */export async function getActiveJobOperationByJobId(client: SupabaseClient<Database>,jobId: string,@@ -707,6 +721,7 @@ export async function getActiveJobOperationByJobId(return jobOperations.data[0];}+/** @mcp read */export async function getActiveJobOperationsByLocation(client: SupabaseClient<Database>,locationId: string,@@ -718,6 +733,7 @@ export async function getActiveJobOperationsByLocation(});}+/** @mcp read */export async function getJobsByDateRange(client: SupabaseClient<Database>,locationId: string,@@ -731,6 +747,7 @@ export async function getJobsByDateRange(});}+/** @mcp read */export async function getUnscheduledJobs(client: SupabaseClient<Database>,locationId: string@@ -740,6 +757,7 @@ export async function getUnscheduledJobs(});}+/** @mcp read */export async function getActiveProductionEvents(client: SupabaseClient<Database>,companyId: string@@ -753,6 +771,7 @@ export async function getActiveProductionEvents(.is("endTime", null);}+/** @mcp delete */export async function deleteScrapReason(client: SupabaseClient<Database>,scrapReasonId: string@@ -760,6 +779,7 @@ export async function deleteScrapReason(return client.from("scrapReason").delete().eq("id", scrapReasonId);}+/** @mcp delete */export async function deleteFailureMode(client: SupabaseClient<Database>,failureModeId: string@@ -767,6 +787,7 @@ export async function deleteFailureMode(return client.from("maintenanceFailureMode").delete().eq("id", failureModeId);}+/** @mcp delete */export async function deleteMaintenanceDispatch(client: SupabaseClient<Database>,dispatchId: string@@ -781,6 +802,7 @@ export async function deleteMaintenanceDispatchComment(return client.from("maintenanceDispatchComment").delete().eq("id", commentId);}+/** @mcp delete */export async function deleteMaintenanceDispatchEvent(client: SupabaseClient<Database>,eventId: string@@ -788,6 +810,7 @@ export async function deleteMaintenanceDispatchEvent(return client.from("maintenanceDispatchEvent").delete().eq("id", eventId);}+/** @mcp delete */export async function deleteMaintenanceDispatchItem(client: SupabaseClient<Database>,itemId: string@@ -805,6 +828,7 @@ export async function deleteMaintenanceDispatchWorkCenter(.eq("id", workCenterId);}+/** @mcp delete */export async function deleteMaintenanceSchedule(client: SupabaseClient<Database>,scheduleId: string@@ -819,6 +843,7 @@ export async function deleteMaintenanceScheduleItem(return client.from("maintenanceScheduleItem").delete().eq("id", itemId);}+/** @mcp read */export async function getDemandForecasts(client: SupabaseClient<Database>,params: {@@ -837,6 +862,7 @@ export async function getDemandForecasts(.in("periodId", params.periodIds);}+/** @mcp read */export async function getDemandProjections(client: SupabaseClient<Database>,params: {@@ -855,6 +881,7 @@ export async function getDemandProjections(.in("periodId", params.periodIds);}+/** @mcp read */export async function getJobDocuments(client: SupabaseClient<Database>,companyId: string,@@ -927,6 +954,7 @@ export const getPartDocuments = async (return results.filter((f) => f !== null).flat();};+/** @mcp read */export async function getJobDocumentsWithItemId(client: SupabaseClient<Database>,companyId: string,@@ -966,6 +994,7 @@ export async function getJobDocumentsWithItemId(}}+/** @mcp read */export async function getJob(client: SupabaseClient<Database>, id: string) {return client.from("jobs").select("*").eq("id", id).single();}@@ -980,6 +1009,7 @@ export async function getJob(client: SupabaseClient<Database>, id: string) {// IN-PROCESS (persists nothing) and returns the projected completion +// bottleneck cause. Returns null when the job isn't in the schedulable set// (e.g. not Ready/In Progress/Paused).+/** @mcp read */export async function getJobExpediteForecast(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -1026,6 +1056,7 @@ export async function getJobExpediteForecast(}}+/** @mcp read */export async function getJobByOperationId(client: SupabaseClient<Database>,operationId: string@@ -1037,6 +1068,7 @@ export async function getJobByOperationId(.single();}+/** @mcp read */export async function getJobPurchaseOrderLines(client: SupabaseClient<Database>,jobId: string@@ -1049,6 +1081,7 @@ export async function getJobPurchaseOrderLines(.eq("jobId", jobId);}+/** @mcp read */export async function getJobOperationsForTimeline(client: SupabaseClient<Database>,jobId: string@@ -1064,6 +1097,7 @@ export async function getJobOperationsForTimeline(.order("order");}+/** @mcp read */export async function getCapacityReservationsByJob(client: SupabaseClient<Database>,jobId: string@@ -1081,6 +1115,7 @@ export async function getCapacityReservationsByJob(* The Outbound report: open jobs at a location that fill a sales order, with* where each one ships (RPC `get_completion_jobs`), ordered by the plant-calendar* day they complete — the report groups on that order.+ * @mcp read*/export async function getCompletionJobs(client: SupabaseClient<Database>,@@ -1110,6 +1145,7 @@ export async function getCompletionJobs();}+/** @mcp read */export async function getCapacityReservationsForResources(client: SupabaseClient<Database>,companyId: string,@@ -1154,6 +1190,7 @@ export async function getCapacityReservationsForResources(return query.order("startAt");}+/** @mcp read */export async function getMaintenanceDowntimeForResources(client: SupabaseClient<Database>,companyId: string,@@ -1180,6 +1217,7 @@ export async function getMaintenanceDowntimeForResources(return query.order("plannedStartTime");}+/** @mcp read */export async function getProductionEventsByJob(client: SupabaseClient<Database>,jobId: string@@ -1192,6 +1230,7 @@ export async function getProductionEventsByJob(.eq("jobOperation.jobId", jobId);}+/** @mcp read */export async function getJobs(client: SupabaseClient<Database>,companyId: string,@@ -1217,6 +1256,7 @@ export async function getJobs(return query;}+/** @mcp read */export async function getJobsBySalesOrderLine(client: SupabaseClient<Database>,salesOrderLineId: string@@ -1228,6 +1268,7 @@ export async function getJobsBySalesOrderLine(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getJobsList(client: SupabaseClient<Database>,companyId: string,@@ -1245,6 +1286,7 @@ export async function getJobsList(});}+/** @mcp read */export async function getJobMakeMethodById(client: SupabaseClient<Database>,jobMakeMethodId: string,@@ -1258,6 +1300,7 @@ export async function getJobMakeMethodById(.single();}+/** @mcp read */export async function getRootMakeMethod(client: SupabaseClient<Database>,jobId: string,@@ -1272,6 +1315,7 @@ export async function getRootMakeMethod(.single();}+/** @mcp read */export async function getJobMaterialsWithQuantityOnHand(client: SupabaseClient<Database>,jobId: string,@@ -1314,6 +1358,7 @@ export async function getJobMaterialsWithQuantityOnHand(}// Distinct item ids on a job — scopes the Materials-page Item filter.+/** @mcp read */export async function getJobMaterialItemIds(client: SupabaseClient<Database>,jobId: string,@@ -1349,6 +1394,7 @@ function methodAllocationRank(methodType: MethodType | null): number {// "in stock" on one line and "needs order" on another.// Stock is shared with no per-job reservation, so order matters. Result is keyed// by jobMaterial id (the line), not item id.+/** @mcp read */export async function getJobMaterialShortfallByItem(client: SupabaseClient<Database>,jobId: string,@@ -1684,6 +1730,7 @@ function getJobOrderStatusByMaterial(// One status per material id for a job — the single source the table and tree// both consume. Empty for jobs that show no indicators.+/** @mcp read */export async function getJobOrderStatusMap(client: SupabaseClient<Database>,jobId: string,@@ -1748,6 +1795,7 @@ export async function getJobOrderStatusMap();}+/** @mcp read */export async function getJobMethodTree(client: SupabaseClient<Database>,jobId: string@@ -1763,6 +1811,7 @@ export async function getJobMethodTree(};}+/** @mcp read */export async function getJobMethodTreeArray(client: SupabaseClient<Database>,jobId: string@@ -1822,6 +1871,7 @@ export type JobMethodTreeItem = {children: JobMethodTreeItem[];};+/** @mcp read */export async function getJobMaterial(client: SupabaseClient<Database>,materialId: string@@ -1845,6 +1895,7 @@ function isMissingQuantityColumn(return error?.code === "42703" || error?.code === "PGRST204";}+/** @mcp read */export async function getJobMaterialsByMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string@@ -1868,6 +1919,7 @@ export async function getJobMaterialsByMethodId(return result;}+/** @mcp read */export async function getJobOperation(client: SupabaseClient<Database>,jobOperationId: string@@ -1879,6 +1931,7 @@ export async function getJobOperation(.single();}+/** @mcp read */export async function getJobOperations(client: SupabaseClient<Database>,jobId: string,@@ -1909,6 +1962,7 @@ export async function getJobOperations(return query;}+/** @mcp read */export async function getJobOperationDependencies(client: SupabaseClient<Database>,jobId: string@@ -1919,6 +1973,7 @@ export async function getJobOperationDependencies(.eq("jobId", jobId);}+/** @mcp read */export async function getJobOperationsAssignedToEmployee(client: SupabaseClient<Database>,employeeId: string,@@ -1933,6 +1988,7 @@ export async function getJobOperationsAssignedToEmployee(.eq("companyId", companyId);}+/** @mcp read */export async function getJobOperationAttachments(client: SupabaseClient<Database>,jobOperationIds: string[]@@ -1966,6 +2022,7 @@ export async function getJobOperationAttachments(return attachmentsByOperation;}+/** @mcp read */export async function getJobOperationsList(client: SupabaseClient<Database>,jobId: string@@ -1977,6 +2034,7 @@ export async function getJobOperationsList(.order("order", { ascending: true });}+/** @mcp read */export async function getJobOperationsByMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string@@ -1990,6 +2048,7 @@ export async function getJobOperationsByMethodId(.order("order", { ascending: true });}+/** @mcp read */export async function getJobOperationStepRecords(client: SupabaseClient<Database>,jobId: string,@@ -2016,6 +2075,7 @@ export async function getJobOperationStepRecords(return query;}+/** @mcp read */export async function getOutsideOperationsByJobId(client: SupabaseClient<Database>,jobId: string,@@ -2029,6 +2089,7 @@ export async function getOutsideOperationsByJobId(.eq("operationType", "Outside Processing");}+/** @mcp read */export async function getProcedure(client: SupabaseClient<Database>,id: string@@ -2040,6 +2101,7 @@ export async function getProcedure(.single();}+/** @mcp read */export async function getProcedureSteps(client: SupabaseClient<Database>,procedureId: string@@ -2050,6 +2112,7 @@ export async function getProcedureSteps(.eq("procedureId", procedureId);}+/** @mcp read */export async function getProcedureParameters(client: SupabaseClient<Database>,procedureId: string@@ -2060,6 +2123,7 @@ export async function getProcedureParameters(.eq("procedureId", procedureId);}+/** @mcp read */export async function getProcedureVersions(client: SupabaseClient<Database>,procedure: { name: string; version: number },@@ -2074,6 +2138,7 @@ export async function getProcedureVersions(.order("version", { ascending: false });}+/** @mcp read */export async function getProcedures(client: SupabaseClient<Database>,companyId: string,@@ -2099,6 +2164,7 @@ export async function getProcedures(return query;}+/** @mcp read */export async function getProceduresList(client: SupabaseClient<Database>,companyId: string@@ -2117,6 +2183,7 @@ export async function getProceduresList();}+/** @mcp read */export async function getProductionEvent(client: SupabaseClient<Database>,id: string@@ -2128,6 +2195,7 @@ export async function getProductionEvent(.single();}+/** @mcp read */export async function getProductionEvents(client: SupabaseClient<Database>,jobOperationIds: string[],@@ -2157,6 +2225,7 @@ export async function getProductionEvents(return query;}+/** @mcp read */export async function getProductionEventsPage(client: SupabaseClient<Database>,jobOperationId: string,@@ -2190,6 +2259,7 @@ export async function getProductionEventsPage(};}+/** @mcp read */export async function getProductionEventsByOperations(client: SupabaseClient<Database>,jobOperationIds: string[]@@ -2203,6 +2273,7 @@ export async function getProductionEventsByOperations(.order("startTime", { ascending: true });}+/** @mcp read */export async function getProductionPlanning(client: SupabaseClient<Database>,locationId: string,@@ -2237,6 +2308,7 @@ export async function getProductionPlanning(return query;}+/** @mcp read */export async function getProductionProjections(client: SupabaseClient<Database>,locationId: string,@@ -2271,6 +2343,7 @@ export async function getProductionProjections(return query;}+/** @mcp read */export async function getProductionQuantity(client: SupabaseClient<Database>,id: string@@ -2282,6 +2355,7 @@ export async function getProductionQuantity(.single();}+/** @mcp read */export async function getProductionQuantities(client: SupabaseClient<Database>,jobOperationIds: string[],@@ -2310,6 +2384,7 @@ export async function getProductionQuantities(return query;}+/** @mcp read */export async function getProductionDataByOperations(client: SupabaseClient<Database>,jobOperationIds: string[]@@ -2340,6 +2415,7 @@ export async function getProductionDataByOperations(};}+/** @mcp read */export async function getScrapReasonsList(client: SupabaseClient<Database>,companyId: string@@ -2351,6 +2427,7 @@ export async function getScrapReasonsList(.order("name");}+/** @mcp read */export async function getScrapReason(client: SupabaseClient<Database>,scrapReasonId: string@@ -2362,6 +2439,7 @@ export async function getScrapReason(.single();}+/** @mcp read */export async function getScrapReasons(client: SupabaseClient<Database>,companyId: string,@@ -2385,6 +2463,7 @@ export async function getScrapReasons(return query;}+/** @mcp read */export async function getFailureMode(client: SupabaseClient<Database>,failureModeId: string@@ -2396,6 +2475,7 @@ export async function getFailureMode(.single();}+/** @mcp read */export async function getFailureModes(client: SupabaseClient<Database>,companyId: string,@@ -2419,6 +2499,7 @@ export async function getFailureModes(return query;}+/** @mcp read */export async function getFailureModesList(client: SupabaseClient<Database>,companyId: string@@ -2430,6 +2511,7 @@ export async function getFailureModesList(.order("name");}+/** @mcp read */export async function getMaintenanceDispatch(client: SupabaseClient<Database>,dispatchId: string@@ -2447,6 +2529,7 @@ export async function getMaintenanceDispatch(.single();}+/** @mcp read */export async function getMaintenanceDispatches(client: SupabaseClient<Database>,companyId: string,@@ -2470,6 +2553,7 @@ export async function getMaintenanceDispatches(return query;}+/** @mcp read */export async function getMaintenanceDispatchComments(client: SupabaseClient<Database>,dispatchId: string@@ -2484,6 +2568,7 @@ export async function getMaintenanceDispatchComments(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getMaintenanceDispatchEvents(client: SupabaseClient<Database>,dispatchId: string@@ -2499,6 +2584,7 @@ export async function getMaintenanceDispatchEvents(.order("startTime", { ascending: false });}+/** @mcp read */export async function getMaintenanceDispatchItems(client: SupabaseClient<Database>,dispatchId: string@@ -2512,6 +2598,7 @@ export async function getMaintenanceDispatchItems(.eq("maintenanceDispatchId", dispatchId);}+/** @mcp read */export async function getMaintenanceDispatchWorkCenters(client: SupabaseClient<Database>,dispatchId: string@@ -2525,6 +2612,7 @@ export async function getMaintenanceDispatchWorkCenters(.eq("maintenanceDispatchId", dispatchId);}+/** @mcp read */export async function getMaintenanceSchedule(client: SupabaseClient<Database>,scheduleId: string@@ -2539,6 +2627,7 @@ export async function getMaintenanceSchedule(.single();}+/** @mcp read */export async function getMaintenanceSchedules(client: SupabaseClient<Database>,companyId: string,@@ -2566,6 +2655,7 @@ export async function getMaintenanceSchedules(return query;}+/** @mcp read */export async function getMaintenanceScheduleItems(client: SupabaseClient<Database>,scheduleId: string@@ -2579,6 +2669,7 @@ export async function getMaintenanceScheduleItems(.eq("maintenanceScheduleId", scheduleId);}+/** @mcp read */export async function getTrackedEntityByJobId(client: SupabaseClient<Database>,jobId: string@@ -2614,6 +2705,7 @@ export async function getTrackedEntityByJobId(};}+/** @mcp read */export async function getTrackedEntitiesByJobId(client: SupabaseClient<Database>,jobId: string@@ -2646,6 +2738,7 @@ export async function getTrackedEntitiesByJobId(* same snapshot and a receipt committing mid-read cannot pair a new quantity* with old units. Kysely because itemLedger is readable only with inventory or* accounting view, and production users need the answer; the route authorizes.+ * @mcp read*/export async function getJobReceiptSnapshot(db: Kysely<KyselyDatabase>,@@ -2677,6 +2770,7 @@ export async function getJobReceiptSnapshot(/*** Reschedule a job using the unified scheduling engine.* This recalculates dates, work centers, and priorities for all operations.+ * @mcp update*/export async function recalculateJobOperationDependencies(client: SupabaseClient<Database>,@@ -2719,6 +2813,7 @@ export async function recalculateJobOperationDependencies(};}}+/** @mcp update */export async function recalculateJobRequirements(client: SupabaseClient<Database>,params: {@@ -2735,6 +2830,7 @@ export async function recalculateJobRequirements(});}+/** @mcp update */export async function recalculateJobMakeMethodRequirements(client: SupabaseClient<Database>,params: {@@ -2751,6 +2847,7 @@ export async function recalculateJobMakeMethodRequirements(});}+/** @mcp update */export async function runMRP(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -2783,6 +2880,7 @@ export async function runMRP(}}+/** @mcp update */export async function updateJobBatchNumber(client: SupabaseClient<Database>,companyId: string,@@ -2825,6 +2923,7 @@ export type JobReleaseReadiness = {// What stands between these jobs and release, read in one query per table for// any number of jobs. The job Release dialog and batch release both read it, so// a job released through a batch is held to the job page's rules.+/** @mcp read */export async function getJobReleaseReadiness(client: SupabaseClient<Database>,jobIds: string[],@@ -3011,6 +3110,7 @@ export async function getJobReleaseReadiness(};}+/** @mcp update */export async function updateJobStatus(client: SupabaseClient<Database>,params: {@@ -3076,6 +3176,7 @@ export async function updateJobStatus(return result;}+/** @mcp update */export async function updateJobMaterialOrder(client: SupabaseClient<Database>,updates: {@@ -3090,6 +3191,7 @@ export async function updateJobMaterialOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateJobOperationOrder(client: SupabaseClient<Database>,updates: {@@ -3104,6 +3206,7 @@ export async function updateJobOperationOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateJobOperationStepOrder(client: SupabaseClient<Database>,updates: {@@ -3121,6 +3224,7 @@ export async function updateJobOperationStepOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateKanbanJob(client: SupabaseClient<Database>,params: {@@ -3138,6 +3242,7 @@ export async function updateKanbanJob(.eq("companyId", companyId);}+/** @mcp update */export async function updateQuoteOperationStepOrder(client: SupabaseClient<Database>,updates: {@@ -3155,6 +3260,7 @@ export async function updateQuoteOperationStepOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateMethodOperationStepOrder(client: SupabaseClient<Database>,updates: {@@ -3172,6 +3278,7 @@ export async function updateMethodOperationStepOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateJobOperationStatus(client: SupabaseClient<Database>,id: string,@@ -3256,6 +3363,7 @@ export async function returnPickedRemaindersForJob(});}+/** @mcp update */export async function updateJobOperationDueDate(client: SupabaseClient<Database>,id: string,@@ -3275,6 +3383,7 @@ export async function updateJobOperationDueDate(.single();}+/** @mcp update */export async function updateProcedureStepOrder(client: SupabaseClient<Database>,updates: {@@ -3289,6 +3398,7 @@ export async function updateProcedureStepOrder(return Promise.all(updatePromises);}+/** @mcp upsert */export async function upsertProductionEvent(client: SupabaseClient<Database>,productionEvent:@@ -3348,6 +3458,7 @@ export async function updateProductionQuantity(.single();}+/** @mcp upsert */export async function upsertProductionQuantity(client: SupabaseClient<Database>,productionQuantity:@@ -3399,6 +3510,7 @@ export async function upsertProductionQuantity(* Kept out of the options type literal on purpose: the MCP metadata generator* parses that object textually and turns a JSDoc block above a property into a* property name of its own, which then ships in the public tool schema.+ * @mcp create*/export async function insertJob(client: SupabaseClient<Database>,@@ -3672,6 +3784,7 @@ async function assignJobSerialNumbers(}}+/** @mcp update */export async function updateJob(client: SupabaseClient<Database>,input: {@@ -3736,7 +3849,10 @@ export async function updateJob(.single();}-/** @deprecated Use insertJob for new jobs, updateJob for existing jobs */+/**+ * @deprecated Use insertJob for new jobs, updateJob for existing jobs+ * @mcp upsert+ */export async function upsertJob(client: SupabaseClient<Database>,job:@@ -3824,6 +3940,10 @@ export async function upsertJobMaterial(.single();}+/**+ * @mcp upsert+ * @mcp key jobOperation id+ */export async function upsertJobOperation(client: SupabaseClient<Database>,jobOperation:@@ -3891,6 +4011,7 @@ export async function upsertJobOperation(return operationInsert;}+/** @mcp upsert */export async function upsertJobOperationStep(client: SupabaseClient<Database>,jobOperationStep:@@ -3931,6 +4052,7 @@ export async function upsertJobOperationStep(// 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.+/** @mcp create */export async function duplicateJobOperationStep(client: SupabaseClient<Database>,args: { id: string; companyId: string; createdBy: string }@@ -4060,6 +4182,7 @@ export async function duplicateJobOperationStep(// 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.+/** @mcp upsert */export async function upsertJobOperationStepSlide(client: SupabaseClient<Database>,slide:@@ -4101,6 +4224,7 @@ export async function upsertJobOperationStepSlide(.single();}+/** @mcp upsert */export async function upsertJobOperationParameter(client: SupabaseClient<Database>,jobOperationParameter:@@ -4139,6 +4263,7 @@ export async function upsertJobOperationParameter(* Implements the §7 `{ date, confidence? }` contract — confidence is a string* enum, "low" when the schedule may not hold (a conflicted op or a pending* replan) and "scheduled" otherwise.+ * @mcp read*/export async function getJobPromiseDate(client: SupabaseClient<Database>,@@ -4177,6 +4302,7 @@ export async function getJobPromiseDate(};}+/** @mcp upsert */export async function upsertJobOperationTool(client: SupabaseClient<Database>,jobOperationTool:@@ -4252,6 +4378,7 @@ export async function replaceJobMaterialSteps(// `linked` true = link the material to the step, false = unlink. Idempotent on link.// `quantity` is the per-step share of the BOM line (NULL = the full line quantity);// re-linking an existing link updates the quantity, so the same call edits a split.+/** @mcp update destructive */export async function setJobMaterialStepLink(client: SupabaseClient<Database>,args: {@@ -4290,6 +4417,7 @@ export async function setJobMaterialStepLink(// row the operation's Tools tab would create) before linking it to the step. Unlink// removes only the step link; the operation tool row stays (the Tools tab owns it).// Twin of setJobMaterialStepLink.+/** @mcp update destructive */export async function setJobOperationToolStepLink(client: SupabaseClient<Database>,args: {@@ -4349,6 +4477,7 @@ export async function setJobOperationToolStepLink(.eq("jobOperationStepId", args.jobOperationStepId);}+/** @mcp upsert */export async function upsertJobMethod(client: SupabaseClient<Database>,type: "itemToJob" | "quoteLineToJob" | "jobToJob",@@ -4429,6 +4558,7 @@ export async function upsertJobMethod(});}+/** @mcp upsert */export async function upsertJobMaterialMakeMethod(client: SupabaseClient<Database>,jobMaterial: {@@ -4511,6 +4641,7 @@ export async function upsertJobMaterialMakeMethod(* method (BOM + operations) into it. Shared by the job-material create and edit* routes: both flip a material to "Make to Order" and must populate the newly* created child make method.+ * @mcp action*/export async function pullJobMaterialMakeMethod(client: SupabaseClient<Database>,@@ -4548,6 +4679,7 @@ export async function pullJobMaterialMakeMethod(});}+/** @mcp upsert */export async function upsertMakeMethodFromJob(client: SupabaseClient<Database>,jobMethod: {@@ -4577,6 +4709,7 @@ export async function upsertMakeMethodFromJob(});}+/** @mcp upsert */export async function upsertMakeMethodFromJobMethod(client: SupabaseClient<Database>,jobMethod: {@@ -4615,6 +4748,7 @@ export async function upsertMakeMethodFromJobMethod(return { data: null, error: null };}+/** @mcp upsert */export async function upsertProcedure(client: SupabaseClient<Database>,procedure:@@ -4709,6 +4843,7 @@ export async function upsertProcedure(return insert;}+/** @mcp upsert */export async function upsertProcedureStep(client: SupabaseClient<Database>,procedureStep:@@ -4736,6 +4871,7 @@ export async function upsertProcedureStep(.single();}+/** @mcp upsert */export async function upsertProcedureParameter(client: SupabaseClient<Database>,procedureParameter:@@ -4763,6 +4899,7 @@ export async function upsertProcedureParameter(.single();}+/** @mcp upsert */export async function upsertScrapReason(client: SupabaseClient<Database>,scrapReason:@@ -4787,6 +4924,7 @@ export async function upsertScrapReason(}}+/** @mcp upsert */export async function upsertFailureMode(client: SupabaseClient<Database>,failureMode:@@ -4845,6 +4983,7 @@ export async function upsertMaintenanceDispatch(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchComment(client: SupabaseClient<Database>,comment:@@ -4871,6 +5010,7 @@ export async function upsertMaintenanceDispatchComment(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchEvent(client: SupabaseClient<Database>,event:@@ -4897,6 +5037,7 @@ export async function upsertMaintenanceDispatchEvent(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchItem(client: SupabaseClient<Database>,item:@@ -4949,6 +5090,7 @@ export async function upsertMaintenanceDispatchWorkCenter(}}+/** @mcp upsert */export async function upsertMaintenanceSchedule(client: SupabaseClient<Database>,schedule:@@ -5001,6 +5143,7 @@ export async function upsertMaintenanceScheduleItem(}}+/** @mcp read */export async function getPeopleAssignments(client: SupabaseClient<Database>,companyId: string,@@ -5016,6 +5159,7 @@ export async function getPeopleAssignments(.eq("date", args.date);}+/** @mcp read */export async function getPeopleAbsences(client: SupabaseClient<Database>,companyId: string,@@ -5028,6 +5172,7 @@ export async function getPeopleAbsences(.eq("date", date);}+/** @mcp read */export async function getPeopleAssignmentsRange(client: SupabaseClient<Database>,companyId: string,@@ -5046,6 +5191,7 @@ export async function getPeopleAssignmentsRange(.order("shiftId", { nullsFirst: true });}+/** @mcp read */export async function getPeopleAbsencesRange(client: SupabaseClient<Database>,companyId: string,@@ -5064,6 +5210,7 @@ export async function getPeopleAbsencesRange(* Planned jobs are excluded — only released (firm) work counts toward load,* matching the industry release-gating convention. Paginated — the default* PostgREST max_rows (1000) would silently truncate a busy location.+ * @mcp read*/export async function getPeopleCapacityOperations(client: SupabaseClient<Database>,@@ -5114,6 +5261,7 @@ export async function getPeopleCapacityOperations(* The `workCenterShift` links (rung 1 of the availability ladder) for a set of* work centers, in ONE `.in()` query. Feeds the Capacity view's per-work-center* calendar-hours DISPLAY mirror of the engine ladder.+ * @mcp read*/export async function getWorkCenterShifts(client: SupabaseClient<Database>,@@ -5132,6 +5280,7 @@ export async function getWorkCenterShifts(* Scheduled series. Bounded by the window (not "recent only") so earlier days* of the current week keep their completed bookings, filtered to WorkCenter* rows server-side, and paginated past the PostgREST max_rows cap.+ * @mcp read*/export async function getWorkCenterReservationsRange(client: SupabaseClient<Database>,@@ -5163,6 +5312,7 @@ export async function getWorkCenterReservationsRange();}+/** @mcp read */export async function getLocationEmployees(client: SupabaseClient<Database>,companyId: string,@@ -5179,6 +5329,7 @@ export async function getLocationEmployees(* Gated abilities per work center at a location, for the people board's* advisory qualification badge. Chained lookups instead of a PostgREST embed —* the composite tenant FKs break alias:fkColumn(...) embeds.+ * @mcp read*/export async function getWorkCenterRequiredAbilities(client: SupabaseClient<Database>,@@ -5253,6 +5404,7 @@ export async function getWorkCenterRequiredAbilities(return { data: rows, error: null };}+/** @mcp read */export async function getActiveEmployeeAbilities(client: SupabaseClient<Database>,companyId: string@@ -5360,6 +5512,7 @@ async function requirePeopleBoardRefs(/*** Move-semantics upsert: one magnet per person per date/shift — any existing* assignment for the person on that date/shift is replaced.+ * @mcp upsert destructive*/export async function upsertPeopleAssignment(db: Kysely<KyselyDatabase>,@@ -5477,6 +5630,7 @@ export async function upsertPeopleAssignment(});}+/** @mcp delete */export async function deletePeopleAssignment(client: SupabaseClient<Database>,id: string,@@ -5491,6 +5645,7 @@ export async function deletePeopleAssignment(.single();}+/** @mcp update */export async function setPeopleAbsence(client: SupabaseClient<Database>,absence: {@@ -5505,6 +5660,7 @@ export async function setPeopleAbsence(return client.from("peopleAbsence").insert([absence]).select("id").single();}+/** @mcp action destructive */export async function clearPeopleAbsence(client: SupabaseClient<Database>,id: string,@@ -5527,6 +5683,7 @@ export async function clearPeopleAbsence(* Move one assignment row to another station (drag = move). If the person* already has a row at the target station for the same shift/date, the rows* merge (hours add; a whole-shift row absorbs the other).+ * @mcp update destructive*/export async function movePeopleAssignment(db: Kysely<KyselyDatabase>,@@ -5607,6 +5764,7 @@ export async function movePeopleAssignment(* stations are updated (hours/overtime), new stations inserted, stations* not in `rows` deleted. Scoped to the shift when one is given. One* transaction — the Working-hours popover's Save.+ * @mcp update destructive*/export async function setPeopleDay(db: Kysely<KyselyDatabase>,@@ -5715,6 +5873,7 @@ export async function setPeopleDay(* shift). Lowering hours releases the remainder back to the board's* free-hours pool; splitting across stations = lower here, then drag the* remainder card to the next station.+ * @mcp update*/export async function setPeopleAssignmentHours(client: SupabaseClient<Database>,@@ -5739,6 +5898,7 @@ export async function setPeopleAssignmentHours(* department (via the location's work centers) and/or a shift. One UPDATE so* partial application can't happen; department resolves server-side (never a* client-supplied work-center list).+ * @mcp update*/export async function setPeopleOvertimeBulk(db: Kysely<KyselyDatabase>,@@ -5784,6 +5944,7 @@ export async function setPeopleOvertimeBulk(});}+/** @mcp create */export async function copyPeopleBoard(db: Kysely<KyselyDatabase>,args: {@@ -5888,6 +6049,7 @@ const toIsoDate = (value: unknown) => {* Assign a person to a station for a whole Monday-start week: one row per* working day (the shift's weekdays when a shift is given, Mon–Fri* otherwise), skipping days where they're absent or already assigned.+ * @mcp action*/export async function assignPeopleWeek(db: Kysely<KyselyDatabase>,@@ -6008,8 +6170,11 @@ export async function assignPeopleWeek(});}-/** Remove a person from a station for the whole week (their other stations- * and other weeks are untouched). */+/**+ * Remove a person from a station for the whole week (their other stations+ * and other weeks are untouched).+ * @mcp action destructive+ */export async function unassignPeopleWeek(db: Kysely<KyselyDatabase>,args: {@@ -6037,6 +6202,7 @@ export async function unassignPeopleWeek(* Move a person's whole week from one station to another. Days where they* already have a row at the target station keep the target row (the source* row is dropped); other days simply change station.+ * @mcp update destructive*/export async function movePeopleWeek(db: Kysely<KyselyDatabase>,@@ -6108,6 +6274,7 @@ export async function movePeopleWeek(* Copy a whole Monday-start week of people assignments onto another week,* day by day, with the same skip rules as the day copy (people already* assigned or absent on the target date are left alone). One transaction.+ * @mcp create*/export async function copyPeopleWeek(db: Kysely<KyselyDatabase>,@@ -6144,6 +6311,7 @@ export async function copyPeopleWeek(/*** Mark a person absent for every date in [fromDate, toDate] (vacation as one* action). Dates that already carry an absence for the person are skipped.+ * @mcp update*/export async function setPeopleAbsenceRange(db: Kysely<KyselyDatabase>,@@ -6212,6 +6380,7 @@ export async function setPeopleAbsenceRange(* Reactive replanning: notify that a scheduling INPUT changed (shift,* qualification, work center, location). Marks the company's active jobs* schedule-outdated immediately and schedules a debounced replan wave.+ * @mcp action*/export async function notifyScheduleInputsChanged(companyId: string,@@ -6246,6 +6415,7 @@ export async function notifyScheduleInputsChanged(// batch builder's candidate query) so the dashboard number matches what the// builder surfaces. Head count only — no rows. !inner turns the nested filters// on process/job into real join predicates that constrain the count.+/** @mcp read */export async function getUnbatchedBatchableOperationCount(client: SupabaseClient<Database>,companyId: string@@ -6263,6 +6433,7 @@ export async function getUnbatchedBatchableOperationCount(.not("job.status", "in", "(Completed,Closed,Cancelled)");}+/** @mcp read */export async function getJobOperationBatches(client: SupabaseClient<Database>,companyId: string,@@ -6305,6 +6476,7 @@ function deriveSharedWorkCenterName(// work-center name: a batch created from the board carries no header work// center until it is dragged, but when every member sits on one work center// that IS the batch's work center — the board itself falls back the same way.+/** @mcp read */export async function getJobOperationBatchMemberStats(client: SupabaseClient<Database>,companyId: string,@@ -6378,6 +6550,7 @@ export type JobOperationBatchListMember = {// (same no-N+1 pattern as getJobOperationBatchMemberStats — collect ids, one// .in(), tally). getJobOperationBatchWithMembers is single-batch and would be// N+1 across the list, so the list uses this leaner grouped read instead.+/** @mcp read */export async function getJobOperationBatchMembers(client: SupabaseClient<Database>,companyId: string,@@ -6428,6 +6601,7 @@ export async function getJobOperationBatchMembers(// WIP tracked entity (tagged with its jobMakeMethod), narrowed to lots still// Available with stock. Drives the drawer's "Merge output lots" action — >=2 of// one item are mergeable, and a merged batch returns none (parents Consumed).+/** @mcp read */export async function getBatchOutputLots(client: SupabaseClient<Database>,batchId: string,@@ -6457,6 +6631,7 @@ export async function getBatchOutputLots(.gt("quantity", 0);}+/** @mcp read */export async function getJobOperationBatchWithMembers(client: SupabaseClient<Database>,batchId: string,@@ -6501,6 +6676,7 @@ export async function getJobOperationBatchWithMembers(// The batch's production events: the live aggregate run while Active, and the// per-member slices after completion (slices keep the jobOperationBatchId tag).+/** @mcp read */export async function getJobOperationBatchEvents(client: SupabaseClient<Database>,batchId: string,@@ -6516,6 +6692,7 @@ export async function getJobOperationBatchEvents(.order("startTime", { ascending: true });}+/** @mcp read */export async function getBatchableOperations(client: SupabaseClient<Database>,companyId: string,@@ -6534,6 +6711,7 @@ export async function getBatchableOperations(return result;}+/** @mcp read */export async function getBatchableProcesses(client: SupabaseClient<Database>,companyId: string@@ -6547,6 +6725,7 @@ export async function getBatchableProcesses(.order("name");}+/** @mcp create */export async function createJobOperationBatch(client: SupabaseClient<Database>,args: {@@ -6569,6 +6748,7 @@ export async function createJobOperationBatch(});}+/** @mcp update */export async function updateJobOperationBatch(client: SupabaseClient<Database>,args: {@@ -6586,6 +6766,7 @@ export async function updateJobOperationBatch(});}+/** @mcp update */export async function releaseJobOperationBatch(client: SupabaseClient<Database>,args: { batchId: string; companyId: string; userId: string }@@ -6595,6 +6776,7 @@ export async function releaseJobOperationBatch(});}+/** @mcp action */export async function unreleaseJobOperationBatch(client: SupabaseClient<Database>,args: { batchId: string; companyId: string; userId: string }@@ -6606,6 +6788,7 @@ export async function unreleaseJobOperationBatch(// --- Assembly Instructions ---------------------------------------------+/** @mcp read */export async function getAssemblyInstruction(client: SupabaseClient<Database>,id: string@@ -6619,6 +6802,7 @@ export async function getAssemblyInstruction(.single();}+/** @mcp read */export async function getAssemblyInstructions(client: SupabaseClient<Database>,args: {@@ -6660,6 +6844,7 @@ export async function getAssemblyInstructions(return query.order("updatedAt", { ascending: false, nullsFirst: false });}+/** @mcp read */export async function getAssemblyInstructionsForItem(client: SupabaseClient<Database>,itemId: string,@@ -6678,6 +6863,7 @@ export async function getAssemblyInstructionsForItem(* their model via item.modelUploadId. Conversion to viewer artifacts (GLB +* graph) is lazy — `modelState` tells the caller whether the model is ready,* convertible on demand, or unusable.+ * @mcp read*/export async function getModelForItem(client: SupabaseClient<Database>,@@ -6713,6 +6899,7 @@ export async function getModelForItem(};}+/** @mcp read */export async function getAssemblyInstructionSteps(client: SupabaseClient<Database>,assemblyInstructionId: string@@ -6724,6 +6911,7 @@ export async function getAssemblyInstructionSteps(.order("sortOrder", { ascending: true });}+/** @mcp upsert */export async function upsertAssemblyInstruction(client: SupabaseClient<Database>,data: {@@ -6763,6 +6951,7 @@ export async function upsertAssemblyInstruction(.single();}+/** @mcp update */export async function updateAssemblyInstructionStatus(client: SupabaseClient<Database>,id: string,@@ -6794,6 +6983,7 @@ export async function updateAssemblyInstructionStatus(* versions of one instruction share a group root: NULL rootInstructionId means* "I am the root", so the group root is `rootInstructionId ?? id` and siblings* are the rows whose id = root OR whose rootInstructionId = root.+ * @mcp read*/export async function getAssemblyInstructionVersions(client: SupabaseClient<Database>,@@ -6819,6 +7009,7 @@ export async function getAssemblyInstructionVersions(* the self-referential tree) and each step's live child rows (materials,* slides, tools). Non-atomic multi-insert — a partial copy leaves a deletable* Draft, matching the procedure/make-method copy precedents.+ * @mcp create*/export async function copyAssemblyInstructionAsVersion(client: SupabaseClient<Database>,@@ -6953,6 +7144,7 @@ export async function copyAssemblyInstructionAsVersion(* but only active job operations (status not Done/Canceled) on active jobs* (status not Completed/Closed/Cancelled). Method operations are intentionally* left untouched.+ * @mcp action*/export async function activateAssemblyInstructionVersion(client: SupabaseClient<Database>,@@ -7122,6 +7314,7 @@ export async function activateAssemblyInstructionVersion(return publish;}+/** @mcp delete */export async function deleteAssemblyInstruction(client: SupabaseClient<Database>,id: string@@ -7251,6 +7444,7 @@ async function invalidateAssemblyPlanCache(* convert can run. This is the user-facing escape hatch for stale caches* (e.g. after a geometry-service upgrade that changes nodeIds); routine* instruction deletion uses the narrower invalidateAssemblyPlanCache instead.+ * @mcp action destructive*/export async function invalidateAssemblyModelCache(client: SupabaseClient<Database>,@@ -7311,6 +7505,7 @@ export async function invalidateAssemblyModelCache(.eq("id", modelUploadId);}+/** @mcp upsert */export async function upsertAssemblyInstructionStep(client: SupabaseClient<Database>,data: {@@ -7426,6 +7621,7 @@ export async function upsertAssemblyInstructionStep(* `title` and the typed-step fields) so the 3D editor can autosave a drag or a* "Set view" click without touching the rest of the step. `camera: null` clears* the pose (return to auto-framing); omitting a field leaves it untouched.+ * @mcp update*/export async function updateAssemblyStepMotion(client: SupabaseClient<Database>,@@ -7454,6 +7650,7 @@ export async function updateAssemblyStepMotion(// Autosave target for the Details panel's Add/remove component controls: patches// only the step's assigned components, leaving the title/typed fields and motion// untouched.+/** @mcp update */export async function updateAssemblyStepComponents(client: SupabaseClient<Database>,data: {@@ -7476,6 +7673,7 @@ export async function updateAssemblyStepComponents(// Replaces a step's hidden list. The step's own components are stripped (and the// list deduped) by the assembly_step_strip_own_hidden_components trigger.+/** @mcp update */export async function updateAssemblyStepHiddenComponents(client: SupabaseClient<Database>,data: {@@ -7501,6 +7699,7 @@ export async function updateAssemblyStepHiddenComponents(// Sub-assembly staging: `parentStepId` = the later JOIN step this step is built// aside for (NULL = built in place). Which links are allowed is `joinTargets`,// the one rule the select and playback share.+/** @mcp update */export async function updateAssemblyStepJoin(client: SupabaseClient<Database>,data: {@@ -7555,6 +7754,7 @@ export async function updateAssemblyStepJoin(// ends up on exactly the target. `remove` (no target) strips them from EVERY// step, unassigning them entirely. One transaction: a half-applied move (added// to target but not removed from the source, or vice versa) would be a real bug.+/** @mcp action destructive */export async function reassignAssemblyStepComponents(db: Kysely<KyselyDatabase>,data: {@@ -7711,6 +7911,7 @@ async function getNextStepSortOrder(return (lastStep.data?.sortOrder ?? 0) + 1;}+/** @mcp update */export async function updateAssemblyInstructionStepStatus(client: SupabaseClient<Database>,id: string,@@ -7731,6 +7932,7 @@ export async function updateAssemblyInstructionStepStatus(.single();}+/** @mcp update */export async function updateAssemblyInstructionStepOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -7767,6 +7969,7 @@ export async function updateAssemblyInstructionStepOrder(});}+/** @mcp delete */export async function deleteAssemblyInstructionStep(client: SupabaseClient<Database>,id: string@@ -7774,6 +7977,7 @@ export async function deleteAssemblyInstructionStep(return client.from("assemblyInstructionStep").delete().eq("id", id);}+/** @mcp read */export async function getAssemblyInstructionStepSlides(client: SupabaseClient<Database>,stepIds: string[]@@ -7788,6 +7992,7 @@ export async function getAssemblyInstructionStepSlides(.order("sortOrder", { ascending: true });}+/** @mcp upsert */export async function upsertAssemblyInstructionStepSlide(client: SupabaseClient<Database>,slide:@@ -7829,6 +8034,7 @@ export async function upsertAssemblyInstructionStepSlide(.single();}+/** @mcp delete */export async function deleteAssemblyInstructionStepSlide(client: SupabaseClient<Database>,id: string@@ -7836,6 +8042,7 @@ export async function deleteAssemblyInstructionStepSlide(return client.from("assemblyInstructionStepSlide").delete().eq("id", id);}+/** @mcp read */export async function getAssemblyInstructionStepTools(client: SupabaseClient<Database>,stepIds: string[]@@ -7850,6 +8057,7 @@ export async function getAssemblyInstructionStepTools(.order("sortOrder", { ascending: true });}+/** @mcp upsert */export async function upsertAssemblyInstructionStepTool(client: SupabaseClient<Database>,data: {@@ -7908,6 +8116,7 @@ async function getNextStepToolSortOrder(return (last.data?.sortOrder ?? 0) + 1;}+/** @mcp delete */export async function deleteAssemblyInstructionStepTool(client: SupabaseClient<Database>,id: string@@ -7915,6 +8124,7 @@ export async function deleteAssemblyInstructionStepTool(return client.from("assemblyInstructionStepTool").delete().eq("id", id);}+/** @mcp read */export async function getAssemblyInstructionStepMaterials(client: SupabaseClient<Database>,stepIds: string[]@@ -7929,6 +8139,7 @@ export async function getAssemblyInstructionStepMaterials(.order("sortOrder", { ascending: true });}+/** @mcp upsert */export async function upsertAssemblyInstructionStepMaterial(client: SupabaseClient<Database>,data: {@@ -7987,6 +8198,7 @@ async function getNextStepMaterialSortOrder(return (last.data?.sortOrder ?? 0) + 1;}+/** @mcp update */export async function updateAssemblyInstructionStepMaterialOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -8013,6 +8225,7 @@ export async function updateAssemblyInstructionStepMaterialOrder(});}+/** @mcp delete */export async function deleteAssemblyInstructionStepMaterial(client: SupabaseClient<Database>,id: string@@ -8091,6 +8304,7 @@ function insertAssemblyStepMaterialSeeds(* assemblyComponentMapping) as step materials. Additive and best-effort:* existing rows are never updated or removed — manual quantities and* deliberate deletions survive — and failures never block the caller.+ * @mcp update*/export async function syncAssemblyStepMaterialsFromMappings(client: SupabaseClient<Database>,@@ -8184,6 +8398,7 @@ export async function syncAssemblyStepMaterialsFromMappings(return { created: insert.error ? 0 : seeds.length };}+/** @mcp read */export async function getAssemblyUnits(client: SupabaseClient<Database>,modelUploadId: string@@ -8195,6 +8410,7 @@ export async function getAssemblyUnits(.order("name");}+/** @mcp upsert */export async function upsertAssemblyUnit(client: SupabaseClient<Database>,data: {@@ -8237,6 +8453,7 @@ export async function upsertAssemblyUnit(.single();}+/** @mcp delete */export async function deleteAssemblyUnit(client: SupabaseClient<Database>,id: string@@ -8247,6 +8464,7 @@ export async function deleteAssemblyUnit(/*** Latest successful motion plan for a model. The editor uses plan.json to* auto-fill step motions and to generate draft step sequences.+ * @mcp read*/export async function getLatestAssemblyPlan(client: SupabaseClient<Database>,@@ -8267,6 +8485,7 @@ export async function getLatestAssemblyPlan(/*** Latest plan job in any state — used to tell "planning is running" apart* from "planning failed" and to avoid enqueueing duplicate plan runs.+ * @mcp read*/export async function getLatestAssemblyPlanJob(client: SupabaseClient<Database>,@@ -8289,6 +8508,7 @@ export async function getLatestAssemblyPlanJob(* it to Processing; without this the row only exists after event pickup, and* the post-action revalidation lands in that gap — nothing polls, and the run* (and its finished motions) never surface without a manual reload.+ * @mcp create*/export async function createAssemblyPlanJob(client: SupabaseClient<Database>,@@ -8317,6 +8537,7 @@ export async function createAssemblyPlanJob(* case and same-version format drift.) Absence flows into the existing* no-plan path, which triggers a fresh planner run and auto-generates steps* when it lands.+ * @mcp read*/export async function getAssemblyPlanJson(client: SupabaseClient<Database>,@@ -8343,7 +8564,10 @@ export async function getAssemblyPlanJson(// --- Model component ↔ engineering BOM mappings ---------------------------/** Mappings from distinct model components (geometry hashes) to BOM items. */+/**+ * Mappings from distinct model components (geometry hashes) to BOM items.+ * @mcp read+ */export async function getAssemblyComponentMappings(client: SupabaseClient<Database>,modelUploadId: string@@ -8354,6 +8578,7 @@ export async function getAssemblyComponentMappings(.eq("modelUploadId", modelUploadId);}+/** @mcp upsert */export async function upsertAssemblyComponentMapping(client: SupabaseClient<Database>,data: {@@ -8384,6 +8609,7 @@ export async function upsertAssemblyComponentMapping(.single();}+/** @mcp delete */export async function deleteAssemblyComponentMapping(client: SupabaseClient<Database>,id: string@@ -8406,6 +8632,7 @@ export type FlattenedBomMaterial = {* Make subassemblies (makeMethod → methodMaterial → materialMakeMethodId),* with quantities multiplied per level. Uses the Active make method, or* the first one when none is active.+ * @mcp read*/export async function getFlattenedBomMaterials(client: SupabaseClient<Database>,@@ -8475,6 +8702,7 @@ export type AutoMatchResult = {* strong name matches first (greedy, best score wins), then unique* quantity matches (a component appearing N times matched to the only BOM line* with quantity N) as low-confidence fallbacks. Existing mappings are kept.+ * @mcp action*/export async function autoMatchAssemblyComponents(client: SupabaseClient<Database>,@@ -8802,6 +9030,7 @@ export function planAssemblyStepMarkerSync(/*** 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).+ * @mcp read*/export function maxToolQuantityByItem(sourceTools: { itemId: string; quantity: number | null }[]@@ -8844,6 +9073,7 @@ export function buildAssemblyToolStepLinks(return rows;}+/** @mcp update destructive */export async function syncAssemblyInstructionToOperation(db: Kysely<KyselyDatabase>,args: {@@ -9308,6 +9538,7 @@ export async function syncAssemblyInstructionToOperation(* 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.+ * @mcp create destructive*/export async function generateAssemblyStepsFromPlan(client: SupabaseClient<Database>,@@ -9575,6 +9806,7 @@ export async function generateAssemblyStepsFromPlan(* Maps a DB step row to the viewer's step shape. JSONB columns are validated* defensively — `path` motions with invalid keyframes throw inside the viewer,* so anything that fails the schema falls back to a safe default.+ * @mcp action*/export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {const motion = motionSchema.safeParse(step.motion);@@ -9603,6 +9835,7 @@ export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {// Purchase order lines for a job's materials, scoped by item + location (not// jobId, since planning-generated POs aren't linked to the job). Flattened to// the procurement-status shape used by the BoM tree and the Materials table.+/** @mcp read */export async function getJobMaterialPurchaseOrderLines(client: SupabaseClient<Database>,materials: Array<{ jobMaterialItemId: string | null }>,@@ -9639,6 +9872,7 @@ export async function getJobMaterialPurchaseOrderLines(// Active jobs that produce these material items — the supply-side counterpart to// getJobMaterialPurchaseOrderLines. A manufactured material is "covered" when an// active job (its own itemId) is planned/in-flight at the same location.+/** @mcp read */export async function getJobMaterialSupplyJobLines(client: SupabaseClient<Database>,materials: Array<{ jobMaterialItemId: string | null }>,@@ -9696,6 +9930,7 @@ export async function getJobMaterialSupplyJobLines(** NOTE: mirrors apps/mes complete.tsx (non-tracked branch) + finishJobOperation; these should share* a service function eventually rather than duplicate the orchestration.+ * @mcp action*/export async function completeOperation(client: SupabaseClient<Database>,@@ -9866,6 +10101,9 @@ export async function completeOperation(* upload flow: PUT the file bytes to the returned `signedUrl`, then call* `documents_insertUploadedDocument` with the returned `path`,* `sourceDocument: "Job"`, and `sourceDocumentId: jobId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createJobDocumentUploadUrl(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex c34562380c..b10fabf9d9 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -1375,7 +1375,10 @@ function JobCompleteModal({.select("*").eq("attributes->>Job Make Method", makeMethod.data?.id!).eq("companyId", company.id)- .order("createdAt", { ascending: true });+ // Unit-axis order — see getTrackedEntitiesByMakeMethodId.+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });if (trackedEntities.data?.length) {const availableQuantity = trackedEntities.data.reduce((acc, curr) => {diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 612ff9f45d..34a657036b 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -94,6 +94,7 @@ export async function closePurchaseOrder(.single();}+/** @mcp update */export async function convertSupplierQuoteToOrder(client: SupabaseClient<Database>,payload: {@@ -111,6 +112,7 @@ export async function convertSupplierQuoteToOrder(});}+/** @mcp delete */export async function deletePurchaseOrder(client: SupabaseClient<Database>,purchaseOrderId: string@@ -118,6 +120,7 @@ export async function deletePurchaseOrder(return client.from("purchaseOrder").delete().eq("id", purchaseOrderId);}+/** @mcp delete */export async function deletePurchaseOrderLine(client: SupabaseClient<Database>,purchaseOrderLineId: string@@ -131,6 +134,7 @@ export async function deletePurchaseOrderLine(// Creates a new Draft PO header + delivery + payment via insertPurchaseOrder// and copies the source PO's lines into it. Receipt/invoice progress is// reset; only the order/line definition is duplicated.+/** @mcp create */export async function duplicatePurchaseOrder(client: SupabaseClient<Database>,{@@ -222,6 +226,7 @@ export async function duplicatePurchaseOrder(return insertResult;}+/** @mcp delete */export async function deleteSupplier(client: SupabaseClient<Database>,supplierId: string@@ -229,6 +234,7 @@ export async function deleteSupplier(return client.from("supplier").delete().eq("id", supplierId);}+/** @mcp delete */export async function deleteSupplierContact(client: SupabaseClient<Database>,supplierId: string,@@ -253,6 +259,7 @@ export async function deleteSupplierContact(return supplierContact;}+/** @mcp delete */export async function deleteSupplierLocation(client: SupabaseClient<Database>,supplierId: string,@@ -277,6 +284,7 @@ export async function deleteSupplierLocation(}}+/** @mcp delete */export async function deleteSupplierBankAccount(client: SupabaseClient<Database>,id: string@@ -284,6 +292,7 @@ export async function deleteSupplierBankAccount(return client.from("supplierBankAccount").delete().eq("id", id);}+/** @mcp read */export async function getSupplierBankAccounts(client: SupabaseClient<Database>,supplierId: string@@ -295,6 +304,7 @@ export async function getSupplierBankAccounts(.order("name");}+/** @mcp upsert */export async function upsertSupplierBankAccount(db: Kysely<KyselyDatabase>,bankAccount:@@ -335,6 +345,7 @@ export async function upsertSupplierBankAccount(.executeTakeFirstOrThrow();}+/** @mcp delete */export async function deleteSupplierProcess(client: SupabaseClient<Database>,supplierProcessId: string@@ -342,6 +353,7 @@ export async function deleteSupplierProcess(return client.from("supplierProcess").delete().eq("id", supplierProcessId);}+/** @mcp delete */export async function deleteSupplierQuote(client: SupabaseClient<Database>,supplierQuoteId: string@@ -349,6 +361,7 @@ export async function deleteSupplierQuote(return client.from("supplierQuote").delete().eq("id", supplierQuoteId);}+/** @mcp delete */export async function deleteSupplierQuoteLine(client: SupabaseClient<Database>,id: string@@ -356,6 +369,7 @@ export async function deleteSupplierQuoteLine(return client.from("supplierQuoteLine").delete().eq("id", id);}+/** @mcp delete */export async function deleteSupplierType(client: SupabaseClient<Database>,supplierTypeId: string@@ -363,6 +377,7 @@ export async function deleteSupplierType(return client.from("supplierType").delete().eq("id", supplierTypeId);}+/** @mcp read */export async function getPurchaseOrder(client: SupabaseClient<Database>,purchaseOrderId: string@@ -374,6 +389,7 @@ export async function getPurchaseOrder(.single();}+/** @mcp update */export async function finalizeSupplierQuote(client: SupabaseClient<Database>,supplierQuoteId: string,@@ -395,6 +411,7 @@ export async function finalizeSupplierQuote(return { data: null, error: null };}+/** @mcp read */export async function getPurchaseOrders(client: SupabaseClient<Database>,companyId: string,@@ -426,6 +443,7 @@ export async function getPurchaseOrders(return query;}+/** @mcp read */export async function getPurchaseOrderDelivery(client: SupabaseClient<Database>,purchaseOrderId: string@@ -437,6 +455,7 @@ export async function getPurchaseOrderDelivery(.single();}+/** @mcp read */export async function getPurchaseOrderLocations(client: SupabaseClient<Database>,purchaseOrderId: string@@ -448,6 +467,7 @@ export async function getPurchaseOrderLocations(.single();}+/** @mcp read */export async function getPurchaseOrderPayment(client: SupabaseClient<Database>,purchaseOrderId: string@@ -459,6 +479,7 @@ export async function getPurchaseOrderPayment(.single();}+/** @mcp read */export async function getPurchaseOrderLines(client: SupabaseClient<Database>,purchaseOrderId: string@@ -471,6 +492,7 @@ export async function getPurchaseOrderLines(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getPurchaseOrderLine(client: SupabaseClient<Database>,purchaseOrderLineId: string@@ -482,6 +504,7 @@ export async function getPurchaseOrderLine(.single();}+/** @mcp read */export async function getPurchaseOrderSuppliers(client: SupabaseClient<Database>,companyId: string@@ -493,6 +516,7 @@ export async function getPurchaseOrderSuppliers(.order("name");}+/** @mcp read */export async function getPurchasingDocumentsAssignedToMe(client: SupabaseClient<Database>,userId: string,@@ -534,6 +558,7 @@ export async function getPurchasingDocumentsAssignedToMe(return merged;}+/** @mcp read */export async function getPurchasingPlanning(client: SupabaseClient<Database>,locationId: string,@@ -568,6 +593,7 @@ export async function getPurchasingPlanning(return query;}+/** @mcp read */export async function getPurchasingTerms(client: SupabaseClient<Database>,companyId: string@@ -579,6 +605,7 @@ export async function getPurchasingTerms(.single();}+/** @mcp read */export async function getSupplier(client: SupabaseClient<Database>,supplierId: string@@ -586,6 +613,7 @@ export async function getSupplier(return client.from("suppliers").select("*").eq("id", supplierId).single();}+/** @mcp read */export async function getSupplierContact(client: SupabaseClient<Database>,supplierContactId: string,@@ -601,6 +629,7 @@ export async function getSupplierContact(return query.single();}+/** @mcp read */export async function getSupplierContacts(client: SupabaseClient<Database>,supplierId: string@@ -613,6 +642,7 @@ export async function getSupplierContacts(.eq("supplierId", supplierId);}+/** @mcp read */export async function getSupplierInteraction(client: SupabaseClient<Database>,opportunityId: string | null@@ -654,6 +684,7 @@ export async function getSupplierInteraction(}>;}+/** @mcp read */export async function getSupplierInteractionDocuments(client: SupabaseClient<Database>,companyId: string,@@ -676,6 +707,7 @@ export async function getSupplierInteractionDocuments(}));}+/** @mcp read */export async function getSupplierInteractionLineDocuments(client: SupabaseClient<Database>,companyId: string,@@ -698,6 +730,7 @@ export async function getSupplierInteractionLineDocuments(}));}+/** @mcp read */export async function getSupplierLocations(client: SupabaseClient<Database>,supplierId: string@@ -710,6 +743,7 @@ export async function getSupplierLocations(.eq("supplierId", supplierId);}+/** @mcp read */export async function getSupplierLocation(client: SupabaseClient<Database>,supplierContactId: string@@ -723,6 +757,7 @@ export async function getSupplierLocation(.single();}+/** @mcp read */export async function getSupplierPayment(client: SupabaseClient<Database>,supplierId: string@@ -734,6 +769,7 @@ export async function getSupplierPayment(.single();}+/** @mcp read */export async function getSupplierProcessById(client: SupabaseClient<Database>,supplierProcessId: string@@ -745,6 +781,7 @@ export async function getSupplierProcessById(.single();}+/** @mcp read */export async function getSupplierProcessesByProcess(client: SupabaseClient<Database>,processId: string@@ -755,6 +792,7 @@ export async function getSupplierProcessesByProcess(.eq("processId", processId);}+/** @mcp read */export async function getSupplierProcessesBySupplier(client: SupabaseClient<Database>,supplierId: string@@ -765,6 +803,7 @@ export async function getSupplierProcessesBySupplier(.eq("supplierId", supplierId);}+/** @mcp read */export async function getSupplierQuote(client: SupabaseClient<Database>,supplierQuoteId: string@@ -776,6 +815,7 @@ export async function getSupplierQuote(.single();}+/** @mcp read */export async function getSupplierQuoteByInteractionId(client: SupabaseClient<Database>,interactionId: string@@ -787,6 +827,7 @@ export async function getSupplierQuoteByInteractionId(.single();}+/** @mcp read */export async function getSupplierQuoteByExternalLinkId(client: SupabaseClient<Database>,externalLinkId: string@@ -798,6 +839,7 @@ export async function getSupplierQuoteByExternalLinkId(.single();}+/** @mcp read */export async function getSupplierQuotes(client: SupabaseClient<Database>,companyId: string,@@ -822,6 +864,7 @@ export async function getSupplierQuotes(return query;}+/** @mcp read */export async function getSupplierQuoteLine(client: SupabaseClient<Database>,supplierQuoteLineId: string@@ -833,6 +876,7 @@ export async function getSupplierQuoteLine(.single();}+/** @mcp read */export async function getSupplierQuoteLines(client: SupabaseClient<Database>,supplierQuoteId: string@@ -844,6 +888,7 @@ export async function getSupplierQuoteLines(.order("sortOrder", { ascending: true });}+/** @mcp read */export async function getSupplierQuoteLinePrices(client: SupabaseClient<Database>,supplierQuoteLineId: string@@ -854,6 +899,7 @@ export async function getSupplierQuoteLinePrices(.eq("supplierQuoteLineId", supplierQuoteLineId);}+/** @mcp read */export async function getSupplierQuoteLinePricesByQuoteId(client: SupabaseClient<Database>,supplierQuoteId: string@@ -865,6 +911,7 @@ export async function getSupplierQuoteLinePricesByQuoteId(.order("supplierQuoteLineId", { ascending: true });}+/** @mcp read */export async function getSupplierQuotesList(client: SupabaseClient<Database>,companyId: string@@ -877,6 +924,7 @@ export async function getSupplierQuotesList();}+/** @mcp read */export async function getSupplierShipping(client: SupabaseClient<Database>,supplierId: string@@ -895,6 +943,7 @@ export async function getSupplierShipping(// (supplierId, companyId), which supabase-js's type generator marks `isOneToOne:// false` even though supplierId alone is the real PK, so a reverse embed would type// (and risk behaving) as an array instead of a single object.+/** @mcp read */export async function getSupplierReportContacts(client: SupabaseClient<Database>,companyId: string,@@ -929,6 +978,7 @@ export async function getSupplierReportContacts(]);}+/** @mcp read */export async function getSuppliers(client: SupabaseClient<Database>,companyId: string,@@ -966,6 +1016,7 @@ export async function getSuppliers(return query;}+/** @mcp read */export async function getSuppliersList(client: SupabaseClient<Database>,companyId: string@@ -978,6 +1029,7 @@ export async function getSuppliersList();}+/** @mcp read */export async function getSupplierType(client: SupabaseClient<Database>,supplierTypeId: string@@ -989,6 +1041,7 @@ export async function getSupplierType(.single();}+/** @mcp read */export async function getSupplierTypes(client: SupabaseClient<Database>,companyId: string,@@ -1012,6 +1065,7 @@ export async function getSupplierTypes(return query;}+/** @mcp read */export async function getSupplierTypesList(client: SupabaseClient<Database>,companyId: string@@ -1023,6 +1077,7 @@ export async function getSupplierTypesList(.order("name");}+/** @mcp create */export async function insertSupplier(client: SupabaseClient<Database>,supplier: Omit<z.infer<typeof supplierValidator>, "id"> & {@@ -1034,6 +1089,7 @@ export async function insertSupplier(return client.from("supplier").insert([supplier]).select("*").single();}+/** @mcp create */export async function insertSupplierContact(client: SupabaseClient<Database>,supplierContact: {@@ -1092,6 +1148,7 @@ export async function insertSupplierInteraction(.single();}+/** @mcp create */export async function insertSupplierLocation(client: SupabaseClient<Database>,supplierLocation: {@@ -1140,6 +1197,7 @@ export async function insertSupplierLocation(.single();}+/** @mcp update */export async function finalizePurchaseOrder(client: SupabaseClient<Database>,purchaseOrderId: string,@@ -1172,6 +1230,7 @@ export async function finalizePurchaseOrder(.eq("id", purchaseOrderId);}+/** @mcp update */export async function sendSupplierQuote(client: SupabaseClient<Database>,supplierQuoteId: string,@@ -1208,6 +1267,7 @@ export async function updatePurchaseOrderStatusLegacy(.eq("id", purchaseOrder.id);}+/** @mcp update */export async function updatePurchaseOrderExchangeRate(client: SupabaseClient<Database>,data: {@@ -1224,6 +1284,7 @@ export async function updatePurchaseOrderExchangeRate(return client.from("purchaseOrder").update(update).eq("id", update.id);}+/** @mcp update destructive */export async function updatePurchaseOrderFavorite(client: SupabaseClient<Database>,args: {@@ -1246,6 +1307,7 @@ export async function updatePurchaseOrderFavorite(}}+/** @mcp update */export async function updatePurchaseOrderStatus(client: SupabaseClient<Database>,update: {@@ -1264,6 +1326,7 @@ export async function updatePurchaseOrderStatus(* Compare-and-swap: the increment and the eligibility conditions are both in* SQL, so concurrent requests can't share a revision number and an ineligible* order matches no rows. Returns rows updated — 0 means it was not eligible.+ * @mcp action*/export async function reopenPurchaseOrderAsRevision(db: Kysely<KyselyDatabase>,@@ -1307,6 +1370,7 @@ export async function updateSupplierAccounting(.eq("id", supplierAccounting.id);}+/** @mcp update */export async function updateSupplierContact(client: SupabaseClient<Database>,supplierContact: {@@ -1337,6 +1401,7 @@ export async function updateSupplierContact(.single();}+/** @mcp update */export async function updateSupplierLocation(client: SupabaseClient<Database>,supplierLocation: {@@ -1374,6 +1439,7 @@ export async function updateSupplierLocation(.single();}+/** @mcp update */export async function updateSupplierPayment(client: SupabaseClient<Database>,supplierPayment: z.infer<typeof supplierPaymentValidator> & {@@ -1387,6 +1453,7 @@ export async function updateSupplierPayment(.eq("supplierId", supplierPayment.supplierId);}+/** @mcp update */export async function updateSupplierQuoteExchangeRate(client: SupabaseClient<Database>,data: {@@ -1425,6 +1492,7 @@ export async function updateSupplierQuoteFavorite(}}+/** @mcp update */export async function updateSupplierQuoteStatus(client: SupabaseClient<Database>,update: {@@ -1437,6 +1505,7 @@ export async function updateSupplierQuoteStatus(return client.from("supplierQuote").update(update).eq("id", update.id);}+/** @mcp update */export async function updateSupplierShipping(client: SupabaseClient<Database>,supplierShipping: z.infer<typeof supplierShippingValidator> & {@@ -1450,6 +1519,7 @@ export async function updateSupplierShipping(.eq("supplierId", supplierShipping.supplierId);}+/** @mcp read */export async function getSupplierTax(client: SupabaseClient<Database>,supplierId: string@@ -1461,6 +1531,7 @@ export async function getSupplierTax(.maybeSingle();}+/** @mcp update */export async function updateSupplierTax(client: SupabaseClient<Database>,supplierTax: z.infer<typeof supplierTaxValidator> & {@@ -1476,6 +1547,7 @@ export async function updateSupplierTax(.eq("companyId", supplierTax.companyId);}+/** @mcp create */export async function insertPurchaseOrder(client: SupabaseClient<Database>,input: {@@ -1627,6 +1699,7 @@ export async function insertPurchaseOrder(return { data: { id: orderId, purchaseOrderId }, error: null };}+/** @mcp update */export async function updatePurchaseOrder(client: SupabaseClient<Database>,input: {@@ -1684,7 +1757,10 @@ export async function updatePurchaseOrder(.single();}-/** @deprecated Use insertPurchaseOrder for new orders, updatePurchaseOrder for existing orders */+/**+ * @deprecated Use insertPurchaseOrder for new orders, updatePurchaseOrder for existing orders+ * @mcp upsert+ */export async function upsertPurchaseOrder(client: SupabaseClient<Database>,purchaseOrder:@@ -1822,6 +1898,7 @@ export async function upsertPurchaseOrder(return order;}+/** @mcp upsert */export async function upsertPurchaseOrderDelivery(client: SupabaseClient<Database>,purchaseOrderDelivery:@@ -1892,6 +1969,7 @@ function normalizePurchaseOrderLineReferences<return { ...line, itemId: null, accountId: null, assetId: null };}+/** @mcp upsert */export async function upsertPurchaseOrderLine(client: SupabaseClient<Database>,purchaseOrderLine:@@ -1934,6 +2012,7 @@ export async function upsertPurchaseOrderLine(.single();}+/** @mcp update */export async function updatePurchaseOrderLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -1964,6 +2043,7 @@ export async function updatePurchaseOrderLineOrder(* received quantity is already fully invoiced gets `invoicedComplete` too —* otherwise the order could never reach Completed. Reopening restores the* natural rule (fully invoiced = ordered quantity).+ * @mcp action*/export async function shortClosePurchaseOrderLine(db: Kysely<KyselyDatabase>,@@ -2035,6 +2115,7 @@ export async function shortClosePurchaseOrderLine(});}+/** @mcp upsert */export async function upsertPurchaseOrderPayment(client: SupabaseClient<Database>,purchaseOrderPayment:@@ -2063,6 +2144,7 @@ export async function upsertPurchaseOrderPayment(.single();}+/** @mcp upsert */export async function upsertSupplier(client: SupabaseClient<Database>,supplier:@@ -2095,6 +2177,7 @@ export async function upsertSupplier(.single();}+/** @mcp upsert */export async function upsertSupplierProcess(client: SupabaseClient<Database>,supplierProcess:@@ -2124,6 +2207,7 @@ export async function upsertSupplierProcess(.single();}+/** @mcp create */export async function insertSupplierQuote(client: SupabaseClient<Database>,input: {@@ -2240,6 +2324,7 @@ export async function insertSupplierQuote(return { data: { id: createdQuoteId, supplierQuoteId }, error: null };}+/** @mcp update */export async function updateSupplierQuote(client: SupabaseClient<Database>,input: {@@ -2438,6 +2523,7 @@ export async function upsertSupplierQuote(}}+/** @mcp upsert */export async function upsertSupplierQuoteLine(client: SupabaseClient<Database>,supplierQuoteLine:@@ -2484,6 +2570,7 @@ export async function upsertSupplierQuoteLine(.single();}+/** @mcp update */export async function updateSupplierQuoteLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -2501,6 +2588,7 @@ export async function updateSupplierQuoteLineOrder(});}+/** @mcp upsert */export async function upsertSupplierType(client: SupabaseClient<Database>,supplierType:@@ -2533,6 +2621,7 @@ export async function upsertSupplierType(// PURCHASING RFQ FUNCTIONS// ============================================================+/** @mcp delete */export async function deletePurchasingRFQ(client: SupabaseClient<Database>,purchasingRfqId: string@@ -2540,6 +2629,7 @@ export async function deletePurchasingRFQ(return client.from("purchasingRfq").delete().eq("id", purchasingRfqId);}+/** @mcp delete */export async function deletePurchasingRFQLine(client: SupabaseClient<Database>,purchasingRfqLineId: string@@ -2550,6 +2640,7 @@ export async function deletePurchasingRFQLine(.eq("id", purchasingRfqLineId);}+/** @mcp read */export async function getPurchasingRFQ(client: SupabaseClient<Database>,id: string@@ -2557,6 +2648,7 @@ export async function getPurchasingRFQ(return client.from("purchasingRfqs").select("*").eq("id", id).single();}+/** @mcp read */export async function getPurchasingRFQs(client: SupabaseClient<Database>,companyId: string,@@ -2579,6 +2671,7 @@ export async function getPurchasingRFQs(return query;}+/** @mcp read */export async function getPurchasingRFQLine(client: SupabaseClient<Database>,lineId: string@@ -2590,6 +2683,7 @@ export async function getPurchasingRFQLine(.single();}+/** @mcp read */export async function getPurchasingRFQLines(client: SupabaseClient<Database>,purchasingRfqId: string@@ -2615,6 +2709,7 @@ type LinkedSupplierQuote = {| null;};+/** @mcp read */export async function getPurchasingRFQSuppliers(client: SupabaseClient<Database>,purchasingRfqId: string@@ -2628,6 +2723,7 @@ export async function getPurchasingRFQSuppliers(.eq("purchasingRfqId", purchasingRfqId);}+/** @mcp create */export async function insertPurchasingRFQ(client: SupabaseClient<Database>,input: {@@ -2725,7 +2821,10 @@ export async function updatePurchasingRFQ(.single();}-/** @deprecated Use insertPurchasingRFQ for new RFQs, updatePurchasingRFQ for existing RFQs */+/**+ * @deprecated Use insertPurchasingRFQ for new RFQs, updatePurchasingRFQ for existing RFQs+ * @mcp upsert+ */export async function upsertPurchasingRFQ(client: SupabaseClient<Database>,purchasingRfq: {@@ -2757,6 +2856,7 @@ export async function upsertPurchasingRFQ(.single();}+/** @mcp upsert */export async function upsertPurchasingRFQLine(client: SupabaseClient<Database>,purchasingRfqLine:@@ -2803,6 +2903,7 @@ export async function upsertPurchasingRFQLine(.single();}+/** @mcp update */export async function updatePurchasingRFQLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -2820,6 +2921,7 @@ export async function updatePurchasingRFQLineOrder(});}+/** @mcp upsert destructive */export async function upsertPurchasingRFQSuppliers(client: SupabaseClient<Database>,purchasingRfqId: string,@@ -2851,6 +2953,7 @@ export async function upsertPurchasingRFQSuppliers(.select("id");}+/** @mcp update */export async function updatePurchasingRFQStatus(client: SupabaseClient<Database>,args: {@@ -2873,6 +2976,7 @@ export async function updatePurchasingRFQStatus(.single();}+/** @mcp read */export async function getLinkedSupplierQuotes(client: SupabaseClient<Database>,purchasingRfqId: string@@ -2889,6 +2993,7 @@ export async function getLinkedSupplierQuotes(.eq("purchasingRfqId", purchasingRfqId);}+/** @mcp read */export async function getLinkedPurchasingRfqs(client: SupabaseClient<Database>,supplierQuoteId: string@@ -2904,6 +3009,7 @@ export async function getLinkedPurchasingRfqs(.eq("supplierQuoteId", supplierQuoteId);}+/** @mcp read */export async function getLinkedPurchasingRfqsForInteraction(client: SupabaseClient<Database>,supplierInteractionId: string@@ -2933,6 +3039,7 @@ export async function getLinkedPurchasingRfqsForInteraction(}// Get sibling quotes (quotes sharing any RFQ with current quote)+/** @mcp read */export async function getSiblingQuotesForQuote(client: SupabaseClient<Database>,supplierQuoteId: string@@ -2967,6 +3074,7 @@ export async function getSiblingQuotesForQuote(}// Direct Order→RFQ lookup (more efficient than going through interaction)+/** @mcp read */export async function getLinkedPurchasingRfqsForOrder(client: SupabaseClient<Database>,purchaseOrderId: string@@ -2982,6 +3090,7 @@ export async function getLinkedPurchasingRfqsForOrder(.eq("purchaseOrderId", purchaseOrderId);}+/** @mcp read */export async function getSupplierQuotesForComparison(client: SupabaseClient<Database>,purchasingRfqId: string@@ -3047,6 +3156,7 @@ export async function getSupplierQuotesForComparison(}// Get RFQ suppliers with their supplier info+/** @mcp read */export async function getPurchasingRFQSuppliersWithLinks(client: SupabaseClient<Database>,purchasingRfqId: string@@ -3065,6 +3175,7 @@ export type PoDefaultAttachment = {path: string;};+/** @mcp read */export async function getDefaultAttachmentsForPO(client: SupabaseClient<Database>,args: {@@ -3114,6 +3225,7 @@ export async function getDefaultAttachmentsForPO(// ─── Purchase Return Orders (Supplier Returns) ───+/** @mcp read */export async function getPurchaseReturnOrders(client: SupabaseClient<Database>,companyId: string,@@ -3151,6 +3263,7 @@ export async function getPurchaseReturnOrders(return query;}+/** @mcp read */export async function getPurchaseReturnOrder(client: SupabaseClient<Database>,purchaseReturnOrderId: string@@ -3162,6 +3275,7 @@ export async function getPurchaseReturnOrder(.single();}+/** @mcp read */export async function getPurchaseReturnOrderLines(client: SupabaseClient<Database>,purchaseReturnOrderId: string,@@ -3177,6 +3291,7 @@ export async function getPurchaseReturnOrderLines(.order("lineNumber");}+/** @mcp read */export async function getPurchaseReturnOrderLine(client: SupabaseClient<Database>,lineId: string@@ -3188,6 +3303,7 @@ export async function getPurchaseReturnOrderLine(.single();}+/** @mcp read */export async function getPurchaseReturnOrderLineTrackedEntities(client: SupabaseClient<Database>,lineIds: string[]@@ -3198,6 +3314,7 @@ export async function getPurchaseReturnOrderLineTrackedEntities(.in("purchaseReturnOrderLineId", lineIds);}+/** @mcp create */export async function insertPurchaseReturnOrder(client: SupabaseClient<Database>,input: {@@ -3321,6 +3438,7 @@ export async function updatePurchaseReturnOrder(.single();}+/** @mcp upsert */export async function upsertPurchaseReturnOrderLine(client: SupabaseClient<Database>,line:@@ -3371,6 +3489,7 @@ export async function upsertPurchaseReturnOrderLine(.single();}+/** @mcp delete */export async function deletePurchaseReturnOrder(client: SupabaseClient<Database>,purchaseReturnOrderId: string@@ -3381,6 +3500,7 @@ export async function deletePurchaseReturnOrder(.eq("id", purchaseReturnOrderId);}+/** @mcp delete */export async function deletePurchaseReturnOrderLine(client: SupabaseClient<Database>,lineId: string@@ -3388,6 +3508,7 @@ export async function deletePurchaseReturnOrderLine(return client.from("purchaseReturnOrderLine").delete().eq("id", lineId);}+/** @mcp update destructive */export async function setPurchaseReturnOrderLineTrackedEntities(client: SupabaseClient<Database>,lineId: string,@@ -3414,6 +3535,7 @@ export async function setPurchaseReturnOrderLineTrackedEntities();}+/** @mcp read */export async function getPurchaseReturnOrderShipments(client: SupabaseClient<Database>,purchaseReturnOrderId: string,@@ -3428,6 +3550,7 @@ export async function getPurchaseReturnOrderShipments(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getPurchaseReturnOrderCredits(client: SupabaseClient<Database>,purchaseReturnOrderId: string,@@ -3441,6 +3564,7 @@ export async function getPurchaseReturnOrderCredits(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getPurchaseReturnOrderIssues(client: SupabaseClient<Database>,purchaseReturnOrderId: string,@@ -3461,6 +3585,7 @@ export async function getPurchaseReturnOrderIssues(* row-locked so two concurrent confirms against the same source line* serialize, and the aggregates are re-read under that lock* (replaceInvoiceSettlements pattern).+ * @mcp action*/export async function confirmPurchaseReturnOrder(db: Kysely<KyselyDatabase>,@@ -3686,6 +3811,7 @@ export async function confirmPurchaseReturnOrder(* No cap is released: a Draft return still counts as authorized against its* source lines (the confirm check excludes only "Cancelled"), so the* authorization it holds is unchanged — only its editability.+ * @mcp action*/export async function reopenPurchaseReturnOrder(db: Kysely<KyselyDatabase>,@@ -3745,6 +3871,7 @@ export async function reopenPurchaseReturnOrder(* a shipment posting racing this cancel serializes: whichever commits first* wins, and the loser sees the new state instead of producing a Cancelled* order with shipped stock (whose caps and Issue coverage then vanish).+ * @mcp action*/export async function cancelPurchaseReturnOrder(db: Kysely<KyselyDatabase>,@@ -3809,6 +3936,7 @@ export async function cancelPurchaseReturnOrder(* shortClosePurchaseOrderLine mechanic. The header status is derived from the* lines afterwards, so short-closing the last open line completes the return* (there is no separate manual Complete action, mirroring the Purchase Order).+ * @mcp action*/export async function shortClosePurchaseReturnOrderLine(db: Kysely<KyselyDatabase>,@@ -3900,6 +4028,7 @@ export async function shortClosePurchaseReturnOrderLine(* receipt" modal stays responsive when a supplier has thousands of receipt* lines. Each row carries `totalCount` — the size of the full returnable set* before limit/offset — so the UI can page through the rest.+ * @mcp read*/export async function getReturnableLinesForSupplier(client: SupabaseClient<Database>,@@ -3927,6 +4056,7 @@ export async function getReturnableLinesForSupplier(* that were received from this supplier. Provenance is the Receipt attribute* (written by the receipt tracking route) resolved to the receipt's supplier* — no code writes a Supplier attribute onto tracked entities.+ * @mcp read*/export async function getReturnableEntitiesForSupplier(client: SupabaseClient<Database>,@@ -3960,6 +4090,7 @@ export async function getReturnableEntitiesForSupplier(* The Available tracked entities that came in on ONE receipt line, for the item.* Used to pre-select the batch/serial when a return line is added from a specific* receipt — provenance is the `Receipt Line` attribute stamped at receipt.+ * @mcp read*/export async function getReturnableEntitiesForReceiptLine(client: SupabaseClient<Database>,@@ -3980,6 +4111,7 @@ export async function getReturnableEntitiesForReceiptLine(* Per-line creditable pool = shipped − already credited. Draft memos count* against the pool (two Drafts must not double-credit); the VIEW's displayed* quantityCredited still derives from Posted memos only.+ * @mcp read*/export async function getCreditableQuantitiesForPurchaseReturn(client: SupabaseClient<Database>,@@ -4052,6 +4184,8 @@ export async function getCreditableQuantitiesForPurchaseReturn(* `getCompanyHasOpenCredits` select supplier memos with* `direction = "Debit"`, so a Credit-direction memo here is also invisible to* "Apply Credit" on a supplier invoice.+ * @mcp create+ * @mcp audit companyGroupId, createdBy, updatedBy, userId*/export async function createPurchaseReturnOrderCredit(client: SupabaseClient<Database>,@@ -4236,6 +4370,7 @@ export async function createPurchaseReturnOrderCredit(* Create Replacement Purchase Order: a draft PO from the return lines,* priced from the linked PO line (purchase-UOM price + conversion factor* copied) else the supplierPart default. One replacement per return.+ * @mcp create*/export async function createReplacementPurchaseOrder(client: SupabaseClient<Database>,@@ -4418,6 +4553,9 @@ export async function createReplacementPurchaseOrder(* the returned `signedUrl`, then call `documents_insertUploadedDocument` with the* returned `path`, the document type as `sourceDocument`, and the document id as* `sourceDocumentId`. The storage folder is scoped by `interactionId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createSupplierInteractionDocumentUploadUrl(client: SupabaseClient<Database>,@@ -4436,6 +4574,9 @@ export async function createSupplierInteractionDocumentUploadUrl(* of the two-step upload flow: PUT the file bytes to the returned `signedUrl`, then* call `documents_insertUploadedDocument` with the returned `path`, the line's* document type as `sourceDocument`, and the line id as `sourceDocumentId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createSupplierInteractionLineDocumentUploadUrl(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex aa9c941409..33d9ef19b8 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -39,6 +39,7 @@ import type {riskSource,riskStatus} from "./quality.models";+/** @mcp action */export async function activateGauge(client: SupabaseClient<Database>,gaugeId: string@@ -49,6 +50,7 @@ export async function activateGauge(.eq("id", gaugeId);}+/** @mcp action */export async function deactivateGauge(client: SupabaseClient<Database>,gaugeId: string@@ -59,6 +61,7 @@ export async function deactivateGauge(.eq("id", gaugeId);}+/** @mcp delete */export async function deleteGauge(client: SupabaseClient<Database>,gaugeId: string@@ -66,6 +69,7 @@ export async function deleteGauge(return client.from("gauges").delete().eq("id", gaugeId);}+/** @mcp delete */export async function deleteGaugeCalibrationRecord(client: SupabaseClient<Database>,gaugeCalibrationRecordId: string@@ -76,6 +80,7 @@ export async function deleteGaugeCalibrationRecord(.eq("id", gaugeCalibrationRecordId);}+/** @mcp delete */export async function deleteGaugeType(client: SupabaseClient<Database>,gaugeTypeId: string@@ -83,6 +88,7 @@ export async function deleteGaugeType(return client.from("gaugeType").delete().eq("id", gaugeTypeId);}+/** @mcp delete */export async function deleteIssue(client: SupabaseClient<Database>,nonConformanceId: string@@ -90,6 +96,7 @@ export async function deleteIssue(return client.from("nonConformance").delete().eq("id", nonConformanceId);}+/** @mcp delete */export async function deleteIssueAssociation(client: SupabaseClient<Database>,type: string,@@ -189,6 +196,7 @@ export async function deleteIssueAssociation(}}+/** @mcp delete */export async function deleteIssueType(client: SupabaseClient<Database>,nonConformanceTypeId: string@@ -199,6 +207,7 @@ export async function deleteIssueType(.eq("id", nonConformanceTypeId);}+/** @mcp delete */export async function deleteIssueWorkflow(client: SupabaseClient<Database>,nonConformanceWorkflowId: string@@ -209,6 +218,7 @@ export async function deleteIssueWorkflow(.eq("id", nonConformanceWorkflowId);}+/** @mcp delete */export async function deleteRequiredAction(client: SupabaseClient<Database>,requiredActionId: string@@ -219,6 +229,7 @@ export async function deleteRequiredAction(.eq("id", requiredActionId);}+/** @mcp delete */export async function deleteQualityDocument(client: SupabaseClient<Database>,qualityDocumentId: string@@ -238,6 +249,7 @@ export async function deleteQualityDocumentStep(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteRisk(client: SupabaseClient<Database>,riskId: string@@ -245,6 +257,7 @@ export async function deleteRisk(return client.from("riskRegister").delete().eq("id", riskId);}+/** @mcp read */export async function getIssueFromExternalLink(client: SupabaseClient<Database>,id: string@@ -256,6 +269,7 @@ export async function getIssueFromExternalLink(.single();}+/** @mcp read */export async function getGauge(client: SupabaseClient<Database>,gaugeId: string@@ -263,6 +277,7 @@ export async function getGauge(return client.from("gauges").select("*").eq("id", gaugeId).single();}+/** @mcp read */export async function getGauges(client: SupabaseClient<Database>,companyId: string,@@ -288,6 +303,7 @@ export async function getGauges(return query;}+/** @mcp read */export async function getGaugesList(client: SupabaseClient<Database>,companyId: string@@ -302,6 +318,7 @@ export async function getGaugesList();}+/** @mcp read */export async function getGaugeCalibrationRecord(client: SupabaseClient<Database>,id: string@@ -313,6 +330,7 @@ export async function getGaugeCalibrationRecord(.single();}+/** @mcp read */export async function getGaugeCalibrationRecords(client: SupabaseClient<Database>,companyId: string,@@ -339,6 +357,7 @@ export async function getGaugeCalibrationRecords(return query;}+/** @mcp read */export async function getGaugeCalibrationRecordsByGaugeId(client: SupabaseClient<Database>,gaugeId: string@@ -350,6 +369,7 @@ export async function getGaugeCalibrationRecordsByGaugeId(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getGaugeTypesList(client: SupabaseClient<Database>,companyId: string@@ -361,6 +381,7 @@ export async function getGaugeTypesList(.order("name");}+/** @mcp read */export async function getGaugeType(client: SupabaseClient<Database>,gaugeTypeId: string@@ -368,6 +389,7 @@ export async function getGaugeType(return client.from("gaugeType").select("*").eq("id", gaugeTypeId).single();}+/** @mcp read */export async function getGaugeTypes(client: SupabaseClient<Database>,companyId: string,@@ -391,6 +413,7 @@ export async function getGaugeTypes(return query;}+/** @mcp read */export async function getIssue(client: SupabaseClient<Database>,nonConformanceId: string@@ -402,6 +425,7 @@ export async function getIssue(.single();}+/** @mcp read */export async function getIssues(client: SupabaseClient<Database>,companyId: string,@@ -427,6 +451,7 @@ export async function getIssues(return query;}+/** @mcp read */export async function getIssueWorkflow(client: SupabaseClient<Database>,nonConformanceWorkflowId: string@@ -438,6 +463,7 @@ export async function getIssueWorkflow(.single();}+/** @mcp read */export async function getIssueActionTasks(client: SupabaseClient<Database>,id: string,@@ -501,6 +527,7 @@ export async function getIssueActionTasks(};}+/** @mcp read */export async function getIssueApprovalTasks(client: SupabaseClient<Database>,id: string,@@ -514,6 +541,7 @@ export async function getIssueApprovalTasks(.order("approvalType", { ascending: true });}+/** @mcp read */export async function getIssueItems(client: SupabaseClient<Database>,id: string,@@ -527,6 +555,7 @@ export async function getIssueItems(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getIssueAssociations(client: SupabaseClient<Database>,nonConformanceId: string,@@ -895,6 +924,7 @@ export async function getIssueAssociations(};}+/** @mcp read */export async function getIssueReviewers(client: SupabaseClient<Database>,id: string,@@ -908,6 +938,7 @@ export async function getIssueReviewers(.order("id", { ascending: true });}+/** @mcp read */export async function getIssueSuppliers(client: SupabaseClient<Database>,id: string,@@ -921,6 +952,7 @@ export async function getIssueSuppliers(.order("id", { ascending: true });}+/** @mcp read */export async function getIssueTasks(client: SupabaseClient<Database>,id: string,@@ -942,6 +974,7 @@ export async function getIssueTasks(]);}+/** @mcp read */export async function getIssueType(client: SupabaseClient<Database>,nonConformanceTypeId: string@@ -953,6 +986,7 @@ export async function getIssueType(.single();}+/** @mcp read */export async function getIssueTypeByName(client: SupabaseClient<Database>,companyId: string,@@ -974,6 +1008,7 @@ export async function getIssueTypeByName(return query.limit(1).maybeSingle();}+/** @mcp read */export async function getIssueTypes(client: SupabaseClient<Database>,companyId: string,@@ -997,6 +1032,7 @@ export async function getIssueTypes(return query;}+/** @mcp read */export async function getIssueWorkflows(client: SupabaseClient<Database>,companyId: string,@@ -1021,6 +1057,7 @@ export async function getIssueWorkflows(return query;}+/** @mcp read */export async function getIssueWorkflowsList(client: SupabaseClient<Database>,companyId: string@@ -1033,6 +1070,7 @@ export async function getIssueWorkflowsList(.order("name");}+/** @mcp read */export async function getIssueTypesList(client: SupabaseClient<Database>,companyId: string@@ -1044,6 +1082,7 @@ export async function getIssueTypesList(.order("name");}+/** @mcp read */export async function getQualityActions(client: SupabaseClient<Database>,companyId: string,@@ -1069,6 +1108,7 @@ export async function getQualityActions(return query;}+/** @mcp read */export async function getQualityDocument(client: SupabaseClient<Database>,id: string@@ -1080,6 +1120,7 @@ export async function getQualityDocument(.single();}+/** @mcp read */export async function getQualityDocumentSteps(client: SupabaseClient<Database>,qualityDocumentId: string@@ -1090,6 +1131,7 @@ export async function getQualityDocumentSteps(.eq("qualityDocumentId", qualityDocumentId);}+/** @mcp read */export async function getQualityDocumentVersions(client: SupabaseClient<Database>,qualityDocument: { name: string; version: number },@@ -1104,6 +1146,7 @@ export async function getQualityDocumentVersions(.order("version", { ascending: false });}+/** @mcp read */export async function getQualityDocuments(client: SupabaseClient<Database>,companyId: string,@@ -1129,6 +1172,7 @@ export async function getQualityDocuments(return query;}+/** @mcp read */export async function getQualityDocumentsList(client: SupabaseClient<Database>,companyId: string@@ -1146,6 +1190,7 @@ export async function getQualityDocumentsList();}+/** @mcp read */export async function getQualityFiles(client: SupabaseClient<Database>,id: string,@@ -1157,6 +1202,7 @@ export async function getQualityFiles(return result.data ?? [];}+/** @mcp read */export async function getRequiredActionsList(client: SupabaseClient<Database>,companyId: string@@ -1169,6 +1215,7 @@ export async function getRequiredActionsList(.order("name");}+/** @mcp read */export async function getRequiredActions(client: SupabaseClient<Database>,companyId: string,@@ -1192,6 +1239,7 @@ export async function getRequiredActions(return query;}+/** @mcp read */export async function getRequiredAction(client: SupabaseClient<Database>,requiredActionId: string@@ -1203,6 +1251,7 @@ export async function getRequiredAction(.single();}+/** @mcp read */export async function getRisk(client: SupabaseClient<Database>,riskId: string@@ -1210,6 +1259,7 @@ export async function getRisk(return client.from("riskRegister").select("*").eq("id", riskId).single();}+/** @mcp read */export async function getRisks(client: SupabaseClient<Database>,companyId: string,@@ -1255,6 +1305,7 @@ export async function getRisks(return query;}+/** @mcp create */export async function insertIssueReviewer(client: SupabaseClient<Database>,reviewer: z.infer<typeof nonConformanceReviewerValidator> & {@@ -1266,6 +1317,7 @@ export async function insertIssueReviewer(return client.from("nonConformanceReviewer").insert(reviewer);}+/** @mcp update destructive */export async function updateIssueActionProcesses(client: SupabaseClient<Database>,args: {@@ -1301,6 +1353,7 @@ export async function updateIssueActionProcesses(}}+/** @mcp update */export async function updateIssueStatus(client: SupabaseClient<Database>,update: {@@ -1314,6 +1367,7 @@ export async function updateIssueStatus(return client.from("nonConformance").update(update).eq("id", update.id);}+/** @mcp update */export async function updateIssueTaskStatus(client: SupabaseClient<Database>,args: {@@ -1362,6 +1416,7 @@ export async function updateIssueTaskStatus(.single();}+/** @mcp update */export async function updateIssueTaskContent(client: SupabaseClient<Database>,args: {@@ -1411,6 +1466,7 @@ export async function updateRiskStatus(return client.from("riskRegister").update({ status }).eq("id", riskId);}+/** @mcp create */export async function insertGauge(client: SupabaseClient<Database>,input: {@@ -1490,6 +1546,7 @@ export async function insertGauge(};}+/** @mcp update */export async function updateGauge(client: SupabaseClient<Database>,input: {@@ -1553,6 +1610,7 @@ export async function upsertGauge(}}+/** @mcp upsert */export async function upsertGaugeCalibrationRecord(client: SupabaseClient<Database>,gaugeCalibrationRecord:@@ -1637,6 +1695,7 @@ export async function upsertGaugeCalibrationRecord(.eq("id", gaugeCalibrationRecord.id);}+/** @mcp upsert */export async function upsertGaugeType(client: SupabaseClient<Database>,gaugeType:@@ -1661,6 +1720,7 @@ export async function upsertGaugeType(}}+/** @mcp create */export async function insertIssue(client: SupabaseClient<Database>,input: {@@ -1887,6 +1947,7 @@ export async function insertIssue(};}+/** @mcp update */export async function updateIssue(client: SupabaseClient<Database>,input: {@@ -2090,6 +2151,7 @@ export async function upsertIssue(}}+/** @mcp upsert */export async function upsertIssueWorkflow(client: SupabaseClient<Database>,nonConformanceWorkflow:@@ -2116,6 +2178,7 @@ export async function upsertIssueWorkflow(}}+/** @mcp upsert */export async function upsertIssueType(client: SupabaseClient<Database>,nonConformanceType:@@ -2143,6 +2206,7 @@ export async function upsertIssueType(}}+/** @mcp upsert */export async function upsertRequiredAction(client: SupabaseClient<Database>,requiredAction:@@ -2170,6 +2234,7 @@ export async function upsertRequiredAction(}}+/** @mcp upsert */export async function upsertQualityDocument(client: SupabaseClient<Database>,qualityDocument:@@ -2274,6 +2339,7 @@ export async function upsertQualityDocumentStep(.single();}+/** @mcp upsert */export async function upsertRisk(client: SupabaseClient<Database>,risk:@@ -2325,6 +2391,7 @@ export async function upsertRisk(// Inbound Inspections (lot-based)// -------------------------------------------------------------+/** @mcp read */export async function getInspections(client: SupabaseClient<Database>,companyId: string,@@ -2369,6 +2436,7 @@ export async function getInspections(return query;}+/** @mcp read */export async function getInspection(client: SupabaseClient<Database>,id: string@@ -2385,6 +2453,7 @@ export async function getInspection(// 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.+/** @mcp read */export async function getReceiptInspections(client: SupabaseClient<Database>,receiptId: string,@@ -2401,6 +2470,7 @@ export async function getReceiptInspections(// Receipt-sourced lots only: the received tracked entities are linked to the// receipt line through their attributes.+/** @mcp read */export async function getInspectionTrackedEntities(client: SupabaseClient<Database>,receiptLineId: string,@@ -2413,6 +2483,7 @@ export async function getInspectionTrackedEntities(.eq("companyId", companyId);}+/** @mcp read */export async function getInspectionSamplingPlans(client: SupabaseClient<Database>,inspectionId: string,@@ -2433,6 +2504,7 @@ export async function getInspectionSamplingPlans(// selectable options — Inactive gauges are retired and never offered, the// engine refuses them too) plus any gauge already recorded on this lot, even// if it has since been retired, so the record keeps showing its readable id.+/** @mcp read */export async function getInspectionGauges(client: SupabaseClient<Database>,companyId: string,@@ -2464,6 +2536,7 @@ export async function getInspectionGauges().order("gaugeId");}+/** @mcp read */export async function getInspectionMeasurements(client: SupabaseClient<Database>,inspectionId: string,@@ -2476,6 +2549,7 @@ export async function getInspectionMeasurements(.eq("companyId", companyId);}+/** @mcp read */export async function getItemInspectionDocumentAssignments(client: SupabaseClient<Database>,itemId: string,@@ -2488,6 +2562,7 @@ export async function getItemInspectionDocumentAssignments(.eq("companyId", companyId);}+/** @mcp upsert destructive */export async function upsertItemInspectionDocumentAssignment(client: SupabaseClient<Database>,assignment: z.infer<typeof itemInspectionDocumentAssignmentValidator> & {@@ -2589,6 +2664,7 @@ function mapInspectionDocument(row: Record<string, unknown>) {};}+/** @mcp read */export async function getInspectionDocuments(client: SupabaseClient<Database>,companyId: string,@@ -2622,6 +2698,7 @@ export async function getInspectionDocuments(};}+/** @mcp read */export async function getInspectionDocumentsForItem(client: SupabaseClient<Database>,itemId: string,@@ -2635,6 +2712,7 @@ export async function getInspectionDocumentsForItem(.order("updatedAt", { ascending: false, nullsFirst: false });}+/** @mcp read */export async function getInspectionDocument(client: SupabaseClient<Database>,id: string,@@ -2694,6 +2772,7 @@ async function resolveInspectionDocumentDrawingNumber(return `${base} (${suffix})`;}+/** @mcp upsert */export async function upsertInspectionDocument(client: SupabaseClient<Database>,diagram:@@ -2826,6 +2905,7 @@ export async function upsertInspectionDocument(.single();}+/** @mcp delete */export async function deleteInspectionDocument(client: SupabaseClient<Database>,id: string,@@ -2924,6 +3004,7 @@ function mapBalloon(row: Record<string, unknown>) {};}+/** @mcp read */export async function getInspectionFeatures(client: SupabaseClient<Database>,inspectionDocumentId: string@@ -2966,6 +3047,7 @@ async function getInspectionFeaturesRaw(.order("createdAt", { ascending: true });}+/** @mcp read */export async function getBalloons(client: SupabaseClient<Database>,inspectionDocumentId: string@@ -2982,6 +3064,7 @@ export async function getBalloons(};}+/** @mcp read */export async function getInspectionPlan(client: SupabaseClient<Database>,inspectionDocumentId: string@@ -3032,6 +3115,7 @@ export async function getInspectionPlan(};}+/** @mcp update */export async function updateInspectionDocumentSampling(client: SupabaseClient<Database>,args: z.infer<typeof inspectionDocumentSamplingValidator> & {@@ -3052,6 +3136,7 @@ export async function updateInspectionDocumentSampling(.eq("companyId", companyId);}+/** @mcp action */export async function saveInspectionDocumentAtomic(client: SupabaseClient<Database>,args: {diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex 5297b444b5..87765b8e36 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -33,6 +33,7 @@ import type {workCenterValidator} from "./resources.models";+/** @mcp action */export async function activateWorkCenter(client: SupabaseClient<Database>,id: string@@ -40,6 +41,7 @@ export async function activateWorkCenter(return client.from("workCenter").update({ active: true }).eq("id", id);}+/** @mcp delete */export async function deleteAbility(client: SupabaseClient<Database>,abilityId: string,@@ -50,6 +52,7 @@ export async function deleteAbility(: client.from("ability").update({ active: false }).eq("id", abilityId);}+/** @mcp delete */export async function deleteContractor(client: SupabaseClient<Database>,contractorId: string@@ -57,6 +60,7 @@ export async function deleteContractor(return client.from("contractor").delete().eq("id", contractorId);}+/** @mcp delete */export async function deleteEmployeeAbility(client: SupabaseClient<Database>,employeeAbilityId: string@@ -64,6 +68,7 @@ export async function deleteEmployeeAbility(return client.from("employeeAbility").delete().eq("id", employeeAbilityId);}+/** @mcp delete */export async function deleteFailureMode(client: SupabaseClient<Database>,failureModeId: string@@ -71,6 +76,7 @@ export async function deleteFailureMode(return client.from("maintenanceFailureMode").delete().eq("id", failureModeId);}+/** @mcp delete */export async function deleteLocation(client: SupabaseClient<Database>,locationId: string@@ -78,6 +84,7 @@ export async function deleteLocation(return client.from("location").delete().eq("id", locationId);}+/** @mcp delete */export async function deleteMaintenanceDispatch(client: SupabaseClient<Database>,dispatchId: string@@ -92,6 +99,7 @@ export async function deleteMaintenanceDispatchComment(return client.from("maintenanceDispatchComment").delete().eq("id", commentId);}+/** @mcp delete */export async function deleteMaintenanceDispatchEvent(client: SupabaseClient<Database>,eventId: string@@ -99,6 +107,7 @@ export async function deleteMaintenanceDispatchEvent(return client.from("maintenanceDispatchEvent").delete().eq("id", eventId);}+/** @mcp delete */export async function deleteMaintenanceDispatchItem(client: SupabaseClient<Database>,itemId: string@@ -116,6 +125,7 @@ export async function deleteMaintenanceDispatchWorkCenter(.eq("id", workCenterId);}+/** @mcp delete */export async function deleteMaintenanceSchedule(client: SupabaseClient<Database>,scheduleId: string@@ -130,6 +140,7 @@ export async function deleteMaintenanceScheduleItem(return client.from("maintenanceScheduleItem").delete().eq("id", itemId);}+/** @mcp delete */export async function deletePartner(client: SupabaseClient<Database>,partnerId: string@@ -137,6 +148,7 @@ export async function deletePartner(return client.from("partner").delete().eq("id", partnerId);}+/** @mcp action */export async function activateProcess(client: SupabaseClient<Database>,processId: string@@ -144,6 +156,7 @@ export async function activateProcess(return client.from("process").update({ active: true }).eq("id", processId);}+/** @mcp action */export async function processDeactivate(client: SupabaseClient<Database>,processId: string@@ -151,6 +164,7 @@ export async function processDeactivate(return client.from("process").update({ active: false }).eq("id", processId);}+/** @mcp delete */export async function deleteProcess(client: SupabaseClient<Database>,processId: string@@ -158,6 +172,7 @@ export async function deleteProcess(return client.from("process").delete().eq("id", processId);}+/** @mcp delete */export async function deleteShift(client: SupabaseClient<Database>,shiftId: string@@ -166,6 +181,7 @@ export async function deleteShift(return client.from("shift").update({ active: false }).eq("id", shiftId);}+/** @mcp delete */export async function deleteSuggestion(client: SupabaseClient<Database>,suggestionId: string@@ -173,6 +189,7 @@ export async function deleteSuggestion(return client.from("suggestion").delete().eq("id", suggestionId);}+/** @mcp delete */export async function deleteTraining(client: SupabaseClient<Database>,trainingId: string@@ -180,6 +197,7 @@ export async function deleteTraining(return client.from("training").delete().eq("id", trainingId);}+/** @mcp delete */export async function deleteTrainingAssignment(client: SupabaseClient<Database>,assignmentId: string@@ -187,6 +205,7 @@ export async function deleteTrainingAssignment(return client.from("trainingAssignment").delete().eq("id", assignmentId);}+/** @mcp delete */export async function deleteTrainingQuestion(client: SupabaseClient<Database>,trainingQuestionId: string,@@ -199,6 +218,7 @@ export async function deleteTrainingQuestion(.eq("companyId", companyId);}+/** @mcp delete */export async function deleteWorkCenter(client: SupabaseClient<Database>,id: string@@ -206,6 +226,7 @@ export async function deleteWorkCenter(return client.from("workCenter").update({ active: false }).eq("id", id);}+/** @mcp read */export async function getAbilities(client: SupabaseClient<Database>,companyId: string,@@ -279,6 +300,7 @@ export async function getAbilities(};}+/** @mcp read */export async function getAbilitiesList(client: SupabaseClient<Database>,companyId: string@@ -291,6 +313,7 @@ export async function getAbilitiesList(.order("name");}+/** @mcp read */export async function getAbility(client: SupabaseClient<Database>,abilityId: string@@ -324,6 +347,7 @@ export async function getAbility(};}+/** @mcp read */export async function getContractor(client: SupabaseClient<Database>,contractorId: string@@ -335,6 +359,7 @@ export async function getContractor(.single();}+/** @mcp read */export async function getContractors(client: SupabaseClient<Database>,companyId: string,@@ -361,6 +386,7 @@ export async function getContractors(return query;}+/** @mcp read */export async function getEmployeeAbilities(client: SupabaseClient<Database>,employeeId: string,@@ -373,6 +399,7 @@ export async function getEmployeeAbilities(.eq("companyId", companyId);}+/** @mcp read */export async function getEmployeeAbility(client: SupabaseClient<Database>,employeeAbilityId: string@@ -384,6 +411,7 @@ export async function getEmployeeAbility(.single();}+/** @mcp read */export async function getFailureMode(client: SupabaseClient<Database>,failureModeId: string@@ -395,6 +423,7 @@ export async function getFailureMode(.single();}+/** @mcp read */export async function getFailureModes(client: SupabaseClient<Database>,companyId: string,@@ -418,6 +447,7 @@ export async function getFailureModes(return query;}+/** @mcp read */export async function getFailureModesList(client: SupabaseClient<Database>,companyId: string@@ -429,6 +459,7 @@ export async function getFailureModesList(.order("name");}+/** @mcp read */export async function getLocation(client: SupabaseClient<Database>,locationId: string@@ -436,6 +467,7 @@ export async function getLocation(return client.from("location").select("*").eq("id", locationId).single();}+/** @mcp read */export async function getLocations(client: SupabaseClient<Database>,companyId: string,@@ -459,6 +491,7 @@ export async function getLocations(return query;}+/** @mcp read */export async function getLocationsList(client: SupabaseClient<Database>,companyId: string@@ -470,6 +503,7 @@ export async function getLocationsList(.order("name");}+/** @mcp read */export async function getMaintenanceDispatch(client: SupabaseClient<Database>,dispatchId: string@@ -488,6 +522,7 @@ export async function getMaintenanceDispatch(.single();}+/** @mcp read */export async function getMaintenanceDispatchComments(client: SupabaseClient<Database>,dispatchId: string@@ -502,6 +537,7 @@ export async function getMaintenanceDispatchComments(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getMaintenanceDispatchEvents(client: SupabaseClient<Database>,dispatchId: string@@ -517,6 +553,7 @@ export async function getMaintenanceDispatchEvents(.order("startTime", { ascending: false });}+/** @mcp read */export async function getMaintenanceDispatchItems(client: SupabaseClient<Database>,dispatchId: string@@ -530,6 +567,7 @@ export async function getMaintenanceDispatchItems(.eq("maintenanceDispatchId", dispatchId);}+/** @mcp read */export async function getMaintenanceDispatchItemTrackedEntities(client: SupabaseClient<Database>,maintenanceDispatchItemId: string@@ -545,6 +583,7 @@ export async function getMaintenanceDispatchItemTrackedEntities(.eq("maintenanceDispatchItemId", maintenanceDispatchItemId);}+/** @mcp read */export async function getMaintenanceDispatches(client: SupabaseClient<Database>,companyId: string,@@ -568,6 +607,7 @@ export async function getMaintenanceDispatches(return query;}+/** @mcp read */export async function getMaintenanceDispatchesByLocation(client: SupabaseClient<Database>,companyId: string,@@ -596,6 +636,7 @@ export async function getMaintenanceDispatchesByLocation(return query;}+/** @mcp read */export async function getMaintenanceDispatchWorkCenters(client: SupabaseClient<Database>,dispatchId: string@@ -609,6 +650,7 @@ export async function getMaintenanceDispatchWorkCenters(.eq("maintenanceDispatchId", dispatchId);}+/** @mcp read */export async function getMaintenanceSchedule(client: SupabaseClient<Database>,scheduleId: string@@ -623,6 +665,7 @@ export async function getMaintenanceSchedule(.single();}+/** @mcp read */export async function getMaintenanceScheduleItems(client: SupabaseClient<Database>,scheduleId: string@@ -636,6 +679,7 @@ export async function getMaintenanceScheduleItems(.eq("maintenanceScheduleId", scheduleId);}+/** @mcp read */export async function getMaintenanceSchedules(client: SupabaseClient<Database>,companyId: string,@@ -663,6 +707,7 @@ export async function getMaintenanceSchedules(return query;}+/** @mcp read */export async function getMaintenanceSchedulesByLocation(client: SupabaseClient<Database>,companyId: string,@@ -695,6 +740,7 @@ export async function getMaintenanceSchedulesByLocation(return query;}+/** @mcp read */export async function getOutstandingTrainingsForUser(client: SupabaseClient<Database>,companyId: string,@@ -723,6 +769,7 @@ export async function getOutstandingTrainingsForUser(return { data: filteredData, error: null };}+/** @mcp read */export async function getTrainingAssignmentStatusForEmployee(client: SupabaseClient<Database>,companyId: string,@@ -754,6 +801,7 @@ export async function getTrainingAssignmentStatusForEmployee(return { data: sorted, error: null };}+/** @mcp read */export async function getPartner(client: SupabaseClient<Database>,partnerId: string,@@ -767,6 +815,7 @@ export async function getPartner(.single();}+/** @mcp read */export async function getPartnerBySupplierId(client: SupabaseClient<Database>,partnerId: string@@ -778,6 +827,7 @@ export async function getPartnerBySupplierId(.single();}+/** @mcp read */export async function getPartners(client: SupabaseClient<Database>,companyId: string,@@ -802,6 +852,7 @@ export async function getPartners(return query;}+/** @mcp read */export async function getProcess(client: SupabaseClient<Database>,processId: string@@ -809,6 +860,7 @@ export async function getProcess(return client.from("processes").select("*").eq("id", processId).single();}+/** @mcp read */export async function getProcesses(client: SupabaseClient<Database>,companyId: string,@@ -832,6 +884,7 @@ export async function getProcesses(return query;}+/** @mcp read */export async function getProcessesList(client: SupabaseClient<Database>,companyId: string@@ -844,6 +897,7 @@ export async function getProcessesList(.order("name");}+/** @mcp read */export async function getSuggestion(client: SupabaseClient<Database>,suggestionId: string@@ -851,6 +905,7 @@ export async function getSuggestion(return client.from("suggestions").select("*").eq("id", suggestionId).single();}+/** @mcp read */export async function getSuggestions(client: SupabaseClient<Database>,companyId: string,@@ -874,6 +929,7 @@ export async function getSuggestions(return query;}+/** @mcp read */export async function getTraining(client: SupabaseClient<Database>,id: string@@ -885,6 +941,7 @@ export async function getTraining(.single();}+/** @mcp read */export async function getTrainingAssignment(client: SupabaseClient<Database>,assignmentId: string@@ -896,6 +953,7 @@ export async function getTrainingAssignment(.single();}+/** @mcp read */export async function getTrainingAssignmentForCompletion(client: SupabaseClient<Database>,assignmentId: string@@ -920,6 +978,7 @@ export async function getTrainingAssignmentForCompletion(.single();}+/** @mcp read */export async function getTrainingAssignments(client: SupabaseClient<Database>,companyId: string,@@ -937,6 +996,7 @@ export async function getTrainingAssignments(return query;}+/** @mcp read */export async function getTrainingAssignmentStatus(client: SupabaseClient<Database>,companyId: string,@@ -991,6 +1051,7 @@ export async function getTrainingAssignmentStatus(return { data: filteredData, error: null, count };}+/** @mcp read */export async function getTrainingAssignmentSummary(client: SupabaseClient<Database>,companyId: string@@ -1000,6 +1061,7 @@ export async function getTrainingAssignmentSummary(});}+/** @mcp read */export async function getTrainingQuestions(client: SupabaseClient<Database>,trainingId: string@@ -1011,6 +1073,7 @@ export async function getTrainingQuestions(.order("sortOrder", { ascending: true });}+/** @mcp read */export async function getTrainings(client: SupabaseClient<Database>,companyId: string,@@ -1036,6 +1099,7 @@ export async function getTrainings(return query;}+/** @mcp read */export async function getTrainingsList(client: SupabaseClient<Database>,companyId: string@@ -1048,6 +1112,7 @@ export async function getTrainingsList(.order("name", { ascending: true });}+/** @mcp read */export async function getWorkCenter(client: SupabaseClient<Database>,id: string@@ -1081,6 +1146,7 @@ export async function getWorkCenter(};}+/** @mcp read */export async function getWorkCenters(client: SupabaseClient<Database>,companyId: string,@@ -1106,6 +1172,7 @@ export async function getWorkCenters(return query;}+/** @mcp read */export async function getWorkCentersByLocation(client: SupabaseClient<Database>,locationId: string@@ -1148,6 +1215,7 @@ export async function getWorkCentersByLocation(return { data: mergedData, error: null };}+/** @mcp read */export async function getWorkCentersList(client: SupabaseClient<Database>,companyId: string@@ -1160,6 +1228,7 @@ export async function getWorkCentersList(.order("name");}+/** @mcp read */export async function getWorkCentersListWithBlockingStatus(client: SupabaseClient<Database>,companyId: string@@ -1176,6 +1245,7 @@ export async function getWorkCentersListWithBlockingStatus(* Processes that do not yet have an ability. Feeds the New Ability picker so a* planner can only mint an ability for a process that lacks one — an ability is* a process's qualification, and a process may have at most one.+ * @mcp read*/export async function getProcessesWithoutAbility(client: SupabaseClient<Database>,@@ -1233,6 +1303,7 @@ export async function insertTrainingCompletion(* Completing training upserts an `employeeAbility` via the* `grant_ability_on_training_completion` trigger, so the caller can restamp the* scheduler (`notifyScheduleInputsChanged`) for that ability's operator pool.+ * @mcp read*/export async function getTrainingGrantedAbilityId(client: SupabaseClient<Database>,@@ -1256,6 +1327,7 @@ export async function getTrainingGrantedAbilityId(return training.data?.grantsAbilityId ?? null;}+/** @mcp update */export async function updateAbility(client: SupabaseClient<Database>,id: string,@@ -1274,6 +1346,7 @@ export async function updateAbility(* Resolves the qualification expiry for an employee ability. An explicit* expiresAt wins; otherwise it is computed from lastTrainingDate + the* ability's recertifyEveryDays (null when the ability never expires).+ * @mcp action*/export async function resolveEmployeeAbilityExpiresAt(client: SupabaseClient<Database>,@@ -1297,6 +1370,7 @@ export async function resolveEmployeeAbilityExpiresAt(.slice(0, 10);}+/** @mcp upsert */export async function upsertEmployeeAbilityCell(client: SupabaseClient<Database>,cell: {@@ -1318,6 +1392,7 @@ export async function upsertEmployeeAbilityCell(* Find-or-create the ability linked 1:1 to a process. Called when a process* has "Requires Ability" toggled on — the ability (named after the process)* is what employees get qualified against.+ * @mcp action*/export async function ensureProcessAbility(client: SupabaseClient<Database>,@@ -1359,6 +1434,7 @@ export async function ensureProcessAbility(.single();}+/** @mcp update */export async function updateSuggestionEmoji(client: SupabaseClient<Database>,suggestionId: string,@@ -1375,6 +1451,7 @@ export async function updateSuggestionTags(return client.from("suggestion").update({ tags }).eq("id", suggestionId);}+/** @mcp update */export async function updateTrainingQuestionOrder(client: SupabaseClient<Database>,updates: {@@ -1392,6 +1469,10 @@ export async function updateTrainingQuestionOrder(return Promise.all(updatePromises);}+/**+ * @mcp upsert destructive+ * @mcp key contractor id+ */export async function upsertContractor(client: SupabaseClient<Database>,contractorWithAbilities:@@ -1450,6 +1531,7 @@ export async function upsertContractor(return client.from("contractorAbility").insert(contractorAbilities);}+/** @mcp upsert */export async function upsertFailureMode(client: SupabaseClient<Database>,failureMode:@@ -1477,6 +1559,7 @@ export async function upsertFailureMode(}}+/** @mcp upsert */export async function upsertLocation(client: SupabaseClient<Database>,location:@@ -1500,6 +1583,7 @@ export async function upsertLocation(return client.from("location").insert([location]).select("*").single();}+/** @mcp create */export async function insertMaintenanceDispatch(client: SupabaseClient<Database>,input: {@@ -1584,6 +1668,7 @@ export async function insertMaintenanceDispatch(};}+/** @mcp update */export async function updateMaintenanceDispatch(client: SupabaseClient<Database>,input: {@@ -1661,6 +1746,7 @@ export async function upsertMaintenanceDispatch(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchComment(client: SupabaseClient<Database>,comment:@@ -1687,6 +1773,7 @@ export async function upsertMaintenanceDispatchComment(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchEvent(client: SupabaseClient<Database>,event:@@ -1713,6 +1800,7 @@ export async function upsertMaintenanceDispatchEvent(}}+/** @mcp upsert */export async function upsertMaintenanceDispatchItem(client: SupabaseClient<Database>,item:@@ -1765,6 +1853,7 @@ export async function upsertMaintenanceDispatchWorkCenter(}}+/** @mcp upsert */export async function upsertMaintenanceSchedule(client: SupabaseClient<Database>,schedule:@@ -1817,6 +1906,10 @@ export async function upsertMaintenanceScheduleItem(}}+/**+ * @mcp upsert+ * @mcp key partner id+ */export async function upsertPartner(client: SupabaseClient<Database>,partner:@@ -1880,6 +1973,7 @@ function extractBatchRules<return { batchRules, rest };}+/** @mcp upsert destructive */export async function upsertProcess(client: SupabaseClient<Database>,process:@@ -1973,6 +2067,7 @@ export async function upsertProcess(return processUpdate;}+/** @mcp upsert */export async function upsertTraining(client: SupabaseClient<Database>,training:@@ -1997,6 +2092,7 @@ export async function upsertTraining(return client.from("training").insert([training]).select("id").single();}+/** @mcp upsert */export async function upsertTrainingAssignment(client: SupabaseClient<Database>,assignment: {@@ -2031,6 +2127,7 @@ export async function upsertTrainingAssignment(.single();}+/** @mcp upsert */export async function upsertTrainingQuestion(client: SupabaseClient<Database>,trainingQuestion:@@ -2058,6 +2155,7 @@ export async function upsertTrainingQuestion(.single();}+/** @mcp upsert destructive */export async function upsertWorkCenter(client: SupabaseClient<Database>,workCenter:diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 1aa75b0202..ca07920ab3 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -146,6 +146,7 @@ export async function closeSalesOrder(.single();}+/** @mcp update */export async function convertSalesRfqToQuote(client: SupabaseClient<Database>,payload: {@@ -162,6 +163,7 @@ export async function convertSalesRfqToQuote(});}+/** @mcp update */export async function convertQuoteToOrder(client: SupabaseClient<Database>,payload: {@@ -211,6 +213,7 @@ export async function convertQuoteToOrder(return result;}+/** @mcp create */export async function copyQuoteLine(client: SupabaseClient<Database>,payload: z.infer<typeof getMethodValidator> & {@@ -234,6 +237,7 @@ export async function copyQuoteLine(});}+/** @mcp create */export async function copyQuote(client: SupabaseClient<Database>,payload: Omit<z.infer<typeof getMethodValidator>, "type"> & {@@ -249,6 +253,7 @@ export async function copyQuote(});}+/** @mcp create */export async function createPricingRule(client: SupabaseClient<Database>,companyId: string,@@ -318,6 +323,7 @@ function normalizePricingRule<};}+/** @mcp delete */export async function deleteCustomer(client: SupabaseClient<Database>,customerId: string@@ -325,6 +331,7 @@ export async function deleteCustomer(return client.from("customer").delete().eq("id", customerId);}+/** @mcp delete */export async function deleteCustomerBankAccount(client: SupabaseClient<Database>,id: string@@ -332,6 +339,7 @@ export async function deleteCustomerBankAccount(return client.from("customerBankAccount").delete().eq("id", id);}+/** @mcp read */export async function getCustomerBankAccounts(client: SupabaseClient<Database>,customerId: string@@ -343,6 +351,7 @@ export async function getCustomerBankAccounts(.order("name");}+/** @mcp upsert */export async function upsertCustomerBankAccount(db: Kysely<KyselyDatabase>,bankAccount:@@ -383,6 +392,7 @@ export async function upsertCustomerBankAccount(.executeTakeFirstOrThrow();}+/** @mcp delete */export async function deleteCustomerContact(client: SupabaseClient<Database>,customerId: string,@@ -408,6 +418,7 @@ export async function deleteCustomerContact(return customerContact;}+/** @mcp delete */export async function deleteCustomerLocation(client: SupabaseClient<Database>,customerId: string,@@ -432,6 +443,7 @@ export async function deleteCustomerLocation(}}+/** @mcp delete */export async function deleteCustomerStatus(client: SupabaseClient<Database>,customerStatusId: string@@ -439,6 +451,7 @@ export async function deleteCustomerStatus(return client.from("customerStatus").delete().eq("id", customerStatusId);}+/** @mcp delete */export async function deleteCustomerType(client: SupabaseClient<Database>,customerTypeId: string@@ -446,6 +459,7 @@ export async function deleteCustomerType(return client.from("customerType").delete().eq("id", customerTypeId);}+/** @mcp delete */export async function deleteNoQuoteReason(client: SupabaseClient<Database>,noQuoteReasonId: string@@ -453,6 +467,7 @@ export async function deleteNoQuoteReason(return client.from("noQuoteReason").delete().eq("id", noQuoteReasonId);}+/** @mcp delete */export async function deletePricingRule(client: SupabaseClient<Database>,pricingRuleId: string@@ -460,6 +475,7 @@ export async function deletePricingRule(return client.from("pricingRule").delete().eq("id", pricingRuleId);}+/** @mcp delete */export async function deleteQuote(client: SupabaseClient<Database>,quoteId: string@@ -474,6 +490,7 @@ export async function deleteQuoteMakeMethod(return client.from("quoteMakeMethod").delete().eq("id", quoteMakeMethodId);}+/** @mcp delete */export async function deleteQuoteLine(client: SupabaseClient<Database>,quoteLineId: string@@ -481,6 +498,7 @@ export async function deleteQuoteLine(return client.from("quoteLine").delete().eq("id", quoteLineId);}+/** @mcp delete */export async function deleteQuoteMaterial(client: SupabaseClient<Database>,quoteMaterialId: string@@ -495,6 +513,7 @@ export async function deleteQuoteOperation(return client.from("quoteOperation").delete().eq("id", quoteOperationId);}+/** @mcp delete */export async function deleteQuoteOperationStep(client: SupabaseClient<Database>,id: string@@ -502,6 +521,7 @@ export async function deleteQuoteOperationStep(return client.from("quoteOperationStep").delete().eq("id", id);}+/** @mcp delete */export async function deleteQuoteOperationParameter(client: SupabaseClient<Database>,id: string@@ -509,6 +529,7 @@ export async function deleteQuoteOperationParameter(return client.from("quoteOperationParameter").delete().eq("id", id);}+/** @mcp delete */export async function deleteQuoteOperationTool(client: SupabaseClient<Database>,id: string@@ -516,6 +537,7 @@ export async function deleteQuoteOperationTool(return client.from("quoteOperationTool").delete().eq("id", id);}+/** @mcp delete */export async function deleteSalesOrder(client: SupabaseClient<Database>,salesOrderId: string@@ -523,6 +545,7 @@ export async function deleteSalesOrder(return client.from("salesOrder").delete().eq("id", salesOrderId);}+/** @mcp delete */export async function deleteSalesOrderLine(client: SupabaseClient<Database>,salesOrderLineId: string@@ -530,6 +553,7 @@ export async function deleteSalesOrderLine(return client.from("salesOrderLine").delete().eq("id", salesOrderLineId);}+/** @mcp delete */export async function deleteSalesRFQ(client: SupabaseClient<Database>,salesRfqId: string@@ -537,6 +561,7 @@ export async function deleteSalesRFQ(return client.from("salesRfq").delete().eq("id", salesRfqId);}+/** @mcp delete */export async function deleteSalesRFQLine(client: SupabaseClient<Database>,salesRFQLineId: string@@ -544,6 +569,7 @@ export async function deleteSalesRFQLine(return client.from("salesRfqLine").delete().eq("id", salesRFQLineId);}+/** @mcp create */export async function duplicatePricingRule(client: SupabaseClient<Database>,id: string,@@ -583,6 +609,7 @@ export async function duplicatePricingRule(.single();}+/** @mcp read */export async function getConfigurationParametersByQuoteLineId(client: SupabaseClient<Database>,quoteLineId: string,@@ -628,6 +655,7 @@ export async function getConfigurationParametersByQuoteLineId(return { groups: groups.data ?? [], parameters: parameters.data ?? [] };}+/** @mcp read */export async function getCustomer(client: SupabaseClient<Database>,customerId: string,@@ -638,6 +666,7 @@ export async function getCustomer(return query.single();}+/** @mcp read */export async function getCustomerContact(client: SupabaseClient<Database>,customerContactId: string,@@ -653,6 +682,7 @@ export async function getCustomerContact(return query.single();}+/** @mcp read */export async function getCustomerContacts(client: SupabaseClient<Database>,customerId: string,@@ -668,6 +698,7 @@ export async function getCustomerContacts(return query;}+/** @mcp read */export async function getCustomerItemPriceOverride(client: SupabaseClient<Database>,customerId: string,@@ -691,6 +722,7 @@ export async function getCustomerItemPriceOverride(return { data: applyBreakToParent(data, quantity, date), error: null };}+/** @mcp read */export async function getCustomerLocation(client: SupabaseClient<Database>,customerLocationId: string,@@ -706,6 +738,7 @@ export async function getCustomerLocation(return query.single();}+/** @mcp read */export async function getCustomerLocations(client: SupabaseClient<Database>,customerId: string,@@ -721,6 +754,7 @@ export async function getCustomerLocations(return query;}+/** @mcp read */export async function getCustomerPayment(client: SupabaseClient<Database>,customerId: string,@@ -734,6 +768,7 @@ export async function getCustomerPayment(return query.single();}+/** @mcp read */export async function getCustomerShipping(client: SupabaseClient<Database>,customerId: string,@@ -747,6 +782,7 @@ export async function getCustomerShipping(return query.single();}+/** @mcp read */export async function getCustomerTax(client: SupabaseClient<Database>,customerId: string,@@ -760,6 +796,7 @@ export async function getCustomerTax(return query.single();}+/** @mcp read */export async function getCustomerTypeItemPriceOverride(client: SupabaseClient<Database>,customerTypeId: string,@@ -783,6 +820,7 @@ export async function getCustomerTypeItemPriceOverride(return { data: applyBreakToParent(data, quantity, date), error: null };}+/** @mcp read */export async function getAllCustomersItemPriceOverride(client: SupabaseClient<Database>,itemId: string,@@ -871,6 +909,7 @@ function pickBestBreak(return best;}+/** @mcp read */export async function getCustomers(client: SupabaseClient<Database>,companyId: string,@@ -895,6 +934,7 @@ export async function getCustomers(return query;}+/** @mcp read */export async function getCustomersList(client: SupabaseClient<Database>,companyId: string@@ -907,6 +947,7 @@ export async function getCustomersList();}+/** @mcp read */export async function getCustomerStatus(client: SupabaseClient<Database>,customerStatusId: string@@ -918,6 +959,7 @@ export async function getCustomerStatus(.single();}+/** @mcp read */export async function getCustomerStatuses(client: SupabaseClient<Database>,companyId: string,@@ -941,6 +983,7 @@ export async function getCustomerStatuses(return query;}+/** @mcp read */export async function getCustomerStatusesList(client: SupabaseClient<Database>,companyId: string@@ -952,6 +995,7 @@ export async function getCustomerStatusesList(.order("name");}+/** @mcp read */export async function getCustomerType(client: SupabaseClient<Database>,customerTypeId: string@@ -963,6 +1007,7 @@ export async function getCustomerType(.single();}+/** @mcp read */export async function getCustomerTypes(client: SupabaseClient<Database>,companyId: string,@@ -986,6 +1031,7 @@ export async function getCustomerTypes(return query;}+/** @mcp read */export async function getCustomerTypesList(client: SupabaseClient<Database>,companyId: string@@ -997,6 +1043,7 @@ export async function getCustomerTypesList(.order("name");}+/** @mcp read */export async function getExternalSalesOrderLines(client: SupabaseClient<Database>,customerId: string,@@ -1025,6 +1072,7 @@ export async function getExternalSalesOrderLines(return query;}+/** @mcp read */export async function getModelByQuoteLineId(client: SupabaseClient<Database>,quoteLineId: string@@ -1040,6 +1088,7 @@ export async function getModelByQuoteLineId(return getModelByItemId(client, quoteLine.data.itemId);}+/** @mcp read */export async function getNoQuoteReasonsList(client: SupabaseClient<Database>,companyId: string@@ -1051,6 +1100,7 @@ export async function getNoQuoteReasonsList(.order("name");}+/** @mcp read */export async function getNoQuoteReason(client: SupabaseClient<Database>,noQuoteReasonId: string@@ -1062,6 +1112,7 @@ export async function getNoQuoteReason(.single();}+/** @mcp read */export async function getNoQuoteReasons(client: SupabaseClient<Database>,companyId: string,@@ -1085,6 +1136,7 @@ export async function getNoQuoteReasons(return query;}+/** @mcp read */export async function getOpportunity(client: SupabaseClient<Database>,opportunityId: string | null@@ -1125,6 +1177,7 @@ export async function getOpportunity(}>;}+/** @mcp read */export async function getOpportunityDocuments(client: SupabaseClient<Database>,companyId: string,@@ -1147,6 +1200,7 @@ export async function getOpportunityDocuments(}));}+/** @mcp read */export async function getOpportunityLineDocuments(client: SupabaseClient<Database>,companyId: string,@@ -1185,6 +1239,7 @@ export async function getOpportunityLineDocuments(return [...opportunityLineDocs, ...itemDocs];}+/** @mcp read */export async function getPricingRule(client: SupabaseClient<Database>,id: string@@ -1192,6 +1247,7 @@ export async function getPricingRule(return client.from("pricingRule").select("*").eq("id", id).single();}+/** @mcp read */export async function getPricingRules(client: SupabaseClient<Database>,companyId: string,@@ -1221,6 +1277,7 @@ export const priceSourceTypes = ["Rule"] as const;+/** @mcp read */export async function getQuote(client: SupabaseClient<Database>,quoteId: string@@ -1228,6 +1285,7 @@ export async function getQuote(return client.from("quotes").select("*").eq("id", quoteId).single();}+/** @mcp read */export async function getQuotes(client: SupabaseClient<Database>,companyId: string,@@ -1252,6 +1310,7 @@ export async function getQuotes(return query;}+/** @mcp read */export async function getQuotesList(client: SupabaseClient<Database>,companyId: string@@ -1265,6 +1324,7 @@ export async function getQuotesList();}+/** @mcp read */export async function getQuoteAssembliesByLine(client: SupabaseClient<Database>,quoteLineId: string@@ -1275,6 +1335,7 @@ export async function getQuoteAssembliesByLine(.eq("quoteLineId", quoteLineId);}+/** @mcp read */export async function getQuoteAssemblies(client: SupabaseClient<Database>,quoteId: string@@ -1282,6 +1343,7 @@ export async function getQuoteAssemblies(return client.from("quoteMakeMethod").select("*").eq("quoteId", quoteId);}+/** @mcp read */export async function getQuoteCustomerDetails(client: SupabaseClient<Database>,quoteId: string@@ -1293,6 +1355,7 @@ export async function getQuoteCustomerDetails(.single();}+/** @mcp read */export async function getQuoteLine(client: SupabaseClient<Database>,quoteLineId: string@@ -1300,6 +1363,7 @@ export async function getQuoteLine(return client.from("quoteLines").select("*").eq("id", quoteLineId).single();}+/** @mcp read */export async function getQuoteLinesList(client: SupabaseClient<Database>,quoteId: string@@ -1319,6 +1383,7 @@ type QuoteMethodTreeItem = {children: QuoteMethodTreeItem[];};+/** @mcp read */export async function getQuoteMakeMethod(client: SupabaseClient<Database>,quoteMakeMethodId: string@@ -1330,6 +1395,7 @@ export async function getQuoteMakeMethod(.single();}+/** @mcp read */export async function getRootQuoteMakeMethod(client: SupabaseClient<Database>,quoteLineId: string@@ -1342,6 +1408,7 @@ export async function getRootQuoteMakeMethod(.single();}+/** @mcp read */export async function getQuoteMethodTrees(client: SupabaseClient<Database>,quoteId: string@@ -1357,6 +1424,7 @@ export async function getQuoteMethodTrees(};}+/** @mcp read */export async function getQuoteMethodTreeArray(client: SupabaseClient<Database>,quoteId: string@@ -1409,6 +1477,7 @@ function getQuoteMethodTreeArrayToTree(// return rootItems.map((item) => traverseAndRenameIds(item));}+/** @mcp read */export async function getQuoteLines(client: SupabaseClient<Database>,quoteId: string@@ -1421,6 +1490,7 @@ export async function getQuoteLines(.order("itemReadableId", { ascending: true });}+/** @mcp read */export async function getQuoteByExternalId(client: SupabaseClient<Database>,externalId: string@@ -1432,6 +1502,7 @@ export async function getQuoteByExternalId(.single();}+/** @mcp read */export async function getQuoteLinePrices(client: SupabaseClient<Database>,quoteLineId: string@@ -1442,6 +1513,7 @@ export async function getQuoteLinePrices(.eq("quoteLineId", quoteLineId);}+/** @mcp read */export async function getQuoteLinePricesByQuoteId(client: SupabaseClient<Database>,quoteId: string@@ -1453,6 +1525,7 @@ export async function getQuoteLinePricesByQuoteId(.order("quoteLineId", { ascending: true });}+/** @mcp read */export async function getQuoteLinePricesByItemId(client: SupabaseClient<Database>,itemId: string,@@ -1467,6 +1540,7 @@ export async function getQuoteLinePricesByItemId(.order("qty", { ascending: true });}+/** @mcp read */export async function getQuoteLinePricesByItemIds(client: SupabaseClient<Database>,itemIds: string[],@@ -1482,6 +1556,7 @@ export async function getQuoteLinePricesByItemIds(.limit(10);}+/** @mcp read */export async function getQuoteMaterials(client: SupabaseClient<Database>,quoteId: string@@ -1489,6 +1564,7 @@ export async function getQuoteMaterials(return client.from("quoteMaterial").select("*").eq("quoteId", quoteId);}+/** @mcp read */export async function getQuoteMaterial(client: SupabaseClient<Database>,materialId: string@@ -1500,6 +1576,7 @@ export async function getQuoteMaterial(.single();}+/** @mcp read */export async function getQuoteMaterialsByLine(client: SupabaseClient<Database>,quoteLineId: string@@ -1510,6 +1587,7 @@ export async function getQuoteMaterialsByLine(.eq("quoteLineId", quoteLineId);}+/** @mcp read */export async function getQuoteMaterialsByMethodId(client: SupabaseClient<Database>,quoteMakeMethodId: string@@ -1521,6 +1599,7 @@ export async function getQuoteMaterialsByMethodId(.order("order", { ascending: true });}+/** @mcp read */export async function getQuoteMaterialsByOperation(client: SupabaseClient<Database>,quoteOperationId: string@@ -1531,6 +1610,7 @@ export async function getQuoteMaterialsByOperation(.eq("quoteOperationId", quoteOperationId);}+/** @mcp read */export async function getQuoteOperation(client: SupabaseClient<Database>,quoteOperationId: string@@ -1542,6 +1622,7 @@ export async function getQuoteOperation(.single();}+/** @mcp read */export async function getQuoteOperationsByLine(client: SupabaseClient<Database>,quoteLineId: string@@ -1552,6 +1633,7 @@ export async function getQuoteOperationsByLine(.eq("quoteLineId", quoteLineId);}+/** @mcp read */export async function getQuoteOperationsByMethodId(client: SupabaseClient<Database>,quoteMakeMethodId: string@@ -1565,6 +1647,7 @@ export async function getQuoteOperationsByMethodId(.order("order", { ascending: true });}+/** @mcp read */export async function getQuoteOperations(client: SupabaseClient<Database>,quoteId: string@@ -1572,6 +1655,7 @@ export async function getQuoteOperations(return client.from("quoteOperation").select("*").eq("quoteId", quoteId);}+/** @mcp read */export async function getQuotePayment(client: SupabaseClient<Database>,quoteId: string@@ -1579,6 +1663,7 @@ export async function getQuotePayment(return client.from("quotePayment").select("*").eq("id", quoteId).single();}+/** @mcp read */export async function getQuoteShipment(client: SupabaseClient<Database>,quoteId: string@@ -1586,6 +1671,7 @@ export async function getQuoteShipment(return client.from("quoteShipment").select("*").eq("id", quoteId).single();}+/** @mcp read */export async function getRelatedPricesForQuoteLine(client: SupabaseClient<Database>,itemId: string,@@ -1614,6 +1700,7 @@ export async function getRelatedPricesForQuoteLine(};}+/** @mcp read */export async function getSalesDocumentsAssignedToMe(client: SupabaseClient<Database>,userId: string,@@ -1646,6 +1733,7 @@ export async function getSalesDocumentsAssignedToMe(return merged;}+/** @mcp read */export async function getSalesOrder(client: SupabaseClient<Database>,salesOrderId: string@@ -1653,6 +1741,7 @@ export async function getSalesOrder(return client.from("salesOrders").select("*").eq("id", salesOrderId).single();}+/** @mcp read */export async function getSalesOrderCustomerDetails(client: SupabaseClient<Database>,salesOrderId: string@@ -1664,6 +1753,7 @@ export async function getSalesOrderCustomerDetails(.single();}+/** @mcp read */export async function getSalesOrderRelatedItems(client: SupabaseClient<Database>,salesOrderId: string,@@ -1715,6 +1805,7 @@ export async function getSalesOrderRelatedItems(};}+/** @mcp read */export async function getSalesOrders(client: SupabaseClient<Database>,companyId: string,@@ -1746,6 +1837,7 @@ export async function getSalesOrders(return query;}+/** @mcp read */export async function getSalesOrdersList(client: SupabaseClient<Database>,companyId: string@@ -1758,6 +1850,7 @@ export async function getSalesOrdersList();}+/** @mcp read */export async function getSalesOrdersByIds(client: SupabaseClient<Database>,ids: string[]@@ -1765,6 +1858,7 @@ export async function getSalesOrdersByIds(return client.from("salesOrder").select("id, salesOrderId").in("id", ids);}+/** @mcp read */export async function getSalesOrderPayment(client: SupabaseClient<Database>,salesOrderId: string@@ -1776,6 +1870,7 @@ export async function getSalesOrderPayment(.single();}+/** @mcp read */export async function getSalesTerms(client: SupabaseClient<Database>,companyId: string@@ -1783,6 +1878,7 @@ export async function getSalesTerms(return client.from("terms").select("salesTerms").eq("id", companyId).single();}+/** @mcp read */export async function getSalesOrderShipment(client: SupabaseClient<Database>,salesOrderId: string@@ -1794,10 +1890,12 @@ export async function getSalesOrderShipment(.single();}+/** @mcp read */export async function getSalesOrderCustomers(client: SupabaseClient<Database>) {return client.from("salesOrderCustomers").select("id, name");}+/** @mcp read */export async function getSalesOrderLines(client: SupabaseClient<Database>,salesOrderId: string@@ -1810,6 +1908,7 @@ export async function getSalesOrderLines(.order("itemReadableId", { ascending: true });}+/** @mcp read */export async function getSalesOrderInvoiceLines(client: SupabaseClient<Database>,salesOrderId: string@@ -1820,6 +1919,7 @@ export async function getSalesOrderInvoiceLines(.eq("salesOrderId", salesOrderId);}+/** @mcp read */export async function getSalesOrderInvoicesByIds(client: SupabaseClient<Database>,invoiceIds: string[]@@ -1830,6 +1930,7 @@ export async function getSalesOrderInvoicesByIds(.in("id", invoiceIds);}+/** @mcp read */export async function getSalesOrderInvoicePaymentsByIds(client: SupabaseClient<Database>,companyId: string,@@ -1853,6 +1954,7 @@ export async function getSalesOrderInvoicePaymentsByIds();}+/** @mcp read */export async function getSalesOrderLinesByItemId(client: SupabaseClient<Database>,itemId: string@@ -1870,6 +1972,7 @@ export async function getSalesOrderLinesByItemId(* job's item, on sales orders that are still open (not Completed/Invoiced/* Cancelled/Closed). Joins the base salesOrder header so we can filter on its* status (the salesOrderLines view only exposes the line-level status).+ * @mcp read*/export async function getOpenSalesOrderLinesForItem(client: SupabaseClient<Database>,@@ -1887,6 +1990,7 @@ export async function getOpenSalesOrderLinesForItem(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getSalesOrderLinesByItemIds(client: SupabaseClient<Database>,itemIds: string[]@@ -1900,6 +2004,7 @@ export async function getSalesOrderLinesByItemIds(.limit(10);}+/** @mcp read */export async function getSalesOrderLine(client: SupabaseClient<Database>,salesOrderLineId: string@@ -1911,6 +2016,7 @@ export async function getSalesOrderLine(.single();}+/** @mcp read */export async function getSalesOrderLineShipments(client: SupabaseClient<Database>,salesOrderLineId: string@@ -1922,6 +2028,7 @@ export async function getSalesOrderLineShipments(.gt("shippedQuantity", 0);}+/** @mcp read */export async function getSalesRFQ(client: SupabaseClient<Database>,id: string@@ -1929,6 +2036,7 @@ export async function getSalesRFQ(return client.from("salesRfqs").select("*").eq("id", id).single();}+/** @mcp read */export async function getSalesRFQs(client: SupabaseClient<Database>,companyId: string,@@ -1953,6 +2061,7 @@ export async function getSalesRFQs(return query;}+/** @mcp read */export async function getSalesRFQLine(client: SupabaseClient<Database>,lineId: string@@ -1960,6 +2069,7 @@ export async function getSalesRFQLine(return client.from("salesRfqLines").select("*").eq("id", lineId).single();}+/** @mcp read */export async function getSalesRFQLines(client: SupabaseClient<Database>,salesRfqId: string@@ -1972,6 +2082,7 @@ export async function getSalesRFQLines(.order("customerPartId", { ascending: true });}+/** @mcp create */export async function insertCustomerContact(client: SupabaseClient<Database>,customerContact: {@@ -2017,6 +2128,7 @@ export async function insertCustomerContact(.single();}+/** @mcp create */export async function insertCustomerLocation(client: SupabaseClient<Database>,customerLocation: {@@ -2085,6 +2197,7 @@ export async function insertSalesOrderLines(return client.from("salesOrderLine").insert(linesWithDefaults).select("id");}+/** @mcp update */export async function finalizeQuote(client: SupabaseClient<Database>,quoteId: string,@@ -2129,6 +2242,7 @@ export async function finalizeQuote(return lineUpdate;}+/** @mcp update */export async function releaseSalesOrder(client: SupabaseClient<Database>,salesOrderId: string,@@ -2144,6 +2258,7 @@ export async function releaseSalesOrder(.eq("id", salesOrderId);}+/** @mcp action */export async function resolvePrice(client: SupabaseClient<Database>,companyId: string,@@ -2378,6 +2493,7 @@ async function resolvePostingGroupFilter(return { itemIds, filters: remaining };}+/** @mcp action */export async function resolvePriceList(client: SupabaseClient<Database>,companyId: string,@@ -2694,6 +2810,7 @@ export async function resolvePriceList(};}+/** @mcp read */export async function getBaseCatalog(client: SupabaseClient<Database>,companyId: string,@@ -2763,6 +2880,7 @@ export async function getBaseCatalog(return { data: rows, count: count ?? 0 };}+/** @mcp upsert */export async function upsertCustomer(client: SupabaseClient<Database>,customer:@@ -2795,6 +2913,7 @@ export async function upsertCustomer(.single();}+/** @mcp upsert destructive */export async function upsertCustomerItemPriceOverride(db: Kysely<KyselyDatabase>,companyId: string,@@ -3008,6 +3127,7 @@ export async function upsertCustomerItemPriceOverride(}}+/** @mcp delete */export async function deleteCustomerItemPriceOverride(client: SupabaseClient<Database>,id: string,@@ -3033,6 +3153,7 @@ type CustomerItemPriceOverrideWithRelations =}[];};+/** @mcp read */export async function getCustomerItemPriceOverrideById(client: SupabaseClient<Database>,id: string,@@ -3055,6 +3176,7 @@ export async function getCustomerItemPriceOverrideById(.single();}+/** @mcp read */export async function getCustomerItemPriceOverridesList(client: SupabaseClient<Database>,companyId: string,@@ -3115,6 +3237,7 @@ export async function updateCustomerAccounting(.eq("id", customerAccounting.id);}+/** @mcp update */export async function updateCustomerContact(client: SupabaseClient<Database>,customerContact: {@@ -3145,6 +3268,7 @@ export async function updateCustomerContact(.single();}+/** @mcp update */export async function updateCustomerLocation(client: SupabaseClient<Database>,customerLocation: {@@ -3181,6 +3305,7 @@ export async function updateCustomerLocation(.select("id").single();}+/** @mcp update */export async function updateCustomerPayment(client: SupabaseClient<Database>,customerPayment: z.infer<typeof customerPaymentValidator> & {@@ -3193,6 +3318,7 @@ export async function updateCustomerPayment(.eq("customerId", customerPayment.customerId);}+/** @mcp update */export async function updateCustomerShipping(client: SupabaseClient<Database>,customerShipping: z.infer<typeof customerShippingValidator> & {@@ -3205,6 +3331,7 @@ export async function updateCustomerShipping(.eq("customerId", customerShipping.customerId);}+/** @mcp update */export async function updateCustomerTax(client: SupabaseClient<Database>,customerTax: z.infer<typeof customerTaxValidator> & {@@ -3218,6 +3345,7 @@ export async function updateCustomerTax(.eq("customerId", customerTax.customerId);}+/** @mcp update */export async function updatePricingRule(client: SupabaseClient<Database>,id: string,@@ -3238,6 +3366,7 @@ export async function updatePricingRule(.single();}+/** @mcp upsert */export async function upsertCustomerStatus(client: SupabaseClient<Database>,customerStatus:@@ -3262,6 +3391,7 @@ export async function upsertCustomerStatus(}}+/** @mcp upsert */export async function upsertCustomerType(client: SupabaseClient<Database>,customerType:@@ -3286,6 +3416,7 @@ export async function upsertCustomerType(}}+/** @mcp upsert */export async function upsertNoQuoteReason(client: SupabaseClient<Database>,noQuoteReason:@@ -3332,6 +3463,7 @@ export async function updateSalesRFQFavorite(}}+/** @mcp update */export async function updateQuoteExchangeRate(client: SupabaseClient<Database>,data: {@@ -3348,6 +3480,7 @@ export async function updateQuoteExchangeRate(return client.from("quote").update(update).eq("id", update.id);}+/** @mcp update */export async function updateQuoteLinePrecision(db: Kysely<KyselyDatabase>,companyId: string,@@ -3374,6 +3507,7 @@ export async function updateQuoteLinePrecision(});}+/** @mcp update */export async function updateSalesOrderExchangeRate(client: SupabaseClient<Database>,data: {@@ -3410,6 +3544,7 @@ export async function updateQuoteFavorite(}}+/** @mcp update */export async function updateSalesRFQStatus(client: SupabaseClient<Database>,update: {@@ -3436,6 +3571,7 @@ export async function updateSalesRFQStatus(return client.from("salesRfq").update(updateData).eq("id", update.id);}+/** @mcp update */export async function updateQuoteMaterialOrder(client: SupabaseClient<Database>,updates: {@@ -3450,6 +3586,7 @@ export async function updateQuoteMaterialOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateQuoteOperationOrder(client: SupabaseClient<Database>,updates: {@@ -3464,6 +3601,7 @@ export async function updateQuoteOperationOrder(return Promise.all(updatePromises);}+/** @mcp update */export async function updateQuoteStatus(client: SupabaseClient<Database>,update: {@@ -3484,6 +3622,7 @@ export async function updateQuoteStatus(return client.from("quote").update(updateData).eq("id", update.id);}+/** @mcp upsert */export async function upsertMakeMethodFromQuoteLine(client: SupabaseClient<Database>,lineMethod: {@@ -3514,6 +3653,7 @@ export async function upsertMakeMethodFromQuoteLine(});}+/** @mcp upsert */export async function upsertMakeMethodFromQuoteMethod(client: SupabaseClient<Database>,quoteMethod: {@@ -3552,6 +3692,7 @@ export async function upsertMakeMethodFromQuoteMethod(return { data: null, error: null };}+/** @mcp create */export async function insertQuote(client: SupabaseClient<Database>,input: {@@ -3724,6 +3865,7 @@ export async function insertQuote(return { data: { id: createdQuoteId, quoteId }, error: null };}+/** @mcp update */export async function updateQuote(client: SupabaseClient<Database>,input: {@@ -3801,7 +3943,10 @@ export async function updateQuote(.single();}-/** @deprecated Use insertQuote for new quotes, updateQuote for existing quotes */+/**+ * @deprecated Use insertQuote for new quotes, updateQuote for existing quotes+ * @mcp upsert+ */export async function upsertQuote(client: SupabaseClient<Database>,quote:@@ -3980,6 +4125,7 @@ export async function upsertQuote(}}+/** @mcp upsert */export async function upsertQuoteLine(client: SupabaseClient<Database>,quotationLine:@@ -4020,6 +4166,7 @@ export async function upsertQuoteLine(.single();}+/** @mcp update */export async function updateQuoteLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -4037,6 +4184,7 @@ export async function updateQuoteLineOrder(});}+/** @mcp upsert */export async function upsertQuoteLineAdditionalCharges(client: SupabaseClient<Database>,lineId: string,@@ -4065,6 +4213,12 @@ type QuoteLinePriceInput = {priceTrace?: PriceTraceStep[] | null;};+/**+ * @mcp upsert destructive — it delegates to rewriteQuoteLinePrices, which+ * deleteFrom("quoteLinePrice") then re-inserts. The body of+ * THIS function holds no delete, so reading it cannot show+ * that; declaring it is the point.+ */export async function upsertQuoteLinePrices(db: Kysely<KyselyDatabase>,companyId: string,@@ -4546,6 +4700,7 @@ async function getConfiguredSalePrice(return { data: data?.unitSalePrice ?? null, error };}+/** @mcp action */export async function buildMakeToOrderPriceRows(client: SupabaseClient<Database>,quoteId: string,@@ -4680,6 +4835,7 @@ export async function buildMakeToOrderPriceRows(return { rows: priceRows, error: null };}+/** @mcp action */export async function calculatePricesForQuantities(client: SupabaseClient<Database>,quoteId: string,@@ -4708,6 +4864,7 @@ export async function calculatePricesForQuantities(return { error: null };}+/** @mcp action */export async function buildPullFromInventoryPriceRows(client: SupabaseClient<Database>,companyId: string,@@ -4776,6 +4933,7 @@ export async function buildPullFromInventoryPriceRows(return { rows: priceRows, error: null };}+/** @mcp action */export async function resolveQuoteLinePrices(client: SupabaseClient<Database>,companyId: string,@@ -4806,6 +4964,7 @@ export async function resolveQuoteLinePrices(return { error: null };}+/** @mcp action */export async function buildPurchaseToOrderPriceRows(client: SupabaseClient<Database>,companyId: string,@@ -4880,6 +5039,7 @@ export async function buildPurchaseToOrderPriceRows(return { rows: priceRows, error: null };}+/** @mcp action */export async function resolvePurchaseToOrderPrices(client: SupabaseClient<Database>,companyId: string,@@ -4910,6 +5070,7 @@ export async function resolvePurchaseToOrderPrices(return { error: null };}+/** @mcp update */export async function recalculateQuoteLinePrices(client: SupabaseClient<Database>,companyId: string,@@ -5097,15 +5258,18 @@ export async function recalculateQuoteLinePrices(return { error: null };}-// Explains each quantity's price on a quote line. `trace` is the snapshot-// written with the price — how it was actually reached, whatever the rules say-// now. `currentTrace` re-runs today's pipeline from the base the row's builder-// starts from — the cost-plus rollup (or a configured part's sale price) for-// Make to Order, the supplier price break for Purchase to Order, the item's-// sale price for Pull from Inventory — so the UI can show what repricing would-// change. A manual row has neither: a person stated that price and no rule-// touched it. Read-only — null data when the line is not this quote's in this-// company.+/**+ * Explains each quantity's price on a quote line. `trace` is the snapshot+ * written with the price — how it was actually reached, whatever the rules say+ * now. `currentTrace` re-runs today's pipeline from the base the row's builder+ * starts from — the cost-plus rollup (or a configured part's sale price) for+ * Make to Order, the supplier price break for Purchase to Order, the item's+ * sale price for Pull from Inventory — so the UI can show what repricing would+ * change. A manual row has neither: a person stated that price and no rule+ * touched it. Read-only — null data when the line is not this quote's in this+ * company.+ * @mcp read+ */export async function getQuoteLinePriceTraces(client: SupabaseClient<Database>,companyId: string,@@ -5252,12 +5416,15 @@ export class QuoteLockedError extends Error {}}-// Reprices a quote line's system rows to what today's rules give — the-// `currentTrace` getQuoteLinePriceTraces shows — storing that trace with the-// price. Manual rows, and rows today's pipeline cannot price, are rewritten-// unchanged; one transaction either way. Draft quotes only (QuoteLockedError-// otherwise) — checked here, not in the route, because this is also an MCP-// tool.+/**+ * Reprices a quote line's system rows to what today's rules give — the+ * `currentTrace` getQuoteLinePriceTraces shows — storing that trace with the+ * price. Manual rows, and rows today's pipeline cannot price, are rewritten+ * unchanged; one transaction either way. Draft quotes only (QuoteLockedError+ * otherwise) — checked here, not in the route, because this is also an MCP+ * tool.+ * @mcp action+ */export async function repriceQuoteLineFromRules(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -5324,6 +5491,7 @@ export async function repriceQuoteLineFromRules(return { data: null, error: null };}+/** @mcp upsert */export async function upsertQuoteLineMethod(client: SupabaseClient<Database>,lineMethod: {@@ -5381,6 +5549,10 @@ export async function upsertQuoteLineMethod(});}+/**+ * @mcp upsert+ * @mcp key quoteMaterial id+ */export async function upsertQuoteMaterial(client: SupabaseClient<Database>,quoteMaterial:@@ -5428,6 +5600,7 @@ export async function upsertQuoteMaterial(.single();}+/** @mcp upsert */export async function upsertQuoteMaterialMakeMethod(client: SupabaseClient<Database>,quoteMethod: {@@ -5493,6 +5666,10 @@ export async function upsertQuoteMaterialMakeMethod(return { data: null, error: null };}+/**+ * @mcp upsert+ * @mcp key quoteOperation id+ */export async function upsertQuoteOperation(client: SupabaseClient<Database>,operation:@@ -5545,6 +5722,7 @@ export async function upsertQuoteOperation(.single();}+/** @mcp upsert */export async function upsertQuoteOperationStep(client: SupabaseClient<Database>,quoteOperationStep:@@ -5579,6 +5757,7 @@ export async function upsertQuoteOperationStep(.single();}+/** @mcp upsert */export async function upsertQuoteOperationParameter(client: SupabaseClient<Database>,quoteOperationParameter:@@ -5608,6 +5787,7 @@ export async function upsertQuoteOperationParameter(.single();}+/** @mcp upsert */export async function upsertQuoteOperationTool(client: SupabaseClient<Database>,quoteOperationTool:@@ -5637,6 +5817,7 @@ export async function upsertQuoteOperationTool(.single();}+/** @mcp upsert */export async function upsertQuotePayment(client: SupabaseClient<Database>,quotePayment:@@ -5665,6 +5846,7 @@ export async function upsertQuotePayment(.single();}+/** @mcp upsert */export async function upsertQuoteShipment(client: SupabaseClient<Database>,quoteShipment:@@ -5713,6 +5895,7 @@ export async function updateSalesOrderFavorite(}}+/** @mcp update */export async function updateSalesOrderStatus(client: SupabaseClient<Database>,update: {@@ -5736,6 +5919,7 @@ export async function updateSalesOrderStatus(return client.from("salesOrder").update(updateData).eq("id", update.id);}+/** @mcp create */export async function insertSalesOrder(client: SupabaseClient<Database>,input: {@@ -5911,6 +6095,7 @@ export async function insertSalesOrder(return { data: { id: orderId, salesOrderId }, error: null };}+/** @mcp update */export async function updateSalesOrder(client: SupabaseClient<Database>,input: {@@ -5987,6 +6172,7 @@ export const LIVE_JOB_STATUSES: Database["public"]["Enums"]["jobStatus"][] = ["Paused"];+/** @mcp action */export async function cancelSalesOrder(client: SupabaseClient<Database>,args: {@@ -6074,7 +6260,10 @@ export async function cancelSalesOrder(};}-/** @deprecated Use insertSalesOrder for new orders, updateSalesOrder for existing orders */+/**+ * @deprecated Use insertSalesOrder for new orders, updateSalesOrder for existing orders+ * @mcp upsert+ */export async function upsertSalesOrder(client: SupabaseClient<Database>,salesOrder:@@ -6256,6 +6445,7 @@ export async function upsertSalesOrder(return order;}+/** @mcp upsert */export async function upsertSalesOrderShipment(client: SupabaseClient<Database>,salesOrderShipment:@@ -6284,6 +6474,7 @@ export async function upsertSalesOrderShipment(.single();}+/** @mcp upsert */export async function upsertSalesOrderLine(client: SupabaseClient<Database>,salesOrderLine:@@ -6355,6 +6546,7 @@ export async function upsertSalesOrderLine(.single();}+/** @mcp update */export async function updateSalesOrderLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -6372,6 +6564,7 @@ export async function updateSalesOrderLineOrder(});}+/** @mcp upsert */export async function upsertSalesOrderPayment(client: SupabaseClient<Database>,salesOrderPayment:@@ -6400,6 +6593,7 @@ export async function upsertSalesOrderPayment(.single();}+/** @mcp create */export async function insertSalesRFQ(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -6625,7 +6819,10 @@ export async function updateSalesRFQ(.single();}-/** @deprecated Use insertSalesRFQ for new RFQs, updateSalesRFQ for existing RFQs */+/**+ * @deprecated Use insertSalesRFQ for new RFQs, updateSalesRFQ for existing RFQs+ * @mcp upsert+ */export async function upsertSalesRFQ(client: SupabaseClient<Database>,rfq:@@ -6694,6 +6891,7 @@ export async function upsertSalesRFQ(}}+/** @mcp upsert */export async function upsertSalesRFQLine(client: SupabaseClient<Database>,@@ -6734,6 +6932,7 @@ export async function upsertSalesRFQLine(.single();}+/** @mcp update */export async function updateSalesRFQLineOrder(db: Kysely<KyselyDatabase>,companyId: string,@@ -6753,6 +6952,7 @@ export async function updateSalesRFQLineOrder(// ─── Sales Return Orders (RMAs) ───+/** @mcp read */export async function getReturnReasons(client: SupabaseClient<Database>,companyId: string,@@ -6776,6 +6976,7 @@ export async function getReturnReasons(return query;}+/** @mcp read */export async function getReturnReasonsList(client: SupabaseClient<Database>,companyId: string@@ -6787,6 +6988,7 @@ export async function getReturnReasonsList(.order("name");}+/** @mcp read */export async function getReturnReason(client: SupabaseClient<Database>,returnReasonId: string@@ -6798,6 +7000,7 @@ export async function getReturnReason(.single();}+/** @mcp upsert */export async function upsertReturnReason(client: SupabaseClient<Database>,returnReason:@@ -6831,6 +7034,7 @@ export async function upsertReturnReason(.single();}+/** @mcp delete */export async function deleteReturnReason(client: SupabaseClient<Database>,returnReasonId: string@@ -6838,6 +7042,7 @@ export async function deleteReturnReason(return client.from("returnReason").delete().eq("id", returnReasonId);}+/** @mcp read */export async function getSalesReturnOrders(client: SupabaseClient<Database>,companyId: string,@@ -6875,6 +7080,7 @@ export async function getSalesReturnOrders(return query;}+/** @mcp read */export async function getSalesReturnOrder(client: SupabaseClient<Database>,salesReturnOrderId: string@@ -6886,6 +7092,7 @@ export async function getSalesReturnOrder(.single();}+/** @mcp read */export async function getSalesReturnOrderLines(client: SupabaseClient<Database>,salesReturnOrderId: string,@@ -6901,6 +7108,7 @@ export async function getSalesReturnOrderLines(.order("lineNumber");}+/** @mcp read */export async function getSalesReturnOrderLine(client: SupabaseClient<Database>,lineId: string@@ -6912,6 +7120,7 @@ export async function getSalesReturnOrderLine(.single();}+/** @mcp read */export async function getSalesReturnOrderLineTrackedEntities(client: SupabaseClient<Database>,lineIds: string[]@@ -6922,6 +7131,7 @@ export async function getSalesReturnOrderLineTrackedEntities(.in("salesReturnOrderLineId", lineIds);}+/** @mcp create */export async function insertSalesReturnOrder(client: SupabaseClient<Database>,input: {@@ -7043,6 +7253,7 @@ export async function updateSalesReturnOrder(.single();}+/** @mcp upsert */export async function upsertSalesReturnOrderLine(client: SupabaseClient<Database>,line:@@ -7093,6 +7304,7 @@ export async function upsertSalesReturnOrderLine(.single();}+/** @mcp delete */export async function deleteSalesReturnOrder(client: SupabaseClient<Database>,salesReturnOrderId: string@@ -7100,6 +7312,7 @@ export async function deleteSalesReturnOrder(return client.from("salesReturnOrder").delete().eq("id", salesReturnOrderId);}+/** @mcp delete */export async function deleteSalesReturnOrderLine(client: SupabaseClient<Database>,lineId: string@@ -7107,6 +7320,7 @@ export async function deleteSalesReturnOrderLine(return client.from("salesReturnOrderLine").delete().eq("id", lineId);}+/** @mcp read */export async function getSalesReturnOrderReceipts(client: SupabaseClient<Database>,salesReturnOrderId: string,@@ -7121,6 +7335,7 @@ export async function getSalesReturnOrderReceipts(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getSalesReturnOrderCredits(client: SupabaseClient<Database>,salesReturnOrderId: string,@@ -7134,6 +7349,7 @@ export async function getSalesReturnOrderCredits(.order("createdAt", { ascending: false });}+/** @mcp read */export async function getSalesReturnOrderIssues(client: SupabaseClient<Database>,salesReturnOrderId: string,@@ -7153,6 +7369,7 @@ export async function getSalesReturnOrderIssues(* the governing SOURCE rows (shipment/SO/invoice lines) are row-locked so two* concurrent confirms against the same source line serialize, and the* aggregates are re-read under that lock (replaceInvoiceSettlements pattern).+ * @mcp action*/export async function confirmSalesReturnOrder(db: Kysely<KyselyDatabase>,@@ -7367,6 +7584,7 @@ export async function confirmSalesReturnOrder(* receipt exists and nothing received, so reviving is safe). "To Receive" no* longer implies nothing received (it also covers partially received), so the* nothing-received invariant is enforced on the line quantities directly.+ * @mcp action*/export async function reopenSalesReturnOrder(db: Kysely<KyselyDatabase>,@@ -7417,6 +7635,7 @@ export async function reopenSalesReturnOrder(});}+/** @mcp action */export async function cancelSalesReturnOrder(db: Kysely<KyselyDatabase>,{ id, companyId, userId }: { id: string; companyId: string; userId: string }@@ -7481,6 +7700,7 @@ export async function cancelSalesReturnOrder(* short-closing the last open line completes the RMA (there is no separate* manual Complete action, mirroring the Purchase Order). Disposition is tracked* independently and does not gate completion.+ * @mcp action*/export async function shortCloseSalesReturnOrderLine(db: Kysely<KyselyDatabase>,@@ -7572,6 +7792,7 @@ export async function shortCloseSalesReturnOrderLine(* lines from shipment" modal stays responsive when a customer has thousands of* shipment lines. Each row carries `totalCount` — the size of the full* returnable set before limit/offset — so the UI can page through the rest.+ * @mcp read*/export async function getReturnableLinesForCustomer(client: SupabaseClient<Database>,@@ -7598,6 +7819,7 @@ export async function getReturnableLinesForCustomer(* Entity picker source for RMA lines: serials/batches shipped to this* customer (Consumed entities tagged with a posted shipment's id — the* attributes->>X query pattern from getTrackedEntitiesByMakeMethodId).+ * @mcp read*/export async function getShippedTrackedEntitiesForCustomer(client: SupabaseClient<Database>,@@ -7674,6 +7896,7 @@ export async function getShippedTrackedEntitiesForCustomer(* Per-line creditable pool = received − already credited. Draft memos count* against the pool (two Drafts must not double-credit); the VIEW's displayed* quantityCredited still derives from Posted memos only.+ * @mcp read*/export async function getCreditableQuantities(client: SupabaseClient<Database>,@@ -7732,6 +7955,8 @@ export async function getCreditableQuantities(* Drafts count so two drafts can't double-credit) is validated inside the* transaction under a row lock on the RMA lines. Amount is rounded ONCE at* the currency's decimals (settlement boundary). Returns the memo id.+ * @mcp create+ * @mcp audit companyGroupId, createdBy, updatedBy, userId*/export async function createSalesReturnOrderCredit(client: SupabaseClient<Database>,@@ -7914,6 +8139,7 @@ export async function createSalesReturnOrderCredit(* lines, priced via resolvePrice (user adjusts on the draft — e.g. to zero* for warranty). One replacement per RMA; re-invoking returns the existing* link. Rollback-by-delete on line failure (the insertSalesOrder pattern).+ * @mcp create*/export async function createReplacementSalesOrder(client: SupabaseClient<Database>,@@ -8038,6 +8264,7 @@ export async function createReplacementSalesOrder(* shape the NCR disposition writes. Scrap/Rework are set via Issue escalation* (the line's issue route), not through this function's callers' UI, but the* write itself is shared: those dispositions have no entity side effects here.+ * @mcp update*/export async function setSalesReturnOrderLineDisposition(client: SupabaseClient<Database>,@@ -8274,6 +8501,9 @@ export async function setSalesReturnOrderLineDisposition(* returned `path`, the document type as `sourceDocument`, and the quote/order id as* `sourceDocumentId`. The storage folder is scoped by `opportunityId`, which is a* different id from `sourceDocumentId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createOpportunityDocumentUploadUrl(client: SupabaseClient<Database>,@@ -8292,6 +8522,9 @@ export async function createOpportunityDocumentUploadUrl(* two-step upload flow: PUT the file bytes to the returned `signedUrl`, then call* `documents_insertUploadedDocument` with the returned `path`, the line's document* type as `sourceDocument`, and the line id as `sourceDocumentId`.+ * @mcp create — part of the documented MCP signed-URL upload flow+ * (packages/files/AGENTS.md): a non-browser caller mints a staged+ * upload URL, then insertUploadedDocument converts and lands it.*/export async function createOpportunityLineDocumentUploadUrl(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex a8bf41d518..c77ff1256f 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -42,6 +42,7 @@ import { companyValidator } from "./settings.models";const PUBLIC_STORAGE_URL_PREFIX = `${SUPABASE_URL}/storage/v1/object/public/public/`;+/** @mcp read */export async function getAccountsPayableBillingAddress(client: SupabaseClient<Database>,companyId: string@@ -53,6 +54,7 @@ export async function getAccountsPayableBillingAddress(.single();}+/** @mcp read */export async function getAccountsReceivableBillingAddress(client: SupabaseClient<Database>,companyId: string@@ -64,6 +66,7 @@ export async function getAccountsReceivableBillingAddress(.single();}+/** @mcp update */export async function updateAccountsPayableBillingAddress(client: SupabaseClient<Database>,companyId: string,@@ -76,6 +79,7 @@ export async function updateAccountsPayableBillingAddress(.eq("id", companyId);}+/** @mcp update */export async function updateAccountsReceivableBillingAddress(client: SupabaseClient<Database>,companyId: string,@@ -94,6 +98,10 @@ export async function deleteSubsidiary(return client.from("company").delete().eq("id", companyId);}+/**+ * @mcp read+ * @mcp permission users:update+ */export async function getApiKeys(client: SupabaseClient<Database>,companyId: string,@@ -133,7 +141,10 @@ function withLogoUrls(company: CompaniesRow) {};}-// The view already carries `companyGroupName`, so there is nothing to embed.+/**+ * The view already carries `companyGroupName`, so there is nothing to embed.+ * @mcp read+ */export async function getCompanies(client: SupabaseClient<Database>,userId: string@@ -151,12 +162,6 @@ export async function getCompanies(return { data: companies.data.map(withLogoUrls), error: null };}-/**- * The companies a user can enter in the ERP. ERP is an employee app, so- * supplier/customer-only memberships (which belong to the portals) are- * excluded. Single source of truth for the login callback, the select-company- * picker, and the x+/_layout enforcement guard — keep those in sync via this.- *//** The `getEmployeeCompanies` filter, for a list already loaded by `getCompanies`. */export function employeeCompaniesOf<T extends { role: string | null }>(companies: T[]@@ -164,6 +169,13 @@ export function employeeCompaniesOf<T extends { role: string | null }>(return companies.filter((company) => company.role === "employee");}+/**+ * The companies a user can enter in the ERP. ERP is an employee app, so+ * supplier/customer-only memberships (which belong to the portals) are+ * excluded. Single source of truth for the login callback, the select-company+ * picker, and the x+/_layout enforcement guard — keep those in sync via this.+ * @mcp read+ */export async function getEmployeeCompanies(client: SupabaseClient<Database>,userId: string@@ -182,6 +194,7 @@ export async function getEmployeeCompanies(return { data: companies.data.map(withLogoUrls), error: null };}+/** @mcp read */export async function getIndustries(client: SupabaseClient<Database>) {return client.from("industry")@@ -190,6 +203,7 @@ export async function getIndustries(client: SupabaseClient<Database>) {.order("sortOrder");}+/** @mcp read */export async function getCompany(client: SupabaseClient<Database>,companyId: string@@ -226,6 +240,7 @@ export async function getCompany(};}+/** @mcp read */export async function getCompanyIntegrations(client: SupabaseClient<Database>,companyId: string@@ -236,6 +251,7 @@ export async function getCompanyIntegrations(.eq("companyId", companyId);}+/** @mcp read */export async function getCompanyPlan(client: SupabaseClient,companyId: string@@ -243,6 +259,7 @@ export async function getCompanyPlan(return client.from("companyPlan").select("*").eq("id", companyId).single();}+/** @mcp read */export async function getCompanySettings(client: SupabaseClient<Database>,companyId: string@@ -254,10 +271,12 @@ export async function getCompanySettings(.single();}+/** @mcp read */export async function getConfig(client: SupabaseClient<Database>) {return client.from("config").select("*").single();}+/** @mcp read */export async function getCurrentSequence(client: SupabaseClient<Database>,table: string,@@ -283,6 +302,7 @@ export async function getCurrentSequence(};}+/** @mcp read */export async function getCustomField(client: SupabaseClient<Database>,id: string@@ -290,6 +310,7 @@ export async function getCustomField(return client.from("customField").select("*").eq("id", id).single();}+/** @mcp read */export async function getCustomFields(client: SupabaseClient<Database>,table: string,@@ -303,6 +324,7 @@ export async function getCustomFields(.single();}+/** @mcp read */export async function getCustomFieldsTables(client: SupabaseClient<Database>,companyId: string,@@ -327,6 +349,7 @@ export async function getCustomFieldsTables(return query;}+/** @mcp read */export async function getIntegration(client: SupabaseClient<Database>,id: string,@@ -340,6 +363,7 @@ export async function getIntegration(.maybeSingle();}+/** @mcp read */export async function getIntegrations(client: SupabaseClient<Database>,companyId: string@@ -347,6 +371,7 @@ export async function getIntegrations(return client.from("integrations").select("*").eq("companyId", companyId);}+/** @mcp read */export async function getKanbanOutputSetting(client: SupabaseClient<Database>,companyId: string@@ -358,6 +383,7 @@ export async function getKanbanOutputSetting(.single();}+/** @mcp read */export async function getNextSequence(client: SupabaseClient<Database>,table: string,@@ -369,14 +395,17 @@ export async function getNextSequence(});}+/** @mcp read */export async function getPlanById(client: SupabaseClient, planId: string) {return client.from("plan").select("*").eq("id", planId).single();}+/** @mcp read */export async function getPlans(client: SupabaseClient) {return client.from("plan").select("*");}+/** @mcp read */export async function getSequence(client: SupabaseClient<Database>,table: string,@@ -390,6 +419,7 @@ export async function getSequence(.single();}+/** @mcp read */export async function getSequences(client: SupabaseClient<Database>,companyId: string,@@ -414,6 +444,7 @@ export async function getSequences(return query;}+/** @mcp read */export async function getSequencesList(client: SupabaseClient<Database>,table: string,@@ -427,6 +458,7 @@ export async function getSequencesList(.order("table");}+/** @mcp read */export async function getItemSerialSequences(client: SupabaseClient<Database>,companyId: string,@@ -456,6 +488,7 @@ export async function getItemSerialSequences(return query;}+/** @mcp read */export async function getItemSerialSequence(client: SupabaseClient<Database>,id: string,@@ -469,6 +502,7 @@ export async function getItemSerialSequence(.single();}+/** @mcp read */export async function getItemSerialSequenceByItemId(client: SupabaseClient<Database>,itemId: string,@@ -482,6 +516,7 @@ export async function getItemSerialSequenceByItemId(.maybeSingle();}+/** @mcp upsert */export async function upsertItemSerialSequence(client: SupabaseClient<Database>,itemSerialSequence:@@ -512,6 +547,7 @@ export async function upsertItemSerialSequence(.single();}+/** @mcp delete */export async function deleteItemSerialSequence(client: SupabaseClient<Database>,id: string,@@ -524,6 +560,7 @@ export async function deleteItemSerialSequence(.eq("companyId", companyId);}+/** @mcp read */export async function getSubsidiaries(client: SupabaseClient<Database>,companyGroupId: string@@ -537,6 +574,7 @@ export async function getSubsidiaries(.order("name");}+/** @mcp read */export async function getSubsidiary(client: SupabaseClient<Database>,companyId: string@@ -544,6 +582,7 @@ export async function getSubsidiary(return client.from("company").select("*").eq("id", companyId).single();}+/** @mcp read */export async function getTerms(client: SupabaseClient<Database>,companyId: string@@ -551,6 +590,7 @@ export async function getTerms(return client.from("terms").select("*").eq("id", companyId).single();}+/** @mcp read */export async function getDocumentTemplate(client: SupabaseClient<Database>,companyId: string,@@ -568,6 +608,7 @@ export async function getDocumentTemplate(* Load a stored document template as a `DocumentTemplate | null` ready to pass* to a PDF (which runs it through `resolveTemplate`). Returns null when no row* is stored, so the PDF falls back to the type's default.+ * @mcp read*/export async function getDocumentTemplateConfig(client: SupabaseClient<Database>,@@ -578,6 +619,7 @@ export async function getDocumentTemplateConfig(return toDocumentTemplate(stored.data, documentType);}+/** @mcp upsert */export async function upsertDocumentTemplate(client: SupabaseClient<Database>,documentTemplate: {@@ -603,6 +645,7 @@ export async function upsertDocumentTemplate();}+/** @mcp read */export async function getDocumentSections(client: SupabaseClient<Database>,companyId: string@@ -614,6 +657,7 @@ export async function getDocumentSections(.order("name");}+/** @mcp read */export async function getDocumentSection(client: SupabaseClient<Database>,id: string,@@ -627,6 +671,7 @@ export async function getDocumentSection(.maybeSingle();}+/** @mcp read */export async function getDocumentSectionsByIds(client: SupabaseClient<Database>,companyId: string,@@ -639,6 +684,7 @@ export async function getDocumentSectionsByIds(.in("id", ids);}+/** @mcp upsert */export async function upsertDocumentSection(client: SupabaseClient<Database>,documentSection: {@@ -701,6 +747,7 @@ export async function upsertDocumentSection(.select("id");}+/** @mcp delete */export async function deleteDocumentSection(client: SupabaseClient<Database>,id: string,@@ -713,7 +760,10 @@ export async function deleteDocumentSection(.eq("companyId", companyId);}-/** Fetch the given section ids and return them keyed by id for rendering. */+/**+ * Fetch the given section ids and return them keyed by id for rendering.+ * @mcp action+ */export async function resolveSections(client: SupabaseClient<Database>,companyId: string,@@ -743,10 +793,12 @@ export async function resolveSections(return map;}+/** @mcp read */export async function getWebhook(client: SupabaseClient<Database>, id: string) {return client.from("webhook").select("*").eq("id", id).single();}+/** @mcp read */export async function getWebhooks(client: SupabaseClient<Database>,companyId: string,@@ -772,6 +824,7 @@ export async function getWebhooks(return query;}+/** @mcp read */export async function getWebhookTables(client: SupabaseClient<Database>) {return client.from("webhookTable").select("*").order("name");}@@ -800,6 +853,7 @@ export async function insertSubsidiary(return client.from("company").insert(data).select("id").single();}+/** @mcp update */export async function updateSubsidiary(client: SupabaseClient<Database>,id: string,@@ -843,6 +897,7 @@ export async function updateCompanyPlan(return client.from("companyPlan").update(updateData).eq("id", companyId);}+/** @mcp update */export async function updateDefaultCustomerCc(client: SupabaseClient<Database>,companyId: string,@@ -859,6 +914,7 @@ export async function updateDefaultCustomerCc();}+/** @mcp update */export async function updateCompany(client: SupabaseClient<Database>,companyId: string,@@ -875,6 +931,7 @@ export async function updateCompany(* — a committed base flip with surviving old-base pins silently mis-rates* every new document, and a non-atomic cleanup can race a freshly created* new-base override. Kysely throws on rollback; the route try/catches.+ * @mcp update destructive*/export async function updateCompanyWithBaseCurrencyChange(db: Kysely<KyselyDatabase>,@@ -904,6 +961,7 @@ export async function updateCompanyWithBaseCurrencyChange(});}+/** @mcp update */export async function updateShelfLifeSettings(client: SupabaseClient<Database>,companyId: string,@@ -931,6 +989,7 @@ export async function updateShelfLifeSettings(.eq("id", companyId);}+/** @mcp update */export async function updateDigitalQuoteSetting(client: SupabaseClient<Database>,companyId: string,@@ -955,6 +1014,7 @@ export async function updateDigitalQuoteSetting(// client barrel (~/modules/settings) — a `@carbon/auth/client.server` import here// would pull the service-role client into the browser bundle (Vite blocks it).+/** @mcp update */export async function updateAccountingEnabledSetting(client: SupabaseClient<Database>,companyId: string,@@ -966,6 +1026,7 @@ export async function updateAccountingEnabledSetting(.eq("id", companyId);}+/** @mcp update */export async function updateAssetTaxDepreciationSettings(client: SupabaseClient<Database>,companyId: string,@@ -980,6 +1041,7 @@ export async function updateAssetTaxDepreciationSettings(.eq("id", companyId);}+/** @mcp update */export async function updateTimeCardSetting(client: SupabaseClient<Database>,companyId: string,@@ -991,6 +1053,7 @@ export async function updateTimeCardSetting(.eq("id", companyId);}+/** @mcp update */export async function updateKanbanOutputSetting(client: SupabaseClient<Database>,companyId: string,@@ -1002,6 +1065,7 @@ export async function updateKanbanOutputSetting(.eq("id", companyId);}+/** @mcp update */export async function updateLogoDark(client: SupabaseClient<Database>,companyId: string,@@ -1017,6 +1081,7 @@ export async function updateLogoDark(.eq("id", companyId);}+/** @mcp update */export async function updateLogoDarkIcon(client: SupabaseClient<Database>,companyId: string,@@ -1028,6 +1093,7 @@ export async function updateLogoDarkIcon(.eq("id", companyId);}+/** @mcp update */export async function updateLogoLight(client: SupabaseClient<Database>,companyId: string,@@ -1039,6 +1105,7 @@ export async function updateLogoLight(.eq("id", companyId);}+/** @mcp update */export async function updateLogoLightIcon(client: SupabaseClient<Database>,companyId: string,@@ -1050,6 +1117,7 @@ export async function updateLogoLightIcon(.eq("id", companyId);}+/** @mcp update */export async function updateLogoWatermark(client: SupabaseClient<Database>,companyId: string,@@ -1061,6 +1129,7 @@ export async function updateLogoWatermark(.eq("id", companyId);}+/** @mcp update */export async function updateMaintenanceDispatchNotificationSettings(client: SupabaseClient<Database>,companyId: string,@@ -1077,6 +1146,7 @@ export async function updateMaintenanceDispatchNotificationSettings(.eq("id", companyId);}+/** @mcp update */export async function updateMaterialGeneratedIdsSetting(client: SupabaseClient<Database>,companyId: string,@@ -1088,6 +1158,7 @@ export async function updateMaterialGeneratedIdsSetting(.eq("id", companyId);}+/** @mcp update */export async function updateMetricSettings(client: SupabaseClient<Database>,companyId: string,@@ -1099,6 +1170,7 @@ export async function updateMetricSettings(.eq("id", companyId);}+/** @mcp update */export async function updateAllowLowercaseItemIdsSetting(client: SupabaseClient<Database>,companyId: string,@@ -1110,6 +1182,7 @@ export async function updateAllowLowercaseItemIdsSetting(.eq("id", companyId);}+/** @mcp update */export async function updateBomExplorerReadableIdSetting(client: SupabaseClient<Database>,companyId: string,@@ -1121,6 +1194,7 @@ export async function updateBomExplorerReadableIdSetting(.eq("id", companyId);}+/** @mcp update */export async function updatePlmReleaseControlSetting(client: SupabaseClient<Database>,companyId: string,@@ -1143,6 +1217,7 @@ export async function updateProductLabelSize(.eq("id", companyId);}+/** @mcp update */export async function updatePurchasePriceUpdateTimingSetting(client: SupabaseClient<Database>,companyId: string,@@ -1154,6 +1229,7 @@ export async function updatePurchasePriceUpdateTimingSetting(.eq("id", companyId);}+/** @mcp update */export async function updateLeadTimesOnReceiptSetting(client: SupabaseClient<Database>,companyId: string,@@ -1164,6 +1240,7 @@ export async function updateLeadTimesOnReceiptSetting(.eq("id", companyId);}+/** @mcp update */export async function updateIncludeMaterialsOnTravelerSetting(client: SupabaseClient<Database>,companyId: string,@@ -1177,6 +1254,7 @@ export async function updateIncludeMaterialsOnTravelerSetting(.eq("id", companyId);}+/** @mcp update */export async function updateIncludeOperationsOnTravelerSetting(client: SupabaseClient<Database>,companyId: string,@@ -1188,6 +1266,7 @@ export async function updateIncludeOperationsOnTravelerSetting(.eq("id", companyId);}+/** @mcp update */export async function updateAccountsPayableAddressSetting(client: SupabaseClient<Database>,companyId: string,@@ -1204,6 +1283,7 @@ export async function updateAccountsPayableAddressSetting(** See `party-contact.ts` for why the requirement lives on the PARTY and why the* bar is an email rather than merely a contact row.+ * @mcp update*/export async function updateRequireSupplierContactSetting(client: SupabaseClient<Database>,@@ -1216,7 +1296,10 @@ export async function updateRequireSupplierContactSetting(.eq("id", companyId);}-/** The customer-side mirror. Ships off; nothing downstream forces it today. */+/**+ * The customer-side mirror. Ships off; nothing downstream forces it today.+ * @mcp update+ */export async function updateRequireCustomerContactSetting(client: SupabaseClient<Database>,companyId: string,@@ -1228,6 +1311,7 @@ export async function updateRequireCustomerContactSetting(.eq("id", companyId);}+/** @mcp update */export async function updateAccountsReceivableAddressSetting(client: SupabaseClient<Database>,companyId: string,@@ -1263,6 +1347,7 @@ export async function updateAccountsReceivableEmail(.eq("id", companyId);}+/** @mcp update */export async function updateSalesRuleNotificationSetting(client: SupabaseClient<Database>,companyId: string,@@ -1274,6 +1359,7 @@ export async function updateSalesRuleNotificationSetting(.eq("id", companyId);}+/** @mcp update */export async function updateQuoteLineCategoryMarkups(client: SupabaseClient<Database>,companyId: string,@@ -1285,6 +1371,7 @@ export async function updateQuoteLineCategoryMarkups(.eq("id", companyId);}+/** @mcp update */export async function updateRfqReadySetting(client: SupabaseClient<Database>,companyId: string,@@ -1296,6 +1383,7 @@ export async function updateRfqReadySetting(.eq("id", companyId);}+/** @mcp update */export async function updateSequence(client: SupabaseClient<Database>,table: string,@@ -1311,6 +1399,7 @@ export async function updateSequence(.eq("table", table);}+/** @mcp update */export async function updateSuggestionNotificationSetting(client: SupabaseClient<Database>,companyId: string,@@ -1322,6 +1411,7 @@ export async function updateSuggestionNotificationSetting(.eq("id", companyId);}+/** @mcp update */export async function updateSupplierQuoteNotificationSetting(client: SupabaseClient<Database>,companyId: string,@@ -1333,6 +1423,7 @@ export async function updateSupplierQuoteNotificationSetting(.eq("id", companyId);}+/** @mcp update */export async function updateDefaultSupplierCc(client: SupabaseClient<Database>,companyId: string,@@ -1344,6 +1435,7 @@ export async function updateDefaultSupplierCc(.eq("id", companyId);}+/** @mcp update */export async function updateShowCurrencyTrailingZerosSetting(client: SupabaseClient<Database>,companyId: string,@@ -1355,6 +1447,7 @@ export async function updateShowCurrencyTrailingZerosSetting(.eq("id", companyId);}+/** @mcp update */export async function updateShowSupplierReadableIdSetting(client: SupabaseClient<Database>,companyId: string,@@ -1366,6 +1459,7 @@ export async function updateShowSupplierReadableIdSetting(.eq("id", companyId);}+/** @mcp update */export async function updateShowCustomerReadableIdSetting(client: SupabaseClient<Database>,companyId: string,@@ -1377,6 +1471,7 @@ export async function updateShowCustomerReadableIdSetting(.eq("id", companyId);}+/** @mcp update */export async function updateAutoSelectMaterialWithoutPickingListSetting(client: SupabaseClient<Database>,companyId: string,@@ -1388,6 +1483,7 @@ export async function updateAutoSelectMaterialWithoutPickingListSetting(.eq("id", companyId);}+/** @mcp update */export async function updateIncompletePickingListPolicySetting(client: SupabaseClient<Database>,companyId: string,@@ -1399,6 +1495,7 @@ export async function updateIncompletePickingListPolicySetting(.eq("id", companyId);}+/** @mcp update */export async function updateReturnPickedMaterialTimingSetting(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 81bbcec1be..a8cee6ce69 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -21,6 +21,7 @@ export async function deleteNote(return client.from("note").update({ active: false }).eq("id", noteId);}+/** @mcp delete */export async function deleteSavedView(client: SupabaseClient<Database>,viewId: string@@ -51,6 +52,7 @@ export async function generateEmbedding(return response.data.embedding as number[];}+/** @mcp read */export async function getBase64ImageFromSupabase(client: SupabaseClient<Database>,path: string@@ -84,6 +86,7 @@ export async function getBase64ImageFromSupabase(return `data:${mimeType};base64,${base64String}`;}+/** @mcp read */export async function getCountries(client: SupabaseClient<Database>) {return client.from("country").select("*").order("name");}@@ -92,6 +95,7 @@ export async function getCountries(client: SupabaseClient<Database>) {* Timezone names from the database's own tzdata (pg_timezone_names via the* get_timezone_names RPC) — the authoritative list for what AT TIME ZONE* resolves.+ * @mcp read*/export async function getTimezoneNames(client: SupabaseClient<Database>) {return client.rpc("get_timezone_names");@@ -103,6 +107,7 @@ export { getDocumentType } from "@carbon/files";* The item's CAD model in the same shape the line views expose it, so it drops* straight into `<CadModel modelUpload={...} />`. Always the full shape — an item* with no model is every field null, never a narrower branch.+ * @mcp read*/export async function getModelByItemId(client: SupabaseClient<Database>,@@ -143,6 +148,7 @@ export async function getModelByItemId(};}+/** @mcp read */export async function getNotes(client: SupabaseClient<Database>,documentId: string@@ -157,6 +163,7 @@ export async function getNotes(.order("createdAt");}+/** @mcp read */export async function getPeriods(client: SupabaseClient<Database>,{ startDate, endDate }: { startDate: string; endDate: string }@@ -169,6 +176,7 @@ export async function getPeriods(.lte("endDate", endWithTime);}+/** @mcp read */export async function getSavedViews(client: SupabaseClient<Database>,userId: string,@@ -182,6 +190,7 @@ export async function getSavedViews(.order("name");}+/** @mcp read */export async function getTagsList(client: SupabaseClient<Database>,companyId: string,@@ -196,6 +205,7 @@ export async function getTagsList(return query.order("name");}+/** @mcp action */export async function importCsv(client: SupabaseClient<Database>,args: {@@ -212,6 +222,7 @@ export async function importCsv(});}+/** @mcp create */export async function insertNote(client: SupabaseClient<Database>,note: {@@ -224,6 +235,7 @@ export async function insertNote(return client.from("note").insert([note]).select("*").single();}+/** @mcp create */export async function insertTag(client: SupabaseClient<Database>,tag: Database["public"]["Tables"]["tag"]["Insert"]@@ -231,6 +243,7 @@ export async function insertTag(return client.from("tag").insert(tag).select("*").single();}+/** @mcp read */export async function getExternalLink(client: SupabaseClient<Database>,id: string@@ -240,6 +253,7 @@ export async function getExternalLink(return query;}+/** @mcp upsert */export async function upsertExternalLink(client: SupabaseClient<Database>,externalLink:@@ -263,6 +277,7 @@ export async function upsertExternalLink(.single();}+/** @mcp read */export async function getCustomerPortals(client: SupabaseClient<Database>,companyId: string,@@ -287,6 +302,7 @@ export async function getCustomerPortals(return query;}+/** @mcp read */export async function getCustomerPortal(client: SupabaseClient<Database>,id: string@@ -343,6 +359,7 @@ export async function updateNote(return client.from("note").update({ note }).eq("id", id);}+/** @mcp upsert */export async function upsertSavedView(client: SupabaseClient<Database>,view: {@@ -397,6 +414,7 @@ export async function upsertSavedView(.single();}+/** @mcp update */export async function updateSavedViewOrder(client: SupabaseClient<Database>,updates: {@@ -415,6 +433,7 @@ export async function updateSavedViewOrder(* Core sync lookup: given price break tiers and a requested quantity,* return the unit price from the highest qualifying tier* (where tier.quantity <= requestedQty). Falls back to fallbackPrice.+ * @mcp read*/export function lookupPriceFromBreaks(priceBreaks: PriceBreak[],@@ -433,6 +452,7 @@ export function lookupPriceFromBreaks(/*** Map-aware wrapper: look up itemId in a SupplierPriceMap, then resolve* via lookupPriceFromBreaks. Used by useLineCosts for BOM tree costing.+ * @mcp read*/export function lookupBuyPriceFromMap(itemId: string,@@ -456,6 +476,7 @@ export function lookupBuyPriceFromMap(* lookupBuyPriceFromMap directly silently ignores a typed cost.** Mirrored in the Deno edge runtime (`functions/lib/methods.ts`).+ * @mcp action*/export function resolveBuyUnitCost(material: {@@ -486,6 +507,7 @@ export function resolveBuyUnitCost(** @param fallbackUnitPrice base currency, used when no break matches* @returns the price in the supplier's currency+ * @mcp read*/export function resolveSupplierPrice(priceBreaks: PriceBreak[],@@ -524,6 +546,7 @@ export type EnforcementRuleRow =// they embed the commercial `requireEntitlement` gate. The read helpers below// stay here (ERP admin surface, client-safe).+/** @mcp read */export async function getEnforcementRules(client: SupabaseClient<Database>,family: EnforcementRuleFamily,@@ -556,6 +579,7 @@ export async function getEnforcementRules(]) as unknown as Promise<PostgrestResponse<EnforcementRuleRow>>;}+/** @mcp read */export async function getEnforcementRule(client: SupabaseClient<Database>,family: EnforcementRuleFamily,@@ -584,6 +608,7 @@ export async function getEnforcementRule(* no family predicate even though the item table is shared between families.* Work-center pins only exist for the storage family; passing sales ids simply* matches nothing there.+ * @mcp read*/export async function getEnforcementRuleAssignmentCounts(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex 8de8df349a..a9fbb8c3a0 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -17,6 +17,7 @@ const logger = getLogger("erp", "users");* The ITAR gate: does a valid, unexpired entity Rider acceptance exist for this* company, and a valid user attestation for this user? Both are required before* a person can enter a controlled environment.+ * @mcp read*/export async function getItarCertificationStatus(client: SupabaseClient<Database>,@@ -59,6 +60,7 @@ export async function getItarCertificationStatus(** Carbon staff never appear here: the Rider binds the customer's own* organization, so only the customer's admin can produce this row.+ * @mcp read*/export async function getItarEntityCertification(client: SupabaseClient<Database>,@@ -83,6 +85,7 @@ export async function getItarEntityCertification(* certifications) don't silently lose rows; certs are already company-scoped, so* we fetch them all and group in memory rather than passing an unbounded `userId`* array to `.in()`. Last login is layered on in the route from the Auth admin API.+ * @mcp read*/export async function getItarCertificationReport(client: SupabaseClient<Database>,@@ -150,6 +153,7 @@ export async function getItarCertificationReport(return { data, error: null };}+/** @mcp delete */export async function deleteGroup(client: SupabaseClient<Database>,groupId: string@@ -157,6 +161,7 @@ export async function deleteGroup(return client.from("group").delete().eq("id", groupId);}+/** @mcp read */export async function getCompaniesForUser(client: SupabaseClient<Database>,userId: string@@ -174,6 +179,7 @@ export async function getCompaniesForUser(return data?.map((row) => row.companyId) ?? [];}+/** @mcp read */export async function getCustomers(client: SupabaseClient<Database>,companyId: string,@@ -201,6 +207,7 @@ export async function getCustomers(return query;}+/** @mcp read */export async function getEmployee(client: SupabaseClient<Database>,id: string,@@ -216,6 +223,7 @@ export async function getEmployee(// Pending only (mirrors the 'Invited' condition in the `employees` view): counting// accepted invites would leave a deactivated employee with no way to be re-invited.+/** @mcp read */export async function getUnrevokedInviteEmails(client: SupabaseClient<Database>,companyId: string@@ -234,6 +242,7 @@ export async function getUnrevokedInviteEmails(* One RPC rather than a per-row lookup: TOTP factors live in Supabase's* `auth.mfa_factors`, so the alternative is an admin-API call per employee —* an N+1 that degrades with headcount.+ * @mcp read*/export async function getUsersWithVerifiedMfa(client: SupabaseClient<Database>,@@ -242,6 +251,7 @@ export async function getUsersWithVerifiedMfa(return client.rpc("users_with_verified_mfa", { company_id: companyId });}+/** @mcp read */export async function getEmployees(client: SupabaseClient<Database>,companyId: string,@@ -281,6 +291,7 @@ export async function getEmployees(** TODO: After running db:generate, replace email pattern filter with* .eq("isConsoleOperator", true) once the column is in the employees view.+ * @mcp read*/export async function getConsoleOperators(client: SupabaseClient<Database>,@@ -305,6 +316,7 @@ export async function getConsoleOperators(return query;}+/** @mcp read */export async function getEmployeeType(client: SupabaseClient<Database>,employeeTypeId: string@@ -316,6 +328,7 @@ export async function getEmployeeType(.single();}+/** @mcp read */export async function getEmployeeTypes(client: SupabaseClient<Database>,companyId: string,@@ -339,6 +352,7 @@ export async function getEmployeeTypes(return query;}+/** @mcp read */export async function getInvitable(client: SupabaseClient<Database>,companyId: string@@ -351,10 +365,12 @@ export async function getInvitable(.order("lastName");}+/** @mcp read */export async function getModules(client: SupabaseClient<Database>) {return client.from("modules").select("name").order("name");}+/** @mcp read */export async function getGroup(client: SupabaseClient<Database>,groupId: string@@ -362,6 +378,7 @@ export async function getGroup(return client.from("group").select("id, name").eq("id", groupId).single();}+/** @mcp read */export async function getGroupMembers(client: SupabaseClient<Database>,groupId: string@@ -372,6 +389,7 @@ export async function getGroupMembers(.eq("groupId", groupId);}+/** @mcp read */export async function getGroups(client: SupabaseClient<Database>,companyId: string,@@ -392,6 +410,7 @@ export async function getGroups(return query;}+/** @mcp read */export async function getGroupEmails(client: SupabaseClient<Database>,groupIds: string[]@@ -407,6 +426,7 @@ export async function getGroupEmails(return getUserEmails(client, userIdsResult.data);}+/** @mcp read */export async function getUserSelectGroups(client: SupabaseClient<Database>,companyId: string,@@ -421,6 +441,7 @@ export async function getUserSelectGroups(});}+/** @mcp read */export async function getUserSelectGroupMembers(client: SupabaseClient<Database>,companyId: string,@@ -439,6 +460,7 @@ export async function getUserSelectGroupMembers(};}+/** @mcp read */export async function searchUsersForSelect(client: SupabaseClient<Database>,companyId: string,@@ -486,6 +508,7 @@ export async function searchUsersForSelect(return query;}+/** @mcp action */export async function resolveUserSelectIds(client: SupabaseClient<Database>,companyId: string,@@ -506,6 +529,7 @@ export async function resolveUserSelectIds(return { users, groups };}+/** @mcp read */export async function getPermissionsByEmployeeType(client: SupabaseClient<Database>,employeeTypeId: string@@ -516,6 +540,7 @@ export async function getPermissionsByEmployeeType(.eq("employeeTypeId", employeeTypeId);}+/** @mcp read */export async function getSuppliers(client: SupabaseClient<Database>,companyId: string,@@ -543,6 +568,7 @@ export async function getSuppliers(return query;}+/** @mcp read */export async function getUsers(client: SupabaseClient<Database>) {return fetchAllFromTable<{id: string;@@ -559,6 +585,7 @@ export async function getUsers(client: SupabaseClient<Database>) {);}+/** @mcp read */export async function getUserEmails(client: SupabaseClient<Database>,userIds: string[]@@ -578,6 +605,7 @@ export async function getUserEmails(.filter((email): email is string => !!email);}+/** @mcp create */export async function insertGroup(client: SupabaseClient<Database>,group: { name: string; companyId: string }@@ -585,6 +613,7 @@ export async function insertGroup(return client.from("group").insert(group).select("*").single();}+/** @mcp upsert */export async function upsertGroup(client: SupabaseClient<Database>,{@@ -600,6 +629,7 @@ export async function upsertGroup(return client.from("group").upsert([{ id, name, companyId }]);}+/** @mcp upsert destructive */export async function upsertGroupMembers(client: SupabaseClient<Database>,groupId: string,diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.tsindex b87e009bcb..c39f98f06a 100644--- a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts@@ -49,7 +49,10 @@ export const MCP_BLOCKED_TOOL_NAMES: readonly string[] = ["sales_updateSalesOrderFavorite","sales_updateSalesRFQFavorite","purchasing_updateSupplierQuoteFavorite",- "resources_insertTrainingCompletion"+ "resources_insertTrainingCompletion",+ // Variadic (`...items`): the dispatcher fills one positional argument per+ // parameter from a JSON object and has no slot for a rest tail.+ "production_getPartDocuments"];export function isMcpBlockedTool(name: string): boolean {diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.tsnew file mode 100644index 0000000000..2ae1429b8d--- /dev/null+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.ts@@ -0,0 +1,154 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * How a service function becomes an MCP / v1-API tool: it SAYS so, in its doc+ * comment. Nothing about a tool is read off the function's name.+ *+ * ```ts+ * /**+ * * Creates or updates a customer.+ * * @mcp upsert+ * *\/+ * export async function upsertCustomer(…)+ * ```+ *+ * The published name is still `{module}_{functionName}`; everything else — what+ * the tool is, which permission it needs, which audit fields it is handed — is+ * declared.+ *+ * It used to be inferred. Every exported function was a tool, and its name+ * decided the rest: `get*` was a read whatever it did (two that inserted rows+ * were published on `view`), `upsert*` meant "stamp createdBy and updatedBy"+ * whether or not the table had them (`items_upsertItemCustomerPart` failed+ * every call with PGRST204), and a read named `diffMethod` demanded `update`.+ * Blocking tools one at a time reached 18 entries against 1557 tools while 211+ * tools had no in-app caller at all.+ */++import type { AuthField, Classification, PermissionAction } from "@carbon/api";++/**+ * Modules whose functions may be exposed at all. A module absent here exposes+ * nothing, whatever its functions are tagged with — the coarse gate, so taking+ * a whole domain off the API is one line rather than a tagging sweep.+ */+export const MCP_MODULE_ALLOWLIST: readonly string[] = [+ "account",+ "accounting",+ "documents",+ "inventory",+ "invoicing",+ "items",+ "people",+ "production",+ "purchasing",+ "quality",+ "resources",+ "sales",+ "settings",+ "shared",+ "users"+];++/**+ * The one tag. Every line a function says about itself as a tool starts with+ * it, in lowercase:+ *+ * ```+ * @mcp <verb> [destructive] required — no such line, not a tool+ * @mcp permission <module>:<action>[+<action>]+ * @mcp audit <field>[, <field>]+ * @mcp key <table> <column>[=<field>][, …]+ * ```+ *+ * Free text after a declaration is a note for the reader+ * (`@mcp upsert destructive — it delegates to …`).+ */+export const MCP_EXPOSURE_TAG = "@mcp";++/**+ * The verbs, and what each one means for the tool. This table is the whole+ * contract: the generator copies these values and never looks at a name.+ *+ * `audit` is what the dispatcher stamps onto the payload besides `companyId`.+ * A field the function's one table has no column for is still dropped, and a+ * payload that declares its own `userId` still gets it — both are read from+ * the schema and the signature, not guessed.+ *+ * `action` is a state change that is not a row edit — lock a period, complete+ * an operation, finalize a quote. It needs `update` and is handed no audit+ * fields; the service or the function it calls records who did it.+ */+export const MCP_VERBS = {+ read: { classification: "READ", actions: ["view"], audit: [] },+ create: {+ classification: "WRITE",+ actions: ["create"],+ audit: ["createdBy", "updatedBy"]+ },+ update: {+ classification: "WRITE",+ actions: ["update"],+ audit: ["updatedBy"]+ },+ upsert: {+ classification: "WRITE",+ actions: ["create", "update"],+ audit: ["createdBy", "updatedBy"]+ },+ delete: { classification: "DESTRUCTIVE", actions: ["delete"], audit: [] },+ action: { classification: "WRITE", actions: ["update"], audit: [] }+} as const satisfies Record<+ string,+ {+ classification: Classification;+ actions: readonly PermissionAction[];+ audit: readonly AuthField[];+ }+>;++export type McpVerb = keyof typeof MCP_VERBS;++/**+ * The word after the verb for a write that can REMOVE data the caller did not+ * name — a delete-then-reinsert upsert drops whatever was left out of the+ * payload. It only changes how the tool is labelled to a client; permission+ * and audit fields stay the verb's. The generator refuses a write whose body+ * deletes rows without it, and refuses `read` on a body that writes at all.+ */+export const MCP_DESTRUCTIVE = "destructive";++/**+ * The words that start an `@mcp` line which is a SETTING rather than the verb.+ *+ * `permission <module>:<action>[+<action>]` — only when the tool gates on+ * something other than its own module and its verb's action. `getApiKeys`+ * lives in settings but is an admin capability: its route gates on+ * `users:update`, so a settings-scoped key must not read the key list.+ *+ * `audit <field>[, <field>]` — only when the verb's audit fields are wrong for+ * INTENT the schema cannot express, and stated in full (plus `companyId`, which+ * is always stamped). A ledger insert takes `createdBy` alone: the `updatedBy`+ * column exists, but a ledger row is never edited and a stamped `updatedBy`+ * would break its "untouched since creation" guarantee.+ *+ * `key <table> <column>[=<field>][, …]` — the row an upsert UPDATES when it+ * already exists, for a service whose payload cannot say whether it is creating+ * or updating. Most upserts take an optional `id`: sent means update, omitted+ * means create, and the generator reads that off the parameter's type. A few+ * cannot be read that way — a part's `id` is its part number on create and its+ * item id (or part number) on update; a pick method has no id at all, only an+ * item and a location. For those the dispatcher looks the row up, scoped to the+ * caller's company, and updates when it is there. `column` is compared with the+ * payload field of the same name unless `=<field>` names another, and several+ * `key` lines are alternatives. These tools used to demand a+ * `_operation: "create" | "update"` argument, which made every caller state+ * something the server could find out.+ */+export const MCP_SETTINGS = {+ permission: "permission",+ audit: "audit",+ key: "key"+} as const;diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex e3ecba59b9..a0c0bf13b6 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1561,+ "totalTools": 1478,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -11,13 +11,10 @@{"name":"account_getNotificationPreferences","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0486649779fc","injectAuth":"companyId","permission":"none","paginates":false},{"name":"account_getPrivateAttributes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},{"name":"account_getPublicAttributes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_updateAvatar","classification":"WRITE","paramCount":1,"schema":"a2f2d0de3049","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},- {"name":"account_updatePublicAccount","classification":"WRITE","paramCount":5,"schema":"1995f647bdcf","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},+ {"name":"account_updateAvatar","classification":"WRITE","paramCount":1,"schema":"a2f2d0de3049","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"account_updatePublicAccount","classification":"WRITE","paramCount":5,"schema":"1995f647bdcf","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"account_upsertNotificationPreference","classification":"WRITE","paramCount":3,"schema":"4bf056fb8af6","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},{"name":"account_upsertUserAttributeValue","classification":"WRITE","paramCount":4,"schema":"ed5ec8d6e08d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},- {"name":"accounting_addCloseTask","classification":"WRITE","paramCount":5,"schema":"2f7e1f0d1298","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"accounting_applyCtaToReportPeriodSeries","classification":"WRITE","paramCount":2,"schema":"08ae866b4ea8","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_closeAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"accounting:update","paginates":false},{"name":"accounting_closePeriodWithChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"accounting:update","paginates":false},{"name":"accounting_completeCloseTask","classification":"WRITE","paramCount":2,"schema":"5d2e9a90637b","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_createFiscalYearPeriods","classification":"WRITE","paramCount":1,"schema":"de7d8726d5e4","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},@@ -33,12 +30,9 @@{"name":"accounting_deleteFixedAsset","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},{"name":"accounting_deleteFixedAssetClass","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},{"name":"accounting_deleteJournalEntry","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteJournalEntryLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},{"name":"accounting_deletePaymentTerm","classification":"DESTRUCTIVE","paramCount":1,"schema":"5386fbcf056f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deletePeriodCloseTaskDefinition","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"accounting:delete","paginates":false},{"name":"accounting_deleteProject","classification":"DESTRUCTIVE","paramCount":1,"schema":"8e1d73142851","response":"3797626bd17e","injectAuth":"companyId","permission":"accounting:delete","paginates":false},{"name":"accounting_deleteReportView","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_evaluateCloseChecklist","classification":"WRITE","paramCount":3,"schema":"cf52d6c91233","response":"10fdf56c425e","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_generateEliminations","classification":"WRITE","paramCount":1,"schema":"6205bcefb9ed","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},{"name":"accounting_getAccount","classification":"READ","paramCount":1,"schema":"ecb746f60913","response":"9d6890743f52","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getAccountingPeriodDeletability","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"fdd16df03940","injectAuth":"companyId","permission":"accounting:view","paginates":false},@@ -101,11 +95,11 @@{"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"86eb1184c5df","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getJournalLineDimensions","classification":"READ","paramCount":1,"schema":"4a6413e2bb5a","response":"b731368c1d3c","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getJournalSyncCompleteness","classification":"READ","paramCount":3,"schema":"6eb0a36bbd4b","response":"58d45b19b00c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getOrCreateAccountingPeriod","classification":"READ","paramCount":2,"schema":"7dd9558cffe4","response":"00404e686415","injectAuth":"companyId","permission":"accounting:view","paginates":false},+ {"name":"accounting_getOrCreateAccountingPeriod","classification":"WRITE","paramCount":2,"schema":"6f30968ab39a","response":"00404e686415","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_getPaymentTerm","classification":"READ","paramCount":1,"schema":"5386fbcf056f","response":"f7f39c0d662f","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getPaymentTerms","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"7e3500d5e372","injectAuth":"companyId","permission":"accounting:view","paginates":true},{"name":"accounting_getPaymentTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodCloseChecklist","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"032d2a02eff5","injectAuth":"companyId","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPeriodCloseChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"032d2a02eff5","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_getPeriodCloseReadiness","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"8d3446dc0828","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getPeriodCloseTaskDefinitions","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"273a27083497","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getPeriodExternalGlSyncReadiness","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"0963c785f5ca","injectAuth":"companyId","permission":"accounting:view","paginates":false},@@ -121,51 +115,39 @@{"name":"accounting_insertFixedAsset","classification":"WRITE","paramCount":17,"schema":"edafa07d33e5","response":"e0e9c463a967","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},{"name":"accounting_lockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_postJournalEntry","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_reopenAccountingPeriod","classification":"DESTRUCTIVE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_reverseJournalEntry","classification":"WRITE","paramCount":2,"schema":"d25804b3560c","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_runIntercompanyMatching","classification":"WRITE","paramCount":0,"schema":"efddc7bd8bbc","response":"c07d47c6ac75","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},{"name":"accounting_saveJournalEntryWithLines","classification":"DESTRUCTIVE","paramCount":4,"schema":"229dfb3214ba","response":"8394fbabd845","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_saveJournalLineDimensions","classification":"DESTRUCTIVE","paramCount":2,"schema":"7982c7b53f63","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_skipCloseTask","classification":"WRITE","paramCount":2,"schema":"8d4ab2b60f5f","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_translateCompanyBalances","classification":"WRITE","paramCount":4,"schema":"ba889d393571","response":"be5b093fb6e6","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_translateCompanyPeriodSeries","classification":"WRITE","paramCount":3,"schema":"1c8e97655391","response":"0c01d5ac39c2","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"accounting_unlockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},{"name":"accounting_updateDefaultAccounts","classification":"WRITE","paramCount":51,"schema":"e69493bf3220","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},{"name":"accounting_updateFiscalYearSettings","classification":"WRITE","paramCount":2,"schema":"b13ac9bf329b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},{"name":"accounting_updateFixedAsset","classification":"WRITE","paramCount":16,"schema":"c5872851f04c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_updateJournalEntry","classification":"WRITE","paramCount":2,"schema":"8025126e300c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_upsertAccount","classification":"WRITE","paramCount":10,"schema":"9b9c21487a2b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertCostCenter","classification":"WRITE","paramCount":5,"schema":"589460b554cc","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertCurrency","classification":"WRITE","paramCount":5,"schema":"cd0ad32775f8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertDimension","classification":"DESTRUCTIVE","paramCount":2,"schema":"51d776fcb518","response":"660c8bead643","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},+ {"name":"accounting_upsertAccount","classification":"WRITE","paramCount":10,"schema":"0b4871d25164","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},+ {"name":"accounting_upsertCostCenter","classification":"WRITE","paramCount":5,"schema":"cb41a65d1346","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},+ {"name":"accounting_upsertCurrency","classification":"WRITE","paramCount":5,"schema":"8b35738390cc","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},+ {"name":"accounting_upsertDimension","classification":"DESTRUCTIVE","paramCount":2,"schema":"820eea627efe","response":"660c8bead643","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},{"name":"accounting_upsertExchangeRateOverride","classification":"WRITE","paramCount":2,"schema":"4576f689f2fa","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertFixedAsset","classification":"WRITE","paramCount":1,"schema":"23cb5ea22443","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertFixedAssetClass","classification":"WRITE","paramCount":1,"schema":"f138d83c3894","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertFixedAssetUsageLog","classification":"WRITE","paramCount":1,"schema":"12272e046f40","response":"3797626bd17e","injectAuth":"companyId+createdBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertJournalEntryLine","classification":"WRITE","paramCount":7,"schema":"535ba5f8fa1f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertPaymentTerm","classification":"WRITE","paramCount":7,"schema":"9161dcdce108","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertPeriodCloseTaskDefinition","classification":"WRITE","paramCount":9,"schema":"22eb270aa01a","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertProject","classification":"WRITE","paramCount":3,"schema":"3e95164b39d4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},+ {"name":"accounting_upsertFixedAssetClass","classification":"WRITE","paramCount":1,"schema":"1b7fede70b27","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},+ {"name":"accounting_upsertPaymentTerm","classification":"WRITE","paramCount":7,"schema":"857007388d52","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},+ {"name":"accounting_upsertProject","classification":"WRITE","paramCount":3,"schema":"8bcec28be313","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},{"name":"accounting_upsertReportPin","classification":"WRITE","paramCount":2,"schema":"28ab82d5033e","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create+update","paginates":false},{"name":"accounting_upsertReportView","classification":"WRITE","paramCount":1,"schema":"d91fde891b7f","response":"b8ded59f5c56","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_validateDefaultIncomeAccounts","classification":"WRITE","paramCount":29,"schema":"9249b04e60e2","response":"090ed1ebfbc1","injectAuth":"companyId","permission":"accounting:update","paginates":false},{"name":"documents_createDocumentUploadUrl","classification":"WRITE","paramCount":3,"schema":"9034f525c97e","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},{"name":"documents_deleteDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete","paginates":false},- {"name":"documents_deleteDocumentFavorite","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete","paginates":false},- {"name":"documents_deleteDocumentLabel","classification":"DESTRUCTIVE","paramCount":2,"schema":"5c453c6c156d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete","paginates":false},{"name":"documents_getDocument","classification":"READ","paramCount":1,"schema":"e7617eb689c8","response":"88539143f954","injectAuth":"companyId","permission":"documents:view","paginates":false},{"name":"documents_getDocumentExtensions","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b24f77557f86","injectAuth":"companyId","permission":"documents:view","paginates":false},{"name":"documents_getDocumentLabels","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7e2eeb0066ab","injectAuth":"companyId","permission":"documents:view","paginates":false},{"name":"documents_getDocuments","classification":"READ","paramCount":6,"schema":"848cac7bea79","response":"806ff23e9acc","injectAuth":"companyId","permission":"documents:view","paginates":true},{"name":"documents_insertDocumentExtraction","classification":"WRITE","paramCount":4,"schema":"790f2b883984","response":"d181256b2684","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},- {"name":"documents_insertDocumentFavorite","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},- {"name":"documents_insertDocumentLabel","classification":"WRITE","paramCount":2,"schema":"5c453c6c156d","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},{"name":"documents_insertUploadedDocument","classification":"WRITE","paramCount":5,"schema":"d82e74374bd6","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},{"name":"documents_moveDocumentToTrash","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"documents:update","paginates":false},{"name":"documents_restoreDocument","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:update","paginates":false},- {"name":"documents_updateDocumentFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"documents:update","paginates":false},- {"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","paramCount":2,"schema":"0adc09fa2bb3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"documents:update","paginates":false},- {"name":"documents_upsertDocument","classification":"WRITE","paramCount":11,"schema":"c26ae983ace8","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create+update","paginates":false},+ {"name":"documents_updateDocumentFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","paramCount":2,"schema":"0adc09fa2bb3","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"documents:update","paginates":false},+ {"name":"documents_upsertDocument","classification":"WRITE","paramCount":11,"schema":"7b71f5ddd67a","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create+update","paginates":false,"upsert":"id"},{"name":"inventory_cancelOpenPickingListsForJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"844f8eedb019","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},{"name":"inventory_correctStockMovement","classification":"WRITE","paramCount":3,"schema":"fb389b0474f2","response":"3797626bd17e","injectAuth":"companyId","permission":"inventory:update","paginates":false},{"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create","paginates":false},@@ -173,7 +155,6 @@{"name":"inventory_deleteInventoryCount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteKanban","classification":"DESTRUCTIVE","paramCount":1,"schema":"369f807bc840","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deletePickingList","classification":"DESTRUCTIVE","paramCount":1,"schema":"0a4ec3e7319b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deletePickingListLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"063a6777d378","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteReceipt","classification":"DESTRUCTIVE","paramCount":1,"schema":"e00a9764517d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteReceiptLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"17337505bb69","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteShipment","classification":"DESTRUCTIVE","paramCount":1,"schema":"2e39a760a5ca","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},@@ -205,7 +186,7 @@{"name":"inventory_getInventoryValuation","classification":"READ","paramCount":2,"schema":"288f0d29701b","response":"4005e935f8f1","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getInventoryValuationTieOut","classification":"READ","paramCount":1,"schema":"cb789596bf56","response":"20aee38c95a3","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"de680470ebb1","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":true},+ {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"7ef5489d0abf","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":true},{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},@@ -283,24 +264,19 @@{"name":"inventory_updateInventoryCountLine","classification":"WRITE","paramCount":3,"schema":"d0dcc5796dc7","response":"ae8f99e1d130","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updateInventoryCountStatus","classification":"WRITE","paramCount":3,"schema":"7b6f2e6e7731","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updatePickingListStatus","classification":"WRITE","paramCount":2,"schema":"27fb9b18332a","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updateStockTransfer","classification":"WRITE","paramCount":4,"schema":"a10345a94a51","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updateStockTransferStatus","classification":"WRITE","paramCount":4,"schema":"e201e5617e35","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updateTrackedEntityExpiry","classification":"WRITE","paramCount":4,"schema":"ebdc5286d20c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"inventory:update","paginates":false},{"name":"inventory_updateWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"a809aeb69e6d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updateWarehouseTransferStatus","classification":"WRITE","paramCount":2,"schema":"70cb7f36b2a6","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_upsertBatchProperty","classification":"WRITE","paramCount":6,"schema":"6fcfef7093ed","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertKanban","classification":"WRITE","paramCount":14,"schema":"de40aff7a237","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertPickingList","classification":"WRITE","paramCount":7,"schema":"f0bb853dd6ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertPickingListLine","classification":"WRITE","paramCount":8,"schema":"a674c3f5c5e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"9fbe31e51f4b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"7add3f6cc5e4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertShippingMethod","classification":"WRITE","paramCount":6,"schema":"9825e1f6e05b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertStockTransfer","classification":"WRITE","paramCount":1,"schema":"9dd788fdbfa9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertStockTransferLine","classification":"WRITE","paramCount":9,"schema":"2e75475fc5dd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertStockTransferLines","classification":"WRITE","paramCount":2,"schema":"d1730a1b398d","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertStorageType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertStorageUnit","classification":"WRITE","paramCount":8,"schema":"4fde38482a62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},+ {"name":"inventory_upsertKanban","classification":"WRITE","paramCount":14,"schema":"4b5b4cc14d79","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertPickingList","classification":"WRITE","paramCount":7,"schema":"dbe65909f79e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"a3061dfb8ce9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"b672e5466228","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertShippingMethod","classification":"WRITE","paramCount":6,"schema":"6d157a6086d0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertStockTransferLine","classification":"WRITE","paramCount":9,"schema":"9d7761b29bb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertStorageType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},+ {"name":"inventory_upsertStorageUnit","classification":"WRITE","paramCount":8,"schema":"31c5351820e4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},{"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"none","injectAuth":"companyId","permission":"invoicing:view","paginates":false},@@ -308,17 +284,16 @@{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},{"name":"invoicing_createSalesInvoiceFromShipment","classification":"WRITE","paramCount":1,"schema":"2e39a760a5ca","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_deleteInvoiceSettlement","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deleteMemo","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deletePayment","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deletePurchaseInvoice","classification":"DESTRUCTIVE","paramCount":1,"schema":"9fcbb4e4e012","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deletePurchaseInvoiceLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"af656ed8709f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deleteSalesInvoice","classification":"DESTRUCTIVE","paramCount":1,"schema":"9e382a0affeb","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},{"name":"invoicing_deleteSalesInvoiceLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"352db7d38a15","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},- {"name":"invoicing_getApAging","classification":"READ","paramCount":2,"schema":"8c0a142b94d0","response":"eca97da3238d","injectAuth":"companyId","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getApAging","classification":"READ","paramCount":2,"schema":"a0de641b20f5","response":"eca97da3238d","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getApOpenBySupplier","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"cfaa2af435c0","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getApTieOut","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"194f80599d96","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getArAging","classification":"READ","paramCount":2,"schema":"8c0a142b94d0","response":"10729e9f1c72","injectAuth":"companyId","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArAging","classification":"READ","paramCount":2,"schema":"a0de641b20f5","response":"10729e9f1c72","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getArOpenByCustomer","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"8cd731dddf0d","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getArTieOut","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"194f80599d96","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_getAvailableCreditsForParty","classification":"READ","paramCount":3,"schema":"cc95c9088447","response":"f8e7a5443d43","injectAuth":"companyId","permission":"invoicing:view","paginates":false},@@ -364,14 +339,11 @@{"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},{"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},{"name":"invoicing_updateSalesInvoiceStatus","classification":"WRITE","paramCount":4,"schema":"be5f9d03d216","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_upsertInvoiceSettlement","classification":"WRITE","paramCount":14,"schema":"3c09ba7df374","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"b19aa6b4c8f5","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertPayment","classification":"WRITE","paramCount":14,"schema":"b1ce8828dedf","response":"1a922c685a61","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertPurchaseInvoice","classification":"DESTRUCTIVE","paramCount":16,"schema":"3ac5ffa004e5","response":"5cc94f07494c","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","paramCount":8,"schema":"b8c735d9fdc9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},+ {"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"1e192982b199","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id"},+ {"name":"invoicing_upsertPayment","classification":"WRITE","paramCount":14,"schema":"7170f90a5e0f","response":"1a922c685a61","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id"},+ {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","paramCount":8,"schema":"b8c735d9fdc9","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:create+update","paginates":false},{"name":"invoicing_upsertPurchaseInvoiceLine","classification":"WRITE","paramCount":23,"schema":"fcdedfb7917d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},{"name":"invoicing_upsertReimbursementLines","classification":"DESTRUCTIVE","paramCount":2,"schema":"bbd679fc02ea","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertSalesInvoice","classification":"DESTRUCTIVE","paramCount":16,"schema":"1136706f1443","response":"5cc94f07494c","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},{"name":"invoicing_upsertSalesInvoiceLine","classification":"WRITE","paramCount":21,"schema":"269af72d8a49","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},{"name":"invoicing_upsertSalesInvoiceShipment","classification":"WRITE","paramCount":8,"schema":"f7667f28735c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},{"name":"items_activateMethodVersion","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"5cb338fa12e6","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},@@ -379,9 +351,7 @@{"name":"items_assertMethodOperationIsDraft","classification":"WRITE","paramCount":1,"schema":"c407a9edb930","response":"none","injectAuth":"companyId","permission":"parts:update","paginates":false},{"name":"items_cascadeItemTrackingType","classification":"WRITE","paramCount":2,"schema":"cb7a14748215","response":"none","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},{"name":"items_copyItem","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_copyItemPostingGroup","classification":"WRITE","paramCount":2,"schema":"5219ef529638","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_copyMakeMethod","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_createChangeNoticeDraftMethod","classification":"DESTRUCTIVE","paramCount":4,"schema":"c47fe46ab49c","response":"dbe070b1fcb2","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},{"name":"items_createItemDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6dcd390c3681","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_createRevision","classification":"WRITE","paramCount":3,"schema":"6a0f8669f4a7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_deleteChangeNotice","classification":"DESTRUCTIVE","paramCount":1,"schema":"29578070edb2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},@@ -401,14 +371,13 @@{"name":"items_deleteMaterialSubstance","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMaterialType","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMethodMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodOperation","classification":"DESTRUCTIVE","paramCount":1,"schema":"09c7108756e9","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMethodOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMethodOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMethodOperationStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteMethodOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteSupplierPart","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},{"name":"items_deleteUnitOfMeasure","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_diffMethod","classification":"WRITE","paramCount":1,"schema":"8e916e7918fd","response":"945cb97c37b8","injectAuth":"companyId","permission":"parts:update","paginates":false},+ {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"8e916e7918fd","response":"945cb97c37b8","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_duplicateMethodOperationStep","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -516,15 +485,12 @@{"name":"items_getUnitOfMeasuresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1333b6f93ca5","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getUnitOfMeasureUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"bf91be568e5a","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_insertChangeNotice","classification":"WRITE","paramCount":12,"schema":"c534f032ec75","response":"9645fed81b3e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},- {"name":"items_lookupBuyPrice","classification":"WRITE","paramCount":3,"schema":"c440ca0b7efc","response":"cddf8275afa1","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_matchItemIdByText","classification":"WRITE","paramCount":1,"schema":"f2e9aceb3e6b","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_mintPlaceholderPart","classification":"WRITE","paramCount":3,"schema":"c65d3a570f8f","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:update","paginates":false},+ {"name":"items_lookupBuyPrice","classification":"READ","paramCount":3,"schema":"c440ca0b7efc","response":"cddf8275afa1","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_matchItemIdByText","classification":"READ","paramCount":1,"schema":"f2e9aceb3e6b","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_removeChangeNoticeAffectedItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_replaceMethodMaterialSteps","classification":"DESTRUCTIVE","paramCount":2,"schema":"4f13bc7f5929","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},{"name":"items_resolveItemIdFromExtractedText","classification":"WRITE","paramCount":2,"schema":"19341b333045","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_seedDefaultChangeNoticeActions","classification":"WRITE","paramCount":1,"schema":"29578070edb2","response":"ce08332e0ce6","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},{"name":"items_setChangeNoticeActionTasks","classification":"DESTRUCTIVE","paramCount":2,"schema":"0a99ac2dd23d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"9a5230c97e72","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},+ {"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"9a5230c97e72","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},{"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"3912df9a58b9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateChangeNotice","classification":"WRITE","paramCount":13,"schema":"a99b6ea4de95","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","paramCount":2,"schema":"cab02bf4c21b","response":"none","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},@@ -532,7 +498,7 @@{"name":"items_updateChangeNoticeAffectedItemChangeType","classification":"WRITE","paramCount":2,"schema":"a694b3096020","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},{"name":"items_updateChangeNoticeAffectedItemCutover","classification":"WRITE","paramCount":4,"schema":"a06ee719b5b5","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},{"name":"items_updateChangeNoticeStatus","classification":"WRITE","paramCount":4,"schema":"fb1c5bc3ec27","response":"b7cda6fcc03b","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateConfigurationParameterGroupOrder","classification":"WRITE","paramCount":2,"schema":"cf28ccd3b252","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},+ {"name":"items_updateConfigurationParameterGroupOrder","classification":"WRITE","paramCount":2,"schema":"cf28ccd3b252","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},{"name":"items_updateConfigurationParameterOrder","classification":"WRITE","paramCount":3,"schema":"3c4e90ddafb4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateDefaultRevision","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"6411d1997ad5","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateItem","classification":"WRITE","paramCount":18,"schema":"f24ba73701ab","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},@@ -543,41 +509,39 @@{"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateRevision","classification":"WRITE","paramCount":2,"schema":"25c295d358ea","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","paramCount":3,"schema":"e790518da1ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertChangeNoticeType","classification":"WRITE","paramCount":1,"schema":"59701583cf40","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertChangeNoticeType","classification":"WRITE","paramCount":1,"schema":"a91f73f30ea3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertConfigurationParameter","classification":"WRITE","paramCount":8,"schema":"4dc6f3365b3b","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConfigurationParameterGroup","classification":"WRITE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConfigurationRule","classification":"WRITE","paramCount":3,"schema":"da9804f66a45","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConsumable","classification":"WRITE","paramCount":18,"schema":"42c0cffc4fee","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationParameterGroup","classification":"WRITE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationRule","classification":"WRITE","paramCount":3,"schema":"da9804f66a45","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConsumable","classification":"WRITE","paramCount":18,"schema":"917cf6c69912","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},{"name":"items_upsertItemCost","classification":"WRITE","paramCount":5,"schema":"ec5d1c8dde0d","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemCustomerPart","classification":"WRITE","paramCount":5,"schema":"cde0dd9223dd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemDefaultPickMethod","classification":"WRITE","paramCount":2,"schema":"690ef95891d4","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemCustomerPart","classification":"WRITE","paramCount":5,"schema":"cde0dd9223dd","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemManufacturing","classification":"WRITE","paramCount":6,"schema":"23bfb7b15eab","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemPlanning","classification":"WRITE","paramCount":12,"schema":"8145f3998164","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemPostingGroup","classification":"WRITE","paramCount":4,"schema":"d2a988acbd01","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemPlanning","classification":"WRITE","paramCount":12,"schema":"437b38df79d5","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"itemPlanning(itemId,locationId)"},+ {"name":"items_upsertItemPostingGroup","classification":"WRITE","paramCount":4,"schema":"c20041c48790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertItemPurchasing","classification":"WRITE","paramCount":5,"schema":"a2cbed8e5d35","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemShelfLife","classification":"DESTRUCTIVE","paramCount":6,"schema":"327adabe8717","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemSupersession","classification":"DESTRUCTIVE","paramCount":8,"schema":"e50423246d68","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemUnitSalePrice","classification":"WRITE","paramCount":3,"schema":"fafa19d3d976","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},{"name":"items_upsertMakeMethodVersion","classification":"WRITE","paramCount":3,"schema":"068ef4e9b168","response":"83e06908ebb7","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterial","classification":"WRITE","paramCount":25,"schema":"4b81671162f9","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterial","classification":"WRITE","paramCount":25,"schema":"bf3ac65a6327","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},{"name":"items_upsertMaterialDimension","classification":"WRITE","paramCount":4,"schema":"cd59518ed575","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},{"name":"items_upsertMaterialFinish","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterialForm","classification":"WRITE","paramCount":4,"schema":"50ac0c460dd0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialForm","classification":"WRITE","paramCount":4,"schema":"e647d9d4d7bd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertMaterialGrade","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterialSubstance","classification":"WRITE","paramCount":4,"schema":"50ac0c460dd0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialSubstance","classification":"WRITE","paramCount":4,"schema":"e647d9d4d7bd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertMaterialType","classification":"WRITE","paramCount":5,"schema":"c033d56db90c","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"d52e20f3488d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodOperation","classification":"WRITE","paramCount":22,"schema":"1bab96040db4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodOperationParameter","classification":"WRITE","paramCount":5,"schema":"7886eea4515f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodOperationStep","classification":"WRITE","paramCount":11,"schema":"b00e13983658","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"c6bc69cc2080","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodOperationTool","classification":"WRITE","paramCount":5,"schema":"7876b6d0a497","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertPart","classification":"WRITE","paramCount":21,"schema":"37a9a8506af0","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertPickMethod","classification":"WRITE","paramCount":5,"schema":"b14e368c85f6","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"c08028a572a0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"methodMaterial(id)"},+ {"name":"items_upsertMethodOperation","classification":"WRITE","paramCount":22,"schema":"c1059df4fd9a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"methodOperation(id)"},+ {"name":"items_upsertMethodOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertMethodOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertMethodOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"9ff3ddbe053a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertMethodOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertPart","classification":"WRITE","paramCount":21,"schema":"121d76f81f4e","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},+ {"name":"items_upsertPickMethod","classification":"WRITE","paramCount":5,"schema":"0e196a6930be","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"pickMethod(itemId,locationId)"},{"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","paramCount":6,"schema":"3af3fd086443","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"ca47ea7769d4","response":"87c54a97c0fa","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":10,"schema":"4885a2836c70","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertTool","classification":"WRITE","paramCount":21,"schema":"37a9a8506af0","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"3045c73336fc","response":"87c54a97c0fa","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},+ {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":10,"schema":"3f49bc187ea4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertTool","classification":"WRITE","paramCount":21,"schema":"121d76f81f4e","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},{"name":"items_upsertUnitOfMeasure","classification":"WRITE","paramCount":4,"schema":"e954af0763b4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},{"name":"people_clockIn","classification":"WRITE","paramCount":1,"schema":"3d90cb5d0437","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:update","paginates":false},{"name":"people_clockOut","classification":"WRITE","paramCount":3,"schema":"f1fa7800aa59","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:update","paginates":false},@@ -619,28 +583,26 @@{"name":"people_getWeeklyHoursForEmployees","classification":"READ","paramCount":1,"schema":"392d5681b870","response":"96915ea19193","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_insertAttribute","classification":"WRITE","paramCount":5,"schema":"a9cc1aa15a69","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},{"name":"people_insertAttributeCategory","classification":"WRITE","paramCount":3,"schema":"0f2b5b298e7f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},- {"name":"people_insertEmployeeJob","classification":"WRITE","paramCount":2,"schema":"8518dfd7feec","response":"4a3b9b98079b","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},+ {"name":"people_insertEmployeeJob","classification":"WRITE","paramCount":2,"schema":"8518dfd7feec","response":"4a3b9b98079b","injectAuth":"companyId+updatedBy","permission":"people:create","paginates":false},{"name":"people_updateAttribute","classification":"WRITE","paramCount":4,"schema":"f66dbb270538","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateAttributeCategory","classification":"WRITE","paramCount":4,"schema":"7bf8c03306de","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateAttributeSortOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateEmployeeJob","classification":"DESTRUCTIVE","paramCount":2,"schema":"fd3a2eef5bc2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateTimeCardEntry","classification":"WRITE","paramCount":4,"schema":"486c249ce3fa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_upsertDepartment","classification":"WRITE","paramCount":4,"schema":"0008ef42654d","response":"10600fcaa49e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false},- {"name":"people_upsertHoliday","classification":"WRITE","paramCount":4,"schema":"d8ad23388542","response":"8d2b62b6a13b","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false},- {"name":"people_upsertShift","classification":"WRITE","paramCount":13,"schema":"4474d9885d69","response":"4cc67c58f3c9","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false},+ {"name":"people_upsertHoliday","classification":"WRITE","paramCount":4,"schema":"8c7f86c0ca61","response":"8d2b62b6a13b","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},+ {"name":"people_upsertShift","classification":"WRITE","paramCount":13,"schema":"0c60da442fe7","response":"4cc67c58f3c9","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},{"name":"production_activateAssemblyInstructionVersion","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"production:update","paginates":false},{"name":"production_assignPeopleWeek","classification":"WRITE","paramCount":5,"schema":"ea0a43e3afd6","response":"31035ceec7a6","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_autoMatchAssemblyComponents","classification":"WRITE","paramCount":1,"schema":"f9ddf194f67e","response":"41dc031a100a","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_buildAssemblyToolStepLinks","classification":"WRITE","paramCount":4,"schema":"050136ded025","response":"560413db6168","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_calculateJobPriority","classification":"WRITE","paramCount":4,"schema":"89fd15c91371","response":"cddf8275afa1","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_clearPeopleAbsence","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"11d6b03b19bc","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_completeJob","classification":"WRITE","paramCount":4,"schema":"722de9754d1b","response":"b520ca8e3ab4","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_completeOperation","classification":"WRITE","paramCount":2,"schema":"92c192733c55","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_convertSalesOrderLinesToJobs","classification":"WRITE","paramCount":1,"schema":"94c4cbf5579d","response":"56af520891c7","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_copyAssemblyInstructionAsVersion","classification":"WRITE","paramCount":1,"schema":"87207f927319","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},{"name":"production_copyPeopleBoard","classification":"WRITE","paramCount":4,"schema":"3cb969f05928","response":"cbf943bfb8ed","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_copyPeopleWeek","classification":"WRITE","paramCount":4,"schema":"bd6e745b6883","response":"cbf943bfb8ed","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_createAssemblyPlanJob","classification":"WRITE","paramCount":1,"schema":"277f7d872d8c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},+ {"name":"production_createAssemblyPlanJob","classification":"WRITE","paramCount":1,"schema":"277f7d872d8c","response":"3797626bd17e","injectAuth":"companyId+createdBy+userId","permission":"production:create","paginates":false},{"name":"production_createJobDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6d2b672646dc","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_createJobOperationBatch","classification":"WRITE","paramCount":8,"schema":"fffa9134447f","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},{"name":"production_deleteAssemblyComponentMapping","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},@@ -653,7 +615,6 @@{"name":"production_deleteFailureMode","classification":"DESTRUCTIVE","paramCount":1,"schema":"4a3e0384d72f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteJob","classification":"DESTRUCTIVE","paramCount":1,"schema":"4999bd4be598","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteJobMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"9b0d4f228240","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobOperation","classification":"DESTRUCTIVE","paramCount":1,"schema":"6889e2589fdc","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteJobOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteJobOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteJobOperationStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},@@ -661,9 +622,7 @@{"name":"production_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","paramCount":1,"schema":"34cb412f1fae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"281c418606f0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteMaintenanceDispatchItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceDispatchWorkCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"7f43ff7a4fc5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceScheduleItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deletePeopleAssignment","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"6ce160f0feca","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteProcedure","classification":"DESTRUCTIVE","paramCount":1,"schema":"0611728fa5e0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},{"name":"production_deleteProcedureParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"2a17205fafa2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},@@ -675,7 +634,7 @@{"name":"production_generateAssemblyStepsFromPlan","classification":"DESTRUCTIVE","paramCount":2,"schema":"80eeb7b6dd7c","response":"6a32a10b17d9","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},{"name":"production_getActiveEmployeeAbilities","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"123f68c94eac","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getActiveJobOperationByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"ebe9a86ba8b7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getActiveJobOperationsByLocation","classification":"READ","paramCount":2,"schema":"bcf41dd63247","response":"4440776603ed","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_getActiveJobOperationsByLocation","classification":"READ","paramCount":2,"schema":"e1b255975233","response":"4440776603ed","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getActiveProductionEvents","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"953528dd70d7","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getAssemblyComponentMappings","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"da74e5f4208a","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getAssemblyInstruction","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"76b132dcfb0d","injectAuth":"companyId","permission":"production:view","paginates":false},@@ -769,7 +728,7 @@{"name":"production_getProductionEvents","classification":"READ","paramCount":2,"schema":"304bd714250f","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":true},{"name":"production_getProductionEventsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"0c36813c32a1","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getProductionEventsByOperations","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEventsPage","classification":"READ","paramCount":3,"schema":"86ca80961401","response":"d82d26b306e9","injectAuth":"companyId","permission":"production:view","paginates":true},+ {"name":"production_getProductionEventsPage","classification":"READ","paramCount":3,"schema":"d3ce152358d0","response":"d82d26b306e9","injectAuth":"companyId","permission":"production:view","paginates":true},{"name":"production_getProductionPlanning","classification":"READ","paramCount":3,"schema":"d561f840242a","response":"684c3b20f68c","injectAuth":"companyId","permission":"production:view","paginates":true},{"name":"production_getProductionProjections","classification":"READ","paramCount":3,"schema":"d561f840242a","response":"4973a62dfd1b","injectAuth":"companyId","permission":"production:view","paginates":true},{"name":"production_getProductionQuantities","classification":"READ","paramCount":2,"schema":"304bd714250f","response":"3b4cf7a6bc87","injectAuth":"companyId","permission":"production:view","paginates":true},@@ -787,24 +746,19 @@{"name":"production_getWorkCenterShifts","classification":"READ","paramCount":1,"schema":"e94892850934","response":"2b4835f80e6c","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_maxToolQuantityByItem","classification":"READ","paramCount":1,"schema":"8b9e90037b9a","response":"none","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"ac83813d8c48","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"production:update","paginates":false},{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_recalculateJobOperationDependencies","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"a70079765330","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_recalculateJobRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_releaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_replaceJobMaterialSteps","classification":"DESTRUCTIVE","paramCount":2,"schema":"876f8375508a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_runMRP","classification":"WRITE","paramCount":2,"schema":"6e039fba26f6","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_scheduleJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"a70079765330","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_setJobMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"805d2a5ebf8e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_setJobMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"805d2a5ebf8e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_setJobOperationToolStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"2d14950ae331","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_setPeopleAbsence","classification":"WRITE","paramCount":4,"schema":"efea076202c2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_setPeopleAbsenceRange","classification":"WRITE","paramCount":5,"schema":"f40e1c93667c","response":"9859df3143fe","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},@@ -836,43 +790,38 @@{"name":"production_updateKanbanJob","classification":"WRITE","paramCount":2,"schema":"2c22838be2d2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateProductionQuantity","classification":"WRITE","paramCount":6,"schema":"64f19a2cbfe0","response":"7cb043dcb64d","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_upsertAssemblyComponentMapping","classification":"WRITE","paramCount":4,"schema":"9ed1f38ce764","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstruction","classification":"WRITE","paramCount":4,"schema":"a1796f1bd347","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","paramCount":16,"schema":"db59420ad99a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","paramCount":5,"schema":"a21b4fac4b90","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstructionStepSlide","classification":"WRITE","paramCount":9,"schema":"c6bc69cc2080","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStepSlide","classification":"WRITE","paramCount":9,"schema":"9ff3ddbe053a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},{"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","paramCount":5,"schema":"d64500fd5c94","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyUnit","classification":"WRITE","paramCount":5,"schema":"74497d782594","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertFailureMode","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"73f73c34c970","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobMaterial","classification":"WRITE","paramCount":17,"schema":"55d0ec00089d","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},+ {"name":"production_upsertFailureMode","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"ace4b17e3fd4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertJobMaterial","classification":"WRITE","paramCount":17,"schema":"c9c68d632c9d","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"jobMaterial(id)"},{"name":"production_upsertJobMaterialMakeMethod","classification":"WRITE","paramCount":5,"schema":"d603e9c57b46","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},{"name":"production_upsertJobMethod","classification":"WRITE","paramCount":2,"schema":"170fba7b05c6","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperation","classification":"WRITE","paramCount":26,"schema":"0b8f8e4e68ee","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperationParameter","classification":"WRITE","paramCount":5,"schema":"7886eea4515f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperationStep","classification":"WRITE","paramCount":11,"schema":"b00e13983658","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"c6bc69cc2080","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperationTool","classification":"WRITE","paramCount":5,"schema":"7876b6d0a497","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceDispatch","classification":"WRITE","paramCount":13,"schema":"5255ffcd7a1c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"f79295d5eb89","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"834d4e0bf908","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"04fec211f623","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceDispatchWorkCenter","classification":"WRITE","paramCount":3,"schema":"d5b48775f398","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceSchedule","classification":"WRITE","paramCount":8,"schema":"474f19565321","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertMaintenanceScheduleItem","classification":"WRITE","paramCount":5,"schema":"00e2e6d24e50","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},+ {"name":"production_upsertJobOperation","classification":"WRITE","paramCount":26,"schema":"46e4f69aa1f7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"jobOperation(id)"},+ {"name":"production_upsertJobOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertJobOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertJobOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"9ff3ddbe053a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertJobOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"15129a94d57d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"a98569352969","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"41c857266e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertMaintenanceSchedule","classification":"WRITE","paramCount":8,"schema":"4f46ce8d0845","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},{"name":"production_upsertMakeMethodFromJob","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},{"name":"production_upsertMakeMethodFromJobMethod","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},{"name":"production_upsertPeopleAssignment","classification":"DESTRUCTIVE","paramCount":7,"schema":"1ec71dfcea20","response":"a726aa587ccc","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertProcedure","classification":"WRITE","paramCount":6,"schema":"1956f23f1d21","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertProcedureParameter","classification":"WRITE","paramCount":4,"schema":"d58a41fa9f2f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertProcedureStep","classification":"WRITE","paramCount":10,"schema":"e0352a783337","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertProductionEvent","classification":"WRITE","paramCount":8,"schema":"487f567809f9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertProductionQuantity","classification":"WRITE","paramCount":6,"schema":"bab2dacfa3a7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertScrapReason","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},+ {"name":"production_upsertProductionEvent","classification":"WRITE","paramCount":8,"schema":"05b066cee802","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertProductionQuantity","classification":"WRITE","paramCount":6,"schema":"24b2fd6be216","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},+ {"name":"production_upsertScrapReason","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},{"name":"purchasing_cancelPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_closePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_confirmPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"purchasing:update","paginates":false},{"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"03ce7e291c3c","response":"5cb338fa12e6","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},{"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},@@ -967,7 +916,6 @@{"name":"purchasing_insertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"cb4ec49c926e","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplier","classification":"WRITE","paramCount":9,"schema":"05cf2198c6ac","response":"9d2416e8ad75","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplierContact","classification":"WRITE","paramCount":4,"schema":"987f8dd2f02d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertSupplierInteraction","classification":"WRITE","paramCount":1,"schema":"67043a31b1b5","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplierLocation","classification":"WRITE","paramCount":4,"schema":"c903cae736f0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplierQuote","classification":"WRITE","paramCount":13,"schema":"aa8560bfb767","response":"77e21c1e2e32","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_reopenPurchaseOrderAsRevision","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"cddf8275afa1","injectAuth":"companyId","permission":"purchasing:update","paginates":false},@@ -978,15 +926,11 @@{"name":"purchasing_shortClosePurchaseReturnOrderLine","classification":"WRITE","paramCount":3,"schema":"a21cfee98b1a","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchaseOrder","classification":"WRITE","paramCount":11,"schema":"f254c2222188","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"744101d1c67c","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchaseOrderStatus","classification":"WRITE","paramCount":3,"schema":"da4b3835e841","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderStatusLegacy","classification":"WRITE","paramCount":2,"schema":"443b40ba5bdd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseReturnOrder","classification":"WRITE","paramCount":13,"schema":"65e2a245cbbe","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"f1f07b8e0c83","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"3be259f3e887","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","paramCount":3,"schema":"8dc0490a9402","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierAccounting","classification":"WRITE","paramCount":2,"schema":"00634b037a3e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updateSupplierContact","classification":"WRITE","paramCount":4,"schema":"f6b4a36788e6","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updateSupplierLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updateSupplierPayment","classification":"WRITE","paramCount":6,"schema":"7c667f4542f3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},@@ -997,19 +941,18 @@{"name":"purchasing_updateSupplierShipping","classification":"WRITE","paramCount":8,"schema":"ac0c2133e800","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_updateSupplierTax","classification":"WRITE","paramCount":8,"schema":"9467cd226e93","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_upsertPurchaseOrder","classification":"WRITE","paramCount":2,"schema":"9fe37a5a07e3","response":"1b33aad6f934","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchaseOrderDelivery","classification":"WRITE","paramCount":15,"schema":"5fb9d54c12e7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderDelivery","classification":"WRITE","paramCount":15,"schema":"5fb9d54c12e7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:create+update","paginates":false},{"name":"purchasing_upsertPurchaseOrderLine","classification":"WRITE","paramCount":25,"schema":"adfb0bd2408c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchaseOrderPayment","classification":"WRITE","paramCount":6,"schema":"1e1be871f655","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchaseReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"0f306178224d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderPayment","classification":"WRITE","paramCount":6,"schema":"1e1be871f655","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchaseReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"9272c7cdfeaf","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},{"name":"purchasing_upsertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"fdd694519621","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},{"name":"purchasing_upsertPurchasingRFQLine","classification":"WRITE","paramCount":1,"schema":"60751ccac2a4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},{"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa459fc25bca","response":"5c9ba5bee3f1","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertSupplier","classification":"WRITE","paramCount":10,"schema":"9bd3cb688e5f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertSupplierBankAccount","classification":"WRITE","paramCount":13,"schema":"e650c0c7754d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertSupplierProcess","classification":"WRITE","paramCount":6,"schema":"1367b80281cb","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertSupplierQuote","classification":"WRITE","paramCount":15,"schema":"afff6c561cd5","response":"4ed5e2358875","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertSupplier","classification":"WRITE","paramCount":10,"schema":"999cedb57790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},+ {"name":"purchasing_upsertSupplierBankAccount","classification":"WRITE","paramCount":13,"schema":"cde0d3ca4444","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},+ {"name":"purchasing_upsertSupplierProcess","classification":"WRITE","paramCount":6,"schema":"26d15056f196","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},{"name":"purchasing_upsertSupplierQuoteLine","classification":"WRITE","paramCount":14,"schema":"903d170d2231","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertSupplierType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertSupplierType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},{"name":"quality_activateGauge","classification":"WRITE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:update","paginates":false},{"name":"quality_deactivateGauge","classification":"WRITE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:update","paginates":false},{"name":"quality_deleteGauge","classification":"DESTRUCTIVE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},@@ -1021,7 +964,6 @@{"name":"quality_deleteIssueType","classification":"DESTRUCTIVE","paramCount":1,"schema":"bb6b04f68710","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},{"name":"quality_deleteIssueWorkflow","classification":"DESTRUCTIVE","paramCount":1,"schema":"15a80db054e6","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},{"name":"quality_deleteQualityDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"6d79e6870690","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteQualityDocumentStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"6d1c301b650d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},{"name":"quality_deleteRequiredAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"cca3bf9f3ebb","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},{"name":"quality_deleteRisk","classification":"DESTRUCTIVE","paramCount":1,"schema":"7002f7ae1c58","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},{"name":"quality_getBalloons","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"3fec0abbc97d","injectAuth":"companyId","permission":"quality:view","paginates":false},@@ -1087,19 +1029,14 @@{"name":"quality_updateIssueStatus","classification":"WRITE","paramCount":4,"schema":"57b4fe5217e7","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},{"name":"quality_updateIssueTaskContent","classification":"WRITE","paramCount":3,"schema":"dcd51db087bc","response":"a78c6c21c084","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},{"name":"quality_updateIssueTaskStatus","classification":"WRITE","paramCount":4,"schema":"cd763f773f42","response":"a78c6c21c084","injectAuth":"companyId+updatedBy+userId","permission":"quality:update","paginates":false},- {"name":"quality_updateQualityDocumentStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateRiskStatus","classification":"WRITE","paramCount":2,"schema":"27ac2e505123","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_upsertGauge","classification":"WRITE","paramCount":16,"schema":"6969c2f67b33","response":"3ec91e2c9200","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertGaugeCalibrationRecord","classification":"WRITE","paramCount":15,"schema":"80febac2c711","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertGaugeType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},+ {"name":"quality_upsertGaugeCalibrationRecord","classification":"WRITE","paramCount":15,"schema":"edcab69c8c1a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},+ {"name":"quality_upsertGaugeType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},{"name":"quality_upsertInspectionDocument","classification":"WRITE","paramCount":10,"schema":"68e08a92df7a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertIssue","classification":"WRITE","paramCount":21,"schema":"5a6a8f4280d9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertIssueType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertIssueWorkflow","classification":"WRITE","paramCount":7,"schema":"ed37ccdc2f7a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},+ {"name":"quality_upsertIssueType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},+ {"name":"quality_upsertIssueWorkflow","classification":"WRITE","paramCount":7,"schema":"e1638767f6ac","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},{"name":"quality_upsertItemInspectionDocumentAssignment","classification":"DESTRUCTIVE","paramCount":3,"schema":"3e4ebfc49e2a","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"quality:create+update","paginates":false},{"name":"quality_upsertQualityDocument","classification":"WRITE","paramCount":5,"schema":"6ddca1e4a601","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertQualityDocumentStep","classification":"WRITE","paramCount":10,"schema":"cd38e003477a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertRequiredAction","classification":"WRITE","paramCount":3,"schema":"33e654329126","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},+ {"name":"quality_upsertRequiredAction","classification":"WRITE","paramCount":3,"schema":"f0cd89df8f83","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},{"name":"quality_upsertRisk","classification":"WRITE","paramCount":12,"schema":"6cdac0001c75","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},{"name":"resources_activateProcess","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},{"name":"resources_activateWorkCenter","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},@@ -1111,9 +1048,7 @@{"name":"resources_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","paramCount":1,"schema":"34cb412f1fae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"281c418606f0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteMaintenanceDispatchItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceDispatchWorkCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"7f43ff7a4fc5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceScheduleItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deletePartner","classification":"DESTRUCTIVE","paramCount":1,"schema":"74d289586b4f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteProcess","classification":"DESTRUCTIVE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteShift","classification":"DESTRUCTIVE","paramCount":1,"schema":"fbdb1fa56a88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},@@ -1179,33 +1114,28 @@{"name":"resources_resolveEmployeeAbilityExpiresAt","classification":"WRITE","paramCount":3,"schema":"ec5fc6dfaa43","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:update","paginates":false},{"name":"resources_updateAbility","classification":"WRITE","paramCount":2,"schema":"331c98a989f9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},{"name":"resources_updateMaintenanceDispatch","classification":"WRITE","paramCount":18,"schema":"02877e9f1f8d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},- {"name":"resources_updateSuggestionEmoji","classification":"WRITE","paramCount":2,"schema":"dc61bce0f764","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},- {"name":"resources_updateSuggestionTags","classification":"WRITE","paramCount":2,"schema":"ab3b2e298cdb","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},+ {"name":"resources_updateSuggestionEmoji","classification":"WRITE","paramCount":2,"schema":"dc61bce0f764","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},{"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},- {"name":"resources_upsertContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"ba913d44dc52","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertEmployeeAbilityCell","classification":"WRITE","paramCount":4,"schema":"800b78f5bbae","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertFailureMode","classification":"WRITE","paramCount":4,"schema":"d864dff7b59d","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},+ {"name":"resources_upsertContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"6630f8761e37","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"contractor(id)"},+ {"name":"resources_upsertEmployeeAbilityCell","classification":"WRITE","paramCount":4,"schema":"800b78f5bbae","response":"3797626bd17e","injectAuth":"companyId","permission":"resources:create+update","paginates":false},+ {"name":"resources_upsertFailureMode","classification":"WRITE","paramCount":4,"schema":"e4d170d8f468","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"resources_upsertLocation","classification":"WRITE","paramCount":13,"schema":"28b97eeddff1","response":"5fe568931f57","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceDispatch","classification":"WRITE","paramCount":15,"schema":"33186b41e4bb","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"f79295d5eb89","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"834d4e0bf908","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"04fec211f623","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceDispatchWorkCenter","classification":"WRITE","paramCount":3,"schema":"d5b48775f398","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceSchedule","classification":"WRITE","paramCount":20,"schema":"89ff27d11274","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertMaintenanceScheduleItem","classification":"WRITE","paramCount":5,"schema":"00e2e6d24e50","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"4730e805ea1b","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":17,"schema":"dfd1f2ba4547","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},+ {"name":"resources_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"15129a94d57d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},+ {"name":"resources_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"a98569352969","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},+ {"name":"resources_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"41c857266e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},+ {"name":"resources_upsertMaintenanceSchedule","classification":"WRITE","paramCount":20,"schema":"f0980197b765","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},+ {"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"bcf9a7c682d9","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"partner(id)"},+ {"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":17,"schema":"adaba2327d43","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"resources_upsertTraining","classification":"WRITE","paramCount":4,"schema":"be53f09f9856","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},{"name":"resources_upsertTrainingAssignment","classification":"WRITE","paramCount":3,"schema":"9f8996544bb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},{"name":"resources_upsertTrainingQuestion","classification":"WRITE","paramCount":12,"schema":"f27342252292","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertWorkCenter","classification":"DESTRUCTIVE","paramCount":15,"schema":"cc81867b6509","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},+ {"name":"resources_upsertWorkCenter","classification":"DESTRUCTIVE","paramCount":15,"schema":"cbbc99da1ba7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"sales_buildMakeToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_buildPullFromInventoryPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_buildPurchaseToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_calculatePricesForQuantities","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_cancelSalesOrder","classification":"WRITE","paramCount":2,"schema":"745d2b9e6ebc","response":"903bb804a4ff","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},{"name":"sales_cancelSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_closeSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_confirmSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_convertQuoteToOrder","classification":"WRITE","paramCount":5,"schema":"fc53803a89ca","response":"5cb338fa12e6","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},{"name":"sales_convertSalesRfqToQuote","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"5cb338fa12e6","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},@@ -1227,9 +1157,7 @@{"name":"sales_deletePricingRule","classification":"DESTRUCTIVE","paramCount":1,"schema":"360072ef68fd","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuote","classification":"DESTRUCTIVE","paramCount":1,"schema":"c726ae407913","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuoteLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"e0050938a2c8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteMakeMethod","classification":"DESTRUCTIVE","paramCount":1,"schema":"899e2f637661","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuoteMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"5718812a5810","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteOperation","classification":"DESTRUCTIVE","paramCount":1,"schema":"9d2e26473601","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuoteOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuoteOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_deleteQuoteOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},@@ -1242,7 +1170,7 @@{"name":"sales_deleteSalesRFQLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"8b2f2f9d8451","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},{"name":"sales_duplicatePricingRule","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_finalizeQuote","classification":"WRITE","paramCount":1,"schema":"c726ae407913","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_getAllCustomersItemPriceOverride","classification":"READ","paramCount":3,"schema":"a6cc9782168c","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},+ {"name":"sales_getAllCustomersItemPriceOverride","classification":"READ","paramCount":3,"schema":"746e975d6c8f","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getBaseCatalog","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:view","paginates":true},{"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"c36ad21b447b","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCreditableQuantities","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"da2f02c5bdac","injectAuth":"companyId","permission":"sales:view","paginates":false},@@ -1250,7 +1178,7 @@{"name":"sales_getCustomerBankAccounts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"d8173b9c2e54","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerContact","classification":"READ","paramCount":1,"schema":"ad038ec2602b","response":"d16ba475ee9a","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerContacts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"acc29dbe9746","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemPriceOverride","classification":"READ","paramCount":4,"schema":"8e0420ef7552","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemPriceOverride","classification":"READ","paramCount":4,"schema":"3f17d1d3bb22","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerItemPriceOverrideById","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerItemPriceOverridesList","classification":"READ","paramCount":6,"schema":"d5065f366ab1","response":"bae32978787b","injectAuth":"companyId","permission":"sales:view","paginates":true},{"name":"sales_getCustomerLocation","classification":"READ","paramCount":1,"schema":"339ac15c3167","response":"be52ec9b4436","injectAuth":"companyId","permission":"sales:view","paginates":false},@@ -1264,7 +1192,7 @@{"name":"sales_getCustomerStatusesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerTax","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"35cfe732826b","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerType","classification":"READ","paramCount":1,"schema":"b79bc02c5595","response":"8b3eca34dbfd","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerTypeItemPriceOverride","classification":"READ","paramCount":4,"schema":"4da3cd3b0779","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerTypeItemPriceOverride","classification":"READ","paramCount":4,"schema":"e4596e241f82","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getCustomerTypes","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"7c6550dea5b1","injectAuth":"companyId","permission":"sales:view","paginates":true},{"name":"sales_getCustomerTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getExternalSalesOrderLines","classification":"READ","paramCount":2,"schema":"dbfcdb73551d","response":"3279b7b05d49","injectAuth":"companyId","permission":"sales:view","paginates":true},@@ -1361,7 +1289,6 @@{"name":"sales_resolveQuoteLinePrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},{"name":"sales_setSalesReturnOrderLineDisposition","classification":"WRITE","paramCount":2,"schema":"a8526e566c94","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},{"name":"sales_shortCloseSalesReturnOrderLine","classification":"WRITE","paramCount":3,"schema":"a3098b18fc68","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerAccounting","classification":"WRITE","paramCount":2,"schema":"165c42d97441","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateCustomerContact","classification":"WRITE","paramCount":4,"schema":"f0fc7be0eef2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateCustomerLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateCustomerPayment","classification":"WRITE","paramCount":5,"schema":"f4b0bf1f4ec1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},@@ -1379,39 +1306,37 @@{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"fc73ab432ad8","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesOrderStatus","classification":"WRITE","paramCount":3,"schema":"ba9f86dc4f78","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesReturnOrder","classification":"WRITE","paramCount":13,"schema":"d2b0eab7a550","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesRFQ","classification":"WRITE","paramCount":13,"schema":"29d3ed584bda","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"7a17ee77c8c5","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesRFQStatus","classification":"WRITE","paramCount":4,"schema":"987b1b266fe8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_upsertCustomer","classification":"WRITE","paramCount":11,"schema":"5f03a003004d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"2f6b498df5e9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertCustomer","classification":"WRITE","paramCount":11,"schema":"27fc0d9d8eb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"71b1f32160c0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},{"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":10,"schema":"6f67d6ad287a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertCustomerStatus","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertCustomerType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertCustomerStatus","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertCustomerType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},{"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","paramCount":4,"schema":"ca78a9869ff2","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},{"name":"sales_upsertMakeMethodFromQuoteMethod","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertNoQuoteReason","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuote","classification":"WRITE","paramCount":21,"schema":"c8e476a66d0a","response":"3acbb53b8c04","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertNoQuoteReason","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertQuote","classification":"WRITE","paramCount":21,"schema":"0c5ee8c52242","response":"3acbb53b8c04","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},{"name":"sales_upsertQuoteLine","classification":"WRITE","paramCount":19,"schema":"d3c525861e1c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},{"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","paramCount":2,"schema":"483aa73b0c32","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},{"name":"sales_upsertQuoteLineMethod","classification":"WRITE","paramCount":5,"schema":"5f94e8a4cbf6","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},{"name":"sales_upsertQuoteLinePrices","classification":"DESTRUCTIVE","paramCount":3,"schema":"03bc74906afb","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteMaterial","classification":"WRITE","paramCount":17,"schema":"196337e8929e","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteMaterial","classification":"WRITE","paramCount":17,"schema":"ab28a6a008f4","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"quoteMaterial(id)"},{"name":"sales_upsertQuoteMaterialMakeMethod","classification":"WRITE","paramCount":4,"schema":"06f97e90fc79","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteOperation","classification":"WRITE","paramCount":27,"schema":"3babae40d38f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteOperationParameter","classification":"WRITE","paramCount":5,"schema":"7886eea4515f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteOperationStep","classification":"WRITE","paramCount":11,"schema":"b00e13983658","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteOperationTool","classification":"WRITE","paramCount":5,"schema":"7876b6d0a497","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuotePayment","classification":"WRITE","paramCount":6,"schema":"36ca53e35fa3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteShipment","classification":"WRITE","paramCount":7,"schema":"b67f297e5398","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertReturnReason","classification":"WRITE","paramCount":4,"schema":"765854e5447a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteOperation","classification":"WRITE","paramCount":27,"schema":"4fa5726841a8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"quoteOperation(id)"},+ {"name":"sales_upsertQuoteOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertQuoteOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertQuoteOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertQuotePayment","classification":"WRITE","paramCount":6,"schema":"36ca53e35fa3","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteShipment","classification":"WRITE","paramCount":7,"schema":"b67f297e5398","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertReturnReason","classification":"WRITE","paramCount":4,"schema":"85bdd818fbab","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},{"name":"sales_upsertSalesOrder","classification":"WRITE","paramCount":19,"schema":"c7fa1aa49c04","response":"5cc20a44d4fe","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},{"name":"sales_upsertSalesOrderLine","classification":"WRITE","paramCount":25,"schema":"f36171418dd8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesOrderPayment","classification":"WRITE","paramCount":8,"schema":"310037cea6c3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesOrderShipment","classification":"WRITE","paramCount":17,"schema":"a1ab551afe2a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"f4a19f25c389","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesRFQ","classification":"WRITE","paramCount":15,"schema":"3875863b88c1","response":"2e56e1180d37","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesRFQLine","classification":"WRITE","paramCount":11,"schema":"24400721553b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderPayment","classification":"WRITE","paramCount":8,"schema":"310037cea6c3","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderShipment","classification":"WRITE","paramCount":17,"schema":"a1ab551afe2a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"2715ff7be34d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertSalesRFQ","classification":"WRITE","paramCount":15,"schema":"d213ee469a92","response":"2e56e1180d37","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},+ {"name":"sales_upsertSalesRFQLine","classification":"WRITE","paramCount":11,"schema":"f00afd5737b0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},{"name":"settings_deleteDocumentSection","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},{"name":"settings_deleteItemSerialSequence","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},{"name":"settings_getAccountsPayableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},@@ -1452,61 +1377,55 @@{"name":"settings_getWebhook","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"cb2b17a3252e","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getWebhooks","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"f236afae1a37","injectAuth":"companyId","permission":"settings:view","paginates":true},{"name":"settings_getWebhookTables","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"633f9f3bffc6","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_insertSubsidiary","classification":"WRITE","paramCount":20,"schema":"b6b1b6ddf516","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create","paginates":false},{"name":"settings_resolveSections","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"9cf53d9645e3","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountingEnabledSetting","classification":"WRITE","paramCount":1,"schema":"82d5e14a67e0","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsPayableAddressSetting","classification":"WRITE","paramCount":1,"schema":"7a679bb0d746","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateAccountingEnabledSetting","classification":"WRITE","paramCount":1,"schema":"82d5e14a67e0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateAccountsPayableAddressSetting","classification":"WRITE","paramCount":1,"schema":"7a679bb0d746","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateAccountsPayableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsPayableEmail","classification":"WRITE","paramCount":1,"schema":"5ea2ba22400c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsReceivableAddressSetting","classification":"WRITE","paramCount":1,"schema":"aee1361e5321","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateAccountsReceivableAddressSetting","classification":"WRITE","paramCount":1,"schema":"aee1361e5321","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateAccountsReceivableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsReceivableEmail","classification":"WRITE","paramCount":1,"schema":"0bd52dc112c3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAllowLowercaseItemIdsSetting","classification":"WRITE","paramCount":1,"schema":"4bfa8b2e5538","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAssetTaxDepreciationSettings","classification":"WRITE","paramCount":2,"schema":"6decaad55e9c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateAutoSelectMaterialWithoutPickingListSetting","classification":"WRITE","paramCount":1,"schema":"c8c780d1ee3a","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateBomExplorerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"f58f54c509a0","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateAllowLowercaseItemIdsSetting","classification":"WRITE","paramCount":1,"schema":"4bfa8b2e5538","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateAssetTaxDepreciationSettings","classification":"WRITE","paramCount":2,"schema":"6decaad55e9c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateAutoSelectMaterialWithoutPickingListSetting","classification":"WRITE","paramCount":1,"schema":"c8c780d1ee3a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateBomExplorerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"f58f54c509a0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateCompany","classification":"WRITE","paramCount":17,"schema":"51b47fb4a6bd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateCompanyPlan","classification":"WRITE","paramCount":4,"schema":"dc5417676df7","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateCompanyWithBaseCurrencyChange","classification":"DESTRUCTIVE","paramCount":17,"schema":"51b47fb4a6bd","response":"none","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateDefaultCustomerCc","classification":"WRITE","paramCount":1,"schema":"69d7696df422","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateDefaultSupplierCc","classification":"WRITE","paramCount":1,"schema":"862b3d182ce1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateDigitalQuoteSetting","classification":"WRITE","paramCount":3,"schema":"01dcd07bf6d9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateIncludeMaterialsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"c44d043f2507","response":"none","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateIncludeOperationsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"dcfff3bec454","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateIncompletePickingListPolicySetting","classification":"WRITE","paramCount":1,"schema":"0f134dc7536d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateKanbanOutputSetting","classification":"WRITE","paramCount":1,"schema":"ca53dc098fc8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateLeadTimesOnReceiptSetting","classification":"WRITE","paramCount":1,"schema":"95c137844a39","response":"none","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateDefaultCustomerCc","classification":"WRITE","paramCount":1,"schema":"69d7696df422","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateDefaultSupplierCc","classification":"WRITE","paramCount":1,"schema":"862b3d182ce1","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateDigitalQuoteSetting","classification":"WRITE","paramCount":3,"schema":"01dcd07bf6d9","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateIncludeMaterialsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"c44d043f2507","response":"none","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateIncludeOperationsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"dcfff3bec454","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateIncompletePickingListPolicySetting","classification":"WRITE","paramCount":1,"schema":"0f134dc7536d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateKanbanOutputSetting","classification":"WRITE","paramCount":1,"schema":"ca53dc098fc8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateLeadTimesOnReceiptSetting","classification":"WRITE","paramCount":1,"schema":"95c137844a39","response":"none","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateLogoDark","classification":"WRITE","paramCount":1,"schema":"f2a952625b72","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateLogoDarkIcon","classification":"WRITE","paramCount":1,"schema":"cc8cf36714fa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateLogoLight","classification":"WRITE","paramCount":1,"schema":"9baa1881adb6","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateLogoLightIcon","classification":"WRITE","paramCount":1,"schema":"17c809b3aebf","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateLogoWatermark","classification":"WRITE","paramCount":1,"schema":"22e7a3b83c3a","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateMaintenanceDispatchNotificationSettings","classification":"WRITE","paramCount":4,"schema":"c857a8ae87fd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateMaterialGeneratedIdsSetting","classification":"WRITE","paramCount":1,"schema":"8de91cc6fb4f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateMetricSettings","classification":"WRITE","paramCount":1,"schema":"6310a488e8b2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updatePlmReleaseControlSetting","classification":"WRITE","paramCount":1,"schema":"b74d1adb972d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateProductLabelSize","classification":"WRITE","paramCount":1,"schema":"26bfb6ebfdda","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateRequireCustomerContactSetting","classification":"WRITE","paramCount":1,"schema":"4cff457269be","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateRequireSupplierContactSetting","classification":"WRITE","paramCount":1,"schema":"36a0cd98c43c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateRfqReadySetting","classification":"WRITE","paramCount":1,"schema":"8828dbf1724d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateSalesRuleNotificationSetting","classification":"WRITE","paramCount":1,"schema":"fcb0888da832","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateMaintenanceDispatchNotificationSettings","classification":"WRITE","paramCount":4,"schema":"c857a8ae87fd","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateMaterialGeneratedIdsSetting","classification":"WRITE","paramCount":1,"schema":"8de91cc6fb4f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateMetricSettings","classification":"WRITE","paramCount":1,"schema":"6310a488e8b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updatePlmReleaseControlSetting","classification":"WRITE","paramCount":1,"schema":"b74d1adb972d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateRequireCustomerContactSetting","classification":"WRITE","paramCount":1,"schema":"4cff457269be","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateRequireSupplierContactSetting","classification":"WRITE","paramCount":1,"schema":"36a0cd98c43c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateRfqReadySetting","classification":"WRITE","paramCount":1,"schema":"8828dbf1724d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateSalesRuleNotificationSetting","classification":"WRITE","paramCount":1,"schema":"fcb0888da832","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateSequence","classification":"WRITE","paramCount":2,"schema":"c28f12fe484d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateShelfLifeSettings","classification":"WRITE","paramCount":4,"schema":"a6f593fa5702","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateShowCurrencyTrailingZerosSetting","classification":"WRITE","paramCount":1,"schema":"42d586011b23","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateShowCustomerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"8b384c0bd6a0","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateShowSupplierReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"e28a3e070640","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateShelfLifeSettings","classification":"WRITE","paramCount":4,"schema":"a6f593fa5702","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateShowCurrencyTrailingZerosSetting","classification":"WRITE","paramCount":1,"schema":"42d586011b23","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateShowCustomerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"8b384c0bd6a0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateShowSupplierReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"e28a3e070640","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateSubsidiary","classification":"WRITE","paramCount":2,"schema":"7827cc68ef29","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateSuggestionNotificationSetting","classification":"WRITE","paramCount":1,"schema":"ac461e36d464","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateSupplierQuoteNotificationSetting","classification":"WRITE","paramCount":1,"schema":"56a6d061d358","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateTimeCardSetting","classification":"WRITE","paramCount":1,"schema":"9389085b800b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_upsertDocumentSection","classification":"WRITE","paramCount":5,"schema":"b894407ce0d0","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},+ {"name":"settings_updateSupplierQuoteNotificationSetting","classification":"WRITE","paramCount":1,"schema":"56a6d061d358","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateTimeCardSetting","classification":"WRITE","paramCount":1,"schema":"9389085b800b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_upsertDocumentSection","classification":"WRITE","paramCount":5,"schema":"eb83baf2cc33","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false,"upsert":"id"},{"name":"settings_upsertDocumentTemplate","classification":"WRITE","paramCount":6,"schema":"5d28da0e0ad6","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},- {"name":"settings_upsertItemSerialSequence","classification":"WRITE","paramCount":7,"schema":"95750d9ab5ae","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},+ {"name":"settings_upsertItemSerialSequence","classification":"WRITE","paramCount":7,"schema":"ddbb6ec42577","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false,"upsert":"id"},{"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","paramCount":1,"schema":"1fbe3d41dab0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_generateEmbedding","classification":"WRITE","paramCount":1,"schema":"e3dce8d1afb8","response":"569f4d6b0385","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_getBase64ImageFromSupabase","classification":"READ","paramCount":1,"schema":"923b083c9bca","response":"174e29b899b9","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getCountries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0e8a11b4e81c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getCustomerPortal","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"none","paginates":false},@@ -1524,14 +1443,12 @@{"name":"shared_importCsv","classification":"WRITE","paramCount":4,"schema":"8f2d77f74ffb","response":"none","injectAuth":"companyId+userId","permission":"none","paginates":false},{"name":"shared_insertNote","classification":"WRITE","paramCount":2,"schema":"260839f76e18","response":"c2fb0e5225f8","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_insertTag","classification":"WRITE","paramCount":1,"schema":"11926edb131b","response":"27f67ae1958c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},- {"name":"shared_lookupBuyPriceFromMap","classification":"WRITE","paramCount":4,"schema":"4360b71230e3","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_lookupPriceFromBreaks","classification":"WRITE","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_lookupBuyPriceFromMap","classification":"READ","paramCount":4,"schema":"4360b71230e3","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_lookupPriceFromBreaks","classification":"READ","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_resolveBuyUnitCost","classification":"WRITE","paramCount":3,"schema":"4c58915f44dd","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_resolveSupplierPrice","classification":"WRITE","paramCount":4,"schema":"c92834c91ef5","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_updateModelThumbnail","classification":"WRITE","paramCount":2,"schema":"7d1e1e5f7144","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},+ {"name":"shared_resolveSupplierPrice","classification":"READ","paramCount":4,"schema":"c92834c91ef5","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},- {"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},- {"name":"shared_upsertModelUpload","classification":"WRITE","paramCount":1,"schema":"b024a13e3afd","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},+ {"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},{"name":"users_deleteGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"c4dcdfdf8647","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:delete","paginates":false},{"name":"users_getCompaniesForUser","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},@@ -1558,10 +1475,10 @@{"name":"users_getUserSelectGroupMembers","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"b754519017cb","injectAuth":"companyId","permission":"users:view","paginates":false},{"name":"users_getUserSelectGroups","classification":"READ","paramCount":4,"schema":"b459d00208b5","response":"51b54791b40a","injectAuth":"companyId","permission":"users:view","paginates":false},{"name":"users_getUsersWithVerifiedMfa","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"4c1fdc714231","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_insertGroup","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"06c8b45796ca","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create","paginates":false},+ {"name":"users_insertGroup","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"06c8b45796ca","injectAuth":"companyId","permission":"users:create","paginates":false},{"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"62ac845cad71","injectAuth":"companyId","permission":"users:update","paginates":false},{"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"80d2a04ba04a","injectAuth":"companyId+userId","permission":"users:view","paginates":false},- {"name":"users_upsertGroup","classification":"WRITE","paramCount":2,"schema":"f06d2d858884","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false},- {"name":"users_upsertGroupMembers","classification":"DESTRUCTIVE","paramCount":2,"schema":"b32a69080685","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false}+ {"name":"users_upsertGroup","classification":"WRITE","paramCount":2,"schema":"f06d2d858884","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false},+ {"name":"users_upsertGroupMembers","classification":"DESTRUCTIVE","paramCount":2,"schema":"b32a69080685","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false}]}diff --git a/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts b/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.tsindex 04cdaffc14..de15c0a315 100644--- a/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts+++ b/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts@@ -134,6 +134,11 @@ export async function action({ request, params }: ActionFunctionArgs) {});}+ // A line that could not be mapped is reported, not swallowed: the modal+ // closes on `success`, so answering `true` here told the user every line was+ // mapped when some were not.+ let failed = 0;+for (const map of mappings) {if (map.action === "ignore") continue;@@ -181,35 +186,74 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!created.error && created.data?.id) {finalItemId = created.data.id;+ } else {+ failed++;+ logger.error("Failed to create part for RFQ line", {+ companyId,+ rfqId,+ lineId: map.lineId,+ readableId: createName,+ error: created.error+ });}}}if (finalItemId) {// Update salesRfqLine- await client+ const { error: lineError } = await client.from("salesRfqLine").update({itemId: finalItemId,updatedBy: userId}).eq("id", map.lineId);+ if (lineError) {+ failed++;+ logger.error("Failed to map RFQ line to item", {+ companyId,+ rfqId,+ lineId: map.lineId,+ itemId: finalItemId,+ error: lineError+ });+ continue;+ }- // Upsert customerPartToItem+ // Upsert customerPartToItem. The table has no audit columns — a+ // `createdBy` here made every upsert fail with PGRST204, and the+ // unchecked result meant the mapping silently never persisted.if (customerId && map.customerPartId) {- await serviceRole.from("customerPartToItem").upsert(- {+ const { error: customerPartError } = await serviceRole+ .from("customerPartToItem")+ .upsert(+ {+ customerId,+ customerPartId: map.customerPartId,+ itemId: finalItemId,+ companyId+ },+ { onConflict: "customerId,itemId" }+ );+ if (customerPartError) {+ failed++;+ logger.error("Failed to map customer part to item", {+ companyId,customerId,- customerPartId: map.customerPartId,itemId: finalItemId,- companyId,- createdBy: userId- },- { onConflict: "customerId, itemId" }- );+ customerPartId: map.customerPartId,+ error: customerPartError+ });+ }}}}+ if (failed > 0) {+ return {+ success: false,+ error: "Some lines could not be mapped. Review them and try again."+ };+ }return { success: true };}diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.tsindex 8a48325b26..49774d00c9 100644--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts@@ -106,7 +106,8 @@ import { DATABASE_ERROR_MESSAGES } from "./database-errors";import {type DispatchResult,dispatchOperation,- enrichWithAuthContext+ enrichWithAuthContext,+ resolveUpsertOperation} from "./dispatch.server";import { openApiHandler } from "./handler.server";import {@@ -406,18 +407,44 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa);});- it("f. missing _operation on a tool that requires it is rejected before the service runs", async () => {+ // No caller has to say whether an upsert creates or updates. accounting_upsertAccount+ // takes an optional id, so sending one IS the answer.+ it("f. no _operation, no id: a create — createdBy stamped, updatedBy not", async () => {const r = await runDispatch("accounting_upsertAccount",spies.upsertAccount,- {- account: { name: "x" }- }+ { account: { name: "x" } }+ );+ const [, payload] = r.calls[0] as [unknown, Record<string, unknown>];+ expect(payload).toMatchObject({ name: "x", createdBy: "u1" });+ expect("updatedBy" in payload).toBe(false);+ });++ it("f2. no _operation, id sent (flat or wrapped): an update — updatedBy stamped, createdBy not", async () => {+ for (const args of [+ { account: { id: "a1", name: "x" } },+ { id: "a1", name: "x" }+ ]) {+ const r = await runDispatch(+ "accounting_upsertAccount",+ spies.upsertAccount,+ args+ );+ const [, payload] = r.calls[0] as [unknown, Record<string, unknown>];+ expect(payload).toMatchObject({ id: "a1", updatedBy: "u1" });+ expect("createdBy" in payload).toBe(false);+ }+ });++ it("f3. an _operation that is neither create nor update is refused", async () => {+ const r = await runDispatch(+ "accounting_upsertAccount",+ spies.upsertAccount,+ { _operation: "replace", account: { name: "x" } });expect(r.calls).toEqual([]);- expect(r.dispatchError).toBeInstanceOf(ORPCError);expect((r.dispatchError as ORPCError<string, unknown>).message).toBe(- 'accounting_upsertAccount requires _operation to be "create" (insert a new record) or "update" (modify an existing one).'+ 'accounting_upsertAccount: _operation must be "create" or "update" when it is sent. It can be left out.');});@@ -744,19 +771,137 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction paid: "jm1"});});+});- it("q. an inverted-discriminator tool requires _operation, same as the createdBy convention", async () => {- const r = await runDispatch(- "production_upsertJobMaterial",- spies.upsertJobMaterial,- { jobId: "j1", itemId: "i1" }+// Where the payload cannot say (the id is required either way, or there is none),+// the manifest names the row to look for and the answer is whether it exists. The+// rules are the REAL ones from the generated manifest; only the database is stood in.+describe("upserts decided by whether the record exists", () => {+ const rule = (name: string) => {+ const upsert = operationsByName.get(name)?.upsert;+ if (!upsert) throw new Error(`${name} has no upsert rule`);+ return upsert;+ };+ // The service's payload parameter — the only object a key may be wrapped in.+ const PARAMS = ["record"];+ const database = (rows: Record<string, Record<string, unknown>[]>) => {+ const asked: [string, Record<string, unknown>][] = [];+ const rowExists = async (+ table: string,+ filter: Record<string, unknown>+ ) => {+ asked.push([table, filter]);+ return (rows[table] ?? []).some((row) =>+ Object.entries(filter).every(([column, value]) => row[column] === value)+ );+ };+ return { asked, rowExists };+ };++ it("q. a job material with a client-chosen id: created when new, updated once it exists", async () => {+ const upsert = rule("production_upsertJobMaterial");+ const args = { id: "jm1", jobId: "j1", quantity: 2 };++ const empty = database({});+ expect(+ await resolveUpsertOperation(upsert, args, PARAMS, empty.rowExists)+ ).toBe("create");+ expect(empty.asked).toEqual([["jobMaterial", { id: "jm1" }]]);++ const stored = database({ jobMaterial: [{ id: "jm1" }] });+ expect(+ await resolveUpsertOperation(upsert, args, PARAMS, stored.rowExists)+ ).toBe("update");+ });++ it("r. a part is found by its item id OR its part number", async () => {+ const upsert = rule("items_upsertPart");+ const items = { item: [{ id: "item_1", readableId: "PN-100" }] };++ for (const id of ["item_1", "PN-100"]) {+ const db = database(items);+ expect(+ await resolveUpsertOperation(upsert, { id }, PARAMS, db.rowExists)+ ).toBe("update");+ }+ const db = database(items);+ expect(+ await resolveUpsertOperation(+ upsert,+ { id: "PN-200" },+ PARAMS,+ db.rowExists+ )+ ).toBe("create");+ expect(db.asked).toEqual([+ ["item", { id: "PN-200" }],+ ["item", { readableId: "PN-200" }]+ ]);+ });++ it("s. a composite key: every column is matched, and a missing one means create without asking", async () => {+ const upsert = rule("items_upsertPickMethod");+ const db = database({+ pickMethod: [{ itemId: "i1", locationId: "l1" }]+ });+ expect(+ await resolveUpsertOperation(+ upsert,+ { itemId: "i1", locationId: "l1" },+ PARAMS,+ db.rowExists+ )+ ).toBe("update");+ expect(+ await resolveUpsertOperation(+ upsert,+ { itemId: "i1", locationId: "l2" },+ PARAMS,+ db.rowExists+ )+ ).toBe("create");++ const untouched = database({});+ expect(+ await resolveUpsertOperation(+ upsert,+ { itemId: "i1" },+ PARAMS,+ untouched.rowExists+ )+ ).toBe("create");+ expect(untouched.asked).toEqual([]);+ });++ it("u. the key is the RECORD's: an id inside some other nested object is not it", async () => {+ const byId = { keys: ["id"] };+ const never = database({}).rowExists;+ const resolve = (args: Record<string, unknown>) =>+ resolveUpsertOperation(byId, args, PARAMS, never);++ // A create whose custom fields happen to hold an `id` used to be sent down+ // the update branch.+ expect(await resolve({ name: "x", customFields: { id: "z" } })).toBe(+ "create");- expect(r.calls).toEqual([]);- expect(r.dispatchError).toBeInstanceOf(ORPCError);- expect((r.dispatchError as ORPCError<string, unknown>).message).toBe(- 'production_upsertJobMaterial requires _operation to be "create" (insert a new record) or "update" (modify an existing one).'+ // The record's own id, flat or inside its wrapper, still means update.+ expect(await resolve({ id: "a1", name: "x" })).toBe("update");+ expect(await resolve({ record: { id: "a1", name: "x" } })).toBe("update");+ // A lone unnamed wrapper is unwrapped, as the dispatcher does.+ expect(await resolve({ guessed: { id: "a1" } })).toBe("update");+ expect(await resolve({ record: { name: "x" }, other: { id: "z" } })).toBe(+ "create");});++ it("t. no operation publishes _operation, and every branching upsert has a rule", () => {+ for (const meta of operationsByName.values()) {+ expect(JSON.stringify(meta.schema)).not.toContain("_operation");+ }+ expect(+ [...operationsByName.values()].filter((meta) => meta.upsert).length+ ).toBeGreaterThan(80);+ });});// The exact ids the workflow engine's create actions dispatchdiff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.tsindex ad092f63df..c723958884 100644--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts@@ -5,7 +5,8 @@// The bridge from an oRPC procedure to a Carbon service function.//// Owns the executeFunction lineage in full: positional-arg assembly from-// serviceParams, payload stamping via enrichWithAuthContext, `_operation` handling,+// serviceParams, payload stamping via enrichWithAuthContext, create-vs-update+// resolution for upserts,// and the Supabase unwrap. HTTP, MCP, the agent and the workflow dispatcher all pass// through here. Unlike the legacy executor (which returned { success, … }), this// THROWS an ORPCError on failure: the HTTP handler maps that to a status code and@@ -92,8 +93,8 @@ export function enrichWithAuthContext(// discriminates on `"updatedBy" in` (update-branch first — upsertJobMaterial,// upsertQuoteMaterial, …) down its UPDATE branch, which matches zero rows for a// new id and returns PGRST116, so the record never inserts. Suppress it on an- // explicit create so the row inserts. With no _operation (operation undefined)- // both audit fields are stamped, exactly as before.+ // create so the row inserts. With no upsert rule (operation undefined) both+ // audit fields are stamped, exactly as before.if (operation === "create") {delete enriched.updatedBy;} else if (fields.includes("updatedBy")) {@@ -160,8 +161,11 @@ function overwriteIdentityKeys(return row;}-// Pulls the MCP-only `_operation` flag out of the args, top level or nested.-// Returns every value it found so the caller can reject contradictory ones.+// Pulls a caller-supplied `_operation` out of the args, top level or nested.+// No schema publishes it any more — the dispatcher works out create-vs-update+// itself (resolveUpsertOperation) — but callers written against the old+// contract still send it, and an explicit answer wins. Returns every value it+// found so the caller can reject contradictory ones.export function extractOperation(args: Record<string, any> | undefined): {operations: string[];args: Record<string, any> | undefined;@@ -189,6 +193,91 @@ export function extractOperation(args: Record<string, any> | undefined): {return { operations, args: cleaned };}+type UpsertRule = NonNullable<ManifestEntry["upsert"]>;++/** Service params the dispatcher fills itself; the rest carry the payload. */+const UPSERT_CONTEXT_PARAMS = new Set([+ "client",+ "db",+ "userId",+ "companyId",+ "companyGroupId",+ "eliminationClient"+]);++/**+ * A field of the RECORD the call is about: at the top level of the body, or+ * inside the object the payload is wrapped in — `{ job: { id } }`, where `job`+ * is one of the service's payload parameters, or a lone unnamed wrapper, which+ * the dispatcher unwraps the same way.+ *+ * Never inside any other nested object. Searching them all read+ * `{ name, customFields: { id } }` as an update of record `id`, and a create+ * was sent down the service's update branch.+ */+function recordField(+ args: Record<string, any> | undefined,+ field: string,+ payloadParams: readonly string[]+): unknown {+ if (!args) return undefined;+ if (args[field] !== undefined) return args[field];++ const isObject = (value: unknown): value is Record<string, any> =>+ value !== null && typeof value === "object" && !Array.isArray(value);++ for (const name of payloadParams) {+ const wrapper = args[name];+ if (isObject(wrapper) && wrapper[field] !== undefined)+ return wrapper[field];+ }+ const keys = Object.keys(args);+ if (keys.length === 1 && !payloadParams.includes(keys[0])) {+ const wrapper = args[keys[0]];+ if (isObject(wrapper)) return wrapper[field];+ }+ return undefined;+}++/**+ * Whether this call creates or updates, for a service that needs exactly one of+ * `createdBy` / `updatedBy` stamped. The caller is never asked:+ *+ * - a key field missing or empty → create;+ * - no lookups → the keys were sent, so update;+ * - lookups → update when one of them finds the row, else create.+ *+ * `rowExists` is the only thing here that touches the database.+ */+export async function resolveUpsertOperation(+ rule: UpsertRule,+ args: Record<string, any> | undefined,+ payloadParams: readonly string[],+ rowExists: (+ table: string,+ filter: Record<string, unknown>+ ) => Promise<boolean>+): Promise<McpOperation> {+ const values: Record<string, unknown> = {};+ for (const key of rule.keys) {+ const value = recordField(args, key, payloadParams);+ if (value === undefined || value === null || value === "") return "create";+ values[key] = value;+ }+ if (!rule.lookups) return "update";++ for (const lookup of rule.lookups) {+ const filter = Object.fromEntries(+ Object.entries(lookup.match).map(([column, field]) => [+ column,+ values[field]+ ])+ );+ if (await rowExists(lookup.table, filter)) return "update";+ }+ return "create";+}+const SCALAR_PARAM_TYPES = new Set(["string", "number", "integer", "boolean"]);// The declared JSON-Schema type of a top-level parameter, when that type is a@@ -230,9 +319,9 @@ const CONTEXT_PARAM_NAMES = new Set([** A wrapper op declares exactly one property named for the param — read it. An op* whose schema lists the param's own FIELDS is describing the object, not- * addressing it — pass the whole body. `_operation` is a synthetic discriminator- * and any property that is itself another serviceParam is addressed on its own- * pass, so neither counts toward that decision.+ * addressing it — pass the whole body. A property that is itself another+ * serviceParam is addressed on its own pass, so it does not count toward that+ * decision.*/function addressesWholeParam(meta: ManifestEntry, paramName: string): boolean {const properties = (meta.schema as { properties?: Record<string, unknown> })@@ -247,8 +336,7 @@ function addressesWholeParam(meta: ManifestEntry, paramName: string): boolean {if (payloadParams.length !== 1 || payloadParams[0] !== paramName) return true;const own = Object.keys(properties).filter(- (k) =>- k !== "_operation" && !(k !== paramName && meta.serviceParams.includes(k))+ (k) => !(k !== paramName && meta.serviceParams.includes(k)));return own.length === 1 && own[0] === paramName;}@@ -271,7 +359,7 @@ export async function dispatchOperation(? (input as Record<string, any>): undefined;- // Strip the MCP `_operation` discriminator before the args reach the service.+ // A legacy `_operation` never reaches the service.const { operations: requestedOperations, args: normalizedArgs } =extractOperation(rawArgs);@@ -285,29 +373,48 @@ export async function dispatchOperation(});}- const needsOperation = Boolean(- (meta.schema as { properties?: Record<string, unknown> })?.properties- ?._operation- );const distinctOperations = [...new Set(requestedOperations)];- if (needsOperation && distinctOperations.length > 1) {+ if (meta.upsert && distinctOperations.length > 1) {throw new ORPCError("BAD_REQUEST", {message: `${meta.name} received conflicting _operation values (${distinctOperations.join(", ")}).`});}const requestedOperation = distinctOperations[0];if (- needsOperation &&+ meta.upsert &&+ requestedOperation !== undefined &&requestedOperation !== "create" &&requestedOperation !== "update") {throw new ORPCError("BAD_REQUEST", {- message: `${meta.name} requires _operation to be "create" (insert a new record) or "update" (modify an existing one).`+ message: `${meta.name}: _operation must be "create" or "update" when it is sent. It can be left out.`});}- const operation = needsOperation- ? (requestedOperation as McpOperation)- : undefined;+ const operation: McpOperation | undefined = !meta.upsert+ ? undefined+ : ((requestedOperation as McpOperation | undefined) ??+ (await resolveUpsertOperation(+ meta.upsert,+ normalizedArgs,+ meta.serviceParams.filter((name) => !UPSERT_CONTEXT_PARAMS.has(name)),+ async (table, filter) => {+ // Scoped to the caller's company on top of RLS: a user-scoped client+ // can see every company the user belongs to.+ const { data, error } = await (context.client as any)+ .from(table)+ .select("companyId")+ .match(filter)+ .eq("companyId", context.companyId)+ .limit(1);+ if (error) {+ throw new ORPCError("BAD_REQUEST", {+ message: supabaseErrorMessage(error),+ data: { supabase: error }+ });+ }+ return Array.isArray(data) && data.length > 0;+ }+ )));const functionArgs: any[] = [];for (const paramName of meta.serviceParams) {diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 29243766ce..1791da7db8 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -178,7 +178,7 @@"lint": "biome lint --write ","start": "NODE_ENV=production react-router-serve ./build/server/index.js","test": "vitest run",- "typecheck": "tsgo --noEmit",+ "typecheck": "react-router typegen && tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/erp/test/mcp-manifest-cache-inputs.test.ts b/apps/erp/test/mcp-manifest-cache-inputs.test.tsnew file mode 100644index 0000000000..60c8cafde9--- /dev/null+++ b/apps/erp/test/mcp-manifest-cache-inputs.test.ts@@ -0,0 +1,87 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { existsSync, readdirSync, readFileSync } from "node:fs";+import { dirname, join, matchesGlob, relative, resolve } from "node:path";+import ts from "typescript";+import { describe, expect, it } from "vitest";++// The tool manifest is CACHED by turbo (`//#generate:mcp` in the root+// turbo.json), keyed on a list of input globs. A file the generator reads that+// is missing from that list is how a stale manifest ships: turbo sees nothing+// changed, restores the old output, and the app validates requests against a+// schema the code no longer has.+//+// The validators are the part that reaches furthest — the generator EXECUTES+// every `*.models.ts`, so whatever those files import can change a schema (an+// enum array in `sales.utils.ts`, a helper in `@carbon/utils`). This pins every+// such import to the cache inputs.+const ROOT = resolve(__dirname, "../../..");+const APP = join(ROOT, "apps/erp/app");+const MODULES = join(APP, "modules");++const inputs: string[] = JSON.parse(+ readFileSync(join(ROOT, "turbo.json"), "utf8")+).tasks["//#generate:mcp"].inputs;+const covered = (file: string) =>+ inputs.some((glob) => matchesGlob(relative(ROOT, file), glob));++// @carbon/* → its directory, from the workspace's own package.json files.+const packageDirs = new Map<string, string>();+for (const dir of [+ ...readdirSync(join(ROOT, "packages")).map((d) => join(ROOT, "packages", d)),+ join(ROOT, "docs/content")+]) {+ const manifest = join(dir, "package.json");+ if (existsSync(manifest)) {+ packageDirs.set(JSON.parse(readFileSync(manifest, "utf8")).name, dir);+ }+}++/** The repo file an import lands on, or null for a third-party package. */+function resolveImport(from: string, specifier: string): string | null {+ const onDisk = (base: string) =>+ [`${base}.ts`, `${base}.tsx`, join(base, "index.ts"), base].find(+ (candidate) => existsSync(candidate) && !candidate.endsWith("/")+ ) ?? `${base}.ts`;++ if (specifier.startsWith(".")) return onDisk(resolve(dirname(from), specifier));+ if (specifier.startsWith("~/")) return onDisk(join(APP, specifier.slice(2)));+ const scoped = /^(@carbon\/[^/]+)/.exec(specifier)?.[1];+ const dir = scoped ? packageDirs.get(scoped) : undefined;+ // Any file under the package's source stands for the package.+ return dir ? join(dir, "src/index.ts") : null;+}++const modelsFiles = readdirSync(MODULES).flatMap((module) =>+ readdirSync(join(MODULES, module))+ .filter((file) => file.endsWith(".models.ts"))+ .map((file) => join(MODULES, module, file))+);++describe("the manifest cache inputs", () => {+ it("found the models files", () => {+ expect(modelsFiles.length).toBeGreaterThan(10);+ });++ it("cover every file a models file imports", () => {+ const missing: string[] = [];+ for (const file of modelsFiles) {+ if (!covered(file)) missing.push(relative(ROOT, file));+ for (const { fileName } of ts.preProcessFile(readFileSync(file, "utf8"))+ .importedFiles) {+ const target = resolveImport(file, fileName);+ if (target && !covered(target)) {+ missing.push(+ `${relative(ROOT, target)} (imported by ${relative(ROOT, file)})`+ );+ }+ }+ }+ expect(+ missing,+ "add these to the //#generate:mcp inputs in turbo.json (and to the manifest trigger in .husky/pre-commit)"+ ).toEqual([]);+ });+});diff --git a/apps/erp/test/mcp-service-ast.test.ts b/apps/erp/test/mcp-service-ast.test.tsnew file mode 100644index 0000000000..4bb48b12c2--- /dev/null+++ b/apps/erp/test/mcp-service-ast.test.ts@@ -0,0 +1,381 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ branchesOnKeyPresence,+ dbWrites,+ namedTables,+ paginates,+ parseServiceSource+} from "../../../scripts/lib/service-ast";+import {+ declarationOf,+ upsertRule,+ withoutAbsentAuditColumns+} from "../../../scripts/lib/service-metadata";++// The generator's questions about a service function, asked of real source+// through the real compiler — no fixtures on disk, nothing stubbed.+function parse(source: string) {+ return Object.fromEntries(+ parseServiceSource("mod", source).map((fn) => [fn.name, fn])+ );+}++describe("service discovery", () => {+ const fns = parse(`+ /** Stray block above the real one. @mcp */+ /**+ * Reads a thing.+ * @mcp read+ */+ export async function getThing(+ client: Client,+ /** Newest first. */+ sortDescending: boolean = false,+ page = 1,+ { a, b }: { a: string; /** inner */ b: number },+ opts?: { limit: number }+ ) {}++ export const listThings = async (client: Client, ...ids: string[]) => {};++ const notExported = () => {};+ export const NOT_A_FUNCTION = 3;+ function helper() {}+ `);++ it("collects exported declarations and arrow consts, nothing else", () => {+ expect(Object.keys(fns)).toEqual(["getThing", "listThings"]);+ expect(fns.getThing?.toolName).toBe("mod_getThing");+ });++ it("reads a typed default as its declared type, and optional", () => {+ expect(fns.getThing?.params[1]).toEqual({+ name: "sortDescending",+ typeStr: "boolean",+ optional: true,+ description: "Newest first.",+ rest: false+ });+ expect(fns.getThing?.params[2]).toMatchObject({+ name: "page",+ typeStr: "number",+ optional: true+ });+ });++ it("names a destructured param and keeps comments out of its type", () => {+ const param = fns.getThing?.params[3];+ expect(param?.name).toBe("destructured");+ expect(param?.typeStr).not.toContain("inner");+ expect(param?.typeStr).toContain("b: number");+ // The description is the PARAM's own doc, never a field's.+ expect(param?.description).toBeUndefined();+ expect(fns.getThing?.params[4]).toMatchObject({ optional: true });+ });++ it("flags a rest parameter", () => {+ expect(fns.listThings?.params.map((p) => p.rest)).toEqual([false, true]);+ });++ it("takes tags from the doc block attached to the declaration only", () => {+ expect(fns.getThing?.tags).toEqual([{ name: "mcp", comment: "read" }]);+ expect(fns.getThing?.jsdoc).toContain("Reads a thing.");+ expect(fns.listThings?.tags).toEqual([]);+ });+});++describe("what a body does", () => {+ const fns = parse(`+ export async function castChain(client: any) {+ return (client.from("accountingPeriod") as any).insert({ a: 1 });+ }+ export async function viaVariable(client: any) {+ const query = client.from("job");+ await query.delete().eq("id", "x");+ }+ export async function kysely(trx: any) {+ await trx.deleteFrom("jobMaterial").execute();+ await trx.insertInto("jobMaterial").values({}).execute();+ }+ export async function setDelete(client: any) {+ const members = new Set<string>();+ members.delete("x");+ const rows = await client.from("item").select("*").range(0, 9);+ return rows.data.toString();+ }+ export async function storageWrite(client: any) {+ await client.storage.from("private").update("path", "body");+ }+ export async function upsertBranch(client: any, row: any) {+ if ("createdBy" in row) return client.from("a").insert(row);+ return client.from("b").update(row);+ }+ `);+ const writes = (name: string) => dbWrites(fns[name]!.node);++ it("follows a query chain through casts and a local variable", () => {+ expect(writes("castChain")).toEqual([+ { kind: "insert", table: "accountingPeriod" }+ ]);+ expect(writes("viaVariable")).toEqual([{ kind: "delete", table: "job" }]);+ });++ it("sees the Kysely spellings", () => {+ expect(writes("kysely")).toEqual([+ { kind: "delete", table: "jobMaterial" },+ { kind: "insert", table: "jobMaterial" }+ ]);+ });++ it("does not mistake a Set, a prototype method or storage for a row write", () => {+ expect(writes("setDelete")).toEqual([]);+ expect(writes("storageWrite")).toEqual([]);+ expect(namedTables(fns.storageWrite!.node)).toEqual([]);+ });++ it("answers the pagination, table and discriminator questions", () => {+ expect(paginates(fns.setDelete!.node)).toBe(true);+ expect(paginates(fns.castChain!.node)).toBe(false);+ expect(namedTables(fns.upsertBranch!.node)).toEqual(["a", "b"]);+ expect(+ branchesOnKeyPresence(fns.upsertBranch!.node, ["createdBy", "updatedBy"])+ ).toBe(true);+ expect(+ branchesOnKeyPresence(fns.castChain!.node, ["createdBy", "updatedBy"])+ ).toBe(false);+ });+});++// A tool is what its doc comment declares. The declaration is checked against+// the body in the one direction that can be checked.+describe("the @mcp declaration", () => {+ const fns = parse(`+ export async function untagged(client: any) {}++ /** @mcp read */+ export async function lookupPrice(client: any) {+ return client.from("price").select("*");+ }++ /**+ * Rewrites the prices for a line.+ * @mcp upsert destructive — replaces every row for the line+ */+ export async function upsertPrices(client: any) {+ await client.from("price").delete().eq("lineId", "x");+ return client.from("price").insert([]);+ }++ /** @mcp action */+ export async function lockPeriod(client: any) {+ return client.rpc("lock_period");+ }++ /** @mcp read */+ export async function getOrCreatePeriod(client: any) {+ return client.from("period").insert({});+ }++ /** @mcp upsert */+ export async function upsertSteps(client: any) {+ await client.from("step").delete().eq("id", "x");+ }++ /** @mcp fetch */+ export async function getThing(client: any) {}++ /**+ * @mcp update+ * @mcp delete+ */+ export async function twice(client: any) {}++ /**+ * @mcp update+ * @mcp audit createdBy+ * @mcp permission users:update+ */+ export async function withSettings(client: any) {}++ /** @mcp audit createdBy */+ export async function settingOnly(client: any) {}+ `);+ const declare = (name: string) => declarationOf(fns[name]!);++ it("is undefined without a tag — the function is simply not a tool", () => {+ expect(declare("untagged")).toBeUndefined();+ });++ it("reads the verb and the destructive modifier, whatever the function is called", () => {+ expect(declare("lookupPrice")).toEqual({ verb: "read", destructive: false });+ expect(declare("upsertPrices")).toEqual({+ verb: "upsert",+ destructive: true+ });+ expect(declare("lockPeriod")).toEqual({+ verb: "action",+ destructive: false+ });+ });++ it("refuses a read whose body writes", () => {+ expect(() => declare("getOrCreatePeriod")).toThrow(+ /declares `@mcp read` but its body writes to period/+ );+ });++ it("refuses a write whose body deletes rows without saying destructive", () => {+ expect(() => declare("upsertSteps")).toThrow(+ /Declare `@mcp upsert destructive`/+ );+ });++ it("tells a setting line from the verb line", () => {+ expect(declare("withSettings")).toEqual({+ verb: "update",+ destructive: false+ });+ expect(() => declare("settingOnly")).toThrow(/it has 0/);+ });++ it("refuses a verb outside the vocabulary, and two declarations", () => {+ expect(() => declare("getThing")).toThrow(/`@mcp fetch` is not a verb/);+ expect(() => declare("twice")).toThrow(+ /must declare exactly one `@mcp <verb>` line; it has 2/+ );+ });+});++// An upsert that branches on an audit field needs a rule for telling create+// from update, and the generator refuses to publish one without it. Table and+// column names are checked against the real generated database types.+describe("the upsert rule", () => {+ const fns = parse(`+ type Shape = { name: string };+ /** @mcp upsert */+ export async function byId(+ client: any,+ row: (Shape & { createdBy: string }) | (Shape & { id: string; updatedBy: string })+ ) {}++ /** @mcp upsert */+ export async function idBothWays(+ client: any,+ row:+ | (Shape & { id: string; createdBy: string })+ | (Shape & { id: string; updatedBy: string })+ ) {}++ /**+ * @mcp upsert+ * @mcp key pickMethod itemId, locationId+ */+ export async function composite(client: any, row: any) {}++ /**+ * @mcp upsert+ * @mcp key item id+ * @mcp key item readableId=id+ */+ export async function alternatives(client: any, row: any) {}++ /**+ * @mcp upsert+ * @mcp key notATable id+ */+ export async function unknownTable(client: any, row: any) {}++ /**+ * @mcp upsert+ * @mcp key pickMethod bogus+ */+ export async function unknownColumn(client: any, row: any) {}++ /**+ * @mcp upsert+ * @mcp key pickMethod itemId+ */+ export async function fieldNotInInput(client: any, row: any) {}+ `);+ const schema = (...fields: string[]) => ({+ type: "object",+ properties: Object.fromEntries(fields.map((f) => [f, { type: "string" }]))+ });++ it("reads `id decides` off the parameter type", () => {+ expect(upsertRule(fns.byId!, schema("id", "name"))).toEqual({+ keys: ["id"]+ });+ });++ it("refuses an upsert whose payload cannot say, until a key is declared", () => {+ expect(() => upsertRule(fns.idBothWays!, schema("id", "name"))).toThrow(+ /cannot say whether it creates or updates.*`@mcp key <table>/s+ );+ });++ it("turns key lines into lookups, several lines being alternatives", () => {+ expect(upsertRule(fns.composite!, schema("itemId", "locationId"))).toEqual({+ keys: ["itemId", "locationId"],+ lookups: [+ {+ table: "pickMethod",+ match: { itemId: "itemId", locationId: "locationId" }+ }+ ]+ });+ expect(upsertRule(fns.alternatives!, schema("id"))).toEqual({+ keys: ["id"],+ lookups: [+ { table: "item", match: { id: "id" } },+ { table: "item", match: { readableId: "id" } }+ ]+ });+ });++ it("refuses a key that names nothing real", () => {+ expect(() => upsertRule(fns.unknownTable!, schema("id"))).toThrow(+ /"notATable", which is not a table or view/+ );+ expect(() => upsertRule(fns.unknownColumn!, schema("bogus"))).toThrow(+ /"pickMethod" has no "bogus" column/+ );+ expect(() => upsertRule(fns.fieldNotInInput!, schema("id"))).toThrow(+ /field "itemId" is not part of the tool's input/+ );+ });+});++// The bug this branch started from: createdBy stamped onto a payload that is+// spread into a table with no such column (PGRST204).+describe("audit fields the table does not have", () => {+ const fns = parse(`+ export async function linkTable(client: any, row: any) {+ return client.from("customerPartToItem").insert([row]);+ }+ export async function audited(client: any, row: any) {+ return client.from("customer").insert([row]);+ }+ export async function twoTables(client: any, row: any) {+ await client.from("item").select("id");+ return client.from("customerPartToItem").insert([row]);+ }+ `);+ const fields = ["companyId", "createdBy", "updatedBy"] as const;+ const drop = (name: string) =>+ withoutAbsentAuditColumns([...fields], fns[name]!);++ it("drops them when the function's one table lacks the columns", () => {+ expect(drop("linkTable")).toEqual(["companyId"]);+ });++ it("keeps them when the table has the columns, or the table is ambiguous", () => {+ expect(drop("audited")).toEqual([...fields]);+ expect(drop("twoTables")).toEqual([...fields]);+ });+});+diff --git a/apps/erp/test/mcp-tool-metadata.test.ts b/apps/erp/test/mcp-tool-metadata.test.tsindex 29ea78551c..6fb420636c 100644--- a/apps/erp/test/mcp-tool-metadata.test.ts+++ b/apps/erp/test/mcp-tool-metadata.test.ts@@ -14,6 +14,10 @@ type Tool = {name: string;classification: "READ" | "WRITE" | "DESTRUCTIVE";serviceParams: string[];+ upsert?: {+ keys: string[];+ lookups?: { table: string; match: Record<string, string> }[];+ };schema: {type?: string;properties?: Record<string, any>;@@ -146,8 +150,12 @@ describe("mcp tool-metadata generator", () => {(t) => t.name === "production_upsertJobMaterial");expect(entries).toHaveLength(1);- // The wrapper keeps the service's discriminated-upsert contract.- expect(props(entries[0]!)._operation?.enum).toEqual(["create", "update"]);+ // The wrapper keeps the service's discriminated-upsert contract: its own+ // body branches, and its own doc names the row it updates.+ expect(entries[0]!.upsert).toEqual({+ keys: ["id"],+ lookups: [{ table: "jobMaterial", match: { id: "id" } }]+ });});// A union/intersection AROUND a validator reference publishes the@@ -288,28 +296,38 @@ describe("mcp tool-metadata generator", () => {expect(ability?.required).toBeUndefined();});- // Insert-vs-update discriminator, BOTH directions, gets a required `_operation`.+ // Insert-vs-update discriminator, BOTH directions, gets an upsert rule.// upsertQuoteMaterial / upsertJobMaterial branch on `if ("updatedBy" in …)` — the- // generator used to detect only the `"createdBy" in` convention, so these tools- // shipped without `_operation`, the dispatch always stamped updatedBy, and every- // create was forced down the UPDATE branch (0 rows → PGRST116, silent no-op).- it("gives an `_operation` flag to `\"updatedBy\" in` upserts, not only `\"createdBy\" in` ones", () => {- const requiresOperation = (name: string) => {- const t = get(name);- expect(props(t)._operation, `${name} should expose _operation`).toMatchObject({- enum: ["create", "update"]- });- expect(t.schema.required ?? [], `${name} should require _operation`).toContain(- "_operation"- );- };- // Inverted (`"updatedBy" in`) — the ones that were broken.- requiresOperation("sales_upsertQuoteMaterial");- requiresOperation("production_upsertJobMaterial");- requiresOperation("production_upsertJob");- requiresOperation("production_upsertProductionQuantity");- requiresOperation("resources_upsertPartner");- // Standard (`"createdBy" in`) control — unchanged, still carries the flag.- requiresOperation("sales_upsertQuoteOperation");+ // generator used to detect only the `"createdBy" in` convention, so the dispatch+ // always stamped updatedBy and every create was forced down the UPDATE branch+ // (0 rows → PGRST116, silent no-op). The rule is what lets the dispatcher stamp+ // exactly one audit field without the caller saying which.+ it("gives an upsert rule to `\"updatedBy\" in` upserts, not only `\"createdBy\" in` ones", () => {+ // Inverted (`"updatedBy" in`), id decides.+ expect(get("production_upsertJob").upsert).toEqual({ keys: ["id"] });+ expect(get("production_upsertProductionQuantity").upsert).toEqual({+ keys: ["id"]+ });+ // Inverted, id required either way — looked up.+ expect(get("sales_upsertQuoteMaterial").upsert?.lookups).toEqual([+ { table: "quoteMaterial", match: { id: "id" } }+ ]);+ expect(get("resources_upsertPartner").upsert?.lookups).toEqual([+ { table: "partner", match: { id: "id" } }+ ]);+ // Standard (`"createdBy" in`) control.+ expect(get("sales_upsertCustomerType").upsert).toEqual({ keys: ["id"] });+ });++ // `_operation: "create" | "update"` made every caller state what the server+ // can work out. It is gone from every schema; a non-branching write has no rule.+ it("never asks the caller whether an upsert creates or updates", () => {+ for (const tool of tools) {+ expect(JSON.stringify(tool.schema), tool.name).not.toContain("_operation");+ }+ expect(get("sales_insertQuote").upsert).toBeUndefined();+ expect(props(get("sales_upsertCustomerType")).id?.description).toContain(+ "omit to create"+ );});});diff --git a/apps/erp/test/mcp-tool-permissions.test.ts b/apps/erp/test/mcp-tool-permissions.test.tsindex 843cabeb5d..1b49b54563 100644--- a/apps/erp/test/mcp-tool-permissions.test.ts+++ b/apps/erp/test/mcp-tool-permissions.test.ts@@ -3,13 +3,14 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";+import { MCP_VERBS } from "../app/routes/api+/mcp+/lib/mcp-exposure";import metadata from "../app/routes/api+/mcp+/lib/tool-metadata.json";-// Pins the permission-derivation rules in scripts/lib/service-metadata.ts-// (derivePermission + permissionActionsFor) against the REAL generated manifest.-// These permissions gate every API-key call at the oRPC layer, so a generator-// change that silently re-derives them is an authorization change — it must fail-// here first.+// Pins what a tool's declared verb means for the permission it gates on, against+// the REAL generated manifest. These permissions gate every API-key call at the+// oRPC layer, so a change to the verb table is an authorization change — it must+// fail here first. Nothing below looks at a function's name: a tool is what its+// `@mcp <verb>` tag says it is.type Tool = {name: string;@@ -20,17 +21,15 @@ type Tool = {const allTools = metadata.tools as Tool[];-// PERMISSION_OVERRIDES in scripts/lib/service-metadata.ts — route-verified-// exceptions that win over the derivation rules. Pinned exactly below and-// excluded from the rule-based assertions. The API-key WRITES (upsert/delete)-// moved to @carbon/ee/api-keys.server behind requireEntitlement, so they are no-// longer MCP tools — only the read (getApiKeys) remains and keeps the override.+// `@mcp permission` on the function — a route-verified exception that wins over+// the verb. Pinned exactly below and excluded from the verb-based assertions.+// The API-key WRITES (upsert/delete) moved to @carbon/ee/api-keys.server behind+// requireEntitlement, so they are no longer MCP tools — only the read+// (getApiKeys) remains and keeps the override.const OVERRIDDEN = new Set(["settings_getApiKeys"]);const tools = allTools.filter((t) => !OVERRIDDEN.has(t.name));-const funcName = (t: Tool) => t.name.slice(t.module.length + 1).toLowerCase();-describe("permission overrides", () => {it("API-key management gates on users_update, matching its ERP routes", () => {for (const name of OVERRIDDEN) {@@ -68,49 +67,52 @@ describe("permission module mapping", () => {});});-describe("permission action derivation", () => {- it("every READ op gates on view only", () => {- for (const t of tools.filter((t) => t.classification === "READ")) {- expect(t.permission.actions, t.name).toEqual(["view"]);- }+describe("the verb table", () => {+ it("is the authorization contract — changing it is deliberate", () => {+ expect(+ Object.fromEntries(+ Object.entries(MCP_VERBS).map(([verb, rule]) => [+ verb,+ `${rule.classification} ${rule.actions.join("+")} [${rule.audit.join(",")}]`+ ])+ )+ ).toEqual({+ read: "READ view []",+ create: "WRITE create [createdBy,updatedBy]",+ update: "WRITE update [updatedBy]",+ // Pinned so a change is deliberate: an upsert needs BOTH, since one call+ // can insert or modify.+ upsert: "WRITE create+update [createdBy,updatedBy]",+ delete: "DESTRUCTIVE delete []",+ action: "WRITE update []"+ });});+});- it("every delete* op gates on delete", () => {- for (const t of tools.filter(- (t) => t.classification !== "READ" && funcName(t).startsWith("delete")- )) {- expect(t.permission.actions, t.name).toEqual(["delete"]);- }- });+describe("permission actions in the manifest", () => {+ const verbActions = Object.values(MCP_VERBS).map((rule) =>+ rule.actions.join("+")+ );- it("every upsert* op gates on create AND update (open question 2 in the parent plan — pinned so a change is deliberate)", () => {- for (const t of tools.filter(- (t) => t.classification !== "READ" && funcName(t).startsWith("upsert")- )) {- expect(t.permission.actions, t.name).toEqual(["create", "update"]);+ it("every op gates on exactly one verb's actions", () => {+ for (const t of tools) {+ expect(verbActions, t.name).toContain(t.permission.actions.join("+"));}});- it("insert|create|add|new|copy|duplicate|generate* ops gate on create", () => {- for (const t of tools.filter(- (t) =>- t.classification !== "READ" &&- !funcName(t).startsWith("upsert") &&- /^(insert|create|add|new|copy|duplicate|generate)/.test(funcName(t))- )) {- expect(t.permission.actions, t.name).toEqual(["create"]);+ it("a READ gates on view, and nothing else does", () => {+ for (const t of tools) {+ expect(t.permission.actions.includes("view"), t.name).toBe(+ t.classification === "READ"+ );}});- it("every remaining write verb gates on update", () => {- for (const t of tools.filter(- (t) =>- t.classification !== "READ" &&- !/^(upsert|delete|insert|create|add|new|copy|duplicate|generate)/.test(- funcName(t)- )+ it("gating on delete means the tool is labelled DESTRUCTIVE", () => {+ for (const t of tools.filter((t) =>+ t.permission.actions.includes("delete"))) {- expect(t.permission.actions, t.name).toEqual(["update"]);+ expect(t.classification, t.name).toBe("DESTRUCTIVE");}});diff --git a/apps/erp/turbo.json b/apps/erp/turbo.jsonnew file mode 100644index 0000000000..b040ad7bdf--- /dev/null+++ b/apps/erp/turbo.json@@ -0,0 +1,15 @@+{+ "$schema": "https://turborepo.org/schema.json",+ "extends": ["//"],+ "tasks": {+ "build": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ },+ "test": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ },+ "typecheck": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ }+ }+}diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.tsindex bb3d7cbdfe..c9c0a4d9af 100644--- a/apps/erp/vite.config.ts+++ b/apps/erp/vite.config.ts@@ -73,6 +73,15 @@ export default defineConfig(({ command, isSsrBuild, mode }) => {command === "build" && process.env.ASSETS_URL? process.env.ASSETS_URL.replace(/\/*$/, "/"): undefined,+ /**+ * The jSquash image codecs (paperless thumbnails, via+ * `@carbon/files/media/node`) import their wasm as `?inline` data URIs, so+ * the bytes ride in the server bundle instead of being resolved off disk at+ * runtime — a bundled `require.resolve` is anchored in the output directory,+ * where neither `@jsquash` nor the .wasm exists. Vite only honours `?inline`+ * for a file it treats as an asset, and `.wasm` is not one by default.+ */+ assetsInclude: ["**/*.wasm"],build: {minify: true,rolldownOptions: {diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 87fb8b5156..decbb0d73d 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -147,7 +147,10 @@ export async function getJobOperationBatch(.select("id, readableId, attributes, createdAt").in("attributes->>Job Make Method", makeMethodIds).eq("companyId", companyId)+ // Unit-axis order — see getTrackedEntitiesByMakeMethodId..order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true }): { data: [], error: null };const entityByMakeMethod = new Map<string,@@ -1907,6 +1910,34 @@ export async function getScrapReasonsList(.order("name");}+/**+ * The tracked entities of a make method in UNIT-AXIS order — position `i` here is+ * the `index` every `jobOperationStepRecord` (and inspection result) for unit `i`+ * is stored under (`deriveUnits` in `~/utils/units`). So this order is not+ * cosmetic: it is the join key between a recorded value and the serial it was+ * recorded for, and it must be the same on every read, forever.+ *+ * `createdAt` alone is NOT that. `assign-serial-numbers` used to mint every+ * serial after the first in one INSERT, so they share a `createdAt`; Postgres+ * returns tied rows in physical order, and any UPDATE moves a row to the end of+ * it. Logging one serial complete therefore reshuffled the others, and the+ * values recorded at position 2 displayed under whichever serial slid into+ * position 2 — and the Assembly view then auto-completed that unit.+ *+ * The tiebreakers make the order a pure function of immutable columns:+ * `readableId` puts tied serials back in the sequence they were minted in+ * (serials are zero-padded, so text order is number order within a batch) and+ * `id` settles anything left. New serials no longer tie at all — the mint now+ * spaces their `createdAt` — so this only decides rows minted before that.+ *+ * ponytail: text order, so a batch whose counter overflowed its pad width+ * (…99 → …100 at size 2) sorts wrong among PRE-EXISTING tied rows. Sort with a+ * numeric collator in JS if that ever turns up.+ *+ * Kept in step with the ERP copy (`inventory.service.ts`), the inline copies+ * (`getJobOperationBatch` here, `JobHeader.tsx`) and the `issue` edge+ * function's serial-complete branch — they all index into this same axis.+ */export async function getTrackedEntitiesByMakeMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string,@@ -1917,7 +1948,9 @@ export async function getTrackedEntitiesByMakeMethodId(.select("*").eq("attributes->>Job Make Method", jobMakeMethodId).eq("companyId", companyId)- .order("createdAt", { ascending: true });+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });}type SerialEntityForSelection = Pick<diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex 37833fb86e..32726ace93 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -117,7 +117,7 @@"lint": "biome lint --write ","start": "NODE_ENV=production react-router-serve ./build/server/index.js","test": "vitest run",- "typecheck": "tsgo --noEmit",+ "typecheck": "react-router typegen && tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/starter/package.json b/apps/starter/package.jsonindex 7209b878bc..9798b9fec1 100644--- a/apps/starter/package.json+++ b/apps/starter/package.json@@ -61,7 +61,7 @@"dev": "react-router dev","lint": "biome lint --write ","start": "react-router-serve ./build/server/index.js",- "typecheck": "tsgo --noEmit",+ "typecheck": "react-router typegen && tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/docs/content/turbo.json b/docs/content/turbo.jsonnew file mode 100644index 0000000000..1a60fbf9e9--- /dev/null+++ b/docs/content/turbo.json@@ -0,0 +1,9 @@+{+ "$schema": "https://turborepo.org/schema.json",+ "extends": ["//"],+ "tasks": {+ "test": {+ "cache": false+ }+ }+}diff --git a/docs/turbo.json b/docs/turbo.jsonnew file mode 100644index 0000000000..b040ad7bdf--- /dev/null+++ b/docs/turbo.json@@ -0,0 +1,15 @@+{+ "$schema": "https://turborepo.org/schema.json",+ "extends": ["//"],+ "tasks": {+ "build": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ },+ "test": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ },+ "typecheck": {+ "dependsOn": ["$TURBO_EXTENDS$", "//#generate:mcp"]+ }+ }+}diff --git a/package.json b/package.jsonindex a4b4e4940c..0d122cab9f 100755--- a/package.json+++ b/package.json@@ -16,7 +16,7 @@"npm-run-all": "catalog:","rimraf": "catalog:","supabase": "catalog:",- "ts-morph": "22.0.0",+ "ts-morph": "28.0.0","tsx": "catalog:","turbo": "2.9.6","typescript": "catalog:",@@ -68,7 +68,7 @@"lingui:compile": "lingui compile --namespace es","lingui:extract": "lingui extract --clean","lint": "turbo run lint",- "postinstall": "pnpm --filter @carbon/documents build && pnpm run generate:mcp",+ "postinstall": "turbo run @carbon/documents#build //#generate:mcp --output-logs=new-only","prepare": "pnpm exec husky install; if [ -f .ai/scripts/install-skills.sh ]; then bash .ai/scripts/install-skills.sh; fi","test": "turbo run test","translate": "pnpm run lingui:extract && pnpm exec linguito translate --llm && pnpm lingui:clean",diff --git a/packages/api/AGENTS.md b/packages/api/AGENTS.mdindex 11e1a886c5..7f1f6a8594 100644--- a/packages/api/AGENTS.md+++ b/packages/api/AGENTS.md@@ -8,7 +8,7 @@ zod round-trip. Internal workspace package — never published to npm.- Treat `ManifestEntry` as the shape of the GENERATED manifest — the data itself isthe erp app's gitignored `routes/api+/mcp+/lib/tool-metadata.json`, produced by- `pnpm generate:mcp` (turbo root task `//#generate:mcp`; `typecheck`/`build`/`test`+ `pnpm generate:mcp` (turbo root task `//#generate:mcp`; erp's and docs' `typecheck`/`build`/`test`depend on it). Change the generator (`scripts/lib/service-metadata.ts`) and thesetypes together.- Keep `jsonSchema()` a pass-through validator (never rejects). It is the **output**diff --git a/packages/api/src/manifest-types.ts b/packages/api/src/manifest-types.tsindex 17a03749ab..138c1ffdac 100644--- a/packages/api/src/manifest-types.ts+++ b/packages/api/src/manifest-types.ts@@ -45,10 +45,18 @@ export interface ManifestEntry {* fetchAll read — pagination args are inert in the service, and the MCP* layer pages the response at its own boundary instead. */paginates: boolean;- /** The JSON Schema for the operation's input. When the service branches on- * `"createdBy" in payload`, a required `_operation: "create" | "update"`- * property is present here — that property IS the marker (there is no parallel- * flag), matching how the dispatcher decides today. */+ /** Present when the service picks insert-vs-update by testing for an audit+ * field on the payload (`"createdBy" in payload`), so the dispatcher has to+ * stamp exactly one of them. `keys` are the payload fields that identify the+ * record; a call missing any of them is a create. With no `lookups`, a call+ * carrying them all is an update. With `lookups`, it is an update only when+ * one of them finds a row in the caller's company — `match` maps a column of+ * `table` to the payload field it is compared with. */+ upsert?: {+ keys: string[];+ lookups?: Array<{ table: string; match: Record<string, string> }>;+ };+ /** The JSON Schema for the operation's input. */schema: Record<string, unknown>;/** The JSON Schema for the operation's RESPONSE `data`, reflected from the* service function's TypeScript return type — absent when nothing useful coulddiff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.mdindex 76f28770b9..d0b8a732c3 100644--- a/packages/checks/AGENTS.md+++ b/packages/checks/AGENTS.md@@ -35,6 +35,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)- **Authz ownership** (`CONFORMANCE_CHECKS` via `collectFindings`): `noAuthzDdlInMigrations(helpers)` fails a migration newer than `20260927000000` that runs `CREATE`/`ALTER POLICY` on a public table (storage bucket policies stay allowed), or defines, alters or drops a managed RLS helper — policies live in `packages/database/src/authz/manifest.ts`, helpers in `packages/database/src/authz/helpers/<name>.sql`, and `authz sync` applies both after migrations. The helper list is read from that directory (`loadAuthzHelperNames`), so it cannot drift from the files. `DROP POLICY` is allowed (dropping a column a policy uses). Files starting with the `authz migration` header are exempt; `@carbon/database`'s `migration.test.ts` verifies their contents. Older migrations are history, so there are no baseline entries- **Forwarded headers** (own source, `REQUEST_HANDLING_ROOTS`: every app + auth, ee, jobs, lib, utils, edge functions): `noRawForwardedHeaders` fails a raw read of `X-Forwarded-For/-Host/-Proto` or `X-Real-IP` outside `packages/utils/src/headers.ts` — use `getClientIp` / `getRequestProtocol` / `getRequestHost` / `getRequestOrigin`. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable first `X-Forwarded-For` entry. No baseline entries- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`+- **Missing audit columns** (built in `collectFindings`, not `TS_CHECKS`): `noMissingAuditColumn(columns)` fails a write that names `createdBy`/`updatedBy` on a relation that has no such column — PostgREST rejects the whole statement (`PGRST204 Could not find the 'createdBy' column of '<table>'`) and TypeScript does not flag it, because supabase-js widens the insert/upsert argument enough for the excess property to survive. That is how the `customerPartToItem` upsert in `sales-rfq.$rfqId.map-lines.ts` shipped with an unchecked result, so every RFQ-line → customer-part mapping silently failed. Roughly a third of Carbon's tables have no audit columns (favourites, link tables, the lean material lookups, `companySettings`) while golden rule 3 says to include them, so it is an easy assumption to carry into the wrong table. It takes the column map as an ARGUMENT — `loadDbTableColumns(root)` (`sources/db-columns.ts`) reads the generated `packages/database/src/types.ts` `Row:` blocks, so the I/O stays in `sources/` and `scan` stays pure, the same shape as `noAuthzDdlInMigrations(loadAuthzHelperNames(root))`. Scope is the LITERAL argument of the write (`.from`/`insertInto`/`updateTable` + `.insert`/`.upsert`/`.update`/`.values`/`.set`); a payload object spread into the row is invisible here, and for the MCP/API layer that same generated schema drives `withoutAbsentAuditColumns` in `scripts/lib/service-metadata.ts`. No baseline entries — the one hit was fixed when it was added- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app` or `packages/jobs/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. Edge functions and `packages/ee` are out of scope (see the file header). One baseline entry: the `companyGroup` delete in `packages/jobs/.../scheduled/purge-company.ts` (a group has no `companyId` column; its `id` is the tenant-group key). Every other hit was fixed when it was added- **Unguarded submit buttons** (in `TS_CHECKS`, `.tsx` only): `noUnguardedSubmit` fails a `<Button>`/`<button>`/`<IconButton>` carrying `type="submit"` whose own opening tag names no in-flight signal (`isLoading`, `isSubmitting`, `isPending`, `isSaving`, `useIsSubmitting`, or a `*fetcher|navigation|transition*.state` read). A live submit button posts again on every click and each POST runs to completion server-side — `fetcher.submit` aborts the previous BROWSER request, but no route action reads `request.signal` — which is how one quote finalize emailed the customer the same PDF three times. It parses the real opening tag (brace- and quote-aware), so a guard written after `type="submit"` still counts and a `>` inside `{a > b}` does not end the tag early. **The presence of `isDisabled` is deliberately not enough**: the incident's button was `isDisabled={loading}` where `loading` was the modal's data-fetch flag, so a check that accepted any `isDisabled` would have passed the exact line it exists to catch; word boundaries matter too (`loading` must not satisfy `isLoading`). Buttons inside a `<ValidatedForm>` are skipped — `ValidatedForm.handleSubmit` drops a re-entrant submit, so a second click cannot produce a second POST however the button is written. `packages/form/src/components/Submit.tsx` is excluded; it IS the guard. The check cannot do dataflow, so a guard held in a differently-named local (`disabled={busy}`) is baselined rather than rewritten. 32 baseline entries, all reviewed: logout/company-switch/theme/console-toggle (idempotent), delete and rule-unassign (a second delete is a no-op), the two chat composers (guarded by a `flushSync` clear plus an empty-message return), and `ConfiguratorForm` (its submit is an `onSubmit` callback — the in-flight state lives at the caller)- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential firstdiff --git a/packages/checks/src/conformance/no-missing-audit-column.test.ts b/packages/checks/src/conformance/no-missing-audit-column.test.tsnew file mode 100644index 0000000000..e96beb7cce--- /dev/null+++ b/packages/checks/src/conformance/no-missing-audit-column.test.ts@@ -0,0 +1,192 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { noMissingAuditColumn } from "./no-missing-audit-column";++const FILE = "apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts";++// customerPartToItem really has these six columns and no audit ones; item has+// both; company has updatedBy but not createdBy. A table absent from the map is+// unknown to the check.+const COLUMNS = new Map([+ [+ "customerPartToItem",+ new Set([+ "id",+ "customerId",+ "customerPartId",+ "customerPartRevision",+ "itemId",+ "companyId"+ ])+ ],+ ["item", new Set(["id", "companyId", "createdBy", "updatedBy"])],+ ["company", new Set(["id", "name", "updatedBy"])]+]);++const check = noMissingAuditColumn(COLUMNS);+const snippets = (ts: string) => check.scan(FILE, ts).map((v) => v.snippet);++describe("noMissingAuditColumn", () => {+ it("flags the real customerPartToItem upsert that failed with PGRST204", () => {+ const ts = [+ 'await serviceRole.from("customerPartToItem").upsert(',+ " {",+ " customerId,",+ " customerPartId: map.customerPartId,",+ " itemId: finalItemId,",+ " companyId,",+ " createdBy: userId",+ " },",+ ' { onConflict: "customerId,itemId" }',+ ");"+ ].join("\n");+ const v = check.scan(FILE, ts);+ expect(v).toHaveLength(1);+ expect(v[0]?.snippet).toBe("createdBy");+ expect(v[0]?.line).toBe(7);+ expect(v[0]?.message).toContain("customerPartToItem");+ });++ it("flags both fields, and only the ones the table lacks", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").insert({ createdBy, updatedBy });'+ )+ ).toEqual(["createdBy", "updatedBy"]);+ // company has updatedBy but not createdBy+ expect(+ snippets('client.from("company").update({ createdBy, updatedBy });')+ ).toEqual(["createdBy"]);+ });++ it("allows audit fields on a table that has them", () => {+ expect(+ snippets(+ 'client.from("item").insert({ readableId, companyId, createdBy });'+ )+ ).toEqual([]);+ });++ it("ignores a read and a delete on the same table", () => {+ const ts = [+ 'const { data } = await client.from("customerPartToItem").select("*")',+ ' .eq("createdBy", userId);',+ 'await client.from("customerPartToItem").delete().eq("id", id);'+ ].join("\n");+ expect(snippets(ts)).toEqual([]);+ });++ it("ignores a table it has no columns for", () => {+ expect(+ snippets('client.from("someFutureTable").insert({ createdBy });')+ ).toEqual([]);+ });++ it("covers the Kysely spellings", () => {+ const insert = [+ 'await trx.insertInto("customerPartToItem")',+ " .values({ customerId, itemId, companyId, createdBy: userId })",+ " .execute();"+ ].join("\n");+ expect(snippets(insert)).toEqual(["createdBy"]);++ const update = [+ 'await trx.updateTable("customerPartToItem")',+ " .set({ customerPartId, updatedBy: userId })",+ " .execute();"+ ].join("\n");+ expect(snippets(update)).toEqual(["updatedBy"]);+ });++ // The write must come from the target's own chain. A character window reached+ // into the following statement and blamed the wrong table; an earlier version+ // of this test only passed because it padded the gap with comments.+ describe("binds the write to the matched chain", () => {+ it("does not blame a link table for the next statement's write", () => {+ const ts = [+ 'client.from("customerPartToItem").select("id");',+ 'client.from("item").insert({ createdBy });'+ ].join("\n");+ expect(snippets(ts)).toEqual([]);+ });++ it("does not blame a table for a write on the preceding line", () => {+ const ts = [+ 'client.from("item").insert({ createdBy });',+ 'client.from("customerPartToItem").select("id");'+ ].join("\n");+ expect(snippets(ts)).toEqual([]);+ });++ it("still follows a chain broken across lines", () => {+ const ts = [+ "await client",+ ' .from("customerPartToItem")',+ " // staged by the RFQ mapping",+ " .upsert({ customerId, createdBy: userId })",+ ' .select("id");'+ ].join("\n");+ expect(snippets(ts)).toEqual(["createdBy"]);+ });+ });++ // A name only counts in KEY position in a row object.+ describe("inspects row keys, not identifier occurrences", () => {+ it("ignores an audit identifier used as a value", () => {+ expect(+ snippets(+ 'client.from("company").update({ name: createdBy, updatedBy });'+ )+ ).toEqual([]);+ });++ it("flags a quoted key", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").insert({ "createdBy": userId });'+ )+ ).toEqual(["createdBy"]);+ });++ it("ignores the keys of a nested value object", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").update({ meta: { createdBy } });'+ )+ ).toEqual([]);+ });++ it("ignores a write option in the second argument", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").upsert({ customerId }, { onConflict: "createdBy" });'+ )+ ).toEqual([]);+ });++ it("ignores an audit name inside a call in a value position", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").update({ customerPartId: pick(row, createdBy) });'+ )+ ).toEqual([]);+ });++ it("flags every row of an inserted array", () => {+ expect(+ snippets(+ 'client.from("customerPartToItem").insert([{ createdBy }, { updatedBy }]);'+ )+ ).toEqual(["createdBy", "updatedBy"]);+ });++ it("finds nothing in a spread payload — that is the generator's job", () => {+ expect(+ snippets('client.from("customerPartToItem").insert([customerPart]);')+ ).toEqual([]);+ });+ });+});diff --git a/packages/checks/src/conformance/no-missing-audit-column.ts b/packages/checks/src/conformance/no-missing-audit-column.tsnew file mode 100644index 0000000000..1c10895126--- /dev/null+++ b/packages/checks/src/conformance/no-missing-audit-column.ts@@ -0,0 +1,287 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ConformanceCheck, Violation } from "../check";++/**+ * A write must not name `createdBy` / `updatedBy` on a table that has no such+ * column. PostgREST rejects the whole statement with+ * `PGRST204 Could not find the 'createdBy' column of '<table>' in the schema+ * cache`, and TypeScript does not catch it — supabase-js widens the+ * insert/upsert argument enough that the excess property survives, which is how+ * `sales-rfq.$rfqId.map-lines.ts` shipped an upsert on `customerPartToItem`+ * (six columns, none of them audit) whose result was never checked, so every+ * RFQ-line → customer-part mapping silently failed.+ *+ * Roughly a third of Carbon's tables have no audit columns — favourites, link+ * tables, the lean material lookups, `companySettings` — while the convention+ * (`conventions-index.md` golden rule 3) says to include them, so this is an+ * easy assumption to carry into the wrong table.+ *+ * Scope is the KEYS of the literal row object(s) in the write's FIRST argument.+ * A payload object spread into the row (`insert([row])`) can carry the same bad+ * key, but only the caller knows what is in it; for the MCP/API layer that+ * decision is derived from this same generated schema by+ * `withoutAbsentAuditColumns` in `scripts/lib/service-metadata.ts`.+ *+ * Both halves of the match are structural rather than textual, because the loose+ * version of each produced false findings and this check gates commits through+ * `collectFindings`:+ *+ * - The write must sit in the matched target's OWN call chain. A character+ * window picks up the NEXT statement's write instead, so+ * `from("link").select("id"); from("item").insert({ createdBy })` reported+ * `createdBy` against `link`.+ * - A name must be in key POSITION in a row object. Matching the bare name+ * anywhere flagged an identifier used as a value+ * (`update({ name: createdBy })`), flagged the keys of nested value objects,+ * and missed a quoted key (`{ "createdBy": userId }`) entirely.+ */+const AUDIT_FIELDS = ["createdBy", "updatedBy"] as const;+type AuditField = (typeof AUDIT_FIELDS)[number];++/** `.from("t")`, `insertInto("t")`, `updateTable("t")`. */+const TARGET_RE = /(?:\.from|insertInto|updateTable)\(\s*["'`](\w+)["'`]\s*\)/g;++/** Chain members whose first argument carries the row(s). */+const WRITE_VERBS = new Set(["insert", "upsert", "update", "values", "set"]);++const IDENT_START = /[A-Za-z_$]/;+const IDENT_PART = /[\w$]/;++/** Index just past the string literal that opens at `i`. */+function skipString(text: string, i: number): number {+ const quote = text[i];+ for (let j = i + 1; j < text.length; j++) {+ if (text[j] === "\\") {+ j++;+ continue;+ }+ if (text[j] === quote) return j + 1;+ }+ return text.length;+}++/** Index just past the comment that opens at `i`, or `i` when there is none. */+function skipComment(text: string, i: number): number {+ if (text[i] !== "/") return i;+ if (text[i + 1] === "/") {+ const nl = text.indexOf("\n", i);+ return nl === -1 ? text.length : nl + 1;+ }+ if (text[i + 1] === "*") {+ const end = text.indexOf("*/", i + 2);+ return end === -1 ? text.length : end + 2;+ }+ return i;+}++/** Index of the first character at or after `i` that is neither space nor comment. */+function skipTrivia(text: string, i: number): number {+ for (;;) {+ while (i < text.length && /\s/.test(text[i] as string)) i++;+ const after = skipComment(text, i);+ if (after === i) return i;+ i = after;+ }+}++/** Index of the bracket matching the one at `open`, skipping strings and comments. */+function matchBracket(text: string, open: number): number {+ const close = { "(": ")", "[": "]", "{": "}" }[text[open] as string];+ if (!close) return open;+ let depth = 0;+ for (let i = open; i < text.length; i++) {+ const c = text[i] as string;+ if (c === '"' || c === "'" || c === "`") {+ i = skipString(text, i) - 1;+ continue;+ }+ if (c === "/") {+ const after = skipComment(text, i);+ if (after !== i) {+ i = after - 1;+ continue;+ }+ }+ if (c === text[open]) depth++;+ else if (c === close) {+ depth--;+ if (depth === 0) return i;+ }+ }+ return text.length - 1;+}++/**+ * The opening paren of the write call belonging to the SAME chain as a target+ * that ends at `from`, else null. Walks `.member(…)` segments and stops at+ * anything that is not one — a `;`, a new statement, the end of an expression.+ */+function writeInChain(contents: string, from: number): number | null {+ let i = from;+ for (;;) {+ i = skipTrivia(contents, i);+ if (contents[i] !== ".") return null;+ i = skipTrivia(contents, i + 1);+ if (!IDENT_START.test(contents[i] ?? "")) return null;+ let end = i;+ while (end < contents.length && IDENT_PART.test(contents[end] as string)) {+ end++;+ }+ const member = contents.slice(i, end);+ const afterMember = skipTrivia(contents, end);+ if (contents[afterMember] !== "(") {+ // A property access rather than a call — keep walking the same chain.+ i = afterMember;+ continue;+ }+ if (WRITE_VERBS.has(member)) return afterMember;+ i = matchBracket(contents, afterMember) + 1;+ }+}++/**+ * Top-level keys of the row object(s) in the call's FIRST argument, each with+ * its absolute index. A ROW object is an object literal with no enclosing object+ * literal, so `insert({…})` and `insert([{…}, {…}])` both yield rows while a+ * nested value object does not. The second argument (`{ onConflict }`) is never+ * reached, and shorthand, `key:` and `"key":` forms all count.+ */+function rowKeys(+ contents: string,+ open: number+): { name: string; index: number }[] {+ const close = matchBracket(contents, open);+ const keys: { name: string; index: number }[] = [];+ // One frame per open object literal: whether it is a row, and whether we are+ // inside a nested bracket/paren of it (where a comma separates values, not+ // keys).+ const frames: { isRow: boolean; nesting: number }[] = [];+ // Brackets/parens seen OUTSIDE every object literal, so an array of rows+ // (`insert([{…}, {…}])`) is not mistaken for a second argument.+ let outerNesting = 0;+ let expectKey = false;++ for (let i = open + 1; i < close; i++) {+ const c = contents[i] as string;+ const frame = frames[frames.length - 1];+ const inKeyPosition =+ expectKey && frame?.isRow === true && frame.nesting === 0;++ if (c === '"' || c === "'" || c === "`") {+ const end = skipString(contents, i);+ if (inKeyPosition) {+ const raw = contents.slice(i + 1, end - 1);+ // Only a quoted KEY counts — it must be followed by a colon.+ if (/^\w+$/.test(raw) && contents[skipTrivia(contents, end)] === ":") {+ keys.push({ name: raw, index: i });+ }+ }+ expectKey = false;+ i = end - 1;+ continue;+ }+ if (c === "/") {+ const after = skipComment(contents, i);+ if (after !== i) {+ i = after - 1;+ continue;+ }+ }+ if (c === "{") {+ frames.push({ isRow: frames.length === 0, nesting: 0 });+ expectKey = true;+ continue;+ }+ if (c === "}") {+ frames.pop();+ expectKey = false;+ continue;+ }+ if (c === "[" || c === "(") {+ if (frame) frame.nesting++;+ else outerNesting++;+ expectKey = false;+ continue;+ }+ if (c === "]" || c === ")") {+ if (frame) frame.nesting--;+ else outerNesting--;+ expectKey = false;+ continue;+ }+ if (c === ",") {+ if (!frame) {+ // A comma outside every object literal AND every bracket separates+ // ARGUMENTS: the row(s) are the first one, so stop before+ // `{ onConflict }` and friends. Inside a bracket it separates rows.+ if (outerNesting === 0) break;+ continue;+ }+ expectKey = frame.nesting === 0;+ continue;+ }+ if (/\s/.test(c)) continue;++ if (inKeyPosition && IDENT_START.test(c)) {+ let end = i;+ while (end < close && IDENT_PART.test(contents[end] as string)) end++;+ const afterKey = contents[skipTrivia(contents, end)];+ // `key:`, or shorthand terminated by a comma or the closing brace.+ if (afterKey === ":" || afterKey === "," || afterKey === "}") {+ keys.push({ name: contents.slice(i, end), index: i });+ }+ expectKey = false;+ i = end - 1;+ continue;+ }+ expectKey = false;+ }+ return keys;+}++export function noMissingAuditColumn(+ columns: Map<string, Set<string>>+): ConformanceCheck {+ return {+ id: "no-missing-audit-column",+ description:+ "A write never names createdBy/updatedBy on a table that has no such column — PostgREST rejects the statement with PGRST204 and TypeScript does not catch it.",+ provenance: {+ deprecates:+ "stamping createdBy/updatedBy on a table without audit columns (the customerPartToItem upsert in sales-rfq.$rfqId.map-lines.ts, which failed every call)",+ replacedBy:+ "writing only the columns the table has; the MCP/API layer derives the same answer from the generated types in scripts/lib/service-metadata.ts",+ since: "PGRST204 on items_upsertItemCustomerPart"+ },+ scan(file, contents) {+ const violations: Violation[] = [];+ TARGET_RE.lastIndex = 0;+ for (const target of contents.matchAll(TARGET_RE)) {+ const table = target[1];+ const present = table ? columns.get(table) : undefined;+ if (!present) continue;+ const missing: AuditField[] = AUDIT_FIELDS.filter(+ (f) => !present.has(f)+ );+ if (missing.length === 0) continue;++ const open = writeInChain(contents, target.index + target[0].length);+ if (open === null) continue;++ for (const key of rowKeys(contents, open)) {+ if (!missing.includes(key.name as AuditField)) continue;+ violations.push({+ file,+ line: contents.slice(0, key.index).split("\n").length,+ snippet: key.name,+ message: `"${table}" has no "${key.name}" column — this write fails with PGRST204 (and TypeScript will not flag it). Remove the field.`+ });+ }+ }+ return violations;+ }+ };+}diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex 8718e08653..b3d6488c0f 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -19,6 +19,7 @@ export { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits"export { noIntegrationIdBranching } from "./conformance/no-integration-id-branching";export { noLegacyRls } from "./conformance/no-legacy-rls";export { noLocalTimezone } from "./conformance/no-local-timezone";+export { noMissingAuditColumn } from "./conformance/no-missing-audit-column";export { noNumericPrecision } from "./conformance/no-numeric-precision";export { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";export { noRawRounding } from "./conformance/no-raw-rounding";@@ -54,6 +55,7 @@ export {scanModules,TS_CHECKS} from "./run";+export { loadDbTableColumns } from "./sources/db-columns";export { loadEdgeFunctions } from "./sources/edge-functions";export {listLicenseCandidates,diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex 5920cd270b..d8017c2dbf 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -22,6 +22,7 @@ import { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits"import { noIntegrationIdBranching } from "./conformance/no-integration-id-branching";import { noLegacyRls } from "./conformance/no-legacy-rls";import { noLocalTimezone } from "./conformance/no-local-timezone";+import { noMissingAuditColumn } from "./conformance/no-missing-audit-column";import { noNumericPrecision } from "./conformance/no-numeric-precision";import { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";import { noRawRounding } from "./conformance/no-raw-rounding";@@ -32,6 +33,7 @@ import { noUnscopedKyselyWrite } from "./conformance/no-unscoped-kysely-write";import { noViewWithoutInvoker } from "./conformance/no-view-without-invoker";import { noZeroConcurrency } from "./conformance/no-zero-concurrency";import { spdxLicenseHeader } from "./conformance/spdx-license-header";+import { loadDbTableColumns } from "./sources/db-columns";import { loadEdgeFunctions } from "./sources/edge-functions";import { loadLicenseFiles } from "./sources/license-files";import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";@@ -123,7 +125,13 @@ export function collectFindings(root: string = repoRoot()): Finding[] {]),...scanModules(loadModules(modulesDir(root))),...scanAll(loadServerFiles(root), SERVER_CHECKS),- ...scanAll(loadTypescriptFiles(root), TS_CHECKS),+ // noMissingAuditColumn needs the real column list, so it is built from the+ // generated types here rather than sitting in TS_CHECKS — the same shape as+ // noAuthzDdlInMigrations above, which keeps every `scan` pure.+ ...scanAll(loadTypescriptFiles(root), [+ ...TS_CHECKS,+ noMissingAuditColumn(loadDbTableColumns(root))+ ]),...scanAll(loadTypescriptFiles(root, REQUEST_HANDLING_ROOTS), [noRawForwardedHeaders]),diff --git a/packages/checks/src/sources/db-columns.ts b/packages/checks/src/sources/db-columns.tsnew file mode 100644index 0000000000..4bf3a93a65--- /dev/null+++ b/packages/checks/src/sources/db-columns.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { readFileSync } from "node:fs";+import { join } from "node:path";++/**+ * Column names per table, read out of the GENERATED `@carbon/database` types+ * (`packages/database/src/types.ts` `Row:` blocks). That file is regenerated by+ * `pnpm run generate:types` after every migration, so it is the freshest+ * machine-readable schema in the repo — fresher than+ * `packages/jobs/manifests/schema.json`, which only regenerates when the backup+ * check runs.+ *+ * I/O lives here rather than in a check, so `scan` stays pure: the caller loads+ * the map once and closes a check over it (the same shape as+ * `noAuthzDdlInMigrations(loadAuthzHelperNames(root))`).+ */+export function loadDbTableColumns(root: string): Map<string, Set<string>> {+ const contents = readFileSync(+ join(root, "packages/database/src/types.ts"),+ "utf-8"+ );+ const out = new Map<string, Set<string>>();+ // Both `Tables` and `Views` are shaped the same; a view is a legitimate read+ // target and never a write one, so including it costs nothing and keeps the+ // map a plain "what does this relation have" lookup.+ for (const m of contents.matchAll(+ /\n {6}(\w+): \{\n {8}Row: \{\n([\s\S]*?)\n {8}\}\n/g+ )) {+ const [, table, block] = m;+ if (!table || !block) continue;+ const fields = new Set(+ [...block.matchAll(/^ {10}(\w+)\??:/gm)].map((f) => f[1] as string)+ );+ if (fields.size > 0 && !out.has(table)) out.set(table, fields);+ }+ return out;+}diff --git a/packages/checks/turbo.json b/packages/checks/turbo.jsonnew file mode 100644index 0000000000..1a60fbf9e9--- /dev/null+++ b/packages/checks/turbo.json@@ -0,0 +1,9 @@+{+ "$schema": "https://turborepo.org/schema.json",+ "extends": ["//"],+ "tasks": {+ "test": {+ "cache": false+ }+ }+}diff --git a/packages/config/vitest.mts b/packages/config/vitest.mtsindex 4b1075dc92..71126b6ed2 100644--- a/packages/config/vitest.mts+++ b/packages/config/vitest.mts@@ -1,6 +1,10 @@import { defineConfig } from "vitest/config";export default defineConfig({+ // The jSquash wasm codecs are loaded as `?inline` data URIs (see+ // packages/files/src/media/node.ts) — Vite only honours that query for a file+ // it treats as an asset, and `.wasm` is not one by default.+ assetsInclude: ["**/*.wasm"],test: {globals: false,environment: "node",diff --git a/packages/database/supabase/functions/assign-serial-numbers/index.ts b/packages/database/supabase/functions/assign-serial-numbers/index.tsindex 0b2ede0406..dd239ee70c 100644--- a/packages/database/supabase/functions/assign-serial-numbers/index.ts+++ b/packages/database/supabase/functions/assign-serial-numbers/index.ts@@ -145,7 +145,15 @@ serve(async (req: Request) => {.execute();if (count > 1) {- const rows = serials.slice(1).map((readableId) => ({+ // Each row gets its OWN `createdAt`, one millisecond apart, in serial+ // order. Left to the column default they would all take the+ // transaction's `now()` and tie — and `createdAt` is the unit axis+ // every step record is indexed against (see+ // getTrackedEntitiesByMakeMethodId). Tied rows come back in physical+ // order, which an UPDATE changes, so recorded values slid onto other+ // serials. The seed keeps its earlier timestamp and stays unit 0.+ const rows = serials.slice(1).map((readableId, offset) => ({+ createdAt: sql<string>`now() + ${offset + 1}::int * interval '1 millisecond'`,sourceDocument: seed.sourceDocument,sourceDocumentId: seed.sourceDocumentId,sourceDocumentReadableId: seed.sourceDocumentReadableId,diff --git a/packages/database/supabase/functions/batch-operations/index.ts b/packages/database/supabase/functions/batch-operations/index.tsindex 1df30a3405..05a3ab9cb0 100644--- a/packages/database/supabase/functions/batch-operations/index.ts+++ b/packages/database/supabase/functions/batch-operations/index.ts@@ -147,7 +147,10 @@ async function loadMemberOutputs(.where(sql`"attributes"->>'Job Make Method'`, "in", jobMakeMethodIds).where("companyId", "=", companyId).where("status", "not in", ["Consumed", "Scrapped", "Rejected"])+ // Deterministic among tied `createdAt` (bulk-minted serials)..orderBy("createdAt", "asc")+ .orderBy("readableId", "asc")+ .orderBy("id", "asc").execute();const entityByMakeMethod = new Map<string, string>();for (const e of entities) {diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.tsindex b0db3e35ce..5df094cfc4 100644--- a/packages/database/supabase/functions/create/index.ts+++ b/packages/database/supabase/functions/create/index.ts@@ -2966,7 +2966,11 @@ serve(async (req: Request) => {.select("*").eq("companyId", companyId).eq("attributes->>Job Make Method", jobMakeMethod.id)- .order("createdAt", { ascending: true });+ // Unit-axis order, so "Shipment Line Index" follows serial order+ // instead of the physical order of tied `createdAt` rows.+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });let index = 0;for await (const trackedEntity of trackedEntities?.data ??@@ -3272,7 +3276,11 @@ serve(async (req: Request) => {.select("*").eq("companyId", companyId).eq("attributes->>Job Make Method", jobMakeMethod.id)- .order("createdAt", { ascending: true });+ // Unit-axis order, so "Shipment Line Index" follows serial order+ // instead of the physical order of tied `createdAt` rows.+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });let index = 0;for await (const trackedEntity of trackedEntities?.data ??diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex 5dc3a6dd77..4365f6a9b1 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -2230,17 +2230,31 @@ serve(async (req: Request) => {throw new Error("Job operation not found");}+ // UNIT-AXIS order, identical to the apps' getTrackedEntitiesByMakeMethodId:+ // position here is the `index` step records are stored under, so the+ // tiebreakers are not optional — `createdAt` ties for bulk-minted serials+ // and Postgres breaks a tie by physical row order, which any UPDATE moves.const trackedEntities = await client.from("trackedEntity").select("*").eq("attributes->>Job Make Method", jobOperation.data.jobMakeMethodId).eq("companyId", companyId)- .order("createdAt", { ascending: true });+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });if (!trackedEntities.data || trackedEntities.data.length === 0) {throw new Error("Tracked entities not found");}+ // The unit this completion is for, as the 0-based axis index its step+ // records are keyed by. Derived HERE rather than taken from the caller:+ // three routes post this payload and none of them should be trusted, or+ // required, to know the axis.+ const completedUnitIndex = trackedEntities.data.findIndex(+ (entity: { id: string }) => entity.id === trackedEntityId+ );+const relatedTrackedEntities = trackedEntities.data.filter((trackedEntity) =>`Operation ${row.jobOperationId}` in@@ -2313,9 +2327,18 @@ serve(async (req: Request) => {type: "Complete",sourceDocument: "Job Operation",sourceDocumentId: row.jobOperationId,+ // `Job` is what the traceability sidebar loads step records by,+ // and `Unit` is what scopes them to THIS serial. Without `Job`+ // the sidebar showed none; without `Unit` it would show every+ // unit's values under one serial. Same two keys the production+ // event activity already writes (MES startProductionEvent).attributes: {+ Job: jobOperation.data.jobId,"Job Operation": row.jobOperationId,Employee: userId,+ ...(completedUnitIndex >= 0+ ? { Unit: completedUnitIndex }+ : {}),},companyId,createdBy: userId,@@ -4023,7 +4046,10 @@ serve(async (req: Request) => {// run's dead entity can be the oldest match — it must not absorb// this member's consumption..where("status", "not in", ["Consumed", "Scrapped", "Rejected"])+ // Deterministic among tied `createdAt` (bulk-minted serials)..orderBy("createdAt", "asc")+ .orderBy("readableId", "asc")+ .orderBy("id", "asc").executeTakeFirst();if (!parent) {throw new Error(diff --git a/packages/ee/src/mcp/describe-format.ts b/packages/ee/src/mcp/describe-format.tsindex 4fc127f8cb..2cc0ac9b72 100644--- a/packages/ee/src/mcp/describe-format.ts+++ b/packages/ee/src/mcp/describe-format.ts@@ -26,7 +26,7 @@ export function deriveNameDescription(name: string): string {/*** One-line argument summary for search results: required params spelled out,* optionals as a count — enough to call a simple tool without a describe round- * trip. "(id)" / "(jobId, _operation, +12 optional)" / "()".+ * trip. "(id)" / "(jobId, itemId, +12 optional)" / "()".*/export function formatParamSummary(tool: ManifestEntry): string {const schema = tool.schema as {diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex 587ec89d0c..a6e2e43cfb 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -9,7 +9,7 @@ in the codebase, shared by the browser, Node, and the Supabase edge runtime.| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id) with the legacy shared `private` bucket folded in — reads (`download` / `info` / `createSignedUrl`) fall back to it, `list` unions both, `remove` deletes from both, writes (`upload` / `move` / `copy` / `createSignedUploadUrl`) go to the company bucket only. Every key must sit under `${companyId}/` (under a service-role client that prefix is the ONLY tenant boundary on the shared legacy bucket) and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. All legacy-bucket fallback lives in `storage.ts` so removing it later is a one-file change; `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) || `./csv` | `encodeCsv` (object rows) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection || `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` |-| `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). Touches `node:fs`: never import from client code |+| `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). The wasm comes from the BUNDLER (`?inline` data URIs), never off disk — so this module is consumable only from a Vite pipeline, and that pipeline needs `assetsInclude: ["**/*.wasm"]` (already set in `apps/erp/vite.config.ts` and `@carbon/config/vitest`). Never import from client code || `./cad` | CAD/model formats: `supportedModelTypes`, `optimizableModelFormat`, `modelPathOptimizeFormat`, `isModelRawDownloadable` || `./pdf` | PDF *reading* on [unpdf](https://github.com/unjs/unpdf): `extractPdfText` (`--- Page N ---` joined, what the AI extraction prompts consume), `extractPdfPages`, `getPdfPageCount`, `getPdfMeta`, and `openPdf`/`closePdf` for page-level work (the inspection overlay export and anchor crop drive pages themselves; `closePdf` destroys the loading task — `cleanup()` alone leaks the document transport). Generation stays in `@carbon/documents` — this is file handling, not templating || `./pdf/worker` | `registerReactPdfWorker(pdfjs)` — browser-only, synchronous; both app `entry.client.tsx` files call it once. Nothing else may set `GlobalWorkerOptions.workerSrc` |@@ -27,6 +27,15 @@ jSquash resize. No ImageMagick anywhere. Node cannot load wasm over `fetch(file:hence `./media/node`. Bare specifiers resolve via `package.json` in Node/browser andvia `functions/deno.json` `imports` in Deno — add BOTH when adding a codec.+**Never resolve a codec's `.wasm` from disk.** `./media/node` used+`createRequire(import.meta.url).resolve(...)`, which works only while the file sits+at its real path next to `packages/files/node_modules`; every server build inlines+`@carbon/files`, which moves the anchor into the output directory and loses both the+package and the asset — that is why every deployed paperless thumbnail failed with+`MODULE_NOT_FOUND` on Vercel AND on the ECS image, while dev and vitest passed. A new+codec's wasm is a `?inline` import (a `?url` one is a CLIENT public path and is not+emitted into the server build at all).+Shape modes (`ImageShapeOptions`): default = center-crop 300×300 (avatars),`contained` = fit + 10% pad to 300×300 (item thumbnails), `height: n` = proportional(logos, 128/512), `convert` = format normalization only (attachments). JPEG/HEIC/AVIFdiff --git a/packages/files/src/media/image-pipeline.test.ts b/packages/files/src/media/image-pipeline.test.tsindex 0217cffa3d..ceec776816 100644--- a/packages/files/src/media/image-pipeline.test.ts+++ b/packages/files/src/media/image-pipeline.test.ts@@ -95,13 +95,15 @@ describe("image pipeline", () => {// webp encode is test-only (nothing in prod encodes webp), so its wasm// init lives here rather than in initNodeImageCodecs- const webpEncode = await import("@jsquash/webp/encode.js");- const { createRequire } = await import("node:module");- const require = createRequire(import.meta.url);+ const [webpEncode, webpEncWasm] = await Promise.all([+ import("@jsquash/webp/encode.js"),+ import("@jsquash/webp/codec/enc/webp_enc_simd.wasm?inline")+ ]);await webpEncode.init(await WebAssembly.compile(- await readFile(- require.resolve("@jsquash/webp/codec/enc/webp_enc_simd.wasm")+ Buffer.from(+ webpEncWasm.default.slice(webpEncWasm.default.indexOf(",") + 1),+ "base64")));diff --git a/packages/files/src/media/node.ts b/packages/files/src/media/node.tsindex 5c29172e71..7a94f8e36e 100644--- a/packages/files/src/media/node.ts+++ b/packages/files/src/media/node.ts@@ -2,43 +2,73 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-// Node-only: pre-instantiate the jSquash wasm codecs from disk. Their default-// loaders fetch the .wasm relative to import.meta.url, which Node's fetch-// refuses for file: URLs — so server-side consumers of the image pipeline-// (paperless-parts, jobs, vitest) call this once first. Browser and Deno load-// the same wasm automatically; libheif needs nothing anywhere (its wasm is-// embedded in the JS bundle). Import via "@carbon/files/media/node" only from-// server code — this module touches node:fs.-import { readFile } from "node:fs/promises";-import { createRequire } from "node:module";+/// <reference path="../vite-env.d.ts" />+// The reference is load-bearing, not decoration: `@carbon/files` exports SOURCE+// (`./src/*.ts`), so a consumer typechecks this very file inside its own program+// — where `packages/files/tsconfig.json`'s `include` does not reach and the+// `*.wasm?inline` declaration would be invisible. @carbon/ee and @carbon/jobs+// both failed that way. Same fix as packages/viewer/src/raw/rawWorker.ts.+// Node-only: pre-instantiate the jSquash wasm codecs. Their default loaders+// fetch the .wasm relative to import.meta.url, which Node's fetch refuses for+// file: URLs — so server-side consumers of the image pipeline (paperless-parts,+// jobs, vitest) call this once first. Browser and Deno load the same wasm+// automatically; libheif needs nothing anywhere (its wasm is embedded in the JS+// bundle).+//+// The bytes come from the BUNDLER (`?inline` → a base64 data URI), never from+// disk. Resolving them at runtime — `createRequire(import.meta.url).resolve()` —+// works only while this file sits at its real path next to+// packages/files/node_modules; once a server build inlines @carbon/files the+// anchor moves into the output directory and both the package and the .wasm+// disappear, which is how every deployed paperless thumbnail failed with+// MODULE_NOT_FOUND. `?inline` is a Vite query, so this module is consumable only+// from a Vite pipeline (the ERP/MES server builds and vitest — the Deno+// functions never import it).let initialized: Promise<void> | null = null;+const compile = (mod: { default: string }) =>+ WebAssembly.compile(+ Buffer.from(mod.default.slice(mod.default.indexOf(",") + 1), "base64")+ );+export function initNodeImageCodecs(): Promise<void> {initialized ??= (async () => {- const require = createRequire(import.meta.url);- const wasm = async (specifier: string) =>- WebAssembly.compile(await readFile(require.resolve(specifier)));-- const [jpegDecode, jpegEncode, pngDecode, pngEncode, webpDecode, resize] =- await Promise.all([- import("@jsquash/jpeg/decode.js"),- import("@jsquash/jpeg/encode.js"),- import("@jsquash/png/decode.js"),- import("@jsquash/png/encode.js"),- import("@jsquash/webp/decode.js"),- import("@jsquash/resize")- ]);+ const [+ jpegDecode,+ jpegEncode,+ pngDecode,+ pngEncode,+ webpDecode,+ resize,+ jpegDecWasm,+ jpegEncWasm,+ pngWasm,+ webpDecWasm,+ resizeWasm+ ] = await Promise.all([+ import("@jsquash/jpeg/decode.js"),+ import("@jsquash/jpeg/encode.js"),+ import("@jsquash/png/decode.js"),+ import("@jsquash/png/encode.js"),+ import("@jsquash/webp/decode.js"),+ import("@jsquash/resize"),+ import("@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm?inline"),+ import("@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm?inline"),+ import("@jsquash/png/codec/pkg/squoosh_png_bg.wasm?inline"),+ import("@jsquash/webp/codec/dec/webp_dec.wasm?inline"),+ import("@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm?inline")+ ]);+ // png decode and encode share one wasm, but each module keeps its own+ // instance — compile twice rather than hand the same Module to both.await Promise.all([- jpegDecode.init(await wasm("@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm")),- jpegEncode.init(await wasm("@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm")),- pngDecode.init(await wasm("@jsquash/png/codec/pkg/squoosh_png_bg.wasm")),- pngEncode.init(await wasm("@jsquash/png/codec/pkg/squoosh_png_bg.wasm")),- webpDecode.init(await wasm("@jsquash/webp/codec/dec/webp_dec.wasm")),- resize.initResize(- await wasm("@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm")- )+ jpegDecode.init(await compile(jpegDecWasm)),+ jpegEncode.init(await compile(jpegEncWasm)),+ pngDecode.init(await compile(pngWasm)),+ pngEncode.init(await compile(pngWasm)),+ webpDecode.init(await compile(webpDecWasm)),+ resize.initResize(await compile(resizeWasm))]);})();return initialized;diff --git a/packages/files/src/vite-env.d.ts b/packages/files/src/vite-env.d.tsnew file mode 100644index 0000000000..6881ef3c5b--- /dev/null+++ b/packages/files/src/vite-env.d.ts@@ -0,0 +1,11 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// This package ships raw source compiled by the consuming app's Vite build.+// Type the Vite asset queries the source references without depending on vite+// (typecheck runs standalone via tsgo).+declare module "*.wasm?inline" {+ const dataUri: string;+ export default dataUri;+}diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.tsindex 96adf3eaa8..7848465124 100644--- a/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts+++ b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts@@ -166,7 +166,11 @@ async function queryTrackedEntities(.select("*").eq("attributes->>Job Make Method", jobOperation?.jobMakeMethodId).eq("companyId", companyId)- .order("createdAt", { ascending: true });+ // Unit-axis order (see MES getTrackedEntitiesByMakeMethodId), so+ // labels print in serial order even for serials minted together.+ .order("createdAt", { ascending: true })+ .order("readableId", { ascending: true })+ .order("id", { ascending: true });return {trackedEntities,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5d0fb635b1..769e346031 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -476,8 +476,8 @@ importers:specifier: 'catalog:'version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)ts-morph:- specifier: 22.0.0- version: 22.0.0+ specifier: 28.0.0+ version: 28.0.0tsx:specifier: 'catalog:'version: 4.21.0@@ -10018,8 +10018,8 @@ packages:'@ts-morph/[email protected]':resolution: {integrity: sha512-7hWZS0NRpEsNV8vWJzg7FEz6V8MaLNeJOmwmghqUXTpzk16V1LLZhdo+4QvE/+zv4cVci0OviuJFnqhEfoV3+g==}- '@ts-morph/[email protected]':- resolution: {integrity: sha512-m7Lllj9n/S6sOkCkRftpM7L24uvmfXQFedlW/4hENcuJH1HHm9u5EgxZb9uVjQSCGrbBWBkOGgcTxNg36r6ywA==}+ '@ts-morph/[email protected]':+ resolution: {integrity: sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg==}'@turbo/[email protected]':resolution: {integrity: sha512-X/56SnVXIQZBLKwniGTwEQTGmtE5brSACnKMBWpY3YafuxVYefrC2acamfjgxP7BG5w3I+6jf0UrLoSzgPcSJg==}@@ -16188,8 +16188,8 @@ packages:resolution: {integrity: sha512-VHC8XgU2fFW7yO1f/b3mxKDje1vmyzFXHWzOYmKEkCEwcLjDtbdLgBQviqj4ZwP4MJkQtRo6Ha2I29lq/B+VxA==}- resolution: {integrity: sha512-M9MqFGZREyeb5fTl6gNHKZLqBQA0TjA1lea+CR48R8EBTDuWrNqW6ccC5QvjNR4s6wDumD3LTCjOFSp9iwlzaw==}+ resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==}resolution: {integrity: sha512-FZIXf1ksVyLcfr7M317jbB67XFJhOO1YqdTcuGaq9q5jLUoTikukZ+98TPjKiP2jC5CgmYdWWYs0s2nLSU0/1A==}@@ -24220,12 +24220,11 @@ snapshots:mkdirp: 1.0.4path-browserify: 1.0.1- '@ts-morph/[email protected]':+ '@ts-morph/[email protected]':dependencies:- fast-glob: 3.3.3- minimatch: 9.0.9- mkdirp: 3.0.1+ minimatch: 10.2.5path-browserify: 1.0.1+ tinyglobby: 0.2.17'@turbo/[email protected]':optional: true@@ -31494,9 +31493,9 @@ snapshots:'@ts-morph/common': 0.11.1code-block-writer: 10.1.1dependencies:- '@ts-morph/common': 0.23.0+ '@ts-morph/common': 0.29.0code-block-writer: 13.0.3diff --git a/scripts/check-manifest.ts b/scripts/check-manifest.tsindex f32d58d2fd..483fb89347 100644--- a/scripts/check-manifest.ts+++ b/scripts/check-manifest.ts@@ -54,13 +54,17 @@ async function main(): Promise<void> {console.log(`check-manifest: ok — ${fresh.totalTools} operations across ${fresh.modules} modules, digest current.`);- // A validator that silently fell back to source-text parsing publishes a lossy- // schema. The digest can be perfectly current and still be built that way, so- // report it separately rather than folding it into the pass/fail.+ // A module that will not load no longer degrades to source-text parsing — the+ // schemas it should have contributed are simply absent, so the digest being+ // current says nothing about whether it is complete.if (registryStats.moduleErrors.length > 0) {- console.warn(- ` ⚠ ${registryStats.moduleErrors.length} module(s) failed to load; their schemas came from the textual fallback.`+ console.error(+ ` ✗ ${registryStats.moduleErrors.length} module(s) failed to load, so their schemas are missing:`);+ for (const e of registryStats.moduleErrors) {+ console.error(` ${e.module}: ${e.error}`);+ }+ process.exit(1);}return;}diff --git a/scripts/generate-mcp.ts b/scripts/generate-mcp.tsindex 665e49145a..78248de5a2 100644--- a/scripts/generate-mcp.ts+++ b/scripts/generate-mcp.ts@@ -40,11 +40,55 @@ export const DIGEST_FILE = path.join(export async function generateToolMetadata(): Promise<void> {console.log("Generating tool metadata from service files...");+ const auditDrops: { toolName: string; table: string; dropped: string[] }[] =+ [];+ const untagged: string[] = [];+ const skippedModules: { module: string; functionCount: number }[] = [];+const { tools: allTools, registryStats, responseStats, resolutions } =await buildAllToolMetadataWithValidators({onModule: (mod, count) => console.log(` ✓ ${mod}: ${count} tools`),+ onAuditColumnsDropped: (toolName, table, dropped) =>+ auditDrops.push({ toolName, table, dropped }),+ onUntagged: (toolName) => untagged.push(toolName),+ onModuleSkipped: (module, functionCount) =>+ skippedModules.push({ module, functionCount }),});+ // Refuse BEFORE writing. Every `z.infer` param must resolve NATIVELY — the+ // real validator, converted by zod itself. There is no longer a source-text+ // fallback to absorb a module that will not load: it published a lossy+ // contract, and measured over the real tree it never once fired. A manifest+ // with `{}` where a real schema belongs invites an MCP client to guess field+ // names, and a guessed field reaches the insert and fails with PGRST204 — so+ // leaving the previous good manifest in place beats overwriting it with one+ // nobody can trust.+ const unresolved = resolutions.filter((r) => r.how !== "native");+ const failures: string[] = [];+ if (registryStats.moduleErrors.length > 0) {+ console.error(+ `\n ✗ ${registryStats.moduleErrors.length} module(s) failed to load:`+ );+ for (const e of registryStats.moduleErrors) {+ console.error(` ${e.module}: ${e.error}`);+ }+ failures.push(+ `${registryStats.moduleErrors.length} module(s) failed to load`+ );+ }+ if (unresolved.length > 0) {+ const unique = [...new Set(unresolved.map((f) => f.validatorName))];+ console.error(+ `\n ✗ ${unresolved.length} param(s) could not resolve their validator: ${unique.slice(0, 12).join(", ")}`+ );+ failures.push(`${unresolved.length} param(s) have no validator schema`);+ }+ if (failures.length > 0) {+ throw new Error(+ `generate:mcp refused to publish a lossy manifest — ${failures.join("; ")}. Nothing was written.`+ );+ }+// No timestamp: the file must be a pure function of the sources so repeated// runs on an unchanged tree are byte-identical.const metadata = {@@ -64,22 +108,40 @@ export async function generateToolMetadata(): Promise<void> {console.log(` Output: ${path.relative(ROOT, METADATA_FILE)} (gitignored)`);console.log(` Digest: ${path.relative(ROOT, DIGEST_FILE)} (committed)`);- // Schema provenance. A validator that fell back to source-text parsing still- // produces a manifest entry, so surface it rather than letting the degrade pass- // silently — that fallback is the only path that can publish a lossy schema.- const fallbacks = resolutions.filter((r) => r.how !== "native");+ // Exposure. A function reaches the API because its doc comment declares+ // `@mcp <verb>`, not because it is exported — see mcp-exposure.ts.+ if (skippedModules.length > 0) {+ console.log(+ `\n Modules not on MCP_MODULE_ALLOWLIST: ${skippedModules.map((m) => `${m.module} (${m.functionCount} fns)`).join(", ")}`+ );+ }+ if (untagged.length > 0) {+ console.log(+ `\n Exported but not exposed (no @mcp tag): ${untagged.length}`+ );+ }++ // Audit-column provenance. A `create`/`update`/`upsert` tool is handed+ // createdBy/updatedBy, and dispatch stamps them onto the payload OBJECT — so a+ // service that spreads its argument into the write would send a column the+ // table does not have (PGRST204). Each drop below is the verb's set being+ // corrected against the generated types; a drop that looks wrong means the+ // table really does have the column, or the tool needs an `@mcp audit` line.+ if (auditDrops.length > 0) {+ console.log(+ `\n Audit columns dropped (absent from the tool's table): ${auditDrops.length}`+ );+ for (const d of auditDrops) {+ console.log(` ${d.toolName} → ${d.table}: ${d.dropped.join(", ")}`);+ }+ }+console.log(` Schemas: ${registryStats.validatorsConverted} validators converted from ${registryStats.modulesLoaded}/${MODULE_LIST.length} modules`);console.log(` Responses: ${responseStats.derived}/${responseStats.functions} reflected from return types (${responseStats.empty} yielded nothing usable)`);- if (registryStats.moduleErrors.length > 0) {- console.warn(` ⚠ ${registryStats.moduleErrors.length} module(s) failed to load:`);- for (const e of registryStats.moduleErrors) {- console.warn(` ${e.module}: ${e.error}`);- }- }if (registryStats.conversionFailures.length > 0) {console.warn(` ⚠ ${registryStats.conversionFailures.length} validator(s) failed to convert:`@@ -88,12 +150,6 @@ export async function generateToolMetadata(): Promise<void> {console.warn(` ${f.module}.${f.name}: ${f.error}`);}}- if (fallbacks.length > 0) {- const unique = [...new Set(fallbacks.map((f) => f.validatorName))];- console.warn(- ` ⚠ ${fallbacks.length} param(s) used the source-text fallback: ${unique.slice(0, 12).join(", ")}`- );- }}if (require.main === module) {diff --git a/scripts/lib/manifest-digest.ts b/scripts/lib/manifest-digest.tsindex 91d81f628d..4fd40caf7f 100644--- a/scripts/lib/manifest-digest.ts+++ b/scripts/lib/manifest-digest.ts@@ -35,6 +35,9 @@ export interface DigestEntry {permission: string;/** Whether the service pages itself — decides who applies limit/offset. */paginates: boolean;+ /** How create is told from update: the key fields, or `table(columns)` for+ * each row the dispatcher looks up. Absent when the service does not branch. */+ upsert?: string;}export interface ManifestDigest {@@ -85,6 +88,20 @@ export function serializeManifestDigest(digest: ManifestDigest): string {].join("\n");}+function describeUpsert(upsert: NonNullable<ManifestEntry["upsert"]>): string {+ if (!upsert.lookups) return upsert.keys.join(",");+ return upsert.lookups+ .map(+ (lookup) =>+ `${lookup.table}(${Object.entries(lookup.match)+ .map(([column, field]) =>+ column === field ? column : `${column}=${field}`+ )+ .join(",")})`+ )+ .join("|");+}+export function buildManifestDigest(tools: ManifestEntry[]): ManifestDigest {return {totalTools: tools.length,@@ -103,7 +120,8 @@ export function buildManifestDigest(tools: ManifestEntry[]): ManifestDigest {permission: t.permission?.module? `${t.permission.module}:${[...t.permission.actions].sort().join("+")}`: "none",- paginates: t.paginates+ paginates: t.paginates,+ ...(t.upsert ? { upsert: describeUpsert(t.upsert) } : {})}))};}@@ -159,6 +177,9 @@ export function formatDigestDiff(diff: DigestDiff): string {if (before.paginates !== after.paginates) {parts.push(`paginates ${before.paginates} → ${after.paginates}`);}+ if (before.upsert !== after.upsert) {+ parts.push(`upsert ${before.upsert ?? "none"} → ${after.upsert ?? "none"}`);+ }if (before.schema !== after.schema) parts.push("input schema changed");if (before.response !== after.response) {if (before.response === "none") parts.push("response added");diff --git a/scripts/lib/response-schema.ts b/scripts/lib/response-schema.tsindex 76f9824a60..1b35596467 100644--- a/scripts/lib/response-schema.ts+++ b/scripts/lib/response-schema.ts@@ -16,16 +16,11 @@* schema, ~10s to walk. The manifest grows 1.3 -> 1.6 MB, and it is gitignored.*/-import * as fs from "fs";-import * as path from "path";-import { Node, Project, type Type } from "ts-morph";+import { Node, type Type } from "ts-morph";+import type { ServiceAst } from "./service-ast";export type JsonSchema = Record<string, unknown>;-const ROOT = path.resolve(__dirname, "../..");-const ERP_ROOT = path.join(ROOT, "apps/erp");-const MODULES_DIR = path.join(ERP_ROOT, "app/modules");-/*** Rows are wide (40+ columns) and embeds nest, so an uncapped walk can emit a* megabyte for one operation. Depth 6 covers the deepest real select — a row, an@@ -140,7 +135,17 @@ export function typeToJsonSchema(return { type: "object" };}- const key = type.getText();+ // The checker's own type id, NOT `type.getText()`. getText() serializes the+ // whole structural type to a string, and a supabase row with embeds+ // serializes to a very large one — paying that at every object node was+ // measured at 5.2s of a 5.2s walk, i.e. effectively the entire cost of+ // walking 1574 return types. The id is O(1), it is only ever a Map key here+ // (never emitted — that is the `__@toStringTag@75448` trap noted above), and+ // it is per-program so it stays valid for the one walk that uses it.+ // Verified byte-identical over all 1574 functions.+ const key = String(+ (type.compilerType as unknown as { id?: number }).id ?? type.getText()+ );// Cycle: the type is already being expanded further up this branch.if (seen.has(key)) return { type: "object" };@@ -265,36 +270,26 @@ function isUseful(schema: JsonSchema): boolean {}/**- * Reflect every module's service functions once. Loading the TS project is the- * expensive part (~4s), so it happens here and the result is a plain lookup the- * synchronous manifest builder can consult.+ * Reflect the return type of every published service function. Takes the AST+ * `buildServiceAst` already parsed, so the manifest builder and this index share+ * ONE ts-morph project — the type checker is the expensive part of generation,+ * and two projects paid for it twice.*/-export function buildResponseSchemaIndex(- modules: readonly string[]-): ResponseSchemaIndex {- const project = new Project({- tsConfigFilePath: path.join(ERP_ROOT, "tsconfig.json"),- skipAddingFilesFromTsConfig: true- });-- const sources = modules.flatMap((mod) =>- [`${mod}.service.ts`, `${mod}.ee.service.ts`, `${mod}.mcp.server.ts`]- .map((name) => ({ mod, file: path.join(MODULES_DIR, mod, name) }))- .filter((entry) => fs.existsSync(entry.file))- .map((entry) => ({ mod: entry.mod, source: project.addSourceFileAtPath(entry.file) }))- );- project.resolveSourceFileDependencies();+export function buildResponseSchemaIndex(ast: ServiceAst): ResponseSchemaIndex {+ ast.project.resolveSourceFileDependencies();const schemas = new Map<string, JsonSchema>();const stats = { functions: 0, derived: 0, empty: 0 };- for (const { mod, source } of sources) {- for (const fn of source.getFunctions()) {- if (!fn.isExported()) continue;+ for (const mod of ast.modules.values()) {+ for (const fn of mod.functions) {stats.functions++;let schema: JsonSchema;try {- schema = typeToJsonSchema(unwrapResponseType(fn.getReturnType(), fn), fn);+ schema = typeToJsonSchema(+ unwrapResponseType(fn.node.getReturnType(), fn.node),+ fn.node+ );} catch {stats.empty++;continue;@@ -303,7 +298,7 @@ export function buildResponseSchemaIndex(stats.empty++;continue;}- schemas.set(`${mod}_${fn.getName()}`, schema);+ schemas.set(fn.toolName, schema);stats.derived++;}}diff --git a/scripts/lib/service-ast.ts b/scripts/lib/service-ast.tsnew file mode 100644index 0000000000..3f2157850d--- /dev/null+++ b/scripts/lib/service-ast.ts@@ -0,0 +1,558 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * The service files as an AST: which functions a module publishes, what their+ * parameters and doc tags are, and what their bodies do to the database.+ *+ * Everything here used to be read off the files' TEXT, and each text reader had+ * its own way of being wrong:+ *+ * - Functions were found with `/export\s+(async\s+)?function\s+(\w+)\s*\(/`, so an+ * exported ARROW function was invisible (`production.getPartDocuments`).+ * - A function's body ran "from its name to the next `\nexport `", so a+ * non-exported helper defined below it was read as part of it, and a+ * `mcp.server.ts` wrapper was scanned as the service function it shadows.+ * - "Does it delete" was `/\.delete\s*\(/`, which a `Set#delete` satisfies+ * (`production.reassignAssemblyStepComponents` calls `members.delete(…)`).+ * - Doc tags were regexes over the comment's lines, and the script that wrote+ * them mis-spliced single-line blocks three separate ways.+ *+ * One ts-morph `Project` is built here and shared with `response-schema.ts`,+ * which reflects return types over the same files.+ */+import * as fs from "fs";+import * as path from "path";+import {+ type ArrowFunction,+ type CallExpression,+ type FunctionDeclaration,+ type FunctionExpression,+ type JSDoc,+ Node,+ type ParameterDeclaration,+ Project,+ type SourceFile,+ SymbolFlags,+ SyntaxKind+} from "ts-morph";++const ROOT = path.resolve(__dirname, "../..");+const ERP_ROOT = path.join(ROOT, "apps/erp");+const MODULES_DIR = path.join(ERP_ROOT, "app/modules");++export type ServiceFunctionNode =+ | FunctionDeclaration+ | ArrowFunction+ | FunctionExpression;++export interface ServiceParam {+ name: string;+ /** The declared type's source text, comments removed. */+ typeStr: string;+ optional: boolean;+ description?: string;+ /** `...rest` — a variadic tail has no JSON-object representation. */+ rest: boolean;+}++export interface ServiceTag {+ /** Tag name without the `@`. */+ name: string;+ comment: string;+}++export interface ServiceFunction {+ module: string;+ name: string;+ /** `{module}_{name}` — the published operation name. */+ toolName: string;+ node: ServiceFunctionNode;+ params: ServiceParam[];+ /** Raw body of the JSDoc block attached to the declaration, if any. */+ jsdoc?: string;+ tags: ServiceTag[];+}++export interface ServiceModule {+ /** Published functions in source order; a companion's shadow replaces in place. */+ functions: ServiceFunction[];+ /** Source text of the module's service file(s), for alias lookups by text. */+ text: string;+}++export interface ServiceAst {+ readonly project: Project;+ readonly modules: ReadonlyMap<string, ServiceModule>;+}++// ---------------------------------------------------------------------------+// Discovery+// ---------------------------------------------------------------------------++/** Source text of `node` with every comment inside it removed. */+function textWithoutComments(node: Node): string {+ const start = node.getStart();+ const text = node.getText();+ const cuts: [number, number][] = [];+ const collect = (n: Node) => {+ for (const range of [+ ...n.getLeadingCommentRanges(),+ ...n.getTrailingCommentRanges()+ ]) {+ const from = range.getPos() - start;+ const to = range.getEnd() - start;+ if (from >= 0 && to <= text.length) cuts.push([from, to]);+ }+ };+ collect(node);+ // getDescendants() includes TOKENS; a comment before a closing brace is the+ // leading trivia of that token and of no node.+ for (const descendant of node.getDescendants()) collect(descendant);+ if (cuts.length === 0) return text;++ cuts.sort((a, b) => a[0] - b[0]);+ let out = "";+ let cursor = 0;+ for (const [from, to] of cuts) {+ if (from < cursor) continue;+ out += text.slice(cursor, from);+ cursor = to;+ }+ return out + text.slice(cursor);+}++/** The body of a `/** … *\/` block as prose: leading `*` gutters dropped. */+function docCommentProse(body: string): string | undefined {+ return (+ body+ .split("\n")+ .map((line) => line.replace(/^\s*\*?\s?/, "").trim())+ .join(" ")+ .trim() || undefined+ );+}++function typeOfDefault(initializer: Node): string {+ if (+ Node.isTrueLiteral(initializer) ||+ Node.isFalseLiteral(initializer)+ ) {+ return "boolean";+ }+ if (Node.isNumericLiteral(initializer)) return "number";+ if (+ Node.isPrefixUnaryExpression(initializer) &&+ Node.isNumericLiteral(initializer.getOperand())+ ) {+ return "number";+ }+ if (+ Node.isStringLiteral(initializer) ||+ Node.isNoSubstitutionTemplateLiteral(initializer) ||+ Node.isTemplateExpression(initializer)+ ) {+ return "string";+ }+ return "unknown";+}++function readParam(+ param: ParameterDeclaration,+ existing: ServiceParam[]+): ServiceParam {+ const nameNode = param.getNameNode();+ // A destructuring pattern is not a name. Its source text put braces and+ // newlines into the manifest, so reformatting a signature churned the digest;+ // the synthetic name only has to avoid CONTEXT_PARAMS and the dispatcher's+ // `args` branch — nothing else reads a param name for meaning.+ let name = nameNode.getText();+ if (+ Node.isObjectBindingPattern(nameNode) ||+ Node.isArrayBindingPattern(nameNode)+ ) {+ name = "destructured";+ for (let i = 2; existing.some((p) => p.name === name); i++) {+ name = `destructured${i}`;+ }+ }++ const typeNode = param.getTypeNode();+ const initializer = param.getInitializer();+ const leadingDoc = param+ .getLeadingCommentRanges()+ .map((range) => range.getText())+ .filter((text) => text.startsWith("/**"))+ .pop();++ return {+ name,+ typeStr: typeNode+ ? textWithoutComments(typeNode).trim()+ : initializer+ ? typeOfDefault(initializer)+ : "unknown",+ optional: param.hasQuestionToken() || initializer !== undefined,+ description: leadingDoc+ ? docCommentProse(leadingDoc.slice(3, -2))+ : undefined,+ rest: param.isRestParameter()+ };+}++function readTags(doc: JSDoc): ServiceTag[] {+ return doc.getTags().map((tag) => ({+ name: tag.getTagName(),+ comment: (tag.getCommentText() ?? "").trim()+ }));+}++function toServiceFunction(+ module: string,+ name: string,+ node: ServiceFunctionNode,+ docs: JSDoc[]+): ServiceFunction {+ const params: ServiceParam[] = [];+ for (const param of node.getParameters()) {+ params.push(readParam(param, params));+ }+ // The block closest to the declaration is its doc — description AND tags.+ // An earlier block is a stray comment that happens to sit above it.+ const doc = docs[docs.length - 1];+ return {+ module,+ name,+ toolName: `${module}_${name}`,+ node,+ params,+ jsdoc: doc ? doc.getText().slice(3, -2) : undefined,+ tags: doc ? readTags(doc) : []+ };+}++/** Every exported function of a file — declarations AND arrow/function consts. */+export function exportedFunctions(+ module: string,+ source: SourceFile+): ServiceFunction[] {+ const found: { pos: number; fn: ServiceFunction }[] = [];++ for (const fn of source.getFunctions()) {+ const name = fn.getName();+ if (!name || !fn.isExported() || !fn.hasBody()) continue;+ found.push({+ pos: fn.getStart(),+ fn: toServiceFunction(module, name, fn, fn.getJsDocs())+ });+ }++ for (const statement of source.getVariableStatements()) {+ if (!statement.isExported()) continue;+ for (const declaration of statement.getDeclarations()) {+ const initializer = declaration.getInitializer();+ if (+ !initializer ||+ !(+ Node.isArrowFunction(initializer) ||+ Node.isFunctionExpression(initializer)+ )+ ) {+ continue;+ }+ found.push({+ pos: declaration.getStart(),+ fn: toServiceFunction(+ module,+ declaration.getName(),+ initializer,+ statement.getJsDocs()+ )+ });+ }+ }++ return found.sort((a, b) => a.pos - b.pos).map((entry) => entry.fn);+}++/** The exported functions of service source held in memory — no files, no+ * tsconfig. What the tests feed the generator's questions with. */+export function parseServiceSource(+ module: string,+ source: string+): ServiceFunction[] {+ const project = new Project({ useInMemoryFileSystem: true });+ return exportedFunctions(+ module,+ project.createSourceFile(`${module}.service.ts`, source)+ );+}++/**+ * Parse every module's service file — plus its `mcp.server.ts` companion, for+ * the tools that must import `*.server` modules and so cannot live in the+ * client-reachable service file. A same-named companion export SHADOWS the+ * service one, matching the runtime registry where the companion's spread wins,+ * and here the shadow is total: the wrapper's own parameters, doc and BODY are+ * what get published and inspected.+ */+export function buildServiceAst(modules: readonly string[]): ServiceAst {+ const project = new Project({+ tsConfigFilePath: path.join(ERP_ROOT, "tsconfig.json"),+ skipAddingFilesFromTsConfig: true+ });+ const out = new Map<string, ServiceModule>();++ for (const mod of modules) {+ // A module may keep its single service file under the `.ee`-licensed name.+ const servicePath = [`${mod}.service.ts`, `${mod}.ee.service.ts`]+ .map((file) => path.join(MODULES_DIR, mod, file))+ .find((file) => fs.existsSync(file));+ if (!servicePath) continue;++ const service = project.addSourceFileAtPath(servicePath);+ let functions = exportedFunctions(mod, service);+ let text = service.getFullText();++ const companionPath = path.join(MODULES_DIR, mod, `${mod}.mcp.server.ts`);+ if (fs.existsSync(companionPath)) {+ const companion = project.addSourceFileAtPath(companionPath);+ const companionFunctions = exportedFunctions(mod, companion);+ const shadowed = new Set(companionFunctions.map((fn) => fn.name));+ functions = [+ ...functions.filter((fn) => !shadowed.has(fn.name)),+ ...companionFunctions+ ];+ text = `${text}\n${companion.getFullText()}`;+ }++ out.set(mod, { functions, text });+ }++ return { project, modules: out };+}++// ---------------------------------------------------------------------------+// What a body does+// ---------------------------------------------------------------------------++export type DbWriteKind = "insert" | "update" | "delete";++// Maps, not object literals: a member named `toString` or `constructor` would+// otherwise find Object.prototype's and read as a write.+const SUPABASE_WRITES = new Map<string, DbWriteKind>([+ ["insert", "insert"],+ ["upsert", "insert"],+ ["update", "update"],+ ["delete", "delete"]+]);+const KYSELY_WRITES = new Map<string, DbWriteKind>([+ ["insertInto", "insert"],+ ["updateTable", "update"],+ ["deleteFrom", "delete"]+]);++/** Peel wrappers that do not change what an expression evaluates to. */+function unwrap(node: Node | undefined): Node | undefined {+ let current = node;+ while (current) {+ if (+ Node.isParenthesizedExpression(current) ||+ Node.isAsExpression(current) ||+ Node.isNonNullExpression(current) ||+ Node.isAwaitExpression(current) ||+ Node.isSatisfiesExpression(current) ||+ Node.isTypeAssertion(current)+ ) {+ current = current.getExpression();+ continue;+ }+ return current;+ }+ return undefined;+}++function memberName(call: CallExpression): string | undefined {+ const callee = unwrap(call.getExpression());+ if (callee && Node.isPropertyAccessExpression(callee)) {+ return callee.getName();+ }+ if (callee && Node.isIdentifier(callee)) return callee.getText();+ return undefined;+}++function stringArgument(call: CallExpression): string | undefined {+ const arg = call.getArguments()[0];+ if (+ arg &&+ (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg))+ ) {+ return arg.getLiteralText();+ }+ return undefined;+}++/** `x.storage.from("bucket")` names a storage bucket, not a relation. */+function isStorageFrom(call: CallExpression): boolean {+ const callee = unwrap(call.getExpression());+ if (!callee || !Node.isPropertyAccessExpression(callee)) return false;+ const receiver = unwrap(callee.getExpression());+ return (+ receiver !== undefined &&+ Node.isPropertyAccessExpression(receiver) &&+ receiver.getName() === "storage"+ );+}++/**+ * The `.from(…)` call a supabase chain is rooted in, following the receiver of+ * each member call down the chain and through one local variable+ * (`const query = client.from("t"); query.delete()`). Undefined when the chain+ * is not a query at all — which is what separates `client.from("t").delete()`+ * from `members.delete(id)` on a Set.+ */+function queryRoot(node: Node | undefined, depth = 0): CallExpression | undefined {+ const current = unwrap(node);+ if (!current || depth > 4) return undefined;++ if (Node.isCallExpression(current)) {+ if (memberName(current) === "from" && !isStorageFrom(current)) {+ return current;+ }+ const callee = unwrap(current.getExpression());+ return callee && Node.isPropertyAccessExpression(callee)+ ? queryRoot(callee.getExpression(), depth)+ : undefined;+ }+ if (Node.isPropertyAccessExpression(current)) {+ return queryRoot(current.getExpression(), depth);+ }+ if (Node.isIdentifier(current)) {+ const declaration = current.getSymbol()?.getValueDeclaration();+ return declaration && Node.isVariableDeclaration(declaration)+ ? queryRoot(declaration.getInitializer(), depth + 1)+ : undefined;+ }+ return undefined;+}++export interface DbWrite {+ kind: DbWriteKind;+ /** The relation, when it is named by a string literal. */+ table?: string;+}++/** Every database write a function's own body performs. */+export function dbWrites(fn: ServiceFunctionNode): DbWrite[] {+ const writes: DbWrite[] = [];+ for (const call of fn.getDescendantsOfKind(SyntaxKind.CallExpression)) {+ const name = memberName(call);+ if (!name) continue;++ const kysely = KYSELY_WRITES.get(name);+ if (kysely) {+ writes.push({ kind: kysely, table: stringArgument(call) });+ continue;+ }++ const supabase = SUPABASE_WRITES.get(name);+ if (!supabase) continue;+ const callee = unwrap(call.getExpression());+ if (!callee || !Node.isPropertyAccessExpression(callee)) continue;+ const root = queryRoot(callee.getExpression());+ if (root) writes.push({ kind: supabase, table: stringArgument(root) });+ }+ return writes;+}++/**+ * Relations the function names — `.from("t")`, `insertInto("t")`,+ * `updateTable("t")`. Reads count: a function that reads one table and writes+ * another yields two names, which the audit-column rule treats as "can't tell".+ */+export function namedTables(fn: ServiceFunctionNode): string[] {+ const names = new Set<string>();+ for (const call of fn.getDescendantsOfKind(SyntaxKind.CallExpression)) {+ const name = memberName(call);+ if (name !== "from" && name !== "insertInto" && name !== "updateTable") {+ continue;+ }+ if (name === "from" && isStorageFrom(call)) continue;+ const table = stringArgument(call);+ if (table) names.add(table);+ }+ return [...names];+}++/** Whether the function applies limit/offset itself. */+export function paginates(fn: ServiceFunctionNode): boolean {+ return fn+ .getDescendantsOfKind(SyntaxKind.CallExpression)+ .some((call) => {+ const name = memberName(call);+ return name === "setGenericQueryFilters" || name === "range";+ });+}++/**+ * Whether the function branches on `"createdBy" in x` / `"updatedBy" in x` to+ * pick its insert-vs-update path — the `in` operator itself, not the words.+ */+export function branchesOnKeyPresence(+ fn: ServiceFunctionNode,+ keys: readonly string[]+): boolean {+ return fn+ .getDescendantsOfKind(SyntaxKind.BinaryExpression)+ .some((binary) => {+ if (binary.getOperatorToken().getKind() !== SyntaxKind.InKeyword) {+ return false;+ }+ const left = binary.getLeft();+ return (+ (Node.isStringLiteral(left) ||+ Node.isNoSubstitutionTemplateLiteral(left)) &&+ keys.includes(left.getLiteralText())+ );+ });+}++/**+ * Whether sending `id` is what separates an update from an insert, read off the+ * payload parameter's TYPE: every member of its union that requires `updatedBy`+ * (the update shape) has an `id`, and no other member REQUIRES one. Then a call+ * with an `id` can only mean "update this record" and a call without one can+ * only mean "create".+ *+ * False when both shapes require an `id` (a part's `id` is its part number on+ * create and its item id on update) or neither has one (a pick method is keyed+ * by item and location) — there the payload cannot say which it is.+ */+export function idDistinguishesUpdate(+ fn: ServiceFunctionNode,+ contextParams: ReadonlySet<string>+): boolean {+ for (const param of fn.getParameters()) {+ if (contextParams.has(param.getName())) continue;+ const type = param.getType();+ const members = type.isUnion() ? type.getUnionTypes() : [type];+ // The update shape is the one that REQUIRES `updatedBy`. A validator may+ // itself carry an optional `createdBy`, so its presence proves nothing.+ const updates = members.filter((m) => {+ const updatedBy = m.getProperty("updatedBy");+ return updatedBy !== undefined && !updatedBy.hasFlags(SymbolFlags.Optional);+ });+ const creates = members.filter((m) => !updates.includes(m));+ if (updates.length === 0 || creates.length === 0) continue;++ return (+ updates.every((m) => m.getProperty("id") !== undefined) &&+ creates.every((m) => {+ const id = m.getProperty("id");+ return id === undefined || id.hasFlags(SymbolFlags.Optional);+ })+ );+ }+ return false;+}diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.tsindex 18f1d7c18f..066782dd3c 100644--- a/scripts/lib/service-metadata.ts+++ b/scripts/lib/service-metadata.ts@@ -6,12 +6,16 @@* Service metadata parser — the pure core behind the MCP tool manifest and the* Carbon API contract.*- * Textually parses every `apps/erp/app/modules/*.service.ts` (+ `.ee` / `.mcp.server`+ * Turns every `apps/erp/app/modules/*.service.ts` (+ `.ee` / `.mcp.server`* companions) into operation metadata: classification, description, positional* service params, the audit fields to inject, the required permission, and a JSON* Schema for the input. NO filesystem writes and no process side effects — callers- * (`scripts/generate-mcp.ts`) own emitting the manifest. Grounded against the- * long-standing generator logic; the parsing helpers are moved verbatim.+ * (`scripts/generate-mcp.ts`) own emitting the manifest.+ *+ * Which functions exist, their parameters, their doc tags and what their bodies+ * do all come from the AST (`service-ast.ts`). The one thing still read as TEXT+ * is a parameter's declared type, which `typeToJsonSchema` below turns into a+ * JSON Schema.*/import * as fs from "fs";@@ -25,11 +29,29 @@ import type {ToolPermission,} from "@carbon/api";import { MCP_BLOCKED_TOOL_NAMES } from "../../apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools";+import {+ MCP_DESTRUCTIVE,+ MCP_EXPOSURE_TAG,+ MCP_MODULE_ALLOWLIST,+ MCP_SETTINGS,+ MCP_VERBS,+ type McpVerb+} from "../../apps/erp/app/routes/api+/mcp+/lib/mcp-exposure";import {buildResponseSchemaIndex,type ResponseSchemaIndex,} from "./response-schema";import { getDbEnumValues, getDbTableTypeFields } from "./db-types";+import {+ branchesOnKeyPresence,+ buildServiceAst,+ dbWrites,+ idDistinguishesUpdate,+ namedTables,+ paginates as bodyPaginates,+ type ServiceAst,+ type ServiceFunction+} from "./service-ast";import {buildValidatorRegistry,CONTEXT_PARAMS,@@ -88,54 +110,6 @@ const DESCRIPTION_OVERRIDES: Record<string, string> = {inventory_updateWarehouseTransfer: "Update an existing warehouse transfer",};-// Per-tool overrides of the auto-computed injectAuth set. The default rule-// (insert* → companyId + createdBy + updatedBy) is wrong for tools that spread-// their argument object straight into an INSERT on an append-only ledger table.-// Those tables now carry an updatedBy column (schema uniformity, migration-// 20260701143512), but by convention it must stay NULL — an "edit" is a new-// offsetting row, never an in-place mutation. Injecting updatedBy would stamp it-// on the ledger row and destroy the "untouched since creation" guarantee, so we-// drop it here. Both tools below insert([data]) where data is built from the-// spread of their injected args:-// - inventory_insertManualInventoryAdjustment → itemLedger-// - accounting_upsertFixedAssetUsageLog → fixedAssetUsageLog-// account_upsertNotificationPreference spreads its argument into an upsert on-// notificationPreference, which (like userModulePreference) carries no-// createdBy/updatedBy columns at all — injecting them breaks the write. The-// four lean material lookups (dimension, finish, grade, type) are the same:-// no audit columns, argument spread into the row.-const INJECT_AUTH_OVERRIDES: Record<string, AuthField[]> = {- inventory_insertManualInventoryAdjustment: ["companyId", "createdBy"],- accounting_upsertFixedAssetUsageLog: ["companyId", "createdBy"],- account_upsertNotificationPreference: ["companyId"],- items_upsertMaterialDimension: ["companyId"],- items_upsertMaterialFinish: ["companyId"],- items_upsertMaterialGrade: ["companyId"],- items_upsertMaterialType: ["companyId"],- // Both operations replace settlement rows in a transaction. Their verbs do- // not imply INSERT to the name-based rule, but the service requires the- // authenticated creator for every replacement row.- invoicing_replaceInvoiceSettlements: ["companyId", "createdBy"],- invoicing_applyCreditsToInvoices: ["companyId", "createdBy"],- // Both read the caller's group-scoped currency with the payload's- // companyGroupId and write a memo, so it must come from the auth context —- // a caller-supplied group would resolve another group's currency rows.- purchasing_createPurchaseReturnOrderCredit: [- "companyId",- "companyGroupId",- "createdBy",- "updatedBy",- "userId",- ],- sales_createSalesReturnOrderCredit: [- "companyId",- "companyGroupId",- "createdBy",- "updatedBy",- "userId",- ],-};-// service-module → permission-module. `items` operations are gated by the `parts`// permission; `account` and `shared` gate only on a valid key of the company (no// module permission), so they map to null. Every other module is identity.@@ -145,37 +119,6 @@ const PERMISSION_MODULE_MAP: Record<string, string | null> = {shared: null,};-// Per-tool permission overrides, for operations whose route gates on a DIFFERENT-// module than their service module (spot-checked against the real routes). Keep-// this hand-curated list small and grounded — each entry needs a verified route.-const PERMISSION_OVERRIDES: Record<string, ToolPermission> = {- // API-key management is an admin capability: the list loader- // (x+/settings+/api-keys.tsx) gates on { update: "users" }, not "settings" —- // deriving "settings" would let a settings-scoped key read the key family.- // The WRITES (upsert/delete) moved to @carbon/ee/api-keys.server behind- // requireEntitlement, so they are no longer scanned as MCP tools; only the- // read remains here.- settings_getApiKeys: { module: "users", actions: ["update"] },-};--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------interface ParsedParam {- name: string;- typeStr: string;- optional: boolean;- description?: string;-}--interface ParsedFunction {- name: string;- params: ParsedParam[];- /** Body of a JSDoc block comment immediately preceding the export, if any. */- jsdoc?: string;-}-// ---------------------------------------------------------------------------// Parsing helpers// ---------------------------------------------------------------------------@@ -250,62 +193,6 @@ function isArrowClose(str: string, i: number): boolean {return str[i] === ">" && str[i - 1] === "=";}-/** Index of the first `char` at nesting depth 0, or -1. A defaulted parameter- * splits on `=`, so that scan skips `=>` and `==`/`!=`/`<=`/`>=`. */-function findTopLevel(str: string, char: ":" | "="): number {- let depth = 0;- for (let i = 0; i < str.length; i++) {- const j = skipComment(str, i);- if (j !== i) {- i = j - 1;- continue;- }- const ch = str[i];- if ("({[<".includes(ch)) depth++;- else if (")}]>".includes(ch) && !isArrowClose(str, i)) depth--;- if (ch !== char || depth !== 0) continue;- if (char === "=") {- const prev = str[i - 1];- if (str[i + 1] === ">" || str[i + 1] === "=" || "!<>=".includes(prev)) {- continue;- }- }- return i;- }- return -1;-}--function inferTypeFromDefaultLiteral(literal: string): string {- const t = literal.trim();- if (t === "true" || t === "false") return "boolean";- if (/^-?\d+(\.\d+)?$/.test(t)) return "number";- if (/^["'`].*["'`]$/.test(t)) return "string";- return "unknown";-}--// A destructuring pattern is not a name; storing the raw source text put braces and-// newlines into the manifest, so reformatting a signature churned the committed-// digest. The synthetic name only has to avoid `CONTEXT_PARAMS` and the dispatcher's-// `args` branch — nothing else reads a param name for meaning.-function destructuredParamName(raw: string, existing: ParsedParam[]): string {- if (!raw.startsWith("{")) return raw;- const base = "destructured";- if (!existing.some((p) => p.name === base)) return base;- let i = 2;- while (existing.some((p) => p.name === `${base}${i}`)) i++;- return `${base}${i}`;-}--/** The body of a JSDoc block whose closing marker directly precedes `index`. */-function precedingJsdoc(content: string, index: number): string | undefined {- const before = content.slice(0, index);- const end = before.lastIndexOf("*/");- if (end === -1 || before.slice(end + 2).trim() !== "") return undefined;- const start = before.lastIndexOf("/**", end);- if (start === -1) return undefined;- return before.slice(start + 3, end);-}-/*** Reduce a function-level JSDoc body to a one-line tool description: the prose* before the first `@tag`, first sentence only, whitespace collapsed. The@@ -331,84 +218,6 @@ export function extractJsdocSummary(raw: string): string | undefined {return cased.length > 160 ? `${cased.slice(0, 159).trimEnd()}…` : cased;}-function parseExportedFunctions(content: string): ParsedFunction[] {- const results: ParsedFunction[] = [];- const regex = /export\s+(?:async\s+)?function\s+(\w+)\s*\(/g;- let match;-- while ((match = regex.exec(content)) !== null) {- const name = match[1];- const jsdoc = precedingJsdoc(content, match.index);- const openParen = match.index + match[0].length - 1;- const closeParen = findMatchingBrace(content, openParen);- const rawParams = content.substring(openParen + 1, closeParen).trim();-- if (!rawParams) {- results.push({ name, params: [], jsdoc });- continue;- }-- const paramStrings = splitAtTopLevel(rawParams, ",");- const params: ParsedParam[] = [];-- for (const p of paramStrings) {- if (!p) continue;- // With comment-inert splitting, a param keeps the comment that precedes- // it: keep a `/** doc */` as its description, drop everything else.- const doc = p.match(/\/\*\*([\s\S]*?)\*\//);- const description = doc- ? doc[1]- .split("\n")- .map((line) => line.replace(/^\s*\*?\s?/, "").trim())- .join(" ")- .trim() || undefined- : undefined;- const stripped = p- .replace(/\/\*[\s\S]*?\*\//g, "")- .split("\n")- .map((line) => line.replace(/\/\/.*$/, ""))- .join("\n")- .trim();- if (!stripped) continue;- const colonIdx = findTopLevel(stripped, ":");- if (colonIdx === -1) {- const eqIdx = findTopLevel(stripped, "=");- if (eqIdx === -1) {- params.push({- name: destructuredParamName(stripped, params),- typeStr: "unknown",- optional: false- });- } else {- const paramName = stripped.substring(0, eqIdx).trim();- const defaultLiteral = stripped.substring(eqIdx + 1).trim();- params.push({- name: paramName,- typeStr: inferTypeFromDefaultLiteral(defaultLiteral),- optional: true,- description- });- }- continue;- }- const before = stripped.substring(0, colonIdx).trim();- const optional = before.endsWith("?");- const rawName = before.replace(/\?$/, "").trim();- const typeStr = stripped.substring(colonIdx + 1).trim();- params.push({- name: destructuredParamName(rawName, params),- typeStr,- optional,- description- });- }-- results.push({ name, params, jsdoc });- }-- return results;-}-// ---------------------------------------------------------------------------// Type → JSON Schema conversion// ---------------------------------------------------------------------------@@ -421,7 +230,6 @@ function parseExportedFunctions(content: string): ParsedFunction[] {* — a guessed `contact.phone` reached the insert and failed with PGRST204.*/type TypeResolveContext = SchemaBuildContext & {- modelsContent: string | null;/** Module-local sources searched for `type X = …` / `interface X {…}`. */aliasSources?: string[];/** Cycle guard for alias-to-alias references. */@@ -788,7 +596,7 @@ function resolveInferExpression(return null;}-/** Registry-first, textual-fallback validator lookup, mirroring the top-level+/** Registry lookup for a nested validator reference, mirroring the top-level* param resolution in `buildToolSchema` (including its provenance report). */function lookupValidatorSchema(validatorName: string,@@ -799,13 +607,6 @@ function lookupValidatorSchema(ctx.onResolved?.(validatorName, "native");return native as Record<string, unknown>;}- if (ctx.modelsContent) {- const textual = parseValidatorFields(validatorName, ctx.modelsContent);- if (textual) {- ctx.onResolved?.(validatorName, "textual");- return textual;- }- }ctx.onResolved?.(validatorName, "unresolved");return null;}@@ -909,51 +710,6 @@ function splitObjectFields(inner: string): string[] {// Validator resolution// ----------------------------------------------------------------------------function parseValidatorFields(- validatorName: string,- modelsContent: string,- seen: Set<string> = new Set()-): Record<string, unknown> | null {- // Cycle guard for mutually-referential validators.- if (seen.has(validatorName)) return null;- seen = new Set(seen).add(validatorName);-- const rhs = extractValidatorRhs(validatorName, modelsContent);- if (rhs === null) return null;-- const properties: Record<string, unknown> = {};- const required: string[] = [];- const mergeIn = (sub: Record<string, unknown> | null) => {- if (!sub) return;- Object.assign(properties, sub.properties as Record<string, unknown>);- for (const r of (sub.required as string[] | undefined) ?? []) {- if (!required.includes(r)) required.push(r);- }- };-- // Base validators pulled in by `Base.merge(...)` / `Base.extend(...)` — resolve- // each referenced `*Validator` (same file) and fold its fields in first, so the- // extension below can override. This is what makes- // `applyX(itemValidator.merge(z.object({...})))` resolvable instead of opaque.- const refs = new Set(- (rhs.match(/\b\w+Validator\b/g) ?? []).filter((n) => n !== validatorName)- );- for (const ref of refs) {- mergeIn(parseValidatorFields(ref, modelsContent, seen));- }-- // This validator's own object literal — for a `.merge(z.object({...}))` /- // wrapped chain the FIRST z.object is the extension; for a plain- // `z.object({...})` it is the whole thing. Wrappers (`applyX(...)`, `.refine`,- // `.superRefine`) are transparent to this scan.- mergeIn(parseFirstZObject(rhs));-- if (Object.keys(properties).length === 0) return null;- const result: Record<string, unknown> = { type: "object", properties };- if (required.length > 0) result.required = required;- return result;-}-/*** Resolve a bare type-alias name against the module's own sources (service* file, `types.ts`, models, and the shared equivalents): `type X = <rhs>` and@@ -1017,210 +773,197 @@ function resolveTypeAlias(return null;}-// The assignment expression of `export const {name} = <expr>;`, captured to the-// first top-level `;` (arrow-guarded) so a `*Validator` reference or `z.object`-// from a later declaration is never pulled in.-function extractValidatorRhs(- validatorName: string,- modelsContent: string-): string | null {- const regex = new RegExp(`export\\s+const\\s+${validatorName}\\s*=\\s*`);- const match = regex.exec(modelsContent);- if (!match) return null;- const start = match.index + match[0].length;-- let depth = 0;- for (let i = start; i < modelsContent.length; i++) {- const ch = modelsContent[i];- if ("({[<".includes(ch)) depth++;- else if (")}]>".includes(ch) && !isArrowClose(modelsContent, i)) depth--;- else if (ch === ";" && depth === 0) {- return modelsContent.substring(start, i);- }- }- return modelsContent.substring(start);-}--// Parse the first `z.object({ ... })` in an expression into a JSON-Schema object.-function parseFirstZObject(expr: string): Record<string, unknown> | null {- const idx = expr.indexOf("z.object(");- if (idx === -1) return null;- const braceStart = expr.indexOf("{", idx);- if (braceStart === -1) return null;- const braceEnd = findMatchingBrace(expr, braceStart);- const inner = expr.substring(braceStart + 1, braceEnd).trim();-- const properties: Record<string, unknown> = {};- const required: string[] = [];+// ---------------------------------------------------------------------------+// Classification, auth & permission+// ---------------------------------------------------------------------------- // Validator fields are comma-separated, not semicolon-separated- const fields = splitAtTopLevel(inner, ",");+const AUTH_FIELDS: readonly AuthField[] = [+ "companyId",+ "companyGroupId",+ "createdBy",+ "updatedBy",+ "userId"+];+const PERMISSION_ACTIONS: readonly PermissionAction[] = [+ "view",+ "create",+ "update",+ "delete"+];- for (const field of fields) {- const f = field.trim();- if (!f || f.startsWith("//")) continue;+type McpSetting = keyof typeof MCP_SETTINGS;- const colonMatch = f.match(/^(\w+)\s*:/);- if (!colonMatch) continue;- const fieldName = colonMatch[1];+/** Every `@mcp …` line on a function: its first word, and the rest. */+function mcpLines(fn: ServiceFunction): { word: string; rest: string }[] {+ return fn.tags+ .filter((tag) => `@${tag.name}` === MCP_EXPOSURE_TAG)+ .map((tag) => {+ const [word = "", ...rest] = tag.comment.split(/\s+/);+ return { word, rest: rest.join(" ") };+ });+}- if (CONTEXT_PARAMS.has(fieldName)) continue;+/** What follows `@mcp <setting>` on each such line. */+function settingLines(fn: ServiceFunction, setting: McpSetting): string[] {+ return mcpLines(fn)+ .filter((line) => line.word === MCP_SETTINGS[setting])+ .map((line) => line.rest);+}- const zodExpr = f.substring(colonMatch[0].length).trim();- const schema = zodExprToJsonSchema(zodExpr);- const isOptional =- zodExpr.includes(".optional()") ||- zodExpr.includes(".nullable()") ||- zodExpr.startsWith("zfd.text(") ||- zodExpr.startsWith("zfd.numeric(") ||- zodExpr.includes(".default(");-- properties[fieldName] = schema;- if (!isOptional) required.push(fieldName);+/** A setting that may be given once. Twice is two answers to one question,+ * read differently depending on which came first. */+function singleSetting(+ fn: ServiceFunction,+ setting: McpSetting+): string | undefined {+ const lines = settingLines(fn, setting);+ if (lines.length > 1) {+ throw new Error(+ `${fn.toolName} has ${lines.length} \`${MCP_EXPOSURE_TAG} ${setting}\` lines. Keep one.`+ );}-- if (Object.keys(properties).length === 0) return null;- const result: Record<string, unknown> = { type: "object", properties };- if (required.length > 0) result.required = required;- return result;+ return lines[0];}-function zodExprToJsonSchema(expr: string): Record<string, unknown> {- const e = expr.trim();-- if (e.includes("z.enum(")) {- const enumMatch = e.match(/z\.enum\(\[([^\]]+)\]\)/);- if (enumMatch) {- const values = enumMatch[1]- .split(",")- .map((s) => s.trim().replace(/^["']|["']$/g, ""))- .filter(Boolean);- return { type: "string", enum: values };- }- }+export interface Declaration {+ verb: McpVerb;+ destructive: boolean;+}- if (e.startsWith("z.array(")) {- // Resolve the element schema so the array is well-formed rather than a bare- // `{type:"array"}` a caller can't fill.- const open = e.indexOf("(");- const close = findMatchingBrace(e, open);- const inner = e.substring(open + 1, close).trim();- return { type: "array", items: inner ? zodExprToJsonSchema(inner) : {} };+/**+ * What the function declares itself to be: `@mcp <verb> [destructive]`.+ * Undefined when it carries no `@mcp` line — then it is simply not a tool.+ * Anything else the generator needs follows from the verb (`MCP_VERBS`); the+ * function's NAME is never consulted.+ *+ * The declaration is checked against what the body does, in the direction that+ * matters: `read` on a body that writes, or a write whose body deletes rows+ * without `destructive`, fails generation. The reverse cannot be checked — a+ * body with no write of its own may hand the work to a helper, an RPC or an+ * edge function — which is exactly why it has to be declared.+ */+export function declarationOf(fn: ServiceFunction): Declaration | undefined {+ const lines = mcpLines(fn);+ if (lines.length === 0) return undefined;++ const settings: readonly string[] = Object.values(MCP_SETTINGS);+ const verbs = lines.filter((line) => !settings.includes(line.word));+ if (verbs.length !== 1) {+ throw new Error(+ `${fn.toolName} must declare exactly one \`${MCP_EXPOSURE_TAG} <verb>\` line; it has ${verbs.length}.`+ );}- if (e.includes("z.number()")) return { type: "number" };- if (e.includes("z.boolean()")) return { type: "boolean" };- if (e.includes("z.string()") || e.startsWith("zfd.text("))- return { type: "string" };- if (e.includes("z.any()")) return {};- if (e.startsWith("zfd.numeric(")) return { type: "number" };- if (e.startsWith("z.preprocess(")) {- // A preprocessed enum whose values aren't an inline array can't be- // enumerated (the top-of-function z.enum check already ran on this same- // expr), so treat it as a string. Recursing on `e` here looped forever.- if (e.includes("z.enum(")) return { type: "string" };- if (e.includes("z.number()")) return { type: "number" };- return { type: "string" };+ const { word, rest } = verbs[0];+ if (!Object.hasOwn(MCP_VERBS, word)) {+ throw new Error(+ `${fn.toolName}: \`${MCP_EXPOSURE_TAG} ${word}\` is not a verb. Use one of ${Object.keys(MCP_VERBS).join(", ")}.`+ );}+ const verb = word as McpVerb;+ const destructive = rest.split(/\s+/)[0] === MCP_DESTRUCTIVE;- return { type: "string" };+ const writes = dbWrites(fn.node);+ if (verb === "read") {+ if (destructive) {+ throw new Error(`${fn.toolName}: a read cannot be ${MCP_DESTRUCTIVE}.`);+ }+ if (writes.length > 0) {+ throw new Error(+ `${fn.toolName} declares \`${MCP_EXPOSURE_TAG} read\` but its body writes to ${writes[0]?.table ?? "the database"}. Declare the verb it really is.`+ );+ }+ } else if (+ verb !== "delete" &&+ !destructive &&+ writes.some((w) => w.kind === "delete")+ ) {+ throw new Error(+ `${fn.toolName} declares \`${MCP_EXPOSURE_TAG} ${verb}\` but its body deletes rows. Declare \`${MCP_EXPOSURE_TAG} ${verb} ${MCP_DESTRUCTIVE}\`.`+ );+ }+ return { verb, destructive };}-// ----------------------------------------------------------------------------// Classification, auth & permission-// -----------------------------------------------------------------------------function classifyFunction(- name: string,- content?: string-): Classification {- if (/^delete/.test(name)) return "DESTRUCTIVE";- // Require a camelCase boundary after the read prefix so a mutating name that merely starts with- // those letters is not misread as a reader — e.g. `issueMaterial` ("is"+lowercase) is a WRITE,- // while `isBlocked`/`getJob` ("is"/"get"+uppercase) stay READ.- if (/^(get|list|fetch|search|find|count|check|is|has|compute)(?![a-z])/.test(name))- return "READ";- // Destructive-by-omission: a write whose body deletes rows (e.g. the- // delete-then-reinsert `upsert*Prices` rewrite) can silently drop data the- // caller didn't include. Flag it so the client treats it as destructive, even- // though its name says `upsert`/`update`. injectAuth stays name-based below, so- // the insert branch still gets its createdBy.- if (content && functionBodyDeletes(content, name)) return "DESTRUCTIVE";- return "WRITE";+/** `@mcp audit a, b` → the fields to stamp, companyId always among them. */+function declaredAudit(fn: ServiceFunction): AuthField[] | undefined {+ const line = singleSetting(fn, "audit");+ if (line === undefined) return undefined;+ const fields = line+ .split(",")+ .map((field) => field.trim())+ .filter(Boolean);+ for (const field of fields) {+ if (!AUTH_FIELDS.includes(field as AuthField)) {+ throw new Error(+ `${fn.toolName}: \`${MCP_EXPOSURE_TAG} audit\` names "${field}". Use ${AUTH_FIELDS.join(", ")}.`+ );+ }+ }+ return [...new Set<AuthField>(["companyId", ...(fields as AuthField[])])];}-// True when the function body issues a row delete (supabase `.delete(` or Kysely-// `.deleteFrom(`). Comment/URL-safe via stripComments.-function functionBodyDeletes(content: string, funcName: string): boolean {- const body = extractFunctionBody(content, funcName);- if (body === null) return false;- const stripped = stripComments(body);- return /\.delete\s*\(/.test(stripped) || /\.deleteFrom\s*\(/.test(stripped);+/** `@mcp permission module:action+action` → the permission to gate on. */+function declaredPermission(fn: ServiceFunction): ToolPermission | undefined {+ const line = singleSetting(fn, "permission");+ if (line === undefined) return undefined;+ const [module = "", actionList = ""] = line.split(/\s+/)[0].split(":");+ const actions = actionList.split("+").filter(Boolean);+ if (+ !module ||+ actions.length === 0 ||+ actions.some(+ (action) => !PERMISSION_ACTIONS.includes(action as PermissionAction)+ )+ ) {+ throw new Error(+ `${fn.toolName}: \`${MCP_EXPOSURE_TAG} permission\` must read <module>:<action>[+<action>] with actions from ${PERMISSION_ACTIONS.join(", ")}.`+ );+ }+ return { module, actions: actions as PermissionAction[] };}+/** The keys an upsert branches on to pick insert vs update. */+const OPERATION_FIELDS = ["createdBy", "updatedBy"] as const;+/**- * Whether the service itself applies limit/offset — `setGenericQueryFilters`- * (the canonical pager) or a direct `.range(`. A list operation without either- * ignores pagination args entirely (the fetchAll `get*List` reads), so the MCP- * layer pages the response instead. Same body-scan mechanism (and shadowed-- * wrapper first-match caveat) as `functionBodyDeletes`.+ * Drop `createdBy` / `updatedBy` when the function's ONE table has no such+ * column. The verb says which audit fields a tool is handed, and+ * `enrichWithAuthContext` stamps them onto the payload OBJECT — so a+ * service that spreads its argument into the write (`insert([row])`,+ * `update(sanitize(row))`) sends a nonexistent column to PostgREST and the call+ * fails with PGRST204. The HTML form routes build the row from their validator+ * and never saw it, so this only ever broke MCP and the v1 API.+ *+ * The generated types are the source of truth (`pnpm run generate:types` runs+ * after every migration, so they cannot lag a new table). Ambiguity is left+ * alone: zero or several tables keeps the computed set, as does a table missing+ * from the generated types. `companyId` is never derived away — it is frequently+ * an `.eq()` filter argument rather than a column.*/-function functionBodyPaginates(content: string, funcName: string): boolean {- const body = extractFunctionBody(content, funcName);- if (body === null) return false;- const stripped = stripComments(body);- return (- /setGenericQueryFilters\s*\(/.test(stripped) || /\.range\s*\(/.test(stripped)- );-}+export function withoutAbsentAuditColumns(+ fields: AuthField[],+ fn: ServiceFunction,+ onDrop?: (table: string, dropped: AuthField[]) => void+): AuthField[] {+ const audit: AuthField[] = ["createdBy", "updatedBy"];+ if (!audit.some((f) => fields.includes(f))) return fields;-function extractFunctionBody(content: string, funcName: string): string | null {- const regex = new RegExp(- `export\\s+(?:async\\s+)?function\\s+${funcName}\\s*\\(`- );- const match = regex.exec(content);- if (!match) return null;- const closeParen = findMatchingBrace(- content,- match.index + match[0].length - 1- );- const nextExport = content.indexOf("\nexport ", closeParen);- return content.substring(- closeParen,- nextExport === -1 ? content.length : nextExport- );-}+ const tables = namedTables(fn.node);+ if (tables.length !== 1) return fields;+ const columns = getDbTableTypeFields(tables[0], "Row");+ if (!columns) return fields;-function computeInjectAuth(- funcName: string,- classification: Classification-): AuthField[] {- const lower = funcName.toLowerCase();- // Only READ tools take no audit fields. A DESTRUCTIVE label is just a caller- // hint — a delete-then-reinsert `upsert*` still inserts rows and needs its- // createdBy/updatedBy, so audit injection is keyed off the name verb, not the- // classification. A genuine `delete*` matches neither verb group and falls- // through to companyId-only.- if (classification === "READ") {- return ["companyId"];- }- if (- /^(upsert|create|insert|add|new|copy|duplicate|generate)/.test(lower)- ) {- return ["companyId", "createdBy", "updatedBy"];- }- if (- /^(update|modify|set|change|edit|approve|reject|finalize|toggle|move|reorder|recalculate|sync|favorite|unfavorite|send|release|close|convert|run)/.test(- lower- )- ) {- return ["companyId", "updatedBy"];- }- return ["companyId"];+ const present = new Set(columns.map((c) => c.name));+ const dropped = audit.filter((f) => fields.includes(f) && !present.has(f));+ if (dropped.length === 0) return fields;++ onDrop?.(tables[0], dropped);+ return fields.filter((f) => !dropped.includes(f));}export function withPayloadUserId(fields: AuthField[],- func: ParsedFunction+ func: Pick<ServiceFunction, "params">): AuthField[] {if (fields.includes("userId")) return fields;const declaresUserId = func.params.some(@@ -1229,65 +972,6 @@ export function withPayloadUserId(return declaresUserId ? [...fields, "userId"] : fields;}-// The permission an API-key caller must hold. `module` follows the service→permission-// map; `actions` are derived from the operation verb, mirroring `computeInjectAuth`'s-// verb groups but split into CRUD actions. An unmatched write verb (issue/post/ship/-// complete/...) requires `update` — the conservative mutation gate.-function derivePermission(- toolName: string,- mod: string,- funcName: string,- classification: Classification-): ToolPermission {- if (PERMISSION_OVERRIDES[toolName]) return PERMISSION_OVERRIDES[toolName];-- const permModule =- mod in PERMISSION_MODULE_MAP ? PERMISSION_MODULE_MAP[mod] : mod;-- return { module: permModule, actions: permissionActionsFor(funcName, classification) };-}--function permissionActionsFor(- funcName: string,- classification: Classification-): PermissionAction[] {- if (classification === "READ") return ["view"];- const lower = funcName.toLowerCase();- if (/^upsert/.test(lower)) return ["create", "update"];- if (/^delete/.test(lower)) return ["delete"];- if (/^(insert|create|add|new|copy|duplicate|generate)/.test(lower))- return ["create"];- // Everything else that writes — the explicit update group plus unmatched- // mutation verbs (issue/post/ship/receive/complete/...) — gates on update.- return ["update"];-}--// Services that pick insert-vs-update by testing for an audit field on the-// payload are the only ones MCP can't infer, so they need the `_operation` flag.-// BOTH directions count: `"createdBy" in` (create-branch first, e.g.-// upsertQuoteOperation) and `"updatedBy" in` (update-branch first, e.g.-// upsertQuoteMaterial / upsertJobMaterial). The dispatch stamps createdBy on-// create and updatedBy on update and suppresses the other, so either convention-// lands on the branch the caller asked for.-function usesOperationDiscriminator(- content: string,- funcName: string-): boolean {- const body = extractFunctionBody(content, funcName);- if (body === null) return false;- const stripped = stripComments(body);- return (- stripped.includes('"createdBy" in') || stripped.includes('"updatedBy" in')- );-}--// The `:` guard keeps `https://` intact.-function stripComments(source: string): string {- return source- .replace(/\/\*[\s\S]*?\*\//g, "")- .replace(/(^|[^:])\/\/.*$/gm, "$1");-}-/*** Delete `pattern` wherever a sibling `format` is present, recursively. zod* v4's email conversion emits BOTH — `format: "email"` plus a ~200-character@@ -1309,18 +993,138 @@ function stripRedundantPatterns(node: unknown): void {}}-function addOperationArg(schema: Record<string, unknown>): void {- const properties = (schema.properties ?? {}) as Record<string, unknown>;- properties._operation = {- type: "string",- enum: ["create", "update"],- description:- "Required. 'create' inserts a new record, 'update' modifies the existing record with this id.",+/**+ * How the dispatcher tells create from update for a service that branches on an+ * audit field. Never the caller's job: the answer is either in the payload or+ * in the database.+ *+ * - `@mcp key <table> <column>[=<field>], …` on the function — look the row+ * up, `column` compared with the payload's `field` (same name by default).+ * Several lines are alternatives: a part's `id` may be its item id or its+ * part number.+ * - otherwise the parameter's type must make `id` decisive (sent = update).+ *+ * Anything else fails generation, so a new upsert cannot quietly become a tool+ * that needs to be told what it is doing.+ */+export function upsertRule(+ fn: ServiceFunction,+ schema: Record<string, unknown>+): NonNullable<ManifestEntry["upsert"]> {+ const keyLines = settingLines(fn, "key");+ if (keyLines.length === 0) {+ if (idDistinguishesUpdate(fn.node, CONTEXT_PARAMS)) return { keys: ["id"] };+ throw new Error(+ `${fn.toolName} branches on createdBy/updatedBy, but its payload cannot say whether it creates or updates: \`id\` is required (or absent) in both shapes. Declare the row it updates: \`${MCP_EXPOSURE_TAG} key <table> <column>[, <column>]\`.`+ );+ }++ // The dispatcher reads a key at the top level or inside the one object the+ // payload is wrapped in, so the schema must declare it at one of the two.+ const properties = (schema.properties ?? {}) as Record<+ string,+ { properties?: Record<string, unknown> }+ >;+ const declares = (field: string) =>+ field in properties ||+ Object.values(properties).some(+ (property) => property?.properties && field in property.properties+ );+ const fail = (message: string): never => {+ throw new Error(`${fn.toolName}: \`${MCP_EXPOSURE_TAG} key\` ${message}`);};- schema.properties = properties;- const required = ((schema.required as string[] | undefined) ?? []).slice();- if (!required.includes("_operation")) required.push("_operation");- schema.required = required;++ // Each line is one row to look for; several lines are alternatives.+ const lookups = keyLines.map((line) => {+ const [table = "", ...rest] = line.split(/\s+/);+ const columns = getDbTableTypeFields(table, "Row")?.map((c) => c.name);+ if (!columns) {+ return fail(+ `names "${table}", which is not a table or view in the generated types.`+ );+ }+ // The lookup is always scoped to the caller's company.+ if (!columns.includes("companyId")) {+ return fail(`"${table}" has no companyId column to scope the lookup by.`);+ }+ const match: Record<string, string> = {};+ for (const pair of rest.join(" ").split(",")) {+ const [column = "", field = column] = pair+ .split("=")+ .map((part) => part.trim());+ if (!column) continue;+ if (!columns.includes(column)) {+ return fail(`"${table}" has no "${column}" column.`);+ }+ if (!declares(field)) {+ return fail(`field "${field}" is not part of the tool's input.`);+ }+ match[column] = field;+ }+ if (Object.keys(match).length === 0) {+ return fail(`${table} names no key column.`);+ }+ return { table, match };+ });++ return {+ keys: [...new Set(lookups.flatMap((lookup) => Object.values(lookup.match)))],+ lookups+ };+}++/** Say on the key field itself what sending it does — the one place a caller+ * reading the schema is certain to look. */+function describeUpsertKeys(+ schema: Record<string, unknown>,+ rule: NonNullable<ManifestEntry["upsert"]>+): void {+ type Property = Record<string, unknown> & {+ properties?: Record<string, Property>;+ };+ const note = rule.lookups+ ? "Updates the existing record with this key; creates one when there is none."+ : "Send to update that record; omit to create a new one.";+ const annotate = (properties: Record<string, Property> | undefined) => {+ if (!properties) return false;+ let found = false;+ for (const key of rule.keys) {+ const property = properties[key];+ if (!property || typeof property !== "object") continue;+ const existing =+ typeof property.description === "string" ? property.description : "";+ properties[key] = {+ ...property,+ description: existing ? `${existing} ${note}` : note+ };+ found = true;+ }+ return found;+ };++ const top = schema.properties as Record<string, Property> | undefined;+ if (annotate(top)) return;+ // The payload is wrapped (`{ job: {…} }`): the key lives one level down, or+ // in an object the schema does not spell out — say it on the wrapper then.+ for (const property of Object.values(top ?? {})) {+ if (!property || typeof property !== "object") continue;+ if (annotate(property.properties)) return;+ }+ const wrapper = Object.entries(top ?? {}).find(+ ([, property]) =>+ property && typeof property === "object" && property.type !== "array"+ );+ if (wrapper && top) {+ const [name, property] = wrapper;+ const hint = `Include \`${rule.keys.join("`, `")}\` to update that record; leave it out to create a new one.`;+ top[name] = {+ ...property,+ description:+ typeof property.description === "string"+ ? `${property.description} ${hint}`+ : hint+ };+ }}function generateDescription(funcName: string): string {@@ -1335,12 +1139,11 @@ function generateDescription(funcName: string): string {// ---------------------------------------------------------------------------function buildToolSchema(- func: ParsedFunction,- modelsContent: string | null,+ func: Pick<ServiceFunction, "params">,ctx: SchemaBuildContext = {}): { schema: Record<string, unknown>; paramCount: number } {const userParams = func.params.filter((p) => !CONTEXT_PARAMS.has(p.name));- const resolveCtx: TypeResolveContext = { ...ctx, modelsContent };+ const resolveCtx: TypeResolveContext = { ...ctx };if (userParams.length === 0) {return { schema: { type: "object", properties: {} }, paramCount: 0 };@@ -1423,8 +1226,8 @@ function buildToolSchema(if (validatorMatch) {const validatorName = validatorMatch[1];- // Preferred path: the REAL validator, converted by zod itself. Carries enum- // values, numeric bounds and nested shapes the source-text parser cannot see.+ // The REAL validator, converted by zod itself: enum values, numeric+ // bounds and nested shapes come from the schema object, not its source.const native = ctx.validators?.getSchema(ctx.module ?? "", validatorName);if (native) {ctx.onResolved?.(validatorName, "native");@@ -1434,19 +1237,9 @@ function buildToolSchema(return { schema: native, paramCount: propCount };}- // Fallback: parse the validator's source text. Reached when the module failed- // to load or zod could not represent the validator — never a silent downgrade,- // the caller records it.- if (modelsContent) {- const resolved = parseValidatorFields(validatorName, modelsContent);- if (resolved) {- ctx.onResolved?.(validatorName, "textual");- const propCount = Object.keys(- (resolved.properties as Record<string, unknown>) || {}- ).length;- return { schema: resolved, paramCount: propCount };- }- }+ // No fallback. A validator that cannot be loaded is reported as+ // `unresolved` and the generator FAILS — see the note on+ // ValidatorResolution.ctx.onResolved?.(validatorName, "unresolved");}@@ -1562,7 +1355,19 @@ function loadModelsContent(mod: string): string | null {// ---------------------------------------------------------------------------/** How a `z.infer<typeof X>` param's schema was obtained, for the accuracy report. */-export type ValidatorResolution = "native" | "textual" | "unresolved";+/**+ * How a `z.infer<typeof v>` parameter's schema was obtained. `native` is the only+ * good answer: the REAL validator, converted by zod's own `z.toJSONSchema`.+ *+ * There used to be a `textual` route that re-parsed the validator's SOURCE TEXT+ * when the module would not load — a hand-rolled zod-expression evaluator that+ * could not see enum values, numeric bounds or nested shapes, so it published a+ * lossy contract to MCP, the v1 OpenAPI spec and the docs. Measured over the real+ * tree it fired ZERO times out of 342, so it was 145 lines of the most fragile+ * code in this file standing in for a case that never happens. It is gone;+ * `unresolved` now fails the generator instead of degrading quietly.+ */+export type ValidatorResolution = "native" | "unresolved";/** Per-module state threaded into `buildToolSchema`. */interface SchemaBuildContext {@@ -1581,9 +1386,8 @@ export interface BuildOptions {/** Optional per-module progress callback (module name, tool count). */onModule?: (mod: string, count: number) => void;/**- * Pre-converted validators. When absent every `z.infer<typeof X>` param falls- * back to source-text parsing, which is the long-standing behavior — so callers- * that cannot run the async loader still get a manifest.+ * Pre-converted validators. When absent every `z.infer<typeof X>` param is+ * reported `unresolved` and published without its fields.*/validators?: ValidatorRegistry;/** Reflected response schemas, keyed `{module}_{fn}`. Absent = inputs only. */@@ -1594,53 +1398,46 @@ export interface BuildOptions {validatorName: string,how: ValidatorResolution) => void;+ /**+ * The parsed service files. Passed in by the async entry point so the response+ * index reflects return types over the same ts-morph project; built here when+ * absent, which keeps this function sync and self-contained.+ */+ ast?: ServiceAst;+ /** An exported function with no `@mcp` tag, so it is not a tool. */+ onUntagged?: (toolName: string) => void;+ /** A module absent from `MCP_MODULE_ALLOWLIST`, so none of it is exposed. */+ onModuleSkipped?: (module: string, functionCount: number) => void;+ /**+ * Reported whenever the verb's audit fields include a column the tool's+ * table does not have. Surfaced by the generator so a wrong drop is+ * visible in the run output, not only in the digest diff.+ */+ onAuditColumnsDropped?: (+ toolName: string,+ table: string,+ dropped: AuthField[]+ ) => void;}/**- * Parse every module's service file(s) into the full operation manifest. Pure —+ * Build the full operation manifest from every module's service file(s). Pure —* reads source files, returns metadata, writes nothing.*/export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {const allTools: ManifestEntry[] = [];+ const ast = opts.ast ?? buildServiceAst(MODULE_LIST);for (const mod of MODULE_LIST) {- let serviceFile = path.join(MODULES_DIR, mod, `${mod}.service.ts`);- if (!fs.existsSync(serviceFile)) {- // Fall back to the `.ee`-licensed variant (see root LICENSE) when a- // module keeps its single service file under that name (e.g.- // accounting.service.ts).- const eeServiceFile = path.join(MODULES_DIR, mod, `${mod}.ee.service.ts`);- if (!fs.existsSync(eeServiceFile)) {- console.warn(` ⚠ Service file not found: ${serviceFile}`);- continue;- }- serviceFile = eeServiceFile;+ const parsed = ast.modules.get(mod);+ if (!parsed) {+ console.warn(` ⚠ Service file not found for module: ${mod}`);+ continue;}- let content = fs.readFileSync(serviceFile, "utf-8");- const modelsContent = loadModelsContent(mod);- const functions = parseExportedFunctions(content);-- // A module may expose MCP tools from a server-only companion file- // (`{mod}.mcp.server.ts`) when those functions must import `*.server`- // modules and therefore cannot live in the client-reachable service file.- const mcpServerFile = path.join(MODULES_DIR, mod, `${mod}.mcp.server.ts`);- if (fs.existsSync(mcpServerFile)) {- const mcpServerContent = fs.readFileSync(mcpServerFile, "utf-8");- content = `${content}\n${mcpServerContent}`;- // A same-named mcp.server export SHADOWS the service one — matching the- // runtime registry, where the mcp.server spread wins — so an orchestration- // wrapper can replace a bare service function without renaming the- // published tool. Its PARAMS come from the wrapper; note that body scans- // (classification, the `_operation` discriminator) read the FIRST match in- // the concatenated content, i.e. the service body — a wrapper must keep- // the same discriminator convention as the function it shadows.- const mcpFunctions = parseExportedFunctions(mcpServerContent);- const shadowed = new Set(mcpFunctions.map((f) => f.name));- for (let i = functions.length - 1; i >= 0; i--) {- if (shadowed.has(functions[i].name)) functions.splice(i, 1);- }- functions.push(...mcpFunctions);+ if (!MCP_MODULE_ALLOWLIST.includes(mod)) {+ opts.onModuleSkipped?.(mod, parsed.functions.length);+ continue;}// Sources searched when a param references a bare type alias, most@@ -1648,23 +1445,48 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {// models, then the shared module's equivalents (the common cross-module// import target).const aliasSources = [- content,+ parsed.text,readIfExists(path.join(MODULES_DIR, mod, "types.ts")),- modelsContent,+ loadModelsContent(mod),readIfExists(path.join(MODULES_DIR, "shared", "types.ts")),readIfExists(path.join(MODULES_DIR, "shared", "shared.models.ts"))].filter((s): s is string => s !== null);let toolCount = 0;- for (const func of functions) {- const toolName = `${mod}_${func.name}`;+ for (const func of parsed.functions) {+ const { toolName } = func;if (MCP_BLOCKED_TOOL_NAMES.includes(toolName)) continue;- const classification = classifyFunction(func.name, content);+ // A function is a tool because it says so, and it says what kind.+ const declared = declarationOf(func);+ if (!declared) {+ opts.onUntagged?.(toolName);+ continue;+ }+ const verb = MCP_VERBS[declared.verb];+ const classification: Classification = declared.destructive+ ? "DESTRUCTIVE"+ : verb.classification;+ // The dispatcher fills one positional argument per parameter from a JSON+ // object; a variadic tail has no such slot.+ const rest = func.params.find((p) => p.rest);+ if (rest) {+ throw new Error(+ `${toolName} takes a rest parameter (...${rest.name}), which the API cannot express. Give it an array parameter, or add it to MCP_BLOCKED_TOOL_NAMES.`+ );+ }+ // A declared `@mcp audit` states INTENT and wins outright (a ledger row+ // keeps `updatedBy` NULL even though the column exists); only the verb's+ // own set is checked against the real schema.const injectAuth = withPayloadUserId(- INJECT_AUTH_OVERRIDES[toolName] ||- computeInjectAuth(func.name, classification),+ declaredAudit(func) ??+ withoutAbsentAuditColumns(+ ["companyId", ...verb.audit],+ func,+ (table, dropped) =>+ opts.onAuditColumnsDropped?.(toolName, table, dropped)+ ),func);// A JSDoc on the function itself beats the override table (code closest@@ -1674,13 +1496,11 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {DESCRIPTION_OVERRIDES[toolName] ||generateDescription(func.name);const serviceParams = func.params.map((p) => p.name);- const permission = derivePermission(- toolName,- mod,- func.name,- classification- );- const { schema, paramCount } = buildToolSchema(func, modelsContent, {+ const permission: ToolPermission = declaredPermission(func) ?? {+ module: mod in PERMISSION_MODULE_MAP ? PERMISSION_MODULE_MAP[mod] : mod,+ actions: [...verb.actions]+ };+ const { schema, paramCount } = buildToolSchema(func, {module: mod,validators: opts.validators,aliasSources,@@ -1688,15 +1508,20 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {opts.onValidatorResolved?.(toolName, validatorName, how),});stripRedundantPatterns(schema);- if (+ // A service that picks insert-vs-update by testing for an audit field on+ // the payload needs exactly ONE of them stamped. BOTH directions count:+ // `"createdBy" in` (create-branch first, upsertQuoteOperation) and+ // `"updatedBy" in` (update-branch first, upsertQuoteMaterial /+ // upsertJobMaterial). Which one is decided by the dispatcher from the+ // rule recorded here, never by an argument the caller has to supply.+ const upsert =injectAuth.includes("createdBy") &&- usesOperationDiscriminator(content, func.name)- ) {- addOperationArg(schema);- }+ branchesOnKeyPresence(func.node, OPERATION_FIELDS)+ ? upsertRule(func, schema)+ : undefined;+ if (upsert) describeUpsertKeys(schema, upsert);const responseSchema = opts.responses?.get(mod, func.name) ?? undefined;- const paginates = functionBodyPaginates(content, func.name);allTools.push({name: toolName,@@ -1707,7 +1532,11 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {serviceParams,injectAuth,permission,- paginates,+ // Whether the service applies limit/offset itself. A list operation+ // that does not ignores pagination args entirely (the fetchAll+ // `get*List` reads), so the MCP layer pages the response instead.+ paginates: bodyPaginates(func.node),+ ...(upsert ? { upsert } : {}),schema,...(responseSchema ? { responseSchema } : {}),});@@ -1735,20 +1564,22 @@ export interface BuildWithValidatorsResult {}/**- * The production entry point: load and convert the real validators, then build the- * manifest against them. Falls back per-validator to source-text parsing, so a- * module that fails to load degrades exactly one module's schemas rather than the- * whole run — and `registryStats` / `resolutions` report every such case.+ * The production entry point: load and convert the real validators, parse the+ * service files once, and build the manifest and its response schemas against+ * both. `registryStats` / `resolutions` report every validator that failed to+ * load; the generator refuses to write a manifest when any did.*/export async function buildAllToolMetadataWithValidators(opts: Omit<BuildOptions, "validators"> = {}): Promise<BuildWithValidatorsResult> {const validators = await buildValidatorRegistry(MODULE_LIST);- const responses = buildResponseSchemaIndex(MODULE_LIST);+ const ast = opts.ast ?? buildServiceAst(MODULE_LIST);+ const responses = buildResponseSchemaIndex(ast);const resolutions: ValidatorResolutionRecord[] = [];const tools = buildAllToolMetadata({...opts,+ ast,validators,responses,onValidatorResolved: (toolName, validatorName, how) => {diff --git a/scripts/lib/validator-registry.ts b/scripts/lib/validator-registry.tsindex deb05d1ded..270d8d2e25 100644--- a/scripts/lib/validator-registry.ts+++ b/scripts/lib/validator-registry.ts@@ -24,9 +24,8 @@ import {* because forms submit them, but publishing them in the manifest would invite a* caller to set `companyId`.*- * Shared with the textual parser in `service-metadata.ts`: a validator resolved- * natively and the same one resolved textually must strip the same set, so this is- * the single copy.+ * Shared with `service-metadata.ts`, which strips the same set from a service's+ * own parameter list, so this is the single copy.** `eliminationClient` is a second Supabase client for consolidation reads. Left out* of this set it becomes a required field no caller can express.@@ -55,7 +54,7 @@ export interface ValidatorRegistry {/*** The converted schema for `validatorName`, looked up in `mod` and then in* `shared` (cross-module validators). Null when unknown or unconvertible — the- * caller must fall back to textual parsing.+ * caller reports it `unresolved` and the generator refuses to write.*/getSchema(mod: string, validatorName: string): JsonSchema | null;/** Values of an exported `as const` string array, for `(typeof X)[number]` params. */@@ -113,8 +112,8 @@ function isConstStringArray(value: unknown): value is string[] {/*** Load every module's models file and convert its validators. Never throws: a module* that fails to load, or a validator that fails to convert, is recorded in `stats`- * and simply absent from the lookup, so the generator falls back to textual parsing- * for exactly those and nothing else.+ * and simply absent from the lookup; the generator reports each one and refuses to+ * write a manifest until it loads.*/export async function buildValidatorRegistry(modules: readonly string[]@@ -171,9 +170,9 @@ export async function buildValidatorRegistry(null;// Hand out a COPY. One validator backs many operations (supplierValidator// backs both insertSupplier and upsertSupplier), and downstream steps mutate- // the schema in place — `addOperationArg` writes `_operation` onto it. Sharing- // the object leaked that required argument onto sibling operations that never- // take it.+ // the schema in place — `describeUpsertKeys` annotates the key fields. Sharing+ // the object leaked one operation's edits onto sibling operations that never+ // made them.return found ? (structuredClone(found) as JsonSchema) : null;},getConstArray(mod, exportName) {diff --git a/turbo.json b/turbo.jsonindex 329b5b3caa..c7be377f71 100644--- a/turbo.json+++ b/turbo.json@@ -2,8 +2,9 @@"$schema": "https://turborepo.org/schema.json","tasks": {"build": {- "dependsOn": ["^build", "//#lingui:compile", "//#generate:mcp"],- "env": ["ASSETS_URL"],+ "dependsOn": ["^build", "//#lingui:compile"],+ "inputs": ["$TURBO_DEFAULT$", "!**/AGENTS.md", "!**/CLAUDE.md"],+ "env": ["ASSETS_URL", "VERCEL"],"outputs": ["dist/**","build/**",@@ -19,27 +20,30 @@"outputs": ["src/pdf/fonts.data.ts"]},"//#lingui:compile": {- "inputs": [- "lingui.config.js",- "apps/erp/app/**",- "apps/mes/app/**",- "packages/react/src/**",- "docs/content/src/glossary/**",- "packages/ee/src/workflows/**",- "packages/locale/locales/**/*.po"- ],+ "inputs": ["lingui.config.js", "packages/locale/locales/**/*.po"],"outputs": ["packages/locale/locales/**/*.mjs"]},+ "transit": {+ "dependsOn": ["^transit"],+ "inputs": ["$TURBO_DEFAULT$", "!**/AGENTS.md", "!**/CLAUDE.md"]+ },"test": {- "cache": false,- "dependsOn": ["^build", "//#generate:mcp"]+ "dependsOn": ["^build", "transit"],+ "inputs": ["$TURBO_DEFAULT$", "!**/AGENTS.md", "!**/CLAUDE.md"],+ "outputs": []},"typecheck": {- "cache": false,- "dependsOn": ["//#generate:mcp"]+ "dependsOn": ["transit"],+ "inputs": ["$TURBO_DEFAULT$", "!**/AGENTS.md", "!**/CLAUDE.md"],+ "outputs": [".react-router/types/**", ".source/**", "lib/*.generated.ts"]},"lint": {- "dependsOn": ["^build"],+ "inputs": [+ "$TURBO_DEFAULT$",+ "!**/AGENTS.md",+ "!**/CLAUDE.md",+ "$TURBO_ROOT$/biome.jsonc"+ ],"outputs": []},"dev": {@@ -74,12 +78,15 @@"outputs": []},"//#generate:mcp": {- "cache": false,"inputs": [- "apps/erp/app/modules/*/*.service.ts",- "apps/erp/app/modules/*/*.mcp.server.ts",- "apps/erp/app/modules/*/*.models.ts",+ "apps/erp/app/modules/**/*.ts",+ "apps/erp/app/types/**",+ "apps/erp/app/utils/**","apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts",+ "apps/erp/app/routes/api+/mcp+/lib/mcp-exposure.ts",+ "apps/erp/tsconfig.json",+ "packages/{api,database,documents,files,locale,logger,notifications,printing,utils}/src/**",+ "packages/database/supabase/functions/shared/**","scripts/generate-mcp.ts","scripts/lib/**"],