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
Merge remote-tracking branch 'origin/main' into feat/infinite-scroll
aashu2529fcbd3566
diff --cc .ai/specs/2026-10-13-infinite-scroll-tables.mdindex 36cfa2ce0d,0000000000..4afed2c697mode 100644,000000..100644--- a/.ai/specs/2026-10-13-infinite-scroll-tables.md+++ b/.ai/specs/2026-10-13-infinite-scroll-tables.md@@@ -1,498 -1,0 +1,499 @@@+# Infinite scroll for ERP list tables++> Status: in-progress+> Author: Aashu+> Date: 2026-10-13+> Research: `.ai/research/2026-10-13-infinite-scroll-tables.md`++## TL;DR++- Every paginated ERP list loads more rows as you scroll, on desktop and on phones. The pager goes away.+- Loaders change from offset paging (`?offset=`) to cursor paging (`?after=`, meaning "the rows after this one").+- The shared `<Table>` virtualizes its rows with `@tanstack/react-virtual`, so thousands of loaded rows still scroll smoothly.+- The next 100 rows start to load when the user is 600px from the bottom, so the user does not see a wait.+- "Select all matching" and CSV export work on every matching row. Up to 1,000 rows they run in the browser; above that, an Inngest job (one per company at a time) does the work.+- Footer totals stay as today (the rows on screen), with a label that says so.+- Filters, sorts, search, saved views, inline editing and the phone list keep working as today.++## Overview diagram++```mermaid+sequenceDiagram+ participant U as User+ participant T as Table (useInfiniteRows)+ participant L as Route loader+ participant DB as PostgREST+ U->>L: open /x/sales/orders?sort=…&filter=…+ L->>DB: first 100 rows + estimated count+ L-->>T: rows, count, nextCursor+ U->>T: scrolls to 600px from the bottom+ T->>L: fetcher.load(same URL + &after=nextCursor)+ L->>DB: keyset query: rows after the cursor, 100 rows+ L-->>T: rows, nextCursor+ T->>T: append rows, virtualizer renders only visible rows+```++## Problem Statement++1. Desktop lists show one page at a time (`PAGE_SIZES = [20, 100, 500, 1000]`). Each Prev/Next click is a GET navigation that re-runs every matched loader.+2. Offset paging gets slower on deep pages. The database reads and discards every row before the offset.+3. Offset paging shifts rows when a record is added or deleted between two requests. The user then sees a row twice or misses one.+4. The phone list has a stopgap "Load more" button (`CompactList.tsx:129-165`). It raises `?limit` up to 1000 and then falls back to Prev/Next.+5. The shared `<Table>` renders every row as a real `<Tr>` (`Table.tsx:1482-1590`). A page of 1000 rows is slow to render.++## Goals++- Infinite scroll on all ~130 paginated list pages that use the shared `<Table>`, on desktop and on phones.+- Infinite scroll on the 2 hand-paged tables: `SyncActivity.tsx` and `AccountLedgerDrawer.tsx`.+- Stable, fast paging at any depth (cursor paging).+- Smooth scrolling with thousands of loaded rows (row virtualization).+- No visible wait at the bottom of the list (prefetch at 600px).++## Non-goals++- MES. It has no paginated tables (`apps/mes/app/routes/x+/jobs.tsx` loads all open jobs).+- The 17 tables with `withPagination={false}` (wizards, grids, reports). They stay as they are.+- Small tables inside detail pages that use the plain `@carbon/react` `Table`.+- Server-side totals for footer rows.+- Sorting by a column of another table (see Decision 6).++## Proposed Solution++### 1. Cursor paging in the loaders++`getGenericQueryFilters` (`apps/erp/app/utils/query.ts:57-93`) reads a new `?after=` param. It stops reading `?offset=`. The param holds an opaque token: base64url JSON of the last row's sort values plus its `id`.++`setGenericQueryFilters` (`query.ts:157-203`) changes in 4 ways:++1. It adds `id` as the last sort key, so the order is always total. A list whose rows have no unique `id` passes its own key column.+2. If a cursor is present, it adds a keyset filter with `.or(…)`. For one sort column `c` (ascending) the filter is `c > v OR (c = v AND id > lastId)`. For more sort columns, the filter expands the same way.+3. It handles NULLs the way Postgres orders them: ascending puts NULLs last, descending puts NULLs first. A NULL cursor value uses `c IS NULL AND id > lastId`.+4. It replaces `.range(offset, …)` with `.limit(limit + 1)`. The extra row tells the loader that more rows exist.++A new helper `toPage(rows, args)` returns `{ rows, nextCursor }`. It drops the extra row and builds `nextCursor` from the last kept row, or returns `null` at the end.++The cursor reads the sort values from the returned row. So every sortable column must be in the list's select. In development, `toPage` throws if a sort column is missing from the row.++Values in the `.or()` string are quoted and escaped. Commas, parentheses and quotes in a value must not break the filter.++Counts: only the first request (no `?after=`) asks for `count: LIST_COUNT`. Later requests ask for no count.++### 2. Loader contract++Each list loader returns its rows, `count` (first page only), and `nextCursor`. The rows keep their current key (for example `salesOrders`). Example for `sales+/orders.tsx`:++```ts+// salesOrdersList (utils/list-registry/sales.server.ts) wraps getSalesOrders.+const page = await fetchListPage(salesOrdersList, client, companyId, searchParams);+return { salesOrders: page.rows, count: page.count, nextCursor: page.nextCursor };+```++The page size is fixed at 100. `?limit=` and `?offset=` are removed. Old bookmarks with `?offset=` or `?limit=` are ignored.++### 3. Shared Table: `useInfiniteRows`++The table component passes a new prop `infinite={{ dataKey: "salesOrders", nextCursor }}` to `<Table>`. A new hook `useInfiniteRows` inside the Table does this:++1. It starts with the loader's rows and `nextCursor`.+2. It calls `fetcher.load(pathname + search + "&after=" + cursor)` when the user is 600px from the bottom. It reads `fetcher.data[dataKey]` and appends the rows.+3. It runs one fetch at a time. It stops when `nextCursor` is `null`.+4. If a fetch fails, the list shows "Couldn't load more rows" with a Retry button.+5. If the reset key changes, it drops the loaded rows and starts again from the loader's first page. The reset key is the URL search without `after` and without the list's `ignoreParams` (Review fix A). So a filter, sort, search or saved view resets the list, and a drawer param does not.++The fetcher re-uses the route's own loader (Decision 3). No new API routes.++### 4. Row virtualization++The Table uses `useVirtualizer` on its existing scroll element `#table-container` (`Table.tsx:1264-1276`). It copies the `Grid.tsx` pattern:++- Spacer `<tr>` rows above and below the visible rows (`Grid.tsx:442-465`).+- `measureElement` for rows of different height (expanded rows, group headers).+- A `rangeExtractor` that keeps the selected cell's row mounted during inline editing (`Grid.tsx:390-403`).+- `overscan: 10`.++The sticky header, pinned columns and edge shadows stay as they are. The prefetch check uses the scroll element: `scrollHeight - scrollTop - clientHeight < 600`.++### 5. Phones++- `CompactList` drops its "Load more" button and its Prev/Next fallback. It uses the same `useInfiniteRows` hook and a virtualizer on the phone list's scroll element.+- The 9 tables with `mobileLayout="table"` behave like desktop.+- The phone keeps one scroll surface, the existing one (`.ai/lessons.md:1326-1336`).++### 6. Header row count++The `<Pagination>` bar, page-size dropdown and Prev/Next buttons go away. The ArrowLeft / ArrowRight pagination shortcuts go away. The table header shows the total:++- An exact number below 1,000 rows: "245 rows".+- At 1,000 rows or more, "about 2,300 rows" while `LIST_COUNT` (an estimate there) is all the page has, then the exact number ("2,317 rows"). A second request (`?count=exact`) gets it after page 1 shows, so the rows never wait for it.++### 7. Selection and "Select all matching"++- The Table sets `getRowId` to the row's `id`. Appending rows then never clears the selection (today it clears when `data.length` changes, `Table.tsx:383-387`).+- The header checkbox selects the loaded rows.+- If more rows exist, a bar shows "100 selected · Select all 2,345 matching". The selection then becomes "all rows that match the current URL filters", not a list of rows.+- Every bulk-action route that receives ids splits them into chunks of 100 for `.in()` (`.ai/lessons.md:2946-2958`).++The bulk action runs in one of 2 ways:++| Matching rows | How the action runs |+|---|---|+| 1,000 or fewer | The browser loads the remaining rows with the cursor loop (at most 10 requests of 100). Then it calls the action with full rows, as today (`renderActions(selectedRows)`). |+| More than 1,000 | The browser posts the action name, its value and the list's URL search to the action route. The route starts an Inngest job. Collect steps read the matching ids, at most 10,000 rows per step, and store each step's ids as one file in `temp-staging`. Apply steps then run the action on one slice of ids each, 100 ids per call. |++Rules for the background bulk action:++1. The job applies the same per-row checks as the browser does today. Example: Jobs Release acts only on Draft and Planned jobs (`JobsTable.tsx:757`). These checks move into the server code of each of the 15 bulk actions.+2. One background job runs per company at a time (Inngest concurrency key `companyId`, limit 1, and a Redis lock). A second request from the same company gets "A bulk action is already running for your company", with the latest time it ends.+3. The job runs with the requesting user's permissions and `companyId`. It never reads another company's rows.+4. When the job ends, the user gets a notification with the counts: done, skipped, failed.+5. Jobs Release and Batches Release run on at most 2,000 matching rows in the background. Each released job runs MRP. Past 2,000 rows the route refuses: "Filter the list to 2,000 rows or fewer" (Review fix D).++### 8. CSV export++Columns stay WYSIWYG: the visible columns in display order (`selectExportColumns`), with the translated headers.++| Matching rows | How the export runs |+|---|---|+| 1,000 or fewer | In the browser, as today. The browser loads the remaining rows with the cursor loop (at most 10 requests of 100). Each cell uses the on-screen format (`meta.exportValue`). |+| More than 1,000 | An Inngest job. The browser sends the list key, the URL search, the visible columns and their translated headers. Each job step reads at most 10,000 rows and writes them as one part file. A last step streams the parts into one CSV file in storage. Then the job sends the user a notification with a download link. |++Rules for the background export:++1. Cells hold the plain database values (for example `2026-10-13`, `1250.5`, the stored status). The on-screen format code runs in the browser, so the job cannot use it. One generic exporter serves every table.+2. The job never holds the whole file in memory. It reads 500 rows per query, and one part (at most 10,000 rows) is in memory at a time. The export stops at 100,000 rows or after the page that passes 200 MB.+3. One export job runs per company at a time (Inngest concurrency key `companyId`, limit 1, and a Redis lock). A second request from the same company gets "An export is already running for your company", with the latest time it ends.+4. The job runs as the requesting user, scoped to their `companyId`.+5. The decision between the 2 ways uses the header count. If the browser loop reaches 1,000 rows and more rows remain, it hands the export to the job.+6. The file belongs to the user who asked for it: `{companyId}/exports/{userId}/{exportId}.csv`. The download route `api+/table.export.$exportId` builds that key from the session and checks the list's permission again (Review fix D).++Accepted risk: background jobs run in the ERP containers (`apps/erp/app/routes/api+/inngest.ts`). Many companies can each run 1 big export at the same time, and those jobs share CPU with web requests. A separate worker container removes that risk; it is out of scope for now. The code puts a `// TODO(scale):` comment on the export and bulk-action Inngest functions that says this.++### 9. Footer totals++The 11 tables with `meta.renderTotal` keep their footer row, and it works as today: it totals the rows on screen, which are now the loaded rows (`aggregateForCol`, `Table.tsx:204-215`). The footer adds a label so the user knows the scope: "Total of 300 loaded rows". There is no "Total all" link.++### 10. Live updates (realtime)++`RouteRealtime` revalidates the loader, which returns only the first page. `useInfiniteRows` then re-fetches the remaining loaded pages in order with fresh cursors, and replaces them. The scroll position stays. Changed rows update in place, new rows appear, and deleted rows leave.++### 11. Back navigation++`useInfiniteRows` keeps the loaded rows, `nextCursor` and the scroll offset in memory, keyed by the company id, `dataKey` and the page URL key (Review fix A). On Back to the same URL, it restores them and scrolls to the same row. A page reload clears the memory. A realtime revalidation on return refreshes the restored rows (section 10).++### 12. The 2 hand-paged tables++- `SyncActivity.tsx` (page state plus `useFetcher`) switches to cursor paging and infinite scroll.+- `AccountLedgerDrawer.tsx` (`?offset=`/`?limit=` URL params) switches to cursor paging and infinite scroll inside the drawer.++### 13. Removal++After every list is converted, delete `usePagination`, `<Pagination>`, `PAGE_SIZES`, `getPageOffset`, `pageBounds` and the pagination shortcuts. Before deleting each one, confirm with a grep that it has no callers.++### Design Decisions++| # | Decision | Choice | Rationale |+|---|----------|--------|-----------|+| 1 | Virtualization library | `@tanstack/react-virtual` 3.13.23 | Already a dependency, used in 7 places, headless, ~5 kB. User decision. |+| 2 | Paging method | Cursor (keyset) paging | Stable under inserts and deletes, fast at any depth. User decision. |+| 3 | How the browser fetches the next page | `useFetcher` on the route's own loader with `?after=` | One place returns each list's rows; no 130 duplicate API routes. User decision. |+| 4 | When to prefetch | 600px from the bottom | The user does not feel a wait. User decision. |+| 5 | Page size | 100 rows, fixed | Matches `DEFAULT_PAGE_SIZE`. Below PostgREST `max_rows = 1000`. |+| 6 | Sort by another table's column (7 tables) | Turn off those sorts | No database change. User decision. |+| 7 | Row count in the header | Exact at any size: "about N" only until the exact count arrives | Users need the exact number of records. An exact count reads every matching row, so it runs in its own request after page 1 (`useExactCount`) instead of slowing page 1. User decision (revised). |+| 8 | Select all | Gmail-style "Select all N matching" bar, no cap. Exception: Jobs Release and Batches Release act on at most 2,000 rows in the background | User decision. The 2,000 cap: Review fix D, because each released job runs MRP. |+| 9 | Browser or server for "all matching" work | Browser up to 1,000 rows; Inngest job above 1,000 | Small lists stay instant. Journals and ledgers pass 10,000 rows (research file). User decision. |+| 10 | CSV export | All matching rows, visible columns only. Big exports hold plain DB values | The on-screen format code runs only in the browser. User decision. |+| 11 | Footer totals | As today: the rows on screen, with a "loaded rows" label | User decision. |+| 11a | Load on the database and servers | 1 background job per company at a time; accept the risk that many companies run jobs at once | A separate worker container fixes it later; marked with `TODO(scale)`. User decision. |+| 12 | Live updates | Refresh the loaded rows in place | User decision. |+| 13 | Back navigation | Restore rows and scroll position | User decision. |+| 14 | Scope | ~130 paginated lists + 2 hand-paged tables | User decision. Unpaginated tables and MES stay out. |+| 15 | Rollout | Core + 3 pilots (Sales Orders, Parts, Jobs), then module batches | User decision. Same branch. |+| 16 | Tie-breaker column | `id` by default, override per list | Keyset paging needs a total order. |+| 17 | Count on later pages | No count after the first page | Saves one estimate query per scroll. |+| 18 | Size of one job step | At most 10,000 rows (20 pages of 500) | The load balancer cuts a request at 600 s, and one step is one request. Review fix D. |+| 19 | Who can download a big export | Only the user who asked for it, through `api+/table.export.$exportId`, with the list's permission checked again | Review fix D. |++## Data Model Changes++None. No migrations. Decision 6 removes the 7 cross-table sorts instead of changing views.++## API / Service Changes++- `apps/erp/app/utils/query.ts`: `getGenericQueryFilters` reads `?after=`. `setGenericQueryFilters` adds the tie-breaker sort, the keyset filter and `.limit(limit + 1)`. New `toPage` helper. New cursor encode and decode functions.+- `apps/erp/app/utils/pagination.ts`: shrinks to the fixed page size, then goes away (section 13).+- ~130 route loaders under `apps/erp/app/routes/x+/` return `nextCursor` and drop `limit`/`offset`.+- Service functions keep their signature. They receive `cursor` instead of `offset` inside the generic filter args.+- Bulk-action routes for the 15 tables with `withSelectableRows` split id lists into chunks of 100. Each route also accepts "all matching" (the list's URL search) and then starts the background bulk-action job.+- The per-row checks of each bulk action (for example "only Draft and Planned jobs") move from the table component into the route's server code, so the browser path and the job path share them.+- New Inngest functions in `packages/jobs`: a table export job and a table bulk-action job, each with `concurrency: { key: "event.data.companyId", limit: 1 }`. `packages/jobs` cannot import `~/modules`, so the ERP app hands the jobs a dispatcher, like `setWorkflowDispatch` (`apps/erp/app/routes/api+/inngest.ts:34-47`).+- The export job writes the CSV to `temp-staging` at `{companyId}/exports/{userId}/{exportId}.csv` and notifies the user with a link to `api+/table.export.$exportId`.++## Closest Sibling++N/A for a record type. Code precedent:++- `Grid.tsx:384-465`: virtualizer, spacer rows and `rangeExtractor` in a TanStack table.+- `InfiniteScroll.tsx` with `$itemId.activity.tsx:237-321`: keyset cursor paging (`entryNumber`) with a load-more trigger.++## UI Changes++- List page archetype: no change to layout. The pager bar at the bottom goes away.+- Table header: row count ("245 rows" / "about 2,300 rows").+- A loading row at the bottom while the next page loads, and an error row with Retry.+- A selection bar with "Select all N matching".+- CSV export up to 1,000 rows downloads at once. Above 1,000 rows, a toast says "Your export is being prepared. We'll notify you when it's ready."+- A bulk action above 1,000 rows shows a toast "Running in the background. We'll notify you when it's done."+- Footer totals get a "Total of N loaded rows" label.+- Phone list: no "Load more" button; rows load as you scroll.+- All new copy uses Lingui (`t` / `Trans`), with plurals through `plural`.++## Acceptance Criteria++- [ ] On Sales Orders with 2,500 orders, scrolling to 600px from the bottom loads the next 100 rows. No pager shows.+- [ ] Scrolling through 2,500 rows on Sales Orders shows each order exactly once, in sort order, for each sortable column, ascending and descending.+- [ ] A sort on a column with NULL values (for example a blank due date) returns every row exactly once.+- [ ] A sort value (the cursor) with a comma, a parenthesis or a quote does not break the next-page request.+- [ ] Changing a filter, sort, search or saved view resets the list to the first 100 rows of the new result.+- [ ] With 2,000 rows loaded, only the visible rows (plus overscan) exist in the DOM.+- [ ] Inline editing on a table with `withInlineEditing` keeps the selected cell while the user scrolls far away and back.+- [ ] Pinned columns and the sticky header stay in place while rows load and scroll.+- [ ] On a phone (< 48rem), the compact list loads more rows on scroll, with no "Load more" button.+- [ ] The header shows "245 rows" for 245 rows. For 2,317 rows it shows "about 2,300 rows" at first, then "2,317 rows".+- [ ] On Jobs with 800 matching jobs, "Select all 800 matching" then Release releases every Draft and Planned job in the browser path.+- [ ] On Jobs with 3,000 matching jobs, "Select all 3,000 matching" then Release starts one background job. It releases only Draft and Planned jobs and notifies the user with the counts.+- [ ] CSV export of 800 matching rows downloads at once, with on-screen formatting and only the visible columns.+- [ ] CSV export of 12,000 matching rows starts a background job. The user gets a notification with a link, and the file has 12,000 data rows with plain database values.+- [ ] A second big export (or bulk action) from the same company while one runs gets the "already running" message. A big export from another company still starts.+- [ ] The background export never reads rows of another company.+- [ ] A footer total on Sales Orders reads "Total of 100 loaded rows" and grows as more rows load.+- [ ] Another user's edit to a loaded row on row 300 shows up without a scroll jump.+- [ ] Open row 400, press Back: rows 1–400 are still loaded and row 400 is in view.+- [ ] `SyncActivity` and `AccountLedgerDrawer` load more rows on scroll.+- [ ] The 7 cross-table sort columns no longer offer a sort.+- [ ] `pnpm exec turbo run typecheck --filter=erp`, Biome and the ERP unit tests pass. Cursor encode/decode and the keyset filter builder have unit tests.++## Verification status++None of the Acceptance Criteria above is browser-verified. This worktree had no running stack (decision "End-to-end check (Task 16)").++Unit tests cover the logic without a browser:++| Area | Tests |+|---|---|+| Cursor encode and decode, `keys`, offset tokens, keyset filter, `toPage` | `apps/erp/app/utils/cursor.test.ts`, `query.test.ts` |+| Registry merge, list select columns | `utils/list-registry/registry.test.ts`, `apps/erp/test/list-select-columns.test.ts` |+| Reset key, store, merge, edits overlay, virtual rows | `components/Table/infiniteRowsStore.test.ts`, `rowEdits.test.ts`, `useVirtualRows.test.ts`, `utils.test.ts` |+| Job ids, row limit, client factory | `apps/erp/app/utils/table-jobs.test.ts` |+| Job steps, lock, CSV, bulk counts | `packages/jobs/src/table-jobs/{run,lock,csv,bulk}.test.ts` |++The type and unit gates run in the final wave of the review fixes; record their result here.++Check in a browser after `crbn up`, in this order:++1. Every Acceptance Criterion above.+2. A drawer opened over a planning grid keeps the loaded rows (`ignoreParams`).+3. A star on a document past row 100 shows at once and stays.+4. A failed later page shows "Couldn't load more rows" with Retry.+5. A background export downloads through `api+/table.export.$exportId`. Another user of the company gets 404 for the same link.+6. "Select all" on more than 2,000 jobs, then Release, shows the 2,000-row refusal.++## Open Questions (resolved)++- [x] Which virtualization library? — **Answer:** TanStack Virtual. It is already installed and used, and it is headless.+- [x] Offset paging or cursor paging? — **Answer:** Cursor paging, because it works well with infinite scroll.+- [x] When to start the next fetch? — **Answer:** At 500–600px from the bottom. The spec uses 600px.+- [x] Reuse the route loader or add API routes? — **Answer:** Reuse the route loader (option A). New API routes would duplicate the loaders.+- [x] What replaces the pager's "1–100 of N"? — **Answer:** A row total in the table header.+- [x] Sorts by another table's column? — **Answer:** Turn off those sorts.+- [x] Row count wording? — **Answer:** Exact below 1,000, "about N" above. **Revised:** exact at any size; above 1,000 the exact count loads in a second request after page 1.+- [x] What does "select all" select? — **Answer:** Every matching row, through a Gmail-style "Select all N matching" bar.+- [x] What does CSV export download? — **Answer:** All matching rows. Columns stay WYSIWYG.+- [x] Load-all cap? — **Answer:** First 5,000 rows in the browser. Then changed: the research suggests journals pass 10,000 rows, so work above 1,000 rows moves to the server.+- [x] Can the server path become an attack surface? — **Answer:** Yes, if requests wait inside the server. Requests above 1,000 rows become Inngest jobs, 1 per company at a time. Many companies at once is an accepted risk until a separate worker container exists.+- [x] What do big exports contain? — **Answer:** Plain database values with the visible columns and translated headers.+- [x] How far does "select all matching" go? — **Answer:** No cap. Above 1,000 rows, the bulk action runs as an Inngest job.+- [x] Live updates while scrolled deep? — **Answer:** Refresh the loaded rows in place.+- [x] Back navigation? — **Answer:** Restore the same rows and scroll position.+- [x] Footer totals? — **Answer:** As today: total of the rows on screen, with a "loaded rows" label. No "Total all".+- [x] Scope? — **Answer:** All paginated lists plus the 2 hand-paged tables.+- [x] Rollout? — **Answer:** Core plus 3 pilots, then the rest in module batches.++## Autonomous Decisions++The user approved the spec, then asked for the whole pipeline (plan, build, test, review, fixes) to run without questions. The code research for the plan found facts the interview did not cover. Each decision below was made without the user. Review the high-stakes ones first.++### High-stakes++- [x] **A second big job from the same company** — **Autonomous:** The route takes a Redis lock (`SET key NX EX`) per company and job type before it starts the Inngest job. If the lock exists, the route answers "already running". If Redis is down (`redis.set` returns `null` and `redis.get` returns `null`), the route starts the job anyway: Inngest's per-company concurrency still runs the jobs one at a time. *(The lock is now a Lua script: Review fix D, "the lock".)* — Codebase rung: Inngest concurrency queues a second run, it never refuses it (`company-export.ts:363-370`); `@carbon/kv` returns `null` on failure (`packages/kv/src/resilient.ts`).+- [x] **Where big CSV files go** — **Autonomous:** The `temp-staging` bucket, under `{companyId}/exports/{jobId}.csv`. The download link is the existing `/file/preview/temp-staging/...` route. The nightly cleanup deletes the file after 7 days. *(Key and link replaced by Review fix D, "per-user export files".)* — Codebase rung: company buckets cap one file at 50 MB (`packages/files/src/storage.ts:36`); `temp-staging` allows 2.5 GB and the preview route already checks the `companyId` prefix (`file+/preview+/$bucket.$.tsx:69-90`).+- [x] **Row ceiling for one background export** — **Autonomous:** 100,000 rows. Above that, the job writes the first 100,000 rows and the notification says the file is cut. — Product judgement: the earlier chat named 100k as the guard; without a ceiling one export can run for a very long time on the shared containers.+- [x] **Which bulk actions get the background path** — **Autonomous:** Only the actions whose request is "ids + one field/value": item bulk update (Parts, Materials, Tools, Consumables, Services), Jobs Release, Jobs Delete, Purchase Order Delete, Batches Release and Dissolve, and user Deactivate / Send Invite / Edit Permissions. The planning tables (Order Parts, Create Jobs, Apply Suggested Changes) and Kanban Print Labels stay browser-only, capped at 1,000 selected rows. — Codebase rung: the planning payloads are built from browser state (drawer edits, time fence, supplier map: `PurchasingPlanningTable.tsx:349-421`); a PDF of thousands of labels is not a bulk action.+- [x] **Server-side checks that were browser-only** — **Autonomous:** Jobs Delete gets a server check for the `delete: production` permission and for the allowed statuses (Draft, Planned, Due Today, Overdue), plus a `companyId` filter on its status read. Purchase Order Delete gets a `companyId` filter and a Draft/Planned status check. — Spec rule 7.1: the job path must apply the same per-row checks; the research found these checks only in the browser (`job+/update.tsx:39-58`, `purchase-order+/update.tsx:26-31`).++### Other decisions++- [x] **Sort gates** — **Autonomous:** Both sort entry points (the header menu, `Table.tsx:1357-1361`, and the toolbar Sort picker, `Table/utils.ts:79-82`) skip any `accessorKey` that contains a `.` and any column with `enableSorting: false`. This turns off the 7 cross-table sorts (Decision 6). Jobs `orderQuantity` and `inventoryQuantity` get `enableSorting: false`: the `jobs` view has no such columns, so their sort fails today.+- [x] **Array sort columns (`tags`, `suppliers`)** — **Autonomous:** The keyset filter encodes an array value as a quoted Postgres array literal. If a unit test or a manual check shows PostgREST rejects it, the executor sets `enableSorting: false` on array columns instead and records it here.+- [x] **Custom field sorts (`customFields->>{id}`)** — **Autonomous:** The cursor reads the value from `row.customFields[id]` and compares it as text.+- [x] **Lists without a unique `id`** — **Autonomous:** `contractors` uses `supplierContactId`, `customFieldTables` uses `table`. The customer portal share page (`share+/customer.$id.tsx`, RPC without a row id) and the customer/supplier account lists (foreign default sort `user(lastName)`, no top-level `id` selected) keep a single load of up to 1,000 rows with no paging. They are small per company.+- [x] **Lists that do not page today** — **Autonomous:** `getCurrencies`, `getJobMaterialsWithQuantityOnHand`, `sync-tieout`, `invoicing+/_index` (a dashboard), `getPrintJobs` and `getGlobalAuditLog` keep their current loading. `getPrintJobs` and `getGlobalAuditLog` use their own offset paging (an RPC with `p_offset`); they get the infinite-scroll UI on top of offset requests, because their sources are outside `setGenericQueryFilters`.+- [x] **Revalidation cost** — **Autonomous:** A loader revalidation with the same URL search replaces the first page and re-fetches the other loaded pages one by one, up to 20 pages (2,000 rows). Rows past 2,000 are dropped and the cursor restarts from row 2,000. — The router re-runs the list loader on every drawer open and close (`defaultShouldRevalidate`), so an unbounded refresh would re-read every loaded row each time.+- [x] **Back-navigation memory** — **Autonomous:** A module-level `Map` (max 10 entries, oldest dropped first) keyed by `pathname + search`. *(Key replaced by Review fix A: company id + `dataKey` + page URL key.)* — The 3 pilot lists unmount when a record opens (`path.to.salesOrderDetails` is outside `sales+/orders`), so component state cannot hold it.+- [x] **Extra per-page data** — **Autonomous:** `infinite` takes an optional `onPage(data)` callback, so a table can merge per-page extras. Jobs uses it for `batchesByJobId`. *(Replaced by Review fix C: `mapRows` puts the extras on each row; `onPage` is gone. The other decisions below that name `onPage` are replaced the same way.)*+- [x] **Search escaping** — **Autonomous:** Out of scope. 49 services put the raw search into `.or()`; that bug exists today and is independent of paging. The acceptance criterion about commas now covers cursor values only. Recorded as a follow-up.+- [x] **Commits** — **Autonomous:** No commits. The user's standing rule forbids commits without permission; the work stays in the working tree for review.+- [x] **A page fetch whose loader throws** — **Autonomous:** The route's error screen shows, as for every fetcher in the app today. *(Replaced by Review fixes A and B: a failed later page returns `listError`, and the list shows "Couldn't load more rows".)* The inline "Couldn't load more rows" row with Retry shows when a request ends without a new rows array. — Codebase rung: React Router sends a fetcher's loader error to the nearest error boundary and drops the fetcher (`setFetcherError`, `react-router/dist/development/chunk-OB3PAWPO.mjs:3141`). A fetcher cannot catch it, and Decision 3 keeps the fetcher.+- [x] **The URL of the next page** — **Autonomous:** `useInfiniteRows` loads the list route's own URL from `useFormAction()`, not `location.pathname`. — Codebase rung: with a drawer open, `location.pathname` is the child route, whose loader has no rows. `useFormAction()` also adds `?index` for an index route (`chunk-OB3PAWPO.mjs:11027`), which `fetcher.load` needs to reach the index loader.+- [x] **Back-navigation restore** — **Autonomous:** The hook restores only on a Back/Forward (`POP`) navigation. Page 1 always comes fresh from the loader. The memory keeps the rows after page 1, their page count, the cursor and the scroll offset. The restored rows can be stale, so the hook fetches them again in the background with the revalidation rule (at most 20 pages). — Product judgement: a sidebar link click should open the list at the top; a record the user just edited must not show its old values after Back.+- [x] **The scroll offset for Back** — **Autonomous:** `useInfiniteRows` returns `rememberScrollTop(scrollTop)`. The Table calls it from its scroll listener. — Plan gap: the hook cannot read the scroll element on unmount, because React detaches the ref before the effect cleanup runs.+- [x] **A cursor that does not fit the sorts** — **Autonomous:** `setGenericQueryFilters` ignores a cursor whose value count differs from the sort count, and the request returns page 1. If every user sort is a cross-table sort (dropped by Decision 6), the default sorts apply. — Product judgement: only a hand-edited URL produces this, and an error screen helps nobody there.+- [x] **One virtual item per row** — **Autonomous:** Each virtual item is one `<tbody>` that holds the group header row, the data row and the expanded row. The virtualizer measures the `<tbody>`. `Row.tsx` and `rowMemo.ts` do not change. — Plan gap: a ref on the data row measures that row only, and a context-menu row gets no ref through `ContextMenuTrigger`. A table can hold many `<tbody>` elements.+- [x] **Row ids** — **Autonomous:** The Table keys rows by `id` only when every row has an `id` and no two rows share it (`hasUniqueRowIds`). Otherwise it keeps index keys, as before. — Product judgement: a list that repeats an id would break React keys and select two rows with one click.+- [x] **A new list query** — **Autonomous:** When the URL search changes (without `after`), the desktop table scrolls to the top and clears an uncontrolled selection. — Codebase rung: before, a new result set cleared the selection through the `data.length` effect and the pager scrolled to the top. With id keys, that effect no longer fires.+- [x] **Header count and footer label** — **Autonomous:** The header shows the row count where the condensed Prev/Next buttons were, only when `withPagination` is on and `count` is above 0. The footer label "Total of N loaded rows" shows only on a table with `infinite`. — Product judgement: a table without `infinite` has all its rows, and a table without a count would read "0 rows".+- [x] **The loading row** — **Autonomous:** While the next page loads, the row under the last row shows a spinner and "Loading more rows". The phone list shows a spinner above its footer text. — Plan step 7 named a spinner only; the text tells a screen reader user what happens.+- [x] **Phone list scroll element** — **Autonomous:** `CompactList` virtualizes against the nearest ancestor that scrolls and has content past its edge. On a page that is `<main>`. — Product judgement: a phone list in a drawer or a modal scrolls inside it. A virtualizer on `<main>` would never render the rows below the first view there.+- [x] **Phone group headers** — **Autonomous:** On phones, a group header is its own virtual item, and the range keeps the header above the first row in view rendered. So the header stays sticky while its rows scroll. — Plan step 5 says "keep group headers as they are". A header inside a per-row wrapper can only stick inside that wrapper.+- [x] **Phone footer text** — **Autonomous:** The phone footer "{n} of {count} rows" shows on every list with `withPagination` or `infinite`, also at the end of the list. An estimated count below the loaded rows shows the loaded number. — Product judgement: at the end of the list the footer is the only total on screen.+- [x] **Registry shape** — **Autonomous:** The registry is a folder, `utils/list-registry/`, with `index.server.ts` (types, `LIST_REGISTRY`, `getListDefinition`, `fetchListPage`) and one file per module. The files for every Task 12 batch exist from the start, and the index merges all of them. A loader imports its definition from the module file to keep the row type. — Parallel batches must not edit the same file. `fetchListPage` keeps each converted loader to one call that the jobs (Tasks 10 and 11) can share.+- [x] **Reference data on later pages** — **Autonomous:** When `?after=` is set, the Parts and Jobs loaders skip `tags` and `locations`. — Plan step 4: the Table reads a fetched page for its rows, `nextCursor` and `onPage` only. No component reads those keys from a fetched page.+- [x] **Jobs tracked entities** — **Autonomous:** `JobsTable` loads the tracked-entity labels of each page from `onPage` and merges them into one map. — Plan gap: the labels came from a browser query over page 1 only, so rows past 100 lost them.+- [x] **Lingui catalogs** — **Autonomous:** Tasks 4–7 add the strings through `Trans`, `Plural` and `t`, and a Vite compile of the 3 changed Table files shows no `@lingui/core` import. The `.po` catalogs are not extracted in these tasks. — `pnpm lingui:extract` rewrites 13 locale files; Task 16 runs it once after all batches, so parallel batches do not conflict on them.+- [x] **Browser check of the pilots (Task 6)** — **Autonomous:** Not run. This worktree has no running dev stack: `https://erp.infinite-scroll.dev/login` returns 502 from the portless proxy, and Docker has no container for this worktree. `crbn up` would create and migrate a new database, which this run must not do. Task 16 repeats the check. — Run rule: never touch the database.+- [x] **Loaders without `bypassRls` (Task 12d)** — **Autonomous:** If a list loader did not pass `bypassRls` before, it still does not. The loader calls `requirePermissions(request, xList.permission)`, and the permission keeps `role: "employee"`. This applies to 13 Items lists (change notices, the material property lists, item groups, units of measure and the 2 method lists). — Product judgement: recipe step 4 assumes every loader bypasses RLS. A switch to the service-role client changes who can read the rows, and paging needs no such change.+- [x] **Material dimensions unit system (Task 12d)** — **Autonomous:** The `material-dimensions` registry query reads `companySettings.useMetric` itself, on every page. — Codebase rung: the loader read it before the list query (`dimensions.tsx`). A background job calls the registry query without the loader, so the query must find the unit system on its own.+- [x] **Rows key `data` (Task 12d)** — **Autonomous:** The units of measure, change notice actions and change notice types loaders returned the raw service result. They now return `{ data, count, nextCursor }`, and the tables use `dataKey: "data"`. — Minimal change: the route components already read `data`.+- [x] **Purchasing Material Planning has no registry entry (Task 12b)** — **Autonomous:** `purchasing+/planning` pages with a cursor (`toPage` in the loader), but it has no `listKey`. Its export and bulk actions keep the 1,000-row browser path. — Codebase rung: the grid RPC needs the location that `resolveLocationId` reads from the user's defaults, and a registry query gets only the URL search. The spec already keeps the planning bulk actions browser-only.+- [x] **Planning rows and actions on later pages (Task 12b)** — **Autonomous:** `PurchasingPlanningTable` merges each later page's `items` and `planningActions` by item id through `onPage`. The supplier defaults, the order drawer and the bulk Order action then see every loaded row. A later page skips the `?item=` drawer-row read. — Plan step 8: the loader reads the actions of its own page only, so rows past 100 had no actions and no planned orders.+- [x] **Supplier contacts on later pages (Task 12b)** — **Autonomous:** The suppliers loader reads the report contacts of every page, and `SuppliersTable` merges them through `onPage`. A background export of more than 1,000 suppliers has no values for the 11 contact and address columns, because they are not columns of the `suppliers` view. — Plan step 8; the background export reads the registry rows only.+- [x] **Loaders without `bypassRls` (Task 12b)** — **Autonomous:** Supplier returns and leases keep the RLS client, by the Task 12d rule. Supplier types keeps `role: "employee"` and no column filters, as its loader had before.+- [x] **Loaders without `bypassRls` (Task 12a)** — **Autonomous:** RMAs, contracts, rental agreements, the price list, pricing rules, customer portals and the 4 reason and type lists keep the RLS client, by the Task 12d rule. The last 7 keep `role: "employee"`.+- [x] **Price list paging (Task 12a)** — **Autonomous:** The `price-list` registry query runs `resolvePriceList` with a customer or customer type in the URL, else `getBaseCatalog`, as the loader did. It reads `quantity` from the URL itself. The rows carry the item id as `itemId`, so the entry sets `idColumn: "itemId"`; the query still breaks ties on `item.id`. A later page skips the scope options. — Codebase rung: the services build each row from one `item` row (`itemId: item.id`).+- [x] **Sorts on computed columns (Task 12a)** — **Autonomous:** The 5 price list columns (Item, Item Group, Base Price, Resolved Price, Source) and the customer portal "Portal Link" column get `enableSorting: false`. — Codebase rung: the `item` table and `externalLink` have no such columns, so their sort fails today; the Jobs columns in "Sort gates" got the same fix.+- [x] **Select all past 1,000 rows without a `listKey` (Task 8)** — **Autonomous:** The bar offers "Select the first 1,000 rows". The browser loads and selects the first 1,000 rows. — Spec 7: browser-only lists cap the selection at 1,000 rows; the export uses the same cap.+- [x] **Rows loaded after "all matching" (Task 8)** — **Autonomous:** The Table selects each row that loads while every matching row is selected. A tick, an untick or "Clear selection" ends the "all matching" state. — Product judgement: an unticked row under "All matching rows selected" contradicts the bar.+- [x] **Select all on phones (Task 8)** — **Autonomous:** Phones get no new select-all control. The bar shows in selection mode when every loaded row is selected. — Standing rule: phone changes adapt the layout and add no features.+- [x] **The `allMatching` tooltip (Task 8)** — **Autonomous:** `useAllMatchingUnsupportedLabel()` (exported from `~/components/Table`) returns "Filter the list to 1,000 rows or fewer". A table whose action has no background path uses it. Until Task 11, Parts and Jobs ignore `allMatching` and act on the loaded rows only. — The plan puts the per-table handling in Task 11.+- [x] **When the export goes to the job (Task 9)** — **Autonomous:** 3 rules, in this order:+ 1. If the list has a `listKey` and the count is above 1,000, the browser posts to the export route at once.+ 2. Else the browser loads up to 1,000 rows. If rows remain and the list has a `listKey`, it posts to the route.+ 3. Else it downloads the first 1,000 rows and shows "Exported the first 1,000 rows."++ A list with every row loaded exports the table's own rows, so inline edits stay in the file. — Spec 8, rule 5: the loop hands the export to the job when rows remain after 1,000.+- [x] **The export request (Task 9)** — **Autonomous:** The browser posts with `fetch`, not a fetcher. The success toast needs `{ success: true }`. On an error the toast shows the route's `error` text, else "The export could not start. Try again." — Codebase rung: a fetcher action revalidates the list loader, which re-fetches every loaded page (`fetch` precedent: `SalesOrderLineForm.tsx:317`).+- [x] **Production lists with no registry entry (Task 12c)** — **Autonomous:** Production Material Planning, Demand Forecasts and the 4 job lists (events, operations, quantities, steps) page with a cursor (`toPage` in the loader), with no `listKey`. Their export and bulk actions keep the 1,000-row browser path. — Codebase rung: a registry query gets only the URL search. The job lists need the `jobId` route param, and the planning lists need the user's default location (same rule as Task 12b).+- [x] **Production planning rows and actions on later pages (Task 12c)** — **Autonomous:** `ProductionPlanningTable` merges each later page's `items` and `planningActions` by item id through `onPage`, and clears them when the page scope changes. A later page skips the `?item=` drawer-row read. — Same rule as Task 12b: the loader reads the actions of its own page only.+- [x] **Production events order (Task 12c)** — **Autonomous:** `getProductionEvents` no longer orders by `startTime` ahead of every sort. `startTime` ascending is now the first default sort, then `createdAt` descending, so a user sort replaces it. — Codebase rung: the cursor must follow every column of the ORDER BY. A fixed first order breaks it.+- [x] **Assembly instructions order (Task 12c)** — **Autonomous:** The default sort is `createdAt` descending, not `updatedAt` descending NULLS LAST. `getAssemblyInstructions` now applies the URL sorts and filters through `setGenericQueryFilters`; before, it ignored them. — Codebase rung: `DefaultSort` has no NULLS option, and a descending cursor puts NULLs first. Instructions never edited would then lead the list.+- [x] **Demand Forecasts count (Task 12c)** — **Autonomous:** The loader returns the RPC's count from the first page, not `data.length`. — Codebase rung: with paging, `data.length` is one page. Production planning already reads the count of the same kind of RPC.+- [x] **Batches sorts on computed columns (Task 12c)** — **Autonomous:** The Jobs and Quantity columns of `BatchesTable` (`memberCount`, `totalQuantity`) get `enableSorting: false`. — The loader computes them per page, so the table has no such column. Same rule as the Jobs `orderQuantity` sort.+- [x] **Loaders without `bypassRls` (Task 12c)** — **Autonomous:** Scrap reasons, procedures, assembly instructions and batches keep the RLS client, by the Task 12d rule. The scrap reasons loader keeps the rows key `data`, by the Task 12d rule.+- [x] **Loaders without `bypassRls` (Task 12g)** — **Autonomous:** All 12 quality lists keep the RLS client and `role: "employee"`, by the Task 12d rule. Gauge types, issue types and required actions keep the rows key `data`. — None of the quality loaders passed `bypassRls` before.+- [x] **Quality reference data on later pages (Task 12g)** — **Autonomous:** On `?after=`, the loaders skip the issue types (issues, actions), the required actions (actions), the gauge types and company settings (gauges, calibrations) and the tags (quality documents). — Plan step 6; the customers loader skips its statuses by the same rule.+- [x] **Inspection plans sort (Task 12g)** — **Autonomous:** `getInspectionDocuments` adds `drawingNumber` to each mapped row, and the plan "Name" column gets `enableSorting: false`. — Codebase rung: the service maps each row, so the cursor found no `drawingNumber` (the default sort). The `inspectionDocuments` view has no `name` column, so that sort fails today.+- [x] **Location-scoped inventory lists (Task 12e)** — **Autonomous:** Quantities, kanbans and stock transfers page with `toPage` in the loader and have no registry entry and no `listKey`. Their export and bulk actions keep the 1,000-row browser path. — Codebase rung: without `?location=`, the loaders read the location from the user's defaults, which a registry query cannot see (the Task 12b planning rule). Quantities pages through its RPC: PostgREST applies the keyset filter, the order and the limit to the rows of `get_inventory_quantities`.+- [x] **Storage units tree (Task 12e)** — **Autonomous:** The storage units list does not page. The loader reads up to 1,000 roots in one load, and `getStorageUnitSubtrees` reads their subtrees 100 root ids per request. — Codebase rung: the Table appends a later page's rows flat, outside their parents, and the tree builds its rows from `data`. The spec's "single load" rule covers lists that cannot page.+- [x] **Realtime by loaded ids (Task 12e)** — **Autonomous:** The receipts, shipments, warehouse transfers and inventory counts tables drop their `useRealtime(table, "id=in.(…)")` call. — Codebase rung: each route's `handle.realtime` already follows every row of that table in the company. The id filter named page 1 only, so it added nothing.+- [x] **Blind count sorts (Task 12e)** — **Autonomous:** While a count is blind, the count lines loader drops a sort on `systemQuantity` or `variance`, as it already drops a filter on them. — Product judgement: the next-page cursor holds the last row's sort values, so it would send the withheld quantity to the browser.+- [x] **Inventory reference data on later pages (Task 12e)** — **Autonomous:** On `?after=`, the loaders skip the option lists (quantities, count lines), the locations (inventory counts), the company settings (tracked entities) and the count summary and movements (count lines). Tracked entities read the shelf-life policies of each page, and `TrackedEntitiesTable` merges them through `onPage`. — Plan steps 6 and 8.+- [x] **Storage rules single load (Task 12e)** — **Autonomous:** `x+/inventory+/storage-rules` passes `cursor: null` in place of `offset: 0`. It still reads up to 1,000 rules in one load. — The batch table does not list it, but it is in the module's folder and failed typecheck on the removed `offset`.+- [x] **Loaders without `bypassRls` (Task 12f)** — **Autonomous:** All 7 invoicing lists and all 11 accounting lists keep the RLS client, by the Task 12d rule. The accounting lists keep `role: "employee"`.+- [x] **Realtime by loaded ids (Task 12f)** — **Autonomous:** The sales invoice and purchase invoice tables drop their `useRealtime(table, "id=in.(…)")` call, as in Task 12e. No id list is built, so the `.in()` bound in `.ai/lessons.md` does not apply. — Codebase rung: `handle.realtime` on `invoicing+/sales` and `invoicing+/purchasing` follows every row of the table (`RouteRealtime` adds a string entry with no filter). A change reloads page 1, and the Table then fetches the loaded pages again.+- [x] **Group-scoped accounting lists (Task 12f)** — **Autonomous:** The `accounting-dimensions` and `intercompany-transactions` registry queries read `company.companyGroupId` for the company, then call the service with the group. — Codebase rung: a registry query gets the company only; `invoicing.service.ts` reads the group with the same `company` select.+- [x] **Period runs (Task 12f)** — **Autonomous:** Revenue recognition runs and lease runs are 2 registry entries on one query factory. `loadPeriodRuns` picks the entry by run type from `periodRunsLists`. `getRevenueRecognitionRuns` and `getDepreciationRuns` add `createdAt` to their selects. — Codebase rung: both default sorts are `createdAt`, so the cursor found no value.+- [x] **Intercompany company sorts (Task 12f)** — **Autonomous:** The Source and Target columns get `enableSorting: false`. — Codebase rung: `sourceCompany` and `targetCompany` are embedded companies, not columns of `intercompanyTransaction`, so their sort fails today.+- [x] **Accounting reference data on later pages (Task 12f)** — **Autonomous:** On `?after=`, fixed assets and fleet skip the asset class reads, and asset classes skips the company settings. Depreciation runs and the period runs keep their one-row "last run" read. — Plan step 6. The last run decides the next period, and it is one row.+- [x] **Invoicing dashboard (Task 12f)** — **Autonomous:** `invoicing+/_index` passes `cursor: null` and keeps the first 6 payments. — Codebase rung: `setGenericQueryFilters` reads `limit + 1` rows for the next-page check.+- [x] **Loaders without `bypassRls` (Task 12h)** — **Autonomous:** Attributes, timecards, employee types, groups, abilities, failure modes, both maintenance lists, training, the 4 settings lists, documents and both workflow lists keep the RLS client, by the Task 12d rule.+- [x] **Groups and partners single load (Task 12h)** — **Autonomous:** `users+/groups` and `resources+/partners` load up to 1,000 rows once, with no registry entry and no next page. — Codebase rung: groups build a tree with `arrayToTree`, and a page cut splits a group from its parent. A partner has one row per ability (primary key `id` + `abilityId`), so `id` cannot break ties.+- [x] **Sales rules and other single loads (Task 12h)** — **Autonomous:** `sales+/sales-rules`, `settings+/serial-numbers.new` and `resources+/assignments.$trainingId` pass `cursor: null` in place of `offset: 0` and keep their single load. Sales rules gets no registry entry: `SalesRulesGroups` is not a `<Table>`, so no `listKey` reads it. Its plan gate does not change. — The same fix as storage rules (Task 12e).+- [x] **Training assignment status (Task 12h)** — **Autonomous:** `getTrainingAssignmentStatus` cuts its in-memory rows at `limit` from row 0. — Codebase rung: the RPC returns every row, `GenericQueryFilters` has no `offset`, and both callers read one list.+- [x] **Recent documents (Task 12h)** — **Autonomous:** The "Recent" view is its own registry entry, `recent-documents`, with the default sorts `lastActivityAt` descending, then `favorite`. A sort the user picks replaces both. The loader picks the entry from `?q=`, and `DocumentsTable` gets the key as a prop. — Codebase rung: `getDocuments` put the `lastActivityAt` order before `setGenericQueryFilters`, so the cursor did not follow it. A registry entry has one fixed `defaultSorts`.+- [x] **Maintenance location (Task 12h)** — **Autonomous:** The 2 maintenance registry queries read `?location=` and fall back to the company's first location, as the loaders did. The loaders set the resolved location on the params they pass to `fetchListPage`. — The Task 12d material dimensions rule: a background job calls the query without the loader.+- [x] **API key hash (Task 12h)** — **Autonomous:** The `api-keys` registry query drops `keyHash` from every row, so an export never holds it. `ApiKeysTable` types its rows without the hash. — The loader dropped it before; the registry query is now the one place that reads the rows.+- [x] **Per-page extras (Task 12h)** — **Autonomous:** `WorkflowsTable` merges the version numbers and last runs of each later page through `onPage`. Workflow runs and documents compute the record names and download tokens per page in the loader, so each row carries its own. On `?after=`, the loaders skip the tags, the option lists, the invites, the MFA users, the document labels and file types, and the webhook config. — Plan steps 6 and 8.+- [x] **Optimistic document rows (Task 12h)** — **Autonomous:** *(Corrected by Review fix C.)* The first version skipped a row past page 1, and no revalidation followed, so a star or a label on such a row never showed. Now `DocumentsTable` lays each star and label change over every loaded row with the edit overlay (`applyRowEdits`). The change stays until its write ends. Then the table revalidates, and a load that starts after the write drops the change. See "Review fix C: Documents keeps the user's changes".+- [x] **Sync Activity pages (Task 13)** — **Autonomous:** The tab loads 100 rows per page, newest first, `id` ascending on ties. The integration loader reads page 1. A new resource route, `api+/integrations.$id.sync-activity`, reads each later page. A revalidation re-reads the loaded rows in one request, up to 2,000 rows. *(Replaced by Review fix C: Sync Activity pages through `pageUrl`, one page per request.)* `getSyncOperations` (`@carbon/ee`) gets an optional `after` keyset and the `id` tie-break, the same keyset as `getSyncOperationsExportPage`. The `syncPage` param is gone. — Codebase rung: the integration loader calls the provider (`listChartOfAccounts`), so a scroll must not re-run it.+- [x] **Account ledger drawer (Task 13)** — **Autonomous:** `getAccountLedger` pages with a cursor through `setGenericQueryFilters` and `ACCOUNT_LEDGER_DEFAULT_SORTS` (posting date, then entry, both descending). Lines of one entry now tie-break on `id` ascending, not descending. The 4 drawer routes read 100 lines per page (before: 50) and skip the summary on `?after=`. The drawer loads more through `useInfiniteRows` when its body scrolls to the end. — Codebase rung: the keyset filter compares the id ascending only.+- [x] **Print jobs and audit log (Task 13)** — **Autonomous:** Both loaders keep their offset sources and read 101 rows. The `after` token is `{ values: [], id: "<next offset>" }`. Neither list has a registry entry, so export and bulk actions keep the 1,000-row browser path. The audit log RPC still counts every page: `@carbon/ee` stays unchanged. — Spec decision "Lists that do not page today".+- [x] **Single-load lists (Task 13)** — **Autonomous:** The customer and supplier account lists and the customer portal share page load up to 1,000 rows and pass no `infinite`. Before, each showed its first 100 rows only. `getExternalSalesOrderLines` passes `idColumn: "salesOrderId"`. — Codebase rung: the RPC returns no `id`, so the default `id` tie-break would fail. A table without `infinite` holds all its rows (decision "Header count and footer label").+- [x] **Contractors and custom fields (Task 13)** — **Autonomous:** Both lists are registered with their `idColumn` and key their rows by it (`getRowId`). `getContractors` now reads the count; before, the list's count was always 0. The custom fields loader now throws its error redirect; before, it built the redirect and dropped it.+- [x] **Job leftovers (Task 13)** — **Autonomous:** `$jobId.materials` passes `cursor`, which `getJobMaterialsWithQuantityOnHand` ignores, so the page still loads every material. `job+/new` passes `cursor: null` and keeps the first 100 assets under construction. — Keep behavior.+- [x] **Which client the table jobs read with (Task 10)** — **Autonomous:** Every table job reads its list as the requesting user (`getUserScopedClient`), also for lists whose loader bypasses RLS. `ListDefinition` gets no RLS flag. — Spec 8.4 says the job runs as the user. A service-role read would rely on each list query to filter by `companyId`, and the queries of the RLS-client lists were not written for that. Risk: a list whose RLS is stricter than its permission exports fewer rows than the screen shows.+- [x] **The job's permission check (Task 10)** — **Autonomous:** The job reads the user's claims as the user (`get_claims`, the `readOwnerPermissions` pattern) and requires the employee role plus the list's permission. The route requires the same through `requirePermissions`. — Codebase rung: `getUserClaims` reads through a cache that can hold a revoked permission for an hour (`owner.ts`).+- [x] **Export page size (Task 10)** — **Autonomous:** The job reads 500 rows per query, not 1,000. — Codebase rung: the list query asks for `limit + 1` rows (`query.ts`), and PostgREST caps a response at `max_rows = 1000` (`config.toml`). A limit of 1,000 gets 1,000 rows back, so `toPage` sees no next page and the export stops at row 1,000. Task 11 must use the same limit.+- [x] **Export upload (Task 10)** — **Autonomous:** The job pages into a temp file, then reads the file into a Buffer and uploads it. *(Replaced by Review fix D: part files and a streamed upload.)* — `storage-js` accepts a Node stream, but no code in this repo uploads a stream, and no running stack was available to prove one against Storage. The 100,000-row ceiling bounds the Buffer.+- [x] **Lock value and release (Task 10)** — **Autonomous:** The lock value is the export id, not the user id. The job deletes the lock only while it still holds that id, in its last step and in `onFailure`. If `trigger` fails, the route deletes the lock. — A lock that expired after one hour and was taken by the next export must not be deleted by the first one.+- [x] **Export notifications (Task 10)** — **Autonomous:** `NotificationEvent.TableExport` (topic General) goes in-app and by email when the file is ready. The text comes from the payload, like `IntegrationSync`, in English, like every notification built in `content.ts`. A refused or failed export goes in-app only, with documentId `failed:{exportId}`, and its row opens the home page. A ready export's row downloads the file with a full page request (`reloadDocument`): the preview route is a resource route. — Product judgement: an email for a failure would carry a download button with no file behind it.+- [x] **Who can open an export file (Task 10)** — **Autonomous:** Any employee of the company who has the link. *(Replaced by Review fix D: the user who asked for it only.)* The preview route checks the employee role and the `{companyId}/` prefix only. The export id is a `nanoid`, so nobody guesses a link. The daily cleanup (cron `0 7 * * *`) deletes the file after 7 days: it is in no `modelUpload` row (`cleanup.ts`, "prune-staged-raw-models").+- [x] **The bulk job reads every id first (Task 11)** — **Autonomous:** The job reads all matching ids (500 per query, at most 100,000, duplicates dropped) before it acts. *(Steps replaced by Review fix D: collect steps of 10,000 rows, ids stored in `temp-staging`.)* Then it runs the action 100 ids at a time. Past 100,000 rows the notification says that only the first 100,000 were processed. — Product judgement: an update moves `updatedAt`, so on a list sorted by `updatedAt` an updated row lands behind the cursor and the job would read it again without end. The 100,000 ceiling is the export's.+- [x] **No retry for the bulk job (Task 11)** — **Autonomous:** `table-bulk-action` has `retries: 0`. A chunk that throws counts as `failed` and the run goes on. — A retry runs every chunk again, and Send Invite would email each user twice.+- [x] **Where the production bulk actions live (Task 11)** — **Autonomous:** `bulkReleaseJobs`, `bulkDeleteJobs`, `bulkReleaseBatches` and `bulkDissolveBatches` are in `modules/production/bulk-actions.server.ts`, not `production.server.ts`. Items and purchasing use their `{module}.server.ts`. — Codebase rung: `job+/release.test.ts` replaces `releaseJobs` in `production.server.ts`, and a module cannot replace its own internal calls. The module already has other `.server.ts` files (`forecast.server.ts`).+- [x] **Rows an action may not act on (Task 11)** — **Autonomous:** On both paths the server skips them and counts them as `skipped`: a job that is not Draft / Planned / Due Today / Overdue (Delete) or Draft / Planned (Release), a purchase order that is not Draft / Planned, a batch that is not Planned (Release) or Planned / Active (Dissolve), and an id of another company. The small path answers success for the rest, as Jobs Release did for a stale selection. Purchase Order Delete also requires `delete: purchasing` on the server, as the table did. Batch Dissolve now skips a Completing or Completed batch; before, the server function refused it and the toast named it as failed. — Spec rule 7.1; codebase rung: `job+/release.tsx` skipped a stale selection silently.+- [x] **Bulk action notification (Task 11)** — **Autonomous:** `NotificationEvent.TableBulkAction` (topic General), in-app only. The title holds the action and the 3 counts ("Release jobs finished: 1,200 done, 3 skipped, 0 failed"); the row opens the home page. — The topbar shows the title only, and a run has no file or record to link to.+- [x] **User bulk actions (Task 11)** — **Autonomous:** For Deactivate, Send Invite and Edit Permissions, "done" means queued: the job queues the existing `user-admin` and `update-permissions` jobs. The job picks the users with `canBulkActOnUser` (`users.models.ts`), the rule the table applies to its selection, and reads them with the service role scoped to the company, as the routes do. With `allMatching`, the modal posts through a fetcher that `EmployeesTable` owns, and the route answers `{ background: true }` instead of a redirect. — Codebase rung: the modals close on submit, and an unmounted fetcher never reports its result. The toast text needs Lingui, so it cannot be a flash message.+- [x] **Planning and Kanban bulk actions (Task 11)** — **Autonomous:** No change. These tables have no `listKey`, and the Table sets `allMatching` only for a list with a `listKey` (`Table.tsx:718`), so their actions never see it. — Minimal change: a disabled state for a value that cannot occur is dead code.+- [x] **Item bulk update writes (Task 11)** — **Autonomous:** `bulkUpdateItems` sets the item posting group with one read, one update and one insert per 100 items. Before, the route made 2 queries per item. Jobs Release schedules each location once per chunk of 100 jobs in the background job. — `AGENTS.md`: never query inside a loop. A per-chunk schedule keeps `runBulkAction` one call per chunk.+- [x] **`MAX_PAGE_SIZE` callers (Task 14)** — **Autonomous:** `users+/groups` and `resources+/partners` pass `limit: 1000`, as `storage-rules` and `sales-rules` do. `utils/pagination.ts` keeps `PAGE_SIZE` only. — Plan step 1 deletes `MAX_PAGE_SIZE`, and these 2 single loads were its last callers.+- [x] **Old `offset` resets (Task 14)** — **Autonomous:** `SearchFilter`, the count lines quick filters and the 3 ledger openers (chart of accounts, trial balance, multi-period statements) no longer delete `offset` or `limit` from the URL. `revalidateIgnoringOffset` drops its `offset` handling and becomes `revalidateOnSearchChange` in its 5 routes (4 reports and the chart of accounts). — Codebase rung: no list or drawer writes `?offset=` now (Task 13 moved the ledger drawer to a cursor), and `?after=` never enters the page URL. The old name described a param that no longer exists.+- [x] **Keyboard shortcuts page (Task 14)** — **Autonomous:** `docs/content/docs/reference/keyboard-shortcuts.mdx` drops the ← / → page keys, and its section is now "From a list page". — `keep-sources-in-sync.md`: a user-facing doc must not describe a removed shortcut.+- [x] **Where the paging guide lives (Task 15)** — **Autonomous:** A new rule, `.claude/rules/table-infinite-scroll.md`, with `paths:` on the Table, `query.ts`, `cursor.ts`, the registry and `routes/x+/**`. The root `AGENTS.md` Task Router links it. — Codebase rung: `apps/erp/AGENTS.md` does not exist (plan step 3), and a rule auto-loads where loaders are written. `packages/query/AGENTS.md` names no pager or offset, so it does not change.+- [x] **MCP and v1 API paging (Task 16)** — **Autonomous:** `GenericQueryFilters` keeps an optional `offset`. `setGenericQueryFilters` uses cursor paging (`limit + 1`) when the args carry a `cursor` key, and exact offset paging (`.range`) otherwise. — The MCP generator publishes `limit` + `offset` for every `GenericQueryFilters` service (`scripts/lib/service-metadata.ts`), and `dispatch-parity.test.ts` failed: without this, MCP and agent callers would get page 1 for every offset. `getAccountLedger` takes an optional `cursor` (typed `Cursor`) and `offset` for the same reason.+- [x] **End-to-end check (Task 16)** — **Autonomous:** Not run. This worktree has no running stack, and `crbn up` would create and migrate a new database (AGENTS.md: wait for the user before rebuilding a database). The only other running stack (`carbon-feat-active-pieces-integration`) has a corrupted database: PostgREST logs `missing chunk number 0 for toast value 99130 in pg_toast_2619`. Run `crbn up` in this worktree, then walk the Acceptance Criteria.+- [x] **Review fix A: drawer params keep the list (B4)** — **Autonomous:** `InfiniteOptions.ignoreParams` names the URL params that do not define the list. `getSearchKey` drops them with `after`, so the reset key, the Back store key and the selection ignore them. `useInfiniteRows` returns `resetKey`, and the Table reads it instead of deriving its own.+- [x] **Review fix A: failed later page (B7, client)** — **Autonomous:** A loader returns `listError` (a string) next to its rows key for a failed `?after=` page (`InfiniteListError`, `components/Table/types.ts`). `readPage` reads it as an error, so the list shows "Couldn't load more rows" with Retry. `readPage` also ends the list when `nextCursor` equals the cursor it requested (R1 client guard).+- [x] **Review fix A: Back store per company (B8, R13)** — **Autonomous:** The store key is company id + `dataKey` + page URL key. The company id comes from the authenticated root route data (`useRouteData`), not `useUser()`, which throws outside `/x`. The first store read or write with another company empties the store. A save keeps at most 19 later pages (20 with page 1), the same cap a revalidation re-reads. The rows on screen are never cut. The restored scroll offset stops at the end of the content.+- [x] **Review fix A: edits overlay (B9)** — **Autonomous:** The Table keeps `edits` (row id → edited values and a tick) in place of the `internalData` copy. A logical clock (`tick()`, `rowEdits.ts`) orders edits and loads. `useInfiniteRows.syncedAt` is the tick when the current rows started to load: a new page 1 when no later page is loaded, else the start of the last refresh. An edit before `syncedAt`, or one the row already holds, is dropped. An append does not move `syncedAt`, so it keeps every edit. A table without `infinite` gets a new `syncedAt` with each new `data`, so it drops edits as the old copy did. The values are keyed by column id, not `Partial<T>`, because a nested editable column uses a `a_b` path.+- [x] **Review fix A: one scroll mechanism (C5, R12, R14)** — **Autonomous:** `useInfiniteScroll` observes a sentinel after the rows with an IntersectionObserver (root = the scroll element, `rootMargin: "0px 0px 600px 0px"`). It loads again after each page while the sentinel stays in range, so a short list fills the view. It also remembers the offset for Back, restores it, and scrolls to the top on a new `resetKey`. `isNearEnd` is gone. The Table, the phone list and the account ledger drawer (root "auto": the nearest scrolling ancestor) use it. A `loadMore` during a refresh waits and runs when the task queue is empty. The phone list finds its scroll element again on each resize of the list.+- [x] **Review fix A: shared virtual rows and select-all (C6, C7, C8)** — **Autonomous:** `useVirtualRows` (virtualizer, kept index, spacer slots) serves the Table, the phone list and the Grid. `useSelectAllMatching` derives "all matching" from the choice, the list key and the selection it was made over: a new selection or a new list ends it, with no effect. `useInfiniteRows` has one ref for the latest render's values, one failed-task state and one `isStale` guard.+- [x] **Review fix A: new API for the other waves** — **Autonomous:** `InfiniteOptions.pageUrl` (default `useFormAction()`) lets an `api+` loader serve the pages. `InfiniteOptions.idColumn` keys and de-duplicates rows with no unique `id`. A parent may call `useInfiniteRows` itself and pass the result as `<Table infiniteRows={…}>`; the Table then runs its own hook with infinite scroll off. `loadAll` returns the `resetKey` at its end: the CSV download and "Select all" compare it with the key at the start and stop when the list changed (R15). `EXACT_COUNT_LIMIT` (1,000) replaces the bare `1000` in the row count copy; the "first 1,000 rows" copy takes the number as a value.+- [x] **Review fix D: the table jobs run in steps (B1)** — **Autonomous:** One step reads at most 20 pages of 500 rows (`TABLE_JOB_ROWS_PER_STEP`, 10,000). The export writes one part file per step and a last `compose` step streams the parts into the file. The bulk job stores the ids of each collect step in one file and then runs one apply step per slice. A step returns counts and the next cursor only, and the function sums them outside the steps. — The load balancer cuts a request at 600 s (`sst.config.ts`), and one step is one request. 20 queries stay well below that on a slow view. This replaces the decisions "The bulk job reads every id first" (one step) and "Export upload" (one Buffer).+- [x] **Review fix D: where the bulk ids live (B1)** — **Autonomous:** In `temp-staging`, at `{companyId}/bulk-actions/{runId}/{n}.json`, not in Redis. The job deletes them at the end; the nightly cleanup is the backstop. If an apply step cannot read its file, it counts the slice as failed and the run goes on. — A Redis key with a TTL can be evicted under memory pressure, and the run would then act on nothing without an error.+- [x] **Review fix D: duplicate ids across steps** — **Autonomous:** A collect step drops duplicate ids within its own pages only. A row can appear in two steps only when its sort value changes during the collection. Every action checks the row's status again, so a repeat is skipped or writes the same value. Send Invite can then email a user twice. — An exact check across steps needs every earlier id in each step.+- [x] **Review fix D: ids per apply step** — **Autonomous:** 1,000 by default, 100 per call. Jobs Release takes 25 per step and Batches Release 10, because each job runs the requirements recalculation and MRP. Batches Dissolve takes 100. The route sends `maxRows` and `idsPerStep` on the event (`BULK_ACTIONS`, `utils/table-jobs.ts`). — Product judgement: no measured MRP time was available; these keep a step far below 600 s for a run of one minute per job.+- [x] **Review fix D: 2,000-row limit for the two releases (B1)** — **Autonomous:** The route reads the list's header count (exact up to 1,000, an estimate above) and refuses past 2,000: "Release jobs runs on at most 2,000 rows. Filter the list to 2,000 rows or fewer." The job also stops at 2,000 rows and says so. In the menu, the disabled item shows "Filter the list to 2,000 rows or fewer" as its second line (`useAllMatchingLimitLabel`), because a disabled item takes no pointer events, so a tooltip cannot show. — The count is an estimate, so both checks are needed.+- [x] **Review fix D: the lock (R9)** — **Autonomous:** Take, release and extend are each one Lua script (`packages/jobs/src/table-jobs/lock.ts`): SET NX EX with the remaining TTL on refusal, compare-and-delete, compare-and-expire. Each step of a running job sets the TTL back to one hour. The 409 says "at the latest in N minutes" from the TTL. When Redis answers nothing, the route still starts the job (fail-open, as before). — A long run must not lose its lock to the next request.+- [x] **Review fix D: a new user token every four minutes (B2)** — **Autonomous:** The job passes a client factory (`refreshingClientFactory`, `utils/table-jobs.ts`) that signs a new token when the last is four minutes old. Jobs Release, Batches Release and Batches Dissolve ask it for the client before each row; the other actions ask once per chunk. The action routes pass the request's client. — A token lives five minutes, and a chunk of releases can run longer.+- [x] **Review fix D: per-user export files (R6)** — **Autonomous:** The file is `{companyId}/exports/{userId}/{exportId}.csv`, and the export id is `{listKey}.{random}`. `api+/table.export.$exportId.ts` builds the key from the session, so a user reaches their own exports only, and it requires the list's permission again. The notification links there. The general preview route still serves `temp-staging` under the company prefix, but no link names an export key any more. That route was outside this fix and is not changed. — The list key in the id lets the route check the permission with no second store; changing it names a file that does not exist. This replaces the decision "Who can open an export file".+- [x] **Review fix D: the export upload streams (R7)** — **Autonomous:** `compose` uploads a `ReadableStream` that downloads one part at a time. storage-js 2.117.2 sends a stream as a chunked body with `duplex: "half"`; a local HTTP server received the exact bytes. Supabase Storage itself was not exercised (no running stack). The export also stops after the page that passes 200 MB (`MAX_EXPORT_BYTES`). — A part holds at most 10,000 rows in memory.+- [x] **Review fix D: one notification per outcome (R10)** — **Autonomous:** `notifyTableJobUser` sends `notify` with an event id per run and outcome (`table-export:{id}:ready`, `:failed`, `:denied`). Inngest drops a second event with the same id for 24 hours, so a retried step does not notify twice.+- [x] **Review fix D: one bulk delete (C10, R8)** — **Autonomous:** `bulkDeleteByStatus` (`utils/bulk-delete.server.ts`) deletes 100 ids per request with the company and the allowed statuses in the DELETE itself and `.select("id")`. Deleted = the rows the database returned; skipped = the rest of the chunk. The purchase order statuses come from the enum filtered by `isPurchaseOrderBulkDeletable`. — One statement per chunk, and a row whose status changed after the selection stays.+- [x] **Review fix D: one answer shape for "every matching row" (C11)** — **Autonomous:** Every bulk route answers `{ success: true, background: true }` or `{ success: false, message }` (`BulkActionStart`) through `startAllMatchingBulkAction`. The three form routes add `data` and `error` (`bulkStartFormResponse`), because about 20 property panels type their fetcher with the items update action and read `error`. The tables use `useBulkFormAction`, `useBulkStartToast` and `bulkSelectionBody` / `appendBulkSelection`. The bulk action metadata (`BULK_ACTIONS`) is in the pure `utils/table-jobs.ts`; what each action does stays in `table-jobs.server.ts`.+- [x] **Review fix D: the handler interface stays as it is (C9)** — **Autonomous:** `canReadList` and `canRunBulkAction` stay two methods. The shared parts moved to `packages/jobs/src/table-jobs/` (`paging.ts`, `lock.ts`, `notify.ts`, `storage.ts`, `export-run.ts`, `bulk-run.ts`). — One `authorize(kind, payload)` method would hide the same two checks behind a union and delete no code.+- [x] **Review fix D: one notification target (C12)** — **Autonomous:** `notificationTarget` (`utils/notification-target.ts`) serves the topbar row and `api+/link.ts`. Three targets changed: Stock Transfer Assignment opens the stock transfer (the topbar opened a sales order of that id); an email link for Integration Sync opens the integration page (it opened the home page); an approval with no document type opens the purchase order in both. The job pages use the `…Details` routes. Jobs Projected Late keeps no topbar row (it had none), but its email link still opens the job.+- [x] **Review fix D: item bulk update reports partial work (R11, C13)** — **Autonomous:** `bulkUpdateItems` moved to `modules/items/bulk-actions.server.ts` (logger `items-bulk-actions`). It first reads the ids under the company, so the `itemCost` insert names only the company's items and an unknown id counts as skipped. If a chunk fails after others committed, the route answers the error with `done` and `failed`, and the toast says "Updated N. Could not update M: …".+- [x] **Review fix D: Edit Permissions re-checks the plan in the job** — **Autonomous:** `canRunBulkAction` also calls `companyHasFeature` for an action with a `feature` (`users.permissions` → `PERMISSIONS`), with the service-role client. The route keeps `requireFeature`.+- [x] **Review fix B: one loader helper (C3, B7)** — **Autonomous:** `loadListPage(request, list, { dataKey, bypassRls?, guard?, params?, firstPage?, onError? })` (`utils/list-registry/load.server.ts`) is the whole loader of a registered list. It runs `requirePermissions` with the list's permission, `guard` on every page, `fetchListPage`, and `firstPage` on page 1 only. A failed later page logs the error (`erp/list-registry`) and returns `listError: "Failed to load more rows"`. A failed page 1 throws the loader's old redirect with its flash (`onError`); without `onError` it shows no rows, as before. Every bare `redirect(...)` in a converted loader is now thrown. A loader that does not fit calls `fetchListPage` and returns `listErrorPage(dataKey)`.+- [x] **Review fix B: one paging constant per list (C4, J4)** — **Autonomous:** `X_PAGING: Paging = { defaultSorts, idColumn? }` replaces the 118 `X_DEFAULT_SORTS` constants. `setGenericQueryFilters(query, args, X_PAGING)`, `toPage(rows, { limit, sorts }, X_PAGING)` and the registry entry read it. The two planning constants keep their names (`PURCHASING_PLANNING_DEFAULT_SORTS`, `PRODUCTION_PLANNING_DEFAULT_SORTS`): wave C owns their routes. The price list's paging names `itemId`, but its item query breaks ties on the item's own `id` (the same value), so the service passes only `PRICE_LIST_PAGING.defaultSorts`.+- [x] **Review fix B: the query context and `searchList` (C2, J2, S2)** — **Autonomous:** `fetchListPage` parses `getGenericQueryFilters` once and calls `query(client, companyId, { params, limit, cursor, sorts, filters, companyGroupId? })`. `searchList({ key, permission, paging, service, params })` builds the common entry: the service gets `{ search, ...params, limit, cursor, sorts, filters }`. A `params` entry names a URL param or reads one (`(params) => …`). 94 of 110 entries use it. The dimension and intercompany lists read the group with `resolveCompanyGroupId`: a loader passes the group from `requirePermissions`; a background job has none, so the list reads it once per page, as before. The group is an optional 6th argument, so `fetchListPage` stays compatible with the jobs.+- [x] **Review fix B: a missing sort column ends the list (R1)** — **Autonomous:** `toPage` no longer throws in development. In every environment, if the last row has no value for a sort column or the id column, it returns `nextCursor: null` and logs a warning (`erp/cursor`). Fixed assets now select `createdAt` and `updatedAt`. `test/list-select-columns.test.ts` also checks that each listed `*_LIST_COLUMNS` holds the sort and id columns of its paging.+- [x] **Review fix B: cursor or offset (R2)** — **Autonomous:** `setGenericQueryFilters` pages by cursor when `args.cursor !== undefined`, not when the key exists.+- [x] **Review fix B: a cursor names its order (R4)** — **Autonomous:** A cursor stores `keys`, each keyset column with its direction (`createdAt:desc`). If the keys differ from the request's order, the query adds a filter that no row matches (`and(id.is.null,id.not.is.null)`). The list then ends instead of restarting at page 1. A cursor without `keys` does not decode.+- [x] **Review fix B: offset tokens (S3)** — **Autonomous:** Printing jobs and the audit log use `encodeOffsetToken` / `decodeOffsetToken`, not a `Cursor` with an offset in `id`. A failed later page of either returns `listError`.+- [x] **Review fix B: no cursor in MCP (R3)** — **Autonomous:** `getAccountLedger` (MCP) pages by `offset` only. The 4 ledger drawers call `getAccountLedgerPage` (`accounting.server.ts`), which reads `getAccountLedgerLines` (no `@mcp` tag) and replaced `getConsolidatedAccountLedger`. `getAssemblyInstructions` (MCP) takes its old flat args with `offset?` again and ends with `query = setGenericQueryFilters(…); return query;`; with only `limit` it reads from offset 0. The list reads `getAssemblyInstructionsPage` (no `@mcp` tag). Typing the MCP args as `GenericQueryFilters & {…}` was rejected: the generator then publishes them nested under `args`, a contract change.++- [x] **Merge with the service-function refactor (2026-10-20)** — **Autonomous:** main removed module barrels and moved operations into `defineServiceFn` consts. The bulk routes now call main's operations for a selection and start the background job for `allMatching` (or a selection too big for one request). The background job's production work runs main's operations (`releaseCheckedJobs`, `releaseBatches`, `updateBatch`) in `systemContext` on behalf of the user (`utils/production-bulk-actions.server.ts`); its other building blocks moved into the module service files (`bulkUpdateItems` → `items.service.ts`, `bulkDeleteJobs` → `production.service.ts`, `bulkDeletePurchaseOrders` → `purchasing.service.ts`, the user queue helpers → `users.service.ts`). `getAccountLedgerPage` moved to `accounting.service.ts` and `loadPeriodRuns` to `routes/x+/accounting+/period-runs.server.ts`, where main put them.+- [x] **Review fix B: sync operations (R17)** — **Autonomous:** `getSyncOperations` counts on the first page only (no `after`, offset 0). It quotes the cursor values with the escape of `cursor.ts`, copied into ee because ee cannot import the app.+- [x] **Review fix C: per-row extras come with each page (C1)** — **Autonomous:** `loadListPage` takes `mapRows(rows, context)`, which runs on every page after a load without an error. Jobs (batches and the tracked entity), Suppliers (report contacts), Tracked Entities (shelf-life policy) and Workflows (published version number, last run) put the value on the row, and their tables read it from the row. `onPage` and every "merge later pages" state are gone; `InfiniteOptions.onPage` is removed. The Jobs tracked-entity lookup moved from the browser to the loader (the loader's client, filtered by `companyId`). — One page carries its own values, so a revalidation re-read of the loaded pages refreshes them too.+- [x] **Review fix C: the planning grids own their rows (C1, B4, B5)** — **Autonomous:** The planning loaders attach each item's actions to its row (`withPlanningActions`, `planning-action-scope.ts`), and to the linked drawer row. The table calls `useInfiniteRows` with `ignoreParams: [PLANNING_DRAWER_PARAM]` and passes it as `infiniteRows`. The drawer rows add the linked row only when it is not loaded, and the actions are read from those rows, so a loaded drawer row is counted once (production and purchasing alike). The constants are now `PURCHASING_PLANNING_PAGING` and `PRODUCTION_PLANNING_PAGING`. A failed later page returns `listErrorPage("items")`; a failed page 1 now throws its redirect (it was a bare `redirect(...)`). This replaces the Review fix B note that the two planning constants keep their names.+- [x] **Review fix C: Documents keeps the user's changes, not the rows (B3)** — **Autonomous:** `DocumentsTable` runs `useInfiniteRows` and lays the user's star and label changes over every loaded row with the Table's edit overlay (`applyRowEdits`, `rowEdits.ts`). A change is pending (never dropped) until its write ends; it then takes a tick and the table revalidates, so a load that starts after the write drops it. The "Starred" view hides a row the overlay unstars. This replaces the decision "Optimistic document rows (Task 12h)". The loader uses `loadListPage` with `mapRows` for the download tokens.+- [x] **Review fix C: Sync Activity pages from its API route (B6)** — **Autonomous:** `SyncActivity` uses `useInfiniteRows` with `pageUrl: path.to.api.integrationSyncActivity(id, status)` and `ignoreParams: ["tab"]`. The API route reads one page (no `?limit=`) and returns `{ operations, nextCursor }` or `listErrorPage`. Each row carries its `reference` (the document number and the Carbon row id, `withSyncOperationReferences`), which replaces the page-level `readableIds` map. A revalidation re-reads at most 20 pages, as every list.+- [x] **Review fix C: single-load lists read exactly 1,000 rows (R5)** — **Autonomous:** `SINGLE_LOAD_LIMIT` (`utils/pagination.ts`) with offset mode, `{ limit, offset: 0 }` → `.range(0, 999)`. A list with search or filters returns `isTruncated` when it gets 1,000 rows, and `<Table isTruncated>` shows "Showing the first 1,000 rows. Search or filter to see the rest." in a row under the rows (desktop) or under the list (phones), where "Loading more rows" shows on an infinite list (`RowLimitNote`): groups, partners, the customer and supplier accounts, the storage unit roots and the customer portal. Sales rules, storage rules, the new serial number form and a training's assignments use offset mode with no note: the first three have no search or filter, and the assignments page searches only the rows it loaded, so the note would be false. `getTrainingAssignmentStatus` (MCP) takes `offset` again.+- [x] **Review fix C: the customer portal's lookups are bounded (R16)** — **Autonomous:** The thumbnails download 8 at a time (`async.map`). `getJobOperationAttachments` sends 100 operation ids per request, 8 requests at a time, and logs a failed request; the page shows without those attachments, as before.+- [x] **Review fix C: the ERP tests import no list registry through a service** — **Autonomous:** `listErrorPage` and `LOAD_MORE_ERROR` moved to `utils/list-registry/list-error.ts`, which imports nothing; `load.server.ts` re-exports them. `accounting.server.ts` imported `load.server.ts`, which loads the registry and every module's service, and through them a Lingui `msg` macro (`@carbon/onboarding`) that vitest does not compile: `lease-run-posting.test.ts` failed to load.+- [x] **Review fix C: five tables keep their indentation** — **Autonomous:** `PricingRulesTable`, `SalesRFQsTable`, `ContractsTable`, `ReturnReasonsTable` and `CustomerTypesTable` read their props in the body (`memo((props) => { const { … } = props;`), so the change is the new prop and the `infinite` block only.++## Risks++- A list without a unique `id` column needs its own tie-breaker. The plan lists every such list before conversion.+- A sortable column that is not in the list's select ends the list after the page: `toPage` logs a warning. The plan checks each list.+- Background jobs share the ERP containers with web requests. Many companies with big jobs at once can slow every user. Accepted for now; a separate worker container fixes it (`TODO(scale)`).+- Each of the 15 bulk actions needs its per-row checks on the server. A check that stays only in the browser lets the job act on rows the user could not act on before.+- Big exports show plain values, so they differ from small exports (for example `1250.5` instead of `$1,250.50`).++## Changelog++- 2026-10-13: First draft, written after the design interview.+- 2026-10-13: Replaced the 5,000-row browser cap with a 1,000-row split: browser below, Inngest job above. Footer totals stay as today.+- 2026-10-13: Spec approved. Added Autonomous Decisions from the plan research.+- 2026-10-13: Review fixes A–D recorded. Corrected the Documents decision, marked the replaced decisions, and updated sections 3, 7, 8, 11 and the Design Decisions for job steps, the 2,000-row release limit and per-user export files. Added "Verification status".diff --cc apps/erp/app/components/Table/Table.tsxindex c6b1e8d6af,09185e0ad9..cac5d0e173--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@@ -64,8 -79,15 +64,8 @@@ import type} from "~/components/Editable";import { useUrlParams } from "~/hooks";import { useSavedViews } from "~/hooks/useSavedViews";- import type { fieldMappings } from "~/modules/shared";+ import type { fieldMappings } from "~/modules/shared/imports.models";-import {- IndeterminateCheckbox,- Pagination,- Row,- TableHeader,- usePagination,- useSort-} from "./components";+import { Row, TableHeader, useSort } from "./components";import { CompactList } from "./components/Compact";import { CompactToolbar } from "./components/Compact/CompactToolbar";import type { ColumnFilter } from "./components/Filter/types";diff --cc apps/erp/app/modules/accounting/accounting.service.tsindex 0d9469180d,aa61ff1a26..5585b651da--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@@ -33,13 -188,69 +188,73 @@@ import} from "@carbon/utils";import { endOfMonth, parseDate, startOfMonth } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+ import type { Transaction as KyselyTransaction, Selectable } from "kysely";import { sql } from "kysely";- import type { z } from "zod";- import { getNextSequence } from "~/modules/settings";+ import { nanoid } from "nanoid";+ import { z } from "zod";+ import {+ buildPurchaseReceiptJournalLines,+ buildReturnShipmentJournal,+ buildSalesReturnReceiptJournalLines,+ buildSalesShipmentJournal,+ type PurchaseReceiptLine,+ type PurchaseReceiptLineCost,+ purchaseReceiptLineCosts+ } from "~/modules/inventory/inventory.service";+ import {+ buildPurchaseInvoicePostingLines,+ buildSalesInvoiceJournal,+ calculatePurchasePostingAmounts,+ isItemLineType,+ loadLeasePostingFacts,+ type PurchaseInvoiceItem,+ type PurchaseInvoicePostingLine,+ planSalesInvoiceAccounts,+ rebuildMemoJournals,+ rebuildPaymentJournals,+ resolveLeasePostingLine,+ resolveSalesInvoiceAccounts,+ type SalesInvoiceLine,+ type SalesLineRevenue,+ salesLineDimensions+ } from "~/modules/invoicing/invoicing.service";+ import { getOnRentLineForAsset } from "~/modules/sales/sales.service";+ import { getNextSequence } from "~/modules/settings/settings.service";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { Cursor } from "~/utils/cursor";++import { decodeCursor, toPage } from "~/utils/cursor";++import { listErrorPage } from "~/utils/list-registry/list-error";++import { PAGE_SIZE } from "~/utils/pagination";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";+ import {+ allocateJournalLineIds,+ assertAccountingCutover,+ assertCompanyRecords,+ bookAdjustment,+ buildAdjustmentJournalLines,+ buildCapitalizationLines,+ buildReturnToInventoryLines,+ CHARGE_VOID_BEFORE_CUTOVER_ERROR,+ calculateCOGS,+ costCenterAndProjectDimensions,+ createAdjustmentJournal,+ getCurrentAccountingPeriod as ensureCurrentAccountingPeriod,+ fromServerFn,+ getAccountingPeriodForDate,+ getDefaultPostingGroup,+ getOffsetAccount,+ insertNegatedJournal,+ invokePosting,+ loadContractPositions,+ lockContractPositions,+ type PostingLine,+ REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR,+ refuseVoidBeforeCutover,+ resolveAccountingPeriod,+ resolveInventoryAccount,+ syncDraftRecognitionRuns+ } from "../shared/shared.service";import type {AnalyticsAccountScope,AnalyticsReportDefinition,@@@ -239,57 -447,20 +460,55 @@@ function accountLedgerQuery} else if (args.companyIds && args.companyIds.length > 0) {query = query.in("companyId", args.companyIds);}+ return query;+}- const result = await query- .order("postingDate", { ascending: false })- .order("journalEntryId", { ascending: false })- .order("id", { ascending: false })- .range(args.offset, args.offset + args.limit - 1);+type AccountLedgerResult = {+ data: AccountLedgerLine[] | null;+ count: number | null;+ error: PostgrestError | null;+};- /** @mcp read */- return result as unknown as {- data: AccountLedgerLine[] | null;- count: number | null;- error: PostgrestError | null;- };+export async function getAccountLedger(+ client: SupabaseClient<Database>,+ args: {+ accountId: string;+ companyId: string | null;+ // Consolidated drill-down: restrict to an explicit set of companies (the+ // group's operating companies + elimination entities) so a service-role read+ // doesn't leak across tenants. Ignored when companyId is set.+ companyIds?: string[];+ startDate: string | null;+ endDate: string | null;+ limit: number;+ offset?: number;+ }+) {+ const result = await setGenericQueryFilters(+ accountLedgerQuery(client, args, "exact"),+ { limit: args.limit, offset: args.offset ?? 0 },+ ACCOUNT_LEDGER_PAGING+ );+ return result as unknown as AccountLedgerResult;+}++/**+ * One cursor page of an account's ledger lines (`limit + 1` rows for+ * `toPage`), for the ledger drawers. Not an MCP tool: MCP and the API page+ * by offset through `getAccountLedger`. Only the first page counts.+ */+export async function getAccountLedgerLines(+ client: SupabaseClient<Database>,+ args: AccountLedgerScope & { limit: number; cursor: Cursor | null }+) {+ const result = await setGenericQueryFilters(+ accountLedgerQuery(client, args, args.cursor ? undefined : "exact"),+ { limit: args.limit, cursor: args.cursor },+ ACCOUNT_LEDGER_PAGING+ );+ return result as unknown as AccountLedgerResult;}- /** @mcp read */export async function getAccountLedgerSummary(client: SupabaseClient<Database>,companyGroupId: string,@@@ -4373,11 -4495,6 +4543,10 @@@ export async function getPaymentTerm.single();}+export const PAYMENT_TERMS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getPaymentTerms(client: SupabaseClient<Database>,companyId: string,@@@ -4717,11 -4822,6 +4872,10 @@@ export async function getProject.single();}+export const PROJECTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getProjects(client: SupabaseClient<Database>,companyId: string,@@@ -4734,12 -4834,12 +4888,10 @@@.eq("active", true);if (args.search) {- query = query.or(- `name.ilike.%${args.search}%,description.ilike.%${args.search}%`- );+ query = query.or(searchFilter(["name", "description"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PROJECTS_PAGING);return query;}@@@ -4776,11 -4875,6 +4927,10 @@@ export async function upsertProject.single();}+export const DIMENSIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getDimensions(client: SupabaseClient<Database>,companyGroupId: string,@@@ -5606,11 -5694,6 +5748,10 @@@ export async function getConsolidatedBa// -- Intercompany --+export const INTERCOMPANY_TRANSACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getIntercompanyTransactions(client: SupabaseClient<Database>,companyGroupId: string,@@@ -5810,16 -5889,6 +5945,15 @@@ export async function getExchangeRateHi// Manual JEs start as Draft and are posted by flipping status to Posted.// amount > 0 = debit, amount < 0 = credit.+// The enable writes many journals in one transaction, so they share a+// createdAt; the entry number breaks the tie.+export const JOURNAL_ENTRIES_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "journalEntryId", ascending: false }+ ]+};+- /** @mcp read */export async function getJournalEntries(client: SupabaseClient<Database>,companyId: string,@@@ -6785,11 -6855,6 +6915,10 @@@ export async function reverseJournalEnt// -- Asset Classes --+export const FIXED_ASSET_CLASSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getFixedAssetClasses(client: SupabaseClient<Database>,companyId: string,@@@ -6875,16 -6938,6 +7000,15 @@@ export async function deleteFixedAssetC// -- Fixed Assets --+// `createdAt` and `updatedAt` are selected for a sort the URL can ask for:+// `toPage` reads every sort column from the row.+const FIXED_ASSETS_LIST_COLUMNS =+ "id,fixedAssetId,fixedAssetClassId,name,serialNumber,status,depreciationMethod,acquisitionCost,accumulatedDepreciation,createdAt,updatedAt,fixedAssetClass:fixedAssetClassId(id, name),location:locationId(id, name)" as const;++export const FIXED_ASSETS_PAGING: Paging = {+ defaultSorts: [{ column: "fixedAssetId", ascending: true }]+};+- /** @mcp read */export async function getFixedAssets(client: SupabaseClient<Database>,companyId: string,@@@ -7455,11 -7504,6 +7572,10 @@@ export async function deleteDepreciatio// -- Depreciation --+export const DEPRECIATION_RUNS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getDepreciationRuns(client: SupabaseClient<Database>,companyId: string,@@@ -7510,35 -7554,6 +7624,33 @@@ export async function getDepreciationRu// -- Revenue Recognition --+export const PERIOD_RUNS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */+export async function getRevenueRecognitionRuns(+ client: SupabaseClient<Database>,+ companyId: string,+ type: Database["public"]["Enums"]["runType"],+ args: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("revenueRecognitionRun")+ .select(+ "id, runId, type, periodEnd, status, postedAt, journalId, createdAt",+ { count: args.cursor ? undefined : "exact" }+ )+ .eq("companyId", companyId)+ .eq("type", type);++ if (args.search) {+ query = query.ilike("runId", `%${args.search}%`);+ }++ query = setGenericQueryFilters(query, args, PERIOD_RUNS_PAGING);+ return query;+}+- /** @mcp read */export async function getRevenueRecognitionRun(client: SupabaseClient<Database>,id: string,@@@ -8556,11 -8561,6 +8658,10 @@@ export async function upsertFixedAssetU// -- Fleet --+export const FLEET_ASSETS_PAGING: Paging = {+ defaultSorts: [{ column: "fixedAssetId", ascending: true }]+};+- /** @mcp read */export async function getFleetAssets(client: SupabaseClient<Database>,companyId: string,@@@ -9473,3 -9486,12042 +9585,12058 @@@ export async function getAccountingSyncreturn { data: { cell, journals, truncated }, error: null };}+ /**+ * The cutover date the enable wizard works against, with the earliest and the+ * latest date its date picker allows (`activationCutoverDates`), from the+ * company's current period.+ */+ export async function getActivationCutover(+ client: SupabaseClient<Database>,+ companyId: string,+ request: Request+ ): Promise<ActivationCutoverDates> {+ const timeZone = await getCompanyTimeZone(client, companyId);+ return activationCutoverDates(+ new URL(request.url).searchParams.get(ACTIVATION_CUTOVER_PARAM),+ datetime.today(timeZone),+ CUTOVER_MAX_PERIODS_BACK+ );+ }++ /**+ * Saves a currency's config and, when given, pins its exchange rate as a+ * company override — in ONE transaction, so a failed pin never leaves the+ * config saved behind a "failed to save" message. The route has already+ * checked `update: accounting`; the writes are scoped to the company group+ * (config) and the company (override). Returns null when the currency is not+ * in the group.+ */+ export async function saveCurrencyWithRateOverride(+ db: Kysely<KyselyDatabase>,+ args: {+ currencyId: string;+ companyId: string;+ companyGroupId: string;+ userId: string;+ config: {+ decimalPlaces: number;+ historicalExchangeRate: number | null;+ customFields: Json;+ };+ overrideRate: number | null;+ }+ ): Promise<{ code: string } | null> {+ return db.transaction().execute(async (trx) => {+ const currency = await trx+ .updateTable("currency")+ .set({+ decimalPlaces: args.config.decimalPlaces,+ historicalExchangeRate: args.config.historicalExchangeRate,+ customFields: args.config.customFields,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", args.currencyId)+ .where("companyGroupId", "=", args.companyGroupId)+ .returning("code")+ .executeTakeFirst();++ if (!currency) return null;++ if (args.overrideRate !== null) {+ // Update-in-place on conflict so re-pinning keeps the original creator.+ await trx+ .insertInto("exchangeRateOverride")+ .values({+ companyId: args.companyId,+ currencyCode: currency.code,+ rate: args.overrideRate,+ createdBy: args.userId+ })+ .onConflict((oc) =>+ oc.columns(["companyId", "currencyCode"]).doUpdateSet({+ rate: args.overrideRate as number,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();+ }++ return { code: currency.code };+ });+ }++ /** The company's business day, `YYYY-MM-DD`. */+ export async function getCompanyToday(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<string> {+ return datetime.today(await getCompanyTimeZone(client, companyId)).toString();+ }++ /**+ * The refusal for a period run (revenue recognition, depreciation) that ends+ * after the company's current month, or null when the period may run. New,+ * Repeat and Post all ask, so a run for a month that has not started can+ * neither be created nor posted.+ */+ export async function futureRunPeriodError(+ client: SupabaseClient<Database>,+ companyId: string,+ periodEnd: string+ ): Promise<string | null> {+ if (!isFutureRunPeriod(periodEnd, await getCompanyToday(client, companyId))) {+ return null;+ }+ return `${formatDate(periodEnd, { month: "long", year: "numeric" })} has not started yet. A run can cover the current month or an earlier one.`;+ }++ /** A Draft period run (revenue recognition, depreciation) no longer matches+ * what its period should post. Its message is meant for the user — the post+ * routes show it, where other posting failures get a generic toast. */+ export class RunOutOfDateError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "RunOutOfDateError";+ }+ }++ /** Resolve only the authorized group's root CTA configuration for reporting.+ * Operating-company balances continue to use the loader's RLS client.+ */+ export async function applyCtaToReportPeriodSeriesForReport(+ request: Request,+ reportingCompanyId: string,+ args: Parameters<typeof applyCtaToReportPeriodSeries>[3]+ ) {+ const { client, companyGroupId } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ bypassRls: true+ });+ const root = await client+ .from("company")+ .select("id")+ .eq("id", reportingCompanyId)+ .eq("companyGroupId", companyGroupId)+ .is("parentCompanyId", null)+ .single();+ if (root.error || !root.data) {+ return {+ data: null,+ error: root.error ?? {+ message:+ "Reporting company must be the root of the authorized company group"+ }+ };+ }+ // Use the authenticated client returned above: API keys never gain service-role+ // privileges, even if their request also supplies the bypassRls option.+ return applyCtaToReportPeriodSeries(+ client,+ companyGroupId,+ root.data.id,+ args+ );+ }++ // Report loaders consolidate a group the user is authorized for, but the+ // synthetic elimination entities are read via service role (no user is a member+ // of them — see the consolidation service). These thin wrappers own that+ // privileged-client decision in ONE server-only place so the loaders never+ // thread a `getCarbonServiceRole()` argument through their call sites. The RLS+ // `client` still reads every operating company; only elimination entities are+ // read privileged.+ export function getConsolidatedPeriodSeriesForReport(+ client: SupabaseClient<Database>,+ companyGroupId: string,+ companyIds: string[],+ targetCurrency: string,+ args: { buckets: ReportPeriodBucket[]; includeCurrentYearEarnings?: boolean }+ ) {+ return getConsolidatedPeriodSeries(+ client,+ companyGroupId,+ companyIds,+ targetCurrency,+ args,+ getCarbonServiceRole()+ );+ }++ export function getConsolidatedBalancesForReport(+ client: SupabaseClient<Database>,+ companyGroupId: string,+ companyIds: string[],+ targetCurrency: string,+ periodEnd: string,+ periodStart?: string+ ) {+ return getConsolidatedBalances(+ client,+ companyGroupId,+ companyIds,+ targetCurrency,+ periodEnd,+ periodStart,+ getCarbonServiceRole()+ );+ }+-// Consolidated account drill-down ("All Companies"). Reads via service role so-// the synthetic elimination entities' journal lines (invisible to the user's-// RLS session — no user is a member of them) appear in the ledger and the-// summary ties to the consolidated report. Scoped to the group's own companies-// so a service-role read cannot cross tenants.-export async function getConsolidatedAccountLedger(- companyGroupId: string,++/**++ * One page of an account's ledger lines for the ledger drawers (the chart of++ * accounts and the three statement reports), with the drawer's summary on++ * the first page.++ *++ * "All Companies" (`consolidated`) reads via service role so the synthetic++ * elimination entities' journal lines (invisible to the user's RLS session —++ * no user is a member of them) appear in the ledger and the summary ties to++ * the consolidated report. It is scoped to the group's own companies so a++ * service-role read cannot cross tenants.++ *++ * A failed later page (`after`) returns `listError` for the drawer's list.++ */++export async function getAccountLedgerPage(++ client: SupabaseClient<Database>,+ args: {+ accountId: string;++ companyGroupId: string;++ /** One company's lines; null reads every company the client can see. */++ companyId: string | null;++ consolidated?: boolean;+ startDate: string | null;+ endDate: string | null;- limit: number;- offset: number;++ /** The `?after=` token; a later page reads its lines only. */++ after: string | null;+ }+ ) {- const serviceRole = getCarbonServiceRole();- const { data: groupCompanies } = await serviceRole- .from("company")- .select("id")- .eq("companyGroupId", companyGroupId)- .eq("active", true);- const companyIds = (groupCompanies ?? []).map((c) => c.id);++ const cursor = decodeCursor(args.after);++ let readClient = client;++ let companyIds: string[] | undefined;++ if (args.consolidated) {++ readClient = getCarbonServiceRole();++ const { data: groupCompanies } = await readClient++ .from("company")++ .select("id")++ .eq("companyGroupId", args.companyGroupId)++ .eq("active", true);++ companyIds = (groupCompanies ?? []).map((c) => c.id);++ }++ const companyId = args.consolidated ? null : args.companyId;++ const { accountId, startDate, endDate } = args;++ const [ledger, summary] = await Promise.all([- getAccountLedger(serviceRole, {- accountId: args.accountId,- companyId: null,++ getAccountLedgerLines(readClient, {++ accountId,++ companyId,+ companyIds,- startDate: args.startDate,- endDate: args.endDate,- limit: args.limit,- offset: args.offset++ startDate,++ endDate,++ limit: PAGE_SIZE,++ cursor+ }),- getAccountLedgerSummary(serviceRole, companyGroupId, null, {- accountId: args.accountId,- startDate: args.startDate,- endDate: args.endDate- })++ cursor++ ? null++ : getAccountLedgerSummary(readClient, args.companyGroupId, companyId, {++ accountId,++ startDate,++ endDate++ })+ ]);+- return { ledger, summary };++ const emptySummary = { opening: 0, netChange: 0, closing: 0 };++ if (ledger.error) {++ logger.error("Failed to load an account ledger page", {++ accountId,++ companyGroupId: args.companyGroupId,++ error: ledger.error++ });++ if (cursor) return listErrorPage("lines");++ }++++ const page = toPage(++ ledger.data ?? [],++ { limit: PAGE_SIZE },++ ACCOUNT_LEDGER_PAGING++ );++ return {++ lines: page.rows,++ count: ledger.count ?? 0,++ nextCursor: page.nextCursor,++ summary: summary?.data ?? emptySummary++ };+ }++ /**+ * Inserts a Posted run journal (`@carbon/database/run-journals`) with its+ * lines, and a dimension row for each line value whose dimension the company+ * has. A journal with no lines is still inserted, as the run posters always+ * have.+ */+ async function insertPostedRunJournal(+ trx: KyselyTx,+ journal: RunJournal,+ posting: {+ accountingPeriodId: string;+ postingDate: string;+ dimensionIds: Partial<Record<DimensionEntityType, string | undefined>>;+ companyId: string;+ userId: string;+ now: string;+ }+ ): Promise<{ id: string; journalEntryId: string }> {+ const { accountingPeriodId, postingDate, dimensionIds, companyId, userId } =+ posting;+ const journalEntryId = await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ );+ const { id } = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ companyId,+ description: journal.description,+ postingDate,+ sourceType: journal.sourceType,+ status: "Posted",+ postedAt: posting.now,+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ if (journal.lines.length === 0) return { id, journalEntryId };++ const lines = await trx+ .insertInto("journalLine")+ .values(+ journal.lines.map(({ dimensions: _, ...line }) => ({+ ...line,+ journalId: id,+ journalLineReference: crypto.randomUUID(),+ companyId+ }))+ )+ .returning(["id"])+ .execute();+ const dimensionRows = lines.flatMap((line, index) =>+ Object.entries(journal.lines[index]!.dimensions).flatMap(+ ([entityType, valueId]) => {+ const dimensionId = dimensionIds[entityType as DimensionEntityType];+ return dimensionId && valueId+ ? [{ journalLineId: line.id, dimensionId, valueId, companyId }]+ : [];+ }+ )+ );+ if (dimensionRows.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionRows)+ .execute();+ }+ return { id, journalEntryId };+ }++ export async function postDisposal(+ db: Kysely<KyselyDatabase>,+ args: {+ fixedAssetId: string;+ fixedAssetReadableId: string;+ disposalDate: string;+ disposalMethod: "Sale" | "Scrapping";+ acquisitionCost: number;+ accumulatedDepreciation: number;+ locationId: string | null;+ fixedAssetClassId: string;+ assetAccountId: string;+ accumulatedDepreciationAccountId: string;+ lossOnDisposalAccountId: string;+ accountingPeriodId: string;+ locationDimensionId: string | undefined;+ assetClassDimensionId: string | undefined;+ companyId: string;+ userId: string;+ }+ ) {+ const {+ fixedAssetId,+ fixedAssetReadableId,+ disposalDate,+ disposalMethod,+ acquisitionCost,+ accumulatedDepreciation,+ locationId,+ fixedAssetClassId,+ assetAccountId,+ accumulatedDepreciationAccountId,+ lossOnDisposalAccountId,+ accountingPeriodId,+ locationDimensionId,+ assetClassDimensionId,+ companyId,+ userId+ } = args;++ if (!(await readAccountingCutoverDate(db, companyId))) {+ throw new Error(ACCOUNTING_NOT_STARTED);+ }++ const journal = buildDisposalJournal({+ assetReadableId: fixedAssetReadableId,+ disposalMethod,+ disposalDate,+ acquisitionCost,+ accumulatedDepreciation,+ locationId,+ fixedAssetClassId,+ assetAccountId,+ accumulatedDepreciationAccountId,+ lossOnDisposalAccountId+ });+ const nbv = journal.netBookValue;+ const now = datetime.timestamp();++ return db.transaction().execute(async (trx) => {+ const { id: journalId } = await insertPostedRunJournal(trx, journal, {+ accountingPeriodId,+ postingDate: journal.postingDate,+ dimensionIds: {+ Location: locationDimensionId,+ FixedAssetClass: assetClassDimensionId+ },+ companyId,+ userId,+ now+ });++ await trx+ .insertInto("fixedAssetDisposal")+ .values({+ fixedAssetId,+ disposalMethod,+ disposalDate,+ saleProceeds: 0,+ netBookValueAtDisposal: nbv,+ gainLoss: -nbv,+ journalId,+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .updateTable("fixedAsset")+ .set({+ status: "Disposed",+ disposalDate,+ disposalMethod,+ saleProceeds: 0,+ updatedBy: userId+ })+ .where("id", "=", fixedAssetId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ /**+ * Registers a Draft asset: Active, or Under Construction for a+ * construction-in-progress class. It posts the acquisition journal first:+ * Provisional before the accounting cutover (no period), Posted after it, in+ * the acquisition date's period. The status is read once, in the transaction,+ * under the lock the enable takes, so no registration writes a Provisional+ * journal after the enable commits. One transaction, so no asset is+ * registered without its journal or its CIP cost row.+ */+ export async function postAssetRegistration(+ db: Kysely<KyselyDatabase>,+ args: {+ fixedAssetId: string;+ fixedAssetReadableId: string;+ registration: {+ acquisitionCost: number;+ acquisitionDate: string;+ accumulatedDepreciation: number;+ depreciationStartDate: string;+ };+ posting: {+ locationId: string | null;+ fixedAssetClassId: string;+ assetAccountId: string;+ // Contra-asset account credited with any opening accumulated+ // depreciation when the asset is capitalized mid-life (from the class).+ accumulatedDepreciationAccountId: string;+ // Equity offset for a direct (non-purchase) registration — owner equity+ // / retained earnings. Brings the asset onto the books at NBV.+ offsetAccountId: string;+ locationDimensionId: string | undefined;+ assetClassDimensionId: string | undefined;+ /** The period of a Posted journal. Called only after the cutover. */+ resolveAccountingPeriodId: (postingDate: string) => Promise<string>;+ };+ // "Under Construction" for an asset registered into a construction-in-+ // progress class: it accumulates cost and is not depreciated until it is+ // capitalized into its in-service class.+ status?: "Active" | "Under Construction";+ companyId: string;+ userId: string;+ }+ ) {+ const {+ fixedAssetId,+ fixedAssetReadableId,+ registration,+ posting,+ status = "Active",+ companyId,+ userId+ } = args;+ const {+ locationId,+ fixedAssetClassId,+ assetAccountId,+ accumulatedDepreciationAccountId,+ offsetAccountId,+ locationDimensionId,+ assetClassDimensionId+ } = posting;++ const { acquisitionCost, acquisitionDate, accumulatedDepreciation } =+ registration;+ const now = datetime.timestamp();++ return db.transaction().execute(async (trx) => {+ const postingStatus = await journalPostingStatus(trx, companyId);+ let accountingPeriodId: string | null = null;+ if (postingStatus === "Posted") {+ // A Provisional journal counts nowhere, so only a Posted one needs the+ // dimensions.+ if (!locationDimensionId || !assetClassDimensionId) {+ throw new Error("Missing dimensions required for asset registration");+ }+ accountingPeriodId =+ await posting.resolveAccountingPeriodId(acquisitionDate);+ }++ // Post the acquisition journal FIRST, then flip the asset to Active — so a+ // capitalized asset can never exist without its GL entry (if the journal+ // fails the whole transaction rolls back and the asset stays Draft).+ // Dr assetAccountId acquisitionCost (capitalize at gross cost)+ // Cr accumulatedDepreciationAccountId accumulatedDepreciation (opening contra, mid-life only)+ // Cr offsetAccountId nbv (owner equity)+ const journalEntryId = await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ );++ const journal = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ companyId,+ description: `Asset Registration: ${fixedAssetReadableId}`,+ postingDate: acquisitionDate,+ sourceType: "Manual",+ status: postingStatus,+ postedAt: now,+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ acquisitionLines(acquisitionCost, accumulatedDepreciation).map(+ (line) => ({+ journalId: journal.id,+ accountId:+ line.role === "asset"+ ? assetAccountId+ : line.role === "accumulatedDepreciation"+ ? accumulatedDepreciationAccountId+ : offsetAccountId,+ description: line.description,+ amount: line.amount,+ journalLineReference: crypto.randomUUID(),+ companyId+ })+ )+ )+ .returning(["id"])+ .execute();++ if (locationDimensionId && locationId) {+ await trx+ .insertInto("journalLineDimension")+ .values(+ journalLineResults.map((jl) => ({+ journalLineId: jl.id,+ dimensionId: locationDimensionId,+ valueId: locationId,+ companyId+ }))+ )+ .execute();+ }++ if (assetClassDimensionId && fixedAssetClassId) {+ await trx+ .insertInto("journalLineDimension")+ .values(+ journalLineResults.map((jl) => ({+ journalLineId: jl.id,+ dimensionId: assetClassDimensionId,+ valueId: fixedAssetClassId,+ companyId+ }))+ )+ .execute();+ }++ const updateResult = await trx+ .updateTable("fixedAsset")+ .set({+ status,+ acquisitionCost: registration.acquisitionCost,+ acquisitionDate: registration.acquisitionDate,+ accumulatedDepreciation: registration.accumulatedDepreciation,+ depreciationStartDate: registration.depreciationStartDate,+ updatedBy: userId+ })+ .where("id", "=", fixedAssetId)+ .where("status", "=", "Draft")+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (!updateResult.numUpdatedRows) {+ // Lost the race (already registered/disposed) — roll back the journal.+ throw new Error("Asset is no longer in Draft status");+ }++ // An asset registered straight into a construction-in-progress class keeps+ // its registration cost as a CIP cost row, so capitalizing it into service+ // later sweeps that cost together with everything attached since+ // (post-asset-transfer sums the rows, not the asset's acquisitionCost).+ if (status === "Under Construction" && acquisitionCost > 0) {+ await trx+ .insertInto("fixedAssetCipCost")+ .values({+ fixedAssetId,+ sourceType: "Manual",+ amount: acquisitionCost,+ costDate: acquisitionDate,+ journalId: journal.id,+ companyId,+ createdBy: userId+ })+ .execute();+ }+ });+ }++ /**+ * Replaces a Draft depreciation run's lines with `lines`, keeping the run's id+ * and number. A run left with nothing to depreciate is deleted. Returns+ * whether the lines changed, so the route can say "already up to date".+ */+ export async function replaceDepreciationRunLines(+ db: Kysely<KyselyDatabase>,+ args: {+ depreciationRunId: string;+ lines: DepreciationLine[];+ companyId: string;+ userId: string;+ }+ ): Promise<{ changed: boolean; deleted: boolean }> {+ const { depreciationRunId, lines, companyId, userId } = args;++ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("depreciationRun")+ .select(["depreciationRunId", "status", "periodEnd"])+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Draft") {+ throw new Error(+ `Depreciation run ${run.depreciationRunId} is ${run.status}; only a draft can be recalculated`+ );+ }++ const before = await trx+ .selectFrom("depreciationRunLine")+ .select(["fixedAssetId", "periodEnd", "amount", "taxAmount"])+ .where("depreciationRunId", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();+ // A line from before per-month lines has no periodEnd: it is the run's.+ const changed = !depreciationRunLinesMatch(+ before.map((line) => ({+ ...line,+ periodEnd: line.periodEnd ?? run.periodEnd+ })),+ lines+ );++ if (lines.length === 0) {+ await trx+ .deleteFrom("depreciationRun")+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();+ return { changed, deleted: true };+ }+ if (!changed) return { changed, deleted: false };++ await trx+ .deleteFrom("depreciationRunLine")+ .where("depreciationRunId", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("depreciationRunLine")+ .values(+ lines.map((line) => ({+ depreciationRunId,+ periodEnd: line.periodEnd,+ fixedAssetId: line.fixedAssetId,+ amount: line.amount,+ taxAmount: line.taxAmount,+ companyId+ }))+ )+ .execute();+ await trx+ .updateTable("depreciationRun")+ .set({ updatedBy: userId })+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();++ return { changed, deleted: false };+ });+ }++ /**+ * The period and posting date for each month a run covers: the month's own+ * end, in its own period, so a catch-up run posts each month where it+ * belongs — or the run's `periodEnd` when the month's period is Closed. Runs+ * post as an "accounting" source, so a Locked period still accepts them.+ */+ export async function resolveRunPostingPeriods(+ client: SupabaseClient<Database>,+ args: { companyId: string; monthEnds: string[]; runPeriodEnd: string }+ ): Promise<+ | { data: RunPostingPeriods; error: null }+ | { data: null; error: { message: string } }+ > {+ const { companyId, runPeriodEnd } = args;+ const months = [...new Set(args.monthEnds)].sort();+ if (months.length === 0) return { data: new Map(), error: null };++ const existing = await client+ .from("accountingPeriod")+ .select("startDate, endDate, closeStatus, closedAt")+ .eq("companyId", companyId)+ .lte("startDate", runPeriodEnd)+ .gte("endDate", months[0]);+ if (existing.error) return { data: null, error: existing.error };++ const closedMonths = new Set(+ months.filter((month) =>+ existing.data.some(+ (period) =>+ period.startDate <= month &&+ period.endDate >= month &&+ (period.closeStatus === "Closed" || period.closedAt !== null)+ )+ )+ );+ const targets = runPostingTargets({ months, runPeriodEnd, closedMonths });++ // One call per distinct target month (it creates a missing period), never+ // one per line.+ const byTarget = new Map<+ string,+ { accountingPeriodId: string; postingDate: string }+ >();+ for (const target of new Set(targets.values())) {+ const period = await getOrCreateAccountingPeriod(+ client,+ companyId,+ target,+ "accounting"+ );+ if (period.error || !period.data) {+ return {+ data: null,+ error: period.error ?? {+ message: `No accounting period for ${target}`+ }+ };+ }+ byTarget.set(target, {+ accountingPeriodId: period.data,+ postingDate: target+ });+ }++ return {+ data: new Map(+ months.map((month) => [month, byTarget.get(targets.get(month)!)!])+ ),+ error: null+ };+ }++ /** Each month a run covers → the period and posting date its journals use. */+ export type RunPostingPeriods = Map<+ string,+ { accountingPeriodId: string; postingDate: string }+ >;++ export async function postDepreciationRun(+ db: Kysely<KyselyDatabase>,+ args: {+ depreciationRunId: string;+ depreciationRunReadableId: string;+ periods: RunPostingPeriods;+ /** The lines the route checked against the assets. Posting refuses when+ * the run holds any other lines by the time it is locked. */+ lineIds: string[];+ locationDimensionId: string | undefined;+ assetClassDimensionId: string | undefined;+ taxEnabled: boolean;+ taxRate: number | null;+ dtlAccountId: string | null;+ dtExpenseAccountId: string | null;+ companyId: string;+ userId: string;+ }+ ) {+ const {+ depreciationRunId,+ depreciationRunReadableId,+ periods,+ lineIds,+ locationDimensionId,+ assetClassDimensionId,+ taxEnabled,+ taxRate,+ dtlAccountId,+ dtExpenseAccountId,+ companyId,+ userId+ } = args;++ if (!(await readAccountingCutoverDate(db, companyId))) {+ throw new Error(ACCOUNTING_NOT_STARTED);+ }+ const now = datetime.timestamp();++ const periodOf = (monthEnd: string) => {+ const period = periods.get(monthEnd);+ if (!period) {+ throw new Error(`No accounting period resolved for ${monthEnd}`);+ }+ return period;+ };++ return db.transaction().execute(async (trx) => {+ // Lock the run first: two posts of one Draft must not both get through.+ const run = await trx+ .selectFrom("depreciationRun")+ .select(["depreciationRunId", "status", "periodEnd"])+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Draft") {+ throw new RunOutOfDateError(+ `Depreciation run ${run.depreciationRunId} is already ${run.status}`+ );+ }++ // The lines and the assets as they are now, not as the route read them.+ const runLines = await trx+ .selectFrom("depreciationRunLine as l")+ .innerJoin("fixedAsset as a", (join) =>+ join+ .onRef("a.id", "=", "l.fixedAssetId")+ .on("a.companyId", "=", companyId)+ )+ .innerJoin("fixedAssetClass as c", (join) =>+ join+ .onRef("c.id", "=", "a.fixedAssetClassId")+ .on("c.companyId", "=", companyId)+ )+ .select([+ "l.id",+ "l.fixedAssetId",+ sql<string | null>`l."periodEnd"::text`.as("periodEnd"),+ "l.amount",+ "l.taxAmount",+ "a.fixedAssetId as assetReadableId",+ "a.locationId",+ "a.fixedAssetClassId",+ "c.depreciationExpenseAccountId",+ "c.accumulatedDepreciationAccountId"+ ])+ .where("l.depreciationRunId", "=", depreciationRunId)+ .where("l.companyId", "=", companyId)+ .execute();++ const expected = new Set(lineIds);+ if (+ runLines.length !== expected.size ||+ runLines.some((line) => !expected.has(line.id))+ ) {+ throw new RunOutOfDateError(+ `Depreciation run ${run.depreciationRunId} changed while it was being posted; review it and post again`+ );+ }++ const assetIds = [...new Set(runLines.map((line) => line.fixedAssetId))];+ const assets =+ assetIds.length === 0+ ? []+ : await trx+ .selectFrom("fixedAsset")+ .select([+ "id",+ "fixedAssetId",+ "status",+ "acquisitionCost",+ "accumulatedDepreciation",+ "residualValuePercent"+ ])+ .where("id", "in", assetIds)+ .where("companyId", "=", companyId)+ .forUpdate()+ .execute();+ const assetById = new Map(assets.map((asset) => [asset.id, asset]));+ const notDepreciable = assets.find(+ (asset) =>+ asset.status !== "Active" && asset.status !== "Fully Depreciated"+ );+ if (notDepreciable) {+ throw new RunOutOfDateError(+ `${notDepreciable.fixedAssetId} is ${notDepreciable.status}; recalculate depreciation run ${run.depreciationRunId} before posting`+ );+ }++ // A line from before per-month lines has no periodEnd: it is the run's.+ const lines = runLines.map((line) => ({+ ...line,+ monthEnd: line.periodEnd ?? run.periodEnd,+ amount: Number(line.amount),+ taxAmount: Number(line.taxAmount ?? 0)+ }));+ const dimensionIds = {+ Location: locationDimensionId,+ FixedAssetClass: assetClassDimensionId+ };++ for (const journal of buildDepreciationJournals(lines)) {+ const { id } = await insertPostedRunJournal(trx, journal, {+ ...periodOf(journal.monthEnd),+ dimensionIds,+ companyId,+ userId,+ now+ });+ await trx+ .updateTable("depreciationRunLine")+ .set({ journalId: id })+ .where("id", "=", journal.lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // One update per asset with every month's amount. Each line used to add+ // its own amount to the same starting value, so with several months of+ // one asset only the last month reached accumulatedDepreciation.+ const byAsset = new Map<string, { amount: number; taxAmount: number }>();+ for (const line of lines) {+ const sums = byAsset.get(line.fixedAssetId) ?? {+ amount: 0,+ taxAmount: 0+ };+ sums.amount += line.amount;+ sums.taxAmount += line.taxAmount;+ byAsset.set(line.fixedAssetId, sums);+ }++ for (const [fixedAssetId, sums] of byAsset) {+ const asset = assetById.get(fixedAssetId)!;+ // Round at persist: a catch-up run adds many months, and float sums+ // stored 20187.59999999999 for 30 months of 672.92. The increment is+ // written in SQL against the row locked above.+ const amount = round(sums.amount);+ const taxAmount = round(sums.taxAmount);+ const newAccumulated = round(+ Number(asset.accumulatedDepreciation) + amount+ );+ const cost = Number(asset.acquisitionCost);+ const residualValue = cost * (Number(asset.residualValuePercent) / 100);+ const nbv = cost - newAccumulated;++ await trx+ .updateTable("fixedAsset")+ .set({+ accumulatedDepreciation: sql<number>`"accumulatedDepreciation" + ${amount}`,+ ...(nbv <= residualValue + 0.01+ ? { status: "Fully Depreciated" as const }+ : {}),+ ...(taxEnabled && taxAmount > 0+ ? {+ accumulatedTaxDepreciation: sql<number>`COALESCE("accumulatedTaxDepreciation", 0) + ${taxAmount}`+ }+ : {}),+ updatedBy: userId+ })+ .where("id", "=", fixedAssetId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Deferred tax journal entry, one per month, linked to that month's+ // lines so Reverse Run can find it.+ const deferredTax = buildDeferredTaxJournals({+ runReadableId: depreciationRunReadableId,+ lines,+ settings: deferredTaxSettings({+ enabled: taxEnabled,+ taxRate,+ dtlAccountId,+ dtExpenseAccountId+ })+ });+ for (const journal of deferredTax) {+ const { id } = await insertPostedRunJournal(trx, journal, {+ ...periodOf(journal.monthEnd),+ dimensionIds,+ companyId,+ userId,+ now+ });+ await trx+ .updateTable("depreciationRunLine")+ .set({ deferredTaxJournalId: id })+ .where("id", "in", journal.lineIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("depreciationRun")+ .set({+ status: "Posted",+ postedAt: now,+ postedBy: userId+ })+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ // ── Revenue recognition runs ─────────────────────────────────────────────────+ // Spec: `.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part I §1. Proposals are+ // built by the `propose-revenue-recognition-run` server function (shared with the Inngest job);+ // posting and deletion are human actions and live here, beside the+ // depreciation-run posters they mirror.++ export type RevenueRecognitionDimensionIds = {+ customer?: string;+ item?: string;+ location?: string;+ /** Contract rows only: the contract line's project, else the contract's. */+ project?: string;+ /** Lessee lease rows only: the lease's supplier. */+ supplier?: string;+ };++ type AccountClass = NonNullable<Database["public"]["Enums"]["glAccountClass"]>;++ export type DimensionEntityType =+ Database["public"]["Enums"]["dimensionEntityType"];++ /**+ * Posts a Draft revenue recognition run as one journal per month its rows+ * fall in (`sourceType` 'Revenue Recognition'), each in that month's period —+ * the run's own when the month is Closed: two lines per schedule row, each+ * row's own debit/credit accounts, signed by account class. Stamps each row+ * with its month's journal, the run with the journal of its own period, and+ * flips both to Posted, all in one transaction. The route resolves the+ * periods (`resolveRunPostingPeriods`, `source: "accounting"`, so a Locked+ * period accepts them) and the dimension ids before calling.+ */+ export async function postRevenueRecognitionRun(+ db: Kysely<KyselyDatabase>,+ args: {+ runId: string;+ companyId: string;+ userId: string;+ /** Each month the run's rows fall in → its period and posting date+ * (`resolveRunPostingPeriods`). */+ periods: RunPostingPeriods;+ dimensionIds: RevenueRecognitionDimensionIds;+ }+ ) {+ const { runId, companyId, userId, periods, dimensionIds } = args;+ if (!(await readAccountingCutoverDate(db, companyId))) {+ throw new Error(ACCOUNTING_NOT_STARTED);+ }+ const now = datetime.timestamp();++ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("revenueRecognitionRun")+ .select(["id", "runId", "status", "periodEnd", "type"])+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Draft") {+ throw new Error(+ `${runLabelSentence(run.type)} ${run.runId} is already ${run.status}`+ );+ }++ const rows = await trx+ .selectFrom("revenueRecognitionRunLine as l")+ .innerJoin("revenueRecognitionSchedule as s", (join) =>+ join+ .onRef("s.id", "=", "l.scheduleId")+ .on("s.companyId", "=", companyId)+ )+ .select([+ "l.amount",+ "s.amount as scheduleAmount",+ "s.status as scheduleStatus",+ "s.id as scheduleId",+ sql<string>`s."scheduledDate"::text`.as("scheduledDate"),+ "s.type",+ "s.debitAccountId",+ "s.creditAccountId",+ "s.salesInvoiceLineId",+ "s.rentalAgreementLineId",+ "s.rentalLeaseScheduleLineId",+ "s.customerContractLineId",+ "s.customerContractRevenueId",+ "s.leaseId",+ "s.leaseScheduleLineId"+ ])+ .where("l.runId", "=", runId)+ .where("l.companyId", "=", companyId)+ .execute();+ if (rows.length === 0) {+ throw new Error(+ `${runLabelSentence(run.type)} ${run.runId} has no lines`+ );+ }++ // A Draft is a snapshot of the schedule when it was proposed. Posting it+ // after a row it holds changed, or after another row fell due by its+ // period end, would recognize the wrong amount or leave that revenue to a+ // later period. Recalculating rebuilds it from the schedule as it is now.+ const unclaimed = await trx+ .selectFrom("revenueRecognitionSchedule")+ .select("id")+ .where("companyId", "=", companyId)+ .where(runTypeFilter(run.type))+ .where("status", "=", "Planned")+ .where("runLineId", "is", null)+ .where("scheduledDate", "<=", run.periodEnd)+ .executeTakeFirst();+ // Contract months are synthesized into schedule rows at proposal time, so+ // a month that fell due since (a contract confirmed later) has no row yet;+ // and a held contract row whose plan month an amendment replaced (its+ // `customerContractRevenueId` nulled) would recognize a stale amount.+ const unsynthesizedContractRevenue =+ run.type !== "Revenue Recognition"+ ? undefined+ : await trx+ .selectFrom("customerContractRevenue as r")+ .innerJoin("customerContract as c", (join) =>+ join+ .onRef("c.id", "=", "r.customerContractId")+ .onRef("c.companyId", "=", "r.companyId")+ )+ .select("r.id")+ .where("r.companyId", "=", companyId)+ .where("r.status", "=", "Planned")+ .where("r.periodStart", "<=", run.periodEnd)+ .where("r.amount", "<>", 0)+ .where("c.status", "<>", "Draft")+ .where(({ not, exists, selectFrom }) =>+ not(+ exists(+ selectFrom("revenueRecognitionSchedule as s")+ .select("s.id")+ .whereRef("s.customerContractRevenueId", "=", "r.id")+ .where("s.companyId", "=", companyId)+ )+ )+ )+ .executeTakeFirst();+ const drifted = rows.some(+ (row) =>+ row.scheduleStatus !== "Planned" ||+ !equals(Number(row.amount), Number(row.scheduleAmount)) ||+ (row.customerContractLineId && !row.customerContractRevenueId)+ );+ if (unclaimed || unsynthesizedContractRevenue || drifted) {+ throw new RunOutOfDateError(+ `${runLabelSentence(run.type)} ${run.runId} is out of date with its schedule; recalculate it before posting`+ );+ }++ // `account` is group-scoped (no companyId); the ids came from rows already+ // scoped to this company.+ const accountIds = [+ ...new Set(+ rows.flatMap((row) => [row.debitAccountId, row.creditAccountId])+ )+ ];+ const accounts = await trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "in", accountIds)+ .execute();+ const classById = new Map<string, AccountClass>();+ for (const account of accounts) {+ if (account.class) classById.set(account.id, account.class);+ }++ // Deferral rows point at the invoice line that funded them; the journal+ // line references the invoice and carries its customer/item/location.+ const invoiceLineIds = [+ ...new Set(+ rows+ .map((row) => row.salesInvoiceLineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ const invoiceLines =+ invoiceLineIds.length === 0+ ? []+ : await trx+ .selectFrom("salesInvoiceLine as sil")+ .innerJoin("salesInvoice as si", (join) =>+ join+ .onRef("si.id", "=", "sil.invoiceId")+ .on("si.companyId", "=", companyId)+ )+ .select([+ "sil.id",+ "sil.invoiceId",+ "sil.itemId",+ "sil.locationId",+ "si.customerId"+ ])+ .where("sil.id", "in", invoiceLineIds)+ .where("sil.companyId", "=", companyId)+ .execute();+ const invoiceLineById = new Map(+ invoiceLines.map((line) => [line.id, line])+ );++ // Accrual (and later Interest) rows point at a rental agreement line; the+ // journal line references the agreement and carries its customer, the+ // line's item and the agreement's location.+ const rentalLineIds = [+ ...new Set(+ rows+ .filter((row) => !row.salesInvoiceLineId)+ .map((row) => row.rentalAgreementLineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ const rentalLines =+ rentalLineIds.length === 0+ ? []+ : await trx+ .selectFrom("rentalAgreementLine as ral")+ .innerJoin("rentalAgreement as ra", (join) =>+ join+ .onRef("ra.id", "=", "ral.rentalAgreementId")+ .on("ra.companyId", "=", companyId)+ )+ .select([+ "ral.id",+ "ral.itemId",+ "ra.id as rentalAgreementId",+ "ra.customerId",+ "ra.locationId"+ ])+ .where("ral.id", "in", rentalLineIds)+ .where("ral.companyId", "=", companyId)+ .execute();+ const rentalLineById = new Map(rentalLines.map((line) => [line.id, line]));++ // Contract rows (synthesized from the contract's revenue plan) point at a+ // contract line; the journal line references the contract and carries its+ // customer, the line's item and the line's (else the contract's) project.+ const contractLineIds = [+ ...new Set(+ rows+ .map((row) => row.customerContractLineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ const contractLines =+ contractLineIds.length === 0+ ? []+ : await trx+ .selectFrom("customerContractLine as ccl")+ .innerJoin("customerContract as cc", (join) =>+ join+ .onRef("cc.id", "=", "ccl.customerContractId")+ .on("cc.companyId", "=", companyId)+ )+ .select([+ "ccl.id",+ "ccl.itemId",+ "cc.id as customerContractId",+ "cc.customerId",+ sql<string | null>`COALESCE(ccl."projectId", cc."projectId")`.as(+ "projectId"+ )+ ])+ .where("ccl.id", "in", contractLineIds)+ .where("ccl.companyId", "=", companyId)+ .execute();+ const contractLineById = new Map(+ contractLines.map((line) => [line.id, line])+ );++ // One journal per month: a row posts in the period of the month it was+ // scheduled for (the run's own period when that month is Closed), so a+ // catch-up run puts each month's revenue where it was earned.+ const periodOfMonth = (monthEnd: string) => {+ const period = periods.get(monthEnd);+ if (!period) {+ throw new Error(`No accounting period resolved for ${monthEnd}`);+ }+ return period;+ };+ const periodIdByDate = new Map<string, string>();+ const scheduleRows = rows.map((row) => {+ const period = periodOfMonth(monthEndOf(row.scheduledDate));+ periodIdByDate.set(period.postingDate, period.accountingPeriodId);+ return { ...row, postingDate: period.postingDate };+ });+ // Lessee lease rows reference the lease, with its supplier and location.+ const leaseIds = [+ ...new Set(+ rows.map((row) => row.leaseId).filter((id): id is string => Boolean(id))+ )+ ];+ const leases =+ leaseIds.length === 0+ ? []+ : await trx+ .selectFrom("lease")+ .select(["id", "supplierId", "locationId"])+ .where("id", "in", leaseIds)+ .where("companyId", "=", companyId)+ .execute();+ const leaseScheduleLineIds = rows+ .map((row) => row.leaseScheduleLineId)+ .filter((id): id is string => Boolean(id));+ const leaseAssets =+ leaseScheduleLineIds.length === 0+ ? []+ : await trx+ .selectFrom("leaseScheduleLine as sl")+ .innerJoin("leaseLine as l", (join) =>+ join+ .onRef("l.id", "=", "sl.leaseLineId")+ .onRef("l.companyId", "=", "sl.companyId")+ )+ .select(["sl.id", "sl.leaseLineId", "l.locationId"])+ .where("sl.id", "in", leaseScheduleLineIds)+ .where("sl.companyId", "=", companyId)+ .execute();++ const sources: RecognitionSources = {+ invoiceLines: invoiceLineById,+ rentalLines: rentalLineById,+ contractLines: contractLineById,+ leases: new Map(leases.map((lease) => [lease.id, lease])),+ leaseAssets: new Map(leaseAssets.map((asset) => [asset.id, asset]))+ };+ // Throws when an account has no class.+ const { journals, runJournal } = buildRecognitionJournals({+ runType: run.type,+ runReadableId: run.runId,+ runPeriodEnd: run.periodEnd,+ rows: scheduleRows,+ sources,+ classById+ });+ const recognitionDimensionIds = {+ Customer: dimensionIds.customer,+ Item: dimensionIds.item,+ Location: dimensionIds.location,+ Project: dimensionIds.project,+ Supplier: dimensionIds.supplier+ };++ const written = new Map<+ (typeof journals)[number],+ { id: string; journalEntryId: string }+ >();+ for (const journal of journals) {+ const inserted = await insertPostedRunJournal(trx, journal, {+ accountingPeriodId: periodIdByDate.get(journal.postingDate)!,+ postingDate: journal.postingDate,+ dimensionIds: recognitionDimensionIds,+ companyId,+ userId,+ now+ });+ written.set(journal, inserted);++ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({ journalId: inserted.id, status: "Posted", updatedBy: userId })+ .where("id", "in", journal.scheduleIds)+ .where("companyId", "=", companyId)+ .execute();+ // Each contract row's Recognition ledger entry records the journal+ // that posted it.+ if (journal.contractScheduleIds.length > 0) {+ await trx+ .updateTable("customerContractLedgerEntry")+ .set({ journalId: inserted.id })+ .where(+ "revenueRecognitionScheduleId",+ "in",+ journal.contractScheduleIds+ )+ .where("companyId", "=", companyId)+ .execute();+ }+ // An Interest row posts one period of a sales-type lease's effective+ // interest schedule; the schedule line records the journal that posted+ // it, which is how the net investment report tells posted principal+ // from future principal.+ if (journal.leaseScheduleLineIds.length > 0) {+ await trx+ .updateTable("rentalLeaseScheduleLine")+ .set({+ journalId: inserted.id,+ postedAt: now,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "in", journal.leaseScheduleLineIds)+ .where("companyId", "=", companyId)+ .execute();+ }+ // A lessee lease's month: its schedule line records the journal that+ // posted it.+ if (journal.lesseeScheduleLineIds.length > 0) {+ await trx+ .updateTable("leaseScheduleLine")+ .set({+ journalId: inserted.id,+ postedAt: now,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "in", journal.lesseeScheduleLineIds)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // A contract month is recognized once its schedule rows post.+ const recognizedRevenueIds = [+ ...new Set(+ rows+ .map((row) => row.customerContractRevenueId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (recognizedRevenueIds.length > 0) {+ await trx+ .updateTable("customerContractRevenue")+ .set({ status: "Recognized", updatedBy: userId, updatedAt: now })+ .where("id", "in", recognizedRevenueIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ // The run names the journal of its own period, else its latest month's;+ // every journal is reachable from the schedule rows it posted. The run+ // has rows, so it has a journal.+ const runJournalRow = written.get(runJournal!)!;++ await trx+ .updateTable("revenueRecognitionRun")+ .set({+ journalId: runJournalRow.id,+ status: "Posted",+ postedAt: now,+ postedBy: userId,+ updatedBy: userId+ })+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .execute();++ return {+ journalId: runJournalRow.id,+ journalEntryId: runJournalRow.journalEntryId+ };+ });+ }++ /** A Posted period run cannot be reversed; the message is meant for the user+ * (the reverse routes show it, where other failures get a generic toast). */+ export class RunReversalError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "RunReversalError";+ }+ }++ /**+ * Where each journal of a run is reversed: on its own posting date when that+ * period is not Closed, else on the company's today. Keyed by the original+ * posting date.+ */+ export async function resolveReversalPeriods(+ client: SupabaseClient<Database>,+ args: { companyId: string; postingDates: string[] }+ ): Promise<+ | { data: RunPostingPeriods; error: null }+ | { data: null; error: { message: string } }+ > {+ const { companyId } = args;+ const dates = [...new Set(args.postingDates)].sort();+ if (dates.length === 0) return { data: new Map(), error: null };++ const [existing, companyToday] = await Promise.all([+ client+ .from("accountingPeriod")+ .select("startDate, endDate, closeStatus, closedAt")+ .eq("companyId", companyId)+ .lte("startDate", dates[dates.length - 1])+ .gte("endDate", dates[0]),+ getCompanyToday(client, companyId)+ ]);+ if (existing.error) return { data: null, error: existing.error };++ const targetOf = new Map(+ dates.map((date) => {+ const closed = existing.data.some(+ (period) =>+ period.startDate <= date &&+ period.endDate >= date &&+ (period.closeStatus === "Closed" || period.closedAt !== null)+ );+ return [date, closed ? companyToday : date] as const;+ })+ );++ // One call per distinct target date, never one per journal line.+ const byTarget = new Map<+ string,+ { accountingPeriodId: string; postingDate: string }+ >();+ for (const target of new Set(targetOf.values())) {+ const period = await getOrCreateAccountingPeriod(+ client,+ companyId,+ target,+ "accounting"+ );+ if (period.error || !period.data) {+ return {+ data: null,+ error: period.error ?? {+ message: `No accounting period for ${target}`+ }+ };+ }+ byTarget.set(target, {+ accountingPeriodId: period.data,+ postingDate: target+ });+ }++ return {+ data: new Map(+ dates.map((date) => [date, byTarget.get(targetOf.get(date)!)!])+ ),+ error: null+ };+ }++ /**+ * Reverses posted journals the way `reverseJournalEntry` does — a Posted+ * entry with every line negated, the original marked Reversed — but keeps+ * each line's document and dimensions, and dates each reversal by `periods`+ * (keyed by the original's posting date). Shared by Reverse Run for revenue+ * recognition and depreciation, inside the caller's transaction.+ */+ export async function reverseRunJournals(+ trx: KyselyTx,+ args: {+ journalIds: string[];+ periods: RunPostingPeriods;+ companyId: string;+ userId: string;+ }+ ): Promise<void> {+ const { journalIds, periods, companyId, userId } = args;+ if (journalIds.length === 0) return;+ const now = datetime.timestamp();++ const [journals, lines] = await Promise.all([+ trx+ .selectFrom("journal")+ .select([+ "id",+ "journalEntryId",+ "status",+ "sourceType",+ sql<string>`"postingDate"::text`.as("postingDate")+ ])+ .where("id", "in", journalIds)+ .where("companyId", "=", companyId)+ .orderBy("postingDate")+ .orderBy("journalEntryId")+ .forUpdate()+ .execute(),+ trx+ .selectFrom("journalLine")+ .select([+ "id",+ "journalId",+ "accountId",+ "description",+ "amount",+ "documentType",+ "documentId"+ ])+ .where("journalId", "in", journalIds)+ .where("companyId", "=", companyId)+ .orderBy("id")+ .execute()+ ]);+ const notPosted = journals.find((journal) => journal.status !== "Posted");+ if (notPosted) {+ throw new RunReversalError(+ `Journal ${notPosted.journalEntryId} is ${notPosted.status}, so the run cannot be reversed`+ );+ }++ const dimensions =+ lines.length === 0+ ? []+ : await trx+ .selectFrom("journalLineDimension")+ .select(["journalLineId", "dimensionId", "valueId"])+ .where(+ "journalLineId",+ "in",+ lines.map((line) => line.id)+ )+ .where("companyId", "=", companyId)+ .execute();++ const reversedLineId = new Map<string, string>();+ for (const journal of journals) {+ const period = periods.get(journal.postingDate);+ if (!period) {+ throw new Error(`No reversal period resolved for ${journal.postingDate}`);+ }+ const journalEntryId = await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ );+ const reversal = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId: period.accountingPeriodId,+ companyId,+ description: `Reversal of ${journal.journalEntryId}`,+ postingDate: period.postingDate,+ sourceType: journal.sourceType,+ reversalOfId: journal.id,+ status: "Posted",+ postedAt: now,+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLines = lines.filter((line) => line.journalId === journal.id);+ if (journalLines.length > 0) {+ // RETURNING follows the VALUES order, so each new line pairs with its+ // original.+ const inserted = await trx+ .insertInto("journalLine")+ .values(+ journalLines.map((line) => ({+ journalId: reversal.id,+ accountId: line.accountId,+ description: line.description,+ amount: -Number(line.amount),+ documentType: line.documentType,+ documentId: line.documentId,+ journalLineReference: crypto.randomUUID(),+ companyId+ }))+ )+ .returning(["id"])+ .execute();+ journalLines.forEach((line, index) => {+ reversedLineId.set(line.id, inserted[index]!.id);+ });+ }++ await trx+ .updateTable("journal")+ .set({ status: "Reversed", reversedById: reversal.id, updatedBy: userId })+ .where("id", "=", journal.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (dimensions.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(+ dimensions.map((dimension) => ({+ journalLineId: reversedLineId.get(dimension.journalLineId)!,+ dimensionId: dimension.dimensionId,+ valueId: dimension.valueId,+ companyId+ }))+ )+ .execute();+ }+ }++ /**+ * Reverse Run for revenue recognition (NetSuite ARM's void: the plan lines+ * become recognizable again). Reverses every journal the run posted, puts+ * its schedule rows back to Planned — still held by the run — clears what+ * posting stamped (lease schedule lines, contract ledger entries, contract+ * revenue months) and returns the run to Draft, so it can be recalculated,+ * posted again or deleted.+ */+ export async function reverseRevenueRecognitionRun(+ db: Kysely<KyselyDatabase>,+ args: {+ runId: string;+ periods: RunPostingPeriods;+ companyId: string;+ userId: string;+ }+ ): Promise<{ runId: string; deleted: boolean }> {+ const { runId, periods, companyId, userId } = args;+ const now = datetime.timestamp();++ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("revenueRecognitionRun")+ .select(["id", "runId", "status", "periodEnd", "type"])+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Posted") {+ throw new RunReversalError(+ `${runLabelSentence(run.type)} ${run.runId} is ${run.status}; only a posted run can be reversed`+ );+ }+ // The reversed run becomes the period's Draft, and a period holds one.+ const draft = await trx+ .selectFrom("revenueRecognitionRun")+ .select("runId")+ .where("companyId", "=", companyId)+ .where("type", "=", run.type)+ .where("periodEnd", "=", run.periodEnd)+ .where("status", "=", "Draft")+ .executeTakeFirst();+ if (draft) {+ throw new RunReversalError(+ `${draft.runId} is a draft for this period. Post or delete it before reversing ${run.runId}.`+ );+ }++ const rows = await trx+ .selectFrom("revenueRecognitionRunLine as l")+ .innerJoin("revenueRecognitionSchedule as s", (join) =>+ join+ .onRef("s.id", "=", "l.scheduleId")+ .on("s.companyId", "=", companyId)+ )+ .select([+ "s.id",+ "s.journalId",+ "s.rentalLeaseScheduleLineId",+ "s.customerContractRevenueId",+ "s.leaseScheduleLineId",+ "s.rentalAgreementLineId",+ "s.leaseId",+ "l.id as lineId"+ ])+ .where("l.runId", "=", runId)+ .where("l.companyId", "=", companyId)+ .execute();+ const journalIds = [+ ...new Set(+ rows+ .map((row) => row.journalId)+ .filter((id): id is string => Boolean(id))+ )+ ];++ await reverseRunJournals(trx, { journalIds, periods, companyId, userId });++ const scheduleIds = rows.map((row) => row.id);+ if (scheduleIds.length > 0) {+ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({ status: "Planned", journalId: null, updatedBy: userId })+ .where("id", "in", scheduleIds)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .updateTable("customerContractLedgerEntry")+ .set({ journalId: null })+ .where("revenueRecognitionScheduleId", "in", scheduleIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ const leaseScheduleLineIds = [+ ...new Set(+ rows+ .map((row) => row.rentalLeaseScheduleLineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (leaseScheduleLineIds.length > 0) {+ await trx+ .updateTable("rentalLeaseScheduleLine")+ .set({+ journalId: null,+ postedAt: null,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "in", leaseScheduleLineIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ const lesseeScheduleLineIds = [+ ...new Set(+ rows+ .map((row) => row.leaseScheduleLineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (lesseeScheduleLineIds.length > 0) {+ await trx+ .updateTable("leaseScheduleLine")+ .set({+ journalId: null,+ postedAt: null,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "in", lesseeScheduleLineIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ const contractRevenueIds = [+ ...new Set(+ rows+ .map((row) => row.customerContractRevenueId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (contractRevenueIds.length > 0) {+ await trx+ .updateTable("customerContractRevenue")+ .set({ status: "Planned", updatedBy: userId, updatedAt: now })+ .where("id", "in", contractRevenueIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ // A run posted before lease runs existed can hold rental rows. Those now+ // belong to the lease run: release them, so the next lease run claims+ // them. A run left holding nothing is deleted rather than kept as an+ // empty Draft.+ const otherFamily = rows.filter(+ (row) => runTypeOfScheduleRow(row) !== run.type+ );+ if (otherFamily.length > 0) {+ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({ runLineId: null, updatedBy: userId })+ .where(+ "id",+ "in",+ otherFamily.map((row) => row.id)+ )+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("revenueRecognitionRunLine")+ .where(+ "id",+ "in",+ otherFamily.map((row) => row.lineId)+ )+ .where("companyId", "=", companyId)+ .execute();+ }+ if (otherFamily.length === rows.length) {+ await trx+ .deleteFrom("revenueRecognitionRun")+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .execute();+ return { runId: run.runId, deleted: true };+ }++ await trx+ .updateTable("revenueRecognitionRun")+ .set({+ status: "Draft",+ journalId: null,+ postedAt: null,+ postedBy: null,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .execute();++ return { runId: run.runId, deleted: false };+ });+ }++ /**+ * Reverse Run for depreciation. Reverses every journal the run posted (each+ * month's, and each month's deferred tax), takes the run's amounts back off+ * each asset's accumulated book and tax depreciation, returns a Fully+ * Depreciated asset that is above its residual value to Active, and returns+ * the run to Draft. Only the latest posted run can be reversed: a later run+ * was calculated from the accumulated depreciation this one wrote.+ */+ export async function reverseDepreciationRun(+ db: Kysely<KyselyDatabase>,+ args: {+ depreciationRunId: string;+ periods: RunPostingPeriods;+ companyId: string;+ userId: string;+ }+ ): Promise<{ depreciationRunId: string }> {+ const { depreciationRunId, periods, companyId, userId } = args;++ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("depreciationRun")+ .select(["depreciationRunId", "status", "periodEnd"])+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Posted") {+ throw new RunReversalError(+ `Depreciation run ${run.depreciationRunId} is ${run.status}; only a posted run can be reversed`+ );+ }++ const later = await trx+ .selectFrom("depreciationRun")+ .select("depreciationRunId")+ .where("companyId", "=", companyId)+ .where("status", "=", "Posted")+ .where("periodEnd", ">", run.periodEnd)+ .orderBy("periodEnd")+ .executeTakeFirst();+ if (later) {+ throw new RunReversalError(+ `${later.depreciationRunId} is posted for a later period and builds on this run. Reverse it first.`+ );+ }++ const lines = await trx+ .selectFrom("depreciationRunLine as l")+ .innerJoin("fixedAsset as a", (join) =>+ join+ .onRef("a.id", "=", "l.fixedAssetId")+ .on("a.companyId", "=", companyId)+ )+ .select([+ "l.fixedAssetId",+ "l.amount",+ "l.taxAmount",+ "l.journalId",+ "l.deferredTaxJournalId",+ "a.fixedAssetId as assetReadableId",+ "a.status",+ "a.acquisitionCost",+ "a.accumulatedDepreciation",+ "a.accumulatedTaxDepreciation",+ "a.residualValuePercent"+ ])+ .where("l.depreciationRunId", "=", depreciationRunId)+ .where("l.companyId", "=", companyId)+ .execute();++ const disposed = lines.find((line) => line.status === "Disposed");+ if (disposed) {+ throw new RunReversalError(+ `${disposed.assetReadableId} was disposed after this run. Reverse the disposal first.`+ );+ }++ const journalIds = [+ ...new Set(+ lines+ .flatMap((line) => [line.journalId, line.deferredTaxJournalId])+ .filter((id): id is string => Boolean(id))+ )+ ];+ await reverseRunJournals(trx, { journalIds, periods, companyId, userId });++ // One update per asset with every month's amount, as posting wrote it.+ // Tax depreciation is taken back when the run carried it, not when the+ // setting is on today: a line has a taxAmount exactly when tax+ // depreciation was enabled as the run posted (Post refuses a run whose+ // lines no longer match the setting), and posting added it then.+ const byAsset = new Map<+ string,+ {+ line: (typeof lines)[number];+ amount: number;+ taxAmount: number;+ hasTax: boolean;+ }+ >();+ for (const line of lines) {+ const sums = byAsset.get(line.fixedAssetId) ?? {+ line,+ amount: 0,+ taxAmount: 0,+ hasTax: false+ };+ sums.amount += Number(line.amount);+ sums.taxAmount += Number(line.taxAmount ?? 0);+ sums.hasTax ||= line.taxAmount !== null;+ byAsset.set(line.fixedAssetId, sums);+ }+ for (const [fixedAssetId, { line, amount, taxAmount, hasTax }] of byAsset) {+ const accumulated = round(Number(line.accumulatedDepreciation) - amount);+ const cost = Number(line.acquisitionCost);+ const residualValue = cost * (Number(line.residualValuePercent) / 100);+ const assetUpdate: Record<string, unknown> = {+ accumulatedDepreciation: accumulated,+ updatedBy: userId+ };+ if (hasTax && taxAmount > 0) {+ assetUpdate.accumulatedTaxDepreciation = round(+ Number(line.accumulatedTaxDepreciation ?? 0) - taxAmount+ );+ }+ // Posting marks an asset Fully Depreciated at its residual value.+ if (+ line.status === "Fully Depreciated" &&+ cost - accumulated > residualValue + 0.01+ ) {+ assetUpdate.status = "Active";+ }+ await trx+ .updateTable("fixedAsset")+ .set(assetUpdate)+ .where("id", "=", fixedAssetId)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("depreciationRunLine")+ .set({ journalId: null, deferredTaxJournalId: null })+ .where("depreciationRunId", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("depreciationRun")+ .set({+ status: "Draft",+ postedAt: null,+ postedBy: null,+ updatedBy: userId+ })+ .where("id", "=", depreciationRunId)+ .where("companyId", "=", companyId)+ .execute();++ return { depreciationRunId: run.depreciationRunId };+ });+ }++ /** Deletes a Draft run and releases its claimed schedule rows (`runLineId`+ * back to null) so a later proposal can claim them again. A Posted run is+ * never deleted: Reverse Run (`reverseRevenueRecognitionRun`) returns it to+ * Draft first. */+ export async function deleteRevenueRecognitionRun(+ db: Kysely<KyselyDatabase>,+ args: { runId: string; companyId: string; userId: string }+ ) {+ const { runId, companyId, userId } = args;++ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("revenueRecognitionRun")+ .select(["runId", "status", "type"])+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (run.status !== "Draft") {+ throw new Error(+ `${runLabelSentence(run.type)} ${run.runId} is ${run.status}; reverse the run instead of deleting it`+ );+ }++ const lineIds = (+ await trx+ .selectFrom("revenueRecognitionRunLine")+ .select("id")+ .where("runId", "=", runId)+ .where("companyId", "=", companyId)+ .execute()+ ).map((line) => line.id);++ if (lineIds.length > 0) {+ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({ runLineId: null, updatedBy: userId })+ .where("runLineId", "in", lineIds)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("revenueRecognitionRunLine")+ .where("runId", "=", runId)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .deleteFrom("revenueRecognitionRun")+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ /** A refusal a building block returned or threw ("Only open periods can be+ * locked"): its own message, unless it came from the data layer. */+ export function refusal(+ ctx: ServiceContext,+ err: unknown,+ fallback: string+ ): CarbonError {+ const message = (err as { message?: unknown } | null)?.message;+ return typeof message === "string" && message !== "" && !isDataLayerError(err)+ ? ctx.error("rule", message, err)+ : ctx.error("internal", fallback, err);+ }++ // ── Depreciation runs ───────────────────────────────────────────────────────++ /** A Draft depreciation run for `periodEnd`, from what each asset should+ * depreciate up to it. Shared by New Run and the period close. */+ export async function createDepreciationRunAt(+ ctx: ServiceContext,+ periodEnd: string+ ) {+ // Never an empty run: with nothing to depreciate this refuses.+ const result = await createDepreciationRun(ctx.asCaller.supabase, {+ companyId: ctx.company.id,+ companyGroupId: ctx.company.groupId,+ periodEnd,+ userId: ctx.auditUserId+ });+ if (result.error) {+ return refusal(ctx, result.error, "Failed to create depreciation run");+ }+ return { id: result.data.id, readableId: result.data.depreciationRunId };+ }++ // ── Revenue recognition and lease runs ──────────────────────────────────────++ /** A Draft run of `type` for `periodEnd`, unless the month has not started or+ * a Draft of the type already holds the period. Shared by New Run, Repeat+ * and the period close. */+ export async function proposeRunAt(+ ctx: ServiceContext,+ periodEnd: string,+ type: RunType+ ) {+ const client = ctx.asCaller.supabase;+ const futureError = await futureRunPeriodError(+ client,+ ctx.company.id,+ periodEnd+ );+ if (futureError) return ctx.error("rule", futureError);++ // A period can have more than one run of a type (a second picks up rows+ // that fell due after the first posted), but only one Draft at a time.+ const existingDraft = await client+ .from("revenueRecognitionRun")+ .select("id, runId")+ .eq("periodEnd", periodEnd)+ .eq("companyId", ctx.company.id)+ .eq("type", type)+ .eq("status", "Draft")+ .maybeSingle();+ if (existingDraft.data) {+ return ctx.error(+ "conflict",+ `${existingDraft.data.runId} is already a draft for this period. Recalculate it instead.`,+ { draftRunId: existingDraft.data.id }+ );+ }++ // The proposal creates nothing when nothing is due.+ const proposal = await invokePosting(+ ctx,+ "propose-revenue-recognition-run",+ {+ periodEnd,+ type+ },+ proposeRevenueRecognitionRun+ );+ if (proposal.error) {+ return fromServerFn(ctx, proposal.error, "Failed to create the run");+ }+ if (!proposal.data) {+ return ctx.error("rule", "Nothing to post for this period");+ }+ return { id: proposal.data.id, readableId: proposal.data.runId, type };+ }++ /** The Draft run an "already a draft for this period" refusal names, for the+ * page to open instead (`proposeRunAt`, `createRunForPeriod`). */+ export function existingDraftRunId(+ error: { category: string; cause?: unknown } | null+ ): string | null {+ const cause = error?.category === "conflict" ? error.cause : null;+ return cause && typeof cause === "object" && "draftRunId" in cause+ ? String(cause.draftRunId)+ : null;+ }++ // ── Fixed assets ────────────────────────────────────────────────────────────++ /**+ * Why an asset cannot be taken out of service now, or null. The page's loader+ * and the operation both ask: the form can be submitted long after it was+ * opened.+ */+ export async function outOfServiceRefusal(+ caller: SupabaseClient<Database>,+ system: SupabaseClient<Database>,+ fixedAssetId: string,+ companyId: string+ ): Promise<{+ category: ErrorCategory;+ message: string;+ cause?: unknown;+ } | null> {+ const asset = await getFixedAsset(caller, fixedAssetId, companyId);+ if (asset.error) {+ return {+ category: "notFound",+ message: "Failed to get fixed asset",+ cause: asset.error+ };+ }+ if (asset.data.outOfServiceSince) {+ return { category: "rule", message: "The asset is already out of service" };+ }+ if (asset.data.status === "Disposed") {+ return {+ category: "rule",+ message: "A disposed asset cannot be taken out of service"+ };+ }++ // A unit on rent goes to maintenance through the agreement's Return (with+ // "Take out of service"), never around it. Read with the service role,+ // scoped to the company and the asset: agreement lines need sales_view,+ // which an accountant may not hold, and under RLS that reads as "not on+ // rent". A failed read refuses rather than passes.+ const onRent = await getOnRentLineForAsset(system, fixedAssetId, companyId);+ if (onRent.error) {+ return {+ category: "internal",+ message: "Failed to check whether the asset is on rent",+ cause: onRent.error+ };+ }+ if (onRent.data) {+ const agreement = onRent.data.rentalAgreement;+ return {+ category: "rule",+ message: `The asset is on rent${agreement ? ` on ${agreement.rentalAgreementId}` : ""}; return it from the agreement and take it out of service there`+ };+ }+ return null;+ }+-// -- Revenue Recognition ----export async function getRevenueRecognitionRuns(- client: SupabaseClient<Database>,- companyId: string,- type: Database["public"]["Enums"]["runType"],- args: GenericQueryFilters & { search: string | null }-) {- let query = client- .from("revenueRecognitionRun")- .select("id, runId, type, periodEnd, status, postedAt, journalId", {- count: "exact"- })- .eq("companyId", companyId)- .eq("type", type);-- if (args.search) {- query = query.ilike("runId", `%${args.search}%`);- }-- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);- return query;-}+ /**+ * Input contract and pure helpers for `post-asset-transfer`. No I/O and no+ * imports beyond zod, the generated types and `@carbon/utils`, so the server function's own+ * logic can be pinned without a database.+ */++ // Calendar dates travel as `YYYY-MM-DD` text end to end: the transfer, the+ // journal and the ledger rows all store DATE columns, and a JavaScript Date+ // would shift the day by the runtime timezone.+ const calendarDate = z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date");++ /** Consume an Available serialized unit from stock into a fixed asset. */+ export const capitalizeValidator = z.object({+ type: z.literal("capitalize"),+ fixedAssetClassId: z.string().min(1),+ itemId: z.string().min(1),+ trackedEntityId: z.string().min(1),+ locationId: z.string().min(1),+ storageUnitId: z.string().optional().nullable(),+ transferDate: calendarDate,+ name: z.string().optional().nullable(),+ // An existing Draft asset to fill; otherwise the function creates one.+ fixedAssetId: z.string().optional().nullable(),+ // What the unit cost to make, for a unit inventory carries at nothing (a job+ // that recorded no production or material, a no-cost issue). Refused for a+ // unit that carries a cost: that value moves from inventory as it is.+ cost: z.number().positive().optional().nullable(),+ // The other side of an entered cost: where that value was booked when it+ // was spent. Required with `cost`.+ offsetAccountId: z.string().optional().nullable()+ });++ /** Return an asset to stock at its net book value. */+ export const returnValidator = z.object({+ type: z.literal("return"),+ fixedAssetId: z.string().min(1),+ locationId: z.string().min(1),+ storageUnitId: z.string().optional().nullable(),+ transferDate: calendarDate+ });++ /** Point a job at a Construction in Progress asset and sweep its WIP to it. */+ export const attachJobValidator = z.object({+ type: z.literal("attachJob"),+ fixedAssetId: z.string().min(1),+ jobId: z.string().min(1)+ });++ /** Move a Construction in Progress asset into its in-service class. */+ export const capitalizeCipValidator = z.object({+ type: z.literal("capitalizeCip"),+ fixedAssetId: z.string().min(1),+ toClassId: z.string().min(1),+ inServiceDate: calendarDate+ });++ /**+ * Raise an asset's cost after it was capitalized (post-capitalization): Dr the+ * class asset account / Cr `offsetAccountId`. Raise only — lowering a cost is+ * a write-down.+ */+ export const adjustCostValidator = z.object({+ type: z.literal("adjustCost"),+ fixedAssetId: z.string().min(1),+ amount: z.number().positive(),+ offsetAccountId: z.string().optional().nullable(),+ locationId: z.string().min(1),+ transferDate: calendarDate+ });++ export const postAssetTransferInput = z.discriminatedUnion("type", [+ capitalizeValidator,+ returnValidator,+ attachJobValidator,+ capitalizeCipValidator,+ adjustCostValidator+ ]);++ export type AssetTransferInput = z.output<typeof postAssetTransferInput>;++ /** One `itemLedger` net per storage unit for a tracked entity at a location. */+ export type StockByBin = {+ storageUnitId: string | null;+ onHand: number | string | null;+ };++ /**+ * Where a serialized unit's stock is, from its ledger nets per bin. `onHand` is+ * the unit's total at the location; `storageUnitId` is the bin with the+ * highest positive net — a picked or transferred unit has rows in more than+ * one bin, so "the first row's bin" would book the consumption against a bin+ * that no longer holds it (see `.ai/lessons.md`, tracked-entity bin resolution).+ * Falls back to `preferredStorageUnitId` only when no bin nets positive.+ */+ export function resolveCapitalizationStock(+ rows: StockByBin[],+ preferredStorageUnitId: string | null = null+ ): { onHand: number; storageUnitId: string | null } {+ let onHand = 0;+ let bestBin: string | null = null;+ let bestQuantity = 0;+ for (const row of rows) {+ const quantity = Number(row.onHand ?? 0);+ onHand += quantity;+ if (row.storageUnitId && quantity > bestQuantity) {+ bestQuantity = quantity;+ bestBin = row.storageUnitId;+ }+ }+ return { onHand, storageUnitId: bestBin ?? preferredStorageUnitId };+ }++ /** Job statuses that can no longer take on a Construction in Progress asset. */+ export const CLOSED_JOB_STATUSES: ReadonlySet<+ Database["public"]["Enums"]["jobStatus"]+ > = new Set(["Completed", "Cancelled", "Closed"] as const);++ /** Asset statuses a unit can be returned to inventory from. */+ export const RETURNABLE_ASSET_STATUSES: ReadonlySet<+ Database["public"]["Enums"]["fixedAssetStatus"]+ > = new Set(["Active", "Fully Depreciated"] as const);++ /** Asset statuses whose cost can be adjusted. */+ export const ADJUSTABLE_ASSET_STATUSES: ReadonlySet<+ Database["public"]["Enums"]["fixedAssetStatus"]+ > = new Set(["Active", "Fully Depreciated"] as const);++ /**+ * The cost a unit is capitalized at: what inventory carries it at, or — only+ * when that is nothing — the cost the user entered. Returns the refusal+ * message instead when neither gives the asset a value, or when a cost is+ * entered for a unit that already carries one.+ */+ export function resolveCapitalizationCost(args: {+ carried: number;+ entered: number | null | undefined;+ serial: string;+ itemReadableId: string;+ }): { cost: number; source: "inventory" | "entered" } | { error: string } {+ const { carried, entered, serial, itemReadableId } = args;+ if (carried > 0) {+ if (entered != null) {+ return {+ error: `${serial} is carried in inventory at a cost, so it is capitalized at that cost; clear the entered cost`+ };+ }+ return { cost: carried, source: "inventory" };+ }+ if (entered != null && entered > 0) {+ return { cost: entered, source: "entered" };+ }+ return {+ error: `${serial} has no cost in inventory, so the asset would be worth nothing. Enter what it cost, or set a unit cost on ${itemReadableId}, then capitalize it.`+ };+ }++ /**+ * An asset's status once its cost is raised: a Fully Depreciated asset whose+ * net book value is above its residual again has depreciation left to take,+ * so it returns to Active and the depreciation runs pick it up.+ */+ export function statusAfterCostAdjustment(args: {+ status: Database["public"]["Enums"]["fixedAssetStatus"];+ acquisitionCost: number;+ accumulatedDepreciation: number;+ residualValuePercent: number;+ }): Database["public"]["Enums"]["fixedAssetStatus"] {+ if (args.status !== "Fully Depreciated") return args.status;+ const residual = args.acquisitionCost * (args.residualValuePercent / 100);+ const remaining = args.acquisitionCost - args.accumulatedDepreciation;+ return remaining - residual > EPSILON ? "Active" : args.status;+ }+ // The single write path for moving value between inventory and the fixed+ // asset register (spec §2, "Fleet bridge"). Five actions, each creating and+ // posting one `fixedAssetTransfer` document in ONE transaction:+ //+ // capitalize stock → asset at the unit's carrying cost (the serial is+ // consumed INTO the asset; Dr class asset / Cr inventory);+ // a unit carried at zero takes the cost the user enters+ // instead (Dr class asset / Cr the chosen offset account),+ // and is refused without one+ // return asset → stock at net book value (Dr inventory N / Dr+ // accumulated depreciation / Cr class asset at cost)+ // attachJob point a job at a Construction in Progress asset and sweep+ // its WIP balance there (Dr CIP / Cr WIP), SAP AuC style+ // capitalizeCip CIP asset → its in-service class (Dr class / Cr CIP)+ // adjustCost raise an asset's cost after it was capitalized (Dr class+ // asset / Cr the chosen offset account), SAP+ // post-capitalization style+ //+ // Every action writes its journal: Provisional before the company's+ // accounting cutover, Posted after it.+ //+ // Business-validation failures are 400s (`InvalidInputError`) with the exact+ // message the app shows; a referenced record the caller's company does not own+ // is a 404 (`NotFoundError`); everything else is a 500 so real outages surface+ // in monitoring.++ type Db = Kysely<DB>;++ type Trx = KyselyTransaction<DB>;++ type Scoped<T extends AssetTransferInput["type"]> = Extract<+ AssetTransferInput,+ { type: T }+ > & { companyId: string; userId: string };++ type AccountingContext = {+ // Provisional before the company's accounting cutover, Posted after it+ postingStatus: AutomaticJournalStatus;+ // null for a Provisional journal: it has no accounting period+ accountingPeriodId: string | null;+ accountDefaults: {+ rawMaterialsAccount: string;+ finishedGoodsAccount: string;+ workInProgressAccount: string;+ };+ // active dimensions for the company group, entityType → dimension id+ dimensions: Record<string, string>;+ };++ export type AssetTransferResult = {+ // fixedAssetTransfer row id / readable number; null when nothing was swept+ id: string | null;+ transferId: string | null;+ // fixedAsset row id / readable number+ fixedAssetId: string;+ fixedAssetReadableId: string;+ };++ // Everything a journal needs that is known before the transaction opens. The+ // period resolver opens (and commits) its own transaction when given `db`.+ async function loadAccounting(+ db: Db,+ companyId: string,+ postingDate: string+ ): Promise<AccountingContext> {+ const postingStatus = await journalPostingStatus(db, companyId);++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ const company = await db+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirst();+ if (!company) throw new Error("Failed to fetch company");+ // Fail closed: journal lines must not silently lose dimension tags (a+ // failed read throws).+ const dimensionRows = await db+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", company.companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["Item", "Location", "FixedAssetClass"])+ .execute();+ const dimensions: Record<string, string> = {};+ for (const dimension of dimensionRows) {+ dimensions[dimension.entityType] = dimension.id;+ }++ // A Provisional journal has no period, and no posting creates one before+ // the cutover.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getAccountingPeriodForDate(companyId, db, postingDate)+ : null;++ return {+ postingStatus,+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,+ workInProgressAccount: accountDefaults.data.workInProgressAccount+ },+ dimensions+ };+ }++ // One 'Asset Transfer' journal from already-balanced lines (Provisional before+ // the accounting cutover, Posted after it), tagged with+ // the Location / FixedAssetClass / Item dimensions the company group has+ // active (post-receipt precedent for fixed-asset lines).+ async function postAssetJournal(+ trx: Trx,+ args: {+ accounting: AccountingContext;+ companyId: string;+ userId: string;+ postingDate: string;+ description: string;+ lines: PostingLine[];+ documentId: string;+ documentLineReference?: string | null;+ tags: {+ locationId: string | null;+ fixedAssetClassId: string | null;+ itemId: string | null;+ };+ }+ ): Promise<string> {+ const { accounting, companyId, userId } = args;+ const journalId = await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: accounting.accountingPeriodId,+ status: accounting.postingStatus,+ description: args.description,+ postingDate: args.postingDate,+ userId,+ sourceType: "Asset Transfer"+ });++ const journalLineReference = nanoid();+ const journalLines = await trx+ .insertInto("journalLine")+ .values(+ args.lines.map((line) => ({+ journalId,+ accountId: line.accountId,+ description: line.description,+ amount: round(line.amount),+ quantity: 1,+ documentType: "Asset Transfer" as const,+ documentId: args.documentId,+ documentLineReference: args.documentLineReference ?? null,+ journalLineReference,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const tagValues: Array<[string, string | null]> = [+ ["Location", args.tags.locationId],+ ["FixedAssetClass", args.tags.fixedAssetClassId],+ ["Item", args.tags.itemId]+ ];+ const dimensionInserts = journalLines.flatMap((line) =>+ tagValues+ .filter(+ ([entityType, valueId]) => accounting.dimensions[entityType] && valueId+ )+ .map(([entityType, valueId]) => ({+ journalLineId: line.id,+ dimensionId: accounting.dimensions[entityType] as string,+ valueId: valueId as string,+ companyId+ }))+ );+ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }++ return journalId;+ }++ type AssetRow = {+ id: string;+ fixedAssetId: string;+ fixedAssetClassId: string;+ name: string;+ status: Database["public"]["Enums"]["fixedAssetStatus"];+ itemId: string | null;+ trackedEntityId: string | null;+ locationId: string | null;+ acquisitionCost: number;+ accumulatedDepreciation: number;+ outOfServiceSince: unknown;+ };++ async function getAsset(+ db: Db,+ companyId: string,+ id: string+ ): Promise<AssetRow> {+ const asset = await db+ .selectFrom("fixedAsset")+ .select([+ "id",+ "fixedAssetId",+ "fixedAssetClassId",+ "name",+ "status",+ "itemId",+ "trackedEntityId",+ "locationId",+ "acquisitionCost",+ "accumulatedDepreciation",+ "outOfServiceSince"+ ])+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!asset) throw new NotFoundError("Fixed asset not found");+ return {+ ...asset,+ acquisitionCost: Number(asset.acquisitionCost ?? 0),+ accumulatedDepreciation: Number(asset.accumulatedDepreciation ?? 0)+ };+ }++ type AssetClassRow = {+ id: string;+ name: string;+ assetAccountId: string;+ accumulatedDepreciationAccountId: string;+ isConstructionInProgress: boolean;+ depreciationMethod: Database["public"]["Enums"]["depreciationMethod"];+ usefulLifeMonths: number;+ residualValuePercent: number;+ };++ async function getAssetClass(+ db: Db,+ companyId: string,+ id: string+ ): Promise<AssetClassRow> {+ const assetClass = await db+ .selectFrom("fixedAssetClass")+ .select([+ "id",+ "name",+ "assetAccountId",+ "accumulatedDepreciationAccountId",+ "isConstructionInProgress",+ "depreciationMethod",+ "usefulLifeMonths",+ "residualValuePercent"+ ])+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!assetClass) throw new NotFoundError("Fixed asset class not found");+ return assetClass;+ }++ type InventoryItem = {+ id: string;+ name: string;+ readableId: string;+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"] | null;+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null;+ itemPostingGroupId: string | null;+ itemCost: {+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];+ unitCost: number | null;+ standardCost: number | null;+ };+ };++ async function getInventoryItem(+ db: Db,+ companyId: string,+ itemId: string+ ): Promise<InventoryItem> {+ const [item, itemCost] = await inOrder([+ () =>+ db+ .selectFrom("item")+ .select([+ "id",+ "name",+ "readableId",+ "itemTrackingType",+ "replenishmentSystem"+ ])+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst(),+ () =>+ db+ .selectFrom("itemCost")+ .select([+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ ]);+ if (!item) throw new NotFoundError("Item not found");+ if (!itemCost) throw new NotFoundError("Item cost not found");+ return {+ ...item,+ itemPostingGroupId: itemCost.itemPostingGroupId,+ itemCost: {+ costingMethod: itemCost.costingMethod,+ unitCost: itemCost.unitCost,+ standardCost: itemCost.standardCost+ }+ };+ }++ type TrackedEntityRow = {+ id: string;+ itemId: string | null;+ readableId: string | null;+ status: Database["public"]["Enums"]["trackedEntityStatus"];+ };++ async function getTrackedEntity(+ db: Db,+ companyId: string,+ id: string+ ): Promise<TrackedEntityRow> {+ const entity = await db+ .selectFrom("trackedEntity")+ .select(["id", "itemId", "readableId", "status"])+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new NotFoundError("Tracked entity not found");+ return entity;+ }++ // The traceability graph records the asset as the consumer (capitalize) or+ // the producer (return) of the unit, mirroring complete_job_to_inventory's+ // 'Capitalize' activity.+ async function insertAssetActivity(+ trx: Trx,+ args: {+ type: "Capitalize" | "Return to Inventory";+ direction: "input" | "output";+ asset: { id: string; fixedAssetId: string };+ trackedEntityId: string;+ companyId: string;+ userId: string;+ }+ ): Promise<void> {+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: args.type,+ sourceDocument: "Fixed Asset",+ sourceDocumentId: args.asset.id,+ sourceDocumentReadableId: args.asset.fixedAssetId,+ attributes: { "Fixed Asset": args.asset.id },+ companyId: args.companyId,+ createdBy: args.userId+ })+ .execute();+ await trx+ .insertInto(+ args.direction === "input"+ ? "trackedActivityInput"+ : "trackedActivityOutput"+ )+ .values({+ trackedActivityId: activityId,+ trackedEntityId: args.trackedEntityId,+ quantity: 1,+ companyId: args.companyId,+ createdBy: args.userId+ })+ .execute();+ }++ async function postTransfer(+ trx: Trx,+ args: {+ id: string;+ amount: number;+ journalId: string | null;+ companyId: string;+ userId: string;+ }+ ): Promise<void> {+ await trx+ .updateTable("fixedAssetTransfer")+ .set({+ amount: round(args.amount),+ journalId: args.journalId,+ status: "Posted",+ postedAt: datetime.timestamp(),+ postedBy: args.userId,+ updatedAt: datetime.timestamp(),+ updatedBy: args.userId+ })+ .where("id", "=", args.id)+ .where("companyId", "=", args.companyId)+ .execute();+ }++ async function capitalize(+ db: Db,+ payload: Scoped<"capitalize">+ ): Promise<AssetTransferResult> {+ const { companyId, userId, itemId, trackedEntityId, locationId } = payload;++ const [assetClass, item, entity] = await inOrder([+ () => getAssetClass(db, companyId, payload.fixedAssetClassId),+ () => getInventoryItem(db, companyId, itemId),+ () => getTrackedEntity(db, companyId, trackedEntityId),+ () =>+ assertCompanyRecords(db, "location", [locationId], companyId, "Location"),+ () =>+ assertCompanyRecords(+ db,+ "storageUnit",+ [payload.storageUnitId],+ companyId,+ "Storage unit"+ )+ ]);+ const draftAsset = payload.fixedAssetId+ ? await getAsset(db, companyId, payload.fixedAssetId)+ : null;++ if (entity.itemId !== itemId) {+ throw new InvalidInputError("The unit does not belong to this item");+ }+ if (entity.status !== "Available") {+ throw new InvalidInputError(+ `Only an Available unit can be capitalized; ${+ entity.readableId ?? entity.id+ } is ${entity.status}`+ );+ }+ if (draftAsset && draftAsset.status !== "Draft") {+ throw new InvalidInputError(+ `Asset ${draftAsset.fixedAssetId} is ${draftAsset.status}; only a Draft asset can be filled`+ );+ }++ // The partial unique index refuses two live assets on one unit as well; the+ // read gives the caller a reason instead of a constraint name.+ const liveAsset = await db+ .selectFrom("fixedAsset")+ .select("fixedAssetId")+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .where("status", "<>", "Disposed")+ .limit(1)+ .executeTakeFirst();+ if (liveAsset) {+ throw new InvalidInputError(+ `${+ entity.readableId ?? entity.id+ } is already on asset ${liveAsset.fixedAssetId}`+ );+ }++ const accounting = await loadAccounting(db, companyId, payload.transferDate);+ // Only read when a cost was entered; whether one may be is decided once the+ // unit's carrying cost is known, inside the transaction.+ const offsetAccount =+ payload.cost != null+ ? await getOffsetAccount(db, companyId, payload.offsetAccountId)+ : null;+ const serial = entity.readableId ?? entity.id;+ const status = assetClass.isConstructionInProgress+ ? ("Under Construction" as const)+ : ("Active" as const);++ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {+ await assertPostingStatusUnchanged(+ trx,+ companyId,+ accounting.postingStatus+ );+ // Net on-hand per bin at the location, read inside the transaction so the+ // consumption below books against the same snapshot.+ const stockRows = await trx+ .selectFrom("itemLedger")+ .select([+ "storageUnitId",+ (eb) => eb.fn.sum<number>("quantity").as("onHand")+ ])+ .where("trackedEntityId", "=", trackedEntityId)+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .groupBy("storageUnitId")+ .execute();+ const stock = resolveCapitalizationStock(+ stockRows,+ payload.storageUnitId ?? null+ );+ if (round(stock.onHand) !== 1) {+ throw new InvalidInputError(+ `${serial} must have exactly one unit on hand at this location (found ${round(+ stock.onHand+ )})`+ );+ }++ const transferId = await getNextSequenceInTransaction(+ trx,+ "fixedAssetTransfer",+ companyId+ );++ // The asset first: the transfer references it. Its cost is filled in once+ // the ledger has relieved the unit's carrying value below.+ let asset: { id: string; fixedAssetId: string };+ const assetFields = {+ fixedAssetClassId: assetClass.id,+ itemId,+ trackedEntityId,+ serialNumber: entity.readableId,+ locationId,+ acquisitionDate: payload.transferDate,+ // A CIP asset does not depreciate until it is capitalized.+ depreciationStartDate: assetClass.isConstructionInProgress+ ? null+ : payload.transferDate,+ depreciationMethod: assetClass.depreciationMethod,+ usefulLifeMonths: assetClass.usefulLifeMonths,+ residualValuePercent: assetClass.residualValuePercent,+ status+ };+ if (draftAsset) {+ // Same Draft race guard as registration: a concurrent fill or disposal+ // wins and this transaction rolls back.+ const filled = await trx+ .updateTable("fixedAsset")+ .set({+ ...assetFields,+ ...(payload.name ? { name: payload.name } : {}),+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", draftAsset.id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Draft")+ .executeTakeFirst();+ if (!filled.numUpdatedRows) {+ throw new InvalidInputError("Asset is no longer in Draft status");+ }+ asset = { id: draftAsset.id, fixedAssetId: draftAsset.fixedAssetId };+ } else {+ const fixedAssetId = await getNextSequenceInTransaction(+ trx,+ "fixedAsset",+ companyId+ );+ const inserted = await trx+ .insertInto("fixedAsset")+ .values({+ ...assetFields,+ fixedAssetId,+ name: payload.name?.trim() || `${item.name} ${serial}`,+ quantity: 1,+ acquisitionCost: 0,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ asset = { id: inserted.id, fixedAssetId };+ }++ const transfer = await trx+ .insertInto("fixedAssetTransfer")+ .values({+ transferId,+ type: "Capitalization",+ sourceType: "Inventory",+ fixedAssetId: asset.id,+ itemId,+ trackedEntityId,+ locationId,+ storageUnitId: stock.storageUnitId,+ quantity: 1,+ transferDate: payload.transferDate,+ amount: 0,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // Relieve the unit from stock at its carrying cost — the same layer+ // consumer shipments use, for any costing method. accounting: null keeps+ // the core from posting a variance journal; the asset journal is below.+ const booked = await bookAdjustment(trx, {+ ledger: {+ postingDate: payload.transferDate,+ itemId,+ quantity: -1,+ locationId,+ storageUnitId: stock.storageUnitId,+ trackedEntityId,+ entryType: "Negative Adjmt.",+ documentType: "Asset Transfer",+ documentId: transfer.id,+ companyId,+ createdBy: userId+ },+ item: {+ itemTrackingType: item.itemTrackingType,+ replenishmentSystem: item.replenishmentSystem,+ itemPostingGroupId: item.itemPostingGroupId+ },+ itemCost: item.itemCost,+ accounting: null+ });+ // The transfer moves the value inventory already holds. A unit carried at+ // nothing (a job that recorded no production or material, a no-cost+ // issue) would become an asset worth nothing with no journal to say so,+ // so it takes the cost the user entered instead — booked from the offset+ // account that value was spent from — and is refused without one.+ const resolved = resolveCapitalizationCost({+ carried: round(booked.cost),+ entered: payload.cost == null ? null : round(payload.cost),+ serial,+ itemReadableId: item.readableId+ });+ if ("error" in resolved) throw new InvalidInputError(resolved.error);+ const cost = resolved.cost;++ const inventoryAccount = resolveInventoryAccount(+ item.replenishmentSystem,+ accounting.accountDefaults+ );+ const credit =+ resolved.source === "entered" && offsetAccount+ ? {+ account: offsetAccount.id,+ description: "Capitalized Cost",+ type: offsetAccount.type+ }+ : { ...inventoryAccount, type: "asset" as const };+ const journalId = await postAssetJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: payload.transferDate,+ description: `Capitalize ${item.readableId} ${serial} → ${asset.fixedAssetId}`,+ lines: buildCapitalizationLines({+ cost,+ assetAccountId: assetClass.assetAccountId,+ creditAccountId: credit.account,+ creditDescription: credit.description,+ creditAccountType: credit.type+ }),+ documentId: transfer.id,+ tags: { locationId, fixedAssetClassId: assetClass.id, itemId }+ });++ await trx+ .updateTable("fixedAsset")+ .set({+ acquisitionCost: cost,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .execute();++ // A CIP-class asset is later capitalized for Σ fixedAssetCipCost, so the+ // value that arrived from stock has to be on that ledger too.+ if (assetClass.isConstructionInProgress) {+ await trx+ .insertInto("fixedAssetCipCost")+ .values({+ fixedAssetId: asset.id,+ sourceType: "Manual",+ sourceDocumentId: transfer.id,+ amount: cost,+ costDate: payload.transferDate,+ journalId,+ companyId,+ createdBy: userId+ })+ .execute();+ }++ // The unit is consumed into the asset: no longer stock, and the asset id+ // on its attributes is how the fleet finds it again.+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ attributes: sql<Json>`COALESCE("attributes", '{}'::jsonb) || jsonb_build_object('Fixed Asset', ${asset.id}::text)`+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ await insertAssetActivity(trx, {+ type: "Capitalize",+ direction: "input",+ asset,+ trackedEntityId,+ companyId,+ userId+ });++ await postTransfer(trx, {+ id: transfer.id,+ amount: cost,+ journalId,+ companyId,+ userId+ });++ return {+ id: transfer.id,+ transferId,+ fixedAssetId: asset.id,+ fixedAssetReadableId: asset.fixedAssetId+ };+ });+ }++ async function returnToInventory(+ db: Db,+ payload: Scoped<"return">+ ): Promise<AssetTransferResult> {+ const { companyId, userId, locationId } = payload;++ const asset = await getAsset(db, companyId, payload.fixedAssetId);+ if (!RETURNABLE_ASSET_STATUSES.has(asset.status)) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${asset.status}; only an Active or Fully Depreciated asset can be returned to inventory`+ );+ }+ if (asset.outOfServiceSince) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is out of service; return it to service first`+ );+ }+ if (!asset.itemId || !asset.trackedEntityId) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is not linked to a serialized inventory unit`+ );+ }+ const netBookValue = round(+ asset.acquisitionCost - asset.accumulatedDepreciation+ );+ if (netBookValue < 0) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} has a negative net book value`+ );+ }++ const assetItemId = asset.itemId;+ const assetTrackedEntityId = asset.trackedEntityId;+ const [assetClass, item, entity] = await inOrder([+ () => getAssetClass(db, companyId, asset.fixedAssetClassId),+ () => getInventoryItem(db, companyId, assetItemId),+ () => getTrackedEntity(db, companyId, assetTrackedEntityId),+ () =>+ assertCompanyRecords(db, "location", [locationId], companyId, "Location"),+ () =>+ assertCompanyRecords(+ db,+ "storageUnit",+ [payload.storageUnitId],+ companyId,+ "Storage unit"+ )+ ]);+ if (entity.status !== "Consumed") {+ throw new InvalidInputError(+ `Unit ${+ entity.readableId ?? entity.id+ } is ${entity.status}, not consumed into the asset`+ );+ }++ const accounting = await loadAccounting(db, companyId, payload.transferDate);+ const serial = entity.readableId ?? entity.id;+ const trackedEntityId = entity.id;+ const itemId = item.id;++ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {+ await assertPostingStatusUnchanged(+ trx,+ companyId,+ accounting.postingStatus+ );+ // A unit reserved or on rent belongs to that agreement until it comes+ // back: the live-line statuses are the ones the fleetAssets view and the+ // rentalAgreementLine_asset_live_idx unique index key on.+ const liveLine = await trx+ .selectFrom("rentalAgreementLine as ral")+ .innerJoin("rentalAgreement as ra", (join) =>+ join+ .onRef("ra.id", "=", "ral.rentalAgreementId")+ .onRef("ra.companyId", "=", "ral.companyId")+ )+ .select(["ral.status", "ra.rentalAgreementId"])+ .where("ral.fixedAssetId", "=", asset.id)+ .where("ral.companyId", "=", companyId)+ .where("ral.status", "in", ["Pending", "On Rent"])+ .executeTakeFirst();+ if (liveLine) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${+ liveLine.status === "On Rent" ? "on rent" : "reserved"+ } on rental agreement ${liveLine.rentalAgreementId}; return it from the agreement first`+ );+ }++ const transferId = await getNextSequenceInTransaction(+ trx,+ "fixedAssetTransfer",+ companyId+ );+ const transfer = await trx+ .insertInto("fixedAssetTransfer")+ .values({+ transferId,+ type: "Return to Inventory",+ sourceType: "Inventory",+ fixedAssetId: asset.id,+ itemId,+ trackedEntityId,+ locationId,+ storageUnitId: payload.storageUnitId ?? null,+ quantity: 1,+ transferDate: payload.transferDate,+ amount: netBookValue,+ accumulatedDepreciation: round(asset.accumulatedDepreciation),+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // Back into stock at net book value: a cost layer at N stamped with the+ // serial, so under FIFO / LIFO that unit is later relieved at N (gross+ // revenue + COGS at N), not at the oldest layer (cost-layer-order.ts).+ await bookAdjustment(trx, {+ ledger: {+ postingDate: payload.transferDate,+ itemId,+ quantity: 1,+ locationId,+ storageUnitId: payload.storageUnitId ?? null,+ trackedEntityId,+ entryType: "Positive Adjmt.",+ documentType: "Asset Transfer",+ documentId: transfer.id,+ companyId,+ createdBy: userId+ },+ item: {+ itemTrackingType: item.itemTrackingType,+ replenishmentSystem: item.replenishmentSystem,+ itemPostingGroupId: item.itemPostingGroupId+ },+ itemCost: item.itemCost,+ accounting: null,+ fixedUnitCost: netBookValue+ });++ // An asset carried at zero cost has nothing on the books to move.+ let journalId: string | null = null;+ if (round(asset.acquisitionCost) > 0) {+ const inventoryAccount = resolveInventoryAccount(+ item.replenishmentSystem,+ accounting.accountDefaults+ );+ journalId = await postAssetJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: payload.transferDate,+ description: `Return to inventory ${asset.fixedAssetId} → ${item.readableId} ${serial}`,+ lines: buildReturnToInventoryLines({+ cost: asset.acquisitionCost,+ accumulatedDepreciation: asset.accumulatedDepreciation,+ inventoryAccountId: inventoryAccount.account,+ inventoryDescription: inventoryAccount.description,+ accounts: {+ assetAccountId: assetClass.assetAccountId,+ accumulatedDepreciationAccountId:+ assetClass.accumulatedDepreciationAccountId+ }+ }),+ documentId: transfer.id,+ tags: { locationId, fixedAssetClassId: assetClass.id, itemId }+ });+ }++ const disposed = await trx+ .updateTable("fixedAsset")+ .set({+ status: "Disposed",+ disposalMethod: "Transfer to Inventory",+ disposalDate: payload.transferDate,+ saleProceeds: 0,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .where("status", "in", [...RETURNABLE_ASSET_STATUSES])+ .executeTakeFirst();+ if (!disposed.numUpdatedRows) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} changed status while it was being returned`+ );+ }+ await trx+ .insertInto("fixedAssetDisposal")+ .values({+ fixedAssetId: asset.id,+ disposalMethod: "Transfer to Inventory",+ disposalDate: payload.transferDate,+ saleProceeds: 0,+ netBookValueAtDisposal: netBookValue,+ gainLoss: 0,+ journalId,+ companyId,+ createdBy: userId+ })+ .execute();++ // The return inspection already happened on the agreement, so the unit+ // comes back Available (an RMA reactivates to On Hold because none has).+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ attributes: sql<Json>`COALESCE("attributes", '{}'::jsonb) - 'Fixed Asset'`+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ await insertAssetActivity(trx, {+ type: "Return to Inventory",+ direction: "output",+ asset,+ trackedEntityId,+ companyId,+ userId+ });++ await postTransfer(trx, {+ id: transfer.id,+ amount: netBookValue,+ journalId,+ companyId,+ userId+ });++ return {+ id: transfer.id,+ transferId,+ fixedAssetId: asset.id,+ fixedAssetReadableId: asset.fixedAssetId+ };+ });+ }++ async function attachJob(+ db: Db,+ payload: Scoped<"attachJob">+ ): Promise<AssetTransferResult> {+ const { companyId, userId, jobId } = payload;++ const asset = await getAsset(db, companyId, payload.fixedAssetId);+ const [assetClass, jobRow] = await inOrder([+ () => getAssetClass(db, companyId, asset.fixedAssetClassId),+ () =>+ db+ .selectFrom("job")+ .select([+ "id",+ "jobId",+ "itemId",+ "status",+ "locationId",+ "salesOrderLineId",+ "fixedAssetClassId",+ "fixedAssetId"+ ])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ ]);+ if (!jobRow) throw new NotFoundError("Job not found");+ const job = jobRow;++ if (!assetClass.isConstructionInProgress) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is not in a Construction in Progress class`+ );+ }+ if (asset.status !== "Draft" && asset.status !== "Under Construction") {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${asset.status}; a job can only be attached while it is Draft or Under Construction`+ );+ }+ if (CLOSED_JOB_STATUSES.has(job.status)) {+ throw new InvalidInputError(+ `Job ${job.jobId} is ${job.status} and can no longer be attached to an asset`+ );+ }+ if (job.salesOrderLineId) {+ throw new InvalidInputError(+ `Job ${job.jobId} is linked to a sales order line and cannot build an asset`+ );+ }+ if (job.fixedAssetClassId || job.fixedAssetId) {+ throw new InvalidInputError(+ `Job ${job.jobId} already completes to a fixed asset`+ );+ }++ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+ const accounting = await loadAccounting(db, companyId, today);++ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {+ await assertPostingStatusUnchanged(+ trx,+ companyId,+ accounting.postingStatus+ );+ // The job's WIP balance so far: cost leaves WIP at attachment (SAP AuC).+ // Before the cutover it sits in Provisional journals and is swept by one.+ const wip = await trx+ .selectFrom("journalLine as jl")+ .innerJoin("journal as j", (join) =>+ join+ .onRef("j.id", "=", "jl.journalId")+ .onRef("j.companyId", "=", "jl.companyId")+ )+ .select((eb) =>+ eb.fn+ .coalesce(eb.fn.sum<number>("jl.amount"), sql<number>`0`)+ .as("balance")+ )+ .where(+ "jl.accountId",+ "=",+ accounting.accountDefaults.workInProgressAccount+ )+ .where("jl.documentId", "=", jobId)+ .where("jl.companyId", "=", companyId)+ .where("j.status", "in", [...DOCUMENT_JOURNAL_STATUSES])+ .executeTakeFirst();+ const balance = round(Number(wip?.balance ?? 0));++ let result: Pick<AssetTransferResult, "id" | "transferId"> = {+ id: null,+ transferId: null+ };+ if (balance > 0) {+ const transferId = await getNextSequenceInTransaction(+ trx,+ "fixedAssetTransfer",+ companyId+ );+ const transfer = await trx+ .insertInto("fixedAssetTransfer")+ .values({+ transferId,+ type: "Capitalization",+ sourceType: "Job",+ fixedAssetId: asset.id,+ itemId: job.itemId,+ jobId,+ locationId: job.locationId,+ quantity: 1,+ transferDate: today,+ amount: balance,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // Both lines carry the job as documentId so the per-job WIP balance+ // still nets to zero; the transfer rides in documentLineReference.+ const journalId = await postAssetJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: today,+ description: `Attach job ${job.jobId} → ${asset.fixedAssetId}`,+ lines: buildCapitalizationLines({+ cost: balance,+ assetAccountId: assetClass.assetAccountId,+ creditAccountId: accounting.accountDefaults.workInProgressAccount,+ creditDescription: "WIP Account"+ }),+ documentId: jobId,+ documentLineReference: transferId,+ tags: {+ locationId: job.locationId,+ fixedAssetClassId: assetClass.id,+ itemId: job.itemId+ }+ });++ await trx+ .insertInto("fixedAssetCipCost")+ .values({+ fixedAssetId: asset.id,+ sourceType: "Job",+ jobId,+ amount: balance,+ costDate: today,+ journalId,+ companyId,+ createdBy: userId+ })+ .execute();++ await postTransfer(trx, {+ id: transfer.id,+ amount: balance,+ journalId,+ companyId,+ userId+ });+ result = { id: transfer.id, transferId };+ }++ // The link itself: guarded on the job still having no target, so two+ // concurrent attachments cannot both win.+ const linked = await trx+ .updateTable("job")+ .set({+ fixedAssetId: asset.id,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .where("fixedAssetId", "is", null)+ .where("fixedAssetClassId", "is", null)+ .executeTakeFirst();+ if (!linked.numUpdatedRows) {+ throw new InvalidInputError(+ `Job ${job.jobId} already completes to a fixed asset`+ );+ }+ // Guarded on the status read above and written relative to the row as+ // it is now: a concurrent capitalization or another attachment must not+ // be overwritten with a cost read before this transaction began.+ const swept = await trx+ .updateTable("fixedAsset")+ .set({+ status: "Under Construction",+ acquisitionCost: sql<number>`COALESCE("acquisitionCost", 0) + ${balance}`,+ // A self-built asset lives where it is built (post-receipt precedent:+ // the receiving location fills an unset asset location).+ locationId: sql<+ string | null+ >`COALESCE("locationId", ${job.locationId})`,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .where("status", "in", ["Draft", "Under Construction"])+ .executeTakeFirst();+ if (!swept.numUpdatedRows) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is no longer Draft or Under Construction`+ );+ }++ return {+ ...result,+ fixedAssetId: asset.id,+ fixedAssetReadableId: asset.fixedAssetId+ };+ });+ }++ async function capitalizeCip(+ db: Db,+ payload: Scoped<"capitalizeCip">+ ): Promise<AssetTransferResult> {+ const { companyId, userId, inServiceDate } = payload;++ const asset = await getAsset(db, companyId, payload.fixedAssetId);+ const [cipClass, targetClass] = await inOrder([+ () => getAssetClass(db, companyId, asset.fixedAssetClassId),+ () => getAssetClass(db, companyId, payload.toClassId)+ ]);++ if (asset.status !== "Under Construction") {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${asset.status}; only an Under Construction asset can be capitalized`+ );+ }+ if (!cipClass.isConstructionInProgress) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is not in a Construction in Progress class`+ );+ }+ if (targetClass.isConstructionInProgress) {+ throw new InvalidInputError(+ `${targetClass.name} is a Construction in Progress class; choose the in-service class`+ );+ }++ // The transfer document needs a location: the asset's own, else the site+ // of the job that built it.+ let locationId = asset.locationId;+ if (!locationId) {+ const builder = await db+ .selectFrom("job")+ .select("locationId")+ .where("fixedAssetId", "=", asset.id)+ .where("companyId", "=", companyId)+ .orderBy("createdAt", "desc")+ .limit(1)+ .executeTakeFirst();+ locationId = builder?.locationId ?? null;+ }+ if (!locationId) {+ throw new InvalidInputError(+ `Set a location on asset ${asset.fixedAssetId} before capitalizing it`+ );+ }+ const assetLocationId = locationId;++ const accounting = await loadAccounting(db, companyId, inServiceDate);++ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {+ await assertPostingStatusUnchanged(+ trx,+ companyId,+ accounting.postingStatus+ );+ // Lock the asset before summing its cost rows: an attachment or a+ // receipt adding a row after the sum would be left out of the+ // capitalized cost while the asset leaves Under Construction.+ const locked = await trx+ .selectFrom("fixedAsset")+ .select("status")+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (locked?.status !== "Under Construction") {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is no longer Under Construction`+ );+ }++ const cipCost = await trx+ .selectFrom("fixedAssetCipCost")+ .select((eb) =>+ eb.fn.coalesce(eb.fn.sum<number>("amount"), sql<number>`0`).as("total")+ )+ .where("fixedAssetId", "=", asset.id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const total = round(Number(cipCost?.total ?? 0));+ if (total <= 0) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} has no Construction in Progress cost to capitalize`+ );+ }++ const transferId = await getNextSequenceInTransaction(+ trx,+ "fixedAssetTransfer",+ companyId+ );+ const transfer = await trx+ .insertInto("fixedAssetTransfer")+ .values({+ transferId,+ type: "Capitalization",+ sourceType: "Construction in Progress",+ fixedAssetId: asset.id,+ itemId: asset.itemId,+ trackedEntityId: asset.trackedEntityId,+ fromClassId: cipClass.id,+ locationId: assetLocationId,+ quantity: 1,+ transferDate: inServiceDate,+ inServiceDate,+ amount: total,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalId = await postAssetJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: inServiceDate,+ description: `Capitalize ${asset.fixedAssetId} — ${cipClass.name} → ${targetClass.name}`,+ lines: buildCapitalizationLines({+ cost: total,+ assetAccountId: targetClass.assetAccountId,+ creditAccountId: cipClass.assetAccountId,+ creditDescription: "Construction in Progress"+ }),+ documentId: transfer.id,+ tags: {+ locationId: assetLocationId,+ fixedAssetClassId: targetClass.id,+ itemId: asset.itemId+ }+ });++ // Depreciation starts at the in-service date under the in-service class's+ // policy; the CIP class's method / life / residual were placeholders that+ // never ran.+ const capitalized = await trx+ .updateTable("fixedAsset")+ .set({+ fixedAssetClassId: targetClass.id,+ acquisitionCost: total,+ acquisitionDate: inServiceDate,+ depreciationStartDate: inServiceDate,+ depreciationMethod: targetClass.depreciationMethod,+ usefulLifeMonths: targetClass.usefulLifeMonths,+ residualValuePercent: targetClass.residualValuePercent,+ locationId: assetLocationId,+ status: "Active",+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Under Construction")+ .executeTakeFirst();+ if (!capitalized.numUpdatedRows) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is no longer Under Construction`+ );+ }++ await postTransfer(trx, {+ id: transfer.id,+ amount: total,+ journalId,+ companyId,+ userId+ });++ return {+ id: transfer.id,+ transferId,+ fixedAssetId: asset.id,+ fixedAssetReadableId: asset.fixedAssetId+ };+ });+ }++ async function adjustCost(+ db: Db,+ payload: Scoped<"adjustCost">+ ): Promise<AssetTransferResult> {+ const { companyId, userId, locationId } = payload;++ const asset = await getAsset(db, companyId, payload.fixedAssetId);+ if (!ADJUSTABLE_ASSET_STATUSES.has(asset.status)) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${asset.status}; only an Active or Fully Depreciated asset's cost can be adjusted`+ );+ }+ const [assetClass] = await inOrder([+ () => getAssetClass(db, companyId, asset.fixedAssetClassId),+ () =>+ assertCompanyRecords(db, "location", [locationId], companyId, "Location")+ ]);++ const amount = round(payload.amount);+ if (amount <= 0) {+ throw new InvalidInputError("The cost adjustment must be more than zero");+ }++ const accounting = await loadAccounting(db, companyId, payload.transferDate);+ const offsetAccount = await getOffsetAccount(+ db,+ companyId,+ payload.offsetAccountId+ );++ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {+ await assertPostingStatusUnchanged(+ trx,+ companyId,+ accounting.postingStatus+ );+ // Re-read under a row lock: a concurrent run, disposal or adjustment+ // changes the values the new status is derived from.+ const current = await trx+ .selectFrom("fixedAsset")+ .select([+ "status",+ "acquisitionCost",+ "accumulatedDepreciation",+ "residualValuePercent"+ ])+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (!ADJUSTABLE_ASSET_STATUSES.has(current.status)) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} is ${current.status}; only an Active or Fully Depreciated asset's cost can be adjusted`+ );+ }+ const acquisitionCost = round(Number(current.acquisitionCost) + amount);++ const transferId = await getNextSequenceInTransaction(+ trx,+ "fixedAssetTransfer",+ companyId+ );+ const transfer = await trx+ .insertInto("fixedAssetTransfer")+ .values({+ transferId,+ type: "Cost Adjustment",+ sourceType: "Manual",+ fixedAssetId: asset.id,+ itemId: asset.itemId,+ trackedEntityId: asset.trackedEntityId,+ locationId,+ quantity: 1,+ transferDate: payload.transferDate,+ amount: 0,+ accumulatedDepreciation: Number(current.accumulatedDepreciation),+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalId = await postAssetJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: payload.transferDate,+ description: `Cost Adjustment ${asset.fixedAssetId}`,+ lines: buildCapitalizationLines({+ cost: amount,+ assetAccountId: assetClass.assetAccountId,+ creditAccountId: offsetAccount.id,+ creditDescription: "Capitalized Cost",+ creditAccountType: offsetAccount.type+ }),+ documentId: transfer.id,+ tags: {+ locationId,+ fixedAssetClassId: assetClass.id,+ itemId: asset.itemId+ }+ });++ // Depreciation already taken stays; the next run catches a Straight Line+ // asset up on the months it took at the old cost (buildDepreciationLines).+ const adjusted = await trx+ .updateTable("fixedAsset")+ .set({+ acquisitionCost,+ status: statusAfterCostAdjustment({+ status: current.status,+ acquisitionCost,+ accumulatedDepreciation: Number(current.accumulatedDepreciation),+ residualValuePercent: Number(current.residualValuePercent)+ }),+ locationId: asset.locationId ?? locationId,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", asset.id)+ .where("companyId", "=", companyId)+ .where("status", "in", [...ADJUSTABLE_ASSET_STATUSES])+ .executeTakeFirst();+ if (!adjusted.numUpdatedRows) {+ throw new InvalidInputError(+ `Asset ${asset.fixedAssetId} changed status while its cost was being adjusted`+ );+ }++ await postTransfer(trx, {+ id: transfer.id,+ amount,+ journalId,+ companyId,+ userId+ });++ return {+ id: transfer.id,+ transferId,+ fixedAssetId: asset.id,+ fixedAssetReadableId: asset.fixedAssetId+ };+ });+ }++ export const postAssetTransferPermission = {+ by: "type",+ rules: {+ capitalize: { create: "accounting" },+ return: { create: "accounting" },+ attachJob: { create: "accounting" },+ capitalizeCip: { create: "accounting" },+ adjustCost: { update: "accounting" }+ }+ } satisfies PermissionRule<z.output<typeof postAssetTransferInput>>;++ /**+ * Creates and posts one `fixedAssetTransfer` document between inventory and+ * the fixed asset register, per `type`. Every record id in the input is+ * re-read under companyId before anything is written.+ */+ export async function postAssetTransfer(+ ctx: ServiceContext,+ raw: z.input<typeof postAssetTransferInput>+ ) {+ const input = postAssetTransferInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ switch (input.type) {+ case "capitalize":+ // An entered cost puts a number of the caller's own on the books.+ if (input.cost != null && !ctx.can({ update: "accounting" })) {+ throw new ForbiddenError();+ }+ return capitalize(db, { ...input, companyId, userId });+ case "return":+ return returnToInventory(db, { ...input, companyId, userId });+ case "attachJob":+ return attachJob(db, { ...input, companyId, userId });+ case "capitalizeCip":+ return capitalizeCip(db, { ...input, companyId, userId });+ case "adjustCost":+ return adjustCost(db, { ...input, companyId, userId });+ }+ }+ export const previewAssetCapitalizationInput = z.object({+ trackedEntityId: z.string().min(1)+ });++ export type CapitalizationPreview = { cost: number };++ /** Thrown at the end of the preview transaction so it never commits. */+ class RollbackPreview extends Error {+ constructor(readonly preview: CapitalizationPreview) {+ super("preview rollback");+ }+ }++ export const previewAssetCapitalizationPermission = {+ view: "accounting"+ } satisfies PermissionRule<z.output<typeof previewAssetCapitalizationInput>>;++ export async function previewAssetCapitalization(+ ctx: ServiceContext,+ raw: z.input<typeof previewAssetCapitalizationInput>+ ) {+ const { trackedEntityId } = previewAssetCapitalizationInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const entity = await db+ .selectFrom("trackedEntity")+ .select("itemId")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity?.itemId) throw new NotFoundError("Tracked entity not found");+ const itemId = entity.itemId;++ try {+ await db.transaction().execute(async (trx) => {+ const cogs = await calculateCOGS(trx, {+ itemId,+ quantity: 1,+ companyId,+ trackedEntityIds: [trackedEntityId]+ });+ throw new RollbackPreview({ cost: round(cogs.totalCost) });+ });+ } catch (error) {+ if (error instanceof RollbackPreview) return error.preview;+ throw error;+ }+ throw new Error("Capitalization preview did not roll back");+ }+ const logger = getLogger("server-functions", "apply-account-import");++ /** A trimmed, non-empty text value. */+ const text = () => z.string().trim().min(1);++ export const applyAccountImportInput = z.object({+ chart: z+ .array(+ z.object({+ line: z.number().int(),+ number: text(),+ name: text(),+ class: z+ .enum(["Asset", "Liability", "Equity", "Revenue", "Expense"])+ .nullable(),+ accountType: z+ .enum(ACCOUNT_TYPES as [AccountType, ...AccountType[]])+ .nullable(),+ group: text()+ })+ )+ .min(1)+ .max(10000),+ defaults: z+ .array(+ z.object({+ line: z.number().int(),+ key: text(),+ number: text().nullable()+ })+ )+ .min(1)+ .max(2000),+ resolutions: z.object({ targets: z.record(z.string(), z.number().int()) })+ });++ export type ApplyAccountImportResult = {+ counts: { updated: number; created: number; merged: number; deleted: number };+ };++ type ChartRow = z.infer<typeof applyAccountImportInput>["chart"][number];++ const key = (value: string) => value.trim().toLowerCase();++ /** Re-point every reference a merge moves, from each source to its target. */+ async function repointReferences(+ trx: Trx,+ pairs: { source: string; target: string }[],+ companyIds: string[]+ ) {+ const m = sql`(VALUES ${sql.join(+ pairs.map((p) => sql`(${p.source}, ${p.target})`)+ )}) AS m(source, target)`;+ const inCompanies = sql`t."companyId" IN (${sql.join(companyIds)})`;+ for (const ref of REFERENCE_POLICY) {+ const t = sql.table(ref.table);+ const col = sql.id(ref.column);+ const matches = sql`t.${col} = m.source AND ${inCompanies}`;+ switch (ref.policy) {+ case "history":+ continue;+ case "repoint":+ await sql`UPDATE ${t} AS t SET ${col} = m.target FROM ${m}+ WHERE ${matches}`.execute(trx);+ continue;+ case "repoint-if-status":+ await sql`UPDATE ${t} AS t SET ${col} = m.target FROM ${m}+ WHERE ${matches}+ AND t."status"::text IN (${sql.join(ref.statuses.map((x) => sql.lit(x)))})`.execute(+ trx+ );+ continue;+ case "repoint-if-parent-status":+ await sql`UPDATE ${t} AS t SET ${col} = m.target+ FROM ${m}, ${sql.table(ref.parentTable)} AS p+ WHERE ${matches}+ AND p."id" = t.${sql.id(ref.parentColumn)} AND p."companyId" = t."companyId"+ AND p."status"::text IN (${sql.join(ref.statuses.map((x) => sql.lit(x)))})`.execute(+ trx+ );+ continue;+ }+ }++ // The references with no foreign key.+ await sql`UPDATE "intercompanyEliminationLine" AS t+ SET "accountId" = m.target+ FROM ${m}, "journalLine" AS jl, "journal" AS j+ WHERE t."accountId" = m.source AND ${inCompanies}+ AND jl."id" = t."journalLineId" AND j."id" = jl."journalId"+ AND j."status" IN ('Draft', 'Provisional')`.execute(trx);+ await sql`UPDATE "companyIntegration" AS t+ SET "metadata" = jsonb_set(t."metadata"::jsonb, '{paymentFeeAccount}', to_jsonb(m.target::text))::json+ FROM ${m}+ WHERE t."metadata"->>'paymentFeeAccount' = m.source AND ${inCompanies}`.execute(+ trx+ );+ }++ export const applyAccountImportPermission = {+ update: "accounting"+ } satisfies PermissionRule<z.output<typeof applyAccountImportInput>>;++ export async function applyAccountImport(+ ctx: ServiceContext,+ raw: z.input<typeof applyAccountImportInput>+ ) {+ const { chart, defaults, resolutions } = applyAccountImportInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ return db.transaction().execute(async (trx) => {+ const company = await trx+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirst();+ if (!company?.companyGroupId) {+ throw new NotFoundError("Company not found");+ }+ const groupId = company.companyGroupId;++ // Nothing may activate accounting, or change the chart, while the plan+ // is applied. Settings first, in the order activation takes them.+ await sql`SELECT cs."id" FROM "companySettings" cs+ JOIN "company" c ON c."id" = cs."id"+ WHERE c."companyGroupId" = ${groupId} FOR SHARE OF cs`.execute(trx);+ await sql`SELECT "id" FROM "account" WHERE "companyGroupId" = ${groupId} FOR UPDATE`.execute(+ trx+ );+ // Lets the charge and reimbursement guards accept the account change+ // of a posted row, for this transaction only (20261013035046).+ await sql`SELECT set_config('app.account_import', 'true', true)`.execute(+ trx+ );++ const ctx = await loadAccountImportContext(trx, groupId, companyId);+ const plan = planAccountImport(chart, defaults, ctx, resolutions);+ if (!isApplicable(plan)) {+ const open = plan.replacements.filter((r) => r.targetLine === null);+ throw new InvalidInputError(+ plan.errors.some((e) => e.code === "accounting-activated")+ ? "Accounting is already set up, so the chart of accounts cannot be imported."+ : `The import has ${plan.errors.length} error(s) and ${open.length} account(s) that need a replacement.`,+ { errors: plan.errors.map((e) => e.code) }+ );+ }++ const companyIds = ctx.companies.map((c) => c.id);+ const now = datetime.timestamp();+ const removed = [...plan.deletes, ...plan.merges.map((m) => m.sourceId)];++ // Groups. A group's name is unique among groups only, so a new group+ // never meets a leaf's name.+ const groupIdByName = new Map(+ ctx.chart.filter((a) => a.isGroup).map((g) => [key(g.name), g.id])+ );+ const rootByBalance = new Map(+ ctx.chart+ .filter((a) => a.isGroup && a.isSystem && a.parentId === null)+ .map((r) => [r.incomeBalance, r.id])+ );+ if (plan.groupCreates.length > 0) {+ const created = await trx+ .insertInto("account")+ .values(+ plan.groupCreates.map((g) => {+ const incomeBalance = incomeBalanceOf(g.class);+ const parentId = rootByBalance.get(incomeBalance);+ if (!parentId) throw new Error(`No ${incomeBalance} root account`);+ return {+ name: g.name,+ number: null,+ isGroup: true,+ class: g.class,+ incomeBalance,+ parentId,+ companyGroupId: groupId,+ createdBy: userId+ };+ })+ )+ .returning(["id", "name"])+ .execute();+ for (const g of created) groupIdByName.set(key(g.name), g.id);+ }+ const groupIdOf = (name: string) => {+ const id = groupIdByName.get(key(name));+ if (!id) throw new Error(`Unknown group "${name}"`);+ return id;+ };++ // Free every leaf number and name that changes or goes: two accounts+ // may swap, and a created account may reuse a removed one's.+ const freed = [...plan.updates.map((u) => u.accountId), ...removed];+ if (freed.length > 0) {+ await trx+ .updateTable("account")+ .set({+ number: sql`'__import_' || "id"`,+ name: sql`'__import_' || "id"`+ })+ .where("id", "in", freed)+ .where("companyGroupId", "=", groupId)+ .execute();+ }++ // Updates: the account keeps its id, so everything that points at it+ // follows.+ if (plan.updates.length > 0) {+ const values = sql.join(+ plan.updates.map(+ (u) =>+ sql`(${u.accountId}, ${u.number}, ${u.name}, ${u.accountType}, ${u.class}, ${incomeBalanceOf(u.class)}, ${groupIdOf(u.group)})`+ )+ );+ await sql`UPDATE "account" AS a SET+ "number" = v.number,+ "name" = v.name,+ "accountType" = v."accountType"::"accountType",+ "class" = v.class::"glAccountClass",+ "incomeBalance" = v."incomeBalance"::"glIncomeBalance",+ "parentId" = v."parentId",+ "active" = true,+ "updatedBy" = ${userId},+ "updatedAt" = ${now}+ FROM (VALUES ${values}) AS v(id, number, name, "accountType", class, "incomeBalance", "parentId")+ WHERE a."id" = v.id AND a."companyGroupId" = ${groupId}`.execute(trx);+ }++ // Creates.+ const accountIdByLine = new Map(+ plan.claims.map((c) => [c.line, c.accountId])+ );+ if (plan.creates.length > 0) {+ const created = await trx+ .insertInto("account")+ .values(+ plan.creates.map((c) => ({+ number: c.number,+ name: c.name,+ class: c.class,+ accountType: c.accountType,+ incomeBalance: incomeBalanceOf(c.class),+ parentId: groupIdOf(c.group),+ isGroup: false,+ companyGroupId: groupId,+ createdBy: userId+ }))+ )+ .returning(["id", "number"])+ .execute();+ const lineByNumber = new Map(plan.creates.map((c) => [c.number, c.line]));+ for (const c of created) {+ const line = c.number === null ? undefined : lineByNumber.get(c.number);+ if (line !== undefined) accountIdByLine.set(line, c.id);+ }+ }+ const accountOfLine = (line: number) => {+ const id = accountIdByLine.get(line);+ if (!id) throw new Error(`Row ${line} has no account`);+ return id;+ };++ await setDefaults(trx, plan, accountOfLine, companyIds, userId);+ await setAssetClasses(trx, plan, accountOfLine, userId, now);++ // Merges: the source's documents and unposted journal lines follow it+ // to its target.+ if (plan.merges.length > 0) {+ await repointReferences(+ trx,+ plan.merges.map((m) => ({+ source: m.sourceId,+ target: accountOfLine(m.targetLine)+ })),+ companyIds+ );+ }++ // Removed accounts: their integration mappings go with them. Journal+ // and document lines refuse the delete (ON DELETE RESTRICT) if anything+ // still points at one.+ if (removed.length > 0) {+ await trx+ .deleteFrom("externalIntegrationMapping")+ .where("entityType", "=", "account")+ .where("entityId", "in", removed)+ .where("companyId", "in", companyIds)+ .execute();+ await trx+ .deleteFrom("account")+ .where("id", "in", removed)+ .where("companyGroupId", "=", groupId)+ .execute();+ }++ // Groups left with no children, deepest first.+ for (;;) {+ const emptied = await sql`DELETE FROM "account" AS g+ WHERE g."companyGroupId" = ${groupId} AND g."isGroup" AND NOT g."isSystem"+ AND NOT EXISTS (SELECT 1 FROM "account" AS c WHERE c."parentId" = g."id")+ RETURNING g."id"`.execute(trx);+ if (emptied.rows.length === 0) break;+ }++ await assertPostcondition(trx, groupId, companyIds, chart);++ return {+ counts: {+ updated: plan.updates.length,+ created: plan.creates.length,+ merged: plan.merges.length,+ deleted: plan.deletes.length+ }+ };+ });+ }++ /** Every company's defaults, in one statement: the file names the same+ * account for a role in every company. */+ async function setDefaults(+ trx: Trx,+ plan: AccountImportPlan,+ accountOfLine: (line: number) => string,+ companyIds: string[],+ userId: string+ ) {+ const set = Object.fromEntries(+ plan.roleMoves.map((m) => [+ m.role,+ m.toLine === null ? null : accountOfLine(m.toLine)+ ])+ );+ await trx+ .updateTable("accountDefault")+ .set({ ...set, updatedBy: userId })+ .where("companyId", "in", companyIds)+ .execute();+ }++ /** Every fixed asset class's accounts, in one statement. */+ async function setAssetClasses(+ trx: Trx,+ plan: AccountImportPlan,+ accountOfLine: (line: number) => string,+ userId: string,+ now: string+ ) {+ if (plan.assetClassMoves.length === 0) return;+ const columns = sql.join(FIXED_ASSET_CLASS_COLUMNS.map((c) => sql.id(c)));+ const values = sql.join(+ plan.assetClassMoves.map(+ (m) =>+ sql`(${m.classId}, ${m.companyId}, ${sql.join(+ FIXED_ASSET_CLASS_COLUMNS.map((c) => accountOfLine(m.toLines[c]))+ )})`+ )+ );+ const assignments = sql.join(+ FIXED_ASSET_CLASS_COLUMNS.map((c) => sql`${sql.id(c)} = v.${sql.id(c)}`)+ );+ await sql`UPDATE "fixedAssetClass" AS t SET ${assignments},+ "updatedBy" = ${userId}, "updatedAt" = ${now}+ FROM (VALUES ${values}) AS v(id, "companyId", ${columns})+ WHERE t."id" = v.id AND t."companyId" = v."companyId"`.execute(trx);+ }++ /**+ * The chart now equals the file, and every company can still post. A failure+ * means the apply and the plan disagree: a server bug, so a plain Error (500),+ * and the transaction rolls back.+ */+ async function assertPostcondition(+ trx: Trx,+ groupId: string,+ companyIds: string[],+ chart: ChartRow[]+ ) {+ const accounts = await trx+ .selectFrom("account")+ .select([+ "id",+ "number",+ "name",+ "class",+ "accountType",+ "parentId",+ "isGroup",+ "isSystem"+ ])+ .where("companyGroupId", "=", groupId)+ .execute();+ const byId = new Map(accounts.map((a) => [a.id, a]));+ const leaves = accounts.filter((a) => !a.isGroup && !a.isSystem);+ const describe = (r: {+ number: string | null;+ name: string;+ class: string | null;+ accountType: string | null;+ group: string;+ }) =>+ [+ r.number ?? "",+ r.name,+ r.class ?? "",+ r.accountType ?? "",+ key(r.group)+ ].join("|");+ const actual = new Set(+ leaves.map((a) =>+ describe({ ...a, group: byId.get(a.parentId ?? "")?.name ?? "" })+ )+ );+ const failures: string[] = [];+ // A row with no class or type takes them from the plan; compare by number,+ // name and group for those.+ const expected = chart.map((r) =>+ r.class && r.accountType ? describe(r) : null+ );+ const loose = new Set(+ leaves.map((a) =>+ [+ a.number ?? "",+ a.name,+ key(byId.get(a.parentId ?? "")?.name ?? "")+ ].join("|")+ )+ );+ chart.forEach((r, i) => {+ const exact = expected[i];+ const found = exact+ ? actual.has(exact)+ : loose.has([r.number, r.name, key(r.group)].join("|"));+ if (!found)+ failures.push(`line ${r.line} was not written as the file says`);+ });+ if (leaves.length !== chart.length) {+ failures.push(`${leaves.length} accounts for ${chart.length} rows`);+ }+ if (+ accounts.some(+ (g) =>+ g.isGroup && !g.isSystem && !accounts.some((c) => c.parentId === g.id)+ )+ ) {+ failures.push("an empty group is left");+ }++ const leafIds = new Set(leaves.map((a) => a.id));+ const defaults = await trx+ .selectFrom("accountDefault")+ .select(["companyId", ...requiredRoles(), "migrationClearingAccount"])+ .where("companyId", "in", companyIds)+ .execute();+ for (const row of defaults) {+ for (const role of requiredRoles()) {+ if (!leafIds.has(row[role] ?? "")) {+ failures.push(`${row.companyId}: the default "${role}" has no account`);+ }+ }+ const clearing = byId.get(row.migrationClearingAccount ?? "");+ if (clearing && clearing.class !== MIGRATION_CLEARING_ACCOUNT_CLASS) {+ failures.push(`${row.companyId}: Migration Clearing is not Equity`);+ }+ }+ const classes = await trx+ .selectFrom("fixedAssetClass")+ .select(["name", ...FIXED_ASSET_CLASS_COLUMNS])+ .where("companyId", "in", companyIds)+ .execute();+ for (const fac of classes) {+ for (const column of FIXED_ASSET_CLASS_COLUMNS) {+ if (!leafIds.has(fac[column])) {+ failures.push(`fixed asset class "${fac.name}" has no ${column}`);+ }+ }+ }++ if (failures.length > 0) {+ logger.error("The chart of accounts import broke its postcondition", {+ groupId,+ failures+ });+ throw new Error("The chart of accounts import could not be applied.");+ }+ }+ export type ChargeType =+ | "Charge"+ | "Credit"+ | "Payment"+ | "Cashback"+ | "Repayment";++ export interface ChargeLineInput {+ accountId: string;+ amount: number;+ costCenterId?: string | null;+ projectId?: string | null;+ description?: string | null;+ }++ export interface BuildChargeJournalInput {+ transaction: {+ type: ChargeType;+ amount: number;+ cardAccountId: string;+ offsetAccountId: string | null;+ currencyCode: string;+ exchangeRate: number;+ };+ lines: ChargeLineInput[];+ // Resolved account classes, keyed by accountId. Only the accounts this+ // transaction touches need be present.+ accounts: Record<string, { class: AccountClass }>;+ // Internal charge record id — becomes `documentId` on every line.+ documentId: string;+ // Human-readable id (chargeId) — used only in error messages.+ documentReadableId: string;+ }++ // A journal line this builder emits. Deliberately self-contained — a pure unit+ // shouldn't depend on the generated DB types. The driver adds `journalId`,+ // `journalLineReference`, `companyId` and `quantity` before the Kysely insert,+ // and consumes `costCenterId` to write the CostCenter journalLineDimension.+ export interface ChargeJournalLine {+ accountId: string;+ amount: number;+ description: string;+ documentType: "Charge";+ documentId: string;+ costCenterId?: string | null;+ projectId?: string | null;+ }++ export interface BuildChargeJournalResult {+ journalLines: ChargeJournalLine[];+ }++ // Maximum residual (base ccy) tolerated before refusing to post. Above this a+ // logic/rounding bug has produced an unbalanced entry. Matches post-payment's+ // business threshold (multi-currency journals carry sub-cent cross-rate+ // residuals), NOT the float-noise EPSILON.+ const BALANCE_TOLERANCE = 0.01;++ export function buildChargeJournal(+ input: BuildChargeJournalInput+ ): BuildChargeJournalResult {+ const { transaction, lines, accounts, documentId, documentReadableId } =+ input;+ const { type, amount, cardAccountId, offsetAccountId, exchangeRate } =+ transaction;++ // Journal lines hit the GL in base currency. `exchangeRate` is the canonical+ // foreign-per-base rate (units of the document currency per 1 unit of base,+ // via get_exchange_rate; base currency → 1), so a document amount converts to+ // base by DIVIDING — the shared `toBaseAmount`, which rounds once per call at+ // internal SCALE. Both sides convert the same way so the entry stays balanced;+ // the offset/card side accumulates the rounded per-line magnitudes so rounding+ // dust can never unbalance a split. The column is NOT NULL default 1 (> 0), so+ // this guard passes for the rate=1 base-currency fallback and only refuses a+ // corrupt (0 / negative / non-finite) rate before it can post.+ assertExchangeRate(exchangeRate);+ const toBase = (value: number) => toBaseAmount(value, exchangeRate);++ const classOf = (accountId: string): LedgerAccountType => {+ const account = accounts[accountId];+ if (!account) {+ throw new Error(+ `Charge ${documentReadableId}: missing account class for ${accountId}`+ );+ }+ return account.class.toLowerCase() as LedgerAccountType;+ };++ const journalLines: ChargeJournalLine[] = [];+ // True debit(+)/credit(−) space. A balanced double entry sums to ~0 here.+ let signedDebitTotal = 0;++ const pushLine = (+ side: "debit" | "credit",+ accountType: LedgerAccountType,+ magnitude: number,+ fields: {+ accountId: string;+ description: string;+ costCenterId?: string | null;+ projectId?: string | null;+ }+ ) => {+ signedDebitTotal += side === "debit" ? magnitude : -magnitude;+ journalLines.push({+ accountId: fields.accountId,+ amount:+ side === "debit"+ ? debit(accountType, magnitude)+ : credit(accountType, magnitude),+ description: fields.description,+ documentType: "Charge",+ documentId,+ costCenterId: fields.costCenterId ?? null,+ projectId: fields.projectId ?? null+ });+ };++ // Line-bearing types must have lines that sum to the header amount, or the+ // subledger and the GL disagree. Throw a typed error naming the mismatch.+ const requireLineSum = () => {+ if (lines.length === 0) {+ throw new Error(+ `Charge ${documentReadableId}: ${type} requires at least one line`+ );+ }+ if (+ lines.some((line) => !Number.isFinite(line.amount) || line.amount <= 0)+ ) {+ throw new Error(+ `Charge ${documentReadableId}: coding line amounts must be finite and greater than zero`+ );+ }+ const lineSum = lines.reduce((sum, l) => sum + l.amount, 0);+ if (Math.abs(lineSum - amount) > EPSILON) {+ throw new Error(+ `Charge ${documentReadableId}: line sum ${lineSum} does not equal header amount ${amount}`+ );+ }+ };++ // Header-only transaction types derive their complete journal from the+ // card and offset accounts. Refuse unexpected persisted detail instead of+ // silently dropping it from the GL.+ const requireNoLines = () => {+ if (lines.length > 0) {+ throw new Error(+ `Charge ${documentReadableId}: ${type} cannot have coding lines`+ );+ }+ };++ const requireOffset = (): string => {+ if (!offsetAccountId) {+ throw new Error(+ `Charge ${documentReadableId}: ${type} requires an offset account`+ );+ }+ return offsetAccountId;+ };++ switch (type) {+ // Purchase on the card: expense/asset lines debited, card liability+ // credited for the total.+ case "Charge": {+ requireLineSum();+ let cardMagnitude = 0;+ for (const line of lines) {+ const magnitude = toBase(line.amount);+ cardMagnitude += magnitude;+ pushLine("debit", classOf(line.accountId), magnitude, {+ accountId: line.accountId,+ description: line.description ?? "Card charge",+ costCenterId: line.costCenterId,+ projectId: line.projectId+ });+ }+ pushLine("credit", "liability", cardMagnitude, {+ accountId: cardAccountId,+ description: "Card liability"+ });+ break;+ }++ // Refund/return to the card — mirror image of a Charge.+ case "Credit": {+ requireLineSum();+ let cardMagnitude = 0;+ for (const line of lines) {+ const magnitude = toBase(line.amount);+ cardMagnitude += magnitude;+ pushLine("credit", classOf(line.accountId), magnitude, {+ accountId: line.accountId,+ description: line.description ?? "Card credit",+ costCenterId: line.costCenterId,+ projectId: line.projectId+ });+ }+ pushLine("debit", "liability", cardMagnitude, {+ accountId: cardAccountId,+ description: "Card liability"+ });+ break;+ }++ // Statement payment: pay down the card liability from a bank asset.+ case "Payment": {+ requireNoLines();+ const offset = requireOffset();+ const magnitude = toBase(amount);+ pushLine("debit", "liability", magnitude, {+ accountId: cardAccountId,+ description: "Card liability"+ });+ pushLine("credit", classOf(offset), magnitude, {+ accountId: offset,+ description: "Card payment"+ });+ break;+ }++ // Cashback/rewards: reduce the card liability, book the offset as income.+ case "Cashback": {+ requireNoLines();+ const offset = requireOffset();+ const magnitude = toBase(amount);+ pushLine("debit", "liability", magnitude, {+ accountId: cardAccountId,+ description: "Card liability"+ });+ pushLine("credit", "revenue", magnitude, {+ accountId: offset,+ description: "Card cashback"+ });+ break;+ }++ // Repayment: the offset (bank asset or card liability, per funding) is+ // debited for the total; each line account is credited.+ case "Repayment": {+ requireLineSum();+ const offset = requireOffset();+ const lineMagnitudes = lines.map((l) => toBase(l.amount));+ const offsetMagnitude = lineMagnitudes.reduce((sum, m) => sum + m, 0);+ pushLine("debit", classOf(offset), offsetMagnitude, {+ accountId: offset,+ description: "Card repayment"+ });+ lines.forEach((line, index) => {+ pushLine("credit", classOf(line.accountId), lineMagnitudes[index]!, {+ accountId: line.accountId,+ description: line.description ?? "Card repayment",+ costCenterId: line.costCenterId,+ projectId: line.projectId+ });+ });+ break;+ }++ default: {+ // Exhaustiveness guard — a new chargeType must add a branch here.+ throw new Error(+ `Charge ${documentReadableId}: unsupported type ${type as string}`+ );+ }+ }++ // Defensive backstop: assert the entry balances in true debit/credit space.+ // By construction every branch pushes matched debit/credit legs (`pushLine`+ // adds +m for a debit, −m for a credit), and the card/offset side accumulates+ // the SAME rounded per-line magnitudes as the coding lines — so this holds by+ // construction today and cannot fire. The real integrity guard is+ // `requireLineSum` (the subledger must equal the header). This assert exists so+ // a future edit that breaks the matched-legs invariant fails loudly here rather+ // than writing an unbalanced journal to the GL.+ assertBalanced(signedDebitTotal, 0, BALANCE_TOLERANCE, "Charge journal");++ return { journalLines };+ }+ export type ChargeContext = {+ trx: KyselyTransaction<KyselyDatabase>;+ charge: Pick<+ Selectable<KyselyDatabase["charge"]>,+ | "id"+ | "chargeId"+ | "type"+ | "status"+ | "amount"+ | "cardAccountId"+ | "offsetAccountId"+ | "currencyCode"+ | "exchangeRate"+ | "transactionDate"+ | "postingDate"+ | "journalId"+ >;+ company: Pick<+ Selectable<KyselyDatabase["company"]>,+ "companyGroupId" | "baseCurrencyCode" | "timezone"+ >;+ postingStatus: AutomaticJournalStatus;+ companyId: string;+ userId: string;+ timestamp: string;+ today: string;+ };++ export async function postChargeJournal(+ context: ChargeContext+ ): Promise<{ journalId: string }> {+ const { trx, charge, company, postingStatus, companyId, userId, timestamp } =+ context;+ // The parent lock serializes line writes. Locking line tuples too would+ // deadlock with an UPDATE whose BEFORE trigger is waiting for that parent.+ const lines = await trx+ .selectFrom("chargeLine")+ .selectAll()+ .where("chargeId", "=", charge.id)+ .where("companyId", "=", companyId)+ .orderBy("sequence")+ .orderBy("id")+ .execute();+ const accountIds = [+ ...new Set([+ charge.cardAccountId,+ ...(charge.offsetAccountId ? [charge.offsetAccountId] : []),+ ...lines.map((line) => line.accountId)+ ])+ ];+ const postingAccounts = await trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "in", accountIds)+ .where("companyGroupId", "=", company.companyGroupId)+ .where("active", "=", true)+ .where("isGroup", "=", false)+ .execute();+ if (+ postingAccounts.length !== accountIds.length ||+ postingAccounts.some((account) => !isAccountClass(account.class))+ ) {+ throw new Error(+ "Charge accounts must be active posting accounts in this company group"+ );+ }+ const accounts: Record<string, { class: AccountClass }> = {};+ for (const account of postingAccounts) {+ if (!isAccountClass(account.class)) {+ throw new Error("Charge account class is missing");+ }+ accounts[account.id] = { class: account.class };+ }+ if (accounts[charge.cardAccountId]?.class !== "Liability") {+ throw new Error("Charge card account must be a Liability account");+ }+ if (+ charge.type === "Payment" &&+ charge.offsetAccountId &&+ accounts[charge.offsetAccountId]?.class !== "Asset"+ ) {+ throw new Error("Card payment offset account must be an Asset account");+ }+ if (+ charge.type === "Cashback" &&+ charge.offsetAccountId &&+ accounts[charge.offsetAccountId]?.class !== "Revenue"+ ) {+ throw new Error("Card cashback offset account must be a Revenue account");+ }++ const costCenterIds = [+ ...new Set(+ lines.flatMap((line) => (line.costCenterId ? [line.costCenterId] : []))+ )+ ];+ if (costCenterIds.length) {+ const costCenters = await trx+ .selectFrom("costCenter")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", costCenterIds)+ .execute();+ if (costCenters.length !== costCenterIds.length) {+ throw new NotFoundError("Charge cost center not found in this company");+ }+ }++ const projectIds = [+ ...new Set(+ lines.flatMap((line) => (line.projectId ? [line.projectId] : []))+ )+ ];+ if (projectIds.length) {+ const projects = await trx+ .selectFrom("project")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", projectIds)+ .execute();+ if (projects.length !== projectIds.length) {+ throw new NotFoundError("Charge project not found in this company");+ }+ }++ let postingDate = charge.postingDate ?? charge.transactionDate;+ // A Provisional journal has no accounting period, and no posting creates a+ // period before the cutover.+ let accountingPeriodId: string | null = null;+ if (postingStatus === "Posted") {+ const period = await resolveAccountingPeriod(+ trx,+ companyId,+ postingDate,+ "historical-with-shift"+ );+ postingDate = period.postingDate;+ accountingPeriodId = period.id;+ }+ const built = buildChargeJournal({+ transaction: {+ type: charge.type,+ amount: Number(charge.amount),+ cardAccountId: charge.cardAccountId,+ offsetAccountId: charge.offsetAccountId,+ currencyCode: charge.currencyCode,+ exchangeRate: Number(charge.exchangeRate)+ },+ lines: lines.map((line) => ({+ accountId: line.accountId,+ amount: Number(line.amount),+ costCenterId: line.costCenterId,+ projectId: line.projectId,+ description: line.description+ })),+ accounts,+ documentId: charge.id,+ documentReadableId: charge.chargeId+ });+ const { costCenter: costCenterDimensionId, project: projectDimensionId } =+ costCenterIds.length || projectIds.length+ ? await costCenterAndProjectDimensions(trx, company.companyGroupId)+ : { costCenter: null, project: null };+ if (costCenterIds.length && !costCenterDimensionId) {+ throw new Error("Company group has no active Cost Center dimension");+ }+ if (projectIds.length && !projectDimensionId) {+ throw new Error("Company group has no active Project dimension");+ }++ const journal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ ),+ accountingPeriodId,+ description: `Charge ${charge.chargeId}`,+ postingDate,+ companyId,+ sourceType: "Charge",+ status: postingStatus,+ postedAt: timestamp,+ postedBy: userId,+ createdBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const journalId = journal.id;+ const journalLineReference = nanoid();+ const journalLineIds = await allocateJournalLineIds(+ trx,+ built.journalLines.length+ );+ await trx+ .insertInto("journalLine")+ .values(+ built.journalLines.map((line, index) => ({+ id: journalLineIds[index],+ journalId,+ accountId: line.accountId,+ amount: line.amount,+ quantity: 1,+ description: line.description,+ documentType: "Charge" as const,+ documentId: line.documentId,+ journalLineReference,+ companyId+ }))+ )+ .execute();+ if (costCenterDimensionId) {+ const dimensionValues = built.journalLines.flatMap((line, index) => {+ const journalLineId = journalLineIds[index];+ if (!line.costCenterId) return [];+ if (!journalLineId) throw new Error("Failed to map card journal line");+ return [+ {+ journalLineId,+ dimensionId: costCenterDimensionId,+ valueId: line.costCenterId,+ companyId+ }+ ];+ });+ if (dimensionValues.length) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionValues)+ .execute();+ }+ }+ if (projectDimensionId) {+ const projectDimensionValues = built.journalLines.flatMap((line, index) => {+ const journalLineId = journalLineIds[index];+ if (!line.projectId) return [];+ if (!journalLineId) throw new Error("Failed to map card journal line");+ return [+ {+ journalLineId,+ dimensionId: projectDimensionId,+ valueId: line.projectId,+ companyId+ }+ ];+ });+ if (projectDimensionValues.length) {+ await trx+ .insertInto("journalLineDimension")+ .values(projectDimensionValues)+ .execute();+ }+ }++ await trx+ .updateTable("charge")+ .set({+ status: "Posted",+ journalId,+ postingDate,+ postedAt: timestamp,+ postedBy: userId,+ updatedAt: timestamp,+ updatedBy: userId+ })+ .where("id", "=", charge.id)+ .where("companyId", "=", companyId)+ .execute();+ return { journalId };+ }+ export type PostChargeArgs = {+ type: "post" | "void";+ chargeId: string;+ companyId: string;+ userId: string;+ };++ export function postChargeTransaction(+ db: Kysely<KyselyDatabase>,+ args: PostChargeArgs+ ): Promise<{ journalId: string | null }> {+ const { type, chargeId, companyId, userId } = args;+ return db.transaction().execute(async (trx) => {+ // This is deliberately the first database read. The line mutation trigger+ // takes the same parent lock, so every snapshot below is stable.+ const charge = await trx+ .selectFrom("charge")+ .select([+ "id",+ "chargeId",+ "type",+ "status",+ "amount",+ "cardAccountId",+ "offsetAccountId",+ "currencyCode",+ "exchangeRate",+ "journalId",+ sql<string>`"transactionDate"::text`.as("transactionDate"),+ sql<string | null>`"postingDate"::text`.as("postingDate")+ ])+ .where("id", "=", chargeId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!charge) throw new NotFoundError("Charge not found");++ if (type === "post" && charge.status === "Posted") {+ return { journalId: charge.journalId };+ }+ if (type === "void" && charge.status === "Voided") {+ return { journalId: charge.journalId };+ }+ const expectedStatus = type === "post" ? "Draft" : "Posted";+ if (charge.status !== expectedStatus) {+ throw new Error(`Cannot ${type} charge in status ${charge.status}`);+ }++ // Every posting writes a journal: Provisional before the company's+ // accounting cutover, Posted after it. FOR SHARE holds the status until+ // commit.+ const postingStatus = await journalPostingStatus(trx, companyId);++ const company = await trx+ .selectFrom("company")+ .select(["companyGroupId", "baseCurrencyCode", "timezone"])+ .where("id", "=", companyId)+ .executeTakeFirst();+ if (!company?.companyGroupId) {+ throw new Error("Charge company configuration not found");+ }++ const timestamp = datetime.timestamp();+ const today = datetime.today(company.timezone).toString();+ const context = {+ trx,+ charge,+ company,+ postingStatus,+ companyId,+ userId,+ timestamp,+ today+ };++ return type === "post"+ ? await postChargeJournal(context)+ : await voidCharge(context);+ });+ }+ export async function voidCharge(+ context: ChargeContext+ ): Promise<{ journalId: string | null }> {+ const { trx, charge, postingStatus, companyId, userId, timestamp, today } =+ context;++ // The enable superseded the journal of a charge dated before the cutover+ // and opened its balances in the opening journal, so a reversal of its own+ // lines would undo nothing. The date is the one the posting used.+ await refuseVoidBeforeCutover(+ trx,+ companyId,+ charge.postingDate ?? charge.transactionDate,+ CHARGE_VOID_BEFORE_CUTOVER_ERROR+ );++ if (charge.journalId) {+ const originalJournal = await trx+ .selectFrom("journal")+ .select(["id", "status", "sourceType"])+ .where("id", "=", charge.journalId)+ .where("companyId", "=", companyId)+ .forShare()+ .executeTakeFirst();+ if (+ !originalJournal ||+ !(OPEN_ITEM_JOURNAL_STATUSES as readonly string[]).includes(+ originalJournal.status+ ) ||+ originalJournal.sourceType !== "Charge"+ ) {+ throw new Error("Original charge journal has invalid provenance");+ }+ const originalLines = await trx+ .selectFrom("journalLine")+ .selectAll()+ // The journal's status was checked above, under FOR SHARE.+ .where("journalId", "=", originalJournal.id)+ .where("companyId", "=", companyId)+ .orderBy("id")+ .execute();+ if (+ !originalLines.length ||+ originalLines.some(+ (line) =>+ line.documentType !== "Charge" || line.documentId !== charge.id+ )+ ) {+ throw new Error("Original charge journal has invalid lines");+ }+ await insertNegatedJournal(trx, {+ companyId,+ userId,+ originalLines,+ description: `VOID Charge ${charge.chargeId}`,+ sourceType: "Charge",+ postingStatus,+ date: today,+ periodMode: "current",+ postedAt: timestamp+ });+ }++ await trx+ .updateTable("charge")+ .set({+ status: "Voided",+ voidedAt: timestamp,+ voidedBy: userId,+ updatedAt: timestamp,+ updatedBy: userId+ })+ .where("id", "=", charge.id)+ .where("companyId", "=", companyId)+ .execute();+ return { journalId: charge.journalId };+ }+ export const postChargeInput = z.object({+ type: z.enum(["post", "void"]).default("post"),+ chargeId: z.string()+ });++ export const postChargePermission = {+ update: "invoicing"+ } satisfies PermissionRule<z.output<typeof postChargeInput>>;++ /**+ * Posts or voids a charge and its journal, atomically. The transaction re-reads+ * the record under companyId, so a foreign id fails as "not found".+ */+ export async function postCharge(+ ctx: ServiceContext,+ raw: z.input<typeof postChargeInput>+ ) {+ const { type, chargeId } = postChargeInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const result = await postChargeTransaction(db, {+ type,+ chargeId,+ companyId,+ userId+ });+ return { success: true, ...result };+ }+ export interface ReimbursementLineInput {+ accountId: string;+ amount: number;+ costCenterId?: string | null;+ projectId?: string | null;+ description?: string | null;+ }++ export interface BuildReimbursementJournalInput {+ reimbursement: {+ amount: number;+ payableAccountId: string;+ currencyCode: string;+ exchangeRate: number;+ };+ // Resolved account classes, keyed by accountId. Only the accounts this+ // reimbursement touches need be present.+ accounts: Record<string, { class: AccountClass }>;+ lines: ReimbursementLineInput[];+ // Internal reimbursement record id — becomes `documentId` on every line.+ documentId: string;+ // Human-readable id (reimbursementId) — used only in error messages.+ documentReadableId: string;+ }++ // A journal line this builder emits. Deliberately self-contained — a pure unit+ // shouldn't depend on the generated DB types. The driver adds `journalId`,+ // `journalLineReference`, `companyId` and `quantity` before the Kysely insert,+ // and consumes `costCenterId`/`projectId` to write the journalLineDimension+ // rows.+ export interface ReimbursementJournalLine {+ accountId: string;+ amount: number;+ description: string;+ documentType: "Reimbursement";+ documentId: string;+ costCenterId?: string | null;+ projectId?: string | null;+ }++ export interface BuildReimbursementJournalResult {+ journalLines: ReimbursementJournalLine[];+ }++ // Maximum residual (base ccy) tolerated before refusing to post. Above this a+ // logic/rounding bug has produced an unbalanced entry. Matches post-payment's+ // business threshold (multi-currency journals carry sub-cent cross-rate+ // residuals), NOT the float-noise EPSILON.++ export function buildReimbursementJournal(+ input: BuildReimbursementJournalInput+ ): BuildReimbursementJournalResult {+ const { reimbursement, lines, accounts, documentId, documentReadableId } =+ input;+ const { amount, payableAccountId, exchangeRate } = reimbursement;++ // Journal lines hit the GL in base currency. `exchangeRate` is the canonical+ // foreign-per-base rate (units of the document currency per 1 unit of base,+ // via get_exchange_rate; base currency → 1), so a document amount converts to+ // base by DIVIDING — the shared `toBaseAmount`, which rounds once per call at+ // internal SCALE. The payable side accumulates the SAME rounded per-line+ // magnitudes as the coding lines, so rounding dust can never unbalance a+ // split. The column is NOT NULL default 1 (> 0), so this guard passes for the+ // rate=1 base-currency fallback and only refuses a corrupt (0 / negative /+ // non-finite) rate before it can post.+ assertExchangeRate(exchangeRate);+ const toBase = (value: number) => toBaseAmount(value, exchangeRate);++ const classOf = (accountId: string): LedgerAccountType => {+ const account = accounts[accountId];+ if (!account) {+ throw new Error(+ `Reimbursement ${documentReadableId}: missing account class for ${accountId}`+ );+ }+ return account.class.toLowerCase() as LedgerAccountType;+ };++ const journalLines: ReimbursementJournalLine[] = [];+ // True debit(+)/credit(−) space. A balanced double entry sums to ~0 here.+ let signedDebitTotal = 0;++ const pushLine = (+ side: "debit" | "credit",+ accountType: LedgerAccountType,+ magnitude: number,+ fields: {+ accountId: string;+ description: string;+ costCenterId?: string | null;+ projectId?: string | null;+ }+ ) => {+ signedDebitTotal += side === "debit" ? magnitude : -magnitude;+ journalLines.push({+ accountId: fields.accountId,+ amount:+ side === "debit"+ ? debit(accountType, magnitude)+ : credit(accountType, magnitude),+ description: fields.description,+ documentType: "Reimbursement",+ documentId,+ costCenterId: fields.costCenterId ?? null,+ projectId: fields.projectId ?? null+ });+ };++ // The coding lines must sum to the header amount, or the subledger and the GL+ // disagree. This is the invariant the detail page's totals guard mirrors+ // before it will enable Post — the message text below is what a developer+ // sees if that guard is ever bypassed.+ const requireLineSum = () => {+ if (lines.length === 0) {+ throw new Error(+ `Reimbursement ${documentReadableId}: requires at least one line`+ );+ }+ if (+ lines.some((line) => !Number.isFinite(line.amount) || line.amount <= 0)+ ) {+ throw new Error(+ `Reimbursement ${documentReadableId}: coding line amounts must be finite and greater than zero`+ );+ }+ const lineSum = lines.reduce((sum, l) => sum + l.amount, 0);+ if (Math.abs(lineSum - amount) > EPSILON) {+ throw new Error(+ `Reimbursement ${documentReadableId}: line sum ${lineSum} does not equal header amount ${amount}`+ );+ }+ };++ requireLineSum();++ // Each coding line is debited; the employee payable is credited for the sum+ // of the SAME rounded magnitudes.+ let payableMagnitude = 0;+ for (const line of lines) {+ const magnitude = toBase(line.amount);+ payableMagnitude += magnitude;+ pushLine("debit", classOf(line.accountId), magnitude, {+ accountId: line.accountId,+ description: line.description ?? "Employee reimbursement",+ costCenterId: line.costCenterId,+ projectId: line.projectId+ });+ }+ pushLine("credit", classOf(payableAccountId), payableMagnitude, {+ accountId: payableAccountId,+ // The payout reader (`post-payment`) finds this line BY DESCRIPTION to+ // recover the reimbursement's booked carrying value. Editing the literal+ // here would silently stop it matching — so both sides share the constant.+ description: REIMBURSEMENT_PAYABLE_POSTING_DESCRIPTION+ });++ // Defensive backstop: assert the entry balances in true debit/credit space.+ // By construction the payable leg accumulates the same rounded per-line+ // magnitudes as the coding legs, so this holds by construction today and+ // cannot fire. The real integrity guard is `requireLineSum` (the subledger+ // must equal the header). This assert exists so a future edit that breaks the+ // matched-legs invariant fails loudly here rather than writing an unbalanced+ // journal to the GL.+ assertBalanced(+ signedDebitTotal,+ 0,+ BALANCE_TOLERANCE,+ "Reimbursement journal"+ );++ return { journalLines };+ }+ export type ReimbursementContext = {+ trx: KyselyTransaction<KyselyDatabase>;+ reimbursement: Pick<+ Selectable<KyselyDatabase["reimbursement"]>,+ | "id"+ | "reimbursementId"+ | "employeeId"+ | "status"+ | "amount"+ | "currencyCode"+ | "exchangeRate"+ | "payableAccountId"+ | "reimbursementDate"+ | "postingDate"+ | "journalId"+ >;+ company: Pick<+ Selectable<KyselyDatabase["company"]>,+ "companyGroupId" | "baseCurrencyCode" | "timezone"+ >;+ postingStatus: AutomaticJournalStatus;+ companyId: string;+ userId: string;+ timestamp: string;+ today: string;+ };++ export async function postReimbursementJournal(+ context: ReimbursementContext+ ): Promise<{ journalId: string }> {+ const {+ trx,+ reimbursement,+ company,+ postingStatus,+ companyId,+ userId,+ timestamp+ } = context;+ // The parent lock serializes line writes. Locking line tuples too would+ // deadlock with an UPDATE whose BEFORE trigger is waiting for that parent.+ const lines = await trx+ .selectFrom("reimbursementLine")+ .selectAll()+ .where("reimbursementId", "=", reimbursement.id)+ .where("companyId", "=", companyId)+ .orderBy("sequence")+ .orderBy("id")+ .execute();++ // Resolve the employee-payable control account by ID from `accountDefault` —+ // never by account number or name, which are user-editable at any time+ // (lessons.md: "Never resolve a control account by number/name"). The+ // `employeeReimbursementsPayableAccount` column is nullable by design: an+ // upgrading company that has never configured it must still be able to post,+ // so the AP trade account is the documented fallback.+ const defaults = await trx+ .selectFrom("accountDefault")+ .select(["employeeReimbursementsPayableAccount", "payablesAccount"])+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const payableAccountId =+ reimbursement.payableAccountId ??+ defaults?.employeeReimbursementsPayableAccount ??+ defaults?.payablesAccount ??+ null;+ if (!payableAccountId) {+ throw new Error(+ "No employee reimbursements payable account and no payables account is configured"+ );+ }++ const accountIds = [+ ...new Set([payableAccountId, ...lines.map((line) => line.accountId)])+ ];+ const postingAccounts = await trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "in", accountIds)+ .where("companyGroupId", "=", company.companyGroupId)+ .where("active", "=", true)+ .where("isGroup", "=", false)+ .execute();+ if (+ postingAccounts.length !== accountIds.length ||+ postingAccounts.some((account) => !isAccountClass(account.class))+ ) {+ throw new Error(+ "Reimbursement accounts must be active posting accounts in this company group"+ );+ }+ const accounts: Record<string, { class: AccountClass }> = {};+ for (const account of postingAccounts) {+ if (!isAccountClass(account.class)) {+ throw new Error("Reimbursement account class is missing");+ }+ accounts[account.id] = { class: account.class };+ }+ // Take the class from the RESOLVED account, so a mis-classed default (either+ // column) fails loudly instead of crediting the wrong side of the ledger.+ if (accounts[payableAccountId]?.class !== "Liability") {+ throw new Error(+ "Reimbursement payable account must be a Liability account"+ );+ }++ const costCenterIds = [+ ...new Set(+ lines.flatMap((line) => (line.costCenterId ? [line.costCenterId] : []))+ )+ ];+ if (costCenterIds.length) {+ const costCenters = await trx+ .selectFrom("costCenter")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", costCenterIds)+ .execute();+ if (costCenters.length !== costCenterIds.length) {+ throw new NotFoundError(+ "Reimbursement cost center not found in this company"+ );+ }+ }++ const projectIds = [+ ...new Set(+ lines.flatMap((line) => (line.projectId ? [line.projectId] : []))+ )+ ];+ if (projectIds.length) {+ const projects = await trx+ .selectFrom("project")+ .select("id")+ .where("companyId", "=", companyId)+ .where("id", "in", projectIds)+ .execute();+ if (projects.length !== projectIds.length) {+ throw new NotFoundError(+ "Reimbursement project not found in this company"+ );+ }+ }++ let postingDate =+ reimbursement.postingDate ?? reimbursement.reimbursementDate;+ // A Provisional journal has no accounting period, and no posting creates a+ // period before the cutover.+ let accountingPeriodId: string | null = null;+ if (postingStatus === "Posted") {+ const period = await resolveAccountingPeriod(+ trx,+ companyId,+ postingDate,+ "historical-with-shift"+ );+ postingDate = period.postingDate;+ accountingPeriodId = period.id;+ }+ const built = buildReimbursementJournal({+ reimbursement: {+ amount: Number(reimbursement.amount),+ payableAccountId,+ currencyCode: reimbursement.currencyCode,+ exchangeRate: Number(reimbursement.exchangeRate)+ },+ lines: lines.map((line) => ({+ accountId: line.accountId,+ amount: Number(line.amount),+ costCenterId: line.costCenterId,+ projectId: line.projectId,+ description: line.description+ })),+ accounts,+ documentId: reimbursement.id,+ documentReadableId: reimbursement.reimbursementId+ });+ // The builder emits one debit per coding line IN ORDER, then the payable+ // credit. The dimension pass below pairs `built.journalLines[i]` with+ // `lines[i]` on that contract, so assert it rather than trusting it.+ if (+ built.journalLines.length !== lines.length + 1 ||+ lines.some(+ (line, index) => built.journalLines[index]?.accountId !== line.accountId+ )+ ) {+ throw new Error("Reimbursement journal lines do not match coding lines");+ }++ const { costCenter: costCenterDimensionId, project: projectDimensionId } =+ costCenterIds.length || projectIds.length+ ? await costCenterAndProjectDimensions(trx, company.companyGroupId)+ : { costCenter: null, project: null };+ if (costCenterIds.length && !costCenterDimensionId) {+ throw new Error("Company group has no active Cost Center dimension");+ }+ if (projectIds.length && !projectDimensionId) {+ throw new Error("Company group has no active Project dimension");+ }++ // The generic per-line dimension rows — where a human's edit in the line+ // editor lands.+ const lineIds = lines.map((line) => line.id);+ const genericDimensions = lineIds.length+ ? await trx+ .selectFrom("reimbursementLineDimension")+ .select(["reimbursementLineId", "dimensionId", "valueId"])+ .where("companyId", "=", companyId)+ .where("reimbursementLineId", "in", lineIds)+ .orderBy("dimensionId")+ .execute()+ : [];+ const genericDimensionIds = [+ ...new Set(genericDimensions.map((row) => row.dimensionId))+ ];+ if (genericDimensionIds.length) {+ const activeDimensions = await trx+ .selectFrom("dimension")+ .select("id")+ .where("companyGroupId", "=", company.companyGroupId)+ .where("active", "=", true)+ .where("id", "in", genericDimensionIds)+ .execute();+ if (activeDimensions.length !== genericDimensionIds.length) {+ throw new Error(+ "Reimbursement line dimension is not an active dimension in this company group"+ );+ }+ }+ const genericByLineId = new Map<+ string,+ { dimensionId: string; valueId: string }[]+ >();+ for (const row of genericDimensions) {+ const existing = genericByLineId.get(row.reimbursementLineId);+ if (existing) existing.push(row);+ else genericByLineId.set(row.reimbursementLineId, [row]);+ }++ const journal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ ),+ accountingPeriodId,+ description: `Reimbursement ${reimbursement.reimbursementId}`,+ postingDate,+ companyId,+ sourceType: "Reimbursement",+ status: postingStatus,+ postedAt: timestamp,+ postedBy: userId,+ createdBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const journalId = journal.id;+ const journalLineReference = nanoid();+ const journalLineIds = await allocateJournalLineIds(+ trx,+ built.journalLines.length+ );+ await trx+ .insertInto("journalLine")+ .values(+ built.journalLines.map((line, index) => ({+ id: journalLineIds[index],+ journalId,+ accountId: line.accountId,+ amount: line.amount,+ quantity: 1,+ description: line.description,+ documentType: "Reimbursement" as const,+ documentId: line.documentId,+ journalLineReference,+ companyId+ }))+ )+ .execute();++ // Two sources feed one destination. `journalLineDimension` is UNIQUE on+ // (journalLineId, dimensionId) — one value per dimension per line — so the+ // legacy `costCenterId`/`projectId` columns and the generic+ // `reimbursementLineDimension` rows must be MERGED before the insert, not+ // written as two passes.+ //+ // When both name the same dimension, the GENERIC TABLE WINS. The two legacy+ // columns are what the Ramp SYNC wrote at import; the generic table is+ // where a HUMAN's edit in the line editor lands — and human intent beats a+ // machine default. A reader who finds that precedence surprising needs the+ // sentence here, at the call site.+ const dimensionRows: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];+ built.journalLines.forEach((journalLine, index) => {+ const sourceLine = lines[index];+ // The trailing payable leg is a control account and carries no coding.+ if (!sourceLine) return;+ const journalLineId = journalLineIds[index];+ if (!journalLineId) {+ throw new Error("Failed to map reimbursement journal line");+ }+ const byDimension = new Map<string, string>();+ if (costCenterDimensionId && journalLine.costCenterId) {+ byDimension.set(costCenterDimensionId, journalLine.costCenterId);+ }+ if (projectDimensionId && journalLine.projectId) {+ byDimension.set(projectDimensionId, journalLine.projectId);+ }+ for (const row of genericByLineId.get(sourceLine.id) ?? []) {+ byDimension.set(row.dimensionId, row.valueId);+ }+ for (const [dimensionId, valueId] of byDimension) {+ dimensionRows.push({+ journalLineId,+ dimensionId,+ valueId,+ companyId+ });+ }+ });+ if (dimensionRows.length) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionRows)+ .execute();+ }++ await trx+ .updateTable("reimbursement")+ .set({+ status: "Posted",+ journalId,+ postingDate,+ payableAccountId,+ postedAt: timestamp,+ postedBy: userId,+ updatedAt: timestamp,+ updatedBy: userId+ })+ .where("id", "=", reimbursement.id)+ .where("companyId", "=", companyId)+ .execute();+ return { journalId };+ }+ export type PostReimbursementArgs = {+ type: "post" | "void";+ reimbursementId: string;+ companyId: string;+ userId: string;+ };++ export function postReimbursementTransaction(+ db: Kysely<KyselyDatabase>,+ args: PostReimbursementArgs+ ): Promise<{ journalId: string | null }> {+ const { type, reimbursementId, companyId, userId } = args;+ return db.transaction().execute(async (trx) => {+ // This is deliberately the first database read, and it is scoped to+ // `companyId` — a reimbursement id from another tenant is simply not found.+ // The line mutation trigger takes the same parent lock, so every snapshot+ // below is stable.+ const reimbursement = await trx+ .selectFrom("reimbursement")+ .select([+ "id",+ "reimbursementId",+ "employeeId",+ "status",+ "amount",+ "currencyCode",+ "exchangeRate",+ "payableAccountId",+ "journalId",+ sql<string>`"reimbursementDate"::text`.as("reimbursementDate"),+ sql<string | null>`"postingDate"::text`.as("postingDate")+ ])+ .where("id", "=", reimbursementId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!reimbursement) throw new NotFoundError("Reimbursement not found");++ // Re-posting a Posted row and re-voiding a Voided row both return the+ // stored journal id without writing a second journal.+ if (type === "post" && reimbursement.status === "Posted") {+ return { journalId: reimbursement.journalId };+ }+ if (type === "void" && reimbursement.status === "Voided") {+ return { journalId: reimbursement.journalId };+ }+ const expectedStatus = type === "post" ? "Draft" : "Posted";+ if (reimbursement.status !== expectedStatus) {+ throw new Error(+ `Cannot ${type} reimbursement in status ${reimbursement.status}`+ );+ }++ // Every posting writes a journal: Provisional before the company's+ // accounting cutover, Posted after it. FOR SHARE holds the status until+ // commit.+ const postingStatus = await journalPostingStatus(trx, companyId);++ const company = await trx+ .selectFrom("company")+ .select(["companyGroupId", "baseCurrencyCode", "timezone"])+ .where("id", "=", companyId)+ .executeTakeFirst();+ if (!company?.companyGroupId) {+ throw new Error("Reimbursement company configuration not found");+ }++ const timestamp = datetime.timestamp();+ const today = datetime.today(company.timezone).toString();+ const context = {+ trx,+ reimbursement,+ company,+ postingStatus,+ companyId,+ userId,+ timestamp,+ today+ };++ return type === "post"+ ? await postReimbursementJournal(context)+ : await voidReimbursement(context);+ });+ }+ export async function voidReimbursement(+ context: ReimbursementContext+ ): Promise<{ journalId: string | null }> {+ const {+ trx,+ reimbursement,+ postingStatus,+ companyId,+ userId,+ timestamp,+ today+ } = context;++ // The enable superseded the journal of a reimbursement dated before the+ // cutover and opened its balances in the opening journal, so a reversal of+ // its own lines would undo nothing. The date is the one the posting used.+ await refuseVoidBeforeCutover(+ trx,+ companyId,+ reimbursement.postingDate ?? reimbursement.reimbursementDate,+ REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR+ );++ // A paid-out reimbursement cannot be voided. Without this the void wrote a+ // second journal crediting the employee payable again, leaving that account+ // negative with nothing that will ever clear it, the cash already gone, and a+ // live `invoiceSettlement` row pointing at a Voided document. `post-memo`+ // refuses the same shape ("Cannot void a consumed memo"); this is its+ // counterpart, and the only reason it was missing is that reimbursements got+ // their payout path after the void path was written.+ const settlement = await trx+ .selectFrom("invoiceSettlement as s")+ .leftJoin("payment as applying", "applying.id", "s.paymentId")+ .select("s.id")+ .where("s.companyId", "=", companyId)+ .where("s.targetReimbursementId", "=", reimbursement.id)+ .where((eb) =>+ eb.or([+ eb("s.paymentId", "is", null),+ eb("applying.status", "=", "Posted")+ ])+ )+ .limit(1)+ .executeTakeFirst();+ if (settlement) {+ throw new Error("Cannot void a paid reimbursement; void its payment first");+ }++ if (reimbursement.journalId) {+ const originalJournal = await trx+ .selectFrom("journal")+ .select(["id", "status", "sourceType"])+ .where("id", "=", reimbursement.journalId)+ .where("companyId", "=", companyId)+ .forShare()+ .executeTakeFirst();+ if (+ !originalJournal ||+ !(OPEN_ITEM_JOURNAL_STATUSES as readonly string[]).includes(+ originalJournal.status+ ) ||+ originalJournal.sourceType !== "Reimbursement"+ ) {+ throw new Error("Original reimbursement journal has invalid provenance");+ }+ const originalLines = await trx+ .selectFrom("journalLine")+ .selectAll()+ // The journal's status was checked above, under FOR SHARE.+ .where("journalId", "=", originalJournal.id)+ .where("companyId", "=", companyId)+ .orderBy("id")+ .execute();+ if (+ !originalLines.length ||+ originalLines.some(+ (line) =>+ line.documentType !== "Reimbursement" ||+ line.documentId !== reimbursement.id+ )+ ) {+ throw new Error("Original reimbursement journal has invalid lines");+ }+ await insertNegatedJournal(trx, {+ companyId,+ userId,+ originalLines,+ description: `VOID Reimbursement ${reimbursement.reimbursementId}`,+ sourceType: "Reimbursement",+ postingStatus,+ date: today,+ periodMode: "current",+ postedAt: timestamp+ });+ }++ await trx+ .updateTable("reimbursement")+ .set({+ status: "Voided",+ voidedAt: timestamp,+ voidedBy: userId,+ updatedAt: timestamp,+ updatedBy: userId+ })+ .where("id", "=", reimbursement.id)+ .where("companyId", "=", companyId)+ .execute();+ return { journalId: reimbursement.journalId };+ }+ export const postReimbursementInput = z.object({+ type: z.enum(["post", "void"]).default("post"),+ reimbursementId: z.string()+ });++ export const postReimbursementPermission = {+ update: "invoicing"+ } satisfies PermissionRule<z.output<typeof postReimbursementInput>>;++ /**+ * Posts or voids a reimbursement and its journal, atomically. The transaction re-reads+ * the record under companyId, so a foreign id fails as "not found".+ */+ export async function postReimbursement(+ ctx: ServiceContext,+ raw: z.input<typeof postReimbursementInput>+ ) {+ const { type, reimbursementId } = postReimbursementInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const result = await postReimbursementTransaction(db, {+ type,+ reimbursementId,+ companyId,+ userId+ });+ return { success: true, ...result };+ }+ type AccountDefaults = Database["public"]["Tables"]["accountDefault"]["Row"];++ export type LegacyAdjustmentJournals = {+ inventoryAdjustments: LegacyJournal[];+ inventoryCounts: LegacyJournal[];+ nonConformances: LegacyJournal[];+ maintenanceConsumptions: LegacyJournal[];+ };++ type Offset = {+ accountId: string | null;+ accountDefaultRole: OptionalDefaultRole | null;+ description: string;+ };++ /** "Label — comment", or the label alone, as the postings describe. */+ function withComment(label: string, comment: string | null | undefined) {+ return comment?.trim() ? `${label} — ${comment.trim()}` : label;+ }++ function sign(quantity: number) {+ return quantity < 0 ? "out" : "in";+ }++ export async function buildLegacyAdjustmentJournals(+ trx: KyselyTx,+ {+ companyId,+ cutoverDate,+ defaults+ }: { companyId: string; cutoverDate: string; defaults: AccountDefaults }+ ): Promise<LegacyAdjustmentJournals> {+ const result: LegacyAdjustmentJournals = {+ inventoryAdjustments: [],+ inventoryCounts: [],+ nonConformances: [],+ maintenanceConsumptions: []+ };+ const rows = await legacyAdjustmentCostRows(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (rows.length === 0) return result;++ const ledgerColumns = [+ "id",+ "itemId",+ "quantity",+ "documentType",+ "documentId",+ "comment",+ "createdBy",+ "locationId",+ "scrapReasonId",+ sql<string>`"createdAt"::text`.as("createdAt")+ ] as const;++ // The movement a cost row names itself: an adjustment, a CSV import row, a+ // manual scrap or unscrap. The core sets the cost row's document to the+ // ledger row's id when the movement has no document.+ const ownLedgers = await readByIds(+ rows.map((row) => row.documentId),+ (ids) =>+ trx+ .selectFrom("itemLedger")+ .select(ledgerColumns)+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .where("documentId", "is", null)+ .execute()+ );+ const ownLedgerById = new Map(ownLedgers.map((row) => [row.id, row]));+ const ownLedger = (row: (typeof rows)[number]) => {+ const ledger = ownLedgerById.get(row.documentId);+ return ledger && ledger.documentType === row.documentType+ ? ledger+ : undefined;+ };++ // The movements of a document, paired with its cost rows in entry order.+ const documentRows = rows.filter(+ (row) =>+ !ownLedger(row) &&+ row.documentType !== null &&+ row.documentType !== "Maintenance Consumption"+ );+ const documentLedgers = await readByIds(+ documentRows.map((row) => row.documentId),+ (ids) =>+ trx+ .selectFrom("itemLedger")+ .select(ledgerColumns)+ .where("companyId", "=", companyId)+ .where("documentId", "in", ids)+ .where("documentType", "in", [+ "Scrap",+ "Inventory Count",+ "Non-Conformance",+ "Inbound Inspection"+ ])+ .where("correctionOfItemLedgerId", "is", null)+ .orderBy("entryNumber")+ .execute()+ );+ const pairKey = (row: {+ documentType: string | null;+ documentId: string | null;+ itemId: string | null;+ createdAt: string;+ quantity: number;+ }) =>+ `${row.documentType}|${row.documentId}|${row.itemId}|${row.createdAt}|${sign(Number(row.quantity))}`;+ const ledgerQueues = Map.groupBy(documentLedgers, (row) => pairKey(row));+ const pairedLedger = new Map<string, (typeof documentLedgers)[number]>();+ for (const row of documentRows) {+ const next = ledgerQueues.get(pairKey(row))?.shift();+ if (next) pairedLedger.set(row.id, next);+ }++ // How many movements with no document each transaction wrote: more than+ // one is a CSV import file.+ const batchSizes = await readByIds(+ rows+ .filter((row) => row.documentType === null && ownLedger(row))+ .map((row) => row.documentId),+ (ids) =>+ trx+ .selectFrom("itemLedger as batch")+ .select([+ sql<string>`"batch"."createdAt"::text`.as("createdAt"),+ sql<number>`count(*)`.as("count")+ ])+ .where("batch.companyId", "=", companyId)+ .where("batch.documentType", "is", null)+ .where("batch.documentId", "is", null)+ .where("batch.correctionOfItemLedgerId", "is", null)+ .where("batch.createdAt", "in", (eb) =>+ eb+ .selectFrom("itemLedger")+ .select("createdAt")+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ )+ .groupBy("batch.createdAt")+ .execute()+ );+ const batchSizeByCreatedAt = new Map(+ batchSizes.map((row) => [row.createdAt, Number(row.count)])+ );++ const documentIds = (documentType: string) =>+ rows+ .filter((row) => row.documentType === documentType)+ .map((row) => row.documentId);+ const counts = await readByIds(documentIds("Inventory Count"), (ids) =>+ trx+ .selectFrom("inventoryCount")+ .select(["id", "inventoryCountId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const nonConformances = await readByIds(+ documentIds("Non-Conformance"),+ (ids) =>+ trx+ .selectFrom("nonConformance")+ .select(["id", "nonConformanceId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const dispatches = await readByIds(+ documentIds("Maintenance Consumption"),+ (ids) =>+ trx+ .selectFrom("maintenanceDispatch")+ .select(["id", "maintenanceDispatchId", "locationId", "workCenterId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemIds = rows.map((row) => row.itemId);+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ const countById = new Map(counts.map((row) => [row.id, row]));+ const nonConformanceById = new Map(+ nonConformances.map((row) => [row.id, row])+ );+ const dispatchById = new Map(dispatches.map((row) => [row.id, row]));++ const variance: Offset = {+ accountId: defaults.inventoryAdjustmentVarianceAccount,+ accountDefaultRole: null,+ description: "Inventory Adjustment"+ };+ // Before the cutover an empty scrap account is a stand-in line.+ const scrapAccount = resolveDefaultAccount(+ defaults,+ "scrapAccount",+ "Provisional"+ );++ const groups = new Map<+ string,+ { family: keyof LegacyAdjustmentJournals; journal: LegacyJournal }+ >();+ for (const row of rows) {+ const { itemId, documentId } = row;+ const quantity = Number(row.quantity);+ const own = ownLedger(row);+ const ledger = own ?? pairedLedger.get(row.id);+ let key: string;+ // The family the detection names (legacy-documents.ts), so the wizard's+ // counts and these journals agree.+ const family: keyof LegacyAdjustmentJournals = row.family;+ let description: string;+ let sourceType: LegacyJournal["sourceType"] = "Inventory Adjustment";+ let offset = variance;+ let locationId = ledger?.locationId ?? null;+ let extra: Partial<Record<DimensionEntityType, string | null>> = {};++ switch (row.documentType) {+ case null: {+ // Not a movement of the core (a revaluation names its unit).+ if (!own) continue;+ const isImport = (batchSizeByCreatedAt.get(own.createdAt) ?? 1) > 1;+ key = isImport ? `import:${own.createdAt}` : `adjustment:${own.id}`;+ description = isImport+ ? "Inventory Adjustment — CSV import"+ : withComment("Inventory Adjustment", own.comment);+ break;+ }+ case "Scrap": {+ if (own) {+ key = `scrap:${own.id}`;+ description = withComment(+ quantity < 0 ? "Scrap" : "Unscrap",+ own.comment+ );+ } else {+ key = `job-scrap:${row.id}`;+ description = `Scrap — ${itemById.get(itemId)?.readableIdWithRevision ?? ""}`;+ }+ offset = { ...scrapAccount, description: "Scrap Account" };+ extra = {+ ScrapReason: ledger?.scrapReasonId ?? null,+ Employee: ledger?.createdBy ?? null+ };+ break;+ }+ case "Inventory Count": {+ key = `count:${documentId}:${row.createdAt}`;+ const count = countById.get(documentId);+ description = count+ ? `Inventory Count ${count.inventoryCountId}`+ : (ledger?.comment ?? "Inventory Count");+ break;+ }+ case "Non-Conformance":+ case "Inbound Inspection": {+ key = `${row.documentType}:${documentId}:${row.createdAt}`;+ sourceType = row.documentType;+ description =+ row.documentType === "Non-Conformance"+ ? `NC ${nonConformanceById.get(documentId)?.nonConformanceId ?? documentId} disposition`+ : "Inbound inspection lot rejected";+ offset = { ...scrapAccount, description: "Scrap / Cost of Quality" };+ break;+ }+ case "Maintenance Consumption": {+ key = `maintenance:${documentId}:${row.createdAt}`;+ const dispatch = dispatchById.get(documentId);+ description = `Maintenance Consumption ${dispatch?.maintenanceDispatchId ?? documentId}`;+ // An empty maintenance account falls back to the variance account+ // in the core's pair builder.+ offset = {+ accountId: defaults.maintenanceAccount,+ accountDefaultRole: null,+ description: "Maintenance Expense"+ };+ locationId = dispatch?.locationId ?? null;+ extra = { WorkCenter: dispatch?.workCenterId ?? null };+ break;+ }+ default:+ continue;+ }++ const [inventoryLine, offsetLine] = buildAdjustmentJournalLines({+ journalId: "",+ documentId,+ documentType: row.documentType,+ journalLineReference: nanoid(),+ isGain: quantity > 0,+ cost: Math.abs(Number(row.cost)),+ quantity: Math.abs(quantity),+ replenishmentSystem: itemById.get(itemId)?.replenishmentSystem ?? null,+ accountDefaults: defaults,+ offsetAccount: offset.accountId,+ offsetDescription: offset.description,+ companyId+ });+ const dimensions = {+ Item: itemId,+ ItemPostingGroup: postingGroupByItem.get(itemId) ?? null,+ Location: locationId,+ ...extra+ };+ const lines: LegacyJournalLine[] = [inventoryLine, offsetLine].map(+ ({ journalId: _journalId, companyId: _companyId, ...line }) => ({+ ...line,+ dimensions+ })+ );+ lines[1]!.accountDefaultRole = offset.accountDefaultRole;++ const group = groups.get(key);+ if (group) {+ group.journal.lines.push(...lines);+ } else {+ groups.set(key, {+ family,+ journal: {+ description,+ postingDate: String(row.postingDate),+ sourceType,+ lines+ }+ });+ }+ }++ for (const { family, journal } of groups.values()) {+ result[family].push(journal);+ }+ return result;+ }+ export async function buildLegacyChargeJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ cutoverDate+ }: { companyId: string; companyGroupId: string; cutoverDate: string }+ ): Promise<LegacyDocumentJournal[]> {+ const charges = await legacyCharges(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (charges.length === 0) return [];++ const lines = await readByIds(+ charges.map((charge) => charge.id),+ (ids) =>+ trx+ .selectFrom("chargeLine")+ .selectAll()+ .where("companyId", "=", companyId)+ .where("chargeId", "in", ids)+ .orderBy("chargeId")+ .orderBy("sequence")+ .orderBy("id")+ .execute()+ );+ const accounts = await readByIds(+ [+ ...charges.flatMap((charge) => [+ charge.cardAccountId,+ charge.offsetAccountId+ ]),+ ...lines.map((line) => line.accountId)+ ],+ (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ );+ const accountClasses: Record<string, { class: AccountClass }> = {};+ for (const account of accounts) {+ if (isAccountClass(account.class)) {+ accountClasses[account.id] = { class: account.class };+ }+ }+ const dimensionIds = await costCenterAndProjectDimensions(+ trx,+ companyGroupId+ );++ const linesByCharge = Map.groupBy(lines, (line) => line.chargeId);++ return charges.map((charge) => {+ const built = buildChargeJournal({+ transaction: {+ type: charge.type,+ amount: Number(charge.amount),+ cardAccountId: charge.cardAccountId,+ offsetAccountId: charge.offsetAccountId,+ currencyCode: charge.currencyCode,+ exchangeRate: Number(charge.exchangeRate)+ },+ lines: (linesByCharge.get(charge.id) ?? []).map((line) => ({+ accountId: line.accountId,+ amount: Number(line.amount),+ costCenterId: line.costCenterId,+ projectId: line.projectId,+ description: line.description+ })),+ accounts: accountClasses,+ documentId: charge.id,+ documentReadableId: charge.chargeId+ });+ const journalLineReference = nanoid();+ return {+ documentId: charge.id,+ description: `Charge ${charge.chargeId}`,+ postingDate: String(charge.postingDate ?? charge.transactionDate),+ sourceType: "Charge" as const,+ lines: built.journalLines.map((line) => ({+ accountId: line.accountId,+ amount: line.amount,+ quantity: 1,+ description: line.description,+ documentType: "Charge" as const,+ documentId: line.documentId,+ journalLineReference,+ dimensions: {},+ dimensionValues: [+ ...(dimensionIds.costCenter && line.costCenterId+ ? [+ {+ dimensionId: dimensionIds.costCenter,+ valueId: line.costCenterId+ }+ ]+ : []),+ ...(dimensionIds.project && line.projectId+ ? [{ dimensionId: dimensionIds.project, valueId: line.projectId }]+ : [])+ ]+ }))+ };+ });+ }+ /** The documents the enable wrote a journal for, per family: the families+ * `getLegacyDocumentCounts` counts before the enable. */+ export type LegacyJournalCounts = LegacyDocumentCounts & {+ /** Cost rows written for movements that stored none. */+ movementCostRows: number;+ };++ export async function journalLegacyDocuments(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults+ }: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ }+ ): Promise<{+ counts: LegacyJournalCounts;+ /** Every journal written, Provisional. */+ journalIds: string[];+ }> {+ const args = { companyId, companyGroupId, cutoverDate, defaults };++ // Before the builders that read the sale rows.+ const movementCosts = await writeLegacyMovementCosts(trx, {+ companyId,+ cutoverDate,+ defaults+ });++ const salesInvoices = await buildLegacySalesInvoiceJournals(trx, args);+ const purchaseInvoices = await buildLegacyPurchaseInvoiceJournals(trx, args);+ const memos = await buildLegacyMemoJournals(trx, args);+ const charges = await buildLegacyChargeJournals(trx, args);+ const reimbursements = await buildLegacyReimbursementJournals(trx, args);+ const documentJournals: [JournalDocumentTable, LegacyDocumentJournal[]][] = [+ ["memo", memos],+ ["charge", charges],+ ["reimbursement", reimbursements]+ ];+ const documentJournalIds = await insertProvisionalJournals(trx, {+ companyId,+ companyGroupId,+ userId,+ journals: [+ ...salesInvoices,+ ...purchaseInvoices,+ ...documentJournals.flatMap(([, journals]) => journals)+ ]+ });+ // The memo, charge and reimbursement store the journal, as their postings do.+ let offset = salesInvoices.length + purchaseInvoices.length;+ for (const [table, journals] of documentJournals) {+ await attachJournalIds(trx, {+ table,+ companyId,+ userId,+ rows: journals.map((journal, index) => ({+ id: journal.documentId,+ journalId: documentJournalIds[offset + index] ?? null,+ payableAccountId: journal.payableAccountId+ }))+ });+ offset += journals.length;+ }++ // After every document a payment can settle has its journal. The payment+ // builder stores each journal on its payment.+ const paymentIds = (+ await legacyPayments(trx, { companyId, cutoverDate })+ .clearSelect()+ .select("payment.id")+ .execute()+ ).map((payment) => payment.id);+ const payments = await journalLegacyPayments(trx, {+ companyId,+ companyGroupId,+ userId,+ cutoverDate+ });+ const paymentJournalIds = await readByIds(paymentIds, (ids) =>+ trx+ .selectFrom("payment")+ .select("journalId")+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .where("journalId", "is not", null)+ .execute()+ );++ // The movements last: no document journal reads them, and the re-cost+ // after this step reads their inventory lines.+ const movementArgs = { companyId, cutoverDate, defaults };+ const purchaseReceipts = await buildLegacyPurchaseReceiptJournals(+ trx,+ movementArgs+ );+ const salesReturnReceipts = await buildLegacySalesReturnReceiptJournals(+ trx,+ movementArgs+ );+ const salesShipments = await buildLegacySalesShipmentJournals(+ trx,+ movementArgs+ );+ const returnShipments = await buildLegacyReturnShipmentJournals(+ trx,+ movementArgs+ );+ const adjustments = await buildLegacyAdjustmentJournals(trx, movementArgs);+ const movements = [+ ...purchaseReceipts,+ ...salesReturnReceipts,+ ...salesShipments,+ ...returnShipments,+ ...adjustments.inventoryAdjustments,+ ...adjustments.inventoryCounts,+ ...adjustments.nonConformances,+ ...adjustments.maintenanceConsumptions,+ ...movementCosts.jobConsumptions,+ ...movementCosts.jobOutputs+ ];+ const movementJournalIds = await insertProvisionalJournals(trx, {+ companyId,+ companyGroupId,+ userId,+ journals: movements+ });++ // No other journal reads them, and the re-cost never touches them.+ const runs = await journalLegacyRuns(trx, {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults+ });++ // A journal with no lines is not written (`insertProvisionalJournals`).+ const written = (journals: { lines: unknown[] }[]) =>+ journals.filter((journal) => journal.lines.length > 0).length;+ return {+ counts: {+ salesInvoices: written(salesInvoices),+ purchaseInvoices: written(purchaseInvoices),+ memos: written(memos),+ charges: written(charges),+ reimbursements: written(reimbursements),+ payments,+ purchaseReceipts: written(purchaseReceipts),+ salesReturnReceipts: written(salesReturnReceipts),+ salesShipments: written(salesShipments),+ returnShipments: written(returnShipments),+ inventoryAdjustments: written(adjustments.inventoryAdjustments),+ inventoryCounts: written(adjustments.inventoryCounts),+ nonConformances: written(adjustments.nonConformances),+ maintenanceConsumptions: written(adjustments.maintenanceConsumptions),+ jobConsumptions: written(movementCosts.jobConsumptions),+ jobOutputs: written(movementCosts.jobOutputs),+ movementCostRows: movementCosts.costRows,+ ...runs.counts+ },+ journalIds: [+ ...documentJournalIds,+ ...paymentJournalIds.map((payment) => payment.journalId),+ ...movementJournalIds,+ ...runs.journalIds+ ].filter((id): id is string => id !== null)+ };+ }+ export async function buildLegacyMemoJournals(+ trx: KyselyTx,+ { companyId, cutoverDate }: { companyId: string; cutoverDate: string }+ ): Promise<LegacyDocumentJournal[]> {+ const memos = await legacyMemos(trx, {+ companyId,+ cutoverDate+ }).execute();+ const journals: LegacyDocumentJournal[] = [];+ for (const batch of chunkArray(memos, ROWS_PER_STATEMENT)) {+ const rebuilt = await rebuildMemoJournals(trx, batch, companyId, {+ postingStatus: "Provisional"+ });+ batch.forEach((memo, index) => {+ const { lines, dimensions } = rebuilt[index]!;+ journals.push({+ documentId: memo.id,+ description: `${memo.direction} Memo ${memo.memoId}`,+ postingDate: String(memo.postingDate),+ sourceType: memo.direction === "Credit" ? "Credit Memo" : "Debit Memo",+ lines: lines.map(({ companyId: _, ...line }) => ({+ ...line,+ dimensions: {},+ dimensionValues: dimensions+ }))+ });+ });+ }+ return journals;+ }+ type CostLedgerInsert = Database["public"]["Tables"]["costLedger"]["Insert"];++ export type LegacyMovementCosts = {+ /** Cost rows written: sales, job issues and returns, job output layers. */+ costRows: number;+ jobConsumptions: LegacyJournal[];+ jobOutputs: LegacyJournal[];+ };++ /** A job movement: one issue or return ledger row, or one completion. */+ export type JobMovement = {+ /** The ledger row of an issue or return; the rows of a completion. */+ key: string;+ kind: "Consumption" | "Output";+ jobId: string;+ itemId: string;+ /** Signed, as the ledger stores it. */+ quantity: number;+ postingDate: string;+ /** A fixed-width UTC instant (`utcInstant`), so it sorts as text. */+ createdAt: string;+ documentLineId: string | null;+ locationId: string | null;+ /** The serial unit an issue relieves first. */+ trackedEntityIds: string[];+ };++ /** A cost row a posting stored for a job movement. Signed. */+ export type StoredJobCost = {+ kind: JobMovement["kind"];+ jobId: string;+ itemId: string;+ quantity: number;+ cost: number;+ };++ /** A movement, and the part of it stored cost rows cover. */+ export type CoveredJobMovement = {+ movement: JobMovement;+ coveredQuantity: number;+ coveredCost: number;+ /** The quantity no stored row covers, unsigned. A new row books it. */+ missingQuantity: number;+ };++ export type PlannedJobMovement = CoveredJobMovement & {+ /** The new row's cost, unsigned. */+ missingCost: number;+ /** The pair to write, unsigned; null when the day kept its journal. */+ journal: { quantity: number; cost: number } | null;+ };++ const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);++ const instantOf = (movement: { postingDate: string; createdAt: string }) =>+ `${movement.postingDate}|${movement.createdAt}`;++ /**+ * Splits each movement into what the stored cost rows cover and what is+ * missing, in the order the postings ran: by time, and at one instant the+ * issues before the completions (the posting backflushes the material, then+ * receives the output, in one transaction). Stored rows cover the earliest+ * movements of a job, item and direction.+ */+ export function coverJobMovements({+ movements,+ stored+ }: {+ movements: JobMovement[];+ stored: StoredJobCost[];+ }): CoveredJobMovement[] {+ const coverKey = (row: {+ kind: string;+ jobId: string;+ itemId: string;+ quantity: number;+ }) => `${row.kind}:${row.jobId}:${row.itemId}:${row.quantity < 0}`;+ const budgets = new Map<string, { quantity: number; unitCost: number }[]>();+ for (const row of stored) {+ const quantity = Math.abs(row.quantity);+ if (quantity <= EPSILON) continue;+ const list = budgets.get(coverKey(row)) ?? [];+ list.push({ quantity, unitCost: Math.abs(row.cost) / quantity });+ budgets.set(coverKey(row), list);+ }+ const ordered = [...movements].sort(+ (a, b) =>+ byText(instantOf(a), instantOf(b)) ||+ (a.kind === b.kind ? 0 : a.kind === "Consumption" ? -1 : 1)+ );+ return ordered.map((movement) => {+ let wanted = Math.abs(movement.quantity);+ let coveredQuantity = 0;+ let coveredCost = 0;+ for (const budget of budgets.get(coverKey(movement)) ?? []) {+ if (wanted <= EPSILON) break;+ const take = Math.min(wanted, budget.quantity);+ if (take <= 0) continue;+ budget.quantity -= take;+ wanted -= take;+ coveredQuantity += take;+ coveredCost += take * budget.unitCost;+ }+ return {+ movement,+ coveredQuantity,+ coveredCost: round(coveredCost),+ missingQuantity: wanted > EPSILON ? round(wanted) : 0+ };+ });+ }++ /**+ * Plans the cost rows and journal pairs of the covered job movements, in+ * their order. An issue's or return's missing quantity costs what+ * `missingCostByKey` gives it; a completion takes the job's material cost+ * not yet received. `journaledDays` holds `<kind>:<jobId>:<postingDate>` for+ * a job and date that kept its journal: only what is missing there gets a+ * pair. Every other movement gets its pair, at zero too.+ */+ export function planLegacyJobCosts({+ covered,+ journaledDays,+ missingCostByKey+ }: {+ covered: CoveredJobMovement[];+ journaledDays: ReadonlySet<string>;+ missingCostByKey: ReadonlyMap<string, number>;+ }): PlannedJobMovement[] {+ // The material cost each job has in WIP and no completion has taken.+ const wipByJob = new Map<string, number>();+ return covered.map((cover) => {+ const { movement, coveredQuantity, coveredCost, missingQuantity } = cover;+ const journaled = journaledDays.has(+ `${movement.kind}:${movement.jobId}:${movement.postingDate}`+ );+ const wip = wipByJob.get(movement.jobId) ?? 0;+ if (movement.kind === "Consumption") {+ const missingCost =+ missingQuantity > 0 ? missingCostByKey.get(movement.key) : 0;+ if (missingCost === undefined) {+ throw new Error(+ `The missing cost of job movement ${movement.key} was not computed`+ );+ }+ const value = coveredCost + missingCost;+ wipByJob.set(+ movement.jobId,+ movement.quantity < 0 ? wip + value : wip - value+ );+ const quantity = journaled+ ? missingQuantity+ : coveredQuantity + missingQuantity;+ return {+ ...cover,+ missingCost,+ journal:+ quantity > EPSILON+ ? {+ quantity: round(quantity),+ cost: journaled ? missingCost : value+ }+ : null+ };+ }+ const afterCovered = wip - coveredCost;+ const missingCost =+ missingQuantity > 0 ? round(Math.max(afterCovered, 0)) : 0;+ wipByJob.set(movement.jobId, afterCovered - missingCost);+ return {+ ...cover,+ missingCost,+ journal:+ !journaled || missingQuantity > 0+ ? {+ quantity: round(+ journaled ? missingQuantity : Math.abs(movement.quantity)+ ),+ cost: (journaled ? 0 : coveredCost) + missingCost+ }+ : null+ };+ });+ }++ /**+ * Writes the missing cost rows and returns the journals of the job+ * movements. Runs before the invoice and shipment builders read the sale+ * rows, and before the inventory reset.+ */+ export async function writeLegacyMovementCosts(+ trx: KyselyTx,+ {+ companyId,+ cutoverDate,+ defaults+ }: { companyId: string; cutoverDate: string; defaults: AccountDefaults }+ ): Promise<LegacyMovementCosts> {+ const args = { companyId, cutoverDate };+ const sales = await legacySaleMovements(trx, args).execute();+ const ledgerRows = await legacyJobMovements(trx, args).execute();+ if (sales.length === 0 && ledgerRows.length === 0) {+ return {+ costRows: 0,+ jobConsumptions: [],+ jobOutputs: []+ };+ }++ const jobs = await readByIds(+ ledgerRows.map((row) => row.documentId),+ (ids) =>+ trx+ .selectFrom("job")+ .select(["id", "jobId", "locationId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const jobById = new Map(jobs.map((job) => [job.id, job]));+ const storedRows = await readByIds(jobById.keys(), (ids) =>+ trx+ .selectFrom("costLedger")+ .select(["itemLedgerType", "documentId", "itemId", "quantity", "cost"])+ .where("companyId", "=", companyId)+ .where("documentId", "in", ids)+ .where("postingDate", ">=", cutoverDate)+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .where((eb) =>+ eb.or([+ eb.and([+ eb("documentType", "=", "Job Consumption"),+ eb("itemLedgerType", "=", "Consumption")+ ]),+ eb.and([+ eb("documentType", "=", "Job Receipt"),+ eb("itemLedgerType", "=", "Output")+ ])+ ])+ )+ .orderBy("postingDate")+ .orderBy("entryNumber")+ .execute()+ );++ const itemIds = [+ ...sales.map((row) => row.itemId),+ ...ledgerRows.map((row) => row.itemId)+ ];+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ const itemCosts = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("itemCost")+ .select(["itemId", "costingMethod", "standardCost", "unitCost"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", ids)+ .execute()+ );+ const itemCostById = new Map(itemCosts.map((row) => [row.itemId, row]));+ const itemCostOf = (itemId: string) => {+ const itemCost = itemCostById.get(itemId);+ if (!itemCost) {+ throw new InvalidInputError(+ `Item ${itemById.get(itemId)?.readableIdWithRevision ?? itemId} has no cost record, so its movements after the cutover cannot be costed.`+ );+ }+ return itemCost;+ };+ // Today's unit cost, as calculateCOGS reads it for a Standard or Average+ // item.+ const unitCostOf = (itemId: string) => {+ const itemCost = itemCostOf(itemId);+ return Number(+ (itemCost.costingMethod === "Standard"+ ? itemCost.standardCost+ : itemCost.unitCost) ?? 0+ );+ };+ const layeredMethod = (itemId: string): CostingMethod | null => {+ const method = itemCostOf(itemId).costingMethod;+ return method === "FIFO" || method === "LIFO" ? method : null;+ };++ // One movement per issue or return ledger row, and one per completion: the+ // rows of one completion (a unit each, when serialized) share an instant.+ const consumptionRows = ledgerRows.filter(+ (row) => row.entryType === "Consumption" && jobById.has(row.documentId!)+ );+ const outputRows = ledgerRows.filter(+ (row) => row.entryType === "Assembly Output" && jobById.has(row.documentId!)+ );+ const movements: JobMovement[] = [+ ...consumptionRows.map((row) => ({+ key: row.id,+ kind: "Consumption" as const,+ jobId: row.documentId!,+ itemId: row.itemId,+ quantity: Number(row.quantity),+ postingDate: row.postingDate,+ createdAt: row.createdAt,+ documentLineId: row.documentLineId,+ locationId: row.locationId,+ trackedEntityIds: row.trackedEntityId ? [row.trackedEntityId] : []+ })),+ ...[+ ...Map.groupBy(+ outputRows,+ (row) =>+ `${row.documentId}:${row.itemId}:${row.postingDate}:${row.createdAt}`+ )+ ].map(([key, group]) => ({+ key,+ kind: "Output" as const,+ jobId: group[0]!.documentId!,+ itemId: group[0]!.itemId,+ quantity: group.reduce((sum, row) => sum + Number(row.quantity), 0),+ postingDate: group[0]!.postingDate,+ createdAt: group[0]!.createdAt,+ documentLineId: null,+ locationId: group[0]!.locationId,+ trackedEntityIds: []+ }))+ ];+ const covered = coverJobMovements({+ movements,+ stored: storedRows.map((row) => ({+ kind:+ row.itemLedgerType === "Output"+ ? ("Output" as const)+ : ("Consumption" as const),+ jobId: String(row.documentId),+ itemId: String(row.itemId),+ quantity: Number(row.quantity),+ cost: Number(row.cost)+ }))+ });++ // The outbound quantities with no cost row, in movement order: the sales,+ // and the missing quantity of each issue.+ const saleKey = (row: (typeof sales)[number]) =>+ `sale:${row.documentId}:${row.itemId}`;+ const saleQuantity = (row: (typeof sales)[number]) =>+ round(Number(row.quantity) - Number(row.covered));+ const outbound = [+ ...sales.map((row) => ({+ order: instantOf(row),+ key: saleKey(row),+ itemId: row.itemId,+ quantity: saleQuantity(row),+ trackedEntityIds: row.trackedEntityIds+ })),+ ...covered+ .filter(+ ({ movement, missingQuantity }) =>+ movement.kind === "Consumption" &&+ movement.quantity < 0 &&+ missingQuantity > 0+ )+ .map(({ movement, missingQuantity }) => ({+ order: instantOf(movement),+ key: movement.key,+ itemId: movement.itemId,+ quantity: missingQuantity,+ trackedEntityIds: movement.trackedEntityIds+ }))+ ].sort((a, b) => byText(a.order, b.order));+ const relievedCostByKey = await relieveOpenLayers(trx, {+ companyId,+ reliefs: outbound.filter((relief) => layeredMethod(relief.itemId)),+ methodByItem: new Map(+ outbound.flatMap((relief) => {+ const method = layeredMethod(relief.itemId);+ return method ? [[relief.itemId, method] as const] : [];+ })+ ),+ // calculateCOGS costs a quantity no layer covers at the unit cost.+ fallbackUnitCostByItem: new Map(+ outbound.map((relief) => [+ relief.itemId,+ Number(itemCostOf(relief.itemId).unitCost ?? 0)+ ])+ )+ });+ const outboundCost = (relief: (typeof outbound)[number]) =>+ relievedCostByKey.get(relief.key) ??+ round(relief.quantity * unitCostOf(relief.itemId));+ const costByKey = new Map(+ outbound.map((relief) => [relief.key, outboundCost(relief)])+ );+ // A return costs at today's unit cost.+ for (const { movement, missingQuantity } of covered) {+ if (movement.kind === "Consumption" && movement.quantity > 0) {+ costByKey.set(+ movement.key,+ round(missingQuantity * unitCostOf(movement.itemId))+ );+ }+ }+ const planned = planLegacyJobCosts({+ covered,+ journaledDays: new Set(+ ledgerRows+ .filter((row) => row.journaled)+ .map(+ (row) =>+ `${row.entryType === "Consumption" ? "Consumption" : "Output"}:${row.documentId}:${row.postingDate}`+ )+ ),+ missingCostByKey: costByKey+ });++ // The rows, in the order of their movements, so the re-cost relieves+ // the layers in that order.+ const inserts: (CostLedgerInsert & { order: string })[] = [+ ...sales.map((row) => {+ const cost = costByKey.get(saleKey(row))!;+ return {+ order: instantOf(row),+ itemLedgerType: "Sale" as const,+ costLedgerType: "Direct Cost" as const,+ adjustment: false,+ documentType: "Sales Shipment" as const,+ documentId: row.documentId,+ itemId: row.itemId,+ quantity: -saleQuantity(row),+ cost: -cost,+ remainingQuantity: 0,+ postingDate: row.postingDate,+ createdAt: row.createdAt,+ companyId+ };+ }),+ ...planned+ .filter((plan) => plan.missingQuantity > 0)+ .map(({ movement, missingQuantity, missingCost }) => {+ const sign = movement.quantity < 0 ? -1 : 1;+ const isOutput = movement.kind === "Output";+ return {+ order: instantOf(movement),+ itemLedgerType: movement.kind,+ costLedgerType: "Direct Cost" as const,+ adjustment: false,+ documentType: isOutput+ ? ("Job Receipt" as const)+ : ("Job Consumption" as const),+ documentId: movement.jobId,+ itemId: movement.itemId,+ quantity: sign * missingQuantity,+ cost: sign * missingCost,+ // An output is a layer; an issue or return relieves or holds none.+ remainingQuantity: isOutput ? missingQuantity : 0,+ postingDate: movement.postingDate,+ createdAt: movement.createdAt,+ companyId+ };+ })+ ].sort((a, b) => byText(a.order, b.order));+ for (const rows of chunkArray(inserts, ROWS_PER_STATEMENT)) {+ await trx+ .insertInto("costLedger")+ .values(rows.map(({ order: _order, ...row }) => row))+ .execute();+ }++ // The journals of the job movements.+ const dimensions = (movement: JobMovement) => ({+ Item: movement.itemId,+ ItemPostingGroup: postingGroupByItem.get(movement.itemId) ?? null,+ Location:+ movement.locationId ?? jobById.get(movement.jobId)?.locationId ?? null+ });+ const inventoryOf = (itemId: string) =>+ resolveInventoryAccount(+ itemById.get(itemId)?.replenishmentSystem ?? null,+ defaults+ );+ const jobNumber = (jobId: string) => jobById.get(jobId)!.jobId;+ const withPair = planned.flatMap((plan) =>+ plan.journal ? [{ ...plan, journal: plan.journal }] : []+ );++ const jobConsumptions = [+ ...Map.groupBy(+ withPair.filter((plan) => plan.movement.kind === "Consumption"),+ (plan) => `${plan.movement.jobId}:${plan.movement.postingDate}`+ ).values()+ ].map((group): LegacyJournal => {+ const { jobId, postingDate } = group[0]!.movement;+ const lines = group.flatMap(+ ({ movement, journal }): LegacyJournalLine[] => {+ const inventory = inventoryOf(movement.itemId);+ const keys = {+ quantity: journal.quantity,+ documentType: "Job Consumption" as const,+ documentId: jobId,+ documentLineReference: movement.documentLineId+ ? journalReference.to.materialIssue(movement.documentLineId)+ : journalReference.to.job(jobId),+ journalLineReference: nanoid(),+ dimensions: dimensions(movement)+ };+ const wip = {+ ...keys,+ accountId: defaults.workInProgressAccount,+ description: "WIP Account"+ };+ const stock = {+ ...keys,+ accountId: inventory.account,+ description: inventory.description+ };+ return movement.quantity < 0+ ? [+ { ...wip, amount: round(debit("asset", journal.cost)) },+ { ...stock, amount: round(credit("asset", journal.cost)) }+ ]+ : [+ { ...stock, amount: round(debit("asset", journal.cost)) },+ { ...wip, amount: round(credit("asset", journal.cost)) }+ ];+ }+ );+ return {+ description: `Material Issue to Job ${jobNumber(jobId)}`,+ postingDate,+ sourceType: "Job Consumption",+ lines+ };+ });++ const jobOutputs = withPair+ .filter((plan) => plan.movement.kind === "Output")+ .map(({ movement, journal, coveredQuantity }): LegacyJournal => {+ const inventory = inventoryOf(movement.itemId);+ const keys = {+ quantity: journal.quantity,+ documentType: "Job Receipt" as const,+ documentId: movement.jobId,+ documentLineReference: journalReference.to.job(movement.jobId),+ journalLineReference: nanoid(),+ dimensions: dimensions(movement)+ };+ return {+ description: `Job Completion ${jobNumber(movement.jobId)}`,+ postingDate: movement.postingDate,+ sourceType: "Job Receipt",+ lines: [+ {+ ...keys,+ accountId: inventory.account,+ description: inventory.description,+ amount: round(debit("asset", journal.cost))+ },+ {+ ...keys,+ accountId: defaults.workInProgressAccount,+ description: "WIP Account",+ amount: round(credit("asset", journal.cost))+ }+ ]+ };+ });++ return {+ costRows: inserts.length,+ jobConsumptions,+ jobOutputs+ };+ }++ /**+ * Relieves the open layers of FIFO and LIFO items for the reliefs, in order,+ * as successive `calculateCOGS` calls would: reads the layers and their open+ * children once, locked as `calculateCOGS` locks them, replays the reliefs+ * (`replayReliefs`) and writes the remaining quantities that changed. A layer+ * this step writes (a job's output) is not open to a relief in the same+ * step; its quantity costs at the fallback, as negative stock does. Returns+ * each relief's cost by key.+ */+ async function relieveOpenLayers(+ trx: KyselyTx,+ {+ companyId,+ reliefs,+ methodByItem,+ fallbackUnitCostByItem+ }: {+ companyId: string;+ reliefs: {+ key: string;+ itemId: string;+ quantity: number;+ trackedEntityIds: readonly string[];+ }[];+ methodByItem: ReadonlyMap<string, CostingMethod>;+ fallbackUnitCostByItem: ReadonlyMap<string, number>;+ }+ ): Promise<Map<string, number>> {+ if (reliefs.length === 0) return new Map();+ const layers = await readByIds(+ reliefs.map((relief) => relief.itemId),+ (ids) =>+ trx+ .selectFrom("costLedger")+ .select([+ "id",+ "itemId",+ "quantity",+ "cost",+ "remainingQuantity",+ "trackedEntityId"+ ])+ .where("companyId", "=", companyId)+ .where("itemId", "in", ids)+ .where("remainingQuantity", ">", 0)+ .where(isCostLayer)+ .orderBy("itemId")+ .orderBy("postingDate")+ .orderBy("createdAt")+ .forUpdate()+ .execute()+ );+ const children = await readByIds(+ layers.map((layer) => layer.id),+ (ids) =>+ trx+ .selectFrom("costLedger")+ .select([+ "id",+ "appliesToCostLedgerId",+ "quantity",+ "cost",+ "remainingQuantity"+ ])+ .where("companyId", "=", companyId)+ .where("appliesToCostLedgerId", "in", ids)+ .where("remainingQuantity", ">", 0)+ .orderBy("createdAt")+ .forUpdate()+ .execute()+ );+ const childrenByLayer = Map.groupBy(+ children,+ (child) => child.appliesToCostLedgerId+ );+ const loaded = new Map<string, number>();+ const events: ReliefEvent[] = [+ ...layers.map((layer): ReliefEvent => {+ loaded.set(layer.id, Number(layer.remainingQuantity));+ return {+ kind: "layer",+ itemId: layer.itemId!,+ layer: {+ id: layer.id,+ quantity: Number(layer.quantity),+ cost: Number(layer.cost),+ remainingQuantity: Number(layer.remainingQuantity),+ trackedEntityId: layer.trackedEntityId,+ children: (childrenByLayer.get(layer.id) ?? []).map((child) => {+ loaded.set(child.id, Number(child.remainingQuantity));+ return {+ id: child.id,+ quantity: Number(child.quantity),+ cost: Number(child.cost),+ remainingQuantity: Number(child.remainingQuantity)+ };+ })+ }+ };+ }),+ ...reliefs.map((relief): ReliefEvent => ({ kind: "relief", ...relief }))+ ];+ const { costByKey, remainingById } = replayReliefs({+ events,+ methodByItem,+ fallbackUnitCostByItem+ });+ const changed = [...remainingById].filter(+ ([id, remaining]) => loaded.get(id) !== remaining+ );+ for (const rows of chunkArray(changed, ROWS_PER_STATEMENT)) {+ await sql`+ UPDATE "costLedger" AS c+ SET "remainingQuantity" = v."remaining"+ FROM (VALUES ${sql.join(+ rows.map(([id, remaining]) => sql`(${id}, ${remaining}::numeric)`)+ )}) AS v("id", "remaining")+ WHERE c."id" = v."id" AND c."companyId" = ${companyId}+ `.execute(trx);+ }+ return costByKey;+ }+ export async function journalLegacyPayments(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ userId,+ cutoverDate+ }: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ cutoverDate: string;+ /** Not read: the processor fee reads its own account defaults. */+ defaults?: AccountDefaults;+ }+ ): Promise<number> {+ const payments = await legacyPayments(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (payments.length === 0) return 0;+ const { fees: feeByPaymentId } = await readPaymentProcessorFees(+ trx,+ companyId,+ payments+ );++ let written = 0;+ for (const batch of chunkArray(payments, ROWS_PER_STATEMENT)) {+ const rebuilt = await rebuildPaymentJournals(trx, batch, companyId, {+ postingStatus: "Provisional",+ feeByPaymentId+ });+ const journals: LegacyJournal[] = batch.map((payment, index) => {+ const { lines, dimensions } = rebuilt[index]!;+ return {+ description: `Payment ${payment.paymentId}`,+ postingDate: String(payment.postingDate),+ sourceType: "Payment" as const,+ lines: lines.map(+ ({ companyId: _, documentLineReference, ...line }) => ({+ ...line,+ documentLineReference: documentLineReference ?? null,+ dimensions: {},+ dimensionValues: dimensions+ })+ )+ };+ });+ const journalIds = await insertProvisionalJournals(trx, {+ companyId,+ companyGroupId,+ userId,+ journals+ });+ await attachJournalIds(trx, {+ table: "payment",+ companyId,+ userId,+ rows: batch.map((payment, index) => ({+ id: payment.id,+ journalId: journalIds[index] ?? null+ }))+ });+ written += journalIds.filter(Boolean).length;+ }+ return written;+ }+ type ReceiptGroup = { postingDate: string; quantity: number; cost: number };++ export async function buildLegacyPurchaseInvoiceJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ cutoverDate,+ defaults+ }: {+ companyId: string;+ companyGroupId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ }+ ): Promise<LegacyJournal[]> {+ const invoices = await legacyPurchaseInvoices(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (invoices.length === 0) return [];+ const invoiceIds = invoices.map((invoice) => invoice.id);++ const lines = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("purchaseInvoiceLine")+ .selectAll()+ .where("companyId", "=", companyId)+ .where("invoiceId", "in", ids)+ .orderBy("invoiceId")+ .orderBy("createdAt")+ .orderBy("id")+ .execute()+ );+ const itemIds = lines.map((line) => line.itemId);+ const purchaseOrderLineIds = lines.map((line) => line.purchaseOrderLineId);++ const deliveries = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("purchaseInvoiceDelivery")+ .select(["id", "supplierShippingCost"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const suppliers = await readByIds(+ invoices.map((invoice) => invoice.supplierId),+ (ids) =>+ trx+ .selectFrom("supplier")+ .select(["id", "supplierTypeId", "intercompanyCompanyId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const items = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("item")+ .select(["id", "itemTrackingType", "replenishmentSystem"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemCosts = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("itemCost")+ .select(["itemId", "itemPostingGroupId", "costingMethod"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", ids)+ .execute()+ );+ const purchaseOrderLines = await readByIds(purchaseOrderLineIds, (ids) =>+ trx+ .selectFrom("purchaseOrderLine")+ .select(["id", "jobOperationId", "locationId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const jobOperations = await readByIds(+ purchaseOrderLines.map((line) => line.jobOperationId),+ (ids) =>+ trx+ .selectFrom("jobOperation")+ .select(["id", "processId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ // Each PO line's receipts, in the order the posting's walk reads them.+ const receiptLines = await readByIds(purchaseOrderLineIds, (ids) =>+ trx+ .selectFrom("receiptLine as line")+ .innerJoin("receipt", (join) =>+ join+ .onRef("receipt.id", "=", "line.receiptId")+ .onRef("receipt.companyId", "=", "line.companyId")+ )+ .select([+ "line.receiptId",+ "line.lineId",+ "line.itemId",+ "line.receivedQuantity",+ "line.unitPrice",+ "receipt.postingDate"+ ])+ .where("line.companyId", "=", companyId)+ .where("receipt.status", "=", "Posted")+ .where("receipt.sourceDocument", "=", "Purchase Order")+ .where("line.lineId", "in", ids)+ .where("line.receivedQuantity", ">", 0)+ .orderBy("receipt.postingDate")+ .orderBy("receipt.createdAt")+ .orderBy("receipt.id")+ .execute()+ );+ const receiptLayers = await readByIds(+ receiptLines.map((line) => line.receiptId),+ (ids) =>+ trx+ .selectFrom("costLedger")+ .select([+ "documentId",+ "itemId",+ sql<number>`sum("cost")`.as("cost"),+ sql<number>`sum("quantity")`.as("quantity")+ ])+ .where("companyId", "=", companyId)+ .where("documentType", "=", "Purchase Receipt")+ .where("documentId", "in", ids)+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .where("quantity", ">", 0)+ .groupBy(["documentId", "itemId"])+ .execute()+ );+ // Every posted invoice line on these PO lines, in posting order: what was+ // invoiced before each legacy invoice.+ const invoicedLines = await readByIds(purchaseOrderLineIds, (ids) =>+ trx+ .selectFrom("purchaseInvoiceLine as line")+ .innerJoin("purchaseInvoice as invoice", (join) =>+ join+ .onRef("invoice.id", "=", "line.invoiceId")+ .onRef("invoice.companyId", "=", "line.companyId")+ )+ .select([+ "invoice.id as invoiceId",+ "line.purchaseOrderLineId",+ "line.quantity",+ "line.conversionFactor"+ ])+ .where("line.companyId", "=", companyId)+ .where("line.purchaseOrderLineId", "in", ids)+ .where("invoice.status", "not in", [...POSTED_INVOICE_EXCLUDED_STATUSES])+ .orderBy("invoice.postingDate")+ .orderBy("invoice.createdAt")+ .orderBy("invoice.id")+ .execute()+ );+ // The invoice's write-up of receipt layers that survive the reset.+ const writeUps = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("costLedger as child")+ .innerJoin("costLedger as layer", (join) =>+ join+ .onRef("layer.id", "=", "child.appliesToCostLedgerId")+ .onRef("layer.companyId", "=", "child.companyId")+ )+ .select([+ "child.documentId",+ "child.itemId",+ sql<number>`sum("child"."cost")`.as("cost")+ ])+ .where("child.companyId", "=", companyId)+ .where("child.adjustment", "=", true)+ .where("child.documentType", "=", "Purchase Invoice")+ .where("child.documentId", "in", ids)+ .where("layer.postingDate", ">=", cutoverDate)+ .groupBy(["child.documentId", "child.itemId"])+ .execute()+ );+ // A direct stock line whose receipt was posted with the invoice wrote an+ // item ledger row under the invoice; one whose receipt was left Draft+ // (skipReceiptPost) wrote none and booked WIP.+ const receivedWithInvoice = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("itemLedger")+ .select(["documentId", "itemId"])+ .distinct()+ .where("companyId", "=", companyId)+ .where("documentType", "=", "Purchase Receipt")+ .where("documentId", "in", ids)+ .execute()+ );+ const assets = await readByIds(+ lines.map((line) => line.assetId),+ (ids) =>+ trx+ .selectFrom("fixedAsset as asset")+ .innerJoin("fixedAssetClass as class", (join) =>+ join+ .onRef("class.id", "=", "asset.fixedAssetClassId")+ .onRef("class.companyId", "=", "asset.companyId")+ )+ .select([+ "asset.id",+ "asset.locationId",+ "asset.fixedAssetClassId",+ "class.assetAccountId"+ ])+ .where("asset.companyId", "=", companyId)+ .where("asset.id", "in", ids)+ .execute()+ );+ const glAccounts = await readByIds(+ lines.map((line) => line.accountId),+ (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "name", "isGroup"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ );++ const linesByInvoice = Map.groupBy(lines, (line) => line.invoiceId);+ const shippingByInvoice = new Map(+ deliveries.map((row) => [row.id, Number(row.supplierShippingCost ?? 0)])+ );+ const supplierById = new Map(suppliers.map((row) => [row.id, row]));+ const itemById = new Map(items.map((row) => [row.id, row]));+ const itemCostByItem = new Map(itemCosts.map((row) => [row.itemId, row]));+ const purchaseOrderLineById = new Map(+ purchaseOrderLines.map((row) => [row.id, row])+ );+ const processByOperation = new Map(+ jobOperations.map((row) => [row.id, row.processId])+ );+ const assetById = new Map(assets.map((row) => [row.id, row]));+ const glAccountById = new Map(glAccounts.map((row) => [row.id, row]));++ // Lease lines post as at posting (post-purchase-invoice), with its checks.+ const leaseFacts = await loadLeasePostingFacts(trx, {+ companyId,+ companyGroupId,+ defaults,+ lines: lines.filter((line) => line.invoiceLineType === "Lease")+ });+ const receivedWithInvoiceKeys = new Set(+ receivedWithInvoice.map((row) => `${row.documentId}:${row.itemId}`)+ );+ const writeUpByInvoiceItem = new Map(+ writeUps.map((row) => [`${row.documentId}:${row.itemId}`, Number(row.cost)])+ );++ // Receipt groups per PO line, one per receipt, costed from the layers.+ const layerByReceiptItem = new Map(+ receiptLayers.map((row) => [+ `${row.documentId}:${row.itemId}`,+ { cost: Number(row.cost), quantity: Number(row.quantity) }+ ])+ );+ const receiptsByLine = new Map<string, ReceiptGroup[]>();+ const groupByReceiptLine = new Map<string, ReceiptGroup>();+ for (const line of receiptLines) {+ const purchaseOrderLineId = line.lineId as string;+ const quantity = Number(line.receivedQuantity);+ const layer = layerByReceiptItem.get(`${line.receiptId}:${line.itemId}`);+ const cost =+ layer && layer.quantity > EPSILON+ ? (quantity / layer.quantity) * layer.cost+ : quantity * Number(line.unitPrice ?? 0);+ const key = `${line.receiptId}:${purchaseOrderLineId}`;+ const group = groupByReceiptLine.get(key);+ if (group) {+ group.quantity += quantity;+ group.cost += cost;+ continue;+ }+ const created = {+ postingDate: String(line.postingDate),+ quantity,+ cost+ };+ groupByReceiptLine.set(key, created);+ const list = receiptsByLine.get(purchaseOrderLineId);+ if (list) list.push(created);+ else receiptsByLine.set(purchaseOrderLineId, [created]);+ }++ // What the invoices posted before an invoice invoiced on a PO line, in+ // inventory units. A PO line's rows are in posting order.+ const invoicedRowsByLine = Map.groupBy(+ invoicedLines,+ (row) => row.purchaseOrderLineId+ );+ const invoicedBefore = (invoiceId: string, purchaseOrderLineId: string) => {+ let sum = 0;+ for (const row of invoicedRowsByLine.get(purchaseOrderLineId) ?? []) {+ if (row.invoiceId === invoiceId) break;+ sum += Number(row.quantity) * Number(row.conversionFactor ?? 1);+ }+ return sum;+ };++ return invoices.map((invoice) => {+ const supplier = invoice.supplierId+ ? supplierById.get(invoice.supplierId)+ : undefined;+ // An intercompany payable before the cutover: a stand-in when its+ // default is empty, which the enable re-points.+ const payables = supplier?.intercompanyCompanyId+ ? resolveDefaultAccount(+ defaults,+ "intercompanyPayablesAccount",+ "Provisional"+ )+ : { accountId: defaults.payablesAccount, accountDefaultRole: null };+ const invoiceLines = linesByInvoice.get(invoice.id) ?? [];+ const amountsByLine = new Map(+ calculatePurchasePostingAmounts({+ lines: invoiceLines,+ exchangeRate: invoice.exchangeRate ?? 1,+ supplierShippingCost: shippingByInvoice.get(invoice.id) ?? 0+ }).map((amounts) => [amounts.id, amounts])+ );+ const postingDate = String(invoice.postingDate);+ /** The receipts the posting saw: posted on or before the invoice. */+ const receiptsBefore = (purchaseOrderLineId: string) =>+ (receiptsByLine.get(purchaseOrderLineId) ?? []).filter(+ (group) => group.postingDate <= postingDate+ );++ const postingLines: PurchaseInvoicePostingLine[] = [];+ for (const invoiceLine of invoiceLines) {+ if (invoiceLine.invoiceLineType === "Comment") continue;+ const base = {+ id: invoiceLine.id,+ invoiceLineType: invoiceLine.invoiceLineType,+ locationId: invoiceLine.locationId ?? null,+ amounts: amountsByLine.get(invoiceLine.id)!+ };+ const purchaseOrderLineId = invoiceLine.purchaseOrderLineId;+ const purchaseOrderLine = purchaseOrderLineId+ ? purchaseOrderLineById.get(purchaseOrderLineId)+ : undefined;++ if (isItemLineType(invoiceLine.invoiceLineType)) {+ const item = invoiceLine.itemId+ ? itemById.get(invoiceLine.itemId)+ : undefined;+ const itemCost = invoiceLine.itemId+ ? itemCostByItem.get(invoiceLine.itemId)+ : undefined;+ const itemFacts: PurchaseInvoiceItem = {+ itemId: invoiceLine.itemId ?? null,+ itemTrackingType: item?.itemTrackingType ?? null,+ replenishmentSystem: item?.replenishmentSystem ?? null,+ itemPostingGroupId: itemCost?.itemPostingGroupId ?? null,+ costingMethod: itemCost?.costingMethod ?? null+ };+ const itemKey = `${invoice.id}:${invoiceLine.itemId}`;+ if (!purchaseOrderLineId) {+ postingLines.push({+ ...base,+ kind: "direct",+ item: itemFacts,+ receivedWithInvoice: receivedWithInvoiceKeys.has(itemKey)+ });+ continue;+ }+ const receipts = receiptsBefore(purchaseOrderLineId);+ postingLines.push({+ ...base,+ kind: "ordered",+ item: itemFacts,+ purchaseOrderLine: {+ purchaseOrderLineId,+ quantityReceived: receipts.reduce(+ (sum, group) => sum + group.quantity,+ 0+ ),+ quantityInvoiced: invoicedBefore(invoice.id, purchaseOrderLineId),+ receiptGroups: receipts,+ isOutsideProcessing: Boolean(purchaseOrderLine?.jobOperationId),+ processId: purchaseOrderLine?.jobOperationId+ ? (processByOperation.get(purchaseOrderLine.jobOperationId) ??+ null)+ : null,+ coverage: { storedWriteUp: writeUpByInvoiceItem.get(itemKey) ?? 0 }+ }+ });+ continue;+ }++ switch (invoiceLine.invoiceLineType) {+ case "Fixed Asset": {+ if (!invoiceLine.assetId) {+ throw new InvalidInputError(+ `Purchase invoice ${invoice.invoiceId} has a fixed asset line with no asset selected.`+ );+ }+ const asset = assetById.get(invoiceLine.assetId);+ if (!asset) {+ throw new InvalidInputError(+ `Purchase invoice ${invoice.invoiceId} names fixed asset ${invoiceLine.assetId}, which no longer exists.`+ );+ }+ const receipts = purchaseOrderLineId+ ? receiptsBefore(purchaseOrderLineId)+ : [];+ postingLines.push({+ ...base,+ kind: "fixedAsset",+ purchaseOrderLineId,+ purchaseOrderLineLocationId: purchaseOrderLine?.locationId ?? null,+ assetLocationId: asset.locationId,+ fixedAssetClassId: asset.fixedAssetClassId,+ acquisition:+ receipts.length > 0+ ? {+ receiptCost: receipts.reduce(+ (sum, group) => sum + group.cost,+ 0+ )+ }+ : { assetAccountId: asset.assetAccountId }+ });+ break;+ }+ case "G/L Account": {+ const glAccount = invoiceLine.accountId+ ? glAccountById.get(invoiceLine.accountId)+ : undefined;+ if (!glAccount) {+ throw new InvalidInputError(+ `Purchase invoice ${invoice.invoiceId} has a G/L line on account ${invoiceLine.accountId ?? "(none)"}, which is not in the chart of accounts.`+ );+ }+ if (glAccount.isGroup) {+ throw new InvalidInputError(+ `Purchase invoice ${invoice.invoiceId} has a G/L line on ${glAccount.name}, a group account. Move the line to a posting account.`+ );+ }+ postingLines.push({+ ...base,+ kind: "glAccount",+ purchaseOrderLineId,+ account: glAccount,+ costCenterId: invoiceLine.costCenterId ?? null,+ projectId: invoiceLine.projectId ?? null+ });+ break;+ }+ case "Lease": {+ let lease: ReturnType<typeof resolveLeasePostingLine>;+ try {+ lease = resolveLeasePostingLine(+ invoiceLine,+ base.amounts,+ leaseFacts+ );+ } catch (error) {+ if (!(error instanceof InvalidInputError)) throw error;+ throw new InvalidInputError(+ `Purchase invoice ${invoice.invoiceId}: ${error.message}`+ );+ }+ postingLines.push({ ...base, kind: "lease", ...lease });+ break;+ }+ default:+ throw new Error(+ `Unsupported invoice line type: ${invoiceLine.invoiceLineType}`+ );+ }+ }++ const { lines: journalLines } = buildPurchaseInvoicePostingLines({+ invoice: {+ id: invoice.id,+ supplierId: invoice.supplierId,+ supplierReference: invoice.supplierReference+ },+ supplierTypeId: supplier?.supplierTypeId ?? null,+ accounts: defaults,+ payables,+ lines: postingLines+ });+ return {+ description: `Purchase Invoice ${invoice.invoiceId}`,+ postingDate,+ sourceType: "Purchase Invoice" as const,+ lines: journalLines+ };+ });+ }+ type Args = {+ companyId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ };++ /** Shares `total` across the weights; equal weights when they sum to 0. */+ function share(total: number, weights: number[]): number[] {+ const sum = weights.reduce((acc, weight) => acc + weight, 0);+ if (Math.abs(sum) <= EPSILON) {+ return weights.map(() => total / Math.max(weights.length, 1));+ }+ return weights.map((weight) => (total * weight) / sum);+ }++ function receiptLines(trx: KyselyTx, companyId: string, receiptIds: string[]) {+ return readByIds(receiptIds, (ids) =>+ trx+ .selectFrom("receiptLine")+ .select([+ "id",+ "receiptId",+ "lineId",+ "itemId",+ "receivedQuantity",+ "unitPrice",+ "locationId"+ ])+ .where("companyId", "=", companyId)+ .where("receiptId", "in", ids)+ .orderBy("receiptId")+ .orderBy("createdAt")+ .orderBy("id")+ .execute()+ );+ }++ /** The cost a receipt stored per item and sign, from its own rows only. */+ function storedCosts(+ trx: KyselyTx,+ {+ companyId,+ receiptIds,+ documentType,+ itemLedgerType+ }: {+ companyId: string;+ receiptIds: string[];+ documentType: Database["public"]["Enums"]["itemLedgerDocumentType"];+ itemLedgerType: Database["public"]["Enums"]["itemLedgerType"];+ }+ ) {+ return readByIds(receiptIds, (ids) =>+ trx+ .selectFrom("costLedger")+ .select([+ "documentId",+ "itemId",+ sql<number>`coalesce(sum("cost") filter (where "quantity" > 0), 0)`.as(+ "inbound"+ ),+ sql<number>`coalesce(sum("cost") filter (where "quantity" < 0), 0)`.as(+ "outbound"+ ),+ sql<number>`count(*) filter (where "quantity" < 0)`.as("outboundRows")+ ])+ .where("companyId", "=", companyId)+ .where("documentType", "=", documentType)+ .where("itemLedgerType", "=", itemLedgerType)+ .where("costLedgerType", "=", "Direct Cost")+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .where("documentId", "in", ids)+ .groupBy(["documentId", "itemId"])+ .execute()+ ).then(+ (rows) =>+ new Map(+ rows.map((row) => [+ `${row.documentId}:${row.itemId}`,+ {+ inbound: Number(row.inbound),+ outbound: Number(row.outbound),+ hasOutbound: Number(row.outboundRows) > 0+ }+ ])+ )+ );+ }++ export async function buildLegacyPurchaseReceiptJournals(+ trx: KyselyTx,+ { companyId, cutoverDate, defaults }: Args+ ): Promise<LegacyJournal[]> {+ const receipts = await legacyReceipts(+ trx,+ { companyId, cutoverDate },+ "Purchase Order"+ ).execute();+ if (receipts.length === 0) return [];+ const receiptIds = receipts.map((receipt) => receipt.id);+ const purchaseOrderIds = receipts.map((receipt) => receipt.sourceDocumentId);++ const lines = await receiptLines(trx, companyId, receiptIds);+ const itemIds = lines.map((line) => line.itemId);+ const purchaseOrders = await readByIds(purchaseOrderIds, (ids) =>+ trx+ .selectFrom("purchaseOrder")+ .select([+ "id",+ "supplierId",+ "supplierReference",+ "exchangeRate",+ "purchaseOrderType"+ ])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const deliveries = await readByIds(purchaseOrderIds, (ids) =>+ trx+ .selectFrom("purchaseOrderDelivery")+ .select(["id", "supplierShippingCost"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const suppliers = await readByIds(+ purchaseOrders.map((order) => order.supplierId),+ (ids) =>+ trx+ .selectFrom("supplier")+ .select(["id", "supplierTypeId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ const purchaseOrderLines = await readByIds(+ lines.map((line) => line.lineId),+ (ids) =>+ trx+ .selectFrom("purchaseOrderLine")+ .select(["id", "jobOperationId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const jobOperations = await readByIds(+ purchaseOrderLines.map((line) => line.jobOperationId),+ (ids) =>+ trx+ .selectFrom("jobOperation")+ .select(["id", "processId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const stored = await storedCosts(trx, {+ companyId,+ receiptIds,+ documentType: "Purchase Receipt",+ itemLedgerType: "Purchase"+ });++ const purchaseOrderById = new Map(+ purchaseOrders.map((order) => [order.id, order])+ );+ const shippingByOrder = new Map(+ deliveries.map((row) => [row.id, Number(row.supplierShippingCost ?? 0)])+ );+ const supplierTypeById = new Map(+ suppliers.map((row) => [row.id, row.supplierTypeId])+ );+ const jobOperationByLine = new Map(+ purchaseOrderLines.map((row) => [row.id, row.jobOperationId])+ );+ const processByOperation = new Map(+ jobOperations.map((row) => [row.id, row.processId])+ );+ const linesByReceipt = Map.groupBy(lines, (line) => line.receiptId);++ return receipts.map((receipt) => {+ const order = receipt.sourceDocumentId+ ? purchaseOrderById.get(receipt.sourceDocumentId)+ : undefined;+ const isOutsideProcessing =+ order?.purchaseOrderType === "Outside Processing";+ // Supplier currency to base divides by the order's rate (post-receipt).+ const shippingCost =+ (receipt.sourceDocumentId+ ? (shippingByOrder.get(receipt.sourceDocumentId) ?? 0)+ : 0) / (Number(order?.exchangeRate) || 1);+ const receiptJournalLines: PurchaseReceiptLine[] = (+ linesByReceipt.get(receipt.id) ?? []+ ).map((line) => {+ const item = line.itemId ? itemById.get(line.itemId) : undefined;+ const jobOperationId = line.lineId+ ? jobOperationByLine.get(line.lineId)+ : undefined;+ return {+ purchaseOrderLineId: line.lineId,+ itemId: line.itemId,+ quantity: postedQuantity(line.receivedQuantity),+ unitPrice: Number(line.unitPrice ?? 0),+ itemTrackingType: item?.itemTrackingType,+ replenishmentSystem: item?.replenishmentSystem,+ itemPostingGroupId: line.itemId+ ? (postingGroupByItem.get(line.itemId) ?? null)+ : null,+ locationId: line.locationId,+ processId:+ isOutsideProcessing && jobOperationId+ ? (processByOperation.get(jobOperationId) ?? null)+ : null+ };+ });+ const costs = purchaseReceiptLineCosts(receiptJournalLines, {+ shippingCost,+ isOutsideProcessing+ });+ const storedCost = storedLayerCosts(receiptJournalLines, costs, (itemId) =>+ stored.get(`${receipt.id}:${itemId}`)+ );++ return {+ description: `Purchase Receipt ${receipt.receiptId}`,+ postingDate: String(receipt.postingDate),+ sourceType: "Purchase Receipt" as const,+ lines: buildPurchaseReceiptJournalLines({+ documentId: receipt.id,+ externalDocumentId: order?.supplierReference ?? null,+ isOutsideProcessing,+ supplierId: order?.supplierId ?? null,+ supplierTypeId: order?.supplierId+ ? (supplierTypeById.get(order.supplierId) ?? null)+ : null,+ accounts: defaults,+ lines: receiptJournalLines.map((line, index) => ({+ ...line,+ cost: storedCost.get(index) ?? costs[index]!.cost+ })),+ fixedAssets: []+ })+ };+ });+ }++ /**+ * The cost each layer line stored, by line index, shared across the lines of+ * its item and sign by PO cost. The posting stores the cost it relieved, its+ * PO cost fallback included; an outbound group with no stored row books its+ * PO cost.+ */+ function storedLayerCosts(+ lines: PurchaseReceiptLine[],+ costs: PurchaseReceiptLineCost[],+ storedFor: (+ itemId: string+ ) => { inbound: number; outbound: number; hasOutbound: boolean } | undefined+ ): Map<number, number> {+ const costByLine = new Map<number, number>();+ const layerGroups = Map.groupBy(+ lines.flatMap((line, index) =>+ costs[index]!.createsLayers ? [{ line, index }] : []+ ),+ ({ line }) => `${line.itemId}:${line.quantity > 0 ? "in" : "out"}`+ );+ for (const group of layerGroups.values()) {+ const { line: first } = group[0]!;+ const rows = storedFor(String(first.itemId));+ const poCosts = group.map(({ index }) => costs[index]!.poCost);+ const total =+ first.quantity > 0+ ? (rows?.inbound ?? 0)+ : rows?.hasOutbound+ ? -rows.outbound+ : poCosts.reduce((sum, cost) => sum + cost, 0);+ const shares = share(total, poCosts);+ for (const [position, { index }] of group.entries()) {+ costByLine.set(index, shares[position]!);+ }+ }+ return costByLine;+ }++ export async function buildLegacySalesReturnReceiptJournals(+ trx: KyselyTx,+ { companyId, cutoverDate, defaults }: Args+ ): Promise<LegacyJournal[]> {+ const receipts = await legacyReceipts(+ trx,+ { companyId, cutoverDate },+ "Sales Return Order"+ ).execute();+ if (receipts.length === 0) return [];+ const receiptIds = receipts.map((receipt) => receipt.id);++ const lines = await receiptLines(trx, companyId, receiptIds);+ const itemIds = lines.map((line) => line.itemId);+ const returnOrders = await readByIds(+ receipts.map((receipt) => receipt.sourceDocumentId),+ (ids) =>+ trx+ .selectFrom("salesReturnOrder")+ .select(["id", "customerId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const customers = await readByIds(+ returnOrders.map((order) => order.customerId),+ (ids) =>+ trx+ .selectFrom("customer")+ .select(["id", "customerTypeId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ const stored = await storedCosts(trx, {+ companyId,+ receiptIds,+ documentType: "Sales Return Receipt",+ itemLedgerType: "Sale"+ });++ const customerByOrder = new Map(+ returnOrders.map((order) => [order.id, order.customerId])+ );+ const customerTypeById = new Map(+ customers.map((row) => [row.id, row.customerTypeId])+ );+ const linesByReceipt = Map.groupBy(lines, (line) => line.receiptId);++ return receipts.map((receipt) => {+ const customerId = receipt.sourceDocumentId+ ? (customerByOrder.get(receipt.sourceDocumentId) ?? null)+ : null;+ // The lines that stored a cost row: positive, with an item that is not+ // Non-Inventory.+ const layerLines = (linesByReceipt.get(receipt.id) ?? []).filter(+ (line) =>+ line.itemId &&+ line.lineId &&+ postedQuantity(line.receivedQuantity) > 0 &&+ (itemById.get(line.itemId)?.itemTrackingType ?? "Inventory") !==+ "Non-Inventory"+ );+ const costByLine = new Map<string, number>();+ for (const group of Map.groupBy(layerLines, (line) =>+ String(line.itemId)+ ).values()) {+ const total =+ stored.get(`${receipt.id}:${group[0]!.itemId}`)?.inbound ?? 0;+ const shares = share(+ total,+ group.map((line) => postedQuantity(line.receivedQuantity))+ );+ for (const [index, line] of group.entries()) {+ costByLine.set(line.id, shares[index]!);+ }+ }++ const journalLines = buildSalesReturnReceiptJournalLines({+ documentId: receipt.id,+ externalDocumentId: receipt.externalDocumentId ?? null,+ customerId,+ customerTypeId: customerId+ ? (customerTypeById.get(customerId) ?? null)+ : null,+ accounts: defaults,+ lines: layerLines.map((line) => {+ const itemId = line.itemId as string;+ return {+ returnLineId: line.lineId as string,+ itemId,+ quantity: postedQuantity(line.receivedQuantity),+ cost: costByLine.get(line.id) ?? 0,+ replenishmentSystem: itemById.get(itemId)?.replenishmentSystem,+ itemPostingGroupId: postingGroupByItem.get(itemId) ?? null,+ locationId: line.locationId+ };+ })+ });++ return {+ description: `Sales Return Receipt ${receipt.receiptId}`,+ postingDate: String(receipt.postingDate),+ sourceType: "Sales Return Receipt" as const,+ lines: journalLines+ };+ });+ }+ export async function buildLegacyReimbursementJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ cutoverDate,+ defaults+ }: {+ companyId: string;+ companyGroupId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ }+ ): Promise<LegacyDocumentJournal[]> {+ const reimbursements = await legacyReimbursements(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (reimbursements.length === 0) return [];++ const lines = await readByIds(+ reimbursements.map((reimbursement) => reimbursement.id),+ (ids) =>+ trx+ .selectFrom("reimbursementLine")+ .selectAll()+ .where("companyId", "=", companyId)+ .where("reimbursementId", "in", ids)+ .orderBy("reimbursementId")+ .orderBy("sequence")+ .orderBy("id")+ .execute()+ );+ const payableAccountOf = (payableAccountId: string | null) => {+ const accountId =+ payableAccountId ??+ defaults.employeeReimbursementsPayableAccount ??+ defaults.payablesAccount;+ if (!accountId) {+ throw new InvalidInputError(+ "Set the Employee Reimbursements Payable or the Accounts Payable account in Accounting → Default Accounts."+ );+ }+ return accountId;+ };+ const accounts = await readByIds(+ [+ ...reimbursements.map((reimbursement) =>+ payableAccountOf(reimbursement.payableAccountId)+ ),+ ...lines.map((line) => line.accountId)+ ],+ (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ );+ const accountClasses: Record<string, { class: AccountClass }> = {};+ for (const account of accounts) {+ if (isAccountClass(account.class)) {+ accountClasses[account.id] = { class: account.class };+ }+ }+ const dimensionIds = await costCenterAndProjectDimensions(+ trx,+ companyGroupId+ );+ const lineDimensions = await readByIds(+ lines.map((line) => line.id),+ (ids) =>+ trx+ .selectFrom("reimbursementLineDimension as lineDimension")+ .innerJoin("dimension", "dimension.id", "lineDimension.dimensionId")+ .select([+ "lineDimension.reimbursementLineId",+ "lineDimension.dimensionId",+ "lineDimension.valueId"+ ])+ .where("lineDimension.companyId", "=", companyId)+ .where("lineDimension.reimbursementLineId", "in", ids)+ .where("dimension.companyGroupId", "=", companyGroupId)+ .where("dimension.active", "=", true)+ .orderBy("lineDimension.dimensionId")+ .execute()+ );++ const linesByReimbursement = Map.groupBy(+ lines,+ (line) => line.reimbursementId+ );+ const dimensionsByLine = Map.groupBy(+ lineDimensions,+ (row) => row.reimbursementLineId+ );++ return reimbursements.map((reimbursement) => {+ const codingLines = linesByReimbursement.get(reimbursement.id) ?? [];+ const payableAccountId = payableAccountOf(reimbursement.payableAccountId);+ const built = buildReimbursementJournal({+ reimbursement: {+ amount: Number(reimbursement.amount),+ payableAccountId,+ currencyCode: reimbursement.currencyCode,+ exchangeRate: Number(reimbursement.exchangeRate)+ },+ lines: codingLines.map((line) => ({+ accountId: line.accountId,+ amount: Number(line.amount),+ costCenterId: line.costCenterId,+ projectId: line.projectId,+ description: line.description+ })),+ accounts: accountClasses,+ documentId: reimbursement.id,+ documentReadableId: reimbursement.reimbursementId+ });+ // One debit per coding line in order, then the payable credit.+ if (+ built.journalLines.length !== codingLines.length + 1 ||+ codingLines.some(+ (line, index) => built.journalLines[index]?.accountId !== line.accountId+ )+ ) {+ throw new Error("Reimbursement journal lines do not match coding lines");+ }+ const journalLineReference = nanoid();+ return {+ documentId: reimbursement.id,+ payableAccountId,+ description: `Reimbursement ${reimbursement.reimbursementId}`,+ postingDate: String(+ reimbursement.postingDate ?? reimbursement.reimbursementDate+ ),+ sourceType: "Reimbursement" as const,+ lines: built.journalLines.map((line, index) => {+ const codingLine = codingLines[index];+ // The trailing payable leg is a control account and carries no+ // coding. A line's own dimension rows win over its columns.+ const byDimension = new Map<string, string>();+ if (codingLine) {+ if (dimensionIds.costCenter && line.costCenterId) {+ byDimension.set(dimensionIds.costCenter, line.costCenterId);+ }+ if (dimensionIds.project && line.projectId) {+ byDimension.set(dimensionIds.project, line.projectId);+ }+ for (const row of dimensionsByLine.get(codingLine.id) ?? []) {+ byDimension.set(row.dimensionId, row.valueId);+ }+ }+ return {+ accountId: line.accountId,+ amount: line.amount,+ quantity: 1,+ description: line.description,+ documentType: "Reimbursement" as const,+ documentId: line.documentId,+ journalLineReference,+ dimensions: {},+ dimensionValues: [...byDimension].map(([dimensionId, valueId]) => ({+ dimensionId,+ valueId+ }))+ };+ })+ };+ });+ }+ /** The runs and disposals the enable wrote a journal for. */+ export type LegacyRunCounts = Pick<+ LegacyDocumentCounts,+ "depreciationRuns" | "assetDisposals" | "revenueRecognitionRuns"+ >;++ /** A journal and the rows that store its id. */+ type Built<T> = { journal: LegacyJournal; attach: T };++ /** A built run journal, dated, with a new reference on each line. */+ function legacyJournal(+ journal: RunJournal,+ postingDate: string+ ): LegacyJournal {+ return {+ description: journal.description,+ postingDate,+ sourceType: journal.sourceType,+ lines: journal.lines.map((line) => ({+ ...line,+ journalLineReference: nanoid()+ }))+ };+ }++ /** The month end of a `YYYY-MM-DD` date. */+ // ---------------------------------------------------------------------------+ // Depreciation+ // ---------------------------------------------------------------------------++ export type DepreciationRunLineRow = DepreciationRunLine & {+ depreciationRunId: string;+ runReadableId: string;+ journalId: string | null;+ deferredTaxJournalId: string | null;+ };++ /**+ * The depreciation journals the legacy lines miss: one per line with a book+ * amount and no journal, and one deferred tax journal per run and month with+ * none, with today's settings. A month whose lines all have no tax amount+ * was built with tax depreciation off, so it had no deferred tax journal.+ */+ export function buildLegacyDepreciationJournals(+ rows: DepreciationRunLineRow[],+ settings: DeferredTaxSettings | null+ ): {+ depreciation: Built<{ runId: string; lineIds: string[] }>[];+ deferredTax: Built<{ runId: string; lineIds: string[] }>[];+ } {+ const runByLine = new Map(rows.map((row) => [row.id, row.depreciationRunId]));+ const depreciation = buildDepreciationJournals(+ rows.filter((row) => row.journalId === null)+ ).map((journal) => ({+ journal: legacyJournal(journal, journal.monthEnd),+ attach: { runId: runByLine.get(journal.lineId)!, lineIds: [journal.lineId] }+ }));++ const runs = Map.groupBy(+ rows.filter((row) => row.deferredTaxJournalId === null),+ (row) => row.depreciationRunId+ );+ const deferredTax = [...runs].flatMap(([runId, runLines]) => {+ const taxedMonths = new Set(+ runLines+ .filter((row) => row.taxAmount !== null)+ .map((row) => row.monthEnd)+ );+ return buildDeferredTaxJournals({+ runReadableId: runLines[0]!.runReadableId,+ lines: runLines.filter((row) => taxedMonths.has(row.monthEnd)),+ settings+ }).map((journal) => ({+ journal: legacyJournal(journal, journal.monthEnd),+ attach: { runId, lineIds: journal.lineIds }+ }));+ });+ return { depreciation, deferredTax };+ }++ async function loadDepreciationRunLines(+ trx: KyselyTx,+ companyId: string,+ cutoverDate: string+ ): Promise<DepreciationRunLineRow[]> {+ const rows = await legacyDepreciationRunLines(trx, {+ companyId,+ cutoverDate+ }).execute();+ return rows.map((row) => ({+ id: row.id,+ depreciationRunId: row.depreciationRunId,+ runReadableId: row.runReadableId,+ monthEnd: row.monthEnd,+ amount: Number(row.amount),+ taxAmount: row.taxAmount === null ? null : Number(row.taxAmount),+ journalId: row.journalId,+ deferredTaxJournalId: row.deferredTaxJournalId,+ assetReadableId: row.assetReadableId,+ locationId: row.locationId,+ fixedAssetClassId: row.fixedAssetClassId,+ depreciationExpenseAccountId: row.depreciationExpenseAccountId,+ accumulatedDepreciationAccountId: row.accumulatedDepreciationAccountId+ }));+ }++ // ---------------------------------------------------------------------------+ // Disposal+ // ---------------------------------------------------------------------------++ /** Scrap disposals on or after the cutover with no journal. The asset's+ * cost and accumulated depreciation did not change after its disposal. */+ async function loadDisposals(+ trx: KyselyTx,+ companyId: string,+ cutoverDate: string+ ): Promise<(Disposal & { id: string })[]> {+ const rows = await legacyDisposals(trx, { companyId, cutoverDate }).execute();+ return rows.map((row) => ({+ ...row,+ disposalMethod: REBUILT_DISPOSAL_METHOD,+ acquisitionCost: Number(row.acquisitionCost),+ accumulatedDepreciation: Number(row.accumulatedDepreciation)+ }));+ }++ // ---------------------------------------------------------------------------+ // Revenue recognition+ // ---------------------------------------------------------------------------++ export type RecognitionRow = RecognitionScheduleRow & {+ runId: string;+ runReadableId: string;+ runPeriodEnd: string;+ /** The run's type: a lease run's journals post as 'Lease Run'. */+ runType: RunType;+ };++ /**+ * The journals of the legacy recognition rows, one per run and month (the+ * row's `postingDate` is its month end). The run's journal is the one of its+ * own period, else its latest month's.+ */+ export function buildLegacyRecognitionJournals(+ rows: RecognitionRow[],+ sources: RecognitionSources,+ classById: Map<string, AccountClass>+ ): Built<{+ runId: string;+ scheduleIds: string[];+ leaseScheduleLineIds: string[];+ lesseeScheduleLineIds: string[];+ isRunJournal: boolean;+ }>[] {+ const unclassified = recognitionAccountWithoutClass(rows, classById);+ if (unclassified) {+ throw new InvalidInputError(+ `Account ${unclassified} on the revenue schedule has no class. Set its class in Accounting → Chart of Accounts.`+ );+ }+ return [...Map.groupBy(rows, (row) => row.runId)].flatMap(+ ([runId, runRows]) => {+ const { journals, runJournal } = buildRecognitionJournals({+ runType: runRows[0]!.runType,+ runReadableId: runRows[0]!.runReadableId,+ runPeriodEnd: runRows[0]!.runPeriodEnd,+ rows: runRows,+ sources,+ classById+ });+ return journals.map((journal) => ({+ journal: legacyJournal(journal, journal.postingDate),+ attach: {+ runId,+ scheduleIds: journal.scheduleIds,+ leaseScheduleLineIds: journal.leaseScheduleLineIds,+ lesseeScheduleLineIds: journal.lesseeScheduleLineIds,+ isRunJournal: journal === runJournal+ }+ }));+ }+ );+ }++ /**+ * Schedule rows a Posted run recognized on or after the cutover, with no+ * journal, the sources their journal lines reference (the invoice, else the+ * rental agreement, else the contract) and the class of their accounts.+ */+ async function loadRecognitionRows(+ trx: KyselyTx,+ companyId: string,+ companyGroupId: string,+ cutoverDate: string+ ): Promise<{+ rows: RecognitionRow[];+ sources: RecognitionSources;+ classById: Map<string, AccountClass>;+ }> {+ const scheduled = await legacyRecognitionSchedule(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (scheduled.length === 0) {+ return {+ rows: [],+ sources: {+ invoiceLines: new Map(),+ rentalLines: new Map(),+ contractLines: new Map(),+ leases: new Map(),+ leaseAssets: new Map()+ },+ classById: new Map()+ };+ }++ const invoiceLines = await readByIds(+ scheduled.map((row) => row.salesInvoiceLineId),+ (ids) =>+ trx+ .selectFrom("salesInvoiceLine as invoiceLine")+ .innerJoin("salesInvoice as invoice", (join) =>+ join+ .onRef("invoice.id", "=", "invoiceLine.invoiceId")+ .onRef("invoice.companyId", "=", "invoiceLine.companyId")+ )+ .select([+ "invoiceLine.id",+ "invoiceLine.invoiceId",+ "invoiceLine.itemId",+ "invoiceLine.locationId",+ "invoice.customerId"+ ])+ .where("invoiceLine.companyId", "=", companyId)+ .where("invoiceLine.id", "in", ids)+ .execute()+ );+ const rentalLines = await readByIds(+ scheduled+ .filter((row) => !row.salesInvoiceLineId)+ .map((row) => row.rentalAgreementLineId),+ (ids) =>+ trx+ .selectFrom("rentalAgreementLine as rentalLine")+ .innerJoin("rentalAgreement as agreement", (join) =>+ join+ .onRef("agreement.id", "=", "rentalLine.rentalAgreementId")+ .onRef("agreement.companyId", "=", "rentalLine.companyId")+ )+ .select([+ "rentalLine.id",+ "rentalLine.itemId",+ "agreement.id as rentalAgreementId",+ "agreement.customerId",+ "agreement.locationId"+ ])+ .where("rentalLine.companyId", "=", companyId)+ .where("rentalLine.id", "in", ids)+ .execute()+ );+ const contractLines = await readByIds(+ scheduled.map((row) => row.customerContractLineId),+ (ids) =>+ trx+ .selectFrom("customerContractLine as contractLine")+ .innerJoin("customerContract as contract", (join) =>+ join+ .onRef("contract.id", "=", "contractLine.customerContractId")+ .onRef("contract.companyId", "=", "contractLine.companyId")+ )+ .select([+ "contractLine.id",+ "contractLine.itemId",+ "contract.id as customerContractId",+ "contract.customerId",+ sql<+ string | null+ >`coalesce("contractLine"."projectId", "contract"."projectId")`.as(+ "projectId"+ )+ ])+ .where("contractLine.companyId", "=", companyId)+ .where("contractLine.id", "in", ids)+ .execute()+ );+ const leases = await readByIds(+ scheduled.map((row) => row.leaseId),+ (ids) =>+ trx+ .selectFrom("lease")+ .select(["id", "supplierId", "locationId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const leaseAssets = await readByIds(+ scheduled.map((row) => row.leaseScheduleLineId),+ (ids) =>+ trx+ .selectFrom("leaseScheduleLine as scheduleLine")+ .innerJoin("leaseLine as line", (join) =>+ join+ .onRef("line.id", "=", "scheduleLine.leaseLineId")+ .onRef("line.companyId", "=", "scheduleLine.companyId")+ )+ .select([+ "scheduleLine.id",+ "scheduleLine.leaseLineId",+ "line.locationId"+ ])+ .where("scheduleLine.companyId", "=", companyId)+ .where("scheduleLine.id", "in", ids)+ .execute()+ );+ const accounts = await readByIds(+ scheduled.flatMap((row) => [row.debitAccountId, row.creditAccountId]),+ (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ );+ const classById = new Map<string, AccountClass>();+ for (const account of accounts) {+ if (isAccountClass(account.class)) classById.set(account.id, account.class);+ }++ const rows = scheduled.map(+ (row): RecognitionRow => ({+ scheduleId: row.scheduleId,+ runId: row.runId,+ runReadableId: row.runReadableId,+ runPeriodEnd: row.runPeriodEnd,+ runType: row.runType,+ // Every journal takes its own month: there is no period yet.+ postingDate: monthEndOf(row.scheduledDate),+ type: row.type,+ amount: Number(row.amount),+ debitAccountId: row.debitAccountId,+ creditAccountId: row.creditAccountId,+ salesInvoiceLineId: row.salesInvoiceLineId,+ rentalAgreementLineId: row.rentalAgreementLineId,+ customerContractLineId: row.customerContractLineId,+ rentalLeaseScheduleLineId: row.rentalLeaseScheduleLineId,+ leaseId: row.leaseId,+ leaseScheduleLineId: row.leaseScheduleLineId+ })+ );+ return {+ rows,+ sources: {+ invoiceLines: new Map(invoiceLines.map((row) => [row.id, row])),+ rentalLines: new Map(rentalLines.map((row) => [row.id, row])),+ contractLines: new Map(contractLines.map((row) => [row.id, row])),+ leases: new Map(leases.map((row) => [row.id, row])),+ leaseAssets: new Map(leaseAssets.map((row) => [row.id, row]))+ },+ classById+ };+ }++ // ---------------------------------------------------------------------------+ // Writes+ // ---------------------------------------------------------------------------++ /** A table that stores the journal a run or disposal wrote. */+ type JournalTable =+ | "depreciationRunLine"+ | "fixedAssetDisposal"+ | "revenueRecognitionSchedule"+ | "revenueRecognitionRun"+ | "customerContractLedgerEntry"+ | "rentalLeaseScheduleLine"+ | "leaseScheduleLine";++ /**+ * Sets each row's journal column where it is still empty, one statement per+ * chunk. `key` is the column the ids match.+ */+ async function setJournalColumn(+ trx: KyselyTx,+ {+ companyId,+ table,+ column = "journalId",+ key = "id",+ rows+ }: {+ companyId: string;+ table: JournalTable;+ column?: "journalId" | "deferredTaxJournalId";+ key?: "id" | "revenueRecognitionScheduleId";+ rows: { id: string; journalId: string }[];+ }+ ) {+ for (const chunk of chunkArray(rows, ROWS_PER_STATEMENT)) {+ await sql`UPDATE ${sql.table(table)} AS t+ SET ${sql.ref(column)} = v."journalId"+ FROM jsonb_to_recordset(${JSON.stringify(chunk)}::jsonb)+ AS v("id" text, "journalId" text)+ WHERE t.${sql.ref(key)} = v."id"+ AND t."companyId" = ${companyId}+ AND t.${sql.ref(column)} IS NULL`.execute(trx);+ }+ }++ /**+ * Writes the journals of the legacy runs and scrap disposals dated on or+ * after the cutover, Provisional, sets the rows' journal columns, and keeps+ * the journals out of provider sync.+ */+ export async function journalLegacyRuns(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults+ }: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ }+ ): Promise<{ counts: LegacyRunCounts; journalIds: string[] }> {+ const settings = await trx+ .selectFrom("companySettings")+ .select(["assetTaxDepreciationEnabled", "assetTaxRate"])+ .where("id", "=", companyId)+ .executeTakeFirst();+ const taxSettings = deferredTaxSettings({+ enabled: settings?.assetTaxDepreciationEnabled,+ taxRate: Number(settings?.assetTaxRate ?? 0),+ dtlAccountId: defaults.deferredTaxLiabilityAccountId,+ dtExpenseAccountId: defaults.deferredTaxExpenseAccountId+ });++ const runLines = await loadDepreciationRunLines(trx, companyId, cutoverDate);+ const { depreciation, deferredTax } = buildLegacyDepreciationJournals(+ runLines,+ taxSettings+ );+ const disposalRows = await loadDisposals(trx, companyId, cutoverDate);+ const disposals = disposalRows.map((row) => {+ const journal = buildDisposalJournal(row);+ return {+ journal: legacyJournal(journal, journal.postingDate),+ attach: { disposalId: row.id }+ };+ });+ const recognitionFacts = await loadRecognitionRows(+ trx,+ companyId,+ companyGroupId,+ cutoverDate+ );+ const recognition = buildLegacyRecognitionJournals(+ recognitionFacts.rows,+ recognitionFacts.sources,+ recognitionFacts.classById+ );++ const built = [...depreciation, ...deferredTax, ...disposals, ...recognition];+ const ids = await insertProvisionalJournals(trx, {+ companyId,+ companyGroupId,+ userId,+ journals: built.map(({ journal }) => journal)+ });+ let offset = 0;+ const idsOf = <T>(list: T[]) => {+ const slice = ids.slice(offset, offset + list.length);+ offset += list.length;+ return list.map((item, index) => ({ item, journalId: slice[index] }));+ };+ const written = <T>(+ list: { item: T; journalId: string | null | undefined }[]+ ) =>+ list.filter(+ (entry): entry is { item: T; journalId: string } => !!entry.journalId+ );++ const depreciationIds = written(idsOf(depreciation));+ const deferredTaxIds = written(idsOf(deferredTax));+ const disposalIds = written(idsOf(disposals));+ const recognitionIds = written(idsOf(recognition));++ await setJournalColumn(trx, {+ companyId,+ table: "depreciationRunLine",+ rows: depreciationIds.flatMap(({ item, journalId }) =>+ item.attach.lineIds.map((id) => ({ id, journalId }))+ )+ });+ await setJournalColumn(trx, {+ companyId,+ table: "depreciationRunLine",+ column: "deferredTaxJournalId",+ rows: deferredTaxIds.flatMap(({ item, journalId }) =>+ item.attach.lineIds.map((id) => ({ id, journalId }))+ )+ });+ await setJournalColumn(trx, {+ companyId,+ table: "fixedAssetDisposal",+ rows: disposalIds.map(({ item, journalId }) => ({+ id: item.attach.disposalId,+ journalId+ }))+ });++ // Each schedule row, its contract ledger entry and its lease schedule line+ // record the journal of the row's own month.+ const journalBySchedule = new Map<string, string>();+ for (const { item, journalId } of recognitionIds) {+ for (const scheduleId of item.attach.scheduleIds) {+ journalBySchedule.set(scheduleId, journalId);+ }+ }+ const scheduleJournals = [...journalBySchedule].map(([id, journalId]) => ({+ id,+ journalId+ }));+ await setJournalColumn(trx, {+ companyId,+ table: "revenueRecognitionSchedule",+ rows: scheduleJournals+ });+ await setJournalColumn(trx, {+ companyId,+ table: "customerContractLedgerEntry",+ key: "revenueRecognitionScheduleId",+ rows: scheduleJournals+ });+ await setJournalColumn(trx, {+ companyId,+ table: "rentalLeaseScheduleLine",+ rows: recognitionIds.flatMap(({ item, journalId }) =>+ item.attach.leaseScheduleLineIds.map((id) => ({ id, journalId }))+ )+ });+ await setJournalColumn(trx, {+ companyId,+ table: "leaseScheduleLine",+ rows: recognitionIds.flatMap(({ item, journalId }) =>+ item.attach.lesseeScheduleLineIds.map((id) => ({ id, journalId }))+ )+ });+ // The run names the journal of its own period, else its latest month's.+ await setJournalColumn(trx, {+ companyId,+ table: "revenueRecognitionRun",+ rows: recognitionIds+ .filter(({ item }) => item.attach.isRunJournal)+ .map(({ item, journalId }) => ({ id: item.attach.runId, journalId }))+ });++ return {+ counts: {+ depreciationRuns: new Set(+ [...depreciationIds, ...deferredTaxIds].map(+ ({ item }) => item.attach.runId+ )+ ).size,+ assetDisposals: disposalIds.length,+ revenueRecognitionRuns: new Set(+ recognitionIds.map(({ item }) => item.attach.runId)+ ).size+ },+ journalIds: ids.filter((id): id is string => id !== null)+ };+ }+ export async function buildLegacySalesInvoiceJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ cutoverDate,+ defaults+ }: {+ companyId: string;+ companyGroupId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ }+ ): Promise<LegacyJournal[]> {+ const invoices = await legacySalesInvoices(trx, {+ companyId,+ cutoverDate+ }).execute();+ if (invoices.length === 0) return [];+ const invoiceIds = invoices.map((invoice) => invoice.id);++ const lines = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("salesInvoiceLine")+ .selectAll()+ .where("companyId", "=", companyId)+ .where("invoiceId", "in", ids)+ .orderBy("invoiceId")+ .orderBy("createdAt")+ .orderBy("id")+ .execute()+ );+ const lineIds = lines.map((line) => line.id);+ const itemIds = lines.map((line) => line.itemId);++ const shipments = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("salesInvoiceShipment")+ .select(["id", "shippingCost"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const customers = await readByIds(+ invoices.map((invoice) => invoice.customerId),+ (ids) =>+ trx+ .selectFrom("customer")+ .select(["id", "customerTypeId", "intercompanyCompanyId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const items = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("item")+ .select(["id", "itemTrackingType", "replenishmentSystem"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemCosts = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("itemCost")+ .select(["itemId", "itemPostingGroupId"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", ids)+ .execute()+ );+ const salesOrderLines = await readByIds(+ lines.map((line) => line.salesOrderLineId),+ (ids) =>+ trx+ .selectFrom("salesOrderLine")+ .select(["id", "locationId", "sentComplete"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const assets = await readByIds(+ lines.map((line) => line.assetId),+ (ids) =>+ trx+ .selectFrom("fixedAsset")+ .select(["id", "locationId", "fixedAssetClassId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const agreementLines = await readByIds(+ lines.map((line) => line.rentalAgreementLineId),+ (ids) =>+ trx+ .selectFrom("rentalAgreementLine")+ .select(["id", "rentalAgreementId", "itemId", "lessorClassification"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ // What the posting deferred and a run has still to recognize: each line's+ // Deferral rows dated on or after the cutover, per deferred revenue account.+ const deferrals = await readByIds(lineIds, (ids) =>+ trx+ .selectFrom("revenueRecognitionSchedule")+ .select([+ "salesInvoiceLineId",+ "debitAccountId",+ sql<number>`sum("amount")`.as("amount")+ ])+ .where("companyId", "=", companyId)+ .where("salesInvoiceLineId", "in", ids)+ .where("type", "=", "Deferral")+ .where("scheduledDate", ">=", cutoverDate)+ .groupBy(["salesInvoiceLineId", "debitAccountId"])+ .orderBy("salesInvoiceLineId")+ .orderBy("debitAccountId")+ .execute()+ );+ // The cost a direct line's shipment relieved, where the posting stored it.+ const costRows = await readByIds(invoiceIds, (ids) =>+ trx+ .selectFrom("costLedger")+ .select(["id", "documentId", "itemId", "quantity", "cost"])+ .where("companyId", "=", companyId)+ .where("documentType", "=", "Sales Shipment")+ .where("documentId", "in", ids)+ .where("adjustment", "=", false)+ .where("quantity", "<", 0)+ .orderBy("entryNumber")+ .execute()+ );++ // The posting's accounts, with the stand-in rule of a posting before the+ // cutover: the enable writes these journals Provisional. Plain revenue+ // needs no deferral, rental or contract default; the deferral rows name+ // their own accounts.+ const plan = planSalesInvoiceAccounts(defaults, "Provisional", {+ deferredRevenue: false,+ rental: null,+ contract: false,+ accountIds: deferrals.map((row) => row.debitAccountId)+ });+ const accountRows = await readByIds(plan.accountIds, (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "class", "active", "isGroup"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ );+ const accounts = resolveSalesInvoiceAccounts(+ plan,+ // Read by the company group, so it is the group's.+ accountRows.map((row): SalesPostingAccount => ({ ...row, companyGroupId })),+ companyGroupId+ );++ const linesByInvoice = Map.groupBy(lines, (line) => line.invoiceId);+ const shippingByInvoice = new Map(+ shipments.map((row) => [row.id, Number(row.shippingCost ?? 0)])+ );+ const customerById = new Map(customers.map((row) => [row.id, row]));+ const deferralsByLine = Map.groupBy(+ deferrals,+ (row) => row.salesInvoiceLineId+ );+ const costRowsByInvoice = Map.groupBy(costRows, (row) => row.documentId);+ const facts = {+ companyId,+ companyGroupId,+ items: new Map(items.map((row) => [row.id, row])),+ postingGroups: new Map(+ itemCosts.map((row) => [row.itemId, row.itemPostingGroupId])+ ),+ salesOrderLines: new Map(salesOrderLines.map((row) => [row.id, row])),+ assets: new Map(assets.map((row) => [row.id, row])),+ rentalAgreementLines: new Map(agreementLines.map((row) => [row.id, row])),+ accounts,+ contract: null,+ rental: null,+ disposal: null+ };++ // A line with deferral rows credits them, and the rest to sales; every+ // other line books plain revenue.+ const revenue = (line: SalesInvoiceLine): SalesLineRevenue => {+ const deferred = deferralsByLine.get(line.id) ?? [];+ if (deferred.length === 0) return { book: "sales" };+ return {+ book: "legs",+ legs: [+ ...deferred.map((row) => ({+ account: accounts.account(row.debitAccountId),+ accountClass: "Liability" as const,+ description: "Deferred Revenue",+ amount: Number(row.amount)+ })),+ {+ account: accounts.account(defaults.salesAccount),+ accountClass: "Revenue" as const,+ description: "Sales Account"+ }+ ]+ };+ };++ return invoices.map((invoice) => {+ const customer = invoice.customerId+ ? customerById.get(invoice.customerId)+ : undefined;+ const invoiceLines = linesByInvoice.get(invoice.id) ?? [];+ const unusedCostRows = [...(costRowsByInvoice.get(invoice.id) ?? [])];+ // The cost row of a direct line: the first unused one of its item and+ // quantity, else of its item.+ const directCost = (line: SalesInvoiceLine): number | null => {+ if (!line.itemId) return null;+ const quantity = round(Number(line.quantity));+ const sameItem = unusedCostRows.filter(+ (row) => row.itemId === line.itemId+ );+ const costRow =+ sameItem.find((row) => round(-Number(row.quantity)) === quantity) ??+ sameItem[0];+ if (!costRow) return null;+ unusedCostRows.splice(unusedCostRows.indexOf(costRow), 1);+ return -Number(costRow.cost);+ };+ const journal = buildSalesInvoiceJournal({+ ...facts,+ invoice,+ customerTypeId: customer?.customerTypeId ?? null,+ intercompanyPartnerId: customer?.intercompanyCompanyId ?? null,+ lines: invoiceLines,+ headerShipping: allocateSalesHeaderShipping(+ invoiceLines,+ shippingByInvoice.get(invoice.id) ?? 0+ ),+ revenue,+ directCost+ });++ return {+ description: `Sales Invoice ${invoice.invoiceId}`,+ postingDate: String(invoice.postingDate),+ sourceType: "Sales Invoice" as const,+ lines: journal.lines.map((line, index) => ({+ ...accounts.standIns.storedLine(line),+ dimensions: salesLineDimensions(+ journal.metadata[index]!,+ invoice.customerId+ )+ }))+ };+ });+ }+ export async function buildLegacySalesShipmentJournals(+ trx: KyselyTx,+ { companyId, cutoverDate, defaults }: Args+ ): Promise<LegacyJournal[]> {+ const shipments = await legacyShipments(+ trx,+ { companyId, cutoverDate },+ LEGACY_SALES_SHIPMENT+ ).execute();+ if (shipments.length === 0) return [];+ const shipmentIds = shipments.map((shipment) => shipment.id);++ const lines = await readByIds(shipmentIds, (ids) =>+ trx+ .selectFrom("shipmentLine")+ .select(["id", "shipmentId", "itemId", "shippedQuantity", "locationId"])+ .where("companyId", "=", companyId)+ .where("shipmentId", "in", ids)+ .orderBy("shipmentId")+ .orderBy("createdAt")+ .orderBy("id")+ .execute()+ );+ const itemIds = lines.map((line) => line.itemId);+ const salesOrders = await readByIds(+ shipments.map((shipment) => shipment.sourceDocumentId),+ (ids) =>+ trx+ .selectFrom("salesOrder")+ .select(["id", "customerId", "customerReference"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const customers = await readByIds(+ salesOrders.map((order) => order.customerId),+ (ids) =>+ trx+ .selectFrom("customer")+ .select(["id", "customerTypeId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ // The cost the shipment relieved per item, stored negative.+ const sales = await readByIds(shipmentIds, (ids) =>+ shipmentCostRows(trx, companyId, LEGACY_SALES_SHIPMENT)+ .select([+ "cost.documentId",+ "cost.itemId",+ sql<number>`sum("cost"."cost")`.as("cost")+ ])+ .where("cost.documentId", "in", ids)+ .groupBy(["cost.documentId", "cost.itemId"])+ .execute()+ );++ const orderById = new Map(salesOrders.map((order) => [order.id, order]));+ const customerTypeById = new Map(+ customers.map((row) => [row.id, row.customerTypeId])+ );+ const relievedCostByShipment = new Map(+ [...Map.groupBy(sales, (row) => row.documentId)].map(+ ([shipmentId, rows]) => [+ shipmentId,+ new Map(rows.map((row) => [String(row.itemId), -Number(row.cost)]))+ ]+ )+ );+ const linesByShipment = Map.groupBy(lines, (line) => line.shipmentId);++ return shipments.map((shipment) => {+ const order = shipment.sourceDocumentId+ ? orderById.get(shipment.sourceDocumentId)+ : undefined;+ const customerId = order?.customerId ?? null;+ const journal = buildSalesShipmentJournal({+ shipmentId: shipment.id,+ shipmentReadableId: shipment.shipmentId,+ externalDocumentId: order?.customerReference ?? null,+ customerId,+ customerTypeId: customerId+ ? (customerTypeById.get(customerId) ?? null)+ : null,+ defaults,+ lines: (linesByShipment.get(shipment.id) ?? []).map((line) => {+ const item = line.itemId ? itemById.get(line.itemId) : undefined;+ return {+ shipmentLineId: line.id,+ itemId: line.itemId,+ shippedQuantity: postedQuantity(line.shippedQuantity),+ itemTrackingType: item?.itemTrackingType ?? null,+ replenishmentSystem: item?.replenishmentSystem ?? null,+ itemPostingGroupId: line.itemId+ ? (postingGroupByItem.get(line.itemId) ?? null)+ : null,+ locationId: line.locationId ?? shipment.locationId+ };+ }),+ relievedCostByItem: relievedCostByShipment.get(shipment.id) ?? new Map(),+ // Not rebuilt: the asset register carries a fixed asset sale.+ fixedAssetSales: []+ });+ return { ...journal, postingDate: String(shipment.postingDate) };+ });+ }++ /** Sales and purchase return shipments, in that order. */+ export async function buildLegacyReturnShipmentJournals(+ trx: KyselyTx,+ { companyId, cutoverDate, defaults }: Args+ ): Promise<LegacyJournal[]> {+ const salesReturns = await legacyShipments(+ trx,+ { companyId, cutoverDate },+ LEGACY_SALES_RETURN_SHIPMENT+ ).execute();+ const purchaseReturns = await legacyShipments(+ trx,+ { companyId, cutoverDate },+ LEGACY_PURCHASE_RETURN_SHIPMENT+ ).execute();+ if (salesReturns.length === 0 && purchaseReturns.length === 0) return [];++ // The cost rows, in the order the posting wrote them.+ const costRows = (ids: string[], kind: LegacyShipmentKind) =>+ shipmentCostRows(trx, companyId, kind)+ .select(["cost.documentId", "cost.itemId", "cost.quantity", "cost.cost"])+ .where("cost.documentId", "in", ids)+ .where("cost.itemId", "is not", null)+ .$narrowType<{ documentId: string; itemId: string }>()+ .orderBy("cost.entryNumber")+ .execute();+ const rows = [+ ...(await readByIds(+ salesReturns.map((shipment) => shipment.id),+ (ids) => costRows(ids, LEGACY_SALES_RETURN_SHIPMENT)+ )),+ ...(await readByIds(+ purchaseReturns.map((shipment) => shipment.id),+ (ids) => costRows(ids, LEGACY_PURCHASE_RETURN_SHIPMENT)+ ))+ ];+ const itemIds = rows.map((row) => row.itemId);+ const itemById = await readItems(trx, companyId, itemIds);+ const postingGroupByItem = await readPostingGroups(trx, companyId, itemIds);+ const salesReturnOrders = await readByIds(+ salesReturns.map((shipment) => shipment.sourceDocumentId),+ (ids) =>+ trx+ .selectFrom("salesReturnOrder")+ .select(["id", "customerId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const purchaseReturnOrders = await readByIds(+ purchaseReturns.map((shipment) => shipment.sourceDocumentId),+ (ids) =>+ trx+ .selectFrom("purchaseReturnOrder")+ .select(["id", "supplierId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const customers = await readByIds(+ salesReturnOrders.map((order) => order.customerId),+ (ids) =>+ trx+ .selectFrom("customer")+ .select(["id", "customerTypeId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ const suppliers = await readByIds(+ purchaseReturnOrders.map((order) => order.supplierId),+ (ids) =>+ trx+ .selectFrom("supplier")+ .select(["id", "supplierTypeId"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );++ const customerByOrder = new Map(+ salesReturnOrders.map((order) => [order.id, order.customerId])+ );+ const supplierByOrder = new Map(+ purchaseReturnOrders.map((order) => [order.id, order.supplierId])+ );+ const customerTypeById = new Map(+ customers.map((row) => [row.id, row.customerTypeId])+ );+ const supplierTypeById = new Map(+ suppliers.map((row) => [row.id, row.supplierTypeId])+ );+ const rowsByShipment = Map.groupBy(rows, (row) => row.documentId);++ const build = (+ shipment: (typeof salesReturns)[number],+ sourceDocument: "Sales Return Order" | "Purchase Return Order"+ ): LegacyJournal => {+ const isSalesReturn = sourceDocument === "Sales Return Order";+ const orderParty = isSalesReturn ? customerByOrder : supplierByOrder;+ const partyTypeById = isSalesReturn ? customerTypeById : supplierTypeById;+ const partyId = shipment.sourceDocumentId+ ? (orderParty.get(shipment.sourceDocumentId) ?? null)+ : null;+ const journal = buildReturnShipmentJournal({+ sourceDocument,+ shipmentId: shipment.id,+ shipmentReadableId: shipment.shipmentId,+ locationId: shipment.locationId,+ partyId,+ partyTypeId: partyId ? (partyTypeById.get(partyId) ?? null) : null,+ defaults,+ items: (rowsByShipment.get(shipment.id) ?? []).map((row) => ({+ itemId: row.itemId,+ quantity: -Number(row.quantity),+ cost: -Number(row.cost),+ replenishmentSystem:+ itemById.get(row.itemId)?.replenishmentSystem ?? null,+ itemPostingGroupId: postingGroupByItem.get(row.itemId) ?? null+ }))+ });+ return { ...journal, postingDate: String(shipment.postingDate) };+ };++ return [+ ...salesReturns.map((shipment) => build(shipment, "Sales Return Order")),+ ...purchaseReturns.map((shipment) =>+ build(shipment, "Purchase Return Order")+ )+ ];+ }+ const legacyJournalsLogger = getLogger("server-functions", "legacy-journals");++ type Enums = Database["public"]["Enums"];++ type JournalLineInsert = Database["public"]["Tables"]["journalLine"]["Insert"];++ /** One line, as the document's posting writes it, and its dimension values. */+ export type LegacyJournalLine = Omit<+ JournalLineInsert,+ "journalId" | "companyId" | "createdBy"+ > & {+ dimensions: Partial<Record<DimensionEntityType, string | null>>;+ /** Values by dimension id, as a posting that resolves its own dimensions+ * writes them. One wins over a `dimensions` value of the same dimension. */+ dimensionValues?: { dimensionId: string; valueId: string }[];+ };++ export type LegacyJournal = {+ description: string;+ postingDate: string;+ sourceType: Enums["journalEntrySourceType"];+ lines: LegacyJournalLine[];+ };++ /** A legacy journal and the document whose `journalId` gets its id. */+ export type LegacyDocumentJournal = LegacyJournal & {+ documentId: string;+ /** A reimbursement's payable account, set on a row that has none. */+ payableAccountId?: string;+ };++ /** Rows per statement, well inside Postgres's 65,535 bind parameters. */+ export const ROWS_PER_STATEMENT = 1000;++ /** Runs `read` once per chunk of the distinct ids and concatenates the rows. */+ export async function readByIds<T>(+ ids: Iterable<string | null | undefined>,+ read: (chunk: string[]) => Promise<T[]>+ ): Promise<T[]> {+ const unique = [+ ...new Set([...ids].filter((id): id is string => Boolean(id)))+ ];+ const rows: T[] = [];+ for (const chunk of chunkArray(unique, ROWS_PER_STATEMENT)) {+ rows.push(...(await read(chunk)));+ }+ return rows;+ }++ /** A received or shipped quantity as the posting reads it: null and NaN are+ * 0. */+ export function postedQuantity(value: number | null): number {+ const quantity = Number(value ?? 0);+ return Number.isNaN(quantity) ? 0 : quantity;+ }++ /** Items by id, with what the movement journals read. */+ export async function readItems(+ trx: KyselyTx,+ companyId: string,+ itemIds: Iterable<string | null | undefined>+ ) {+ const rows = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("item")+ .select([+ "id",+ "itemTrackingType",+ "replenishmentSystem",+ "readableIdWithRevision"+ ])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ );+ return new Map(rows.map((row) => [row.id, row]));+ }++ /** Each item's posting group (the ItemPostingGroup dimension), by item id. */+ export async function readPostingGroups(+ trx: KyselyTx,+ companyId: string,+ itemIds: Iterable<string | null | undefined>+ ) {+ const rows = await readByIds(itemIds, (ids) =>+ trx+ .selectFrom("itemCost")+ .select(["itemId", "itemPostingGroupId"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", ids)+ .execute()+ );+ return new Map(rows.map((row) => [row.itemId, row.itemPostingGroupId]));+ }++ /**+ * Refuses journals dated in a Closed or Locked period, naming the period,+ * before any is written: the journal trigger refuses a Closed period with a+ * bare error, and a Locked one fails later, when the journal gets its+ * period. The enable meets none (no period on or after the cutover can be+ * closed before it); a repair after it can.+ */+ async function assertPeriodsOpen(+ trx: KyselyTx,+ companyId: string,+ postingDates: string[]+ ) {+ const dates = [...new Set(postingDates)].sort();+ const first = dates[0];+ const last = dates[dates.length - 1];+ if (!first || !last) return;+ const periods = await trx+ .selectFrom("accountingPeriod")+ .select([+ sql<string>`"startDate"::text`.as("startDate"),+ sql<string>`"endDate"::text`.as("endDate"),+ "closeStatus",+ "closedAt"+ ])+ .where("companyId", "=", companyId)+ .where("endDate", ">=", first)+ .where("startDate", "<=", last)+ .where((eb) =>+ eb.or([+ eb("closeStatus", "in", ["Closed", "Locked"]),+ eb("closedAt", "is not", null)+ ])+ )+ .orderBy("startDate")+ .execute();+ const blocked = periods.find((period) =>+ dates.some((date) => period.startDate <= date && date <= period.endDate)+ );+ if (!blocked) return;+ const name = formatPeriodLabel(blocked.startDate);+ const locked = blocked.closeStatus === "Locked" && blocked.closedAt === null;+ legacyJournalsLogger.warn("Refused legacy journals in a closed period", {+ companyId,+ period: blocked.startDate,+ closeStatus: blocked.closeStatus+ });+ throw new InvalidInputError(+ locked+ ? `The period ${name} is locked. Unlock it, then write the missing journals.`+ : `The period ${name} is closed. Reopen it, then write the missing journals.`+ );+ }++ /**+ * Inserts the journals, their lines and the lines' dimensions in a few+ * statements, each kept out of provider sync (`keepOutOfProviderSync`). A journal with no lines is skipped, as a posting skips a+ * zero-value document. Refuses a journal dated in a Closed or Locked period. The journal entry numbers are allocated in order.+ * Returns the id of each journal, in the order given (null when skipped).+ */+ export async function insertProvisionalJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ userId,+ journals+ }: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ journals: LegacyJournal[];+ }+ ): Promise<(string | null)[]> {+ const writable = journals.filter((journal) => journal.lines.length > 0);+ if (writable.length === 0) return journals.map(() => null);+ await assertPeriodsOpen(+ trx,+ companyId,+ writable.map((journal) => journal.postingDate)+ );++ const entryIds = await getNextSequences(+ trx,+ "journalEntry",+ companyId,+ writable.length+ );+ const postedAt = datetime.timestamp();+ const journalIdByEntry = new Map<string, string>();+ for (const rows of chunkArray(+ writable.map((journal, index) => ({ journal, entryId: entryIds[index]! })),+ ROWS_PER_STATEMENT+ )) {+ const inserted = await trx+ .insertInto("journal")+ .values(+ rows.map(({ journal, entryId }) => ({+ journalEntryId: entryId,+ accountingPeriodId: null,+ description: journal.description,+ postingDate: journal.postingDate,+ sourceType: journal.sourceType,+ status: "Provisional" as const,+ postedAt,+ postedBy: userId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id", "journalEntryId"])+ .execute();+ for (const row of inserted)+ journalIdByEntry.set(row.journalEntryId, row.id);+ }++ const dimensions = await trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", companyGroupId)+ .where("active", "=", true)+ .execute();+ const dimensionIdByEntity = new Map(+ dimensions.map((dimension) => [dimension.entityType, dimension.id])+ );++ const lines = writable.flatMap((journal, index) => {+ const journalId = journalIdByEntry.get(entryIds[index]!)!;+ return journal.lines.map(+ ({ dimensions: values, dimensionValues, ...line }) => ({+ insert: { ...line, journalId, companyId, createdBy: userId },+ values,+ dimensionValues: dimensionValues ?? []+ })+ );+ });+ for (const rows of chunkArray(lines, ROWS_PER_STATEMENT)) {+ // Returned in insert order, as every posting reads them back.+ const inserted = await trx+ .insertInto("journalLine")+ .values(rows.map((row) => row.insert))+ .returning("id")+ .execute();+ const dimensionInserts = inserted.flatMap((line, index) => {+ const row = rows[index]!;+ const valueByDimension = new Map<string, string>();+ for (const [entityType, valueId] of Object.entries(row.values)) {+ const dimensionId = dimensionIdByEntity.get(+ entityType as DimensionEntityType+ );+ if (dimensionId && valueId) valueByDimension.set(dimensionId, valueId);+ }+ for (const { dimensionId, valueId } of row.dimensionValues) {+ valueByDimension.set(dimensionId, valueId);+ }+ return [...valueByDimension].map(([dimensionId, valueId]) => ({+ journalLineId: line.id,+ dimensionId,+ valueId,+ companyId+ }));+ });+ for (const dimensionRows of chunkArray(+ dimensionInserts,+ ROWS_PER_STATEMENT+ )) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionRows)+ .execute();+ }+ }+ const idByJournal = new Map(+ writable.map((journal, index) => [+ journal,+ journalIdByEntry.get(entryIds[index]!)!+ ])+ );+ await keepOutOfProviderSync(trx, {+ companyId,+ userId,+ journals: writable.map((journal) => ({+ id: idByJournal.get(journal)!,+ sourceType: journal.sourceType+ }))+ });+ return journals.map((journal) => idByJournal.get(journal) ?? null);+ }++ /** A document whose posting stores the journal it wrote. */+ export type JournalDocumentTable =+ | "payment"+ | "memo"+ | "charge"+ | "reimbursement";++ /**+ * Sets each document's `journalId` to the journal the enable wrote for it, as+ * its posting does, so a later void reverses that journal. A reimbursement+ * with no payable account also gets the one its journal credits. One+ * statement per chunk.+ */+ export async function attachJournalIds(+ trx: KyselyTx,+ {+ table,+ companyId,+ userId,+ rows+ }: {+ table: JournalDocumentTable;+ companyId: string;+ userId: string;+ rows: { id: string; journalId: string | null; payableAccountId?: string }[];+ }+ ): Promise<void> {+ const attached = rows.filter((row) => row.journalId !== null);+ const updatedAt = datetime.timestamp();+ for (const chunk of chunkArray(attached, ROWS_PER_STATEMENT)) {+ const values = sql`jsonb_to_recordset(${JSON.stringify(chunk)}::jsonb)+ AS v("id" text, "journalId" text, "payableAccountId" text)`;+ if (table === "reimbursement") {+ await sql`UPDATE "reimbursement" AS d+ SET "journalId" = v."journalId",+ "payableAccountId" = COALESCE(d."payableAccountId", v."payableAccountId"),+ "updatedAt" = ${updatedAt}, "updatedBy" = ${userId}+ FROM ${values}+ WHERE d."id" = v."id" AND d."companyId" = ${companyId}`.execute(trx);+ } else {+ await sql`UPDATE ${sql.table(table)} AS d+ SET "journalId" = v."journalId",+ "updatedAt" = ${updatedAt}, "updatedBy" = ${userId}+ FROM ${values}+ WHERE d."id" = v."id" AND d."companyId" = ${companyId}`.execute(trx);+ }+ }+ }++ export const CUTOVER_REBUILT_SYNC_CODE = "CUTOVER_REBUILT";++ /**+ * Records an Excluded `journalEntry` sync operation for each journal and+ * each accounting integration of the company, active or not. The reconciler+ * (events and the outbound sweep) and the journal backfill skip a journal+ * that has any operation, so none of them pushes it; the period close counts+ * Excluded as settled. Re-send in Sync Activity still pushes one on purpose.+ *+ * Every journal the legacy backfill or its repair writes gets one. The reset+ * deleted a company's journals and their sync records, not the provider's+ * copies, so a journal written again of a document that had one before may+ * already be in the provider, and pushing it would post it twice there.+ * Which documents had one cannot be told reliably from the rows: a company+ * that had accounting on wrote a journal for every family, and the stored+ * cost rows say only that a posting ran, not that it journaled. So every+ * rebuilt journal is kept out, and a user sends the ones the provider lacks+ * from Sync Activity.+ */+ async function keepOutOfProviderSync(+ trx: KyselyTx,+ {+ companyId,+ userId,+ journals+ }: {+ companyId: string;+ userId: string;+ journals: { id: string; sourceType: Enums["journalEntrySourceType"] }[];+ }+ ) {+ if (journals.length === 0) return;+ // The accounting providers, by the role the integration declares.+ const integrations = await trx+ .selectFrom("companyIntegration")+ .innerJoin("integration", "integration.id", "companyIntegration.id")+ .select("companyIntegration.id")+ .where("companyIntegration.companyId", "=", companyId)+ .where("integration.providerRole", "=", "accounting")+ .execute();+ if (integrations.length === 0) return;+ const completedAt = datetime.timestamp();+ const rows = integrations.flatMap((integration) =>+ journals.map((journal) => ({+ companyId,+ integration: integration.id,+ entityType: "journalEntry",+ entityId: journal.id,+ direction: "push-to-accounting",+ trigger: "posting",+ status: "Excluded" as const,+ idempotencyKey: `journalEntry:${journal.id}:push-to-accounting:cutover-rebuilt`,+ errorCode: CUTOVER_REBUILT_SYNC_CODE,+ errorMessage:+ "Written again when accounting was set up; the original may already be in the accounting system",+ metadata: toJson({ sourceType: journal.sourceType }),+ completedAt,+ createdBy: userId+ }))+ );+ for (const chunk of chunkArray(rows, ROWS_PER_STATEMENT)) {+ await trx.insertInto("accountingSyncOperation").values(chunk).execute();+ }+ }+ /**+ * The Provisional journals a step takes: those dated on or after the cutover+ * (the enable), or the ones with these ids (a repair after the enable).+ */+ export type JournalScope =+ | { cutoverDate: string }+ | { journalIds: readonly string[] };++ /** The ids of the Provisional journals in the scope, as a subquery. */+ function scopedJournals(trx: KyselyTx, companyId: string, scope: JournalScope) {+ const provisional = trx+ .selectFrom("journal")+ .select("id")+ .where("companyId", "=", companyId)+ .where("status", "=", "Provisional");+ return "cutoverDate" in scope+ ? provisional.where("postingDate", ">=", scope.cutoverDate)+ : // One array parameter, whatever the number of ids.+ provisional.where("id", "=", sql<string>`ANY(${[...scope.journalIds]})`);+ }++ /**+ * Step 8. Gives every Provisional journal in the scope the period that+ * holds its date, resolving each month once.+ */+ export async function assignPeriods(+ trx: KyselyTx,+ companyId: string,+ scope: JournalScope+ ) {+ const dates = await trx+ .selectFrom("journal")+ .select("postingDate")+ .distinct()+ .where("companyId", "=", companyId)+ .where("id", "in", scopedJournals(trx, companyId, scope))+ .execute();+ const months = new Map<string, { start: string; end: string }>();+ for (const { postingDate } of dates) {+ const date = parseDate(String(postingDate));+ const start = startOfMonth(date).toString();+ months.set(start, { start, end: endOfMonth(date).toString() });+ }+ if (months.size === 0) return;++ const periods: { start: string; end: string; periodId: string }[] = [];+ for (const month of months.values()) {+ const period = await resolveAccountingPeriod(+ trx,+ companyId,+ month.start,+ "historical"+ );+ periods.push({ ...month, periodId: period.id });+ }+ await sql`+ UPDATE "journal" AS j+ SET "accountingPeriodId" = v."periodId"+ FROM (VALUES ${sql.join(+ periods.map(+ (period) =>+ sql`(${period.start}::date, ${period.end}::date, ${period.periodId})`+ )+ )}) AS v("start", "end", "periodId")+ WHERE j."companyId" = ${companyId}+ AND j."id" IN (${scopedJournals(trx, companyId, scope)})+ AND j."postingDate" BETWEEN v."start" AND v."end"+ `.execute(trx);+ }++ const OPTIONAL_DEFAULTS: ReadonlySet<string> = new Set(OPTIONAL_DEFAULT_ROLES);++ const isOptionalDefaultRole = (role: string): role is OptionalDefaultRole =>+ OPTIONAL_DEFAULTS.has(role);++ /**+ * Step 9. A stand-in line sits on retained earnings and names the default it+ * wanted. Before promotion it moves to that default, one UPDATE per role. An+ * intercompany elimination line copies the account of the journal line it+ * mirrors (post-sales-invoice and post-purchase-invoice copy it when they+ * post), so it moves with its line.+ */+ export async function repointStandInLines(+ trx: KyselyTx,+ companyId: string,+ scope: JournalScope,+ defaults: AccountDefaults+ ) {+ const staying = scopedJournals(trx, companyId, scope);+ const roles = await trx+ .selectFrom("journalLine")+ .select("accountDefaultRole")+ .distinct()+ .where("companyId", "=", companyId)+ .where("accountDefaultRole", "is not", null)+ .where("journalId", "in", staying)+ .execute();+ for (const { accountDefaultRole: role } of roles) {+ if (!role) continue;+ if (!isOptionalDefaultRole(role)) {+ throw new ServerFnError(+ `A journal line names ${role}, which is not an account default a stand-in line can wait for.`+ );+ }+ // A role with a fallback resolves to it, as a posting today would.+ const accountId = configuredDefaultAccount(defaults, role);+ if (!accountId) throw new MissingAccountDefaultError(role);+ const standIns = trx+ .selectFrom("journalLine")+ .select("id")+ .where("companyId", "=", companyId)+ .where("accountDefaultRole", "=", role)+ .where("journalId", "in", staying);+ await trx+ .updateTable("intercompanyEliminationLine")+ .set({ accountId })+ .where("companyId", "=", companyId)+ .where("journalLineId", "in", standIns)+ .where("accountId", "=", defaults.retainedEarningsAccount)+ .execute();+ await trx+ .updateTable("journalLine")+ .set({ accountId, accountDefaultRole: null })+ .where("companyId", "=", companyId)+ .where("accountDefaultRole", "=", role)+ .where("journalId", "in", staying)+ .execute();+ }+ }++ /** Step 9, continued. Promotes the Provisional journals in the scope to Posted. */+ export async function promoteJournals(+ trx: KyselyTx,+ companyId: string,+ userId: string,+ scope: JournalScope+ ) {+ const now = datetime.timestamp();+ await trx+ .updateTable("journal")+ .set({+ status: "Posted",+ postedAt: now,+ postedBy: userId,+ updatedBy: userId,+ updatedAt: now+ })+ .where("companyId", "=", companyId)+ .where("id", "in", scopedJournals(trx, companyId, scope))+ .execute();+ }+ const RECOST_DESCRIPTION = "Cutover recost";++ /** Sets each row's `column` to its value, one statement per chunk. */+ async function setCostLedger(+ trx: KyselyTx,+ companyId: string,+ column: "remainingQuantity" | "cost",+ rows: [id: string, value: number][]+ ) {+ for (const chunk of chunkArray(rows, ROWS_PER_STATEMENT)) {+ await sql`+ UPDATE "costLedger" AS c+ SET ${sql.ref(column)} = v."value"+ FROM (VALUES ${sql.join(+ chunk.map(([id, value]) => sql`(${id}, ${value}::numeric)`)+ )}) AS v("id", "value")+ WHERE c."id" = v."id" AND c."companyId" = ${companyId}+ `.execute(trx);+ }+ }++ /**+ * Closes the cost layers dated before the cutover and opens one layer per+ * item at the reviewed unit cost. Then re-costs every outbound movement of a+ * FIFO or LIFO item dated on or after the cutover: the opening layer and+ * every layer and movement after it run again in the order they were posted+ * (`recostOutbound`), each movement relieving the layers open then as+ * `calculateCOGS` does, with its serial units and the layers' invoice+ * write-ups. Each document's difference is booked as a Provisional "Cutover+ * recost" journal between the accounts its own posting used. Standard and+ * Average items cost from `itemCost`, not layers, so their movements keep+ * their cost. A serial recost (`costLedgerType` "Revaluation") keeps its+ * cost: it relieves the layers in the run, but the account its difference+ * was booked against is not stored, so it is not re-costed.+ */+ export async function resetAndRecostInventory(+ trx: KyselyTx,+ {+ companyId,+ userId,+ cutoverDate,+ companyGroupId,+ inventory,+ defaults+ }: {+ companyId: string;+ userId: string;+ cutoverDate: string;+ companyGroupId: string;+ inventory: Awaited<ReturnType<typeof getCutoverInventory>>;+ defaults: AccountDefaults;+ }+ ) {+ // The layers before the cutover close, their invoice write-ups with them.+ const openBefore = trx+ .selectFrom("costLedger")+ .select("id")+ .where("companyId", "=", companyId)+ .where(isCostLayer)+ .where("postingDate", "<", cutoverDate)+ .where("remainingQuantity", ">", 0);+ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: 0 })+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ .where((eb) =>+ eb.or([+ eb("id", "in", openBefore),+ eb("appliesToCostLedgerId", "in", openBefore)+ ])+ )+ .execute();+ const openingLayers = planInventoryReset(+ inventory.map((item) => ({ itemId: item.itemId, quantity: item.quantity })),+ new Map(inventory.map((item) => [item.itemId, item.unitCost]))+ );++ // The FIFO and LIFO items' layers and movements after the cutover, in the+ // order they were posted, and the layers' invoice write-ups.+ const layeredItems = trx+ .selectFrom("itemCost")+ .select("itemId")+ .where("companyId", "=", companyId)+ .where("costingMethod", "in", ["FIFO", "LIFO"]);+ const afterCutover = trx+ .selectFrom("costLedger")+ .where("companyId", "=", companyId)+ .where("postingDate", ">=", cutoverDate)+ .where("itemId", "in", layeredItems);+ const [layeredCosts, ledger, children, leaving] = await inOrder([+ () =>+ trx+ .selectFrom("itemCost")+ .select(["itemId", "unitCost", "costingMethod"])+ .where("companyId", "=", companyId)+ .where("costingMethod", "in", ["FIFO", "LIFO"])+ .execute(),+ () =>+ afterCutover+ .select([+ "id",+ "itemId",+ "quantity",+ "cost",+ "remainingQuantity",+ "trackedEntityId",+ "costLedgerType",+ "documentType",+ "documentId",+ "postingDate"+ ])+ .where((eb) => eb.or([isCostLayer(eb), isCostRelief(eb)]))+ .orderBy("postingDate")+ .orderBy("createdAt")+ .orderBy("entryNumber")+ .execute(),+ () =>+ trx+ .selectFrom("costLedger")+ .select([+ "id",+ "appliesToCostLedgerId",+ "quantity",+ "cost",+ "remainingQuantity"+ ])+ .where("companyId", "=", companyId)+ .where(+ "appliesToCostLedgerId",+ "in",+ afterCutover.select("id").where(isCostLayer)+ )+ .orderBy("createdAt")+ .execute(),+ // The serial units each document's outbound rows took out.+ () =>+ trx+ .selectFrom("itemLedger")+ .select(["documentId", "itemId", "trackedEntityId"])+ .distinct()+ .where("companyId", "=", companyId)+ .where("postingDate", ">=", cutoverDate)+ .where("itemId", "in", layeredItems)+ .where("quantity", "<", 0)+ .where("trackedEntityId", "is not", null)+ .execute()+ ]);+ const methodByItem = new Map(+ layeredCosts.map((row): [string, CostingMethod] => [+ row.itemId,+ row.costingMethod === "LIFO" ? "LIFO" : "FIFO"+ ])+ );+ const childrenByLayer = Map.groupBy(+ children,+ (child) => child.appliesToCostLedgerId+ );+ const leavingByDocumentItem = Map.groupBy(+ leaving,+ (row) => `${row.documentId}:${row.itemId}`+ );++ const openingKey = (itemId: string) => `opening:${itemId}`;+ // Every layer runs again from its full quantity.+ const events: RecostEvent[] = [+ ...openingLayers+ .filter((layer) => methodByItem.has(layer.itemId))+ .map((layer) => ({+ layer: {+ id: openingKey(layer.itemId),+ itemId: layer.itemId,+ quantity: layer.quantity,+ cost: layer.cost,+ remainingQuantity: layer.quantity,+ trackedEntityId: null,+ children: []+ }+ })),+ ...ledger.map((row): RecostEvent => {+ const itemId = row.itemId!;+ return Number(row.quantity) > 0+ ? {+ layer: {+ id: row.id,+ itemId,+ quantity: Number(row.quantity),+ cost: Number(row.cost),+ remainingQuantity: Number(row.quantity),+ trackedEntityId: row.trackedEntityId,+ children: (childrenByLayer.get(row.id) ?? []).map((child) => ({+ id: child.id,+ quantity: Number(child.quantity),+ cost: Number(child.cost),+ remainingQuantity: Number(child.quantity)+ }))+ }+ }+ : {+ outbound: {+ costLedgerId: row.id,+ itemId,+ quantity: -Number(row.quantity),+ cost: -Number(row.cost),+ trackedEntityIds: row.trackedEntityId+ ? [row.trackedEntityId]+ : (+ leavingByDocumentItem.get(`${row.documentId}:${itemId}`) ??+ []+ ).map((unit) => unit.trackedEntityId!)+ }+ };+ })+ ];+ // A quantity no layer covers costs at the item's unit cost, as+ // calculateCOGS costs negative inventory.+ const recost = recostOutbound(+ events,+ methodByItem,+ new Map(layeredCosts.map((row) => [row.itemId, Number(row.unitCost ?? 0)]))+ );++ // The opening layers, with what the re-cost left of them.+ if (openingLayers.length > 0) {+ const timeZone = await getCompanyTimeZone(trx, companyId);+ const createdAt = sql<string>`(${cutoverDate}::date::timestamp AT TIME ZONE ${timeZone})`;+ await trx+ .insertInto("costLedger")+ .values(+ openingLayers.map((layer) => ({+ itemLedgerType: "Purchase" as const,+ costLedgerType: "Direct Cost" as const,+ documentType: "Purchase Receipt" as const,+ adjustment: false,+ itemId: layer.itemId,+ quantity: layer.quantity,+ cost: layer.cost,+ nominalCost: layer.cost,+ remainingQuantity:+ recost.remainingById.get(openingKey(layer.itemId)) ??+ layer.quantity,+ postingDate: cutoverDate,+ // Before any layer posted on the cutover day, so later relief+ // takes the opening stock first.+ createdAt,+ companyId+ }))+ )+ .execute();+ }++ // The layers and write-ups after the cutover, where the re-cost moved them.+ const stored = new Map<string, number>([+ ...ledger.map((row) => [row.id, Number(row.remainingQuantity)] as const),+ ...children.map(+ (child) => [child.id, Number(child.remainingQuantity)] as const+ )+ ]);+ await setCostLedger(+ trx,+ companyId,+ "remainingQuantity",+ [...recost.remainingById].filter(+ ([id, remaining]) => stored.has(id) && stored.get(id) !== remaining+ )+ );++ const ledgerById = new Map(ledger.map((row) => [row.id, row]));+ const changed = recost.movements.filter(+ (movement) =>+ Math.abs(movement.delta) > EPSILON &&+ ledgerById.get(movement.costLedgerId)!.costLedgerType !== "Revaluation"+ );+ if (changed.length === 0) return;+ await setCostLedger(+ trx,+ companyId,+ "cost",+ changed.map((movement) => [movement.costLedgerId, -movement.newCost])+ );++ // One Provisional journal per document and posting date.+ await postRecostJournals(trx, {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults,+ deltas: changed.map((movement) => {+ const row = ledgerById.get(movement.costLedgerId)!;+ return {+ itemId: row.itemId!,+ documentId: row.documentId,+ documentType: row.documentType,+ postingDate: String(row.postingDate),+ quantity: -Number(row.quantity),+ delta: movement.delta+ };+ })+ });+ }++ type RecostDelta = {+ itemId: string;+ documentId: string | null;+ documentType: string | null;+ postingDate: string;+ quantity: number;+ delta: number;+ };++ /**+ * Books each re-costed movement's difference between the two accounts its+ * document's own Provisional journal used: the item's inventory line and the+ * line paired with it by `journalLineReference`. Inventory is credited by a+ * positive delta and the paired line moves the other way, signed as the+ * original pair is; the lines copy the original's document keys, so a reader+ * of the document's chain (close-job's WIP sum, a void) sees the new cost. A+ * pair posted at zero (a movement costed at nothing) carries no sign, so the+ * offset takes the debit sign of its own account's class: every re-costed+ * movement is outbound, so its inventory line is a credit and the offset a+ * debit. Refuses rather than guess an account.+ */+ async function postRecostJournals(+ trx: KyselyTx,+ {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults,+ deltas+ }: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ cutoverDate: string;+ defaults: AccountDefaults;+ deltas: RecostDelta[];+ }+ ) {+ const label = (delta: RecostDelta) =>+ `${delta.documentType ?? "document"} ${delta.documentId ?? "(none)"}`;+ const missingDocument = deltas.find((delta) => !delta.documentId);+ if (missingDocument) {+ throw new ServerFnError(+ `The cutover re-cost changed a movement of item ${missingDocument.itemId} that names no document, so its journal cannot be adjusted.`,+ 409+ );+ }+ const documentIds = [...new Set(deltas.map((delta) => delta.documentId!))];++ const [items, lines] = await inOrder([+ () =>+ readByIds(+ deltas.map((delta) => delta.itemId),+ (ids) =>+ trx+ .selectFrom("item")+ .select(["id", "replenishmentSystem"])+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute()+ ),+ () =>+ readByIds(documentIds, (ids) =>+ trx+ .selectFrom("journalLine as line")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "line.journalId")+ .onRef("journal.companyId", "=", "line.companyId")+ )+ .select([+ "line.id",+ "line.journalId",+ "line.journalLineReference",+ "line.accountId",+ "line.accountDefaultRole",+ "line.amount",+ "line.quantity",+ "line.documentId",+ "line.documentType",+ "line.documentLineReference",+ "journal.postingDate",+ "journal.sourceType"+ ])+ .where("line.companyId", "=", companyId)+ .where("line.documentId", "in", ids)+ .where("journal.status", "=", "Provisional")+ .where("journal.postingDate", ">=", cutoverDate)+ .execute()+ )+ ]);+ type Line = (typeof lines)[number];+ const replenishmentByItem = new Map(+ items.map((item) => [item.id, item.replenishmentSystem])+ );+ const linesByPair = Map.groupBy(+ lines,+ (line) => `${line.journalId}:${line.journalLineReference}`+ );+ // A document's credit lines on an account, on one posting date.+ const creditsByDocument = Map.groupBy(+ lines.filter((line) => Number(line.amount) <= EPSILON),+ (line) => `${line.documentId}:${String(line.postingDate)}:${line.accountId}`+ );++ type Pair = { inventory: Line; offset: Line };+ const resolved = deltas.map((delta) => {+ const inventoryAccountId = resolveInventoryAccount(+ replenishmentByItem.get(delta.itemId) ?? null,+ defaults+ ).account;+ const pairs: Pair[] = (+ creditsByDocument.get(+ `${delta.documentId}:${delta.postingDate}:${inventoryAccountId}`+ ) ?? []+ ).flatMap((inventory) => {+ const others = (+ linesByPair.get(+ `${inventory.journalId}:${inventory.journalLineReference}`+ ) ?? []+ ).filter((line) => line.id !== inventory.id);+ return others.length === 1 ? [{ inventory, offset: others[0]! }] : [];+ });+ const offsetKey = (pair: Pair) =>+ `${pair.offset.accountId}:${pair.offset.accountDefaultRole ?? ""}`;+ let candidates = pairs;+ if (new Set(candidates.map(offsetKey)).size > 1) {+ candidates = pairs.filter((pair) =>+ equals(Number(pair.inventory.quantity), delta.quantity)+ );+ }+ if (candidates.length === 0) {+ throw new ServerFnError(+ `The cutover re-cost could not find the inventory line of ${label(delta)} and the line paired with it, so it cannot adjust that journal.`,+ 409+ );+ }+ if (new Set(candidates.map(offsetKey)).size > 1) {+ throw new ServerFnError(+ `The inventory lines of ${label(delta)} pair with more than one account, so the cutover re-cost cannot tell which to adjust.`,+ 409+ );+ }+ return { delta, pair: candidates[0]! };+ });++ // The class of each offset in a pair posted at zero, which signs it. A+ // stand-in line is signed for the default it stands in for, which no+ // account class records, so it keeps the refusal below.+ const zeroOffsetIds = resolved.flatMap(({ pair }) =>+ Number(pair.inventory.amount) === 0 &&+ Number(pair.offset.amount) === 0 &&+ !pair.offset.accountDefaultRole &&+ pair.offset.accountId+ ? [pair.offset.accountId]+ : []+ );+ const classByAccount = new Map(+ (+ await readByIds(zeroOffsetIds, (ids) =>+ trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("companyGroupId", "=", companyGroupId)+ .where("id", "in", ids)+ .execute()+ )+ ).map((account) => [account.id, account.class])+ );+ const signRelation = (pair: Pair): number => {+ const relation =+ Math.sign(Number(pair.inventory.amount)) *+ Math.sign(Number(pair.offset.amount));+ if (relation !== 0) return relation;+ if (pair.offset.accountDefaultRole) return 0;+ const offsetClass = classByAccount.get(pair.offset.accountId ?? "");+ if (!offsetClass) return 0;+ return (+ Math.sign(credit("asset", 1)) *+ Math.sign(debit(accountTypeFromClass(offsetClass), 1))+ );+ };++ // One journal per document and posting date, numbered in one statement.+ const groups = [+ ...Map.groupBy(+ resolved,+ (entry) => `${entry.delta.documentId}:${entry.delta.postingDate}`+ ).values()+ ];+ const entryIds = await getNextSequences(+ trx,+ "journalEntry",+ companyId,+ groups.length+ );+ const postedAt = datetime.timestamp();+ const journals = await trx+ .insertInto("journal")+ .values(+ groups.map((entries, index) => ({+ journalEntryId: entryIds[index]!,+ description: RECOST_DESCRIPTION,+ postingDate: entries[0]!.delta.postingDate,+ sourceType: entries[0]!.pair.inventory.sourceType,+ status: "Provisional" as const,+ accountingPeriodId: null,+ postedAt,+ postedBy: userId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id", "journalEntryId"])+ .execute();+ const journalIdByEntry = new Map(+ journals.map((journal) => [journal.journalEntryId, journal.id])+ );++ const lineInserts: JournalLineInsert[] = groups.flatMap((entries, index) => {+ const journalId = journalIdByEntry.get(entryIds[index]!)!;+ return entries.flatMap(({ delta, pair }) => {+ // The offset mirrors the original pair's sign relation rather than+ // re-deriving it from the offset's account class: a stand-in line sits+ // on retained earnings but is signed for the account it stands in for.+ const relation = signRelation(pair);+ if (relation === 0) {+ throw new ServerFnError(+ `The inventory line of ${label(delta)} or the line paired with it has no amount, so the cutover re-cost cannot sign its adjustment.`,+ 409+ );+ }+ const inventoryAmount = round(credit("asset", delta.delta));+ const journalLineReference = nanoid();+ const keys = (line: Line) => ({+ documentType: line.documentType,+ documentId: line.documentId,+ documentLineReference: line.documentLineReference+ });+ return [+ {+ journalId,+ accountId: pair.inventory.accountId,+ description: RECOST_DESCRIPTION,+ amount: inventoryAmount,+ quantity: 0,+ ...keys(pair.inventory),+ journalLineReference,+ companyId,+ createdBy: userId+ },+ {+ journalId,+ accountId: pair.offset.accountId,+ accountDefaultRole: pair.offset.accountDefaultRole,+ description: RECOST_DESCRIPTION,+ amount: round(inventoryAmount * relation),+ quantity: 0,+ ...keys(pair.offset),+ journalLineReference,+ companyId,+ createdBy: userId+ }+ ];+ });+ });+ for (const rows of chunkArray(lineInserts, ROWS_PER_STATEMENT)) {+ await trx.insertInto("journalLine").values(rows).execute();+ }+ }+ const activateAccountingLogger = getLogger(+ "server-functions",+ "activate-accounting"+ );++ export const activateAccountingInput = z.object({+ cutoverDate: z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date"),+ confirmation: z.string()+ });++ export type ActivateAccountingResult = {+ cutoverDate: string;+ /** Null when nothing was open and the trial balance was empty. */+ openingJournalId: string | null;+ /** Legacy documents dated on or after the cutover that got their journal. */+ legacyJournals: LegacyJournalCounts;+ };++ const OPENING_JOURNAL_DESCRIPTION = "Opening Balance";++ export const activateAccountingPermission = {+ update: "accounting"+ } satisfies PermissionRule<z.output<typeof activateAccountingInput>>;++ export async function activateAccounting(+ ctx: ServiceContext,+ raw: z.input<typeof activateAccountingInput>+ ) {+ const { cutoverDate, confirmation } = activateAccountingInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ return db+ .transaction()+ .execute(async (trx): Promise<ActivateAccountingResult> => {+ const refuse = (reason: string): never => {+ activateAccountingLogger.warn("Refused the accounting enable", {+ companyId,+ cutoverDate,+ reason+ });+ throw new InvalidInputError(reason);+ };+ const now = datetime.timestamp();++ // Spec section 5, step 1. Lock the cutover stamp. Every posting reads+ // it FOR SHARE.+ const settings = await trx+ .selectFrom("companySettings")+ .select("accountingCutoverDate")+ .where("id", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!settings) throw new NotFoundError("Company settings not found");+ if (settings.accountingCutoverDate) refuse(ACCOUNTING_ALREADY_SET_UP);++ // Step 1, continued. The typed company name.+ const company = await trx+ .selectFrom("company")+ .select(["name", "companyGroupId"])+ .where("id", "=", companyId)+ .executeTakeFirst();+ if (!company?.companyGroupId) {+ throw new NotFoundError("Company not found");+ }+ const companyGroupId = company.companyGroupId;+ if (confirmation.trim() !== company.name.trim()) {+ refuse("Type the company name to confirm.");+ }++ // Step 1, continued. Every readiness check and Migration Clearing,+ // under the lock.+ // These read the Provisional ledger, so they run before any write.+ const args = { companyId, cutoverDate };+ const readiness = await getActivationReadiness(trx, args);+ const failed = readiness.checks.find((check) => !check.passed);+ if (failed) refuse(failed.detail ?? failed.label);+ const clearing = await getMigrationClearing(trx, args);+ if (!isMigrationClearingZero(clearing.total)) {+ refuse(+ `Migration Clearing totals ${clearing.total}. It must be zero to set up accounting.`+ );+ }+ const migrationClearing =+ clearing.migrationClearingAccount ??+ refuse(missingDefaultMessage("migrationClearingAccount"));+ const defaults = await trx+ .selectFrom("accountDefault")+ .selectAll()+ .where("companyId", "=", companyId)+ .executeTakeFirstOrThrow();++ // Step 1a. The journals of legacy documents dated on or+ // after the cutover, Provisional, so the steps below treat them like+ // every other Provisional journal.+ const legacy = await journalLegacyDocuments(trx, {+ companyId,+ companyGroupId,+ userId,+ cutoverDate,+ defaults+ });++ // Steps 2 and 3. Inventory as of the cutover, and the movements after+ // it.+ await resetAndRecostInventory(trx, {+ companyId,+ userId,+ cutoverDate,+ companyGroupId,+ inventory: await getCutoverInventory(trx, args),+ defaults+ });++ // Step 4. Journals before the cutover leave the ledger for good.+ await trx+ .updateTable("journal")+ .set({ status: "Superseded", updatedBy: userId, updatedAt: now })+ .where("companyId", "=", companyId)+ .where("status", "=", "Provisional")+ .where("postingDate", "<", cutoverDate)+ .execute();++ // Step 5. Recognition and lease interest due before the cutover is in+ // the opening balance; no run posts it. Step 6 (fixed assets) writes+ // nothing: the register already holds the values at the cutover.+ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({+ status: "Posted",+ journalId: null,+ updatedBy: userId,+ updatedAt: now+ })+ .where("companyId", "=", companyId)+ .where("status", "=", "Planned")+ .where("scheduledDate", "<", cutoverDate)+ .execute();++ // Step 7. The opening journal, the day before the cutover. It replaces+ // the Draft trial balance the wizard kept.+ const openingDate = dayBeforeCutover(cutoverDate);++ // The invoices ignored on Migration Clearing were settled in the+ // system that kept the books before the cutover. They are not in the+ // opening journal, so they close as Paid on the day before it, as the+ // Xero and QuickBooks pulls close them; every receivables and payables+ // reader treats that as settled. A sync write: no workflow, webhook or+ // provider push fires for it.+ await markIgnoredInvoicesPaid(trx, {+ companyId,+ items: clearing.ignoredItems,+ datePaid: openingDate,+ userId,+ now+ });++ const draftTrialBalances = trx+ .selectFrom("journal")+ .select("id")+ .where("companyId", "=", companyId)+ .where("status", "=", "Draft")+ .where("sourceType", "=", "Opening Balance");+ await trx+ .deleteFrom("journalLine")+ .where("companyId", "=", companyId)+ .where("journalId", "in", draftTrialBalances)+ .execute();+ await trx+ .deleteFrom("journal")+ .where("companyId", "=", companyId)+ .where("status", "=", "Draft")+ .where("sourceType", "=", "Opening Balance")+ .execute();++ const openingLines = buildOpeningJournalLines(+ clearing.items,+ clearing.trialBalance,+ clearing.controlAccountIds,+ migrationClearing+ );+ // A company with nothing open and no trial balance opens with no+ // journal at all, rather than an empty one.+ let openingJournalId: string | null = null;+ if (openingLines.length > 0) {+ const openingPeriod = await resolveAccountingPeriod(+ trx,+ companyId,+ openingDate,+ "historical"+ );+ const openingJournal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: await getNextSequenceInTransaction(+ trx,+ "journalEntry",+ companyId+ ),+ accountingPeriodId: openingPeriod.id,+ description: OPENING_JOURNAL_DESCRIPTION,+ postingDate: openingDate,+ sourceType: "Opening Balance",+ status: "Posted",+ postedAt: now,+ postedBy: userId,+ companyId,+ createdBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ openingJournalId = openingJournal.id;+ for (const rows of chunkArray(openingLines, ROWS_PER_STATEMENT)) {+ await trx+ .insertInto("journalLine")+ .values(+ rows.map((line) => ({+ journalId: openingJournal.id,+ accountId: line.accountId,+ amount: line.amount,+ description: line.description,+ documentType: line.documentType,+ documentId: line.documentId,+ documentLineReference: line.documentLineReference,+ quantity: line.quantity ?? 0,+ accrual: line.accrual ?? false,+ journalLineReference: nanoid(),+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }+ }++ // Step 8. Periods for the journals that stay. A Superseded journal keeps+ // none.+ const staying = { cutoverDate };+ await assignPeriods(trx, companyId, staying);++ // Step 9. Stand-in lines written while a default was empty.+ await repointStandInLines(trx, companyId, staying, defaults);++ // Step 9, continued. Promote.+ await promoteJournals(trx, companyId, userId, staying);++ // Step 10. Close every period before the cutover, oldest first. Not+ // closeAccountingPeriod: it opens its own transaction.+ const periodsToClose = await trx+ .selectFrom("accountingPeriod")+ .select("id")+ .where("companyId", "=", companyId)+ .where("endDate", "<", cutoverDate)+ .where("closeStatus", "!=", "Closed")+ .orderBy("startDate")+ .execute();+ if (periodsToClose.length > 0) {+ await trx+ .updateTable("accountingPeriod")+ .set({+ closeStatus: "Closed",+ closedAt: now,+ closedBy: userId,+ updatedBy: userId,+ updatedAt: now+ })+ .where("companyId", "=", companyId)+ .where(+ "id",+ "in",+ periodsToClose.map((period) => period.id)+ )+ .execute();+ // The snapshot takes one period; the periods are few (at most+ // three before the current one, plus the opening journal's).+ for (const period of periodsToClose) {+ await sql`SELECT "snapshotAccountingPeriodBalances"(${companyId}, ${period.id}, ${userId})`.execute(+ trx+ );+ }+ }++ // Step 10a. Make the period that holds today Active, as the first+ // posting would. The cutover is never after today, so step 10 never+ // closes it.+ await ensureCurrentAccountingPeriod(companyId, trx);++ // Step 11. The stamp. One-way: a trigger refuses any later change.+ await trx+ .updateTable("companySettings")+ .set({+ accountingCutoverDate: cutoverDate,+ accountingActivatedAt: now,+ accountingActivatedBy: userId+ })+ .where("id", "=", companyId)+ .execute();++ activateAccountingLogger.info("Set up accounting", {+ companyId,+ cutoverDate,+ openingJournalId,+ legacyJournals: legacy.counts+ });+ return { cutoverDate, openingJournalId, legacyJournals: legacy.counts };+ });+ }++ /** Marks the ignored invoices Paid, with the sync flag on. */+ async function markIgnoredInvoicesPaid(+ trx: KyselyTx,+ {+ companyId,+ items,+ datePaid,+ userId,+ now+ }: {+ companyId: string;+ items: OpenItem[];+ datePaid: string;+ userId: string;+ now: string;+ }+ ) {+ const idsOf = (openItemType: OpenItem["openItemType"]) =>+ items.flatMap((item) =>+ item.openItemType === openItemType && item.documentId+ ? [item.documentId]+ : []+ );+ const salesInvoiceIds = idsOf("Receivable");+ const purchaseInvoiceIds = idsOf("Payable");+ if (salesInvoiceIds.length === 0 && purchaseInvoiceIds.length === 0) return;++ const { rows } = await sql<{ previous: string | null }>`+ SELECT current_setting('app.sync_in_progress', true) AS previous+ `.execute(trx);+ const previous = rows[0]?.previous ?? "";+ await sql`SELECT set_config('app.sync_in_progress', 'true', true)`.execute(+ trx+ );+ const set = {+ status: "Paid" as const,+ datePaid,+ updatedBy: userId,+ updatedAt: now+ };+ for (const ids of chunkArray(salesInvoiceIds, ROWS_PER_STATEMENT)) {+ await trx+ .updateTable("salesInvoice")+ .set(set)+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute();+ }+ for (const ids of chunkArray(purchaseInvoiceIds, ROWS_PER_STATEMENT)) {+ await trx+ .updateTable("purchaseInvoice")+ .set(set)+ .where("companyId", "=", companyId)+ .where("id", "in", ids)+ .execute();+ }+ await sql`SELECT set_config('app.sync_in_progress', ${previous}, true)`.execute(+ trx+ );+ }++ const journalLegacyDocumentsLogger = getLogger(+ "server-functions",+ "journal-legacy-documents"+ );++ export const journalLegacyDocumentsInput = z.object({});++ export type JournalLegacyDocumentsResult = {+ /** The legacy documents that got their journal, per family. */+ legacyJournals: LegacyJournalCounts;+ };++ export const journalLegacyDocumentsPermission = {+ update: "accounting"+ } satisfies PermissionRule<z.output<typeof journalLegacyDocumentsInput>>;++ export async function repairLegacyJournals(+ ctx: ServiceContext,+ raw: z.input<typeof journalLegacyDocumentsInput>+ ) {+ journalLegacyDocumentsInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ return db+ .transaction()+ .execute(async (trx): Promise<JournalLegacyDocumentsResult> => {+ // Every posting reads this row FOR SHARE, so no posting writes a+ // journal while this runs.+ const settings = await trx+ .selectFrom("companySettings")+ .innerJoin("company", "company.id", "companySettings.id")+ .select([+ sql<string | null>`"accountingCutoverDate"::text`.as("cutover"),+ "company.companyGroupId"+ ])+ .where("companySettings.id", "=", companyId)+ .forUpdate("companySettings")+ .executeTakeFirst();+ if (!settings?.companyGroupId) {+ journalLegacyDocumentsLogger.warn("Company not found", { companyId });+ throw new NotFoundError("Company not found");+ }+ const cutoverDate = settings.cutover;+ if (!cutoverDate) {+ journalLegacyDocumentsLogger.warn("Refused: accounting is not set up", {+ companyId+ });+ throw new InvalidInputError(ACCOUNTING_NOT_STARTED);+ }+ const defaults = await trx+ .selectFrom("accountDefault")+ .selectAll()+ .where("companyId", "=", companyId)+ .executeTakeFirstOrThrow();++ const legacy = await journalLegacyDocuments(trx, {+ companyId,+ companyGroupId: settings.companyGroupId,+ userId,+ cutoverDate,+ defaults+ });+ if (legacy.journalIds.length > 0) {+ const scope = { journalIds: legacy.journalIds };+ await assignPeriods(trx, companyId, scope);+ await repointStandInLines(trx, companyId, scope, defaults);+ await promoteJournals(trx, companyId, userId, scope);+ // The period that holds today Active, as the enable leaves it.+ await ensureCurrentAccountingPeriod(companyId, trx);+ }++ journalLegacyDocumentsLogger.info(+ "Wrote the journals of legacy documents",+ {+ companyId,+ journals: legacy.journalIds.length,+ legacyJournals: legacy.counts+ }+ );+ return { legacyJournals: legacy.counts };+ });+ }+ export type RunProposalContext = {+ companyId: string;+ /** `YYYY-MM-DD`, the last day of the period being recognized. */+ periodEnd: string;+ userId: string;+ };++ /**+ * A synthesizer inserts the schedule rows that only exist once the period is+ * known — operating-rental accruals are the first. It runs inside the proposal+ * transaction before the due rows are selected, and must be idempotent:+ * proposing the same period twice must not duplicate rows.+ */+ export type RunRowSynthesizer = (+ trx: KyselyTx,+ ctx: RunProposalContext+ ) => Promise<void>;++ /**+ * Accrues earned-but-unbilled operating rent for the calendar month ending+ * `periodEnd` (Dr contract asset / Cr rental income), so the month's rental+ * revenue is right whenever the invoice for it posts. Spec §3, Decision 7.+ *+ * What is accrued: every non-adjustment billing period of a Rental-treated line+ * (`On Rent` or `Returned`) that no POSTED invoice covers yet — status+ * `Pending`, or `Invoiced` onto a Draft/Pending invoice. A drafted-but-unposted+ * invoice has written nothing to the ledger: the daily job drafts an Arrears+ * period on its last day, before the month-end run, so "Pending only" would+ * accrue nothing for exactly the Arrears case the accrual exists for. Advance+ * and Arrears are treated alike — an Advance period whose invoice has not+ * posted by month end has earned the same unbilled rent. Invoice posting+ * (post-sales-invoice) credits the contract asset for the accruals of the+ * period it bills, so an accrual is never recognized twice.+ *+ * How much: the part of the billing period's `amount` earned inside the+ * month, by days, with the window clipped to the line's custody+ * `[deliveredAt, returnedAt]` — no rent is earned before the unit is+ * delivered, and after a return the period was re-cut anyway. Each slice is+ * the difference of two cumulative roundings from the period's first day, so+ * a period's slices across months sum to its amount exactly.+ *+ * Row shape: `periodStart`/`periodEnd` are the accrued slice itself (never the+ * whole billing period or the whole month), so a slice lies inside exactly one+ * billing period — which is how invoice posting finds "the accruals of the+ * period it bills" by overlap — and two months of one billing period never+ * share a key. `scheduledDate` is the run's period end, so the proposal that+ * synthesized a row claims it. Any existing Accrual row of the line that+ * overlaps a slice (Planned or Posted) suppresses it, so proposing the same+ * month twice — or after a delete — inserts nothing new.+ *+ * Amounts are in the agreement currency, which activation holds to the base+ * currency in Phase C (post-rental-agreement).+ */+ /** The company's proposal lock, taken by `synthesizeRentalAccruals`. A+ * transaction-scoped advisory lock, so taking it again is a no-op. */+ export async function lockRecognitionProposals(+ trx: KyselyTx,+ companyId: string+ ): Promise<void> {+ await sql`SELECT pg_advisory_xact_lock(hashtext(${`revenue-recognition-accrual:${companyId}`}))`.execute(+ trx+ );+ }++ export async function synthesizeRentalAccruals(+ trx: KyselyTx,+ ctx: RunProposalContext+ ): Promise<void> {+ const { companyId, periodEnd, userId } = ctx;+ const { year, month } = parseIsoDate(periodEnd);+ const monthStart = formatIsoDate(year, month, 1);++ // Serialize concurrent proposals for one company (the monthly job and a+ // human "New run"): the existence check below is read-then-insert.+ await lockRecognitionProposals(trx, companyId);++ const periods = await trx+ .selectFrom("rentalBillingPeriod as p")+ .innerJoin("rentalAgreementLine as l", (join) =>+ join+ .onRef("l.id", "=", "p.rentalAgreementLineId")+ .onRef("l.companyId", "=", "p.companyId")+ )+ .leftJoin("salesInvoiceLine as sil", (join) =>+ join+ .onRef("sil.id", "=", "p.salesInvoiceLineId")+ .onRef("sil.companyId", "=", "p.companyId")+ )+ .leftJoin("salesInvoice as si", (join) =>+ join+ .onRef("si.id", "=", "sil.invoiceId")+ .onRef("si.companyId", "=", "sil.companyId")+ )+ .select([+ "p.rentalAgreementLineId",+ // DATE decodes to a JS Date through pg; compare and store the text form.+ sql<string>`p."periodStart"::text`.as("periodStart"),+ sql<string>`p."periodEnd"::text`.as("periodEnd"),+ "p.days",+ "p.amount",+ sql<string>`l."deliveredAt"::text`.as("deliveredAt"),+ sql<string | null>`l."returnedAt"::text`.as("returnedAt")+ ])+ .where("p.companyId", "=", companyId)+ .where("p.isAdjustment", "=", false)+ .where("p.periodStart", "<=", periodEnd)+ .where("p.periodEnd", ">=", monthStart)+ .where((eb) =>+ eb.or([+ eb("p.status", "=", "Pending"),+ eb("si.status", "in", ["Draft", "Pending"])+ ])+ )+ .where("l.lessorClassification", "=", "Rental")+ .where("l.status", "in", ["On Rent", "Returned"])+ .where("l.deliveredAt", "is not", null)+ .where("l.deliveredAt", "<=", periodEnd)+ .where((eb) =>+ eb.or([+ eb("l.returnedAt", "is", null),+ eb("l.returnedAt", ">=", monthStart)+ ])+ )+ .orderBy("p.rentalAgreementLineId")+ .orderBy("p.periodStart")+ .execute();+ if (periods.length === 0) return;++ // Every Accrual row touching the month, whatever its status: a slice that+ // overlaps one was already accrued.+ const existing = await trx+ .selectFrom("revenueRecognitionSchedule")+ .select([+ "rentalAgreementLineId",+ sql<string>`"periodStart"::text`.as("periodStart"),+ sql<string>`"periodEnd"::text`.as("periodEnd")+ ])+ .where("companyId", "=", companyId)+ .where("type", "=", "Accrual")+ .where("rentalAgreementLineId", "is not", null)+ .where("periodStart", "<=", periodEnd)+ .where("periodEnd", ">=", monthStart)+ .execute();+ const accruedByLine = new Map<string, { start: string; end: string }[]>();+ for (const row of existing) {+ const lineId = row.rentalAgreementLineId!;+ const spans = accruedByLine.get(lineId) ?? [];+ spans.push({ start: row.periodStart, end: row.periodEnd });+ accruedByLine.set(lineId, spans);+ }++ const maxDate = (...dates: string[]) =>+ dates.reduce((a, b) => (a > b ? a : b));+ const minDate = (...dates: string[]) =>+ dates.reduce((a, b) => (a < b ? a : b));++ const slices: {+ rentalAgreementLineId: string;+ periodStart: string;+ periodEnd: string;+ amount: number;+ }[] = [];+ for (const period of periods) {+ const start = maxDate(period.periodStart, monthStart, period.deliveredAt);+ const end = period.returnedAt+ ? minDate(period.periodEnd, periodEnd, period.returnedAt)+ : minDate(period.periodEnd, periodEnd);+ if (start > end) continue;++ const alreadyAccrued = (+ accruedByLine.get(period.rentalAgreementLineId) ?? []+ ).some((span) => span.start <= end && span.end >= start);+ if (alreadyAccrued) continue;++ // Cumulative rounding from the period's first day: slice = earned through+ // `end` minus earned before `start`, so every slice of one period sums to+ // its amount exactly across months.+ const amount = Number(period.amount);+ const days = Number(period.days);+ const earnedThrough = (dayCount: number) =>+ round((amount * dayCount) / days);+ const daysBeforeStart = daysBetweenInclusive(period.periodStart, start) - 1;+ const daysThroughEnd = daysBetweenInclusive(period.periodStart, end);+ const accrual = round(+ earnedThrough(daysThroughEnd) - earnedThrough(daysBeforeStart)+ );+ if (accrual === 0) continue;++ slices.push({+ rentalAgreementLineId: period.rentalAgreementLineId,+ periodStart: start,+ periodEnd: end,+ amount: accrual+ });+ }+ if (slices.length === 0) return;++ const defaults = await trx+ .selectFrom("accountDefault")+ .select(["contractAssetAccount", "rentalIncomeAccount"])+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!defaults?.contractAssetAccount || !defaults.rentalIncomeAccount) {+ throw new Error(+ "Set the Contract Assets and Rental Income account defaults before recognizing rental revenue"+ );+ }++ await trx+ .insertInto("revenueRecognitionSchedule")+ .values(+ slices.map((slice) => ({+ companyId,+ type: "Accrual" as const,+ status: "Planned" as const,+ rentalAgreementLineId: slice.rentalAgreementLineId,+ periodStart: slice.periodStart,+ periodEnd: slice.periodEnd,+ scheduledDate: periodEnd,+ amount: slice.amount,+ debitAccountId: defaults.contractAssetAccount!,+ creditAccountId: defaults.rentalIncomeAccount!,+ createdBy: userId+ }))+ )+ .execute();+ }++ /**+ * Recognizes contract revenue (plan D5): every Planned `customerContractRevenue`+ * month starting on or before `periodEnd`, of a confirmed contract (Active, or+ * Ended with months still to recognize — a cancellation's catch-up rows), that+ * no schedule row has synthesized yet. Each month is a movement of −amount on+ * its line's position against revenue, at the period end's rate: the part the+ * deferred pool covers becomes a Deferral row (Dr Deferred Revenue / Cr Sales),+ * the rest an Accrual row (Dr Contract Assets / Cr Sales). A negative month (a+ * catch-up) raises the position instead, so its rows come out negative and post+ * with their sides swapped. One Recognition ledger entry per schedule row, so a+ * row deleted with its entry (the FK cascades) leaves the position consistent.+ *+ * Idempotent: a month with a schedule row is skipped. The plan row is marked+ * Recognized when its run posts, not here. A Planned contract schedule row+ * whose plan month has since been replaced (an amendment reconciles Planned+ * months by delete + insert, which nulls the row's `customerContractRevenueId`)+ * is dropped first, with its ledger entry, so the replacement is recognized+ * once.+ */+ export async function synthesizeContractRevenue(+ trx: KyselyTx,+ ctx: RunProposalContext+ ): Promise<void> {+ const { companyId, periodEnd, userId } = ctx;++ // The position lock, shared with invoice posting and credit memos: the+ // movements below are computed from the positions as read.+ await lockContractPositions(trx, companyId);++ const orphans = await trx+ .selectFrom("revenueRecognitionSchedule")+ .select("id")+ .where("companyId", "=", companyId)+ .where("status", "=", "Planned")+ .where("customerContractLineId", "is not", null)+ .where("customerContractRevenueId", "is", null)+ .execute();+ if (orphans.length > 0) {+ const orphanIds = orphans.map((row) => row.id);+ await syncDraftRecognitionRuns(trx, {+ companyId,+ userId,+ deletedScheduleIds: orphanIds+ });+ await trx+ .deleteFrom("revenueRecognitionSchedule")+ .where("companyId", "=", companyId)+ .where("id", "in", orphanIds)+ .execute();+ }++ const due = await trx+ .selectFrom("customerContractRevenue as r")+ .innerJoin("customerContract as c", (join) =>+ join+ .onRef("c.id", "=", "r.customerContractId")+ .onRef("c.companyId", "=", "r.companyId")+ )+ .innerJoin("company as co", "co.id", "r.companyId")+ .select([+ "r.id",+ "r.customerContractId",+ "r.customerContractLineId",+ sql<string>`r."periodStart"::text`.as("periodStart"),+ sql<string>`r."periodEnd"::text`.as("periodEnd"),+ "r.amount",+ // Base currency → 1; raises when the currency has no rate.+ sql<number>`get_exchange_rate(r."companyId", COALESCE(c."currencyCode", co."baseCurrencyCode"), ${periodEnd}::date)`.as(+ "rate"+ )+ ])+ .where("r.companyId", "=", companyId)+ .where("r.status", "=", "Planned")+ .where("r.periodStart", "<=", periodEnd)+ .where("r.amount", "<>", 0)+ .where("c.status", "<>", "Draft")+ .where(({ not, exists, selectFrom }) =>+ not(+ exists(+ selectFrom("revenueRecognitionSchedule as s")+ .select("s.id")+ .whereRef("s.customerContractRevenueId", "=", "r.id")+ .where("s.companyId", "=", companyId)+ )+ )+ )+ .orderBy("r.customerContractLineId")+ .orderBy("r.periodStart")+ .orderBy("r.id")+ .execute();+ if (due.length === 0) return;++ const defaults = await trx+ .selectFrom("accountDefault")+ .select(["deferredRevenueAccount", "contractAssetAccount", "salesAccount"])+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (+ !defaults?.deferredRevenueAccount ||+ !defaults.contractAssetAccount ||+ !defaults.salesAccount+ ) {+ throw new Error(+ "Set the Deferred Revenue, Contract Assets and Sales account defaults before recognizing contract revenue"+ );+ }++ const positions = await loadContractPositions(+ trx,+ companyId,+ due.map((row) => row.customerContractLineId)+ );++ type Planned = {+ schedule: {+ companyId: string;+ type: "Deferral" | "Accrual";+ status: "Planned";+ customerContractLineId: string;+ customerContractRevenueId: string;+ periodStart: string;+ periodEnd: string;+ scheduledDate: string;+ amount: number;+ contractAmount: number;+ debitAccountId: string;+ creditAccountId: string;+ createdBy: string;+ };+ entry: {+ customerContractId: string;+ customerContractLineId: string;+ customerContractRevenueId: string;+ postingDate: string;+ deferredAmount: number;+ deferredBase: number;+ assetAmount: number;+ assetBase: number;+ };+ };+ const planned: Planned[] = [];+ for (const row of due) {+ const position =+ positions.get(row.customerContractLineId) ?? EMPTY_POSITION;+ const movement = applyContractMovement({+ position,+ amount: -Number(row.amount),+ rate: Number(row.rate),+ counterpart: "revenue"+ });+ positions.set(row.customerContractLineId, addMovement(position, movement));+ // A month ending after the run's period end (a mid-month period end)+ // still belongs to this run.+ const scheduledDate = row.periodEnd < periodEnd ? row.periodEnd : periodEnd;+ const common = {+ companyId,+ status: "Planned" as const,+ customerContractLineId: row.customerContractLineId,+ customerContractRevenueId: row.id,+ periodStart: row.periodStart,+ periodEnd: row.periodEnd,+ scheduledDate,+ creditAccountId: defaults.salesAccount,+ createdBy: userId+ };+ const entry = {+ customerContractId: row.customerContractId,+ customerContractLineId: row.customerContractLineId,+ customerContractRevenueId: row.id,+ postingDate: scheduledDate+ };+ if (movement.deferredAmount !== 0 || movement.deferredBase !== 0) {+ planned.push({+ schedule: {+ ...common,+ type: "Deferral",+ amount: round(-movement.deferredBase),+ contractAmount: round(-movement.deferredAmount),+ debitAccountId: defaults.deferredRevenueAccount+ },+ entry: {+ ...entry,+ deferredAmount: movement.deferredAmount,+ deferredBase: movement.deferredBase,+ assetAmount: 0,+ assetBase: 0+ }+ });+ }+ if (movement.assetAmount !== 0 || movement.assetBase !== 0) {+ planned.push({+ schedule: {+ ...common,+ type: "Accrual",+ amount: movement.assetBase,+ contractAmount: movement.assetAmount,+ debitAccountId: defaults.contractAssetAccount+ },+ entry: {+ ...entry,+ deferredAmount: 0,+ deferredBase: 0,+ assetAmount: movement.assetAmount,+ assetBase: movement.assetBase+ }+ });+ }+ }+ if (planned.length === 0) return;++ // RETURNING follows the VALUES order, so each entry pairs with its row.+ const inserted = await trx+ .insertInto("revenueRecognitionSchedule")+ .values(planned.map((p) => p.schedule))+ .returning("id")+ .execute();+ await trx+ .insertInto("customerContractLedgerEntry")+ .values(+ planned.map((p, index) => ({+ ...p.entry,+ entryType: "Recognition" as const,+ revenueRecognitionScheduleId: inserted[index]!.id,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ /** The synthesizers a run of `type` runs before it selects its rows. A lease+ * run synthesizes rental accruals; a revenue recognition run synthesizes+ * contract revenue. Neither ever runs the other's. */+ export function runRowSynthesizers(type: RunType): RunRowSynthesizer[] {+ return type === "Lease"+ ? [synthesizeRentalAccruals]+ : [synthesizeContractRevenue];+ }++ export type RunProposal = { id: string; runId: string; lineCount: number };++ /** Every Planned row of the run type dated on or before `periodEnd` that no+ * run holds yet. */+ export async function selectDueScheduleRows(+ trx: KyselyTx,+ { companyId, periodEnd }: RunProposalContext,+ type: RunType+ ) {+ return trx+ .selectFrom("revenueRecognitionSchedule")+ .select(["id", "amount"])+ .where("companyId", "=", companyId)+ .where(runTypeFilter(type))+ .where("status", "=", "Planned")+ .where("runLineId", "is", null)+ .where("scheduledDate", "<=", periodEnd)+ .orderBy("scheduledDate")+ .orderBy("id")+ .execute();+ }++ /** Claims `due` into the run: one line per row, each copying the row's+ * amount, and the row stamped with its line. */+ export async function claimScheduleRows(+ trx: KyselyTx,+ runId: string,+ due: { id: string; amount: number }[],+ { companyId, userId }: RunProposalContext+ ): Promise<void> {+ if (due.length === 0) return;++ await trx+ .insertInto("revenueRecognitionRunLine")+ .values(+ due.map((row) => ({+ runId,+ scheduleId: row.id,+ amount: row.amount,+ companyId,+ createdBy: userId+ }))+ )+ .execute();++ // Stamp each claimed row with its line in one statement (the line ↔+ // schedule pair is unique per company, so the join is one-to-one).+ await trx+ .updateTable("revenueRecognitionSchedule as s")+ .from("revenueRecognitionRunLine as l")+ .set({ runLineId: sql`l.id`, updatedBy: userId })+ .whereRef("l.scheduleId", "=", "s.id")+ .where("l.runId", "=", runId)+ .where("l.companyId", "=", companyId)+ .where("s.companyId", "=", companyId)+ .execute();+ }++ /**+ * Claims every Planned schedule row dated on or before `periodEnd` that no run+ * holds yet, into ONE Draft run. Returns null (and writes nothing) when nothing+ * is due, so a second proposal for the same period is a no-op rather than an+ * empty run.+ */+ async function createRevenueRecognitionRunProposal(+ db: Kysely<KyselyDatabase>,+ args: RunProposalContext,+ type: RunType+ ): Promise<RunProposal | null> {+ const { companyId, periodEnd, userId } = args;++ return db.transaction().execute(async (trx) => {+ for (const synthesize of runRowSynthesizers(type)) {+ await synthesize(trx, args);+ }++ const due = await selectDueScheduleRows(trx, args, type);+ if (due.length === 0) return null;++ // One Draft per period and run type (the partial unique index+ // revenueRecognitionRun_one_draft_per_period is the backstop): a period+ // that already has a Draft is recalculated, not proposed again.+ const draft = await trx+ .selectFrom("revenueRecognitionRun")+ .select("runId")+ .where("companyId", "=", companyId)+ .where("type", "=", type)+ .where("periodEnd", "=", periodEnd)+ .where("status", "=", "Draft")+ .executeTakeFirst();+ if (draft) {+ throw new InvalidInputError(+ `${draft.runId} is already a draft for this period. Recalculate it instead.`+ );+ }++ const runId = await getNextSequenceInTransaction(+ trx,+ RUN_SEQUENCE[type],+ companyId+ );+ const run = await trx+ .insertInto("revenueRecognitionRun")+ .values({+ runId,+ type,+ periodEnd,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ await claimScheduleRows(trx, run.id, due, args);++ return { id: run.id, runId, lineCount: due.length };+ });+ }++ /** Whether `date` is a real `YYYY-MM-DD` that is the last day of its month. */+ function isMonthEnd(date: string): boolean {+ try {+ return endOfMonth(parseDate(date)).toString() === date;+ } catch {+ // parseDate throws on a day or month out of range ("2026-02-30").+ return false;+ }+ }++ export const proposeRevenueRecognitionRunInput = z.object({+ /** `YYYY-MM-DD`, the last day of the period being recognized. A mid-month+ * date would accrue rent only up to it and leave the rest of the month to+ * no run. */+ periodEnd: z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/)+ .refine(isMonthEnd, {+ message: "periodEnd must be the last day of a month"+ }),+ /** Which run: revenue recognition (service lines, contracts) or lease+ * (rental agreements, lessee leases). */+ type: z.enum(["Revenue Recognition", "Lease"]).default("Revenue Recognition")+ });++ export const proposeRevenueRecognitionRunPermission = {+ create: "accounting"+ } satisfies PermissionRule<z.output<typeof proposeRevenueRecognitionRunInput>>;++ /** Proposes ONE Draft run for the period, or null when nothing is due (see+ * `createRevenueRecognitionRunProposal`). */+ export async function proposeRevenueRecognitionRun(+ ctx: ServiceContext,+ raw: z.input<typeof proposeRevenueRecognitionRunInput>+ ) {+ const { periodEnd, type } = proposeRevenueRecognitionRunInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ await assertAccountingCutover(db, companyId);+ // A run may cover the current month or an earlier one, never a month that+ // has not started (the ERP's isFutureRunPeriod; this package cannot import+ // it). Guards the monthly job as well as the routes.+ const today = datetime.today(await getCompanyTimeZone(db, companyId));+ if (periodEnd > endOfMonth(today).toString()) {+ throw new InvalidInputError(+ `${formatDate(periodEnd, { month: "long", year: "numeric" })} has not started yet. A run can cover the current month or an earlier one.`+ );+ }+ return createRevenueRecognitionRunProposal(+ db,+ { companyId, periodEnd, userId },+ type+ );+ }+ export const previewRevenueRecognitionRunInput = z.object({+ /** `YYYY-MM-DD`, the last day of the period. */+ periodEnd: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ /** Which run to preview. */+ type: z.enum(["Revenue Recognition", "Lease"]).default("Revenue Recognition")+ });++ export type RunRowsPreview = { count: number; amount: number };++ /** Thrown at the end of the preview transaction so it never commits. */+ class PreviewRollback extends Error {+ constructor(readonly preview: RunRowsPreview) {+ super("preview rollback");+ }+ }++ export const previewRevenueRecognitionRunPermission = {+ view: "accounting"+ } satisfies PermissionRule<z.output<typeof previewRevenueRecognitionRunInput>>;++ export async function previewRevenueRecognitionRun(+ ctx: ServiceContext,+ raw: z.input<typeof previewRevenueRecognitionRunInput>+ ) {+ const { periodEnd, type } = previewRevenueRecognitionRunInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ try {+ await db.transaction().execute(async (trx) => {+ const ctx = { companyId, periodEnd, userId };+ for (const synthesize of runRowSynthesizers(type)) {+ await synthesize(trx, ctx);+ }+ const due = await selectDueScheduleRows(trx, ctx, type);+ throw new PreviewRollback({+ count: due.length,+ amount: round(due.reduce((sum, row) => sum + Number(row.amount), 0))+ });+ });+ } catch (error) {+ if (error instanceof PreviewRollback) return error.preview;+ throw error;+ }+ throw new Error("Revenue recognition preview did not roll back");+ }+ export const recalculateRevenueRecognitionRunInput = z.object({+ runId: z.string().min(1)+ });++ export type RunRecalculation = {+ runId: string;+ lineCount: number;+ /** False when the run already held exactly what is due. */+ changed: boolean;+ /** Nothing is due any more, so the run was deleted. */+ deleted: boolean;+ };++ export const recalculateRevenueRecognitionRunPermission = {+ update: "accounting"+ } satisfies PermissionRule<+ z.output<typeof recalculateRevenueRecognitionRunInput>+ >;++ export async function recalculateRevenueRecognitionRun(+ ctx: ServiceContext,+ raw: z.input<typeof recalculateRevenueRecognitionRunInput>+ ) {+ const { runId } = recalculateRevenueRecognitionRunInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ await assertAccountingCutover(db, companyId);+ return db.transaction().execute(async (trx) => {+ const run = await trx+ .selectFrom("revenueRecognitionRun")+ .select(["id", "runId", "status", "periodEnd", "type"])+ .where("id", "=", runId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!run) throw new NotFoundError("Revenue recognition run not found");+ if (run.status !== "Draft") {+ throw new InvalidInputError(+ `Revenue recognition run ${run.runId} is ${run.status}; only a draft can be recalculated`+ );+ }++ const ctx: RunProposalContext = {+ companyId,+ periodEnd: String(run.periodEnd),+ userId+ };++ // The synthesizers' locks, in their order, before anything else: a+ // concurrent proposal cannot claim a row between the release and the+ // claim below, and an invoice void (which takes the position lock and+ // then deletes held run lines) cannot deadlock with the release.+ await lockRecognitionProposals(trx, companyId);+ await lockContractPositions(trx, companyId);++ // Release the run's own rows BEFORE the synthesizers. A synthesizer+ // that drops a held row (a contract month an amendment replaced) keeps+ // Draft runs in step and deletes a run it empties — which, with the run+ // still holding only that row, deleted this run and failed the claim+ // below on its foreign key.+ const before = await trx+ .selectFrom("revenueRecognitionRunLine")+ .select(["id", "scheduleId", "amount"])+ .where("runId", "=", run.id)+ .where("companyId", "=", companyId)+ .execute();+ if (before.length > 0) {+ await trx+ .updateTable("revenueRecognitionSchedule")+ .set({ runLineId: null, updatedBy: userId })+ .where("companyId", "=", companyId)+ .where(+ "runLineId",+ "in",+ before.map((line) => line.id)+ )+ .execute();+ await trx+ .deleteFrom("revenueRecognitionRunLine")+ .where("runId", "=", run.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ for (const synthesize of runRowSynthesizers(run.type)) {+ await synthesize(trx, ctx);+ }++ const due = await selectDueScheduleRows(trx, ctx, run.type);+ const held = new Map(+ before.map((line) => [line.scheduleId, Number(line.amount)])+ );+ const changed =+ due.length !== before.length ||+ due.some(+ (row) =>+ !held.has(row.id) || !equals(held.get(row.id)!, Number(row.amount))+ );++ if (due.length === 0) {+ await trx+ .deleteFrom("revenueRecognitionRun")+ .where("id", "=", run.id)+ .where("companyId", "=", companyId)+ .execute();+ return { runId: run.runId, lineCount: 0, changed, deleted: true };+ }++ await claimScheduleRows(trx, run.id, due, ctx);+ await trx+ .updateTable("revenueRecognitionRun")+ .set({ updatedBy: userId, updatedAt: datetime.timestamp() })+ .where("id", "=", run.id)+ .where("companyId", "=", companyId)+ .execute();++ return {+ runId: run.runId,+ lineCount: due.length,+ changed,+ deleted: false+ };+ });+ }diff --cc apps/erp/app/modules/documents/documents.service.tsindex 1ae8388577,ceced41bbe..99410e5cb5--- a/apps/erp/app/modules/documents/documents.service.ts+++ b/apps/erp/app/modules/documents/documents.service.ts@@@ -2,16 -2,22 +2,22 @@@// 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 { ServiceContext } from "@carbon/api/service-fn.server";import type { Database } from "@carbon/database";- import { imageTransformErrorMessage, storage } from "@carbon/files";+ import {+ getDocumentType,+ imageTransformErrorMessage,+ isUnsafeStoragePath,+ storage+ } from "@carbon/files";import { isHeic } from "@carbon/files/media";import { trigger } from "@carbon/jobs";+ import { datetime, searchFilter } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";- import { getDocumentType } from "../shared/shared.service";import type {documentLabelsValidator,documentSourceTypes,@@@ -63,20 -43,6 +43,19 @@@ export async function getDocumentreturn client.from("documents").select("*").eq("id", documentId).single();}+export const DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "favorite", ascending: false }]+};++// The "Recent" view: the last activity first. It is a default sort, so the+// cursor follows it and a sort the user picks replaces it.+export const RECENT_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "lastActivityAt", ascending: false },+ ...DOCUMENTS_PAGING.defaultSorts+ ]+};+- /** @mcp read */export async function getDocuments(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsxindex c28fa04c5a,c91be39ff8..ab333a0fe1--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx@@@ -48,14 -48,8 +48,14 @@@ import { DateTime, EmployeeAvatar, Hypeimport DocumentIcon from "~/components/DocumentIcon";import { Enumerable } from "~/components/Enumerable";import { Confirm, ConfirmDelete } from "~/components/Modals";+import {+ applyRowEdits,+ type RowEdits,+ tick+} from "~/components/Table/rowEdits";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";import { usePermissions, useUrlParams } from "~/hooks";- import { documentTypes } from "~/modules/shared";+ import { documentTypes } from "~/modules/shared/shared.models";import { usePeople } from "~/stores";import { path } from "~/utils/path";import { documentSourceTypes } from "../../documents.models";diff --cc apps/erp/app/modules/inventory/inventory.service.tsindex 1e2fef8b62,30c8caa062..460888b33f--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@@ -2,29 -2,191 +2,192 @@@// 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 {+ InvalidInputError,+ NotFoundError,+ ServerFnError+ } from "@carbon/api/errors";+ import type { PermissionRule } from "@carbon/api/permissions";+ import {+ type IssueResult,+ issueInput,+ postInventoryAdjustmentInput,+ postPickingInput+ } from "@carbon/api/postings";+ import {+ type CarbonError,+ ERROR_STATUS,+ type ErrorCategory,+ type ServiceContext+ } from "@carbon/api/service-fn.server";import type { Database, Json } from "@carbon/database";- import { fetchAllFromTable } from "@carbon/database";- import type { Kysely, KyselyDatabase } from "@carbon/database/client";import {+ fetchAllFromTable,+ getCompanyTimeZone,+ journalReference+ } from "@carbon/database";+ import type {+ KyselyDatabase as DB,+ Kysely,+ KyselyDatabase,+ KyselyTx+ } from "@carbon/database/client";+ import {+ type AutomaticJournalStatus,+ assertPostingStatusUnchanged,+ journalPostingStatus,+ resolveDefaultAccount+ } from "@carbon/database/journal-posting-status";+ import { toJson } from "@carbon/database/json";+ import {+ allocateAcrossBudgets,+ getOperationLinesideBin,+ getPickedBudgets,type LinesideClaim,- linesideCredit+ linesideCredit,+ orderOldFirst,+ recordSharedTakes,+ type SharedTakes,+ splitTakeByBin} from "@carbon/database/picked-consumption";- import { expandSerialTrackedLines } from "@carbon/database/stock-transfer";+ import {+ idsWithLiveStockHistory,+ releaseReceiptSerialEntities,+ voidedReceiptIds+ } from "@carbon/database/receipt-serials";+ import {+ contains,+ deleteRows,+ inOrder,+ insertRows,+ lt,+ many,+ maybeSingle,+ neq,+ notNull,+ rpcRows,+ single,+ type Tables,+ updateRows+ } from "@carbon/database/rows";+ import {+ resolveFeatureSamplingPlan,+ resolveSamplingPlan,+ type SamplingStandard+ } from "@carbon/database/sampling";+ import * as sequence from "@carbon/database/sequence";+ import {+ expandSerialTrackedLines,+ kanbanReplenishmentNote,+ levelReplenishmentQuantity,+ type StockTransferLineDraft+ } from "@carbon/database/stock-transfer";import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";+ import { evaluateLinesForSurface } from "@carbon/ee/rules.server";import { storage } from "@carbon/files";+ import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";- import { type ServerFnInput, serverFns } from "@carbon/server-functions";+ import { getCachedPrinterConfig } from "@carbon/printing/printing.server";import type { TrackedEntityAttributes } from "@carbon/utils";- import { async, datetime, getErrorMessage } from "@carbon/utils";+ import {+ assertEntityCoversPick,+ async,+ buildBatchMergeRecords,+ buildBatchSplitRecords,+ buildMergeRecords,+ credit,+ datetime,+ debit,+ EPSILON,+ equals,+ getErrorMessage,+ indexByMapped,+ isFullDraw,+ PickGuardError,+ pluckUnique,+ resolvePick,+ resolveReturnUnitCost,+ resolveTrackedEntityBin,+ round,+ searchFilter,+ settleQuantity,+ splitPickAcrossMembers,+ statusAfterQuantityChange,+ type Violation+ } from "@carbon/utils";+ import type { CalendarDate } from "@internationalized/date";+ import { parseDate } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+ import type { Insertable, Transaction } from "kysely";+ import { type Selectable, sql } from "kysely";import { nanoid } from "nanoid";- import type { z } from "zod";- import { getNextSequence } from "~/modules/settings/settings.service";+ import { z } from "zod";+ import { upsertDocument } from "~/modules/documents/documents.service";+ import {+ futureDeliveryError,+ futureReturnError,+ insertUnitActivity,+ lockAgreement,+ type RentalUnitReturn,+ receiptReturnError,+ rentalShipmentVoidBlocker,+ returnRentalUnit,+ unitLabel,+ unitReturnValidator+ } from "~/modules/sales/sales.service";+ import * as settingsService from "~/modules/settings/settings.service";+ import {+ assertCompanyRecords,+ assertPostable,+ attributesContain,+ bookAdjustment,+ buildCostLedgerRow,+ buildJournalLineDimensions,+ buildOffsetLines,+ calculateCOGS,+ createAdjustmentJournal,+ documentJournalLines,+ type ExpiredEntityPolicy,+ type ExpiryOverride,+ expiredEntities,+ expiryVerdict,+ FixedAssetWrites,+ getAccountingPeriodForDate,+ getCurrentAccountingPeriod,+ getDefaultPostingGroup,+ getExpiredEntityPolicy,+ getOffsetAccount,+ getStorageUnitWithHighestQuantity,+ getTrackedEntityBins,+ getTrackedEntityOnHandInBin,+ INVENTORY_VOID_BEFORE_CUTOVER_ERROR,+ invokePosting,+ type JournalLineDimensionValues,+ journalLineDimensionRows,+ leavingTrackedEntityIds,+ refuseVoidBeforeCutover,+ resolveAccountingPeriod,+ resolveInventoryAccount,+ STOCK_CORRECTION_BEFORE_CUTOVER_ERROR,+ serialUnitCost,+ type UnitCostChild,+ updatePickMethodDefaultStorageUnitIfNeeded,+ valueMovement+ } from "~/modules/shared/shared.service";+ import {+ assertBinCovers,+ binCoverProblem,+ getStrictBackflushSettings,+ isStrictBackflush,+ lockStrictBins,+ resolvePullFromStorageUnits,+ strictBackflushRefusal+ } from "~/modules/shared/strict-backflush";import type { StorageItem } from "~/types";-import type { Filter, GenericQueryFilters } from "~/utils/query";+import type { Filter, GenericQueryFilters, Paging } from "~/utils/query";import {LIST_COUNT,+ listCount,setGenericQueryFilters,setSearchFilter} from "~/utils/query";@@@ -338,11 -445,6 +446,10 @@@ export async function getBatchPropertie.order("sortOrder");}+export const INVENTORY_ITEMS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getInventoryItems(client: SupabaseClient<Database>,locationId: string,@@@ -537,11 -639,6 +643,10 @@@ export async function createInventoryRe}}+export const KANBANS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getKanbans(client: SupabaseClient<Database>,locationId: string,@@@ -649,11 -742,6 +748,10 @@@ export async function getStockTransferT.eq("companyId", companyId);}+export const STOCK_TRANSFERS_PAGING: Paging = {+ defaultSorts: [{ column: "stockTransferId", ascending: false }]+};+- /** @mcp read */export async function getStockTransfers(client: SupabaseClient<Database>,companyId: string,@@@ -738,11 -823,6 +835,10 @@@ export async function getDefaultStoragereturn storageUnitWithHighestQuantity?.storageUnitId ?? null;}+export const RECEIPTS_PAGING: Paging = {+ defaultSorts: [{ column: "receiptId", ascending: false }]+};+- /** @mcp read */export async function getReceipts(client: SupabaseClient<Database>,companyId: string,@@@ -1167,11 -1391,6 +1405,10 @@@ export async function getEffectiveWorkC// Roots only (depth = 1). Honors search/filter/pagination so the table can// paginate top-level storage units while children load lazily on demand.+export const STORAGE_UNIT_ROOTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getStorageUnitRoots(client: SupabaseClient<Database>,companyId: string,@@@ -1329,14 -1532,6 +1562,13 @@@ export async function searchStorageUnit};}+export const STOCK_MOVEMENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "entryNumber", ascending: false }+ ]+};+- /** @mcp read */export async function getStockMovements(client: SupabaseClient<Database>,companyId: string,@@@ -1365,11 -1568,6 +1602,10 @@@return query;}+export const SHIPMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "shipmentId", ascending: false }]+};+- /** @mcp read */export async function getShipments(client: SupabaseClient<Database>,companyId: string,@@@ -1580,11 -1758,6 +1794,10 @@@ export async function getShippingMethod.single();}+export const SHIPPING_METHODS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getShippingMethods(client: SupabaseClient<Database>,companyId: string,@@@ -1686,19 -1832,18 +1870,22 @@@ export async function mergeTrackedEntituserId: string;}) {- return serverFns- .as({ client, db, companyId: args.companyId, userId: args.userId })- .invoke("issue", {+ return invokePosting(+ { client, db, companyId: args.companyId, userId: args.userId },+ "issue",+ {type: "mergeTrackedEntities",...args- });+ },+ issueMaterial,+ { as: issueMaterialPermission }+ );}+export const TRACKED_ENTITIES_PAGING: Paging = {+ defaultSorts: [{ column: "sourceDocumentReadableId", ascending: true }]+};+- /** @mcp read */export async function getTrackedEntities(client: SupabaseClient<Database>,companyId: string,@@@ -1857,11 -2003,6 +2043,10 @@@ export async function getTrackedEntitie);}+export const WAREHOUSE_TRANSFERS_PAGING: Paging = {+ defaultSorts: [{ column: "transferId", ascending: false }]+};+- /** @mcp read */export async function getWarehouseTransfers(client: SupabaseClient<Database>,companyId: string,@@@ -1880,12 -2021,12 +2065,10 @@@.eq("companyId", companyId);if (args.search) {- query = query.or(- `transferId.ilike.%${args.search}%,reference.ilike.%${args.search}%`- );+ query = query.or(searchFilter(["transferId", "reference"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "transferId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, WAREHOUSE_TRANSFERS_PAGING);return query;}@@@ -2118,11 -2227,6 +2269,10 @@@ export async function getStockMovementE// Inventory Count / Cycle Count// ===========================================================================+export const INVENTORY_COUNTS_PAGING: Paging = {+ defaultSorts: [{ column: "inventoryCountId", ascending: false }]+};+- /** @mcp read */export async function getInventoryCounts(client: SupabaseClient<Database>,companyId: string,@@@ -2155,14 -2260,6 +2304,13 @@@ export async function getInventoryCount.single();}+export const INVENTORY_COUNT_LINES_PAGING: Paging = {+ defaultSorts: [+ { column: "itemReadableIdWithRevision", ascending: true },+ { column: "id", ascending: true }+ ]+};+- /** @mcp read */export async function getInventoryCountLines(client: SupabaseClient<Database>,inventoryCountId: string,@@@ -3020,31 -3078,23 +3126,27 @@@ export async function deleteStorageTypeid: string,companyId: string) {- const { data: units, error: fetchError } = await client- .from("storageUnit")- .select("id, storageTypeIds")- .eq("companyId", companyId)- .contains("storageTypeIds", [id]);-- if (fetchError) return { error: fetchError };-- for (const unit of units ?? []) {- const next = (unit.storageTypeIds ?? []).filter((x) => x !== id);- const { error: updateError } = await client- .from("storageUnit")- .update({ storageTypeIds: next })- .eq("id", unit.id);- if (updateError) return { error: updateError };- }-- return client.from("storageType").delete().eq("id", id);+ return db.transaction().execute(async (trx) => {+ await trx+ .updateTable("storageUnit")+ .set({+ storageTypeIds: sql<string[]>`array_remove("storageTypeIds", ${id})`+ })+ .where("companyId", "=", companyId)+ .where(sql<boolean>`"storageTypeIds" @> ARRAY[${id}]::text[]`)+ .execute();+ return trx+ .deleteFrom("storageType")+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ });}+export const STORAGE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getStorageTypes(client: SupabaseClient<Database>,companyId: string,@@@ -3157,11 -3204,6 +3254,10 @@@ export async function getTrackedEntityE// Picking List CRUD// ----------------------------------------------------------------------------+export const PICKING_LISTS_PAGING: Paging = {+ defaultSorts: [{ column: "pickingListId", ascending: false }]+};+- /** @mcp read */export async function getPickingLists(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsxindex 5f2301eafc,4e7fd41bc7..ee85170757--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx@@@ -25,9 -25,9 +25,9 @@@ importimport { useNavigate } from "react-router";import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";- import type { InventoryCount } from "~/modules/inventory";- import { InventoryCountStatus } from "~/modules/inventory";+ import type { InventoryCount } from "~/modules/inventory/types";+ import { InventoryCountStatus } from "~/modules/inventory/ui";import { usePeople } from "~/stores";import { path } from "~/utils/path";diff --cc apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsxindex c0e7ac258a,715caecc44..afe5e68f72--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx@@@ -36,14 -36,14 +36,14 @@@ importimport { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";import { NewAction } from "~/components/New";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";- import type { Receipt } from "~/modules/inventory";import {- ReceiptStatus,receiptSourceDocumentType,receiptStatusType- } from "~/modules/inventory";+ } from "~/modules/inventory/inventory.models";+ import type { Receipt } from "~/modules/inventory/types";+ import { ReceiptStatus } from "~/modules/inventory/ui";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";diff --cc apps/erp/app/modules/invoicing/invoicing.service.tsindex 20c8fa9f96,5a46f499bf..e2614147f1--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@@ -45,9 -173,46 +173,46 @@@ importgetSupplierPayment,getSupplierShipping,insertSupplierInteraction- } from "~/modules/purchasing";+ } from "~/modules/purchasing/purchasing.service";+ import {+ getCustomer,+ getCustomerContact,+ getCustomerLocation,+ getCustomerTax,+ recordSalesRuleOutcome,+ updateCustomerContact+ } from "~/modules/sales/sales.service";+ import { getCompanySettings } from "~/modules/settings/settings.service";+ import {+ assertNoMigrationClearing,+ assertPostable,+ calculateCOGS,+ documentJournalLines,+ FixedAssetWrites,+ getCompanyTimeZone as getCachedCompanyTimeZone,+ getCurrentAccountingPeriod,+ getDefaultPostingGroup,+ type JournalLineDimensionValues,+ journalLineDimensionRows,+ loadContractPositions,+ loadPartyDimensions,+ lockContractPositions,+ PURCHASE_INVOICE_VOID_BEFORE_CUTOVER_ERROR,+ partyDimensionValues,+ partyDimensionValuesFrom,+ refuseUnlessOwned,+ refuseVoidBeforeCutover,+ resolveInventoryAccount,+ SALES_INVOICE_VOID_BEFORE_CUTOVER_ERROR,+ salesInvoiceStandIns,+ samePosition,+ signedCreditAmount,+ syncDraftRecognitionRuns+ } from "~/modules/shared/shared.service";+ import { getUser } from "~/modules/users/users.service";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";+ import { stripSpecialCharacters } from "~/utils/string";import { sanitize } from "~/utils/supabase";import { getExchangeRate } from "../accounting/accounting.service";import { getEmployeeJob } from "../people/people.service";@@@ -362,11 -546,6 +546,10 @@@ export async function getPurchaseInvoic.single();}+export const PURCHASE_INVOICES_PAGING: Paging = {+ defaultSorts: [{ column: "invoiceId", ascending: false }]+};+- /** @mcp read */export async function getPurchaseInvoices(client: SupabaseClient<Database>,companyId: string,@@@ -456,11 -630,6 +634,10 @@@ export async function getSalesInvoiceCu.single();}+export const SALES_INVOICES_PAGING: Paging = {+ defaultSorts: [{ column: "invoiceId", ascending: false }]+};+- /** @mcp read */export async function getSalesInvoices(client: SupabaseClient<Database>,companyId: string,@@@ -1367,14 -1522,6 +1530,13 @@@ export async function getPaymentreturn query.single();}+// Newest first by the sequential paymentId (PAY-yyyy-mm-NNNNNN), matching the+// sales/purchase invoice lists (invoiceId desc), so the most recently created+// payment is at the top (paymentDate ties otherwise).+export const PAYMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "paymentId", ascending: false }]+};+- /** @mcp read */export async function getPayments(client: SupabaseClient<Database>,companyId: string,@@@ -1434,13 -1585,6 +1595,12 @@@ export async function getCharge.single();}+// Newest first by the sequential chargeId (CHG-yyyy-mm-NNNNNN), mirroring the+// payments' paymentId desc default.+export const CHARGES_PAGING: Paging = {+ defaultSorts: [{ column: "chargeId", ascending: false }]+};+- /** @mcp read */export async function getCharges(client: SupabaseClient<Database>,companyId: string,@@@ -1487,13 -1632,6 +1644,12 @@@ export async function getReimbursement.single();}+// Newest first by the sequential reimbursementId (REIMB-yyyy-mm-NNNNNN),+// mirroring the charges' chargeId desc default.+export const REIMBURSEMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "reimbursementId", ascending: false }]+};+- /** @mcp read */export async function getReimbursements(client: SupabaseClient<Database>,companyId: string,@@@ -3908,14 -4031,6 +4045,13 @@@ export async function getMemoreturn query.single();}+// Newest first by creation date (not the readable memoId — Credit and Debit+// share the table but use separate CR-/DR- sequences, so a memoId sort+// interleaves them oddly).+export const MEMOS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getMemos(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsxindex 155898d3d1,2772897807..4d266be24d--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx@@@ -36,13 -36,11 +36,11 @@@ import} from "~/components";import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";-import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useCurrencyFormatter, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";- import type { PurchaseInvoiceListItem } from "~/modules/invoicing";- import {- PurchaseInvoicingStatus,- purchaseInvoiceStatusType- } from "~/modules/invoicing";+ import { purchaseInvoiceStatusType } from "~/modules/invoicing/invoicing.models";+ import type { PurchaseInvoiceListItem } from "~/modules/invoicing/types";+ import { PurchaseInvoicingStatus } from "~/modules/invoicing/ui";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";diff --cc apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsxindex f691850977,4f267eaae9..61292df720--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx@@@ -39,10 -39,10 +39,10 @@@ import} from "~/components";import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";-import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useCurrencyFormatter, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";- import type { SalesInvoiceListItem } from "~/modules/invoicing";- import { salesInvoiceStatusType } from "~/modules/invoicing";+ import { salesInvoiceStatusType } from "~/modules/invoicing/invoicing.models";+ import type { SalesInvoiceListItem } from "~/modules/invoicing/types";import { useCustomers, usePeople } from "~/stores";import { path } from "~/utils/path";import SalesInvoiceStatus from "./SalesInvoiceStatus";diff --cc apps/erp/app/modules/items/items.service.tsindex 75319006b3,a0d82e99b7..28115f0806--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@@ -14,21 -24,38 +24,39 @@@ import typeKyselyDatabase,KyselyTx} from "@carbon/database/client";+ import { insertRows, many, maybeSingle } from "@carbon/database/rows";+ import { hasPendingApproval } from "@carbon/ee/approvals.server";import {- buildSupplierPriceMap,- type SupplierPriceBreak,- supplierPartCurrency- } from "@carbon/database/supplier-part-price";- import { storage } from "@carbon/files";+ isUnsafeStoragePath,+ storage,+ TEMP_STAGING_BUCKET+ } from "@carbon/files";+ import { supportedModelTypes } from "@carbon/files/cad";+ import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";- import { serverFns } from "@carbon/server-functions";- import { datetime, isUniqueViolation, withPathIds } from "@carbon/utils";+ import { oncePerRead } from "@carbon/logger/middleware.server";+ import { NotificationEvent } from "@carbon/notifications";+ import {++ chunkArray,+ datetime,+ getReadableIdWithRevision,+ isUniqueViolation,+ pick,+ pluckUnique,+ searchFilter,+ textToTiptap,+ withPathIds+ } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";- import type { z } from "zod";+ import type { Transaction } from "kysely";+ import { nanoid } from "nanoid";+ import { data } from "react-router";+ import { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";+ import { getCompanySettings } from "~/modules/settings/settings.service";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import {- LIST_COUNT,+ listCount,setGenericQueryFilters,setSearchFilter} from "~/utils/query";@@@ -64,8 -94,8 +95,10 @@@ importtype configurationRuleValidator,type consumableValidator,type customerPartValidator,++ deriveItemMethodUpdate,EACH_UNIT_OF_MEASURE_CODE,type getMethodValidator,++ type ItemBulkUpdateField,ItemTrackingType,isAllowedChangeNoticeTransition,type itemCostValidator,@@@ -885,11 -858,6 +861,10 @@@ export async function getConsumable.single();}+export const CONSUMABLES_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getConsumables(client: SupabaseClient<Database>,companyId: string,@@@ -1177,11 -1120,6 +1125,10 @@@ export async function getItemPostingGroreturn client.from("itemPostingGroup").select("*").eq("id", id).single();}+export const ITEM_POSTING_GROUPS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getItemPostingGroups(client: SupabaseClient<Database>,companyId: string,@@@ -1583,11 -1420,6 +1427,10 @@@ export async function getMaterial.single();}+export const MATERIALS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getMaterials(client: SupabaseClient<Database>,companyId: string,@@@ -1650,14 -1465,6 +1474,13 @@@ export async function getMaterialDimensreturn client.from("materialDimension").select("*").eq("id", id).single();}+export const MATERIAL_DIMENSIONS_PAGING: Paging = {+ defaultSorts: [+ { column: "formName", ascending: true },+ { column: "name", ascending: true }+ ]+};+- /** @mcp read */export async function getMaterialDimensions(client: SupabaseClient<Database>,companyId: string,@@@ -1707,14 -1515,6 +1528,13 @@@ export async function getMaterialFinishreturn client.from("materialFinish").select("*").eq("id", id).single();}+export const MATERIAL_FINISHES_PAGING: Paging = {+ defaultSorts: [+ { column: "substanceName", ascending: true },+ { column: "name", ascending: true }+ ]+};+- /** @mcp read */export async function getMaterialFinishes(client: SupabaseClient<Database>,companyId: string,@@@ -1761,11 -1562,6 +1579,10 @@@ export async function getMaterialFormreturn client.from("materialForm").select("*").eq("id", id).single();}+export const MATERIAL_FORMS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getMaterialForms(client: SupabaseClient<Database>,companyId: string,@@@ -1801,14 -1598,6 +1617,13 @@@ export async function getMaterialFormsL.order("name");}+export const MATERIAL_GRADES_PAGING: Paging = {+ defaultSorts: [+ { column: "substanceName", ascending: true },+ { column: "name", ascending: true }+ ]+};+- /** @mcp read */export async function getMaterialGrades(client: SupabaseClient<Database>,companyId: string,@@@ -1863,11 -1652,6 +1675,10 @@@ export async function getMaterialSubstareturn client.from("materialSubstance").select("*").eq("id", id).single();}+export const MATERIAL_SUBSTANCES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getMaterialSubstances(client: SupabaseClient<Database>,companyId: string,@@@ -1903,21 -1688,6 +1713,19 @@@ export async function getMaterialSubsta.order("name");}- /** @mcp read */+export async function getMethodMaterial(+ client: SupabaseClient<Database>,+ materialId: string+) {+ return client+ .from("methodMaterial")+ .select("*, item(name)")+ .eq("id", materialId)+ .single();+}++export const METHOD_MATERIALS_PAGING: Paging = { defaultSorts: [] };+- /** @mcp read */export async function getMethodMaterials(client: SupabaseClient<Database>,companyId: string,@@@ -1980,11 -1749,6 +1787,10 @@@ export async function getMethodMaterialreturn result;}+export const METHOD_OPERATIONS_PAGING: Paging = {+ defaultSorts: [{ column: "order", ascending: true }]+};+- /** @mcp read */export async function getMethodOperations(client: SupabaseClient<Database>,companyId: string,@@@ -2269,11 -2026,6 +2066,10 @@@ export async function getPart.single();}+export const PARTS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getParts(client: SupabaseClient<Database>,companyId: string,@@@ -2462,11 -2210,6 +2253,10 @@@ export async function getPickMethods.eq("companyId", companyId);}+export const SERVICES_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getServices(client: SupabaseClient<Database>,companyId: string,@@@ -2584,11 -2324,6 +2369,10 @@@ export async function getTool.single();}+export const TOOLS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getTools(client: SupabaseClient<Database>,companyId: string,@@@ -2665,11 -2382,6 +2429,10 @@@ export async function getUnitOfMeasureUreturn client.rpc("get_unit_of_measure_usage", { p_id: id });}+export const UNIT_OF_MEASURES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getUnitOfMeasures(client: SupabaseClient<Database>,companyId: string,@@@ -2683,10 -2395,12 +2446,10 @@@.eq("companyId", companyId);if (args.search) {- query = query.or(`name.ilike.%${args.search}%,code.ilike.%${args.search}%`);+ query = query.or(searchFilter(["name", "code"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, UNIT_OF_MEASURES_PAGING);return query;}@@@ -6235,9 -5820,6 +5869,8 @@@ export async function deleteMaterialTypreturn client.from("materialType").delete().eq("id", id);}+export const MATERIAL_TYPES_PAGING: Paging = { defaultSorts: [] };+- /** @mcp read */export async function getMaterialTypes(client: SupabaseClient<Database>,companyId: string,@@@ -6907,11 -6313,6 +6364,10 @@@ export async function getChangeNotice.single();}+export const CHANGE_NOTICES_PAGING: Paging = {+ defaultSorts: [{ column: "changeOrderId", ascending: false }]+};+- /** @mcp read */export async function getChangeNotices(client: SupabaseClient<Database>,companyId: string,@@@ -7153,11 -6580,6 +6633,10 @@@ export async function updateChangeNotic// -----------------------------------------------------------------------------// Change Notice Types (the "Category" lookup — configured like Issue Types)// -----------------------------------------------------------------------------+export const CHANGE_NOTICE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getChangeNoticeTypes(client: SupabaseClient<Database>,companyId: string,@@@ -8508,11 -7734,6 +7789,10 @@@ export async function updateChangeNotic// Change Notice Required Actions (the configurable default-action templates the// config CRUD page manages, and the source new change notices are seeded from).// =============================================================================+export const CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getChangeNoticeRequiredActions(client: SupabaseClient<Database>,companyId: string,@@@ -9656,3 -9092,2018 +9153,2214 @@@ export async function createItemDocumenname: args.name});}+ // An item page's layout and its tab loaders run in ONE request and each read the+ // item's methods and change notices. These share that read across the loaders;+ // on a mutation they are plain calls, so a revalidation never sees stale rows.++ export const getMakeMethodsOnce = (+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+ ) =>+ oncePerRead(`makeMethods:${companyId}:${itemId}`, () =>+ getMakeMethods(client, itemId, companyId)+ );++ export const getMakeMethodByIdOnce = (+ client: SupabaseClient<Database>,+ makeMethodId: string,+ companyId: string+ ) =>+ oncePerRead(`makeMethod:${companyId}:${makeMethodId}`, () =>+ getMakeMethodById(client, makeMethodId, companyId)+ );++ export const findChangeNoticesForItemOnce = (+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+ ) =>+ oncePerRead(`changeNotices:${args.companyId}:${args.itemId}`, () =>+ findChangeNoticesForItem(client, args)+ );++ export async function getItemChangeNoticeDataOnce(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+ ) {+ const [changeNotices, changeNoticeTypes] = await Promise.all([+ findChangeNoticesForItemOnce(client, { itemId, companyId }),+ getChangeNoticeTypesList(client, companyId)+ ]);+ return {+ changeNotices: changeNotices.data,+ changeNoticeTypes: changeNoticeTypes.data ?? []+ };+ }++ // Release-lock helpers — gate BOM/BOP mutations on a released (Production)+ // revision. A Production revision is the controlled, released make method;+ // changes must flow through a change notice. The pending revision an ECO creates+ // is Design/Prototype (NOT Production), so it stays editable.++ export type ReleaseControl = (typeof plmReleaseControl)[number];++ type ItemRevisionStatus = Database["public"]["Enums"]["itemRevisionStatus"];++ export const LOCKED_REVISION_MESSAGE =+ "This revision is released (Production). Open a change notice to modify it.";++ export type LockKind =+ | "item"+ | "makeMethod"+ | "material"+ | "operation"+ | "step"+ | "tool"+ | "parameter";++ export type RevisionLock = {+ isLocked: boolean;+ releaseControl: ReleaseControl;+ revisionStatus: ItemRevisionStatus | null;+ };++ export type LockCheck =+ | { ok: true; warn: false }+ | { ok: true; warn: true; message: string }+ | { ok: false; warn: false; message: string };++ export function getLockVerdict(lock: {+ isLocked: boolean;+ releaseControl: ReleaseControl;+ }): LockCheck {+ if (!lock.isLocked || lock.releaseControl === "off") {+ return { ok: true, warn: false };+ }+ if (lock.releaseControl === "warn") {+ return { ok: true, warn: true, message: LOCKED_REVISION_MESSAGE };+ }+ return { ok: false, warn: false, message: LOCKED_REVISION_MESSAGE };+ }++ type MethodLock = {+ revisionStatus: ItemRevisionStatus | null;+ changeNoticeId: string | null;+ changeNoticeStatus: string | null;+ };++ const NO_LOCK: MethodLock = {+ revisionStatus: null,+ changeNoticeId: null,+ changeNoticeStatus: null+ };++ // The FK chain from each lock kind up to its owning make method, expressed once.+ // The two lock inputs (the item's revisionStatus and the owning change notice's+ // status) hang off that method, so one nested select answers both — walking the+ // chain twice would double a query that runs on every BOM/BOP mutation.+ // `methodMaterial` has two FKs to `makeMethod` (makeMethodId and+ // materialMakeMethodId); the parent method is methodMaterial_methodId_fkey.+ const METHOD_LOCK_SOURCE = "changeOrder(id, status), item(revisionStatus)";++ const methodLockQueries = {+ makeMethod: ["makeMethod", METHOD_LOCK_SOURCE],+ material: [+ "methodMaterial",+ `makeMethod!methodMaterial_methodId_fkey(${METHOD_LOCK_SOURCE})`+ ],+ operation: ["methodOperation", `makeMethod(${METHOD_LOCK_SOURCE})`],+ step: [+ "methodOperationStep",+ `methodOperation(makeMethod(${METHOD_LOCK_SOURCE}))`+ ],+ tool: [+ "methodOperationTool",+ `methodOperation(makeMethod(${METHOD_LOCK_SOURCE}))`+ ],+ parameter: [+ "methodOperationParameter",+ `methodOperation(makeMethod(${METHOD_LOCK_SOURCE}))`+ ]+ } as const satisfies Partial<Record<LockKind, readonly [string, string]>>;++ // Every base query is scoped by companyId (defense-in-depth; the id is a global+ // UUID but tenant scoping is a golden rule). The lock is advisory — RLS ++ // requirePermissions are the real boundary — so a null/unresolvable status+ // leaves the gate open by design (see checkRevisionLock).+ async function resolveMethodLock(+ client: SupabaseClient<Database>,+ kind: LockKind,+ id: string,+ companyId: string+ ): Promise<MethodLock> {+ if (kind === "item") {+ const item = await client+ .from("item")+ .select("revisionStatus")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ // item.changeOrderId is a PERMANENT back-link stamped at release (not cleared+ // like makeMethod's), so it means "was created by" — never "is owned by".+ // Resolving it would lock every CO-created item forever once its CO hit Done.+ return { ...NO_LOCK, revisionStatus: item.data?.revisionStatus ?? null };+ }++ const [table, select] = methodLockQueries[kind];+ const result = await client+ .from(table)+ .select(select)+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();++ // The select is built from a lookup, so PostgREST's row typing degrades to a+ // generic shape — narrow it once, here, rather than at each read below.+ const method = unwrapMakeMethod(result.data as MethodLockRow | null, kind);+ return {+ revisionStatus: method?.item?.revisionStatus ?? null,+ changeNoticeId: method?.changeOrder?.id ?? null,+ changeNoticeStatus: method?.changeOrder?.status ?? null+ };+ }++ type MakeMethodLockRow = {+ changeOrder: { id: string; status: string | null } | null;+ item: { revisionStatus: ItemRevisionStatus | null } | null;+ };++ type MethodLockRow =+ | MakeMethodLockRow+ | { makeMethod: MakeMethodLockRow | null }+ | { methodOperation: { makeMethod: MakeMethodLockRow | null } | null };++ function unwrapMakeMethod(+ row: MethodLockRow | null,+ kind: LockKind+ ): MakeMethodLockRow | null {+ if (!row) return null;+ if (kind === "makeMethod") return row as MakeMethodLockRow;+ if (kind === "tool" || kind === "parameter" || kind === "step") {+ return (+ (row as { methodOperation: { makeMethod: MakeMethodLockRow | null } })+ .methodOperation?.makeMethod ?? null+ );+ }+ return (row as { makeMethod: MakeMethodLockRow | null }).makeMethod ?? null;+ }++ async function getReleaseControl(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<ReleaseControl> {+ const settings = await getCompanySettings(client, companyId);+ return (settings.data?.plmReleaseControl ?? "enforce") as ReleaseControl;+ }++ // Read variant for loaders that need the raw lock state (revisionStatus ++ // releaseControl) to drive read-only UI. A revision is locked ONLY when it is+ // "Production".+ export async function getRevisionLock(+ client: SupabaseClient<Database>,+ args: { itemId: string | null; companyId: string }+ ): Promise<RevisionLock> {+ const [lock, releaseControl] = await Promise.all([+ args.itemId+ ? resolveMethodLock(client, "item", args.itemId, args.companyId)+ : Promise.resolve(NO_LOCK),+ getReleaseControl(client, args.companyId)+ ]);++ return {+ isLocked: lock.revisionStatus === "Production",+ releaseControl,+ revisionStatus: lock.revisionStatus+ };+ }++ // The single guard entry point for mutation routes: resolves the entity's+ // parent item and returns the enforce/warn/off verdict. A missing/null id+ // (cannot resolve) leaves the lock unlocked, so the gate is safely skipped.+ export async function checkRevisionLock(+ client: SupabaseClient<Database>,+ args: { kind: LockKind; id: string | null | undefined; companyId: string }+ ): Promise<LockCheck> {+ const [lock, releaseControl] = await Promise.all([+ args.id+ ? resolveMethodLock(client, args.kind, args.id, args.companyId)+ : Promise.resolve(NO_LOCK),+ getReleaseControl(client, args.companyId)+ ]);++ // Hard block, independent of releaseControl — releaseControl only governs the+ // revision lock.+ const changeNoticeLock = lock.changeNoticeId+ ? await getChangeNoticeEngineeringLock(+ lock.changeNoticeId,+ lock.changeNoticeStatus+ )+ : null;+ if (changeNoticeLock) {+ return { ok: false, warn: false, message: changeNoticeLock };+ }++ return getLockVerdict({+ isLocked: lock.revisionStatus === "Production",+ releaseControl+ });+ }++ /**+ * The first refusal among several locks, else the first warning. An update+ * that can move a row checks both the method it leaves and the one it joins.+ */+ /**+ * The one make method that every row in `ids` belongs to, or null when the+ * rows are missing or span several methods. A bulk bill of material or bill of+ * process write checks one method's lock, so its rows must share it.+ */+ export async function getSingleMakeMethodId(+ client: SupabaseClient<Database>,+ companyId: string,+ table: "methodMaterial" | "methodOperation",+ ids: string[]+ ) {+ const rows = await client+ .from(table)+ .select("makeMethodId")+ .in("id", ids)+ .eq("companyId", companyId);+ const makeMethodIds = new Set(+ (rows.data ?? []).map((row) => row.makeMethodId)+ );+ return {+ data: makeMethodIds.size === 1 ? [...makeMethodIds][0] : null,+ error: rows.error+ };+ }++ export async function checkRevisionLocks(+ client: SupabaseClient<Database>,+ companyId: string,+ targets: { kind: LockKind; id: string | null | undefined }[]+ ): Promise<LockCheck> {+ const checks = await Promise.all(+ targets.map((target) => checkRevisionLock(client, { ...target, companyId }))+ );+ return (+ checks.find((check) => !check.ok) ??+ checks.find((check) => check.warn) ?? { ok: true, warn: false }+ );+ }++ /**+ * Why a step, a slide or a step link cannot change, or null. Only a Draft+ * method's steps change. The release lock is the caller's: its warning is+ * returned with the write.+ */+ export async function methodStepRefusal(+ client: SupabaseClient<Database>,+ companyId: string,+ ref: { operationId: string } | { stepId: string } | { slideId: string }+ ): Promise<string | null> {+ let operationId: string | null = null;+ if ("operationId" in ref) {+ operationId = ref.operationId;+ } else if ("stepId" in ref) {+ const step = await client+ .from("methodOperationStep")+ .select("operationId")+ .eq("id", ref.stepId)+ .eq("companyId", companyId)+ .maybeSingle();+ operationId = step.data?.operationId ?? null;+ } else {+ const slide = await client+ .from("methodOperationStepSlide")+ .select("methodOperationStep(operationId)")+ .eq("id", ref.slideId)+ .eq("companyId", companyId)+ .maybeSingle();+ operationId = slide.data?.methodOperationStep?.operationId ?? null;+ }+ if (!operationId) return "Failed to find method operation";++ try {+ await assertMethodOperationIsDraft(client, operationId);+ return null;+ } catch (err) {+ return err instanceof Error+ ? err.message+ : "Failed to find method operation";+ }+ }++ // =============================================================================+ // Change Notices — server-only helpers (imports @carbon/jobs).+ // =============================================================================++ type ChangeNoticeEditScope = "engineering" | "workflow";++ // Why a change notice's engineering content cannot be edited, or null. An+ // approval request can only be pending at Engineering Complete (approval gates+ // the move to Implementation), so only that stage pays for the lookup;+ // approvalRequest is service-role only.+ async function getChangeNoticeEngineeringLock(+ changeNoticeId: string,+ status: string | null | undefined+ ): Promise<string | null> {+ if (!canEditChangeNoticeEngineering(status)) {+ return changeNoticeLockedMessage(status);+ }+ if (+ status === "Engineering Complete" &&+ (await hasPendingApproval(+ getCarbonServiceRole(),+ "changeOrder",+ changeNoticeId+ ))+ ) {+ return changeNoticeAwaitingApprovalMessage;+ }+ return null;+ }++ // One status read + predicate. Mutation routes call this before writing; the+ // UI disable is cosmetic on top of it.+ export async function requireChangeNoticeEditable(+ client: SupabaseClient<Database>,+ args: {+ changeNoticeId: string;+ companyId: string;+ scope: ChangeNoticeEditScope;+ }+ ): Promise<{ error: { message: string }; data: null } | null> {+ const existing = await client+ .from("changeOrder")+ .select("status")+ .eq("id", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .maybeSingle();++ if (existing.error || !existing.data) {+ return { error: { message: "Could not find change notice" }, data: null };+ }++ const { status } = existing.data;+ const message =+ args.scope === "engineering"+ ? await getChangeNoticeEngineeringLock(args.changeNoticeId, status)+ : canEditChangeNoticeWorkflow(status)+ ? null+ : changeNoticeLockedMessage(status);++ return message ? { error: { message }, data: null } : null;+ }++ // A child row (affected item, action task) is addressed by its own id, so its+ // notice is the one the row belongs to, not one the caller names.+ export async function requireChangeNoticeChildEditable(+ client: SupabaseClient<Database>,+ args: {+ table: "changeOrderAffectedItem" | "changeOrderActionTask";+ id: string;+ companyId: string;+ scope: ChangeNoticeEditScope;+ }+ ): Promise<{ error: { message: string }; data: null } | null> {+ const row = await client+ .from(args.table)+ .select("changeOrderId")+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .maybeSingle();+ if (row.error || !row.data) {+ return {+ error: { message: "Could not find the change notice record" },+ data: null+ };+ }+ return requireChangeNoticeEditable(client, {+ changeNoticeId: row.data.changeOrderId,+ companyId: args.companyId,+ scope: args.scope+ });+ }++ // The inverse gate: an item owned by an open change notice must not get a manual+ // revision, because the notice authors it. Fails closed — a lookup we couldn't+ // read cannot prove the item is free.+ export async function requireItemChangeNoticeUnlocked(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+ ): Promise<{ error: { message: string }; data: null } | null> {+ const open = await findChangeNoticesForItem(client, {+ itemId: args.itemId,+ companyId: args.companyId,+ statuses: changeNoticeOpenStatuses+ });++ if (open.error) {+ return {+ error: { message: "Could not check open change notices for this item" },+ data: null+ };+ }++ if (open.data.length === 0) return null;++ const ids = open.data.map((co) => co.changeOrderId).join(", ");+ return {+ error: {+ message: `This item is open in change notice ${ids}. Release it to create new revisions.`+ },+ data: null+ };+ }++ // Child rows (affected items, action tasks) are addressed by their own id, so+ // authorizing the change notice in the URL proves nothing about the row being+ // mutated — an editable notice's URL would otherwise let a user mutate a frozen+ // notice's rows. Same failure contract as requireEditableChangeNoticeRoute;+ // null means the route may proceed.+ export async function requireChangeNoticeChildRoute(+ request: Request,+ args: {+ client: SupabaseClient<Database>;+ table: "changeOrderAffectedItem" | "changeOrderActionTask";+ id: string;+ changeNoticeId: string;+ companyId: string;+ }+ ) {+ const row = await args.client+ .from(args.table)+ .select("id")+ .eq("id", args.id)+ .eq("changeOrderId", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .maybeSingle();++ if (row.error || !row.data) {+ const message = "Record does not belong to this change notice";+ return data(+ { success: false },+ await flash(request, error(row.error, message))+ );+ }++ return null;+ }++ // The route-level guard: resolves the change notice from the URL, checks the+ // scope, and returns the flashed failure response so all eight mutation routes+ // share one failure contract. Returns null when the route may proceed.+ export async function requireEditableChangeNoticeRoute(+ request: Request,+ args: {+ client: SupabaseClient<Database>;+ changeNoticeId: string | undefined;+ companyId: string;+ scope: ChangeNoticeEditScope;+ }+ ) {+ if (!args.changeNoticeId) throw new Error("Could not find id");++ const locked = await requireChangeNoticeEditable(args.client, {+ changeNoticeId: args.changeNoticeId,+ companyId: args.companyId,+ scope: args.scope+ });+ if (!locked) return null;++ return data(+ { success: false },+ await flash(request, error(locked.error, locked.error.message))+ );+ }++ // Maps a notifying stage to its notification event. Only Start / Implementation+ // / Done notify; Draft / Engineering Complete are silent, so callers simply+ // don't invoke this for those stages.+ export const changeNoticeStageEvent: Record<string, NotificationEvent> = {+ Start: NotificationEvent.ChangeNoticeStarted,+ Implementation: NotificationEvent.ChangeNoticeImplementation,+ Done: NotificationEvent.ChangeNoticeDone+ };++ // Notifies the people involved in the CO — its assignee plus every action-task+ // assignee — on a stage entry (best-effort). Deliberately NOT a company-wide+ // broadcast; the notify function dedupes and drops the acting user itself.+ export async function notifyChangeNoticeTransition(args: {+ client: SupabaseClient<Database>;+ event: NotificationEvent;+ changeNoticeId: string;+ companyId: string;+ userId: string;+ }): Promise<void> {+ try {+ const [changeNotice, actionTasks] = await Promise.all([+ args.client+ .from("changeOrder")+ .select("assignee")+ .eq("id", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .single(),+ args.client+ .from("changeOrderActionTask")+ .select("assignee")+ .eq("changeOrderId", args.changeNoticeId)+ .eq("companyId", args.companyId)+ .not("assignee", "is", null)+ ]);++ if (changeNotice.error) {+ logger.error("Failed to resolve change notice for CO notification", {+ error: changeNotice.error,+ changeNoticeId: args.changeNoticeId,+ companyId: args.companyId+ });+ return;+ }++ if (actionTasks.error) {+ logger.error("Failed to resolve CO action-task assignees", {+ error: actionTasks.error,+ changeNoticeId: args.changeNoticeId,+ companyId: args.companyId+ });+ }++ const userIds = [+ ...new Set(+ [+ changeNotice.data?.assignee,+ ...(actionTasks.data ?? []).map((task) => task.assignee)+ ].filter((id): id is string => !!id)+ )+ ];++ if (userIds.length === 0) return;++ await trigger("notify", {+ event: args.event,+ companyId: args.companyId,+ documentId: args.changeNoticeId,+ recipient: { type: "users", userIds },+ from: args.userId+ });+ } catch (e) {+ logger.error("Failed to trigger change notice notification", { error: e });+ }+ }++ // =============================================================================+ // applyChangeNotice — the top-to-bottom "release", run on the Implementation →+ // Done transition (this function IS that transition). It materializes each+ // affected item's CO-staged end-state onto a NEW inactive revision, activates+ // it, then auto-writes the oldRev → newRev supersession (Q1/Q2/Q5).+ //+ // Atomicity (G2): createRevision + activateMethodVersion call the get-method /+ // convert operations, each of which commits its own transaction, so this CANNOT+ // be one Kysely transaction. The apply is therefore an idempotent, CAS-guarded orchestration:+ // - PER-AFFECTED-ITEM idempotency: each changeOrderAffectedItem gets its+ // created revision id stamped into `newItemId` at the END of its processing.+ // A re-run skips any affected item whose `newItemId` is already set, so a+ // partial failure re-run resumes at the first unprocessed item instead of+ // re-creating revisions.+ // - CO-LEVEL idempotency: the final flip to 'Done' is a compare-and-swap on+ // status='Implementation', so a re-run can't double-transition the CO; only+ // the closing status flip is transactional.+ // =============================================================================+ export async function applyChangeNotice(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ changeNoticeId: string;+ userId: string;+ companyId: string;+ }+ ): Promise<{ data: { id: string } | null; error: { message: string } | null }> {+ const { changeNoticeId, userId, companyId } = args;++ const cn = await client+ .from("changeOrder")+ .select("id, status")+ .eq("id", changeNoticeId)+ .eq("companyId", companyId)+ .single();+ if (cn.error || !cn.data) {+ return { data: null, error: ruleError("Change notice not found") };+ }+ if (cn.data.status !== "Implementation") {+ return { data: null, error: { message: changeNoticeUpdatedElsewhere } };+ }++ // Load the affected items with change type + draft refs + cutover config.+ // v2: the draft make method already holds the edited BOM/BOP; release just+ // activates it (and reveals the new item for Revision/New Part). Idempotency+ // is per-item inside releaseAffectedItem (skip once the draft is no longer+ // CO-owned).+ const affectedItems = await client+ .from("changeOrderAffectedItem")+ .select(+ "id, itemId, changeType, draftMakeMethodId, baseMakeMethodId, newItemId, supersessionMode, discontinuationDate, successorEffectivityDate"+ )+ .eq("changeOrderId", changeNoticeId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: true })+ .order("createdAt", { ascending: true });+ if (affectedItems.error) {+ return { data: null, error: affectedItems.error };+ }++ // Release New Part (net-new) items first, so a parent assembly whose draft BOM+ // references a new part resolves to an already-active item when its own method+ // activates. Stable sort preserves the sortOrder/createdAt order within groups.+ const ordered = [...(affectedItems.data ?? [])].sort(+ (a, b) =>+ (a.changeType === "New Part" ? 0 : 1) -+ (b.changeType === "New Part" ? 0 : 1)+ );++ for (const affected of ordered) {+ const result = await releaseAffectedItem(client, db, {+ changeNoticeId,+ companyId,+ userId,+ affected+ });+ if (result.error) return { data: null, error: result.error };+ }++ // Final compare-and-swap: Implementation → Done (the only transactional write).+ try {+ const updated = await db.transaction().execute(async (trx) => {+ const res = await trx+ .updateTable("changeOrder")+ .set({ status: "Done", updatedBy: userId })+ .where("id", "=", changeNoticeId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Implementation")+ .executeTakeFirst();+ return Number(res.numUpdatedRows);+ });+ if (updated === 0) {+ return { data: null, error: { message: changeNoticeUpdatedElsewhere } };+ }+ } catch (err) {+ return {+ data: null,+ error: { message: err instanceof Error ? err.message : "Apply failed" }+ };+ }++ return { data: { id: changeNoticeId }, error: null };+ }++ // -----------------------------------------------------------------------------+ // releaseAffectedItem (v2) — dispatch by change type. The CO-owned Draft make+ // method already holds the edited BOM/BOP, so release just:+ // Version → activate the Draft on the SAME item (prior Active →+ // Archived); no new item, no supersession.+ // Revision → activate the Draft + reveal the new revision item + auto+ // oldRev→newRev supersession.+ // Replacement Part → activate the Draft + reveal the new part + auto+ // affected→new supersession.+ // New Part → activate the Draft + reveal the net-new part; NO+ // supersession (no predecessor).+ // Idempotent: once the Draft's changeOrderId is cleared it counts as released.+ // -----------------------------------------------------------------------------+ async function releaseAffectedItem(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ input: {+ changeNoticeId: string;+ companyId: string;+ userId: string;+ affected: {+ id: string;+ itemId: string;+ changeType: Database["public"]["Enums"]["changeOrderChangeType"];+ draftMakeMethodId: string | null;+ baseMakeMethodId: string | null;+ newItemId: string | null;+ supersessionMode: Database["public"]["Enums"]["supersessionMode"] | null;+ discontinuationDate: string | null;+ successorEffectivityDate: string | null;+ };+ }+ ): Promise<{ error: { message: string } | null }> {+ const { changeNoticeId, companyId, userId, affected } = input;+ const { changeType, draftMakeMethodId, newItemId } = affected;+ const sourceItemId = affected.itemId;++ if (!draftMakeMethodId) {+ return { error: { message: "Affected item has no draft make method" } };+ }++ // Idempotency: a Draft still owned by this CO has not been released yet; once+ // released we clear changeOrderId, so a re-run skips it.+ const draft = await client+ .from("makeMethod")+ .select("changeOrderId")+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (draft.error) return { error: draft.error };+ if (!draft.data || !draft.data.changeOrderId) {+ return { error: null };+ }++ // Activate the Draft method (Draft → Active; prior Active → Archived). A+ // Version simply appends a new Active version and archives the prior one — the+ // prior version's rows are preserved as method history, so there is nothing to+ // merge even if another CO released a newer version in the meantime.+ const activated = await activateMethodVersion(client, db, {+ id: draftMakeMethodId,+ companyId,+ userId+ });+ if (activated.error) {+ return {+ error: {+ message: activated.error.message || "Failed to activate method"+ }+ };+ }++ // Reveal the new item for Revision / New Part (Version edits the same item).+ if (newItemId) {+ const reveal = await client+ .from("item")+ .update({+ active: true,+ changeOrderId: changeNoticeId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", newItemId)+ .eq("companyId", companyId);+ if (reveal.error) return { error: reveal.error };+ }++ // Auto supersession: Revision (oldRev→newRev) / Replacement Part (affected→new).+ // Version edits the SAME item, and a net-new New Part has NO predecessor — so+ // neither writes a supersession (they still reveal their item above). This runs+ // BEFORE clearing the CO-ownership marker so a supersession failure leaves the+ // draft still owned by the CO (changeOrderId set) — the item is re-attempted on+ // retry instead of the CO silently completing without its required supersession.+ // Re-runs are safe: activate/reveal are idempotent and upsertItemSupersession is+ // an upsert.+ if (+ (changeType === "Revision" || changeType === "Replacement Part") &&+ newItemId+ ) {+ const sup = await upsertItemSupersession(client, {+ itemId: sourceItemId,+ successorItemId: newItemId,+ supersessionMode: normalizeSupersessionMode(affected.supersessionMode),+ // Empty per-item dates mean "effective immediately at release" — the+ // supersession redirect map treats a null successorEffectivityDate as+ // always-effective. Cutover timing is driven purely per affected item now.+ discontinuationDate: affected.discontinuationDate ?? undefined,+ successorEffectivityDate: affected.successorEffectivityDate ?? undefined,+ companyId,+ createdBy: userId,+ updatedBy: userId+ });+ if (sup.error) {+ logger.error("Failed to write revision supersession", {+ error: sup.error+ });+ return { error: sup.error };+ }+ }++ // Clear CO ownership on the Draft — the FINAL, idempotency-marking step. Once+ // cleared the draft is normal method history and a re-run skips this item.+ const clear = await client+ .from("makeMethod")+ .update({ changeOrderId: null })+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId);+ if (clear.error) return { error: clear.error };++ return { error: null };+ }++ // Coerce a possibly-null DB supersession mode to a valid enum member, defaulting+ // to 'Consume First' (Q3 default) when unset/invalid.+ function normalizeSupersessionMode(+ mode: string | null | undefined+ ): Database["public"]["Enums"]["supersessionMode"] {+ return (supersessionModes as readonly string[]).includes(mode ?? "")+ ? (mode as Database["public"]["Enums"]["supersessionMode"])+ : "Consume First";+ }++ // -----------------------------------------------------------------------------+ // Unreleased-change-order guard.+ //+ // Release is what activates a change notice's items: `applyChangeNotice` flips+ // `active` on the revisions and parts the notice minted. Nothing stops a user+ // switching the Active toggle on by hand first, and once it is on the item is+ // selectable everywhere — carrying the notice's un-approved draft BOM, since a+ // minted revision's only make method is that Draft and `activeMakeMethods` falls+ // back to it when no Active version exists.+ //+ // So two kinds of write ask this question: one that would ACTIVATE such an item,+ // and one that would CONSUME it (a sales order line, a purchase order line, a+ // job).+ //+ // `item.changeOrderId` is NOT a draft marker on its own — release leaves it in+ // place as a provenance back-link, so the owning change order's status decides.+ // Release IS the Implementation -> Done transition, so every other status means+ // the item is still a draft.+ //+ // Pass a service-role client: reading `changeOrder` requires `parts_view`, which+ // the caller need not have.+ // -----------------------------------------------------------------------------+ const RELEASED_CHANGE_ORDER_STATUS = "Done";++ export type UnreleasedChangeOrderItem = {+ itemId: string;+ itemName: string;+ changeOrderReadableId: string;+ };++ // Both reads go through fetchAllByIds: an `in` filter rides in the URL and a+ // response stops at PostgREST's row cap. Truncating either one would drop an+ // item from the answer, and a missing row reads as "no change order holds it".++ // Two queries per batch of ids — the bulk item update can carry a whole table+ // selection.+ //+ // `error` is a message to show the user, not a thrown failure — a read that did+ // not answer says nothing about the items, so callers block on it rather than+ // wave the write through on a database blip.+ export async function getUnreleasedChangeOrderItems(+ client: SupabaseClient<Database>,+ args: { itemIds: string[]; companyId: string }+ ): Promise<{ data: UnreleasedChangeOrderItem[]; error: string | null }> {+ if (args.itemIds.length === 0) return { data: [], error: null };++ const items = await fetchAllByIds(args.itemIds, (batch) =>+ client+ .from("item")+ .select("id, readableIdWithRevision, changeOrderId")+ .in("id", batch)+ .eq("companyId", args.companyId)+ .order("id")+ );++ if (items.error) {+ logger.error("Failed to read items for change order check", {+ error: items.error,+ itemIds: args.itemIds+ });+ return {+ data: [],+ error: "These items could not be checked against their change orders."+ };+ }++ const owned = (items.data ?? []).filter(+ (item): item is typeof item & { changeOrderId: string } =>+ !!item.changeOrderId+ );+ if (owned.length === 0) return { data: [], error: null };++ const changeOrders = await fetchAllByIds(+ [...new Set(owned.map((item) => item.changeOrderId))],+ (batch) =>+ client+ .from("changeOrder")+ .select("id, changeOrderId, status")+ .in("id", batch)+ .eq("companyId", args.companyId)+ .order("id")+ );++ if (changeOrders.error) {+ logger.error("Failed to read change orders for change order check", {+ error: changeOrders.error,+ itemIds: args.itemIds+ });+ return {+ data: [],+ error: "These items could not be checked against their change orders."+ };+ }++ const unreleased = new Map(+ (changeOrders.data ?? [])+ .filter((co) => co.status !== RELEASED_CHANGE_ORDER_STATUS)+ .map((co) => [co.id, co.changeOrderId])+ );++ return {+ data: owned.flatMap((item) => {+ const changeOrderReadableId = unreleased.get(item.changeOrderId);+ if (!changeOrderReadableId) return [];+ return [+ {+ itemId: item.id,+ itemName: item.readableIdWithRevision ?? "This item",+ changeOrderReadableId+ }+ ];+ }),+ error: null+ };+ }++ // Single-item form for the loaders that only need to know whether to lock the+ // Active toggle on this one item's page. Best-effort: a failed read leaves the+ // toggle unlocked, and the action behind it still refuses the write.+ export async function getUnreleasedChangeOrderForItem(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+ ): Promise<UnreleasedChangeOrderItem | null> {+ const unreleased = await getUnreleasedChangeOrderItems(client, {+ itemIds: [args.itemId],+ companyId: args.companyId+ });+ return unreleased.data[0] ?? null;+ }++ // Single-item form for the actions that put an item into circulation. Returns+ // the reason to refuse, or null. Unlike the loader form this fails closed: a+ // read that did not answer says nothing about the item.+ //+ // Deliberately does NOT judge `active`. Plain inactive items are allowed onto+ // these documents today, and changing that is a separate decision from closing+ // the change order hole.+ export async function getUnreleasedChangeOrderIssue(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+ ): Promise<string | null> {+ const unreleased = await getUnreleasedChangeOrderItems(client, {+ itemIds: [args.itemId],+ companyId: args.companyId+ });+ if (unreleased.error) return unreleased.error;+ if (unreleased.data.length === 0) return null;+ return unreleasedChangeOrderItemsMessage(unreleased.data);+ }++ // Names every offending item so a bulk edit says which row to fix.+ export function unreleasedChangeOrderItemsMessage(+ unreleased: UnreleasedChangeOrderItem[]+ ) {+ return unreleased+ .map(+ (item) =>+ `${item.itemName} was created by change order ${item.changeOrderReadableId}, which has not been released yet.`+ )+ .join(" ");+ }++ // Not awaited by the item layouts: only the header badge and the properties+ // sidebar read these, so they stream instead of holding the page.+ export function streamItemSupersession(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+ ) {+ return {+ supersession: getItemSupersession(client, itemId, companyId).then(+ (result) => result.data,+ (error) => {+ logger.error("Failed to load item supersession", {+ companyId,+ itemId,+ error+ });+ return null;+ }+ ),+ supersededBy: getItemSupersededBy(client, itemId, companyId).then(+ (result) => result.data ?? [],+ (error) => {+ logger.error("Failed to load item predecessors", {+ companyId,+ itemId,+ error+ });+ return [];+ }+ )+ };+ }++ export function priceBreakRows(+ ctx: ServiceContext,+ supplierPartId: string,+ priceBreaks: z.output<typeof supplierPartPriceBreaksValidator>+ ) {+ return priceBreaks.map((priceBreak) => ({+ supplierPartId,+ quantity: priceBreak.quantity,+ supplierUnitPrice: priceBreak.supplierUnitPrice,+ leadTime: priceBreak.leadTime ?? 0,+ sourceType: "Manual Entry" as const,+ companyId: ctx.company.id,+ createdBy: ctx.auditUserId,+ updatedBy: ctx.auditUserId+ }));+ }++ // ── Make methods ────────────────────────────────────────────────────────────++ export const isMakeMethodId = (id: string) => id.startsWith("make_");++ // ── Change notices ──────────────────────────────────────────────────────────++ // Reason and description arrive as plain text; the columns are tiptap JSON, so+ // non-empty text becomes a doc the detail page's editor can edit.+ export function toRichText(value: string | undefined): Json | undefined {+ if (!value) return undefined;+ return textToTiptap(value) as unknown as Json;+ }++ const onShapeDataValidator = z.object({+ index: z.string(),+ id: z.string().optional(),+ readableId: z.string().optional(),+ revision: z.string().optional(),+ name: z.string(),+ quantity: z.number(),+ replenishmentSystem: z.enum(["Make", "Buy", "Buy and Make"]),+ defaultMethodType: z.enum([+ "Make to Order",+ "Purchase to Order",+ "Pull from Inventory"+ ]),+ data: z.record(z.string(), z.any())+ });++ export const syncInput = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("onshape"),+ makeMethodId: z.string(),+ data: onShapeDataValidator.array()+ })+ ]);++ interface MakeMethodInfo {+ id: string;+ itemId: string;+ version: number;+ status: "Draft" | "Active" | "Archived";+ }++ async function copyMakeMethodOperations(+ trx: Transaction<KyselyDatabase>,+ sourceMakeMethodId: string,+ targetMakeMethodId: string,+ companyId: string,+ userId: string+ ) {+ // Fetch source operations+ const sourceOperations = await trx+ .selectFrom("methodOperation")+ .selectAll()+ .where("makeMethodId", "=", sourceMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();++ if (sourceOperations.length === 0) return;++ // Insert operations and copy related records+ for (const operation of sourceOperations) {+ const {+ id: oldOpId,+ createdAt: _createdAt,+ updatedAt: _updatedAt,+ updatedBy: _updatedBy,+ ...opData+ } = operation;++ const newOperation = await trx+ .insertInto("methodOperation")+ .values({+ ...opData,+ makeMethodId: targetMakeMethodId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();++ if (!newOperation) continue;++ // Copy tools+ const tools = await trx+ .selectFrom("methodOperationTool")+ .selectAll()+ .where("operationId", "=", oldOpId)+ .execute();++ if (tools.length > 0) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ tools.map(+ ({+ id: _id,+ createdAt: _createdAt,+ updatedAt: _updatedAt,+ updatedBy: _updatedBy,+ ...tool+ }) => ({+ ...tool,+ operationId: newOperation.id,+ createdBy: userId+ })+ )+ )+ .execute();+ }++ // Copy parameters+ const parameters = await trx+ .selectFrom("methodOperationParameter")+ .selectAll()+ .where("operationId", "=", oldOpId)+ .execute();++ if (parameters.length > 0) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ parameters.map(+ ({+ id: _id,+ createdAt: _createdAt,+ updatedAt: _updatedAt,+ updatedBy: _updatedBy,+ ...param+ }) => ({+ ...param,+ operationId: newOperation.id,+ createdBy: userId+ })+ )+ )+ .execute();+ }++ // Copy steps+ const steps = await trx+ .selectFrom("methodOperationStep")+ .selectAll()+ .where("operationId", "=", oldOpId)+ .execute();++ if (steps.length > 0) {+ await trx+ .insertInto("methodOperationStep")+ .values(+ steps.map(+ ({+ id: _id,+ createdAt: _createdAt,+ updatedAt: _updatedAt,+ updatedBy: _updatedBy,+ ...step+ }) => ({+ ...step,+ operationId: newOperation.id,+ createdBy: userId+ })+ )+ )+ .execute();+ }+ }+ }++ export const syncMakeMethodPermission = {+ update: "resources"+ } satisfies PermissionRule<z.output<typeof syncInput>>;++ /** Syncs an external CAD structure (Onshape) into a make method's BOM, per `type`. */+ export async function syncMakeMethod(+ ctx: ServiceContext,+ raw: z.input<typeof syncInput>+ ) {+ const payload = syncInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ switch (payload.type) {+ case "onshape": {+ const { type, makeMethodId, data } = payload;++ logger.info({+ type,+ makeMethodId,+ data,+ companyId,+ userId+ });++ // Check if top-level make method is Active and find or create a Draft+ const topLevelMakeMethod = await maybeSingle(+ db,+ "makeMethod",+ { id: makeMethodId, companyId },+ { columns: ["id", "itemId", "version", "status"] }+ );++ // Service-role client: a make method outside companyId is a 404.+ if (!topLevelMakeMethod.data) {+ throw new NotFoundError("Make method not found");+ }++ const existingItemIds = new Set(+ data.map((item) => item.id).filter((id): id is string => Boolean(id))+ );++ const existingItems = await many(+ db,+ "item",+ { companyId, id: Array.from(existingItemIds) },+ {+ columns: [+ "id",+ "readableId",+ "readableIdWithRevision",+ "unitOfMeasureCode",+ "type",+ "revision"+ ]+ }+ );+ if (existingItems.error) throw new Error("Failed to fetch items");++ const existingItemsByItemId = new Map(+ existingItems.data?.map((item) => [item.id, item]) ?? []+ );++ // Every item id in the body is updated by id alone below, so each must+ // have come back from the companyId-scoped read above. Checked before+ // anything is written (the Draft make method below).+ for (const itemId of existingItemIds) {+ if (!existingItemsByItemId.has(itemId as string)) {+ throw new NotFoundError("Item not found");+ }+ }++ let activeMakeMethodId = makeMethodId;+ let topLevelSourceMakeMethodId: string | null = null;++ if (topLevelMakeMethod.data?.status === "Active") {+ // Check if there's already a Draft version we can use+ const existingDraft = await maybeSingle(+ db,+ "makeMethod",+ {+ itemId: topLevelMakeMethod.data.itemId,+ status: "Draft",+ companyId+ },+ {+ columns: ["id", "version"],+ orderBy: [{ desc: "version" }],+ limit: 1+ }+ );++ if (existingDraft.data) {+ // Use the existing Draft+ activeMakeMethodId = existingDraft.data.id;+ } else {+ // Get max version across ALL make methods for this item+ const allVersions = await maybeSingle(+ db,+ "makeMethod",+ { itemId: topLevelMakeMethod.data.itemId, companyId },+ { columns: ["version"], orderBy: [{ desc: "version" }], limit: 1 }+ );++ const maxVersion = Number(allVersions.data?.version ?? 0);+ const newVersion = maxVersion + 1;++ logger.info({+ action: "creating_top_level_draft",+ itemId: topLevelMakeMethod.data.itemId,+ maxVersion,+ newVersion+ });++ const newTopLevelMakeMethod = await insertRows(db, "makeMethod", {+ itemId: topLevelMakeMethod.data.itemId,+ version: newVersion,+ status: "Draft",+ companyId,+ createdBy: userId+ });++ const inserted = newTopLevelMakeMethod.data[0];+ if (inserted) {+ activeMakeMethodId = inserted.id;+ topLevelSourceMakeMethodId = makeMethodId;+ }+ }+ }++ // Read after the Draft above may have been created, as before.+ const existingMakeMethods = await many(+ db,+ "activeMakeMethods",+ { companyId, itemId: Array.from(existingItemIds) },+ { columns: ["id", "itemId", "version", "status"] }+ );+ if (existingMakeMethods.error) {+ throw new Error("Failed to fetch make methods");+ }++ logger.info({+ action: "fetched_active_make_methods",+ count: existingMakeMethods.data?.length ?? 0,+ data: existingMakeMethods.data+ });++ const existingMakeMethodsByItemId = new Map<string, MakeMethodInfo>(+ existingMakeMethods.data?.map((makeMethod) => [+ makeMethod.itemId!,+ {+ id: makeMethod.id!,+ itemId: makeMethod.itemId!,+ version: Number(makeMethod.version),+ status: makeMethod.status as "Draft" | "Active" | "Archived"+ }+ ]) ?? []+ );++ {+ interface TreeNode {+ data: z.infer<typeof onShapeDataValidator>;+ children: TreeNode[];+ level: number;+ }++ // Sort the data by index to ensure parent nodes come before children+ const sortedData = [...data].sort((a, b) => {+ const aIndices = a.index.toString().split(".");+ const bIndices = b.index.toString().split(".");++ // Compare each level of the index+ for (let i = 0; i < Math.min(aIndices.length, bIndices.length); i++) {+ const aVal = parseInt(aIndices[i]!);+ const bVal = parseInt(bIndices[i]!);+ if (aVal !== bVal) {+ return aVal - bVal;+ }+ }++ // If one index is a prefix of the other, the shorter one comes first+ return aIndices.length - bIndices.length;+ });++ // Build the tree+ const buildTree = (+ d: z.infer<typeof onShapeDataValidator>[]+ ): TreeNode[] => {+ const result: TreeNode[] = [];+ const nodeMap = new Map<string, TreeNode>();++ d.forEach((item) => {+ const indexStr = item.index.toString();+ const node: TreeNode = {+ data: item,+ children: [],+ level: indexStr.split(".").length+ };++ nodeMap.set(indexStr, node);++ // Find parent node+ const lastDotIndex = indexStr.lastIndexOf(".");+ if (lastDotIndex === -1) {+ // This is a root node+ result.push(node);+ } else {+ // This is a child node+ const parentIndex = indexStr.substring(0, lastDotIndex);+ const parentNode = nodeMap.get(parentIndex);+ if (parentNode) {+ parentNode.children.push(node);+ }+ }+ });++ return result;+ };++ const tree = buildTree(sortedData);++ await db+ .transaction()+ .execute(async (trx: Transaction<KyselyDatabase>) => {+ // If we created a new draft for the top-level, copy operations from the active version+ if (topLevelSourceMakeMethodId) {+ await copyMakeMethodOperations(+ trx,+ topLevelSourceMakeMethodId,+ activeMakeMethodId,+ companyId,+ userId+ );+ }++ await trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "=", activeMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();++ // Track newly created items and make methods to avoid duplicate inserts+ const newlyCreatedItemsByPartId = new Map<string, string>();+ const newlyCreatedMakeMethodsByItemId = new Map<+ string,+ MakeMethodInfo+ >();++ async function traverseTree(+ node: TreeNode,+ parentMakeMethodId: string,+ index: number+ ) {+ const { data, children } = node;+ const {+ id,+ readableId,+ revision,+ name,+ quantity,+ replenishmentSystem,+ defaultMethodType+ } = data;++ const partId = readableId || name;+ if (!partId) return;++ const externalPartId = getReadableIdWithRevision(+ partId,+ revision+ );++ const isMade = children.length > 0;+ let itemId = id;++ if (itemId) {+ // Update existing item+ await trx+ .updateTable("item")+ .set({+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("externalIntegrationMapping")+ .where("entityType", "=", "item")+ .where("entityId", "=", itemId)+ .where("integration", "=", "onshapeData")+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .insertInto("externalIntegrationMapping")+ .values({+ entityType: "item",+ entityId: itemId,+ integration: "onshapeData",+ externalId: externalPartId,+ metadata: data.data,+ companyId,+ allowDuplicateExternalId: false+ })+ .onConflict((oc) =>+ oc+ .columns([+ "integration",+ "externalId",+ "entityType",+ "companyId"+ ])+ .where("allowDuplicateExternalId", "=", false)+ .doUpdateSet({+ entityId: itemId,+ metadata: data.data,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();+ } else {+ // Check if we've already created this part in this transaction+ itemId = newlyCreatedItemsByPartId.get(partId);++ if (!itemId) {+ // Create new item and part+ const item = await trx+ .insertInto("item")+ .values({+ readableId: partId,+ revision: revision ?? "0",+ name,+ type: "Part",+ unitOfMeasureCode: "EA",+ itemTrackingType: "Inventory",+ replenishmentSystem,+ defaultMethodType,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();++ itemId = item?.id;++ // Create OnShape mapping for the new item+ if (itemId) {+ await trx+ .insertInto("externalIntegrationMapping")+ .values({+ entityType: "item",+ entityId: itemId,+ integration: "onshapeData",+ externalId: externalPartId,+ metadata: data.data,+ companyId,+ allowDuplicateExternalId: false+ })+ .onConflict((oc) =>+ oc+ .columns([+ "integration",+ "externalId",+ "entityType",+ "companyId"+ ])+ .where("allowDuplicateExternalId", "=", false)+ .doUpdateSet({+ entityId: itemId,+ metadata: data.data,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();+ }++ await trx+ .insertInto("part")+ .values({+ id: partId,+ companyId,+ createdBy: userId+ })+ .onConflict((oc) =>+ oc.columns(["id", "companyId"]).doUpdateSet({+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();++ // Store the newly created item to avoid duplicate inserts+ if (itemId) {+ newlyCreatedItemsByPartId.set(partId, itemId);+ // Also update our existing items map for later reference+ existingItemsByItemId.set(itemId, {+ id: itemId,+ readableId: partId,+ readableIdWithRevision: getReadableIdWithRevision(+ partId,+ revision+ ),+ revision: revision ?? "0",+ unitOfMeasureCode: "EA",+ type: "Part"+ });+ }+ }+ }++ if (!itemId) throw new Error("Failed to create item");++ let materialMakeMethodId: string | undefined;+ const existingMakeMethod =+ existingMakeMethodsByItemId.get(itemId) ||+ newlyCreatedMakeMethodsByItemId.get(itemId);++ logger.info({+ action: "processing_item",+ itemId,+ partId,+ isMade,+ defaultMethodType,+ existingMakeMethod: existingMakeMethod ?? null+ });++ if (defaultMethodType === "Make to Order" || isMade) {+ if (existingMakeMethod) {+ if (existingMakeMethod.status === "Draft") {+ // Draft - use existing make method directly+ materialMakeMethodId = existingMakeMethod.id;+ } else {+ // Active - check if there's already a Draft we can use+ const existingDraft = await trx+ .selectFrom("makeMethod")+ .select(["id", "version"])+ .where("itemId", "=", itemId)+ .where("status", "=", "Draft")+ .where("companyId", "=", companyId)+ .orderBy("version", "desc")+ .executeTakeFirst();++ logger.info({+ action: "check_existing_draft",+ itemId,+ companyId,+ existingDraft: existingDraft ?? null+ });++ if (existingDraft) {+ // Use the existing Draft+ materialMakeMethodId = existingDraft.id;+ const makeMethodInfo: MakeMethodInfo = {+ id: existingDraft.id,+ itemId,+ version: Number(existingDraft.version),+ status: "Draft"+ };+ newlyCreatedMakeMethodsByItemId.set(+ itemId,+ makeMethodInfo+ );+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);+ } else {+ // Get max version across ALL make methods for this item+ const maxVersionRow = await trx+ .selectFrom("makeMethod")+ .select(["version"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .orderBy("version", "desc")+ .executeTakeFirst();++ const maxVersion = Number(maxVersionRow?.version ?? 0);+ const newVersion = maxVersion + 1;++ logger.info({+ action: "creating_child_draft",+ itemId,+ companyId,+ maxVersionRow: maxVersionRow ?? null,+ maxVersion,+ newVersion+ });++ const newMakeMethod = await trx+ .insertInto("makeMethod")+ .values({+ itemId,+ version: newVersion,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();++ if (newMakeMethod) {+ materialMakeMethodId = newMakeMethod.id;++ // Copy operations from active version to new draft+ await copyMakeMethodOperations(+ trx,+ existingMakeMethod.id,+ newMakeMethod.id,+ companyId,+ userId+ );++ // Update tracking maps+ const newMakeMethodInfo: MakeMethodInfo = {+ id: newMakeMethod.id,+ itemId,+ version: newVersion,+ status: "Draft"+ };+ newlyCreatedMakeMethodsByItemId.set(+ itemId,+ newMakeMethodInfo+ );+ existingMakeMethodsByItemId.set(+ itemId,+ newMakeMethodInfo+ );+ }+ }+ }+ } else {+ // No existing make method - check if trigger created one, or create new+ const triggerCreatedMakeMethod = await trx+ .selectFrom("makeMethod")+ .select(["id", "version", "status"])+ .where("itemId", "=", itemId)+ .executeTakeFirst();++ if (triggerCreatedMakeMethod) {+ materialMakeMethodId = triggerCreatedMakeMethod.id;+ const makeMethodInfo: MakeMethodInfo = {+ id: triggerCreatedMakeMethod.id,+ itemId,+ version: Number(triggerCreatedMakeMethod.version),+ status: triggerCreatedMakeMethod.status as+ | "Draft"+ | "Active"+ | "Archived"+ };+ newlyCreatedMakeMethodsByItemId.set(itemId, makeMethodInfo);+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);+ } else {+ // Create a new make method if needed+ const newMakeMethod = await trx+ .insertInto("makeMethod")+ .values({+ itemId,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();++ materialMakeMethodId = newMakeMethod?.id;++ if (materialMakeMethodId) {+ const makeMethodInfo: MakeMethodInfo = {+ id: materialMakeMethodId,+ itemId,+ version: 1,+ status: "Draft"+ };+ newlyCreatedMakeMethodsByItemId.set(+ itemId,+ makeMethodInfo+ );+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);+ }+ }+ }+ }++ await trx+ .insertInto("methodMaterial")+ .values({+ itemId,+ quantity: quantity ?? 1,+ makeMethodId: parentMakeMethodId,+ materialMakeMethodId,+ methodType: defaultMethodType,+ order: index,+ itemType: existingItemsByItemId.get(itemId)?.type ?? "Part",+ unitOfMeasureCode:+ existingItemsByItemId.get(itemId)?.unitOfMeasureCode ??+ "EA",+ companyId,+ createdBy: userId+ })+ .execute();++ if (materialMakeMethodId) {+ await trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "=", materialMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();++ for await (const child of children) {+ const childIndex = children.indexOf(child);+ await traverseTree(child, materialMakeMethodId, childIndex);+ }+ }+ }++ let index = 0;+ for await (const node of tree) {+ await traverseTree(node, activeMakeMethodId, index);+ index++;+ }+ });+ }++ return {+ success: true,+ makeMethodId: activeMakeMethodId+ };+ }+ }+ }++ // ── Service function helpers ────────────────────────────────────────────────++ /** The write's result, with the release lock's warning when release control only warns. */+ export function withLockNotice<T>(lock: LockCheck, result: T | CarbonError) {+ if (result instanceof CarbonError || !lock.warn) return result;+ return Object.assign({}, result, { notice: lock.message });+ }++ /** A change notice write's own refusal, passed through; anything else is internal. */+ export function changeNoticeRefusal(+ ctx: ServiceContext,+ error: { message: string; code?: string } | null,+ fallback: string+ ) {+ if (error?.message === changeNoticeUpdatedElsewhere) {+ return ctx.error("conflict", error.message);+ }+ if (error?.code === SERVICE_RULE_ERROR_CODE) {+ return ctx.error("rule", error.message);+ }+ return ctx.error("internal", fallback, error);+ }++ /**+ * Write a drag-sort of one make method's materials or operations: one+ * statement, scoped to the company and the method, all or nothing.+ */+ export async function reorderMethodRows(+ ctx: ServiceContext,+ table: "methodMaterial" | "methodOperation",+ updates: { id: string; order: number }[]+ ) {+ if (updates.length === 0) return { ids: [] as string[], notice: undefined };+ const companyId = ctx.company.id;+ // Both tables carry makeMethodId; the cast only gives supabase-js one table to type.+ const rows = await ctx.asCaller.supabase+ .from(table as "methodMaterial")+ .select("makeMethodId")+ .in(+ "id",+ updates.map((update) => update.id)+ )+ .eq("companyId", companyId);+ if (rows.error) {+ return ctx.error("internal", "Failed to update sort order", rows.error);+ }+ const [makeMethodId, ...others] = pluckUnique(+ rows.data,+ (row) => row.makeMethodId+ );+ if (+ !makeMethodId ||+ others.length > 0 ||+ rows.data.length !== updates.length+ ) {+ return ctx.error("rule", "The rows must belong to one make method");+ }++ const lock = await checkRevisionLock(ctx.asCaller.supabase, {+ kind: "makeMethod",+ id: makeMethodId,+ companyId+ });+ if (!lock.ok) return ctx.error("rule", lock.message);++ await updateSortOrder(ctx.asSystem.pg, {+ table,+ column: "order",+ companyId,+ userId: ctx.auditUserId,+ parent: { column: "makeMethodId", id: makeMethodId },+ updates: updates.map(({ id, order }) => ({ id, sortOrder: order }))+ });+ return {+ ids: updates.map((update) => update.id),+ notice: lock.warn ? lock.message : undefined+ };+ }++ /**+ * Why a job cannot be created from these records, or null: every id must be+ * this company's (the job is written with the service role), the item must+ * not be one an unreleased change notice holds (the job would take its draft+ * method), and a Make to Asset item must be able to complete to its asset.+ * The last is checked here, not only at release, so the form says why while+ * the item is still being chosen.+ */+ export async function jobCreationRefusal(+ ctx: ServiceContext,+ job: {+ itemId: string;+ quantity?: number;+ locationId?: string | null;+ customerId?: string | null;+ modelUploadId?: string | null;+ fixedAssetClassId?: string | null;+ fixedAssetId?: string | null;+ storageUnitId?: string | null;+ salesOrderId?: string | null;+ salesOrderLineId?: string | null;+ quoteId?: string | null;+ quoteLineId?: string | null;+ }+ ): Promise<CarbonError | null> {+ const owned = await productionPostings.requireOwnRecords(ctx, [+ ["item", job.itemId, "item"],+ ["location", job.locationId, "location"],+ ["customer", job.customerId, "customer"],+ ["modelUpload", job.modelUploadId, "model"],+ ["fixedAssetClass", job.fixedAssetClassId, "fixed asset class"],+ ["fixedAsset", job.fixedAssetId, "fixed asset"],+ ["storageUnit", job.storageUnitId, "storage unit"],+ ["salesOrder", job.salesOrderId, "sales order"],+ ["salesOrderLine", job.salesOrderLineId, "sales order line"],+ ["quote", job.quoteId, "quote"],+ ["quoteLine", job.quoteLineId, "quote line"]+ ]);+ if (owned) return owned;++ const unreleasedIssue = await getUnreleasedChangeOrderIssue(+ ctx.asSystem.supabase,+ { itemId: job.itemId, companyId: ctx.company.id }+ );+ if (unreleasedIssue) {+ return ctx.error("rule", `${unreleasedIssue} A job cannot be made for it.`);+ }++ if (job.fixedAssetClassId || job.fixedAssetId) {+ const item = await ctx.asSystem.supabase+ .from("item")+ .select("itemTrackingType")+ .eq("id", job.itemId)+ .eq("companyId", ctx.company.id)+ .single();+ const itemError = makeToAssetItemError({+ ...job,+ itemTrackingType: item.data?.itemTrackingType+ });+ if (itemError) return ctx.error("rule", itemError);+ }+ return null;+ }++ /**+ * Why a job's method cannot be saved onto make method `targetId`, or null:+ * the item's revision is released and release control enforces it, or a+ * change notice holds the method. The same lock as the items' Save Method.+ */+ export async function saveMethodRefusal(ctx: ServiceContext, targetId: string) {+ const lock = await checkRevisionLock(ctx.asSystem.supabase, {+ kind: "makeMethod",+ id: targetId,+ companyId: ctx.company.id+ });+ return lock.ok ? null : ctx.error("rule", lock.message);+ }++++/**++ * The bulk Update of the item tables (Parts, Materials, Tools, Consumables,++ * Services). Called by `x+/items+/update.tsx` with the selected items and by++ * the background bulk-action job (`~/utils/table-jobs.server`) with up to 100++ * items at a time.++ */++++export type BulkUpdateItemsResult = {++ /** Items updated. */++ done: number;++ /** Ids that are not an item of the company. */++ skipped: number;++ /** Items whose chunk failed. */++ failed: number;++ /** The first failure's message, or null. */++ error: string | null;++};++++/** An `.in()` filter rides in the request URL, so items go 100 at a time. */++const ITEM_BULK_CHUNK = 100;++++/**++ * Sets one field on many items. Writes as `client` (the user), and the++ * cascades through `db`. Each chunk commits on its own: a failed chunk leaves++ * the chunks before it applied, and the result counts both, so the caller can++ * say what was done.++ */++export async function bulkUpdateItems(++ client: SupabaseClient<Database>,++ db: Kysely<KyselyDatabase>,++ args: {++ itemIds: string[];++ field: ItemBulkUpdateField;++ value: string;++ companyId: string;++ userId: string;++ }++): Promise<BulkUpdateItemsResult> {++ const result: BulkUpdateItemsResult = {++ done: 0,++ skipped: 0,++ failed: 0,++ error: null++ };++ const ids = [...new Set(args.itemIds.filter(Boolean))];++ for (const chunk of chunkArray(ids, ITEM_BULK_CHUNK)) {++ // The writes below trust these ids (the itemCost insert names them), so++ // keep only the company's own items.++ const items = await client++ .from("item")++ .select("id")++ .in("id", chunk)++ .eq("companyId", args.companyId);++ if (items.error) {++ logger.error("Failed to read the items of a bulk update", {++ companyId: args.companyId,++ error: items.error++ });++ result.failed += chunk.length;++ result.error ??= items.error.message;++ continue;++ }++ const itemIds = items.data.map((item) => item.id);++ result.skipped += chunk.length - itemIds.length;++ if (itemIds.length === 0) continue;++++ const error = await updateItemsChunk(client, db, { ...args, itemIds });++ if (error) {++ logger.error("Failed to bulk update items", {++ companyId: args.companyId,++ field: args.field,++ error++ });++ result.failed += itemIds.length;++ result.error ??= error;++ } else {++ result.done += itemIds.length;++ }++ }++ return result;++}++++/** One chunk of `bulkUpdateItems`. Answers the error message, or null. */++async function updateItemsChunk(++ client: SupabaseClient<Database>,++ db: Kysely<KyselyDatabase>,++ {++ itemIds,++ field,++ value,++ companyId,++ userId++ }: {++ itemIds: string[];++ field: ItemBulkUpdateField;++ value: string;++ companyId: string;++ userId: string;++ }++): Promise<string | null> {++ const updatedAt = datetime.timestamp();++ switch (field) {++ case "itemTrackingType": {++ const newType = value as InventoryItemType;++ const update = await client++ .from("item")++ .update({ itemTrackingType: newType, updatedBy: userId, updatedAt })++ .in("id", itemIds)++ .eq("companyId", companyId);++ if (update.error) return update.error.message;++ try {++ await cascadeItemTrackingType(db, {++ itemIds,++ companyId,++ newType,++ userId++ });++ } catch (err) {++ logger.error("Failed to cascade item tracking type", {++ companyId,++ error: err++ });++ return "Failed to cascade tracking flags";++ }++ return null;++ }++ case "replenishmentSystem":++ case "defaultMethodType":++ case "sourcingType": {++ // These three fields are interlocked and each mirror down to the item's++ // method materials. updateItemMethodAndSourcing applies the item write++ // and the cascade in one transaction, so they can't be left half-applied.++ const { itemUpdate, cascade } = deriveItemMethodUpdate(field, value);++ try {++ await updateItemMethodAndSourcing(db, {++ itemIds,++ companyId,++ userId,++ itemUpdate,++ cascade++ });++ } catch (err) {++ logger.error("Failed to update item method/sourcing", {++ companyId,++ field,++ error: err++ });++ return "Failed to update item";++ }++ return null;++ }++ case "itemPostingGroupId": {++ // One read for the chunk, then one update of the items that have an++ // itemCost row and one insert for the rest.++ const existing = await client++ .from("itemCost")++ .select("itemId")++ .in("itemId", itemIds)++ .eq("companyId", companyId);++ if (existing.error) return existing.error.message;++ const withCost = new Set(existing.data.map((row) => row.itemId));++ const itemPostingGroupId = value || null;++++ if (withCost.size > 0) {++ const update = await client++ .from("itemCost")++ .update({ itemPostingGroupId, updatedBy: userId, updatedAt })++ .in("itemId", [...withCost])++ .eq("companyId", companyId);++ if (update.error) return update.error.message;++ }++++ const missing = itemIds.filter((itemId) => !withCost.has(itemId));++ if (missing.length > 0) {++ const insert = await client.from("itemCost").insert(++ missing.map((itemId) => ({++ itemId,++ itemPostingGroupId,++ costingMethod: "Standard" as const,++ standardCost: 0,++ unitCost: 0,++ costIsAdjusted: false,++ companyId,++ createdBy: userId,++ updatedBy: userId,++ createdAt: updatedAt,++ updatedAt++ }))++ );++ if (insert.error) return insert.error.message;++ }++ return null;++ }++ }++}diff --cc apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsxindex 49d749e257,b255afe089..1bc23a1204--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx@@@ -60,11 -62,10 +60,11 @@@ importimport { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import { methodType } from "~/modules/shared";+ import { methodType } from "~/modules/shared/shared.models";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { itemTrackingTypes } from "../../items.models";diff --cc apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsxindex 5984e7e92c,2125654957..4ef7f1f211--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx@@@ -72,12 -74,11 +72,12 @@@ import { Enumerable } from "~/componentimport { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { useFilters } from "~/components/Table/components/Filter/useFilters";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import { methodType } from "~/modules/shared";+ import { methodType } from "~/modules/shared/shared.models";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { itemTrackingTypes } from "../../items.models";diff --cc apps/erp/app/modules/items/ui/Parts/PartsTable.tsxindex 83088c1e76,67a298eb58..200ed5754e--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx@@@ -66,11 -68,10 +66,11 @@@ import { Enumerable } from "~/componentimport { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import { methodType } from "~/modules/shared";+ import { methodType } from "~/modules/shared/shared.models";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import {diff --cc apps/erp/app/modules/items/ui/Services/ServicesTable.tsxindex 068913f2a7,0590591133..bbd8f39ad8--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx@@@ -62,11 -64,10 +62,11 @@@ import { Enumerable } from "~/componentimport { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import { methodType } from "~/modules/shared";+ import { methodType } from "~/modules/shared/shared.models";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { serviceReplenishmentSystems } from "../../items.models";diff --cc apps/erp/app/modules/items/ui/Tools/ToolsTable.tsxindex 3012a68214,22d6bf2219..54322cdcaa--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx@@@ -66,11 -68,10 +66,11 @@@ import { Enumerable } from "~/componentimport { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import { methodType } from "~/modules/shared";+ import { methodType } from "~/modules/shared/shared.models";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import {diff --cc apps/erp/app/modules/people/people.service.tsindex 1e97c29aae,f29e9c5d7c..64838e1542--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@@ -9,11 -10,11 +10,11 @@@ import { datetime, searchFilter } fromimport { getDayOfWeek, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";- import type { DataType } from "~/modules/shared";- import type { Employee } from "~/modules/users";+ import type { DataType } from "~/modules/shared/types";+ import type { Employee } from "~/modules/users/types";import { getEmployees } from "~/modules/users/users.service";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import type {departmentValidator,@@@ -104,11 -99,6 +99,10 @@@ async function getAttributes.order("sortOrder", { foreignTable: "userAttribute", ascending: true });}+export const ATTRIBUTE_CATEGORIES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getAttributeCategories(client: SupabaseClient<Database>,companyId: string,@@@ -256,11 -239,6 +241,10 @@@ export async function getHolidayreturn client.from("holiday").select("*").eq("id", holidayId).single();}+export const HOLIDAYS_PAGING: Paging = {+ defaultSorts: [{ column: "date", ascending: true }]+};+- /** @mcp read */export async function getHolidays(client: SupabaseClient<Database>,companyId: string,@@@ -432,11 -408,6 +412,10 @@@ export async function getShift.single();}+export const SHIFTS_PAGING: Paging = {+ defaultSorts: [{ column: "locationId", ascending: true }]+};+- /** @mcp read */export async function getShifts(client: SupabaseClient<Database>,companyId: string,@@@ -1026,11 -987,6 +993,10 @@@ export async function getTimeCardEntriereturn query;}+export const TIMECARD_ENTRIES_PAGING: Paging = {+ defaultSorts: [{ column: "clockIn", ascending: false }]+};+- /** @mcp read */export async function getTimecardEntries(client: SupabaseClient<Database>,companyId: string,@@@ -1042,12 -998,12 +1008,10 @@@.eq("companyId", companyId);if (args.search) {- query = query.or(- `firstName.ilike.%${args.search}%,lastName.ilike.%${args.search}%`- );+ query = query.or(searchFilter(["firstName", "lastName"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "clockIn", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, TIMECARD_ENTRIES_PAGING);return query;}diff --cc apps/erp/app/modules/production/AGENTS.mdindex b988acd17e,c01dfb52c7..e3ab7acc3d--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@@ -10,9 -10,10 +10,10 @@@ Work orders (jobs), scheduling, routing- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.- - **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` server-function intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, server-function-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` server function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the server function's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the server function uses ids through the same value-agnostic fold, so they always agree. The server function's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the server function is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` server function — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch server-function refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped; `bulkReleaseBatches` in `bulk-actions.server.ts`. With `{ allMatching }` in place of ids, the route starts the background `table-bulk-action` job instead — at most 2,000 matching batches, `ALL_MATCHING_RELEASE_LIMIT` in `utils/table-jobs.ts`). Deleting from ERP = the server function's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Planned or Active ids to the `batches/dissolve` route (`bulkDissolveBatches`: one server-function dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve; a Completing or Completed batch is skipped; `{ allMatching }` runs it in the background job), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` server function. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.-- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` posting intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatches` → `releaseBatchMemberJobs` → `releaseCheckedJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, posting-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` posting (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the posting's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the posting uses ids through the same value-agnostic fold, so they always agree. The posting's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the posting is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` posting — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, the same `releaseBatches` the single-batch `batching.update` release branch calls: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`, member reads in one query; per-batch posting refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the posting's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one posting dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` posting. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.++- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` posting intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatches` → `releaseBatchMemberJobs` → `releaseCheckedJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, posting-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` posting (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the posting's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the posting uses ids through the same value-agnostic fold, so they always agree. The posting's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the posting is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` posting — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, the same `releaseBatches` the single-batch `batching.update` release branch calls: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`, member reads in one query; per-batch posting refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the posting's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one posting dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` posting. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.+ - **Outdated model** — an instruction keeps the `modelUploadId` it was made from; when its part's `item.modelUploadId` is another model (a new upload, a re-push from Onshape), the page shows a notice over the viewer with a link to a new instruction for the part. Derived on read (`getAssemblyInstruction` embeds `item(modelUploadId)`), nothing stored. A new version is no answer: `copyAssemblyInstructionAsVersion` copies the old model and its steps, whose `componentNodeIds` name that model's nodes.- **Sub-assemblies** — a header row (`assemblyInstructionStep.isSubAssembly`, no parts of its own) plus the steps whose `parentStepId` is that header, stored directly BEFORE it in `sortOrder` (play order); the header's `usedInStepId` is the later step that fits the finished unit (NULL = it joins the main build at the header). One level only. Every structural write (`makeAssemblySubAssembly`, `insertAssemblyInstructionStep`, `updateAssemblySubAssembly`, `ungroupAssemblySubAssembly`, `deleteAssemblySubAssembly`, `updateAssemblyInstructionStepOrder`) is a Kysely transaction that locks the instruction, applies the change in memory, checks `validateSubAssemblies` and writes the new order — never a partial update. Header rows are never copied into job steps. The step that uses a sub-assembly never re-lists its parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/subassembly.ts`.- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly; the engine lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.@@@ -92,9 -106,20 +106,20 @@@ pnpm --filter erp tes## Key Service Functions- - `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured+ - `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales/sales.utils`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured- `getJob` / `getJobs` / `getJobMethodTree` / `getJobMethodTreeArray` — job reads with method hierarchy- - `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`, which calls `bulkReleaseJobs` in `bulk-actions.server.ts`; with `{ allMatching }` in place of ids, or more than 25 selected ids (`fitsOneRequest`), it starts the background `table-bulk-action` job, at most 2,000 jobs; the job carries the supplier→PO map from one slice of 25 to the next, so later jobs go on the PO an earlier slice made). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`-- `releaseJobs` (`production.server.ts`, published as `production_releaseJobs`) — the one release operation: the job page's Release dialog (`x+/job+/$jobId.release.tsx`, through `useJobRelease`), the jobs table's bulk **Release Jobs** (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`), the planning page's Release (`useJobPlanningRelease`) and the API/MCP all run it. Per selected job: a job that is not Draft/Planned is listed in `skipped`; the dialog's supplier picks (`supplierProcessByOperationId`) are saved on the operations first (`stampSupplierChoices`, validated: the operation belongs to the jobs, the supplier process to its process); then `getJobReleaseReadiness` once for the selection (every read through `fetchAllByIds`, pinned by `test/job-release-readiness.test.ts`) and `jobReleaseProblems` per job — nothing to make, manufacturing blocked, an assembly with no operations, an outside operation without a supplier, a Make to Asset job that cannot complete to its asset (`makeToAssetReleaseError`), and, when no `purchaseOrdersBySupplierId` was sent, a supplier with Draft POs to choose from. A job with a problem is named in `failed`; the rest go through `releaseCheckedJobs` one by one on a shared supplier→PO map (a supplier's first new PO is reused), then `runLocationSchedule` runs once per location AFTER every status flip. Returns `{ released, warnings, failed, skipped, scheduled }`; a job released whose POs failed is in `released` and `warnings`. Pinned by `test/release-jobs.test.ts`.++- `releaseJobs` (`production.server.ts`, published as `production_releaseJobs`) — the one release operation: the job page's Release dialog (`x+/job+/$jobId.release.tsx`, through `useJobRelease`), the jobs table's bulk **Release Jobs** (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`), the planning page's Release (`useJobPlanningRelease`) and the API/MCP all run it. Per selected job: a job that is not Draft/Planned is listed in `skipped`; the dialog's supplier picks (`supplierProcessByOperationId`) are saved on the operations first (`stampSupplierChoices`, validated: the operation belongs to the jobs, the supplier process to its process); then `getJobReleaseReadiness` once for the selection (every read through `fetchAllByIds`, pinned by `test/job-release-readiness.test.ts`) and `jobReleaseProblems` per job — nothing to make, manufacturing blocked, an assembly with no operations, an outside operation without a supplier, a Make to Asset job that cannot complete to its asset (`makeToAssetReleaseError`), and, when no `purchaseOrdersBySupplierId` was sent, a supplier with Draft POs to choose from. A job with a problem is named in `failed`; the rest go through `releaseCheckedJobs` one by one on a shared supplier→PO map (a supplier's first new PO is reused), then `runLocationSchedule` runs once per location AFTER every status flip. Returns `{ released, warnings, failed, skipped, scheduled }`; a job released whose POs failed is in `released` and `warnings`. Pinned by `test/release-jobs.test.ts`. More than 25 selected jobs, or "every matching job" (up to 2,000), go to the background `table-bulk-action` job instead (`x+/job+/release.tsx`): it releases slices of 25 through `releaseCheckedJobs` (`utils/production-bulk-actions.server.ts`, a system context on behalf of the user) and carries the supplier→PO map from one slice to the next, so later jobs go on the PO an earlier slice made.+ - `releaseCheckedJobs` (`production.server.ts`, unpublished) — the step every release shares, for jobs already checked: recalc, MRP (a failure is logged and never blocks), the guarded Ready flip (`updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` returns `updated: false` when someone cancelled or released the job during the recalc/MRP, so the release stops; pinned by `test/job-status-guard.test.ts`), outside-operation POs, `releasedDate` (a failed write is reported, since nothing else writes it). Returns `releasedJobIds`, the PO map and a `failure`.+ - `releaseBatches` (`production.server.ts`, published as `production_releaseBatches`) — releases Planned batches: member jobs through `releaseBatchMemberJobs` (all-or-nothing on `jobReleaseProblems`), then `releaseJobOperationBatch`, then `notifyScheduleInputsChanged`. Used by the batch drawer (`batching.update` release intent) and the batches table's bulk Release (`production+/batches.release.tsx`). `updateJobStatus` and `releaseJobOperationBatch` are NOT published: each alone skips what release does.+ - **Every path to Ready.** Each refuses a job that fails `jobReleaseProblems`, which includes strict backflush lines with no storage unit (`materialsWithoutStorageUnit` from `getJobReleaseReadiness`):++ | Path | Checks |+ |---|---|+ | `releaseJobs` (Release dialog, bulk release, planning, API/MCP) | `jobReleaseProblems` per job, then `releaseCheckedJobs` |+ | Batch release (`releaseBatchMemberJobs`) | `jobReleaseProblems`, all-or-nothing, then `releaseCheckedJobs` |+ | Kanban scan with `autoRelease` (`scanKanban`, `inventory.server.ts`) | `jobReleaseProblems`, then `releaseCheckedJobs` as the system on behalf of the scanner (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened. A job whose Get Method failed is not released either, and the flash says so |++ `resumeJob` (Paused → Ready) is not a release. `updateJobStatus` is not published, so the API cannot set Ready without the checks. No SQL function sets a job to Ready (the SQL writes of `'Ready'` are on `jobOperation`). A new path to Ready must run `jobReleaseProblems` before `releaseCheckedJobs`.- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation- `getJobOrderStatusMap` — procurement status indicators per materialdiff --cc apps/erp/app/modules/production/production.models.tsindex 1270b9339b,d748a41120..13503a9206--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@@ -110,37 -109,18 +110,49 @@@ export function isJobEditableFromPlanni// The one definition lives in @carbon/utils, shared with the OEE sync.export { isJobLocked, JOB_LOCKED_STATUSES } from "@carbon/utils";+/** The statuses the jobs table's bulk Delete acts on. "Due Today" and+ * "Overdue" are deprecated statuses that old jobs can still hold. */+export const JOB_BULK_DELETABLE_STATUSES = [+ "Draft",+ "Planned",+ "Due Today",+ "Overdue"+] as const;++export function isJobBulkDeletable(status: string | null | undefined): boolean {+ return JOB_BULK_DELETABLE_STATUSES.some((allowed) => allowed === status);+}++/** The statuses the jobs table's bulk Release acts on. */+export function isJobBulkReleasable(+ status: string | null | undefined+): boolean {+ return status === "Draft" || status === "Planned";+}++/** Release is the Planned → Active flip of an operation batch. */+export function isBatchReleasable(status: string | null | undefined): boolean {+ return status === "Planned";+}++/** A started batch must be completed, not dissolved; a completed one is+ * history. */+export function isBatchDissolvable(status: string | null | undefined): boolean {+ return status === "Planned" || status === "Active";+}++ export const JOB_LOCKED_MESSAGE =+ "Cannot modify a locked job. Reopen it first.";++ /** The statuses a job can be cancelled from. */+ export const CANCELLABLE_JOB_STATUSES = [+ "Draft",+ "Planned",+ "Ready",+ "In Progress",+ "Paused"+ ] as const;+export const DATE_COLUMN_SENTINELS = ["unscheduled","next-week",diff --cc apps/erp/app/modules/production/production.service.tsindex c17f1686a8,052642b0d7..4051e49fde--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@@ -44,17 -146,30 +146,35 @@@ importindexAssemblyGraph,validateSubAssemblies} from "@carbon/viewer";- import { isPlanFlagged } from "@carbon/viewer/steps";- import { parseDate } from "@internationalized/date";+ import {+ getDayOfWeek,+ parseDate,+ parseDateTime,+ toCalendarDateTime+ } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { ExpressionBuilder } from "kysely";- import { sql } from "kysely";+ import { type QueryCreator, sql, type Transaction } from "kysely";import { nanoid } from "nanoid";- import type { z } from "zod";+ import { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";+ import {+ assertCompanyRecords,+ attributesContain,+ chunked,+ getCurrentAccountingPeriod,+ getDefaultPostingGroup,+ getStorageUnitId,+ TIME_ENTRY_BEFORE_CUTOVER_ERROR+ } from "~/modules/shared/shared.service";import type { StorageItem } from "~/types";++import {++ type BulkDeleteResult,++ bulkDeleteByStatus++} from "~/utils/bulk-delete.server";+import type { Cursor } from "~/utils/cursor";+ import { makeDurations } from "~/utils/duration";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import {getGenericFilter,LIST_COUNT,@@@ -109,10 -224,12 +230,13 @@@ importgetAssemblyModelState,isJobLocked,isJobOrderStatusHidden,++ JOB_BULK_DELETABLE_STATUSES,+ JOB_LOCKED_MESSAGE,JOB_LOCKED_STATUSES,JOB_SUPPLY_STATUS_PRIORITY,+ makeToAssetReleaseError,motionSchema,- orientationSchema,+ type orientationSchema,PLANNING_EDITABLE_JOB_STATUSES,PO_STATUS_PRIORITY,WEEKDAYS_MONDAY_FIRST@@@ -1264,11 -1347,6 +1354,10 @@@ export async function getProductionEven.eq("jobOperation.jobId", jobId);}+export const JOBS_PAGING: Paging = {+ defaultSorts: [{ column: "jobId", ascending: false }]+};+- /** @mcp read */export async function getJobs(client: SupabaseClient<Database>,companyId: string,@@@ -1972,15 -1964,6 +1974,14 @@@ export async function getJobOperation.single();}+export const JOB_OPERATIONS_PAGING: Paging = {+ defaultSorts: [+ { column: "description", ascending: true },+ { column: "order", ascending: true },+ { column: "createdAt", ascending: false }+ ]+};+- /** @mcp read */export async function getJobOperations(client: SupabaseClient<Database>,jobId: string,@@@ -2106,11 -2075,6 +2102,10 @@@ export async function getJobOperationsB.order("order", { ascending: true });}+export const JOB_OPERATION_STEP_RECORDS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getJobOperationStepRecords(client: SupabaseClient<Database>,jobId: string,@@@ -2202,11 -2159,6 +2192,10 @@@ export async function getProcedureVersi.order("version", { ascending: false });}+export const PROCEDURES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getProcedures(client: SupabaseClient<Database>,companyId: string,@@@ -2262,16 -2213,6 +2249,15 @@@ export async function getProductionEven.single();}+// The start time was a fixed order ahead of every sort. The cursor must follow+// each column the list orders by, so it is the first default sort instead.+export const PRODUCTION_EVENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "startTime", ascending: true },+ { column: "createdAt", ascending: false }+ ]+};+- /** @mcp read */export async function getProductionEvents(client: SupabaseClient<Database>,jobOperationIds: string[],@@@ -2282,17 -2223,21 +2268,17 @@@.select("*, jobOperation(description, jobMakeMethod(parentMaterialId, item(readableIdWithRevision)))",{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: listCount(args)})- .in("jobOperationId", jobOperationIds)- .order("startTime", { ascending: true });+ .in("jobOperationId", jobOperationIds);if (args?.search) {- query = query.or(`jobOperation.description.ilike.%${args.search}%`);+ query = query.or(searchFilter(["jobOperation.description"], args.search));}- if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);- }+ query = setGenericQueryFilters(query, args ?? {}, PRODUCTION_EVENTS_PAGING);return query;}@@@ -2345,17 -2255,6 +2296,16 @@@ export async function getProductionEven.order("startTime", { ascending: true });}+// What the row's Order / Make button offers (the grid RPC's orderQuantity,+// from MRP's open new-supply actions), then the part number so a page is+// stable when many rows have nothing to order.+export const PRODUCTION_PLANNING_PAGING: Paging = {+ defaultSorts: [+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }+ ]+};+- /** @mcp read */export async function getProductionPlanning(client: SupabaseClient<Database>,locationId: string,@@@ -2406,11 -2310,6 +2356,10 @@@return query;}+export const PRODUCTION_PROJECTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+- /** @mcp read */export async function getProductionProjections(client: SupabaseClient<Database>,locationId: string,@@@ -2456,11 -2355,6 +2404,10 @@@ export async function getProductionQuan.single();}+export const PRODUCTION_QUANTITIES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getProductionQuantities(client: SupabaseClient<Database>,jobOperationIds: string[],@@@ -2543,11 -2435,6 +2487,10 @@@ export async function getScrapReason.single();}+export const SCRAP_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getScrapReasons(client: SupabaseClient<Database>,companyId: string,@@@ -6693,11 -6618,6 +6675,10 @@@ export async function getUnbatchedBatch.not("job.status", "in", "(Completed,Closed,Cancelled)");}+export const JOB_OPERATION_BATCHES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getJobOperationBatches(client: SupabaseClient<Database>,companyId: string,@@@ -7410,46 -7332,16 +7406,44 @@@ function assemblyInstructionsQueryif (args.itemId) {query = query.eq("itemId", args.itemId);}- if (args.limit) {- query = query.limit(args.limit);- }- if (args.offset) {- query = query.range(args.offset, args.offset + (args.limit ?? 25) - 1);+ return query;+}+- /** @mcp read */+export async function getAssemblyInstructions(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ search?: string;+ status?: (typeof assemblyInstructionStatuses)[number];+ itemId?: string;+ limit?: number;+ offset?: number;}+) {+ let query = assemblyInstructionsQuery(client, args, LIST_COUNT);+ // With only `limit`, the read starts at offset 0.+ query = setGenericQueryFilters(+ query,+ { limit: args.limit, offset: args.offset ?? 0 },+ ASSEMBLY_INSTRUCTIONS_PAGING+ );+ return query;+}- return query.order("updatedAt", { ascending: false, nullsFirst: false });+/**+ * One cursor page of the assembly instructions list (`limit + 1` rows for+ * `toPage`). Not an MCP tool: MCP pages by offset through+ * `getAssemblyInstructions`. Only the first page counts.+ */+export async function getAssemblyInstructionsPage(+ client: SupabaseClient<Database>,+ args: AssemblyInstructionsScope & Partial<GenericQueryFilters>+) {+ let query = assemblyInstructionsQuery(client, args, listCount(args));+ query = setGenericQueryFilters(query, args, ASSEMBLY_INSTRUCTIONS_PAGING);+ return query;}- /** @mcp read */export async function getAssemblyInstructionsForItem(client: SupabaseClient<Database>,itemId: string,@@@ -11717,3 -11362,13690 +11464,13722 @@@ export async function createJobDocumentname: args.name});}+ /** The `shift` rows returned by getShiftsWithTimes (weekday flags + times). */+ type ShiftRow = {+ startTime: string | null;+ endTime: string | null;+ monday: boolean | null;+ tuesday: boolean | null;+ wednesday: boolean | null;+ thursday: boolean | null;+ friday: boolean | null;+ saturday: boolean | null;+ sunday: boolean | null;+ };++ // dayOfWeek 0 = Sunday .. 6 = Saturday — the ladder's convention, matching the+ // scheduler's own location-shift mapping (master-data-provider.expandShiftDays).+ const WEEKDAY_FLAGS = [+ "sunday",+ "monday",+ "tuesday",+ "wednesday",+ "thursday",+ "friday",+ "saturday"+ ] as const;++ /**+ * Non-working intervals inside [windowStartMs, windowEndMs) for the forecast+ * board's shading — the complement of the plant's operating hours. Uses the+ * SAME availability ladder the scheduler uses (the location's shifts if any,+ * else the stock Mon–Fri 08:00–16:00 week in the plant timezone), so the bars+ * and the shaded background can never disagree. Location-level, not+ * per-work-center: one plant calendar behind every lane. Per-WC shifts /+ * `alwaysOn` are a deliberate follow-up (see #3b).+ */+ export function getForecastNonWorkingIntervals(args: {+ timeZone: string;+ shifts: ShiftRow[];+ windowStartMs: number;+ windowEndMs: number;+ }): { start: number; end: number }[] {+ const { timeZone, shifts, windowStartMs, windowEndMs } = args;++ const locationShiftRows: LadderShiftRow[] = [];+ for (const shift of shifts) {+ if (!shift.startTime || !shift.endTime) continue;+ for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {+ const flag = WEEKDAY_FLAGS[dayOfWeek];+ if (!flag || !shift[flag]) continue;+ locationShiftRows.push({+ dayOfWeek,+ startTime: String(shift.startTime),+ endTime: String(shift.endTime),+ timezone: timeZone+ });+ }+ }++ const working = resolveLocationWindows({+ timezone: timeZone,+ locationShiftRows,+ rangeStart: windowStartMs,+ rangeEnd: windowEndMs+ });++ return subtractIntervals(+ [{ start: windowStartMs, end: windowEndMs }],+ working+ ).map((w) => ({ start: w.start, end: w.end }));+ }+ type CapacityOperation = {+ workCenterId: string | null;+ dueDate: string | null;+ setupTime?: number;+ setupUnit?: string;+ laborTime?: number;+ laborUnit?: string;+ machineTime?: number;+ machineUnit?: string;+ operationQuantity: number | null;+ };++ type CapacityReservation = {+ resourceId: string;+ startAt: string;+ endAt: string;+ workHours: number | null;+ };++ /** A location shift reduced to its per-day hours and which weekdays it runs. */+ type CapacityShift = {+ id: string;+ /** shift hours per day (start→end duration, or the location default). */+ hours: number;+ /** 7 weekday flags, Sunday-first (index 0 = Sunday … 6 = Saturday). */+ runsOn: boolean[];+ };++ // Rung 3 of the ladder: no shifts anywhere → stock Mon–Fri, 8h/day. Mirrors the+ // engine's stock week (08:00–16:00 = 8h) so machine and people capacity assume+ // the same default day.+ const FALLBACK_SHIFT_HOURS = 8;++ /**+ * DAY-granularity mirror of the engine's machine-availability ladder, for the+ * Capacity view's Available series. The engine+ * (`packages/planning/src/scheduling/machine-availability.ts`)+ * owns the AUTHORITATIVE wall-clock ladder; this is DISPLAY math and resolves the+ * same rungs at day granularity.+ *+ * Per work center, per week date, resolved in order:+ * 1. `alwaysOn` → 24h (lights-out).+ * 2. explicit `workCenterShift` rows → Σ (shift hours whose weekday flag covers+ * that date) over the work center's shifts.+ * 3. no WC rows but the location has shifts → the same Σ over the location's+ * shifts.+ * 4. no shifts anywhere → 8h on Mon–Fri, 0 on the weekend.+ */+ export function getWorkCenterCalendarHoursByDay(args: {+ workCenters: { id: string; alwaysOn: boolean }[];+ workCenterShifts: { workCenterId: string; shiftId: string }[];+ locationShifts: CapacityShift[];+ weekDates: string[];+ }): Map<string, Map<string, number>> {+ const { workCenters, workCenterShifts, locationShifts, weekDates } = args;++ const shiftById = new Map(locationShifts.map((shift) => [shift.id, shift]));+ const shiftIdsByWorkCenter = new Map<string, string[]>();+ for (const link of workCenterShifts) {+ const list = shiftIdsByWorkCenter.get(link.workCenterId);+ if (list) list.push(link.shiftId);+ else shiftIdsByWorkCenter.set(link.workCenterId, [link.shiftId]);+ }++ // weekday index per week date — a plain calendar date, so timezone-independent+ const dowByDate = weekDates.map((day) =>+ getDayOfWeek(parseDate(day), "en-US")+ );++ const sumShiftHours = (shifts: CapacityShift[], dow: number) =>+ shifts.reduce(+ (sum, shift) => (shift.runsOn[dow] ? sum + shift.hours : sum),+ 0+ );++ const result = new Map<string, Map<string, number>>();+ for (const workCenter of workCenters) {+ const wcShiftIds = shiftIdsByWorkCenter.get(workCenter.id) ?? [];+ const wcShifts = wcShiftIds.flatMap((id) => {+ const shift = shiftById.get(id);+ return shift ? [shift] : [];+ });+ const byDate = new Map<string, number>();+ weekDates.forEach((day, i) => {+ const dow = dowByDate[i] ?? 0;+ let hours: number;+ if (workCenter.alwaysOn) {+ hours = 24;+ } else if (wcShifts.length > 0) {+ hours = sumShiftHours(wcShifts, dow);+ } else if (locationShifts.length > 0) {+ hours = sumShiftHours(locationShifts, dow);+ } else {+ hours = dow === 0 || dow === 6 ? 0 : FALLBACK_SHIFT_HOURS;+ }+ byDate.set(day, hours);+ });+ result.set(workCenter.id, byDate);+ }+ return result;+ }++ /**+ * The Capacity view's week buckets.+ *+ * Demand = open job-operation hours by due date (overdue lands in `pastDue`,+ * like the classic capacity board's Past Weeks column). Scheduled = each+ * reservation's actual work content distributed across its wall-clock span —+ * a reservation holds the station for its full span (including idle+ * overnight stretches), so distributing `workHours` keeps a spanning op from+ * reading as 24h/day. Day boundaries come from the plant's calendar via+ * `CalendarDate.toDate(tz)` so DST weeks bucket correctly.+ */+ export function buildPeopleCapacityBuckets(args: {+ weekDates: string[];+ timezone: string;+ operations: CapacityOperation[];+ reservations: CapacityReservation[];+ /** per-work-center calendar hours (the ladder above) — clamps null-workHours reservations. */+ calendarHoursByWorkCenter: Map<string, Map<string, number>>;+ }): {+ demandByWorkCenter: Record<+ string,+ { pastDue: number; days: Record<string, number> }+ >;+ scheduledByWorkCenter: Record<string, Record<string, number>>;+ } {+ const {+ weekDates,+ timezone,+ operations,+ reservations,+ calendarHoursByWorkCenter+ } = args;+ const weekStartDate = weekDates[0];++ const demandByWorkCenter: Record<+ string,+ { pastDue: number; days: Record<string, number> }+ > = {};+ for (const operation of operations) {+ if (!operation.workCenterId || !operation.dueDate) continue;+ const durations = makeDurations(operation);+ const hours =+ (durations.setupDuration ++ durations.laborDuration ++ durations.machineDuration) /+ HOUR_MS;+ if (hours <= 0) continue;+ const bucket = (demandByWorkCenter[operation.workCenterId] ??= {+ pastDue: 0,+ days: {}+ });+ if (operation.dueDate < weekStartDate) {+ bucket.pastDue += hours;+ } else {+ bucket.days[operation.dueDate] =+ (bucket.days[operation.dueDate] ?? 0) + hours;+ }+ }++ // day boundaries on the plant's calendar, computed once (not per reservation)+ const dayBounds = weekDates.map((day) => {+ const dayDate = parseDate(day);+ return {+ day,+ startMs: dayDate.toDate(timezone).getTime(),+ endMs: dayDate.add({ days: 1 }).toDate(timezone).getTime()+ };+ });++ const scheduledByWorkCenter: Record<string, Record<string, number>> = {};+ for (const reservation of reservations) {+ const startMs = new Date(reservation.startAt).getTime();+ const endMs = new Date(reservation.endAt).getTime();+ const spanMs = endMs - startMs;+ if (spanMs <= 0) continue;++ let workMs: number;+ if (reservation.workHours != null) {+ workMs = reservation.workHours * HOUR_MS;+ } else {+ // Legacy rows carry no measured work content, so the old code counted the+ // full wall-clock span — which reads as 24h/day for an op that idles+ // overnight. Clamp to the calendar hours actually available at this work+ // center over the days the reservation spans.+ const dayHours = calendarHoursByWorkCenter.get(reservation.resourceId);+ let calendarMsWithinSpan = 0;+ for (const { day, startMs: dayStartMs, endMs: dayEndMs } of dayBounds) {+ const overlapMs =+ Math.min(endMs, dayEndMs) - Math.max(startMs, dayStartMs);+ if (overlapMs > 0) {+ calendarMsWithinSpan += (dayHours?.get(day) ?? 0) * HOUR_MS;+ }+ }+ workMs = Math.min(spanMs, calendarMsWithinSpan);+ }++ for (const { day, startMs: dayStartMs, endMs: dayEndMs } of dayBounds) {+ const overlapMs =+ Math.min(endMs, dayEndMs) - Math.max(startMs, dayStartMs);+ if (overlapMs > 0) {+ const byDay = (scheduledByWorkCenter[reservation.resourceId] ??= {});+ byDay[day] =+ (byDay[day] ?? 0) + (overlapMs / spanMs) * (workMs / HOUR_MS);+ }+ }+ }++ return { demandByWorkCenter, scheduledByWorkCenter };+ }+ // The geometry (assembler) service backs model conversion and motion planning.+ // When it's unreachable those actions can't run, so loaders probe its health and+ // the UI soft-gates the assembler-dependent controls. Result cached so a+ // navigation burst doesn't fan out one probe per route.+ //+ // The default deployment is a scale-to-zero Lambda: a cold /health takes ~2-5s+ // to init, so the probe timeout must outlast a cold start (the old 2s abort+ // read every cold service as down). Healthy sticks longer than unhealthy —+ // a failed probe usually WARMED the service (the request went through; we just+ // stopped waiting), so re-probe quickly instead of pinning "down" for 15s.+ const ASSEMBLER_HEALTHY_TTL_MS = 60_000;++ const ASSEMBLER_UNHEALTHY_TTL_MS = 5_000;++ const ASSEMBLER_HEALTH_TIMEOUT_MS = 10_000;++ let assemblerHealthCache: { healthy: boolean; expires: number } | null = null;++ export async function isAssemblerServiceHealthy(): Promise<boolean> {+ if (!ASSEMBLER_SERVICE_URL) return false;++ const now = Date.now();+ if (assemblerHealthCache && assemblerHealthCache.expires > now) {+ return assemblerHealthCache.healthy;+ }++ let healthy = false;+ const controller = new AbortController();+ const timeout = setTimeout(+ () => controller.abort(),+ ASSEMBLER_HEALTH_TIMEOUT_MS+ );+ try {+ const response = await fetch(`${ASSEMBLER_SERVICE_URL}/health`, {+ method: "GET",+ signal: controller.signal+ });+ healthy = response.ok;+ } catch {+ healthy = false;+ } finally {+ clearTimeout(timeout);+ }++ assemblerHealthCache = {+ healthy,+ expires:+ now + (healthy ? ASSEMBLER_HEALTHY_TTL_MS : ASSEMBLER_UNHEALTHY_TTL_MS)+ };+ return healthy;+ }++ /**+ * Save the release dialog's supplier for outside operations whose process has+ * several, so `purchaseOrderFromJob` resolves it. Runs before the purchase+ * orders are created. Both ids come from the caller and drive an RLS-bypassing+ * write, so the operation must belong to one of `jobIds` and the supplier+ * process to the operation's own process.+ */+ export async function stampSupplierChoices(+ ctx: ServiceContext,+ { jobIds, choices }: { jobIds: string[]; choices: Record<string, string> }+ ): Promise<CarbonError | null> {+ const entries = Object.entries(choices);+ if (entries.length === 0) return null;+ const companyId = ctx.company.id;+ const system = ctx.asSystem.supabase;++ const [operations, supplierProcesses] = await Promise.all([+ system+ .from("jobOperation")+ .select("id, processId")+ .in("jobId", jobIds)+ .eq("companyId", companyId)+ .in(+ "id",+ entries.map(([operationId]) => operationId)+ ),+ system+ .from("supplierProcess")+ .select("id, processId")+ .eq("companyId", companyId)+ .in(+ "id",+ entries.map(([, supplierProcessId]) => supplierProcessId)+ )+ ]);+ if (operations.error || supplierProcesses.error) {+ return ctx.error(+ "internal",+ "Failed to save the supplier choice",+ operations.error ?? supplierProcesses.error+ );+ }++ const processOfOperation = new Map(+ operations.data.map((op) => [op.id, op.processId])+ );+ const processOfSupplierProcess = new Map(+ supplierProcesses.data.map((sp) => [sp.id, sp.processId])+ );+ for (const [operationId, supplierProcessId] of entries) {+ const processId = processOfOperation.get(operationId);+ if (!processId) {+ return ctx.error(+ "validation",+ `Operation ${operationId} does not belong to these jobs`+ );+ }+ if (processOfSupplierProcess.get(supplierProcessId) !== processId) {+ return ctx.error(+ "validation",+ "Selected supplier does not belong to the operation's process"+ );+ }+ }++ const updates = await Promise.all(+ entries.map(([operationId, supplierProcessId]) =>+ system+ .from("jobOperation")+ .update({+ operationSupplierProcessId: supplierProcessId,+ updatedBy: ctx.auditUserId+ })+ .eq("id", operationId)+ .eq("companyId", companyId)+ )+ );+ const failed = updates.find((update) => update.error)?.error;+ return failed+ ? ctx.error("internal", "Failed to save the supplier choice", failed)+ : null;+ }++ export type JobStatus = (typeof jobStatus)[number];++ /**+ * Move a job from one of `from` to `to`, as one guarded UPDATE: the job must be+ * in `from` when it is read and still when it is written.+ */+ export async function moveJobStatus(+ ctx: ServiceContext,+ jobId: string,+ {+ from,+ to,+ refusal+ }: { from: readonly JobStatus[]; to: JobStatus; refusal: string }+ ) {+ const job = await ctx.asCaller.supabase+ .from("job")+ .select("status")+ .eq("id", jobId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (job.error)+ return ctx.error("internal", "Failed to read the job", job.error);+ if (!job.data) return ctx.error("notFound", "Job not found");+ if (!from.includes(job.data.status)) return ctx.error("rule", refusal);++ const update = await updateJobStatus(ctx.asCaller.supabase, {+ id: jobId,+ companyId: ctx.company.id,+ status: to,+ updatedBy: ctx.auditUserId,+ fromStatuses: [...from]+ });+ if (update.error) {+ return ctx.error("internal", "Failed to update job status", update.error);+ }+ if (!update.updated) {+ return ctx.error("conflict", "The job's status changed; reload the job");+ }+ return { jobId, status: to };+ }++ /** Post an ended event's time to the GL; a skip or failure is the reason, not an error. */+ export async function postEndedEvent(+ ctx: ServiceContext,+ productionEventId: string+ ) {+ const posting = await invokePosting(+ {+ db: ctx.asSystem.pg,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ },+ "post-production-event",+ { productionEventId },+ postProductionEvent+ );+ if (posting.error) return posting.error.message || "unknown error";+ if (posting.data.success === false) {+ return posting.data.reason ?? "unknown reason";+ }+ return null;+ }++ type OwnedTable =+ | "item"+ | "location"+ | "customer"+ | "modelUpload"+ | "fixedAssetClass"+ | "fixedAsset"+ | "storageUnit"+ | "salesOrder"+ | "salesOrderLine"+ | "quote"+ | "quoteLine";++ /**+ * `notFound` unless every id is a row of this company. Ids from a form prove+ * nothing about tenancy, and the writes after this run with the service role.+ * Read with the service role, since a production user may not hold the+ * other module's view and RLS would read their own row as absent.+ */+ export async function requireOwnRecords(+ ctx: ServiceContext,+ records: [table: OwnedTable, id: string | null | undefined, label: string][]+ ): Promise<CarbonError | null> {+ const checks = await Promise.all(+ records+ .filter(([, id]) => id)+ .map(async ([table, id, label]) => {+ const row = await ctx.asSystem.supabase+ .from(table as "item")+ .select("id")+ .eq("id", id!)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (row.error) {+ return ctx.error(+ "internal",+ `Failed to verify the ${label}`,+ row.error+ );+ }+ return row.data+ ? null+ : ctx.error(+ "notFound",+ `The ${label} could not be found. It may have been deleted, or it belongs to another company.`+ );+ })+ );+ return checks.find((check) => check !== null) ?? null;+ }++ /**+ * The jobs, read as the caller, refusing the request when any is locked+ * (Completed, Closed or Cancelled). Ids of other companies are not returned.+ */+ export async function readUnlockedJobs(ctx: ServiceContext, ids: string[]) {+ const jobs = await ctx.asCaller.supabase+ .from("job")+ .select(+ "id, status, quantity, fixedAssetClassId, fixedAssetId, dueDate, deadlineType, locationId"+ )+ .in("id", ids)+ .eq("companyId", ctx.company.id);+ if (jobs.error) {+ return ctx.error("internal", "Failed to read the jobs", jobs.error);+ }+ if (jobs.data.some((job) => isJobLocked(job.status))) {+ return ctx.error("rule", JOB_LOCKED_MESSAGE);+ }+ return jobs.data;+ }++ /**+ * Each job's due date when `count` jobs are spread from the first job's due+ * date to the last's: several jobs a day when there are more jobs than days,+ * several days a job otherwise. The last job is due on the last date.+ */+ export function spreadDueDates(+ count: number,+ first: string | undefined,+ last: string | undefined+ ): (string | undefined)[] {+ if (!first || !last) return Array.from({ length: count }, () => first);+ const startDate = toCalendarDateTime(parseDateTime(first));+ const endDate = toCalendarDateTime(parseDateTime(last));+ const daysBetween = endDate.compare(startDate);+ const jobsPerDay = (count - 1) / daysBetween;+ const daysPerJob = daysBetween / (count - 1);++ let cumulativeJobs = 0;+ return Array.from({ length: count }, (_, i) => {+ if (i === count - 1) return last;+ if (jobsPerDay >= 1) {+ cumulativeJobs += 1;+ const dayOffset = Math.floor(cumulativeJobs / jobsPerDay);+ return startDate.add({ days: dayOffset }).toString();+ }+ const dayOffset = Math.floor(i * daysPerJob);+ return startDate.add({ days: dayOffset }).toString();+ });+ }++ /**+ * A job's configuration: an object, or the JSON a form posts. Anything else+ * (invalid JSON) is no configuration.+ */+ export function parseConfiguration(+ value: unknown+ ): Record<string, unknown> | undefined {+ if (value && typeof value === "object") {+ return value as Record<string, unknown>;+ }+ if (typeof value !== "string" || !value) return undefined;+ try {+ return JSON.parse(value);+ } catch {+ return undefined;+ }+ }++ /**+ * The job, read as the caller, for a write to it: `notFound` unless it is+ * this company's, `rule` when it is locked (Completed, Closed or Cancelled).+ */+ export async function requireJob(ctx: ServiceContext, jobId: string) {+ const job = await ctx.asCaller.supabase+ .from("job")+ .select("id, status")+ .eq("id", jobId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (job.error)+ return ctx.error("internal", "Failed to read the job", job.error);+ if (!job.data) return ctx.error("notFound", "Job not found");+ if (isJobLocked(job.data.status)) {+ return ctx.error("rule", JOB_LOCKED_MESSAGE);+ }+ return job.data;+ }++ /**+ * Recalculate a job's requirements and operation dependencies (which also+ * reschedules its location). The first failure is returned.+ */+ export async function recalculateJob(+ ctx: ServiceContext,+ jobId: string,+ { requirements = true }: { requirements?: boolean } = {}+ ): Promise<CarbonError | null> {+ const params = { companyId: ctx.company.id, userId: ctx.auditUserId };+ const [quantities, dependencies] = await Promise.all([+ requirements+ ? recalculateJobRequirements(ctx.asSystem.supabase, ctx.asSystem.pg, {+ id: jobId,+ ...params+ })+ : null,+ recalculateJobOperationDependencies(+ ctx.asSystem.supabase,+ ctx.asSystem.pg,+ {+ jobId,+ ...params+ }+ )+ ]);+ if (quantities?.error) {+ return ctx.error(+ "internal",+ "Failed to calculate job quantities",+ quantities.error+ );+ }+ if (dependencies?.error) {+ return ctx.error(+ "internal",+ "Failed to recalculate job operation dependencies",+ dependencies.error+ );+ }+ return null;+ }++ /** `notFound` unless the make method and operation given hang off this job. */+ export async function requireJobChildren(+ ctx: ServiceContext,+ jobId: string,+ {+ jobMakeMethodId,+ jobOperationId+ }: { jobMakeMethodId?: string; jobOperationId?: string }+ ): Promise<CarbonError | null> {+ const system = ctx.asSystem.supabase;+ const [method, operation] = await Promise.all([+ jobMakeMethodId+ ? system+ .from("jobMakeMethod")+ .select("id")+ .eq("id", jobMakeMethodId)+ .eq("jobId", jobId)+ .eq("companyId", ctx.company.id)+ .maybeSingle()+ : null,+ jobOperationId+ ? system+ .from("jobOperation")+ .select("id")+ .eq("id", jobOperationId)+ .eq("jobId", jobId)+ .eq("companyId", ctx.company.id)+ .maybeSingle()+ : null+ ]);+ const failed = method?.error ?? operation?.error;+ if (failed) return ctx.error("internal", "Failed to read the job", failed);+ if (method && !method.data)+ return ctx.error("notFound", "Make method not found");+ if (operation && !operation.data) {+ return ctx.error("notFound", "Operation not found");+ }+ return null;+ }++ /** Recalculate one make method's requirements, and the job's dependencies. */+ export async function recalculateMaterialMethod(+ ctx: ServiceContext,+ {+ jobId,+ jobMakeMethodId,+ dependencies+ }: { jobId: string; jobMakeMethodId: string; dependencies: boolean }+ ): Promise<CarbonError | null> {+ const params = { companyId: ctx.company.id, userId: ctx.auditUserId };+ const [requirements, dependencyResult] = await Promise.all([+ recalculateJobMakeMethodRequirements(+ ctx.asSystem.supabase,+ ctx.asSystem.pg,+ {+ id: jobMakeMethodId,+ ...params+ }+ ),+ dependencies+ ? recalculateJobOperationDependencies(+ ctx.asSystem.supabase,+ ctx.asSystem.pg,+ { jobId, ...params }+ )+ : null+ ]);+ if (requirements.error) {+ return ctx.error(+ "internal",+ "Failed to recalculate job make method requirements",+ requirements.error+ );+ }+ if (dependencyResult?.error) {+ return ctx.error(+ "internal",+ "Failed to recalculate job operation dependencies",+ dependencyResult.error+ );+ }+ return null;+ }++ // --- People board ---------------------------------------------------------++ type BoardReferenceTable =+ | "department"+ | "employee"+ | "location"+ | "shift"+ | "workCenter";++ /**+ * `notFound` unless every id given is this company's. Every board write puts+ * these ids into this company's rows through Kysely (no RLS), and their+ * single-column foreign keys accept another company's row. Empty values are+ * skipped, so optional fields stay optional.+ */+ export async function requireBoardReferences(+ ctx: ServiceContext,+ refs: Partial<Record<BoardReferenceTable, (string | null | undefined)[]>>+ ): Promise<CarbonError | null> {+ const checks = await Promise.all(+ (Object.entries(refs) as [BoardReferenceTable, unknown[]][]).map(+ async ([table, values]) => {+ const ids = [+ ...new Set(+ values.filter(+ (value): value is string =>+ typeof value === "string" && value.length > 0+ )+ )+ ];+ if (ids.length === 0) return true;+ // Every table in the union has `id` + `companyId`; the cast only+ // narrows the union so Kysely can type the builder.+ const rows = await ctx.asSystem.pg+ .selectFrom(table as "location")+ .select("id")+ .where("id", "in", ids)+ .where("companyId", "=", ctx.company.id)+ .execute();+ return rows.length === ids.length;+ }+ )+ );+ if (checks.every(Boolean)) return null;+ logger.error("People board reference is not in the caller's company", {+ companyId: ctx.company.id,+ refs+ });+ return ctx.error("notFound", "Not found");+ }++ /** Tell the scheduler once per work center; with none, once, unscoped. */+ export async function notifyPeopleChange(+ ctx: ServiceContext,+ reason: string,+ workCenterIds: (string | null | undefined)[] = []+ ) {+ const ids = [...new Set(workCenterIds.filter(Boolean))] as string[];+ if (ids.length === 0) {+ await notifyScheduleInputsChanged(ctx.company.id, "people", reason);+ return;+ }+ for (const workCenterId of ids) {+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "people",+ reason,+ workCenterId+ );+ }+ }++ /** The work centers a person is assigned at on a date, for the notice. */+ export async function notifyForEmployeeDate(+ ctx: ServiceContext,+ employeeId: string,+ date: string,+ reason: string+ ) {+ const assignments = await ctx.asCaller.supabase+ .from("peopleAssignment")+ .select("workCenterId")+ .eq("companyId", ctx.company.id)+ .eq("employeeId", employeeId)+ .eq("date", date);+ await notifyPeopleChange(+ ctx,+ reason,+ (assignments.data ?? []).map((row) => row.workCenterId)+ );+ }++ /** A write that throws on failure, as an `internal` error with `message`. */+ export async function catchInternal<T>(+ ctx: ServiceContext,+ message: string,+ write: () => Promise<T>+ ): Promise<T | CarbonError<"internal">> {+ try {+ return await write();+ } catch (err) {+ return ctx.error("internal", message, err);+ }+ }++ /** A Draft or Planned job of this company at `locationId`, for planning. */+ export async function readPlanningJob(+ ctx: ServiceContext,+ jobId: string,+ locationId: string+ ) {+ const target = await ctx.asSystem.supabase+ .from("job")+ .select("id, status, locationId, salesOrderId, salesOrderLineId")+ .eq("id", jobId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (target.error || !target.data) {+ return ctx.error("notFound", "Job not found", target.error);+ }+ // The drawer lists one location's jobs.+ if (target.data.locationId !== locationId) {+ return ctx.error("conflict", "This job is for another location.");+ }+ return target.data;+ }++ /**+ * Report how many of the requested worklist rows changed; none is a conflict+ * (each one was applied or changed since the page loaded).+ */+ export function changedPlanningActions(+ ctx: ServiceContext,+ result: { data: unknown[] | null; error: unknown },+ requested: number,+ verb: "dismiss" | "reopen" | "assign"+ ) {+ if (result.error) {+ return ctx.error(+ "internal",+ `Failed to ${verb} planning actions`,+ result.error+ );+ }+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return ctx.error(+ "conflict",+ `Nothing to ${verb} — these actions changed since the page loaded`+ );+ }+ return { changed, requested };+ }++ // --- Assembly instructions -------------------------------------------------++ /** The instruction's model id, `notFound` unless it is this company's. */+ export async function readInstructionModel(ctx: ServiceContext, id: string) {+ const instruction = await ctx.asCaller.supabase+ .from("assemblyInstruction")+ .select(+ "modelUploadId, modelUpload(id, processingStatus, glbPath, graphPath, modelPath)"+ )+ .eq("id", id)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (instruction.error) {+ return ctx.error(+ "internal",+ "Failed to read the instruction",+ instruction.error+ );+ }+ if (!instruction.data) return ctx.error("notFound", "Instruction not found");+ if (!instruction.data.modelUploadId) {+ return ctx.error("rule", "This instruction has no model");+ }+ return {+ modelUploadId: instruction.data.modelUploadId,+ modelUpload: instruction.data.modelUpload+ };+ }++ /** The geometry service is down: no conversion or planning can start. */+ export const geometryServiceDown = (ctx: ServiceContext, work: string) =>+ ctx.error(+ "unavailable",+ `The geometry service is unavailable — ${work} can't run right now.`+ );++ /**+ * Start motion planning for a model: the job row first, so the page shows+ * the run on its next load (the worker adopts it via `planJobId`; it inserts+ * its own row when this insert fails), then the event.+ */+ export async function startAssemblyPlan(+ ctx: ServiceContext,+ modelUploadId: string,+ options: { reMotionFor?: string; reDetectUnits?: boolean } = {}+ ) {+ // The service role: the INSERT needs production_create, and the operations+ // that start a plan require only update. Every caller read the model under+ // the company, and the row is written to it.+ const created = await createAssemblyPlanJob(ctx.asSystem.supabase, {+ modelUploadId,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ });+ await trigger("assembly-plan", {+ modelUploadId,+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ ...(created.data?.id ? { planJobId: created.data.id } : {}),+ ...options+ });+ }++ /** What resuming a paused job checks: its status, item and asset links. */+ export async function getJobToResume(+ client: SupabaseClient<Database>,+ jobId: string,+ companyId: string+ ) {+ return client+ .from("job")+ .select(+ "status, quantity, salesOrderLineId, fixedAssetClassId, fixedAssetId, item(itemTrackingType, itemReplenishment(manufacturingBlocked))"+ )+ .eq("id", jobId)+ .eq("companyId", companyId)+ .maybeSingle();+ }+ export const closeJobInput = z.object({+ jobId: z.string()+ });++ /**+ * Closing a job writes off whatever is left in WIP for it as production+ * variance, so the job's WIP nets to zero. Nothing to do when the residual is+ * under a cent. The journal is Provisional before the company's accounting+ * cutover and Posted after it.+ */+ export async function closeJob(+ ctx: ServiceContext,+ raw: z.input<typeof closeJobInput>+ ) {+ const { jobId } = closeJobInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );++ if (companyRecord.error) throw new Error("Failed to fetch company");++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults?.error || !accountDefaults?.data) {+ throw new Error("Error getting account defaults");+ }++ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ // Read inside the transaction so the FOR SHARE lock holds until commit.+ const postingStatus = await journalPostingStatus(trx, companyId);++ const wipBalance = await trx+ .selectFrom("journalLine")+ .innerJoin("journal", "journal.id", "journalLine.journalId")+ .select((eb) => eb.fn.sum("journalLine.amount").as("balance"))+ .where(+ "journalLine.accountId",+ "=",+ accountDefaults.data!.workInProgressAccount+ )+ .where("journalLine.documentId", "=", jobId)+ .where("journal.companyId", "=", companyId)+ .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES])+ .executeTakeFirst();++ const remainingWip = Number(wipBalance?.balance ?? 0);++ if (Math.abs(remainingWip) < 0.01) return;++ const job = await trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .select(["jobId", "itemId", "locationId"])+ .executeTakeFirstOrThrow();++ // Resolve the item dimensions so the WIP variance lines are attributable+ // to the finished good (mirrors the WIP lines posted during completion).+ const companyGroupId = companyRecord.data.companyGroupId;+ const dimensionMap = new Map<string, string>();+ if (companyGroupId) {+ const dimensions = await trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["ItemPostingGroup", "Item", "Location"])+ .execute();+ for (const dim of dimensions) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ }++ const finishedItemCost = job.itemId+ ? await trx+ .selectFrom("itemCost")+ .select(["itemPostingGroupId"])+ .where("itemId", "=", job.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : null;++ const journalLineReference = nanoid();++ const journalLineInserts = [+ {+ accountId: accountDefaults.data!.materialVarianceAccount,+ description: "Production Variance",+ // Signed: a positive residual debits variance / credits WIP; a+ // negative (over-credited) residual reverses — always zeroing WIP.+ amount: round(debit("expense", remainingWip)),+ quantity: 0,+ documentType: "Job Close" as const,+ documentId: jobId,+ documentLineReference: journalReference.to.job(jobId),+ journalLineReference,+ companyId+ },+ {+ accountId: accountDefaults.data!.workInProgressAccount,+ description: "WIP Account",+ amount: round(credit("asset", remainingWip)),+ quantity: 0,+ documentType: "Job Close" as const,+ documentId: jobId,+ documentLineReference: journalReference.to.job(jobId),+ journalLineReference,+ companyId+ }+ ];++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, trx, today)+ : null;++ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Job Close Variance ${job.jobId}`,+ postingDate: today,+ companyId,+ sourceType: "Job Close",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id+ }))+ )+ .returning(["id"])+ .execute();++ if (dimensionMap.size > 0) {+ const dimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ for (const jl of journalLineResults) {+ if (job.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: job.itemId,+ companyId+ });+ }+ if (+ finishedItemCost?.itemPostingGroupId &&+ dimensionMap.has("ItemPostingGroup")+ ) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: finishedItemCost.itemPostingGroupId,+ companyId+ });+ }+ if (job.locationId && dimensionMap.has("Location")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: job.locationId,+ companyId+ });+ }+ }++ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }+ });++ return { success: true };+ }+ export const assignSerialNumbersInput = z.object({+ jobId: z.string()+ });++ /**+ * Assigns configured serial numbers to a job's tracked entities at creation time.+ *+ * Run (best-effort) by `insertJob` only when the job's item has an+ * `itemSerialSequence`. For a Batch item it stamps one number on the single+ * whole-quantity seed entity; for a Serial item it splits the seed into N+ * quantity-1 entities and stamps one number on each. Numbers come from the+ * item's sequence (atomic counter) with %{...} date/week/location tokens.+ *+ * Idempotent: it no-ops when the seed is already numbered or already split.+ */+ export const assignSerialNumbersPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof assignSerialNumbersInput>>;++ export async function assignSerialNumbers(+ ctx: ServiceContext,+ raw: z.input<typeof assignSerialNumbersInput>+ ) {+ const { jobId } = assignSerialNumbersInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;++ return db.transaction().execute(async (trx) => {+ // 1. The job+ const job = await trx+ .selectFrom("job")+ .select(["id", "itemId", "quantity", "locationId"])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!job) throw new NotFoundError(`Job ${jobId} not found`);++ // 2. Only serial/batch tracked items carry serial numbers+ const item = await trx+ .selectFrom("item")+ .select(["itemTrackingType"])+ .where("id", "=", job.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const trackingType = item?.itemTrackingType;+ if (trackingType !== "Serial" && trackingType !== "Batch") {+ return { assigned: 0 };+ }++ // 3. The item's serial sequence (optional, at most one)+ const sequence = await trx+ .selectFrom("itemSerialSequence")+ .select(["prefix", "suffix", "next", "size", "step"])+ .where("itemId", "=", job.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!sequence) return { assigned: 0 };++ // 4. Location context for the %{location} token (code, falling back to name)+ let locationCode: string | null = null;+ let locationName: string | null = null;+ if (job.locationId) {+ const location = await trx+ .selectFrom("location")+ .select(["code", "name"])+ .where("id", "=", job.locationId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ locationCode = location?.code ?? null;+ locationName = location?.name ?? null;+ }++ // 5. The root make-method seed entity for this job. The job-insert+ // interceptor tags it with the Job id; sub-assembly seeds also carry a+ // Job Material id, and split fragments carry a pointer key — the+ // legacy "Split Entity ID" (old convention: departed original) or+ // "Split From Entity ID" (new convention: split child). Exclude all+ // so we only touch the root make method's seed.+ const seeds = await trx+ .selectFrom("trackedEntity")+ .selectAll()+ .where("companyId", "=", companyId)+ .where(attributesContain({ Job: jobId }))+ .where(sql<boolean>`attributes->>'Job Material' IS NULL`)+ .where(sql<boolean>`attributes->>'Split Entity ID' IS NULL`)+ .where(sql<boolean>`attributes->>'Split From Entity ID' IS NULL`)+ .orderBy("createdAt", "asc")+ // Lock the seed row for the duration of the transaction so concurrent+ // runs for the same job serialize here: the second waits, then sees+ // the readableId the first assigned and no-ops the idempotency guard+ // below instead of reserving a duplicate range and inserting duplicates.+ .forUpdate()+ .execute();++ // Idempotency: already split into many, or already numbered → do nothing.+ const seed = seeds[0];+ if (seeds.length !== 1 || !seed) return { assigned: 0 };+ if (seed.readableId) return { assigned: 0 };++ // 6. How many numbers to reserve. Serial → one per unit; Batch → one.+ const count =+ trackingType === "Batch" ? 1 : Math.round(Number(job.quantity));+ if (count < 1) return { assigned: 0 };++ // 7. Atomically reserve + format the next `count` serial numbers.+ const serials = await getNextSerialNumbers(trx, {+ itemId: job.itemId,+ companyId,+ count,+ locationCode,+ locationName+ });+ if (serials.length === 0) return { assigned: 0 };++ // 8. Assign. Batch keeps the single whole-quantity seed; Serial splits it+ // into `count` quantity-1 entities, one number each (seed becomes #1).+ if (trackingType === "Batch") {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId: serials[0] })+ .where("id", "=", seed.id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId: serials[0], quantity: 1 })+ .where("id", "=", seed.id)+ .where("companyId", "=", companyId)+ .execute();++ if (count > 1) {+ // 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,+ quantity: 1,+ status: seed.status,+ attributes: seed.attributes,+ itemId: seed.itemId ?? null,+ expirationDate: seed.expirationDate ?? null,+ readableId,+ companyId,+ createdBy: seed.createdBy+ }));+ await trx.insertInto("trackedEntity").values(rows).execute();+ }+ }++ return { assigned: count };+ });+ }+ const sandboxLogger = getLogger("erp", "configuration-rule");++ /**+ * A stored configuration rule is the TypeScript body of `configure(params)`. It is+ * transpiled by `transpileRule` — the same one the configurator editor runs — and run in+ * QuickJS (`@carbon/database/configuration-rule`), never in this process's own engine.+ *+ * A rule that does not compile, throws, or exceeds a sandbox limit yields null, so one+ * broken rule never fails the whole method: a field keeps its default, and a bill of+ * materials or process keeps all of its lines.+ */+ export async function importTypeScript(code: string): Promise<{+ configure: <T>(params: unknown) => Promise<T | null>;+ }> {+ let javascript: string | null = null;+ try {+ javascript = transpileRule(code);+ } catch (error) {+ sandboxLogger.error("configuration rule does not compile", {+ error: String(error)+ });+ }++ return {+ configure: async <T>(params: unknown) => {+ if (javascript === null) return null;+ try {+ return (await runConfigurationRule(javascript, params)) as T | null;+ } catch (error) {+ sandboxLogger.error("configuration rule failed", {+ error: String(error)+ });+ return null;+ }+ }+ };+ }+ const getMethodLogger = getLogger("erp", "get-method");++ /**+ * An operation-step `description` as a tiptap doc for a jsonb column. The+ * Supabase client returns a jsonb scalar string as a JS string, and re-inserting+ * a JS string makes node-pg send unquoted text that Postgres rejects: objects+ * pass through, strings are wrapped, and null/empty become {}.+ */+ function toTiptapDoc(value: unknown): Json {+ if (value && typeof value === "object") return value as Json;+ if (typeof value === "string" && value.length > 0) {+ return textToTiptap(value) as Json;+ }+ return {};+ }++ // quoteLine's jsonb columns — run through toJsonColumns() in quoteToQuote's per-line copy.+ const QUOTE_LINE_JSON_COLUMNS = [+ "additionalCharges",+ "configuration",+ "customFields",+ "externalNotes",+ "internalNotes",+ "priceTrace"+ ] as const satisfies readonly (keyof Database["public"]["Tables"]["quoteLine"]["Row"])[];++ // Stored configurator rules are user-authored JS that may still return legacy "Inside"/"Outside" operationType values.+ const normalizeOperationType = (value: unknown) =>+ (value === "Inside"+ ? "Process"+ : value === "Outside"+ ? "Outside Processing"+ : value) as Database["public"]["Enums"]["operationType"];++ // Copy an operation step's reference slides (grandchild) when a method/job/quote is+ // copied. Source slides are queried by their (old) step ids and remapped onto the freshly+ // inserted step ids — a bulk insert preserves order, so insertedStepIds[i] ↔ sourceSteps[i].+ // Guarded: a no-op when there are no slides, so it can never break step copying.+ // See .ai/specs/2026-07-14-mes-execution-views.md §4.+ async function copyStepSlides(+ trx: Transaction<KyselyDatabase>,+ sourceSteps: Array<{ id?: string | null }>,+ insertedStepIds: Array<{ id: string }>,+ sourceTable:+ | "methodOperationStepSlide"+ | "jobOperationStepSlide"+ | "quoteOperationStepSlide",+ targetTable:+ | "methodOperationStepSlide"+ | "jobOperationStepSlide"+ | "quoteOperationStepSlide",+ companyId: string,+ userId: string+ ) {+ const sourceStepIds = sourceSteps+ .map((s) => s.id)+ .filter((id): id is string => !!id);+ if (sourceStepIds.length === 0) return;++ // The three slide tables share these columns; one name stands for all.+ const srcSlides = await selectRows(+ trx,+ sourceTable as "methodOperationStepSlide",+ { stepId: sourceStepIds }+ );++ const inserts = srcSlides.flatMap((sl) => {+ const idx = sourceSteps.findIndex((s) => s.id === sl.stepId);+ const newStepId = insertedStepIds[idx]?.id;+ if (!newStepId) return [];+ return [+ {+ stepId: newStepId,+ imagePath: sl.imagePath,+ modelUploadId: sl.modelUploadId,+ caption: sl.caption,+ sortOrder: sl.sortOrder,+ size: sl.size,+ // A raw array reaches Postgres as an array literal: `[]` was stored as+ // the jsonb object `{}`, and a slide with pins failed the insert.+ annotations: toJson(sl.annotations ?? []),+ companyId,+ createdBy: userId+ }+ ];+ });++ if (inserts.length > 0) {+ await trx+ .insertInto(targetTable as any)+ .values(inserts as any)+ .execute();+ }+ }++ // Many-to-many step links (Phase 2): remap a parent's OLD operation-step ids onto the freshly+ // inserted step ids via stepMap, dropping any that don't map. Empty in = the parent applies to+ // the whole operation (no join rows, shown on every step in the MES).+ function remapStepIds(+ oldIds: Array<string | null | undefined> | null | undefined,+ stepMap: Record<string, string>+ ): string[] {+ return (oldIds ?? []).flatMap((id) =>+ id && stepMap[id] ? [stepMap[id]] : []+ );+ }++ // Material twin of remapStepIds: get_method_tree aggregates methodMaterialStep as+ // {id, quantity} objects (quantity NULL = the step uses the full BOM line quantity).+ // Bare-string elements are tolerated for trees read before the aggregate changed.+ function remapStepLinks(+ oldLinks:+ | Array<string | { id?: string | null; quantity?: number | null } | null>+ | null+ | undefined,+ stepMap: Record<string, string>+ ): { stepId: string; quantity: number | null }[] {+ return (oldLinks ?? []).flatMap((link) => {+ const id = typeof link === "string" ? link : link?.id;+ const quantity =+ typeof link === "object" && link !== null+ ? (link.quantity ?? null)+ : null;+ return id && stepMap[id]+ ? [+ {+ stepId: stepMap[id],+ quantity: quantity === null ? null : Number(quantity)+ }+ ]+ : [];+ });+ }++ // A BOM line whose quantity is explicitly 0 contributes nothing, so it is+ // dropped whenever a method is instantiated or copied. `null`/`undefined` is+ // NOT treated as zero — those fall back to a quantity of 1 elsewhere in this+ // file, so only a real numeric 0 removes the line.+ function isZeroQuantity(quantity: unknown): boolean {+ // Only a real numeric 0 removes the line. `getConfiguredValue` returns a+ // dynamically-configured value behind a type assertion, so `""`/`false`/`[]`+ // can reach here — `Number("")`/`Number(false)` are 0 and would wrongly drop+ // the line. A strict typeof check keeps those falling back to a quantity of 1.+ return typeof quantity === "number" && quantity === 0;+ }++ const partsValidator = z+ .object({+ billOfMaterial: z.boolean().default(true),+ billOfProcess: z.boolean().default(true),+ parameters: z.boolean().default(true),+ tools: z.boolean().default(true),+ steps: z.boolean().default(true),+ workInstructions: z.boolean().default(true)+ // prefault, not default: v4's .default() returns {} AS-IS on undefined input,+ // which would skip every inner default and disable all six part flags.+ })+ .prefault({});++ export const getMethodInput = z.object({+ type: z.enum([+ "itemToItem",+ "itemToJob",+ "itemToJobMakeMethod",+ "itemToQuoteLine",+ "itemToQuoteMakeMethod",+ "jobMakeMethodToItem",+ "jobToItem",+ "jobToJob",+ "makeMethodToMakeMethod",+ "procedureToOperation",+ "quoteLineToItem",+ "quoteLineToJob",+ "quoteLineToQuoteLine",+ "quoteMakeMethodToItem",+ "quoteToQuote"+ ]),+ sourceId: z.string(),+ targetId: z.string(),+ configuration: z.record(z.string(), z.unknown()).optional(),+ parts: partsValidator,+ // A specific source makeMethod version (itemToJob / itemToJobMakeMethod+ // only). Absent = the item's active method, as before.+ versionId: z.string().optional()+ });++ /** `newQuoteId` is set by quoteToQuote. */+ export type GetMethodResult = { success: boolean; newQuoteId?: string };++ export const getMethodPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof getMethodInput>>;++ /** Copies a method (BOM + BOP) between items, quotes and jobs, per `type`. */+ // Configuration rule fields name the rows they configure, joined by ":":+ // `<column>:<lineId>` for a method line or operation field, and+ // `billOfMaterial|billOfProcess:<makeMethodId>:<lineId | "undefined">` for a+ // node's list. Copying a method gives every row a new id, so its rules are+ // re-keyed through a map of old id → new id.++ /** Whether a rule field names any of `ids`. */+ export function ruleFieldReferences(field: string, ids: Set<string>) {+ return field.split(":").some((part) => ids.has(part));+ }++ /** The field re-keyed onto the copied rows, or null when it names none of them. */+ export function remapRuleField(field: string, idMap: Map<string, string>) {+ const parts = field.split(":");+ if (!parts.some((part) => idMap.has(part))) return null;+ return parts.map((part) => idMap.get(part) ?? part).join(":");+ }++ // A method copy re-keys the rules of the copied rows onto their new ids (`idMap`:+ // source line, operation and method ids → target ids; see configuration-rules.ts),+ // and drops the target's rules for the rows it replaced. Otherwise a new version's+ // lines carry no rules and the old rules point at deleted rows.+ async function copyConfigurationRules(+ trx: Transaction<KyselyDatabase>,+ args: {+ sourceItemId: string;+ targetItemId: string;+ replacedIds: string[];+ idMap: Map<string, string>;+ companyId: string;+ userId: string;+ }+ ) {+ const { sourceItemId, targetItemId, idMap, companyId, userId } = args;+ const replaced = new Set(args.replacedIds);++ if (replaced.size > 0) {+ const targetRules = await trx+ .selectFrom("configurationRule")+ .select("field")+ .where("itemId", "=", targetItemId)+ .where("companyId", "=", companyId)+ .execute();+ const stale = targetRules+ .map((rule) => rule.field)+ .filter((field) => ruleFieldReferences(field, replaced));+ if (stale.length > 0) {+ await trx+ .deleteFrom("configurationRule")+ .where("itemId", "=", targetItemId)+ .where("companyId", "=", companyId)+ .where("field", "in", stale)+ .execute();+ }+ }++ if (idMap.size === 0) return;+ const sourceRules = await trx+ .selectFrom("configurationRule")+ .select(["field", "code"])+ .where("itemId", "=", sourceItemId)+ .where("companyId", "=", companyId)+ .execute();+ const copies = sourceRules.flatMap((rule) => {+ const field = remapRuleField(rule.field, idMap);+ return field+ ? [+ {+ itemId: targetItemId,+ field,+ code: rule.code,+ companyId,+ updatedBy: userId+ }+ ]+ : [];+ });+ if (copies.length === 0) return;+ await trx+ .insertInto("configurationRule")+ .values(copies)+ .onConflict((oc) =>+ oc.columns(["itemId", "field"]).doUpdateSet((eb) => ({+ code: eb.ref("excluded.code"),+ updatedBy: eb.ref("excluded.updatedBy")+ }))+ )+ .execute();+ }++ export async function getMethod(+ ctx: ServiceContext,+ raw: z.input<typeof getMethodInput>+ ) {+ const { type, sourceId, targetId, configuration, parts, versionId } =+ getMethodInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ getMethodLogger.info("get-method", {+ type,+ sourceId,+ targetId,+ companyId,+ userId,+ parts,+ configuration,+ versionId+ });++ switch (type) {+ case "itemToItem": {+ const [sourceMakeMethod, targetMakeMethod, targetItemReplenishment] =+ await inOrder([+ () =>+ single(db, "activeMakeMethods", { itemId: sourceId, companyId }),+ () =>+ single(db, "activeMakeMethods", { itemId: targetId, companyId }),+ () => single(db, "itemReplenishment", { itemId: targetId, companyId })+ ]);+ if (sourceMakeMethod.error || targetMakeMethod.error) {+ throw new Error("Failed to get make methods");+ }++ if (targetItemReplenishment.error) {+ throw new Error("Failed to get target item replenishment");+ }++ if (targetItemReplenishment.data?.requiresConfiguration) {+ throw new Error("Cannot override method of configured item");+ }++ if (+ sourceMakeMethod.data.id === null ||+ targetMakeMethod.data.id === null+ ) {+ throw new Error("Failed to get make methods");+ }++ const [sourceMaterials, sourceOperations] = await inOrder([+ () =>+ parts.billOfMaterial+ ? many(db, "methodMaterial", {+ makeMethodId: sourceMakeMethod.data.id,+ companyId+ })+ : Promise.resolve({ data: [], error: null }),+ () =>+ parts.billOfProcess+ ? many<+ "methodOperation",+ Tables["methodOperation"]["Row"] & {+ methodOperationTool: Tables["methodOperationTool"]["Row"][];+ methodOperationParameter: Tables["methodOperationParameter"]["Row"][];+ methodOperationStep: Tables["methodOperationStep"]["Row"][];+ }+ >(+ db,+ "methodOperation",+ { makeMethodId: sourceMakeMethod.data.id, companyId },+ {+ embed: {+ methodOperationTool: {+ table: "methodOperationTool",+ on: "operationId"+ },+ methodOperationParameter: {+ table: "methodOperationParameter",+ on: "operationId"+ },+ methodOperationStep: {+ table: "methodOperationStep",+ on: "operationId"+ }+ }+ }+ )+ : Promise.resolve({ data: [], error: null })+ ]);++ if (sourceMaterials.error || sourceOperations.error) {+ throw new Error("Failed to get source materials or operations");+ }++ await db.transaction().execute(async (trx) => {+ // Delete existing materials and operations from target method+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);++ // Operations first, so each copied BOM line can point at the copied+ // operation that consumes it, not at the source method's operation.+ const operationIdMap = new Map<string, string>();+ if (+ parts.billOfProcess &&+ sourceOperations.data &&+ sourceOperations.data.length > 0+ ) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ sourceOperations.data.map(+ ({+ methodOperationTool: _tools,+ methodOperationParameter: _parameters,+ methodOperationStep: _attributes,+ ...operation+ }) => {+ const insert = {+ ...operation,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id!,+ createdBy: userId+ };+ if (!parts.workInstructions) {+ insert.workInstruction = {};+ }+ return insert;+ }+ )+ )+ .returning(["id"])+ .execute();+ sourceOperations.data.forEach((operation, index) => {+ const id = operationIds[index]?.id;+ if (operation.id && id) operationIdMap.set(operation.id, id);+ });++ for await (const [+ index,+ operation+ ] of sourceOperations.data.entries()) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;+ const operationId = operationIds[index]!.id;++ if (+ parts.tools &&+ operationId &&+ Array.isArray(methodOperationTool) &&+ methodOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ methodOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ methodOperationParameter.map((param) => ({+ operationId: operationId!,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops inherit steps from the linked instruction —+ // never copy (possibly stale) template steps alongside it.+ !operation.assemblyInstructionId &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("methodOperationStep")+ .values(+ methodOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId: operationId!,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "methodOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ // Copy materials from source to target, dropping any zero-quantity+ // BOM lines.+ const materialsToCopy = (+ (sourceMaterials.data ??+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]+ ).filter((material) => !isZeroQuantity(material.quantity));+ if (parts.billOfMaterial && materialsToCopy.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialsToCopy.map((material) => ({+ ...material,+ productionQuantity: undefined,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id!,+ // Without the bill of process the source's operations were not+ // copied, so no operation on the target is known to consume it.+ methodOperationId: material.methodOperationId+ ? (operationIdMap.get(material.methodOperationId) ?? null)+ : null,+ createdBy: userId+ }))+ )+ .execute();+ }+ });++ break;+ }+ case "itemToJob": {+ const jobId = targetId;+ if (!jobId) {+ throw new Error("Invalid targetId");+ }+ const itemId = sourceId;+ const isConfigured = !!configuration;+ // Assembly ops whose steps were materialized from an instruction —+ // their material ↔ step links are flushed after the traversal has+ // inserted every node's jobMaterial rows.+ const assemblyOperationsToLink: Array<{+ operationId: string;+ assemblyInstructionId: string;+ }> = [];++ // These lookups go over the direct connection, one after another on+ // purpose: each is a few milliseconds, and running them at once would+ // take five of the process's sixteen pooled connections per call.+ //+ // A chosen version overrides the default active-method lookup; it is+ // re-read under itemId + companyId so a foreign or mismatched+ // makeMethod id can never be exploded.+ const makeMethod = versionId+ ? await db+ .selectFrom("makeMethod")+ .select(["id", "version"])+ .where("id", "=", versionId)+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : await db+ .selectFrom("activeMakeMethods")+ .select(["id", "version"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!makeMethod?.id) {+ throw new Error("Failed to get make method");+ }+ const makeMethodId = makeMethod.id;++ const jobMakeMethods = await db+ .selectFrom("jobMakeMethod")+ .select(["id"])+ .where("jobId", "=", jobId)+ .where("parentMaterialId", "is", null)+ .where("companyId", "=", companyId)+ .execute();+ // Exactly one root make method, as `.single()` required before.+ const jobMakeMethod = jobMakeMethods[0];+ if (!jobMakeMethod || jobMakeMethods.length > 1) {+ throw new Error("Failed to get job make method");+ }++ const workCenters = await db+ .selectFrom("workCenters")+ .selectAll()+ .where("companyId", "=", companyId)+ .execute();+ const supplierProcesses = await db+ .selectFrom("supplierProcess")+ .selectAll()+ .where("companyId", "=", companyId)+ .execute();+ const jobRow = await db+ .selectFrom("job")+ .select(["locationId", "quantity", "startDate", "dueDate"])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!jobRow) {+ throw new Error("Failed to get job");+ }+ const job = jobRow;++ // Way 1 — supersession swap at job creation. Build "old item -> effective+ // successor (x conversion factor)" for this company, gated by the job's+ // build date, using the SAME shared logic as MRP so the job's materials+ // match what planning already redirected. Applied to Buy/Pick lines in the+ // mapper below.+ const supersessionContext = await loadSupersessionRedirect(+ db,+ companyId,+ job+ );+ const supersessionRedirect = supersessionContext.redirect;++ const hydratedConfiguration = await hydrateConfiguration(+ db,+ configuration,+ itemId,+ companyId+ );++ const methodTrees = await getMethodTree(db, makeMethodId);+ const configurationRules = isConfigured+ ? await selectRows(db, "configurationRule", { itemId, companyId })+ : [];++ const methodTree = methodTrees.data?.[0] as MethodTreeItem;+ if (!methodTree) throw new NotFoundError("Method tree not found");++ // The traversal below runs on a single transaction connection, so any+ // per-node or per-material query is O(tree) sequential roundtrips — on+ // a large BOM that exceeds the caller's request timeout. Prefetch each+ // lookup table once per tree instead.+ //+ // Trees arrive INCREMENTALLY, which is why this is a lazy layer rather+ // than one up-front walk: the main method tree here, plus one per+ // made-component supersession swap — swapMadeSubAssembly loads the+ // SUCCESSOR's tree and re-enters traverseMethod on it, and that tree's+ // nodes appear in no walk of this one. Every lookup therefore goes+ // through ensurePrefetched, which is idempotent and extends the maps+ // for ids it has not read yet. Without it an unwalked tree resolves to+ // `?? 0` / `?? []`: a whole sub-assembly with no operations and a+ // permanently wrong 0 scrap percentage (jobMaterial.itemScrapPercentage+ // is NOT NULL, and recalculate only re-derives from itemReplenishment+ // when the stored value is NULL, so nothing downstream can repair it).+ const scrapPercentageByItemId = new Map<string, number>();+ const defaultStorageUnitByItemId = new Map<string, string>();+ const jobLocationId = job.locationId;+ let fullestBinAllowed: boolean | undefined;+ async function withFullestBin(reader: typeof db) {+ fullestBinAllowed ??= !(+ await getStrictBackflushSettings(reader, companyId, jobLocationId)+ ).strict;+ return fullestBinAllowed;+ }++ const operationsByMakeMethodId = new Map<string, MethodOperationRow[]>();++ // "Already read for this id" — deliberately distinct from a map miss,+ // which legitimately means "read, no row" (an item with no+ // itemReplenishment, a make method with no operations). Without these+ // sets a sparse item would be re-queried on every visit, which is the+ // N+1 this prefetch exists to remove.+ const prefetchedItemIds = new Set<string>();+ const prefetchedMakeMethodIds = new Set<string>();+ // Identity-based: getMethodTree structuredClones every node per call,+ // so two trees never share node objects. Also stops corrupt/cyclic+ // tree data from looping the walk.+ const seenTreeNodes = new Set<MethodTreeItem>();++ // `reader` is `db` before the transaction opens and `trx` inside it.+ // On a one-connection pool a `db` query issued while the transaction is+ // open would block until the request timeout. itemReplenishment / itemLedger / pickMethod need no embeds,+ // so they go over the direct Postgres connection — bind parameters, no+ // PostgREST URL-length cap (see .ai/lessons.md).+ async function ensureItemsPrefetched(+ reader: typeof db,+ itemIds: string[]+ ) {+ const missing = [...new Set(itemIds)].filter(+ (id) => id && !prefetchedItemIds.has(id)+ );+ if (missing.length === 0) return;++ const replenishmentRows = await reader+ .selectFrom("itemReplenishment")+ .select(["itemId", "scrapPercentage"])+ .where("itemId", "in", missing)+ .where("companyId", "=", companyId)+ .execute();+ for (const row of replenishmentRows) {+ scrapPercentageByItemId.set(+ row.itemId,+ Number(row.scrapPercentage ?? 0)+ );+ }++ // Default storage units at the job's location — two set-based+ // queries instead of up to two per material (getStorageUnitId):+ // pickMethod default wins, else the bin with the highest on-hand+ // quantity — never the fullest bin under strict backflush.+ if (jobLocationId) {+ const ledgerTotals = !(await withFullestBin(reader))+ ? []+ : await reader+ .selectFrom("itemLedger")+ .where("locationId", "=", jobLocationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("storageUnitId", "is not", null)+ .groupBy(["itemId", "storageUnitId"])+ .select([+ "itemId",+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity")+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .execute();++ const bestQuantityByItemId = new Map<string, number>();+ for (const row of ledgerTotals) {+ const quantity = Number(row.totalQuantity);+ if (+ row.storageUnitId &&+ quantity > (bestQuantityByItemId.get(row.itemId) ?? 0)+ ) {+ bestQuantityByItemId.set(row.itemId, quantity);+ defaultStorageUnitByItemId.set(row.itemId, row.storageUnitId);+ }+ }++ const pickMethods = await reader+ .selectFrom("pickMethod")+ .select(["itemId", "defaultStorageUnitId"])+ .where("locationId", "=", jobLocationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("defaultStorageUnitId", "is not", null)+ .execute();++ for (const pickMethod of pickMethods) {+ if (pickMethod.defaultStorageUnitId) {+ defaultStorageUnitByItemId.set(+ pickMethod.itemId,+ pickMethod.defaultStorageUnitId+ );+ }+ }+ }++ // Marked covered only AFTER the rows land, so an id can never read as+ // "already fetched, no row" while its read is still in flight.+ for (const id of missing) prefetchedItemIds.add(id);+ }++ // One read over the direct connection: no URL length to chunk for and+ // no row cap to page around.+ async function ensureMakeMethodsPrefetched(+ reader: typeof db,+ makeMethodIds: string[]+ ) {+ const missing = [...new Set(makeMethodIds)].filter(+ (id) => id && !prefetchedMakeMethodIds.has(id)+ );+ if (missing.length === 0) return;++ for (const op of await readMethodOperations(+ reader,+ missing,+ companyId+ )) {+ const list = operationsByMakeMethodId.get(op.makeMethodId);+ if (list) {+ list.push(op);+ } else {+ operationsByMakeMethodId.set(op.makeMethodId, [op]);+ }+ }+ for (const id of missing) prefetchedMakeMethodIds.add(id);+ }++ // Walk the nodes of `root` that no pass has walked yet and read their+ // lookups in one batch. An already-covered tree returns at its root.+ async function ensurePrefetched(reader: typeof db, root: MethodTreeItem) {+ const nodes: MethodTreeItem[] = [];+ const collect = (n: MethodTreeItem) => {+ if (seenTreeNodes.has(n)) return;+ seenTreeNodes.add(n);+ nodes.push(n);+ n.children.forEach(collect);+ };+ collect(root);+ if (nodes.length === 0) return;++ // A Buy/Pick line is swapped to its successor below, so the successor's+ // scrap percentage and default bin are needed even though no tree node+ // names it. Derived from THIS tree's nodes, not from the whole company's+ // redirect map: that map is every itemSupersession row in the tenant, and+ // feeding all of its targets here made the three reads scale with the+ // company's supersession count instead of the BOM — the same request-+ // timeout class this prefetch exists to remove (and, unchunked, a+ // bind-parameter overflow past ~65k ids). Successor trees loaded by+ // swapMadeSubAssembly re-enter through here, so each covers its own+ // redirect targets by induction.+ //+ // Deliberately NOT exhaustive: a configuration rule can replace a line's+ // itemId with an item no tree node names, and that item may be superseded+ // in turn. Those land on the per-material ensureItemsPrefetched below,+ // which is the safety net for every post-configuration id — this is a+ // batching hint, not the correctness boundary.+ const redirectTargets: string[] = [];+ for (const n of nodes) {+ const to = supersessionRedirect.get(n.data.itemId)?.to;+ if (to) redirectTargets.push(to);+ }++ await ensureItemsPrefetched(reader, [+ ...nodes.map((n) => n.data.itemId),+ ...redirectTargets+ ]);+ await ensureMakeMethodsPrefetched(+ reader,+ nodes.map((n) => n.data.materialMakeMethodId)+ );+ }++ await ensurePrefetched(db, methodTree);++ const getLaborAndOverheadRates = getRatesFromWorkCenters(workCenters);+ const getOutsideOperationRates =+ getRatesFromSupplierProcesses(supplierProcesses);++ // Get configuration code by field+ const configurationCodeByField = configurationRules.reduce<+ Record<string, string>+ >((acc, rule) => {+ acc[rule.field] = rule.code;+ return acc;+ }, {});++ await db.transaction().execute(async (trx) => {+ const insertedJobMaterialIds: string[] = [];+ if (isConfigured) {+ await trx+ .updateTable("job")+ .set({+ configuration: JSON.stringify(configuration),+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Delete existing jobMakeMethod, jobMakeMethodOperation, jobMakeMethodMaterial+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMakeMethod")+ .where((eb) =>+ eb.and([+ eb("jobId", "=", jobId),+ eb("parentMaterialId", "is not", null)+ ])+ )+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMaterial")+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("jobOperation")+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ trx+ .updateTable("jobMakeMethod")+ .set({ version: makeMethod.version ?? 1 })+ .where("id", "=", jobMakeMethod.id)+ .where("companyId", "=", companyId)+ .execute()+ ]);++ // Default storage units are read by ensureItemsPrefetched above, per+ // tree, so a supersession successor's materials get a bin too.++ async function getConfiguredValue<T>({+ id,+ field,+ defaultValue+ }: {+ id: string;+ field: string;+ defaultValue: T;+ }): Promise<T> {+ if (!configurationCodeByField) return defaultValue;+ const fieldKey = getFieldKey(field, id);++ if (configurationCodeByField?.[fieldKey]) {+ try {+ const mod = await importTypeScript(+ configurationCodeByField[fieldKey]+ );+ const result = await mod.configure(hydratedConfiguration);+ return (result ?? defaultValue) as T;+ } catch (err) {+ getMethodLogger.error("configuration field resolver failed", {+ error: String((err as Error)?.stack ?? err)+ });+ return defaultValue;+ }+ }++ return defaultValue;+ }++ // traverse method tree and create:+ // - jobMakeMethod+ // - jobMakeMethodOperation+ // - jobMakeMethodMaterial+ const deferredJobMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const deferredJobMaterialSteps: Database["public"]["Tables"]["jobMaterialStep"]["Insert"][] =+ [];++ async function traverseMethod(+ node: MethodTreeItem,+ parentJobMakeMethodId: string | null,+ parentEstimatedQuantity: number+ ) {+ // The tree handed to us is not necessarily the one prefetched up+ // front: a made-component supersession swap re-enters here on the+ // SUCCESSOR's tree (swapMadeSubAssembly). Covering it at the entry+ // point is what stops the `?? 0` / `?? []` fallbacks below from+ // silently zeroing a whole sub-assembly, for this caller and any+ // future one. `trx`, never `db` — the pool has one connection and+ // the transaction is holding it.+ await ensurePrefetched(trx, node);++ // For root node, targetQuantity equals the job quantity (parentEstimatedQuantity passed in)+ // For children, targetQuantity = parentEstimatedQuantity * quantityPerParent+ const targetQuantity = node.data.isRoot+ ? parentEstimatedQuantity+ : parentEstimatedQuantity * (node.data.quantity ?? 1);++ // Get scrap percentage for this node's item+ const nodeScrapPercentage =+ scrapPercentageByItemId.get(node.data.itemId) ?? 0;++ // Calculate quantities:+ // - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)+ // - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)+ // - scrapQuantity = targetQuantity * scrapRate (the extra needed for scrap)+ // - totalForChildren = target + scrap (passed to children for cascade)+ const nodeScrapQuantity = scrapAllowance(+ targetQuantity,+ nodeScrapPercentage+ );+ const totalWithScrap = targetQuantity + nodeScrapQuantity;++ // For Make: estimatedQuantity is the good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ // operationQuantity is the total (including scrap); fractional+ // targets flow through — the scrap allowance is already whole+ const operationQuantity = totalWithScrap;+ // Pass total (including scrap) to children so cascade works correctly+ const totalQuantityForChildren = totalWithScrap;++ const nodeLevelConfigurationKey = `${+ node.data.materialMakeMethodId+ }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;++ let methodOperationsToJobOperations: Record<string, string> = {};+ // method step id -> new job step id, for copying the part ↔ step link (Phase 2)+ const methodStepsToJobSteps: Record<string, string> = {};++ // For child nodes, always include operations regardless of parts flags+ if (!node.data.isRoot || parts.billOfProcess) {+ const relatedOperations = {+ data:+ operationsByMakeMethodId.get(node.data.materialMakeMethodId) ??+ []+ };++ let jobOperationsInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =+ [];+ // The method operation each insert came from, kept index-aligned+ // with jobOperationsInserts. The inserted ids come back in the+ // order they were inserted, and that order matches neither the+ // length nor the sequence of relatedOperations.data: a blank+ // configured processId skips a row below, and a billOfProcess+ // configuration reorders and filters them. Pairing the returned+ // ids against the source array instead of this one attaches an+ // operation's tools, parameters and steps to the wrong job+ // operation — or reads past the end of the array and throws.+ let sourceOperations: typeof relatedOperations.data = [];+ for await (const op of relatedOperations?.data ?? []) {+ const [+ processId,+ procedureId,+ workCenterId,+ description,+ setupTime,+ setupUnit,+ laborTime,+ laborUnit,+ machineTime,+ machineUnit,+ operationOrder,+ operationType+ ] = await Promise.all([+ getConfiguredValue({+ id: op.id,+ field: "processId",+ defaultValue: op.processId+ }),+ getConfiguredValue({+ id: op.id,+ field: "procedureId",+ defaultValue: op.procedureId+ }),+ getConfiguredValue({+ id: op.id,+ field: "workCenterId",+ defaultValue: op.workCenterId+ }),+ getConfiguredValue({+ id: op.id,+ field: "description",+ defaultValue: op.description+ }),+ getConfiguredValue({+ id: op.id,+ field: "setupTime",+ defaultValue: op.setupTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "setupUnit",+ defaultValue: op.setupUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "laborTime",+ defaultValue: op.laborTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "laborUnit",+ defaultValue: op.laborUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "machineTime",+ defaultValue: op.machineTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "machineUnit",+ defaultValue: op.machineUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "operationOrder",+ defaultValue: op.operationOrder+ }),+ getConfiguredValue({+ id: op.id,+ field: "operationType",+ defaultValue: op.operationType+ })+ ]);++ if (processId === "") continue;++ sourceOperations.push(op);+ jobOperationsInserts.push({+ jobId,+ jobMakeMethodId: parentJobMakeMethodId!,+ processId,+ procedureId,+ workCenterId,+ description,+ setupTime,+ setupUnit,+ laborTime,+ laborUnit,+ machineTime,+ machineUnit,+ ...getLaborAndOverheadRates(processId, op.workCenterId),+ order: op.order,+ operationOrder,+ operationType: normalizeOperationType(operationType),+ // Carry the Assembly → BOP sync link so the MES can drive the+ // animated instruction player on jobs made from a synced method.+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ operationSupplierProcessId: op.operationSupplierProcessId,+ ...getOutsideOperationRates(+ processId,+ op.operationSupplierProcessId+ ),+ workInstruction: toJson(+ !node.data.isRoot || parts.workInstructions+ ? op.workInstruction+ : {}+ ),+ targetQuantity,+ operationQuantity,+ companyId,+ createdBy: userId,+ customFields: {}+ });+ }++ const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;+ let bopConfiguration: string[] | null = null;++ if (configurationCodeByField?.[bopConfigurationKey]) {+ const mod = await importTypeScript(+ configurationCodeByField[bopConfigurationKey]+ );+ bopConfiguration = await mod.configure(hydratedConfiguration);+ }++ if (bopConfiguration) {+ // Reorder and filter both arrays together so an insert and the+ // method operation it came from stay at the same index.+ // findIndex keeps the original `.find` semantics: with duplicate+ // descriptions the first match wins.+ const configuredInserts: typeof jobOperationsInserts = [];+ const configuredSources: typeof sourceOperations = [];+ bopConfiguration.forEach((description, index) => {+ const position = jobOperationsInserts.findIndex(+ (operation) => operation.description === description+ );+ if (position !== -1) {+ configuredInserts.push({+ ...jobOperationsInserts[position]!,+ order: index + 1+ });+ configuredSources.push(sourceOperations[position]!);+ }+ });+ jobOperationsInserts = configuredInserts;+ sourceOperations = configuredSources;+ }++ if (jobOperationsInserts?.length > 0) {+ const operationIds = await trx+ .insertInto("jobOperation")+ .values(jobOperationsInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of sourceOperations.entries()) {+ const operationId = operationIds[index]?.id;++ if (operationId) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;++ // Tool ids already inserted by the assembly-instruction+ // copy — the method tool copy below must skip these or the+ // job gets the same tool twice (once step-linked, once+ // unlinked → the MES shows it on every step AND its step).+ let assemblyToolIds: Set<string> = new Set();++ if (procedureId) {+ await insertProcedureDataForJobOperation(trx, {+ operationId,+ procedureId,+ companyId,+ userId+ });+ } else {+ if (+ (!node.data.isRoot || parts.parameters) &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ const parameters = await Promise.all(+ methodOperationParameter.map(async (param) => ({+ operationId,+ key: param.key,+ value: await getConfiguredValue({+ id: operation.id,+ field: `parameter:${param.id}:value`,+ defaultValue: param.value+ }),+ companyId,+ createdBy: userId+ }))+ );++ await trx+ .insertInto("jobOperationParameter")+ .values(parameters)+ .execute();+ }++ if (operation.assemblyInstructionId) {+ // Assembly ops inherit their steps from the linked+ // instruction (the method only carries the pointer);+ // material ↔ step links are flushed after the+ // jobMaterial rows exist.+ assemblyToolIds = await insertAssemblyDataForJobOperation(+ trx,+ {+ operationId,+ assemblyInstructionId:+ operation.assemblyInstructionId,+ companyId,+ userId+ }+ );+ assemblyOperationsToLink.push({+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId+ });+ } else if (+ (!node.data.isRoot || parts.steps) &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const attributes = await Promise.all(+ methodOperationStep.map(+ async ({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ minValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${_id}:minValue`,+ defaultValue: attribute.minValue+ }),+ maxValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${_id}:maxValue`,+ defaultValue: attribute.maxValue+ }),+ companyId,+ createdBy: userId+ })+ )+ );++ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(attributes)+ .returning(["id"])+ .execute();++ // Bulk insert preserves order, so insertedSteps[i] ↔+ // methodOperationStep[i]: record each method step -> new job step so+ // materials can carry the part ↔ step link onto the job (Phase 2).+ (methodOperationStep as Array<{ id?: string }>).forEach(+ (s, i) => {+ const newStepId = insertedSteps[i]?.id;+ if (s?.id && newStepId)+ methodStepsToJobSteps[s.id] = newStepId;+ }+ );+ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId+ );+ }+ }++ // Tools after steps (Phase 2): the method-step -> job-step map is now+ // populated, so a tool scoped to steps carries those links onto the job via+ // jobOperationToolStep. Mirrors the material part ↔ step copy above. Tools+ // the assembly-instruction copy already inserted are skipped (see above).+ const toolsToCopy = (+ Array.isArray(methodOperationTool)+ ? methodOperationTool+ : []+ ).filter(+ (tool: { toolId: string }) =>+ !assemblyToolIds.has(tool.toolId)+ );+ if (+ (!node.data.isRoot || parts.tools) &&+ toolsToCopy.length > 0+ ) {+ const insertedTools = await trx+ .insertInto("jobOperationTool")+ .values(+ toolsToCopy.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ // Tool ↔ step links (Phase 2, many-to-many). Bulk insert preserves order,+ // so insertedTools[i] ↔ toolsToCopy[i]. A tool with no links applies+ // to the whole operation (shown on every step in the MES).+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {+ const jobOperationToolId = insertedTools[i]?.id;+ if (!jobOperationToolId) return [];+ const oldStepIds = (+ (tool.methodOperationToolStep ?? []) as Array<{+ methodOperationStepId: string | null;+ }>+ ).map((l) => l.methodOperationStepId);+ return remapStepIds(+ oldStepIds,+ methodStepsToJobSteps+ ).map((jobOperationStepId) => ({+ jobOperationToolId,+ jobOperationStepId+ }));+ });+ if (toolStepRows.length > 0) {+ await trx+ .insertInto("jobOperationToolStep")+ .values(toolStepRows)+ .execute();+ }+ }+ }+ }++ methodOperationsToJobOperations = sourceOperations.reduce<+ Record<string, string>+ >((acc, op, index) => {+ const operationId = operationIds[index]?.id;+ if (operationId) {+ acc[op.id!] = operationId;+ }+ return acc;+ }, {});+ }+ } // end if (parts.billOfProcess)++ if (parts.billOfMaterial) {+ const locationId = job.locationId;++ const mapMethodMaterialToJobMaterial = async (+ child: MethodTreeItem+ ) => {+ let [+ itemId,+ description,+ quantity,+ methodType,+ unitOfMeasureCode+ ] = await Promise.all([+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "itemId",+ defaultValue: child.data.itemId+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "description",+ defaultValue: child.data.description+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "quantity",+ defaultValue: child.data.quantity+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "methodType",+ defaultValue: child.data.methodType+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "unitOfMeasureCode",+ defaultValue: child.data.unitOfMeasureCode+ })+ ]);++ if (itemId === "") return null;+ // A configured (or authored) quantity of 0 removes the line from+ // the BOM. Made sub-assemblies drop out of `configuredChildren`+ // below with the row, so their sub-tree is never exploded either.+ if (isZeroQuantity(quantity)) return null;++ let itemType = child.data.itemType;+ let unitCost = child.data.unitCost;+ let requiresSerialTracking =+ child.data.itemTrackingType === "Serial";+ let requiresBatchTracking =+ child.data.itemTrackingType === "Batch";++ // Supersession swap (Buy/Pick lines only). A Make-to-Order line+ // would need its successor's own sub-method re-exploded (a later+ // layer), so we leave those on the old part. The re-derive block+ // just below refreshes the successor's item fields automatically.+ let substitutedFromItemId: string | null = null;+ let substitutionFactor: number | null = null;+ // Captured before the swap so the revert below can undo it whole.+ const quantityBeforeSupersession = quantity;+ const methodTypeBeforeSupersession = methodType;+ // Post-configuration, pre-supersession. A configuration rule may+ // already have moved this line off the BOM's item, and that choice+ // has to survive a failed successor lookup — see the fallback chain+ // below.+ const configuredItemId = itemId;+ if (methodType !== "Make to Order") {+ const redirect = supersessionRedirect.get(itemId);+ if (redirect) {+ substitutedFromItemId = itemId;+ substitutionFactor = redirect.factor;+ itemId = redirect.to;+ quantity = quantity * redirect.factor;+ }+ } else {+ const pulledFrom = resolveMadeLinePull(+ itemId,+ quantity,+ supersessionContext+ );+ if (pulledFrom) {+ methodType = "Pull from Inventory";+ if (pulledFrom.itemId !== itemId) {+ substitutedFromItemId = itemId;+ substitutionFactor = pulledFrom.factor;+ itemId = pulledFrom.itemId;+ quantity = quantity * pulledFrom.factor;+ }+ }+ }++ // Fall back in order of preference: the successor, then whatever a+ // configuration rule chose, then the BOM's own item. Reverting+ // straight to `child.data.itemId` discarded the configuration+ // rule's decision, which the supersession never overrode — it only+ // redirected the item that rule had already picked.+ //+ // Each candidate is READ before it is accepted, so `itemId` and the+ // fields derived from it can never disagree. `child.data.itemId`+ // needs no read: its fields are the defaults already in scope.+ // What this row WOULD be for if every lookup succeeds.+ const intendedItemId = itemId;+ for (const candidate of [+ ...new Set([itemId, configuredItemId, child.data.itemId])+ ]) {+ itemId = candidate;+ if (candidate === child.data.itemId) break;+ const item = await readItemWithCost(trx, candidate, companyId);+ if (item) {+ itemType = item.type;+ unitCost = item.itemCost[0]?.unitCost ?? child.data.unitCost;+ if (description === child.data.description) {+ description = item.name;+ }+ requiresSerialTracking = item.itemTrackingType === "Serial";+ requiresBatchTracking = item.itemTrackingType === "Batch";+ break;+ }+ }++ if (itemId !== intendedItemId) {+ // The swap could not be completed, so undo it WHOLLY. Reverting+ // only `itemId` left the row on a different item while KEEPING+ // the successor's factor-scaled quantity and a+ // `substitutedFromItemId` that no longer described it — a+ // plausible-looking but wrong quantity nothing downstream can+ // detect or repair.+ quantity = quantityBeforeSupersession;+ methodType = methodTypeBeforeSupersession;+ substitutedFromItemId = null;+ substitutionFactor = null;+ }++ // `itemId` here is post-configuration and post-supersession, so+ // it can be an item no tree node named — a configuration rule may+ // return any item id. Cover it before reading, or its scrap+ // percentage silently resolves to 0 and sticks.+ await ensureItemsPrefetched(trx, [itemId]);++ // Get scrap percentage for this item+ const itemScrapPercentage =+ scrapPercentageByItemId.get(itemId) ?? 0;++ // Calculate scrap quantities for this material+ // targetQuantity for this child = parent's total (including scrap) * quantity per parent+ const childTargetQuantity = totalQuantityForChildren * quantity;+ // scrapQuantity = portion attributable to scrap+ const childScrapQuantity = scrapAllowance(+ childTargetQuantity,+ itemScrapPercentage+ );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;+ // For Make: estimatedQuantity is the good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const childEstimatedQuantity =+ methodType === "Make to Order"+ ? childTargetQuantity+ : childTotalWithScrap;++ return {+ jobId,+ jobMakeMethodId: parentJobMakeMethodId!,+ jobOperationId:+ methodOperationsToJobOperations[child.data.operationId],+ // Transient (Phase 2, many-to-many): the part ↔ step links (with their+ // per-step quantity), remapped onto the job's steps. Stripped before+ // insert; used to build jobMaterialStep rows.+ __stepLinks: remapStepLinks(+ (+ child.data as {+ methodOperationStepIds?: Array<+ | string+ | { id?: string | null; quantity?: number | null }+ > | null;+ }+ ).methodOperationStepIds,+ methodStepsToJobSteps+ ),+ itemId,+ itemType,+ kit: methodType === "Make to Order" && child.data.kit,+ methodType,+ order: child.data.order,+ description,+ quantity,+ scrapQuantity: childScrapQuantity,+ estimatedQuantity: childEstimatedQuantity,+ storageUnitId: locationId+ ? // The bin explicitly set on the BOM line stays keyed on the+ // line, but the default bin belongs to the item this row is+ // actually for — `itemId`, after any supersession or+ // configuration swap. Keyed on child.data.itemId a swapped+ // line took the predecessor's bin, or none when only the+ // successor had one.+ // @ts-ignore+ (child.data.storageUnitIds?.[locationId] as string) ||+ defaultStorageUnitByItemId.get(itemId)+ : undefined,+ requiresSerialTracking,+ requiresBatchTracking,+ unitOfMeasureCode,+ unitCost: unitCost ?? 0,+ itemScrapPercentage,+ substitutedFromItemId,+ substitutionFactor,+ companyId,+ createdBy: userId,+ customFields: {}+ };+ };++ const jobMaterialResults = await Promise.all(+ node.children.map(mapMethodMaterialToJobMaterial)+ );+ const validJobMaterialIndices = jobMaterialResults.reduce<number[]>(+ (acc, m, i) => {+ if (m !== null) acc.push(i);+ return acc;+ },+ []+ );+ let materialsWithConfiguredFields = jobMaterialResults.filter(+ (m): m is NonNullable<typeof m> => m !== null+ );+ let configuredChildren = validJobMaterialIndices.map(+ (i) => node.children[i]!+ );++ const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;+ let bomConfiguration: string[] | null = null;++ if (configurationCodeByField?.[bomConfigurationKey]) {+ const mod = await importTypeScript(+ configurationCodeByField[bomConfigurationKey]+ );+ bomConfiguration = await mod.configure(hydratedConfiguration);+ }++ if (bomConfiguration) {+ const pairByReadableId = new Map<+ string,+ {+ material: (typeof materialsWithConfiguredFields)[number];+ child: MethodTreeItem;+ }+ >();+ configuredChildren.forEach((child, i) => {+ const material = materialsWithConfiguredFields[i];+ if (!material) return;+ const data = child!.data as {+ itemReadableId?: string | null;+ readableIdWithRevision?: string | null;+ };+ for (const key of [+ data.readableIdWithRevision,+ data.itemReadableId+ ]) {+ if (key && !pairByReadableId.has(key)) {+ pairByReadableId.set(key, { material, child });+ }+ }+ });+ const pairs = bomConfiguration.flatMap((readableId, index) => {+ const pair = pairByReadableId.get(readableId);+ return pair+ ? [+ {+ material: { ...pair.material, order: index + 1 },+ child: pair.child+ }+ ]+ : [];+ });+ materialsWithConfiguredFields = pairs.map(+ (pair) => pair.material+ );+ configuredChildren = pairs.map((pair) => pair.child);+ }++ const madeMaterials = materialsWithConfiguredFields.filter(+ (material) => material.methodType === "Make to Order"+ );++ const pickedOrBoughtMaterials =+ materialsWithConfiguredFields.filter(+ (material) => material.methodType !== "Make to Order"+ );++ const madeChildren = configuredChildren.filter(+ (_, i) =>+ materialsWithConfiguredFields[i]?.methodType === "Make to Order"+ );++ if (madeMaterials.length > 0) {+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid()+ }));+ insertedJobMaterialIds.push(+ ...madeMaterialsWithIds.map((m) => m.id)+ );++ await trx+ .insertInto("jobMaterial")+ .values(+ madeMaterialsWithIds.map((m) => {+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ };+ return rest;+ })+ )+ .execute();++ // Part ↔ step links (Phase 2, many-to-many): the transient __stepLinks carried+ // the remapped job step ids + per-step quantity; write them to jobMaterialStep+ // now that the material id exists. No links = whole operation (shown on every+ // step in the MES).+ const madeStepRows = madeMaterialsWithIds.flatMap((m) =>+ (+ (+ m as {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ }+ ).__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity+ }))+ );+ if (madeStepRows.length > 0) {+ await trx+ .insertInto("jobMaterialStep")+ .values(madeStepRows)+ .execute();+ }++ const newMakeMethodIds = madeChildren.map(() => nanoid());+ await renameMakeMethods(trx, {+ table: "jobMakeMethod",+ companyId,+ rows: madeChildren.map((_, index) => ({+ parentMaterialId: madeMaterialsWithIds[index]!.id,+ id: newMakeMethodIds[index]!+ }))+ });++ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index]!.id;+ const newMakeMethodId = newMakeMethodIds[index]!;++ // Get the total quantity (estimated + scrap) for this child material+ // This is what we pass to children for the cascade+ const material = madeMaterials[index];+ const childTotalForCascade =+ (material?.estimatedQuantity ?? 0) ++ (material?.scrapQuantity ?? 0);++ // Made sub-assembly supersession: if this made component has an+ // effective successor that is ITSELF a made item, point the job+ // material at the successor and explode the SUCCESSOR's method+ // (not the old part's). A Make -> Buy successor is a structural+ // flip we leave on the old part (handled/flagged elsewhere).+ // A configuration rule may have moved this line onto another+ // made item; the sub-assembly under it is then that item's.+ const made = await configuredMadeChild(+ trx,+ companyId,+ child,+ material?.itemId+ );+ if (!made) continue;++ const madeSwapHandled = await swapMadeSubAssembly({+ trx,+ companyId,+ child: made,+ material,+ materialId,+ locationId: job.locationId ?? "",+ supersessionRedirect,+ newMakeMethodId,+ traverseMethod+ });++ // prevent an infinite loop+ if (!madeSwapHandled && made.data.itemId !== itemId) {+ await traverseMethod(+ made,+ newMakeMethodId,+ childTotalForCascade || 1+ );+ }+ }+ }++ if (pickedOrBoughtMaterials.length > 0) {+ // Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference+ // each row; strip the transient __stepLinks before inserting the material.+ const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({+ ...m,+ id: (m as { id?: string }).id ?? nanoid()+ }));+ insertedJobMaterialIds.push(...pickedWithIds.map((m) => m.id));+ // Inserted once, after the walk: nothing below reads these rows,+ // and their insert triggers only validate.+ deferredJobMaterials.push(+ ...pickedWithIds.map((m) => {+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ };+ return rest;+ })+ );++ const pickedStepRows = pickedWithIds.flatMap((m) =>+ (+ (+ m as {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ }+ ).__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity+ }))+ );+ deferredJobMaterialSteps.push(...pickedStepRows);+ }+ } // end if (parts.billOfMaterial)+ }++ // Start traversal with job quantity as the root's target/parent estimated quantity+ await traverseMethod(methodTree, jobMakeMethod.id, job.quantity ?? 1);+ await insertDeferredJobMaterials(+ trx,+ deferredJobMaterials,+ deferredJobMaterialSteps+ );++ await linkAssemblyStepMaterialsForJobOperations(+ trx,+ assemblyOperationsToLink,+ companyId+ );++ await settleConsumeFirstLines({+ trx,+ companyId,+ jobId: jobId,+ jobMaterialIds: insertedJobMaterialIds,+ locationId: job.locationId,+ asOfDate: jobBuildDate(job)+ });+ });++ break;+ }+ case "itemToJobMakeMethod": {+ const jobMakeMethodId = targetId;++ if (!jobMakeMethodId) {+ throw new Error("Invalid targetId");+ }+ const itemId = sourceId;+ const isConfigured = !!configuration;+ // Assembly ops whose steps were materialized from an instruction —+ // material ↔ step links flush after the traversal inserts the+ // jobMaterial rows.+ const assemblyOperationsToLink: Array<{+ operationId: string;+ assemblyInstructionId: string;+ }> = [];++ // A chosen version overrides the default active-method lookup; it is+ // re-read under itemId + companyId so a foreign or mismatched+ // makeMethod id can never be exploded.+ const makeMethod = versionId+ ? await single(db, "makeMethod", { id: versionId, itemId, companyId })+ : await single(db, "activeMakeMethods", { itemId, companyId });+ const jobMakeMethod = await single(db, "jobMakeMethod", {+ id: jobMakeMethodId,+ companyId+ });+ const workCenters = await many(db, "workCenters", { companyId });+ const supplierProcesses = await many(db, "supplierProcess", {+ companyId+ });++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (jobMakeMethod.error || !jobMakeMethod.data) {+ throw new Error("Failed to get job make method");+ }++ // FIXME: hydrated here but never applied — this make-method path does+ // not run configuration rules (itemToJob does). Applying them is a+ // behavior change for its own PR.+ // biome-ignore lint/correctness/noUnusedVariables: see FIXME above+ const hydratedConfiguration = await hydrateConfiguration(+ db,+ configuration,+ itemId,+ companyId+ );++ // Get parent estimated quantity context+ let parentEstimatedQuantity = 1;+ if (jobMakeMethod.data.parentMaterialId) {+ // This is a sub-item - get the parent material's estimated quantity+ const parentMaterial = await single(db, "jobMaterial", {+ id: jobMakeMethod.data.parentMaterialId,+ companyId+ });+ parentEstimatedQuantity = parentMaterial.data?.estimatedQuantity ?? 1;+ } else {+ // This is the root - get job's quantity+ const rootJob = await single(db, "job", {+ id: jobMakeMethod.data.jobId,+ companyId+ });+ parentEstimatedQuantity = rootJob.data?.quantity ?? 1;+ }++ const job = await single(db, "job", {+ id: jobMakeMethod.data.jobId,+ companyId+ });+ const methodTrees = await getMethodTree(db, makeMethod.data.id!);+ const configurationRules = isConfigured+ ? await many(db, "configurationRule", { itemId, companyId })+ : { data: [] as Tables["configurationRule"]["Row"][] };++ if (methodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const methodTree = methodTrees.data?.[0] as MethodTreeItem;+ if (!methodTree) throw new NotFoundError("Method tree not found");++ // Loaded ONCE per request, before the transaction — as itemToJob does.+ // This read pages the company's whole itemSupersession table, and it used+ // to sit inside traverseMethod, so a BOM of N nodes issued N full-table+ // reads sequentially inside the transaction holding the pool's single+ // connection. The map depends only on the company and the job's build+ // date, both fixed for the request, so per-node reload bought nothing.+ const supersessionContext = await loadSupersessionRedirect(+ db,+ companyId,+ job.data+ );+ const supersessionRedirect = supersessionContext.redirect;+ const itemDefaults = createItemDefaults(companyId, job.data?.locationId);++ const getLaborAndOverheadRates = getRatesFromWorkCenters(+ workCenters?.data+ );+ const getOutsideOperationRates = getRatesFromSupplierProcesses(+ supplierProcesses?.data+ );++ // Get configuration code by field+ // biome-ignore lint/correctness/noUnusedVariables: unapplied configuration, see FIXME above+ const configurationCodeByField = configurationRules.data?.reduce<+ Record<string, string>+ >((acc, rule) => {+ acc[rule.field] = rule.code;+ return acc;+ }, {});++ await db.transaction().execute(async (trx) => {+ await itemDefaults.load(+ trx,+ treeItemIds(methodTree, supersessionRedirect)+ );+ const insertedJobMaterialIds: string[] = [];+ // Delete existing jobMakeMethodOperation, jobMakeMethodMaterial+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMaterial")+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("jobOperation")+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ trx+ .updateTable("jobMakeMethod")+ .set({ version: makeMethod.data.version ?? 1 })+ .where("id", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ ]);++ // traverse method tree and create:+ // - jobMakeMethod+ // - jobMakeMethodOperation+ // - jobMakeMethodMaterial+ const deferredJobMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const deferredJobMaterialSteps: Database["public"]["Tables"]["jobMaterialStep"]["Insert"][] =+ [];++ async function traverseMethod(+ node: MethodTreeItem,+ parentJobMakeMethodId: string | null,+ nodeParentEstimatedQuantity: number+ ) {+ // Calculate target and estimated quantities for this node+ const targetQuantity = node.data.isRoot+ ? nodeParentEstimatedQuantity+ : nodeParentEstimatedQuantity * (node.data.quantity ?? 1);++ // Get scrap percentage for this node's item+ const nodeScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ node.data.itemId+ );++ // Calculate quantities:+ // - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)+ // - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)+ const nodeScrapQuantity = scrapAllowance(+ targetQuantity,+ nodeScrapPercentage+ );+ const totalWithScrap = targetQuantity + nodeScrapQuantity;+ // operationQuantity is the total (including scrap); fractional+ // targets flow through — the scrap allowance is already whole+ const operationQuantity = totalWithScrap;+ const totalQuantityForChildren = totalWithScrap;++ const relatedOperations = {+ data: await readMethodOperations(+ trx,+ [node.data.materialMakeMethodId],+ companyId+ )+ };++ const jobOperationsInserts =+ relatedOperations?.data?.map((op) => ({+ jobId: jobMakeMethod.data?.jobId!,+ jobMakeMethodId: parentJobMakeMethodId!,+ processId: op.processId,+ procedureId: op.procedureId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ ...getLaborAndOverheadRates(op.processId, op.workCenterId),+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ // Carry the Assembly → BOP sync link so the MES can drive the+ // animated instruction player on jobs made from a synced method.+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ operationUnitCost: op.operationUnitCost ?? 0,+ operationSupplierProcessId: op.operationSupplierProcessId,+ ...getOutsideOperationRates(+ op.processId,+ op.operationSupplierProcessId+ ),+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ targetQuantity,+ operationQuantity,+ companyId,+ createdBy: userId,+ customFields: {}+ })) ?? [];++ let methodOperationsToJobOperations: Record<string, string> = {};+ // method step id -> new job step id, for copying the part ↔ step link (Phase 2)+ const methodStepsToJobSteps: Record<string, string> = {};++ if (parts.billOfProcess) {+ if (jobOperationsInserts?.length > 0) {+ const operationIds = await trx+ .insertInto("jobOperation")+ .values(jobOperationsInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ relatedOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;++ if (operationId) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;++ // Tool ids already inserted by the assembly-instruction+ // copy — the method tool copy below must skip these or the+ // job gets the same tool twice (once step-linked, once+ // unlinked → the MES shows it on every step AND its step).+ let assemblyToolIds: Set<string> = new Set();++ if (procedureId) {+ await insertProcedureDataForJobOperation(trx, {+ operationId,+ procedureId,+ companyId,+ userId+ });+ } else {+ if (+ parts.parameters &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ await trx+ .insertInto("jobOperationParameter")+ .values(+ methodOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (operation.assemblyInstructionId) {+ // Assembly ops inherit their steps from the linked+ // instruction (the method only carries the pointer);+ // material ↔ step links are flushed after the+ // jobMaterial rows exist.+ assemblyToolIds = await insertAssemblyDataForJobOperation(+ trx,+ {+ operationId,+ assemblyInstructionId:+ operation.assemblyInstructionId,+ companyId,+ userId+ }+ );+ assemblyOperationsToLink.push({+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId+ });+ } else if (+ parts.steps &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ methodOperationStep.map(+ ({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ })+ )+ )+ .returning(["id"])+ .execute();++ // Bulk insert preserves order, so insertedSteps[i] ↔+ // methodOperationStep[i]: record each method step -> new job step so+ // materials can carry the part ↔ step link onto the job (Phase 2).+ (methodOperationStep as Array<{ id?: string }>).forEach(+ (s, i) => {+ const newStepId = insertedSteps[i]?.id;+ if (s?.id && newStepId)+ methodStepsToJobSteps[s.id] = newStepId;+ }+ );+ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId+ );+ }+ }++ // Tools after steps (Phase 2): the method-step -> job-step map is now+ // populated, so a tool scoped to steps carries those links onto the job via+ // jobOperationToolStep. Mirrors the material part ↔ step copy above. Tools+ // the assembly-instruction copy already inserted are skipped (see above).+ const toolsToCopy = (+ Array.isArray(methodOperationTool)+ ? methodOperationTool+ : []+ ).filter(+ (tool: { toolId: string }) =>+ !assemblyToolIds.has(tool.toolId)+ );+ if (parts.tools && toolsToCopy.length > 0) {+ const insertedTools = await trx+ .insertInto("jobOperationTool")+ .values(+ toolsToCopy.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ // Tool ↔ step links (Phase 2, many-to-many). Bulk insert preserves order,+ // so insertedTools[i] ↔ toolsToCopy[i]. A tool with no links applies+ // to the whole operation (shown on every step in the MES).+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {+ const jobOperationToolId = insertedTools[i]?.id;+ if (!jobOperationToolId) return [];+ const oldStepIds = (+ (tool.methodOperationToolStep ?? []) as Array<{+ methodOperationStepId: string | null;+ }>+ ).map((l) => l.methodOperationStepId);+ return remapStepIds(+ oldStepIds,+ methodStepsToJobSteps+ ).map((jobOperationStepId) => ({+ jobOperationToolId,+ jobOperationStepId+ }));+ });+ if (toolStepRows.length > 0) {+ await trx+ .insertInto("jobOperationToolStep")+ .values(toolStepRows)+ .execute();+ }+ }+ }+ }++ methodOperationsToJobOperations =+ relatedOperations.data?.reduce<Record<string, string>>(+ (acc, op, index) => {+ if (operationIds[index]!.id) {+ acc[op.id!] = operationIds[index]!.id!;+ }+ return acc;+ },+ {}+ ) ?? {};+ }+ } // end if (parts.billOfProcess)++ if (parts.billOfMaterial) {+ const mapMethodMaterialToJobMaterial = async (+ child: MethodTreeItem+ ) => {+ // Resolve the supersession FIRST, so every field below derives+ // from the item this row ENDS UP being for. This used to run as a+ // second pass over the finished rows, which meant each new derived+ // field silently inherited the predecessor's value unless someone+ // remembered to add it to that pass's patch list — the scrap rate+ // was read here from the OLD item and never revisited, so a swapped+ // line costed the predecessor's scrap forever (the column is NOT+ // NULL, and recalculate only re-derives from NULL). Swapping up+ // front is what itemToJob already does, and it makes the whole+ // class of bug unreachable rather than fixing one instance of it.+ // Buy/Pick only — resolveJobMaterialSupersession returns null for+ // Make to Order, which swapMadeSubAssembly handles during its own+ // explosion.+ const pulledFrom =+ child.data.methodType === "Make to Order"+ ? resolveMadeLinePull(+ child.data.itemId,+ child.data.quantity ?? 1,+ supersessionContext+ )+ : null;+ const methodType = pulledFrom+ ? "Pull from Inventory"+ : child.data.methodType;+ const supersession =+ pulledFrom && pulledFrom.itemId === child.data.itemId+ ? null+ : await resolveJobMaterialSupersession(+ trx,+ companyId,+ pulledFrom+ ? new Map([+ [+ child.data.itemId,+ {+ to: pulledFrom.itemId,+ factor: pulledFrom.factor+ }+ ]+ ])+ : supersessionRedirect,+ { itemId: child.data.itemId, methodType }+ );+ const itemId = supersession?.itemId ?? child.data.itemId;+ // 1 old part = `factor` successors. The line's methodType and unit+ // of measure are deliberately preserved; the factor translates the+ // quantity.+ const quantityPerParent =+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);++ // Get scrap percentage for this item+ const itemScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ itemId+ );++ // Calculate scrap quantities for this material+ // Use totalQuantityForChildren (parent's total including scrap) for child calculations+ const childTargetQuantity =+ totalQuantityForChildren * quantityPerParent;+ const childScrapQuantity = scrapAllowance(+ childTargetQuantity,+ itemScrapPercentage+ );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;+ // For Make: estimatedQuantity is the good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const childEstimatedQuantity =+ methodType === "Make to Order"+ ? childTargetQuantity+ : childTotalWithScrap;++ return {+ jobId: jobMakeMethod.data?.jobId!,+ jobMakeMethodId: parentJobMakeMethodId!,+ jobOperationId:+ methodOperationsToJobOperations[child.data.operationId],+ // Transient (Phase 2, many-to-many): the part ↔ step links (with their+ // per-step quantity), remapped onto the job's steps. Stripped before+ // insert; used to build jobMaterialStep rows.+ __stepLinks: remapStepLinks(+ (+ child.data as {+ methodOperationStepIds?: Array<+ | string+ | { id?: string | null; quantity?: number | null }+ > | null;+ }+ ).methodOperationStepIds,+ methodStepsToJobSteps+ ),+ itemId,+ kit: methodType === "Make to Order" && child.data.kit,+ itemType: supersession?.itemType ?? child.data.itemType,+ methodType,+ order: child.data.order,+ description:+ supersession?.description ?? child.data.description,+ quantity: quantityPerParent,+ scrapQuantity: childScrapQuantity,+ estimatedQuantity: childEstimatedQuantity,+ requiresBatchTracking:+ supersession?.requiresBatchTracking ??+ child.data.itemTrackingType === "Batch",+ requiresSerialTracking:+ supersession?.requiresSerialTracking ??+ child.data.itemTrackingType === "Serial",+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ // Branch on WHETHER a swap happened, not just on the successor+ // having a cost. `supersession?.unitCost ?? child.data.unitCost`+ // valued a successor row at the RETIRED part's cost whenever the+ // successor had no itemCost row — a plausible number for the+ // wrong item. 0 is at least visibly missing.+ unitCost: supersession+ ? (supersession.unitCost ?? 0)+ : (child.data.unitCost ?? 0),+ itemScrapPercentage,+ substitutedFromItemId:+ supersession?.substitutedFromItemId ?? null,+ substitutionFactor: supersession?.factor ?? null,+ // The bin belongs to the item this row is actually for — the+ // post-swap `itemId`. An explicit bin on the BOM line still wins.+ storageUnitId: await itemDefaults.storageUnitId(+ trx,+ itemId,+ // @ts-ignore: storageUnitIds is a dynamic field+ child.data.storageUnitIds?.[job.data.locationId] ?? undefined+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ };+ };++ const madeMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const madeChildren: MethodTreeItem[] = [];+ const pickedOrBoughtMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];++ for await (const child of node.children) {+ if (isZeroQuantity(child.data.quantity)) continue;+ const material = await mapMethodMaterialToJobMaterial(child);+ if (material.methodType === "Make to Order") {+ madeMaterials.push(material);+ madeChildren.push(child);+ } else {+ pickedOrBoughtMaterials.push(material);+ }+ }++ // The supersession swap happens inside mapMethodMaterialToJobMaterial,+ // before any field derives from the item — there is deliberately no+ // second pass here. Made materials are left for their own+ // sub-explosion (swapMadeSubAssembly).++ if (madeMaterials.length > 0) {+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid()+ }));+ insertedJobMaterialIds.push(+ ...madeMaterialsWithIds.map((m) => m.id)+ );++ await trx+ .insertInto("jobMaterial")+ .values(+ madeMaterialsWithIds.map((m) => {+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ };+ return rest;+ })+ )+ .execute();++ // Part ↔ step links (Phase 2, many-to-many): the transient __stepLinks carried+ // the remapped job step ids + per-step quantity; write them to jobMaterialStep+ // now that the material id exists. No links = whole operation (shown on every+ // step in the MES).+ const madeStepRows = madeMaterialsWithIds.flatMap((m) =>+ (+ (+ m as {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ }+ ).__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity+ }))+ );+ if (madeStepRows.length > 0) {+ await trx+ .insertInto("jobMaterialStep")+ .values(madeStepRows)+ .execute();+ }++ const newMakeMethodIds = madeChildren.map(() => nanoid());+ await renameMakeMethods(trx, {+ table: "jobMakeMethod",+ companyId,+ rows: madeChildren.map((_, index) => ({+ parentMaterialId: madeMaterialsWithIds[index]!.id,+ id: newMakeMethodIds[index]!+ }))+ });++ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index]!.id;+ const newMakeMethodId = newMakeMethodIds[index]!;++ // Get the total quantity (estimated + scrap) for this child material+ // This is what we pass to children for the cascade+ const material = madeMaterials[index];+ const childTotalForCascade =+ (material?.estimatedQuantity ?? 0) ++ (material?.scrapQuantity ?? 0);++ // Made sub-assembly supersession (see itemToJob for rationale):+ // if a made component has an effective successor that is itself+ // made, point the job material at the successor and explode the+ // SUCCESSOR's method instead of the old part's.+ // A configuration rule may have moved this line onto another+ // made item; the sub-assembly under it is then that item's.+ const made = await configuredMadeChild(+ trx,+ companyId,+ child,+ material?.itemId+ );+ if (!made) continue;++ const madeSwapHandled = await swapMadeSubAssembly({+ trx,+ companyId,+ child: made,+ material,+ materialId,+ locationId: job.data?.locationId ?? "",+ supersessionRedirect,+ newMakeMethodId,+ traverseMethod+ });++ // prevent an infinite loop+ if (!madeSwapHandled && made.data.itemId !== itemId) {+ await traverseMethod(+ made,+ newMakeMethodId,+ childTotalForCascade || 1+ );+ }+ }+ }++ if (pickedOrBoughtMaterials.length > 0) {+ // Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference+ // each row; strip the transient __stepLinks before inserting the material.+ const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({+ ...m,+ id: (m as { id?: string }).id ?? nanoid()+ }));+ insertedJobMaterialIds.push(...pickedWithIds.map((m) => m.id));+ // Inserted once, after the walk: nothing below reads these rows,+ // and their insert triggers only validate.+ deferredJobMaterials.push(+ ...pickedWithIds.map((m) => {+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ };+ return rest;+ })+ );++ const pickedStepRows = pickedWithIds.flatMap((m) =>+ (+ (+ m as {+ __stepLinks?: {+ stepId: string;+ quantity: number | null;+ }[];+ }+ ).__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity+ }))+ );+ deferredJobMaterialSteps.push(...pickedStepRows);+ }+ } // end if (parts.billOfMaterial)+ }++ // Start traversal with the parent's estimated quantity+ await traverseMethod(+ methodTree,+ jobMakeMethod.data.id,+ parentEstimatedQuantity+ );+ await insertDeferredJobMaterials(+ trx,+ deferredJobMaterials,+ deferredJobMaterialSteps+ );++ await linkAssemblyStepMaterialsForJobOperations(+ trx,+ assemblyOperationsToLink,+ companyId+ );++ await settleConsumeFirstLines({+ trx,+ companyId,+ jobId: jobMakeMethod.data.jobId,+ jobMaterialIds: insertedJobMaterialIds,+ locationId: job.data?.locationId,+ asOfDate: jobBuildDate(job.data)+ });+ });+ break;+ }+ case "itemToQuoteLine": {+ const [quoteId = "", quoteLineId = ""] = (targetId as string).split(":");+ if (!quoteId || !quoteLineId) {+ throw new Error("Invalid targetId");+ }+ const itemId = sourceId;+ const isConfigured = !!configuration;++ const [+ makeMethod,+ quoteMakeMethod,+ workCenters,+ supplierProcesses,+ configurationRules,+ quote,+ ownedQuoteLine+ ] = await inOrder([+ () => single(db, "activeMakeMethods", { itemId, companyId }),+ () =>+ maybeSingle(db, "quoteMakeMethod", {+ quoteLineId,+ parentMaterialId: isNull,+ companyId+ }),+ () => many(db, "workCenters", { companyId }),+ () => many(db, "supplierProcess", { companyId }),+ () =>+ isConfigured+ ? many(db, "configurationRule", { itemId, companyId })+ : Promise.resolve({ data: null, error: null }),+ () => single(db, "quote", { id: quoteId, companyId }),+ () =>+ maybeSingle(db, "quoteLine", {+ id: quoteLineId,+ quoteId,+ companyId+ })+ ]);++ // The permission check proved the CALLER may act in companyId; it proves+ // nothing about the quote line in the body. The quoteMakeMethod lookup+ // is scoped, but a miss INSERTS one and then rewrites the line's+ // materials and operations by quoteLineId alone.+ if (ownedQuoteLine.error) {+ throw new Error("Failed to get quote line");+ }+ if (!ownedQuoteLine.data) {+ throw new NotFoundError("Quote line not found");+ }++ const configurationCodeByField = configurationRules?.data?.reduce<+ Record<string, string>+ >((acc, rule) => {+ acc[rule.field] = rule.code;+ return acc;+ }, {});++ const quoteLocationId = quote.data?.locationId;++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (quoteMakeMethod.error) {+ throw new Error("Failed to get quote make method");+ }++ if (!quoteMakeMethod.data) {+ await db+ .insertInto("quoteMakeMethod")+ .values({+ quoteId,+ quoteLineId,+ itemId,+ companyId,+ createdBy: userId+ })+ .execute();+ // Read back in the shape the rest of this flow uses.+ const inserted = await single(db, "quoteMakeMethod", {+ quoteLineId,+ parentMaterialId: isNull,+ companyId+ });++ if (inserted.error || !inserted.data) {+ throw new Error("Failed to create quote make method");+ }+ quoteMakeMethod.data = inserted.data;+ }++ if (workCenters.error) {+ throw new Error("Failed to get related work centers");+ }++ const hydratedConfiguration = await hydrateConfiguration(+ db,+ configuration,+ itemId,+ companyId+ );++ const [methodTrees] = await inOrder([+ () => getMethodTree(db, makeMethod.data.id!)+ ]);++ if (methodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const methodTree = methodTrees.data?.[0] as MethodTreeItem;+ if (!methodTree) throw new NotFoundError("Method tree not found");++ const getLaborAndOverheadRates = getRatesFromWorkCenters(+ workCenters?.data+ );+ const getOutsideOperationRates = getRatesFromSupplierProcesses(+ supplierProcesses?.data+ );++ await db+ .transaction()+ .execute(async (trx: Transaction<KyselyDatabase>) => {+ if (isConfigured) {+ await trx+ .updateTable("quoteLine")+ .set({+ configuration: JSON.stringify(configuration),+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", quoteLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Delete existing quoteMakeMethod, quoteMakeMethodOperation, quoteMakeMethodMaterial+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("quoteMakeMethod")+ .where((eb) =>+ eb.and([+ eb("quoteLineId", "=", quoteLineId),+ eb("parentMaterialId", "is not", null)+ ])+ )+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("quoteMaterial")+ .where("quoteLineId", "=", quoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteLineId", "=", quoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("quoteOperation")+ .where("quoteLineId", "=", quoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ trx+ .updateTable("quoteMakeMethod")+ .set({ version: makeMethod.data.version ?? 1 })+ .where("id", "=", quoteMakeMethod.data!.id!)+ .where("companyId", "=", companyId)+ .execute()+ ]);++ async function getConfiguredValue<+ T extends number | string | boolean | null+ >({+ id,+ field,+ defaultValue+ }: {+ id: string;+ field: string;+ defaultValue: T;+ }): Promise<T> {+ if (!configurationCodeByField) return defaultValue;++ const fieldKey = getFieldKey(field, id);++ if (configurationCodeByField[fieldKey]) {+ try {+ const code = configurationCodeByField[fieldKey];+ const mod = await importTypeScript(code);+ const result = await mod.configure(hydratedConfiguration);++ return (result ?? defaultValue) as T;+ } catch (err) {+ getMethodLogger.error("configuration field resolver failed", {+ error: String((err as Error)?.stack ?? err)+ });+ return defaultValue;+ }+ }++ return defaultValue;+ }++ // traverse method tree and create:+ // - quoteMakeMethod+ // - quoteMakeMethodOperation+ // - quoteMakeMethodMaterial+ async function traverseMethod(+ node: MethodTreeItem,+ parentQuoteMakeMethodId: string | null+ ) {+ getMethodLogger.debug("[traverseMethod]", {+ isRoot: node.data.isRoot,+ itemId: node.data.itemId,+ methodType: node.data.methodType,+ materialMakeMethodId: node.data.materialMakeMethodId,+ childCount: node.children.length,+ childMethodTypes: node.children.map((c) => ({+ itemId: c.data.itemId,+ methodType: c.data.methodType+ })),+ parentQuoteMakeMethodId+ });++ let methodOperationsToQuoteOperations: Record<string, string> = {};++ const nodeLevelConfigurationKey = `${+ node.data.materialMakeMethodId+ }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;++ // For child nodes, always include operations regardless of parts flags+ if (!node.data.isRoot || parts.billOfProcess) {+ const relatedOperations = {+ data: treeOperations.get(node.data.materialMakeMethodId) ?? []+ };++ let quoteOperationsInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =+ [];+ // Index-aligned with quoteOperationsInserts, as in itemToJob:+ // a blank configured processId skips a row and a billOfProcess+ // configuration reorders and filters them, so the returned ids+ // cannot be paired against relatedOperations.data.+ let sourceOperations: typeof relatedOperations.data = [];+ for await (const op of relatedOperations?.data ?? []) {+ const [+ processId,+ procedureId,+ workCenterId,+ description,+ setupTime,+ setupUnit,+ laborTime,+ laborUnit,+ machineTime,+ machineUnit,+ operationOrder,+ operationType+ ] = await Promise.all([+ getConfiguredValue({+ id: op.id,+ field: "processId",+ defaultValue: op.processId+ }),+ getConfiguredValue({+ id: op.id,+ field: "procedureId",+ defaultValue: op.procedureId+ }),+ getConfiguredValue({+ id: op.id,+ field: "workCenterId",+ defaultValue: op.workCenterId+ }),+ getConfiguredValue({+ id: op.id,+ field: "description",+ defaultValue: op.description+ }),+ getConfiguredValue({+ id: op.id,+ field: "setupTime",+ defaultValue: op.setupTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "setupUnit",+ defaultValue: op.setupUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "laborTime",+ defaultValue: op.laborTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "laborUnit",+ defaultValue: op.laborUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "machineTime",+ defaultValue: op.machineTime+ }),+ getConfiguredValue({+ id: op.id,+ field: "machineUnit",+ defaultValue: op.machineUnit+ }),+ getConfiguredValue({+ id: op.id,+ field: "operationOrder",+ defaultValue: op.operationOrder+ }),+ getConfiguredValue({+ id: op.id,+ field: "operationType",+ defaultValue: op.operationType+ })+ ]);++ if (processId === "") continue;++ const operationRates = getLaborAndOverheadRates(+ processId,+ op.workCenterId+ );+ getMethodLogger.debug("traverseMethod", {+ processId,+ ...operationRates+ });++ sourceOperations.push(op);+ quoteOperationsInserts.push({+ quoteId,+ quoteLineId,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ processId,+ procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId,+ description,+ setupTime,+ setupUnit,+ laborTime,+ laborUnit,+ machineTime,+ machineUnit,+ ...getLaborAndOverheadRates(processId, op.workCenterId),+ order: op.order,+ operationOrder,+ operationType: normalizeOperationType(operationType),+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationUnitCost: op.operationUnitCost ?? 0,+ ...getOutsideOperationRates(+ processId,+ op.operationSupplierProcessId+ ),+ operationMinimumCost: op.operationMinimumCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ !node.data.isRoot || parts.workInstructions+ ? op.workInstruction+ : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ });+ }++ const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;+ let bopConfiguration: string[] | null = null;++ if (configurationCodeByField?.[bopConfigurationKey]) {+ const mod = await importTypeScript(+ configurationCodeByField[bopConfigurationKey]+ );+ bopConfiguration = await mod.configure(hydratedConfiguration);+ }++ if (bopConfiguration) {+ const configuredInserts: typeof quoteOperationsInserts = [];+ const configuredSources: typeof sourceOperations = [];+ bopConfiguration.forEach((description, index) => {+ const position = quoteOperationsInserts.findIndex(+ (operation) => operation.description === description+ );+ if (position !== -1) {+ configuredInserts.push({+ ...quoteOperationsInserts[position]!,+ order: index + 1+ });+ configuredSources.push(sourceOperations[position]!);+ }+ });+ quoteOperationsInserts = configuredInserts;+ sourceOperations = configuredSources;+ }++ if (quoteOperationsInserts?.length > 0) {+ const operationIds = await trx+ .insertInto("quoteOperation")+ .values(quoteOperationsInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of sourceOperations.entries()) {+ const operationId = operationIds[index]?.id;++ if (operationId) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;++ if (+ (!node.data.isRoot || parts.tools) &&+ Array.isArray(methodOperationTool) &&+ methodOperationTool.length > 0+ ) {+ await trx+ .insertInto("quoteOperationTool")+ .values(+ methodOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ (!node.data.isRoot || parts.parameters) &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ const parameters = await Promise.all(+ methodOperationParameter.map(async (param) => ({+ operationId,+ key: param.key,+ value: await getConfiguredValue({+ id: operation.id,+ field: `parameter:${param.id}:value`,+ defaultValue: param.value+ }),+ companyId,+ createdBy: userId+ }))+ );++ await trx+ .insertInto("quoteOperationParameter")+ .values(parameters)+ .execute();+ }++ if (+ (!node.data.isRoot || parts.steps) &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const attributes = await Promise.all(+ methodOperationStep.map(+ async ({+ id,+ // quoteOperationStep has no provenance marker+ assemblyInstructionStepId:+ _assemblyInstructionStepId,+ ...attribute+ }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ minValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${id}:minValue`,+ defaultValue: attribute.minValue+ }),+ maxValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${id}:maxValue`,+ defaultValue: attribute.maxValue+ }),+ companyId,+ createdBy: userId+ })+ )+ );++ const insertedSteps = await trx+ .insertInto("quoteOperationStep")+ .values(attributes)+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "quoteOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }++ methodOperationsToQuoteOperations = sourceOperations.reduce<+ Record<string, string>+ >((acc, op, index) => {+ const operationId = operationIds[index]?.id;+ if (operationId) {+ acc[op.id!] = operationId;+ }+ return acc;+ }, {});+ }+ } // end if (parts.billOfProcess)++ if (parts.billOfMaterial) {+ const mapMethodMaterialToQuoteMaterial = async (+ child: MethodTreeItem+ ) => {+ let [+ itemId,+ description,+ quantity,+ methodType,+ unitOfMeasureCode+ ] = await Promise.all([+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "itemId",+ defaultValue: child.data.itemId+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "description",+ defaultValue: child.data.description+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "quantity",+ defaultValue: child.data.quantity+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "methodType",+ defaultValue: child.data.methodType+ }),+ getConfiguredValue({+ id: child.data.methodMaterialId,+ field: "unitOfMeasureCode",+ defaultValue: child.data.unitOfMeasureCode+ })+ ]);++ if (itemId === "") return null;+ // A configured (or authored) quantity of 0 removes the line from+ // the BOM (and its sub-tree, via configuredChildren below).+ if (isZeroQuantity(quantity)) return null;++ let itemType = child.data.itemType;+ let unitCost = child.data.unitCost;++ // TODO: if the methodType is Make and the default value is not Make, we need to do itemToQuoteMakeMethod for that material++ if (itemId !== child.data.itemId) {+ const item = await single<+ "item",+ Tables["item"]["Row"] & {+ itemCost: Tables["itemCost"]["Row"][];+ }+ >(+ trx,+ "item",+ { id: itemId, companyId },+ {+ embed: { itemCost: { table: "itemCost", on: "itemId" } }+ }+ );+ if (item.data) {+ itemType = item.data.type;+ unitCost =+ item.data.itemCost[0]?.unitCost ?? child.data.unitCost;+ if (description === child.data.description) {+ description = item.data.name;+ }+ } else {+ itemId = child.data.itemId;+ }+ }++ return {+ quoteId,+ quoteLineId,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ quoteOperationId:+ methodOperationsToQuoteOperations[child.data.operationId],+ order: child.data.order,+ itemId,+ itemType,+ kit: child.data.kit,+ methodType,+ description,+ quantity,+ storageUnitId: quoteLocationId+ ? // @ts-ignore: storageUnitIds is a dynamic object with location keys+ (child.data.storageUnitIds?.[+ quoteLocationId+ ] as string) || null+ : null,+ unitOfMeasureCode,+ unitCost: unitCost ?? 0,+ companyId,+ createdBy: userId,+ customFields: {}+ };+ };++ const quoteMaterialResults = await Promise.all(+ node.children.map(mapMethodMaterialToQuoteMaterial)+ );+ const validQuoteMaterialIndices = quoteMaterialResults.reduce<+ number[]+ >((acc, m, i) => {+ if (m !== null) acc.push(i);+ return acc;+ }, []);+ let materialsWithConfiguredFields = quoteMaterialResults.filter(+ (m): m is NonNullable<typeof m> => m !== null+ );+ const configuredChildren = validQuoteMaterialIndices.map(+ (i) => node.children[i]!+ );++ const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;+ let bomConfiguration: string[] | null = null;++ if (configurationCodeByField?.[bomConfigurationKey]) {+ const mod = await importTypeScript(+ configurationCodeByField[bomConfigurationKey]+ );+ bomConfiguration = await mod.configure(hydratedConfiguration);+ }++ if (bomConfiguration) {+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step+ materialsWithConfiguredFields = bomConfiguration+ .map((readableIdWithRevision, index) => {+ const material = materialsWithConfiguredFields.find(+ (material) => material.itemId === itemId+ );+ if (material) {+ return {+ ...material,+ order: index + 1+ };+ }+ })+ .filter(Boolean);+ }++ const madeMaterials = materialsWithConfiguredFields.filter(+ (material) => material.methodType === "Make to Order"+ );++ const pickedOrBoughtMaterials =+ materialsWithConfiguredFields.filter(+ (material) => material.methodType !== "Make to Order"+ );++ const madeChildren = configuredChildren.filter(+ (child) => child!.data.methodType === "Make to Order"+ );++ getMethodLogger.debug("[traverseMethod] materials", {+ totalChildren: materialsWithConfiguredFields.length,+ madeMaterialsCount: madeMaterials.length,+ madeChildrenCount: madeChildren.length,+ pickedOrBoughtCount: pickedOrBoughtMaterials.length+ });++ if (madeMaterials.length > 0) {+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid()+ }));++ await trx+ .insertInto("quoteMaterial")+ .values(madeMaterialsWithIds)+ .execute();++ const newMakeMethodIds = madeChildren.map(() => nanoid());+ await renameMakeMethods(trx, {+ table: "quoteMakeMethod",+ companyId,+ rows: madeChildren.map((_, index) => ({+ parentMaterialId: madeMaterialsWithIds[index]!.id,+ id: newMakeMethodIds[index]!+ }))+ });++ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index]!.id;+ const newMakeMethodId = newMakeMethodIds[index]!;++ getMethodLogger.debug(+ "[traverseMethod] processing made child",+ {+ index,+ materialId,+ newMakeMethodId,+ childItemId: child!.data.itemId,+ parentItemId: itemId,+ willRecurse: child!.data.itemId !== itemId+ }+ );++ // A configuration rule may have moved this line onto another+ // made item; the sub-assembly under it is then that item's.+ const made = await configuredMadeChild(+ trx,+ companyId,+ child!,+ madeMaterialsWithIds[index]!.itemId+ );+ if (!made) continue;+ if (made !== child) {+ for (const [id, ops] of await readOperationsForTree(+ trx,+ made+ ))+ treeOperations.set(id, ops);+ }++ // prevent an infinite loop+ if (made.data.itemId !== itemId) {+ await traverseMethod(made, newMakeMethodId);+ }+ }+ }++ deferredQuoteMaterials.push(...pickedOrBoughtMaterials);+ } // end if (parts.billOfMaterial)+ }++ function logTree(node: MethodTreeItem, depth = 0) {+ getMethodLogger.debug(+ " ".repeat(depth) ++ `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`+ );+ for (const child of node.children) {+ logTree(child, depth + 1);+ }+ }+ logTree(methodTree);++ const treeOperations = await readOperationsForTree(trx, methodTree);+ const deferredQuoteMaterials: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =+ [];+ await traverseMethod(methodTree, quoteMakeMethod.data!.id);+ for (const chunk of chunked(deferredQuoteMaterials)) {+ await trx.insertInto("quoteMaterial").values(chunk).execute();+ }+ });++ await calculateQuoteLinePrices(+ db,+ quoteId,+ quoteLineId,+ companyId,+ userId+ );++ break;+ }+ case "itemToQuoteMakeMethod": {+ const quoteMakeMethodId = targetId;++ if (!quoteMakeMethodId) {+ throw new Error("Invalid targetId");+ }+ const itemId = sourceId;+ const isConfigured = !!configuration;++ const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =+ await inOrder([+ () => single(db, "activeMakeMethods", { itemId, companyId }),+ () =>+ single(db, "quoteMakeMethod", {+ id: quoteMakeMethodId,+ companyId+ }),+ () => many(db, "workCenters", { companyId }),+ () => many(db, "supplierProcess", { companyId })+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (quoteMakeMethod.error || !quoteMakeMethod.data) {+ throw new Error("Failed to get quote make method");+ }++ const hydratedConfiguration = await hydrateConfiguration(+ db,+ configuration,+ itemId,+ companyId+ );++ const [methodTrees, configurationRules] = await inOrder([+ () => getMethodTree(db, makeMethod.data.id!),+ () =>+ isConfigured+ ? many(db, "configurationRule", { itemId, companyId })+ : Promise.resolve({+ data: [] as Tables["configurationRule"]["Row"][]+ })+ ]);++ if (methodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const methodTree = methodTrees.data?.[0] as MethodTreeItem;+ if (!methodTree) throw new NotFoundError("Method tree not found");++ const getLaborAndOverheadRates = getRatesFromWorkCenters(+ workCenters?.data+ );+ const getOutsideOperationRates = getRatesFromSupplierProcesses(+ supplierProcesses?.data+ );++ // Get configuration code by field+ const configurationCodeByField = configurationRules.data?.reduce<+ Record<string, string>+ >((acc, rule) => {+ acc[rule.field] = rule.code;+ return acc;+ }, {});++ await db.transaction().execute(async (trx) => {+ // Delete existing quoteMakeMethodOperation, quoteMakeMethodMaterial+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("quoteMaterial")+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("quoteOperation")+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ trx+ .updateTable("quoteMakeMethod")+ .set({ version: makeMethod.data.version ?? 1 })+ .where("id", "=", quoteMakeMethodId)+ .where("companyId", "=", companyId)+ .execute()+ ]);++ function getFieldKey(field: string, id: string) {+ return `${field}:${id}`;+ }++ // FIXME: never called — configuration rules are not applied on this+ // make-method path.+ // biome-ignore lint/correctness/noUnusedVariables: see FIXME above+ async function getConfiguredValue<T>({+ id,+ field,+ defaultValue+ }: {+ id: string;+ field: string;+ defaultValue: T;+ }): Promise<T> {+ if (!configurationCodeByField) return defaultValue;+ const fieldKey = getFieldKey(field, id);++ if (configurationCodeByField?.[fieldKey]) {+ try {+ const mod = await importTypeScript(+ configurationCodeByField[fieldKey]+ );+ const result = await mod.configure(hydratedConfiguration);+ return (result ?? defaultValue) as T;+ } catch (err) {+ getMethodLogger.error("configuration field resolver failed", {+ error: String((err as Error)?.stack ?? err)+ });+ return defaultValue;+ }+ }++ return defaultValue;+ }++ // traverse method tree and create:+ // - quoteMakeMethod+ // - quoteMakeMethodOperation+ // - quoteMakeMethodMaterial+ async function traverseMethod(+ node: MethodTreeItem,+ parentQuoteMakeMethodId: string | null+ ) {+ const relatedOperations = {+ data: treeOperations.get(node.data.materialMakeMethodId) ?? []+ };++ const quoteOperationInserts =+ relatedOperations?.data?.map((op) => ({+ quoteId: quoteMakeMethod.data?.quoteId!,+ quoteLineId: quoteMakeMethod.data?.quoteLineId!,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ processId: op.processId,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ ...getLaborAndOverheadRates(op.processId, op.workCenterId),+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ operationUnitCost: op.operationUnitCost ?? 0,+ operationSupplierProcessId: op.operationSupplierProcessId,+ ...getOutsideOperationRates(+ op.processId,+ op.operationSupplierProcessId+ ),+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ })) ?? [];++ let methodOperationsToQuoteOperations: Record<string, string> = {};++ if (parts.billOfProcess) {+ if (quoteOperationInserts?.length > 0) {+ const operationIds = await trx+ .insertInto("quoteOperation")+ .values(quoteOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ relatedOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;++ if (operationId) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;++ if (+ parts.tools &&+ Array.isArray(methodOperationTool) &&+ methodOperationTool.length > 0+ ) {+ await trx+ .insertInto("quoteOperationTool")+ .values(+ methodOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ await trx+ .insertInto("quoteOperationParameter")+ .values(+ methodOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops inherit steps from the linked instruction —+ // never copy (possibly stale) template steps alongside it.+ !operation.assemblyInstructionId &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("quoteOperationStep")+ .values(+ methodOperationStep.map(+ ({+ id: _id,+ // quoteOperationStep has no provenance marker+ assemblyInstructionStepId:+ _assemblyInstructionStepId,+ ...attribute+ }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ })+ )+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "quoteOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }++ methodOperationsToQuoteOperations =+ relatedOperations.data?.reduce<Record<string, string>>(+ (acc, op, index) => {+ if (operationIds[index]!.id) {+ acc[op.id!] = operationIds[index]!.id!;+ }+ return acc;+ },+ {}+ ) ?? {};+ }+ } // end if (parts.billOfProcess)++ if (parts.billOfMaterial) {+ const mapMethodMaterialToQuoteMaterial = (+ child: MethodTreeItem+ ) => ({+ quoteId: quoteMakeMethod.data?.quoteId!,+ quoteLineId: quoteMakeMethod.data?.quoteLineId!,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ quoteOperationId:+ methodOperationsToQuoteOperations[child.data.operationId],+ itemId: child.data.itemId,+ itemType: child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ description: child.data.description,+ quantity: child.data.quantity,+ storageUnitId: (child.data as any).storageUnitId || null, // @ts-ignore: storageUnitId field exists in database but types may not be updated+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ unitCost: child.data.unitCost ?? 0,+ companyId,+ createdBy: userId,+ customFields: {}+ });++ // A zero-quantity BOM line is removed from the method. Filtering the+ // children (not the mapped rows) keeps `madeChildren`/`madeMaterials`+ // index-aligned and stops a made line's sub-tree from being exploded.+ const madeChildren = node.children.filter(+ (child) =>+ child.data.methodType === "Make to Order" &&+ !isZeroQuantity(child.data.quantity)+ );+ const unmadeChildren = node.children.filter(+ (child) =>+ child.data.methodType !== "Make to Order" &&+ !isZeroQuantity(child.data.quantity)+ );++ const madeMaterials = madeChildren.map(+ mapMethodMaterialToQuoteMaterial+ );+ const pickedOrBoughtMaterials = unmadeChildren.map(+ mapMethodMaterialToQuoteMaterial+ );+ if (madeMaterials.length > 0) {+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid()+ }));++ await trx+ .insertInto("quoteMaterial")+ .values(madeMaterialsWithIds)+ .execute();++ const newMakeMethodIds = madeChildren.map(() => nanoid());+ await renameMakeMethods(trx, {+ table: "quoteMakeMethod",+ companyId,+ rows: madeChildren.map((_, index) => ({+ parentMaterialId: madeMaterialsWithIds[index]!.id,+ id: newMakeMethodIds[index]!+ }))+ });++ for (const [index, child] of madeChildren.entries()) {+ const newMakeMethodId = newMakeMethodIds[index]!;++ // A configuration rule may have moved this line onto another+ // made item; the sub-assembly under it is then that item's.+ const made = await configuredMadeChild(+ trx,+ companyId,+ child,+ madeMaterialsWithIds[index]!.itemId+ );+ if (!made) continue;+ if (made !== child) {+ for (const [id, ops] of await readOperationsForTree(+ trx,+ made+ ))+ treeOperations.set(id, ops);+ }++ // prevent an infinite loop+ if (made.data.itemId !== itemId) {+ await traverseMethod(made, newMakeMethodId);+ }+ }+ }++ deferredQuoteMaterials.push(...pickedOrBoughtMaterials);+ } // end if (parts.billOfMaterial)+ }++ const treeOperations = await readOperationsForTree(trx, methodTree);+ const deferredQuoteMaterials: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =+ [];+ await traverseMethod(methodTree, quoteMakeMethod.data.id);+ for (const chunk of chunked(deferredQuoteMaterials)) {+ await trx.insertInto("quoteMaterial").values(chunk).execute();+ }+ });+ break;+ }+ case "jobMakeMethodToItem": {+ const jobMakeMethodId = sourceId;+ const makeMethodId = targetId;++ const [makeMethod, jobMakeMethod] = await inOrder([+ () => single(db, "makeMethod", { id: makeMethodId, companyId }),+ () => single(db, "jobMakeMethod", { id: jobMakeMethodId, companyId })+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (jobMakeMethod.error) {+ throw new Error("Failed to get job make method");+ }++ const itemId = makeMethod.data?.itemId;++ const [job, jobOperations, itemReplenishment] = await inOrder([+ () => single(db, "job", { id: jobMakeMethod.data.jobId, companyId }),+ () =>+ many<+ "jobOperationsWithMakeMethods",+ Views["jobOperationsWithMakeMethods"]["Row"] & {+ jobOperationTool: Tables["jobOperationTool"]["Row"][];+ jobOperationParameter: Tables["jobOperationParameter"]["Row"][];+ jobOperationStep: Tables["jobOperationStep"]["Row"][];+ }+ >(+ db,+ "jobOperationsWithMakeMethods",+ { jobId: jobMakeMethod.data.jobId, companyId },+ {+ embed: {+ jobOperationTool: {+ table: "jobOperationTool",+ on: "operationId"+ },+ jobOperationParameter: {+ table: "jobOperationParameter",+ on: "operationId"+ },+ jobOperationStep: {+ table: "jobOperationStep",+ on: "operationId"+ }+ }+ }+ ),+ () => single(db, "itemReplenishment", { itemId, companyId })+ ]);++ if (jobOperations.error) {+ throw new Error("Failed to get job operations");+ }++ if (itemReplenishment.error) {+ throw new Error("Failed to get item replenishment");+ }++ if (itemReplenishment.data?.requiresConfiguration) {+ throw new Error("Cannot override method of configured item");+ }++ const [jobMethodTrees] = await inOrder([+ () =>+ getJobMethodTree(+ db,+ jobMakeMethodId,+ jobMakeMethod.data.parentMaterialId+ )+ ]);++ if (jobMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ if (jobMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) throw new NotFoundError("Job method tree not found");++ const madeItemIds: string[] = [];++ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ madeItemIds.push(node.data.itemId);+ }+ });++ const makeMethods = await many(db, "makeMethod", {+ itemId: madeItemIds+ });+ if (makeMethods.error) {+ throw new Error("Failed to get make methods");+ }++ const makeMethodByItemId: Record<string, string> = {};+ makeMethods.data?.forEach((m) => {+ makeMethodByItemId[m.itemId] = m.id;+ });++ await db.transaction().execute(async (trx) => {+ let makeMethodsToDelete: string[] = [];+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =+ [];+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =+ [];++ traverseJobMethod(jobMethodTree!, (node: JobMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]!);+ }++ node.children.forEach((child) => {+ // A zero-quantity BOM line is dropped from the saved method.+ if (isZeroQuantity(child.data.quantity)) return;+ materialInserts.push({+ makeMethodId: makeMethodByItemId[node.data.itemId]!,+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],+ itemId: child.data.itemId,+ itemType: child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ quantity: child.data.quantity,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ storageUnitIds: job.data?.locationId+ ? {+ [job.data.locationId]: child.data.storageUnitId || null+ }+ : {},+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });+ });++ if (makeMethodsToDelete.length > 0) {+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>+ mm === makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : mm+ );+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);+ }++ if (parts.billOfMaterial && materialInserts.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialInserts.map((insert) => ({+ ...insert,+ productionQuantity: undefined,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId,+ itemId:+ insert.itemId === jobMakeMethod.data.itemId+ ? itemId+ : insert.itemId+ }))+ )+ .execute();+ }++ if (parts.billOfProcess) {+ jobOperations.data?.forEach((op) => {+ operationInserts.push({+ makeMethodId: op.makeMethodId!,+ processId: op.processId!,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description ?? "",+ setupTime: op.setupTime ?? 0,+ setupUnit: op.setupUnit ?? "Total Minutes",+ laborTime: op.laborTime ?? 0,+ laborUnit: op.laborUnit ?? "Minutes/Piece",+ machineTime: op.machineTime ?? 0,+ machineUnit: op.machineUnit ?? "Minutes/Piece",+ order: op.order ?? 1,+ operationOrder: op.operationOrder ?? "After Previous",+ operationType: op.operationType ?? "Process",+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });++ if (operationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ operationInserts.map((insert) => ({+ ...insert,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId+ }))+ )+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ jobOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationStep,+ procedureId+ } = operation;++ if (+ parts.tools &&+ Array.isArray(jobOperationTool) &&+ jobOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ jobOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(jobOperationParameter) &&+ jobOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ jobOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops and inspection ops inherit their steps from+ // the linked instruction/document — never copy materialized+ // steps back onto a template.+ !operation.assemblyInstructionId &&+ !operation.inspectionDocumentId &&+ Array.isArray(jobOperationStep) &&+ jobOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ jobOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ jobOperationStep,+ insertedSteps,+ "jobOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)+ });++ break;+ }+ case "jobToItem": {+ const jobId = sourceId;+ if (!jobId) {+ throw new Error("Invalid sourceId");+ }+ const makeMethodId = targetId;++ const [makeMethod, jobMakeMethod, jobOperations, job] = await inOrder([+ () => single(db, "makeMethod", { id: makeMethodId, companyId }),+ () =>+ single(db, "jobMakeMethod", {+ jobId,+ parentMaterialId: isNull,+ companyId+ }),+ () =>+ many<+ "jobOperationsWithMakeMethods",+ Views["jobOperationsWithMakeMethods"]["Row"] & {+ jobOperationTool: Tables["jobOperationTool"]["Row"][];+ jobOperationParameter: Tables["jobOperationParameter"]["Row"][];+ jobOperationStep: Tables["jobOperationStep"]["Row"][];+ }+ >(+ db,+ "jobOperationsWithMakeMethods",+ { jobId, companyId },+ {+ embed: {+ jobOperationTool: {+ table: "jobOperationTool",+ on: "operationId"+ },+ jobOperationParameter: {+ table: "jobOperationParameter",+ on: "operationId"+ },+ jobOperationStep: {+ table: "jobOperationStep",+ on: "operationId"+ }+ }+ }+ ),+ () => single(db, "job", { id: jobId, companyId })+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (jobMakeMethod.error) {+ throw new Error("Failed to get job make method");+ }++ if (jobOperations.error) {+ throw new Error("Failed to get job operations");+ }++ const itemId = makeMethod.data?.itemId;++ const [jobMethodTrees, itemReplenishment] = await inOrder([+ () => getJobMethodTree(db, jobMakeMethod.data.id),+ () => single(db, "itemReplenishment", { itemId, companyId })+ ]);++ if (itemReplenishment.error) {+ throw new Error("Failed to get item replenishment");+ }++ if (itemReplenishment.data?.requiresConfiguration) {+ throw new Error("Cannot override method of configured item");+ }++ if (jobMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) throw new NotFoundError("Method tree not found");++ const madeItemIds: string[] = [];++ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ madeItemIds.push(node.data.itemId);+ }+ });++ const makeMethods = await many(db, "activeMakeMethods", {+ itemId: madeItemIds,+ companyId+ });+ if (makeMethods.error) {+ throw new Error("Failed to get make methods");+ }++ const makeMethodByItemId: Record<string, string> = {};+ makeMethods.data?.forEach((m) => {+ if (m.itemId) {+ // @ts-expect-error - itemId is not null+ makeMethodByItemId[m.itemId!] = m.id;+ }+ });++ await db.transaction().execute(async (trx) => {+ let makeMethodsToDelete: string[] = [];+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =+ [];+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =+ [];++ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]!);+ }++ node.children.forEach((child) => {+ // A zero-quantity BOM line is dropped from the saved method.+ if (isZeroQuantity(child.data.quantity)) return;+ materialInserts.push({+ makeMethodId: makeMethodByItemId[node.data.itemId]!,+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],+ itemId: child.data.itemId,+ itemType: child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ quantity: child.data.quantity,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ storageUnitIds: job.data?.locationId+ ? {+ [job.data.locationId]: child.data.storageUnitId || null+ }+ : {},+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });+ });++ if (makeMethodsToDelete.length > 0) {+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>+ mm === makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : mm+ );+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);+ }++ if (parts.billOfMaterial && materialInserts.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialInserts.map((insert) => ({+ ...insert,+ productionQuantity: undefined,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId,+ itemId:+ insert.itemId === jobMakeMethod.data.itemId+ ? itemId+ : insert.itemId+ }))+ )+ .execute();+ }++ if (parts.billOfProcess) {+ jobOperations.data?.forEach((op) => {+ operationInserts.push({+ makeMethodId: op.makeMethodId!,+ processId: op.processId!,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ // workCenterId: op.workCenterId,+ description: op.description ?? "",+ setupTime: op.setupTime ?? 0,+ setupUnit: op.setupUnit ?? "Total Minutes",+ laborTime: op.laborTime ?? 0,+ laborUnit: op.laborUnit ?? "Minutes/Piece",+ machineTime: op.machineTime ?? 0,+ machineUnit: op.machineUnit ?? "Minutes/Piece",+ order: op.order ?? 1,+ operationOrder: op.operationOrder ?? "After Previous",+ operationType: op.operationType ?? "Process",+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ operationSupplierProcessId: op.operationSupplierProcessId,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });++ if (operationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ operationInserts.map((insert) => ({+ ...insert,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[jobMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId+ }))+ )+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ jobOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationStep,+ procedureId+ } = operation;++ if (+ parts.tools &&+ Array.isArray(jobOperationTool) &&+ jobOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ jobOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(jobOperationParameter) &&+ jobOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ jobOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops and inspection ops inherit their steps from+ // the linked instruction/document — never copy materialized+ // steps back onto a template.+ !operation.assemblyInstructionId &&+ !operation.inspectionDocumentId &&+ Array.isArray(jobOperationStep) &&+ jobOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("methodOperationStep")+ .values(+ jobOperationStep.map((step) => ({+ operationId,+ name: step.name,+ type: step.type,+ description: toTiptapDoc(step.description),+ required: step.required,+ sortOrder: step.sortOrder,+ unitOfMeasureCode: step.unitOfMeasureCode,+ minValue: step.minValue,+ maxValue: step.maxValue,+ listValues: step.listValues,+ fileTypes: step.fileTypes,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ jobOperationStep,+ insertedSteps,+ "jobOperationStepSlide",+ "methodOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)+ });++ break;+ }+ case "jobToJob": {+ const sourceJobId = sourceId;+ const targetJobId = targetId;+ if (!sourceJobId || !targetJobId) {+ throw new Error("Invalid sourceId or targetId");+ }+ if (sourceJobId === targetJobId) {+ throw new Error("Cannot copy a job method onto itself");+ }++ // Assembly ops whose steps were materialized from an instruction —+ // material ↔ step links flush after the jobMaterial rows exist.+ const assemblyOperationsToLink: Array<{+ operationId: string;+ assemblyInstructionId: string;+ }> = [];++ // The embeds defeat the generated response types (as elsewhere in this+ // file), so the paged rows are typed explicitly.+ type SourceJobMaterialRow =+ Database["public"]["Tables"]["jobMaterial"]["Row"] & {+ jobMaterialStep: {+ jobOperationStepId: string | null;+ quantity: number | null;+ }[];+ };+ type SourceJobOperationRow =+ Database["public"]["Tables"]["jobOperation"]["Row"] & {+ jobOperationTool: (Database["public"]["Tables"]["jobOperationTool"]["Row"] & {+ jobOperationToolStep: { jobOperationStepId: string | null }[];+ })[];+ jobOperationParameter: Database["public"]["Tables"]["jobOperationParameter"]["Row"][];+ jobOperationStep: Database["public"]["Tables"]["jobOperationStep"]["Row"][];+ };++ // Paged: a bare select stops at PostgREST's 1000-row cap and would+ // silently copy a subset of a large job. The secondary `.order("id")`+ // makes paging stable across batches. Started here (not awaited) so the+ // reads below run concurrently with them.+ const targetJob = await single(db, "job", {+ id: targetJobId,+ companyId+ });+ const sourceJob = await single(db, "job", {+ id: sourceJobId,+ companyId+ });+ const targetJobMakeMethod = await single(db, "jobMakeMethod", {+ jobId: targetJobId,+ parentMaterialId: isNull,+ companyId+ });+ const sourceJobMakeMethod = await single(db, "jobMakeMethod", {+ jobId: sourceJobId,+ parentMaterialId: isNull,+ companyId+ });+ const sourceMaterials = await many<"jobMaterial", SourceJobMaterialRow>(+ db,+ "jobMaterial",+ { jobId: sourceJobId, companyId },+ {+ orderBy: ["id"],+ embed: {+ jobMaterialStep: { table: "jobMaterialStep", on: "jobMaterialId" }+ }+ }+ );+ const sourceOperations = await many<+ "jobOperation",+ SourceJobOperationRow+ >(+ db,+ "jobOperation",+ { jobId: sourceJobId, companyId },+ {+ orderBy: ["order", "id"],+ embed: {+ jobOperationTool: {+ table: "jobOperationTool",+ on: "operationId",+ embed: {+ jobOperationToolStep: {+ table: "jobOperationToolStep",+ on: "jobOperationToolId"+ }+ }+ },+ jobOperationParameter: {+ table: "jobOperationParameter",+ on: "operationId"+ },+ jobOperationStep: { table: "jobOperationStep", on: "operationId" }+ }+ }+ );++ if (targetJob.error) {+ throw new Error("Failed to get job");+ }+ if (sourceJob.error) {+ throw new Error("Failed to get source job");+ }+ if (targetJobMakeMethod.error || !targetJobMakeMethod.data) {+ throw new Error("Failed to get job make method");+ }+ if (sourceJobMakeMethod.error || !sourceJobMakeMethod.data) {+ throw new Error("Failed to get source job make method");+ }+ if (sourceMaterials.error) {+ throw new Error("Failed to get source job materials");+ }+ if (sourceOperations.error) {+ throw new Error("Failed to get source job operations");+ }++ const jobMethodTrees = await getJobMethodTree(+ db,+ sourceJobMakeMethod.data.id+ );+ if (jobMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) throw new NotFoundError("Method tree not found");++ // A process-only copy of a multi-level job cannot work: the sub-assembly+ // make methods only come into existence on the bill-of-material path, so+ // their operations would reference make methods that were never created+ // (jobOperation_jobMakeMethodId_fkey). Refuse with an authored message+ // instead of rolling back on the FK.+ if (!parts.billOfMaterial && parts.billOfProcess) {+ let hasSubAssemblies = false;+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ for (const child of node.children) {+ if (child.data.jobMaterialMakeMethodId) {+ hasSubAssemblies = true;+ }+ }+ });+ if (hasSubAssemblies) {+ throw new Error(+ "Copying only the bill of process from a job with sub-assemblies is not supported — include the bill of material as well"+ );+ }+ }++ // Loaded ONCE per request, before the transaction — as every *-ToJob+ // path does. The source job's rows were swapped live at ITS creation;+ // this re-resolves as-of the TARGET job's build date, so a supersession+ // that became effective since then still redirects the copy.+ const { redirect: supersessionRedirect } = await loadSupersessionRedirect(+ db,+ companyId,+ targetJob.data+ );+ const itemDefaults = createItemDefaults(+ companyId,+ targetJob.data.locationId+ );++ let selfConsumedItem: string | null = null;+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ for (const child of node.children) {+ const resolvedItemId =+ child.data.methodType !== "Make to Order"+ ? (supersessionRedirect.get(child.data.itemId)?.to ??+ child.data.itemId)+ : child.data.itemId;+ if (resolvedItemId === targetJob.data.itemId) {+ selfConsumedItem = child.data.itemReadableId ?? resolvedItemId;+ }+ }+ });+ if (selfConsumedItem) {+ throw new Error(+ `The source job's method consumes ${selfConsumedItem}, which is the item this job produces — a job cannot consume its own output`+ );+ }++ const sourceMaterialRows = sourceMaterials.data ?? [];+ const sourceOperationRows = sourceOperations.data ?? [];++ const sourceMaterialById = new Map(+ sourceMaterialRows.map((m) => [m.id, m])+ );++ const sourceMaterialIdToJobMaterialId: Record<string, string> = {};+ const sourceMakeMethodIdToJobMakeMethodId: Record<string, string> = {};+ // Track estimated quantities for each SOURCE make method to set on operations+ const sourceMakeMethodIdToQuantities: Record<+ string,+ {+ targetQuantity: number;+ estimatedQuantity: number;+ totalWithScrap: number;+ }+ > = {};+ // Old job step id -> new job step id, for material/tool ↔ step links.+ const sourceStepsToJobSteps: Record<string, string> = {};+ const sourceOperationIdToJobOperationId: Record<string, string> = {};++ await db.transaction().execute(async (trx) => {+ await itemDefaults.load(+ trx,+ treeItemIds(jobMethodTree, supersessionRedirect)+ );+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for the target job+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMakeMethod")+ .where((eb) =>+ eb.and([+ eb("jobId", "=", targetJobId),+ eb("parentMaterialId", "is not", null)+ ])+ )+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMaterial")+ .where("jobId", "=", targetJobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", targetJobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("jobOperation")+ .where("jobId", "=", targetJobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);++ const insertedJobMaterialIds: string[] = [];+ await traverseJobMethodAsync(+ jobMethodTree,+ async (node: JobMethodTreeItem) => {+ const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =+ [];++ // Get the total quantity for this node (parent level) to pass to children+ // This is estimated + scrap for Make parts (what children use for their target calculation)+ let nodeTotalForChildren: number;+ if (node.data.isRoot) {+ // Root: target = TARGET job quantity — the source job's own+ // quantity is irrelevant; the tree carries per-parent quantities.+ const rootScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ node.data.itemId+ );+ const rootTarget = targetJob.data?.quantity ?? 1;+ // Scrap applies to every method type (mirrors itemToJob)+ const rootScrapQuantity = scrapAllowance(+ rootTarget,+ rootScrapPercentage+ );+ const rootTotalWithScrap = rootTarget + rootScrapQuantity;+ const rootEstimatedQuantity =+ node.data.methodType === "Make to Order"+ ? rootTarget+ : rootTotalWithScrap;++ nodeTotalForChildren = rootTotalWithScrap;++ sourceMakeMethodIdToQuantities[sourceJobMakeMethod.data.id] = {+ targetQuantity: rootTarget,+ estimatedQuantity: rootEstimatedQuantity,+ totalWithScrap: rootTotalWithScrap+ };+ } else {+ // Non-root: get from stored quantities using parent's source jobMakeMethodId+ const parentSourceMakeMethodId =+ node.data.jobMaterialMakeMethodId;+ const parentQuantities =+ sourceMakeMethodIdToQuantities[parentSourceMakeMethodId ?? ""];+ // Children receive parent's total (estimated + scrap) for cascade+ nodeTotalForChildren = parentQuantities?.totalWithScrap ?? 1;+ }++ for await (const child of node.children) {+ // A zero-quantity Buy/Pick line is dropped from the copied job.+ // A made sub-assembly is left intact even at quantity 0: its+ // operations are copied by make method below and would reference+ // a make method that never got created if the row were removed.+ if (+ isZeroQuantity(child.data.quantity) &&+ child.data.methodType !== "Make to Order"+ ) {+ continue;+ }+ const sourceMaterial = sourceMaterialById.get(child.id);+ const newMaterialId = nanoid();+ sourceMaterialIdToJobMaterialId[child.id] = newMaterialId;++ // Resolve the supersession FIRST — see the note in+ // itemToJobMakeMethod's mapper. Every field below derives from+ // the post-swap item, so a field added later follows+ // automatically. Buy/Pick only — made sub-assemblies keep the+ // source job's structure (their successors' methods would have+ // to be re-exploded from the item side).+ const supersession = await resolveJobMaterialSupersession(+ trx,+ companyId,+ supersessionRedirect,+ {+ itemId: child.data.itemId,+ methodType: child.data.methodType+ }+ );+ const itemId = supersession?.itemId ?? child.data.itemId;+ const quantityPerParent =+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);++ // Get scrap percentage for this item+ const itemScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ itemId+ );++ // Calculate scrap quantities for this child material+ // Target = parent's total (including scrap) * quantity per parent+ const childTargetQuantity =+ nodeTotalForChildren * quantityPerParent;+ // Scrap applies to every method type (mirrors itemToJob)+ const childScrapQuantity = scrapAllowance(+ childTargetQuantity,+ itemScrapPercentage+ );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;+ // For Make: estimatedQuantity is good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const childEstimatedQuantity =+ child.data.methodType === "Make to Order"+ ? childTargetQuantity+ : childTotalWithScrap;++ // Store quantities for this child's make method (if it has one)+ if (child.data.jobMaterialMakeMethodId) {+ sourceMakeMethodIdToQuantities[+ child.data.jobMaterialMakeMethodId+ ] = {+ targetQuantity: childTargetQuantity,+ estimatedQuantity: childEstimatedQuantity,+ totalWithScrap: childTotalWithScrap+ };+ }++ jobMaterialInserts.push({+ id: newMaterialId,+ jobId: targetJobId,+ itemId,+ itemType: supersession?.itemType ?? child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ description:+ supersession?.description ?? child.data.description,+ jobMakeMethodId:+ child.data.jobMakeMethodId === sourceJobMakeMethod.data.id+ ? targetJobMakeMethod.data.id+ : sourceMakeMethodIdToJobMakeMethodId[+ child.data.jobMakeMethodId+ ]!,+ quantity: quantityPerParent,+ scrapQuantity: childScrapQuantity,+ estimatedQuantity: childEstimatedQuantity,+ itemScrapPercentage,+ substitutedFromItemId:+ supersession?.substitutedFromItemId ?? null,+ substitutionFactor: supersession?.factor ?? null,+ // ALWAYS set, never conditionally spread — see the note in+ // quoteLineToJob: Kysely builds ONE column list per multi-row+ // insert, and `unitCost` is NOT NULL DEFAULT 0.+ unitCost: supersession+ ? (supersession.unitCost ?? 0)+ : (sourceMaterial?.unitCost ?? child.data.unitCost ?? 0),+ // The bin belongs to the post-swap item; an explicit bin on+ // the source job's line still wins.+ storageUnitId: await itemDefaults.storageUnitId(+ trx,+ itemId,+ child.data.storageUnitId ?? undefined+ ),+ requiresBatchTracking:+ supersession?.requiresBatchTracking ??+ sourceMaterial?.requiresBatchTracking ??+ false,+ requiresSerialTracking:+ supersession?.requiresSerialTracking ??+ sourceMaterial?.requiresSerialTracking ??+ false,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {}+ });++ if (child.data.jobMaterialMakeMethodId) {+ const newMakeMethodId = nanoid();+ sourceMakeMethodIdToJobMakeMethodId[+ child.data.jobMaterialMakeMethodId+ ] = newMakeMethodId;+ jobMakeMethodInserts.push({+ id: newMakeMethodId,+ jobId: targetJobId,+ parentMaterialId: sourceMaterialIdToJobMaterialId[child.id],+ itemId: child.data.itemId,+ quantityPerParent: child.data.quantity,+ companyId,+ createdBy: userId+ });+ }+ }++ if (parts.billOfMaterial && jobMaterialInserts.length > 0) {+ // The supersession swap happens where each row is built, before+ // any field derives from the item — there is deliberately no+ // second pass here.+ await trx+ .insertInto("jobMaterial")+ .values(jobMaterialInserts)+ .execute();+ insertedJobMaterialIds.push(+ ...jobMaterialInserts.flatMap((m) => (m.id ? [m.id] : []))+ );+ }++ if (parts.billOfMaterial && jobMakeMethodInserts.length > 0) {+ await renameMakeMethods(trx, {+ table: "jobMakeMethod",+ companyId,+ scope: { column: "jobId", value: targetJobId },+ rows: jobMakeMethodInserts.map((insert) => ({+ parentMaterialId: insert.parentMaterialId!,+ id: insert.id!,+ quantityPerParent: insert.quantityPerParent+ }))+ });+ }+ }+ );++ if (parts.billOfProcess) {+ const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =+ sourceOperationRows.map((op) => {+ // Get quantities for this operation's SOURCE make method+ const opQuantities =+ sourceMakeMethodIdToQuantities[op.jobMakeMethodId ?? ""];+ // The traversal stores quantities for every make method in the+ // tree, so a miss means the operation references an orphaned+ // make method. Fail the conversion (rolls back the transaction)+ // instead of silently inserting a zero-quantity operation with+ // a NULL jobMakeMethodId.+ if (!opQuantities) {+ throw new Error(+ `No quantities found for source job make method ${op.jobMakeMethodId} referenced by operation ${op.id} — the job method tree and its operations are out of sync`+ );+ }+ return {+ jobId: targetJobId,+ jobMakeMethodId:+ op.jobMakeMethodId === sourceJobMakeMethod.data.id+ ? targetJobMakeMethod.data.id+ : sourceMakeMethodIdToJobMakeMethodId[op.jobMakeMethodId!],+ processId: op.processId,+ procedureId: op.procedureId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ // Carry the Assembly → BOP sync link so the MES can drive the+ // animated instruction player on the copied job.+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ targetQuantity: opQuantities.targetQuantity,+ // Fractional targets flow through; the scrap allowance is already whole+ operationQuantity: opQuantities.totalWithScrap,+ companyId,+ createdBy: userId,+ customFields: {}+ };+ });++ if (jobOperationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("jobOperation")+ .values(jobOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of sourceOperationRows.entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ sourceOperationIdToJobOperationId[operation.id] = operationId;++ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationStep,+ procedureId+ } = operation;++ // Tool ids the assembly-instruction copy inserts itself, so+ // the source job's copies of the same tools are skipped below.+ let assemblyToolIds = new Set<string>();++ if (procedureId) {+ await insertProcedureDataForJobOperation(trx, {+ operationId,+ procedureId,+ companyId,+ userId+ });+ } else {+ if (+ parts.parameters &&+ Array.isArray(jobOperationParameter) &&+ jobOperationParameter.length > 0+ ) {+ await trx+ .insertInto("jobOperationParameter")+ .values(+ jobOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (operation.assemblyInstructionId) {+ // Assembly ops inherit their steps from the linked+ // instruction (fresh from the live definition, as every+ // *-ToJob path does); material ↔ step links are flushed+ // after the jobMaterial rows exist.+ assemblyToolIds = await insertAssemblyDataForJobOperation(+ trx,+ {+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId,+ companyId,+ userId+ }+ );+ assemblyOperationsToLink.push({+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId+ });+ } else if (+ parts.steps &&+ Array.isArray(jobOperationStep) &&+ jobOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ jobOperationStep.map((step) => ({+ operationId,+ name: step.name,+ type: step.type,+ description: toTiptapDoc(step.description),+ required: step.required,+ sortOrder: step.sortOrder,+ unitOfMeasureCode: step.unitOfMeasureCode,+ minValue: step.minValue,+ maxValue: step.maxValue,+ listValues: step.listValues,+ fileTypes: step.fileTypes,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ // Bulk insert preserves order, so insertedSteps[i] ↔+ // jobOperationStep[i]: record old step -> new step so+ // material/tool ↔ step links can be remapped below.+ jobOperationStep.forEach((s, i) => {+ const newStepId = insertedSteps[i]?.id;+ if (s?.id && newStepId) {+ sourceStepsToJobSteps[s.id] = newStepId;+ }+ });++ await copyStepSlides(+ trx,+ jobOperationStep,+ insertedSteps,+ "jobOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId+ );+ }+ }++ // Tools after steps: the old-step -> new-step map is now+ // populated, so a tool scoped to steps carries those links via+ // jobOperationToolStep. Tools the assembly-instruction copy+ // already inserted are skipped (see above).+ const toolsToCopy = (+ Array.isArray(jobOperationTool) ? jobOperationTool : []+ ).filter((tool) => !assemblyToolIds.has(tool.toolId));+ if (parts.tools && toolsToCopy.length > 0) {+ const insertedTools = await trx+ .insertInto("jobOperationTool")+ .values(+ toolsToCopy.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ // Tool ↔ step links. Bulk insert preserves order, so+ // insertedTools[i] ↔ toolsToCopy[i]. A tool with no links+ // applies to the whole operation.+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {+ const jobOperationToolId = insertedTools[i]?.id;+ if (!jobOperationToolId) return [];+ const oldStepIds = (+ (tool.jobOperationToolStep ?? []) as Array<{+ jobOperationStepId: string | null;+ }>+ ).map((l) => l.jobOperationStepId);+ return remapStepIds(oldStepIds, sourceStepsToJobSteps).map(+ (jobOperationStepId) => ({+ jobOperationToolId,+ jobOperationStepId+ })+ );+ });+ if (toolStepRows.length > 0) {+ await trx+ .insertInto("jobOperationToolStep")+ .values(toolStepRows)+ .execute();+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)++ // The links between materials and operations/steps can only be+ // rebuilt when BOTH sides were copied in this run — otherwise one end+ // of each link points at rows this copy never created.+ if (parts.billOfMaterial && parts.billOfProcess) {+ // Material ↔ operation links (jobMaterial.jobOperationId): the+ // materials were inserted during the traversal, before the+ // operations existed, so the link is applied as a second pass —+ // batched as one UPDATE per operation rather than one per material.+ const materialIdsByOperationId = new Map<string, string[]>();+ for (const sourceMaterial of sourceMaterialRows) {+ const newMaterialId =+ sourceMaterialIdToJobMaterialId[sourceMaterial.id];+ const newOperationId = sourceMaterial.jobOperationId+ ? sourceOperationIdToJobOperationId[sourceMaterial.jobOperationId]+ : undefined;+ if (newMaterialId && newOperationId) {+ const ids = materialIdsByOperationId.get(newOperationId) ?? [];+ ids.push(newMaterialId);+ materialIdsByOperationId.set(newOperationId, ids);+ }+ }+ const operationByMaterial = [...materialIdsByOperationId].flatMap(+ ([operationId, materialIds]) =>+ materialIds.map(+ (materialId) => sql`(${materialId}::text, ${operationId}::text)`+ )+ );+ for (const chunk of chunked(operationByMaterial)) {+ await sql`+ UPDATE "jobMaterial" AS t+ SET "jobOperationId" = v."operationId"+ FROM (VALUES ${sql.join(chunk)}) AS v("materialId", "operationId")+ WHERE t."id" = v."materialId" AND t."companyId" = ${companyId}+ `.execute(trx);+ }++ // Material ↔ step links (jobMaterialStep), remapped onto the new+ // material and step ids. Links to procedure/assembly-materialized+ // steps drop out of the map (assembly links are rebuilt from the+ // instruction by linkAssemblyStepMaterialsForJobOperations below).+ const materialStepRows = sourceMaterialRows.flatMap(+ (sourceMaterial) => {+ const newMaterialId =+ sourceMaterialIdToJobMaterialId[sourceMaterial.id];+ if (!newMaterialId) return [];+ return (sourceMaterial.jobMaterialStep ?? []).flatMap((link) => {+ const newStepId = link.jobOperationStepId+ ? sourceStepsToJobSteps[link.jobOperationStepId]+ : undefined;+ return newStepId+ ? [+ {+ jobMaterialId: newMaterialId,+ jobOperationStepId: newStepId,+ quantity: link.quantity+ }+ ]+ : [];+ });+ }+ );+ if (materialStepRows.length > 0) {+ await trx+ .insertInto("jobMaterialStep")+ .values(materialStepRows)+ .execute();+ }+ }++ // Materials were inserted before operations in this direction, so the+ // assembly material ↔ step links can flush immediately.+ await linkAssemblyStepMaterialsForJobOperations(+ trx,+ assemblyOperationsToLink,+ companyId+ );++ await settleConsumeFirstLines({+ trx,+ companyId,+ jobId: targetJobId,+ jobMaterialIds: insertedJobMaterialIds,+ locationId: targetJob.data?.locationId,+ asOfDate: jobBuildDate(targetJob.data)+ });+ });++ break;+ }+ case "makeMethodToMakeMethod": {+ const [sourceMakeMethod, targetMakeMethod] = await inOrder([+ () => single(db, "makeMethod", { id: sourceId, companyId }),+ () => single(db, "makeMethod", { id: targetId, companyId })+ ]);+ if (sourceMakeMethod.error || targetMakeMethod.error) {+ throw new Error("Failed to get make methods");+ }++ const [sourceMaterials, sourceOperations] = await inOrder([+ () =>+ parts.billOfMaterial+ ? many(db, "methodMaterial", {+ makeMethodId: sourceMakeMethod.data.id,+ companyId+ })+ : Promise.resolve({ data: [], error: null }),+ () =>+ parts.billOfProcess+ ? many<+ "methodOperation",+ Tables["methodOperation"]["Row"] & {+ methodOperationTool: Tables["methodOperationTool"]["Row"][];+ methodOperationParameter: Tables["methodOperationParameter"]["Row"][];+ methodOperationStep: Tables["methodOperationStep"]["Row"][];+ }+ >(+ db,+ "methodOperation",+ { makeMethodId: sourceMakeMethod.data.id, companyId },+ {+ embed: {+ methodOperationTool: {+ table: "methodOperationTool",+ on: "operationId"+ },+ methodOperationParameter: {+ table: "methodOperationParameter",+ on: "operationId"+ },+ methodOperationStep: {+ table: "methodOperationStep",+ on: "operationId"+ }+ }+ }+ )+ : Promise.resolve({ data: [], error: null })+ ]);++ if (sourceMaterials.error || sourceOperations.error) {+ throw new Error("Failed to get source materials or operations");+ }++ await db.transaction().execute(async (trx) => {+ // The lines about to be replaced, whose configuration rules go with them.+ const [targetMaterialIds, targetOperationIds] = await Promise.all([+ trx+ .selectFrom("methodMaterial")+ .select("id")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ .then((rows) => rows.map((row) => row.id)),+ trx+ .selectFrom("methodOperation")+ .select("id")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ .then((rows) => rows.map((row) => row.id))+ ]);++ // Delete existing materials and operations from target method+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "=", targetMakeMethod.data.id)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);++ // Operations first, so each copied BOM line can point at the copied+ // operation that consumes it, not at the source method's operation.+ const operationIdMap = new Map<string, string>();+ if (+ parts.billOfProcess &&+ sourceOperations.data &&+ sourceOperations.data.length > 0+ ) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ sourceOperations.data.map(+ ({+ methodOperationTool: _tools,+ methodOperationParameter: _parameters,+ methodOperationStep: _attributes,+ ...operation+ }) => {+ const insert = {+ ...operation,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id,+ createdBy: userId+ };+ if (!parts.workInstructions) {+ insert.workInstruction = {};+ }+ return insert;+ }+ )+ )+ .returning(["id"])+ .execute();+ sourceOperations.data.forEach((operation, index) => {+ const id = operationIds[index]?.id;+ if (operation.id && id) operationIdMap.set(operation.id, id);+ });++ for await (const [+ index,+ operation+ ] of sourceOperations.data.entries()) {+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationStep,+ procedureId+ } = operation;+ const operationId = operationIds[index]!.id;++ if (+ parts.tools &&+ operationId &&+ Array.isArray(methodOperationTool) &&+ methodOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ methodOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(methodOperationParameter) &&+ methodOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ methodOperationParameter.map((param) => ({+ operationId: operationId!,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops inherit steps from the linked instruction —+ // never copy (possibly stale) template steps alongside it.+ !operation.assemblyInstructionId &&+ Array.isArray(methodOperationStep) &&+ methodOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("methodOperationStep")+ .values(+ methodOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId: operationId!,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ methodOperationStep,+ insertedSteps,+ "methodOperationStepSlide",+ "methodOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ // Copy materials from source to target, dropping any zero-quantity+ // BOM lines.+ const materialsToCopy = (+ (sourceMaterials.data ??+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]+ ).filter((material) => !isZeroQuantity(material.quantity));+ const materialIdMap = new Map<string, string>();+ if (parts.billOfMaterial && materialsToCopy.length > 0) {+ const materialIds = await trx+ .insertInto("methodMaterial")+ .values(+ materialsToCopy.map((material) => ({+ ...material,+ productionQuantity: undefined,+ id: undefined, // Let the database generate a new ID+ makeMethodId: targetMakeMethod.data.id,+ // Without the bill of process the source's operations were not+ // copied, so no operation on the target is known to consume it.+ methodOperationId: material.methodOperationId+ ? (operationIdMap.get(material.methodOperationId) ?? null)+ : null,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();+ materialsToCopy.forEach((material, index) => {+ const id = materialIds[index]?.id;+ if (id) materialIdMap.set(material.id, id);+ });+ }++ // Configuration rules are keyed by method line and operation ids:+ // follow the copied lines, and drop the rules of the lines replaced.+ await copyConfigurationRules(trx, {+ sourceItemId: sourceMakeMethod.data.itemId,+ targetItemId: targetMakeMethod.data.itemId,+ replacedIds: [+ ...(parts.billOfMaterial ? targetMaterialIds : []),+ ...(parts.billOfProcess ? targetOperationIds : [])+ ],+ idMap: new Map([+ [sourceMakeMethod.data.id, targetMakeMethod.data.id],+ ...materialIdMap,+ ...operationIdMap+ ]),+ companyId,+ userId+ });+ });+ break;+ }+ case "procedureToOperation": {+ const procedureId = sourceId;+ const operationId = targetId;+ if (!procedureId) {+ throw new Error("Invalid sourceId");+ }++ if (!operationId) {+ throw new Error("Invalid targetId");+ }++ const [procedure, operation] = await inOrder([+ () =>+ single<+ "procedure",+ Tables["procedure"]["Row"] & {+ procedureStep: Tables["procedureStep"]["Row"][];+ procedureParameter: Tables["procedureParameter"]["Row"][];+ }+ >(+ db,+ "procedure",+ { id: procedureId, companyId },+ {+ embed: {+ procedureStep: { table: "procedureStep", on: "procedureId" },+ procedureParameter: {+ table: "procedureParameter",+ on: "procedureId"+ }+ }+ }+ ),+ () =>+ single<+ "jobOperation",+ Tables["jobOperation"]["Row"] & {+ jobOperationStep: Tables["jobOperationStep"]["Row"][];+ }+ >(+ db,+ "jobOperation",+ { id: operationId, companyId },+ {+ embed: {+ jobOperationStep: {+ table: "jobOperationStep",+ on: "operationId"+ }+ }+ }+ )+ ]);++ if (procedure.error) {+ throw new Error("Failed to get procedure");+ }++ if (operation.error) {+ throw new Error("Failed to get operation");+ }++ const existingSteps = operation.data?.jobOperationStep ?? [];++ await db.transaction().execute(async (trx) => {+ // Update or delete existing attributes+ for (const existingStep of existingSteps) {+ const matchingProcedureStep = procedure.data.procedureStep.find(+ (pa) =>+ pa.name === existingStep.name && pa.type === existingStep.type+ );++ if (matchingProcedureStep) {+ // Update matching attribute+ await trx+ .updateTable("jobOperationStep")+ .set({+ description: matchingProcedureStep.description,+ minValue: matchingProcedureStep.minValue,+ maxValue: matchingProcedureStep.maxValue,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", existingStep.id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ // Delete non-matching attribute+ await trx+ .deleteFrom("jobOperationStep")+ .where("id", "=", existingStep.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Delete all existing parameters+ await trx+ .deleteFrom("jobOperationParameter")+ .where("operationId", "=", operationId)+ .where("companyId", "=", companyId)+ .execute();++ // Add new attributes that don't exist yet+ const newSteps = procedure.data.procedureStep.filter(+ (pa) =>+ !existingSteps.some(+ (ea) => ea.name === pa.name && ea.type === pa.type+ )+ );++ if (newSteps.length > 0) {+ await trx+ .insertInto("jobOperationStep")+ .values(+ newSteps.map((attr) => ({+ operationId: operationId,+ name: attr.name,+ type: attr.type,+ description: toTiptapDoc(attr.description),+ minValue: attr.minValue,+ maxValue: attr.maxValue,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }++ // Add all parameters from procedure+ if (procedure.data.procedureParameter.length > 0) {+ await trx+ .insertInto("jobOperationParameter")+ .values(+ procedure.data.procedureParameter.map((param) => ({+ operationId: operationId,+ companyId,+ key: param.key,+ value: param.value,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }++ // update work instruction+ await trx+ .updateTable("jobOperation")+ .set({+ workInstruction: toJson(procedure.data.content),+ procedureId: procedureId+ })+ .where("id", "=", operationId)+ .where("companyId", "=", companyId)+ .execute();+ });+ break;+ }+ case "quoteLineToItem": {+ const [quoteId, quoteLineId] = (sourceId as string).split(":");+ if (!quoteId || !quoteLineId) {+ throw new Error("Invalid sourceId");+ }+ const makeMethodId = targetId;++ const [makeMethod, quoteMakeMethod, quoteOperations] = await inOrder([+ () => single(db, "makeMethod", { id: makeMethodId, companyId }),+ () =>+ single(db, "quoteMakeMethod", {+ quoteLineId,+ parentMaterialId: isNull,+ companyId+ }),+ () =>+ many<+ "quoteOperationsWithMakeMethods",+ Views["quoteOperationsWithMakeMethods"]["Row"] & {+ quoteOperationTool: Tables["quoteOperationTool"]["Row"][];+ quoteOperationParameter: Tables["quoteOperationParameter"]["Row"][];+ quoteOperationStep: Tables["quoteOperationStep"]["Row"][];+ }+ >(+ db,+ "quoteOperationsWithMakeMethods",+ { quoteLineId, companyId },+ {+ embed: {+ quoteOperationTool: {+ table: "quoteOperationTool",+ on: "operationId"+ },+ quoteOperationParameter: {+ table: "quoteOperationParameter",+ on: "operationId"+ },+ quoteOperationStep: {+ table: "quoteOperationStep",+ on: "operationId"+ }+ }+ }+ )+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (quoteMakeMethod.error) {+ throw new Error("Failed to get quote make method");+ }++ if (quoteOperations.error) {+ throw new Error("Failed to get quote operations");+ }++ const itemId = makeMethod.data?.itemId;++ const [quote, quoteMethodTrees, itemReplenishment] = await inOrder([+ () => single(db, "quote", { id: quoteId, companyId }),+ () => getQuoteMethodTree(db, quoteMakeMethod.data.id),+ () => single(db, "itemReplenishment", { itemId, companyId })+ ]);++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ if (itemReplenishment.error) {+ throw new Error("Failed to get item replenishment");+ }++ if (itemReplenishment.data?.requiresConfiguration) {+ throw new Error("Cannot override method of configured item");+ }++ const quoteMethodTree = quoteMethodTrees.data?.[0] as QuoteMethodTreeItem;+ if (!quoteMethodTree) throw new NotFoundError("Method tree not found");++ const madeItemIds: string[] = [];++ await traverseQuoteMethod(+ quoteMethodTree,+ (node: QuoteMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ madeItemIds.push(node.data.itemId);+ }+ }+ );++ const makeMethods = await many(db, "activeMakeMethods", {+ itemId: madeItemIds,+ companyId+ });+ if (makeMethods.error) {+ throw new Error("Failed to get make methods");+ }++ const makeMethodByItemId: Record<string, string> = {};+ makeMethods.data?.forEach((m) => {+ if (m.itemId) {+ // @ts-expect-error - itemId is not null+ makeMethodByItemId[m.itemId!] = m.id;+ }+ });++ await db.transaction().execute(async (trx) => {+ let makeMethodsToDelete: string[] = [];+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =+ [];+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =+ [];++ await traverseQuoteMethod(+ quoteMethodTree,+ (node: QuoteMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]!);+ }++ node.children.forEach((child) => {+ // A zero-quantity BOM line is dropped from the saved method.+ if (isZeroQuantity(child.data.quantity)) return;+ materialInserts.push({+ makeMethodId: makeMethodByItemId[node.data.itemId]!,+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],+ itemId: child.data.itemId,+ itemType: child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ quantity: child.data.quantity,+ storageUnitIds: quote.data?.locationId+ ? // @ts-ignore: storageUnitIds is a dynamic object with location keys+ {+ [quote.data.locationId]: child.data.storageUnitId || null+ }+ : {},+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });+ }+ );++ if (makeMethodsToDelete.length > 0) {+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>+ mm === makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : mm+ );+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);+ }++ if (parts.billOfMaterial && materialInserts.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialInserts.map((insert) => ({+ ...insert,+ productionQuantity: undefined,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId,+ itemId:+ insert.itemId === quoteMakeMethod.data.itemId+ ? itemId+ : insert.itemId+ }))+ )+ .execute();+ }++ if (parts.billOfProcess) {+ quoteOperations.data?.forEach((op) => {+ operationInserts.push({+ makeMethodId: op.makeMethodId!,+ processId: op.processId!,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description ?? "",+ setupTime: op.setupTime ?? 0,+ setupUnit: op.setupUnit ?? "Total Minutes",+ laborTime: op.laborTime ?? 0,+ laborUnit: op.laborUnit ?? "Minutes/Piece",+ machineTime: op.machineTime ?? 0,+ machineUnit: op.machineUnit ?? "Minutes/Piece",+ order: op.order ?? 1,+ operationOrder: op.operationOrder ?? "After Previous",+ operationType: op.operationType ?? "Process",+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });++ if (operationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ operationInserts.map((insert) => ({+ ...insert,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId+ }))+ )+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ quoteOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationStep,+ procedureId+ } = operation;++ if (+ parts.tools &&+ Array.isArray(quoteOperationTool) &&+ quoteOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ quoteOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(quoteOperationParameter) &&+ quoteOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ quoteOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops inherit steps from the linked instruction —+ // never copy (possibly stale) quote steps alongside it.+ !operation.assemblyInstructionId &&+ Array.isArray(quoteOperationStep) &&+ quoteOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("methodOperationStep")+ .values(+ quoteOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ quoteOperationStep,+ insertedSteps,+ "quoteOperationStepSlide",+ "methodOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)+ });++ break;+ }+ case "quoteMakeMethodToItem": {+ const quoteMakeMethodId = sourceId;+ const makeMethodId = targetId;++ const [makeMethod, quoteMakeMethod] = await inOrder([+ () => single(db, "makeMethod", { id: makeMethodId, companyId }),+ () =>+ single(db, "quoteMakeMethod", { id: quoteMakeMethodId, companyId })+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (quoteMakeMethod.error) {+ throw new Error("Failed to get quote make method");+ }++ const itemId = makeMethod.data?.itemId;++ const [quoteOperations, itemReplenishment] = await inOrder([+ () =>+ many<+ "quoteOperationsWithMakeMethods",+ Views["quoteOperationsWithMakeMethods"]["Row"] & {+ quoteOperationTool: Tables["quoteOperationTool"]["Row"][];+ quoteOperationParameter: Tables["quoteOperationParameter"]["Row"][];+ quoteOperationStep: Tables["quoteOperationStep"]["Row"][];+ }+ >(+ db,+ "quoteOperationsWithMakeMethods",+ { quoteLineId: quoteMakeMethod.data.quoteLineId, companyId },+ {+ embed: {+ quoteOperationTool: {+ table: "quoteOperationTool",+ on: "operationId"+ },+ quoteOperationParameter: {+ table: "quoteOperationParameter",+ on: "operationId"+ },+ quoteOperationStep: {+ table: "quoteOperationStep",+ on: "operationId"+ }+ }+ }+ ),+ () => single(db, "itemReplenishment", { itemId, companyId })+ ]);++ if (quoteOperations.error) {+ throw new Error("Failed to get quote operations");+ }++ if (itemReplenishment.error) {+ throw new Error("Failed to get item replenishment");+ }++ if (itemReplenishment.data?.requiresConfiguration) {+ throw new Error("Cannot override method of configured item");+ }++ const [quoteMethodTrees] = await inOrder([+ () =>+ getQuoteMethodTree(+ db,+ quoteMakeMethodId,+ quoteMakeMethod.data.parentMaterialId+ )+ ]);++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const quoteMethodTree = quoteMethodTrees.data?.[0] as QuoteMethodTreeItem;+ if (!quoteMethodTree)+ throw new NotFoundError("Job method tree not found");++ const madeItemIds: string[] = [];++ // Awaited: the walk is async, and without it only the root had been+ // visited when the make methods below were read, so a sub-assembly+ // inside this one had no make method to save its materials under.+ await traverseQuoteMethod(+ quoteMethodTree,+ (node: QuoteMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ madeItemIds.push(node.data.itemId);+ }+ }+ );++ const makeMethods = await many(db, "activeMakeMethods", {+ itemId: madeItemIds,+ companyId+ });+ if (makeMethods.error) {+ throw new Error("Failed to get make methods");+ }++ const makeMethodByItemId: Record<string, string> = {};+ makeMethods.data?.forEach((m) => {+ if (m.itemId) {+ // @ts-expect-error - itemId is not null+ makeMethodByItemId[m.itemId!] = m.id;+ }+ });++ await db.transaction().execute(async (trx) => {+ let makeMethodsToDelete: string[] = [];+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =+ [];+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =+ [];++ await traverseQuoteMethod(+ quoteMethodTree!,+ (node: QuoteMethodTreeItem) => {+ if (node.data.itemId && node.data.methodType === "Make to Order") {+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]!);+ }++ node.children.forEach((child) => {+ // A zero-quantity BOM line is dropped from the saved method.+ if (isZeroQuantity(child.data.quantity)) return;+ materialInserts.push({+ makeMethodId: makeMethodByItemId[node.data.itemId]!,+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],+ itemId: child.data.itemId,+ kit: child.data.kit,+ itemType: child.data.itemType,+ methodType: child.data.methodType,+ order: child.data.order,+ quantity: child.data.quantity,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });+ }+ );++ if (makeMethodsToDelete.length > 0) {+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>+ mm === makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : mm+ );+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("methodMaterial")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("methodOperation")+ .where("makeMethodId", "in", makeMethodsToDelete)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);+ }++ if (parts.billOfMaterial && materialInserts.length > 0) {+ await trx+ .insertInto("methodMaterial")+ .values(+ materialInserts.map((insert) => ({+ ...insert,+ productionQuantity: undefined,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId,+ itemId:+ insert.itemId === quoteMakeMethod.data.itemId+ ? itemId+ : insert.itemId+ }))+ )+ .execute();+ }++ if (parts.billOfProcess) {+ quoteOperations.data?.forEach((op) => {+ operationInserts.push({+ makeMethodId: op.makeMethodId!,+ processId: op.processId!,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description ?? "",+ setupTime: op.setupTime ?? 0,+ setupUnit: op.setupUnit ?? "Total Minutes",+ laborTime: op.laborTime ?? 0,+ laborUnit: op.laborUnit ?? "Minutes/Piece",+ machineTime: op.machineTime ?? 0,+ machineUnit: op.machineUnit ?? "Minutes/Piece",+ order: op.order ?? 1,+ operationOrder: op.operationOrder ?? "After Previous",+ operationType: op.operationType ?? "Process",+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ });+ });++ if (operationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("methodOperation")+ .values(+ operationInserts.map((insert) => ({+ ...insert,+ makeMethodId:+ insert.makeMethodId ===+ makeMethodByItemId[quoteMakeMethod.data.itemId]+ ? makeMethod.data.id+ : insert.makeMethodId+ }))+ )+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ quoteOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationStep,+ procedureId+ } = operation;++ if (+ parts.tools &&+ Array.isArray(quoteOperationTool) &&+ quoteOperationTool.length > 0+ ) {+ await trx+ .insertInto("methodOperationTool")+ .values(+ quoteOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (!procedureId) {+ if (+ parts.parameters &&+ Array.isArray(quoteOperationParameter) &&+ quoteOperationParameter.length > 0+ ) {+ await trx+ .insertInto("methodOperationParameter")+ .values(+ quoteOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ // Assembly ops inherit steps from the linked instruction —+ // never copy (possibly stale) quote steps alongside it.+ !operation.assemblyInstructionId &&+ Array.isArray(quoteOperationStep) &&+ quoteOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("methodOperationStep")+ .values(+ quoteOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ quoteOperationStep,+ insertedSteps,+ "quoteOperationStepSlide",+ "methodOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)+ });++ break;+ }+ case "quoteLineToJob": {+ const jobId = targetId;+ if (!jobId) {+ throw new Error("Invalid targetId");+ }++ const [quoteId, quoteLineId] = (sourceId as string).split(":");+ if (!quoteId || !quoteLineId) {+ throw new Error("Invalid sourceId");+ }+ // Assembly ops whose steps were materialized from an instruction —+ // material ↔ step links flush after the jobMaterial rows exist.+ const assemblyOperationsToLink: Array<{+ operationId: string;+ assemblyInstructionId: string;+ }> = [];++ const job = await single(db, "job", { id: jobId, companyId });+ const jobMakeMethod = await single(db, "jobMakeMethod", {+ jobId,+ parentMaterialId: isNull,+ companyId+ });+ const quoteMakeMethod = await single(db, "quoteMakeMethod", {+ parentMaterialId: isNull,+ quoteLineId,+ companyId+ });+ const quoteMaterials = await many(db, "quoteMaterial", {+ quoteLineId,+ companyId+ });+ const quoteOperations = await many<+ "quoteOperation",+ QuoteOperationWithDetails+ >(+ db,+ "quoteOperation",+ { quoteLineId, companyId },+ { embed: quoteOperationDetails }+ );++ if (job.error) {+ throw new Error("Failed to get job");+ }++ if (jobMakeMethod.error || !jobMakeMethod.data) {+ throw new Error("Failed to get job make method");+ }++ if (+ quoteMakeMethod.error ||+ quoteMaterials.error ||+ quoteOperations.error+ ) {+ if (quoteMakeMethod.error) {+ getMethodLogger.error("quoteMakeMethodError", {+ error: quoteMakeMethod.error+ });+ }+ if (quoteMaterials.error) {+ getMethodLogger.error("quoteMaterialsError", {+ error: quoteMaterials.error+ });+ }+ if (quoteOperations.error) {+ getMethodLogger.error("quoteOperationsError", {+ error: quoteOperations.error+ });+ }+ throw new Error("Failed to fetch quote data");+ }++ const quoteMethodTrees = await getQuoteMethodTree(+ db,+ quoteMakeMethod.data.id+ );++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const quoteMethodTree = quoteMethodTrees.data?.[0] as QuoteMethodTreeItem;+ if (!quoteMethodTree) throw new NotFoundError("Method tree not found");++ // Loaded ONCE per request, before the transaction — as itemToJob does.+ // This read pages the company's whole itemSupersession table, and it used+ // to sit inside the per-node traverseQuoteMethod callback, so a BOM of N+ // nodes issued N full-table reads sequentially inside the transaction+ // holding the pool's single connection. The map depends only on the+ // company and the job's build date, both fixed for the request.+ const { redirect: supersessionRedirect } = await loadSupersessionRedirect(+ db,+ companyId,+ job.data+ );+ const itemDefaults = createItemDefaults(companyId, job.data.locationId);++ const quoteMaterialIdToJobMaterialId: Record<string, string> = {};+ const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};+ // Track estimated quantities for each make method to set on operations+ const quoteMakeMethodIdToQuantities: Record<+ string,+ {+ targetQuantity: number;+ estimatedQuantity: number;+ totalWithScrap: number;+ }+ > = {};++ await db.transaction().execute(async (trx) => {+ await itemDefaults.load(+ trx,+ treeItemIds(quoteMethodTree, supersessionRedirect)+ );+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMakeMethod")+ .where((eb) =>+ eb.and([+ eb("jobId", "=", jobId),+ eb("parentMaterialId", "is not", null)+ ])+ )+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMaterial")+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("jobOperation")+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);++ const insertedJobMaterialIds: string[] = [];+ await traverseQuoteMethod(+ quoteMethodTree,+ async (node: QuoteMethodTreeItem) => {+ const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =+ [];++ // Get the total quantity for this node (parent level) to pass to children+ // This is estimated + scrap for Make parts (what children use for their target calculation)+ let nodeTotalForChildren: number;+ if (node.data.isRoot) {+ // Root: target = job quantity, calculate scrap and total+ const rootScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ node.data.itemId+ );+ const rootTarget = job.data?.quantity ?? 1;+ // Scrap applies to every method type (mirrors itemToJob)+ const rootScrapQuantity = scrapAllowance(+ rootTarget,+ rootScrapPercentage+ );+ const rootTotalWithScrap = rootTarget + rootScrapQuantity;+ // For Make: estimatedQuantity is good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const rootEstimatedQuantity =+ node.data.methodType === "Make to Order"+ ? rootTarget+ : rootTotalWithScrap;++ nodeTotalForChildren = rootTotalWithScrap;++ // Store root quantities+ quoteMakeMethodIdToQuantities[quoteMakeMethod.data.id] = {+ targetQuantity: rootTarget,+ estimatedQuantity: rootEstimatedQuantity,+ totalWithScrap: rootTotalWithScrap+ };+ } else {+ // Non-root: get from stored quantities using parent's quoteMakeMethodId+ const parentQuoteMakeMethodId =+ node.data.quoteMaterialMakeMethodId;+ const parentQuantities =+ quoteMakeMethodIdToQuantities[parentQuoteMakeMethodId ?? ""];+ // Children receive parent's total (estimated + scrap) for cascade+ nodeTotalForChildren = parentQuantities?.totalWithScrap ?? 1;+ }++ for await (const child of node.children) {+ // A zero-quantity Buy/Pick line is dropped from the created job.+ // A made sub-assembly is left intact even at quantity 0: its+ // operations are copied by make method below and would reference+ // a make method that never got created if the row were removed.+ if (+ isZeroQuantity(child.data.quantity) &&+ child.data.methodType !== "Make to Order"+ ) {+ continue;+ }+ const newMaterialId = nanoid();+ quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;++ // Resolve the supersession FIRST — see the note in+ // itemToJobMakeMethod's mapper. Deriving the scrap rate, bin and+ // quantities from the pre-swap item and patching the row+ // afterwards is what left swapped lines costing the+ // predecessor's scrap; swapping up front means every field here,+ // and any field added later, is computed for the item the row+ // ends up being for. Buy/Pick only — made sub-assemblies are not+ // swapped on the quote path at all (their successors' methods+ // would have to be re-exploded from the item side).+ const supersession = await resolveJobMaterialSupersession(+ trx,+ companyId,+ supersessionRedirect,+ {+ itemId: child.data.itemId,+ methodType: child.data.methodType+ }+ );+ const itemId = supersession?.itemId ?? child.data.itemId;+ const quantityPerParent =+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);++ // Get scrap percentage for this item+ const itemScrapPercentage = await itemDefaults.scrapPercentage(+ trx,+ itemId+ );++ // Calculate scrap quantities for this child material+ // Target = parent's total (including scrap) * quantity per parent+ const childTargetQuantity =+ nodeTotalForChildren * quantityPerParent;+ // Scrap applies to every method type (mirrors itemToJob)+ const childScrapQuantity = scrapAllowance(+ childTargetQuantity,+ itemScrapPercentage+ );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;+ // For Make: estimatedQuantity is good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const childEstimatedQuantity =+ child.data.methodType === "Make to Order"+ ? childTargetQuantity+ : childTotalWithScrap;++ // Store quantities for this child's make method (if it has one)+ if (child.data.quoteMaterialMakeMethodId) {+ quoteMakeMethodIdToQuantities[+ child.data.quoteMaterialMakeMethodId+ ] = {+ targetQuantity: childTargetQuantity,+ estimatedQuantity: childEstimatedQuantity,+ totalWithScrap: childTotalWithScrap+ };+ }++ jobMaterialInserts.push({+ id: newMaterialId,+ jobId,+ itemId,+ itemType: supersession?.itemType ?? child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ description:+ supersession?.description ?? child.data.description,+ jobMakeMethodId:+ child.data.quoteMakeMethodId === quoteMakeMethod.data.id+ ? jobMakeMethod.data.id+ : quoteMakeMethodIdToJobMakeMethodId[+ child.data.quoteMakeMethodId+ ]!,+ quantity: quantityPerParent,+ scrapQuantity: childScrapQuantity,+ estimatedQuantity: childEstimatedQuantity,+ itemScrapPercentage,+ substitutedFromItemId:+ supersession?.substitutedFromItemId ?? null,+ substitutionFactor: supersession?.factor ?? null,+ // ALWAYS set, never conditionally spread. Kysely builds ONE+ // column list for a multi-row insert, so the moment a single+ // swapped row carries `unitCost` the column joins the statement+ // and every row that omitted the key is written NULL — and+ // `jobMaterial.unitCost` is NOT NULL DEFAULT 0, so the whole+ // insert fails. Omitting a key only reaches the default when NO+ // row in the batch has it.+ //+ // Branch on whether a swap happened, matching the other two+ // flows: a swapped row must not inherit the predecessor's cost,+ // and an unswapped one keeps the quote line's own. This path+ // never set the column before, so unswapped rows silently took+ // the 0 default even though the quote tree carries a cost.+ unitCost: supersession+ ? (supersession.unitCost ?? 0)+ : (child.data.unitCost ?? 0),+ // The bin belongs to the post-swap item; an explicit bin on the+ // quote line still wins.+ storageUnitId: await itemDefaults.storageUnitId(+ trx,+ itemId,+ child.data.storageUnitId+ ),+ requiresBatchTracking:+ supersession?.requiresBatchTracking ??+ child.data.itemTrackingType === "Batch",+ requiresSerialTracking:+ supersession?.requiresSerialTracking ??+ child.data.itemTrackingType === "Serial",+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {}+ });++ if (child.data.quoteMaterialMakeMethodId) {+ const newMakeMethodId = nanoid();+ quoteMakeMethodIdToJobMakeMethodId[+ child.data.quoteMaterialMakeMethodId+ ] = newMakeMethodId;+ jobMakeMethodInserts.push({+ id: newMakeMethodId,+ jobId,+ parentMaterialId: quoteMaterialIdToJobMaterialId[child.id],+ itemId: child.data.itemId,+ quantityPerParent: child.data.quantity,+ companyId,+ createdBy: userId+ });+ }+ }++ if (parts.billOfMaterial && jobMaterialInserts.length > 0) {+ // The supersession swap happens where each row is built, before+ // any field derives from the item — there is deliberately no+ // second pass here.+ await trx+ .insertInto("jobMaterial")+ .values(jobMaterialInserts)+ .execute();+ insertedJobMaterialIds.push(+ ...jobMaterialInserts.flatMap((m) => (m.id ? [m.id] : []))+ );+ }++ if (parts.billOfMaterial && jobMakeMethodInserts.length > 0) {+ await renameMakeMethods(trx, {+ table: "jobMakeMethod",+ companyId,+ scope: { column: "jobId", value: jobId },+ rows: jobMakeMethodInserts.map((insert) => ({+ parentMaterialId: insert.parentMaterialId!,+ id: insert.id!,+ quantityPerParent: insert.quantityPerParent+ }))+ });+ }+ }+ );++ if (parts.billOfProcess) {+ const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =+ quoteOperations.data.map((op) => {+ // Get quantities for this operation's make method+ const opQuantities =+ quoteMakeMethodIdToQuantities[op.quoteMakeMethodId ?? ""];+ // The traversal stores quantities for every make method in the+ // tree, so a miss means the operation references an orphaned+ // make method. Fail the conversion (rolls back the transaction)+ // instead of silently inserting a zero-quantity operation with+ // a NULL jobMakeMethodId.+ if (!opQuantities) {+ throw new Error(+ `No quantities found for quote make method ${op.quoteMakeMethodId} referenced by operation ${op.id} — the quote method tree and its operations are out of sync`+ );+ }+ return {+ jobId,+ jobMakeMethodId:+ op.quoteMakeMethodId === quoteMakeMethod.data.id+ ? jobMakeMethod.data.id+ : quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],+ processId: op.processId,+ procedureId: op.procedureId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ // Carry the Assembly → BOP sync link so the MES can drive the+ // animated instruction player on jobs made from a synced method.+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ targetQuantity: opQuantities.targetQuantity,+ // Fractional targets flow through; the scrap allowance is already whole+ operationQuantity: opQuantities.totalWithScrap,+ companyId,+ createdBy: userId,+ customFields: {}+ };+ });++ if (jobOperationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("jobOperation")+ .values(jobOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ quoteOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationStep,+ procedureId+ } = operation;+ // abilities are not copied on this path (no quoteOperationAbility table)++ if (+ parts.tools &&+ Array.isArray(quoteOperationTool) &&+ quoteOperationTool.length > 0+ ) {+ await trx+ .insertInto("jobOperationTool")+ .values(+ quoteOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (procedureId) {+ await insertProcedureDataForJobOperation(trx, {+ operationId,+ procedureId,+ companyId,+ userId+ });+ } else {+ if (+ parts.parameters &&+ Array.isArray(quoteOperationParameter) &&+ quoteOperationParameter.length > 0+ ) {+ await trx+ .insertInto("jobOperationParameter")+ .values(+ quoteOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (operation.assemblyInstructionId) {+ // Assembly ops inherit their steps from the linked+ // instruction (the quote only carries the pointer);+ // material ↔ step links are flushed after the jobMaterial+ // rows exist.+ await insertAssemblyDataForJobOperation(trx, {+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId,+ companyId,+ userId+ });+ assemblyOperationsToLink.push({+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId+ });+ } else if (+ parts.steps &&+ Array.isArray(quoteOperationStep) &&+ quoteOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ quoteOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ quoteOperationStep,+ insertedSteps,+ "quoteOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)++ // Materials were inserted before operations in this direction, so the+ // assembly material ↔ step links can flush immediately.+ await linkAssemblyStepMaterialsForJobOperations(+ trx,+ assemblyOperationsToLink,+ companyId+ );++ await settleConsumeFirstLines({+ trx,+ companyId,+ jobId: jobId,+ jobMaterialIds: insertedJobMaterialIds,+ locationId: job.data?.locationId,+ asOfDate: jobBuildDate(job.data)+ });+ });++ break;+ }+ case "quoteLineToQuoteLine": {+ const [, sourceQuoteLineId] = (sourceId as string).split(":");+ const [targetQuoteId, targetQuoteLineId] = (targetId as string).split(+ ":"+ );+ if (!sourceQuoteLineId || !targetQuoteId || !targetQuoteLineId) {+ throw new Error("Invalid sourceId or targetId");+ }++ const [+ targetQuoteMakeMethod,+ sourceQuoteMakeMethod,+ sourceQuoteMaterials,+ sourceQuoteOperations+ ] = await inOrder([+ () =>+ single(db, "quoteMakeMethod", {+ quoteLineId: targetQuoteLineId,+ parentMaterialId: isNull,+ companyId+ }),+ () =>+ single(db, "quoteMakeMethod", {+ parentMaterialId: isNull,+ quoteLineId: sourceQuoteLineId,+ companyId+ }),+ () =>+ many(db, "quoteMaterial", {+ quoteLineId: sourceQuoteLineId,+ companyId+ }),+ () =>+ many<+ "quoteOperation",+ Tables["quoteOperation"]["Row"] & {+ quoteOperationTool: Tables["quoteOperationTool"]["Row"][];+ quoteOperationParameter: Tables["quoteOperationParameter"]["Row"][];+ quoteOperationStep: Tables["quoteOperationStep"]["Row"][];+ }+ >(+ db,+ "quoteOperation",+ { quoteLineId: sourceQuoteLineId, companyId },+ {+ embed: {+ quoteOperationTool: {+ table: "quoteOperationTool",+ on: "operationId"+ },+ quoteOperationParameter: {+ table: "quoteOperationParameter",+ on: "operationId"+ },+ quoteOperationStep: {+ table: "quoteOperationStep",+ on: "operationId"+ }+ }+ }+ )+ ]);++ if (targetQuoteMakeMethod.error || !targetQuoteMakeMethod.data) {+ getMethodLogger.error("Failed to get target quote make method", {+ error: targetQuoteMakeMethod.error+ });+ throw new Error("Failed to get target quote make method");+ }+ // targetQuoteId is written onto new rows and priced below; bind it to+ // the verified target line rather than trusting the body.+ if (targetQuoteMakeMethod.data.quoteId !== targetQuoteId) {+ throw new NotFoundError("Quote line not found");+ }++ if (+ sourceQuoteMakeMethod.error ||+ sourceQuoteMaterials.error ||+ sourceQuoteOperations.error+ ) {+ throw new Error("Failed to source quote data");+ }++ const [quoteMethodTrees] = await inOrder([+ () => getQuoteMethodTree(db, sourceQuoteMakeMethod.data.id)+ ]);++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const quoteMethodTree = quoteMethodTrees.data?.[0] as QuoteMethodTreeItem;+ if (!quoteMethodTree) throw new NotFoundError("Method tree not found");++ const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};+ const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> = {};++ await db.transaction().execute(async (trx) => {+ // Delete existing quoteMakeMethods, quoteMaterials, and quoteOperations for this quote line+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("quoteMakeMethod")+ .where((eb) =>+ eb.and([+ eb("quoteLineId", "=", targetQuoteLineId),+ eb("parentMaterialId", "is not", null)+ ])+ )+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("quoteMaterial")+ .where("quoteLineId", "=", targetQuoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteLineId", "=", targetQuoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("quoteOperation")+ .where("quoteLineId", "=", targetQuoteLineId)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve()+ ]);++ await traverseQuoteMethod(+ quoteMethodTree,+ async (node: QuoteMethodTreeItem) => {+ const quoteMaterialInserts: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =+ [];+ const quoteMakeMethodInserts: Database["public"]["Tables"]["quoteMakeMethod"]["Insert"][] =+ [];++ for await (const child of node.children) {+ // A zero-quantity Buy/Pick line is dropped from the copied quote.+ // A made sub-assembly is left intact even at quantity 0: its+ // operations are copied by make method below and would reference+ // a make method that never got created if the row were removed.+ if (+ isZeroQuantity(child.data.quantity) &&+ child.data.methodType !== "Make to Order"+ ) {+ continue;+ }+ const newMaterialId = nanoid();+ quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;++ quoteMaterialInserts.push({+ id: newMaterialId,+ quoteId: targetQuoteId,+ quoteLineId: targetQuoteLineId,+ itemId: child.data.itemId,+ kit: child.data.kit,+ itemType: child.data.itemType,+ methodType: child.data.methodType,+ order: child.data.order,+ description: child.data.description,+ quoteMakeMethodId:+ child.data.quoteMakeMethodId === sourceQuoteMakeMethod.data.id+ ? targetQuoteMakeMethod.data.id+ : quoteMakeMethodIdToQuoteMakeMethodId[+ child.data.quoteMakeMethodId+ ]!,+ quantity: child.data.quantity,+ storageUnitId: child.data.storageUnitId,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ unitCost: child.data.unitCost ?? 0, // TODO: get real unit cost+ unitCostSource: child.data.unitCostSource ?? "system",+ companyId,+ createdBy: userId,+ customFields: {}+ });++ if (child.data.quoteMaterialMakeMethodId) {+ const newMakeMethodId = nanoid();+ quoteMakeMethodIdToQuoteMakeMethodId[+ child.data.quoteMaterialMakeMethodId+ ] = newMakeMethodId;+ quoteMakeMethodInserts.push({+ id: newMakeMethodId,+ quoteId: targetQuoteId,+ quoteLineId: targetQuoteLineId,+ parentMaterialId: quoteMaterialIdToQuoteMaterialId[child.id],+ itemId: child.data.itemId,+ quantityPerParent: child.data.quantity,+ companyId,+ createdBy: userId+ });+ }+ }++ if (parts.billOfMaterial && quoteMaterialInserts.length > 0) {+ await trx+ .insertInto("quoteMaterial")+ .values(quoteMaterialInserts)+ .execute();+ }++ if (parts.billOfMaterial && quoteMakeMethodInserts.length > 0) {+ await renameMakeMethods(trx, {+ table: "quoteMakeMethod",+ companyId,+ scope: { column: "quoteLineId", value: targetQuoteLineId },+ rows: quoteMakeMethodInserts.map((insert) => ({+ parentMaterialId: insert.parentMaterialId!,+ id: insert.id!,+ quantityPerParent: insert.quantityPerParent+ }))+ });+ }+ }+ );++ if (parts.billOfProcess) {+ const quoteOperationInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =+ sourceQuoteOperations.data.map((op) => ({+ quoteId: targetQuoteId,+ quoteLineId: targetQuoteLineId,+ quoteMakeMethodId:+ op.quoteMakeMethodId === sourceQuoteMakeMethod.data.id+ ? targetQuoteMakeMethod.data.id+ : quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],+ processId: op.processId,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ laborRate: op.laborRate,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ machineRate: op.machineRate,+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ overheadRate: op.overheadRate,+ tags: op.tags ?? [],+ workInstruction: toJson(+ parts.workInstructions ? op.workInstruction : {}+ ),+ companyId,+ createdBy: userId,+ customFields: {}+ }));++ if (quoteOperationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("quoteOperation")+ .values(quoteOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ sourceQuoteOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationStep+ } = operation;++ if (+ parts.tools &&+ Array.isArray(quoteOperationTool) &&+ quoteOperationTool.length > 0+ ) {+ await trx+ .insertInto("quoteOperationTool")+ .values(+ quoteOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.parameters &&+ Array.isArray(quoteOperationParameter) &&+ quoteOperationParameter.length > 0+ ) {+ await trx+ .insertInto("quoteOperationParameter")+ .values(+ quoteOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ parts.steps &&+ Array.isArray(quoteOperationStep) &&+ quoteOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("quoteOperationStep")+ .values(+ quoteOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ quoteOperationStep,+ insertedSteps,+ "quoteOperationStepSlide",+ "quoteOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ } // end if (parts.billOfProcess)+ });++ await calculateQuoteLinePrices(+ db,+ targetQuoteId,+ targetQuoteLineId,+ companyId,+ userId+ );++ break;+ }++ case "quoteToQuote": {+ const sourceQuoteId = sourceId;+ const asRevision = !!targetId;+ let newQuoteId = "";++ const oldLineToNewLineMap: Record<string, string> = {};++ const [+ sourceQuote,+ sourceQuotePayment,+ sourceQuoteShipment,+ sourceQuoteLines+ ] = await inOrder([+ () => single(db, "quote", { id: sourceQuoteId, companyId }),+ () => single(db, "quotePayment", { id: sourceQuoteId, companyId }),+ () => single(db, "quoteShipment", { id: sourceQuoteId, companyId }),+ () => many(db, "quoteLine", { quoteId: sourceQuoteId, companyId })+ ]);++ if (sourceQuote.error) {+ throw new Error("Failed to get source quote");+ }++ if (sourceQuotePayment.error) {+ throw new Error("Failed to get source quote payment");+ }++ if (sourceQuoteShipment.error) {+ throw new Error("Failed to get source quote shipment");+ }++ const sourceQuoteLinePricing = await many(db, "quoteLinePrice", {+ quoteLineId: sourceQuoteLines.data?.map((l) => l.id) ?? []+ });++ if (sourceQuoteLinePricing.error) {+ throw new Error("Failed to get source quote line pricing");+ }++ await db.transaction().execute(async (trx) => {+ let quoteId: string;+ let revisionId = 0;+ if (asRevision) {+ quoteId = sourceQuote.data?.quoteId ?? "";+ revisionId = await getNextRevisionSequence(+ trx,+ "quote",+ "quoteId",+ quoteId,+ companyId+ );+ } else {+ quoteId = await getNextSequence(trx, "quote", companyId);+ }++ // Each revision needs its own link row (the share page resolves a+ // quote by externalLinkId), but documentId is unique per document —+ // qualify it with the revision so a revision of Q000001 doesn't+ // collide with the original's link.+ //+ // A conflict here can only mean an ORPHAN: revisions are numbered+ // max(revisionId) + 1, so this documentId can't belong to a live+ // quote — the previous holder was deleted and deleteQuote leaves the+ // link row behind. Reuse it rather than failing the whole copy.+ const linkDocumentId =+ revisionId > 0 ? `${quoteId}-${revisionId}` : quoteId;+ const externalLinkId = await trx+ .insertInto("externalLink")+ .values({+ documentId: linkDocumentId,+ documentType: "Quote",+ companyId+ })+ .onConflict((oc) =>+ oc+ .columns(["documentId", "documentType", "companyId"])+ .doUpdateSet({ documentId: linkDocumentId })+ )+ .returning(["id"])+ .executeTakeFirstOrThrow();++ let opportunityId: string | undefined = undefined;+ if (asRevision) {+ opportunityId = sourceQuote.data?.opportunityId ?? undefined;+ } else {+ const opportunity = await trx+ .insertInto("opportunity")+ .values({+ companyId,+ customerId: sourceQuote.data?.customerId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ opportunityId = opportunity.id;+ }++ const quote = await trx+ .insertInto("quote")+ .values([+ {+ quoteId,+ revisionId,+ customerId: sourceQuote.data?.customerId,+ customerContactId: sourceQuote.data?.customerContactId,+ customerLocationId: sourceQuote.data?.customerLocationId,+ customerReference: sourceQuote.data?.customerReference,+ locationId: sourceQuote.data?.locationId,+ expirationDate: datetime+ .today(await getCompanyTimeZone(trx, companyId))+ .add({ days: 30 })+ .toString(),+ salesPersonId: sourceQuote.data?.salesPersonId ?? userId,+ status: "Draft",+ externalNotes: toJson(sourceQuote.data?.externalNotes),+ internalNotes: toJson(sourceQuote.data?.internalNotes),+ currencyCode: sourceQuote.data?.currencyCode,+ exchangeRate: sourceQuote.data?.exchangeRate,+ exchangeRateUpdatedAt: datetime.timestamp(),+ externalLinkId: externalLinkId.id,+ opportunityId,+ companyId,+ createdBy: userId+ }+ ])+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!quote.id) {+ throw new Error("Failed to insert quote");+ }++ newQuoteId = quote.id;++ // Insert quotePayment+ await trx+ .insertInto("quotePayment")+ .values({+ id: quote.id,+ invoiceCustomerId: sourceQuotePayment.data?.invoiceCustomerId,+ invoiceCustomerContactId:+ sourceQuotePayment.data?.invoiceCustomerContactId,+ invoiceCustomerLocationId:+ sourceQuotePayment.data?.invoiceCustomerLocationId,+ paymentTermId: sourceQuotePayment.data?.paymentTermId,+ companyId,+ updatedBy: userId+ })+ .execute();++ // Insert quoteShipment+ await trx+ .insertInto("quoteShipment")+ .values({+ id: quote.id,+ locationId: sourceQuoteShipment.data?.locationId,+ shippingMethodId: sourceQuoteShipment.data?.shippingMethodId,+ shippingTermId: sourceQuoteShipment.data?.shippingTermId,+ shippingCost: sourceQuoteShipment.data?.shippingCost,+ receiptRequestedDate:+ sourceQuoteShipment.data?.receiptRequestedDate,+ companyId,+ updatedBy: userId+ })+ .execute();++ for await (const { id, ...line } of sourceQuoteLines.data ?? []) {+ const newLine = await trx+ .insertInto("quoteLine")+ .values({+ ...line,+ ...toJsonColumns(line, QUOTE_LINE_JSON_COLUMNS),+ quoteId: quote.id,+ companyId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!newLine.id) {+ throw new Error("Failed to insert quote line");+ }++ if (line.methodType === "Make to Order") {+ // we only need further processing on make lines+ oldLineToNewLineMap[id] = newLine.id;+ }++ const sourceQuotePricingForLine =+ sourceQuoteLinePricing.data?.filter((l) => l.quoteLineId === id) ??+ [];++ if (sourceQuotePricingForLine.length > 0) {+ await trx+ .insertInto("quoteLinePrice")+ .values(+ sourceQuotePricingForLine.map((l) => ({+ quoteId: newQuoteId!,+ quoteLineId: newLine.id!,+ companyId,+ leadTime: l.leadTime ?? 0,+ discountPercent: l.discountPercent ?? 0,+ quantity: l.quantity ?? 0,+ unitPrice: l.unitPrice ?? 0,+ shippingCost: l.shippingCost ?? 0,+ // Never 0: a zero rate is not a valid snapshot (DB CHECK+ // "exchangeRate" > 0) and zeroes every converted* generated+ // column. A legacy null line rate falls back to the SOURCE+ // QUOTE's own stamped header rate; 1 only when the source+ // header predates stamping too (base-consistent with its+ // line snapshots' old default).+ exchangeRate:+ l.exchangeRate ?? sourceQuote.data?.exchangeRate ?? 1,+ categoryMarkups: JSON.stringify(l.categoryMarkups ?? {}),+ // Copied prices keep their provenance so a manual price+ // stays protected on the new quote/revision, and the+ // trace that explains it.+ priceSource: l.priceSource ?? "system",+ priceTrace: toJson(l.priceTrace),+ createdBy: userId+ }))+ )+ .execute();+ }+ }+ });++ await db.transaction().execute(async (trx) => {+ for await (const [oldLineId, newLineId] of Object.entries(+ oldLineToNewLineMap+ )) {+ const [+ targetQuoteMakeMethod,+ sourceQuoteMakeMethod,+ sourceQuoteMaterials,+ sourceQuoteOperations+ ] = await Promise.all([+ single(trx, "quoteMakeMethod", {+ parentMaterialId: isNull,+ quoteLineId: newLineId,+ companyId+ }),+ single(trx, "quoteMakeMethod", {+ parentMaterialId: isNull,+ quoteLineId: oldLineId,+ companyId+ }),+ many(trx, "quoteMaterial", { quoteLineId: oldLineId, companyId }),+ many<+ "quoteOperation",+ Tables["quoteOperation"]["Row"] & {+ quoteOperationTool: Tables["quoteOperationTool"]["Row"][];+ quoteOperationParameter: Tables["quoteOperationParameter"]["Row"][];+ quoteOperationStep: Tables["quoteOperationStep"]["Row"][];+ }+ >(+ trx,+ "quoteOperation",+ { quoteLineId: oldLineId, companyId },+ {+ embed: {+ quoteOperationTool: {+ table: "quoteOperationTool",+ on: "operationId"+ },+ quoteOperationParameter: {+ table: "quoteOperationParameter",+ on: "operationId"+ },+ quoteOperationStep: {+ table: "quoteOperationStep",+ on: "operationId"+ }+ }+ }+ )+ ]);++ if (targetQuoteMakeMethod.error) {+ getMethodLogger.error("Failed to get target quote make method", {+ error: targetQuoteMakeMethod.error+ });+ throw new Error("Failed to get target quote make method");+ }++ if (+ sourceQuoteMakeMethod.error ||+ sourceQuoteMaterials.error ||+ sourceQuoteOperations.error+ ) {+ throw new Error("Failed to source quote data");+ }++ const [quoteMethodTrees] = await Promise.all([+ getQuoteMethodTree(trx, sourceQuoteMakeMethod.data.id)+ ]);++ if (quoteMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const quoteMethodTree = quoteMethodTrees+ .data?.[0] as QuoteMethodTreeItem;+ if (!quoteMethodTree)+ throw new NotFoundError("Method tree not found");++ const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};+ const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> =+ {};++ await traverseQuoteMethod(+ quoteMethodTree,+ async (node: QuoteMethodTreeItem) => {+ const quoteMaterialInserts: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =+ [];+ const quoteMakeMethodInserts: Database["public"]["Tables"]["quoteMakeMethod"]["Insert"][] =+ [];++ for await (const child of node.children) {+ // A zero-quantity Buy/Pick line is dropped from the new quote.+ // A made sub-assembly is left intact even at quantity 0: its+ // operations are copied by make method below and would reference+ // a make method that never got created if the row were removed.+ if (+ isZeroQuantity(child.data.quantity) &&+ child.data.methodType !== "Make to Order"+ ) {+ continue;+ }+ const newMaterialId = nanoid();+ quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;++ quoteMaterialInserts.push({+ id: newMaterialId,+ quoteId: newQuoteId,+ quoteLineId: newLineId,+ itemId: child.data.itemId,+ kit: child.data.kit,+ itemType: child.data.itemType,+ methodType: child.data.methodType,+ order: child.data.order,+ description: child.data.description,+ quoteMakeMethodId:+ child.data.quoteMakeMethodId ===+ sourceQuoteMakeMethod.data.id+ ? targetQuoteMakeMethod.data.id+ : quoteMakeMethodIdToQuoteMakeMethodId[+ child.data.quoteMakeMethodId+ ]!,+ quantity: child.data.quantity,+ storageUnitId: child.data.storageUnitId,+ unitCost: child.data.unitCost ?? 0, // TODO: get real unit cost+ unitCostSource: child.data.unitCostSource ?? "system",+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {}+ });++ if (child.data.quoteMaterialMakeMethodId) {+ const newMakeMethodId = nanoid();+ quoteMakeMethodIdToQuoteMakeMethodId[+ child.data.quoteMaterialMakeMethodId+ ] = newMakeMethodId;+ quoteMakeMethodInserts.push({+ id: newMakeMethodId,+ quoteId: newQuoteId,+ quoteLineId: newLineId,+ parentMaterialId:+ quoteMaterialIdToQuoteMaterialId[child.id],+ itemId: child.data.itemId,+ quantityPerParent: child.data.quantity,+ companyId,+ createdBy: userId+ });+ }+ }++ if (quoteMaterialInserts.length > 0) {+ await trx+ .insertInto("quoteMaterial")+ .values(quoteMaterialInserts)+ .execute();+ }++ if (quoteMakeMethodInserts.length > 0) {+ await renameMakeMethods(trx, {+ table: "quoteMakeMethod",+ companyId,+ scope: { column: "quoteLineId", value: newLineId },+ rows: quoteMakeMethodInserts.map((insert) => ({+ parentMaterialId: insert.parentMaterialId!,+ id: insert.id!,+ quantityPerParent: insert.quantityPerParent+ }))+ });+ }+ }+ );++ const quoteOperationInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =+ sourceQuoteOperations.data.map((op) => ({+ quoteId: newQuoteId,+ quoteLineId: newLineId,+ quoteMakeMethodId:+ op.quoteMakeMethodId === sourceQuoteMakeMethod.data.id+ ? targetQuoteMakeMethod.data.id+ : quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],+ processId: op.processId,+ procedureId: op.procedureId,+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ laborRate: op.laborRate,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ machineRate: op.machineRate,+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ overheadRate: op.overheadRate,+ tags: op.tags ?? [],+ workInstruction: toJson(op.workInstruction),+ companyId,+ createdBy: userId,+ customFields: {}+ }));++ if (quoteOperationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("quoteOperation")+ .values(quoteOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of (+ sourceQuoteOperations.data ?? []+ ).entries()) {+ const operationId = operationIds[index]!.id;+ if (operationId) {+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationStep+ } = operation;++ if (+ Array.isArray(quoteOperationTool) &&+ quoteOperationTool.length > 0+ ) {+ await trx+ .insertInto("quoteOperationTool")+ .values(+ quoteOperationTool.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ Array.isArray(quoteOperationParameter) &&+ quoteOperationParameter.length > 0+ ) {+ await trx+ .insertInto("quoteOperationParameter")+ .values(+ quoteOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ if (+ Array.isArray(quoteOperationStep) &&+ quoteOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("quoteOperationStep")+ .values(+ quoteOperationStep.map(({ id: _id, ...attribute }) => ({+ ...attribute,+ description: toTiptapDoc(attribute.description),+ operationId,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id"])+ .execute();++ await copyStepSlides(+ trx,+ quoteOperationStep,+ insertedSteps,+ "quoteOperationStepSlide",+ "quoteOperationStepSlide",+ companyId,+ userId+ );+ }+ }+ }+ }+ }+ });+ if (newQuoteId) {+ return { success: true, newQuoteId } as GetMethodResult;+ }+ break;+ }+ default:+ throw new Error(`Invalid type ${type}`);+ }++ return { success: true };+ }++ type Method =+ Database["public"]["Functions"]["get_method_tree"]["Returns"][number];++ type MethodTreeItem = {+ id: string;+ data: Method;+ children: MethodTreeItem[];+ };++ /** A make method's tree, read on the caller's connection (`db`, or `trx`). */+ export async function getMethodTree(+ db: Kysely<KyselyDatabase>,+ makeMethodId: string+ ): Promise<{ data: MethodTreeItem[]; error: null }> {+ const { rows } = await sql<Method>`+ SELECT * FROM get_method_tree(${makeMethodId})+ `.execute(db);+ return { data: getMethodTreeArrayToTree(rows), error: null };+ }++ // Build date for a job's supersession / effectivity decisions: prefer the planned+ // start, fall back to the due date, then to today. Used wherever the method tree is+ // instantiated so swaps and BOM-line effectivity are evaluated as-of the same day.+ function jobBuildDate(+ job: { startDate?: string | null; dueDate?: string | null } | null | undefined+ ): string {+ return (+ job?.startDate ?? job?.dueDate ?? new Date().toISOString().slice(0, 10)+ );+ }++ // Load every supersession for the company and collapse it into the redirect map+ // (chain-collapsed, mode-gated, conversion-factored) as-of the job's build date.+ // Every *-ToJob path needs the same map, so this is the single load point.+ async function loadSupersessionRedirect(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ job:+ | {+ locationId?: string | null;+ startDate?: string | null;+ dueDate?: string | null;+ }+ | null+ | undefined+ ): Promise<SupersessionContext> {+ // Read over the direct connection: no row cap to page around (PostgREST stops+ // at 1000 rows, which is why this used to page), and a fraction of the+ // latency. MRP reads the same table in full, so both redirect every rule.+ //+ // A failure throws, like every other read in this function. An empty map is+ // indistinguishable from "this company supersedes nothing", so swallowing an+ // error would build a real work order out of retired parts and report+ // success.+ let rows: SupersessionRow[] = await db+ .selectFrom("itemSupersession")+ .select([+ "itemId",+ "supersessionMode",+ "successorItemId",+ "successorEffectivityDate",+ "conversionFactor"+ ])+ .where("companyId", "=", companyId)+ .orderBy("itemId")+ .execute();++ const consumeFirstItemIds = rows+ .filter((r) => r.supersessionMode === "Consume First")+ .map((r) => r.itemId);+ const consumeFirstOnHand = new Map<string, number>();+ if (consumeFirstItemIds.length > 0 && job?.locationId) {+ const stock = await db+ .selectFrom("itemStockQuantities")+ .select(["itemId", "quantityOnHand"])+ .where("companyId", "=", companyId)+ .where("locationId", "=", job.locationId)+ .where("itemId", "in", consumeFirstItemIds)+ .execute();+ const items = await db+ .selectFrom("item")+ .select(["id", "replenishmentSystem"])+ .where("companyId", "=", companyId)+ .where("id", "in", consumeFirstItemIds)+ .execute();+ const onHandByItem = new Map<string, number>();+ for (const r of stock) {+ onHandByItem.set(+ r.itemId,+ (onHandByItem.get(r.itemId) ?? 0) + Number(r.quantityOnHand ?? 0)+ );+ }+ const madeItemIds = new Set(+ items+ .filter(+ (i) =>+ effectiveReplenishment(i.replenishmentSystem ?? undefined) ===+ "Make"+ )+ .map((i) => i.id)+ );+ for (const id of madeItemIds) {+ consumeFirstOnHand.set(id, onHandByItem.get(id) ?? 0);+ }+ rows = withoutStockedConsumeFirst(+ rows,+ new Set(+ [...onHandByItem]+ .filter(([id, onHand]) => onHand > 0 && !madeItemIds.has(id))+ .map(([id]) => id)+ )+ );+ }++ const redirect = buildSupersessionRedirectMap(rows, jobBuildDate(job));+ const consumeFirstHops = buildConsumeFirstHops(rows, jobBuildDate(job));+ for (const id of [...consumeFirstOnHand.keys()]) {+ if (!redirect.has(id)) consumeFirstOnHand.delete(id);+ }+ const boughtSuccessors = new Set<string>();+ const successorIds = [...new Set([...redirect.values()].map((r) => r.to))];+ if (successorIds.length > 0) {+ const successors = await db+ .selectFrom("item")+ .select(["id", "replenishmentSystem"])+ .where("companyId", "=", companyId)+ .where("id", "in", successorIds)+ .execute();+ for (const i of successors) {+ if (+ effectiveReplenishment(i.replenishmentSystem ?? undefined) !== "Make"+ ) {+ boughtSuccessors.add(i.id);+ }+ }+ }+ return { redirect, consumeFirstOnHand, consumeFirstHops, boughtSuccessors };+ }++ // EVERY jobMaterial field that is a function of WHICH ITEM the row is for, in+ // one place. A supersession swap has to restate all of them, and the way that+ // goes wrong is a hand-written field list that drifts: `itemScrapPercentage` was+ // simply absent from the swap's `.set({...})`, so a swapped line costed the+ // predecessor's scrap forever. Returning them as an object the caller SPREADS+ // means a field added here reaches the swap without a second edit — the list+ // cannot fall out of sync with itself.+ //+ // Quantities are deliberately NOT here: they depend on the parent's cascade and+ // the method type, which this function has no view of. It returns the scrap RATE+ // and lets the caller derive the allowance.+ async function itemDerivedJobMaterialFields(opts: {+ trx: Transaction<KyselyDatabase>;+ companyId: string;+ itemId: string;+ locationId: string;+ /** An explicit bin on the BOM line still wins over the item's default. */+ lineStorageUnitId?: string;+ }) {+ const { trx, companyId, itemId, locationId, lineStorageUnitId } = opts;+ const { strict } = await getStrictBackflushSettings(+ trx,+ companyId,+ locationId+ );++ const [item, replenishment, storageUnitId] = await Promise.all([+ readItemWithCost(trx, itemId, companyId),+ trx+ .selectFrom("itemReplenishment")+ .select("scrapPercentage")+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst(),+ getStorageUnitId(trx, itemId, locationId, lineStorageUnitId, !strict)+ ]);++ if (!item) return null;++ return {+ itemId,+ itemType: item.type,+ description: item.name,+ unitCost: item.itemCost?.[0]?.unitCost ?? 0,+ requiresSerialTracking: item.itemTrackingType === "Serial",+ requiresBatchTracking: item.itemTrackingType === "Batch",+ itemScrapPercentage: Number(replenishment?.scrapPercentage ?? 0),+ storageUnitId+ };+ }++ // Made-component supersession at job creation: if a made child has an effective+ // successor that is ITSELF a made item, repoint the job material at the successor+ // and explode the SUCCESSOR's method (date-pruned) instead of the old part's,+ // scaling the cascade by the conversion factor. A Make -> Buy successor is a+ // structural flip we leave on the old part (handled elsewhere). Returns true when+ // the swap was applied, so the caller can skip the default traversal.+ /**+ * The tree a made line explodes into. A configuration rule can move a Make to+ * Order line onto another item (a 14 ft body where the BOM names the 12 ft+ * one); the line is then that item's, and so is the sub-assembly under it.+ * Exploding `child` as it stood built the BOM item's sub-assembly under the+ * configured item. The line's own fields (quantity, operation, order, the+ * row's ids) stay the BOM line's; the item and its method become the+ * configured item's. Undefined when the configured item has no make method:+ * there is nothing of its own to explode, and the BOM item's would be wrong.+ */+ async function configuredMadeChild(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ child: MethodTreeItem,+ itemId: string | null | undefined+ ): Promise<MethodTreeItem | undefined> {+ if (!itemId || itemId === child.data.itemId) return child;+ const method = await trx+ .selectFrom("activeMakeMethods")+ .select(["id"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!method?.id) return undefined;+ const root = (await getMethodTree(trx, method.id)).data?.[0];+ if (!root) return undefined;+ return {+ id: child.id,+ data: {+ ...child.data,+ itemId: root.data.itemId,+ itemReadableId: root.data.itemReadableId,+ itemTrackingType: root.data.itemTrackingType,+ itemType: root.data.itemType,+ materialMakeMethodId: root.data.materialMakeMethodId,+ replenishmentSystem: root.data.replenishmentSystem,+ revision: root.data.revision,+ unitCost: root.data.unitCost,+ version: root.data.version+ },+ children: root.children+ };+ }++ async function swapMadeSubAssembly(opts: {+ trx: Transaction<KyselyDatabase>;+ companyId: string;+ child: MethodTreeItem;+ material:+ | {+ quantity?: number | null;+ estimatedQuantity?: number | null;+ scrapQuantity?: number | null;+ }+ | undefined;+ materialId: string;+ /** The job's location — the successor's default bin is resolved against it. */+ locationId: string;+ supersessionRedirect: Map<string, { to: string; factor: number }>;+ newMakeMethodId: string;+ traverseMethod: (+ node: MethodTreeItem,+ parentJobMakeMethodId: string | null,+ parentEstimatedQuantity: number+ ) => Promise<unknown>;+ }): Promise<boolean> {+ const {+ trx,+ companyId,+ child,+ material,+ materialId,+ locationId,+ supersessionRedirect,+ newMakeMethodId,+ traverseMethod+ } = opts;++ const madeRedirect = supersessionRedirect.get(child.data.itemId);+ if (!madeRedirect) return false;++ const successorMakeMethod = await trx+ .selectFrom("activeMakeMethods")+ .select(["id"])+ .where("itemId", "=", madeRedirect.to)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!successorMakeMethod?.id) return false;++ // Every item-dependent field, restated for the successor in ONE step. Spread,+ // never hand-listed: this row is being repointed at a different item, so all+ // of them change together, and a field added to the helper arrives here+ // automatically. `itemScrapPercentage` going missing from a hand-written list+ // is exactly how a swapped line ended up costing the predecessor's scrap.+ const itemFields = await itemDerivedJobMaterialFields({+ trx,+ companyId,+ itemId: madeRedirect.to,+ locationId,+ // @ts-ignore: storageUnitIds is a dynamic field+ lineStorageUnitId: child.data.storageUnitIds?.[locationId] ?? undefined+ });+ if (!itemFields) return false;++ // Quantities are the caller's business, not the helper's — they depend on the+ // cascade and the method type. Make to Order: estimatedQuantity is the GOOD+ // quantity, scrap excluded, and target + scrap is what children explode+ // against. Deriving both from the SAME scrap rate is what stops the row and+ // its sub-tree disagreeing.+ const targetQuantity =+ (material?.estimatedQuantity ?? 0) * madeRedirect.factor;+ const scrapQuantity = scrapAllowance(+ targetQuantity,+ itemFields.itemScrapPercentage+ );+ const totalWithScrap = targetQuantity + scrapQuantity;++ await trx+ .updateTable("jobMaterial")+ .set({+ ...itemFields,+ quantity: (material?.quantity ?? 0) * madeRedirect.factor,+ estimatedQuantity: targetQuantity,+ scrapQuantity,+ substitutedFromItemId: child.data.itemId,+ substitutionFactor: madeRedirect.factor+ })+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .execute();++ const successorTree = await getMethodTree(trx, successorMakeMethod.id);+ const successorRoot = successorTree.data?.[0];+ if (successorRoot) {+ // The SAME total the row above was written with — not the predecessor's,+ // rescaled. `|| 1` mirrors the unswapped path's fallback exactly; the old+ // `(childTotalForCascade || 1) * factor` yielded `factor` for a zero total+ // where the unswapped path yields 1.+ await traverseMethod(successorRoot, newMakeMethodId, totalWithScrap || 1);+ }+ return true;+ }++ async function settleConsumeFirstLines(opts: {+ trx: Transaction<KyselyDatabase>;+ companyId: string;+ jobId: string;+ jobMaterialIds: string[];+ locationId: string | null | undefined;+ asOfDate: string;+ }) {+ const { trx, companyId, jobId, jobMaterialIds, locationId, asOfDate } = opts;+ if (!locationId || jobMaterialIds.length === 0) return;++ const rules = await trx+ .selectFrom("itemSupersession")+ .select([+ "itemId",+ "successorItemId",+ "successorEffectivityDate",+ "conversionFactor"+ ])+ .where("companyId", "=", companyId)+ .where("supersessionMode", "=", "Consume First")+ .where("successorItemId", "is not", null)+ .orderBy("itemId")+ .execute();+ const consumeFirstRules = buildConsumeFirstRules(rules, asOfDate);+ const { successorByPredecessor, predecessorsBySuccessor } = consumeFirstRules;+ if (successorByPredecessor.size === 0) return;++ const materials = await trx+ .selectFrom("jobMaterial")+ .select([+ "id",+ "itemId",+ "quantity",+ "estimatedQuantity",+ "scrapQuantity",+ "substitutedFromItemId",+ "substitutionFactor"+ ])+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .where("id", "in", jobMaterialIds)+ .where("methodType", "!=", "Make to Order")+ .where((eb) =>+ eb.or([eb("quantityIssued", "is", null), eb("quantityIssued", "<=", 0)])+ )+ .where("itemId", "in", [+ ...new Set([+ ...successorByPredecessor.keys(),+ ...predecessorsBySuccessor.keys()+ ])+ ])+ .execute();+ if (materials.length === 0) return;++ const predecessorIds = new Set<string>();+ for (const m of materials) {+ for (const id of consumeFirstStockItems(m, consumeFirstRules)) {+ predecessorIds.add(id);+ }+ }+ const stock = await trx+ .selectFrom("itemStockQuantities")+ .select(["itemId", "quantityOnHand"])+ .where("companyId", "=", companyId)+ .where("locationId", "=", locationId)+ .where("itemId", "in", [...predecessorIds])+ .execute();+ const onHandByItem = new Map<string, number>();+ for (const row of stock) {+ onHandByItem.set(+ row.itemId,+ (onHandByItem.get(row.itemId) ?? 0) + Number(row.quantityOnHand ?? 0)+ );+ }++ const swapLine = async (+ m: (typeof materials)[number],+ toItemId: string,+ factor: number,+ provenance: {+ substitutedFromItemId: string | null;+ substitutionFactor: number | null;+ }+ ) => {+ const fields = await itemDerivedJobMaterialFields({+ trx,+ companyId,+ itemId: toItemId,+ locationId+ });+ if (!fields) return;+ const quantities = pullBackQuantities(+ m,+ factor,+ fields.itemScrapPercentage+ );+ await trx+ .updateTable("jobMaterial")+ .set({+ ...fields,+ ...quantities,+ ...provenance+ })+ .where("id", "=", m.id)+ .where("companyId", "=", companyId)+ .execute();+ };++ materials.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ for (const m of materials) {+ const settlement = settleConsumeFirstLine(+ m,+ consumeFirstRules,+ onHandByItem+ );+ reserveConsumeFirstStock(m, settlement, consumeFirstRules, onHandByItem);+ if (!settlement) continue;+ await swapLine(+ m,+ settlement.toItemId,+ settlement.factor,+ settlement.kind === "revert"+ ? { substitutedFromItemId: null, substitutionFactor: null }+ : {+ substitutedFromItemId: m.itemId,+ substitutionFactor: settlement.factor+ }+ );+ }+ }++ // Shared by every *-ToJob path. For a Buy/Pick job-material row whose item has an+ // effective supersession successor (per the redirect map), returns the successor's+ // item fields so the row points at the right part with consistent tracking / type /+ // cost. Make-to-Order lines are never swapped here (the successor's own sub-method+ // would need re-exploding — a later layer), so the caller passes only Buy/Pick rows+ // or this returns null for them. The line's unit of measure and methodType are+ // intentionally preserved — the conversion factor translates the quantity.+ async function resolveJobMaterialSupersession(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ redirect: Map<string, { to: string; factor: number }>,+ line: { itemId: string; methodType: string }+ ): Promise<{+ itemId: string;+ factor: number;+ substitutedFromItemId: string;+ itemType: string;+ description: string;+ unitCost: number | null;+ requiresSerialTracking: boolean;+ requiresBatchTracking: boolean;+ } | null> {+ if (line.methodType === "Make to Order") return null;+ const r = redirect.get(line.itemId);+ if (!r) return null;+ const successor = await readItemWithCost(db, r.to, companyId);+ if (!successor) return null;+ return {+ itemId: r.to,+ factor: r.factor,+ substitutedFromItemId: line.itemId,+ itemType: successor.type,+ description: successor.name,+ unitCost: successor.itemCost?.[0]?.unitCost ?? null,+ requiresSerialTracking: successor.itemTrackingType === "Serial",+ requiresBatchTracking: successor.itemTrackingType === "Batch"+ };+ }++ function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {+ function traverseAndRenameIds(node: MethodTreeItem) {+ const clone = structuredClone(node);+ clone.id = nanoid(20);+ clone.children = clone.children.map((n) => traverseAndRenameIds(n));+ return clone;+ }++ const rootItems: MethodTreeItem[] = [];+ const lookup: { [id: string]: MethodTreeItem } = {};++ for (const item of items) {+ const itemId = item.methodMaterialId;+ const parentId = item.parentMaterialId;++ if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {+ // @ts-ignore - we add data on the next line+ lookup[itemId] = { id: itemId, children: [] };+ }++ lookup[itemId]!["data"] = item;++ const treeItem = lookup[itemId]!;++ if (parentId === null || parentId === undefined) {+ rootItems.push(treeItem);+ } else {+ if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {+ // @ts-ignore - we don't add data here+ lookup[parentId] = { id: parentId, children: [] };+ }++ lookup[parentId]!["children"].push(treeItem);+ }+ }++ return rootItems.map((item) => traverseAndRenameIds(item));+ }++ type Tables = Database["public"]["Tables"];++ type Views = Database["public"]["Views"];++ /** A method operation with its tools (and their step links), parameters and steps. */+ type MethodOperationRow = Tables["methodOperation"]["Row"] & {+ methodOperationTool: (Tables["methodOperationTool"]["Row"] & {+ methodOperationToolStep: Tables["methodOperationToolStep"]["Row"][];+ })[];+ methodOperationParameter: Tables["methodOperationParameter"]["Row"][];+ methodOperationStep: Tables["methodOperationStep"]["Row"][];+ };++ // makeMethodId is globally unique (makeMethod's PK is "id" alone), so the+ // companyId filter cannot drop a legitimate row — it only closes a+ // cross-tenant read.+ function readMethodOperations(+ db: Kysely<KyselyDatabase>,+ makeMethodIds: string[],+ companyId: string+ ) {+ return selectRows<"methodOperation", MethodOperationRow>(+ db,+ "methodOperation",+ { makeMethodId: makeMethodIds, companyId },+ {+ orderBy: ["order", "id"],+ embed: {+ methodOperationTool: {+ table: "methodOperationTool",+ on: "operationId",+ embed: {+ methodOperationToolStep: {+ table: "methodOperationToolStep",+ on: "methodOperationToolId"+ }+ }+ },+ methodOperationParameter: {+ table: "methodOperationParameter",+ on: "operationId"+ },+ methodOperationStep: { table: "methodOperationStep", on: "operationId" }+ }+ }+ );+ }++ /** A quote operation with its tools, parameters and steps. */+ type QuoteOperationWithDetails = Tables["quoteOperation"]["Row"] & {+ quoteOperationTool: Tables["quoteOperationTool"]["Row"][];+ quoteOperationParameter: Tables["quoteOperationParameter"]["Row"][];+ quoteOperationStep: Tables["quoteOperationStep"]["Row"][];+ };++ const quoteOperationDetails = {+ quoteOperationTool: { table: "quoteOperationTool", on: "operationId" },+ quoteOperationParameter: {+ table: "quoteOperationParameter",+ on: "operationId"+ },+ quoteOperationStep: { table: "quoteOperationStep", on: "operationId" }+ } as const;++ /** Every item a method tree names, plus the successor each would be swapped for. */+ function treeItemIds(+ root: { data: { itemId: string }; children: unknown[] },+ redirect?: Map<string, { to: string }>+ ): string[] {+ const ids: string[] = [];+ const seen = new Set<unknown>();+ const walk = (node: { data: { itemId: string }; children: unknown[] }) => {+ if (seen.has(node)) return;+ seen.add(node);+ ids.push(node.data.itemId);+ const successor = redirect?.get(node.data.itemId)?.to;+ if (successor) ids.push(successor);+ for (const child of node.children) walk(child as typeof node);+ };+ walk(root);+ return ids;+ }++ /**+ * An item's scrap percentage and its default bin at one location, read for+ * many items at once and remembered for the request. The copy flows asked for+ * these one material at a time inside their transaction — three statements+ * per material, 110 of the 164 a 40-line job copy sent.+ *+ * `load` the tree's items up front; an item it did not cover (a successor a+ * swap lands on) is read when first asked for, so nothing resolves to a+ * silent 0 or a missing bin.+ */+ function createItemDefaults(+ companyId: string,+ locationId: string | null | undefined+ ) {+ const scrapByItemId = new Map<string, number>();+ const binByItemId = new Map<string, string>();+ const loaded = new Set<string>();+ let fullestBinAllowed: boolean | undefined;++ async function load(+ reader: Kysely<KyselyDatabase>,+ itemIds: (string | null | undefined)[]+ ) {+ const missing = [...new Set(itemIds)].filter(+ (id): id is string => !!id && !loaded.has(id)+ );+ if (missing.length === 0) return;++ const replenishments = await reader+ .selectFrom("itemReplenishment")+ .select(["itemId", "scrapPercentage"])+ .where("itemId", "in", missing)+ .where("companyId", "=", companyId)+ .execute();+ for (const row of replenishments) {+ scrapByItemId.set(row.itemId, Number(row.scrapPercentage ?? 0));+ }++ // The pick method's default bin wins, else the bin holding the most (never+ // under strict backflush).+ if (locationId) {+ fullestBinAllowed ??= !(+ await getStrictBackflushSettings(reader, companyId, locationId)+ ).strict;+ const ledgerTotals = !fullestBinAllowed+ ? []+ : await reader+ .selectFrom("itemLedger")+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("storageUnitId", "is not", null)+ .groupBy(["itemId", "storageUnitId"])+ .select([+ "itemId",+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity")+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .orderBy("itemId")+ .orderBy("totalQuantity", "desc")+ .orderBy("storageUnitId")+ .execute();+ for (const row of ledgerTotals) {+ // Ordered by quantity: the first row for an item is its fullest bin.+ if (row.storageUnitId && !binByItemId.has(row.itemId)) {+ binByItemId.set(row.itemId, row.storageUnitId);+ }+ }++ const pickMethods = await reader+ .selectFrom("pickMethod")+ .select(["itemId", "defaultStorageUnitId"])+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("defaultStorageUnitId", "is not", null)+ .execute();+ for (const pickMethod of pickMethods) {+ if (pickMethod.defaultStorageUnitId) {+ binByItemId.set(pickMethod.itemId, pickMethod.defaultStorageUnitId);+ }+ }+ }++ // Marked only after the rows land, so an item never reads as "loaded, no+ // row" while its read is still in flight.+ for (const id of missing) loaded.add(id);+ }++ return {+ load,+ async scrapPercentage(reader: Kysely<KyselyDatabase>, itemId: string) {+ await load(reader, [itemId]);+ return scrapByItemId.get(itemId) ?? 0;+ },+ /** An explicit bin on the line wins over the item's default. */+ async storageUnitId(+ reader: Kysely<KyselyDatabase>,+ itemId: string,+ lineStorageUnitId?: string | null+ ) {+ if (lineStorageUnitId) return lineStorageUnitId;+ await load(reader, [itemId]);+ return binByItemId.get(itemId);+ }+ };+ }++ /** An item with its cost row, as the job-material mappers read it. */+ function readItemWithCost(+ db: Kysely<KyselyDatabase>,+ itemId: string,+ companyId: string+ ) {+ return selectRow<+ "item",+ Tables["item"]["Row"] & { itemCost: Tables["itemCost"]["Row"][] }+ >(+ db,+ "item",+ { id: itemId, companyId },+ { embed: { itemCost: { table: "itemCost", on: "itemId" } } }+ );+ }++ function getFieldKey(field: string, id: string) {+ return `${field}:${id}`;+ }++ type ProcedureForJob = {+ content: unknown;+ steps: Record<string, unknown>[];+ parameters: Record<string, unknown>[];+ };++ // One read per procedure per transaction, however many operations use it.+ const procedureCacheByTransaction = new WeakMap<+ object,+ Map<string, Promise<ProcedureForJob | undefined>>+ >();++ function readProcedureForJob(+ trx: Transaction<KyselyDatabase>,+ procedureId: string,+ companyId: string+ ) {+ let cache = procedureCacheByTransaction.get(trx);+ if (!cache) {+ cache = new Map();+ procedureCacheByTransaction.set(trx, cache);+ }+ let procedure = cache.get(procedureId);+ if (!procedure) {+ procedure = sql<ProcedureForJob>`+ SELECT p."content",+ (SELECT coalesce(jsonb_agg(to_jsonb(s)), '[]'::jsonb)+ FROM "procedureStep" s WHERE s."procedureId" = p."id") AS "steps",+ (SELECT coalesce(jsonb_agg(to_jsonb(pp)), '[]'::jsonb)+ FROM "procedureParameter" pp WHERE pp."procedureId" = p."id") AS "parameters"+ FROM "procedure" p+ WHERE p."id" = ${procedureId} AND p."companyId" = ${companyId}+ `+ .execute(trx)+ .then((result) => result.rows[0]);+ cache.set(procedureId, procedure);+ }+ return procedure;+ }++ async function insertProcedureDataForJobOperation(+ trx: Transaction<KyselyDatabase>,+ args: {+ operationId: string;+ procedureId: string;+ companyId: string;+ userId: string;+ }+ ) {+ const { operationId, procedureId, companyId, userId } = args;+ const procedure = await readProcedureForJob(trx, procedureId, companyId);+ if (!procedure) return;++ const copy = (row: Record<string, unknown>) => {+ const {+ id: _id,+ procedureId: _procedureId,+ createdAt: _createdAt,+ ...rest+ } = row;+ return { ...rest, operationId, companyId, createdBy: userId };+ };+ const steps = procedure.steps.map((step) => ({+ ...copy(step),+ description: toTiptapDoc(step.description as never)+ }));+ const parameters = procedure.parameters.map(copy);++ // The steps, parameters and work instruction go in one statement: each+ // data-modifying CTE runs once, whether or not the outer UPDATE reads it.+ let write: QueryCreator<KyselyDatabase> = trx;+ if (steps.length > 0) {+ write = write.with("steps", (db) =>+ db.insertInto("jobOperationStep").values(steps as never)+ ) as unknown as QueryCreator<KyselyDatabase>;+ }+ if (parameters.length > 0) {+ write = write.with("parameters", (db) =>+ db.insertInto("jobOperationParameter").values(parameters as never)+ ) as unknown as QueryCreator<KyselyDatabase>;+ }+ await write+ .updateTable("jobOperation")+ .set({ workInstruction: toJson(procedure.content ?? {}) })+ .where("id", "=", operationId)+ .where("companyId", "=", companyId)+ .execute();+ }++ type TreeOperation = Tables["methodOperation"]["Row"] & {+ methodOperationTool: Tables["methodOperationTool"]["Row"][];+ methodOperationParameter: Tables["methodOperationParameter"]["Row"][];+ methodOperationStep: Tables["methodOperationStep"]["Row"][];+ };++ /** Every node's method operations, read in one query instead of one per node. */+ async function readOperationsForTree(+ trx: Transaction<KyselyDatabase>,+ root: MethodTreeItem+ ) {+ const makeMethodIds = new Set<string>();+ const walk = (node: MethodTreeItem) => {+ if (node.data.materialMakeMethodId)+ makeMethodIds.add(node.data.materialMakeMethodId);+ node.children.forEach(walk);+ };+ walk(root);+ const operations = await many<"methodOperation", TreeOperation>(+ trx,+ "methodOperation",+ { makeMethodId: [...makeMethodIds] },+ {+ embed: {+ methodOperationTool: {+ table: "methodOperationTool",+ on: "operationId"+ },+ methodOperationParameter: {+ table: "methodOperationParameter",+ on: "operationId"+ },+ methodOperationStep: { table: "methodOperationStep", on: "operationId" }+ }+ }+ );+ const byMakeMethodId = new Map<string, TreeOperation[]>();+ for (const operation of operations.data) {+ const list = byMakeMethodId.get(operation.makeMethodId);+ if (list) list.push(operation);+ else byMakeMethodId.set(operation.makeMethodId, [operation]);+ }+ return byMakeMethodId;+ }++ async function insertDeferredJobMaterials(+ trx: Transaction<KyselyDatabase>,+ materials: Database["public"]["Tables"]["jobMaterial"]["Insert"][],+ steps: Database["public"]["Tables"]["jobMaterialStep"]["Insert"][]+ ) {+ // Chunked: a whole tree in one statement can pass Postgres' 65535 bind+ // parameters.+ for (const chunk of chunked(materials)) {+ await trx.insertInto("jobMaterial").values(chunk).execute();+ }+ for (const chunk of chunked(steps)) {+ await trx.insertInto("jobMaterialStep").values(chunk).execute();+ }+ }++ /**+ * Gives the make-method rows that the jobMaterial / quoteMaterial insert+ * trigger created their planned ids, for every made material of an insert in+ * ONE statement.+ */+ async function renameMakeMethods(+ trx: Transaction<KyselyDatabase>,+ args: {+ table: "jobMakeMethod" | "quoteMakeMethod";+ companyId: string;+ /** Narrows the match to one job or quote line, as the loops this replaced did. */+ scope?: { column: "jobId" | "quoteLineId"; value: string };+ /** Left unchanged where undefined, as `.set()` would. */+ rows: {+ parentMaterialId: string;+ id: string;+ quantityPerParent?: number | null;+ }[];+ }+ ) {+ const { table, companyId, scope } = args;+ for (const rows of chunked(args.rows)) {+ await renameMakeMethodChunk(trx, { table, companyId, scope, rows });+ }+ }++ async function renameMakeMethodChunk(+ trx: Transaction<KyselyDatabase>,+ args: Parameters<typeof renameMakeMethods>[1]+ ) {+ const { table, companyId, scope, rows } = args;+ const values = sql.join(+ rows.map(+ (row) =>+ sql`(${row.parentMaterialId}::text, ${row.id}::text, ${row.quantityPerParent ?? null}::numeric, ${row.quantityPerParent !== undefined}::boolean)`+ )+ );+ await sql`+ UPDATE ${sql.table(table)} AS t+ SET "id" = v."id",+ "quantityPerParent" = CASE WHEN v."setQuantity" THEN v."quantityPerParent" ELSE t."quantityPerParent" END+ FROM (VALUES ${values}) AS v("parentMaterialId", "id", "quantityPerParent", "setQuantity")+ WHERE t."parentMaterialId" = v."parentMaterialId"+ AND t."companyId" = ${companyId}+ ${scope ? sql`AND t.${sql.ref(scope.column)} = ${scope.value}` : sql``}+ `.execute(trx);+ }++ // Assembly analog of insertProcedureDataForJobOperation: an Assembly operation+ // inherits its steps from the linked assembly instruction at job-creation time+ // (the method/quote only carry the pointer). Mirrors the payload of+ // syncAssemblyInstructionToOperation (production.service.ts) — including the+ // assemblyInstructionStepId provenance marker, so the job-side re-sync+ // reconciles these rows instead of duplicating them — and attaches the+ // instruction's 3D model as a model slide on every step.+ // Material ↔ step links are flushed separately by+ // linkAssemblyStepMaterialsForJobOperations AFTER the direction's jobMaterial+ // rows exist (operations are inserted before materials in every direction).+ async function insertAssemblyDataForJobOperation(+ trx: Transaction<KyselyDatabase>,+ args: {+ operationId: string;+ assemblyInstructionId: string;+ companyId: string;+ userId: string;+ }+ ) {+ const { operationId, assemblyInstructionId, companyId, userId } = args;+ const instruction = await selectRow<+ "assemblyInstruction",+ Tables["assemblyInstruction"]["Row"] & {+ assemblyInstructionStep: Tables["assemblyInstructionStep"]["Row"][];+ }+ >(+ trx,+ "assemblyInstruction",+ { id: assemblyInstructionId, companyId },+ {+ embed: {+ assemblyInstructionStep: {+ table: "assemblyInstructionStep",+ on: "assemblyInstructionId"+ }+ }+ }+ );++ if (!instruction) return new Set<string>();++ // A sub-assembly (header) row is not a build action, so it never becomes a+ // job step; its member steps are copied in play order like any other.+ const sourceSteps = (instruction.assemblyInstructionStep ?? [])+ .filter((step) => !step.isSubAssembly)+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));+ if (sourceSteps.length === 0) return new Set<string>();++ const sourceStepIds = sourceSteps.map((step) => step.id);+ const sourceSlides = await selectRows(+ trx,+ "assemblyInstructionStepSlide",+ { stepId: sourceStepIds, companyId },+ { orderBy: ["sortOrder"] }+ );+ const sourceTools = await selectRows(trx, "assemblyInstructionStepTool", {+ stepId: sourceStepIds,+ companyId+ });+ const slidesByStep = new Map<string, typeof sourceSlides>();+ for (const slide of sourceSlides) {+ const list = slidesByStep.get(slide.stepId) ?? [];+ list.push(slide);+ slidesByStep.set(slide.stepId, list);+ }+ const toolsByStep = new Map<string, { itemId: string; quantity: number }[]>();+ for (const tool of sourceTools) {+ const list = toolsByStep.get(tool.stepId) ?? [];+ list.push({ itemId: tool.itemId, quantity: tool.quantity ?? 1 });+ toolsByStep.set(tool.stepId, list);+ }++ // The operation's own steps (its procedure's, inserted before this) number+ // from 1 as well: the instruction's steps follow them, or the two interleave.+ const ownSteps = await trx+ .selectFrom("jobOperationStep")+ .select((eb) => eb.fn.max("sortOrder").as("lastSortOrder"))+ .where("operationId", "=", operationId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const firstSortOrder = Number(ownSteps?.lastSortOrder ?? 0) + 1;++ // Correlate inserted job steps back to their source steps via the provenance+ // column, not row order.+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ sourceSteps.map((source, index) => ({+ operationId,+ name: source.title || `Step ${index + 1}`,+ type: source.type ?? "Task",+ description: toTiptapDoc(source.description ?? source.instructionText),+ required: source.required ?? false,+ unitOfMeasureCode: source.unitOfMeasureCode,+ minValue: source.minValue,+ maxValue: source.maxValue,+ listValues: source.listValues,+ fileTypes: source.fileTypes,+ sortOrder: firstSortOrder + index,+ assemblyInstructionStepId: source.id,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id", "assemblyInstructionStepId"])+ .execute();+ const targetIdBySource = new Map(+ insertedSteps.map((step) => [step.assemblyInstructionStepId, step.id])+ );++ // Per-step slides: the instruction's 3D model leads as a model slide,+ // followed by the step's authored slides (image XOR model, with captions,+ // sizes, and annotation pins).+ const slideRows: {+ stepId: string;+ imagePath: string | null;+ modelUploadId: string | null;+ caption: string | null;+ sortOrder: number;+ size: string;+ annotations: string;+ companyId: string;+ createdBy: string;+ }[] = [];+ for (const source of sourceSteps) {+ const targetStepId = targetIdBySource.get(source.id);+ if (!targetStepId) continue;+ const authored = slidesByStep.get(source.id) ?? [];+ const modelUploadId = instruction.modelUploadId;+ if (+ modelUploadId &&+ !authored.some((slide) => slide.modelUploadId === modelUploadId)+ ) {+ slideRows.push({+ stepId: targetStepId,+ imagePath: null,+ modelUploadId,+ caption: null,+ sortOrder: 0,+ size: "medium",+ annotations: JSON.stringify([]),+ companyId,+ createdBy: userId+ });+ }+ for (const slide of authored) {+ slideRows.push({+ stepId: targetStepId,+ imagePath: slide.imagePath,+ modelUploadId: slide.modelUploadId,+ caption: slide.caption,+ sortOrder: slide.sortOrder ?? 1,+ size: slide.size ?? "medium",+ annotations: JSON.stringify(slide.annotations ?? []),+ companyId,+ createdBy: userId+ });+ }+ }+ if (slideRows.length > 0) {+ await trx.insertInto("jobOperationStepSlide").values(slideRows).execute();+ }++ // Per-step tools: one jobOperationTool row per distinct tool item (quantity =+ // max across steps) plus the tool ↔ step scope links.+ const maxQuantityByItemId = new Map<string, number>();+ for (const tools of toolsByStep.values()) {+ for (const tool of tools) {+ maxQuantityByItemId.set(+ tool.itemId,+ Math.max(maxQuantityByItemId.get(tool.itemId) ?? 0, tool.quantity)+ );+ }+ }+ if (maxQuantityByItemId.size > 0) {+ // The operation may already carry rows for these tools (the quote → job+ // direction copies quoteOperationTool BEFORE this runs). Link steps to the+ // existing row instead of inserting a duplicate the MES would list twice.+ const existingTools = await trx+ .selectFrom("jobOperationTool")+ .select(["id", "toolId"])+ .where("operationId", "=", operationId)+ .execute();+ const toolRowIdByItemId = new Map(+ existingTools.map((tool) => [tool.toolId, tool.id])+ );+ const missingTools = [...maxQuantityByItemId.entries()].filter(+ ([itemId]) => !toolRowIdByItemId.has(itemId)+ );+ if (missingTools.length > 0) {+ const insertedTools = await trx+ .insertInto("jobOperationTool")+ .values(+ missingTools.map(([itemId, quantity]) => ({+ operationId,+ toolId: itemId,+ quantity,+ companyId,+ createdBy: userId+ }))+ )+ .returning(["id", "toolId"])+ .execute();+ for (const tool of insertedTools) {+ toolRowIdByItemId.set(tool.toolId, tool.id);+ }+ }+ const toolLinkRows: {+ jobOperationToolId: string;+ jobOperationStepId: string;+ }[] = [];+ for (const source of sourceSteps) {+ const targetStepId = targetIdBySource.get(source.id);+ if (!targetStepId) continue;+ for (const tool of toolsByStep.get(source.id) ?? []) {+ const jobOperationToolId = toolRowIdByItemId.get(tool.itemId);+ if (jobOperationToolId) {+ toolLinkRows.push({+ jobOperationToolId,+ jobOperationStepId: targetStepId+ });+ }+ }+ }+ if (toolLinkRows.length > 0) {+ await trx+ .insertInto("jobOperationToolStep")+ .values(toolLinkRows)+ .execute();+ }+ }+ // Tool ids the instruction accounts for — the method → job copy paths filter+ // methodOperationTool by this set so the same tool isn't inserted a second+ // time (unlinked, so the MES would show it on every step AND on its step).+ return new Set(maxQuantityByItemId.keys());+ }++ // Post-materials pass: link the assembly-materialized job steps to the job's+ // materials, resolving the instruction's per-step itemIds against the+ // operation's own make method (same resolution the app-side sync performs).+ // Must read jobOperation/jobOperationStep/jobMaterial through the TRANSACTION —+ // those rows are uncommitted at this point.+ async function linkAssemblyStepMaterialsForJobOperations(+ trx: Transaction<KyselyDatabase>,+ operations: Array<{ operationId: string; assemblyInstructionId: string }>,+ companyId: string+ ) {+ for (const { operationId } of operations) {+ const operation = await trx+ .selectFrom("jobOperation")+ .select(["jobMakeMethodId"])+ .where("id", "=", operationId)+ .executeTakeFirst();+ if (!operation?.jobMakeMethodId) continue;++ const steps = await trx+ .selectFrom("jobOperationStep")+ .select(["id", "assemblyInstructionStepId"])+ .where("operationId", "=", operationId)+ .where("assemblyInstructionStepId", "is not", null)+ .execute();+ if (steps.length === 0) continue;++ const sourceStepIds = steps.map(+ (step) => step.assemblyInstructionStepId as string+ );+ const stepMaterials = await trx+ .selectFrom("assemblyInstructionStepMaterial")+ .select(["stepId", "itemId", "quantity"])+ .where("stepId", "in", sourceStepIds)+ .where("companyId", "=", companyId)+ .execute();+ if (stepMaterials.length === 0) continue;++ const jobMaterials = await trx+ .selectFrom("jobMaterial")+ .select(["id", "itemId"])+ .where("jobMakeMethodId", "=", operation.jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();+ const materialIdByItemId = new Map(+ jobMaterials.map((material) => [material.itemId, material.id])+ );+ const jobStepBySourceStep = new Map(+ steps.map((step) => [step.assemblyInstructionStepId as string, step.id])+ );++ const linkRows = stepMaterials.flatMap((link) => {+ const jobOperationStepId = jobStepBySourceStep.get(link.stepId);+ const jobMaterialId = link.itemId+ ? materialIdByItemId.get(link.itemId)+ : undefined;+ return jobOperationStepId && jobMaterialId+ ? [+ {+ jobMaterialId,+ jobOperationStepId,+ quantity: link.quantity ?? null+ }+ ]+ : [];+ });++ if (linkRows.length > 0) {+ await trx+ .insertInto("jobMaterialStep")+ .values(linkRows)+ .onConflict((oc) => oc.doNothing())+ .execute();+ }+ }+ }++ async function hydrateConfiguration(+ db: Kysely<KyselyDatabase>,+ configuration: Record<string, unknown> | undefined,+ itemId: string | undefined | null,+ companyId: string+ ): Promise<Record<string, unknown> | undefined> {+ try {+ if (!configuration || !itemId || Object.keys(configuration).length === 0) {+ return configuration;+ }++ const materialParams = await db+ .selectFrom("configurationParameter")+ .select(["key"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("dataType", "=", "material")+ .execute();++ const materialKeys = new Set(materialParams.map((p) => p.key));++ if (materialKeys.size === 0) return configuration;++ const entries = Object.entries(configuration).filter(+ ([key, value]) =>+ materialKeys.has(key) && typeof value === "string" && value+ );++ if (entries.length === 0) return configuration;++ const itemIds = entries.map(([, value]) => value as string);++ // Get items that correspond to the item IDs+ const items = await db+ .selectFrom("item")+ .select(["id", "readableId"])+ .where("id", "in", itemIds)+ .where("companyId", "=", companyId)+ .execute();++ // Create map of itemId to readableId (which is the materialId)+ const itemIdToMaterialId = new Map(items.map((i) => [i.id, i.readableId]));++ const materialIds = items.map((i) => i.readableId);+ if (materialIds.length === 0) return configuration;++ // Get material details using the readableIds (which are the material IDs)+ const materials = await db+ .selectFrom("material")+ .select([+ "id",+ "materialFormId",+ "materialSubstanceId",+ "materialTypeId",+ "dimensionId",+ "finishId",+ "gradeId"+ ])+ .where("id", "in", materialIds)+ .where("companyId", "=", companyId)+ .execute();++ const materialsByMaterialId = new Map(materials.map((m) => [m.id, m]));++ const transformed: Record<string, unknown> = { ...configuration };++ for (const [key, value] of entries) {+ const itemId = value as string;+ const materialId = itemIdToMaterialId.get(itemId);++ if (materialId) {+ const material = materialsByMaterialId.get(materialId);+ if (material) {+ transformed[key] = {+ id: itemId,+ materialFormId: material.materialFormId ?? null,+ materialSubstanceId: material.materialSubstanceId ?? null,+ materialTypeId: material.materialTypeId ?? null,+ dimensionId: material.dimensionId ?? null,+ finishId: material.finishId ?? null,+ gradeId: material.gradeId ?? null+ };+ }+ }+ }++ return transformed;+ } catch (err) {+ getMethodLogger.error("configuration transform failed", {+ error: String((err as Error)?.stack ?? err)+ });+ return configuration;+ }+ }+ const rescheduleJobLogger = getLogger("server-functions", "reschedule");+ // Types+ type JobOperation = {+ id: string;+ jobId: string;+ workCenterId: string | null;+ status: string;+ priority: number | null;+ dueDate: string | null;+ startDate: string | null;+ setupTime: number | null;+ laborTime: number | null;+ machineTime: number | null;+ setupUnit: string | null;+ laborUnit: string | null;+ machineUnit: string | null;+ operationQuantity: number | null;+ };++ type JobOperationDependency = {+ operationId: string;+ dependsOnId: string;+ jobId: string;+ };++ type DependencyGraph = Map<+ string,+ {+ dependsOn: string[];+ requiredBy: string[];+ }+ >;++ type ScheduledOperation = JobOperation & {+ hasConflict: boolean;+ conflictReason: string | null;+ };++ type OperationWithJobInfo = {+ id: string;+ dueDate: string | null;+ priority: number | null;+ deadlineType: string | null;+ jobPriority: number | null;+ workCenterId: string | null;+ };++ // Helper: Get job with operations and dependencies+ async function getJobWithOperations(+ trx: Transaction<KyselyDatabase>,+ jobId: string+ ) {+ const job = await trx+ .selectFrom("job")+ .select(["id", "dueDate", "priority", "deadlineType"])+ .where("id", "=", jobId)+ .executeTakeFirstOrThrow();++ const operations = await trx+ .selectFrom("jobOperation")+ .selectAll()+ .where("jobId", "=", jobId)+ .where("status", "not in", ["Done", "Canceled"])+ .execute();++ const dependencies = await trx+ .selectFrom("jobOperationDependency")+ .selectAll()+ .where("jobId", "=", jobId)+ .execute();++ return { job, operations, dependencies };+ }++ // Helper: Build dependency graph+ function buildDependencyGraph(+ operations: JobOperation[],+ dependencies: JobOperationDependency[]+ ): DependencyGraph {+ const graph = new Map<+ string,+ {+ dependsOn: string[];+ requiredBy: string[];+ }+ >();++ // Initialize all operations+ for (const op of operations) {+ graph.set(op.id, { dependsOn: [], requiredBy: [] });+ }++ // Build edges+ for (const dep of dependencies) {+ const opNode = graph.get(dep.operationId);+ const depNode = graph.get(dep.dependsOnId);++ if (opNode) {+ opNode.dependsOn.push(dep.dependsOnId);+ }+ if (depNode) {+ depNode.requiredBy.push(dep.operationId);+ }+ }++ return graph;+ }++ // Helper: Topological sort+ function topologicalSort(+ operations: JobOperation[],+ graph: DependencyGraph,+ direction: "forward" | "reverse"+ ): JobOperation[] {+ const inDegree = new Map<string, number>();+ const queue: string[] = [];+ const result: JobOperation[] = [];++ // Calculate in-degrees+ for (const op of operations) {+ const deps =+ direction === "forward"+ ? graph.get(op.id)?.dependsOn || []+ : graph.get(op.id)?.requiredBy || [];+ inDegree.set(op.id, deps.length);+ if (deps.length === 0) queue.push(op.id);+ }++ // Process queue+ while (queue.length > 0) {+ const opId = queue.shift()!;+ const op = operations.find((o) => o.id === opId)!;+ result.push(op);++ const neighbors =+ direction === "forward"+ ? graph.get(opId)?.requiredBy || []+ : graph.get(opId)?.dependsOn || [];++ for (const neighborId of neighbors) {+ const degree = inDegree.get(neighborId)! - 1;+ inDegree.set(neighborId, degree);+ if (degree === 0) queue.push(neighborId);+ }+ }++ return result;+ }++ // Helper: Calculate operation duration in days+ function calculateOperationDuration(op: JobOperation): number {+ const quantity = op.operationQuantity || 1;++ // Calculate total hours+ let setupHours = 0;+ let laborHours = 0;+ let machineHours = 0;++ if (op.setupTime) {+ setupHours =+ op.setupUnit === "Hours/Piece" ? op.setupTime * quantity : op.setupTime;+ }++ if (op.laborTime) {+ laborHours =+ op.laborUnit === "Hours/Piece" ? op.laborTime * quantity : op.laborTime;+ }++ if (op.machineTime) {+ machineHours =+ op.machineUnit === "Hours/Piece"+ ? op.machineTime * quantity+ : op.machineTime;+ }++ // Total hours (setup + max of labor/machine since they can overlap)+ const totalHours = setupHours + Math.max(laborHours, machineHours);++ // Convert to days (assuming 8-hour workday)+ const days = totalHours / 8;++ // Round up to at least 1 day+ return Math.max(Math.ceil(days), 1);+ }++ // Helper: Backward schedule operations+ function backwardScheduleOperations(+ operations: JobOperation[],+ graph: DependencyGraph,+ jobDueDate: string | null+ ): ScheduledOperation[] {+ const scheduled = new Map<string, ScheduledOperation>();+ const today = new Date().toISOString().split("T")[0]!;++ // Default to today if no due date+ const finalDueDate = jobDueDate || today;++ // Topological sort (reverse: final ops first)+ const sorted = topologicalSort(operations, graph, "reverse");++ for (const op of sorted) {+ const deps = graph.get(op.id);+ if (!deps) continue;++ const totalDuration = calculateOperationDuration(op);++ // Calculate due date+ let dueDate: string;+ if (deps.requiredBy.length === 0) {+ // Leaf operation: use job due date+ dueDate = finalDueDate;+ } else {+ // Has dependents: must finish before earliest dependent starts+ const dependentStartDates = deps.requiredBy+ .map((depId) => scheduled.get(depId)?.startDate)+ .filter((date): date is string => date !== null && date !== undefined);++ if (dependentStartDates.length === 0) {+ dueDate = finalDueDate;+ } else {+ // Subtract 1 day buffer+ const minDate = new Date(+ Math.min(...dependentStartDates.map((d) => new Date(d).getTime()))+ );+ minDate.setDate(minDate.getDate() - 1);+ dueDate = minDate.toISOString().split("T")[0]!;+ }+ }++ // Calculate start date+ const dueDateObj = new Date(dueDate);+ dueDateObj.setDate(dueDateObj.getDate() - totalDuration);+ const startDate = dueDateObj.toISOString().split("T")[0]!;++ // Check for conflicts+ const hasConflict = startDate < today;+ const conflictReason = hasConflict+ ? `Operation must start on ${startDate} but current date is ${today}`+ : null;++ scheduled.set(op.id, {+ ...op,+ startDate,+ dueDate,+ hasConflict,+ conflictReason+ });+ }++ return Array.from(scheduled.values());+ }++ // Helper: Sort operations by priority criteria+ function sortOperationsByPriority(+ operations: OperationWithJobInfo[]+ ): OperationWithJobInfo[] {+ const deadlineOrder: Record<string, number> = {+ ASAP: 0,+ "Hard Deadline": 1,+ "Soft Deadline": 2,+ "No Deadline": 3+ };++ return operations.sort((a, b) => {+ // 1. Deadline type+ const aDeadline = a.deadlineType || "No Deadline";+ const bDeadline = b.deadlineType || "No Deadline";+ if (aDeadline !== bDeadline) {+ return deadlineOrder[aDeadline]! - deadlineOrder[bDeadline]!;+ }++ // 2. Due date (earliest first, nulls last)+ if (a.dueDate && b.dueDate) {+ const dateCompare =+ new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();+ if (dateCompare !== 0) return dateCompare;+ } else if (a.dueDate) {+ return -1;+ } else if (b.dueDate) {+ return 1;+ }++ // 3. Job priority+ const aPriority = a.jobPriority || 0;+ const bPriority = b.jobPriority || 0;+ return aPriority - bPriority;+ });+ }++ // Helper: Apply fractional priorities+ function applyFractionalPriorities(+ sorted: OperationWithJobInfo[]+ ): OperationWithJobInfo[] {+ return sorted.map((op, index) => {+ if (index === 0) {+ op.priority = 0;+ } else {+ const prevPriority = sorted[index - 1]!.priority || 0;+ op.priority = prevPriority + 1;+ }+ return op;+ });+ }++ // Helper: Recalculate priorities by work center+ async function recalculatePriorities(+ trx: Transaction<KyselyDatabase>,+ scheduledOps: ScheduledOperation[],+ workCenterIds: string[]+ ): Promise<ScheduledOperation[]> {+ const prioritizedOps = [...scheduledOps];++ for (const wcId of workCenterIds) {+ if (!wcId) continue;++ // Get ALL active operations at this work center (not just from current job)+ const allWcOps = await trx+ .selectFrom("jobOperation as jo")+ .innerJoin("job as j", "j.id", "jo.jobId")+ .select([+ "jo.id",+ "jo.dueDate",+ "jo.priority",+ "j.deadlineType",+ "j.priority as jobPriority",+ "jo.workCenterId"+ ])+ .where("jo.workCenterId", "=", wcId)+ .where("jo.status", "not in", ["Done", "Canceled"])+ .execute();++ // Merge with scheduled ops (use scheduled data if available)+ const mergedOps = allWcOps.map((wcOp) => {+ const scheduled = scheduledOps.find((s) => s.id === wcOp.id);+ if (scheduled) {+ return {+ id: scheduled.id,+ dueDate: scheduled.dueDate,+ priority: scheduled.priority,+ deadlineType: wcOp.deadlineType,+ jobPriority: wcOp.jobPriority,+ workCenterId: wcOp.workCenterId+ };+ }+ return wcOp;+ });++ // Sort by priority criteria+ const sorted = sortOperationsByPriority(mergedOps);++ // Apply fractional indexing+ const prioritized = applyFractionalPriorities(sorted);++ // Update prioritized ops+ for (const op of prioritized) {+ const idx = prioritizedOps.findIndex((p) => p.id === op.id);+ if (idx >= 0) {+ prioritizedOps[idx]!.priority = op.priority;+ }+ }+ }++ return prioritizedOps;+ }++ export const rescheduleJobPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof rescheduleInput>>;++ /**+ * Re-plans a job's operations: backward-schedules their dates from the job's due+ * date, flags conflicts, and recalculates priorities on the affected work centers.+ */+ export async function rescheduleJob(+ ctx: ServiceContext,+ raw: z.input<typeof rescheduleInput>+ ) {+ const { jobId } = rescheduleInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ const owned = await db+ .selectFrom("job")+ .select("id")+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!owned) throw new NotFoundError("Job not found");++ rescheduleJobLogger.info(`🔰 Starting reschedule for job ${jobId}`);++ const result = await db.transaction().execute(async (trx) => {+ // 1. Get job and all its operations with dependencies+ const { job, operations, dependencies } = await getJobWithOperations(+ trx,+ jobId+ );++ rescheduleJobLogger.info(+ `📊 Job has ${operations.length} operations, ${dependencies.length} dependencies`+ );++ // 2. Build dependency graph+ const graph = buildDependencyGraph(operations, dependencies);++ // 3. Backward schedule (calculate dates, flag conflicts)+ const scheduledOps = backwardScheduleOperations(+ operations,+ graph,+ job.dueDate+ );++ const conflicts = scheduledOps.filter((op) => op.hasConflict);+ rescheduleJobLogger.info(+ `⚠️ Detected ${conflicts.length} scheduling conflicts`+ );++ // 4. Get affected work centers+ const workCenterIds = [+ ...new Set(+ scheduledOps+ .map((op) => op.workCenterId)+ .filter((id): id is string => id !== null)+ )+ ];++ rescheduleJobLogger.info(+ `🏭 Affected work centers: ${workCenterIds.length}`+ );++ // 5. Recalculate priorities for each work center+ const prioritizedOps = await recalculatePriorities(+ trx,+ scheduledOps,+ workCenterIds+ );++ // 6. Batch update all operations+ for (const op of prioritizedOps) {+ await trx+ .updateTable("jobOperation")+ .set({+ startDate: op.startDate,+ dueDate: op.dueDate,+ priority: op.priority!,+ hasConflict: op.hasConflict,+ conflictReason: op.conflictReason,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", op.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ rescheduleJobLogger.info(`✅ Updated ${prioritizedOps.length} operations`);++ return {+ operationsUpdated: prioritizedOps.length,+ conflictsDetected: conflicts.length,+ workCentersAffected: workCenterIds.length+ };+ });++ return { success: true, ...result };+ }++ export const PRODUCTION_EVENT_POSTED_CONCURRENTLY_ERROR =+ "This production event was just posted by another process.";++ /** The net amount posted for one event so far, per account. */+ async function readPostedNet(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ eventReference: string+ ) {+ const lines = await db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .select([+ "journalLine.accountId",+ "journalLine.accountDefaultRole",+ (eb) => eb.fn.sum("journalLine.amount").as("amount")+ ])+ .where("journalLine.documentLineReference", "=", eventReference)+ .where("journalLine.companyId", "=", companyId)+ .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES])+ .groupBy(["journalLine.accountId", "journalLine.accountDefaultRole"])+ .execute();+ return lines.filter((line) => Math.abs(Number(line.amount)) >= 0.000001);+ }++ /** A posted net as one comparable value, independent of row order. */+ const postedNetKey = (lines: Awaited<ReturnType<typeof readPostedNet>>) =>+ lines+ .map(+ (line) =>+ `${line.accountId}|${line.accountDefaultRole ?? ""}|${round(Number(line.amount))}`+ )+ .sort()+ .join(";");++ export const postProductionEventPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof postProductionEventInput>>;++ /** Posts (or reverses) a production event's labor/machine and overhead cost to WIP. */+ export async function postProductionEvent(+ ctx: ServiceContext,+ raw: z.input<typeof postProductionEventInput>+ ): Promise<PostProductionEventResult> {+ const { productionEventId, reverse } = postProductionEventInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );++ if (companyRecord.error) throw new Error("Failed to fetch company");++ const [productionEvent, accountDefaults, dimensions] = await inOrder([+ () =>+ // `jobOperation!inner`: only an event that belongs to an operation.+ maybeSingle<+ "productionEvent",+ rows.Tables["productionEvent"]["Row"] & {+ jobOperation: Pick<+ rows.Tables["jobOperation"]["Row"],+ "jobId" | "processId"+ > | null;+ }+ >(+ db,+ "productionEvent",+ { id: productionEventId, companyId, jobOperationId: notNull },+ {+ embed: {+ jobOperation: {+ table: "jobOperation",+ via: "jobOperationId",+ columns: ["jobId", "processId"]+ }+ }+ }+ ),+ () => getDefaultPostingGroup(db, companyId),+ () =>+ companyRecord.data.companyGroupId+ ? many(+ db,+ "dimension",+ {+ companyGroupId: companyRecord.data.companyGroupId,+ active: true,+ entityType: [+ "ItemPostingGroup",+ "Item",+ "Location",+ "Employee",+ "WorkCenter",+ "Process"+ ]+ },+ { columns: ["id", "entityType"] }+ )+ : Promise.resolve({ data: null, error: null })+ ]);++ if (productionEvent.error)+ throw new Error("Failed to fetch production event");+ // Service-role client: a production event outside companyId is a 404.+ if (!productionEvent.data) {+ throw new NotFoundError("Production event not found");+ }+ if (accountDefaults?.error || !accountDefaults?.data) {+ throw new Error("Error getting account defaults");+ }++ // Every event with a cost posts a journal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to decide+ // whether to resolve a period, and again inside the transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ // After the cutover an empty absorption account refuses the posting, as+ // it always has. Before it, the line becomes a stand-in (see below).+ if (+ postingStatus === "Posted" &&+ !accountDefaults.data.laborAbsorptionAccount+ ) {+ throw new MissingAccountDefaultError("laborAbsorptionAccount");+ }++ const event = productionEvent.data;++ if (reverse && !event.postedToGL) {+ // Nothing was posted for this event, so there is nothing to reverse.+ return { success: true } as PostProductionEventResult;+ }++ if (!reverse && (!event.endTime || !event.duration || !event.workCenterId)) {+ // Leave postedToGL untouched so the event can still be posted later+ // (manually or by complete_job_to_inventory) once it's completable.+ const reason = !event.endTime+ ? "event has no end time"+ : !event.duration+ ? "event has no duration"+ : "event has no work center";+ return { success: false, reason } as PostProductionEventResult;+ }++ const jobId = (event.jobOperation as any).jobId as string;++ let cost = 0;+ let overheadCost = 0;+ if (!reverse) {+ const workCenter = await single(+ db,+ "workCenter",+ { id: event.workCenterId! },+ { columns: ["laborRate", "machineRate", "overheadRate"] }+ );++ if (workCenter.error)+ throw new Error(+ `Failed to fetch work center ${event.workCenterId}: ${workCenter.error.message}`+ );++ const durationHours = (event.duration ?? 0) / 3600;+ const rate =+ event.type === "Machine"+ ? Number(workCenter.data.machineRate ?? 0)+ : Number(workCenter.data.laborRate ?? 0);++ cost = durationHours * rate;+ overheadCost = durationHours * Number(workCenter.data.overheadRate ?? 0);++ if (+ postingStatus === "Posted" &&+ overheadCost > 0 &&+ !accountDefaults.data.overheadAbsorptionAccount+ ) {+ throw new MissingAccountDefaultError("overheadAbsorptionAccount");+ }+ }++ // Net amount already posted for this specific event, grouped by account.+ const eventReference = journalReference.to.productionEvent(productionEventId);++ // The enable superseded the journal of an event posted before the+ // cutover and opened the job's WIP with its cost, so the reads below see+ // nothing to reverse: a re-post would add the cost again and a reversal+ // would leave it. The re-post is dated today, after the cutover, so no+ // closed period refuses it.+ if (event.postedToGL) {+ const superseded = await db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .select("journalLine.id")+ .where("journalLine.documentLineReference", "=", eventReference)+ .where("journalLine.companyId", "=", companyId)+ .where("journal.status", "=", "Superseded")+ .limit(1)+ .executeTakeFirst();+ if (superseded) {+ throw new InvalidInputError(TIME_ENTRY_BEFORE_CUTOVER_ERROR);+ }+ }+ const reversalLines = event.postedToGL+ ? await readPostedNet(db, companyId, eventReference)+ : [];++ // Did this event's job post any production-event lines under the old+ // job-tagged scheme (documentLineReference = job:...)? Those can't be+ // attributed to one event, so editing/reversing a posted event that has no+ // per-event lines can't be done safely — it needs a manual journal entry.+ // This is rate-independent: unlike recomputing cost, it still recognizes a+ // zero-cost posted event (which posted nothing) as safe to delete even+ // after the work center's rate later changes.+ const hasOldSchemePostings =+ event.postedToGL && reversalLines.length === 0+ ? Number(+ (+ await db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .select((eb) => eb.fn.countAll().as("count"))+ .where("journalLine.documentType", "=", "Production Event")+ .where("journalLine.documentId", "=", jobId)+ .where(+ "journalLine.documentLineReference",+ "=",+ journalReference.to.job(jobId)+ )+ .where("journalLine.companyId", "=", companyId)+ .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES])+ .executeTakeFirst()+ )?.count ?? 0+ ) > 0+ : false;++ // Block only when the event posted amounts under the old scheme that we+ // can't attribute/reverse. A zero-cost posted event posted nothing, so+ // there's nothing to reverse and it's safe to delete.+ if (event.postedToGL && reversalLines.length === 0 && hasOldSchemePostings) {+ return {+ success: false,+ reason:+ "event was posted before per-event journal references; adjust with a manual journal entry"+ } as PostProductionEventResult;+ }++ if (cost <= 0 && overheadCost <= 0 && reversalLines.length === 0) {+ // Nothing to post and nothing to reverse. On a reversal this clears the+ // flag so the event can be deleted; on a post it marks it done.+ await updateRows(+ db,+ "productionEvent",+ { postedToGL: !reverse },+ { id: productionEventId, companyId }+ );+ return { success: true } as PostProductionEventResult;+ }++ const dimensionMap = new Map<string, string>();+ if (dimensions?.data) {+ for (const dim of dimensions.data) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ }++ const job = await single(+ db,+ "job",+ { id: jobId },+ { columns: ["itemId", "locationId", "jobId"] }+ );++ if (job.error) throw new Error("Failed to fetch job");++ const finishedItemCost = job.data.itemId+ ? await single(+ db,+ "itemCost",+ { itemId: job.data.itemId, companyId },+ { columns: ["itemPostingGroupId"] }+ )+ : null;++ const journalLineReference = nanoid();++ // Resolved only for a line that is built: after the cutover an empty+ // default has already refused the posting above.+ const laborAbsorption =+ !reverse && cost > 0+ ? resolveDefaultAccount(+ accountDefaults.data,+ "laborAbsorptionAccount",+ postingStatus+ )+ : null;+ const overheadAbsorption =+ !reverse && overheadCost > 0+ ? resolveDefaultAccount(+ accountDefaults.data,+ "overheadAbsorptionAccount",+ postingStatus+ )+ : null;++ const journalLineInserts = [+ // Reposting an edited event: first negate the net previously posted for+ // this event per account, then post the new amount.+ ...reversalLines.map((line) => ({+ accountId: line.accountId,+ accountDefaultRole: line.accountDefaultRole,+ description: "Production Event Reversal",+ amount: round(-Number(line.amount)),+ quantity: 1,+ documentType: "Production Event" as const,+ documentId: jobId,+ documentLineReference: eventReference,+ journalLineReference,+ companyId+ })),+ ...(laborAbsorption+ ? [+ {+ accountId: accountDefaults.data.workInProgressAccount,+ accountDefaultRole: null,+ description: "WIP Account",+ amount: round(debit("asset", cost)),+ quantity: 1,+ documentType: "Production Event" as const,+ documentId: jobId,+ documentLineReference: eventReference,+ journalLineReference,+ companyId+ },+ {+ accountId: laborAbsorption.accountId,+ accountDefaultRole: laborAbsorption.accountDefaultRole,+ description: "Labor/Machine Absorption",+ amount: round(credit("expense", cost)),+ quantity: 1,+ documentType: "Production Event" as const,+ documentId: jobId,+ documentLineReference: eventReference,+ journalLineReference,+ companyId+ }+ ]+ : []),+ ...(overheadAbsorption+ ? [+ {+ accountId: accountDefaults.data.workInProgressAccount,+ accountDefaultRole: null,+ description: "WIP Account (Overhead)",+ amount: round(debit("asset", overheadCost)),+ quantity: 1,+ documentType: "Production Event" as const,+ documentId: jobId,+ documentLineReference: eventReference,+ journalLineReference,+ companyId+ },+ {+ accountId: overheadAbsorption.accountId,+ accountDefaultRole: overheadAbsorption.accountDefaultRole,+ description: "Overhead Absorption",+ amount: round(credit("expense", overheadCost)),+ quantity: 1,+ documentType: "Production Event" as const,+ documentId: jobId,+ documentLineReference: eventReference,+ journalLineReference,+ companyId+ }+ ]+ : [])+ ];++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ // Several callers post an event as it ends: a press, the OEE sync, an+ // operation finish, an edit's repost. Under the row lock, a second+ // caller that read the event before the first committed sees what the+ // first wrote and stops, instead of posting the cost or the adjustment+ // twice: the flag for a first post, the net already posted for a+ // repost (the flag stays true across reposts).+ const locked = await trx+ .selectFrom("productionEvent")+ .select("postedToGL")+ .where("id", "=", productionEventId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (+ !locked ||+ locked.postedToGL !== event.postedToGL ||+ (locked.postedToGL &&+ postedNetKey(await readPostedNet(trx, companyId, eventReference)) !==+ postedNetKey(reversalLines))+ ) {+ throw new ServerFnError(PRODUCTION_EVENT_POSTED_CONCURRENTLY_ERROR, 409);+ }++ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `${event.type} Time — Job ${job.data.jobId}${+ reverse+ ? " (Reversal)"+ : reversalLines.length > 0+ ? " (Adjustment)"+ : ""+ }`,+ postingDate: today,+ companyId,+ sourceType: "Production Event",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id+ }))+ )+ .returning(["id"])+ .execute();++ if (dimensionMap.size > 0) {+ const dimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ journalLineResults.forEach((jl) => {+ if (+ finishedItemCost?.data?.itemPostingGroupId &&+ dimensionMap.has("ItemPostingGroup")+ ) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: finishedItemCost.data.itemPostingGroupId,+ companyId+ });+ }+ if (job.data.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: job.data.itemId,+ companyId+ });+ }+ if (job.data.locationId && dimensionMap.has("Location")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: job.data.locationId,+ companyId+ });+ }+ if (event.employeeId && dimensionMap.has("Employee")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Employee")!,+ valueId: event.employeeId,+ companyId+ });+ }+ if (event.workCenterId && dimensionMap.has("WorkCenter")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("WorkCenter")!,+ valueId: event.workCenterId,+ companyId+ });+ }+ const processId = (event.jobOperation as any)?.processId as+ | string+ | null;+ if (processId && dimensionMap.has("Process")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Process")!,+ valueId: processId,+ companyId+ });+ }+ });++ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }++ await trx+ .updateTable("productionEvent")+ .set({ postedToGL: !reverse })+ .where("id", "=", productionEventId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return { success: true };+ }+ const recalculateRequirementsLogger = getLogger(+ "server-functions",+ "recalculate"+ );+ export const recalculateRequirementsPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof recalculateInput>>;++ /** Re-derives a job's (or one make method's) material and operation quantities. */+ export async function recalculateRequirements(+ ctx: ServiceContext,+ raw: z.input<typeof recalculateInput>+ ) {+ const { type, id } = recalculateInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ recalculateRequirementsLogger.info({ type, id, companyId, userId });++ // Every read here goes over the direct connection: a PostgREST call costs+ // roughly ten times a statement, and this runs on every job save.+ switch (type) {+ case "jobMakeMethodRequirements": {+ const jobMakeMethodId = id;++ const jobMakeMethod = await db+ .selectFrom("jobMakeMethod")+ .select(["id", "jobId", "parentMaterialId"])+ .where("id", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ // A make method outside companyId is a 404.+ if (!jobMakeMethod) {+ throw new NotFoundError("Job make method not found");+ }++ let parentQuantity = 1;+ if (jobMakeMethod.parentMaterialId) {+ const jobMaterial = await db+ .selectFrom("jobMaterial")+ .select(["methodType", "estimatedQuantity", "quantity"])+ .where("id", "=", jobMakeMethod.parentMaterialId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (jobMaterial?.methodType !== "Make to Order") {+ recalculateRequirementsLogger.info(+ `Job material ${jobMakeMethod.parentMaterialId} is not a 'Make' type. Skipping recalculation.`+ );+ return { success: true };+ }++ parentQuantity = jobMaterial.estimatedQuantity ?? jobMaterial.quantity;+ } else {+ const job = await db+ .selectFrom("job")+ .select(["quantity"])+ .where("id", "=", jobMakeMethod.jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!job) {+ throw new Error("Failed to get job");+ }+ // Use job.quantity as the root's target quantity (not productionQuantity)+ // The item's scrap percentage will be applied within updateJobQuantities+ parentQuantity = job.quantity ?? 1;+ }++ const jobMethodTrees = await getJobMethodTree(+ db,+ jobMakeMethod.id,+ jobMakeMethod.parentMaterialId+ );++ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) {+ throw new NotFoundError("Method tree not found");+ }++ await db.transaction().execute(async (trx) => {+ await updateJobQuantities(trx, jobMethodTree, parentQuantity);+ });++ break;+ }+ case "jobRequirements": {+ const jobId = id;+ const [job, jobMakeMethods] = await inOrder([+ () =>+ db+ .selectFrom("job")+ .select(["quantity"])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst(),+ () =>+ db+ .selectFrom("jobMakeMethod")+ .select(["id"])+ .where("jobId", "=", jobId)+ .where("companyId", "=", companyId)+ .where("parentMaterialId", "is", null)+ .execute()+ ]);++ // A job outside companyId is a 404.+ if (!job) throw new NotFoundError("Job not found");++ // Exactly one root make method, as `.single()` required before.+ const jobMakeMethod = jobMakeMethods[0];+ if (!jobMakeMethod || jobMakeMethods.length > 1) {+ throw new Error(+ `Failed to get job make method: found ${jobMakeMethods.length}`+ );+ }++ const jobMethodTrees = await getJobMethodTree(db, jobMakeMethod.id);++ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) {+ throw new NotFoundError("Method tree not found");+ }++ await db.transaction().execute(async (trx) => {+ // Use job.quantity as the root's target quantity (not productionQuantity)+ // The item's scrap percentage will be applied within updateJobQuantities+ await updateJobQuantities(trx, jobMethodTree, job.quantity ?? 1);+ });++ break;+ }++ default:+ throw new Error(`Invalid type ${type}`);+ }++ return { success: true };+ }++ const updateJobQuantities = async (+ trx: Transaction<KyselyDatabase>,+ tree: JobMethodTreeItem,+ parentEstimatedQuantity: number = 1+ ) => {+ // The tree is already fully loaded, so compute every node's quantities in+ // memory (@carbon/database/job-quantities-engine, mirroring the mrp-engine pattern)+ // and write them set-based. The previous per-node recursion issued 2–4+ // statements per node on one transaction connection — O(tree) sequential+ // roundtrips, which on a large BOM exceeded the request timeout.+ const { nodes, cycleNodeIds: flattenCycles } = flattenJobQuantityTree(tree);++ const jobMaterials = await trx+ .selectFrom("jobMaterial")+ .select(["id", "itemScrapPercentage"])+ .where(+ "id",+ "in",+ nodes.map((n) => n.id)+ )+ .execute();+ const storedScrapById = new Map(+ jobMaterials.map((m) => [m.id, m.itemScrapPercentage])+ );++ const fallbackItemIds = [+ ...new Set(+ nodes+ .filter((n) => storedScrapById.get(n.id) == null)+ .map((n) => n.data.itemId)+ )+ ];+ const replenishmentScrapByItemId = new Map<string, number>();+ if (fallbackItemIds.length > 0) {+ const replenishments = await trx+ .selectFrom("itemReplenishment")+ .select(["itemId", "scrapPercentage"])+ .where("itemId", "in", fallbackItemIds)+ .execute();+ for (const row of replenishments) {+ replenishmentScrapByItemId.set(+ row.itemId,+ Number(row.scrapPercentage ?? 0)+ );+ }+ }++ const { computed, cycleNodeIds } = computeJobQuantities({+ tree,+ parentEstimatedQuantity,+ storedScrapById,+ replenishmentScrapByItemId+ });+ const allCycleNodeIds = new Set([...flattenCycles, ...cycleNodeIds]);+ if (allCycleNodeIds.size > 0) {+ // Corrupt tree data — the nodes were skipped rather than looped on.+ recalculateRequirementsLogger.error(+ "recalculate: cyclic job method tree; skipped nodes",+ {+ skippedNodeIds: [...allCycleNodeIds]+ }+ );+ }++ // jobMaterial scrap/estimated — one VALUES-join update for the whole tree+ const materialRows = computed.filter((c) => c.hasJobMaterial);+ if (materialRows.length > 0) {+ await sql`+ UPDATE "jobMaterial" AS m+ SET "scrapQuantity" = v.scrap::numeric,+ "estimatedQuantity" = v.estimated::numeric+ FROM (VALUES ${sql.join(+ materialRows.map(+ (c) => sql`(${c.id}, ${c.scrapQuantity}, ${c.estimatedQuantity})`+ )+ )}) AS v(id, scrap, estimated)+ WHERE m.id = v.id+ `.execute(trx);+ }++ const makeNodes = computed.filter(+ (c): c is ComputedJobQuantityNode & { jobMaterialMakeMethodId: string } =>+ c.jobMaterialMakeMethodId !== null+ );+ if (makeNodes.length > 0) {+ // Not the tree's root: the tree does not know how many of it its parent+ // needs, and writing its placeholder reset a sub-assembly to 1.+ const perParent = makeNodes.filter((c) => c.quantityPerParent !== null);+ if (perParent.length > 0) {+ await sql`+ UPDATE "jobMakeMethod" AS jmm+ SET "quantityPerParent" = v.qpp::numeric+ FROM (VALUES ${sql.join(+ perParent.map(+ (c) => sql`(${c.jobMaterialMakeMethodId}, ${c.quantityPerParent})`+ )+ )}) AS v(id, qpp)+ WHERE jmm.id = v.id+ `.execute(trx);+ }++ await sql`+ UPDATE "jobOperation" AS op+ SET "targetQuantity" = v.target::numeric,+ "operationQuantity" = v.total::numeric+ FROM (VALUES ${sql.join(+ makeNodes.map(+ (c) =>+ sql`(${c.jobMaterialMakeMethodId}, ${c.targetQuantity}, ${c.totalWithScrap})`+ )+ )}) AS v(id, target, total)+ WHERE op."jobMakeMethodId" = v.id+ AND op."reworkId" IS NULL+ `.execute(trx);++ const trackedMakeMethods = await trx+ .selectFrom("jobMakeMethod")+ .select(["id", "trackedEntityId", "requiresSerialTracking"])+ .where(+ "id",+ "in",+ makeNodes.map((c) => c.jobMaterialMakeMethodId)+ )+ .where("trackedEntityId", "is not", null)+ .execute();++ if (trackedMakeMethods.length > 0) {+ const totalByMakeMethodId = new Map(+ makeNodes.map((c) => [c.jobMaterialMakeMethodId, c.totalWithScrap])+ );+ await sql`+ UPDATE "trackedEntity" AS te+ SET "quantity" = v.quantity::numeric+ FROM (VALUES ${sql.join(+ trackedMakeMethods.map(+ (m) =>+ sql`(${m.trackedEntityId}, ${+ m.requiresSerialTracking+ ? 1+ : (totalByMakeMethodId.get(m.id) ?? 1)+ })`+ )+ )}) AS v(id, quantity)+ WHERE te.id = v.id+ `.execute(trx);+ }+ }+ };+ const triggerReworkLogger = getLogger("server-functions", "trigger-rework");++ interface TriggerReworkRequest {+ jobId: string;+ triggeredAtJobOperationId: string;+ targetJobOperationId: string;+ reason: string;+ quantity: number;+ trackedEntityIds?: string[];+ // Provenance link when an inspection disposition triggered the rework —+ // stamped on the Rework productionQuantity row.+ inspectionId?: string;+ companyId: string;+ userId: string;+ }++ /**+ * Finds the shortest path from targetOperationId to triggeredAtOperationId+ * by walking backwards through the DAG from triggeredAt.+ * Returns operations in forward order (target → ... → triggeredAt).+ */+ async function findReworkPath(+ trx: Transaction<KyselyDatabase>,+ jobId: string,+ targetOperationId: string,+ triggeredAtOperationId: string+ ): Promise<string[]> {+ const dependencies = await trx+ .selectFrom("jobOperationDependency")+ .select(["operationId", "dependsOnId"])+ .where("jobId", "=", jobId)+ .execute();++ // Build adjacency list: operationId → [operations it depends on]+ const dependsOn = new Map<string, string[]>();+ for (const dep of dependencies) {+ const existing = dependsOn.get(dep.operationId) ?? [];+ existing.push(dep.dependsOnId);+ dependsOn.set(dep.operationId, existing);+ }++ // BFS backwards from triggeredAt to find target+ const visited = new Set<string>();+ const parent = new Map<string, string>();+ const queue: string[] = [triggeredAtOperationId];+ visited.add(triggeredAtOperationId);++ while (queue.length > 0) {+ const current = queue.shift()!;+ if (current === targetOperationId) break;++ for (const predecessor of dependsOn.get(current) ?? []) {+ if (!visited.has(predecessor)) {+ visited.add(predecessor);+ parent.set(predecessor, current);+ queue.push(predecessor);+ }+ }+ }++ if (!visited.has(targetOperationId)) {+ throw new Error(+ `No path found from target operation ${targetOperationId} to triggered operation ${triggeredAtOperationId}`+ );+ }++ // Trace path from target back to triggeredAt (forward order)+ const path: string[] = [];+ let current = targetOperationId;+ while (current !== triggeredAtOperationId) {+ path.push(current);+ current = parent.get(current)!;+ }+ path.push(triggeredAtOperationId);++ return path;+ }++ async function cloneReworkOperations(+ trx: Transaction<KyselyDatabase>,+ body: TriggerReworkRequest+ ) {+ const {+ jobId,+ triggeredAtJobOperationId,+ targetJobOperationId,+ reason,+ quantity,+ trackedEntityIds,+ inspectionId,+ companyId,+ userId+ } = body;++ // 1. Find the path of operations to clone+ const operationPath = await findReworkPath(+ trx,+ jobId,+ targetJobOperationId,+ triggeredAtJobOperationId+ );++ triggerReworkLogger.info(+ `📋 Rework path: ${operationPath.length} operations to clone`+ );++ // 2. Create the rework record+ const [rework] = await trx+ .insertInto("rework")+ .values({+ jobId,+ triggeredAtJobOperationId,+ targetJobOperationId,+ reason,+ quantity,+ requestedById: userId,+ companyId+ })+ .returning(["id"])+ .execute();++ // 2b. Create tracked activity for traceability+ if (trackedEntityIds && trackedEntityIds.length > 0) {+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Rework",+ sourceDocument: "Rework",+ sourceDocumentId: rework!.id,+ attributes: {+ Job: jobId,+ "Triggered At": triggeredAtJobOperationId,+ Target: targetJobOperationId,+ Reason: reason,+ Quantity: quantity+ },+ companyId,+ createdBy: userId+ })+ .execute();++ const isSerial = trackedEntityIds.length > 1 || quantity === 1;+ for (const entityId of trackedEntityIds) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: entityId,+ quantity: isSerial ? 1 : quantity,+ companyId,+ createdBy: userId+ })+ .execute();+ }+ }++ // 3. Fetch the source operations to clone+ const sourceOperations = await trx+ .selectFrom("jobOperation")+ .selectAll()+ .where("id", "in", operationPath)+ .execute();++ // Sort by path order+ const pathIndex = new Map(operationPath.map((id, i) => [id, i]));+ sourceOperations.sort(+ (a, b) => (pathIndex.get(a.id) ?? 0) - (pathIndex.get(b.id) ?? 0)+ );++ // 4. Compute sort order: place rework ops after the triggering operation+ // "With Previous" on the first rework op lets it run in parallel with+ // the triggering operation's successors until the DAG converges.+ const [triggerOp, nextOp] = await Promise.all([+ trx+ .selectFrom("jobOperation")+ .select("order")+ .where("id", "=", triggeredAtJobOperationId)+ .executeTakeFirstOrThrow(),+ trx+ .selectFrom("jobOperation")+ .select("order")+ .where("jobId", "=", jobId)+ .where(+ "order",+ ">",+ trx+ .selectFrom("jobOperation")+ .select("order")+ .where("id", "=", triggeredAtJobOperationId)+ )+ .orderBy("order", "asc")+ .executeTakeFirst()+ ]);++ const triggerOrder = Number(triggerOp.order);+ const upperBound = nextOp?.order ? Number(nextOp.order) : triggerOrder + 1;+ const gap = upperBound - triggerOrder;+ const increment = gap / (sourceOperations.length + 1);++ // 5. Clone operations (batch insert)+ const clonedOps = await trx+ .insertInto("jobOperation")+ .values(+ sourceOperations.map((sourceOp, i) => ({+ jobId: sourceOp.jobId,+ jobMakeMethodId: sourceOp.jobMakeMethodId,+ order: triggerOrder + increment * (i + 1),+ processId: sourceOp.processId,+ workCenterId: sourceOp.workCenterId,+ description: sourceOp.description,+ setupTime: sourceOp.setupTime,+ setupUnit: sourceOp.setupUnit,+ laborTime: sourceOp.laborTime,+ laborUnit: sourceOp.laborUnit,+ machineTime: sourceOp.machineTime,+ machineUnit: sourceOp.machineUnit,+ operationOrder: i === 0 ? "With Previous" : sourceOp.operationOrder,+ laborRate: sourceOp.laborRate,+ overheadRate: sourceOp.overheadRate,+ machineRate: sourceOp.machineRate,+ operationType: sourceOp.operationType,+ operationMinimumCost: sourceOp.operationMinimumCost,+ operationLeadTime: sourceOp.operationLeadTime,+ operationUnitCost: sourceOp.operationUnitCost,+ operationSupplierProcessId: sourceOp.operationSupplierProcessId,+ workInstruction: sourceOp.workInstruction,+ procedureId: sourceOp.procedureId,+ // A cloned Inspection op must re-inspect against the SAME plan — its+ // lazily-created lot resolves features/sampling from this document.+ // Assembly ops likewise keep their instruction link for 3D playback.+ inspectionDocumentId: sourceOp.inspectionDocumentId,+ assemblyInstructionId: sourceOp.assemblyInstructionId,+ operationQuantity: quantity,+ targetQuantity: quantity,+ tags: sourceOp.tags,+ companyId,+ createdBy: userId,+ reworkId: rework!.id,+ status: i === 0 ? "Ready" : "Waiting",+ customFields: sourceOp.customFields+ }))+ )+ .returning(["id"])+ .execute();++ const clonedOperationIds = clonedOps.map((op) => op.id);+ const sourceToCloneMap = new Map<string, string>();+ sourceOperations.forEach((sourceOp, i) => {+ sourceToCloneMap.set(sourceOp.id, clonedOps[i]!.id);+ });++ triggerReworkLogger.info(`🔧 Cloned ${clonedOperationIds.length} operations`);++ // 6. Clone steps, tools, and parameters (batch fetch + batch insert)+ const [allSteps, allTools, allParams] = await Promise.all([+ trx+ .selectFrom("jobOperationStep")+ .selectAll()+ .where("operationId", "in", operationPath)+ .execute(),+ trx+ .selectFrom("jobOperationTool")+ .selectAll()+ .where("operationId", "in", operationPath)+ .execute(),+ trx+ .selectFrom("jobOperationParameter")+ .selectAll()+ .where("operationId", "in", operationPath)+ .execute()+ ]);++ const stepValues = allSteps.map(+ ({+ id: _id,+ operationId,+ createdAt: _ca,+ updatedAt: _ua,+ updatedBy: _ub,+ ...step+ }) => ({+ ...step,+ operationId: sourceToCloneMap.get(operationId)!,+ createdBy: userId+ })+ );++ const toolValues = allTools.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId: sourceToCloneMap.get(tool.operationId)!,+ companyId,+ createdBy: userId+ }));++ const paramValues = allParams.map((param) => ({+ key: param.key,+ value: param.value,+ operationId: sourceToCloneMap.get(param.operationId)!,+ companyId,+ createdBy: userId+ }));++ await Promise.all([+ stepValues.length > 0+ ? trx.insertInto("jobOperationStep").values(stepValues).execute()+ : null,+ toolValues.length > 0+ ? trx.insertInto("jobOperationTool").values(toolValues).execute()+ : null,+ paramValues.length > 0+ ? trx.insertInto("jobOperationParameter").values(paramValues).execute()+ : null+ ]);++ // 7. Wire the rework operations into the DAG+ // First rework op has no dependencies — it's an independent parallel branch.+ // Traceability is captured via the rework record, not DAG edges.+ const dagEdges: Array<{+ operationId: string;+ dependsOnId: string;+ jobId: string;+ companyId: string;+ }> = [];++ // 7a. Each subsequent rework op depends on the previous+ for (let i = 1; i < clonedOperationIds.length; i++) {+ dagEdges.push({+ operationId: clonedOperationIds[i]!,+ dependsOnId: clonedOperationIds[i - 1]!,+ jobId,+ companyId+ });+ }++ // 7b. Convergence: downstream ops that depended on triggeredAt also depend+ // on the last rework op so the DAG merges back.+ // Filter on `jobId`, not `companyId`: dependency edges are per-job, and+ // `jobId` is the column the scheduler's own rebuild filters on. Trusting the+ // row's stamped `companyId` would trust exactly the field that cross-tenant+ // mis-stamping makes unreliable. Without any filter this read reaches every+ // tenant's edges and re-inserts them under this job's company.+ const downstreamDeps = await trx+ .selectFrom("jobOperationDependency")+ .select(["operationId"])+ .where("jobId", "=", jobId)+ .where("dependsOnId", "=", triggeredAtJobOperationId)+ .where("operationId", "not in", clonedOperationIds)+ .execute();++ const lastReworkOpId = clonedOperationIds[clonedOperationIds.length - 1]!;++ for (const dep of downstreamDeps) {+ dagEdges.push({+ operationId: dep.operationId,+ dependsOnId: lastReworkOpId,+ jobId,+ companyId+ });+ }++ if (dagEdges.length > 0) {+ await trx.insertInto("jobOperationDependency").values(dagEdges).execute();+ }++ triggerReworkLogger.info(+ `🔗 DAG wired with ${downstreamDeps.length} downstream deps rewired`+ );++ // 8. Record a productionQuantity entry for the rework+ await trx+ .insertInto("productionQuantity")+ .values({+ jobOperationId: triggeredAtJobOperationId,+ type: "Rework",+ quantity,+ inspectionId: inspectionId ?? null,+ companyId,+ createdBy: userId+ })+ .execute();++ return {+ reworkId: rework!.id,+ clonedOperationIds,+ operationsCloned: clonedOperationIds.length+ };+ }++ export const triggerReworkPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof triggerReworkInput>>;++ /**+ * Sends a job back to an earlier operation: clones the operations from the+ * target up to where the problem was found, then reschedules the job.+ */+ export async function triggerRework(+ ctx: ServiceContext,+ raw: z.input<typeof triggerReworkInput>+ ) {+ const parsed = triggerReworkInput.parse(raw);++ const db = ctx.asSystem.pg;++ const body: TriggerReworkRequest = {+ ...parsed,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ };++ // `jobId` and `companyId` both arrive in the payload, and nothing proved+ // they belong together. Without this, a request pairing one company's id+ // with another company's job writes rows attributed to the wrong tenant.+ // See .ai/specs/2026-08-25-backup-durability.md Part 3.+ const job = await db+ .selectFrom("job")+ .select(["id", "companyId"])+ .where("id", "=", body.jobId)+ .executeTakeFirst();++ // 404, not 403: a job in another company must be indistinguishable from a+ // job that does not exist.+ if (!job || job.companyId !== body.companyId) {+ throw new NotFoundError("Job not found in this company");+ }++ // The same holds for the two operation ids: triggerRework reads, clones and+ // writes productionQuantity against them by id alone, so both must be+ // operations of this job (the job is already proven to be this company's).+ const operationIds = [+ ...new Set([body.triggeredAtJobOperationId, body.targetJobOperationId])+ ];+ const operations = await db+ .selectFrom("jobOperation")+ .select("id")+ .where("id", "in", operationIds)+ .where("jobId", "=", body.jobId)+ .where("companyId", "=", body.companyId)+ .execute();+ if (operations.length !== operationIds.length) {+ throw new NotFoundError("Job operation not found in this company");+ }++ await assertCompanyRecords(+ db,+ "trackedEntity",+ body.trackedEntityIds ?? [],+ body.companyId,+ "Tracked entity"+ );++ // Written as productionQuantity.inspectionId, whose FK accepts any company's+ // inspection.+ await assertCompanyRecords(+ db,+ "inspection",+ [body.inspectionId],+ body.companyId,+ "Inspection"+ );++ triggerReworkLogger.info(+ `🔰 Starting rework for job ${body.jobId}: go back to ${body.targetJobOperationId} from ${body.triggeredAtJobOperationId}`+ );++ const result = await db.transaction().execute(async (trx) => {+ return await cloneReworkOperations(trx, body);+ });++ // Reschedule for date/priority recalculation (after the transaction). A+ // failure is logged, not raised: the rework itself has committed.+ const rescheduled = await invokePosting(+ { db, companyId: body.companyId, userId: body.userId },+ "reschedule",+ { jobId: body.jobId },+ rescheduleJob+ );+ if (rescheduled.error) {+ triggerReworkLogger.error("Failed to trigger reschedule after rework", {+ error: rescheduled.error+ });+ }++ return { success: true, ...result };+ }+ const NOT_STARTED = ["Todo", "Ready", "Waiting"];+ // The produced item + tracking of each member, and its live WIP entity (the+ // entity a member's output lot is finalized from; its readableId is the lot+ // number).+ async function loadMemberOutputs(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ jobMakeMethodIds: string[]+ ) {+ if (jobMakeMethodIds.length === 0) return new Map();+ const makeMethods = await trx+ .selectFrom("jobMakeMethod")+ .select(["id", "itemId", "requiresBatchTracking"])+ .where("id", "in", jobMakeMethodIds)+ .where("companyId", "=", companyId)+ .execute();+ const entities = await trx+ .selectFrom("trackedEntity")+ .select([+ "id",+ "createdAt",+ sql<string>`"attributes"->>'Job Make Method'`.as("jobMakeMethodId")+ ])+ .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) {+ if (!entityByMakeMethod.has(e.jobMakeMethodId)) {+ entityByMakeMethod.set(e.jobMakeMethodId, e.id);+ }+ }+ return new Map(+ makeMethods.map((m) => [+ m.id,+ {+ itemId: m.itemId as string | null,+ requiresBatchTracking: Boolean(m.requiresBatchTracking),+ trackedEntityId: entityByMakeMethod.get(m.id) ?? null+ }+ ])+ );+ }++ // A merged batch's members must all produce ONE batch-tracked item: lots of+ // different items can never merge, and an untracked item has no lot at all.+ function assertMergeable(+ operations: Array<{ jobMakeMethodId: string | null }>,+ outputs: Map<+ string,+ { itemId: string | null; requiresBatchTracking: boolean }+ >+ ) {+ const items = new Set<string>();+ for (const op of operations) {+ const out = op.jobMakeMethodId+ ? outputs.get(op.jobMakeMethodId)+ : undefined;+ if (!out?.requiresBatchTracking || !out.itemId) {+ throw new Error(+ "Only operations that produce a batch-tracked item can combine into one lot"+ );+ }+ items.add(out.itemId);+ }+ if (items.size > 1) {+ throw new Error("Lots of different items can't combine into one lot");+ }+ }++ async function assertEligible(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ jobOperationIds: string[],+ expectedProcessId?: string+ ) {+ const operations = await trx+ .selectFrom("jobOperation")+ .selectAll()+ .where("id", "in", jobOperationIds)+ .where("companyId", "=", companyId)+ .execute();+ if (operations.length !== jobOperationIds.length) {+ throw new NotFoundError("One or more operations not found");+ }+ const processId = expectedProcessId ?? operations[0]!.processId;+ const process = await trx+ .selectFrom("process")+ .select(["id", "batchable"])+ .where("id", "=", processId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!process?.batchable) {+ throw new Error("The process is not batchable");+ }+ for (const op of operations) {+ if (op.processId !== processId) {+ throw new Error(`Operation ${op.id} is not on the batch's process`);+ }+ if (op.jobOperationBatchId) {+ throw new Error(`Operation ${op.id} is already in a batch`);+ }+ // A batch is one run on one of our work centers; subcontracted work runs+ // at the supplier, and joining a batch would stamp the batch's work center+ // onto it.+ if (op.operationType === "Outside Processing") {+ throw new Error(+ `Operation ${op.id} is outside processing and can't be batched`+ );+ }+ if (!NOT_STARTED.includes(op.status)) {+ throw new Error(`Operation ${op.id} has already started`);+ }+ }+ const events = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationId", "in", jobOperationIds)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (events.length > 0) {+ throw new Error(+ "Operations with recorded production events cannot be batched"+ );+ }+ return { operations, processId };+ }++ // Record ids in the payload come straight from the caller and prove nothing+ // about tenancy — the permission check only authorizes the CALLER for companyId.+ // Re-read the record under companyId and refuse on a miss (the same rule the+ // composite FKs enforce at the schema level; this gives the caller a named+ // error instead of a constraint violation).+ // Enforce the process's "must match" compatibility rules across the WHOLE batch+ // membership (create: the incoming set; add: existing members + incoming). Skips+ // entirely when the process has no "must" dimension. Uses ids where the client+ // (BatchBuilder) uses names — mustViolations is value-agnostic, so both agree.+ async function assertMaterialCompatible(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ processId: string,+ jobOperationIds: string[]+ ) {+ const process = await trx+ .selectFrom("process")+ .select(["batchRules"])+ .where("id", "=", processId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const rules = resolveBatchRules(+ (process?.batchRules ?? null) as BatchRules | null+ );+ if (!BATCH_RULE_DIMENSIONS.some((d) => rules[d] === "must")) return;++ // Mirror the get_batchable_operations fallback: an op's materials are its+ // op-linked BOM lines, or — when it has none — the JOB's unassigned lines+ // (jobOperationId IS NULL). The gate must judge the same materials the+ // builder shows, or a visible "must" match could still be refused (and vice+ // versa).+ // Produced item mirrors the builder's candidate `itemReadableId` (the JOB's+ // item — get_batchable_operations joins item on job.itemId), so the gate and+ // the builder judge the producedItem dimension by the same value.+ const memberOps = await trx+ .selectFrom("jobOperation")+ .innerJoin("job", (join: any) =>+ join+ .onRef("job.id", "=", "jobOperation.jobId")+ .onRef("job.companyId", "=", "jobOperation.companyId")+ )+ .leftJoin("item as pi", (join: any) =>+ join+ .onRef("pi.id", "=", "job.itemId")+ .onRef("pi.companyId", "=", "job.companyId")+ )+ .select([+ "jobOperation.id as id",+ "jobOperation.jobId as jobId",+ "pi.readableId as producedItemReadableId"+ ])+ .where("jobOperation.id", "in", jobOperationIds)+ .where("jobOperation.companyId", "=", companyId)+ .execute();+ const jobIdByOp = new Map(memberOps.map((o) => [o.id, o.jobId]));+ const producedByOp = new Map(+ memberOps.map((o) => [o.id, o.producedItemReadableId])+ );+ const memberJobIds = [...new Set(memberOps.map((o) => o.jobId))];++ const rows = await trx+ .selectFrom("jobMaterial as jm")+ .innerJoin("item as mi", (join: any) =>+ join+ .onRef("mi.id", "=", "jm.itemId")+ .onRef("mi.companyId", "=", "jm.companyId")+ )+ .leftJoin("material as m", (join: any) =>+ join+ .onRef("m.id", "=", "mi.readableId")+ .onRef("m.companyId", "=", "mi.companyId")+ )+ .select([+ "jm.jobOperationId as opId",+ "jm.jobId as jobId",+ "mi.readableId as itemReadableId",+ "m.materialSubstanceId as substanceId",+ "m.gradeId as gradeId",+ "m.dimensionId as dimensionId",+ "m.materialFormId as formId",+ "m.finishId as finishId"+ ])+ .where("jm.companyId", "=", companyId)+ .where((eb: any) =>+ eb.or([+ eb("jm.jobOperationId", "in", jobOperationIds),+ eb.and([+ eb("jm.jobOperationId", "is", null),+ eb("jm.jobId", "in", memberJobIds)+ ])+ ])+ )+ .execute();++ type MaterialRow = (typeof rows)[number];+ const pushRow = (sets: MemberValueSets, r: MaterialRow) => {+ if (r.itemReadableId) sets.item!.push(r.itemReadableId);+ if (r.substanceId) sets.substance!.push(r.substanceId);+ if (r.gradeId) sets.grade!.push(r.gradeId);+ if (r.dimensionId) sets.dimension!.push(r.dimensionId);+ if (r.formId) sets.form!.push(r.formId);+ if (r.finishId) sets.finish!.push(r.finishId);+ };++ const byOp = new Map<string, MemberValueSets>();+ for (const id of jobOperationIds) {+ const produced = producedByOp.get(id);+ byOp.set(id, {+ item: [],+ substance: [],+ grade: [],+ dimension: [],+ form: [],+ finish: [],+ producedItem: produced ? [produced] : []+ });+ }+ const opsWithLinkedRows = new Set(+ rows.map((r) => r.opId).filter(Boolean) as string[]+ );+ const unassignedByJob = new Map<string, MaterialRow[]>();+ for (const r of rows) {+ if (r.opId) {+ const sets = byOp.get(r.opId);+ if (sets) pushRow(sets, r);+ } else if (r.jobId) {+ const list = unassignedByJob.get(r.jobId) ?? [];+ list.push(r);+ unassignedByJob.set(r.jobId, list);+ }+ }+ for (const id of jobOperationIds) {+ if (opsWithLinkedRows.has(id)) continue;+ const jobId = jobIdByOp.get(id);+ const fallback = jobId ? unassignedByJob.get(jobId) : undefined;+ if (!fallback) continue;+ const sets = byOp.get(id)!;+ for (const r of fallback) pushRow(sets, r);+ }++ const violations = mustViolations(rules, Array.from(byOp.values()));+ if (violations.length > 0) {+ throw new Error(+ `These operations can't share a batch — the ${violations.join(+ ", "+ )} must match on this process`+ );+ }+ }++ // Two-phase, resumable batch completion.+ //+ // Phase 1 (one Kysely transaction, runs once): FOR UPDATE the batch row to+ // serialize completers, then slice the recorded aggregate timers into per-member+ // productionEvent rows (∝ operationQuantity) + write per-member productionQuantity+ // rows, and flip the batch Active -> Completing (guarded). productionEvent.duration+ // is a GENERATED column, so the proportional windows make each member's duration —+ // and thus GL cost — proportional with no manual duration write.+ //+ // Phase 2 (post-commit, idempotent): issue each member's own BOM (backflush-capped),+ // flip members Done (skipping already-Done), and post GL per sliced event (skipping+ // already-posted). Any throw here leaves the batch Completing; re-running with the+ // same payload re-enters via planBatchCompletion -> "resume" and finishes phase 2+ // without re-slicing. Only after every phase-2 effect succeeds is the batch flipped+ // Completing -> Completed. This removes the old failure mode where a post-commit+ // error left the batch Completed with unissued materials or unposted GL and no+ // recovery path.+ async function completeBatch(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ batchId: string;+ members: {+ jobOperationId: string;+ quantity: number;+ scrapQuantity?: number;+ trackedEntityId?: string | null;+ batchNumber?: string | null;+ excluded?: boolean;+ }[];+ }+ ): Promise<Record<string, unknown>> {+ const { companyId, userId, batchId } = args;+ // Partition "not in this run" members: they were never physically part of the+ // batch run, so they detach back to the schedule un-run instead of completing.+ // They may not carry quantities, and a batch cannot exclude everyone —+ // dissolve exists for that.+ const members = args.members.filter((m) => !m.excluded);+ const excluded = args.members.filter((m) => m.excluded);+ if (members.length === 0) {+ throw new Error(+ "Every operation is excluded — dissolve the batch instead of completing it"+ );+ }+ for (const m of excluded) {+ if (m.quantity > 0 || (m.scrapQuantity ?? 0) > 0) {+ throw new Error(+ `Excluded operation ${m.jobOperationId} cannot record quantities`+ );+ }+ }+ const memberIds = members.map((m) => m.jobOperationId);+ const excludedIds = excluded.map((m) => m.jobOperationId);+ const now = datetime.timestamp();++ // The per-member sliced events whose GL is posted AFTER the transaction commits.+ // postedToGL lets a resume skip events a prior attempt already posted. Populated+ // inside the transaction: freshly sliced on the first attempt, re-loaded on resume.+ let glEvents: { id: string; postedToGL: boolean }[] = [];++ // Strict backflush: refuse before phase 1 writes, since phase 2 issues after+ // it commits. Every member is checked in one dry run, so members sharing a+ // bin are held to their combined demand. A completed batch skips this, so a+ // retry still gets the "already completed" answer.+ const batchStatus = await db+ .selectFrom("jobOperationBatch")+ .select("status")+ .where("id", "=", batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (batchStatus?.status !== "Completed") {+ await inventoryPostings.dryRunJobOperationIssues(db, {+ companyId,+ userId,+ operations: members.map((m) => ({+ id: m.jobOperationId,+ quantity: m.quantity+ }))+ });+ }+ const system = { db, companyId, userId };++ await db.transaction().execute(async (trx) => {+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select(["id", "status"])+ .where("id", "=", batchId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!batch) throw new NotFoundError(`Batch ${batchId} was not found`);++ if (batch.status === "Completed") {+ throw new ServerFnError("This batch has already been completed", 409, {+ alreadyCompleted: true+ });+ }+ // "resume" if the batch is already Completing (a prior phase-2 step failed);+ // "slice" if Active; throws for a terminal status.+ const phase = planBatchCompletion(batch.status);++ if (phase === "resume") {+ // The payload must cover EXACTLY the batch's membership — phase 2 flips+ // every member Done batch-wide but issues materials only for the submitted+ // members, so a short payload would strand an omitted member Done with+ // unissued BOM. Re-assert membership on resume just as the slice path does.+ const currentMembers = await trx+ .selectFrom("jobOperation")+ .select("id")+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .execute();+ const currentIds = new Set(currentMembers.map((o: any) => o.id));+ // An exclusion that phase 1 already applied is a stale-form resubmission+ // and passes (the op is no longer a member). Excluding an op that IS still+ // a member would rewrite phase 1's committed decision — reject it like a+ // changed quantity.+ const lateExclusion = excludedIds.find((id) => currentIds.has(id));+ if (lateExclusion) {+ throw new Error(+ `Operation ${lateExclusion} was included when completion started — ` ++ `retry with the recorded values; corrections happen after completion.`+ );+ }+ assertBatchCompletionMembership(memberIds, [...currentIds]);++ // Resume contract: the payload must match what phase 1 already recorded —+ // an edited quantity on retry is rejected, never silently ignored and never+ // rewritten (phase 1's slices/quantities are already committed). Batch+ // members were unstarted at batch time and batch completion is the only+ // productionQuantity writer between Active and Completing, so per-op sums+ // equal the phase-1 inserts.+ const recordedQuantities = await trx+ .selectFrom("productionQuantity")+ .select(["jobOperationId", "type", "quantity"])+ .where("jobOperationId", "in", memberIds)+ .where("companyId", "=", companyId)+ .execute();+ const sums = new Map<string, { produced: number; scrap: number }>();+ for (const r of recordedQuantities as any[]) {+ const s = sums.get(r.jobOperationId) ?? { produced: 0, scrap: 0 };+ if (r.type === "Production") s.produced += Number(r.quantity);+ if (r.type === "Scrap") s.scrap += Number(r.quantity);+ sums.set(r.jobOperationId, s);+ }+ const mismatches = members.filter((m) => {+ const s = sums.get(m.jobOperationId) ?? { produced: 0, scrap: 0 };+ return s.produced !== m.quantity || s.scrap !== (m.scrapQuantity ?? 0);+ });+ if (mismatches.length > 0) {+ const detail = mismatches+ .map((m) => {+ const s = sums.get(m.jobOperationId) ?? { produced: 0, scrap: 0 };+ return `${m.jobOperationId}: ${s.produced} produced / ${s.scrap} scrap`;+ })+ .join(", ");+ throw new Error(+ `Quantities were already recorded for this batch (${detail}). ` ++ `Retry with the recorded values; corrections happen after completion.`+ );+ }++ const existing = await trx+ .selectFrom("productionEvent")+ .select(["id", "postedToGL"])+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .where("endTime", "is not", null)+ .execute();+ glEvents = existing.map((e: any) => ({+ id: e.id,+ postedToGL: e.postedToGL ?? false+ }));+ return;+ }++ // phase === "slice": first attempt.+ const operations = await trx+ .selectFrom("jobOperation")+ .select(["id", "operationQuantity"])+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .execute();+ if (operations.length === 0)+ throw new NotFoundError("Batch not found or empty");++ // Reject dupes / unknown ids / omitted members — any would corrupt+ // quantities or material issue. Included AND excluded together must cover+ // the membership exactly; the excluded ones then detach below.+ assertBatchCompletionMembership(+ [...memberIds, ...excludedIds],+ operations.map((o: any) => o.id)+ );++ // Detach "not in this run" members inside the same transaction: back to the+ // schedule un-run — no time slice, no quantities, and phase 2's batch-wide+ // Done flip no longer reaches them.+ if (excludedIds.length > 0) {+ const detached = await trx+ .updateTable("jobOperation")+ .set({ jobOperationBatchId: null, updatedBy: userId })+ .where("id", "in", excludedIds)+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (Number(detached?.numUpdatedRows ?? 0) !== excludedIds.length) {+ throw new Error("Failed to detach excluded operations — retry");+ }+ }+ const excludedIdSet = new Set(excludedIds);+ const runOperations = operations.filter(+ (o: any) => !excludedIdSet.has(o.id)+ );++ const opById = new Map(runOperations.map((o: any) => [o.id, o]));++ // Auto-stop any still-running batch timer, mirroring the single-operation+ // flow: writing jobOperation.status = 'Done' fires sync_finish_job_operation,+ // which closes that op's open productionEvents with endTime = NOW(). A batch+ // completes the same way — stop the shared timer here rather than refusing —+ // so the just-closed aggregate is sliced per member below and its cost posts+ // once in phase 2. (This is inside the phase-1 txn; the batch-tagged End path+ // deliberately skips post-production-event, so there is no double GL post.)+ await trx+ .updateTable("productionEvent")+ .set({ endTime: datetime.timestamp() })+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .where("endTime", "is", null)+ .execute();++ const recorded = await trx+ .selectFrom("productionEvent")+ .select([+ "id",+ "type",+ "startTime",+ "endTime",+ "workCenterId",+ "employeeId"+ ])+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .where("endTime", "is not", null)+ .execute();++ const plan = buildBatchCompletionPlan(+ recorded+ .filter((e: any) => e.endTime)+ .map((e: any) => ({+ id: e.id,+ type: e.type,+ startTime: e.startTime,+ endTime: e.endTime as string,+ workCenterId: e.workCenterId,+ employeeId: e.employeeId+ })),+ members.map((m) => ({+ jobOperationId: m.jobOperationId,+ operationQuantity: Number(+ opById.get(m.jobOperationId)?.operationQuantity ?? 0+ ),+ quantity: m.quantity,+ scrapQuantity: m.scrapQuantity+ }))+ );++ // Replace the aggregate timers with the per-member slices.+ if (recorded.length > 0) {+ await trx+ .deleteFrom("productionEvent")+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .where("endTime", "is not", null)+ .execute();+ }++ for (const e of plan.memberEvents) {+ const inserted = await trx+ .insertInto("productionEvent")+ .values({+ // The shared plan types `type` as `string | null`; narrow it back to+ // the column's enum here rather than casting the whole insert object.+ type: e.type as+ | Database["public"]["Enums"]["productionEventType"]+ | null,+ employeeId: e.employeeId,+ workCenterId: e.workCenterId,+ companyId,+ createdBy: userId,+ jobOperationBatchId: batchId,+ jobOperationId: e.jobOperationId,+ startTime: e.startTime,+ endTime: e.endTime,+ postedToGL: false+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ glEvents.push({ id: inserted.id, postedToGL: false });+ }++ if (plan.quantities.length > 0) {+ await trx+ .insertInto("productionQuantity")+ .values(+ // q.type is "Production" | "Scrap", a subset of productionQuantityType,+ // so the insert types cleanly without a cast.+ plan.quantities.map((q) => ({+ jobOperationId: q.jobOperationId,+ type: q.type,+ quantity: q.quantity,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ // Guarded Active -> Completing. WHERE status='Active' is the backstop to the+ // FOR UPDATE lock: 0 rows means a concurrent completer won — throw and roll+ // back every write in this transaction.+ const marked = await trx+ .updateTable("jobOperationBatch")+ .set({ status: "Completing", updatedBy: userId, updatedAt: now })+ .where("id", "=", batchId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Active")+ .returning("id")+ .executeTakeFirst();+ if (!marked) throw new Error("Only an active batch can be completed");+ });++ // Phase 2 (post-commit, idempotent). Any throw leaves the batch Completing; a+ // retry re-runs these steps alone. Runs as the system: the batch completion+ // itself was authorized.+ for (const m of members) {+ if (m.quantity <= 0) continue;+ const issued = await invokePosting(+ system,+ "issue",+ {+ id: m.jobOperationId,+ type: "jobOperation",+ quantity: m.quantity+ },+ inventoryPostings.issueMaterial+ );+ if (issued.error) {+ // Keep a strict backflush refusal's 409; completing again resumes.+ throw new ServerFnError(+ `Failed to issue materials for operation ${m.jobOperationId}: ${issued.error.message}`,+ issued.error instanceof ServerFnError ? issued.error.status : 500+ );+ }+ }++ // Finalize batch-tracked outputs: for each member producing a batch-tracked+ // item, flip its WIP entity to an Available lot via the lean+ // jobOperationBatchOutput case (Produce activity + entity flip only — the+ // productionQuantity rows were written in Phase 1 and the member's materials+ // were issued above). Idempotent: an already-Available entity is a no-op, so+ // a resume fast-forwards. Runs BEFORE the Done flip so a failure here leaves+ // the batch resumable with no member stranded Done without its output lot.+ const memberOpRows = await many(+ db,+ "jobOperation",+ { id: memberIds, companyId },+ { columns: ["id", "jobMakeMethodId"] }+ );+ if (memberOpRows.error) {+ throw new Error(+ `Failed to load member operations: ${memberOpRows.error.message}`+ );+ }+ const makeMethodIds = [+ ...new Set(+ (memberOpRows.data ?? [])+ .map((o: any) => o.jobMakeMethodId)+ .filter(Boolean) as string[]+ )+ ];+ const makeMethods = makeMethodIds.length+ ? await many(+ db,+ "jobMakeMethod",+ { id: makeMethodIds, companyId },+ { columns: ["id", "requiresBatchTracking"] }+ )+ : { data: [], error: null };+ if (makeMethods.error) {+ throw new Error(+ `Failed to load make methods: ${makeMethods.error.message}`+ );+ }+ const requiresBatchByMakeMethod = new Map(+ (makeMethods.data ?? []).map((m: any) => [m.id, m.requiresBatchTracking])+ );+ const makeMethodByOp = new Map(+ (memberOpRows.data ?? []).map((o: any) => [o.id, o.jobMakeMethodId])+ );++ const outputTrackedEntityIds: string[] = [];+ for (const m of members) {+ const makeMethodId = makeMethodByOp.get(m.jobOperationId);+ const requiresBatch = makeMethodId+ ? (requiresBatchByMakeMethod.get(makeMethodId) ?? false)+ : false;+ if (!requiresBatch) continue;+ if (m.quantity <= 0) continue;+ if (!m.trackedEntityId) {+ throw new Error(+ `Operation ${m.jobOperationId} produces a batch-tracked item — its output lot is required`+ );+ }+ const output = await invokePosting(+ system,+ "issue",+ {+ type: "jobOperationBatchOutput",+ jobOperationId: m.jobOperationId,+ trackedEntityId: m.trackedEntityId,+ quantity: m.quantity,+ readableId: m.batchNumber ?? null+ },+ inventoryPostings.issueMaterial+ );+ if (output.error) {+ throw new Error(+ `Failed to create the output lot for operation ${m.jobOperationId}: ${output.error.message}`+ );+ }+ outputTrackedEntityIds.push(m.trackedEntityId);+ }++ // Flip members Done — sync_finish_job_operation readies each member job's next+ // operation and completes the job independently. Skip already-Done so a resume+ // does not re-fire the trigger.+ const done = await updateRows(+ db,+ "jobOperation",+ { status: "Done", updatedBy: userId },+ { jobOperationBatchId: batchId, companyId, status: neq("Done") }+ );+ if (done.error) {+ throw new Error(`Failed to finish batch operations: ${done.error.message}`);+ }++ // Post GL per sliced event; skip events a prior attempt already posted, and+ // propagate errors so a GL failure keeps the batch resumable.+ for (const e of glEvents) {+ if (e.postedToGL) continue;+ const posted = await invokePosting(+ system,+ "post-production-event",+ {+ productionEventId: e.id+ },+ postProductionEvent+ );+ if (posted.error) {+ throw new Error(+ `Failed to post GL for production event ${e.id}: ${posted.error.message}`+ );+ }+ if (posted.data.success === false) {+ throw new Error(+ `Production event ${e.id} was not posted to GL: ${posted.data.reason}`+ );+ }+ }++ // Finalize: Completing -> Completed now that every phase-2 effect succeeded.+ const finalized = await updateRows(+ db,+ "jobOperationBatch",+ { status: "Completed", updatedBy: userId, updatedAt: now },+ { id: batchId, companyId, status: "Completing" }+ );+ if (finalized.error) {+ throw new Error(+ `Failed to finalize batch completion: ${finalized.error.message}`+ );+ }++ return {+ completed: members.length,+ excluded: excludedIds.length,+ memberIds,+ eventIds: glEvents.map((e) => e.id),+ outputTrackedEntityIds+ };+ }++ export const batchOperationPermission = {+ update: "production"+ } satisfies PermissionRule<z.output<typeof batchOperationsInput>>;++ /** Job-operation batches: create, change membership, release, dissolve and complete. */+ export async function batchOperation(+ ctx: ServiceContext,+ raw: z.input<typeof batchOperationsInput>+ ) {+ const payload = batchOperationsInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ let result: Record<string, unknown> = {};++ switch (payload.type) {+ case "create": {+ result = await db.transaction().execute(async (trx) => {+ const { operations, processId } = await assertEligible(+ trx,+ companyId,+ payload.jobOperationIds+ );+ await assertCompanyRecords(+ trx,+ "location",+ [payload.locationId],+ companyId,+ "Location"+ );+ await assertCompanyRecords(+ trx,+ "workCenter",+ [payload.workCenterId],+ companyId,+ "Work center"+ );+ await assertMaterialCompatible(+ trx,+ companyId,+ processId,+ payload.jobOperationIds+ );+ // The board's "Create batch" sends no work center (assignment is a+ // drag) — but when every member already sits on the same one, that IS+ // the batch's work center; adopt it so the header isn't blank.+ const memberWorkCenters = new Set(+ operations.map((o: any) => o.workCenterId).filter(Boolean)+ );+ const workCenterId =+ payload.workCenterId ??+ (memberWorkCenters.size === 1+ ? ([...memberWorkCenters][0] as string)+ : null);+ // Creating straight onto the floor (release: true) needs no work+ // center: the scheduler's batch pre-pass auto-selects the+ // earliest-finish candidate (load balancing, like single ops) for+ // any Released batch still lacking one, and persists it.+ const outputs = await loadMemberOutputs(+ trx,+ companyId,+ operations.map((o: any) => o.jobMakeMethodId).filter(Boolean)+ );+ const mergeOutput = payload.mergeOutput === true;+ if (mergeOutput) {+ if (!payload.outputLotNumber) {+ throw new Error("A combined output needs its lot number");+ }+ assertMergeable(operations, outputs);+ }+ // Split mode: one number per batch-tracked member, never repeated —+ // two separate lots sharing a number is exactly the ambiguity the+ // merge option exists to remove.+ const lotNumbers = mergeOutput ? [] : (payload.lotNumbers ?? []);+ const seen = new Set<string>();+ const lotWrites: Array<{+ trackedEntityId: string;+ lotNumber: string;+ }> = [];+ for (const entry of lotNumbers) {+ const op = operations.find((o: any) => o.id === entry.jobOperationId);+ const out = op?.jobMakeMethodId+ ? outputs.get(op.jobMakeMethodId)+ : undefined;+ if (!out?.requiresBatchTracking || !out.trackedEntityId) {+ throw new Error(+ `Operation ${entry.jobOperationId} does not produce a batch-tracked lot`+ );+ }+ const key = entry.lotNumber.toLowerCase();+ if (seen.has(key)) {+ throw new Error(+ `Lot number ${entry.lotNumber} is used twice — give each job its own, or combine them into one lot`+ );+ }+ seen.add(key);+ lotWrites.push({+ trackedEntityId: out.trackedEntityId,+ lotNumber: entry.lotNumber+ });+ }++ const readableId = await getNextSequence(+ trx,+ "jobOperationBatch",+ companyId+ );+ const batch = await trx+ .insertInto("jobOperationBatch")+ .values({+ readableId,+ companyId,+ processId,+ workCenterId,+ locationId: payload.locationId,+ status: payload.release ? "Active" : "Planned",+ notes: payload.notes ?? null,+ mergeOutput,+ outputLotNumber: mergeOutput ? payload.outputLotNumber : null,+ createdBy: userId+ })+ .returning(["id", "readableId"])+ .executeTakeFirstOrThrow();++ for (const write of lotWrites) {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId: write.lotNumber, updatedBy: userId })+ .where("id", "=", write.trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const memberUpdate: Record<string, unknown> = {+ jobOperationBatchId: batch.id,+ updatedBy: userId+ };+ if (payload.workCenterId)+ memberUpdate.workCenterId = payload.workCenterId;+ // Claim only ops still unbatched (IS NULL) and in this company: two+ // concurrent creates sharing an op both pass assertEligible's read, so+ // the IS NULL predicate + row-count assert is what actually serializes+ // the claim (assertEligible is not FOR UPDATE).+ const claimed = await trx+ .updateTable("jobOperation")+ .set(memberUpdate)+ .where("id", "in", payload.jobOperationIds)+ .where("companyId", "=", companyId)+ .where("jobOperationBatchId", "is", null)+ .executeTakeFirst();+ assertAllOperationsClaimed(+ payload.jobOperationIds,+ Number(claimed?.numUpdatedRows ?? 0)+ );+ return batch;+ });+ break;+ }++ case "add": {+ result = await db.transaction().execute(async (trx) => {+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .selectAll()+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!batch) throw new NotFoundError("Batch not found");+ // Membership is mutable while the batch is staged (Planned) or on+ // the floor but unstarted (Active); the production-event check below+ // is what actually freezes it.+ if (batch.status !== "Planned" && batch.status !== "Active") {+ throw new Error(+ `Cannot add operations to a batch with status ${batch.status}`+ );+ }++ const batchEvents = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (batchEvents.length > 0) {+ throw new Error(+ "The batch has already started — complete it instead"+ );+ }++ const { operations: incoming } = await assertEligible(+ trx,+ companyId,+ payload.jobOperationIds,+ batch.processId+ );++ // Compatibility is a property of the whole run: check existing members+ // plus the incoming ops together, not the newcomers in isolation.+ const existingMembers = await trx+ .selectFrom("jobOperation")+ .select(["id", "jobMakeMethodId"])+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .execute();++ // A combined-output batch stays one item: a newcomer producing+ // something else could never merge into the planned lot.+ if (batch.mergeOutput) {+ const all = [...existingMembers, ...incoming];+ const outputs = await loadMemberOutputs(+ trx,+ companyId,+ all.map((o: any) => o.jobMakeMethodId).filter(Boolean)+ );+ assertMergeable(all, outputs);+ }+ await assertMaterialCompatible(trx, companyId, batch.processId, [+ ...existingMembers.map((m: any) => m.id as string),+ ...payload.jobOperationIds+ ]);++ const memberUpdate: Record<string, unknown> = {+ jobOperationBatchId: batch.id,+ updatedBy: userId+ };+ if (batch.workCenterId) memberUpdate.workCenterId = batch.workCenterId;+ const claimed = await trx+ .updateTable("jobOperation")+ .set(memberUpdate)+ .where("id", "in", payload.jobOperationIds)+ .where("companyId", "=", companyId)+ .where("jobOperationBatchId", "is", null)+ .executeTakeFirst();+ assertAllOperationsClaimed(+ payload.jobOperationIds,+ Number(claimed?.numUpdatedRows ?? 0)+ );+ return { added: payload.jobOperationIds.length };+ });+ break;+ }++ case "remove": {+ result = await db.transaction().execute(async (trx) => {+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select("status")+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!batch) throw new NotFoundError("Batch not found");+ if (batch.status !== "Planned" && batch.status !== "Active") {+ throw new Error(+ `Cannot remove operations from a batch with status ${batch.status}`+ );+ }+ const batchEvents = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (batchEvents.length > 0) {+ throw new Error(+ "Cannot remove operations: production has been recorded. Complete the batch instead."+ );+ }+ // Count actual detaches — an id that isn't a member of this batch+ // (already removed, or never belonged) must not be reported removed.+ const removedResult = await trx+ .updateTable("jobOperation")+ .set({ jobOperationBatchId: null, updatedBy: userId })+ .where("id", "in", payload.jobOperationIds)+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const removed = Number(removedResult?.numUpdatedRows ?? 0);++ const remaining = await trx+ .selectFrom("jobOperation")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (remaining.length === 0) {+ await trx+ .deleteFrom("jobOperationBatch")+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .execute();+ return { removed, dissolved: true };+ }+ return { removed, dissolved: false };+ });+ break;+ }++ case "update": {+ const nextWorkCenterId = payload.workCenterId ?? null;+ result = await db.transaction().execute(async (trx) => {+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select("status")+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!batch) throw new NotFoundError("Batch not found");+ await assertCompanyRecords(+ trx,+ "workCenter",+ [nextWorkCenterId],+ companyId,+ "Work center"+ );+ // A Completed/Completing batch's events are already attributed to a+ // machine — re-pointing the work center would rewrite that history.+ assertBatchWorkCenterMutable(batch.status);+ // And once any production event exists, production has started against+ // the current work center, so the reassignment is no longer safe.+ const batchEvents = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (batchEvents.length > 0) {+ throw new Error(+ "Cannot change the work center: production has been recorded."+ );+ }+ await trx+ .updateTable("jobOperationBatch")+ .set({+ workCenterId: nextWorkCenterId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .execute();+ // Members mirror the header in BOTH directions: assigning pushes the+ // work center down, and clearing (nextWorkCenterId === null) clears it+ // on the members too — otherwise they keep a stale workCenterId the+ // header no longer has.+ await trx+ .updateTable("jobOperation")+ .set({ workCenterId: nextWorkCenterId, updatedBy: userId })+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .execute();+ return { updated: true };+ });+ break;+ }++ case "release": {+ result = await db.transaction().execute(async (trx) => {+ // FOR UPDATE serializes against concurrent release/complete/dissolve+ // on the same batch; the WHERE status='Planned' on the flip below is+ // the backstop.+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select(["id", "status", "workCenterId"])+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!batch) throw new NotFoundError("Batch not found");+ if (batch.status !== "Planned") {+ throw new Error(`Cannot release a batch with status ${batch.status}`);+ }+ // No work-center requirement: release must never wait on a human+ // picking a machine. The scheduler's batch pre-pass auto-selects the+ // earliest-finish work center among the process's candidates (the+ // same load-balancing rule single operations get) and persists it.+ const members = await trx+ .selectFrom("jobOperation")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (members.length === 0) {+ throw new Error("Cannot release an empty batch");+ }+ const released = await trx+ .updateTable("jobOperationBatch")+ .set({+ status: "Active",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Planned")+ .returning("id")+ .executeTakeFirst();+ if (!released) {+ throw new Error("Only a planned batch can be released");+ }+ return { success: true };+ });+ break;+ }++ case "unrelease": {+ result = await db.transaction().execute(async (trx) => {+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select(["id", "status"])+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!batch) throw new NotFoundError("Batch not found");+ if (batch.status !== "Active") {+ throw new Error(+ `Cannot unrelease a batch with status ${batch.status}`+ );+ }+ // Once anything has run against the batch, pulling it back off the+ // floor would orphan that recorded time.+ const batchEvents = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (batchEvents.length > 0) {+ throw new Error(+ "production has been recorded — complete the batch instead"+ );+ }+ const unreleased = await trx+ .updateTable("jobOperationBatch")+ .set({+ status: "Planned",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Active")+ .returning("id")+ .executeTakeFirst();+ if (!unreleased) {+ throw new Error("Only an active batch can be unreleased");+ }+ return { success: true };+ });+ break;+ }++ case "dissolve": {+ result = await db.transaction().execute(async (trx) => {+ const batchEvents = await trx+ .selectFrom("productionEvent")+ .select("id")+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .limit(1)+ .execute();+ if (batchEvents.length > 0) {+ throw new Error(+ "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."+ );+ }+ const members = await trx+ .updateTable("jobOperation")+ .set({ jobOperationBatchId: null, updatedBy: userId })+ .where("jobOperationBatchId", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .returning("id")+ .execute();+ await trx+ .deleteFrom("jobOperationBatch")+ .where("id", "=", payload.batchId)+ .where("companyId", "=", companyId)+ .execute();+ return { dissolved: members.length };+ });+ break;+ }++ case "complete": {+ result = await completeBatch(db, {+ companyId,+ userId,+ batchId: payload.batchId,+ members: payload.members+ });+ break;+ }+ }++ return { success: true, ...result };+ }++++export type BulkDeleteJobsResult = BulkDeleteResult;++++/**++ * Deletes the jobs the table's bulk Delete may delete: Draft, Planned, Due++ * Today and Overdue. The status filter is part of the DELETE, so a job that++ * moved on since it was selected stays. The caller checks the++ * `delete: production` permission.++ */++export function bulkDeleteJobs({++ client,++ jobIds,++ companyId++}: {++ client: SupabaseClient<Database>;++ jobIds: string[];++ companyId: string;++}): Promise<BulkDeleteJobsResult> {++ return bulkDeleteByStatus({++ ids: jobIds,++ companyId,++ label: "jobs",++ deleteChunk: (ids) =>++ client++ .from("job")++ .delete()++ .in("id", ids)++ .eq("companyId", companyId)++ .in("status", [...JOB_BULK_DELETABLE_STATUSES])++ .select("id")++ });++}diff --cc apps/erp/app/modules/production/ui/Batches/BatchesTable.tsxindex 2ba46e556e,3509cfe9d9..62e8e8fb8e--- a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx+++ b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx@@@ -34,22 -35,13 +35,24 @@@ importimport { Link, useFetcher, useNavigate } from "react-router";import { DateTime, Hyperlink, ItemThumbnail, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import {+ useAllMatchingLimitLabel,+ useBulkStartToast+} from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";+ import type { action as releaseBatchesAction } from "~/routes/x+/production+/batches.release";+import {+ bulkSelectionBody,+ isOverAllMatchingLimit+} from "~/utils/bulk-selection";import { path } from "~/utils/path";+import { ALL_MATCHING_RELEASE_LIMIT } from "~/utils/table-jobs";+import { isBatchDissolvable, isBatchReleasable } from "../../production.models";import type { JobOperationBatch } from "../../types";import { BatchReleaseModal } from "./BatchReleaseModal";+ import { useBatchRelease } from "./useBatchRelease";type BatchesTableProps = {data: JobOperationBatch[];@@@ -260,55 -204,27 +224,41 @@@ const BatchesTable = memo(({ data, coun// Planned → Active flip; Active/Completing/Completed batches are already on or// off the floor). Posts the ids to the release action, which recalcs member// jobs, releases each, and notifies the scheduler; we toast the summary.- const releaseBatchesFetcher = useFetcher<{- success?: boolean;- message?: string;- background?: boolean;- released?: number;- failed?: { readableId: string; message: string }[];- }>();- const wasReleasingBatches = useRef(false);- useEffect(() => {- if (releaseBatchesFetcher.state !== "idle") {- wasReleasingBatches.current = true;- return;- }- if (!wasReleasingBatches.current) return;- wasReleasingBatches.current = false;- const d = releaseBatchesFetcher.data;- if (!d || showBulkStart(d)) return;- if (d.released) {- toast.success(countMessages.released(d.released));- }- if (d.failed?.length) {- toast.error(- t`Could not release ${d.failed.length}: ${d.failed- .map((f) => f.readableId)- .join(", ")}`- );+ const releaseBatchesFetcher = useAction<typeof releaseBatchesAction>({- onSuccess: ({ data }) => {++ onSuccess: (result) => {++ if (showBulkStart(result)) return;++ const { data } = result;+ if (!data) return;+ if (data.released.length) {+ toast.success(countMessages.released(data.released.length));+ }+ if (data.failed.length) {+ toast.error(+ t`Could not release ${data.failed.length}: ${data.failed+ .map((f) => `${f.readableId} (${f.message})`)+ .join(", ")}`+ );+ }++ },++ onError: (result) => {++ showBulkStart(result);}- }, [- releaseBatchesFetcher.state,- releaseBatchesFetcher.data,- t,- countMessages,- showBulkStart- ]);+ });const renderActions = useCallback(- (selectedRows: JobOperationBatch[]) => {- const releasable = selectedRows.filter((r) => r.status === "Planned");- const dissolvable = selectedRows.filter(- (r) => r.status === "Planned" || r.status === "Active"+ (selectedRows: JobOperationBatch[], scope?: BulkActionScope) => {+ const releasable = selectedRows.filter((r) =>+ isBatchReleasable(r.status)+ );+ const dissolvable = selectedRows.filter((r) =>+ isBatchDissolvable(r.status)+ );+ // Every matching row: the server picks the batches each action may act+ // on and skips the rest. Release runs on at most 2,000 of them.+ const allMatching = scope?.allMatching;+ const overReleaseLimit = isOverAllMatchingLimit(+ scope,+ ALL_MATCHING_RELEASE_LIMIT);return (<DropdownMenuContent align="end" className="min-w-[220px]">diff --cc apps/erp/app/modules/production/ui/Jobs/JobsTable.tsxindex 915d00a7ed,7a7a7a6ff2..d867bbb045--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx@@@ -683,19 -723,15 +683,21 @@@ const JobsTable = memo((props: JobsTabl// Bulk release for the selected rows — Draft and Planned jobs only. Posts the// ids to the release action, which holds each job to the job page's release// checks and releases the ones that pass; we toast the summary.+ const showBulkStart = useBulkStartToast();+ const releaseLimitLabel = useAllMatchingLimitLabel(+ ALL_MATCHING_RELEASE_LIMIT+ );const releaseFetcher = useAction<typeof releaseAction>({- onSuccess: ({ data }) => {+ onSuccess: (result) => {- if (showBulkStart(result) || !("released" in result)) return;- if (result.released) {- toast.success(releasedJobsMessage(result.released));++ if (showBulkStart(result)) return;++ const { data } = result;+ if (!data) return;+ if (data.released.length) {+ toast.success(releasedJobsMessage(data.released.length));}- if (result.warnings.length) {+ if (data.warnings.length) {toast.error(- t`Released with problems: ${result.warnings+ t`Released with problems: ${data.warnings.map((w) => `${w.readableId} (${w.message})`).join(", ")}`);@@@ -707,12 -743,9 +709,12 @@@.join(", ")}`);}- if (!result.scheduled) {+ if (!data.scheduled) {toast.error(t`The schedule could not be updated after the release`);}+ },+ onError: (result) => {+ showBulkStart(result);}});diff --cc apps/erp/app/modules/production/ui/Jobs/job-release-logic.tsindex d25d08fa0a,26fdcb0128..3ee63a909a--- a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts+++ b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts@@@ -117,37 -135,35 +135,70 @@@ export function jobReleaseProblems(job];}+/**+ * The purchase order each supplier's outside operations start on in a bulk+ * release, and the suppliers whose jobs must be refused because the user has+ * to choose among their Draft POs.+ *+ * A background release runs in slices of 25 jobs. A slice reads the supplier's+ * Draft POs after an earlier slice has created one. `carried` (the map the+ * previous slice returned) names that PO, so the supplier keeps it instead of+ * asking for a choice. A carried PO that is no longer a Draft of its supplier+ * is ignored.+ */+export function bulkReleaseStartingPurchaseOrders(+ suppliers: {+ supplierId: string;+ draftPurchaseOrders: { id: string }[];+ }[],+ carried: Record<string, string> = {}+): {+ purchaseOrders: Record<string, string>;+ suppliersToChoose: Set<string>;+} {+ const purchaseOrders: Record<string, string> = {};+ const suppliersToChoose = new Set<string>();+ for (const { supplierId, draftPurchaseOrders } of suppliers) {+ const carriedId = carried[supplierId];+ if (carriedId && draftPurchaseOrders.some((po) => po.id === carriedId)) {+ purchaseOrders[supplierId] = carriedId;+ continue;+ }+ purchaseOrders[supplierId] = "new";+ if (draftPurchaseOrders.length > 0) suppliersToChoose.add(supplierId);+ }+ return { purchaseOrders, suppliersToChoose };+}+++ export type StorageUnitLine = {+ id: string;+ description: string;+ methodType: string | null;+ itemType: string | null;+ storageUnitId: string | null;+ item: {+ itemTrackingType: string | null;+ readableIdWithRevision: string | null;+ } | null;+ };++ export function materialsWithoutStorageUnit(+ lines: StorageUnitLine[]+ ): { id: string; description: string }[] {+ const byDescription = new Map<string, { id: string; description: string }>();+ for (const line of lines) {+ if (line.storageUnitId) continue;+ if (+ !needsPullFrom({+ methodType: line.methodType,+ itemType: line.itemType,+ itemTrackingType: line.item?.itemTrackingType ?? null+ })+ )+ continue;+ const description = line.item?.readableIdWithRevision || line.description;+ if (!byDescription.has(description))+ byDescription.set(description, { id: line.id, description });+ }+ return [...byDescription.values()];+ }diff --cc apps/erp/app/modules/purchasing/purchasing.models.test.tsindex 6c3345a657,efb362e931..64a0c667f3--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts@@@ -553,14 -552,100 +553,112 @@@ describe("lease action validators", ()});});+describe("isPurchaseOrderBulkDeletable", () => {+ it("accepts Draft and Planned only", () => {+ expect(isPurchaseOrderBulkDeletable("Draft")).toBe(true);+ expect(isPurchaseOrderBulkDeletable("Planned")).toBe(true);+ for (const status of purchaseOrderStatusType) {+ if (status === "Draft" || status === "Planned") continue;+ expect(isPurchaseOrderBulkDeletable(status)).toBe(false);+ }+ expect(isPurchaseOrderBulkDeletable(null)).toBe(false);+ });+});+++ describe("purchaseOrderDeleteRefusal", () => {+ it("allows a Draft or Planned order whoever asks", () => {+ for (const status of ["Draft", "Planned"]) {+ expect(+ purchaseOrderDeleteRefusal({ status, requestedBy: "u2", userId: "u1" })+ ).toBeNull();+ }+ });++ it("refuses every released or closed order", () => {+ for (const status of PURCHASE_ORDER_LOCKED_STATUSES) {+ expect(+ purchaseOrderDeleteRefusal({ status, requestedBy: null, userId: "u1" })+ ).toBe("status");+ }+ });++ it("lets only the requester delete an order that needs approval", () => {+ const needsApproval = { status: "Needs Approval", userId: "u1" };+ expect(+ purchaseOrderDeleteRefusal({ ...needsApproval, requestedBy: "u1" })+ ).toBeNull();+ expect(+ purchaseOrderDeleteRefusal({ ...needsApproval, requestedBy: "u2" })+ ).toBe("notRequester");+ // No pending request left: nothing to protect.+ expect(+ purchaseOrderDeleteRefusal({ ...needsApproval, requestedBy: null })+ ).toBeNull();+ });+ });++ describe("lockedReturnLineField", () => {+ const saved = {+ quantity: 4,+ itemId: "item-1",+ unitPrice: 10,+ restockFeePercent: 0.1,+ unitOfMeasureCode: "EA",+ purchaseOrderLineId: "pol-1",+ receiptLineId: null,+ purchaseInvoiceLineId: null+ };+ const unchanged = {+ quantity: 4,+ itemId: "item-1",+ unitPrice: 10,+ restockFeePercent: 0.1,+ unitOfMeasureCode: "EA",+ purchaseOrderLineId: "pol-1"+ };++ it("passes a change that moves no locked field", () => {+ expect(lockedReturnLineField(unchanged, saved)).toBeNull();+ });++ it("names the first locked field that moves", () => {+ expect(lockedReturnLineField({ ...unchanged, quantity: 5 }, saved)).toBe(+ "Quantity"+ );+ expect(+ lockedReturnLineField({ ...unchanged, receiptLineId: "rl-1" }, saved)+ ).toBe("Receipt line link");+ });++ it("ignores a field that was not sent", () => {+ expect(+ lockedReturnLineField(+ {+ ...unchanged,+ restockFeePercent: undefined,+ unitOfMeasureCode: undefined+ },+ saved+ )+ ).toBeNull();+ });+ });++ describe("splitRfqModelAttachments", () => {+ const model = (id: string, size: number) => ({ id, size });++ it("attaches what fits in line order and links the rest", () => {+ const { attach, link } = splitRfqModelAttachments(+ [model("a", 10), model("big", 30), model("b", 5)],+ 20+ );+ expect(attach.map((m) => m.id)).toEqual(["a", "b"]);+ expect(link.map((m) => m.id)).toEqual(["big"]);+ });++ it("links every model when documents already use the budget", () => {+ const { attach, link } = splitRfqModelAttachments([model("a", 1)], -5);+ expect(attach).toEqual([]);+ expect(link.map((m) => m.id)).toEqual(["a"]);+ });+ });diff --cc apps/erp/app/modules/purchasing/purchasing.service.tsindex 51853ecf1f,c745c5f970..b9f6278506--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@@ -2,8 -2,21 +2,22 @@@// 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 {+ InvalidInputError,+ isDataLayerError,+ NotFoundError,+ ServerFnError+ } from "@carbon/api/errors";+ import type { PermissionRule } from "@carbon/api/permissions";+ import {+ CarbonError,+ type ServiceContext+ } from "@carbon/api/service-fn.server";+ import { hasPermission } from "@carbon/auth";+ import { getUserClaims } from "@carbon/auth/users.server";import type { Database, Json } from "@carbon/database";import {++ Constants,fetchAllByIds,fetchAllFromTable,fetchAllRecords,@@@ -32,12 -103,24 +104,28 @@@ importtype PostgrestSingleResponse,type SupabaseClient} from "@supabase/supabase-js";- import { sql } from "kysely";- import type { z } from "zod";- import { createDocumentUploadUrl } from "~/modules/documents/documents.service";- import { getEmployeeJob } from "~/modules/people";+ import { sql, type Transaction } from "kysely";+ import { nanoid } from "nanoid";+ import { z } from "zod";+ import { getPaymentTermsList } from "~/modules/accounting/accounting.service";+ import {+ createDocumentUploadUrl,+ upsertDocument+ } from "~/modules/documents/documents.service";+ import { getEmployeeJob } from "~/modules/people/people.service";+ import {+ getCompany,+ getCompanySettings+ } from "~/modules/settings/settings.service";+ import { getUser } from "~/modules/users/users.service";++import {++ type BulkDeleteResult,++ bulkDeleteByStatus++} from "~/utils/bulk-delete.server";+ import { path } from "~/utils/path";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";+ import { stripSpecialCharacters } from "~/utils/string";import { sanitize } from "~/utils/supabase";import {getCurrencyByCode,@@@ -78,7 -170,11 +175,12 @@@ import typesupplierValidator} from "./purchasing.models";import {++ isPurchaseOrderBulkDeletable,leaseDetailFields,+ leaseLineColumns,+ leaseLinePaymentFields,+ type leaseLineValidator,+ leasePaymentTermFields,leaseTermColumns,PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES,PURCHASE_ORDER_LOCKED_STATUSES,@@@ -463,35 -538,6 +544,10 @@@ export async function getPurchaseOrder.single();}- /** @mcp update */- export async function finalizeSupplierQuote(- client: SupabaseClient<Database>,- db: Kysely<KyselyDatabase>,- payload: { supplierQuoteId: string; companyId: string; userId: string }- ) {- const { companyId, userId, ...input } = payload;- return serverFns- .as({ client, db, companyId, userId })- .invoke("finalize-supplier-quote", input);- }-- /** @mcp update */- export async function finalizePurchasingRfq(- client: SupabaseClient<Database>,- db: Kysely<KyselyDatabase>,- payload: { rfqId: string; companyId: string; userId: string }- ) {- const { companyId, userId, ...input } = payload;- return serverFns- .as({ client, db, companyId, userId })- .invoke("finalize-purchasing-rfq", input);- }-+export const PURCHASE_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "purchaseOrderId", ascending: false }]+};+- /** @mcp read */export async function getPurchaseOrders(client: SupabaseClient<Database>,companyId: string,@@@ -519,7 -562,13 +575,11 @@@query = query.eq("supplierId", args.supplierId);}+ if (args.status) {+ query = query.eq("status", args.status as never);+ }+- query = setGenericQueryFilters(query, args, [- { column: "purchaseOrderId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PURCHASE_ORDERS_PAGING);return query;}@@@ -639,17 -681,6 +692,16 @@@ export async function getPurchasingDocureturn merged;}+// What the row's Order / Make button offers (the grid RPC's orderQuantity,+// from MRP's open new-supply actions), then the part number so a page is+// stable when many rows have nothing to order.+export const PURCHASING_PLANNING_PAGING: Paging = {+ defaultSorts: [+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }+ ]+};+- /** @mcp read */export async function getPurchasingPlanning(client: SupabaseClient<Database>,locationId: string,@@@ -981,11 -1005,6 +1021,10 @@@ export async function getSupplierQuoteB.single();}+export const SUPPLIER_QUOTES_PAGING: Paging = {+ defaultSorts: [{ column: "supplierQuoteId", ascending: false }]+};+- /** @mcp read */export async function getSupplierQuotes(client: SupabaseClient<Database>,companyId: string,@@@ -1131,11 -1136,6 +1163,10 @@@ export async function getSupplierReport]);}+export const SUPPLIERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getSuppliers(client: SupabaseClient<Database>,companyId: string,@@@ -1196,11 -1196,6 +1225,10 @@@ export async function getSupplierType.single();}+export const SUPPLIER_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getSupplierTypes(client: SupabaseClient<Database>,companyId: string,@@@ -3169,11 -2921,6 +2952,10 @@@ export async function getPurchasingRFQreturn client.from("purchasingRfqs").select("*").eq("id", id).single();}+export const PURCHASING_RFQS_PAGING: Paging = {+ defaultSorts: [{ column: "rfqId", ascending: false }]+};+- /** @mcp read */export async function getPurchasingRFQs(client: SupabaseClient<Database>,companyId: string,@@@ -3874,11 -3563,6 +3596,10 @@@ export async function updatePurchaseOrd// ─── Purchase Return Orders (Supplier Returns) ───+export const PURCHASE_RETURN_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getPurchaseReturnOrders(client: SupabaseClient<Database>,companyId: string,@@@ -5309,11 -4957,6 +4992,10 @@@ function leaseRefusal(code: string, mes};}+export const LEASES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getLeases(client: SupabaseClient<Database>,companyId: string,@@@ -5733,3 -5373,5177 +5410,5211 @@@ export async function getLeaseRelatedDoerror: null};}+ /**+ * Server-only purchasing helpers: the lease writes that need a Kysely+ * transaction. Lives in a `.server.ts`, not the barrel-exported+ * `purchasing.service.ts`, because the module barrel is bundled for the+ * browser.+ */++ export type Trx = Transaction<KyselyDatabase>;++ /** A Draft lease, locked for the rest of the transaction. Throws when it is+ * missing or no longer a Draft: its rows were cut and measured at+ * activation, and change only with Modify. */+ async function lockDraftLease(+ trx: Trx,+ args: { leaseId: string; companyId: string; what: string }+ ) {+ const lease = await trx+ .selectFrom("lease")+ .select([+ "status",+ "currencyCode",+ "paymentFrequency",+ "paymentTiming",+ "annualEscalationPercent",+ sql<string>`"commencementDate"::text`.as("commencementDate"),+ sql<string | null>`"endDate"::text`.as("endDate"),+ sql<string>`"invoiceFromDate"::text`.as("invoiceFromDate")+ ])+ .where("id", "=", args.leaseId)+ .where("companyId", "=", args.companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!lease) throw new Error("Lease not found");+ if (lease.status !== "Draft") {+ throw new Error(+ `${args.what} changes only while the lease is Draft; modify an active lease instead`+ );+ }+ return lease;+ }++ /** Replaces the payment rows of a locked Draft lease's assets (one asset with+ * `leaseLineId`) with the ones its terms cut (`cutLeasePaymentRows`). An+ * asset with no payment has no rows. An open-ended lease is cut through one+ * period past today (`openEndedLeaseHorizon`); the daily job rolls it+ * forward from there. */+ async function cutDraftLeasePayments(+ trx: Trx,+ args: {+ lease: Awaited<ReturnType<typeof lockDraftLease>>;+ leaseId: string;+ leaseLineId?: string;+ companyId: string;+ userId: string;+ }+ ): Promise<number> {+ const { lease, leaseId, companyId, userId } = args;+ let linesQuery = trx+ .selectFrom("leaseLine")+ .select([+ "id",+ "paymentAmount",+ "purchaseOptionAmount",+ "purchaseOptionReasonablyCertain"+ ])+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId);+ if (args.leaseLineId) {+ linesQuery = linesQuery.where("id", "=", args.leaseLineId);+ }+ const lines = await linesQuery.execute();+ if (args.leaseLineId && lines.length === 0) {+ throw new Error("Asset not found");+ }+ if (lines.length === 0) return 0;++ const currency = await trx+ .selectFrom("currency")+ .innerJoin("company", "company.companyGroupId", "currency.companyGroupId")+ .select("currency.decimalPlaces")+ .where("company.id", "=", companyId)+ .where("currency.code", "=", lease.currencyCode)+ .executeTakeFirst();+ if (!currency) {+ throw new Error(`Currency ${lease.currencyCode} is not set up`);+ }+ const through = lease.endDate+ ? undefined+ : openEndedLeaseHorizon(+ lease.commencementDate,+ datetime.today(await getCompanyTimeZone(trx, companyId)).toString(),+ lease.paymentFrequency+ );++ const rows = lines+ .filter((line) => line.paymentAmount > 0)+ .flatMap(+ (line) =>+ cutLeasePaymentRows({+ lease,+ asset: line,+ decimals: currency.decimalPlaces,+ through+ }).rows+ );++ await trx+ .deleteFrom("leasePayment")+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .where(+ "leaseLineId",+ "in",+ lines.map((line) => line.id)+ )+ .execute();+ if (rows.length > 0) {+ await trx+ .insertInto("leasePayment")+ .values(+ rows.map((row) => ({ ...row, leaseId, companyId, createdBy: userId }))+ )+ .execute();+ }+ return rows.length;+ }++ /** Whether any of `fields` differs between a saved row and its new values. */+ function changed(+ saved: Record<string, unknown>,+ next: Record<string, unknown>,+ fields: readonly string[]+ ): boolean {+ return fields.some(+ (field) =>+ next[field] !== undefined &&+ String(saved[field] ?? "") !== String(next[field] ?? "")+ );+ }++ /**+ * Cuts a Draft lease's payment rows again from its terms, one set per asset+ * at the asset's payment amount, replacing the rows (and any edits to them)+ * in one transaction. Pass `leaseLineId` to cut one asset's rows only. A row+ * due before the lease's `invoiceFromDate` was paid outside Carbon and is+ * created `Skipped`, so the daily job never invoices it. A purchase option row+ * is added only when it is reasonably certain (it is then part of the lease+ * liability).+ */+ export async function regenerateLeasePayments(+ db: Kysely<KyselyDatabase>,+ args: {+ leaseId: string;+ leaseLineId?: string;+ companyId: string;+ userId: string;+ }+ ): Promise<{ count: number }> {+ return db.transaction().execute(async (trx) => {+ const lease = await lockDraftLease(trx, {+ leaseId: args.leaseId,+ companyId: args.companyId,+ what: "A payment row"+ });+ return { count: await cutDraftLeasePayments(trx, { ...args, lease }) };+ });+ }++ /**+ * Saves a Draft lease's terms and, when a term the payment rows are cut from+ * changed (`leasePaymentTermFields`), cuts every asset's rows again — one+ * transaction, so the rows never describe terms the lease no longer has. An+ * invoice-from date that still equals the commencement follows a new one+ * (`resolveLeaseDates`). `customFields` replaces the stored set; leave it out+ * to keep it.+ */+ export async function updateDraftLease(+ db: Kysely<KyselyDatabase>,+ args: {+ leaseId: string;+ companyId: string;+ userId: string;+ terms: Omit<z.infer<typeof leaseValidator>, "id" | "leaseId">;+ customFields?: Json;+ }+ ): Promise<{ paymentsCut: boolean }> {+ const { leaseId, companyId, userId } = args;+ return db.transaction().execute(async (trx) => {+ const saved = await lockDraftLease(trx, {+ leaseId,+ companyId,+ what: "A lease's terms"+ });+ const columns = leaseTermColumns(args.terms, saved);+ await trx+ .updateTable("lease")+ .set({+ ...columns,+ ...(args.customFields !== undefined+ ? { customFields: JSON.stringify(args.customFields) }+ : {}),+ updatedBy: userId,+ updatedAt: sql`now()`+ })+ .where("id", "=", leaseId)+ .where("companyId", "=", companyId)+ .execute();++ if (!changed(saved, columns, leasePaymentTermFields)) {+ return { paymentsCut: false };+ }+ await cutDraftLeasePayments(trx, {+ lease: { ...saved, ...columns },+ leaseId,+ companyId,+ userId+ });+ return { paymentsCut: true };+ });+ }++ /**+ * Adds an asset to a Draft lease (no `leaseLineId`) or changes one, and cuts+ * its payment rows again when it is new or a field they are cut from changed+ * (`leaseLinePaymentFields`) — one transaction. Only the asset's own fields+ * are written (`leaseLineColumns`), never its status, classification or+ * measurement.+ */+ export async function saveDraftLeaseLine(+ db: Kysely<KyselyDatabase>,+ args: {+ leaseId: string;+ leaseLineId?: string;+ companyId: string;+ userId: string;+ line: Omit<z.infer<typeof leaseLineValidator>, "id" | "leaseId">;+ }+ ): Promise<{ id: string; paymentsCut: boolean }> {+ const { leaseId, companyId, userId } = args;+ return db.transaction().execute(async (trx) => {+ const lease = await lockDraftLease(trx, {+ leaseId,+ companyId,+ what: "A leased asset"+ });+ const columns = leaseLineColumns(args.line);++ let id: string;+ let recut: boolean;+ if (args.leaseLineId) {+ const saved = await trx+ .selectFrom("leaseLine")+ .select([...leaseLinePaymentFields])+ .where("id", "=", args.leaseLineId)+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!saved) throw new Error("Asset not found");+ await trx+ .updateTable("leaseLine")+ .set({ ...columns, updatedBy: userId, updatedAt: sql`now()` })+ .where("id", "=", args.leaseLineId)+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .execute();+ id = args.leaseLineId;+ recut = changed(saved, columns, leaseLinePaymentFields);+ } else {+ const last = await trx+ .selectFrom("leaseLine")+ .select((eb) => eb.fn.max("sortOrder").as("sortOrder"))+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const inserted = await trx+ .insertInto("leaseLine")+ .values({+ ...columns,+ leaseId,+ sortOrder: Number(last?.sortOrder ?? 0) + 1,+ companyId,+ createdBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ id = inserted.id;+ recut = true;+ }++ if (recut) {+ await cutDraftLeasePayments(trx, {+ lease,+ leaseId,+ leaseLineId: id,+ companyId,+ userId+ });+ }+ return { id, paymentsCut: recut };+ });+ }++ /** Returns the lease payment rows billed by these purchase invoice lines to+ * Pending, so the next invoice run bills them again, stamped with who did+ * it. The `purchaseInvoiceLine_release_lease_payment` trigger releases a+ * row on ANY delete of its line (it cannot know the user); this runs first,+ * so the trigger then finds nothing left to release. */+ async function releaseLeasePayments(+ trx: Trx,+ args: { companyId: string; purchaseInvoiceLineIds: string[]; userId: string }+ ): Promise<void> {+ const { companyId, purchaseInvoiceLineIds, userId } = args;+ if (purchaseInvoiceLineIds.length === 0) return;+ await trx+ .updateTable("leasePayment")+ .set({+ status: "Pending",+ purchaseInvoiceLineId: null,+ updatedBy: userId,+ updatedAt: sql`now()`+ })+ .where("companyId", "=", companyId)+ .where("purchaseInvoiceLineId", "in", purchaseInvoiceLineIds)+ .execute();+ }++ /**+ * Deletes a Draft purchase invoice and, in the same transaction, returns the+ * lease payment rows it billed to Pending (see `releaseLeasePayments`).+ * Checked here under a row lock, because releasing a POSTED invoice's rows+ * would bill them twice. Throws on a missing or non-Draft invoice.+ */+ export async function deletePurchaseInvoiceReleasingLeases(+ db: Kysely<KyselyDatabase>,+ args: { companyId: string; invoiceId: string; userId: string }+ ): Promise<void> {+ const { companyId, invoiceId, userId } = args;+ await db.transaction().execute(async (trx) => {+ const invoice = await trx+ .selectFrom("purchaseInvoice")+ .select(["id", "status"])+ .where("id", "=", invoiceId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!invoice) throw new Error("Purchase invoice not found");+ if (invoice.status !== "Draft") {+ throw new Error(+ `Cannot delete purchase invoice with status "${invoice.status}". Only Draft invoices can be deleted.`+ );+ }++ const lines = await trx+ .selectFrom("purchaseInvoiceLine")+ .select("id")+ .where("invoiceId", "=", invoiceId)+ .where("companyId", "=", companyId)+ .where("leasePaymentId", "is not", null)+ .execute();+ await releaseLeasePayments(trx, {+ companyId,+ purchaseInvoiceLineIds: lines.map((line) => line.id),+ userId+ });++ await trx+ .deleteFrom("purchaseInvoice")+ .where("id", "=", invoiceId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ /** One line of a Draft purchase invoice, returning the lease payment row it+ * billed to Pending (see `deletePurchaseInvoiceReleasingLeases`). The line+ * must belong to `invoiceId` and that invoice must be Draft — checked here,+ * under a row lock. Throws otherwise. */+ export async function deletePurchaseInvoiceLineReleasingLeases(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ invoiceId: string;+ purchaseInvoiceLineId: string;+ userId: string;+ }+ ): Promise<void> {+ const { companyId, invoiceId, purchaseInvoiceLineId, userId } = args;+ await db.transaction().execute(async (trx) => {+ const line = await trx+ .selectFrom("purchaseInvoiceLine")+ .innerJoin("purchaseInvoice", (join) =>+ join+ .onRef("purchaseInvoice.id", "=", "purchaseInvoiceLine.invoiceId")+ .onRef(+ "purchaseInvoice.companyId",+ "=",+ "purchaseInvoiceLine.companyId"+ )+ )+ .select([+ "purchaseInvoiceLine.invoiceId as invoiceId",+ "purchaseInvoice.status as status"+ ])+ .where("purchaseInvoiceLine.id", "=", purchaseInvoiceLineId)+ .where("purchaseInvoiceLine.companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!line || line.invoiceId !== invoiceId) {+ throw new Error("Purchase invoice line not found on this invoice");+ }+ if (line.status !== "Draft") {+ throw new Error(+ `Cannot delete a line of a purchase invoice with status "${line.status}". Only Draft invoices can be edited.`+ );+ }++ await releaseLeasePayments(trx, {+ companyId,+ purchaseInvoiceLineIds: [purchaseInvoiceLineId],+ userId+ });+ await trx+ .deleteFrom("purchaseInvoiceLine")+ .where("id", "=", purchaseInvoiceLineId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ /** The date a lease that commenced before the accounting cutover opens on, as+ * `post-lease` activate resolves it (`resolveAccountingPeriod`,+ * "historical-with-shift"): the cutover, or the first day of the first open+ * period after it when the cutover's period is locked or closed. Read only —+ * activation is what locks or opens the period — so the Draft's Skipped+ * payment check (`skippedPaymentBlockers`) matches activation. */+ export async function leaseOpeningAsOf(+ db: Kysely<KyselyDatabase>,+ args: { companyId: string; cutoverDate: string }+ ): Promise<string> {+ const { companyId, cutoverDate } = args;+ const period = await db+ .selectFrom("accountingPeriod")+ .select(["closeStatus", "closedAt"])+ .where("companyId", "=", companyId)+ .where("startDate", "<=", cutoverDate)+ .where("endDate", ">=", cutoverDate)+ .orderBy("startDate")+ .orderBy("id")+ .executeTakeFirst();+ const closed =+ period &&+ (period.closeStatus === "Locked" ||+ period.closeStatus === "Closed" ||+ period.closedAt !== null);+ if (!closed) return cutoverDate;+ const next = await db+ .selectFrom("accountingPeriod")+ .select(sql<string>`"startDate"::text`.as("startDate"))+ .where("companyId", "=", companyId)+ .where("startDate", ">", cutoverDate)+ .where("closeStatus", "=", "Open")+ .where("closedAt", "is", null)+ .orderBy("startDate")+ .orderBy("id")+ .executeTakeFirst();+ // With no open period after it, activation refuses; the cutover stands.+ return next?.startDate ?? cutoverDate;+ }++ /** The lease page's "Invoice": drafts the purchase invoices the lease has+ * due, exactly as the daily job would — the `create-lease-invoices` server+ * function. */+ export async function generateLeaseInvoicesNow(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ /** `YYYY-MM-DD` in the company's timezone. */+ asOf: string;+ leaseId: string;+ }+ ): Promise<{ invoices: DraftedLeaseInvoice[]; invoiceIds: string[] }> {+ const { companyId, userId, asOf, leaseId } = args;+ const { invoices, invoiceIds, failures } = await invokePostingOrThrow(+ { db, companyId, userId },+ "create-lease-invoices",+ { asOf, leaseId },+ createLeaseInvoices+ );+ // One lease is billed here, so its failure is the action's failure.+ if (failures.length > 0) {+ throw new Error(failures.map((f) => f.error).join("; "));+ }+ return { invoices, invoiceIds };+ }++ /** Where a Draft lease is worked on: its setup wizard, for someone who can+ * edit it. Null for any other lease, or a viewer, who sees the lease page —+ * as `draftRentalAgreementSetupPath`. */+ export async function draftLeaseSetupPath(+ client: SupabaseClient<Database>,+ args: { companyId: string; userId: string; id: string }+ ): Promise<string | null> {+ const { companyId, userId, id } = args;+ const [lease, claims] = await Promise.all([+ client+ .from("lease")+ .select("status")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle(),+ getUserClaims(userId, companyId)+ ]);+ if (lease.data?.status !== "Draft") return null;+ if (!hasPermission(claims?.permissions, "purchasing", "update", companyId)) {+ return null;+ }+ return path.to.leaseSetup(id, "assets");+ }++ /** Signed links to a supplier interaction's documents, for an email. A file+ * that cannot be signed is logged and left out. */+ export async function interactionAttachments(+ client: SupabaseClient<Database>,+ companyId: string,+ interactionId: string+ ): Promise<{ filename: string; path: string; size?: number }[]> {+ const docs = await getSupplierInteractionDocuments(+ client,+ companyId,+ interactionId+ );+ return signedAttachments(+ client,+ companyId,+ docs.map((doc) => ({+ filename: doc.name,+ path: `${companyId}/supplier-interaction/${interactionId}/${doc.name}`,+ size: doc.metadata?.size as number | undefined+ }))+ );+ }++ export async function signedAttachments(+ client: SupabaseClient<Database>,+ companyId: string,+ files: { filename: string; path: string; size?: number }[]+ ): Promise<{ filename: string; path: string; size?: number }[]> {+ const signed = await async.map(files, async (file) => {+ const { data, error } = await storage(client)+ .company(companyId)+ .createSignedUrl(file.path, 3600);+ if (!data) {+ logger.error("Failed to create signed URL for attachment", {+ storagePath: file.path,+ error+ });+ return null;+ }+ return { filename: file.filename, path: data.signedUrl, size: file.size };+ });+ return signed.flatMap((file) => (file ? [file] : []));+ }++ /**+ * The original CAD file of each item's model, found where the model's Download button+ * finds it: `originalPath`, else a `modelPath` that is still the uploaded file,+ * in the company bucket or in temp-staging before compaction settles. A model+ * with no original, or only a compressed `.zst` raw no CAD tool opens, is left+ * out.+ */+ export async function getItemModelFiles(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ companyId: string,+ itemIds: string[]+ ): Promise<+ {+ modelId: string;+ filename: string;+ bucket: string;+ path: string;+ size: number;+ }[]+ > {+ if (itemIds.length === 0) return [];+ const items = await client+ .from("item")+ .select("id, modelUploadId")+ .in("id", itemIds)+ .eq("companyId", companyId);+ const modelByItem = new Map(+ (items.data ?? []).map((item) => [item.id, item.modelUploadId])+ );+ const modelIds = [+ ...new Set(+ itemIds.flatMap((id) => {+ const modelId = modelByItem.get(id);+ return modelId ? [modelId] : [];+ })+ )+ ];+ if (items.error || modelIds.length === 0) {+ if (items.error) {+ logger.error("Failed to read items for model attachments", {+ companyId,+ error: items.error+ });+ }+ return [];+ }+ const models = await client+ .from("modelUpload")+ .select("id, name, size, modelPath, originalPath")+ .in("id", modelIds)+ .eq("companyId", companyId);+ if (models.error) {+ logger.error("Failed to read models for attachments", {+ companyId,+ error: models.error+ });+ return [];+ }++ const candidates = models.data.flatMap((model) => {+ const path =+ model.originalPath ??+ (model.modelPath && isModelRawDownloadable(model.modelPath)+ ? model.modelPath+ : null);+ if (!path || getFileExtension(path) === "zst") return [];+ return [{ model, path }];+ });+ const buckets = await findStorageObjectBuckets(db, {+ names: candidates.map((candidate) => candidate.path),+ buckets: [getCompanyPrivateBucket(companyId), TEMP_STAGING_BUCKET]+ });++ const byId = new Map(+ candidates.flatMap(({ model, path }) => {+ const bucket = buckets.get(path);+ if (!bucket) return [];+ const extension = getFileExtension(path);+ const name = model.name || model.id;+ const filename = name.toLowerCase().endsWith(`.${extension}`)+ ? name+ : `${name}.${extension}`;+ return [+ [+ model.id,+ {+ modelId: model.id,+ filename,+ bucket,+ path,+ size: model.size ?? Number.POSITIVE_INFINITY+ }+ ]+ ] as const;+ })+ );+ return modelIds.flatMap((id) => {+ const file = byId.get(id);+ return file ? [file] : [];+ });+ }++ /** A signed link to a file `getOriginalModelFiles` found, valid `seconds`. */+ export async function signOriginalModelFile(+ client: SupabaseClient<Database>,+ companyId: string,+ file: { bucket: string; path: string },+ seconds: number+ ): Promise<string | null> {+ const bucket =+ file.bucket === TEMP_STAGING_BUCKET+ ? storage(client).from(TEMP_STAGING_BUCKET)+ : storage(client).company(companyId);+ const { data, error } = await bucket.createSignedUrl(file.path, seconds);+ if (!data) {+ logger.error("Failed to sign a model file", {+ companyId,+ storagePath: file.path,+ error+ });+ return null;+ }+ return data.signedUrl;+ }++ /** The statuses of records an edit is about to touch, for a lock check. */+ export async function statusesOf(+ ctx: ServiceContext,+ table:+ | "purchaseOrder"+ | "purchaseReturnOrder"+ | "purchasingRfq"+ | "supplierQuote",+ ids: string[]+ ): Promise<(string | null)[] | CarbonError> {+ const rows = await ctx.asCaller.supabase+ .from(table as "purchaseOrder")+ .select("status")+ .in("id", ids)+ .eq("companyId", ctx.company.id);+ if (rows.error) {+ return ctx.error("internal", "Failed to read the records", rows.error);+ }+ return rows.data.map((row) => row.status);+ }++ /**+ * The quote's share link: the existing one, or a new one, saved on the quote.+ * The link expires with the quote.+ */+ export async function supplierQuoteLink(+ ctx: ServiceContext,+ quote: {+ id: string;+ externalLinkId: string | null;+ supplierId: string | null;+ expirationDate: string | null;+ }+ ): Promise<string | CarbonError> {+ const client = ctx.asSystem.supabase;+ const link = await upsertExternalLink(client, {+ id: quote.externalLinkId ?? undefined,+ documentType: "SupplierQuote",+ documentId: quote.id,+ supplierId: quote.supplierId,+ expiresAt: quote.expirationDate,+ companyId: ctx.company.id+ });+ if (link.error || !link.data) {+ return ctx.error("internal", "Failed to create the share link", link.error);+ }+ if (quote.externalLinkId !== link.data.id) {+ await client+ .from("supplierQuote")+ .update({ externalLinkId: link.data.id })+ .eq("id", quote.id)+ .eq("companyId", ctx.company.id);+ }+ return link.data.id;+ }++ // ── Supplier quote share link ────────────────────────────────────────────────+ // The supplier answers through the quote's share link, which is the only+ // credential: these run as the system, in the quote's company, on behalf of+ // the quote's creator (`shareLinkContext`).++ /** The supplier quote a share link answers, read with the service role. */+ export async function sharedSupplierQuote(+ ctx: ServiceContext,+ supplierQuoteId: string+ ) {+ const quote = await ctx.asSystem.supabase+ .from("supplierQuote")+ .select("id, createdBy, exchangeRate, externalLinkId, externalNotes")+ .eq("id", supplierQuoteId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (quote.error) {+ return ctx.error("internal", "Failed to read the quote", quote.error);+ }+ if (!quote.data) return ctx.error("notFound", "Quote not found");+ return quote.data;+ }++ /** A refusal thrown by a Kysely write that guards its own rule ("Cannot+ * cancel a return order in Completed status"): its message is for the+ * person, unless it came from the data layer. */+ export function refusedBy(+ ctx: ServiceContext,+ err: unknown,+ fallback: string+ ): CarbonError {+ return err instanceof Error && !isDataLayerError(err)+ ? ctx.error("rule", err.message, err)+ : ctx.error("internal", fallback, err);+ }++ // ── Leases (lessee) ─────────────────────────────────────────────────────────++ /** A refusal unless the lease is the caller's company's (readable as the+ * caller). */+ async function leaseNotFound(+ ctx: ServiceContext,+ leaseId: string+ ): Promise<CarbonError | null> {+ const lease = await getLease(ctx.asCaller.supabase, leaseId, ctx.company.id);+ return lease.error || lease.data?.companyId !== ctx.company.id+ ? ctx.error("notFound", "Lease not found", lease.error)+ : null;+ }++ /** Runs one `post-lease` lifecycle action, which locks the lease and checks+ * its own rules in one transaction. */+ export async function postLease(+ ctx: ServiceContext,+ input: z.input<typeof postLeaseInput>,+ fallback: string+ ): Promise<CarbonError | null> {+ const missing = await leaseNotFound(ctx, input.leaseId);+ if (missing) return missing;+ const result = await invokePosting(+ {+ db: ctx.asSystem.pg,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ },+ "post-lease",+ input,+ postLeaseAction+ );+ return result.error ? fromServerFn(ctx, result.error, fallback) : null;+ }++ /**+ * Write (or clear) a Draft lease asset's classification override, audit+ * logged. An accounting decision, so it runs as the system on the caller's+ * `update: accounting`: an accountant need not hold the purchasing write the+ * lease's own policies ask for.+ */+ export async function writeClassificationOverride(+ ctx: ServiceContext,+ {+ leaseId,+ leaseLineId,+ override+ }: {+ leaseId: string;+ leaseLineId: string;+ override: {+ classification: "Operating" | "Finance";+ reason: string;+ } | null;+ }+ ): Promise<CarbonError | null> {+ const client = ctx.asSystem.supabase;+ const companyId = ctx.company.id;+ const [lease, line] = await Promise.all([+ client+ .from("lease")+ .select("id, status")+ .eq("id", leaseId)+ .eq("companyId", companyId)+ .maybeSingle(),+ client+ .from("leaseLine")+ .select("id, classificationOverride, classificationOverrideReason")+ .eq("id", leaseLineId)+ .eq("leaseId", leaseId)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);+ if (lease.error || line.error) {+ return ctx.error(+ "internal",+ "Leased asset not found",+ lease.error ?? line.error+ );+ }+ if (!lease.data || !line.data) {+ return ctx.error("notFound", "Leased asset not found");+ }+ const fixed = () =>+ ctx.error(+ "rule",+ "The classification is fixed once the lease is activated"+ );+ if (lease.data.status !== "Draft") return fixed();++ // Activation stamps `lesseeClassification`, so an unstamped asset is one+ // still to be classified: an asset activated since the read above matches+ // no row, and its commenced treatment is never overwritten.+ const update = await client+ .from("leaseLine")+ .update({+ classificationOverride: override?.classification ?? null,+ classificationOverrideReason: override?.reason ?? null,+ updatedBy: ctx.auditUserId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", leaseLineId)+ .eq("leaseId", leaseId)+ .eq("companyId", companyId)+ .is("lesseeClassification", null)+ .select("id")+ .maybeSingle();+ if (update.error) {+ return ctx.error(+ "internal",+ override+ ? "Failed to override the classification"+ : "Failed to remove the classification override",+ update.error+ );+ }+ if (!update.data) return fixed();++ // Best-effort: a failed audit write never undoes the change.+ try {+ await insertAuditLogEntries(client, companyId, [+ {+ tableName: "leaseLine",+ entityType: "lease",+ entityId: leaseId,+ recordId: leaseLineId,+ operation: "UPDATE",+ actorId: ctx.auditUserId,+ diff: {+ classificationOverride: {+ old: line.data.classificationOverride,+ new: override?.classification ?? null+ },+ classificationOverrideReason: {+ old: line.data.classificationOverrideReason,+ new: override?.reason ?? null+ }+ }+ }+ ]);+ } catch (err) {+ logger.warn("audit write skipped for a lease classification override", {+ error: err+ });+ }+ return null;+ }++ /** Cancels the orders' pending approval requests. Approved and Rejected ones+ * stay: they are the audit trail. Run it in the transaction that changes the+ * orders, so a failed change leaves the requests pending. */+ export async function cancelPendingApprovals(+ db: Kysely<KyselyDatabase>,+ {+ companyId,+ userId,+ purchaseOrderIds+ }: { companyId: string; userId: string; purchaseOrderIds: string[] }+ ) {+ if (purchaseOrderIds.length === 0) return [];+ return db+ .updateTable("approvalRequest")+ .set({+ status: "Cancelled",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("documentType", "=", "purchaseOrder")+ .where("documentId", "in", purchaseOrderIds)+ .where("companyId", "=", companyId)+ .where("status", "=", "Pending")+ .returning("id")+ .execute();+ }++ /** A file's size as the documents table stores it: whole kilobytes. */+ export function kilobytes(file: Buffer): number {+ return Math.round(file.byteLength / 1024);+ }++ type PurchaseOrderRow = NonNullable<+ Awaited<ReturnType<typeof getPurchaseOrder>>["data"]+ >;++ /**+ * Renders the order's PDF, stores it with the supplier interaction's files+ * and adds it as a document. The step that fails is the message.+ */+ export async function attachPurchaseOrderPdf(+ ctx: ServiceContext,+ { purchaseOrder, locale }: { purchaseOrder: PurchaseOrderRow; locale: string }+ ): Promise<{ fileName: string; path: string; size: number } | CarbonError> {+ const companyId = ctx.company.id;+ const purchaseOrderId = purchaseOrder.id!;+ let pdf: Awaited<ReturnType<typeof renderPurchaseOrderPdf>>;+ try {+ pdf = await renderPurchaseOrderPdf(ctx.asCaller.supabase, {+ companyId,+ companyGroupId: ctx.company.groupId,+ purchaseOrderId,+ locale+ });+ } catch (err) {+ return ctx.error("internal", "Failed to generate PDF", err);+ }++ const fileName = stripSpecialCharacters(+ `${getPurchaseOrderDisplayId(purchaseOrder)} - ${datetime+ .timestamp()+ .slice(0, -5)}.pdf`+ );+ const path = `${companyId}/supplier-interaction/${purchaseOrder.supplierInteractionId}/${fileName}`;+ const upload = await storage(ctx.asSystem.supabase)+ .company(companyId)+ .upload(path, pdf.body, {+ cacheControl: `${12 * 60 * 60}`,+ contentType: "application/pdf",+ upsert: true+ });+ if (upload.error) {+ return ctx.error("internal", "Failed to upload file", upload.error);+ }++ const size = kilobytes(pdf.body);+ const document = await upsertDocument(ctx.asSystem.supabase, {+ path,+ name: fileName,+ size,+ sourceDocument: "Purchase Order",+ sourceDocumentId: purchaseOrderId,+ readGroups: [ctx.auditUserId],+ writeGroups: [ctx.auditUserId],+ createdBy: ctx.auditUserId,+ companyId+ });+ if (document.error) {+ return ctx.error("internal", "Failed to create document", document.error);+ }+ return { fileName, path, size };+ }++ /**+ * The purchase order email to the supplier contact, copied to the buyer:+ * null when the contact has no email address.+ */+ export async function purchaseOrderEmail(+ ctx: ServiceContext,+ {+ purchaseOrderId,+ supplierContactId,+ locale+ }: { purchaseOrderId: string; supplierContactId: string; locale: string }+ ) {+ const client = ctx.asSystem.supabase;+ const companyId = ctx.company.id;+ const [+ company,+ contact,+ purchaseOrder,+ lines,+ locations,+ paymentTerms,+ buyer+ ] = await Promise.all([+ getCompany(client, companyId),+ getSupplierContact(client, supplierContactId, companyId),+ getPurchaseOrder(client, purchaseOrderId),+ getPurchaseOrderLines(client, purchaseOrderId),+ getPurchaseOrderLocations(client, purchaseOrderId),+ getPaymentTermsList(client, companyId),+ getUser(client, ctx.auditUserId)+ ]);+ if (!contact.data?.contact) throw new Error("Failed to get supplier contact");+ if (!company.data) throw new Error("Failed to get company");+ if (!buyer.data) throw new Error("Failed to get user");+ if (!purchaseOrder.data) throw new Error("Failed to get purchase order");+ if (!locations.data)+ throw new Error("Failed to get purchase order locations");+ if (!paymentTerms.data) throw new Error("Failed to get payment terms");+ const supplierEmail = contact.data.contact.email;+ if (!supplierEmail) return null;++ // Same decimals the PDF of this order uses.+ const currency = purchaseOrder.data.currencyCode+ ? await getCurrencyByCode(+ client,+ ctx.company.groupId,+ purchaseOrder.data.currencyCode+ )+ : null;+ const template = PurchaseOrderEmail({+ // @ts-expect-error TS2739 - TODO: fix type+ company: company.data,+ currencyDecimals: currency?.data?.decimalPlaces ?? null,+ locale,+ purchaseOrder: purchaseOrder.data,+ purchaseOrderLines: lines.data ?? [],+ purchaseOrderLocations: locations.data,+ recipient: {+ email: supplierEmail,+ firstName: contact.data.contact.firstName ?? undefined,+ lastName: contact.data.contact.lastName ?? undefined+ },+ sender: {+ email: buyer.data.email,+ firstName: buyer.data.firstName,+ lastName: buyer.data.lastName+ },+ paymentTerms: paymentTerms.data+ });+ return {+ to: [buyer.data.email, supplierEmail],+ from: buyer.data.email,+ subject: `Purchase Order ${getPurchaseOrderDisplayId(purchaseOrder.data)} from ${company.data.name}`,+ html: await renderAsync(template),+ text: await renderAsync(template, { plainText: true }),+ purchaseOrder: purchaseOrder.data,+ lines: lines.data ?? []+ };+ }++ /** Updates the supplier prices from the order when the company updates them+ * on finalize. A failure is logged: the order stands. */+ export async function updatePricesOnFinalize(+ ctx: ServiceContext,+ purchaseOrderId: string+ ) {+ const settings = await getCompanySettings(+ ctx.asSystem.supabase,+ ctx.company.id+ );+ if (settings.data?.purchasePriceUpdateTiming !== "Purchase Order Finalize") {+ return;+ }+ const update = await invokePosting(+ {+ db: ctx.asSystem.pg,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ },+ "update-purchased-prices",+ {+ purchaseOrderId,+ source: "purchaseOrder",+ updatePrices: true,+ updateLeadTimes: false+ },+ updatePurchasedPrices+ );+ if (update.error) {+ logger.error("Failed to update purchased prices", { error: update.error });+ }+ }++ /** After an approval: the PDF, the email and the prices, each logged when it+ * fails. */+ export async function releaseApprovedPurchaseOrder(+ ctx: ServiceContext,+ {+ purchaseOrderId,+ notification,+ supplierContact,+ cc,+ locale+ }: {+ purchaseOrderId: string;+ notification?: "Email" | "None";+ supplierContact?: string;+ cc?: string[];+ locale?: string;+ }+ ) {+ const purchaseOrder = await getPurchaseOrder(+ ctx.asSystem.supabase,+ purchaseOrderId+ );+ if (!purchaseOrder.data) return;++ const pdf = await attachPurchaseOrderPdf(ctx, {+ purchaseOrder: purchaseOrder.data,+ locale: locale ?? "en-US"+ });+ if (pdf instanceof CarbonError) {+ logger.error("Failed to generate PDF after approval", { error: pdf.cause });+ } else if (notification === "Email" && supplierContact) {+ try {+ const email = await purchaseOrderEmail(ctx, {+ purchaseOrderId,+ supplierContactId: supplierContact,+ locale: locale ?? "en-US"+ });+ if (email) {+ const [attachment] = await signedAttachments(+ ctx.asSystem.supabase,+ ctx.company.id,+ [{ filename: pdf.fileName, path: pdf.path }]+ );+ await trigger("send-email", {+ to: email.to,+ cc: cc?.length ? cc : undefined,+ from: email.from,+ subject: email.subject,+ html: email.html,+ text: email.text,+ attachments: attachment ? [attachment] : undefined,+ companyId: ctx.company.id+ });+ }+ } catch (err) {+ logger.error("Failed to send email after approval", { error: err });+ }+ }++ await updatePricesOnFinalize(ctx, purchaseOrderId);+ }++ // ── Purchasing planning ─────────────────────────────────────────────────────++ /**+ * The date the supplier promised for a PO line: the line's own, else its+ * order's delivery date — the same COALESCE the `openPurchaseOrderLines` view+ * gives MRP. MRP dates the line by this ahead of the required date, so a+ * planning date change (which writes the required date) cannot move it.+ */+ export function promisedDateOf(line: {+ promisedDate: string | null;+ receiptPromisedDate: string | null | undefined;+ }): string | null {+ return line.promisedDate ?? line.receiptPromisedDate ?? null;+ }++ /** Sums forecasts that land on the same (item, location, period). */+ export function deduplicateForecasts<+ T extends {+ itemId: string;+ locationId: string;+ periodId: string;+ forecastQuantity: number;+ }+ >(forecasts: T[]): T[] {+ const map = new Map<string, T>();+ for (const forecast of forecasts) {+ const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;+ const existing = map.get(key);+ if (existing) {+ existing.forecastQuantity += forecast.forecastQuantity;+ } else {+ map.set(key, { ...forecast });+ }+ }+ return Array.from(map.values());+ }++ /** How many of `requested` worklist rows a dismiss, reopen or assign changed,+ * as the message; a refusal when none did. */+ export function worklistChange(+ ctx: ServiceContext,+ verb: "Dismissed" | "Reopened" | "Assigned",+ changed: number,+ requested: number+ ) {+ if (changed === 0) {+ const what = {+ Dismissed: "dismiss",+ Reopened: "reopen",+ Assigned: "assign"+ }[verb];+ return ctx.error(+ "conflict",+ `Nothing to ${what} — these actions changed since the page loaded`+ );+ }+ return {+ changed,+ message: `${verb} ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < requested+ ? `; ${requested - changed} changed since the page loaded`+ : ""+ }`+ };+ }+ export const finalizeSupplierQuoteInput = z.object({+ supplierQuoteId: z.string()+ });++ export const finalizeSupplierQuotePermission = {+ create: "purchasing"+ } satisfies PermissionRule<z.output<typeof finalizeSupplierQuoteInput>>;++ /**+ * Marks a supplier quote Active and copies its prices into the supplier's+ * price list, in one transaction: a supplier part per quoted item (created+ * when the supplier has none), one price break per quoted quantity, and the+ * lowest quoted price as the part's own.+ *+ * Prices are recorded as quoted — per purchase unit, in the quote's currency.+ * A part created here takes the quote's currency; an existing part in another+ * currency gets the price converted into its own.+ */+ export async function finalizeSupplierQuote(+ ctx: ServiceContext,+ raw: z.input<typeof finalizeSupplierQuoteInput>+ ) {+ const { supplierQuoteId } = finalizeSupplierQuoteInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ await db.transaction().execute(async (trx) => {+ const quote = await trx+ .selectFrom("supplierQuote")+ .select(["id", "supplierId", "currencyCode", "exchangeRate"])+ .where("id", "=", supplierQuoteId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!quote) throw new NotFoundError("Supplier quote not found");+ if (!quote.supplierId) {+ throw new ServerFnError("Supplier quote has no supplier", 400);+ }+ const supplierId = quote.supplierId;++ const lines = await selectRows(+ trx,+ "supplierQuoteLine",+ { supplierQuoteId, companyId },+ {+ columns: [+ "id",+ "itemId",+ "supplierPartId",+ "purchaseUnitOfMeasureCode",+ "conversionFactor"+ ],+ orderBy: ["sortOrder", "id"]+ }+ );+ const prices = await many(trx, "supplierQuoteLinePrice", {+ supplierQuoteId,+ companyId+ });+ const pricesByLine = groupBy(+ prices.data,+ (price) => price.supplierQuoteLineId+ );++ // Every line needs one quantity with a price and a lead time: a price+ // list entry without either is worse than none.+ const unpriced = lines.find(+ (line) =>+ !(pricesByLine[line.id] ?? []).some(+ (price) => price.supplierUnitPrice && price.leadTime+ )+ );+ if (unpriced) {+ const item = unpriced.itemId+ ? await trx+ .selectFrom("item")+ .select("readableIdWithRevision")+ .where("id", "=", unpriced.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : undefined;+ throw new InvalidInputError(+ `Line ${item?.readableIdWithRevision ?? unpriced.id} must have at least one quantity with price and lead time`+ );+ }++ await trx+ .updateTable("supplierQuote")+ .set({+ status: "Active",+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", supplierQuoteId)+ .where("companyId", "=", companyId)+ .execute();++ const pricedLines = lines.flatMap((line) => {+ const linePrices = pricesByLine[line.id] ?? [];+ return line.itemId && linePrices.length > 0+ ? [{ ...line, itemId: line.itemId, prices: linePrices }]+ : [];+ });+ if (pricedLines.length === 0) return;++ // An item the supplier already has a part for keeps that part as it is.+ await trx+ .insertInto("supplierPart")+ .values(+ pricedLines.map((line) => ({+ itemId: line.itemId,+ supplierId,+ supplierPartId: line.supplierPartId ?? undefined,+ supplierUnitOfMeasureCode:+ line.purchaseUnitOfMeasureCode ?? undefined,+ conversionFactor: line.conversionFactor ?? 1,+ currencyCode: quote.currencyCode,+ companyId,+ createdBy: userId+ }))+ )+ .onConflict((oc) =>+ oc.columns(["itemId", "supplierId", "companyId"]).doNothing()+ )+ .execute();++ const supplierParts = await trx+ .selectFrom("supplierPart")+ .select(["id", "itemId", "currencyCode"])+ .where("supplierId", "=", supplierId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", [+ ...new Set(pricedLines.map((line) => line.itemId))+ ])+ .execute();+ const supplierPartByItem = new Map(+ supplierParts.map((part) => [part.itemId, part])+ );+ const converter = await getSupplierPartPriceConverter(+ trx,+ companyId,+ {+ currencyCode: quote.currencyCode,+ exchangeRate: quote.exchangeRate ?? 1+ },+ supplierParts.map((part) => part.currencyCode)+ );++ // Keyed by (part, quantity): when two lines quote one item at one+ // quantity the later line wins, as it did when these were written in turn.+ const priceBreaks = new Map<+ string,+ {+ supplierPartId: string;+ quantity: number;+ supplierUnitPrice: number;+ leadTime: number;+ }+ >();+ const updatedAt = datetime.timestamp();++ for (const line of pricedLines) {+ const supplierPart = supplierPartByItem.get(line.itemId);+ if (!supplierPart) {+ throw new ServerFnError("Failed to create supplier part", 500);+ }+ const supplierPartId = supplierPart.id;+ // Quote prices are per purchase unit, the basis a supplier part keeps.+ const toPartCurrency = (price: number) =>+ converter.toPartCurrency(price, supplierPart.currencyCode);++ for (const price of line.prices) {+ if (!price.supplierUnitPrice) continue;+ const quantity = price.quantity ?? 1;+ priceBreaks.set(`${supplierPartId}:${quantity}`, {+ supplierPartId,+ quantity,+ supplierUnitPrice: toPartCurrency(price.supplierUnitPrice),+ leadTime: price.leadTime ?? 0+ });+ }++ const bestPrice = line.prices+ .filter((price) => !!price.supplierUnitPrice)+ .sort((a, b) => a.supplierUnitPrice - b.supplierUnitPrice)[0];+ if (bestPrice) {+ await trx+ .updateTable("supplierPart")+ .set({+ supplierUnitPrice: toPartCurrency(bestPrice.supplierUnitPrice),+ minimumOrderQuantity: bestPrice.quantity ?? 1+ })+ .where("id", "=", supplierPartId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (priceBreaks.size > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ [...priceBreaks.values()].map((priceBreak) => ({+ ...priceBreak,+ sourceType: "Quote" as const,+ sourceDocumentId: supplierQuoteId,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ updatedAt+ }))+ )+ .onConflict((oc) =>+ oc.columns(["supplierPartId", "quantity"]).doUpdateSet((eb) => ({+ supplierUnitPrice: eb.ref("excluded.supplierUnitPrice"),+ leadTime: eb.ref("excluded.leadTime"),+ sourceType: eb.ref("excluded.sourceType"),+ sourceDocumentId: eb.ref("excluded.sourceDocumentId"),+ companyId: eb.ref("excluded.companyId"),+ createdBy: eb.ref("excluded.createdBy"),+ updatedBy: eb.ref("excluded.updatedBy"),+ updatedAt: eb.ref("excluded.updatedAt")+ }))+ )+ .execute();+ }+ });++ return { success: true };+ }+ export const finalizePurchasingRfqInput = z.object({+ rfqId: z.string()+ });++ const ITEM_TYPES = [+ "Part",+ "Material",+ "Tool",+ "Consumable",+ "Service"+ ] as const;++ export type FinalizedSupplierQuote = {+ id: string;+ supplierQuoteId: string;+ supplierId: string;+ externalLinkId: string;+ };++ export const finalizePurchasingRfqPermission = {+ create: "purchasing"+ } satisfies PermissionRule<z.output<typeof finalizePurchasingRfqInput>>;++ /**+ * Sends a purchasing RFQ out: one Draft supplier quote per RFQ supplier, each+ * with its share link and a line per RFQ line that names an item, then the RFQ+ * is marked Requested. One transaction — a failure leaves no quotes behind,+ * and only a Draft RFQ is finalized, so a repeated request creates nothing.+ */+ export async function finalizePurchasingRfq(+ ctx: ServiceContext,+ raw: z.input<typeof finalizePurchasingRfqInput>+ ) {+ const { rfqId } = finalizePurchasingRfqInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const quotes = await db.transaction().execute(async (trx) => {+ // Locked: a second submit waits here, then finds the RFQ Requested.+ const rfq = await trx+ .selectFrom("purchasingRfq")+ .select(["id", "status"])+ .where("id", "=", rfqId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!rfq) throw new NotFoundError("RFQ not found");+ if (rfq.status !== "Draft") {+ throw new InvalidInputError(+ `Only a draft RFQ can be finalized; this one is ${rfq.status}`+ );+ }++ const suppliers = await trx+ .selectFrom("purchasingRfqSupplier")+ .select("supplierId")+ .where("purchasingRfqId", "=", rfqId)+ .where("companyId", "=", companyId)+ .orderBy("createdAt")+ .orderBy("id")+ .execute();+ if (suppliers.length === 0) {+ throw new InvalidInputError("No suppliers found for this RFQ");+ }++ const lines = await selectRows(+ trx,+ "purchasingRfqLines",+ { purchasingRfqId: rfqId, companyId },+ { orderBy: ["order"] }+ );+ if (lines.length === 0) {+ throw new InvalidInputError("No line items found for this RFQ");+ }+ // supplierQuoteLine.itemId is NOT NULL+ const quotableLines = lines.flatMap((line) =>+ line.itemId ? [{ ...line, itemId: line.itemId }] : []+ );++ const created: FinalizedSupplierQuote[] = [];+ for (const { supplierId } of suppliers) {+ const supplierQuoteId = await getNextSequence(+ trx,+ "supplierQuote",+ companyId+ );+ const interaction = await trx+ .insertInto("supplierInteraction")+ .values({ companyId, supplierId })+ .returning("id")+ .executeTakeFirstOrThrow();+ const now = datetime.timestamp();+ const quote = await trx+ .insertInto("supplierQuote")+ .values({+ supplierQuoteId,+ supplierId,+ supplierInteractionId: interaction.id,+ status: "Draft",+ exchangeRate: 1,+ exchangeRateUpdatedAt: now,+ quotedDate: now,+ supplierQuoteType: "Purchase",+ companyId,+ createdBy: userId,+ updatedBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ const externalLink = await trx+ .insertInto("externalLink")+ .values({+ documentType: "SupplierQuote",+ documentId: quote.id,+ supplierId,+ companyId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ await trx+ .updateTable("supplierQuote")+ .set({ externalLinkId: externalLink.id })+ .where("id", "=", quote.id)+ .where("companyId", "=", companyId)+ .execute();++ if (quotableLines.length > 0) {+ await trx+ .insertInto("supplierQuoteLine")+ .values(+ quotableLines.map((line, index) => ({+ supplierQuoteId: quote.id,+ supplierQuoteLineType: ITEM_TYPES.some(+ (type) => type === line.itemType+ )+ ? (line.itemType as string)+ : "Part",+ itemId: line.itemId,+ description: line.description ?? "",+ quantity: line.quantity ?? [1],+ inventoryUnitOfMeasureCode:+ line.inventoryUnitOfMeasureCode ?? "EA",+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode ?? "EA",+ conversionFactor: line.conversionFactor ?? 1,+ sortOrder: index + 1,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ await trx+ .insertInto("purchasingRfqToSupplierQuote")+ .values({+ purchasingRfqId: rfqId,+ supplierQuoteId: quote.id,+ companyId+ })+ .execute();++ created.push({+ id: quote.id,+ supplierQuoteId,+ supplierId,+ externalLinkId: externalLink.id+ });+ }++ await trx+ .updateTable("purchasingRfq")+ .set({+ status: "Requested",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", rfqId)+ .where("companyId", "=", companyId)+ .execute();++ return created;+ });++ return { quotes };+ }+ const updatePurchasedPricesLogger = getLogger(+ "server-functions",+ "update-purchased-prices"+ );++ export const updatePurchasedPricesInput = z.discriminatedUnion("source", [+ z.object({+ source: z.literal("purchaseOrder"),+ purchaseOrderId: z.string(),+ updatePrices: z.boolean().optional(),+ updateLeadTimes: z.boolean().optional()+ }),+ z.object({+ source: z.literal("purchaseInvoice"),+ invoiceId: z.string(),+ updatePrices: z.boolean().optional(),+ updateLeadTimes: z.boolean().optional()+ })+ ]);++ interface PurchaseLineData {+ itemId: string | null;+ jobOperationId: string | null;+ /** Base currency, per purchase unit. */+ unitPrice: number;+ /** The document's currency, per purchase unit — what the supplier charged. */+ supplierUnitPrice: number;+ quantity: number;+ conversionFactor: number | null;+ purchaseUnitOfMeasureCode: string | null;+ }++ /** Whole days from order to delivery (`YYYY-MM-DD` each); 0 when either is unparseable. */+ const calculateLeadTimeInDays = (+ orderDate: string,+ deliveryDate: string+ ): number => {+ try {+ return Math.max(0, parseDate(deliveryDate).compare(parseDate(orderDate)));+ } catch {+ return 0;+ }+ };++ export const updatePurchasedPricesPermission = {+ update: "purchasing"+ } satisfies PermissionRule<z.output<typeof updatePurchasedPricesInput>>;++ export async function updatePurchasedPrices(+ ctx: ServiceContext,+ raw: z.input<typeof updatePurchasedPricesInput>+ ) {+ const parsedPayload = updatePurchasedPricesInput.parse(raw);++ const { source } = parsedPayload;+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const shouldUpdatePrices = parsedPayload.updatePrices ?? true;+ const shouldUpdateLeadTimes = parsedPayload.updateLeadTimes ?? false;++ updatePurchasedPricesLogger.info("update-purchased-prices", {+ source,+ companyId,+ shouldUpdatePrices,+ shouldUpdateLeadTimes+ });++ let supplierId: string;+ let lines: PurchaseLineData[];+ let documentCurrency: { currencyCode: string | null; exchangeRate: number };++ switch (source) {+ case "purchaseOrder": {+ const { purchaseOrderId } = parsedPayload;++ updatePurchasedPricesLogger.info("update-purchased-prices", {+ source,+ purchaseOrderId,+ companyId+ });++ const [purchaseOrder, purchaseOrderLines] = await inOrder([+ () =>+ maybeSingle(db, "purchaseOrder", {+ id: purchaseOrderId,+ companyId+ }),+ () => many(db, "purchaseOrderLine", { purchaseOrderId, companyId })+ ]);++ if (purchaseOrder.error) throw new Error("Failed to fetch purchaseOrder");+ if (!purchaseOrder.data)+ throw new NotFoundError("Purchase order not found");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");+ if (!purchaseOrder.data.supplierId)+ throw new Error("Purchase order has no supplier");++ supplierId = purchaseOrder.data.supplierId;+ documentCurrency = {+ currencyCode: purchaseOrder.data.currencyCode,+ exchangeRate: purchaseOrder.data.exchangeRate ?? 1+ };+ lines = purchaseOrderLines.data+ .map((line) => ({+ itemId: line.itemId,+ jobOperationId: null,+ unitPrice: line.unitPrice ?? 0,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,+ quantity: (line.purchaseQuantity ?? 0) * (line.conversionFactor ?? 1),+ conversionFactor: line.conversionFactor,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode+ }))+ .filter((line) => line.quantity > 0);++ if (shouldUpdatePrices) {+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ // Delete any existing cost ledger entries for this PO (handles re-finalization)+ await db+ .deleteFrom("costLedger")+ .where("documentType", "=", "Purchase Order")+ .where("documentId", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .execute();++ // Create new cost ledger entries for each line item. These are+ // planning/cost-history rows, NOT inventory layers — real layers+ // are created at receipt posting. remainingQuantity stays 0 so+ // FIFO/LIFO consumption can never eat unreceived stock.+ const costLedgerInserts = lines+ .filter((line) => line.itemId && line.unitPrice !== 0)+ .map((line) => ({+ itemLedgerType: "Purchase" as const,+ costLedgerType: "Direct Cost" as const,+ adjustment: false,+ documentType: "Purchase Order" as const,+ documentId: purchaseOrderId,+ itemId: line.itemId!,+ quantity: line.quantity,+ cost:+ (line.quantity / (line.conversionFactor ?? 1)) * line.unitPrice,+ remainingQuantity: 0,+ postingDate: today,+ supplierId,+ companyId+ }));++ if (costLedgerInserts.length > 0) {+ await db.insertInto("costLedger").values(costLedgerInserts).execute();+ }+ }++ break;+ }++ case "purchaseInvoice": {+ const { invoiceId } = parsedPayload;++ updatePurchasedPricesLogger.info("update-purchased-prices", {+ source,+ invoiceId,+ companyId+ });++ const [purchaseInvoice, purchaseInvoiceLines] = await inOrder([+ () => maybeSingle(db, "purchaseInvoice", { id: invoiceId, companyId }),+ () => many(db, "purchaseInvoiceLine", { invoiceId, companyId })+ ]);++ if (purchaseInvoice.error)+ throw new Error("Failed to fetch purchaseInvoice");+ if (!purchaseInvoice.data)+ throw new NotFoundError("Purchase invoice not found");+ if (purchaseInvoiceLines.error)+ throw new Error("Failed to fetch invoice lines");+ if (!purchaseInvoice.data.supplierId)+ throw new Error("Purchase invoice has no supplier");++ supplierId = purchaseInvoice.data.supplierId;+ documentCurrency = {+ currencyCode: purchaseInvoice.data.currencyCode,+ exchangeRate: purchaseInvoice.data.exchangeRate ?? 1+ };+ lines = purchaseInvoiceLines.data+ .map((line) => ({+ itemId: line.itemId,+ jobOperationId: line.jobOperationId,+ unitPrice: line.unitPrice ?? 0,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,+ quantity: (line.quantity ?? 0) * (line.conversionFactor ?? 1),+ conversionFactor: line.conversionFactor,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode+ }))+ .filter((line) => line.quantity > 0);+ break;+ }+ }++ const itemIds = Array.from(+ new Set(+ lines+ .filter((line) => Boolean(line.itemId))+ .map((line) => line.itemId as string)+ )+ );++ // Rolling one-year window over postingDate, anchored on the company's+ // calendar day (postingDate itself is company-tz derived).+ const dateOneYearAgo = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .subtract({ years: 1 })+ .toString();++ const itemCostUpdates: Database["public"]["Tables"]["itemCost"]["Update"][] =+ [];+ const itemReplenishmentUpdates: Database["public"]["Tables"]["itemReplenishment"]["Update"][] =+ [];+ const supplierPartInserts: Database["public"]["Tables"]["supplierPart"]["Insert"][] =+ [];+ const supplierPartUpdates: Database["public"]["Tables"]["supplierPart"]["Update"][] =+ [];++ const jobOperationUpdates: Database["public"]["Tables"]["jobOperation"]["Update"][] =+ [];++ const historicalPartCosts: Record<+ string,+ { quantity: number; cost: number }+ > = {};+ const historicalPartLeadTimes: Record<+ string,+ { quantity: number; weightedLeadTime: number }+ > = {};++ let supplierPartRows: Database["public"]["Tables"]["supplierPart"]["Row"][] =+ [];++ if (shouldUpdatePrices && itemIds.length > 0) {+ // Aggregate in SQL: fetching raw rows through PostgREST silently caps+ // at 1000, which skewed the weighted average for high-volume items.+ const [costLedgerTotals, supplierParts] = await inOrder([+ () =>+ db+ .selectFrom("costLedger")+ .select(({ fn }) => [+ "itemId",+ // Adjustment child rows (invoice-vs-receipt price corrections)+ // carry cost but no additional physical quantity, so they count+ // toward cost but not quantity.+ sql<number>`sum(case when "adjustment" then 0 else "quantity" end)`.as(+ "quantity"+ ),+ fn.sum<number>("cost").as("cost")+ ])+ .where("itemId", "in", itemIds)+ .where("companyId", "=", companyId)+ .where("postingDate", ">=", dateOneYearAgo)+ .groupBy("itemId")+ .execute(),+ () => many(db, "supplierPart", { supplierId, itemId: itemIds, companyId })+ ]);++ if (supplierParts.error) {+ throw new Error("Failed to fetch supplier parts");+ }++ supplierPartRows = supplierParts.data ?? [];++ costLedgerTotals.forEach((row) => {+ if (row.itemId) {+ historicalPartCosts[row.itemId] = {+ quantity: Number(row.quantity ?? 0),+ cost: Number(row.cost ?? 0)+ };+ }+ });+ }++ if (shouldUpdateLeadTimes && itemIds.length > 0) {+ const receipts = await many(+ db,+ "receipt",+ {+ companyId,+ sourceDocument: "Purchase Order",+ postingDate: gte(dateOneYearAgo)+ },+ { columns: ["id", "postingDate", "sourceDocumentId"] }+ );++ if (receipts.error) {+ throw new Error("Failed to fetch historical receipts");+ }++ const receiptIds = receipts.data?.map((receipt) => receipt.id) ?? [];+ const purchaseOrderIds = Array.from(+ new Set(+ (receipts.data ?? [])+ .map((receipt) => receipt.sourceDocumentId)+ .filter((id): id is string => Boolean(id))+ )+ );++ if (receiptIds.length > 0 && purchaseOrderIds.length > 0) {+ const [receiptLines, purchaseOrders] = await inOrder([+ () =>+ many(+ db,+ "receiptLine",+ { receiptId: receiptIds, itemId: itemIds, companyId },+ {+ columns: [+ "receiptId",+ "itemId",+ "receivedQuantity",+ "conversionFactor"+ ]+ }+ ),+ () =>+ many(+ db,+ "purchaseOrder",+ { id: purchaseOrderIds, companyId },+ { columns: ["id", "orderDate"] }+ )+ ]);++ if (receiptLines.error) {+ throw new Error("Failed to fetch historical receipt lines");+ }+ if (purchaseOrders.error) {+ throw new Error("Failed to fetch historical purchase orders");+ }++ const receiptsById = (receipts.data ?? []).reduce<+ Record<string, { postingDate: string; sourceDocumentId: string | null }>+ >((acc, receipt) => {+ if (receipt.postingDate) {+ acc[receipt.id] = {+ postingDate: receipt.postingDate,+ sourceDocumentId: receipt.sourceDocumentId+ };+ }+ return acc;+ }, {});++ const purchaseOrdersById = purchaseOrders.data.reduce<+ Record<string, { orderDate: string | null }>+ >((acc, row) => {+ acc[row.id] = { orderDate: row.orderDate };+ return acc;+ }, {});++ receiptLines.data.forEach((line) => {+ if (!line.itemId) return;++ const receipt = receiptsById[line.receiptId];+ if (!receipt?.sourceDocumentId) return;++ const orderDate =+ purchaseOrdersById[receipt.sourceDocumentId]?.orderDate;+ if (!orderDate || !receipt.postingDate) return;++ const safeConversionFactor =+ line.conversionFactor && line.conversionFactor > 0+ ? line.conversionFactor+ : 1;+ const quantity = Math.abs(+ (line.receivedQuantity ?? 0) / safeConversionFactor+ );+ if (quantity <= 0) return;++ const leadTimeInDays = calculateLeadTimeInDays(+ orderDate,+ receipt.postingDate+ );++ historicalPartLeadTimes[line.itemId] ??= {+ quantity: 0,+ weightedLeadTime: 0+ };+ const history = historicalPartLeadTimes[line.itemId]!;+ history.quantity += quantity;+ history.weightedLeadTime += leadTimeInDays * quantity;+ });+ }+ }++ // The supplier part records what the supplier charged, in its own+ // currency: copied exactly when it matches the document's, converted at+ // today's rate when it does not.+ const priceConverter =+ shouldUpdatePrices && itemIds.length > 0+ ? await getSupplierPartPriceConverter(+ db,+ companyId,+ documentCurrency,+ supplierPartRows+ .filter((sp) => sp.supplierId === supplierId)+ .map((sp) => sp.currencyCode)+ )+ : null;++ lines.forEach((line) => {+ if (line.itemId && !line.jobOperationId) {+ const costHistory = historicalPartCosts[line.itemId];+ const hasLeadTimeHistory =+ (historicalPartLeadTimes[line.itemId]?.quantity ?? 0) > 0;++ if (+ shouldUpdatePrices &&+ line.unitPrice !== 0 &&+ costHistory &&+ costHistory.quantity > 0+ ) {+ itemCostUpdates.push({+ itemId: line.itemId,+ unitCost: costHistory.cost / costHistory.quantity,+ updatedBy: "system"+ });++ const supplierPart = supplierPartRows.find(+ (sp) => sp.itemId === line.itemId && sp.supplierId === supplierId+ );++ if (supplierPart && supplierPart.id) {+ supplierPartUpdates.push({+ id: supplierPart.id,+ supplierUnitPrice: priceConverter!.toPartCurrency(+ line.supplierUnitPrice,+ supplierPart.currencyCode+ ),+ conversionFactor: line.conversionFactor ?? 1,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ updatedBy: "system"+ });+ } else {+ supplierPartInserts.push({+ itemId: line.itemId,+ supplierId: supplierId,+ supplierUnitPrice: line.supplierUnitPrice,+ currencyCode: documentCurrency.currencyCode,+ conversionFactor: line.conversionFactor ?? 1,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ createdBy: "system",+ companyId+ });+ }+ }++ if (shouldUpdatePrices || (shouldUpdateLeadTimes && hasLeadTimeHistory)) {+ const itemReplenishmentUpdate: Database["public"]["Tables"]["itemReplenishment"]["Update"] =+ {+ itemId: line.itemId,+ updatedBy: "system"+ };++ if (shouldUpdatePrices) {+ itemReplenishmentUpdate.preferredSupplierId = supplierId;+ itemReplenishmentUpdate.purchasingUnitOfMeasureCode =+ line.purchaseUnitOfMeasureCode;+ itemReplenishmentUpdate.conversionFactor = line.conversionFactor ?? 1;+ }++ const history = historicalPartLeadTimes[line.itemId];+ if (shouldUpdateLeadTimes && hasLeadTimeHistory && history) {+ itemReplenishmentUpdate.leadTime = Math.round(+ history.weightedLeadTime / history.quantity+ );+ }++ itemReplenishmentUpdates.push(itemReplenishmentUpdate);+ }+ }++ if (shouldUpdatePrices && line.jobOperationId && line.unitPrice !== 0) {+ jobOperationUpdates.push({+ id: line.jobOperationId,+ operationMinimumCost: 0,+ operationUnitCost: line.unitPrice ?? 0,+ updatedBy: "system"+ });+ }+ });++ await db.transaction().execute(async (trx) => {+ if (itemCostUpdates.length > 0) {+ for await (const itemCostUpdate of itemCostUpdates) {+ await trx+ .updateTable("itemCost")+ .set(itemCostUpdate)+ .where("itemId", "=", itemCostUpdate.itemId!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (jobOperationUpdates.length > 0) {+ for await (const jobOperationUpdate of jobOperationUpdates) {+ await trx+ .updateTable("jobOperation")+ .set(jobOperationUpdate)+ .where("id", "=", jobOperationUpdate.id!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (supplierPartInserts.length > 0) {+ await trx+ .insertInto("supplierPart")+ .values(supplierPartInserts)+ .onConflict((oc) =>+ oc.columns(["itemId", "supplierId", "companyId"]).doUpdateSet({+ supplierUnitPrice: (eb) => eb.ref("excluded.supplierUnitPrice"),+ currencyCode: (eb) => eb.ref("excluded.currencyCode"),+ conversionFactor: (eb) => eb.ref("excluded.conversionFactor"),+ supplierUnitOfMeasureCode: (eb) =>+ eb.ref("excluded.supplierUnitOfMeasureCode"),+ updatedBy: "system"+ })+ )+ .execute();+ }++ if (supplierPartUpdates.length > 0) {+ for await (const supplierPartUpdate of supplierPartUpdates) {+ await trx+ .updateTable("supplierPart")+ .set(supplierPartUpdate)+ .where("id", "=", supplierPartUpdate.id!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (itemReplenishmentUpdates.length > 0) {+ for await (const itemReplenishmentUpdate of itemReplenishmentUpdates) {+ await trx+ .updateTable("itemReplenishment")+ .set(itemReplenishmentUpdate)+ .where("itemId", "=", itemReplenishmentUpdate.itemId!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });++ return { success: true };+ }+ export type Db = Kysely<KyselyDatabase>;+ type Enums = Database["public"]["Enums"];++ /** The lease header: the term and the payment terms every asset shares. */+ export type LeaseRow = {+ id: string;+ leaseId: string;+ status: Enums["leaseStatus"];+ name: string | null;+ supplierId: string;+ locationId: string | null;+ commencementDate: string;+ /** Null is open-ended: every asset is short-term (spec Addendum A10). */+ endDate: string | null;+ invoiceFromDate: string;+ paymentFrequency: Enums["leasePaymentFrequency"];+ paymentTiming: Enums["rentalBillingTiming"];+ annualEscalationPercent: number;+ discountRate: number;+ currencyCode: string;+ commencementJournalId: string | null;+ };++ /** One leased asset: a separate lease component (ASC 842-10-15-28), with its+ * own payment, classification inputs, classification and measurement. */+ export type LeaseLineRow = {+ id: string;+ description: string;+ serialNumber: string | null;+ locationId: string | null;+ paymentAmount: number;+ fairValue: number | null;+ economicLifeMonths: number | null;+ ownershipTransfers: boolean;+ specializedAsset: boolean;+ purchaseOptionAmount: number | null;+ purchaseOptionReasonablyCertain: boolean;+ status: Enums["leaseLineStatus"];+ lesseeClassification: Enums["lesseeClassification"] | null;+ classificationOverride: Enums["lesseeClassification"] | null;+ initialLiability: number | null;+ rouAssetCost: number | null;+ };++ const num = (value: unknown): number | null =>+ value === null || value === undefined ? null : Number(value);++ // Re-read under the caller's company and lock: the id comes from the payload,+ // and the permission check proves nothing about it. The lock serializes two+ // actions on one lease (a double-clicked Activate, a Modify racing a+ // Terminate of one asset). DATE columns are selected as text — the lease+ // math works on `YYYY-MM-DD` strings.+ export async function lockLease(+ trx: Trx,+ companyId: string,+ id: string+ ): Promise<LeaseRow> {+ const lease = await trx+ .selectFrom("lease")+ .select([+ "id",+ "leaseId",+ "status",+ "name",+ "supplierId",+ "locationId",+ sql<string>`"commencementDate"::text`.as("commencementDate"),+ sql<string | null>`"endDate"::text`.as("endDate"),+ sql<string>`"invoiceFromDate"::text`.as("invoiceFromDate"),+ "paymentFrequency",+ "paymentTiming",+ "annualEscalationPercent",+ "discountRate",+ "currencyCode",+ "commencementJournalId"+ ])+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!lease) throw new NotFoundError("Lease not found");+ return {+ ...lease,+ annualEscalationPercent: Number(lease.annualEscalationPercent),+ discountRate: Number(lease.discountRate)+ };+ }++ /** The lease's assets in their order. The lease row's lock covers them:+ * every writer of a line locks the lease first. */+ export async function readLines(+ trx: Trx,+ companyId: string,+ leaseId: string+ ): Promise<LeaseLineRow[]> {+ const rows = await trx+ .selectFrom("leaseLine")+ .select([+ "id",+ "description",+ "serialNumber",+ "locationId",+ "paymentAmount",+ "fairValue",+ "economicLifeMonths",+ "ownershipTransfers",+ "specializedAsset",+ "purchaseOptionAmount",+ "purchaseOptionReasonablyCertain",+ "status",+ "lesseeClassification",+ "classificationOverride",+ "initialLiability",+ "rouAssetCost"+ ])+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .orderBy("sortOrder")+ .orderBy("createdAt")+ .execute();+ return rows.map((row) => ({+ ...row,+ paymentAmount: Number(row.paymentAmount),+ fairValue: num(row.fairValue),+ economicLifeMonths: num(row.economicLifeMonths),+ purchaseOptionAmount: num(row.purchaseOptionAmount),+ initialLiability: num(row.initialLiability),+ rouAssetCost: num(row.rouAssetCost)+ }));+ }++ /** The one asset of the lease the payload names, or a 404. */+ export function findLine(lines: LeaseLineRow[], id: string): LeaseLineRow {+ const line = lines.find((row) => row.id === id);+ if (!line) throw new NotFoundError("Leased asset not found");+ return line;+ }++ /** The classification of an asset past Draft. Activation stores one for+ * every asset, so a missing one is a broken row, not a default. */+ export function classificationOf(+ line: Pick<LeaseLineRow, "description" | "lesseeClassification">+ ): Enums["lesseeClassification"] {+ if (!line.lesseeClassification) {+ throw new Error(`${line.description} has no lessee classification`);+ }+ return line.lesseeClassification;+ }++ export type LeasePaymentRow = {+ id: string;+ leaseLineId: string;+ paymentType: Enums["leasePaymentType"];+ periodStart: string;+ periodEnd: string;+ dueDate: string;+ amount: number;+ status: Enums["leasePaymentStatus"];+ };++ export async function readPayments(+ trx: Trx,+ companyId: string,+ leaseId: string+ ): Promise<LeasePaymentRow[]> {+ const rows = await trx+ .selectFrom("leasePayment")+ .select([+ "id",+ "leaseLineId",+ "paymentType",+ sql<string>`"periodStart"::text`.as("periodStart"),+ sql<string>`"periodEnd"::text`.as("periodEnd"),+ sql<string>`"dueDate"::text`.as("dueDate"),+ "amount",+ "status"+ ])+ .where("leaseId", "=", leaseId)+ .where("companyId", "=", companyId)+ .orderBy("dueDate")+ .execute();+ return rows.map((row) => ({ ...row, amount: Number(row.amount) }));+ }++ export type LesseeAccounting = {+ // Provisional before the company's accounting cutover, Posted after it.+ postingStatus: AutomaticJournalStatus;+ accounts: LesseeAccounts;+ // active dimensions for the company group, entityType → dimension id+ dimensionMap: Map<string, string>;+ };++ export const LESSEE_ACCOUNTS_REQUIRED =+ "Set the lease (lessee) accounts in Accounting → Default Accounts before activating a lease";++ const LESSEE_DEFAULT_COLUMNS = [+ "rightOfUseAssetAccount",+ "accumulatedRightOfUseAmortizationAccount",+ "leaseLiabilityAccount",+ "operatingLeaseExpenseAccount",+ "rightOfUseAmortizationExpenseAccount",+ "leaseInterestExpenseAccount",+ "assetGainOnDisposalAccount",+ "assetLossOnDisposalAccount"+ ] as const;++ /** The lessee lease accounts with their classes, and the dimensions. Every+ * account is required — the migration seeds and maps them for every+ * company — because the schedule rows name them and are never re-pointed. */+ export async function loadLesseeAccounting(+ trx: Trx,+ args: { companyId: string; companyGroupId: string | null }+ ): Promise<LesseeAccounting> {+ const { companyId } = args;+ const postingStatus = await journalPostingStatus(trx, companyId);+ const defaults = await trx+ .selectFrom("accountDefault")+ .select([...LESSEE_DEFAULT_COLUMNS])+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!defaults) throw new Error("Error getting account defaults");+ const ids = LESSEE_DEFAULT_COLUMNS.map((column) => defaults[column]);+ if (ids.some((id) => !id)) {+ throw new InvalidInputError(LESSEE_ACCOUNTS_REQUIRED);+ }++ // `account` is group-scoped; the ids came from this company's defaults.+ const accounts = await trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "in", ids as string[])+ .execute();+ const classOf = (id: string): AccountClass => {+ const account = accounts.find((row) => row.id === id);+ if (!account?.class) {+ throw new InvalidInputError(+ `Account ${id} in the lease account defaults has no class. Set its class in Accounting → Chart of Accounts.`+ );+ }+ return account.class;+ };+ const account = (column: (typeof LESSEE_DEFAULT_COLUMNS)[number]) => {+ const id = defaults[column] as string;+ return { id, class: classOf(id) };+ };++ // Dimensions are configured per company group; a company outside one+ // tags nothing.+ const dimensions =+ args.companyGroupId === null+ ? []+ : await trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", args.companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["Supplier", "Location"])+ .execute();++ return {+ postingStatus,+ accounts: {+ rightOfUseAsset: account("rightOfUseAssetAccount"),+ accumulatedRightOfUseAmortization: account(+ "accumulatedRightOfUseAmortizationAccount"+ ),+ leaseLiability: account("leaseLiabilityAccount"),+ operatingLeaseExpense: account("operatingLeaseExpenseAccount"),+ rightOfUseAmortizationExpense: account(+ "rightOfUseAmortizationExpenseAccount"+ ),+ leaseInterestExpense: account("leaseInterestExpenseAccount"),+ gain: account("assetGainOnDisposalAccount"),+ loss: account("assetLossOnDisposalAccount")+ },+ dimensionMap: new Map(+ dimensions.map((dimension) => [dimension.entityType, dimension.id])+ )+ };+ }++ /** One asset's balanced journal lines. */+ export type AssetLines = {+ leaseLineId: string;+ /** The asset's location, else the lease's: the Location dimension. */+ locationId: string | null;+ lines: PostingLine[];+ };++ /** One 'Lease' journal from each asset's balanced lines: Provisional before+ * the accounting cutover (no period), Posted after it in the period of its+ * date (the next open period when that one is Locked or Closed). Every line+ * carries the lease as its document and its asset line as the document+ * line, tagged with Supplier and the asset's Location. Null when no asset+ * has a line to post. */+ export async function postLesseeJournal(+ trx: Trx,+ args: {+ accounting: LesseeAccounting;+ companyId: string;+ userId: string;+ postingDate: string;+ description: string;+ assets: AssetLines[];+ lease: Pick<LeaseRow, "id" | "supplierId">;+ }+ ): Promise<string | null> {+ const { accounting, companyId, userId } = args;+ const lines = args.assets.flatMap((asset) =>+ asset.lines.map((line) => ({ ...line, asset }))+ );+ if (lines.length === 0) return null;++ const period =+ accounting.postingStatus === "Posted"+ ? await resolveAccountingPeriod(+ trx,+ companyId,+ args.postingDate,+ "historical-with-shift"+ )+ : null;+ const journalId = await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: period?.id ?? null,+ status: accounting.postingStatus,+ description: args.description,+ postingDate: period?.postingDate ?? args.postingDate,+ userId,+ sourceType: "Lease"+ });++ const journalLineReference = nanoid();+ const journalLineIds = await allocateJournalLineIds(trx, lines.length);+ await trx+ .insertInto("journalLine")+ .values(+ lines.map((line, index) => ({+ id: journalLineIds[index],+ journalId,+ accountId: line.accountId,+ description: line.description,+ amount: round(line.amount),+ quantity: 1,+ documentType: "Lease" as const,+ documentId: args.lease.id,+ documentLineReference: line.asset.leaseLineId,+ journalLineReference,+ companyId+ }))+ )+ .execute();++ const dimensionInserts = buildJournalLineDimensionInserts({+ journalLineIds: journalLineIds as string[],+ meta: lines.map((line) => ({+ supplierId: args.lease.supplierId,+ locationId: line.asset.locationId+ })),+ dimensionMap: accounting.dimensionMap,+ companyId+ });+ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }++ return journalId;+ }++ /** One asset's schedule from lease month `fromMonth` on: line `i` is lease+ * month `fromMonth + i` of the lease that commenced on `commencementDate`. */+ export type AssetSchedule = {+ leaseLineId: string;+ commencementDate: string;+ fromMonth: number;+ lines: LesseeScheduleLine[];+ classification: "Operating" | "Finance";+ };++ /**+ * Writes each asset's schedule lines, and two `revenueRecognitionSchedule`+ * rows per line (Interest and Amortization, each on its own accounts — spec+ * §3) that the lease run posts. A row with no amount is not written. Rows+ * dated before `postedBefore` are written Posted with no journal, and their+ * lines with `postedAt`: their entries are in an opening balance, as the+ * enable's step 5 does for rows before the cutover.+ */+ export async function writeSchedules(+ trx: Trx,+ args: {+ leaseId: string;+ schedules: AssetSchedule[];+ accounts: LesseeAccounts;+ companyId: string;+ userId: string;+ postedBefore?: string;+ }+ ): Promise<void> {+ const { leaseId, companyId, userId } = args;+ const lines = args.schedules.flatMap((schedule) =>+ schedule.lines.map((line, index) => ({ schedule, line, index }))+ );+ if (lines.length === 0) return;+ const postedAt = datetime.timestamp();++ const inserted = await trx+ .insertInto("leaseScheduleLine")+ .values(+ lines.map(({ schedule, line }) => ({+ leaseId,+ leaseLineId: schedule.leaseLineId,+ periodDate: line.periodDate,+ openingLiability: line.openingLiability,+ paymentAmount: line.paymentAmount,+ interestAmount: line.interestAmount,+ principalAmount: line.principalAmount,+ closingLiability: line.closingLiability,+ leaseCost: line.leaseCost,+ rouAmortization: line.rouAmortization,+ closingRouAsset: line.closingRouAsset,+ // An opening-balance month is on the books like a run-posted one;+ // the `leases` view and the lease page read posted state from here.+ postedAt:+ args.postedBefore !== undefined && line.periodDate < args.postedBefore+ ? postedAt+ : null,+ companyId,+ createdBy: userId+ }))+ )+ .returning([+ "id",+ "leaseLineId",+ sql<string>`"periodDate"::text`.as("periodDate")+ ])+ .execute();+ const key = (leaseLineId: string, periodDate: string) =>+ `${leaseLineId}|${periodDate}`;+ const idByKey = new Map(+ inserted.map((row) => [key(row.leaseLineId, row.periodDate), row.id])+ );++ const rows = lines.flatMap(({ schedule, line, index }) => {+ const leaseScheduleLineId = idByKey.get(+ key(schedule.leaseLineId, line.periodDate)+ );+ if (!leaseScheduleLineId) {+ throw new Error(`Schedule line ${line.periodDate} was not written`);+ }+ const accounts = scheduleRowAccounts(+ schedule.classification,+ args.accounts+ );+ const posted =+ args.postedBefore !== undefined && line.periodDate < args.postedBefore;+ const base = {+ status: posted ? ("Posted" as const) : ("Planned" as const),+ leaseId,+ leaseScheduleLineId,+ periodStart: addMonths(+ schedule.commencementDate,+ schedule.fromMonth + index+ ),+ periodEnd: line.periodDate,+ scheduledDate: line.periodDate,+ companyId,+ createdBy: userId+ };+ return [+ {+ ...base,+ type: "Interest" as const,+ amount: line.interestAmount,+ ...accounts.interest+ },+ {+ ...base,+ type: "Amortization" as const,+ amount: line.rouAmortization,+ ...accounts.amortization+ }+ ].filter((row) => row.amount !== 0);+ });+ if (rows.length > 0) {+ await trx.insertInto("revenueRecognitionSchedule").values(rows).execute();+ }+ }++ /** Deletes the schedule lines of `leaseLineIds` dated on or after+ * `startDate`; their Planned run rows cascade with them. */+ export async function deleteSchedulesFrom(+ trx: Trx,+ args: { companyId: string; leaseLineIds: string[]; startDate: string }+ ): Promise<void> {+ if (args.leaseLineIds.length === 0) return;+ await trx+ .deleteFrom("leaseScheduleLine")+ .where("leaseLineId", "in", args.leaseLineIds)+ .where("companyId", "=", args.companyId)+ .where("periodDate", ">=", args.startDate)+ .execute();+ }++ /** The run holding a schedule row of the lease from `fromDate` on, or null.+ * A row a run holds cannot be rewritten until the run is recalculated or+ * deleted. */+ export async function heldByRun(+ trx: Trx,+ args: {+ companyId: string;+ leaseId: string;+ fromDate?: string;+ /** Only the rows of these assets; every asset when absent. */+ leaseLineIds?: string[];+ }+ ): Promise<string | null> {+ let query = trx+ .selectFrom("revenueRecognitionSchedule as s")+ .innerJoin("revenueRecognitionRunLine as l", (join) =>+ join+ .onRef("l.id", "=", "s.runLineId")+ .onRef("l.companyId", "=", "s.companyId")+ )+ .innerJoin("revenueRecognitionRun as r", (join) =>+ join+ .onRef("r.id", "=", "l.runId")+ .onRef("r.companyId", "=", "l.companyId")+ )+ .select("r.runId")+ .where("s.companyId", "=", args.companyId)+ .where("s.leaseId", "=", args.leaseId)+ .where("s.status", "=", "Planned");+ if (args.fromDate) {+ query = query.where("s.scheduledDate", ">=", args.fromDate);+ }+ if (args.leaseLineIds) {+ const ids = args.leaseLineIds;+ if (ids.length === 0) return null;+ query = query.where("s.leaseScheduleLineId", "in", (eb) =>+ eb+ .selectFrom("leaseScheduleLine")+ .select("id")+ .where("leaseLineId", "in", ids)+ .where("companyId", "=", args.companyId)+ );+ }+ const row = await query.executeTakeFirst();+ return row?.runId ?? null;+ }++ /** Voids a lease journal with a negated copy dated today (the next open+ * period when today's is Locked or Closed), keeping its documents and+ * dimensions. */+ export async function voidLeaseJournal(+ trx: Trx,+ args: {+ journalId: string;+ postingStatus: AutomaticJournalStatus;+ companyId: string;+ userId: string;+ today: string;+ }+ ): Promise<string> {+ const { companyId } = args;+ const original = await trx+ .selectFrom("journal")+ .select(["id", "sourceType", "description"])+ .where("id", "=", args.journalId)+ .where("companyId", "=", companyId)+ .forShare()+ .executeTakeFirst();+ if (!original || original.sourceType !== "Lease") {+ throw new Error("The lease journal has invalid provenance");+ }+ const originalLines = await trx+ .selectFrom("journalLine")+ .selectAll()+ .where("journalId", "=", original.id)+ .where("companyId", "=", companyId)+ .orderBy("id")+ .execute();+ return insertNegatedJournal(trx, {+ companyId,+ userId: args.userId,+ originalLines,+ description: `VOID ${original.description ?? "Lease"}`,+ sourceType: "Lease",+ postingStatus: args.postingStatus,+ date: args.today,+ periodMode: "historical-with-shift",+ postedAt: datetime.timestamp()+ });+ }++ export type Scope = { db: Db; companyId: string; userId: string };++ /** The payments' whole-month points from lease month `fromMonth` (0 at+ * commencement). Counted from the commencement, never from a later date: a+ * lease from the 29th–31st has clamped months that a later start would+ * not line up with. */+ export function paymentPoints(+ payments: Pick<+ LeasePaymentRow,+ "periodStart" | "periodEnd" | "dueDate" | "paymentType" | "amount"+ >[],+ commencementDate: string,+ timing: LeaseRow["paymentTiming"],+ fromMonth = 0+ ): LeasePaymentPoint[] {+ return payments.map((payment) => ({+ monthIndex:+ paymentMonthIndex(payment, commencementDate, timing) - fromMonth,+ amount: payment.amount+ }));+ }++ /** Straight-line ROU amortization runs over what is left of the useful life+ * when the lessee will own the asset, else over the `months` the schedule+ * covers. `elapsedMonths` are the lease months before the schedule starts+ * (0 at commencement). */+ export function amortizationMonths(+ line: Pick<+ LeaseLineRow,+ | "ownershipTransfers"+ | "purchaseOptionReasonablyCertain"+ | "economicLifeMonths"+ >,+ months: number,+ elapsedMonths = 0+ ): number {+ const remainingLife = (line.economicLifeMonths ?? 0) - elapsedMonths;+ return (line.ownershipTransfers || line.purchaseOptionReasonablyCertain) &&+ remainingLife > months+ ? remainingLife+ : months;+ }++ type Thresholds = { majorPartPercent: number; substantiallyAllPercent: number };++ export type MeasuredAsset = {+ line: LeaseLineRow;+ liability: number;+ classification: "Operating" | "Finance" | "Short-Term";+ classificationInputs: Json;+ };++ /** One asset's liability (the PV of its payment rows) and classification+ * over the term from lease month `fromMonth` (0 at commencement) to+ * `endDate`. An override wins. */+ export function measureAsset(args: {+ line: LeaseLineRow;+ payments: Pick<+ LeasePaymentRow,+ "periodStart" | "periodEnd" | "dueDate" | "paymentType" | "amount"+ >[];+ fromMonth?: number;+ endDate: string;+ lease: Pick<LeaseRow, "commencementDate" | "paymentTiming" | "discountRate">;+ thresholds: Thresholds;+ shortTermExpedient: boolean;+ }): MeasuredAsset {+ const { line, lease, thresholds } = args;+ const { liability, termMonths, ...result } = measureLesseeAsset({+ commencementDate: lease.commencementDate,+ endDate: args.endDate,+ timing: lease.paymentTiming,+ discountRate: lease.discountRate,+ payments: args.payments,+ fromMonth: args.fromMonth,+ inputs: line,+ shortTermExpedient: args.shortTermExpedient,+ thresholds+ });+ return {+ line,+ liability,+ classification: line.classificationOverride ?? result.classification,+ classificationInputs: {+ ...result,+ termMonths,+ pvPayments: liability,+ discountRate: lease.discountRate,+ thresholds,+ override: line.classificationOverride+ }+ };+ }++ export async function readThresholds(+ trx: Trx,+ companyId: string+ ): Promise<Thresholds & { shortTermExpedient: boolean }> {+ const settings = await trx+ .selectFrom("companySettings")+ .select([+ "leaseMajorPartThresholdPercent",+ "leaseSubstantiallyAllThresholdPercent",+ "leaseShortTermExpedient"+ ])+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ return {+ majorPartPercent: Number(settings.leaseMajorPartThresholdPercent),+ substantiallyAllPercent: Number(+ settings.leaseSubstantiallyAllThresholdPercent+ ),+ shortTermExpedient: settings.leaseShortTermExpedient+ };+ }++ /** Writes each asset's measurement in one statement. Columns left out of a+ * row keep their value. */+ export async function updateLineMeasurements(+ trx: Trx,+ args: {+ companyId: string;+ userId: string;+ rows: {+ id: string;+ lesseeClassification: "Operating" | "Finance" | "Short-Term";+ classificationInputs?: Json;+ initialLiability?: number | null;+ rouAssetCost?: number | null;+ paymentAmount?: number;+ }[];+ }+ ): Promise<void> {+ if (args.rows.length === 0) return;+ const values = sql.join(+ args.rows.map(+ (row) =>+ sql`(${row.id}, ${row.lesseeClassification}, ${+ row.classificationInputs === undefined+ ? null+ : JSON.stringify(row.classificationInputs)+ }, ${row.classificationInputs !== undefined}, ${+ row.initialLiability ?? null+ }, ${row.initialLiability !== undefined}, ${row.rouAssetCost ?? null}, ${+ row.rouAssetCost !== undefined+ }, ${row.paymentAmount ?? null}, ${row.paymentAmount !== undefined})`+ )+ );+ await sql`+ UPDATE "leaseLine" AS l SET+ "lesseeClassification" = v.classification::"lesseeClassification",+ "classificationInputs" = CASE WHEN v."setInputs"::boolean+ THEN v.inputs::jsonb ELSE l."classificationInputs" END,+ "initialLiability" = CASE WHEN v."setInitial"::boolean+ THEN v.initial::numeric ELSE l."initialLiability" END,+ "initialRouAsset" = CASE WHEN v."setInitial"::boolean+ THEN v.initial::numeric ELSE l."initialRouAsset" END,+ "rouAssetCost" = CASE WHEN v."setCost"::boolean+ THEN v.cost::numeric ELSE l."rouAssetCost" END,+ "paymentAmount" = CASE WHEN v."setPayment"::boolean+ THEN v.payment::numeric ELSE l."paymentAmount" END,+ "updatedBy" = ${args.userId},+ "updatedAt" = ${datetime.timestamp()}+ FROM (VALUES ${values}) AS v(+ id, classification, inputs, "setInputs", initial, "setInitial",+ cost, "setCost", payment, "setPayment"+ )+ WHERE l."id" = v.id AND l."companyId" = ${args.companyId}+ `.execute(trx);+ }+ export type LeaseAccount = { id: string; class: AccountClass };++ export type LesseeAccounts = {+ rightOfUseAsset: LeaseAccount;+ accumulatedRightOfUseAmortization: LeaseAccount;+ leaseLiability: LeaseAccount;+ operatingLeaseExpense: LeaseAccount;+ rightOfUseAmortizationExpense: LeaseAccount;+ leaseInterestExpense: LeaseAccount;+ gain: LeaseAccount;+ loss: LeaseAccount;+ };++ /** A journal line with its amount in the account's natural balance. */+ export type PostingLine = {+ accountId: string;+ description: string;+ amount: number;+ };++ type Leg = {+ side: "debit" | "credit";+ account: LeaseAccount;+ description: string;+ amount: number;+ };++ /** Legs → natural-balance-signed journal lines, dropping zero legs and+ * refusing an unbalanced set. A negative leg amount flips its side. */+ export function toPostingLines(legs: Leg[], label: string): PostingLine[] {+ let debits = 0;+ let credits = 0;+ const lines: PostingLine[] = [];+ for (const leg of legs) {+ const amount = round(leg.amount);+ if (amount === 0) continue;+ const side =+ amount > 0 ? leg.side : leg.side === "debit" ? "credit" : "debit";+ const value = Math.abs(amount);+ if (side === "debit") debits += value;+ else credits += value;+ lines.push({+ accountId: leg.account.id,+ description: leg.description,+ amount:+ side === "debit"+ ? toStoredAmount(value, 0, leg.account.class)+ : toStoredAmount(0, value, leg.account.class)+ });+ }+ assertBalanced(round(debits), round(credits), EPSILON, label);+ return lines;+ }++ /** The accounts of the roles a leg names. `fixedAsset` and+ * `retainedEarnings` are not lease defaults: a purchase passes the asset+ * class's account and an opening balance the retained earnings default. */+ type LegAccounts = Partial<Record<LesseeLegAccount, LeaseAccount>>;++ /** The shared legs posted to the company's accounts. A role with no account+ * is a programming error, never a user's. */+ function postLegs(+ legs: LesseeLeg[],+ accounts: LesseeAccounts,+ extra: LegAccounts,+ label: string+ ): PostingLine[] {+ const resolved: LegAccounts = { ...accounts, ...extra };+ return toPostingLines(+ normalizeLesseeLegs(legs).map((leg) => {+ const account = resolved[leg.account];+ if (!account) {+ throw new Error(`${label}: no account for ${leg.account}`);+ }+ return { ...leg, account };+ }),+ label+ );+ }++ /** Commencement: Dr ROU asset / Cr Lease liability, both at the PV. */+ export function commencementLines(args: {+ liability: number;+ accounts: LesseeAccounts;+ }): PostingLine[] {+ return postLegs(+ lesseeCommencementLegs({ liability: args.liability }),+ args.accounts,+ {},+ "Lease commencement journal"+ );+ }++ /** Opening balance of a lease that commenced before the accounting cutover+ * (spec Q8): the balances its schedule reaches on the as-of date, with the+ * difference — the lease cost of the months before it, already in the+ * opening equity — to retained earnings.+ *+ * Dr ROU asset cost+ * Cr Accumulated ROU amortization amortization before the date+ * Cr Lease liability carrying liability on the date+ * Cr / Dr Retained earnings the difference+ */+ export function openingBalanceLines(args: {+ rouAssetCost: number;+ accumulated: number;+ carryingLiability: number;+ retainedEarnings: LeaseAccount;+ accounts: LesseeAccounts;+ }): PostingLine[] {+ return postLegs(+ lesseeOpeningBalanceLegs(args),+ args.accounts,+ { retainedEarnings: args.retainedEarnings },+ "Lease opening balance journal"+ );+ }++ /** Remeasurement (Modify): the ROU asset moves by the liability change; a+ * decrease larger than the ROU asset leaves it at zero and the rest is a+ * gain. `adjustment` = new liability − carrying liability. */+ export function remeasurementLines(args: {+ adjustment: number;+ gain: number;+ accounts: LesseeAccounts;+ }): PostingLine[] {+ return postLegs(+ lesseeRemeasurementLegs(args),+ args.accounts,+ {},+ "Lease remeasurement journal"+ );+ }++ /** Early termination (ASC 842-20-40-1): the liability and the ROU asset+ * leave the books, and the difference is a gain or loss. A penalty stays in+ * the liability as a payment row the next invoice settles.+ *+ * Dr Lease liability carrying − penalty+ * Dr Accumulated ROU amortization accumulated+ * Cr ROU asset cost+ * Cr / Dr gain or loss the difference+ */+ export function terminationLines(args: {+ carryingLiability: number;+ penalty: number;+ rouAssetCost: number;+ accumulated: number;+ accounts: LesseeAccounts;+ }): { lines: PostingLine[]; gainLoss: number } {+ const { legs, gainLoss } = lesseeTerminationLegs(args);+ return {+ lines: postLegs(legs, args.accounts, {}, "Lease termination journal"),+ gainLoss+ };+ }++ /** Purchase option exercise (ASC 842-20-40-2): not a termination. The ROU+ * asset moves into PP&E at its net book value, adjusted by the price less+ * the carrying liability; the price stays in the liability as a payment row+ * the next invoice settles. A price that leaves the asset a negative cost+ * is refused as a 400.+ *+ * Dr Fixed asset class asset account net ROU + price − carrying liability+ * Dr Accumulated ROU amortization accumulated+ * Dr Lease liability carrying liability+ * Cr ROU asset cost+ * Cr Lease liability price+ */+ export function purchaseLines(args: {+ carryingLiability: number;+ price: number;+ rouAssetCost: number;+ accumulated: number;+ assetAccount: LeaseAccount;+ accounts: LesseeAccounts;+ }): { lines: PostingLine[]; assetCost: number } {+ const { legs, assetCost } = lesseePurchaseLegs(args);+ if (assetCost < 0) {+ throw new InvalidInputError(+ "The purchased asset would have a negative cost; check the purchase price"+ );+ }+ return {+ lines: postLegs(+ legs,+ args.accounts,+ { fixedAsset: args.assetAccount },+ "Lease purchase journal"+ ),+ assetCost+ };+ }++ /** The accounts of one month's two schedule rows (spec §3): an operating+ * lease books both to the lease cost; a finance lease books interest and+ * amortization separately. */+ export function scheduleRowAccounts(+ classification: "Operating" | "Finance",+ accounts: LesseeAccounts+ ): {+ interest: { debitAccountId: string; creditAccountId: string };+ amortization: { debitAccountId: string; creditAccountId: string };+ } {+ return {+ interest: {+ debitAccountId:+ classification === "Operating"+ ? accounts.operatingLeaseExpense.id+ : accounts.leaseInterestExpense.id,+ creditAccountId: accounts.leaseLiability.id+ },+ amortization: {+ debitAccountId:+ classification === "Operating"+ ? accounts.operatingLeaseExpense.id+ : accounts.rightOfUseAmortizationExpense.id,+ creditAccountId: accounts.accumulatedRightOfUseAmortization.id+ }+ };+ }+ type Classification = "Operating" | "Finance" | "Short-Term";++ /** The lease month that starts on `startDate`, or null when `startDate` is+ * not a lease-month boundary (the commencement day of a month). */+ export function leaseMonthStarting(+ commencementDate: string,+ startDate: string+ ): number | null {+ if (startDate < commencementDate) return null;+ const month = leaseMonthsAt(commencementDate, startDate);+ return addMonths(commencementDate, month) === startDate ? month : null;+ }++ /** The payment period `startDate` falls inside (after its first day), or+ * null. A change takes effect where a payment period starts: the period+ * before it is paid in full and the one after it is cut from the new terms. */+ export function straddledPeriod(+ rows: { paymentType: string; periodStart: string; periodEnd: string }[],+ startDate: string+ ): { periodStart: string; periodEnd: string } | null {+ return (+ rows.find(+ (row) =>+ row.paymentType === "Rent" &&+ row.periodStart < startDate &&+ row.periodEnd >= startDate+ ) ?? null+ );+ }++ /**+ * The checks every lifecycle action shares, and each asset's carrying+ * amounts at `startDate` (the first day after the change takes effect).+ * Refuses a date that is not a lease-month boundary or falls inside a+ * payment period, a month before it whose run rows are not Posted, a month+ * on or after it that is already Posted, a later row a run holds, and an+ * Invoiced payment due on or after `startDate`.+ */+ async function prepare(+ trx: Trx,+ args: {+ companyId: string;+ lease: LeaseRow;+ lines: LeaseLineRow[];+ startDate: string;+ label: string;+ }+ ): Promise<Map<string, LesseeCarrying>> {+ const { companyId, lease, lines, startDate, label } = args;+ if (lease.status !== "Active") {+ throw new InvalidInputError(+ `The lease is ${lease.status}; only an Active lease can be ${label}`+ );+ }+ const ended = lines.find((line) => line.status !== "Active");+ if (ended) {+ throw new InvalidInputError(+ `${ended.description} is ${ended.status}; only an active asset can be ${label}`+ );+ }+ if (leaseMonthStarting(lease.commencementDate, startDate) === null) {+ throw new InvalidInputError(+ `The date must fall on a lease-month boundary: the month starts on day ${lease.commencementDate.slice(8)} of a month`+ );+ }+ if (lease.endDate && startDate > addDays(lease.endDate, 1)) {+ throw new InvalidInputError("The date is after the end of the lease");+ }++ const lineIds = lines.map((line) => line.id);+ const payments = (await readPayments(trx, companyId, lease.id)).filter(+ (payment) => lineIds.includes(payment.leaseLineId)+ );+ const straddled = straddledPeriod(payments, startDate);+ if (straddled) {+ throw new InvalidInputError(+ `The date falls inside the payment period ${straddled.periodStart} to ${straddled.periodEnd}; choose a date where a payment period starts or ends`+ );+ }+ const invoiced = payments.find(+ (payment) => payment.status === "Invoiced" && payment.dueDate >= startDate+ );+ if (invoiced) {+ throw new InvalidInputError(+ `The payment due ${invoiced.dueDate} is already invoiced; choose a later date or delete the invoice`+ );+ }+ // A Skipped row was paid outside Carbon. One on or after the date would+ // outlive the change: it is neither cut again nor ever invoiced. Checked+ // after the posted months, whose message names the date to choose.+ const refuseSkipped = () => {+ const skipped = payments.find(+ (payment) => payment.status === "Skipped" && payment.dueDate >= startDate+ );+ if (skipped) {+ throw new InvalidInputError(+ `The payment due ${skipped.dueDate} is Skipped (paid outside Carbon); choose a date after it`+ );+ }+ };++ const carrying = new Map<string, LesseeCarrying>(+ lines.map((line) => [+ line.id,+ { liability: 0, accumulated: 0, rouAsset: 0 }+ ])+ );+ const recognized = lines.filter(+ (line) => line.lesseeClassification !== "Short-Term"+ );+ if (recognized.length === 0) {+ refuseSkipped();+ return carrying;+ }+ const recognizedIds = recognized.map((line) => line.id);++ const unposted = await trx+ .selectFrom("revenueRecognitionSchedule as s")+ .innerJoin("leaseScheduleLine as l", (join) =>+ join+ .onRef("l.id", "=", "s.leaseScheduleLineId")+ .onRef("l.companyId", "=", "s.companyId")+ )+ .select(sql<string>`s."scheduledDate"::text`.as("scheduledDate"))+ .where("s.companyId", "=", companyId)+ .where("l.leaseLineId", "in", recognizedIds)+ .where("s.status", "=", "Planned")+ .where("s.scheduledDate", "<", startDate)+ .orderBy("s.scheduledDate")+ .executeTakeFirst();+ if (unposted) {+ throw new InvalidInputError(+ `Post the lease run for ${unposted.scheduledDate} first: the months before the change must be on the books`+ );+ }+ // A month already posted — by a lease run or in an opening balance — is in+ // the GL. Rewriting it from an earlier date would post it twice, or leave+ // its amortization out of the carrying amounts below.+ const postedLater = await trx+ .selectFrom("revenueRecognitionSchedule as s")+ .innerJoin("leaseScheduleLine as l", (join) =>+ join+ .onRef("l.id", "=", "s.leaseScheduleLineId")+ .onRef("l.companyId", "=", "s.companyId")+ )+ .select(sql<string>`s."scheduledDate"::text`.as("scheduledDate"))+ .where("s.companyId", "=", companyId)+ .where("l.leaseLineId", "in", recognizedIds)+ .where("s.status", "=", "Posted")+ .where("s.scheduledDate", ">=", startDate)+ .orderBy("s.scheduledDate", "desc")+ .executeTakeFirst();+ if (postedLater) {+ throw new InvalidInputError(+ `The month ending ${postedLater.scheduledDate} is already posted; choose a date after it`+ );+ }+ const run = await heldByRun(trx, {+ companyId,+ leaseId: lease.id,+ fromDate: startDate,+ leaseLineIds: recognizedIds+ });+ if (run) {+ throw new InvalidInputError(+ `${run} holds this lease's entries from ${startDate}; delete or recalculate it first`+ );+ }+ refuseSkipped();++ const before = await trx+ .selectFrom("leaseScheduleLine")+ .select([+ "leaseLineId",+ "closingLiability",+ "rouAmortization",+ sql<string>`"periodDate"::text`.as("periodDate")+ ])+ .where("leaseLineId", "in", recognizedIds)+ .where("companyId", "=", companyId)+ .where("periodDate", "<", startDate)+ .orderBy("periodDate")+ .execute();+ for (const line of recognized) {+ carrying.set(+ line.id,+ lesseeCarryingAt({+ schedule: before.filter((row) => row.leaseLineId === line.id),+ startDate,+ initialLiability: line.initialLiability,+ rouAssetCost: line.rouAssetCost+ })+ );+ }+ return carrying;+ }++ /**+ * Deletes the Pending payment rows a change ends, for each asset: rows due+ * after `lastDay`, and its Purchase Option row. Returns, per asset, what the+ * deleted rows due on or before `lastDay` add back to the carrying+ * liability: the schedule already counted them as paid, and now they never+ * will be.+ */+ async function deleteEndedPayments(+ trx: Trx,+ args: { companyId: string; leaseLineIds: string[]; lastDay: string }+ ): Promise<Map<string, number>> {+ const addBack = new Map(args.leaseLineIds.map((id) => [id, 0]));+ if (args.leaseLineIds.length === 0) return addBack;+ const deleted = await trx+ .deleteFrom("leasePayment")+ .where("leaseLineId", "in", args.leaseLineIds)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Pending")+ .where((eb) =>+ eb.or([+ eb("dueDate", ">", args.lastDay),+ eb("paymentType", "=", "Purchase Option")+ ])+ )+ .returning([+ "leaseLineId",+ "amount",+ sql<string>`"dueDate"::text`.as("dueDate")+ ])+ .execute();+ for (const row of deleted) {+ if (row.dueDate > args.lastDay) continue;+ addBack.set(+ row.leaseLineId,+ round((addBack.get(row.leaseLineId) ?? 0) + Number(row.amount))+ );+ }+ return addBack;+ }++ type EventRow = {+ leaseLineId: string;+ eventType: "Modification" | "Termination" | "Purchase";+ effectiveDate: string;+ liabilityBefore: number;+ liabilityAfter: number;+ rouAssetBefore: number;+ rouAssetAfter: number;+ gainLoss: number;+ classificationBefore: Classification;+ classificationAfter: Classification;+ fixedAssetId?: string | null;+ journalId: string | null;+ notes?: string | null;+ };++ async function insertEvents(+ trx: Trx,+ args: { companyId: string; userId: string; leaseId: string; rows: EventRow[] }+ ) {+ if (args.rows.length === 0) return;+ await trx+ .insertInto("leaseEvent")+ .values(+ args.rows.map((row) => ({+ ...row,+ leaseId: args.leaseId,+ fixedAssetId: row.fixedAssetId ?? null,+ notes: row.notes ?? null,+ companyId: args.companyId,+ createdBy: args.userId+ }))+ )+ .execute();+ }++ /** Ends one asset and, when it was the last active one, the lease: the lease+ * takes the last asset's status and end date (spec Addendum A8). */+ async function endAsset(+ trx: Trx,+ args: {+ companyId: string;+ userId: string;+ lease: LeaseRow;+ lines: LeaseLineRow[];+ leaseLineId: string;+ status: "Terminated" | "Purchased";+ endDate: string;+ fixedAssetId?: string;+ }+ ): Promise<void> {+ const { companyId, userId } = args;+ const now = datetime.timestamp();+ await trx+ .updateTable("leaseLine")+ .set({+ status: args.status,+ ...(args.fixedAssetId ? { fixedAssetId: args.fixedAssetId } : {}),+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", args.leaseLineId)+ .where("companyId", "=", companyId)+ .execute();+ const stillActive = args.lines.some(+ (line) => line.id !== args.leaseLineId && line.status === "Active"+ );+ if (stillActive) return;+ await trx+ .updateTable("lease")+ .set({+ status: args.status,+ endDate: args.endDate,+ closedAt: now,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", args.lease.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ async function companyAccounting(trx: Trx, companyId: string) {+ const company = await trx+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ return loadLesseeAccounting(trx, {+ companyId,+ companyGroupId: company.companyGroupId+ });+ }++ export async function modify(+ scope: Scope,+ payload: Extract<LeasePayload, { type: "modify" }>+ ): Promise<{ id: string }> {+ const { db, companyId, userId } = scope;+ return db.transaction().execute(async (trx) => {+ const lease = await lockLease(trx, companyId, payload.leaseId);+ const lines = (await readLines(trx, companyId, lease.id)).filter(+ (line) => line.status === "Active"+ );+ if (lines.length === 0) {+ throw new InvalidInputError("The lease has no active asset to modify");+ }+ if (!lease.endDate) {+ throw new InvalidInputError(+ "An open-ended lease has no term to modify; terminate it and enter the new terms as a new lease"+ );+ }+ for (const entry of payload.lines) findLine(lines, entry.leaseLineId);+ const startDate = payload.effectiveDate;+ const carrying = await prepare(trx, {+ companyId,+ lease,+ lines,+ startDate,+ label: "modified"+ });+ if (+ lines.some((line) => line.lesseeClassification === "Short-Term") &&+ !isTermWithinTwelveMonths(lease.commencementDate, payload.endDate)+ ) {+ throw new InvalidInputError(+ "A short-term lease cannot run past 12 months; end it and enter the extension as a new lease"+ );+ }+ // `prepare` accepted the date as a lease-month boundary.+ const fromMonth = leaseMonthsAt(lease.commencementDate, startDate);++ // The remaining payments, cut again from the new terms. A Pending+ // purchase option the schedule paid before the date is never paid now:+ // it goes back into the carrying liability.+ const addBack = await deleteEndedPayments(trx, {+ companyId,+ leaseLineIds: lines.map((line) => line.id),+ lastDay: addDays(startDate, -1)+ });+ const decimals = await currencyDecimals(trx, companyId, lease.currencyCode);+ // The payment entered is the one at the effective date; an asset the+ // payload does not name keeps the rate it pays then.+ const paymentAtStart = (line: LeaseLineRow) =>+ payload.lines.find((entry) => entry.leaseLineId === line.id)+ ?.paymentAmount ??+ escalatedLeasePayment(+ line.paymentAmount,+ lease.annualEscalationPercent,+ fromMonth+ );+ const cut = new Map(+ lines.map((line) => [+ line.id,+ cutLeasePaymentRows({+ lease: {+ commencementDate: lease.commencementDate,+ endDate: payload.endDate,+ invoiceFromDate: lease.invoiceFromDate,+ paymentFrequency: payload.paymentFrequency,+ paymentTiming: lease.paymentTiming,+ annualEscalationPercent: payload.annualEscalationPercent+ },+ asset: line,+ decimals,+ from: { month: fromMonth, paymentAtStart: paymentAtStart(line) }+ })+ ])+ );+ const rowsOf = (line: LeaseLineRow) => cut.get(line.id)?.rows ?? [];+ const newRows = lines.flatMap((line) =>+ rowsOf(line).map((row) => ({+ ...row,+ leaseId: lease.id,+ companyId,+ createdBy: userId+ }))+ );+ if (newRows.length > 0) {+ await trx.insertInto("leasePayment").values(newRows).execute();+ }++ const now = datetime.timestamp();+ await trx+ .updateTable("lease")+ .set({+ endDate: payload.endDate,+ discountRate: payload.discountRate,+ paymentFrequency: payload.paymentFrequency,+ annualEscalationPercent: payload.annualEscalationPercent,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", lease.id)+ .where("companyId", "=", companyId)+ .execute();++ // Remeasure each recognized asset over what is left of the lease, and+ // reassess its classification (a Short-Term asset stays Short-Term).+ const { shortTermExpedient: _, ...thresholds } = await readThresholds(+ trx,+ companyId+ );+ const modified = { ...lease, discountRate: payload.discountRate };+ const span = lesseeScheduleSpan(+ lease.commencementDate,+ payload.endDate,+ fromMonth+ );+ const remeasured = lines+ .filter((line) => classificationOf(line) !== "Short-Term")+ .map((line) => {+ const rows = rowsOf(line);+ const points = paymentPoints(+ rows,+ lease.commencementDate,+ lease.paymentTiming,+ fromMonth+ );+ const carried = carrying.get(line.id)!;+ const before = {+ ...carried,+ liability: round(carried.liability + (addBack.get(line.id) ?? 0))+ };+ const result = remeasureLease({+ carryingLiability: before.liability,+ carryingRouAsset: before.rouAsset,+ remainingPayments: points,+ annualRate: payload.discountRate+ });+ const measured = measureAsset({+ line,+ payments: rows,+ fromMonth,+ endDate: payload.endDate,+ lease: modified,+ thresholds,+ shortTermExpedient: false+ });+ const after: "Operating" | "Finance" =+ line.classificationOverride === "Operating" ||+ line.classificationOverride === "Finance"+ ? line.classificationOverride+ : measured.classification === "Finance"+ ? "Finance"+ : "Operating";+ return { line, points, before, result, after, measured };+ });++ let journalId: string | null = null;+ if (remeasured.length > 0) {+ const accounting = await companyAccounting(trx, companyId);+ journalId = await postLesseeJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: startDate,+ description: `Lease Modification ${lease.leaseId}`,+ assets: remeasured.map(+ (asset): AssetLines => ({+ leaseLineId: asset.line.id,+ locationId: asset.line.locationId ?? lease.locationId,+ lines:+ asset.result.adjustment === 0 && asset.result.gain === 0+ ? []+ : remeasurementLines({+ adjustment: asset.result.adjustment,+ gain: asset.result.gain,+ accounts: accounting.accounts+ })+ })+ ),+ lease+ });++ await deleteSchedulesFrom(trx, {+ companyId,+ leaseLineIds: remeasured.map((asset) => asset.line.id),+ startDate+ });+ await writeSchedules(trx, {+ leaseId: lease.id,+ schedules: remeasured.map(+ (asset): AssetSchedule => ({+ // The months after the change are still the commencement's.+ leaseLineId: asset.line.id,+ commencementDate: lease.commencementDate,+ fromMonth,+ classification: asset.after,+ lines: buildLesseeSchedule({+ openingLiability: asset.result.liability,+ openingRouAsset: asset.result.rouAsset,+ payments: asset.points,+ months: span.months,+ annualRate: payload.discountRate,+ timing: lease.paymentTiming,+ classification: asset.after,+ amortizationMonths: amortizationMonths(+ asset.line,+ span.months,+ fromMonth+ ),+ periodDates: span.periodDates,+ lastMonthShare: span.lastMonthShare+ })+ })+ ),+ accounts: accounting.accounts,+ companyId,+ userId+ });+ }++ await updateLineMeasurements(trx, {+ companyId,+ userId,+ rows: lines.map((line) => {+ const asset = remeasured.find((row) => row.line.id === line.id);+ return {+ id: line.id,+ paymentAmount: cut.get(line.id)!.commencementPayment,+ lesseeClassification: asset?.after ?? "Short-Term",+ ...(asset+ ? {+ classificationInputs: asset.measured.classificationInputs,+ rouAssetCost: round(+ Number(line.rouAssetCost ?? 0) ++ asset.result.rouAsset -+ asset.before.rouAsset+ )+ }+ : {})+ };+ })+ });+ await insertEvents(trx, {+ companyId,+ userId,+ leaseId: lease.id,+ rows: lines.map((line) => {+ const asset = remeasured.find((row) => row.line.id === line.id);+ const before = classificationOf(line);+ return {+ leaseLineId: line.id,+ eventType: "Modification",+ effectiveDate: startDate,+ liabilityBefore: asset?.before.liability ?? 0,+ liabilityAfter: asset?.result.liability ?? 0,+ rouAssetBefore: asset?.before.rouAsset ?? 0,+ rouAssetAfter: asset?.result.rouAsset ?? 0,+ gainLoss: asset?.result.gain ?? 0,+ classificationBefore: before,+ classificationAfter: asset?.after ?? before,+ journalId: asset ? journalId : null,+ notes: payload.notes+ };+ })+ });+ return { id: lease.id };+ });+ }++ export async function terminate(+ scope: Scope,+ payload: Extract<LeasePayload, { type: "terminate" }>+ ): Promise<{ id: string }> {+ const { db, companyId, userId } = scope;+ return db.transaction().execute(async (trx) => {+ const lease = await lockLease(trx, companyId, payload.leaseId);+ const lines = await readLines(trx, companyId, lease.id);+ const line = findLine(lines, payload.leaseLineId);+ const endOfLease = payload.terminationDate;+ if (endOfLease < lease.commencementDate) {+ throw new InvalidInputError(+ `The termination date cannot be before the commencement date, ${lease.commencementDate}`+ );+ }+ const startDate = addDays(endOfLease, 1);+ const carrying = (+ await prepare(trx, {+ companyId,+ lease,+ lines: [line],+ startDate,+ label: "terminated"+ })+ ).get(line.id)!;+ const before = classificationOf(line);++ // Payments after the date are never owed, nor is the purchase option; a+ // penalty is a final row.+ const addBack =+ (+ await deleteEndedPayments(trx, {+ companyId,+ leaseLineIds: [line.id],+ lastDay: endOfLease+ })+ ).get(line.id) ?? 0;+ if (payload.penaltyAmount > 0) {+ await trx+ .insertInto("leasePayment")+ .values({+ leaseId: lease.id,+ leaseLineId: line.id,+ paymentType: "Termination Penalty",+ periodStart: endOfLease,+ periodEnd: endOfLease,+ dueDate: endOfLease,+ amount: payload.penaltyAmount,+ status: "Pending",+ companyId,+ createdBy: userId+ })+ .execute();+ }++ let journalId: string | null = null;+ let gainLoss = 0;+ const carryingLiability = round(carrying.liability + addBack);+ if (before !== "Short-Term") {+ const accounting = await companyAccounting(trx, companyId);+ const termination = terminationLines({+ carryingLiability,+ penalty: payload.penaltyAmount,+ rouAssetCost: Number(line.rouAssetCost ?? 0),+ accumulated: carrying.accumulated,+ accounts: accounting.accounts+ });+ gainLoss = termination.gainLoss;+ journalId = await postLesseeJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: endOfLease,+ description: `Lease Termination ${lease.leaseId} ${line.description}`,+ assets: [+ {+ leaseLineId: line.id,+ locationId: line.locationId ?? lease.locationId,+ lines: termination.lines+ }+ ],+ lease+ });+ await deleteSchedulesFrom(trx, {+ companyId,+ leaseLineIds: [line.id],+ startDate+ });+ }++ await endAsset(trx, {+ companyId,+ userId,+ lease,+ lines,+ leaseLineId: line.id,+ status: "Terminated",+ endDate: endOfLease+ });+ await insertEvents(trx, {+ companyId,+ userId,+ leaseId: lease.id,+ rows: [+ {+ leaseLineId: line.id,+ eventType: "Termination",+ effectiveDate: endOfLease,+ liabilityBefore: carryingLiability,+ liabilityAfter: payload.penaltyAmount,+ rouAssetBefore: carrying.rouAsset,+ rouAssetAfter: 0,+ gainLoss,+ classificationBefore: before,+ classificationAfter: before,+ journalId,+ notes: payload.notes+ }+ ]+ });+ return { id: lease.id };+ });+ }++ export async function purchase(+ scope: Scope,+ payload: Extract<LeasePayload, { type: "purchase" }>+ ): Promise<{ id: string }> {+ const { db, companyId, userId } = scope;+ return db.transaction().execute(async (trx) => {+ const lease = await lockLease(trx, companyId, payload.leaseId);+ const lines = await readLines(trx, companyId, lease.id);+ const line = findLine(lines, payload.leaseLineId);+ if (line.lesseeClassification === "Short-Term") {+ throw new InvalidInputError(+ "A short-term asset has no right-of-use asset to purchase; end it and buy the asset on a purchase order"+ );+ }+ if (!lease.endDate) {+ throw new InvalidInputError(+ "An open-ended lease is short-term and has no right-of-use asset to purchase; end it and buy the asset on a purchase order"+ );+ }+ const exerciseDate = payload.exerciseDate;+ if (exerciseDate < lease.commencementDate) {+ throw new InvalidInputError(+ `The exercise date cannot be before the commencement date, ${lease.commencementDate}`+ );+ }+ // An asset whose ownership transfers is the lessee's at the end of the+ // lease with no option to exercise: it is "purchased" then, for nothing.+ const hasOption = (line.purchaseOptionAmount ?? 0) > 0;+ if (!hasOption) {+ if (!line.ownershipTransfers) {+ throw new InvalidInputError(+ `${line.description} has no purchase option`+ );+ }+ if (exerciseDate !== lease.endDate) {+ throw new InvalidInputError(+ `Ownership of ${line.description} passes at the end of the lease; take it on ${lease.endDate}`+ );+ }+ if (!equals(payload.purchasePrice, 0)) {+ throw new InvalidInputError(+ `${line.description} has no purchase option: ownership passes at the end of the lease for nothing, so the price is 0`+ );+ }+ }+ const startDate = addDays(exerciseDate, 1);+ const carrying = (+ await prepare(trx, {+ companyId,+ lease,+ lines: [line],+ startDate,+ label: "purchased"+ })+ ).get(line.id)!;++ const assetClass = await trx+ .selectFrom("fixedAssetClass")+ .select([+ "id",+ "assetAccountId",+ "depreciationMethod",+ "usefulLifeMonths",+ "residualValuePercent",+ "isConstructionInProgress"+ ])+ .where("id", "=", payload.fixedAssetClassId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!assetClass || assetClass.isConstructionInProgress) {+ throw new InvalidInputError("Choose an in-service fixed asset class");+ }+ // `account` is group-scoped; the id came from this company's class.+ const assetAccount = await trx+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "=", assetClass.assetAccountId)+ .executeTakeFirst();+ if (!assetAccount?.class) {+ throw new InvalidInputError(+ "The fixed asset class's asset account has no class"+ );+ }+ const assetAccountWithClass = {+ id: assetAccount.id,+ class: assetAccount.class+ };++ // An option row already invoiced on or before the exercise date is the+ // price: its invoice settles the liability, so nothing more is payable.+ const invoicedOption = await trx+ .selectFrom("leasePayment")+ .select(["amount"])+ .where("leaseLineId", "=", line.id)+ .where("companyId", "=", companyId)+ .where("paymentType", "=", "Purchase Option")+ .where("status", "=", "Invoiced")+ .where("dueDate", "<=", exerciseDate)+ .executeTakeFirst();+ if (+ invoicedOption &&+ round(Number(invoicedOption.amount)) !== round(payload.purchasePrice)+ ) {+ throw new InvalidInputError(+ `The purchase option is already invoiced at ${Number(invoicedOption.amount)}; exercise it at that price or delete the invoice`+ );+ }++ // Otherwise the option is paid once, on the exercise date; nothing after+ // it. A Pending option row the schedule already counted as paid goes back+ // into the carrying liability before the price replaces it.+ const addBack =+ (+ await deleteEndedPayments(trx, {+ companyId,+ leaseLineIds: [line.id],+ lastDay: exerciseDate+ })+ ).get(line.id) ?? 0;+ if (!invoicedOption && payload.purchasePrice > 0) {+ await trx+ .insertInto("leasePayment")+ .values({+ leaseId: lease.id,+ leaseLineId: line.id,+ paymentType: "Purchase Option",+ periodStart: exerciseDate,+ periodEnd: exerciseDate,+ dueDate: exerciseDate,+ amount: payload.purchasePrice,+ status: "Pending",+ companyId,+ createdBy: userId+ })+ .execute();+ }++ const carryingLiability = round(carrying.liability + addBack);+ const accounting = await companyAccounting(trx, companyId);+ const purchased = purchaseLines({+ carryingLiability,+ price: invoicedOption ? 0 : payload.purchasePrice,+ rouAssetCost: Number(line.rouAssetCost ?? 0),+ accumulated: carrying.accumulated,+ assetAccount: assetAccountWithClass,+ accounts: accounting.accounts+ });+ const journalId = await postLesseeJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: exerciseDate,+ description: `Lease Purchase ${lease.leaseId} ${line.description}`,+ assets: [+ {+ leaseLineId: line.id,+ locationId: line.locationId ?? lease.locationId,+ lines: purchased.lines+ }+ ],+ lease+ });++ const asset = await trx+ .insertInto("fixedAsset")+ .values({+ fixedAssetId: await getNextSequence(trx, "fixedAsset", companyId),+ fixedAssetClassId: assetClass.id,+ name: payload.name,+ serialNumber: line.serialNumber,+ locationId: line.locationId ?? lease.locationId,+ quantity: 1,+ acquisitionCost: purchased.assetCost,+ acquisitionDate: exerciseDate,+ depreciationStartDate: exerciseDate,+ depreciationMethod: assetClass.depreciationMethod,+ usefulLifeMonths: assetClass.usefulLifeMonths,+ residualValuePercent: assetClass.residualValuePercent,+ status: "Active",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ await deleteSchedulesFrom(trx, {+ companyId,+ leaseLineIds: [line.id],+ startDate+ });+ await endAsset(trx, {+ companyId,+ userId,+ lease,+ lines,+ leaseLineId: line.id,+ status: "Purchased",+ endDate: exerciseDate,+ fixedAssetId: asset.id+ });+ const classification = classificationOf(line);+ await insertEvents(trx, {+ companyId,+ userId,+ leaseId: lease.id,+ rows: [+ {+ leaseLineId: line.id,+ eventType: "Purchase",+ effectiveDate: exerciseDate,+ liabilityBefore: carryingLiability,+ liabilityAfter: invoicedOption ? 0 : payload.purchasePrice,+ rouAssetBefore: carrying.rouAsset,+ rouAssetAfter: 0,+ gainLoss: 0,+ classificationBefore: classification,+ classificationAfter: classification,+ fixedAssetId: asset.id,+ journalId,+ notes: payload.notes+ }+ ]+ });+ return { id: lease.id };+ });+ }+ /**+ * Payload contract and pure blockers for `post-lease` (a lessee lease, spec+ * `.ai/specs/2026-10-11-lessee-leases.md`). No I/O, so the server function's+ * decisions can be pinned without a database.+ */++ // Calendar dates travel as `YYYY-MM-DD` text end to end: a JavaScript Date+ // would shift the day by the runtime timezone.+ const calendarDate = z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date");++ // companyId and userId come from the server function's context, not the input.+ const scope = { leaseId: z.string().min(1) };++ // Terminate and Purchase act on one leased asset (one lease component).+ const asset = { leaseLineId: z.string().min(1) };++ /** Draft → Active: classify, measure, post the commencement journal and+ * write the monthly schedule. */+ export const activateValidator = z.object({+ type: z.literal("activate"),+ ...scope+ });++ /** Draft (delete), or Active with nothing invoiced or posted (void the+ * commencement journal) → Cancelled. */+ export const cancelValidator = z.object({+ type: z.literal("cancel"),+ ...scope+ });++ /** Remeasure every active asset from an effective date: the remaining+ * payments are cut again from these terms. An active asset the payload does+ * not name keeps its payment amount. */+ export const modifyValidator = z+ .object({+ type: z.literal("modify"),+ ...scope,+ effectiveDate: calendarDate,+ endDate: calendarDate,+ discountRate: z.number().min(0),+ paymentFrequency: z.enum(["Monthly", "Quarterly", "Annual"]),+ annualEscalationPercent: z.number().min(0).default(0),+ lines: z+ .array(+ z.object({+ leaseLineId: z.string().min(1),+ paymentAmount: z.number().min(0)+ })+ )+ .default([]),+ notes: z.string().optional().nullable()+ })+ .refine((value) => value.endDate >= value.effectiveDate, {+ message: "The end date cannot be before the effective date",+ path: ["endDate"]+ });++ /** End one asset early: derecognize its ROU asset and its liability. */+ export const terminateValidator = z.object({+ type: z.literal("terminate"),+ ...scope,+ ...asset,+ terminationDate: calendarDate,+ penaltyAmount: z.number().min(0).default(0),+ notes: z.string().optional().nullable()+ });++ /** Exercise one asset's purchase option: its ROU asset becomes a fixed+ * asset. */+ export const purchaseValidator = z.object({+ type: z.literal("purchase"),+ ...scope,+ ...asset,+ exerciseDate: calendarDate,+ purchasePrice: z.number().min(0),+ fixedAssetClassId: z.string().min(1),+ name: z.string().trim().min(1),+ notes: z.string().optional().nullable()+ });++ export const payloadValidator = z.discriminatedUnion("type", [+ activateValidator,+ cancelValidator,+ modifyValidator,+ terminateValidator,+ purchaseValidator+ ]);++ export type LeasePayload = z.infer<typeof payloadValidator>;++ /** Why an open-ended lease cannot activate without the short-term expedient,+ * and the two ways to fix it. An open-ended lease can be ended on notice, so+ * its term is short (ASC 842-10-30-1) and carrying it on the balance sheet+ * one notice period at a time is not supported. */+ export const OPEN_ENDED_NEEDS_EXPEDIENT =+ "An open-ended lease is a short-term lease, and this company has the short-term lease expedient turned off. Turn on Short-Term Lease Expedient in Settings → Accounting, or give the lease a fixed duration on its Details step.";++ /** Why a Draft lease cannot activate, or null. */+ export function activateBlocker(args: {+ status: string;+ assetCount: number;+ /** The descriptions of the assets that have no payment row. */+ assetsWithoutPayments: string[];+ currencyCode: string;+ baseCurrencyCode: string | null;+ }): string | null {+ if (args.status !== "Draft") {+ return `The lease is ${args.status}; only a Draft lease can be activated`;+ }+ if (args.assetCount === 0) {+ return "A lease needs at least one asset to activate";+ }+ if (args.assetsWithoutPayments.length > 0) {+ return `Every asset needs a payment row to activate: ${args.assetsWithoutPayments.join(", ")}`;+ }+ if (args.baseCurrencyCode && args.currencyCode !== args.baseCurrencyCode) {+ return "Leases in a foreign currency are not supported yet";+ }+ return null;+ }+ // The lifecycle of a lessee lease (spec `.ai/specs/2026-10-11-lessee-leases.md`).+ // A lease holds one or more assets (`leaseLine`); each asset is a separate+ // lease component (ASC 842-10-15-28) with its own classification,+ // measurement, payment rows and schedule. Each action is ONE transaction that+ // locks the lease row first:+ //+ // activate Draft → Active: classify each asset (ASC 842-10-25-2 or the+ // short-term election), measure its liability at the PV of its+ // payment rows, post ONE commencement journal with lines per+ // asset and write each asset's monthly schedule with its lease+ // run rows. A Short-Term asset posts nothing: its invoices go to+ // lease expense. A lease that started before the accounting+ // cutover posts an opening balance instead (spec Q8).+ // cancel Active with nothing invoiced, posted by a run, modified or+ // ended → Cancelled, the commencement journal voided. A Draft+ // is deleted instead (the app's delete route).+ // modify remeasure every active asset from an effective date+ // (lifecycle.ts).+ // terminate end one asset early, derecognize it, gain or loss+ // (lifecycle.ts).+ // purchase exercise one asset's purchase option into a fixed asset+ // (lifecycle.ts).+ //+ // Business-validation failures are 400s (InvalidInputError) with the message+ // the app shows; a record the caller's company does not own is a 404.++ /** The carrying liability and the accumulated ROU amortization a schedule+ * reaches before `asOf`: the last line's closing liability (the initial+ * liability when no line falls before it) and every earlier line's+ * amortization. */+ export function balancesBefore(+ lines: LesseeScheduleLine[],+ asOf: string,+ initialLiability: number+ ): { carryingLiability: number; accumulated: number } {+ const before = lines.filter((line) => line.periodDate < asOf);+ return {+ carryingLiability: before.at(-1)?.closingLiability ?? initialLiability,+ accumulated: round(+ before.reduce((sum, line) => sum + line.rouAmortization, 0)+ )+ };+ }++ /** Why a Skipped payment of a capitalized asset cannot activate, or null.+ * Skipped means paid outside Carbon (before Invoice From): its invoice will+ * never relieve the lease liability, so it must be one the opening balance+ * holds. A payment due before the commencement is not in the schedule's+ * months and is left alone. */+ export function skippedPaymentBlocker(+ payment: Pick<+ LeasePaymentRow,+ "periodStart" | "periodEnd" | "dueDate" | "paymentType" | "status"+ >,+ args: {+ description: string;+ lease: Pick<LeaseRow, "commencementDate" | "paymentTiming">;+ periodDates: string[];+ /** The opening balance's as-of date; null when there is none. */+ openingAsOf: string | null;+ }+ ): string | null {+ if (payment.status !== "Skipped") return null;+ if (payment.dueDate < args.lease.commencementDate) return null;+ if (+ args.openingAsOf &&+ isPaidBeforeOpening(payment, {+ commencementDate: args.lease.commencementDate,+ timing: args.lease.paymentTiming,+ periodDates: args.periodDates,+ asOf: args.openingAsOf+ })+ ) {+ return null;+ }+ const settledBy = args.openingAsOf+ ? `the opening balance on ${args.openingAsOf} still owes it`+ : "only its invoice settles the lease liability";+ return `${args.description}: the payment due ${payment.dueDate} is Skipped (paid outside Carbon), but ${settledBy}. Set Invoice From on or before ${payment.dueDate} so it is invoiced.`;+ }++ /** The retained earnings account default, with its class: an opening+ * balance's difference goes there. */+ async function retainedEarningsAccount(+ trx: Trx,+ companyId: string+ ): Promise<LeaseAccount> {+ const row = await trx+ .selectFrom("accountDefault")+ .innerJoin(+ "account",+ "account.id",+ "accountDefault.retainedEarningsAccount"+ )+ .select(["account.id", "account.class"])+ .where("accountDefault.companyId", "=", companyId)+ .executeTakeFirst();+ if (!row?.class) {+ throw new InvalidInputError(+ "Set the retained earnings account in Accounting → Default Accounts before activating a lease that started before accounting was set up"+ );+ }+ return { id: row.id, class: row.class };+ }++ async function activate(+ scope: Scope,+ payload: Extract<LeasePayload, { type: "activate" }>+ ): Promise<{ id: string }> {+ const { db, companyId, userId } = scope;+ return db.transaction().execute(async (trx) => {+ const lease = await lockLease(trx, companyId, payload.leaseId);+ const lines = await readLines(trx, companyId, lease.id);+ const payments = await readPayments(trx, companyId, lease.id);+ const paymentsOf = (line: LeaseLineRow) =>+ payments.filter((payment) => payment.leaseLineId === line.id);++ const company = await trx+ .selectFrom("company")+ .select(["baseCurrencyCode", "companyGroupId"])+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ const blocker = activateBlocker({+ status: lease.status,+ assetCount: lines.length,+ assetsWithoutPayments: lines+ .filter((line) => paymentsOf(line).length === 0)+ .map((line) => line.description),+ currencyCode: lease.currencyCode,+ baseCurrencyCode: company.baseCurrencyCode+ });+ if (blocker) throw new InvalidInputError(blocker);++ const { shortTermExpedient, ...thresholds } = await readThresholds(+ trx,+ companyId+ );+ // An open-ended lease can be ended on notice, so every asset is+ // short-term (spec Addendum A10); it needs the expedient.+ const endDate = lease.endDate;+ if (!endDate && !shortTermExpedient) {+ throw new InvalidInputError(OPEN_ENDED_NEEDS_EXPEDIENT);+ }+ const measured: MeasuredAsset[] = lines.map((line) =>+ endDate+ ? measureAsset({+ line,+ payments: paymentsOf(line),+ endDate,+ lease,+ thresholds,+ shortTermExpedient+ })+ : {+ line,+ liability: 0,+ classification: "Short-Term",+ classificationInputs: { openEnded: true }+ }+ );+ const recognized = measured.filter(+ (+ asset+ ): asset is MeasuredAsset & {+ classification: "Operating" | "Finance";+ } => asset.classification !== "Short-Term"+ );+ const now = datetime.timestamp();++ let commencementJournalId: string | null = null;+ if (endDate && recognized.length > 0) {+ const span = lesseeScheduleSpan(lease.commencementDate, endDate);++ // A lease that started before the accounting cutover opens with the+ // balances its schedules reach on the as-of date (spec Q8) — the+ // cutover, or the first open period after it — and the months before+ // that are already in the opening equity: written Posted with no+ // journal. The payments those months pay are in that balance too, so+ // they are not invoiced.+ const cutoverDate = await readAccountingCutoverDate(trx, companyId);+ const openingAsOf =+ cutoverDate && lease.commencementDate < cutoverDate+ ? (+ await resolveAccountingPeriod(+ trx,+ companyId,+ cutoverDate,+ "historical-with-shift"+ )+ ).postingDate+ : null;+ for (const asset of recognized) {+ for (const payment of paymentsOf(asset.line)) {+ const skipped = skippedPaymentBlocker(payment, {+ description: asset.line.description,+ lease,+ periodDates: span.periodDates,+ openingAsOf+ });+ if (skipped) throw new InvalidInputError(skipped);+ }+ }++ const accounting = await loadLesseeAccounting(trx, {+ companyId,+ companyGroupId: company.companyGroupId+ });+ const schedules: AssetSchedule[] = recognized.map((asset) => ({+ leaseLineId: asset.line.id,+ commencementDate: lease.commencementDate,+ fromMonth: 0,+ classification: asset.classification,+ lines: buildLesseeSchedule({+ openingLiability: asset.liability,+ openingRouAsset: asset.liability,+ payments: paymentPoints(+ paymentsOf(asset.line),+ lease.commencementDate,+ lease.paymentTiming+ ),+ months: span.months,+ annualRate: lease.discountRate,+ timing: lease.paymentTiming,+ classification: asset.classification,+ amortizationMonths: amortizationMonths(asset.line, span.months),+ periodDates: span.periodDates,+ lastMonthShare: span.lastMonthShare+ })+ }));++ const retainedEarnings = openingAsOf+ ? await retainedEarningsAccount(trx, companyId)+ : null;+ const assets: AssetLines[] = recognized.map((asset, index) => ({+ leaseLineId: asset.line.id,+ locationId: asset.line.locationId ?? lease.locationId,+ lines:+ openingAsOf && retainedEarnings+ ? openingBalanceLines({+ ...balancesBefore(+ schedules[index]!.lines,+ openingAsOf,+ asset.liability+ ),+ rouAssetCost: asset.liability,+ retainedEarnings,+ accounts: accounting.accounts+ })+ : commencementLines({+ liability: asset.liability,+ accounts: accounting.accounts+ })+ }));+ commencementJournalId = await postLesseeJournal(trx, {+ accounting,+ companyId,+ userId,+ postingDate: openingAsOf ?? lease.commencementDate,+ description: `${openingAsOf ? "Lease Opening Balance" : "Lease Commencement"} ${lease.leaseId}`,+ assets,+ lease+ });++ await writeSchedules(trx, {+ leaseId: lease.id,+ schedules,+ accounts: accounting.accounts,+ companyId,+ userId,+ postedBefore: openingAsOf ?? undefined+ });++ const inOpening = openingAsOf+ ? recognized.flatMap((asset) =>+ paymentsOf(asset.line)+ .filter(+ (payment) =>+ payment.status === "Pending" &&+ isPaidBeforeOpening(payment, {+ commencementDate: lease.commencementDate,+ timing: lease.paymentTiming,+ periodDates: span.periodDates,+ asOf: openingAsOf+ })+ )+ .map((payment) => payment.id)+ )+ : [];+ if (inOpening.length > 0) {+ await trx+ .updateTable("leasePayment")+ .set({ status: "Skipped", updatedBy: userId, updatedAt: now })+ .where("id", "in", inOpening)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ await updateLineMeasurements(trx, {+ companyId,+ userId,+ rows: measured.map((asset) => {+ const isRecognized = asset.classification !== "Short-Term";+ return {+ id: asset.line.id,+ lesseeClassification: asset.classification,+ classificationInputs: asset.classificationInputs,+ initialLiability: isRecognized ? asset.liability : null,+ rouAssetCost: isRecognized ? asset.liability : null+ };+ })+ });+ await trx+ .updateTable("lease")+ .set({+ status: "Active",+ commencementJournalId,+ activatedAt: now,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", lease.id)+ .where("companyId", "=", companyId)+ .execute();+ return { id: lease.id };+ });+ }++ async function cancel(+ scope: Scope,+ payload: Extract<LeasePayload, { type: "cancel" }>+ ): Promise<{ id: string }> {+ const { db, companyId, userId } = scope;+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+ return db.transaction().execute(async (trx: Trx) => {+ const lease = await lockLease(trx, companyId, payload.leaseId);+ if (lease.status === "Draft") {+ throw new InvalidInputError(+ "A Draft lease is deleted, not cancelled; delete it instead"+ );+ }+ if (lease.status !== "Active") {+ throw new InvalidInputError(+ `The lease is ${lease.status}; only an Active lease with nothing invoiced or posted can be cancelled`+ );+ }++ // Cancel undoes the activation and nothing else: once an asset has+ // ended or the lease has changed, its journals and its fixed asset are+ // history that a void would leave half undone.+ const ended = (await readLines(trx, companyId, lease.id)).find(+ (line) => line.status !== "Active"+ );+ if (ended) {+ throw new InvalidInputError(+ `${ended.description} is ${ended.status}; a lease with an ended asset cannot be cancelled. Terminate its other assets instead.`+ );+ }+ const event = await trx+ .selectFrom("leaseEvent")+ .select("eventType")+ .where("leaseId", "=", lease.id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (event) {+ throw new InvalidInputError(+ `The lease has a ${event.eventType} since it commenced; terminate it instead`+ );+ }+ const invoiced = await trx+ .selectFrom("leasePayment")+ .select("id")+ .where("leaseId", "=", lease.id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Invoiced")+ .executeTakeFirst();+ if (invoiced) {+ throw new InvalidInputError(+ "A payment of this lease is already invoiced; terminate the lease instead"+ );+ }+ const run = await heldByRun(trx, { companyId, leaseId: lease.id });+ if (run) {+ throw new InvalidInputError(+ `${run} holds this lease's entries; delete or recalculate it first`+ );+ }+ // Rows an opening balance wrote Posted carry no run line; voiding the+ // opening journal takes them back out with the rest.+ const posted = await trx+ .selectFrom("revenueRecognitionSchedule")+ .select("id")+ .where("leaseId", "=", lease.id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Posted")+ .where("runLineId", "is not", null)+ .executeTakeFirst();+ if (posted) {+ throw new InvalidInputError(+ "A lease run has posted entries of this lease; terminate the lease instead"+ );+ }++ // The only journal an unchanged lease has: its commencement (or opening+ // balance). A Short-Term lease has none.+ if (lease.commencementJournalId) {+ const journal = await trx+ .selectFrom("journal")+ .select(sql<string>`"postingDate"::text`.as("postingDate"))+ .where("id", "=", lease.commencementJournalId)+ .where("companyId", "=", companyId)+ .executeTakeFirstOrThrow();+ const cutoverDate = await readAccountingCutoverDate(trx, companyId);+ if (isBeforeCutover(journal.postingDate, cutoverDate)) {+ throw new InvalidInputError(+ "This lease commenced before accounting was set up; its balances came from the opening journal. Terminate it instead."+ );+ }+ await voidLeaseJournal(trx, {+ journalId: lease.commencementJournalId,+ postingStatus: await journalPostingStatus(trx, companyId),+ companyId,+ userId,+ today+ });+ }++ // The Planned run rows cascade with their schedule lines.+ await trx+ .deleteFrom("leaseScheduleLine")+ .where("leaseId", "=", lease.id)+ .where("companyId", "=", companyId)+ .execute();+ const now = datetime.timestamp();+ await trx+ .updateTable("lease")+ .set({+ status: "Cancelled",+ closedAt: now,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", lease.id)+ .where("companyId", "=", companyId)+ .execute();+ return { id: lease.id };+ });+ }++ export const postLeaseInput = payloadValidator;++ export type PostLeaseInput = LeasePayload;++ export const postLeaseActionPermission = {+ update: "purchasing"+ } satisfies PermissionRule<z.output<typeof postLeaseInput>>;++ export async function postLeaseAction(+ ctx: ServiceContext,+ raw: z.input<typeof postLeaseInput>+ ) {+ const payload = postLeaseInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const scope = { db, companyId, userId };+ switch (payload.type) {+ case "activate":+ return activate(scope, payload);+ case "cancel":+ return cancel(scope, payload);+ case "modify":+ return modify(scope, payload);+ case "terminate":+ return terminate(scope, payload);+ case "purchase":+ return purchase(scope, payload);+ }+ }+ export type LeaseInvoiceGenerationArgs = {+ companyId: string;+ /** `YYYY-MM-DD` in the company's timezone: rows due on or before it are+ * billed. */+ asOf: string;+ /** Bill one lease only (the lease page's action). */+ leaseId?: string;+ userId: string;+ };++ /** One invoice the generator drafted. */+ export type DraftedLeaseInvoice = {+ invoiceId: string;+ leaseId: string;+ };++ export type LeaseInvoiceGenerationFailure = {+ leaseId: string;+ error: string;+ };++ export type LeaseInvoiceGenerationResult = {+ invoices: DraftedLeaseInvoice[];+ /** `invoices.map(i => i.invoiceId)`. */+ invoiceIds: string[];+ /** Leases whose transaction rolled back; their rows stay Pending. */+ failures: LeaseInvoiceGenerationFailure[];+ };++ /**+ * Drafts the purchase invoices of every lease with a Pending payment row due+ * on or before `asOf`: one Draft invoice per lease and due date, one Lease+ * line per row (a lease with several assets has a row per asset). Each+ * lease is its own transaction, so one lease's failure never rolls back another's invoice. The billed rows are stamped Invoiced+ * with their invoice line, which is what makes a second call for the same+ * day a no-op; deleting the Draft invoice or voiding a posted one returns+ * them to Pending.+ */+ async function createLeaseInvoicesForDuePayments(+ db: Kysely<KyselyDatabase>,+ args: LeaseInvoiceGenerationArgs+ ): Promise<LeaseInvoiceGenerationResult> {+ const { companyId, asOf, leaseId } = args;++ let dueQuery = db+ .selectFrom("lease")+ .select("lease.id")+ .where("lease.companyId", "=", companyId)+ // An ended lease can still owe a termination penalty, a purchase+ // price, or a row a voided invoice returned to Pending.+ .where("lease.status", "in", BILLABLE_LEASE_STATUSES)+ .where((eb) =>+ eb.or([+ eb.exists(+ eb+ .selectFrom("leasePayment as p")+ .select("p.id")+ .whereRef("p.leaseId", "=", "lease.id")+ .whereRef("p.companyId", "=", "lease.companyId")+ .where("p.status", "=", "Pending")+ .where("p.dueDate", "<=", asOf)+ ),+ // An Active open-ended lease's next rows are cut by this run.+ eb.and([+ eb("lease.status", "=", "Active"),+ eb("lease.endDate", "is", null)+ ])+ ])+ )+ .orderBy("lease.leaseId");+ if (leaseId) dueQuery = dueQuery.where("lease.id", "=", leaseId);+ const leases = await dueQuery.execute();++ const invoices: DraftedLeaseInvoice[] = [];+ const failures: LeaseInvoiceGenerationFailure[] = [];+ for (const lease of leases) {+ try {+ const drafted = await db+ .transaction()+ .execute((trx) => draftLeaseInvoices(trx, args, lease.id));+ invoices.push(...drafted);+ } catch (error) {+ failures.push({+ leaseId: lease.id,+ error: error instanceof Error ? error.message : String(error)+ });+ }+ }+ return {+ invoices,+ invoiceIds: invoices.map((i) => i.invoiceId),+ failures+ };+ }++ async function draftLeaseInvoices(+ trx: KyselyTx,+ args: LeaseInvoiceGenerationArgs,+ leaseId: string+ ): Promise<DraftedLeaseInvoice[]> {+ const { companyId, asOf, userId } = args;++ const lease = await trx+ .selectFrom("lease")+ .select([+ "id",+ "status",+ "endDate",+ "supplierId",+ "supplierContactId",+ "supplierLocationId",+ "locationId",+ "currencyCode"+ ])+ .where("id", "=", leaseId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (!isBillableLeaseStatus(lease.status)) return [];+ if (lease.status === "Active" && lease.endDate === null) {+ await rollOpenEndedLeasePayments(trx, { companyId, userId, leaseId, asOf });+ }++ const rows = await trx+ .selectFrom("leasePayment as p")+ .innerJoin("leaseLine as l", (join) =>+ join+ .onRef("l.id", "=", "p.leaseLineId")+ .onRef("l.companyId", "=", "p.companyId")+ )+ .select([+ "p.id",+ "p.paymentType",+ "p.amount",+ sql<string>`p."periodStart"::text`.as("periodStart"),+ sql<string>`p."periodEnd"::text`.as("periodEnd"),+ sql<string>`p."dueDate"::text`.as("dueDate"),+ "l.description",+ "l.locationId"+ ])+ .where("p.leaseId", "=", leaseId)+ .where("p.companyId", "=", companyId)+ .where("p.status", "=", "Pending")+ .where("p.dueDate", "<=", asOf)+ .orderBy("p.dueDate")+ .orderBy("l.sortOrder")+ .orderBy("p.paymentType")+ .forUpdate("p")+ .execute();+ if (rows.length === 0) return [];++ const payment = await trx+ .selectFrom("supplierPayment")+ .select([+ "invoiceSupplierId",+ "invoiceSupplierContactId",+ "invoiceSupplierLocationId",+ "paymentTermId"+ ])+ .where("supplierId", "=", lease.supplierId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ const byDueDate = new Map<string, typeof rows>();+ for (const row of rows) {+ const group = byDueDate.get(row.dueDate) ?? [];+ group.push(row);+ byDueDate.set(row.dueDate, group);+ }++ const drafted: DraftedLeaseInvoice[] = [];+ for (const [dueDate, group] of byDueDate) {+ const subtotal = round(+ group.reduce((sum, row) => sum + Number(row.amount), 0)+ );+ const invoiceId = await getNextSequence(trx, "purchaseInvoice", companyId);+ // Every purchase invoice hangs off a supplier interaction, as the ERP's+ // `insertPurchaseInvoice` creates one.+ const interaction = await trx+ .insertInto("supplierInteraction")+ .values({ companyId, supplierId: lease.supplierId })+ .returning("id")+ .executeTakeFirstOrThrow();+ const invoice = await trx+ .insertInto("purchaseInvoice")+ .values({+ invoiceId,+ status: "Draft",+ supplierId: lease.supplierId,+ invoiceSupplierId: payment?.invoiceSupplierId ?? lease.supplierId,+ invoiceSupplierContactId:+ payment?.invoiceSupplierContactId ?? lease.supplierContactId,+ invoiceSupplierLocationId:+ payment?.invoiceSupplierLocationId ?? lease.supplierLocationId,+ supplierInteractionId: interaction.id,+ locationId: lease.locationId,+ paymentTermId: payment?.paymentTermId ?? null,+ // v1 leases are base currency only.+ currencyCode: lease.currencyCode,+ exchangeRate: 1,+ dateIssued: dueDate,+ subtotal,+ totalDiscount: 0,+ totalAmount: subtotal,+ totalTax: 0,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ await trx+ .insertInto("purchaseInvoiceDelivery")+ .values({+ id: invoice.id,+ locationId: lease.locationId,+ supplierShippingCost: 0,+ companyId,+ updatedBy: userId+ })+ .execute();++ await trx+ .insertInto("purchaseInvoiceLine")+ .values(+ group.map((row, index) => ({+ invoiceId: invoice.id,+ invoiceLineType: "Lease" as const,+ leaseId,+ leasePaymentId: row.id,+ locationId: row.locationId ?? lease.locationId,+ description: leasePaymentDescription(row.description, row),+ quantity: 1,+ supplierUnitPrice: Number(row.amount),+ supplierShippingCost: 0,+ supplierTaxAmount: 0,+ taxPercent: 0,+ exchangeRate: 1,+ sortOrder: index + 1,+ companyId,+ createdBy: userId+ }))+ )+ .execute();++ await trx+ .updateTable("leasePayment")+ .set((eb) => ({+ status: "Invoiced",+ purchaseInvoiceLineId: eb+ .selectFrom("purchaseInvoiceLine")+ .select("purchaseInvoiceLine.id")+ .whereRef(+ "purchaseInvoiceLine.leasePaymentId",+ "=",+ "leasePayment.id"+ )+ .where("purchaseInvoiceLine.invoiceId", "=", invoice.id)+ .where("purchaseInvoiceLine.companyId", "=", companyId),+ updatedBy: userId,+ updatedAt: sql`now()`+ }))+ .where("companyId", "=", companyId)+ .where(+ "id",+ "in",+ group.map((row) => row.id)+ )+ .execute();++ drafted.push({ invoiceId: invoice.id, leaseId });+ }+ return drafted;+ }++ /**+ * Cuts an open-ended lease's payment rows forward to one period past `asOf`+ * (`openEndedLeaseHorizon`), for each active asset with a payment: only the+ * periods after its last Rent row, so an edited or deleted row is never cut+ * again (`cutLeasePaymentRows`, as at setup). The lease row is locked by the+ * caller.+ */+ export async function rollOpenEndedLeasePayments(+ trx: KyselyTx,+ args: { companyId: string; userId: string; leaseId: string; asOf: string }+ ): Promise<number> {+ const { companyId, userId, leaseId, asOf } = args;+ const lease = await trx+ .selectFrom("lease")+ .select([+ sql<string>`"commencementDate"::text`.as("commencementDate"),+ sql<string>`"invoiceFromDate"::text`.as("invoiceFromDate"),+ "paymentFrequency",+ "paymentTiming",+ "annualEscalationPercent",+ "currencyCode"+ ])+ .where("id", "=", leaseId)+ .where("companyId", "=", companyId)+ .executeTakeFirstOrThrow();+ const lines = await trx+ .selectFrom("leaseLine as l")+ .leftJoin("leasePayment as p", (join) =>+ join+ .onRef("p.leaseLineId", "=", "l.id")+ .onRef("p.companyId", "=", "l.companyId")+ .on("p.paymentType", "=", "Rent")+ )+ .select([+ "l.id",+ "l.paymentAmount",+ "l.purchaseOptionAmount",+ "l.purchaseOptionReasonablyCertain",+ sql<string | null>`max(p."periodStart")::text`.as("lastPeriodStart")+ ])+ .where("l.leaseId", "=", leaseId)+ .where("l.companyId", "=", companyId)+ .where("l.status", "=", "Active")+ .where("l.paymentAmount", ">", 0)+ .groupBy([+ "l.id",+ "l.paymentAmount",+ "l.purchaseOptionAmount",+ "l.purchaseOptionReasonablyCertain"+ ])+ .execute();+ if (lines.length === 0) return 0;++ const decimals = await currencyDecimals(trx, companyId, lease.currencyCode);+ const through = openEndedLeaseHorizon(+ lease.commencementDate,+ asOf,+ lease.paymentFrequency+ );+ const rows = lines.flatMap(+ (line) =>+ cutLeasePaymentRows({+ lease: { ...lease, endDate: null },+ asset: line,+ decimals,+ through,+ after: line.lastPeriodStart+ }).rows+ );+ if (rows.length > 0) {+ await trx+ .insertInto("leasePayment")+ .values(+ rows.map((row) => ({ ...row, leaseId, companyId, createdBy: userId }))+ )+ .execute();+ }+ return rows.length;+ }++ /** "Forklift FL-12 — 2027-01-01 to 2027-01-31", or for a one-off payment+ * "Forklift FL-12 — Purchase Option": the leased asset and what is paid. */+ export function leasePaymentDescription(+ assetDescription: string,+ row: {+ paymentType: Database["public"]["Enums"]["leasePaymentType"];+ periodStart: string;+ periodEnd: string;+ }+ ): string {+ if (row.paymentType !== "Rent") {+ return `${assetDescription} — ${row.paymentType}`;+ }+ return `${assetDescription} — ${row.periodStart} to ${row.periodEnd}`;+ }++ export const createLeaseInvoicesInput = z.object({+ /** `YYYY-MM-DD` in the company's timezone. */+ asOf: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ /** Bill one lease only. */+ leaseId: z.string().optional()+ });++ export const createLeaseInvoicesPermission = {+ update: "purchasing",+ create: "invoicing"+ } satisfies PermissionRule<z.output<typeof createLeaseInvoicesInput>>;++ /** Drafts the lease invoices due on or before `asOf` (see+ * `createLeaseInvoicesForDuePayments`). A lease that fails is reported in+ * `failures`, never thrown, so the others still draft. */+ export async function createLeaseInvoices(+ ctx: ServiceContext,+ raw: z.input<typeof createLeaseInvoicesInput>+ ) {+ const { asOf, leaseId } = createLeaseInvoicesInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ return createLeaseInvoicesForDuePayments(db, {+ companyId,+ userId,+ asOf,+ leaseId+ });+ }++++export type BulkDeletePurchaseOrdersResult = BulkDeleteResult;++++/** The statuses the bulk Delete deletes, from the table's own rule. */++const BULK_DELETABLE_PURCHASE_ORDER_STATUSES =++ Constants.public.Enums.purchaseOrderStatus.filter(++ isPurchaseOrderBulkDeletable++ );++++/**++ * The purchase orders table's bulk Delete: deletes the Draft and Planned++ * orders of the company, 100 ids per request. The status filter is part of++ * the DELETE, so an order that moved on since it was selected stays. Called++ * by `x+/purchase-order+/update.tsx` and by the background bulk-action job.++ * The caller checks the `delete: purchasing` permission.++ */++export function bulkDeletePurchaseOrders(++ client: SupabaseClient<Database>,++ args: { purchaseOrderIds: string[]; companyId: string }++): Promise<BulkDeletePurchaseOrdersResult> {++ return bulkDeleteByStatus({++ ids: args.purchaseOrderIds,++ companyId: args.companyId,++ label: "purchase orders",++ deleteChunk: (ids) =>++ client++ .from("purchaseOrder")++ .delete()++ .in("id", ids)++ .eq("companyId", args.companyId)++ .in("status", BULK_DELETABLE_PURCHASE_ORDER_STATUSES)++ .select("id")++ });++}diff --cc apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex 5ee453973a,627a4be124..9a8ca2cba8--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@@ -50,15 -52,11 +50,15 @@@ import { Enumerable } from "~/componentimport { usePaymentTerm } from "~/components/Form/PaymentTerm";import { useShippingMethod } from "~/components/Form/ShippingMethod";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";- import type { PurchaseOrderListItem } from "~/modules/purchasing";-import { purchaseOrderStatusType } from "~/modules/purchasing/purchasing.models";+import {+ isPurchaseOrderBulkDeletable,+ purchaseOrderStatusType- } from "~/modules/purchasing";++} from "~/modules/purchasing/purchasing.models";+ import type { PurchaseOrderListItem } from "~/modules/purchasing/types";-import type { action } from "~/routes/x+/purchase-order+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import PurchasingStatus from "./PurchasingStatus";diff --cc apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsxindex 0433a61237,78643e7f80..3f31991c54--- a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx@@@ -45,8 -46,11 +45,11 @@@ import { useSupplierTypes } from "~/comimport { ConfirmDelete } from "~/components/Modals";import { useCompanySettings, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";- import type { Supplier, SupplierReportContacts } from "~/modules/purchasing";- import { supplierStatusType } from "~/modules/purchasing";+ import { supplierStatusType } from "~/modules/purchasing/purchasing.models";+ import type {+ Supplier,- SupplierReportContactsBySupplierId++ SupplierReportContacts+ } from "~/modules/purchasing/types";import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";import { usePeople } from "~/stores";import { path } from "~/utils/path";diff --cc apps/erp/app/modules/quality/quality.service.tsindex 5bf7f82101,92f7df9534..e95498399c--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@@ -7,12 -7,20 +7,20 @@@ import { fetchAllFromTable, getCompanyTimport { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";- import { datetime } from "@carbon/utils";+ import {+ buildBatchSplitRecords,+ datetime,+ EPSILON,+ pick,+ resolveTrackedEntityBin,+ round,+ searchFilter+ } from "@carbon/utils";import { parseDate } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";- import type { z } from "zod";+ import { z } from "zod";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";const logger = getLogger("erp", "quality");@@@ -277,11 -306,6 +306,10 @@@ export async function getGaugereturn client.from("gauges").select("*").eq("id", gaugeId).single();}+export const GAUGES_PAGING: Paging = {+ defaultSorts: [{ column: "gaugeId", ascending: false }]+};+- /** @mcp read */export async function getGauges(client: SupabaseClient<Database>,companyId: string,@@@ -332,14 -359,6 +361,13 @@@ export async function getGaugeCalibrati.single();}+export const GAUGE_CALIBRATION_RECORDS_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "dateCalibrated", ascending: false }+ ]+};+- /** @mcp read */export async function getGaugeCalibrationRecords(client: SupabaseClient<Database>,companyId: string,@@@ -399,11 -412,6 +422,10 @@@ export async function getGaugeTypereturn client.from("gaugeType").select("*").eq("id", gaugeTypeId).single();}+export const GAUGE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getGaugeTypes(client: SupabaseClient<Database>,companyId: string,@@@ -437,11 -446,6 +458,10 @@@ export async function getIssue.single();}+export const ISSUES_PAGING: Paging = {+ defaultSorts: [{ column: "nonConformanceId", ascending: false }]+};+- /** @mcp read */export async function getIssues(client: SupabaseClient<Database>,companyId: string,@@@ -1022,11 -995,6 +1009,10 @@@ export async function getIssueTypeByNamreturn query.limit(1).maybeSingle();}+export const ISSUE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getIssueTypes(client: SupabaseClient<Database>,companyId: string,@@@ -1048,11 -1018,6 +1034,10 @@@return query;}+export const ISSUE_WORKFLOWS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getIssueWorkflows(client: SupabaseClient<Database>,companyId: string,@@@ -1100,11 -1065,6 +1083,10 @@@ export async function getIssueTypesList.order("name");}+export const QUALITY_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getQualityActions(client: SupabaseClient<Database>,companyId: string,@@@ -1166,11 -1128,6 +1148,10 @@@ export async function getQualityDocumen.order("version", { ascending: false });}+export const QUALITY_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getQualityDocuments(client: SupabaseClient<Database>,companyId: string,@@@ -1237,11 -1176,6 +1198,10 @@@ export async function getRequiredAction.order("name");}+export const REQUIRED_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getRequiredActions(client: SupabaseClient<Database>,companyId: string,@@@ -1283,11 -1217,6 +1241,10 @@@ export async function getRiskreturn client.from("riskRegister").select("*").eq("id", riskId).single();}+export const RISKS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getRisks(client: SupabaseClient<Database>,companyId: string,@@@ -2424,11 -2126,6 +2152,10 @@@ export async function upsertRisk// Inbound Inspections (lot-based)// -------------------------------------------------------------+export const INSPECTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getInspections(client: SupabaseClient<Database>,companyId: string,@@@ -2699,11 -2393,6 +2421,10 @@@ function mapInspectionDocument(row: Rec};}+export const INSPECTION_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "drawingNumber", ascending: true }]+};+- /** @mcp read */export async function getInspectionDocuments(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/modules/resources/resources.service.tsindex 5d0d8a5acc,d826603994..25809fa25d--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@@ -6,13 -21,30 +21,30 @@@ import { NotificationEvent } from "@carimport {type BatchRules,compactBatchRules,- resolveBatchRules+ credit,+ datetime,+ debit,+ EPSILON,+ indexBy,+ resolveBatchRules,+ round,+ searchFilter} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+ import { nanoid } from "nanoid";import type { z } from "zod";+ import { notifyScheduleInputsChanged } from "~/modules/production/production.service";+ import {+ createAdjustmentJournal,+ isActiveCompanyEmployee,+ refuseUnlessOwned,+ resolveAccountingPeriod,+ TIME_ENTRY_BEFORE_CUTOVER_ERROR+ } from "~/modules/shared/shared.service";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";+ import { invokePosting } from "../shared/shared.service";import type {failureModeValidator,locationValidator,@@@ -226,11 -205,6 +205,10 @@@ export async function deleteWorkCenterreturn client.from("workCenter").update({ active: false }).eq("id", id);}+export const ABILITIES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getAbilities(client: SupabaseClient<Database>,companyId: string,@@@ -361,13 -334,6 +336,12 @@@ export async function getContractor.single();}+// The `contractors` view has no `id`; a contractor is one supplier contact.+export const CONTRACTORS_PAGING: Paging = {+ defaultSorts: [{ column: "lastName", ascending: true }],+ idColumn: "supplierContactId"+};+- /** @mcp read */export async function getContractors(client: SupabaseClient<Database>,companyId: string,@@@ -429,11 -392,6 +398,10 @@@ export async function getFailureMode.single();}+export const FAILURE_MODES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getFailureModes(client: SupabaseClient<Database>,companyId: string,@@@ -475,11 -433,6 +441,10 @@@ export async function getLocationreturn client.from("location").select("*").eq("id", locationId).single();}+export const LOCATIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getLocations(client: SupabaseClient<Database>,companyId: string,@@@ -617,11 -565,6 +575,10 @@@ export async function getMaintenanceDisreturn query;}+export const MAINTENANCE_DISPATCHES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getMaintenanceDispatchesByLocation(client: SupabaseClient<Database>,companyId: string,@@@ -719,11 -660,6 +672,10 @@@ export async function getMaintenanceSchreturn query;}+export const MAINTENANCE_SCHEDULES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getMaintenanceSchedulesByLocation(client: SupabaseClient<Database>,companyId: string,@@@ -874,11 -807,6 +821,10 @@@ export async function getProcessreturn client.from("processes").select("*").eq("id", processId).single();}+export const PROCESSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getProcesses(client: SupabaseClient<Database>,companyId: string,@@@ -921,11 -849,6 +865,10 @@@ export async function getSuggestionreturn client.from("suggestions").select("*").eq("id", suggestionId).single();}+export const SUGGESTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getSuggestions(client: SupabaseClient<Database>,companyId: string,@@@ -1091,11 -1016,6 +1034,10 @@@ export async function getTrainingQuesti.order("sortOrder", { ascending: true });}+export const TRAININGS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getTrainings(client: SupabaseClient<Database>,companyId: string,@@@ -1166,11 -1086,6 +1106,10 @@@ export async function getWorkCenter};}+export const WORK_CENTERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getWorkCenters(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/modules/sales/sales.service.tsindex a90dd77e40,4257c6bd6e..ff6b9f7bca--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@@ -28,15 -121,43 +121,43 @@@ import typePostgrestSingleResponse,SupabaseClient} from "@supabase/supabase-js";- import { sql } from "kysely";- import type { z } from "zod";- import { createDocumentUploadUrl } from "~/modules/documents/documents.service";- import { getSupplierPriceBreaksForItems } from "~/modules/items/items.service";- import { getEmployeeJob } from "~/modules/people";+ import { generateText, Output } from "ai";+ import { type Selectable, sql, type Transaction } from "kysely";+ import { nanoid } from "nanoid";+ import { z } from "zod";+ import { zfd } from "zod-form-data";+ import {+ createDocumentUploadUrl,+ upsertDocument+ } from "~/modules/documents/documents.service";+ import { upsertPart } from "~/modules/items/items.service";+ import { getSupplierPriceBreaksForItems } from "~/modules/items/items.utils";+ import { getEmployeeJob } from "~/modules/people/people.service";+ import {+ getCompany,+ getCompanySettings+ } from "~/modules/settings/settings.service";+ import { itemType as sellableItemTypes } from "~/modules/shared/shared.models";+ import {+ bookAdjustment,+ createAdjustmentJournal,+ currencyDecimals,+ getCompanyTimeZone as getCachedCompanyTimeZone,+ getCurrentAccountingPeriod,+ refuseUnlessOwned,+ resolveInventoryAccount+ } from "~/modules/shared/shared.service";+ import { getUser } from "~/modules/users/users.service";+ import { path } from "~/utils/path";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";+ import { stripSpecialCharacters } from "~/utils/string";import { sanitize } from "~/utils/supabase";- import { getCurrencyByCode, getExchangeRate } from "../accounting";+ import {+ getCurrencyByCode,+ getExchangeRate+ } from "../accounting/accounting.service";+ import * as productionPostings from "../production/production.service";import type {operationParameterValidator,operationStepValidator,@@@ -943,11 -1046,6 +1046,10 @@@ function pickBestBreakreturn best;}+export const CUSTOMERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getCustomers(client: SupabaseClient<Database>,companyId: string,@@@ -995,11 -1093,6 +1095,10 @@@ export async function getCustomerStatus.single();}+export const CUSTOMER_STATUSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getCustomerStatuses(client: SupabaseClient<Database>,companyId: string,@@@ -1047,11 -1138,6 +1144,10 @@@ export async function getCustomerType.single();}+export const CUSTOMER_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getCustomerTypes(client: SupabaseClient<Database>,companyId: string,@@@ -1157,11 -1240,6 +1251,10 @@@ export async function getNoQuoteReason.single();}+export const NO_QUOTE_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getNoQuoteReasons(client: SupabaseClient<Database>,companyId: string,@@@ -1294,10 -1370,6 +1383,9 @@@ export async function getPricingRulereturn client.from("pricingRule").select("*").eq("id", id).single();}+// No default order: without a sort the list follows the id.+export const PRICING_RULES_PAGING: Paging = { defaultSorts: [] };+- /** @mcp read */export async function getPricingRules(client: SupabaseClient<Database>,companyId: string,@@@ -1335,11 -1406,6 +1422,10 @@@ export async function getQuotereturn client.from("quotes").select("*").eq("id", quoteId).single();}+export const QUOTES_PAGING: Paging = {+ defaultSorts: [{ column: "quoteId", ascending: false }]+};+- /** @mcp read */export async function getQuotes(client: SupabaseClient<Database>,companyId: string,@@@ -1859,11 -1846,6 +1866,10 @@@ export async function getSalesOrderRela};}+export const SALES_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getSalesOrders(client: SupabaseClient<Database>,companyId: string,@@@ -1891,7 -1870,13 +1897,11 @@@query = query.eq("customerId", args.customerId);}+ if (args.status) {+ query = query.eq("status", args.status as never);+ }+- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_ORDERS_PAGING);return query;}@@@ -2095,11 -2057,6 +2082,10 @@@ export async function getSalesRFQreturn client.from("salesRfqs").select("*").eq("id", id).single();}+export const SALES_RFQS_PAGING: Paging = {+ defaultSorts: [{ column: "rfqId", ascending: false }]+};+- /** @mcp read */export async function getSalesRFQs(client: SupabaseClient<Database>,companyId: string,@@@ -2113,12 -2070,12 +2099,10 @@@.eq("companyId", companyId);if (args.search) {- query = query.or(- `rfqId.ilike.%${args.search}%,customerReference.ilike.%${args.search}%`- );+ query = query.or(searchFilter(["rfqId", "customerReference"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "rfqId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_RFQS_PAGING);return query;}@@@ -2557,16 -2470,6 +2497,15 @@@ async function resolvePostingGroupFiltereturn { itemIds, filters: remaining };}+// The price list (`resolvePriceList`, `getBaseCatalog`) has no default order:+// without a sort it follows the item id. Its rows are computed per item, so+// a row's tie-breaker is `itemId`; the item query itself breaks ties on the+// item's own `id`, the same value.+export const PRICE_LIST_PAGING: Paging = {+ defaultSorts: [],+ idColumn: "itemId"+};+- /** @mcp action */export async function resolvePriceList(client: SupabaseClient<Database>,companyId: string,@@@ -7083,11 -6576,6 +6614,10 @@@ export async function updateSalesRFQLin// ─── Sales Return Orders (RMAs) ───+export const RETURN_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getReturnReasons(client: SupabaseClient<Database>,companyId: string,@@@ -7175,11 -6661,6 +6701,10 @@@ export async function deleteReturnReasoreturn client.from("returnReason").delete().eq("id", returnReasonId);}+export const SALES_RETURN_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getSalesReturnOrders(client: SupabaseClient<Database>,companyId: string,@@@ -8681,11 -8121,6 +8163,10 @@@ export async function createOpportunity// the Draft-stage writes.// ----------------------------------------------------------------------+export const RENTAL_AGREEMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getRentalAgreements(client: SupabaseClient<Database>,companyId: string,@@@ -9693,13 -9024,8 +9068,12 @@@ export async function getRentalAgreemen// carry their own guards and build every row from an explicit field picker.// ----------------------------------------------------------------------+export const CONTRACTS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/*** Lists contracts with their customer, value invoiced to date and next invoice date.- * @mcp read*/export async function getContracts(client: SupabaseClient<Database>,diff --cc apps/erp/app/modules/settings/settings.service.tsindex 27e86e47eb,fc6338bff8..468451262e--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@@ -21,23 -68,229 +68,229 @@@ importisBuiltInSectionId,toDocumentTemplate} from "@carbon/documents/template";+ import { withRevisionSuffix } from "@carbon/documents/utils";+ import type {+ DescriptionModes,+ ItemEdit,+ ItemFieldSnapshot,+ MappedRowPlan,+ OnshapeBomNode,+ OnshapePushDefaults,+ OwnedFieldChange,+ PartPlan,+ PartPlanRow,+ PlanCustomField,+ PlanCustomFieldDefinition,+ PlanItemRow,+ PropertyMapEntry,+ ProposedItem,+ ReleasePlanItem,+ StandardFieldWriter+ } from "@carbon/ee";+ import {+ integrations as availableIntegrations,+ bomLineItemType,+ CUSTOM_FIELD_TYPE_LABELS,+ changeNoticeDescriptionJson,+ createdItemExtras,+ defaultUnitOfMeasureCode,+ externalIdForAssembly,+ externalIdForBomLine,+ externalIdForPart,+ flattenNodes,+ getIntegrationConfigById,+ getIntegrationIdsByRole,+ type IntegrationHealthcheckResult,+ type IntegrationID,+ ITEM_METHOD_TYPES,+ ITEM_REPLENISHMENT_SYSTEMS,+ ITEM_TRACKING_TYPES,+ isModelReleaseItem,+ MAPPABLE_VALUE_TYPES,+ MAPPING_MODES,+ mappedFieldValues,+ mergeChangeNoticeEdit,+ mergeCustomFieldValues,+ mergeEditsForCreates,+ mergeExistingItemEdits,+ normalizeConfiguration,+ pickAdoptTarget,+ pickBomChildRow,+ pickReuseRow,+ pickRevisionBase,+ proposeItem,+ reconcilePushDefaults,+ releaseBomKey,+ resolveIntegrationSecrets,+ STANDARD_FIELD_IDS,+ splitSecrets,+ standardField,+ targetKey,+ translationErrors+ } from "@carbon/ee";+ import {+ buildRilletFieldTarget,+ buildXeroTrackingTarget,+ getAccountingIntegration,+ getProviderIntegration,+ getSyncOperationTransitionError,+ isAccountingSyncEnabled,+ ProviderID,+ QBO_DIMENSION_TARGET_CLASS,+ QBO_DIMENSION_TARGET_DEPARTMENT,+ type QboProvider,+ type RilletProvider,+ SYNC_OPERATION_ALLOWED_TRANSITIONS,+ SyncOperationStatusSchema,+ XERO_MAX_JOURNAL_DIMENSION_SLOTS,+ type XeroProvider+ } from "@carbon/ee/accounting";+ import { enableAuditLog } from "@carbon/ee/audit.server";+ import { EntitlementError } from "@carbon/ee/entitlements.server";+ import {+ ensureOnshapeReleaseWebhook,+ getIntegrationServerHooks,+ onshapeConnectionHasWriteScope+ } from "@carbon/ee/hooks.server";+ import type { OeeDevice } from "@carbon/ee/oee";+ import { getOeeProvider } from "@carbon/ee/oee.server";+ import type {+ DraftCandidate,+ ManualLineRow,+ MappedLineRow,+ ReleaseExportSelection,+ StoredReleasePlan+ } from "@carbon/ee/onshape";+ import {+ chunkFilterValues,+ DRAFT_MARKER_ENTITY_TYPE,+ exchangeOnshapeAuthorizationCode,+ getConflictingOnshapeIntegration,+ isOnshapeIntegrationId,+ loadActiveMakeMethods,+ loadMethodLineOwnership,+ loadPartCustomFieldDefinitions,+ loadPlanOptions,+ loadReusableDrafts,+ ONSHAPE_OAUTH_SCOPES,+ type OnshapeOAuthIntegrationId,+ pairOwnedCopiedLines,+ peekPanelPlan,+ releaseExportSelection,+ selectInBatches,+ takePanelPlan+ } from "@carbon/ee/onshape";+ import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";+ import {+ isOnshapeOAuthIntegrationId,+ loadOnshapeOAuthConfig,+ patchOnshapeOAuthGrant,+ patchOnshapeSettings+ } from "@carbon/ee/onshape.server";+ import { isIntegrationComingSoon } from "@carbon/ee/plan";+ import { companyHasFeature } from "@carbon/ee/plan.server";+ import { patchRampSettings } from "@carbon/ee/ramp.server";+ import { resolveCapabilities } from "@carbon/ee/sync";+ import { trigger } from "@carbon/jobs";+ import {+ compatibilityStatus,+ getCompanyTableCatalog,+ purgeScopeViolations,+ reportBackupCompatibility,+ selectExportableTables+ } from "@carbon/jobs/backups";+ import { redis } from "@carbon/kv";+ import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";- import { serverFns } from "@carbon/server-functions";- import { datetime } from "@carbon/utils";- import type { SupabaseClient } from "@supabase/supabase-js";- import type { z } from "zod";- import type { plmReleaseControl as plmReleaseControlOptions } from "~/modules/items/items.models";+ import {+ datetime,+ isInternalEmail,+ labelSizes,+ searchFilter+ } from "@carbon/utils";+ import { parseAbsolute } from "@internationalized/date";+ import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+ import { type Insertable, type Selectable, sql } from "kysely";+ import { nanoid } from "nanoid";+ import { data } from "react-router";+ import { extract as tarExtract } from "tar-stream";+ import { z } from "zod";+ import { getPaymentTermsList } from "~/modules/accounting/accounting.service";+ import {+ getShippingMethodsList,+ getStockTransfer,+ getStockTransferLines+ } from "~/modules/inventory/inventory.service";+ import {+ getSalesInvoice,+ getSalesInvoiceCustomerDetails,+ getSalesInvoiceLines,+ getSalesInvoiceShipment+ } from "~/modules/invoicing/invoicing.service";+ import { canEditChangeNoticeEngineering } from "~/modules/items/items.models";+ import {+ cascadeItemTrackingType,+ copyMakeMethod,+ createRevision,+ deleteChangeNotice,+ deleteItem,+ type getItem,+ getLockVerdict,+ insertChangeNotice,+ type ReleaseControl,+ requireChangeNoticeEditable,+ updateDefaultRevision,+ updateItemMethodAndSourcing,+ upsertMakeMethodVersion,+ upsertPart+ } from "~/modules/items/items.service";+ import { insertEmployeeJob } from "~/modules/people/people.service";+ import {+ getPurchaseOrder,+ getPurchaseOrderLines,+ getPurchaseOrderLocations,+ getPurchasingTerms+ } from "~/modules/purchasing/purchasing.service";+ import { upsertLocation } from "~/modules/resources/resources.service";+ import {+ getQuote,+ getQuoteCustomerDetails,+ getQuotePayment,+ getQuoteShipment,+ getSalesOrder,+ getSalesOrderCustomerDetails,+ getSalesOrderLines,+ getSalesTerms+ } from "~/modules/sales/sales.service";+ import {+ getQuoteLinePricesByQuoteId,+ getQuoteLines+ } from "~/modules/sales/sales.utils";+ import type {+ Integration,+ JobMissingStorageUnit,+ MethodMissingPullFrom+ } from "~/modules/settings/types";+ import { oAuthCallbackSchema } from "~/modules/shared/shared.models";+ import * as sharedService from "~/modules/shared/shared.service";+ import { getPermissionCacheKey } from "~/modules/users/users.service";+ import { canAccessBackups } from "~/utils/backups";+ import { path } from "~/utils/path";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";import { interpolateSequenceDate } from "~/utils/string";import { sanitize } from "~/utils/supabase";+ import {+ type CompanyBackupSummary,+ listCompanyBackupFolders+ } from "./backups.service";+ import type { IntegrationErrorCode } from "./integration-errors";+ import { integrationErrorSearch } from "./integration-errors";+ import type { OAuthPopupOutcome, OAuthPopupResult } from "./oauth-popup";+ import { OAUTH_POPUP_MESSAGE } from "./oauth-popup";+ import { oeeDevicesCacheKey } from "./oee-devices-cache";import type {- accountsPayableBillingAddressValidator,- accountsReceivableBillingAddressValidator,- invoiceAutomations,itemSerialSequenceValidator,- kanbanOutputTypes,- purchasePriceUpdateTimingTypes,sequenceValidator,subsidiaryValidator} from "./settings.models";@@@ -101,30 -327,6 +327,26 @@@ export async function deleteSubsidiaryreturn client.from("company").delete().eq("id", companyId);}+// The key hash never leaves the server.+export async function getApiKey(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+) {+ return client+ .from("apiKey")+ .select(+ "id, name, expiresAt, scopes, keyPreview, lastUsedAt, rateLimit, rateLimitWindow, createdAt, createdBy, updatedBy, companyId"+ )+ .eq("id", id)+ .eq("companyId", companyId)+ .single();+}++export const API_KEYS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: true }]+};+- /**- * @mcp read- * @mcp permission users:update- */export async function getApiKeys(client: SupabaseClient<Database>,companyId: string,@@@ -349,13 -542,6 +560,12 @@@ export async function getCustomFields.single();}+// The `customFieldTables` view has no `id`; one row is one table.+export const CUSTOM_FIELD_TABLES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }],+ idColumn: "table"+};+- /** @mcp read */export async function getCustomFieldsTables(client: SupabaseClient<Database>,companyId: string,@@@ -451,11 -667,6 +689,10 @@@ export async function getSequence.single();}+export const SEQUENCES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getSequences(client: SupabaseClient<Database>,companyId: string,@@@ -492,11 -704,6 +728,10 @@@ export async function getSequencesList.order("table");}+export const ITEM_SERIAL_SEQUENCES_PAGING: Paging = {+ defaultSorts: [{ column: "itemReadableId", ascending: true }]+};+- /** @mcp read */export async function getItemSerialSequences(client: SupabaseClient<Database>,companyId: string,@@@ -512,15 -719,12 +747,10 @@@.eq("companyId", companyId);if (args.search) {- // Strip PostgREST filter-grammar characters so a search term can't alter the- // `or` expression or filter unintended columns (mirrors inventory.service.ts).- const search = args.search.replace(/[,()\\]/g, " ");- query = query.or(- `itemReadableId.ilike.%${search}%,itemName.ilike.%${search}%`- );+ query = query.or(searchFilter(["itemReadableId", "itemName"], args.search));}- query = setGenericQueryFilters(query, args, [- { column: "itemReadableId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ITEM_SERIAL_SEQUENCES_PAGING);return query;}@@@ -837,11 -1024,6 +1050,10 @@@ export async function getWebhook(clientreturn client.from("webhook").select("*").eq("id", id).single();}+export const WEBHOOKS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: true }]+};+- /** @mcp read */export async function getWebhooks(client: SupabaseClient<Database>,companyId: string,@@@ -1560,184 -2001,6666 +2029,6688 @@@ export async function listOeeDevices}/**- * The time of day scheduled MRP runs, on the company's own clock ("HH:MM:SS").- * `null` restores the default cadence, every 3 hours.- * @mcp update+ * Device-mapping data for an OEE integration's Devices tab: the provider's+ * devices, this integration's saved mappings, the work centers another OEE+ * integration already holds, and the active work centers (plus any inactive+ * one a device of this integration is still mapped to) with their location+ * timezone. A provider failure renders the mappings with no devices and the+ * error above the list rather than failing the drawer. The device list is+ * cached for 60 seconds; a provider error is never cached.*/- export async function updateMrpRunTimeSetting(+ export async function getOeeDevicesTabData(client: SupabaseClient<Database>,companyId: string,- mrpRunTime: string | null+ integrationId: string) {- return client- .from("companySettings")- .update({ mrpRunTime })- .eq("id", companyId);- }+ // The provider read runs alongside the mappings. Mappings come before the+ // work centers: the work center list must include an inactive work center a+ // device is still mapped to, or its row shows no work center.+ const [{ devices, error: providerError }, mappings] = await Promise.all([+ listOeeDevices(companyId, integrationId),+ client+ .from("workCenterDevice")+ .select(+ "externalDeviceId, deviceName, externalSiteId, siteTimezone, workCenterId, currentState, lastSyncedAt, lastSyncError"+ )+ .eq("companyId", companyId)+ .eq("integration", integrationId)+ ]);++ const mappedIds = (mappings.data ?? []).map((m) => m.workCenterId);+ const workCentersQuery = client+ .from("workCenter")+ .select("id, name, location(timezone)")+ .eq("companyId", companyId);- /** @mcp update */- export async function updateIncompletePickingListPolicySetting(- client: SupabaseClient<Database>,- companyId: string,- incompletePickingListPolicy: "warn" | "error"- ) {- return client- .from("companySettings")- .update(sanitize({ incompletePickingListPolicy }))- .eq("id", companyId);+ const [takenWorkCenters, workCenters] = await Promise.all([+ client+ .from("workCenterDevice")+ .select("workCenterId, deviceName, integration")+ .eq("companyId", companyId)+ .neq("integration", integrationId),+ (mappedIds.length > 0+ ? workCentersQuery.or(`active.eq.true,id.in.(${mappedIds.join(",")})`)+ : workCentersQuery.eq("active", true)+ ).order("name")+ ]);++ for (const result of [mappings, takenWorkCenters, workCenters]) {+ if (result.error) {+ logger.error("Failed to load OEE device mapping data", {+ companyId,+ integrationId,+ error: result.error+ });+ }+ }++ return {+ devices,+ mappings: mappings.data ?? [],+ takenWorkCenters: takenWorkCenters.data ?? [],+ workCenters: (workCenters.data ?? []).map((workCenter) => ({+ id: workCenter.id,+ name: workCenter.name,+ // Null when the location inherits the company's timezone ('' or null):+ // the tab falls back to the company's.+ locationTimezone: workCenter.location?.timezone || null+ })),+ error: providerError+ };}- /** @mcp update */- export async function updateReturnPickedMaterialTimingSetting(- client: SupabaseClient<Database>,- companyId: string,- returnPickedMaterialTiming: "job" | "operation"- ) {- return client- .from("companySettings")- .update(sanitize({ returnPickedMaterialTiming }))- .eq("id", companyId);+ const INTEGRATION_CACHE_TTL = 3600;++ /**+ * Drop the cached auth record for an API key so a scope change or revocation+ * takes effect immediately in the common case. An in-flight auth read can still+ * re-prime the cache with the pre-write row, so the hard bound is the 30s TTL —+ * callers that delete the row should bust AGAIN after the delete commits, using+ * the returned keyHash (unreadable from the DB once the row is gone).+ *+ * Service-role on purpose: apiKey's RLS SELECT requires `settings_view`, but the+ * routes that revoke or rescope a key gate on `users_update`, so the caller's own+ * client cannot see the row and the bust would silently do nothing.+ */+ export async function invalidateApiKeyCache(+ id: string,+ companyId: string+ ): Promise<string | null> {+ const { data, error } = await getCarbonServiceRole()+ .from("apiKey")+ .select("keyHash")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ // A failed lookup is indistinguishable from a missing row at the return type,+ // and neither may block the revoke — log it so a stale scope surviving its TTL+ // is diagnosable rather than silent.+ if (error) {+ logger.error("Failed to read api key for cache bust", {+ error,+ id,+ companyId+ });+ }+ if (!data?.keyHash) return null;+ await bustApiKeyCache(data.keyHash);+ return data.keyHash;}- // ── Planning ownership + tolerance (spec §P1.3 / §P1.6) ────────────────────- // The responsibleEmployee ladder's configurable rungs: company default →- // per-location → per-(location, item group). The item-group tier is- // LOCATION-SPECIFIC, stored sparsely in itemPostingGroupResponsibility — an- // inheritance tree (the printer AssignmentsCard model), never a matrix.+ export async function clearCustomFieldsCache(companyId?: string) {+ const keys = companyId ? `customFields:${companyId}:*` : "customFields:*";+ redis.keys(keys).then(function (keys) {+ const pipeline = redis.pipeline();+ keys.forEach(function (key) {+ pipeline.del(key);+ });+ return pipeline.exec();+ });+ }- export async function getItemPostingGroupResponsibilities(- client: SupabaseClient<Database>,+ export async function clearCompanyIntegrationCache(companyId: string- ) {- return client- .from("itemPostingGroupResponsibility")- .select("id, locationId, itemPostingGroupId, responsibleEmployee")- .eq("companyId", companyId);+ ): Promise<void> {+ const cacheKey = `integrations:${companyId}`;++ try {+ // Clear both old and new key formats, and the OEE device lists: a new API+ // key or environment can name different stations.+ await redis.del(+ cacheKey,+ `json:${cacheKey}`,+ ...getIntegrationIdsByRole("oee").map((integrationId) =>+ oeeDevicesCacheKey(companyId, integrationId)+ )+ );+ } catch (error) {+ logger.error("Redis cache invalidation error", { error });+ }}- export async function setDefaultResponsibleEmployee(- client: SupabaseClient<Database>,- args: { companyId: string; employeeId: string | null }- ) {- return client- .from("companySettings")- .update({ defaultResponsibleEmployee: args.employeeId })- .eq("id", args.companyId);+ export async function clearAllIntegrationCaches(): Promise<void> {+ try {+ // Clear both old and new key patterns+ const oldPattern = "integrations:*";+ const newPattern = "json:integrations:*";++ const [oldKeys, newKeys] = await Promise.all([+ redis.keys(oldPattern),+ redis.keys(newPattern)+ ]);++ const allKeys = [...oldKeys, ...newKeys];+ if (allKeys.length > 0) {+ logger.info("Clearing integration cache entries", {+ count: allKeys.length+ });+ await redis.del(...allKeys);+ }+ } catch (error) {+ logger.error("Error clearing all integration caches", { error });+ }}- export async function setLocationResponsibleEmployee(+ /**+ * Move accounting sync operations to `to` in one UPDATE. The statement itself+ * holds the transition rule: it matches only operations whose CURRENT status+ * may move to `to`, so one changed since it was read is left alone. Each+ * operation it did not move is reported with its reason.+ */+ export async function transitionSyncOperations(client: SupabaseClient<Database>,args: {+ ids: string[];companyId: string;- locationId: string;- employeeId: string | null;+ to: "Pending" | "Skipped";userId: string;}- ) {- // `location` is a resources table: without resources_update, row-level- // security matches no row and the update succeeds having changed nothing.- // Returning the row lets the caller tell the two apart.- return client- .from("location")- .update({ responsibleEmployee: args.employeeId, updatedBy: args.userId })- .eq("id", args.locationId)- .eq("companyId", args.companyId)+ ): Promise<+ | { moved: number; failures: { id: string; reason: string }[]; error: null }+ | { moved: 0; failures: []; error: PostgrestError }+ > {+ const { ids, companyId, to, userId } = args;+ const from = SyncOperationStatusSchema.options.filter((status) =>+ SYNC_OPERATION_ALLOWED_TRANSITIONS[status].includes(to)+ );++ const updated = await client+ .from("accountingSyncOperation")+ .update({ status: to, updatedBy: userId, updatedAt: datetime.timestamp() })+ .eq("companyId", companyId)+ .in("id", ids)+ .in("status", from).select("id");+ if (updated.error) return { moved: 0, failures: [], error: updated.error };++ const moved = new Set(updated.data.map((row) => row.id));+ const missed = [...new Set(ids)].filter((id) => !moved.has(id));+ if (missed.length === 0) {+ return { moved: moved.size, failures: [], error: null };+ }++ const current = await client+ .from("accountingSyncOperation")+ .select("id, status")+ .eq("companyId", companyId)+ .in("id", missed);+ const statusById = new Map(+ (current.data ?? []).map((row) => [row.id, row.status])+ );+ const failures = missed.map((id) => {+ const status = statusById.get(id);+ return {+ id,+ reason: current.error+ ? current.error.message+ : !status+ ? `Sync operation ${id} not found`+ : (getSyncOperationTransitionError(status, to) ??+ `Sync operation ${id} changed while it was being updated`)+ };+ });+ return { moved: moved.size, failures, error: null };}- /**- * Upsert one (location, item group) ownership cell; clearing the employee- * DELETES the row (unset → inherit up the tree, matching printers).- */- export async function upsertItemPostingGroupResponsibility(+ export async function deactivateIntegration(client: SupabaseClient<Database>,args: {+ id: string;companyId: string;- locationId: string;- itemPostingGroupId: string;- employeeId: string | null;- userId: string;+ updatedBy: string;}) {- if (!args.employeeId) {- return client- .from("itemPostingGroupResponsibility")- .delete()- .eq("companyId", args.companyId)- .eq("locationId", args.locationId)- .eq("itemPostingGroupId", args.itemPostingGroupId);- }- // Update first, insert only when the cell is new: an upsert would restate- // `createdBy` on every reassignment.- const updated = await client- .from("itemPostingGroupResponsibility")+ const { id, companyId, updatedBy } = args;++ const result = await client+ .from("companyIntegration").update({- responsibleEmployee: args.employeeId,- updatedBy: args.userId,- updatedAt: datetime.timestamp()+ active: false,+ updatedBy,+ updatedAt: new Date().toISOString()})- .eq("companyId", args.companyId)- .eq("locationId", args.locationId)- .eq("itemPostingGroupId", args.itemPostingGroupId)- .select("id");- if (updated.error || (updated.data?.length ?? 0) > 0) return updated;- return client- .from("itemPostingGroupResponsibility")- .insert({- companyId: args.companyId,- locationId: args.locationId,- itemPostingGroupId: args.itemPostingGroupId,- responsibleEmployee: args.employeeId,- createdBy: args.userId+ .eq("id", id)+ .eq("companyId", companyId);++ if (result.error) {+ return result;+ }++ await clearCompanyIntegrationCache(companyId);++ return result;+ }++ export async function deleteCustomField(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+ ) {+ try {+ clearCustomFieldsCache(companyId);+ } finally {+ return client.from("customField").delete().eq("id", id);+ }+ }++ interface CompanyIntegration {+ id: string;+ companyId: string;+ metadata: Record<string, any>;+ active: boolean;+ }++ export async function getCachedCompanyIntegrations(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<CompanyIntegration[]> {+ const cacheKey = `integrations:${companyId}`;++ try {+ // Try the new prefixed key first+ let cached = await redis.get(`json:${cacheKey}`);+ if (cached && typeof cached === "string") {+ try {+ return JSON.parse(cached);+ } catch (parseError) {+ logger.error("JSON parse error for prefixed cache key", {+ cacheKey: `json:${cacheKey}`,+ error: parseError+ });+ await redis.del(`json:${cacheKey}`);+ }+ }++ // Fallback to old key format for backwards compatibility+ cached = await redis.get(cacheKey);+ if (cached !== null && cached !== undefined) {+ // Log the type and content for debugging+ logger.info("Cache hit", {+ cacheKey,+ type: typeof cached,+ isArray: Array.isArray(cached),+ value: cached,+ constructor: cached?.constructor?.name+ });++ // Handle different response types from Upstash+ if (Array.isArray(cached)) {+ // Direct array return from Upstash+ return cached as CompanyIntegration[];+ } else if (typeof cached === "object" && cached !== null) {+ // Object return from Upstash - could be a parsed JSON already+ return cached as CompanyIntegration[];+ } else if (typeof cached === "string") {+ // String return - needs JSON parsing+ try {+ return JSON.parse(cached);+ } catch (parseError) {+ logger.error("JSON parse error for cache key", {+ cacheKey,+ error: parseError,+ cached+ });+ await redis.del(cacheKey);+ }+ } else {+ logger.warning("Unexpected cache format for key", {+ cacheKey,+ type: typeof cached,+ cached+ });+ await redis.del(cacheKey);+ }+ }+ } catch (error) {+ logger.error("Redis cache read error", { error });+ // Clear the corrupted cache entry+ try {+ await redis.del(cacheKey);+ } catch (deleteError) {+ logger.error("Failed to delete corrupted cache entry", {+ error: deleteError+ });+ }+ }++ const { data, error } = await client+ .from("companyIntegration")+ .select("*")+ .eq("companyId", companyId);++ if (error) {+ throw error;+ }++ // Secret material must never reach Redis. Strip each integration's secret keys+ // into the vault-backed shape (config only) before caching AND returning, so no+ // consumer of this function depends on a plaintext secret in `metadata` (secret+ // reads go through resolveIntegrationSecrets against the row, not this cache).+ const integrations = (data || []).map((integration) => ({+ ...integration,+ metadata: splitSecrets(integration.id, integration.metadata).config+ }));++ try {+ // Force string storage to avoid Upstash automatic deserialization issues+ const serializedData = JSON.stringify(integrations);+ if (typeof serializedData === "string" && serializedData.length > 0) {+ // Use a prefixed key to ensure we know this is a JSON string+ await redis.setex(+ `json:${cacheKey}`,+ INTEGRATION_CACHE_TTL,+ serializedData+ );+ } else {+ logger.error("Failed to serialize integrations data for cache");+ }+ } catch (error) {+ logger.error("Redis cache write error", { error });+ }++ return integrations as CompanyIntegration[];+ }++ export async function hasIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+ ): Promise<boolean> {+ const integrations = await getCachedCompanyIntegrations(client, companyId);+ return integrations.some((i) => i.id === integrationId && i.active === true);+ }++ export async function getCompanyIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+ ): Promise<CompanyIntegration | null> {+ const integrations = await getCachedCompanyIntegrations(client, companyId);+ return (+ integrations.find((i) => i.id === integrationId && i.active === true) ||+ null+ );+ }++ export async function getSlackIntegration(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<{ token: string; channelId?: string } | null> {+ // The Redis cache (getCompanyIntegration) no longer holds secret material, so+ // read the row directly with a service-role client — required both to resolve+ // the vaulted access_token and, in the transitional window, to see the plaintext+ // still in the column.+ const serviceRole = getCarbonServiceRole();+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata, secretRef, active")+ .eq("companyId", companyId)+ .eq("id", "slack")+ .maybeSingle();++ if (!integration?.active || !integration.metadata) {+ return null;+ }++ const metadata = (await resolveIntegrationSecrets(+ serviceRole,+ companyId,+ "slack",+ integration.metadata,+ integration.secretRef+ )) as any;++ if (!metadata.access_token) {+ return null;+ }++ return {+ token: metadata.access_token,+ channelId: metadata.channel_id || metadata.default_channel_id+ };+ }++ export async function hasSlackIntegration(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<boolean> {+ return hasIntegration(client, companyId, "slack");+ }++ export async function upsertCompanyIntegration(+ client: SupabaseClient<Database>,+ update: {+ id: string;+ active: boolean;+ metadata: Json;+ companyId: string;+ updatedBy: string;+ }+ ) {+ if (update.id === "ramp") {+ try {+ const data = await patchRampSettings(+ getCarbonServiceRole(),+ update.companyId,+ {+ metadata: update.metadata as Record<string, unknown>,+ active: update.active,+ updatedBy: update.updatedBy+ }+ );+ await clearCompanyIntegrationCache(update.companyId);+ return { data, error: null };+ } catch (error) {+ logger.error("Failed to atomically patch Ramp settings", {+ error,+ companyId: update.companyId+ });+ return { data: null, error };+ }+ }++ // The Onshape rows are shared with the token refresh, the OAuth callback and+ // the panel's property map, so a settings save patches only its own keys.+ if (isOnshapeOAuthIntegrationId(update.id)) {+ try {+ const data = await patchOnshapeSettings(+ getCarbonServiceRole(),+ update.companyId,+ update.id,+ {+ metadata: update.metadata as Record<string, unknown>,+ active: update.active,+ updatedBy: update.updatedBy+ }+ );+ await clearCompanyIntegrationCache(update.companyId);+ return { data, error: null };+ } catch (error) {+ logger.error("Failed to patch Onshape settings", {+ error,+ companyId: update.companyId,+ integrationId: update.id+ });+ return { data: null, error };+ }+ }++ // Split secret material out of the metadata: only the non-secret config is+ // written to the column; the secrets go to Supabase Vault. The row is upserted+ // FIRST (so it exists), then the vault RPC stamps `secretRef` onto it.+ // `secrets` is a PARTIAL bag — splitSecrets omits untouched masked fields — so+ // `upsert_integration_secret` MERGES it into the stored bag (an omitted secret+ // keeps its value). A full replace here silently wiped a multi-secret+ // integration's other credential on a partial save.+ const { config, secrets } = splitSecrets(update.id, update.metadata);++ const result = await client+ .from("companyIntegration")+ .upsert([{ ...update, metadata: config as Json }], {+ onConflict: "id,companyId"})- .select("id");+ .select()+ .single();++ if (result.error) {+ return result;+ }++ if (Object.keys(secrets).length > 0) {+ const serviceRole = getCarbonServiceRole();+ const { error: vaultError } = await serviceRole.rpc(+ "upsert_integration_secret",+ {+ p_company_id: update.companyId,+ p_integration_id: update.id,+ p_secret: secrets as never+ }+ );+ if (vaultError) {+ logger.error("Failed to persist integration secret to vault", {+ error: vaultError,+ id: update.id+ });+ return { ...result, data: null, error: vaultError };+ }+ }++ await clearCompanyIntegrationCache(update.companyId);++ return result;}- export async function setRescheduleToleranceDays(+ export async function upsertCustomField(client: SupabaseClient<Database>,- args: { companyId: string; days: number }+ customField:+ | (Omit<z.infer<typeof customFieldValidator>, "id"> & {+ companyId: string;+ createdBy: string;+ })+ | (Omit<z.infer<typeof customFieldValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })) {- return client- .from("companySettings")- .update({ rescheduleToleranceDays: args.days })- .eq("id", args.companyId);+ try {+ clearCustomFieldsCache();+ } finally {+ if ("createdBy" in customField) {+ const sortOrders = await client+ .from("customField")+ .select("sortOrder")+ .eq("table", customField.table);++ if (sortOrders.error) return sortOrders;+ const maxSortOrder = sortOrders.data.reduce((max, item) => {+ return Math.max(max, item.sortOrder);+ }, 0);++ return client+ .from("customField")+ .insert([{ ...customField, sortOrder: maxSortOrder + 1 }]);+ }+ return client+ .from("customField")+ .update(+ sanitize({+ ...customField,+ updatedBy: customField.updatedBy+ })+ )+ .eq("id", customField.id);+ }+ }++ export async function updateCustomFieldsSortOrder(+ client: SupabaseClient<Database>,+ updates: {+ id: string;+ sortOrder: number;+ updatedBy: string;+ }[]+ ) {+ try {+ clearCustomFieldsCache();+ } finally {+ const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>+ client.from("customField").update({ sortOrder, updatedBy }).eq("id", id)+ );+ return Promise.all(updatePromises);+ }}+ export type IntegrationHealthStatus =+ | "healthy"+ | "unhealthy"+ | "inactive"+ | "sync-off";++ type IntegrationHealthFields = {+ health: IntegrationHealthStatus;+ /** Why an unhealthy check failed, when the integration says. */+ healthReason: string | null;+ };+/**- * Whether a purchase order the planning pages raised skips the approval rule- * when it is finalized (`purchaseOrder.createdFromPlanning`, cleared by any- * manual line change). On by default.+ * Connection health, plus `sync-off` for an accounting integration whose+ * connection works but whose sync switch is off (a new connection still being+ * set up, or one switched off since). A broken connection still reads+ * `unhealthy` — that is the more urgent thing to show.*/- export async function setSkipApprovalForPlanningPurchaseOrders(+ export async function getIntegrationHealth(+ companyId: string,+ integration: Integration+ ): Promise<Integration & IntegrationHealthFields> {+ const result = await getConnectionHealth(companyId, integration);+ if (+ result.health === "healthy" &&+ (getIntegrationIdsByRole("accounting") as string[]).includes(+ integration.id ?? ""+ ) &&+ !isAccountingSyncEnabled(integration.metadata)+ ) {+ return { ...result, health: "sync-off" };+ }+ return result;+ }++ async function getConnectionHealth(+ companyId: string,+ integration: Integration+ ): Promise<+ Integration &+ IntegrationHealthFields & { health: "healthy" | "unhealthy" | "inactive" }+ > {+ if (!integration.active) {+ return {+ ...integration,+ health: "inactive",+ healthReason: null+ };+ }++ const serverHooks = getIntegrationServerHooks(integration.id!);+ const config = getIntegrationConfigById(integration.id as IntegrationID);+ const healthcheck = serverHooks?.onHealthcheck ?? config?.onHealthcheck;++ if (!healthcheck) {+ return {+ ...integration,+ health: "healthy",+ healthReason: null+ };+ }++ const key = `integrations:${companyId}:${integration.id}:health`;++ const cached = await redis.get(key);++ // Only cache healthy status+ if (cached === "1") {+ return {+ ...integration,+ health: "healthy",+ healthReason: null+ };+ }++ // Resolve vaulted secrets back into the metadata before the healthcheck+ // builds its provider/client. Since the secret-vault refactor, credentials no+ // longer live in the plaintext `metadata` column, so an unresolved metadata+ // authenticates with nothing and every secret-bearing healthcheck (Rillet,+ // Xero, Email) would read "unhealthy". `resolveIntegrationSecrets` looks up+ // the row's `secretRef` itself (the `integrations` view doesn't expose it) and+ // throws when the secret can't be read — treat that as unhealthy rather than+ // crashing the whole settings page.+ let resolvedMetadata: Record<string, any>;+ try {+ resolvedMetadata = (await resolveIntegrationSecrets(+ getCarbonServiceRole(),+ companyId,+ integration.id!,+ (integration.metadata as Record<string, any>) ?? {}+ )) as Record<string, any>;+ } catch {+ return {+ ...integration,+ health: "unhealthy",+ healthReason: null+ };+ }++ const result = await (+ healthcheck as (+ companyId: string,+ metadata: Record<string, any>+ ) => Promise<boolean | IntegrationHealthcheckResult>+ )(companyId, resolvedMetadata);+ const healthy = typeof result === "boolean" ? result : result.healthy;+ const reason = typeof result === "boolean" ? null : (result.reason ?? null);++ await redis.set(key, healthy ? "1" : "0", "EX", INTEGRATION_CACHE_TTL * 5); // Cache for 5 hours++ return {+ ...integration,+ health: healthy ? "healthy" : "unhealthy",+ healthReason: healthy ? null : reason+ };+ }++ export async function getIntegrationsWithHealth(client: SupabaseClient<Database>,- args: { companyId: string; enabled: boolean }+ companyId: string) {- return client- .from("companySettings")- .update({ skipApprovalForPlanningPurchaseOrders: args.enabled })- .eq("id", args.companyId);+ const results = await client+ .from("integrations")+ .select("*")+ .eq("companyId", companyId);++ if (results.error) return results;++ const integrations = results.data;++ const withHealth = await Promise.all(+ integrations.map((i) => getIntegrationHealth(companyId, i))+ );++ return {+ data: withHealth,+ error: null+ };}- /** The company-wide planning horizon; `null` = no default (no time fence). */- export async function setDefaultPlanningHorizonDays(- client: SupabaseClient<Database>,- args: { companyId: string; days: number | null }+ export async function invalidateIntegrationHealthCache(+ integrationId: string,+ companyId: string) {- return client- .from("companySettings")- .update({ defaultPlanningHorizonDays: args.days })- .eq("id", args.companyId);+ const key = `integrations:${companyId}:${integrationId}:health`;++ return await redis.del(key);}- export async function setForecastConsumptionWindow(+ // Needs the service-role client for the Vault RPC.+ export async function updateIntegrationMetadata(client: SupabaseClient<Database>,- args: { companyId: string; backwardPeriods: number; forwardPeriods: number }+ companyId: string,+ integrationId: string,+ metadata: any,+ updatedBy?: string) {+ if (integrationId === "ramp") {+ try {+ const data = await patchRampSettings(getCarbonServiceRole(), companyId, {+ metadata: metadata as Record<string, unknown>,+ updatedBy+ });+ await clearCompanyIntegrationCache(companyId);+ return { data, error: null };+ } catch (error) {+ return { data: null, error };+ }+ }++ if (isOnshapeOAuthIntegrationId(integrationId)) {+ try {+ const data = await patchOnshapeSettings(+ getCarbonServiceRole(),+ companyId,+ integrationId,+ { metadata: metadata as Record<string, unknown>, updatedBy }+ );+ await clearCompanyIntegrationCache(companyId);+ return { data, error: null };+ } catch (error) {+ return { data: null, error };+ }+ }++ // Split secret material out to Supabase Vault; only the non-secret config is+ // written to the column. The row already exists (this is an update), so vault+ // FIRST (fail-closed: if the vault write fails, the plaintext is left intact+ // rather than stripped-and-lost), then write the stripped config.+ const { config, secrets } = splitSecrets(integrationId, metadata);++ if (Object.keys(secrets).length > 0) {+ const serviceRole = getCarbonServiceRole();+ const { error } = await serviceRole.rpc("upsert_integration_secret", {+ p_company_id: companyId,+ p_integration_id: integrationId,+ p_secret: secrets as never+ });+ if (error) {+ return { data: null, error };+ }+ }+return client- .from("companySettings")- .update({- forecastConsumptionBackwardPeriods: args.backwardPeriods,- forecastConsumptionForwardPeriods: args.forwardPeriods- })- .eq("id", args.companyId);+ .from("companyIntegration")+ .update(+ sanitize({+ metadata: config as Json,+ updatedAt: new Date().toISOString(),+ updatedBy+ })+ )+ .eq("companyId", companyId)+ .eq("id", integrationId);+ }++ /**+ * Where a sync operation's `entityId` resolves to a human-readable document+ * number, per `entityType` (the keys of the accounting sync engine's+ * `ENTITY_DEFINITIONS`). `employee` and `inventoryAdjustment` are absent on+ * purpose: the first is a `user` id with no readable column of its own, the+ * second an `itemLedger` row with no document number at all.+ */+ const SYNC_ENTITY_READABLE_ID_SOURCES: Record<+ string,+ { table: string; column: string }+ > = {+ customer: { table: "customer", column: "name" },+ vendor: { table: "supplier", column: "name" },+ item: { table: "item", column: "readableId" },+ purchaseOrder: { table: "purchaseOrder", column: "purchaseOrderId" },+ bill: { table: "purchaseInvoice", column: "invoiceId" },+ salesOrder: { table: "salesOrder", column: "salesOrderId" },+ invoice: { table: "salesInvoice", column: "invoiceId" },+ payment: { table: "payment", column: "paymentId" },+ charge: { table: "charge", column: "chargeId" },+ reimbursement: { table: "reimbursement", column: "reimbursementId" },+ journalEntry: { table: "journal", column: "journalEntryId" },+ // One table, two entity types — the sweep splits `memo` by party.+ creditMemo: { table: "memo", column: "memoId" },+ supplierCredit: { table: "memo", column: "memoId" }+ };++ const JOURNAL_REVERSAL_SUFFIX = ":reversal";++ const DAILY_CONSOLIDATION_PREFIX = "daily:";++ /** The fields of a sync operation this resolver reads. */+ type SyncOperationReference = {+ integration: string;+ entityType: string;+ entityId: string;+ direction: string;+ };++ /**+ * The lookup key, built identically here and in `SyncActivity`'s+ * `getEntityReference`.+ */+ function syncOperationReadableIdKey(operation: {+ entityType: string;+ entityId: string;+ }) {+ return `${operation.entityType}:${operation.entityId}`;+ }++ /**+ * A pulled operation is keyed by the PROVIDER's remote id, so it only+ * reaches a Carbon row through `externalIntegrationMapping`. One query for+ * the whole page, keyed back by `entityType:externalId`.+ */+ async function getPulledEntityIds(+ client: SupabaseClient<Database>,+ companyId: string,+ operations: SyncOperationReference[]+ ): Promise<Map<string, string>> {+ const pulled = operations.filter(+ (operation) =>+ operation.direction === "pull-from-accounting" &&+ operation.entityType in SYNC_ENTITY_READABLE_ID_SOURCES+ );+ if (pulled.length === 0) return new Map();++ const { data, error } = await client+ .from("externalIntegrationMapping")+ .select("entityType, entityId, externalId")+ .eq("companyId", companyId)+ .in("integration", [+ ...new Set(pulled.map((operation) => operation.integration))+ ])+ .in("entityType", [+ ...new Set(pulled.map((operation) => operation.entityType))+ ])+ .in("externalId", [+ ...new Set(pulled.map((operation) => operation.entityId))+ ]);++ if (error || !data) return new Map();++ return new Map(+ data.map((row) => [`${row.entityType}:${row.externalId}`, row.entityId])+ );+ }++ /**+ * Resolve one page of sync operations to the document numbers a human reads+ * — `PO000001` rather than `po_6UyRfXggN6YrmCSauBaVf1`. One query per entity+ * type on the page (plus one for pulled records' mappings), never one per+ * row.+ *+ * Silently incomplete by design, and the caller falls back to the raw id: a+ * pulled record that never landed a Carbon row has only the provider's+ * remote id, a pulled payment's id is a composite of two remote ids, and a+ * daily-consolidation journal marker backs no row at all.+ *+ * `recordId` is the CARBON row id — the same as `entityId` for a push, the+ * mapped id for a pull — so the table's link goes somewhere real instead of+ * to the provider's remote id.+ */+ export async function getSyncOperationReadableIds(+ client: SupabaseClient<Database>,+ companyId: string,+ operations: SyncOperationReference[]+ ): Promise<Record<string, { label: string; recordId: string }>> {+ const pulledEntityIds = await getPulledEntityIds(+ client,+ companyId,+ operations+ );++ // entityType -> the ids to look up, mapped back to the operation keys they+ // came from (a journal reversal's id is the journal's id plus a suffix, so+ // one row can answer two keys).+ const byEntityType = new Map<string, Map<string, string[]>>();++ for (const operation of operations) {+ if (!(operation.entityType in SYNC_ENTITY_READABLE_ID_SOURCES)) continue;++ let lookupId =+ pulledEntityIds.get(syncOperationReadableIdKey(operation)) ??+ operation.entityId;++ if (operation.entityType === "journalEntry") {+ if (lookupId.startsWith(DAILY_CONSOLIDATION_PREFIX)) continue;+ if (lookupId.endsWith(JOURNAL_REVERSAL_SUFFIX)) {+ lookupId = lookupId.slice(0, -JOURNAL_REVERSAL_SUFFIX.length);+ }+ } else if (lookupId.includes(":")) {+ // A pulled payment's composite remote id — no Carbon row behind it.+ continue;+ }++ const ids = byEntityType.get(operation.entityType) ?? new Map();+ ids.set(lookupId, [+ ...(ids.get(lookupId) ?? []),+ syncOperationReadableIdKey(operation)+ ]);+ byEntityType.set(operation.entityType, ids);+ }++ if (byEntityType.size === 0) return {};++ const results = await Promise.all(+ Array.from(byEntityType.entries()).map(async ([entityType, ids]) => {+ const source = SYNC_ENTITY_READABLE_ID_SOURCES[entityType]!;+ // The table and column are chosen from the const map above, never from+ // request input — but they are values, so the select string can't be+ // typed. Cast, the same way the tie-out read in the route does.+ const { data, error } = (await (client.from(source.table as any) as any)+ .select(`id, ${source.column}`)+ .eq("companyId", companyId)+ .in("id", Array.from(ids.keys()))) as {+ data: { id: string }[] | null;+ error: unknown;+ };++ if (error || !data)+ return [] as [string, { label: string; recordId: string }][];++ return data.flatMap((row) => {+ const value = (row as Record<string, unknown>)[source.column];+ if (typeof value !== "string" || value.length === 0) return [];+ return (ids.get(row.id) ?? []).map(+ (key): [string, { label: string; recordId: string }] => [+ key,+ {+ label: key.endsWith(JOURNAL_REVERSAL_SUFFIX)+ ? `${value} (reversal)`+ : value,+ recordId: row.id+ }+ ]+ );+ });+ })+ );++ return Object.fromEntries(results.flat());+ }+++/**++ * Each operation with its `reference` (`getSyncOperationReadableIds`), or++ * null when it has none. Every page of the Sync Activity tab carries its own.++ */++export async function withSyncOperationReferences<++ T extends SyncOperationReference++>(++ client: SupabaseClient<Database>,++ companyId: string,++ operations: T[]++): Promise<(T & { reference: { label: string; recordId: string } | null })[]> {++ const readableIds = await getSyncOperationReadableIds(++ client,++ companyId,++ operations++ );++ return operations.map((operation) => ({++ ...operation,++ reference: readableIds[syncOperationReadableIdKey(operation)] ?? null++ }));++}+++ /** One provider analytics target with its selectable option values. */+ export type DimensionTargetWithValues = {+ id: string;+ label: string;+ capacity: number;+ values: { id: string; name: string }[];+ };++ /**+ * Provider journal-dimension targets with their selectable values, for+ * the Dimensions tab and the slot-save validation. Guarded on the+ * provider actually implementing `journalDimensionTargets`; option values+ * come from the provider's list methods (Rillet Fields carry their values+ * inline; QBO Classes/Departments and Xero tracking options are the+ * target's own list). A provider API failure degrades to an empty target+ * list + `targetsError` so the settings drawer never blocks on a provider+ * outage.+ */+ export async function getProviderDimensionTargets(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+ ): Promise<{+ supported: boolean;+ targets: DimensionTargetWithValues[];+ maxSlots: number | null;+ targetsError: boolean;+ }> {+ const unsupported = {+ supported: false,+ targets: [],+ maxSlots: null,+ targetsError: false+ };++ const providerId = (Object.values(ProviderID) as string[]).includes(+ integrationId+ )+ ? (integrationId as ProviderID)+ : null;+ if (!providerId) return unsupported;++ try {+ const accountingIntegration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );+ const provider = getProviderIntegration(+ client,+ companyId,+ providerId,+ accountingIntegration.metadata+ );++ if (typeof provider.journalDimensionTargets !== "function") {+ return unsupported;+ }++ if (providerId === ProviderID.RILLET) {+ // One GET /fields serves both the targets and their values (calling+ // journalDimensionTargets() separately would hit the same endpoint+ // twice); target ids come from the engine's composite-id helper.+ const fields = await (provider as RilletProvider).listFields();+ return {+ supported: true,+ targets: fields.map((field) => ({+ id: buildRilletFieldTarget(field.id),+ label: field.name,+ capacity: 1,+ values: (field.values ?? [])+ .filter((value) => !value.deactivated)+ .map((value) => ({ id: value.id, name: value.name }))+ })),+ maxSlots:+ resolveCapabilities(provider.capabilities).maxJournalDimensionSlots ??+ null,+ targetsError: false+ };+ }++ if (providerId === ProviderID.QUICKBOOKS) {+ // journalDimensionTargets() probes the Intuit feature gates, so an+ // org without class/location tracking sees a reduced target list;+ // the values then load from the matching list method.+ const qbo = provider as QboProvider;+ const declared = await qbo.journalDimensionTargets();+ const targets: DimensionTargetWithValues[] = [];+ for (const target of declared) {+ const options =+ target.id === QBO_DIMENSION_TARGET_CLASS+ ? await qbo.listClasses()+ : target.id === QBO_DIMENSION_TARGET_DEPARTMENT+ ? await qbo.listDepartments()+ : [];+ targets.push({+ id: target.id,+ label: target.label,+ capacity: target.capacity ?? 1,+ values: options.map((option) => ({+ id: option.Id,+ name: option.Name+ }))+ });+ }+ return {+ supported: true,+ targets,+ maxSlots:+ resolveCapabilities(qbo.capabilities).maxJournalDimensionSlots ??+ null,+ targetsError: false+ };+ }++ // Xero: one target per active tracking category, options inline.+ const categories = await (+ provider as XeroProvider+ ).listTrackingCategories();+ return {+ supported: true,+ targets: categories.map((category) => ({+ id: buildXeroTrackingTarget(category.TrackingCategoryID),+ label: category.Name,+ capacity: 1,+ values: (category.Options ?? [])+ .filter(+ (option) =>+ option.Status === "ACTIVE" || option.Status === undefined+ )+ .map((option) => ({ id: option.TrackingOptionID, name: option.Name }))+ })),+ maxSlots: XERO_MAX_JOURNAL_DIMENSION_SLOTS,+ targetsError: false+ };+ } catch (err) {+ logger.error("Failed to load provider dimension targets", {+ companyId,+ integrationId,+ error: err+ });+ return { supported: true, targets: [], maxSlots: null, targetsError: true };+ }+ }++ // ─── Operations (`defineServiceFn`) ─────────────────────────────────────────+ // What the routes, the API and MCP all run. A settings page has ONE update+ // operation: it takes the page's fields, all optional, and writes the ones+ // sent. An absent field keeps its stored value, so one form never blanks a+ // neighbouring setting.++ type CompanySettingsUpdate =+ Database["public"]["Tables"]["companySettings"]["Update"];++ /** The fields the caller sent: an absent (undefined) one is left out. */+ export function sentFields<T extends object>(fields: T): Partial<T> {+ return Object.fromEntries(+ Object.entries(fields).filter(([, value]) => value !== undefined)+ ) as Partial<T>;+ }++ export function nothingSent(+ ctx: ServiceContext,+ input: object+ ): CarbonError | null {+ return Object.keys(sentFields(input)).length === 0+ ? ctx.error("validation", "Send at least one setting to change")+ : null;+ }++ /** Writes the sent fields to the company's settings row, as the caller. */+ export async function saveCompanySettings(+ ctx: ServiceContext,+ fields: CompanySettingsUpdate,+ failure: string+ ): Promise<CarbonError | null> {+ const changes = sentFields(fields);+ if (Object.keys(changes).length === 0) return null;+ const { error } = await ctx.asCaller.supabase+ .from("companySettings")+ .update(changes)+ .eq("id", ctx.company.id);+ return error ? ctx.error("internal", failure, error) : null;+ }++ /** Multi-company management is open to internal (Carbon) users only, for now. */+ export async function refuseUnlessInternalUser(+ ctx: ServiceContext+ ): Promise<CarbonError | null> {+ const refused = ctx.error(+ "forbidden",+ "Managing companies is not available to this account"+ );+ if (ctx.actor.type !== "user") return refused;+ const { data } = await ctx.asSystem.supabase+ .from("user")+ .select("email")+ .eq("id", ctx.actor.userId)+ .maybeSingle();+ return isInternalEmail(data?.email ?? "") ? null : refused;+ }++ /** The headquarters location and the creator's job at it: what a new company starts with. */+ export async function createHeadquarters(+ ctx: ServiceContext,+ companyId: string,+ location: Omit<z.output<typeof companyValidator>, "baseCurrencyCode">+ ): Promise<CarbonError | null> {+ const client = ctx.asSystem.supabase;++ // Controlled environments (ITAR/CUI, NIST 800-171 3.3.1) capture audit from+ // day one: enable it at company creation, not just when settings are opened.+ if (CONTROLLED_ENVIRONMENT) {+ await enableAuditLog(client, companyId).catch((err) =>+ logger.error("Failed to enable audit log for new company", {+ companyId,+ error: err+ })+ );+ }++ const headquarters = await upsertLocation(client, {+ ...location,+ name: "Headquarters",+ companyId,+ // The timezone comes with the company's address: HQ shares it.+ createdBy: ctx.auditUserId+ });+ if (headquarters.error || !headquarters.data?.id) {+ return ctx.error(+ "internal",+ "Failed to create headquarters location",+ headquarters.error+ );+ }++ const [job] = await Promise.all([+ insertEmployeeJob(client, {+ id: ctx.auditUserId,+ companyId,+ locationId: headquarters.data.id+ }),+ redis.del(getPermissionCacheKey(ctx.auditUserId))+ ]);+ if (job.error) {+ return ctx.error(+ "internal",+ "Failed to create employee job record",+ job.error+ );+ }+ return null;+ }++ /** A one-label ZPL test page for the route's media size; null for a PDF route or no size. */+ export function generateTestLabel(+ format: string,+ mediaSizeId: string | null+ ): string | null {+ if (format !== "zpl" || !mediaSizeId) return null;+ const labelSize = labelSizes.find((s) => s.id === mediaSizeId);+ if (!labelSize?.zpl) return null;+ const { width, height } = labelSize.zpl;+ const dpi = labelSize.zpl.dpi || 203;+ const widthDots = Math.round(width * dpi);+ const heightDots = Math.round(height * dpi);+ const now = new Date();+ const timestamp = `${now.toLocaleDateString()} ${now.toLocaleTimeString()}`;+ return [+ "^XA",+ `^PW${widthDots}`,+ `^LL${heightDots}`,+ "^MNW",+ "^FO20,20^A0N,30,30^FDTest Print^FS",+ `^FO20,60^A0N,20,20^FD${mediaSizeId} — ${width}x${height}"^FS`,+ `^FO20,90^A0N,16,16^FD${timestamp}^FS`,+ "^XZ"+ ].join("\n");+ }++ /** An API key action on a company without the plan. */+ export function apiKeysEntitlement(ctx: ServiceContext, err: unknown) {+ if (!(err instanceof EntitlementError)) throw err;+ return ctx.error("entitlement", "API keys require the Business plan");+ }++ /** The integration's stored metadata and its `settings` object, for a merge. */+ export async function integrationSettings(+ ctx: ServiceContext,+ integrationId: string+ ) {+ const existing = await getIntegration(+ ctx.asCaller.supabase,+ integrationId,+ ctx.company.id+ );+ if (existing.error || !existing.data) return null;+ const metadata = (existing.data.metadata as Record<string, unknown>) ?? {};+ return {+ active: existing.data.active,+ metadata,+ settings: (metadata.settings as Record<string, unknown> | undefined) ?? {}+ };+ }++ /** Write an integration's merged metadata and drop its cached health. */+ export async function saveIntegrationMetadata(+ ctx: ServiceContext,+ integrationId: string,+ active: boolean,+ metadata: Record<string, unknown>,+ failure: string+ ): Promise<CarbonError | null> {+ const update = await upsertCompanyIntegration(ctx.asCaller.supabase, {+ id: integrationId,+ active,+ metadata: metadata as Json,+ companyId: ctx.company.id,+ updatedBy: ctx.auditUserId+ });+ if (update.error) return ctx.error("internal", failure, update.error);+ await invalidateIntegrationHealthCache(integrationId, ctx.company.id);+ return null;+ }+ type Account = Pick<+ Database["public"]["Tables"]["account"]["Row"],+ | "id"+ | "name"+ | "companyGroupId"+ | "active"+ | "isGroup"+ | "class"+ | "incomeBalance"+ | "accountType"+ | "consolidatedRate"+ | "parentId"+ >;++ export function resolveShippingDefault({+ parentDefaultId,+ accounts,+ companyGroupId+ }: {+ parentDefaultId: string | null;+ accounts: readonly Account[];+ companyGroupId: string;+ }): string {+ const eligible = (account: Account) =>+ account.companyGroupId === companyGroupId &&+ account.active === true &&+ account.isGroup === false &&+ account.class === "Revenue" &&+ account.incomeBalance === "Income Statement";+ const mapped = accounts.find((account) => account.id === parentDefaultId);+ if (mapped && eligible(mapped)) return mapped.id;++ const byId = new Map(accounts.map((account) => [account.id, account]));+ const candidates = accounts.filter((account) => {+ const parent = account.parentId ? byId.get(account.parentId) : undefined;+ return (+ eligible(account) &&+ account.name === "Shipping Revenue" &&+ account.accountType === "Income" &&+ account.consolidatedRate === "Average" &&+ parent?.companyGroupId === companyGroupId &&+ parent.active === true &&+ parent.isGroup === true &&+ parent.class === "Revenue" &&+ parent.accountType === "Income" &&+ parent.incomeBalance === "Income Statement"+ );+ });+ if (candidates.length !== 1) {+ throw new Error(+ "A unique compatible Shipping Revenue default is required for this company group"+ );+ }+ return candidates[0]!.id;+ }+ const seedCompanyLogger = getLogger("erp", "seed-company");++ export const seedCompanyInput = z.object({+ parentCompanyId: z.string().optional(),+ identityOnly: z.boolean().optional()+ });++ export const seedCompanyPermission = "system" satisfies PermissionRule<+ z.output<typeof seedCompanyInput>+ >;++ /** Seeds a new company's reference data, groups and admin link, in one transaction. */+ export async function seedCompany(+ ctx: ServiceContext,+ raw: z.input<typeof seedCompanyInput>+ ) {+ const { parentCompanyId, identityOnly } = seedCompanyInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ seedCompanyLogger.info({+ companyId,+ userId,+ parentCompanyId,+ identityOnly: identityOnly === true+ });++ const company = await single(db, "company", { id: companyId });+ if (company.error) throw new Error(company.error.message);+ if (!company.data) throw new NotFoundError("Company not found");++ // Idempotency guard. The whole seed runs in a single transaction, so a+ // committed run has inserted `userToCompany(userId, companyId)`. A caller+ // that retries a seed which already committed would otherwise throw 23505+ // on the identity inserts. If the link already exists, the prior run+ // finished: no-op.+ const existingLink = await db+ .selectFrom("userToCompany")+ .select("userId")+ .where("userId", "=", userId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (existingLink) {+ return { success: true, alreadySeeded: true };+ }++ // Determine if this is a new root company or joining an existing group+ let companyGroupId = company.data.companyGroupId;+ const isNewGroup = !companyGroupId && !parentCompanyId;++ // If this is a subsidiary, get the parent's companyGroupId+ if (parentCompanyId && !companyGroupId) {+ const parent = await single(+ db,+ "company",+ { id: parentCompanyId },+ { columns: ["companyGroupId"] }+ );+ if (parent.error) throw new Error(parent.error.message);+ if (!parent.data?.companyGroupId)+ throw new Error("Parent company has no group");+ companyGroupId = parent.data.companyGroupId;+ }++ await db.transaction().execute(async (trx) => {+ // If no companyGroupId, create a new company group and assign it+ if (isNewGroup) {+ const companyGroupResult = await trx+ .insertInto("companyGroup")+ .values({+ name: company.data.name,+ createdBy: userId,+ ownerId: userId+ })+ .returning(["id"])+ .execute();++ companyGroupId = companyGroupResult[0]!.id;+ if (!companyGroupId) throw new Error("Failed to create company group");++ await trx+ .updateTable("company")+ .set({ companyGroupId })+ .where("id", "=", companyId)+ .execute();+ }++ // For subsidiaries, companyGroupId + parentCompanyId are set LATER (just+ // before the elimination-entity block), not here. Setting companyGroupId+ // fires the `company_sync_ic_partners` trigger, which inserts an+ // intercompany supplier/customer row in this company for each sibling. Those+ // inserts rely on the `set_{supplier,customer}_readable_id_on_insert`+ // triggers to stamp a readableId from the company's sequence — and the+ // sequences aren't seeded until the reference-data block below. Firing the+ // trigger here left every intercompany row with readableId '' (the auto-fill+ // no-ops when no sequence row exists yet). Since+ // `supplier_readableId_companyId_unique` treats '' as a real value, only the+ // FIRST sibling's row survived; every later sibling collided on+ // (companyId, '') and was silently dropped by ON CONFLICT DO NOTHING — so a+ // company created into a group of 3+ only ever saw one sibling.++ // The generated types cover the public schema only.+ await (+ trx.withSchema("storage") as unknown as Kysely<{+ buckets: { id: string; name: string; public: boolean };+ }>+ )+ .insertInto("buckets")+ .values({+ id: companyId,+ name: companyId,+ public: false+ })+ .onConflict((oc) => oc.column("id").doNothing())+ .execute();++ await trx+ .insertInto("userToCompany")+ .values([{ userId, companyId, role: "employee" }])+ .execute();++ // high-order groups — identity infrastructure: the employeeType insert+ // below fires a trigger that creates a membership row referencing these,+ // so they must exist even in identity-only mode. (The onboarding import+ // skips `group` so the template doesn't duplicate them.)+ await trx+ .insertInto("group")+ .values(+ groups.map(({ idPrefix, ...g }) => ({+ ...g,+ id: getGroupId(idPrefix, companyId),+ companyId+ }))+ )+ .execute();++ const employeeTypes = await trx+ .insertInto("employeeType")+ .values([+ {+ name: "Admin",+ companyId,+ protected: true,+ systemType: "Admin" as const+ }+ ])+ .returning(["id"])+ .execute();++ const employeeTypeId = employeeTypes[0]!.id;+ if (!employeeTypeId)+ throw new Error("Failed to insert admin employee type");++ // get the modules+ const modules = (await trx+ .selectFrom("modules")+ .select("name")+ .execute()) as { name: string }[];++ // create employee type permissions for admin+ const employeeTypePermissions = modules.reduce<+ Database["public"]["Tables"]["employeeTypePermission"]["Insert"][]+ >((acc, module) => {+ if (module.name) {+ acc.push({+ employeeTypeId: employeeTypeId,+ // @ts-expect-error - it's legit, chill typescript+ module: module.name,+ create: [companyId],+ update: [companyId],+ delete: [companyId],+ view: [companyId]+ });+ }+ return acc;+ }, []);++ // insert employee type permissions+ await trx+ .insertInto("employeeTypePermission")+ .values(employeeTypePermissions)+ .execute();++ // insert employee+ await trx+ .insertInto("employee")+ .values([+ {+ id: String(userId),+ employeeTypeId,+ companyId,+ active: true+ }+ ])+ .execute();++ // Reference + accounting data (customer statuses, UoMs, sequences,+ // chart of accounts, …). Skipped in identity-only mode — a company+ // backup carries all of this, so onboarding-from-a-backup seeds only+ // the identity layer above and lets the import provide the rest.+ if (!identityOnly) {+ // customer status+ await trx+ .insertInto("customerStatus")+ .values(+ customerStatuses.map((name) => ({+ name,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ // scrap reason codes+ await trx+ .insertInto("scrapReason")+ .values(+ scrapReasons.map((name) => ({+ name,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ // return reason codes (shared by customer RMAs and supplier returns)+ await trx+ .insertInto("returnReason")+ .values(+ returnReasons.map((name) => ({+ name,+ inventoryValueZero: false,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ // payment terms+ await trx+ .insertInto("paymentTerm")+ .values(paymentTerms.map((pt) => ({ ...pt, companyId })))+ .execute();++ await trx+ .insertInto("unitOfMeasure")+ .values(unitOfMeasures.map((uom) => ({ ...uom, companyId })))+ .execute();++ await trx+ .insertInto("gaugeType")+ .values(+ gaugeTypes.map((gt) => ({+ name: gt,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ await trx+ .insertInto("maintenanceFailureMode")+ .values(+ failureModes.map((name) => ({+ name,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ await trx+ .insertInto("nonConformanceType")+ .values(nonConformanceTypes.map((nc) => ({ ...nc, companyId })))+ .execute();++ await trx+ .insertInto("nonConformanceRequiredAction")+ .values(+ nonConformanceRequiredActions.map((nc) => ({ ...nc, companyId }))+ )+ .execute();++ // change-order default types (the changeOrderType lookup). New on this+ // branch and not yet in the cloud-generated Kysely types, so the insert+ // goes through a cast (mirrors changeOrderRequiredAction below).+ await (trx as any)+ .insertInto("changeOrderType")+ .values(changeOrderTypes.map((ct) => ({ ...ct, companyId })))+ .execute();++ // change-order default actions (system template rows). New on this branch+ // and not yet in the cloud-generated Kysely types, so the insert goes+ // through a cast (mirrors periodCloseTaskDefinition below).+ await (trx as any)+ .insertInto("changeOrderRequiredAction")+ .values(changeOrderRequiredActions.map((ca) => ({ ...ca, companyId })))+ .execute();++ await trx+ .insertInto("sequence")+ .values(sequences.map((s) => ({ ...s, companyId })))+ .execute();++ // period-close checklist definitions (system template rows). The table is+ // new on this branch and not yet in the cloud-generated Kysely types, so+ // the insert goes through a cast (mirrors accounting.service.ts).+ await (trx as any)+ .insertInto("periodCloseTaskDefinition")+ .values(+ periodCloseTaskDefinitions.map((d) => ({+ ...d,+ companyId,+ createdBy: "system"+ }))+ )+ .execute();++ // Shared tables: only seed for new groups (existing groups already have these)+ let accountIdByKey: Record<string, string> = {};+ let siblingDefaults:+ | Selectable<KyselyDatabase["accountDefault"]>+ | undefined;+ let siblingAssetClasses: Selectable<KyselyDatabase["fixedAssetClass"]>[] =+ [];+ if (isNewGroup) {+ await trx+ .insertInto("currency")+ .values(+ currencies.map((c) => ({ ...c, companyGroupId: companyGroupId! }))+ )+ .execute();++ // Insert accounts in order, resolving parentKey to parentId+ for (const { key, parentKey, ...acc } of accounts) {+ const result = await trx+ .insertInto("account")+ .values({+ ...acc,+ companyGroupId: companyGroupId!,+ parentId: parentKey ? (accountIdByKey[parentKey] ?? null) : null+ })+ .returning(["id"])+ .execute();+ if (result[0]?.id) {+ accountIdByKey[key] = result[0].id;+ }+ }++ await trx+ .insertInto("dimension")+ .values(+ dimensions.map((d) => ({+ name: d.name,+ entityType: d.entityType,+ companyGroupId: companyGroupId!,+ createdBy: userId+ }))+ )+ .execute();+ } else {+ // A subsidiary joining an existing group copies the account ids of a+ // company already in it. Its chart may have been imported, so the+ // seeded numbers below are only the fallback for a group with none.+ const sibling = await trx+ .selectFrom("accountDefault")+ .innerJoin("company", "company.id", "accountDefault.companyId")+ .selectAll("accountDefault")+ .where("company.companyGroupId", "=", companyGroupId!)+ .where("accountDefault.companyId", "!=", companyId)+ .orderBy(+ sql`"accountDefault"."companyId" = ${parentCompanyId ?? ""}`,+ "desc"+ )+ .orderBy("accountDefault.companyId")+ .executeTakeFirst();+ if (sibling) {+ siblingDefaults = sibling;+ siblingAssetClasses = await trx+ .selectFrom("fixedAssetClass")+ .selectAll()+ .where("companyId", "=", sibling.companyId)+ .execute();+ } else {+ const existingAccounts = await trx+ .selectFrom("account")+ .select([+ "id",+ "number",+ "name",+ "companyGroupId",+ "active",+ "isGroup",+ "class",+ "incomeBalance",+ "accountType",+ "consolidatedRate",+ "parentId"+ ])+ .where("companyGroupId", "=", companyGroupId!)+ .execute();+ for (const acc of existingAccounts) {+ if (acc.number) {+ accountIdByKey[acc.number] = acc.id;+ }+ }+ accountIdByKey["4050"] = resolveShippingDefault({+ parentDefaultId: null,+ accounts: existingAccounts.filter(+ (account) => account.id !== accountIdByKey["4010"]+ ),+ companyGroupId: companyGroupId!+ });+ }+ }++ // Resolve account numbers to IDs for account defaults+ const resolvedDefaults: Record<string, string | null> = {};+ for (const [key, number] of Object.entries(accountDefaults)) {+ resolvedDefaults[key] = accountIdByKey[number] ?? null;+ }+ // A sibling's defaults are copied exactly, empty ones included: after+ // a chart import the seeded numbers may name unrelated accounts.+ if (siblingDefaults) {+ for (const column of ACCOUNT_DEFAULT_COLUMNS) {+ resolvedDefaults[column] =+ (siblingDefaults[column] as string | null) ?? null;+ }+ }++ // These defaults are NOT NULL in the schema. If a customized COA+ // on an existing group is missing one of their accounts+ // (6050/4130/4120/7060/1150/1210/1220), the lookup yields null and the+ // insert below would violate the not-null constraint. Fall back to an+ // existing default of the same nature so the insert can't fail — mirrors+ // the COALESCE backfills in 20260630093809_ar-ap-payments.sql,+ // 20260711155312_supplier-prepayment-account.sql, and+ // 20260713190909_raw-materials-finished-goods-accounts.sql.+ // Order matters: rawMaterialsAccount resolves before finishedGoodsAccount+ // chains onto it.+ const arApDefaultFallbacks: Record<string, string> = {+ customerWriteOffAccount: "salesDiscountAccount",+ supplierWriteOffAccount: "salesAccount",+ realizedExchangeGainAccount: "salesAccount",+ realizedExchangeLossAccount: "interestAccount",+ assetGainOnDisposalAccount: "assetLossOnDisposalAccount",+ supplierPrepaymentAccount: "receivablesAccount",+ rawMaterialsAccount: "workInProgressAccount",+ finishedGoodsAccount: "rawMaterialsAccount"+ };+ for (const [key, fallbackKey] of Object.entries(arApDefaultFallbacks)) {+ if (!resolvedDefaults[key]) {+ resolvedDefaults[key] = resolvedDefaults[fallbackKey] ?? null;+ }+ }++ // Company-specific accounting defaults and posting groups+ await trx+ .insertInto("accountDefault")+ .values([+ {+ ...resolvedDefaults,+ companyId+ } as Insertable<KyselyDatabase["accountDefault"]>+ ])+ .execute();++ await trx+ .insertInto("fiscalYearSettings")+ .values([{ ...fiscalYearSettings, companyId }])+ .execute();++ // A new company stays Provisional until the activation wizard sets+ // its cutover, so the chart can be imported before anything is+ // Posted (.ai/specs/2026-10-12-chart-of-accounts-import.md).++ // A subsidiary copies the group's fixed asset classes from a sibling,+ // every setting included; a new group seeds them by account number.+ const classRows = siblingDefaults+ ? siblingAssetClasses.map(+ ({+ id: _id,+ createdAt: _createdAt,+ updatedAt: _updatedAt,+ updatedBy: _updatedBy,+ ...fac+ }) => ({ ...fac, companyId, createdBy: userId })+ )+ : fixedAssetClasses.map((fac) => ({+ name: fac.name,+ depreciationMethod: fac.depreciationMethod,+ usefulLifeMonths: fac.usefulLifeMonths,+ residualValuePercent: fac.residualValuePercent,+ assetAccountId: accountIdByKey[fac.assetAccount]!,+ accumulatedDepreciationAccountId:+ accountIdByKey[fac.accumulatedDepreciationAccount]!,+ depreciationExpenseAccountId:+ accountIdByKey[fac.depreciationExpenseAccount]!,+ writeOffAccountId: accountIdByKey[fac.writeOffAccount]!,+ writeDownAccountId: accountIdByKey[fac.writeDownAccount]!,+ gainOnDisposalAccountId: accountIdByKey[fac.gainOnDisposalAccount]!,+ lossOnDisposalAccountId: accountIdByKey[fac.lossOnDisposalAccount]!,+ isConstructionInProgress: fac.isConstructionInProgress,+ companyId,+ createdBy: userId+ }));+ if (classRows.length > 0) {+ await trx.insertInto("fixedAssetClass").values(classRows).execute();+ }+ } // end if (!identityOnly)++ const user = await single(+ trx,+ "userPermission",+ { id: userId },+ { columns: ["permissions"] }+ );+ if (user.error) throw new Error(user.error.message);++ const currentPermissions = (user.data?.permissions ?? {}) as Record<+ string,+ string[]+ >;+ const newPermissions = { ...currentPermissions };+ modules.forEach(({ name }) => {+ const module = name?.toLowerCase();+ if (`${module}_view` in newPermissions) {+ newPermissions[`${module}_view`]!.push(companyId);+ } else {+ newPermissions[`${module}_view`] = [companyId];+ }++ if (`${module}_create` in newPermissions) {+ newPermissions[`${module}_create`]!.push(companyId);+ } else {+ newPermissions[`${module}_create`] = [companyId];+ }++ if (`${module}_update` in newPermissions) {+ newPermissions[`${module}_update`]!.push(companyId);+ } else {+ newPermissions[`${module}_update`] = [companyId];+ }++ if (`${module}_delete` in newPermissions) {+ newPermissions[`${module}_delete`]!.push(companyId);+ } else {+ newPermissions[`${module}_delete`] = [companyId];+ }+ });++ const { error } = await updateRows(+ trx,+ "userPermission",+ { permissions: newPermissions },+ { id: userId }+ );+ if (error) throw new Error(error.message);++ // For subsidiaries: set companyGroupId + parentCompanyId now that the+ // reference data (including the supplier/customer sequences) has been+ // seeded. This is what fires `company_sync_ic_partners`; running it here+ // guarantees the readableId auto-fill triggers can stamp a real id on every+ // intercompany partner row, so no two siblings collide on (companyId, '').+ if (parentCompanyId) {+ await trx+ .updateTable("company")+ .set({ companyGroupId, parentCompanyId })+ .where("id", "=", companyId)+ .execute();+ }++ // Auto-create elimination entity if this is a subsidiary+ if (parentCompanyId && companyGroupId) {+ const siblings = await trx+ .selectFrom("company")+ .select(["id", "isEliminationEntity"])+ .where("companyGroupId", "=", companyGroupId)+ .where("parentCompanyId", "=", parentCompanyId)+ .execute();++ const hasElimination = siblings.some((s) => s.isEliminationEntity);++ if (!hasElimination) {+ const parent = await trx+ .selectFrom("company")+ .select(["name", "baseCurrencyCode", "countryCode"])+ .where("id", "=", parentCompanyId)+ .executeTakeFirst();++ const eliminationCompany = await trx+ .insertInto("company")+ .values({+ name: `Elimination - ${parent?.name ?? "Unknown"}`,+ addressLine1: "",+ city: "",+ stateProvince: "",+ postalCode: "",+ baseCurrencyCode:+ parent?.baseCurrencyCode ?? company.data.baseCurrencyCode,+ countryCode: parent?.countryCode ?? company.data.countryCode ?? "",+ parentCompanyId,+ isEliminationEntity: true,+ companyGroupId+ })+ .returning(["id"])+ .executeTakeFirst();++ // Seed sequences for the elimination entity. It is otherwise a bare+ // consolidation shell, but generateEliminationEntries posts an+ // elimination journal on it and stamps journalEntryId from+ // get_next_sequence('journalEntry', <elim>) — without its own+ // sequence rows that raises "Sequence not found".+ if (eliminationCompany?.id) {+ await trx+ .insertInto("sequence")+ .values(+ sequences.map((s) => ({+ ...s,+ companyId: eliminationCompany.id+ }))+ )+ .execute();+ }+ }+ }+ });++ return { success: true };+ }+ /**+ * OAuth callback page: posts the outcome to the popup's opener and closes, or+ * goes to `fallbackUrl` when there is no opener (popup blocked, callback opened+ * directly). Only Carbon-authored values reach the page, never provider text.+ */+ export function oauthPopupResponse(+ outcome: OAuthPopupOutcome,+ fallbackUrl: string+ ) {+ const message: OAuthPopupResult = { type: OAUTH_POPUP_MESSAGE, ...outcome };++ const html = `<!doctype html>+ <html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="robots" content="noindex">+ <title>Carbon</title>+ </head>+ <body>+ <script>+ (function () {+ var message = ${embed(message)};+ var fallback = ${embed(fallbackUrl)};+ var opener = window.opener;+ var delivered = false;+ try {+ if (opener && !opener.closed) {+ opener.postMessage(message, window.location.origin);+ delivered = true;+ }+ } catch (_) {}+ if (delivered) {+ window.close();+ }+ // Still here: no opener, or the browser refused to close the window. Land+ // where a plain redirect would have.+ window.setTimeout(function () {+ window.location.replace(fallback);+ }, delivered ? 500 : 0);+ })();+ </script>+ <noscript><a href="${escapeAttribute(fallbackUrl)}">Continue</a></noscript>+ </body>+ </html>+ `;++ return new Response(html, {+ status: 200,+ headers: {+ "Content-Type": "text/html; charset=utf-8",+ "Cache-Control": "no-store"+ }+ });+ }++ /** JSON that is safe inside a <script> element. */+ function embed(value: unknown) {+ return JSON.stringify(value)+ .replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028")+ .replace(/\u2029/g, "\\u2029");+ }++ function escapeAttribute(value: string) {+ return value+ .replace(/&/g, "&")+ .replace(/"/g, """)+ .replace(/</g, "<")+ .replace(/>/g, ">");+ }++ type ItemRevisionStatus = Database["public"]["Enums"]["itemRevisionStatus"];+ const onshapeDraftMethodLogger = getLogger("erp", "onshape", "draft-method");++ /**+ * Why the assembly push must not write a parent's BOM, per item id. A Draft a+ * change notice holds is the notice's to change, whatever its stage. A+ * released (Production) revision follows `plmReleaseControl` through+ * `getLockVerdict`, as the BOM editor's `checkRevisionLock` does: `enforce`+ * refuses, `warn` and `off` write. Two reads in all, not one per method.+ */+ export async function loadMethodWriteRefusals(+ client: Client,+ companyId: string,+ targets: Array<{+ itemId: string;+ method: { changeOrderId?: string | null };+ revisionStatus: ItemRevisionStatus | null | undefined;+ }>+ ): Promise<Map<string, string>> {+ const reasons = new Map<string, string>();+ const changeOrderIds = [+ ...new Set(+ targets+ .map((target) => target.method.changeOrderId)+ .filter((id): id is string => !!id)+ )+ ];+ const anyProduction = targets.some(+ (target) =>+ !target.method.changeOrderId && target.revisionStatus === "Production"+ );+ const [notices, settings] = await Promise.all([+ selectInBatches(changeOrderIds, (batch) =>+ client+ .from("changeOrder")+ .select("id, changeOrderId")+ .eq("companyId", companyId)+ .in("id", batch)+ ),+ anyProduction ? getCompanySettings(client, companyId) : null+ ]);+ // The notice's number is for the message only; the refusal stands without it.+ const noticeNumber = new Map(+ (notices.data ?? []).map((notice) => [notice.id, notice.changeOrderId])+ );+ const releaseControl = (settings?.data?.plmReleaseControl ??+ "enforce") as ReleaseControl;+ for (const target of targets) {+ const changeOrderId = target.method.changeOrderId;+ if (changeOrderId) {+ const number = noticeNumber.get(changeOrderId);+ reasons.set(+ target.itemId,+ `its make method is a Draft on ${number ? `change notice ${number}` : "a change notice"}. Change the BOM there.`+ );+ continue;+ }+ const verdict = getLockVerdict({+ isLocked: target.revisionStatus === "Production",+ releaseControl+ });+ if (!verdict.ok) reasons.set(target.itemId, verdict.message);+ }+ return reasons;+ }++ /**+ * The Draft a push writes into when the item's method is Active: the one this+ * integration made from that method (`pickReusableDraft`), else a new copy. The+ * reusable marker is written last; a failure before it deletes the new Draft.+ */+ export async function ensureDraftMakeMethod(+ client: Client,+ db: Kysely<KyselyDatabase>,+ args: {+ itemId: string;+ activeMethodId: string;+ companyId: string;+ userId: string;+ /** Preloaded with `loadReusableDrafts`; null when none, omitted to read it here. */+ reusableDraft?: DraftCandidate | null;+ }+ ): Promise<+ | { ok: true; id: string; created: boolean; version: number | null }+ | { ok: false; error: string }+ > {+ const { itemId, activeMethodId, companyId, userId } = args;+ const serviceRole = getCarbonServiceRole();++ let existing = args.reusableDraft;+ if (existing === undefined) {+ try {+ const reusable = await loadReusableDrafts(+ client,+ serviceRole,+ companyId,+ new Map([[itemId, activeMethodId]])+ );+ existing = reusable.get(itemId) ?? null;+ } catch (error) {+ return {+ ok: false,+ error: error instanceof Error ? error.message : "could not read Drafts"+ };+ }+ }+ if (existing) {+ return {+ ok: true,+ id: existing.id,+ created: false,+ version: existing.version+ };+ }++ // max(version) + 1, not Active + 1: parallel Drafts collide on (itemId, version).+ const highest = await client+ .from("makeMethod")+ .select("version")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .order("version", { ascending: false })+ .limit(1)+ .maybeSingle();+ if (highest.error) {+ return { ok: false, error: highest.error.message };+ }+ const version = (highest.data?.version ?? 0) + 1;++ const draft = await upsertMakeMethodVersion(client, {+ copyFromId: activeMethodId,+ // No `activeVersionId`: it sets a version Active, and the push leaves live methods alone.+ version,+ companyId,+ createdBy: userId+ });+ if (draft.error || !draft.data?.id) {+ return {+ ok: false,+ error: draft.error?.message ?? "could not create a draft version"+ };+ }+ const draftId = draft.data.id;++ // `upsertMakeMethodVersion` copies only the method row; the BOM and routing come here.+ const copied = await copyMakeMethod(client, db, {+ sourceId: activeMethodId,+ targetId: draftId,+ companyId,+ userId,+ billOfMaterial: true,+ billOfProcess: true,+ parameters: true,+ tools: true,+ steps: true,+ workInstructions: true+ });+ const failure = copied.error+ ? `its method could not be copied (${copied.error.message})`+ : await carryLineOwnership(client, serviceRole, {+ sourceMethodId: activeMethodId,+ targetMethodId: draftId,+ companyId,+ userId+ });+ const marked = failure+ ? null+ : await client.from("externalIntegrationMapping").insert({+ entityType: DRAFT_MARKER_ENTITY_TYPE,+ entityId: draftId,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ // Not the source id: two Drafts of one method would collide on the unique index.+ externalId: draftId,+ metadata: { sourceMethodId: activeMethodId, itemId } as Json,+ lastSyncedAt: datetime.timestamp(),+ companyId,+ createdBy: userId+ });+ const problem =+ failure ??+ (marked?.error+ ? `it could not be marked as Onshape's (${marked.error.message})`+ : null);+ if (!problem) {+ return { ok: true, id: draftId, created: true, version };+ }++ // A half-built Draft, released, would ship without what failed to copy. Service+ // role: line mappings have no user DELETE policy. The lines cascade.+ const discarded = await discardDraft(serviceRole, {+ draftId,+ companyId+ });+ return {+ ok: false,+ error: discarded+ ? `a draft version was created but ${problem}, so it was removed; push again`+ : `a draft version was created but ${problem}, and it could not be removed — delete version ${version} before pushing again`+ };+ }++ async function discardDraft(+ serviceRole: Client,+ args: { draftId: string; companyId: string }+ ): Promise<boolean> {+ const { draftId, companyId } = args;+ const mappings = await serviceRole+ .from("externalIntegrationMapping")+ .delete()+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "methodMaterial")+ .eq("metadata->>makeMethodId", draftId);+ const removed = await serviceRole+ .from("makeMethod")+ .delete()+ .eq("id", draftId)+ .eq("companyId", companyId);+ const error = mappings.error ?? removed.error;+ if (error) {+ onshapeDraftMethodLogger.error(+ "Failed to discard a half-built Onshape Draft",+ {+ companyId,+ draftId,+ error+ }+ );+ return false;+ }+ return true;+ }++ /**+ * Copy this integration's line mappings onto the copied lines: ownership is+ * keyed on line id, and unmapped copies would read as manual and be duplicated.+ */+ async function carryLineOwnership(+ client: Client,+ serviceRole: Client,+ args: {+ sourceMethodId: string;+ targetMethodId: string;+ companyId: string;+ userId: string;+ }+ ): Promise<string | null> {+ const { sourceMethodId, targetMethodId, companyId, userId } = args;++ const mappings = await serviceRole+ .from("externalIntegrationMapping")+ .select("entityId, externalId, metadata, lastSyncedAt")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "methodMaterial")+ .eq("metadata->>makeMethodId", sourceMethodId);+ if (mappings.error) return mappings.error.message;+ if ((mappings.data ?? []).length === 0) return null;++ const [sourceLines, targetLines] = await Promise.all([+ client+ .from("methodMaterial")+ .select("id, itemId, order, quantity")+ .eq("makeMethodId", sourceMethodId)+ .eq("companyId", companyId),+ client+ .from("methodMaterial")+ .select("id, itemId, order")+ .eq("makeMethodId", targetMethodId)+ .eq("companyId", companyId)+ ]);+ if (sourceLines.error) return sourceLines.error.message;+ if (targetLines.error) return targetLines.error.message;++ const owned = new Set((mappings.data ?? []).map((row) => row.entityId));+ const paired = pairOwnedCopiedLines(+ sourceLines.data ?? [],+ targetLines.data ?? [],+ owned+ );++ const inserts = [];+ for (const mapping of mappings.data ?? []) {+ const targetLineId = paired.get(mapping.entityId);+ // Unpaired: left unmapped, so it reads as manual and is kept, not duplicated.+ if (!targetLineId) continue;+ const metadata = {+ ...((mapping.metadata as Record<string, unknown> | null) ?? {}),+ makeMethodId: targetMethodId+ };+ inserts.push({+ entityType: "methodMaterial",+ entityId: targetLineId,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ externalId: mapping.externalId,+ metadata: metadata as Json,+ lastSyncedAt: mapping.lastSyncedAt,+ companyId,+ createdBy: userId+ });+ }+ if (inserts.length === 0) return null;++ const written = await client+ .from("externalIntegrationMapping")+ .insert(inserts);+ if (written.error) {+ return `${inserts.length} of its lines could not be linked to Onshape (${written.error.message})`;+ }+ return null;+ }++ type MethodMaterialInsert =+ Database["public"]["Tables"]["methodMaterial"]["Insert"];++ export type OwnedMethodLine = {+ row: Omit<MethodMaterialInsert, "companyId" | "createdBy">;+ /** Ownership row metadata; `makeMethodId` names the line's method. */+ metadata: Record<string, unknown>;+ };+ const onshapePushLogger = getLogger("erp", "onshape", "push");++ /**+ * Replace an item's Onshape link in one transaction: delete any row for this+ * item or this externalId, then insert. Both unique indexes need the deletes first.+ */+ export async function swapItemMapping(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ itemId: string;+ externalId: string;+ metadata: Record<string, unknown>;+ }+ ): Promise<{ id: string; error: null } | { id: null; error: string }> {+ const { companyId, userId, itemId, externalId } = args;+ const now = datetime.timestamp();+ try {+ const inserted = await db.transaction().execute(async (trx) => {+ await trx+ .deleteFrom("externalIntegrationMapping")+ .where("companyId", "=", companyId)+ .where("integration", "=", ONSHAPE_V2_INTEGRATION_ID)+ .where("entityType", "=", "item")+ .where((eb) =>+ eb.or([+ eb("entityId", "=", itemId),+ eb("externalId", "=", externalId)+ ])+ )+ .execute();+ return trx+ .insertInto("externalIntegrationMapping")+ .values({+ entityType: "item",+ entityId: itemId,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ externalId,+ metadata: args.metadata as Json,+ lastSyncedAt: now,+ companyId,+ createdBy: userId,+ updatedBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ });+ return { id: inserted.id, error: null };+ } catch (error) {+ onshapePushLogger.error("Failed to link an item to Onshape", {+ companyId,+ itemId,+ error+ });+ return {+ id: null,+ error: error instanceof Error ? error.message : "link failed"+ };+ }+ }++ /**+ * Insert BOM lines and their ownership rows in one transaction. A line without+ * its ownership row reads as manual, so the next push keeps it and adds a copy.+ */+ export async function insertOwnedMethodLines(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ lines: OwnedMethodLine[];+ }+ ): Promise<+ { mappingIds: string[]; error: null } | { mappingIds: null; error: string }+ > {+ const { companyId, userId, lines } = args;+ if (lines.length === 0) return { mappingIds: [], error: null };+ const now = datetime.timestamp();+ try {+ const mappingIds = await db.transaction().execute(async (trx) => {+ const inserted = await trx+ .insertInto("methodMaterial")+ .values(+ lines.map((line) => ({+ ...line.row,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .returning("id")+ .execute();+ // Mappings pair with lines by index (RETURNING follows VALUES order).+ if (inserted.length !== lines.length) {+ throw new Error(+ `wrote ${inserted.length} of ${lines.length} lines; nothing was kept`+ );+ }+ const mappings = await trx+ .insertInto("externalIntegrationMapping")+ .values(+ lines.map((line, index) => ({+ entityType: "methodMaterial",+ entityId: inserted[index]!.id,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ metadata: line.metadata as Json,+ lastSyncedAt: now,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .returning("id")+ .execute();+ return mappings.map((mapping) => mapping.id);+ });+ return { mappingIds, error: null };+ } catch (error) {+ onshapePushLogger.error("Failed to write Onshape BOM lines", {+ companyId,+ count: lines.length,+ error+ });+ return {+ mappingIds: null,+ error: error instanceof Error ? error.message : "line insert failed"+ };+ }+ }++ /**+ * Take over a manual line in one transaction: set the Onshape-owned columns and+ * write its ownership row. Operation, scrap, tags and kit are kept.+ */+ export async function claimManualMethodLine(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ lineId: string;+ update: {+ itemId: string;+ quantity: number;+ order: number;+ materialMakeMethodId: string | null;+ };+ metadata: Record<string, unknown>;+ }+ ): Promise<+ { mappingId: string; error: null } | { mappingId: null; error: string }+ > {+ const { companyId, userId, lineId } = args;+ const now = datetime.timestamp();+ try {+ const mappingId = await db.transaction().execute(async (trx) => {+ const updated = await trx+ .updateTable("methodMaterial")+ .set({ ...args.update, updatedBy: userId, updatedAt: now })+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .returning("id")+ .executeTakeFirst();+ if (!updated) throw new Error("the line no longer exists");+ const mapping = await trx+ .insertInto("externalIntegrationMapping")+ .values({+ entityType: "methodMaterial",+ entityId: lineId,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ metadata: args.metadata as Json,+ lastSyncedAt: now,+ companyId,+ createdBy: userId,+ updatedBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ return mapping.id;+ });+ return { mappingId, error: null };+ } catch (error) {+ onshapePushLogger.error("Failed to take over a BOM line for Onshape", {+ companyId,+ lineId,+ error+ });+ return {+ mappingId: null,+ error: error instanceof Error ? error.message : "line takeover failed"+ };+ }+ }++ export type OpenReleaseNotice = {+ id: string;+ changeNoticeId: string;+ affectedCount: number;+ };++ /**+ * The notice an earlier push of this release made, while it still takes items:+ * a release spanning two documents is pushed once per document into one notice.+ * Fails closed: a read that fails is an error, never "no open notice", which+ * would open a second notice for the release.+ */+ export async function findOpenReleaseNotice(+ client: SupabaseClient<Database>,+ companyId: string,+ releaseId: string+ ): Promise<+ | { data: OpenReleaseNotice | null; error: null }+ | { data: null; error: string }+ > {+ const failed = (what: string, error: unknown) => {+ onshapePushLogger.error("Could not read a release's earlier push", {+ companyId,+ releaseId,+ read: what,+ error+ });+ return {+ data: null,+ error: `Carbon couldn't read this release's earlier ${what}`+ };+ };++ // Matched on the release id the link's metadata carries, not a LIKE on the+ // key: a synthetic release id holds a part number, which may contain % or _.+ const links = await client+ .from("externalIntegrationMapping")+ .select("entityId")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "item")+ .like("externalId", "release:%")+ .eq("metadata->>releaseId", releaseId);+ if (links.error) return failed("links", links.error);+ if (!links.data?.length) return { data: null, error: null };++ const items = await selectInBatches(+ links.data.map((link) => link.entityId),+ (batch) =>+ client+ .from("item")+ .select("changeOrderId")+ .eq("companyId", companyId)+ .in("id", batch)+ .not("changeOrderId", "is", null)+ );+ if (items.error) return failed("items", items.error);+ const noticeIds = [+ ...new Set(+ items.data+ .map((item) => item.changeOrderId)+ .filter((id): id is string => !!id)+ )+ ];+ if (noticeIds.length === 0) return { data: null, error: null };++ const notices = await selectInBatches(noticeIds, (batch) =>+ client+ .from("changeOrder")+ .select(+ "id, changeOrderId, status, createdAt, changeOrderAffectedItem(id)"+ )+ .eq("companyId", companyId)+ .in("id", batch)+ );+ if (notices.error) return failed("change notices", notices.error);+ // Batches arrive in batch order: the oldest open notice wins.+ const editable = notices.data+ .filter((notice) => canEditChangeNoticeEngineering(notice.status))+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));+ // A pending approval freezes the notice's engineering content; one can be+ // pending only at Engineering Complete. approvalRequest is service-role only.+ const awaitingIds = editable+ .filter((notice) => notice.status === "Engineering Complete")+ .map((notice) => notice.id);+ const awaiting = new Set<string>();+ if (awaitingIds.length > 0) {+ const pending = await selectInBatches(awaitingIds, (batch) =>+ getCarbonServiceRole()+ .from("approvalRequest")+ .select("documentId")+ .eq("companyId", companyId)+ .eq("documentType", "changeOrder")+ .eq("status", "Pending")+ .in("documentId", batch)+ );+ if (pending.error) return failed("change notice approvals", pending.error);+ for (const row of pending.data) awaiting.add(row.documentId);+ }+ const open = editable.find((notice) => !awaiting.has(notice.id));+ return {+ data: open+ ? {+ id: open.id,+ changeNoticeId: open.changeOrderId,+ affectedCount: open.changeOrderAffectedItem?.length ?? 0+ }+ : null,+ error: null+ };+ }++ /**+ * Stage a created item under a change notice as `createChangeNoticeDraftMethod`+ * does: item inactive, item and Draft method stamped, one affected-item row.+ */+ export async function stageChangeNoticeItem(+ db: Kysely<KyselyDatabase>,+ args: {+ /** `changeOrder.id`, not its readable id. */+ changeOrderId: string;+ companyId: string;+ userId: string;+ itemId: string;+ /** The revision this one replaces; null for a New Part. */+ baseItemId: string | null;+ sortOrder: number;+ }+ ): Promise<{ error: string | null }> {+ const { changeOrderId, companyId, userId, itemId, baseItemId } = args;+ const now = datetime.timestamp();+ try {+ await db.transaction().execute(async (trx) => {+ const draft = await trx+ .selectFrom("makeMethod")+ .select("id")+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Draft")+ .orderBy("version", "desc")+ .executeTakeFirst();+ // Release refuses an affected item with no Draft to activate.+ if (!draft) throw new Error("the item has no Draft make method");+ const base = baseItemId+ ? await trx+ .selectFrom("activeMakeMethods")+ .select("id")+ .where("itemId", "=", baseItemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : undefined;++ await trx+ .updateTable("item")+ .set({+ active: false,+ changeOrderId,+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .updateTable("makeMethod")+ .set({ changeOrderId, updatedBy: userId, updatedAt: now })+ .where("id", "=", draft.id)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("changeOrderAffectedItem")+ .values({+ changeOrderId,+ itemId: baseItemId ?? itemId,+ changeType: baseItemId ? "Revision" : "New Part",+ sortOrder: args.sortOrder,+ draftMakeMethodId: draft.id,+ baseMakeMethodId: base?.id ?? null,+ newItemId: itemId,+ companyId,+ createdBy: userId+ })+ .execute();+ });+ return { error: null };+ } catch (error) {+ onshapePushLogger.error("Failed to stage an item under a change notice", {+ companyId,+ changeOrderId,+ itemId,+ error+ });+ return {+ error: error instanceof Error ? error.message : "staging failed"+ };+ }+ }++ type ItemEnums = Database["public"]["Enums"];++ /** Item field values a push writes; an absent key is not written. */+ export type ItemFieldWrite = {+ replenishmentSystem?: ItemEnums["itemReplenishmentSystem"];+ defaultMethodType?: ItemEnums["methodType"];+ sourcingType?: ItemEnums["sourcingType"];+ itemTrackingType?: ItemEnums["itemTrackingType"];+ unitOfMeasureCode?: string;+ mpn?: string | null;+ };++ type WriterContext = {+ client: SupabaseClient<Database>;+ db: Kysely<KyselyDatabase>;+ itemId: string;+ companyId: string;+ userId: string;+ };++ export async function updateItemColumns(+ client: SupabaseClient<Database>,+ args: {+ itemId: string;+ companyId: string;+ userId: string;+ values: Pick<ItemFieldWrite, "mpn" | "unitOfMeasureCode">;+ }+ ) {+ return client+ .from("item")+ .update({+ ...(args.values.mpn !== undefined ? { mpn: args.values.mpn } : {}),+ ...(args.values.unitOfMeasureCode !== undefined+ ? { unitOfMeasureCode: args.values.unitOfMeasureCode }+ : {}),+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", args.itemId)+ .eq("companyId", args.companyId);+ }++ /**+ * One writer per `StandardFieldWriter` key. Each writes as the item page does,+ * so the cascades onto Draft method lines and open documents follow.+ */+ const STANDARD_FIELD_WRITERS: Record<+ StandardFieldWriter,+ (ctx: WriterContext, write: ItemFieldWrite) => Promise<string | null>+ > = {+ itemMethod: async (ctx, write) => {+ const { replenishmentSystem, defaultMethodType, sourcingType } = write;+ await updateItemMethodAndSourcing(ctx.db, {+ itemIds: [ctx.itemId],+ companyId: ctx.companyId,+ userId: ctx.userId,+ itemUpdate: { replenishmentSystem, defaultMethodType, sourcingType },+ cascade: {+ ...(defaultMethodType !== undefined+ ? { methodType: defaultMethodType }+ : {}),+ ...(sourcingType !== undefined ? { sourcingType } : {})+ }+ });+ return null;+ },+ itemTracking: async (ctx, write) => {+ if (write.itemTrackingType === undefined) return null;+ const updated = await ctx.client+ .from("item")+ .update({+ itemTrackingType: write.itemTrackingType,+ updatedBy: ctx.userId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", ctx.itemId)+ .eq("companyId", ctx.companyId);+ if (updated.error) return updated.error.message;+ await cascadeItemTrackingType(ctx.db, {+ itemIds: [ctx.itemId],+ companyId: ctx.companyId,+ newType: write.itemTrackingType,+ userId: ctx.userId+ });+ return null;+ },+ itemColumn: async (ctx, write) => {+ const updated = await updateItemColumns(ctx.client, {+ itemId: ctx.itemId,+ companyId: ctx.companyId,+ userId: ctx.userId,+ values: write+ });+ return updated.error ? updated.error.message : null;+ }+ };++ const WRITER_ORDER: StandardFieldWriter[] = [+ "itemMethod",+ "itemTracking",+ "itemColumn"+ ];++ /** Values must be final: this applies no interlock. Returns an error message, or null. */+ export async function applyItemFieldWrites(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ itemId: string;+ companyId: string;+ userId: string;+ changed: ItemFieldWrite;+ }+ ): Promise<string | null> {+ const { itemId, companyId, userId } = args;+ const ctx: WriterContext = { client, db, itemId, companyId, userId };+ try {+ for (const writer of WRITER_ORDER) {+ const write: ItemFieldWrite = {};+ for (const [field, value] of Object.entries(args.changed)) {+ if (value === undefined) continue;+ if (standardField(field)?.writer !== writer) continue;+ (write as Record<string, unknown>)[field] = value;+ }+ if (Object.keys(write).length === 0) continue;+ const error = await STANDARD_FIELD_WRITERS[writer](ctx, write);+ if (error) return error;+ }+ return null;+ } catch (error) {+ onshapePushLogger.error("Failed to write item fields from Onshape", {+ companyId,+ itemId,+ error+ });+ return error instanceof Error ? error.message : "Failed to update the item";+ }+ }++ /**+ * Write to an item the push did not create: the "everyPush" descriptions, then+ * the plan's target with the reviewer's edits on top. Returns the fields after+ * the write, which a BOM line written later copies its method and unit from.+ */+ export async function applyExistingItemFields(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ itemId: string;+ companyId: string;+ userId: string;+ current: ItemFieldSnapshot | null | undefined;+ target?: ItemFieldSnapshot;+ edit?: ItemEdit;+ descriptions?: OwnedFieldChange[];+ }+ ): Promise<{ values: ItemFieldSnapshot | null; error: string | null }> {+ const { itemId, companyId, userId } = args;+ const merged = args.current+ ? mergeExistingItemEdits(args.current, args.edit, args.target)+ : null;+ if (merged && !merged.ok) {+ return { values: null, error: merged.errors.join("; ") };+ }++ const text: { name?: string; description?: string } = {};+ for (const change of args.descriptions ?? []) {+ if (change.to !== null) text[change.field] = change.to;+ }+ if (Object.keys(text).length > 0) {+ const updated = await client+ .from("item")+ .update({ ...text, updatedBy: userId, updatedAt: datetime.timestamp() })+ .eq("id", itemId)+ .eq("companyId", companyId);+ if (updated.error) {+ return { values: null, error: updated.error.message };+ }+ }++ if (merged?.ok && Object.keys(merged.changed).length > 0) {+ const error = await applyItemFieldWrites(client, db, {+ itemId,+ companyId,+ userId,+ changed: merged.changed+ });+ if (error) return { values: null, error };+ }+ return { values: merged?.ok ? merged.values : null, error: null };+ }+ const onshapeOauthLogger = getLogger("erp", "onshape", "oauth");++ /** Absolute integrations-page URL on this request's origin. */+ function integrationsUrl(request: Request) {+ const requestUrl = new URL(request.url);++ if (!VERCEL_URL || VERCEL_URL.includes("localhost")) {+ requestUrl.protocol = "http";+ }++ return `${requestUrl.origin}${path.to.integrations}`;+ }++ /**+ * The OAuth callback for every Onshape grant (`onshape`, `onshape-government`,+ * `onshape-v2`); `loadOnshapeOAuthConfig` picks the client. Onshape redirects+ * the browser here, in the install popup or the whole tab, so the outcome+ * renders through `oauthPopupResponse`. Only an error code crosses;+ * `integrationErrors` owns the copy.+ */+ export async function completeOnshapeAuthorization({+ request,+ integrationId,+ userId,+ companyId+ }: {+ request: Request;+ integrationId: OnshapeOAuthIntegrationId;+ userId: string;+ companyId: string;+ }) {+ const url = new URL(request.url);+ const searchParams = Object.fromEntries(url.searchParams.entries());++ // The state must be the one issued to THIS browser for this user, company and+ // integration. Without the check anyone could send a victim a callback URL+ // carrying the attacker's own Onshape code, linking the victim's company to+ // the attacker's Onshape account. Single-use: consumed whether it matches or+ // not.+ const consumedState = await consumeOAuthState(+ request,+ url.searchParams.get("state") ?? "",+ { integrationId, userId, companyId }+ );++ // Every Onshape integration declares the same codes, each with its copy.+ const connectionFailed = (+ reason: IntegrationErrorCode<OnshapeOAuthIntegrationId>+ ) =>+ withCookie(+ oauthPopupResponse(+ { integration: integrationId, ok: false, error: reason },+ `${integrationsUrl(request)}${integrationErrorSearch<OnshapeOAuthIntegrationId>(integrationId, reason)}`+ ),+ consumedState.cookie+ );++ if (!consumedState.valid) {+ onshapeOauthLogger.error("Invalid Onshape OAuth state", {+ integrationId,+ companyId+ });+ return connectionFailed("invalid-state");+ }++ // Onshape reports a refused authorization by redirecting here with `error`+ // (and usually `error_description`) in place of `code`. `invalid_scope`+ // means the OAuth application isn't granted a scope we asked for — in+ // practice `OAuth2Write` ("Application can write to your documents"), so the+ // UI can name the exact fix instead of echoing Onshape's wording.+ if (searchParams.error) {+ onshapeOauthLogger.error("Onshape authorization refused", {+ integrationId,+ error: searchParams.error,+ errorDescription: searchParams.error_description+ });+ return connectionFailed(+ searchParams.error === "invalid_scope" ? "write-permission" : "denied"+ );+ }++ const authResponse = oAuthCallbackSchema.safeParse(searchParams);+ if (!authResponse.success) {+ // Log the parameter names (never the values — `code` is a live credential).+ onshapeOauthLogger.error("Invalid Onshape auth response", {+ integrationId,+ params: Object.keys(searchParams)+ });+ return connectionFailed("invalid-response");+ }++ const serviceRole = getCarbonServiceRole();++ // A company holds one Onshape sync connection at a time; two would leave+ // every background job guessing which tenant to talk to. The panel's grant+ // is outside that rule.+ if (+ isOnshapeIntegrationId(integrationId) &&+ (await getConflictingOnshapeIntegration(+ serviceRole,+ companyId,+ integrationId+ ))+ ) {+ return connectionFailed("connection-conflict");+ }++ const oauth = await loadOnshapeOAuthConfig(companyId, integrationId);+ if (!oauth) return connectionFailed("not-configured");++ try {+ let tokenData: Awaited<ReturnType<typeof exchangeOnshapeAuthorizationCode>>;+ try {+ tokenData = await exchangeOnshapeAuthorizationCode(+ oauth,+ authResponse.data.code+ );+ } catch (error) {+ onshapeOauthLogger.error("Onshape token exchange failed", {+ integrationId,+ error+ });+ return connectionFailed("token-exchange");+ }++ if (!tokenData.access_token) {+ onshapeOauthLogger.error("Onshape token response had no access token", {+ integrationId+ });+ return connectionFailed("token-exchange");+ }++ // The scope actually granted by this authorization. Onshape returns it on+ // the token response; fall back to what we requested. A token minted+ // without write can't export assets or manage the release webhook, and a+ // refresh can't widen it, so the grant patch turns asset sync off. The+ // patch writes only the grant's keys, so settings survive a reconnect.+ const scope = tokenData.scope ?? ONSHAPE_OAUTH_SCOPES.join(" ");+ let saved: Awaited<ReturnType<typeof patchOnshapeOAuthGrant>>;+ try {+ saved = await patchOnshapeOAuthGrant(+ serviceRole,+ companyId,+ integrationId,+ {+ accessToken: tokenData.access_token,+ refreshToken: tokenData.refresh_token,+ expiresAt: parseAbsolute(datetime.timestamp(), "UTC")+ .add({ seconds: tokenData.expires_in ?? 3600 })+ .toAbsoluteString(),+ scope,+ baseUrl: oauth.baseUrl,+ canWrite: onshapeConnectionHasWriteScope({ scope }),+ updatedBy: userId+ }+ );+ } catch (error) {+ onshapeOauthLogger.error("Failed to save Onshape integration", {+ integrationId,+ error+ });+ return connectionFailed("save-failed");+ }+ await clearCompanyIntegrationCache(companyId);+ const metadata = (saved.metadata ?? {}) as Record<string, unknown>;++ // A Government connection is configured BEFORE it is authorized, so asset+ // sync may already be on: subscribe to releases now that there is a token.+ // Best-effort — the settings save retries it and reports a failure there.+ if (metadata.assetSyncEnabled === true) {+ const webhook = await ensureOnshapeReleaseWebhook(companyId, true);+ if (!webhook.ok) {+ onshapeOauthLogger.error(+ "Onshape release webhook registration failed",+ {+ integrationId,+ error: webhook.error+ }+ );+ }+ }++ return withCookie(+ oauthPopupResponse(+ { integration: integrationId, ok: true },+ integrationsUrl(request)+ ),+ consumedState.cookie+ );+ } catch (error) {+ onshapeOauthLogger.error("Onshape OAuth Error", { integrationId, error });+ return connectionFailed("unexpected");+ }+ }++ function withCookie(response: Response, cookie: string) {+ response.headers.append("Set-Cookie", cookie);+ return response;+ }++ /**+ * What an Onshape panel operation answers. The panel reads the HTTP status+ * and the JSON body (`error`, `fieldErrors`, `code`), so its route sends both+ * as given (`panelResponse`).+ */+ export type PanelReply = { status: number; body: unknown };++ export function panelReply(+ body: unknown,+ init?: { status?: number; headers?: HeadersInit }+ ): PanelReply {+ return { status: init?.status ?? 200, body };+ }+ const itemEditSchema = z.object({+ name: z.string().optional(),+ description: z.string().nullable().optional(),+ replenishmentSystem: z.string().optional(),+ defaultMethodType: z.string().optional(),+ itemTrackingType: z.string().optional(),+ unitOfMeasureCode: z.string().optional()+ });++ export const onshapePartPushInput = z.object({+ planId: z.string().min(1),+ selected: z.array(z.string().min(1)).min(1).max(50),+ edits: z.record(z.string(), itemEditSchema).default({})+ });++ type ApplyResult = {+ partId: string;+ action: "created" | "adopted" | "updated" | "unchanged" | "skipped" | "error";+ itemId?: string;+ readableId?: string;+ message?: string;+ };++ /** Apply a reviewed part plan: create or adopt items, link them, queue model exports. */+ export async function pushOnshapePart(+ ctx: ServiceContext,+ input: z.infer<typeof onshapePartPushInput>+ ): Promise<PanelReply> {+ const client = ctx.asCaller.supabase;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const { planId } = input;+ const selected = [...new Set(input.selected)];+ const edits = input.edits as Record<string, ItemEdit>;++ const stored = await peekPanelPlan(planId, { companyId, userId });+ if (!stored) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }+ if (stored.plan.kind !== "part") {+ return panelReply(+ { error: "This review is not a part push" },+ { status: 400 }+ );+ }+ const plan: PartPlan = stored.plan;+ const { documentId, wv, wvId, elementId, options } = plan;+ const configuration = plan.configuration ?? null;++ const rowByPartId = new Map(plan.rows.map((row) => [row.partId, row]));+ const selectedRows = selected+ .map((partId) => rowByPartId.get(partId))+ .filter((row): row is PartPlanRow => !!row);++ const merged = mergeEditsForCreates(+ selectedRows+ .filter((row) => row.action === "create" && row.partNumber)+ .map((row) => ({ key: row.partId, proposed: proposedFor(row, plan) })),+ edits,+ options+ );+ const fieldErrors = merged.errors;+ if (fieldErrors.length > 0) {+ return panelReply(+ { error: "Some edits are not valid", fieldErrors },+ { status: 422 }+ );+ }++ if (!(await takePanelPlan(planId, { companyId, userId }))) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }++ // A create whose number now exists adopts it: `upsertPart` reads its new id+ // back by readableId and could get another revision.+ const partNumbers = [+ ...new Set(+ selectedRows+ .map((row) => row.partNumber)+ .filter((number): number is string => !!number)+ )+ ];+ const targetItemIds = [+ ...new Set(+ selectedRows+ .filter((row) => row.action === "adopt" || row.action === "update")+ .map((row) => row.itemId)+ .filter((id): id is string => !!id)+ )+ ];+ const [byNumber, byId] = await Promise.all([+ selectInBatches(partNumbers, (batch) =>+ client+ .from("item")+ .select("id, readableId, revision, active, name, type")+ .eq("companyId", companyId)+ .in("readableId", batch)+ .order("revision")+ ),+ selectInBatches(targetItemIds, (batch) =>+ client+ .from("item")+ .select("id, readableId, revision, active, name, type")+ .eq("companyId", companyId)+ .in("id", batch)+ )+ ]);+ if (byNumber.error || byId.error) {+ return panelReply(+ { error: "Failed to read Carbon items" },+ { status: 500 }+ );+ }+ const rowsByReadableId = new Map<string, PlanItemRow[]>();+ for (const item of (byNumber.data ?? []) as PlanItemRow[]) {+ const list = rowsByReadableId.get(item.readableId) ?? [];+ list.push(item);+ rowsByReadableId.set(item.readableId, list);+ }+ const itemById = new Map(+ ((byId.data ?? []) as PlanItemRow[]).map((item) => [item.id, item])+ );++ const serviceRole = getCarbonServiceRole();+ const db = ctx.asSystem.pg;++ const resolveTarget = (row: PartPlanRow): PlanItemRow | undefined => {+ let target: PlanItemRow | undefined;+ if (row.action === "adopt" || row.action === "update") {+ target = row.itemId ? itemById.get(row.itemId) : undefined;+ }+ if (!target && row.partNumber) {+ target = pickAdoptTarget(+ rowsByReadableId.get(row.partNumber) ?? [],+ row.revision+ );+ }+ return target;+ };++ // `part.id` is the readableId, shared across revisions. Kept current as the+ // loop writes, so a later row cannot clobber a create.+ const partCustomFieldsByReadableId = new Map<string, unknown>();+ const ownedReadableIds = [+ ...new Set(+ selectedRows.flatMap((row) => {+ if (existingCustomFieldValues(row) === null) return [];+ const ids: string[] = [];+ if (row.partNumber) ids.push(row.partNumber);+ const target = row.itemId ? itemById.get(row.itemId) : undefined;+ if (target) ids.push(target.readableId);+ return ids;+ })+ )+ ];+ const partRows = await selectInBatches(ownedReadableIds, (batch) =>+ client+ .from("part")+ .select("id, customFields")+ .eq("companyId", companyId)+ .in("id", batch)+ );+ if (partRows.error) {+ return panelReply(+ { error: "Failed to read Carbon parts" },+ { status: 500 }+ );+ }+ for (const partRow of partRows.data) {+ partCustomFieldsByReadableId.set(partRow.id, partRow.customFields);+ }++ const results: ApplyResult[] = [];++ for (const partId of selected) {+ const row = rowByPartId.get(partId);+ if (!row) {+ results.push({+ partId,+ action: "error",+ message: "Part is not in this review"+ });+ continue;+ }++ if (row.action === "skip-no-part-number") {+ results.push({+ partId,+ action: "skipped",+ message: "Set a part number in Onshape first"+ });+ continue;+ }++ if (row.action === "released") {+ results.push({+ partId,+ action: "skipped",+ message: `Released in Onshape as Rev ${row.item?.revision ?? "?"}: changes come through a release`+ });+ continue;+ }++ if (row.action === "unchanged") {+ // A reviewer edit is still written; no link re-stamp, no export.+ if (row.itemId && edits[partId]) {+ const applied = await applyExistingItemFields(client, db, {+ itemId: row.itemId,+ companyId,+ userId,+ current: row.current,+ edit: edits[partId]+ });+ if (applied.error) {+ results.push({ partId, action: "error", message: applied.error });+ continue;+ }+ results.push({+ partId,+ action: "updated",+ itemId: row.itemId,+ readableId: row.item?.readableId+ });+ continue;+ }+ results.push({+ partId,+ action: "unchanged",+ itemId: row.itemId ?? undefined,+ readableId: row.item?.readableId+ });+ continue;+ }++ const target = resolveTarget(row);+ const resolved: "create" | "adopt" | "update" = target+ ? row.action === "update" && target.id === row.itemId+ ? "update"+ : "adopt"+ : "create";++ let itemId: string;+ let readableId: string;+ if (resolved === "create") {+ const item = merged.items.get(row.partId) ?? proposedFor(row, plan);+ const fieldValues = planCustomFieldValues(row);+ const created = await upsertPart(client, {+ id: item.readableId,+ name: item.name,+ description: item.description ?? undefined,+ revision: item.revision,+ replenishmentSystem: item.replenishmentSystem,+ defaultMethodType: item.defaultMethodType,+ itemTrackingType: item.itemTrackingType,+ unitOfMeasureCode: item.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ ...(Object.keys(fieldValues).length > 0 && {+ customFields: fieldValues+ })+ // partValidator carries many optional form-only fields the panel never sets+ } as any);+ if (created.error || !created.data) {+ results.push({+ partId,+ action: "error",+ message: created.error?.message ?? "Failed to create the item"+ });+ continue;+ }+ itemId = created.data.id as string;+ readableId = item.readableId;+ const extras = createdItemExtras(item);+ if (Object.keys(extras).length > 0) {+ const error = await applyItemFieldWrites(client, db, {+ itemId,+ companyId,+ userId,+ changed: extras+ });+ if (error) {+ results.push({+ partId,+ action: "error",+ itemId,+ readableId,+ message: `Item created, but its mapped fields were not written (${error})`+ });+ continue;+ }+ }+ // A later row with the same number adopts this item, not a second create.+ rowsByReadableId.set(readableId, [+ ...(rowsByReadableId.get(readableId) ?? []),+ {+ id: itemId,+ readableId,+ revision: item.revision,+ name: item.name,+ type: "Part"+ }+ ]);+ if (Object.keys(fieldValues).length > 0) {+ partCustomFieldsByReadableId.set(readableId, fieldValues);+ }+ } else {+ itemId = (target as PlanItemRow).id;+ readableId = (target as PlanItemRow).readableId;+ const applied = await applyExistingItemFields(client, db, {+ itemId,+ companyId,+ userId,+ current: row.current,+ target: row.target,+ edit: edits[partId],+ descriptions: row.changes+ });+ if (applied.error) {+ results.push({ partId, action: "error", message: applied.error });+ continue;+ }+ const owned = existingCustomFieldValues(row);+ if (owned) {+ const mergedFields = mergeCustomFieldValues(+ partCustomFieldsByReadableId.get(readableId),+ owned.values,+ owned.fieldIds+ );+ const partUpdate = await client+ .from("part")+ .update({+ customFields: mergedFields as Json,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", readableId)+ .eq("companyId", companyId);+ if (partUpdate.error) {+ results.push({+ partId,+ action: "error",+ message: partUpdate.error.message+ });+ continue;+ }+ partCustomFieldsByReadableId.set(readableId, mergedFields);+ }+ }++ const externalId = externalIdForPart(+ documentId,+ elementId,+ partId,+ configuration+ );+ const now = datetime.timestamp();+ const linked = await swapItemMapping(db, {+ companyId,+ userId,+ itemId,+ externalId,+ metadata: {+ documentId,+ elementId,+ partId,+ configuration,+ wv,+ wvId,+ // A later plan's only "unchanged" signal.+ microversionId: row.microversionId,+ partNumber: row.partNumber,+ name: row.name,+ revision: row.revision,+ pushedBy: userId,+ pushedAt: now,+ planId+ }+ });+ if (linked.error !== null) {+ results.push({+ partId,+ action: "error",+ message: "Item saved but the Onshape link failed; push again"+ });+ continue;+ }++ if (row.cadUnchanged && resolved === "update") {+ results.push({ partId, action: "updated", itemId, readableId });+ continue;+ }++ try {+ await trigger(+ "onshape-panel-sync",+ {+ companyId,+ userId,+ itemId,+ documentId,+ wvm: wv,+ wvmId: wvId,+ elementId,+ elementKind: "partstudio",+ partId,+ ...(configuration ? { configuration } : {}),+ ...(wv === "w" && row.microversionId+ ? { microversionId: row.microversionId }+ : {}),+ assetBaseName: row.partNumber ?? row.name+ },+ { id: `${planId}:${itemId}:${elementId}` }+ );+ } catch (error) {+ // Unlink so the next plan does not read "unchanged" and skip the export.+ // By id, not externalId: a concurrent push may have replaced the row.+ const rolledBack = await serviceRole+ .from("externalIntegrationMapping")+ .delete()+ .eq("companyId", companyId)+ .eq("id", linked.id);+ results.push({+ partId,+ action: "error",+ itemId,+ readableId,+ message: rolledBack.error+ ? `Item saved but the model export could not be queued, and the Onshape link could not be rolled back (${rolledBack.error.message}); detach this item before pushing again`+ : `Item saved but the model export could not be queued; push again (${+ error instanceof Error ? error.message : "event send failed"+ })`+ });+ continue;+ }++ results.push({+ partId,+ action:+ resolved === "create"+ ? "created"+ : resolved === "adopt"+ ? "adopted"+ : "updated",+ itemId,+ readableId+ });+ }++ return panelReply(+ { results },+ {+ headers: { "Cache-Control": "no-store" }+ }+ );+ }++ /** The plan's proposal, or one built from the row when the target vanished. */+ function proposedFor(row: PartPlanRow, plan: PartPlan): ProposedItem {+ if (row.proposed) return row.proposed;+ return proposeItem(+ {+ partNumber: row.partNumber as string,+ name: row.name,+ description: row.description,+ revision: row.revision+ },+ plan.options+ );+ }++ function planCustomFieldValues(+ row: PartPlanRow+ ): Record<string, string | number | boolean | null> {+ return mappedFieldValues(row.customFields ?? [], true).values;+ }++ /** The "everyPush" values an adopt or update writes; a null value deletes the key. */+ function existingCustomFieldValues(row: PartPlanRow): {+ values: Record<string, string | number | boolean | null>;+ fieldIds: Set<string>;+ } | null {+ if (row.action === "create") return null;+ const mapped = mappedFieldValues(row.customFields ?? [], false);+ return mapped.fieldIds.size > 0 ? mapped : null;+ }+ // Shape only: `mergeItemEdits` validates values, so a bad one is a 422 naming the row.++ export const onshapeAssemblyPushInput = z.object({+ planId: z.string().min(1),+ edits: z.record(z.string(), itemEditSchema).default({}),+ excluded: z.array(z.string().min(1)).default([])+ });++ type AssemblyPushSummary = {+ assemblyItemId: string | null;+ itemsCreated: number;+ itemsReused: number;+ linesWritten: number;+ linesUnchanged: number;+ /** Manual lines now following Onshape; also counted in `linesWritten`. */+ linesTakenOver: number;+ descriptionsUpdated: number;+ /** Reused items whose mapped fields this push wrote. */+ fieldsUpdated: number;+ methodsTouched: number;+ /** Parent part numbers whose BOM went into a new Draft. */+ draftVersionsCreated: string[];+ skipped: string[];+ errors: string[];+ };++ type AssemblyPushItemRow = {+ id: string;+ readableId: string;+ revision: string | null;+ /** Absent on an item this push created (Design). */+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"] | null;+ active?: boolean | null;+ type: string | null;+ defaultMethodType: string | null;+ sourcingType: string | null;+ unitOfMeasureCode: string | null;+ };++ /** Apply a reviewed assembly plan: items, BOM lines per method, links, model export. */+ export async function pushOnshapeAssembly(+ ctx: ServiceContext,+ input: z.infer<typeof onshapeAssemblyPushInput>+ ): Promise<PanelReply> {+ const client = ctx.asCaller.supabase;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const { planId } = input;+ const edits = input.edits as Record<string, ItemEdit>;+ const excluded = new Set(input.excluded);++ // Peek, not take: a 422 on the edits leaves the plan for a retry.+ const stored = await peekPanelPlan(planId, { companyId, userId });+ if (!stored) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }+ if (stored.plan.kind !== "assembly") {+ return panelReply(+ { error: "This review is not an assembly push" },+ { status: 400 }+ );+ }+ const plan = stored.plan;+ const { documentId, wv, wvId, elementId, root, options } = plan;+ const configuration = plan.configuration ?? null;++ if (excluded.has(root.partNumber)) {+ return panelReply(+ { error: "The assembly itself cannot be excluded" },+ { status: 400 }+ );+ }++ const creates: Array<{ key: string; proposed: ProposedItem }> = [];+ if (root.action === "create" && root.proposed) {+ creates.push({ key: root.partNumber, proposed: root.proposed });+ }+ for (const item of plan.items) {+ if (+ item.action === "create" &&+ item.proposed &&+ !excluded.has(item.partNumber)+ ) {+ creates.push({ key: item.partNumber, proposed: item.proposed });+ }+ }+ const merged = mergeEditsForCreates(creates, edits, options);+ if (merged.errors.length > 0) {+ return panelReply(+ { error: "Some edits are not valid", fieldErrors: merged.errors },+ { status: 422 }+ );+ }++ if (!(await takePanelPlan(planId, { companyId, userId }))) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }++ const summary: AssemblyPushSummary = {+ assemblyItemId: null,+ itemsCreated: 0,+ itemsReused: 0,+ linesWritten: 0,+ linesUnchanged: 0,+ linesTakenOver: 0,+ descriptionsUpdated: 0,+ fieldsUpdated: 0,+ methodsTouched: 0,+ draftVersionsCreated: [],+ skipped: [...plan.skipped],+ errors: []+ };+ for (const item of plan.items) {+ if (excluded.has(item.partNumber)) {+ summary.skipped.push(`${item.partNumber}: excluded`);+ }+ }++ const includedItems = plan.items.filter(+ (item) => !excluded.has(item.partNumber)+ );+ const partNumbers = [+ ...new Set([root.partNumber, ...includedItems.map((i) => i.partNumber)])+ ];+ const existing = await selectInBatches(partNumbers, (batch) =>+ client+ .from("item")+ .select(+ "id, readableId, revision, revisionStatus, active, type, defaultMethodType, sourcingType, unitOfMeasureCode"+ )+ .eq("companyId", companyId)+ .in("readableId", batch)+ .order("revision")+ );+ if (existing.error) {+ return panelReply(+ { error: "Failed to read Carbon items" },+ { status: 500 }+ );+ }+ const rowsByReadableId = new Map<string, AssemblyPushItemRow[]>();+ for (const row of (existing.data ?? []) as AssemblyPushItemRow[]) {+ const list = rowsByReadableId.get(row.readableId) ?? [];+ list.push(row);+ rowsByReadableId.set(row.readableId, list);+ }++ // A reuse whose row vanished becomes a create, described from the BOM row.+ const allNodes = flattenNodes(plan.nodes);+ const nodeByPartNumber = new Map<string, OnshapeBomNode>();+ for (const node of allNodes) {+ if (node.partNumber && !nodeByPartNumber.has(node.partNumber)) {+ nodeByPartNumber.set(node.partNumber, node);+ }+ }++ const itemByReadableId = new Map<string, AssemblyPushItemRow>();+ const fallbackUnit = defaultUnitOfMeasureCode(options);++ const serviceRole = getCarbonServiceRole();+ const db = ctx.asSystem.pg;++ type PlannedItem = MappedRowPlan & {+ itemId: string | null;+ current?: ItemFieldSnapshot | null;+ changes?: OwnedFieldChange[];+ };++ const customFieldReadIds = [root, ...includedItems]+ .filter(+ (row) =>+ row.action === "reuse" &&+ mappedFieldValues(row.customFields ?? [], false).fieldIds.size > 0+ )+ .map((row) => row.partNumber);+ const heldParts = await selectInBatches(customFieldReadIds, (batch) =>+ client+ .from("part")+ .select("id, customFields")+ .eq("companyId", companyId)+ .in("id", batch)+ );+ if (heldParts.error) {+ return panelReply(+ { error: "Failed to read Carbon parts" },+ { status: 500 }+ );+ }+ const heldCustomFields = new Map<string, unknown>(+ (heldParts.data ?? []).map((part) => [part.id, part.customFields])+ );++ const ensureItem = async (+ partNumber: string,+ planned: PlannedItem,+ propose: () => ProposedItem+ ): Promise<AssemblyPushItemRow | null> => {+ const rows = rowsByReadableId.get(partNumber) ?? [];+ const found =+ rows.find((row) => row.id === planned.itemId) ??+ pickReuseRow(rows) ??+ null;+ if (found) {+ summary.itemsReused += 1;+ if (planned.itemId === null) {+ summary.skipped.push(+ `${partNumber}: added to Carbon since the review; reused as is`+ );+ }+ // Only the row the review was about takes its values and edits.+ if (planned.itemId !== found.id) {+ itemByReadableId.set(partNumber, found);+ return found;+ }+ const applied = await applyExistingItemFields(client, db, {+ itemId: found.id,+ companyId,+ userId,+ current: planned.current,+ target: planned.target,+ edit: edits[partNumber],+ descriptions: planned.changes+ });+ let fieldsWritten = false;+ if (applied.error) {+ summary.errors.push(`${partNumber}: ${applied.error}`);+ } else {+ if (planned.changes?.length) summary.descriptionsUpdated += 1;+ fieldsWritten = (planned.itemFieldChanges?.length ?? 0) > 0;+ }+ const values = mappedFieldValues(planned.customFields ?? [], false);+ if (values.fieldIds.size > 0) {+ const updatedPart = await client+ .from("part")+ .update({+ customFields: mergeCustomFieldValues(+ heldCustomFields.get(partNumber),+ values.values,+ values.fieldIds+ ) as Json,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .eq("id", partNumber)+ .eq("companyId", companyId);+ if (updatedPart.error) {+ summary.errors.push(+ `${partNumber}: failed to write custom fields (${updatedPart.error.message})`+ );+ } else {+ fieldsWritten = true;+ }+ }+ if (fieldsWritten) summary.fieldsUpdated += 1;+ const row: AssemblyPushItemRow = applied.values+ ? {+ ...found,+ defaultMethodType: applied.values.defaultMethodType,+ sourcingType: applied.values.sourcingType ?? found.sourcingType,+ unitOfMeasureCode:+ applied.values.unitOfMeasureCode ?? found.unitOfMeasureCode+ }+ : found;+ itemByReadableId.set(partNumber, row);+ return row;+ }++ const item = merged.items.get(partNumber) ?? propose();+ const customFields = mappedFieldValues(+ planned.customFields ?? [],+ true+ ).values;+ const created = await upsertPart(client, {+ id: item.readableId,+ name: item.name,+ description: item.description ?? undefined,+ revision: item.revision,+ replenishmentSystem: item.replenishmentSystem,+ defaultMethodType: item.defaultMethodType,+ itemTrackingType: item.itemTrackingType,+ unitOfMeasureCode: item.unitOfMeasureCode,+ ...(Object.keys(customFields).length > 0+ ? { customFields: customFields as Json }+ : {}),+ companyId,+ createdBy: userId+ } as any);+ if (created.error || !created.data) {+ summary.errors.push(+ `${partNumber}: ${created.error?.message ?? "failed to create"}`+ );+ return null;+ }+ const row: AssemblyPushItemRow = {+ id: created.data.id as string,+ readableId: partNumber,+ revision: item.revision,+ type: "Part",+ defaultMethodType: item.defaultMethodType,+ sourcingType: item.sourcingType ?? null,+ unitOfMeasureCode: item.unitOfMeasureCode+ };+ const extras = createdItemExtras(item);+ if (Object.keys(extras).length > 0) {+ const error = await applyItemFieldWrites(client, db, {+ itemId: row.id,+ companyId,+ userId,+ changed: extras+ });+ if (error) {+ summary.errors.push(+ `${partNumber}: created, but its mapped fields were not written (${error})`+ );+ }+ }+ itemByReadableId.set(partNumber, row);+ summary.itemsCreated += 1;+ return row;+ };++ const rootItem = await ensureItem(root.partNumber, root, () =>+ proposeItem(+ {+ partNumber: root.partNumber,+ name: root.name,+ description: root.description,+ revision: root.revision+ },+ options+ )+ );+ if (!rootItem) {+ return panelReply(+ { error: summary.errors.join("; ") || "Failed to create the assembly" },+ { status: 500 }+ );+ }+ summary.assemblyItemId = rootItem.id;++ for (const item of includedItems) {+ await ensureItem(item.partNumber, item, () =>+ proposeItem(+ {+ partNumber: item.partNumber,+ name: item.name,+ description: nodeByPartNumber.get(item.partNumber)?.description,+ revision: item.revision,+ hasChildren: item.isAssembly+ },+ options+ )+ );+ }++ const isAssemblyByPartNumber = new Map(+ plan.items.map((item) => [item.partNumber, item.isAssembly])+ );++ // Every sub-assembly, even one this push writes no lines into: its parent's line+ // points at its method, and a null pointer flattens a `top` push's tree.+ const parentItemIds = [+ ...new Set(+ [+ ...plan.methods.map(+ (method) => itemByReadableId.get(method.parentPartNumber)?.id+ ),+ ...plan.items+ .filter((item) => item.isAssembly)+ .map((item) => itemByReadableId.get(item.partNumber)?.id)+ ].filter((id): id is string => !!id)+ )+ ];+ // A failed read must stop the writes, or a `top` push writes null child pointers.+ let methodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;+ try {+ methodByItemId = await loadActiveMakeMethods(+ client,+ companyId,+ parentItemIds+ );+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error+ ? error.message+ : "Failed to read the make methods"+ },+ { status: 500 }+ );+ }+ // A Make to Order line points at its component's make method, as the BOM+ // editor does; this reads it for made parts that are not sub-assemblies.+ const madePartIds = [+ ...new Set(+ plan.items+ .filter((item) => !item.isAssembly && !excluded.has(item.partNumber))+ .map((item) => itemByReadableId.get(item.partNumber))+ .filter(+ (row): row is AssemblyPushItemRow =>+ !!row &&+ row.defaultMethodType === "Make to Order" &&+ !methodByItemId.has(row.id)+ )+ .map((row) => row.id)+ )+ ];+ let madePartMethodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;+ try {+ madePartMethodByItemId = await loadActiveMakeMethods(+ client,+ companyId,+ madePartIds+ );+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error+ ? error.message+ : "Failed to read the make methods"+ },+ { status: 500 }+ );+ }+ const childMethodFor = (+ childItem: AssemblyPushItemRow,+ childMade: boolean+ ) =>+ childMade+ ? methodByItemId.get(childItem.id)+ : childItem.defaultMethodType === "Make to Order"+ ? (madePartMethodByItemId.get(childItem.id) ??+ methodByItemId.get(childItem.id))+ : null;++ // Not written: a change notice's Draft, or a released revision under+ // `enforce`. Rechecked here; the plan only listed them.+ const refusalByItemId = await loadMethodWriteRefusals(+ client,+ companyId,+ plan.methods.flatMap((planned) => {+ const parentItem = itemByReadableId.get(planned.parentPartNumber);+ const method = parentItem ? methodByItemId.get(parentItem.id) : undefined;+ return parentItem && method+ ? [+ {+ itemId: parentItem.id,+ method,+ revisionStatus: parentItem.revisionStatus+ }+ ]+ : [];+ })+ );++ // An Active method is written through a Draft, made before ownership is read:+ // ownership is keyed by method id, so a later Draft's lines would read as manual.+ const targetMethodByItemId = new Map<string, string>();+ const methodErrorByItemId = new Map<string, string>();+ const activeMethodIdByItemId = new Map<string, string>();+ for (const planned of plan.methods) {+ const parentItem = itemByReadableId.get(planned.parentPartNumber);+ const method = parentItem ? methodByItemId.get(parentItem.id) : undefined;+ if (parentItem && method?.status === "Active") {+ activeMethodIdByItemId.set(parentItem.id, method.id);+ }+ }+ let reusableDraftByItemId: Awaited<ReturnType<typeof loadReusableDrafts>>;+ try {+ reusableDraftByItemId = await loadReusableDrafts(+ client,+ serviceRole,+ companyId,+ activeMethodIdByItemId+ );+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error ? error.message : "Failed to read the Drafts"+ },+ { status: 500 }+ );+ }+ // An Active method whose Onshape lines already match gets no Draft. The+ // check pairs lines as the write loop does.+ let activeOwnership: Awaited<ReturnType<typeof loadMethodLineOwnership>>;+ try {+ activeOwnership = await loadMethodLineOwnership(+ client,+ serviceRole,+ companyId,+ [...activeMethodIdByItemId.entries()]+ .filter(([itemId]) => !reusableDraftByItemId.has(itemId))+ .map(([, methodId]) => methodId)+ );+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error+ ? error.message+ : "Failed to read the existing BOM lines"+ },+ { status: 500 }+ );+ }+ const linesWouldChange = (+ planned: (typeof plan.methods)[number],+ methodId: string+ ) => {+ const reusable = new Map<string, MappedLineRow[]>();+ for (const row of activeOwnership.mappedRows.get(methodId) ?? []) {+ const queue = reusable.get(row.itemId) ?? [];+ queue.push(row);+ reusable.set(row.itemId, queue);+ }+ let order = 0;+ for (const write of planned.writes) {+ if (excluded.has(write.partNumber)) continue;+ const childItem = itemByReadableId.get(write.partNumber);+ if (!childItem || !bomLineItemType(childItem)) continue;+ const childMethod = childMethodFor(+ childItem,+ isAssemblyByPartNumber.get(write.partNumber) === true+ );+ const reuse = reusable.get(childItem.id)?.shift();+ if (!reuse) return true;+ if (+ reuse.quantity !== write.quantity ||+ reuse.order !== order ||+ reuse.materialMakeMethodId !== (childMethod?.id ?? null)+ ) {+ return true;+ }+ order += 1;+ }+ // A leftover line would be removed.+ return [...reusable.values()].some((queue) => queue.length > 0);+ };+ const unchangedItemIds = new Set<string>();++ for (const planned of plan.methods) {+ const parentItem = itemByReadableId.get(planned.parentPartNumber);+ if (!parentItem) continue;+ if (+ targetMethodByItemId.has(parentItem.id) ||+ unchangedItemIds.has(parentItem.id)+ ) {+ continue;+ }+ const method = methodByItemId.get(parentItem.id);+ if (!method) continue; // reported in the write loop+ if (method.status !== "Active") {+ if (!refusalByItemId.has(parentItem.id)) {+ targetMethodByItemId.set(parentItem.id, method.id);+ }+ continue;+ }+ if (+ !reusableDraftByItemId.has(parentItem.id) &&+ !linesWouldChange(planned, method.id)+ ) {+ unchangedItemIds.add(parentItem.id);+ continue;+ }+ // Checked before a Draft is made, so a refusal leaves no Draft behind.+ if (refusalByItemId.has(parentItem.id)) continue;+ const draft = await ensureDraftMakeMethod(client, ctx.asSystem.pg, {+ itemId: parentItem.id,+ activeMethodId: method.id,+ companyId,+ userId,+ reusableDraft: reusableDraftByItemId.get(parentItem.id) ?? null+ });+ if (!draft.ok) {+ methodErrorByItemId.set(parentItem.id, draft.error);+ continue;+ }+ targetMethodByItemId.set(parentItem.id, draft.id);+ if (draft.created) {+ summary.draftVersionsCreated.push(+ draft.version === null+ ? planned.parentPartNumber+ : `${planned.parentPartNumber} (version ${draft.version})`+ );+ }+ }++ // A failed read must stop the writes, or every Onshape line is duplicated.+ let ownership: Awaited<ReturnType<typeof loadMethodLineOwnership>>;+ try {+ ownership = await loadMethodLineOwnership(client, serviceRole, companyId, [+ ...new Set([+ ...[...methodByItemId.values()].map((method) => method.id),+ ...targetMethodByItemId.values()+ ])+ ]);+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error+ ? error.message+ : "Failed to read the existing BOM lines"+ },+ { status: 500 }+ );+ }++ for (const planned of plan.methods) {+ const parentLabel = planned.parentPartNumber;+ const parentItem = itemByReadableId.get(planned.parentPartNumber);+ if (!parentItem) continue;++ const method = methodByItemId.get(parentItem.id);+ if (!method) {+ summary.errors.push(`${parentLabel}: no make method found`);+ continue;+ }+ if (unchangedItemIds.has(parentItem.id)) {+ summary.linesUnchanged += planned.writes.filter(+ (write) => !excluded.has(write.partNumber)+ ).length;+ continue;+ }+ const refusal = refusalByItemId.get(parentItem.id);+ if (refusal) {+ summary.skipped.push(`${parentLabel}: ${refusal}`);+ continue;+ }+ const methodId = targetMethodByItemId.get(parentItem.id);+ if (!methodId) {+ summary.errors.push(+ `${parentLabel}: ${methodErrorByItemId.get(parentItem.id) ?? "no make method to write to"}`+ );+ continue;+ }++ // Owned lines are updated in place so Carbon's columns (operation, scrap,+ // tags, kit, customFields) survive; FIFO per item keeps a repeated component's lines.+ const reusableByItemId = new Map<string, MappedLineRow[]>();+ for (const row of ownership.mappedRows.get(methodId) ?? []) {+ const queue = reusableByItemId.get(row.itemId) ?? [];+ queue.push(row);+ reusableByItemId.set(row.itemId, queue);+ }+ // Manual lines pair by part number in line order, as `pairManualLines` does at plan.+ const manualByReadableId = new Map<string, ManualLineRow[]>();+ for (const row of ownership.manualRows.get(methodId) ?? []) {+ const queue = manualByReadableId.get(row.readableId) ?? [];+ queue.push(row);+ manualByReadableId.set(row.readableId, queue);+ }+ // Mapping rows this method still owns; any other is cleared as an orphan.+ const liveMappingIds: string[] = [];+ const pendingInserts: Array<{+ row: OwnedMethodLine["row"];+ metadata: Record<string, unknown>;+ }> = [];++ summary.methodsTouched += 1;++ let order = 0;+ for (const write of planned.writes) {+ if (excluded.has(write.partNumber)) continue;+ const childItem = itemByReadableId.get(write.partNumber);+ if (!childItem) continue;++ const itemType = bomLineItemType(childItem);+ if (!itemType) {+ summary.errors.push(+ `${parentLabel} → ${write.partNumber}: a ${childItem.type ?? "Part"} cannot be a BOM line`+ );+ continue;+ }++ const childMade = isAssemblyByPartNumber.get(write.partNumber) === true;+ const childMethod = childMethodFor(childItem, childMade);+ const lineSyncedAt = datetime.timestamp();+ const lineMetadata = {+ makeMethodId: methodId,+ documentId,+ elementId,+ partNumber: write.partNumber,+ index: write.index+ };++ // Onshape owns quantity, order and the child-method pointer; method type,+ // sourcing and unit come from the item, at insert only.+ const reuse = reusableByItemId.get(childItem.id)?.shift();+ if (reuse) {+ // Unchanged lines are not written, so the audit log shows no edit.+ const unchanged =+ reuse.quantity === write.quantity &&+ reuse.order === order &&+ reuse.materialMakeMethodId === (childMethod?.id ?? null);+ if (unchanged) {+ liveMappingIds.push(reuse.mappingId);+ order += 1;+ summary.linesUnchanged += 1;+ continue;+ }+ const updated = await client+ .from("methodMaterial")+ .update({+ quantity: write.quantity,+ materialMakeMethodId: childMethod?.id ?? null,+ order,+ updatedBy: userId,+ updatedAt: lineSyncedAt+ })+ .eq("id", reuse.lineId)+ .eq("companyId", companyId);+ if (updated.error) {+ summary.errors.push(+ `${parentLabel} → ${write.partNumber}: ${updated.error.message}`+ );+ // Keep its ownership row, or the next push reads it as manual.+ liveMappingIds.push(reuse.mappingId);+ order += 1;+ continue;+ }+ const remapped = await serviceRole+ .from("externalIntegrationMapping")+ .update({+ metadata: lineMetadata,+ lastSyncedAt: lineSyncedAt,+ updatedBy: userId,+ updatedAt: lineSyncedAt+ })+ .eq("id", reuse.mappingId)+ .eq("companyId", companyId);+ if (remapped.error) {+ summary.errors.push(+ `${parentLabel} → ${write.partNumber}: line updated but its Onshape link was not refreshed (${remapped.error.message})`+ );+ }+ liveMappingIds.push(reuse.mappingId);+ order += 1;+ summary.linesWritten += 1;+ continue;+ }++ // Same item type only: a Material sharing a Part's number is a different item.+ const queue = manualByReadableId.get(write.partNumber);+ const claimIndex =+ queue?.findIndex((row) => !row.itemType || row.itemType === itemType) ??+ -1;+ const claim =+ queue && claimIndex >= 0 ? queue.splice(claimIndex, 1)[0] : undefined;+ if (claim) {+ const claimed = await claimManualMethodLine(db, {+ companyId,+ userId,+ lineId: claim.lineId,+ update: {+ itemId: childItem.id,+ quantity: write.quantity,+ order,+ materialMakeMethodId: childMethod?.id ?? null+ },+ metadata: lineMetadata+ });+ if (claimed.error !== null) {+ summary.errors.push(+ `${parentLabel} → ${write.partNumber}: the line added by hand was not taken over (${claimed.error})`+ );+ continue;+ }+ liveMappingIds.push(claimed.mappingId);+ order += 1;+ summary.linesWritten += 1;+ summary.linesTakenOver += 1;+ continue;+ }++ pendingInserts.push({+ row: {+ itemId: childItem.id,+ quantity: write.quantity,+ makeMethodId: methodId,+ materialMakeMethodId: childMethod?.id ?? null,+ methodType:+ (childItem.defaultMethodType as OwnedMethodLine["row"]["methodType"]) ??+ (childMade ? "Make to Order" : "Pull from Inventory"),+ sourcingType:+ (childItem.sourcingType as OwnedMethodLine["row"]["sourcingType"]) ??+ "Specified",+ order,+ itemType,+ unitOfMeasureCode: childItem.unitOfMeasureCode ?? fallbackUnit+ },+ metadata: lineMetadata+ });+ order += 1;+ }++ if (pendingInserts.length > 0) {+ const written = await insertOwnedMethodLines(db, {+ companyId,+ userId,+ lines: pendingInserts.map((pending) => ({+ row: pending.row,+ metadata: pending.metadata+ }))+ });+ if (written.error !== null) {+ summary.errors.push(+ `${parentLabel}: ${pendingInserts.length} new lines were not written (${written.error})`+ );+ } else {+ summary.linesWritten += pendingInserts.length;+ liveMappingIds.push(...written.mappingIds);+ }+ }++ // Anything still queued is a component the Onshape BOM no longer has.+ const removed = [...reusableByItemId.values()].flat();+ if (removed.length > 0) {+ for (const batch of chunkFilterValues(removed.map((row) => row.lineId))) {+ const removedLines = await client+ .from("methodMaterial")+ .delete()+ .eq("companyId", companyId)+ .in("id", batch);+ if (removedLines.error) {+ summary.errors.push(+ `${parentLabel}: could not remove the lines Onshape no longer lists (${removedLines.error.message})`+ );+ const failed = new Set(batch);+ for (const row of removed) {+ if (failed.has(row.lineId)) liveMappingIds.push(row.mappingId);+ }+ }+ }+ }++ // Orphans are filtered here: a `not in` filter puts every live id in the URL.+ const methodMappings = await serviceRole+ .from("externalIntegrationMapping")+ .select("id")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "methodMaterial")+ .eq("metadata->>makeMethodId", methodId);+ if (methodMappings.error) {+ summary.errors.push(+ `${parentLabel}: could not read the existing line ownership records (${methodMappings.error.message})`+ );+ } else {+ const live = new Set(liveMappingIds);+ const orphaned = (methodMappings.data ?? [])+ .map((row) => row.id)+ .filter((id) => !live.has(id));+ for (const batch of chunkFilterValues(orphaned)) {+ const clearedMappings = await serviceRole+ .from("externalIntegrationMapping")+ .delete()+ .eq("companyId", companyId)+ .in("id", batch);+ if (clearedMappings.error) {+ summary.errors.push(+ `${parentLabel}: could not clear orphaned line ownership records (${clearedMappings.error.message})`+ );+ }+ }+ }+ }++ // A root released in Carbon keeps the link and model its release gave it.+ if (root.released) {+ summary.skipped.push(+ `${root.partNumber}: released in Carbon as Rev ${root.released.revision}; its fields, link and model stay as its release left them`+ );+ const childLinkProblems = await linkChildParts(client, serviceRole, {+ companyId,+ userId,+ nodes: allNodes,+ itemByReadableId+ });+ summary.errors.push(...childLinkProblems);+ return panelReply(+ { summary },+ { headers: { "Cache-Control": "no-store" } }+ );+ }+ const pushedAt = datetime.timestamp();+ const assemblyExternalId = externalIdForAssembly(+ documentId,+ elementId,+ configuration+ );+ const assemblyMapping = await swapItemMapping(db, {+ companyId,+ userId,+ itemId: rootItem.id,+ externalId: assemblyExternalId,+ metadata: {+ documentId,+ elementId,+ configuration,+ wv,+ wvId,+ kind: "assembly",+ partNumber: root.partNumber,+ name: root.name,+ pushedBy: userId,+ pushedAt,+ planId+ }+ });+ if (assemblyMapping.error !== null) {+ summary.errors.push(+ `${root.partNumber}: pushed, but not linked to Onshape (${assemblyMapping.error}); the next push will not recognise it`+ );+ }++ const childLinkProblems = await linkChildParts(client, serviceRole, {+ companyId,+ userId,+ nodes: allNodes,+ itemByReadableId+ });+ summary.errors.push(...childLinkProblems);++ try {+ await trigger(+ "onshape-panel-sync",+ {+ companyId,+ userId,+ itemId: rootItem.id,+ documentId,+ wvm: wv,+ wvmId: wvId,+ elementId,+ elementKind: "assembly",+ ...(configuration ? { configuration } : {}),+ assetBaseName: root.partNumber+ },+ { id: `${planId}:${rootItem.id}:${elementId}` }+ );+ } catch {+ summary.errors.push(+ `${root.partNumber}: pushed, but the model export couldn't be queued. Push again to retry the export.`+ );+ }++ return panelReply({ summary }, { headers: { "Cache-Control": "no-store" } });+ }++ async function linkChildParts(+ client: SupabaseClient<Database>,+ serviceRole: SupabaseClient<Database>,+ input: {+ companyId: string;+ userId: string;+ nodes: OnshapeBomNode[];+ itemByReadableId: Map<string, { id: string; readableId: string }>;+ }+ ) {+ // Links only where neither the item nor the source is linked: a part push owns that link.+ const candidates: Array<{+ itemId: string;+ externalId: string;+ partNumber: string;+ source: NonNullable<OnshapeBomNode["itemSource"]>;+ }> = [];+ const seen = new Set<string>();+ for (const node of input.nodes) {+ const source = node.itemSource;+ if (!node.partNumber) continue;+ const externalId = externalIdForBomLine(source);+ if (!source || !externalId) continue;+ const item = input.itemByReadableId.get(node.partNumber);+ if (!item || seen.has(item.id)) continue;+ seen.add(item.id);+ candidates.push({+ itemId: item.id,+ externalId,+ partNumber: node.partNumber,+ source+ });+ }+ if (candidates.length === 0) return [];++ // One Onshape source claimed by two items is reported, not guessed at.+ const itemsByExternalId = new Map<string, Set<string>>();+ for (const candidate of candidates) {+ const items = itemsByExternalId.get(candidate.externalId) ?? new Set();+ items.add(candidate.itemId);+ itemsByExternalId.set(candidate.externalId, items);+ }+ const problems: string[] = [];+ const ambiguous = new Set(+ [...itemsByExternalId.entries()]+ .filter(([, items]) => items.size > 1)+ .map(([externalId]) => externalId)+ );+ for (const externalId of ambiguous) {+ const numbers = candidates+ .filter((candidate) => candidate.externalId === externalId)+ .map((candidate) => candidate.partNumber);+ problems.push(+ `${numbers.join(" and ")} come from the same Onshape part, so neither was linked to it`+ );+ }+ const unambiguous = candidates.filter(+ (candidate) => !ambiguous.has(candidate.externalId)+ );+ if (unambiguous.length === 0) return problems;++ const [byEntity, byExternal] = await Promise.all([+ selectInBatches(+ unambiguous.map((candidate) => candidate.itemId),+ (batch) =>+ serviceRole+ .from("externalIntegrationMapping")+ .select("entityId")+ .eq("companyId", input.companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "item")+ .in("entityId", batch)+ ),+ selectInBatches(+ unambiguous.map((candidate) => candidate.externalId),+ (batch) =>+ serviceRole+ .from("externalIntegrationMapping")+ .select("externalId")+ .eq("companyId", input.companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "item")+ .in("externalId", batch)+ )+ ]);+ // A failed read is not "no links": that would claim links a part push owns.+ if (byEntity.error || byExternal.error) {+ return [+ ...problems,+ `child parts were not linked to Onshape: ${+ (byEntity.error ?? byExternal.error)?.message ?? "lookup failed"+ }`+ ];+ }+ const linkedItemIds = new Set(+ (byEntity.data ?? []).map((row) => row.entityId)+ );+ const usedExternalIds = new Set(+ (byExternal.data ?? []).map((row) => row.externalId)+ );++ const linkedAt = datetime.timestamp();+ const rows = unambiguous+ .filter(+ (candidate) =>+ !linkedItemIds.has(candidate.itemId) &&+ !usedExternalIds.has(candidate.externalId)+ )+ .map((candidate) => ({+ entityType: "item" as const,+ entityId: candidate.itemId,+ integration: ONSHAPE_V2_INTEGRATION_ID,+ externalId: candidate.externalId,+ metadata: {+ documentId: candidate.source.documentId,+ elementId: candidate.source.elementId,+ partId: candidate.source.partId ?? null,+ configuration: normalizeConfiguration(candidate.source.configuration),+ kind: candidate.source.partId ? "part" : "assembly",+ partNumber: candidate.partNumber,+ viaAssemblyPush: true,+ pushedBy: input.userId,+ pushedAt: linkedAt+ },+ lastSyncedAt: linkedAt,+ companyId: input.companyId,+ createdBy: input.userId+ }));+ if (rows.length === 0) return problems;++ // The bulk insert is all-or-nothing; on refusal retry row by row, so one+ // conflicting row (a concurrent push's link) does not block the rest.+ const linked = await client.from("externalIntegrationMapping").insert(rows);+ if (!linked.error) return problems;++ const failed: string[] = [];+ for (const row of rows) {+ const single = await client.from("externalIntegrationMapping").insert(row);+ if (single.error) failed.push(row.metadata.partNumber);+ }+ if (failed.length > 0) {+ problems.push(+ `${failed.length} part${failed.length === 1 ? "" : "s"} could not be linked to Onshape (${failed+ .slice(0, 5)+ .join(", ")}${failed.length > 5 ? ", …" : ""}); push again to retry`+ );+ }+ return problems;+ }++ export const onshapeReleasePushInput = z.object({+ planId: z.string().min(1),+ edits: z.record(z.string(), itemEditSchema).default({}),+ changeNotice: z+ .object({+ name: z.string().optional(),+ description: z.string().nullable().optional()+ })+ .nullable()+ .optional(),+ makeDefault: z.boolean().optional(),+ createChangeNotice: z.boolean().optional()+ });++ type ReleasePushSummary = {+ releaseName: string | null;+ revisionsCreated: number;+ itemsCreated: number;+ /** BOM children the push created; not on the change notice. */+ childrenCreated: number;+ drawingsQueued: number;+ drawingsOnly: boolean;+ reused: number;+ linesWritten: number;+ methodsTouched: number;+ defaultsUpdated: number;+ changeNotice: string | null;+ alreadyPushed: boolean;+ skipped: string[];+ errors: string[];+ };++ type ReleasePushItemRow = {+ id: string;+ readableId: string;+ revision: string;+ active?: boolean | null;+ name: string;+ type: string | null;+ defaultMethodType: string | null;+ sourcingType: string | null;+ unitOfMeasureCode: string | null;+ };++ type CreatedEntry = {+ partNumber: string;+ revision: string;+ itemId: string;+ baseItemId: string | null;+ };++ function partInsert(+ proposed: ProposedItem,+ companyId: string,+ userId: string,+ customFields: PlanCustomField[] | undefined+ ) {+ const values = mappedFieldValues(customFields ?? [], true).values;+ return {+ id: proposed.readableId,+ name: proposed.name,+ description: proposed.description ?? undefined,+ revision: proposed.revision,+ replenishmentSystem: proposed.replenishmentSystem,+ defaultMethodType: proposed.defaultMethodType,+ itemTrackingType: proposed.itemTrackingType,+ unitOfMeasureCode: proposed.unitOfMeasureCode,+ ...(Object.keys(values).length > 0 ? { customFields: values as Json } : {}),+ companyId,+ createdBy: userId+ } as any;+ }++ /** Apply a reviewed release plan; Carbon's state at apply time outranks the plan. */+ export async function pushOnshapeRelease(+ ctx: ServiceContext,+ input: z.infer<typeof onshapeReleasePushInput>+ ): Promise<PanelReply> {+ const client = ctx.asCaller.supabase;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const { planId, changeNotice: changeNoticeEdit } = input;+ const edits = input.edits as Record<string, ItemEdit>;++ const stored = await peekPanelPlan(planId, { companyId, userId });+ if (!stored) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }+ if (stored.plan.kind !== "release") {+ return panelReply(+ { error: "This review is not a release push" },+ { status: 400 }+ );+ }+ const plan = stored.plan as StoredReleasePlan;+ const makeDefault = input.makeDefault ?? plan.makeDefault;+ // Unset: a notice whenever this push creates something.+ const createChangeNoticeChoice = input.createChangeNotice;++ const merged = mergeEditsForCreates(+ [+ ...plan.items+ .filter((item) => item.action === "create" && item.proposed)+ .map((item) => ({+ key: item.partNumber,+ proposed: item.proposed as ProposedItem+ })),+ ...plan.children+ .filter((child) => child.action === "create" && child.proposed)+ .map((child) => ({+ key: child.partNumber,+ proposed: child.proposed as ProposedItem+ }))+ ],+ edits,+ plan.options+ );+ // A row that vanished since review becomes a create, so even a re-push needs notice values.+ const changeNoticeMerge = mergeChangeNoticeEdit(+ plan.changeNotice ?? {+ name: plan.releaseName ?? `Onshape release ${plan.releaseId}`,+ description: null+ },+ changeNoticeEdit+ );+ if (!changeNoticeMerge.ok) {+ return panelReply(+ {+ error: "Some edits are not valid",+ fieldErrors: [+ ...merged.errors,+ { key: "changeNotice", errors: changeNoticeMerge.errors }+ ]+ },+ { status: 422 }+ );+ }+ if (merged.errors.length > 0) {+ return panelReply(+ { error: "Some edits are not valid", fieldErrors: merged.errors },+ { status: 422 }+ );+ }+ const changeNoticeValues = changeNoticeMerge.changeNotice;++ const modelItems = plan.items.filter(isModelReleaseItem);+ const drawingItems = plan.items.filter((item) => !isModelReleaseItem(item));++ const summary: ReleasePushSummary = {+ releaseName: plan.releaseName,+ revisionsCreated: 0,+ itemsCreated: 0,+ childrenCreated: 0,+ drawingsQueued: 0,+ drawingsOnly: modelItems.length === 0,+ reused: 0,+ linesWritten: 0,+ methodsTouched: 0,+ defaultsUpdated: 0,+ changeNotice: null,+ alreadyPushed: false,+ skipped: [],+ errors: []+ };++ // A part number that is both a release item and a BOM child uses the release item's plan.+ type PlannedRow = MappedRowPlan & {+ current?: ItemFieldSnapshot | null;+ changes?: OwnedFieldChange[];+ };+ const plannedByPartNumber = new Map<string, PlannedRow>();+ for (const child of plan.children) {+ if (child.current) plannedByPartNumber.set(child.partNumber, child);+ }+ for (const item of plan.items) {+ if (item.current) plannedByPartNumber.set(item.partNumber, item);+ }+ // Written at insert. A revision shares its base's `part` row: no create-time values.+ const createdFieldsByPartNumber = new Map<string, PlanCustomField[]>();+ for (const row of [...plan.children, ...plan.items]) {+ if (row.action === "create" && row.customFields) {+ createdFieldsByPartNumber.set(row.partNumber, row.customFields);+ }+ }+ const fieldEditsApplied = new Set<string>();+ /** Writes the plan's values to an item the push did not create; updates `row` in place. */+ const applyItemFieldEdit = async (+ partNumber: string,+ row: ReleasePushItemRow+ ) => {+ if (fieldEditsApplied.has(partNumber)) return;+ const planned = plannedByPartNumber.get(partNumber);+ if (!planned?.current) return;+ fieldEditsApplied.add(partNumber);+ const applied = await applyExistingItemFields(client, db, {+ itemId: row.id,+ companyId,+ userId,+ current: planned.current,+ target: planned.target,+ edit: edits[partNumber],+ descriptions: planned.changes+ });+ if (applied.error) {+ summary.errors.push(`${partNumber}: ${applied.error}`);+ return;+ }+ if (applied.values) {+ row.defaultMethodType = applied.values.defaultMethodType;+ row.sourcingType = applied.values.sourcingType ?? row.sourcingType;+ row.unitOfMeasureCode =+ applied.values.unitOfMeasureCode ?? row.unitOfMeasureCode;+ }+ const values = mappedFieldValues(planned.customFields ?? [], false);+ if (values.fieldIds.size === 0) return;+ const held = await client+ .from("part")+ .select("customFields")+ .eq("id", partNumber)+ .eq("companyId", companyId)+ .maybeSingle();+ if (held.error) {+ summary.errors.push(+ `${partNumber}: failed to read custom fields (${held.error.message})`+ );+ return;+ }+ const updated = await client+ .from("part")+ .update({+ customFields: mergeCustomFieldValues(+ held.data?.customFields,+ values.values,+ values.fieldIds+ ) as Json,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .eq("id", partNumber)+ .eq("companyId", companyId);+ if (updated.error) {+ summary.errors.push(+ `${partNumber}: failed to write custom fields (${updated.error.message})`+ );+ }+ };+ /** The values `upsertPart` does not take: MPN and Sourcing. */+ const writeCreatedExtras = async (+ label: string,+ itemId: string,+ proposed: ProposedItem+ ) => {+ const extras = createdItemExtras(proposed);+ if (Object.keys(extras).length === 0) return;+ const error = await applyItemFieldWrites(client, db, {+ itemId,+ companyId,+ userId,+ changed: extras+ });+ if (error) {+ summary.errors.push(+ `${label}: created, but its mapped fields were not written (${error})`+ );+ }+ };++ // Every revision of every part number, re-read: the plan may be minutes old.+ const partNumbers = [+ ...new Set([+ ...modelItems.map((item) => item.partNumber),+ ...Object.values(plan.bomLinesByElementId)+ .flatMap((lines) => (lines ?? []).map((line) => line.partNumber))+ .filter((partNumber): partNumber is string => !!partNumber)+ ])+ ];+ const existing = await selectInBatches(partNumbers, (batch) =>+ client+ .from("item")+ .select(+ "id, readableId, revision, active, name, type, defaultMethodType, sourcingType, unitOfMeasureCode"+ )+ .eq("companyId", companyId)+ .in("readableId", batch)+ .order("revision")+ );+ if (existing.error) {+ return panelReply(+ { error: "Failed to read Carbon items" },+ { status: 500 }+ );+ }+ const byReadable = new Map<string, ReleasePushItemRow[]>();+ const rememberRow = (row: ReleasePushItemRow) => {+ const list = byReadable.get(row.readableId) ?? [];+ list.push(row);+ byReadable.set(row.readableId, list);+ };+ for (const row of (existing.data ?? []) as ReleasePushItemRow[])+ rememberRow(row);+ const letterRowFor = (partNumber: string, revision: string) =>+ (byReadable.get(partNumber) ?? []).find((row) => row.revision === revision);++ const created: CreatedEntry[] = [];+ const revisionItemByPartNumber = new Map<string, ReleasePushItemRow>();++ // The base the plan pinned is honoured while its row exists.+ type Decision =+ | { item: ReleasePlanItem; kind: "reuse"; row: ReleasePushItemRow }+ | { item: ReleasePlanItem; kind: "revision"; base: ReleasePushItemRow }+ | { item: ReleasePlanItem; kind: "create"; proposed: ProposedItem };+ const decisions: Decision[] = modelItems.map((item): Decision => {+ const existingLetter = letterRowFor(item.partNumber, item.revision);+ if (existingLetter) return { item, kind: "reuse", row: existingLetter };+ const bases = byReadable.get(item.partNumber) ?? [];+ const base =+ bases.find((row) => row.id === item.baseItemId) ??+ pickRevisionBase(bases, item.revision);+ if (base) return { item, kind: "revision", base };+ return {+ item,+ kind: "create",+ proposed:+ merged.items.get(item.partNumber) ??+ proposeItem(+ { partNumber: item.partNumber, name: null, revision: item.revision },+ plan.options+ )+ };+ });++ // An assembly whose BOM was not read at review is not minted: a revision would+ // carry the base's Onshape lines unmapped, and a new item would have no BOM.+ for (const decision of decisions) {+ if (+ decision.kind !== "reuse" &&+ decision.item.elementType === 1 &&+ plan.bomLinesByElementId[releaseBomKey(decision.item)] === null+ ) {+ summary.errors.push(+ `${decision.item.partNumber} Rev ${decision.item.revision}: the BOM was not read at review — review and push again`+ );+ }+ }+ const applicable = decisions.filter(+ (decision) =>+ decision.kind === "reuse" ||+ decision.item.elementType !== 1 ||+ plan.bomLinesByElementId[releaseBomKey(decision.item)] !== null+ );+ decisions.length = 0;+ decisions.push(...applicable);++ const baseIds = [+ ...new Set(+ decisions.flatMap((decision) =>+ decision.kind === "revision" ? [decision.base.id] : []+ )+ )+ ];+ type FullItem = NonNullable<Awaited<ReturnType<typeof getItem>>["data"]>;+ const fullBaseById = new Map<string, FullItem>();+ const bases = await selectInBatches(baseIds, (batch) =>+ client.from("item").select("*").eq("companyId", companyId).in("id", batch)+ );+ // A failed read would look like "no base" and skip revisions: a partial push.+ if (bases.error) {+ return panelReply(+ { error: "Failed to read the base revisions" },+ { status: 500 }+ );+ }+ for (const row of bases.data as FullItem[]) {+ fullBaseById.set(row.id, row);+ }++ // `createRevision` copies the base's lines without mapping rows. Key the base's+ // Onshape lines now: after the revision exists, a failed read leaves manual-looking copies.+ const assemblyBaseIds = [+ ...new Set(+ decisions.flatMap((decision) =>+ decision.kind === "revision" && decision.item.elementType === 1+ ? [decision.base.id]+ : []+ )+ )+ ];+ const lineKey = (line: { itemId: string; order: number; quantity: number }) =>+ `${line.itemId}:${line.order}:${line.quantity}`;+ let baseMethodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;+ try {+ baseMethodByItemId = await loadActiveMakeMethods(+ client,+ companyId,+ assemblyBaseIds+ );+ } catch (error) {+ return panelReply(+ {+ error:+ error instanceof Error+ ? error.message+ : "Failed to read the base revisions' make methods"+ },+ { status: 500 }+ );+ }+ const serviceRole = getCarbonServiceRole();+ const db = ctx.asSystem.pg;+ const copiedKeysByBaseMethodId = new Map<string, Set<string>>();+ const baseMethodIds = [+ ...new Set([...baseMethodByItemId.values()].map((method) => method.id))+ ];+ if (baseMethodIds.length > 0) {+ const baseMapped = await selectInBatches(baseMethodIds, (batch) =>+ serviceRole+ .from("externalIntegrationMapping")+ .select("entityId")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "methodMaterial")+ .in("metadata->>makeMethodId", batch)+ );+ const baseLines = baseMapped.error+ ? null+ : await selectInBatches(+ baseMapped.data.map((mapping) => mapping.entityId),+ (batch) =>+ client+ .from("methodMaterial")+ .select("makeMethodId, itemId, order, quantity")+ .eq("companyId", companyId)+ .in("id", batch)+ );+ const baseReadError = baseMapped.error ?? baseLines?.error;+ if (baseReadError || !baseLines) {+ return panelReply(+ {+ error: `Couldn't identify the Onshape lines on the base revisions (${+ baseReadError?.message ?? "read failed"+ }); nothing was written. Try again.`+ },+ { status: 500 }+ );+ }+ for (const line of baseLines.data) {+ const keys =+ copiedKeysByBaseMethodId.get(line.makeMethodId) ?? new Set<string>();+ keys.add(lineKey(line));+ copiedKeysByBaseMethodId.set(line.makeMethodId, keys);+ }+ }++ // A reused revision held by a change notice whose engineering content is+ // locked (Implementation onward, or awaiting approval) takes no writes: not+ // its fields, not its BOM. A method's changeOrderId is cleared at release, so+ // a set one means a notice holds the item now.+ const lockedByItemId = new Map<string, string>();+ const reusedItemIds = decisions.flatMap((decision) =>+ decision.kind === "reuse" ? [decision.row.id] : []+ );+ if (reusedItemIds.length > 0) {+ const held = await selectInBatches(reusedItemIds, (batch) =>+ client+ .from("makeMethod")+ .select("itemId, changeOrderId, changeOrder(changeOrderId)")+ .eq("companyId", companyId)+ .in("itemId", batch)+ .not("changeOrderId", "is", null)+ );+ if (held.error) {+ return panelReply(+ {+ error: `Couldn't check the change notices that hold the existing revisions (${held.error.message}); nothing was written. Try again.`+ },+ { status: 500 }+ );+ }+ const noticeIds = [+ ...new Set(+ held.data.flatMap((method) =>+ method.changeOrderId ? [method.changeOrderId] : []+ )+ )+ ];+ // One check per notice; a release's revisions share one or two.+ const lockByNoticeId = new Map(+ await Promise.all(+ noticeIds.map(+ async (changeNoticeId) =>+ [+ changeNoticeId,+ (+ await requireChangeNoticeEditable(client, {+ changeNoticeId,+ companyId,+ scope: "engineering"+ })+ )?.error.message ?? null+ ] as const+ )+ )+ );+ for (const method of held.data) {+ const lock = method.changeOrderId+ ? lockByNoticeId.get(method.changeOrderId)+ : null;+ if (!lock || lockedByItemId.has(method.itemId)) continue;+ const notice = method.changeOrder?.changeOrderId;+ lockedByItemId.set(+ method.itemId,+ notice ? `change notice ${notice}: ${lock}` : lock+ );+ }+ }++ // The notice exists before the first item write, so each item is staged as it+ // is written. A second document of the same release reuses the open notice.+ // Read before the take: a failed read must not open a second notice.+ const needsNotice =+ (createChangeNoticeChoice ?? true) &&+ decisions.some((decision) => decision.kind !== "reuse");+ const openNotice = needsNotice+ ? await findOpenReleaseNotice(client, companyId, plan.releaseId)+ : { data: null, error: null };+ if (openNotice.error !== null) {+ return panelReply(+ {+ error: `${openNotice.error}, so it can't tell which change notice to add to; nothing was written. Try again.`+ },+ { status: 500 }+ );+ }++ // Taken after the reads the writes depend on, so a failed read keeps the review;+ // one-shot, so a concurrent apply of the same review finds nothing.+ if (!(await takePanelPlan(planId, { companyId, userId }))) {+ return panelReply(+ { error: "This review has expired — review again" },+ { status: 410 }+ );+ }++ let changeNotice: { id: string; changeNoticeId: string } | null = null;+ let noticeReused = false;+ let noticeSortOrder = 0;+ if (openNotice.data) {+ changeNotice = {+ id: openNotice.data.id,+ changeNoticeId: openNotice.data.changeNoticeId+ };+ noticeReused = true;+ noticeSortOrder = openNotice.data.affectedCount;+ summary.changeNotice = openNotice.data.changeNoticeId;+ } else if (needsNotice) {+ const description = changeNoticeDescriptionJson(+ changeNoticeValues.description+ );+ const inserted = await insertChangeNotice(client, {+ companyId,+ createdBy: userId,+ name: changeNoticeValues.name,+ // Tiptap JSON; omitted, not nulled, when empty.+ ...(description ? { description: description as Json } : {}),+ openDate: datetime+ .today(await sharedService.getCompanyTimeZone(client, companyId))+ .toString()+ });+ if (inserted.error || !inserted.data) {+ return panelReply(+ {+ error: `Couldn't create the change notice (${+ inserted.error?.message ?? "no row returned"+ }); nothing was written. Review and push again.`+ },+ { status: 500 }+ );+ }+ changeNotice = inserted.data;+ summary.changeNotice = inserted.data.changeNoticeId;+ }+ // An item the notice could not take is removed: left in place it is outside+ // change control, and a re-push would reuse it instead of staging it. The+ // service role removes it because the pusher may lack parts_delete.+ const stageInNotice = async (+ label: string,+ itemId: string,+ baseItemId: string | null+ ): Promise<boolean> => {+ if (!changeNotice) return true;+ const staged = await stageChangeNoticeItem(db, {+ changeOrderId: changeNotice.id,+ companyId,+ userId,+ itemId,+ baseItemId,+ sortOrder: noticeSortOrder+ });+ if (!staged.error) {+ noticeSortOrder += 1;+ return true;+ }+ const notice = changeNotice.changeNoticeId;+ const removed = await deleteItem(serviceRole, db, itemId, companyId);+ summary.errors.push(+ removed.error+ ? `${label}: created but not added to change notice ${notice} (${staged.error}), and could not be removed (${removed.error.message}). Delete it in Carbon, then push again.`+ : `${label}: not created, because it could not be added to change notice ${notice} (${staged.error}). Push again.`+ );+ return false;+ };++ for (const decision of decisions) {+ const { item } = decision;+ if (decision.kind === "reuse") {+ summary.reused += 1;+ revisionItemByPartNumber.set(item.partNumber, decision.row);+ const lock = lockedByItemId.get(decision.row.id);+ if (lock) {+ // Also keeps the BOM-child pass from writing its fields.+ fieldEditsApplied.add(item.partNumber);+ summary.skipped.push(+ `${item.partNumber} Rev ${item.revision}: ${lock} Its fields and BOM were left as they are.`+ );+ continue;+ }+ await applyItemFieldEdit(item.partNumber, decision.row);+ continue;+ }++ let row: ReleasePushItemRow | null = null;+ if (decision.kind === "revision") {+ const full = fullBaseById.get(decision.base.id);+ if (!full) {+ summary.errors.push(`${item.partNumber}: failed to read the base item`);+ continue;+ }+ const inserted = await createRevision(client, db, {+ item: full,+ revision: item.revision,+ createdBy: userId,+ active: !changeNotice+ });+ if (inserted.error || !inserted.data) {+ summary.errors.push(+ `${item.partNumber}: ${+ inserted.error?.message ?? "failed to create the revision"+ }`+ );+ continue;+ }+ if (+ !(await stageInNotice(+ `${item.partNumber} Rev ${item.revision}`,+ inserted.data.id,+ decision.base.id+ ))+ ) {+ continue;+ }+ row = {+ id: inserted.data.id,+ readableId: item.partNumber,+ revision: item.revision,+ name: full.name,+ type: full.type,+ defaultMethodType: full.defaultMethodType ?? "Make to Order",+ sourcingType: full.sourcingType ?? null,+ unitOfMeasureCode: full.unitOfMeasureCode ?? "EA"+ };+ created.push({+ partNumber: item.partNumber,+ revision: item.revision,+ itemId: row.id,+ baseItemId: decision.base.id+ });+ summary.revisionsCreated += 1;+ } else {+ // Safe with `upsertPart`'s readback by readableId: no other revision exists.+ const { proposed } = decision;+ const insertedItem = await upsertPart(+ client,+ partInsert(+ proposed,+ companyId,+ userId,+ createdFieldsByPartNumber.get(item.partNumber)+ )+ );+ if (insertedItem.error || !insertedItem.data) {+ summary.errors.push(+ `${item.partNumber}: ${+ insertedItem.error?.message ?? "failed to create the item"+ }`+ );+ continue;+ }+ row = {+ id: insertedItem.data.id as string,+ readableId: item.partNumber,+ revision: item.revision,+ name: proposed.name,+ type: "Part",+ defaultMethodType: proposed.defaultMethodType,+ sourcingType: proposed.sourcingType ?? null,+ unitOfMeasureCode: proposed.unitOfMeasureCode+ };+ await writeCreatedExtras(item.partNumber, row.id, proposed);+ if (+ !(await stageInNotice(+ `${item.partNumber} Rev ${item.revision}`,+ row.id,+ null+ ))+ ) {+ continue;+ }+ created.push({+ partNumber: item.partNumber,+ revision: item.revision,+ itemId: row.id,+ baseItemId: null+ });+ summary.itemsCreated += 1;+ }++ revisionItemByPartNumber.set(item.partNumber, row);+ rememberRow(row);+ await applyItemFieldEdit(item.partNumber, row);+ }++ summary.alreadyPushed = created.length === 0;+ if (changeNotice && !noticeReused && created.length === 0) {+ const dropped = await deleteChangeNotice(+ client,+ db,+ changeNotice.id,+ companyId+ );+ if (dropped.error) {+ summary.errors.push(+ `Change notice ${changeNotice.changeNoticeId} is empty and could not be removed (${dropped.error.message})`+ );+ } else {+ summary.changeNotice = null;+ }+ changeNotice = null;+ }++ // Any BOM read failure skips every BOM write: writing on a partial read+ // duplicates or orphans lines.+ let bomReadFailure: string | null = null;++ const methodByItemId = new Map(baseMethodByItemId);+ try {+ for (const [itemId, method] of await loadActiveMakeMethods(+ client,+ companyId,+ [+ ...[...revisionItemByPartNumber.values()].map((row) => row.id),+ ...created.flatMap((entry) =>+ entry.baseItemId ? [entry.baseItemId] : []+ )+ ]+ )) {+ methodByItemId.set(itemId, method);+ }+ } catch (error) {+ bomReadFailure =+ error instanceof Error ? error.message : "failed to read make methods";+ }++ type BomTarget = {+ item: ReleasePlanItem;+ label: string;+ methodId: string;+ lines: OnshapeBomNode[];+ /** The base method whose Onshape-origin lines the revision copy carries. */+ baseMethodId: string | null;+ };+ const bomTargets: BomTarget[] = [];+ for (const item of bomReadFailure+ ? []+ : modelItems.filter((candidate) => candidate.elementType === 1)) {+ const target = revisionItemByPartNumber.get(item.partNumber);+ if (!target) continue; // creation failed above; error already recorded+ const label = `${item.partNumber} Rev ${item.revision}`;++ const method = methodByItemId.get(target.id);+ if (!method) {+ summary.errors.push(`${label}: no make method found`);+ continue;+ }+ if (method.status === "Active") {+ summary.skipped.push(+ `${label}: make method is released in Carbon, so its BOM was left as it is`+ );+ continue;+ }+ // Reported with its fields above.+ if (lockedByItemId.has(target.id)) continue;++ // null: the review could not read the BOM, so the method is left alone. An+ // empty BOM is [] and is applied.+ const lines = plan.bomLinesByElementId[releaseBomKey(item)];+ if (!lines) {+ summary.skipped.push(+ `${label}: the BOM was not read at review — review and push again`+ );+ continue;+ }++ const createdEntry = created.find(+ (candidate) =>+ candidate.partNumber === item.partNumber &&+ candidate.revision === item.revision+ );+ bomTargets.push({+ item,+ label,+ methodId: method.id,+ lines,+ baseMethodId: createdEntry?.baseItemId+ ? (methodByItemId.get(createdEntry.baseItemId)?.id ?? null)+ : null+ });+ }++ const childItemByPartNumber = new Map<string, ReleasePushItemRow>();+ const childFailed = new Set<string>();+ const releaseItemByPartNumber = new Map(+ modelItems.map((item) => [item.partNumber, item])+ );+ for (const target of bomTargets) {+ for (const child of target.lines) {+ if (!child.partNumber) continue;+ if (+ childItemByPartNumber.has(child.partNumber) ||+ childFailed.has(child.partNumber)+ ) {+ continue;+ }+ // A release item that was held back or failed (its error is reported+ // above) is neither created off the notice nor swapped for another revision.+ const releaseItem = releaseItemByPartNumber.get(child.partNumber);+ if (releaseItem && !revisionItemByPartNumber.has(child.partNumber)) {+ summary.errors.push(+ `${target.label} → ${child.partNumber}: line not written, because ${child.partNumber} Rev ${releaseItem.revision} was not pushed`+ );+ childFailed.add(child.partNumber);+ continue;+ }+ const existingChild =+ revisionItemByPartNumber.get(child.partNumber) ??+ pickBomChildRow(byReadable.get(child.partNumber) ?? [], child.revision)+ .row;+ if (existingChild) {+ childItemByPartNumber.set(child.partNumber, existingChild);+ await applyItemFieldEdit(child.partNumber, existingChild);+ continue;+ }+ const proposed =+ merged.items.get(child.partNumber) ??+ proposeItem(+ {+ partNumber: child.partNumber,+ name: child.name,+ description: child.description,+ revision: child.revision,+ hasChildren: child.children.length > 0,+ standardContent: child.standardContent === true+ },+ plan.options+ );+ const createdChild = await upsertPart(+ client,+ partInsert(+ proposed,+ companyId,+ userId,+ createdFieldsByPartNumber.get(child.partNumber)+ )+ );+ if (createdChild.error || !createdChild.data) {+ summary.errors.push(+ `${target.label} → ${child.partNumber}: ${+ createdChild.error?.message ?? "failed to create the item"+ }`+ );+ childFailed.add(child.partNumber);+ continue;+ }+ const childRow: ReleasePushItemRow = {+ id: createdChild.data.id as string,+ readableId: child.partNumber,+ revision: proposed.revision,+ name: proposed.name,+ type: "Part",+ defaultMethodType: proposed.defaultMethodType,+ sourcingType: proposed.sourcingType ?? null,+ unitOfMeasureCode: proposed.unitOfMeasureCode+ };+ await writeCreatedExtras(child.partNumber, childRow.id, proposed);+ childItemByPartNumber.set(child.partNumber, childRow);+ rememberRow(childRow);+ summary.childrenCreated += 1;+ }+ }++ const madeChildItemIds = [+ ...new Set(+ bomTargets.flatMap((target) =>+ target.lines.flatMap((child) => {+ if (!child.partNumber) return [];+ const row = childItemByPartNumber.get(child.partNumber);+ if (+ child.children.length === 0 &&+ row?.defaultMethodType !== "Make to Order"+ ) {+ return [];+ }+ return row && !methodByItemId.has(row.id) ? [row.id] : [];+ })+ )+ )+ ];+ if (!bomReadFailure) {+ try {+ for (const [itemId, method] of await loadActiveMakeMethods(+ client,+ companyId,+ madeChildItemIds+ )) {+ methodByItemId.set(itemId, method);+ }+ } catch (error) {+ // Without them every sub-assembly line gets a null method and flattens the tree.+ bomReadFailure =+ error instanceof Error+ ? error.message+ : "failed to read the sub-assemblies' make methods";+ }+ }++ // Delete the revision's copies of the base's Onshape lines (manual lines stay),+ // then the lines a previous push of this release wrote.+ const baseMethodIdByTargetMethodId = new Map<string, string>(+ bomTargets.flatMap(+ (target): Array<[string, string]> =>+ target.baseMethodId ? [[target.methodId, target.baseMethodId]] : []+ )+ );+ const copyTargetMethodIds = [...baseMethodIdByTargetMethodId.entries()]+ .filter(([, baseMethodId]) => copiedKeysByBaseMethodId.has(baseMethodId))+ .map(([targetMethodId]) => targetMethodId);+ const targetMethodIds = bomTargets.map((target) => target.methodId);+ const [copies, mapped] = bomReadFailure+ ? [null, null]+ : await Promise.all([+ selectInBatches(copyTargetMethodIds, (batch) =>+ client+ .from("methodMaterial")+ .select("id, makeMethodId, itemId, order, quantity")+ .eq("companyId", companyId)+ .in("makeMethodId", batch)+ ),+ selectInBatches(targetMethodIds, (batch) =>+ serviceRole+ .from("externalIntegrationMapping")+ .select("id, entityId")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "methodMaterial")+ .in("metadata->>makeMethodId", batch)+ )+ ]);+ if (!bomReadFailure && (copies?.error || mapped?.error)) {+ bomReadFailure =+ (copies?.error ?? mapped?.error)?.message ?? "failed to read BOM lines";+ }++ if (bomReadFailure) {+ const carriesCopies = created.some((entry) => {+ const baseMethod = entry.baseItemId+ ? baseMethodByItemId.get(entry.baseItemId)+ : undefined;+ return !!baseMethod && copiedKeysByBaseMethodId.has(baseMethod.id);+ });+ summary.errors.push(+ `The released BOMs were not written: Carbon couldn't read what they replace (${bomReadFailure}). Push the release again.${+ carriesCopies+ ? " A revision this push created still carries its base revision's lines — check its bill of materials before pushing again."+ : ""+ }`+ );+ bomTargets.length = 0;+ }++ const toDelete = (copies?.data ?? [])+ .filter((line) => {+ const baseMethodId = baseMethodIdByTargetMethodId.get(line.makeMethodId);+ return (+ !!baseMethodId &&+ copiedKeysByBaseMethodId.get(baseMethodId)?.has(lineKey(line))+ );+ })+ .map((line) => line.id);+ for (const batch of bomReadFailure ? [] : chunkFilterValues(toDelete)) {+ const deduped = await client+ .from("methodMaterial")+ .delete()+ .eq("companyId", companyId)+ .in("id", batch);+ if (deduped.error) {+ summary.errors.push(+ `Could not remove the lines copied from the base revisions (${deduped.error.message}); released BOMs may contain duplicates`+ );+ }+ }++ if (mapped && !bomReadFailure) {+ const failedLineIds = new Set<string>();+ for (const batch of chunkFilterValues(+ mapped.data.map((mapping) => mapping.entityId)+ )) {+ const removedLines = await client+ .from("methodMaterial")+ .delete()+ .eq("companyId", companyId)+ .in("id", batch);+ if (removedLines.error) {+ for (const id of batch) failedLineIds.add(id);+ summary.errors.push(+ `Could not replace the lines a previous release push wrote (${removedLines.error.message}); this push may add a second copy of them`+ );+ }+ }+ for (const batch of chunkFilterValues(+ mapped.data+ .filter((mapping) => !failedLineIds.has(mapping.entityId))+ .map((mapping) => mapping.id)+ )) {+ const removedMappings = await serviceRole+ .from("externalIntegrationMapping")+ .delete()+ .eq("companyId", companyId)+ .in("id", batch);+ if (removedMappings.error) {+ summary.errors.push(+ `Could not clear the ownership records for the replaced released lines (${removedMappings.error.message})`+ );+ }+ }+ }+ summary.methodsTouched += bomTargets.length;++ // One level only: a sub-assembly gets its lines from its own release item.+ for (const target of bomTargets) {+ const { item, label, methodId } = target;+ const lines: OwnedMethodLine[] = [];+ for (const child of target.lines) {+ if (!child.partNumber) {+ summary.skipped.push(+ `${label} → ${child.name ?? child.index}: no part number in Onshape`+ );+ continue;+ }+ const childItem = childItemByPartNumber.get(child.partNumber);+ if (!childItem) continue; // creation failed above; error already recorded++ // A reused Material or Consumable keeps its type; a Tool or Service cannot be a line.+ const itemType = bomLineItemType(childItem);+ if (!itemType) {+ summary.errors.push(+ `${label} → ${child.partNumber}: a ${+ childItem.type ?? "Part"+ } item cannot be a BOM line`+ );+ continue;+ }++ const childMethod =+ child.children.length > 0 ||+ childItem.defaultMethodType === "Make to Order"+ ? methodByItemId.get(childItem.id)+ : null;+ lines.push({+ row: {+ itemId: childItem.id,+ quantity: child.quantity,+ makeMethodId: methodId,+ materialMakeMethodId: childMethod?.id ?? null,+ methodType:+ (childItem.defaultMethodType as OwnedMethodLine["row"]["methodType"]) ??+ (child.children.length > 0+ ? "Make to Order"+ : "Pull from Inventory"),+ sourcingType:+ (childItem.sourcingType as OwnedMethodLine["row"]["sourcingType"]) ??+ "Specified",+ order: lines.length,+ itemType,+ unitOfMeasureCode: childItem.unitOfMeasureCode ?? "EA"+ },+ metadata: {+ makeMethodId: methodId,+ documentId: plan.documentId,+ elementId: item.elementId,+ partNumber: child.partNumber,+ index: child.index,+ releaseId: plan.releaseId+ }+ });+ }+ const written = await insertOwnedMethodLines(db, {+ companyId,+ userId,+ lines+ });+ if (written.error !== null) {+ summary.errors.push(+ `${label}: the released BOM lines were not written (${written.error}); push the release again`+ );+ } else {+ summary.linesWritten += lines.length;+ }+ }++ // An item holds one Onshape link: a reused revision linked to its part or+ // assembly keeps that link, which status and change detection read.+ const reusedIds = decisions+ .filter((decision) => decision.kind === "reuse")+ .map((decision) => decision.row.id);+ const keepsLink = new Set<string>();+ if (reusedIds.length > 0) {+ const links = await selectInBatches(reusedIds, (batch) =>+ serviceRole+ .from("externalIntegrationMapping")+ .select("entityId, externalId")+ .eq("companyId", companyId)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "item")+ .in("entityId", batch)+ );+ if (links.error) {+ for (const id of reusedIds) keepsLink.add(id);+ summary.errors.push(+ `Could not read the Onshape links of existing revisions (${links.error.message}); they keep their current links`+ );+ } else {+ for (const link of links.data) {+ if (!link.externalId?.startsWith("release:")) {+ keepsLink.add(link.entityId);+ }+ }+ }+ }+ for (const item of modelItems) {+ const row = revisionItemByPartNumber.get(item.partNumber);+ if (!row || keepsLink.has(row.id)) continue;+ const externalId = `release:${plan.releaseId}:${item.partNumber}`;+ const pushedAt = datetime.timestamp();+ const releaseMapping = await swapItemMapping(db, {+ companyId,+ userId,+ itemId: row.id,+ externalId,+ metadata: {+ kind: "release",+ releaseId: plan.releaseId,+ releaseName: plan.releaseName,+ documentId: plan.documentId,+ elementId: item.elementId,+ wv: "v",+ wvId: item.versionId,+ partNumber: item.partNumber,+ revision: item.revision,+ pushedBy: userId,+ pushedAt,+ planId+ }+ });+ if (releaseMapping.error !== null) {+ summary.errors.push(+ `${item.partNumber} Rev ${item.revision}: revision written but not linked to Onshape (${releaseMapping.error}); it is invisible to change detection and to Detach`+ );+ }+ }++ // Make Default repoints every BOM line using a sibling revision to the new one.+ // Not for a staged revision: releasing its notice supersedes the old one instead.+ if (makeDefault && !changeNotice) {+ for (const entry of created) {+ if (!entry.baseItemId) continue; // brand-new item: it is the only revision+ const updated = await updateDefaultRevision(client, {+ id: entry.itemId,+ updatedBy: userId+ });+ if (updated.error) {+ summary.errors.push(+ `${entry.partNumber}: failed to make Rev ${entry.revision} the default`+ );+ } else {+ summary.defaultsUpdated += 1;+ }+ }+ }++ const assetTargets: Array<{+ item: ReleasePlanItem;+ itemId: string;+ kind: "partstudio" | "assembly" | "drawing";+ }> = [];+ for (const item of modelItems) {+ const row = revisionItemByPartNumber.get(item.partNumber);+ if (!row) continue;+ assetTargets.push({+ item,+ itemId: row.id,+ kind: item.elementType === 1 ? "assembly" : "partstudio"+ });+ }+ for (const drawing of drawingItems) {+ // The drawing's model: in this release, or in Carbon at the revision the plan named.+ const model = drawing.drawingOf;+ const targetId = model+ ? (revisionItemByPartNumber.get(model.partNumber)?.id ??+ model.itemId ??+ null)+ : null;+ if (!targetId) {+ summary.skipped.push(+ model+ ? `${drawing.partNumber}: drawing waits for ${model.partNumber}${+ model.revision ? ` Rev ${model.revision}` : ""+ }, which isn't in Carbon; push its release first`+ : `${drawing.partNumber}: drawing has no matching model item in this release`+ );+ continue;+ }+ assetTargets.push({ item: drawing, itemId: targetId, kind: "drawing" });+ }+ for (const target of assetTargets) {+ const selection: ReleaseExportSelection =+ target.kind === "drawing"+ ? { ok: true }+ : releaseExportSelection(target.item);+ if (!selection.ok) {+ summary.skipped.push(+ `${target.item.partNumber} Rev ${target.item.revision}: ${selection.reason}`+ );+ continue;+ }+ // The event id dedupes a retried apply (each run spends Onshape quota). The+ // writes have landed, so a queue failure is reported, not thrown.+ try {+ await trigger(+ "onshape-panel-sync",+ {+ companyId,+ userId,+ itemId: target.itemId,+ documentId: plan.documentId,+ wvm: "v",+ wvmId: target.item.versionId,+ elementId: target.item.elementId,+ elementKind: target.kind,+ ...(selection.partId ? { partId: selection.partId } : {}),+ ...(selection.configuration+ ? { configuration: selection.configuration }+ : {}),+ assetBaseName: `${target.item.partNumber}-${target.item.revision}`+ },+ { id: `${planId}:${target.itemId}:${target.item.elementId}` }+ );+ if (target.kind === "drawing") summary.drawingsQueued += 1;+ } catch {+ summary.errors.push(+ `${target.item.partNumber} Rev ${target.item.revision}: pushed, but the ${+ target.kind === "drawing" ? "drawing" : "model"+ } export couldn't be queued. Push again to retry the export.`+ );+ }+ }++ return panelReply({ summary }, { headers: { "Cache-Control": "no-store" } });+ }+ export const onshapePanelFieldsLogger = getLogger(+ "erp",+ "onshape",+ "panel-fields"+ );++ const modeSchema = z.enum(MAPPING_MODES);++ const entrySchema = z.object({+ onshapePropertyId: z.string().min(1),+ onshapeName: z.string(),+ valueType: z.string().min(1),+ target: z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("customField"), fieldId: z.string().min(1) }),+ z.object({ kind: z.literal("item"), field: z.enum(STANDARD_FIELD_IDS) })+ ]),+ mode: modeSchema,+ translations: z+ .array(+ z.object({+ onshape: z.string().max(255),+ carbon: z.string().nullable()+ })+ )+ .max(100)+ .optional()+ });++ export const onshapePropertyMapInput = z.object({+ entries: z+ .array(entrySchema)+ .max(100)+ // A duplicate propertyId would make one entry silently win.+ .refine(+ (entries) =>+ new Set(entries.map((e) => e.onshapePropertyId)).size === entries.length+ ),+ descriptionModes: z.object({ name: modeSchema, description: modeSchema }),+ pushDefaults: z.object({+ replenishmentSystem: z.enum(ITEM_REPLENISHMENT_SYSTEMS),+ methodTypeForMake: z.enum(ITEM_METHOD_TYPES),+ methodTypeForBuy: z.enum(ITEM_METHOD_TYPES),+ itemTrackingType: z.enum(ITEM_TRACKING_TYPES),+ unitOfMeasureCode: z.string().min(1).nullable()+ })+ });++ // The metadata keys `parsePushDefaults` reads. No unit key when the unit is+ // left to the company's list.+ function pushDefaultsMetadata(defaults: OnshapePushDefaults) {+ return {+ defaultReplenishmentSystem: defaults.replenishmentSystem,+ defaultMethodTypeForMake: defaults.methodTypeForMake,+ defaultMethodTypeForBuy: defaults.methodTypeForBuy,+ defaultItemTrackingType: defaults.itemTrackingType,+ ...(defaults.unitOfMeasureCode+ ? { defaultUnitOfMeasureCode: defaults.unitOfMeasureCode }+ : {})+ };+ }++ type PropertyMapFieldError = { key: string; errors: string[] };++ /** "A, B or C". */+ function orList(values: readonly string[]): string {+ return values.length > 1+ ? `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`+ : (values[0] ?? "");+ }++ /** Replace the property map, the description modes and the push defaults. */+ export async function saveOnshapePropertyMap(+ ctx: ServiceContext,+ input: z.infer<typeof onshapePropertyMapInput>+ ): Promise<PanelReply> {+ const client = ctx.asCaller.supabase;+ const companyId = ctx.company.id;+ const { entries } = input;+ const descriptionModes: DescriptionModes = input.descriptionModes;+ const pushDefaults: OnshapePushDefaults = input.pushDefaults;++ // The same pairs the Part form allows; refused here so the saved value is+ // the value pushes use, not one the plan quietly corrects.+ const reconciled = reconcilePushDefaults(pushDefaults);+ if (reconciled.methodTypeForMake !== pushDefaults.methodTypeForMake) {+ return panelReply(+ {+ error: `${pushDefaults.methodTypeForMake} isn't allowed with ${pushDefaults.replenishmentSystem}`+ },+ { status: 422 }+ );+ }+ if (reconciled.methodTypeForBuy !== pushDefaults.methodTypeForBuy) {+ return panelReply(+ {+ error: `${pushDefaults.methodTypeForBuy} isn't allowed for Buy items`+ },+ { status: 422 }+ );+ }++ const fieldErrors: PropertyMapFieldError[] = [];++ // The editor hides unmappable rows; this guards a hand-made payload.+ for (const entry of entries) {+ if (!Object.hasOwn(MAPPABLE_VALUE_TYPES, entry.valueType)) {+ fieldErrors.push({+ key: entry.onshapePropertyId,+ errors: [`${entry.valueType} properties cannot be mapped`]+ });+ }+ }++ // A target takes one property; each clashing entry names the others.+ const namesByTarget = new Map<string, string[]>();+ for (const entry of entries) {+ const key = targetKey(entry.target);+ namesByTarget.set(key, [+ ...(namesByTarget.get(key) ?? []),+ entry.onshapeName || entry.onshapePropertyId+ ]);+ }+ for (const entry of entries) {+ const own = entry.onshapeName || entry.onshapePropertyId;+ const others = (namesByTarget.get(targetKey(entry.target)) ?? []).filter(+ (name) => name !== own+ );+ if (others.length > 0) {+ fieldErrors.push({+ key: entry.onshapePropertyId,+ errors: [+ `${others.join(", ")} already maps to this Carbon field. A Carbon field takes one property.`+ ]+ });+ }+ }++ const itemEntries = entries.filter((entry) => entry.target.kind === "item");+ let units: Awaited<ReturnType<typeof loadPlanOptions>>["unitsOfMeasure"] = [];+ if (itemEntries.length > 0 || pushDefaults.unitOfMeasureCode) {+ units = (await loadPlanOptions(client, companyId)).unitsOfMeasure;+ }+ if (+ pushDefaults.unitOfMeasureCode &&+ !units.some((unit) => unit.code === pushDefaults.unitOfMeasureCode)+ ) {+ return panelReply(+ {+ error: `${pushDefaults.unitOfMeasureCode} is not a unit of measure in Carbon`+ },+ { status: 422 }+ );+ }+ for (const entry of itemEntries) {+ if (entry.target.kind !== "item") continue;+ const field = standardField(entry.target.field);+ if (!field) continue;+ const errors: string[] = [];+ if (!field.valueTypes.includes(entry.valueType)) {+ errors.push(+ `An Onshape ${entry.valueType} property can't set ${field.label}. It takes ${orList(field.valueTypes)} properties.`+ );+ }+ errors.push(...translationErrors(field, entry.translations ?? [], units));+ if (errors.length > 0) {+ fieldErrors.push({ key: entry.onshapePropertyId, errors });+ }+ }++ const customFieldIds = entries.flatMap((entry) =>+ entry.target.kind === "customField" ? [entry.target.fieldId] : []+ );+ const existingIds = [...new Set(customFieldIds)];+ if (existingIds.length > 0) {+ const existing = await client+ .from("customField")+ .select("id, name, dataTypeId")+ .eq("companyId", companyId)+ .eq("table", "part")+ .in("id", existingIds);+ if (existing.error) {+ onshapePanelFieldsLogger.error("Failed to read custom fields", {+ companyId,+ error: existing.error+ });+ return panelReply(+ { error: "Failed to read custom fields" },+ { status: 500 }+ );+ }+ const fields = new Map((existing.data ?? []).map((row) => [row.id, row]));+ for (const entry of entries) {+ if (entry.target.kind !== "customField") continue;+ const field = fields.get(entry.target.fieldId);+ const dataTypeId = field?.dataTypeId;+ if (field === undefined || dataTypeId === undefined) {+ fieldErrors.push({+ key: entry.onshapePropertyId,+ errors: ["The mapped Carbon field no longer exists"]+ });+ } else if (+ Object.hasOwn(MAPPABLE_VALUE_TYPES, entry.valueType) &&+ !MAPPABLE_VALUE_TYPES[entry.valueType]?.includes(dataTypeId)+ ) {+ const needed = orList(+ (MAPPABLE_VALUE_TYPES[entry.valueType] ?? []).map(+ (id) => CUSTOM_FIELD_TYPE_LABELS[id] ?? String(id)+ )+ );+ fieldErrors.push({+ key: entry.onshapePropertyId,+ errors: [+ `${field.name} is a ${CUSTOM_FIELD_TYPE_LABELS[dataTypeId] ?? "different"} field. An Onshape ${entry.valueType} property needs a ${needed} field.`+ ]+ });+ }+ }+ }+ if (fieldErrors.length > 0) {+ return panelReply(+ { error: "Some field mappings are not valid", fieldErrors },+ { status: 422 }+ );+ }++ // Translations are kept for list item fields only.+ const mapEntries: PropertyMapEntry[] = entries.map((entry) => {+ const field =+ entry.target.kind === "item" ? standardField(entry.target.field) : null;+ return {+ onshapePropertyId: entry.onshapePropertyId,+ onshapeName: entry.onshapeName,+ valueType: entry.valueType,+ target: entry.target,+ mode: entry.mode,+ ...(field?.kind === "list"+ ? {+ translations: (entry.translations ?? []).map((row) => ({+ onshape: row.onshape.trim(),+ carbon: row.carbon+ }))+ }+ : {})+ };+ });++ // Writes only this page's keys (map, modes, push defaults); other writers own+ // the sibling keys. The column is json, hence the casts.+ const db = ctx.asSystem.pg;+ let updatedRows: bigint;+ try {+ const updated = await db+ .updateTable("companyIntegration")+ .set({+ metadata: sql<Json>`((jsonb_set(jsonb_set(metadata::jsonb, '{propertyMap}', ${JSON.stringify(+ mapEntries+ )}::jsonb, true), '{descriptionModes}', ${JSON.stringify(+ descriptionModes+ )}::jsonb, true) || ${JSON.stringify(+ pushDefaultsMetadata(pushDefaults)+ )}::jsonb)${+ pushDefaults.unitOfMeasureCode+ ? sql``+ : sql` - 'defaultUnitOfMeasureCode'`+ })::json`+ })+ .where("id", "=", ONSHAPE_V2_INTEGRATION_ID)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ updatedRows = updated.numUpdatedRows;+ } catch (error) {+ onshapePanelFieldsLogger.error("Failed to save the property map", {+ companyId,+ error+ });+ return panelReply(+ { error: "Failed to save the property map" },+ { status: 500 }+ );+ }+ if (Number(updatedRows) === 0) {+ return panelReply(+ { error: "Onshape is not connected for this company" },+ { status: 422 }+ );+ }++ // The map is saved; a failed re-read is a warning, not a failed save.+ let definitions: PlanCustomFieldDefinition[] | null = null;+ let warning: string | undefined;+ try {+ definitions = await loadPartCustomFieldDefinitions(client, companyId);+ } catch (error) {+ onshapePanelFieldsLogger.error(+ "Failed to re-read custom fields after saving the map",+ {+ companyId,+ error+ }+ );+ warning =+ "Saved. The custom field list couldn't be refreshed — press Refresh to see the latest fields.";+ }++ return panelReply(+ {+ map: mapEntries,+ descriptionModes,+ pushDefaults,+ definitions,+ ...(warning ? { warning } : {})+ },+ { headers: { "Cache-Control": "no-store" } }+ );+ }++ /** A panel operation's result, as its route sends it to the panel. */+ export function panelResponse(+ result:+ | { data: PanelReply; error: null }+ | { data: null; error: { message: string; status: number } }+ ) {+ const headers = { "Cache-Control": "no-store" };+ return result.error+ ? data(+ { error: result.error.message },+ { status: result.error.status, headers }+ )+ : data(result.data.body, { status: result.data.status, headers });+ }++ // Strict backflush gaps. Each count and its drawer list share one query, the+ // SQL form of `needsPullFrom`, so they cannot disagree.++ function methodLinesMissingPullFrom(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ locationIds: string[]+ ) {+ return db+ .selectFrom("methodMaterial")+ .innerJoin("makeMethod", (join) =>+ join+ .onRef("makeMethod.id", "=", "methodMaterial.makeMethodId")+ .on("makeMethod.companyId", "=", companyId)+ .on("makeMethod.status", "=", "Active")+ )+ .innerJoin("item as component", (join) =>+ join+ .onRef("component.id", "=", "methodMaterial.itemId")+ .on("component.companyId", "=", companyId)+ )+ .where("methodMaterial.companyId", "=", companyId)+ .where("methodMaterial.methodType", "!=", "Make to Order")+ .where("methodMaterial.itemType", "in", [...PULLED_ITEM_TYPES])+ .where(+ sql<boolean>`COALESCE("component"."itemTrackingType", 'Inventory') <> 'Non-Inventory'`+ )+ .where(+ sql<boolean>`EXISTS (SELECT 1 FROM unnest(${locationIds}::text[]) AS loc WHERE COALESCE("methodMaterial"."storageUnitIds" ->> loc, '') = '')`+ );+ }++ function jobLinesMissingStorageUnit(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ locationIds: string[]+ ) {+ return db+ .selectFrom("jobMaterial")+ .innerJoin("job", (join) =>+ join+ .onRef("job.id", "=", "jobMaterial.jobId")+ .on("job.companyId", "=", companyId)+ .on("job.status", "in", [...activeJobStatuses])+ )+ .innerJoin("item as component", (join) =>+ join+ .onRef("component.id", "=", "jobMaterial.itemId")+ .on("component.companyId", "=", companyId)+ )+ .where("job.locationId", "in", locationIds)+ .where("jobMaterial.companyId", "=", companyId)+ .where("jobMaterial.storageUnitId", "is", null)+ .where("jobMaterial.methodType", "!=", "Make to Order")+ .where("jobMaterial.itemType", "in", [...PULLED_ITEM_TYPES])+ .where("jobMaterial.requiresBatchTracking", "=", false)+ .where("jobMaterial.requiresSerialTracking", "=", false)+ .where("jobMaterial.quantityToIssue", ">", 0)+ .where(+ sql<boolean>`COALESCE("component"."itemTrackingType", 'Inventory') <> 'Non-Inventory'`+ );+ }++ export async function getStrictBackflushGapCounts(+ db: Kysely<KyselyDatabase>,+ companyId: string+ ): Promise<{+ data: { methods: number; jobs: number } | null;+ error: Error | null;+ }> {+ try {+ // One query at a time: each would otherwise take its own pooled connection.+ const locationIds = (await getPullFromLocations(db, companyId)).map(+ (location) => location.id+ );+ if (locationIds.length === 0) {+ return { data: { methods: 0, jobs: 0 }, error: null };+ }+ const methods = await methodLinesMissingPullFrom(db, companyId, locationIds)+ .select(+ sql<string>`count(DISTINCT "methodMaterial"."makeMethodId")`.as("count")+ )+ .executeTakeFirst();+ const jobs = await jobLinesMissingStorageUnit(db, companyId, locationIds)+ .select(sql<string>`count(DISTINCT "job"."id")`.as("count"))+ .executeTakeFirst();+ return {+ data: {+ methods: Number(methods?.count ?? 0),+ jobs: Number(jobs?.count ?? 0)+ },+ error: null+ };+ } catch (error) {+ return { data: null, error: error as Error };+ }+ }++ export async function getActiveMethodsMissingPullFrom(+ db: Kysely<KyselyDatabase>,+ companyId: string+ ): Promise<{ data: MethodMissingPullFrom[] | null; error: Error | null }> {+ try {+ const locations = await getPullFromLocations(db, companyId);+ if (locations.length === 0) return { data: [], error: null };+ const locationIds = locations.map((location) => location.id);+ const locationName = new Map(+ locations.map((location) => [location.id, location.name])+ );++ const lines = await methodLinesMissingPullFrom(db, companyId, locationIds)+ .innerJoin("item as parent", (join) =>+ join+ .onRef("parent.id", "=", "makeMethod.itemId")+ .on("parent.companyId", "=", companyId)+ )+ .select([+ "makeMethod.id as makeMethodId",+ "makeMethod.version",+ "parent.id as itemId",+ "parent.type as itemType",+ "parent.readableIdWithRevision as readableId",+ "parent.name",+ "methodMaterial.storageUnitIds",+ "component.id as componentId",+ "component.readableIdWithRevision as componentReadableId"+ ])+ .execute();++ const methods = new Map<+ string,+ Omit<MethodMissingPullFrom, "materials" | "locations"> & {+ materials: Set<string>;+ locations: Set<string>;+ }+ >();+ for (const line of lines) {+ const method = methods.get(line.makeMethodId) ?? {+ makeMethodId: line.makeMethodId,+ itemId: line.itemId,+ itemType: line.itemType,+ readableId: line.readableId ?? line.itemId,+ name: line.name,+ version: Number(line.version),+ materials: new Set<string>(),+ locations: new Set<string>()+ };+ method.materials.add(line.componentReadableId ?? line.componentId);+ for (const id of missingPullFromLocations(+ line.storageUnitIds,+ locationIds+ ))+ method.locations.add(locationName.get(id) ?? id);+ methods.set(line.makeMethodId, method);+ }++ return {+ data: [...methods.values()]+ .map((method) => ({+ ...method,+ materials: [...method.materials].sort(),+ locations: [...method.locations].sort()+ }))+ .sort((a, b) => a.readableId.localeCompare(b.readableId)),+ error: null+ };+ } catch (error) {+ return { data: null, error: error as Error };+ }+ }++ export async function getOpenJobsMissingStorageUnit(+ db: Kysely<KyselyDatabase>,+ companyId: string+ ): Promise<{ data: JobMissingStorageUnit[] | null; error: Error | null }> {+ try {+ const locationIds = (await getPullFromLocations(db, companyId)).map(+ (location) => location.id+ );+ if (locationIds.length === 0) return { data: [], error: null };++ const lines = await jobLinesMissingStorageUnit(db, companyId, locationIds)+ .leftJoin("item as jobItem", (join) =>+ join+ .onRef("jobItem.id", "=", "job.itemId")+ .on("jobItem.companyId", "=", companyId)+ )+ .leftJoin("location", (join) =>+ join+ .onRef("location.id", "=", "job.locationId")+ .on("location.companyId", "=", companyId)+ )+ .select([+ "job.id",+ "job.jobId",+ "job.status",+ "jobItem.readableIdWithRevision as readableId",+ "location.name as locationName",+ "component.id as componentId",+ "component.readableIdWithRevision as componentReadableId"+ ])+ .execute();++ const jobs = new Map<+ string,+ Omit<JobMissingStorageUnit, "materials"> & { materials: Set<string> }+ >();+ for (const line of lines) {+ const job = jobs.get(line.id) ?? {+ id: line.id,+ jobId: line.jobId,+ status: line.status,+ readableId: line.readableId,+ locationName: line.locationName,+ materials: new Set<string>()+ };+ job.materials.add(line.componentReadableId ?? line.componentId);+ jobs.set(line.id, job);+ }++ return {+ data: [...jobs.values()]+ .map((job) => ({ ...job, materials: [...job.materials].sort() }))+ .sort((a, b) => a.jobId.localeCompare(b.jobId)),+ error: null+ };+ } catch (error) {+ return { data: null, error: error as Error };+ }}diff --cc apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsxindex 69e193ad5e,e046c3087e..e02617fac2--- a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx@@@ -42,12 -45,8 +43,12 @@@ importLuSend,LuTriangleAlert} from "react-icons/lu";- import { Link, useFetcher } from "react-router";+ import { Link } from "react-router";+import { InfiniteStatus } from "~/components/Table/components/InfiniteStatus";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";+import { useInfiniteScroll } from "~/components/Table/useInfiniteScroll";import { useDateFormatter, usePermissions, useUrlParams } from "~/hooks";+import type { KeysetSort } from "~/utils/cursor";import { path } from "~/utils/path";/**diff --cc apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsxindex cf5e1f4143,600564f92b..774d03a421--- a/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx+++ b/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx@@@ -236,27 -236,27 +237,28 @@@ function ZplPreview({ zpl }: { zpl: str);}-const PrintJobsTable = memo(({ jobs, count }: PrintJobsTableProps) => {+const PrintJobsTable = memo((props: PrintJobsTableProps) => {+ const { jobs, count, nextCursor } = props;const { t } = useLingui();- const fetcher = useFetcher<{- success: boolean;- message?: string;- content?: string;- contentType?: string;- printJobId?: string;- }>();const [viewContent, setViewContent] = useState<ViewContent | null>(null);-- useEffect(() => {- if (fetcher.data && "content" in fetcher.data && fetcher.data.content) {- setViewContent({- content: fetcher.data.content,- contentType: fetcher.data.contentType as string,- printJobId: fetcher.data.printJobId as string- });+ const fetcher = useAction({+ onSuccess: ({ data }) => {+ if (!data) return;+ if ("content" in data) {+ if (data.content) {+ setViewContent({+ content: data.content,+ contentType: data.contentType as string,+ printJobId: data.printJobId as string+ });+ }+ } else if ("printJobId" in data) {+ toast.success(t`Reprint job created`);+ } else {+ toast.success(t`Print job deleted`);+ }}- }, [fetcher.data]);+ });const columns = useMemo<ColumnDef<PrintJob>[]>(() => [diff --cc apps/erp/app/modules/shared/shared.service.tsindex 94bf8694f3,5a379c88e6..b14298b43d--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@@ -22,13 -155,38 +155,40 @@@ import typePostgrestSingleResponse,SupabaseClient} from "@supabase/supabase-js";- import type { GenericQueryFilters, Paging } from "~/utils/query";- import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";- import type {- PriceBreak,- SupplierPartPricing,- SupplierPriceMap- } from "./shared.models";+ import type { Selectable } from "kysely";+ import { sql, type Transaction } from "kysely";+ import { nanoid } from "nanoid";+ import { createCookieSessionStorage, data } from "react-router";+ import { z } from "zod";+ import {+ getCurrencyByCode,+ getPaymentTermsList+ } from "~/modules/accounting/accounting.service";+ import {+ canEditChangeNoticeWorkflow,+ changeNoticeLockedMessage+ } from "~/modules/items/items.models";+ import { getMethod } from "~/modules/production/production.service";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import {+ getCustomerContact,+ getSalesOrder,+ getSalesOrderCustomerDetails,+ getSalesOrderLines+ } from "~/modules/sales/sales.service";+ import { getCompany, withLogoUrls } from "~/modules/settings/settings.service";+ import { getUser, getUserDefaults } from "~/modules/users/users.service";+ import { path } from "~/utils/path";++import type { Paging } from "~/utils/query";+ import {+ type GenericQueryFilters,+ LIST_COUNT,++ listCount,+ setGenericQueryFilters+ } from "~/utils/query";+ import type { CustomFieldsTableType } from "../settings/types";+ import type { assignableTables } from "./shared.models";+ import { assertMethodHasPullFrom, isStrictBackflush } from "./strict-backflush";import type { ItemModelUpload } from "./types";const logger = getLogger("erp", "shared");@@@ -305,19 -450,16 +452,20 @@@ export async function upsertExternalLin.single();}+export const CUSTOMER_PORTALS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+- /** @mcp read */export async function getCustomerPortals(client: SupabaseClient<Database>,companyId: string,args?: GenericQueryFilters & { search: string | null }) {+ // Joined for the search, which matches the customer's name. Every portal+ // has its customer (the form requires one), so the inner join drops none.let query = client.from("externalLink")- .select("*", { count: listCount(args) })- .select("*, customer!inner(id)", { count: LIST_COUNT })++ .select("*, customer!inner(id)", { count: listCount(args) }).eq("companyId", companyId).eq("documentType", "Customer");diff --cc apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsxindex 6865f92a89,6fcef4a90e..06cb8d81cd--- a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx+++ b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx@@@ -29,16 -25,9 +29,16 @@@ importtoCompanyPermissions,usePermissionMatrix} from "~/hooks/usePermissionMatrix";- import type { CompanyPermission } from "~/modules/users";+ import type { CompanyPermission } from "~/modules/users/types";-import { bulkPermissionsValidator } from "~/modules/users/users.models";+import {+ bulkPermissionsAllMatchingValidator,+ bulkPermissionsValidator- } from "~/modules/users";++} from "~/modules/users/users.models";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "../components/AllMatchingUsers";type BulkEditPermissionsProps = {userIds: string[];diff --cc apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsxindex 77a42b33c6,adf24879f6..390f3a1c14--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx@@@ -34,20 -34,17 +34,20 @@@ importimport { useNavigate } from "react-router";import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";+import type { AllMatchingSelection, BulkActionScope } from "~/components/Table";import { usePermissions, useUrlParams, useUser } from "~/hooks";import { useSettings } from "~/hooks/useSettings";- import type { Employee } from "~/modules/users";+ import type { Employee } from "~/modules/users/types";import {BulkEditPermissionsForm,- canBulkActOnUser,DeactivateUsersModal,ResendInviteModal,RevokeInviteModal- } from "~/modules/users";+ } from "~/modules/users/ui";++import { canBulkActOnUser } from "~/modules/users/users.models";import type { ListItem } from "~/types";import { path } from "~/utils/path";+import { useBulkUserActionFetcher } from "../components/AllMatchingUsers";type EmployeesTableProps = {data: Employee[];diff --cc apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsxindex 09465bad8f,93342c7a53..4e316a59d2--- a/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsx+++ b/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsx@@@ -15,19 -15,8 +15,19 @@@ import} from "@carbon/react";import { Trans } from "@lingui/react/macro";import { UserSelect } from "~/components/Selectors";-import { deactivateUsersValidator } from "~/modules/users/users.models";+import {+ type AllMatchingSelection,+ allMatchingRequest+} from "~/components/Table";+import {+ deactivateUsersAllMatchingValidator,+ deactivateUsersValidator- } from "~/modules/users";++} from "~/modules/users/users.models";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "./AllMatchingUsers";type DeactivateUsersModalProps = {userIds: string[];diff --cc apps/erp/app/modules/users/ui/components/ResendInviteModal.tsxindex 4786312060,2e205dc278..9bcc180de8--- a/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx+++ b/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx@@@ -11,24 -12,13 +12,24 @@@ importModalContent,ModalFooter,ModalHeader,- ModalTitle+ ModalTitle,+ toast} from "@carbon/react";- import { Trans } from "@lingui/react/macro";- import { useFetcher } from "react-router";+ import { Trans, useLingui } from "@lingui/react/macro";import { UserSelect } from "~/components/Selectors";-import { resendInviteValidator } from "~/modules/users/users.models";+import {+ type AllMatchingSelection,+ allMatchingRequest+} from "~/components/Table";+import {+ resendInviteAllMatchingValidator,+ resendInviteValidator- } from "~/modules/users";++} from "~/modules/users/users.models";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "./AllMatchingUsers";type ResendInviteModalProps = {userIds: string[];@@@ -44,12 -29,21 +45,23 @@@const ResendInviteModal = ({userIds,isOpen,+ allMatching,+ allMatchingFetcher,onClose}: ResendInviteModalProps) => {- const fetcher = useFetcher<{}>();+ const { t } = useLingui();+ // The modal stays open until the action answers: it unmounts when it+ // closes, and the result is read here.+ const fetcher = useAction({+ onSuccess: (data) =>+ toast.success(+ data.data?.queued+ ? t`Successfully added invites to queue`+ : t`Successfully resent invite`+ ),+ onSettled: () => onClose()+ });- const isSingleUser = userIds.length === 1;+ const isSingleUser = !allMatching && userIds.length === 1;return (<Modal@@@ -95,22 -85,10 +107,22 @@@<ValidatedFormmethod="post"action={path.to.resendInvite}- validator={resendInviteValidator}- fetcher={fetcher}+ validator={+ allMatching+ ? resendInviteAllMatchingValidator+ : resendInviteValidator+ }- onSubmit={onClose}++ onSubmit={allMatching ? onClose : undefined}+ fetcher={allMatching ? allMatchingFetcher : fetcher}>- {userIds.map((id, index) => (+ {allMatching && (+ <input+ type="hidden"+ name="allMatching"+ value={JSON.stringify(allMatchingRequest(allMatching))}+ />+ )}+ {(allMatching ? [] : userIds).map((id, index) => (<inputkey={id}type="hidden"diff --cc apps/erp/app/modules/users/users.models.tsindex ab0632833e,606ac5f067..c46616d2b6--- a/apps/erp/app/modules/users/users.models.ts+++ b/apps/erp/app/modules/users/users.models.ts@@@ -190,48 -196,101 +196,147 @@@ export const userFlagValidator = z.obje});export const userFlagsValidator = z.record(userFlagKeyValidator, z.boolean());++// "Every matching row" in place of the selected users: the list and its URL+// search as JSON (`allMatchingRequest`, `~/components/Table`).+const allMatchingField = z.string().min(1, { message: "Invalid selection" });++export const bulkPermissionsAllMatchingValidator = bulkPermissionsValidator+ .omit({ userIds: true })+ .extend({ allMatching: allMatchingField });++export const deactivateUsersAllMatchingValidator = deactivateUsersValidator+ .omit({ users: true })+ .extend({ allMatching: allMatchingField });++export const resendInviteAllMatchingValidator = z.object({+ allMatching: allMatchingField+});++/** The Employees table's bulk actions on users. */+export type BulkUserAction = "deactivate" | "invite" | "permissions";++/**+ * Whether a bulk action on the Employees table acts on this user: the rule+ * the table applies to its selection, and the background job to every+ * matching row. Edit Permissions takes active users, Deactivate active users+ * other than the actor, and Send Invite inactive users with an email and no+ * unrevoked invite.+ */+export function canBulkActOnUser(+ action: BulkUserAction,+ user: { id: string | null; active: boolean | null; email: string | null },+ context: { actorId: string; unrevokedInviteEmails: ReadonlySet<string> }+): boolean {+ switch (action) {+ case "permissions":+ return user.active === true;+ case "deactivate":+ return user.active === true && user.id !== context.actorId;+ case "invite":+ return (+ user.active === false &&+ !!user.email &&+ !context.unrevokedInviteEmails.has(user.email)+ );+ }+}+++ export const notificationPreferenceValidator = z.object({+ topic: z.nativeEnum(NotificationTopic),+ channel: z.enum(["email", "slack"]),+ enabled: z.enum(["true", "false"])+ });++ // The browser's PushSubscription.toJSON(), plus the endpoint it replaces when+ // the service worker re-subscribes after a pushsubscriptionchange.+ export const pushSubscriptionValidator = z.object({+ endpoint: z.string().url(),+ keys: z.object({+ p256dh: z.string().min(1),+ auth: z.string().min(1)+ }),+ oldEndpoint: z.string().url().optional()+ });++ export const pushSubscriptionEndpointValidator = z.object({+ endpoint: z.string().url()+ });++ export const onboardingUserValidator = z.object({+ firstName: z.string().min(1, { message: "First name is required" }),+ lastName: z.string().min(1, { message: "Last name is required" }),+ // about: zfd.text(z.string().optional()),+ next: z.string().min(1, { message: "Next is required" })+ });++ export const accountLanguageValidator = z.object({+ locale: z.enum(supportedLanguages)+ });++ export const accountPasswordValidator = z+ .object({+ currentPassword: z+ .string()+ .min(6, { message: "Current password is required" }),+ password: z.string().min(6, { message: "Password is required" }),+ confirmPassword: z+ .string()+ .min(6, { message: "Confirm password is required" })+ })+ .superRefine(({ confirmPassword, password }, ctx) => {+ if (confirmPassword !== password) {+ ctx.addIssue({+ code: "custom",+ message: "The passwords did not match"+ });+ }+ });++ export const accountPersonalDataValidator = z.object({});++ const attributeDefaults = {+ type: z.string().min(1, { message: "Type is required" }),+ userAttributeId: z.string().min(20),+ userAttributeValueId: zfd.text(z.string().optional())+ };++ export const attributeBooleanValidator = z.object({+ ...attributeDefaults,+ value: zfd.checkbox()+ });++ export const attributeNumericValidator = z.object({+ ...attributeDefaults,+ value: zfd.numeric(z.number())+ });++ export const attributeTextValidator = z.object({+ ...attributeDefaults,+ value: z.string().min(1, { message: "Value is required" })+ });++ export const attributeUserValidator = z.object({+ ...attributeDefaults,+ value: z.string().min(1, { message: "User is required" })+ });++ export const attributeCustomerValidator = z.object({+ ...attributeDefaults,+ value: z.string().min(1, { message: "Customer is required" })+ });++ export const attributeSupplierValidator = z.object({+ ...attributeDefaults,+ value: z.string().min(1, { message: "Supplier is required" })+ });++ export const attributeFileValidator = z.object({+ ...attributeDefaults,+ value: z.string().min(1, { message: "File is required" })+ });++ export const deleteUserAttributeValueValidator = z.object({+ userAttributeId: z.string().min(20),+ userAttributeValueId: z.string().min(20)+ });diff --cc apps/erp/app/modules/users/users.service.tsindex b61a9631cb,ddc11f6940..9f99844866--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@@ -2,13 -2,59 +2,64 @@@// 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 {+ CarbonError,+ ServiceContext+ } from "@carbon/api/service-fn.server";+ import {+ CONTROLLED_ENVIRONMENT,+ hasPermission,+ ITAR_RIDER_SHA256,+ ITAR_RIDER_VERSION+ } from "@carbon/auth";+ import { deleteAuthAccount } from "@carbon/auth/auth.server";+ import { getCarbonServiceRole } from "@carbon/auth/client.server";+ import {+ deactivateCustomer,+ deactivateEmployee,+ deactivateSupplier,+ getUserClaims+ } from "@carbon/auth/users.server";import type { Database } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";+ import type { Kysely, KyselyDatabase } from "@carbon/database/client";+ import { InviteEmail } from "@carbon/documents/email";+ import { insertAuditLogEntries } from "@carbon/ee/audit.server";+ import { defaultUpgradeMessage, resolveRequirement } from "@carbon/ee/plan";+ import { companyHasFeature } from "@carbon/ee/plan.server";+ import {+ emailDomain,+ getSsoAwareInviteLink,+ getSsoConnection,+ getSsoConnectionByDomain,+ isSsoEnabled,+ mergeInvitePermissions,+ seedSsoIdentityForUser,+ uncoveredSsoDomainError+ } from "@carbon/ee/sso.server";++import { batchTrigger } from "@carbon/jobs";+ import { redis } from "@carbon/kv";+ import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";- import { datetime } from "@carbon/utils";+ import type { NotificationPreferenceChannel } from "@carbon/notifications";-import { datetime, getClientIp } from "@carbon/utils";++import { chunkArray, datetime, getClientIp } from "@carbon/utils";+ import { now, parseAbsolute } from "@internationalized/date";+ import { render } from "@react-email/components";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+ import { nanoid } from "nanoid";+ import type { z } from "zod";+ import { getAttribute } from "~/modules/people/people.service";+ import { getSupplierContact } from "~/modules/purchasing/purchasing.service";+ import { getCustomerContact } from "~/modules/sales/sales.service";+ import type { EmployeeInsert, InviteInsert, User } from "~/modules/users/types";-import type { GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";++import {++ type BulkUserAction,++ canBulkActOnUser++} from "~/modules/users/users.models";+import type { GenericQueryFilters, Paging } from "~/utils/query";+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";+ import { sanitize } from "~/utils/supabase";+ import { insertEmployeeJob } from "../people/people.service";import type { UserSelectGroupMembers } from "./types";const logger = getLogger("erp", "users");@@@ -251,11 -288,6 +293,10 @@@ export async function getUsersWithVerifreturn client.rpc("users_with_verified_mfa", { company_id: companyId });}+export const EMPLOYEES_PAGING: Paging = {+ defaultSorts: [{ column: "lastName", ascending: true }]+};+- /** @mcp read */export async function getEmployees(client: SupabaseClient<Database>,companyId: string,@@@ -332,11 -362,6 +371,10 @@@ export async function getEmployeeType.single();}+export const EMPLOYEE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+- /** @mcp read */export async function getEmployeeTypes(client: SupabaseClient<Database>,companyId: string,@@@ -665,3 -678,2121 +689,2262 @@@ export async function upsertGroupMemberreturn client.from("membership").insert([...memberGroups, ...memberUsers]);}+ /**+ * Controlled environments (ITAR) expire invites 7 days after creation. Computed+ * at read time — no `expiresAt` column. Resend resets `createdAt`, restarting+ * the window. Enforced only when CONTROLLED_ENVIRONMENT is on.+ */+ export const INVITE_EXPIRY_DAYS = 7;++ export function isControlledInviteExpired(createdAt: string): boolean {+ if (!CONTROLLED_ENVIRONMENT) return false;+ const expiresAt = parseAbsolute(createdAt, "UTC").add({+ days: INVITE_EXPIRY_DAYS+ });+ return expiresAt.compare(now("UTC")) < 0;+ }++ /**+ * Once a company has an active SSO connection, employee invites must stay on+ * its covered domains — an uncovered invite would silently bypass the IdP via+ * magic-link auth. Customer/supplier invites are external by nature and are+ * not constrained. Scoped to THIS company's connection: a domain covered by+ * another company's connection is neither required nor blocked here.+ * Returns the refusal message for the email field, or null when the invite+ * may proceed. A failed connection read refuses (fail closed) rather than+ * guessing.+ */+ /**+ * Refuses an invite to an email outside the company's single sign-on+ * domains (a `rule` refusal: the email is wrong), or when the domains cannot+ * be read (`unavailable`: try again). Null without SSO.+ */+ export async function refuseEmailOutsideSso(+ ctx: ServiceContext,+ email: string+ ): Promise<CarbonError<"rule" | "unavailable"> | null> {+ const companyId = ctx.company.id;+ const connection = await getSsoConnection(ctx.asSystem.supabase, companyId);+ if (connection.error) {+ logger.error("Failed to read SSO connection for invite check", {+ companyId,+ error: connection.error+ });+ return ctx.error(+ "unavailable",+ "Could not verify the company's single sign-on configuration. Try again."+ );+ }+ if (!connection.data) return null;+ const refusal = uncoveredSsoDomainError(connection.data.domains ?? [], email);+ return refusal ? ctx.error("rule", refusal) : null;+ }++ export async function acceptInvite(+ serviceRole: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ code: string,+ email?: string+ ) {+ const invite = await serviceRole+ .from("invite")+ .select("*")+ .eq("code", code)+ .is("acceptedAt", null)+ .is("revokedAt", null)+ .single();++ if (invite.error) return invite;++ if (isControlledInviteExpired(invite.data.createdAt)) {+ return {+ data: null,+ error: {+ message:+ "This invite has expired. Please request a new invite to continue."+ }+ };+ }++ // GoTrue stores auth emails lower-cased, while an invite keeps the address+ // as it was typed, so compare the normalized forms.+ if (+ email &&+ invite.data.email.trim().toLowerCase() !== email.trim().toLowerCase()+ ) {+ throw new Error(+ "Invite code does not match email. Please logout and try again."+ );+ }++ const user = await getUserByEmail(invite.data.email);+ if (user.error) return user;++ if (!["employee", "customer", "supplier"].includes(invite.data.role)) {+ return {+ data: null,+ error: {+ message: "Invalid invite role"+ }+ };+ }++ const userId = user.data.id;+ const { companyId, role } = invite.data;++ // Account activation, company membership, the permission merge and the+ // acceptedAt stamp are one unit of work. They used to run as three+ // concurrent writes followed by a compensating rollbackInvite, which could+ // not undo what it had not yet written and silently mismatched the+ // customer/supplier account keys. A transaction removes the half-states+ // instead of trying to repair them: nothing is visible unless all of it+ // commits. Mirrors migrateUserToSso, the SSO path that has to finish the+ // same work.+ try {+ const acceptedInvite = await db.transaction().execute(async (trx) => {+ switch (role) {+ case "employee": {+ // Deactivation dropped this membership and the trigger that seeds it+ // only fires on INSERT, so reactivation has to restore it. Done before+ // the active flip and inside the transaction: an employee is never+ // visible as active while outside their employee type's group.+ const employee = await trx+ .selectFrom("employee")+ .select(["id", "employeeTypeId"])+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (!employee) {+ throw new Error(+ `Employee record not found for user ${userId} in company ${companyId}. The record may have been deleted during deactivation.`+ );+ }++ if (employee.employeeTypeId) {+ await trx+ .insertInto("membership")+ .values({+ groupId: employee.employeeTypeId,+ memberUserId: userId+ })+ .onConflict((oc) =>+ oc.columns(["groupId", "memberUserId"]).doNothing()+ )+ .execute();+ }++ await trx+ .updateTable("employee")+ .set({ active: true })+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .execute();+ break;+ }+ case "customer": {+ const customerAccount = await trx+ .updateTable("customerAccount")+ .set({ active: true })+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .returning("id")+ .executeTakeFirst();++ if (!customerAccount) {+ throw new Error(+ `Customer account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`+ );+ }+ break;+ }+ case "supplier": {+ const supplierAccount = await trx+ .updateTable("supplierAccount")+ .set({ active: true })+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .returning("id")+ .executeTakeFirst();++ if (!supplierAccount) {+ throw new Error(+ `Supplier account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`+ );+ }+ break;+ }+ default: {+ // A new "role" enum value fails typecheck here until it is handled,+ // instead of being activated as a supplier.+ const unhandled: never = role;+ throw new Error(`Invalid invite role: ${unhandled}`);+ }+ }++ await trx+ .insertInto("userToCompany")+ .values({ userId, companyId, role })+ .onConflict((oc) => oc.columns(["userId", "companyId"]).doNothing())+ .execute();++ // Serialize on the user row before the read-merge-write below. The+ // userPermission lock alone holds nothing while that row is absent, so+ // two first acceptances for this user in different companies could both+ // merge from {} and the later upsert would drop the earlier grant.+ // NO KEY UPDATE, not UPDATE: foreign-key checks from rows that reference+ // the user (createdBy and the like) are not blocked.+ await trx+ .selectFrom("user")+ .select("id")+ .where("id", "=", userId)+ .forNoKeyUpdate()+ .executeTakeFirstOrThrow();++ // setUserPermissions semantics, but under a row lock so two concurrent+ // grants cannot lose one another's writes.+ const currentPermission = await trx+ .selectFrom("userPermission")+ .select("permissions")+ .where("id", "=", userId)+ .forUpdate()+ .executeTakeFirst();++ const mergedPermissions = JSON.stringify(+ mergeInvitePermissions(+ (currentPermission?.permissions ?? {}) as Record<string, string[]>,+ (invite.data.permissions ?? {}) as Record<string, string[]>+ )+ );++ await trx+ .insertInto("userPermission")+ .values({ id: userId, permissions: mergedPermissions })+ .onConflict((oc) =>+ oc.column("id").doUpdateSet({ permissions: mergedPermissions })+ )+ .execute();++ // Guarded so a concurrent acceptance can never apply twice, and so a+ // revoke that committed after the lookup above still wins.+ const accepted = await trx+ .updateTable("invite")+ .set({ acceptedAt: datetime.timestamp() })+ .where("code", "=", code)+ .where("companyId", "=", companyId)+ .where("acceptedAt", "is", null)+ .where("revokedAt", "is", null)+ .returningAll()+ .executeTakeFirst();++ if (!accepted) {+ throw new Error(+ "This invite has already been accepted or was revoked."+ );+ }++ return accepted;+ });++ // Post-commit and failure-tolerant: the grants just written are cached by+ // requirePermissions, so a stale entry would outlive the acceptance.+ try {+ await redis.del(getPermissionCacheKey(userId));+ } catch (err) {+ logger.error(+ "Failed to invalidate permission cache after invite accept",+ { error: err, userId }+ );+ }++ return { data: acceptedInvite, error: null };+ } catch (err) {+ logger.error("Failed to accept invite", { error: err, userId, companyId });+ return {+ data: null,+ error: {+ message: err instanceof Error ? err.message : "Failed to accept invite"+ }+ };+ }+ }++ export async function addUserToCompany(+ client: SupabaseClient<Database>,+ userToCompany: {+ userId: string;+ companyId: string;+ role: "employee" | "customer" | "supplier";+ }+ ) {+ return client.from("userToCompany").insert(userToCompany);+ }++ /**+ * Pre-seed a SAML SSO identity for a newly-created auth user when their email+ * domain already has a verified SSO connection — so their first SAML sign-in+ * links to this account instead of being rejected by GOTRUE_DISABLE_SIGNUP.+ * (Existing users on a domain are handled by the backfill in verifySsoDomain.)+ *+ * Best-effort: a failure is logged, never thrown — account creation must not+ * fail because seeding failed, and the domain-verify backfill is a fallback.+ * Rollback-safe: identities cascade-delete with auth.users, so a later insert+ * failure that deletes the auth account also removes this row. Self-gates on+ * isSsoEnabled(); off-Enterprise it does not query.+ */+ async function seedSsoIdentityForNewUser(+ serviceRole: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ { userId, email }: { userId: string; email: string }+ ): Promise<void> {+ if (!isSsoEnabled()) return;+ const domain = emailDomain(email);+ if (!domain) return;++ const connection = await getSsoConnectionByDomain(serviceRole, domain);+ if (connection.error || !connection.data) return;++ const seed = await seedSsoIdentityForUser(db, {+ userId,+ email,+ providerId: connection.data.providerId+ });+ if (seed.error) {+ logger.error("Failed to pre-seed SSO identity for new user", {+ userId,+ domain,+ error: seed.error+ });+ }+ }++ export async function createCustomerAccount(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ {+ id,+ customerId,+ companyId,+ createdBy+ }: {+ id: string;+ customerId: string;+ companyId: string;+ createdBy: string;+ }+ ): Promise<+ | { success: false; message: string }+ | { success: true; code: string; userId: string; email: string }+ > {+ // Both ids come from the form: the contact must be this company's and hang+ // off the customer the account is being created for, or the account (and the+ // contact's userId write below) would point at another tenant's rows.+ const customerContact = await getCustomerContact(client, id, companyId);+ if (+ customerContact.error ||+ customerContact.data === null ||+ customerContact.data.customerId !== customerId ||+ customerContact.data.contact === null ||+ !customerContact.data.contact.email+ ) {+ logger.error("Failed to get customer contact for the company", {+ companyId,+ customerContactId: id,+ customerId,+ error: customerContact.error+ });+ return { success: false, message: "Failed to get customer contact" };+ }++ const { email, firstName, lastName } = customerContact.data.contact;++ const permissions = makeCustomerPermissions(companyId);+ const serviceRole = getCarbonServiceRole();+ const user = await getUserByEmail(email);+ let userId = "";+ let isNewUser = false;++ if (user.data) {+ userId = user.data.id;+ if (!(await authIdentityExists(userId))) {+ return {+ success: false,+ message:+ "This user's auth account no longer exists. Contact support before re-adding."+ };+ }+ } else {+ isNewUser = true;+ const resolvedId = await resolveAuthUserId(email);+ if (!resolvedId) {+ return { success: false, message: "Failed to create auth account" };+ }+ userId = resolvedId;++ const createCarbonUser = await createUser(serviceRole, {+ id: userId,+ email: email.toLowerCase(),+ firstName: firstName ?? "",+ lastName: lastName ?? "",+ avatarUrl: null+ });++ if (createCarbonUser.error) {+ await deleteAuthAccount(serviceRole, userId);+ return { success: false, message: createCarbonUser.error.message };+ }++ await seedSsoIdentityForNewUser(serviceRole, db, { userId, email });+ }++ const code = crypto.randomUUID();+ const [contactUpdate, customerAccountInsert, inviteInsert] =+ await Promise.all([+ client.from("customerContact").update({ userId }).eq("id", id),+ insertCustomerAccount(client, {+ id: userId,+ customerId,+ companyId+ }),+ insertInvite(serviceRole, {+ role: "customer",+ permissions,+ email,+ companyId,+ createdBy,+ code+ })+ ]);++ if (contactUpdate.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateCustomer(serviceRole, userId, companyId);+ }+ return { success: false, message: contactUpdate.error.message };+ }++ if (customerAccountInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateCustomer(serviceRole, userId, companyId);+ }+ return { success: false, message: customerAccountInsert.error.message };+ }++ if (inviteInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateCustomer(serviceRole, userId, companyId);+ }+ return { success: false, message: inviteInsert.error.message };+ }++ return { success: true, code, userId, email };+ }++ export async function createEmployeeAccount(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ {+ email,+ firstName,+ lastName,+ employeeType,+ locationId,+ companyId,+ createdBy,+ attestedBy,+ attestedAt+ }: {+ email: string;+ firstName: string;+ lastName: string;+ employeeType: string;+ locationId: string;+ companyId: string;+ createdBy: string;+ // ITAR (controlled environments): the inviter's 22 CFR 120.62 U.S.-person+ // attestation. Null in ordinary deployments.+ attestedBy?: string | null;+ attestedAt?: string | null;+ }+ ): Promise<+ | { success: false; message: string }+ | { success: true; code: string; userId: string }+ > {+ // Both ids come from the invite form. The employee type's permission rows+ // carry their own company ids, so a foreign type would put another+ // company's grants into this invite; the location lands on employeeJob.+ const [ownedEmployeeType, ownedLocation] = await Promise.all([+ getCarbonServiceRole()+ .from("employeeType")+ .select("id")+ .eq("id", employeeType)+ .eq("companyId", companyId)+ .maybeSingle(),+ getCarbonServiceRole()+ .from("location")+ .select("id")+ .eq("id", locationId)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);+ if (ownedEmployeeType.error || !ownedEmployeeType.data) {+ logger.error("Invite employee type is not in the company", {+ companyId,+ employeeType,+ error: ownedEmployeeType.error+ });+ return { success: false, message: "Employee type not found" };+ }+ if (ownedLocation.error || !ownedLocation.data) {+ logger.error("Invite location is not in the company", {+ companyId,+ locationId,+ error: ownedLocation.error+ });+ return { success: false, message: "Location not found" };+ }++ const employeeTypePermissions = await getPermissionsByEmployeeType(+ client,+ employeeType+ );+ if (employeeTypePermissions.error) {+ return { success: false, message: employeeTypePermissions.error.message };+ }++ const permissions = makePermissionsFromEmployeeType(employeeTypePermissions);+ const serviceRole = getCarbonServiceRole();+ const user = await getUserByEmail(email);+ let userId = "";+ let isNewUser = false;+ let isReactivation = false;++ if (user.data) {+ userId = user.data.id;+ if (!(await authIdentityExists(userId))) {+ return {+ success: false,+ message:+ "This user's auth account no longer exists. Contact support before re-adding."+ };+ }++ const existingEmployee = await client+ .from("employee")+ .select("id, active")+ .eq("id", userId)+ .eq("companyId", companyId)+ .maybeSingle();++ // A failed read must not fall through to the first-time path: there the+ // invite upsert can succeed beside a failing employee insert and leave a+ // redeemable invite behind.+ if (existingEmployee.error) {+ logger.error("Failed to read the existing employee row", {+ companyId,+ userId,+ error: existingEmployee.error+ });+ return { success: false, message: existingEmployee.error.message };+ }++ // Only an *active* employee is genuinely already a member. An inactive row+ // is the residue of a deactivation or a revoked invite: deactivation keeps+ // the "employee" row (and now the "employeeJob" row too), so refusing here+ // dead-ended re-adding someone — the blocking record is also hidden by the+ // employee list's default Active/Invited filter, leaving no way to act on+ // the error. reinviteDeactivatedEmployee reuses those rows instead.+ if (existingEmployee.data?.active) {+ return {+ success: false,+ message: "This user is already an employee in this company"+ };+ }++ isReactivation = Boolean(existingEmployee.data);+ } else {+ isNewUser = true;+ const resolvedId = await resolveAuthUserId(email);+ if (!resolvedId) {+ return { success: false, message: "Failed to create auth account" };+ }+ userId = resolvedId;++ const createCarbonUser = await createUser(serviceRole, {+ id: userId,+ email: email.toLowerCase(),+ firstName,+ lastName,+ avatarUrl: null+ });++ if (createCarbonUser.error) {+ await deleteAuthAccount(serviceRole, userId);+ return { success: false, message: createCarbonUser.error.message };+ }++ await seedSsoIdentityForNewUser(serviceRole, db, { userId, email });+ }++ const code = crypto.randomUUID();+ const invite = {+ role: "employee",+ permissions,+ email,+ companyId,+ createdBy,+ code,+ attestedBy: attestedBy ?? null,+ attestedAt: attestedAt ?? null+ } satisfies InviteInsert;++ if (isReactivation) {+ // Reusing surviving rows is an UPDATE, which RLS would gate behind+ // users_update / people_update, so this path writes outside RLS, scoped by+ // id + companyId. It is one transaction because the three writes are only+ // correct together (see the helper), and it needs no compensation: the+ // auth user already existed, so a rollback leaves nothing behind.+ //+ // Writing outside RLS must not grant more than a first-time add, which+ // inserts under the caller's client: the INSERT policies on "employee" and+ // "employeeJob" require users_update and people_create. The route only+ // requires users_create, so the same two are checked here.+ const claims = await getUserClaims(createdBy, companyId).catch(+ (err: unknown) => {+ logger.error("Failed to read the inviter's permissions", {+ companyId,+ createdBy,+ error: err+ });+ return null;+ }+ );+ if (+ !hasPermission(claims?.permissions, "users", "update", companyId) ||+ !hasPermission(claims?.permissions, "people", "create", companyId)+ ) {+ logger.error("Re-adding a deactivated employee was refused", {+ companyId,+ userId,+ createdBy+ });+ return {+ success: false,+ message:+ "Re-adding a deactivated employee requires the Users update and People create permissions"+ };+ }++ try {+ await reinviteDeactivatedEmployee(db, {+ userId,+ companyId,+ employeeTypeId: employeeType,+ locationId,+ invite+ });+ } catch (err) {+ logger.error("Failed to re-invite employee", {+ error: err,+ userId,+ companyId+ });+ return {+ success: false,+ message:+ err instanceof Error ? err.message : "Failed to re-invite employee"+ };+ }++ return { success: true, code, userId };+ }++ const [employeeInsert, jobInsert, inviteInsert] = await Promise.all([+ insertEmployee(client, {+ id: userId,+ employeeTypeId: employeeType,+ active: false,+ companyId+ }),+ insertEmployeeJob(client, {+ id: userId,+ companyId,+ locationId+ }),+ insertInvite(serviceRole, invite)+ ]);++ if (employeeInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ }+ return { success: false, message: employeeInsert.error.message };+ }++ if (jobInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateEmployee(serviceRole, userId, companyId);+ }+ return { success: false, message: jobInsert.error.message };+ }++ if (inviteInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateEmployee(serviceRole, userId, companyId);+ }+ return { success: false, message: inviteInsert.error.message };+ }++ return { success: true, code, userId };+ }++ export async function createSupplierAccount(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ {+ id,+ supplierId,+ companyId,+ createdBy+ }: {+ id: string;+ supplierId: string;+ companyId: string;+ createdBy: string;+ }+ ): Promise<+ | { success: false; message: string }+ | { success: true; code: string; userId: string; email: string }+ > {+ // Both ids come from the form: the contact must be this company's and hang+ // off the supplier the account is being created for, or the account (and the+ // contact's userId write below) would point at another tenant's rows.+ const supplierContact = await getSupplierContact(client, id, companyId);+ if (+ supplierContact.error ||+ supplierContact.data === null ||+ supplierContact.data.supplierId !== supplierId ||+ supplierContact.data.contact === null ||+ !supplierContact.data.contact.email+ ) {+ logger.error("Failed to get supplier contact for the company", {+ companyId,+ supplierContactId: id,+ supplierId,+ error: supplierContact.error+ });+ return { success: false, message: "Failed to get supplier contact" };+ }++ const { email, firstName, lastName } = supplierContact.data.contact;++ const permissions = makeSupplierPermissions(companyId);+ const serviceRole = getCarbonServiceRole();+ const user = await getUserByEmail(email);+ let userId = "";+ let isNewUser = false;++ if (user.data) {+ userId = user.data.id;+ if (!(await authIdentityExists(userId))) {+ return {+ success: false,+ message:+ "This user's auth account no longer exists. Contact support before re-adding."+ };+ }+ } else {+ isNewUser = true;+ const resolvedId = await resolveAuthUserId(email);+ if (!resolvedId) {+ return { success: false, message: "Failed to create auth account" };+ }+ userId = resolvedId;++ const createCarbonUser = await createUser(serviceRole, {+ id: userId,+ email: email.toLowerCase(),+ firstName: firstName ?? "",+ lastName: lastName ?? "",+ avatarUrl: null+ });++ if (createCarbonUser.error) {+ await deleteAuthAccount(serviceRole, userId);+ return { success: false, message: createCarbonUser.error.message };+ }++ await seedSsoIdentityForNewUser(serviceRole, db, { userId, email });+ }++ const code = crypto.randomUUID();+ const [contactUpdate, supplierAccountInsert, inviteInsert] =+ await Promise.all([+ client.from("supplierContact").update({ userId }).eq("id", id),+ insertSupplierAccount(client, {+ id: userId,+ supplierId,+ companyId+ }),+ insertInvite(serviceRole, {+ role: "supplier",+ permissions,+ email,+ companyId,+ createdBy,+ code+ })+ ]);++ if (contactUpdate.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateSupplier(serviceRole, userId, companyId);+ }+ return { success: false, message: contactUpdate.error.message };+ }++ if (supplierAccountInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateSupplier(serviceRole, userId, companyId);+ }+ return { success: false, message: supplierAccountInsert.error.message };+ }++ if (inviteInsert.error) {+ if (isNewUser) {+ await deleteAuthAccount(serviceRole, userId);+ } else {+ await deactivateSupplier(serviceRole, userId, companyId);+ }+ return { success: false, message: inviteInsert.error.message };+ }++ return { success: true, code, userId, email };+ }++ async function createUser(+ client: SupabaseClient<Database>,+ user: Omit<User, "fullName">+ ) {+ const { data, error } = await insertUser(client, user);++ if (error) {+ await deleteAuthAccount(client, user.id);+ }++ return { data, error };+ }++ export async function getClaims(+ client: SupabaseClient<Database>,+ uid: string,+ company?: string+ ) {+ return client.rpc("get_claims", { uid, company: company ?? "" });+ }++ export function getPermissionCacheKey(userId: string) {+ return `permissions:${userId}`;+ }++ export async function getUser(client: SupabaseClient<Database>, id: string) {+ return client+ .from("user")+ .select("*")+ .eq("id", id)+ .eq("active", true)+ .single();+ }++ export async function getUserByEmail(email: string) {+ return getCarbonServiceRole()+ .from("user")+ .select("*")+ .eq("email", email.toLowerCase())+ .single();+ }++ // Returns false if the auth identity for this userId has been deleted, leaving only an app-side row.+ async function authIdentityExists(userId: string): Promise<boolean> {+ const { error } = await getCarbonServiceRole().auth.admin.getUserById(userId);+ return !error;+ }++ // Creates the auth user for email, or recovers the existing ID if a prior deletion left one behind.+ async function resolveAuthUserId(email: string): Promise<string | null> {+ const serviceRole = getCarbonServiceRole();+ const result = await serviceRole.auth.admin.createUser({+ email: email.toLowerCase(),+ password: crypto.randomUUID(),+ email_confirm: true+ });++ if (!result.error) return result.data.user.id;++ // Only recover for "already registered"; other errors (network, rate limit) surface as-is.+ if (result.error.code !== "user_already_exists") return null;++ // auth record exists but app user row doesn't; find the orphaned ID.+ const target = email.toLowerCase();+ let page = 1;+ const perPage = 1000;+ while (true) {+ const { data, error } = await serviceRole.auth.admin.listUsers({+ page,+ perPage+ });+ if (error || !data?.users?.length) return null;+ const match = data.users.find((u) => u.email?.toLowerCase() === target);+ if (match) return match.id;+ if (data.users.length < perPage) return null;+ page++;+ }+ }++ export async function getUserGroups(+ client: SupabaseClient<Database>,+ userId: string+ ) {+ // Normalize an empty result to [] (not null) — belt-and-suspenders with the+ // groups_for_user COALESCE migration, so a user with no memberships is a+ // well-formed empty array rather than a null the /x guard could mistake for+ // an auth failure.+ const result = await client.rpc("groups_for_user", { uid: userId });+ return { ...result, data: result.data ?? [] };+ }++ export async function getUserDefaults(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return client+ .from("userDefaults")+ .select("*")+ .eq("userId", userId)+ .eq("companyId", companyId)+ .maybeSingle();+ }++ export async function getModulePreferences(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return client+ .from("userModulePreference")+ .select("module, position, hidden")+ .eq("userId", userId)+ .eq("companyId", companyId)+ .order("position");+ }++ export async function upsertModulePreferences(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string,+ preferences: { module: string; position: number; hidden: boolean }[]+ ) {+ return client.from("userModulePreference").upsert(+ preferences.map((p) => ({+ userId,+ companyId,+ module: p.module,+ position: p.position,+ hidden: p.hidden,+ updatedAt: new Date().toISOString()+ })),+ { onConflict: "userId,companyId,module" }+ );+ }++ async function insertCustomerAccount(+ client: SupabaseClient<Database>,+ customerAccount: {+ id: string;+ customerId: string;+ companyId: string;+ }+ ) {+ return client+ .from("customerAccount")+ .insert(customerAccount)+ .select("id")+ .single();+ }++ export async function insertEmployee(+ client: SupabaseClient<Database>,+ employee: EmployeeInsert+ ) {+ return client.from("employee").insert([employee]).select("*").single();+ }++ /**+ * Re-add someone whose "employee" row survived a deactivation or a revoked+ * invite, writing the employee type, org placement and invite in one+ * transaction. They are only correct together: acceptInvite restores the+ * employee-type membership from employee.employeeTypeId, while the invite's+ * permissions come from the type chosen on the form. Written separately, a+ * failed employee write left a redeemable invite for the new type next to a row+ * still naming the old one.+ *+ * The employee row is locked first. That re-checks the caller's "not active"+ * read, so a concurrent acceptance cannot be flipped back to inactive, and it+ * serialises two re-adds of the same person, so the later one overwrites all+ * three rows rather than some of them. The row must still exist: this path+ * only reuses rows, and a first-time employee insert stays under the caller's+ * RLS client. Active stays false until the invite is accepted.+ *+ * "employeeJob" is upserted because deactivation keeps it (title, start date,+ * department, shift, manager, tags and custom fields carry through), but an+ * employee deactivated before that change has none. Only locationId is written+ * on conflict. Kept here rather than in people.service.ts — every export there+ * is also published as an MCP tool.+ *+ * The invite write mirrors insertInvite: upsert on (email, companyId), clearing+ * acceptedAt and revokedAt so a spent invite row becomes redeemable again, and+ * restarting createdAt so the controlled-environment expiry counts from now.+ */+ async function reinviteDeactivatedEmployee(+ db: Kysely<KyselyDatabase>,+ {+ userId,+ companyId,+ employeeTypeId,+ locationId,+ invite+ }: {+ userId: string;+ companyId: string;+ employeeTypeId: string;+ locationId: string;+ invite: Omit<InviteInsert, "permissions"> & {+ permissions: Record<string, string[]>;+ };+ }+ ) {+ await db.transaction().execute(async (trx) => {+ const employee = await trx+ .selectFrom("employee")+ .select("active")+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ if (!employee) {+ throw new Error(+ `Employee record not found for user ${userId} in company ${companyId}. Try adding the employee again.`+ );+ }++ if (employee.active) {+ throw new Error("This user is already an employee in this company");+ }++ await trx+ .updateTable("employee")+ .set({ employeeTypeId })+ .where("id", "=", userId)+ .where("companyId", "=", companyId)+ .execute();++ // updatedBy names the inviter: this connection has no auth.uid(), and the+ // audit log falls back to the row's own audit columns for the actor.+ await trx+ .insertInto("employeeJob")+ .values({ id: userId, companyId, locationId })+ .onConflict((oc) =>+ oc.columns(["id", "companyId"]).doUpdateSet({+ locationId,+ updatedBy: invite.createdBy,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();++ const permissions = JSON.stringify(invite.permissions);++ await trx+ .insertInto("invite")+ .values({+ role: invite.role,+ permissions,+ email: invite.email,+ companyId: invite.companyId,+ createdBy: invite.createdBy,+ code: invite.code,+ attestedBy: invite.attestedBy ?? null,+ attestedAt: invite.attestedAt ?? null,+ acceptedAt: null,+ revokedAt: null+ })+ .onConflict((oc) =>+ oc.columns(["email", "companyId"]).doUpdateSet({+ role: invite.role,+ permissions,+ createdBy: invite.createdBy,+ updatedBy: invite.createdBy,+ // The controlled-environment expiry counts from createdAt. The+ // reused row is the original invite, usually long since accepted,+ // so keeping its createdAt expired the new invite on arrival.+ createdAt: datetime.timestamp(),+ code: invite.code,+ attestedBy: invite.attestedBy ?? null,+ attestedAt: invite.attestedAt ?? null,+ acceptedAt: null,+ revokedAt: null+ })+ )+ .execute();+ });+ }++ export async function insertInvite(+ client: SupabaseClient<Database>,+ invite: InviteInsert+ ) {+ return (+ client+ .from("invite")+ // Re-inviting an email that already has an invite row reuses it via the+ // onConflict upsert. Clear both terminal states so a previously revoked or+ // accepted invite becomes redeemable again — otherwise the acceptance+ // loader (invite.$code.tsx) rejects the row and it can never be accepted.+ // createdAt restarts too: the controlled-environment expiry counts from+ // it, and the reused row's is the original invite's.+ .upsert(+ [+ {+ ...invite,+ createdAt: datetime.timestamp(),+ acceptedAt: null,+ revokedAt: null+ }+ ],+ {+ onConflict: "email, companyId",+ ignoreDuplicates: false+ }+ )+ .select("*")+ .single()+ );+ }++ async function insertSupplierAccount(+ client: SupabaseClient<Database>,+ supplierAccount: {+ id: string;+ supplierId: string;+ companyId: string;+ }+ ) {+ return client+ .from("supplierAccount")+ .insert(supplierAccount)+ .select("id")+ .single();+ }++ async function insertUser(+ client: SupabaseClient<Database>,+ user: Omit<User, "fullName" | "createdAt">+ ) {+ return client.from("user").upsert([user]).select("*");+ }++ /**+ * Creates a console-only operator: a lightweight user record that can pin in+ * at MES terminals without needing email, password, or Supabase Auth.+ *+ * Uses a synthetic email ({uuid}@console.internal) to satisfy the NOT NULL+ * constraint. No auth.users entry is created — operators cannot log in.+ */+ export async function createConsoleOperator(+ client: SupabaseClient<Database>,+ {+ firstName,+ lastName,+ employeeType,+ locationId,+ companyId,+ createdBy+ }: {+ firstName: string;+ lastName: string;+ employeeType: string;+ locationId: string;+ companyId: string;+ createdBy: string;+ }+ ): Promise<+ | { success: false; message: string }+ | { success: true; userId: string; name: string }+ > {+ const serviceRole = getCarbonServiceRole();+ const userId = crypto.randomUUID();+ const syntheticEmail = `${userId}@console.internal`;++ // 1. Insert user record (no Supabase Auth)+ // Note: isConsoleOperator field added by migration 20260319000000_console-mode.sql+ // Type will be available after db:generate runs+ const userInsert = await serviceRole+ .from("user")+ .insert({+ id: userId,+ email: syntheticEmail,+ firstName,+ lastName,+ avatarUrl: null,+ active: true,+ isConsoleOperator: true+ } as any)+ .select("*")+ .single();++ if (userInsert.error) {+ return { success: false, message: userInsert.error.message };+ }++ // 2. Insert employee (auto-active, no invite needed)+ const employeeInsert = await insertEmployee(client, {+ id: userId,+ employeeTypeId: employeeType,+ active: true,+ companyId+ });++ if (employeeInsert.error) {+ // Cleanup: remove user+ await serviceRole.from("user").delete().eq("id", userId);+ return { success: false, message: employeeInsert.error.message };+ }++ // 3. Insert employeeJob+ const jobInsert = await insertEmployeeJob(client, {+ id: userId,+ companyId,+ locationId+ });++ if (jobInsert.error) {+ // Cleanup+ await serviceRole.from("employee").delete().eq("id", userId);+ await serviceRole.from("user").delete().eq("id", userId);+ return { success: false, message: jobInsert.error.message };+ }++ // 4. Add to userToCompany (for billing/plan counting)+ const companyLink = await serviceRole+ .from("userToCompany")+ .insert({ userId, companyId, role: "employee" as const })+ .select("*")+ .single();++ if (companyLink.error) {+ // Non-critical — operator still works without this+ logger.error("Failed to link console operator to company", {+ error: companyLink.error+ });+ }++ return {+ success: true,+ userId,+ name: `${firstName} ${lastName}`+ };+ }++ /**+ * Converts a console-only operator to a full user by adding a Supabase Auth+ * account and updating their email to a real one.+ */+ export async function convertConsoleOperatorToUser(+ client: SupabaseClient<Database>,+ {+ userId,+ email,+ employeeType,+ companyId,+ createdBy+ }: {+ userId: string;+ email: string;+ employeeType: string;+ companyId: string;+ createdBy: string;+ }+ ): Promise<{ success: false; message: string } | { success: true }> {+ const serviceRole = getCarbonServiceRole();++ // userId comes from the URL and every write below is service-role, so prove+ // the operator is an employee of THIS company — otherwise another company's+ // operator could be given an auth login under an email the caller chose —+ // and that the employee type is this company's.+ const [membership, targetEmployeeType] = await Promise.all([+ serviceRole+ .from("employee")+ .select("id")+ .eq("id", userId)+ .eq("companyId", companyId)+ .maybeSingle(),+ serviceRole+ .from("employeeType")+ .select("id")+ .eq("id", employeeType)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);+ if (membership.error || !membership.data) {+ logger.error("Console operator is not an employee of the company", {+ companyId,+ userId,+ error: membership.error+ });+ return { success: false, message: "User is not a console operator" };+ }+ if (targetEmployeeType.error || !targetEmployeeType.data) {+ logger.error("Employee type is not in the company", {+ companyId,+ employeeType,+ error: targetEmployeeType.error+ });+ return { success: false, message: "Employee type not found" };+ }++ // Verify the user is a console operator+ // Note: isConsoleOperator field added by migration 20260319000000_console-mode.sql+ const existingUser = await serviceRole+ .from("user")+ .select("*")+ .eq("id", userId)+ .single();++ if (existingUser.error || !(existingUser.data as any)?.isConsoleOperator) {+ return { success: false, message: "User is not a console operator" };+ }++ // Check email isn't already taken+ const emailCheck = await serviceRole+ .from("user")+ .select("id")+ .eq("email", email.toLowerCase())+ .maybeSingle();++ if (emailCheck.data) {+ return { success: false, message: "Email is already in use" };+ }++ // Create Supabase Auth account with the same user ID+ const createAuth = await serviceRole.auth.admin.createUser({+ id: userId,+ email: email.toLowerCase(),+ password: crypto.randomUUID(),+ email_confirm: true+ });++ if (createAuth.error) {+ return { success: false, message: createAuth.error.message };+ }++ // Update user record: real email + no longer console operator+ const updateUser = await serviceRole+ .from("user")+ .update({+ email: email.toLowerCase(),+ isConsoleOperator: false+ } as any)+ .eq("id", userId);++ if (updateUser.error) {+ // Cleanup auth+ await deleteAuthAccount(serviceRole, userId);+ return { success: false, message: updateUser.error.message };+ }++ // Change employee type to the selected type+ await serviceRole+ .from("employee")+ .update({ employeeTypeId: employeeType })+ .eq("id", userId)+ .eq("companyId", companyId);++ // Create invite so user gets the magic link email+ const code = crypto.randomUUID();+ const employee = await client+ .from("employee")+ .select("employeeTypeId")+ .eq("id", userId)+ .eq("companyId", companyId)+ .single();++ if (employee.data?.employeeTypeId) {+ const employeeTypePermissions = await getPermissionsByEmployeeType(+ client,+ employee.data.employeeTypeId+ );++ if (!employeeTypePermissions.error) {+ const permissions = makePermissionsFromEmployeeType(+ employeeTypePermissions+ );++ const inviteResult = await insertInvite(serviceRole, {+ role: "employee",+ permissions,+ email: email.toLowerCase(),+ companyId,+ createdBy,+ code+ });++ if (inviteResult.error) {+ logger.error("Failed to create invite for converted operator", {+ error: inviteResult.error+ });+ }+ }+ }++ return { success: true };+ }++ function makePermissionsFromEmployeeType({+ data+ }: {+ data: {+ view: string[];+ create: string[];+ update: string[];+ delete: string[];+ module: string;+ }[];+ }) {+ const permissions: Record<string, string[]> = {};++ data.forEach((permission) => {+ if (!permission.module) {+ throw new Error(+ `Permission module is missing for permission ${JSON.stringify(data)}`+ );+ }++ const module = permission.module.toLowerCase();++ permissions[`${module}_view`] = permission.view;+ permissions[`${module}_create`] = permission.create;+ permissions[`${module}_update`] = permission.update;+ permissions[`${module}_delete`] = permission.delete;+ });++ return permissions;+ }++ function makeCustomerPermissions(companyId: string) {+ // TODO: this should be more dynamic+ const permissions: Record<string, string[]> = {+ documents_view: [companyId],+ documents_create: [companyId],+ documents_udpate: [companyId],+ documents_delete: [companyId],+ jobs_view: [companyId],+ sales_view: [companyId],+ parts_view: [companyId]+ };++ return permissions;+ }++ function makeSupplierPermissions(companyId: string) {+ // TODO: this should be more dynamic+ const permissions: Record<string, string[]> = {+ documents_view: [companyId],+ documents_create: [companyId],+ documents_udpate: [companyId],+ documents_delete: [companyId],+ purchasing_view: [companyId],+ parts_view: [companyId]+ };++ return permissions;+ }++ export async function getInvite(+ client: SupabaseClient<Database>,+ email: string,+ companyId: string+ ) {+ return client+ .from("invite")+ .select("*")+ .eq("email", email)+ .eq("companyId", companyId)+ .single();+ }++ export async function resetPassword(userId: string, password: string) {+ return getCarbonServiceRole().auth.admin.updateUserById(userId, {+ password+ });+ }++ /** The request's IP and city, for the operations that record them. */+ export function originOf(request: Request) {+ return {+ ip: getClientIp(request) ?? undefined,+ city: request.headers.get("x-vercel-ip-city") ?? undefined,+ userAgent: request.headers.get("user-agent") ?? undefined+ };+ }++ /**+ * Role authoring is a Business-plan feature. This is the friendly refusal;+ * the lock is `requireEntitlement` inside `@carbon/ee/permissions.server`.+ */+ export async function refuseUnlessPermissionsFeature(ctx: ServiceContext) {+ const spec = { feature: "PERMISSIONS" } as const;+ if (await companyHasFeature(ctx.asCaller.supabase, ctx.company.id, spec)) {+ return null;+ }+ return ctx.error(+ "entitlement",+ defaultUpgradeMessage(resolveRequirement(spec))+ );+ }++ /** The company's name and the inviting user, for the invite email. */+ export async function inviteSender(ctx: ServiceContext) {+ const client = ctx.asCaller.supabase;+ const [company, user] = await Promise.all([+ client.from("company").select("name").eq("id", ctx.company.id).single(),+ client+ .from("user")+ .select("email, fullName")+ .eq("id", ctx.auditUserId)+ .single()+ ]);+ if (!company.data || !user.data) return null;+ return { companyName: company.data.name, invitedBy: user.data };+ }++ export async function sendInviteEmail(+ ctx: ServiceContext,+ invite: {+ email: string;+ code: string;+ name: string;+ companyName: string;+ invitedBy: { email: string; fullName: string | null };+ ip?: string;+ city?: string;+ }+ ) {+ const inviteLink = await getSsoAwareInviteLink(+ ctx.asSystem.supabase,+ invite.email,+ invite.code,+ ctx.company.id+ );+ await sendEmail({+ to: invite.email,+ subject: `You have been invited to join ${invite.companyName} on Carbon`,+ headers: { "X-Entity-Ref-ID": nanoid() },+ html: await render(+ InviteEmail({+ invitedByEmail: invite.invitedBy.email,+ invitedByName: invite.invitedBy.fullName ?? "",+ email: invite.email,+ name: invite.name,+ companyName: invite.companyName,+ inviteLink,+ ip: invite.ip ?? "127.0.0.1",+ location: invite.city ?? "Unknown",+ controlledEnvironment: CONTROLLED_ENVIRONMENT+ })+ )+ });+ }++ /** Email a new customer or supplier account its invite link. */+ export async function emailAccountInvite(+ ctx: ServiceContext,+ account: { userId: string; email: string; code: string },+ origin: { ip?: string; city?: string }+ ) {+ const [sender, invitee] = await Promise.all([+ inviteSender(ctx),+ ctx.asCaller.supabase+ .from("user")+ .select("fullName")+ .eq("id", account.userId)+ .single()+ ]);+ if (!sender) return ctx.error("internal", "Failed to load company or user");+ await sendInviteEmail(ctx, {+ ...sender,+ email: account.email,+ code: account.code,+ name: invitee.data?.fullName ?? "",+ ...origin+ });+ return { userId: account.userId };+ }++ /** `updateEmployee` / `updatePermissions` refusals, by what they mean. */+ export function permissionsWriteError(+ ctx: ServiceContext,+ message = "Failed to update permissions"+ ) {+ switch (message) {+ case "Employee not found":+ case "Employee type not found":+ return ctx.error("notFound", message);+ case "You do not have permission to update permissions":+ return ctx.error("forbidden", message);+ default:+ return ctx.error("internal", message);+ }+ }++ /**+ * Record an ITAR certification (entity or user) that expires in 365 days,+ * plus a best-effort audit-log entry with the IP and user agent. Written with+ * the service role: a self-attesting user does not hold settings create.+ */+ export async function recordItarCertification(+ ctx: ServiceContext,+ certification: {+ type: "entity" | "user";+ fullLegalName: string;+ title?: string;+ complianceContact?: string;+ ipAddress?: string;+ userAgent?: string;+ }+ ) {+ const serviceRole = ctx.asSystem.supabase;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const certifiedAt = datetime.timestamp();+ const expiresAt = parseAbsolute(certifiedAt, "UTC")+ .add({ days: 365 })+ .toAbsoluteString();++ const inserted = await serviceRole+ .from("itarCertification")+ .insert({+ companyId,+ userId,+ type: certification.type,+ docVersion: ITAR_RIDER_VERSION,+ docHash: ITAR_RIDER_SHA256,+ fullLegalName: certification.fullLegalName,+ title: certification.title ?? null,+ complianceContact: certification.complianceContact ?? null,+ certifiedAt,+ ipAddress: certification.ipAddress ?? null,+ userAgent: certification.userAgent ?? null,+ expiresAt,+ createdBy: userId+ })+ .select("id")+ .single();+ if (inserted.error || !inserted.data) {+ return ctx.error(+ "internal",+ "Failed to record certification",+ inserted.error+ );+ }++ // Best effort: a company without audit logging has no audit log table; the+ // certification row is the compliance record.+ try {+ await insertAuditLogEntries(serviceRole, companyId, [+ {+ tableName: "itarCertification",+ entityType: "itarCertification",+ entityId: inserted.data.id,+ recordId: inserted.data.id,+ operation: "INSERT",+ actorId: userId,+ metadata: {+ ipAddress: certification.ipAddress,+ userAgent: certification.userAgent+ },+ createdAt: certifiedAt+ }+ ]);+ } catch (err) {+ logger.warn("[acknowledge] audit write skipped for {type} cert", {+ type: certification.type,+ error: err+ });+ }+ return { certificationId: inserted.data.id };+ }++ /** The first problem, worded for the person who filled the form. */+ export function firstIssue(error: z.ZodError) {+ return error.issues[0]?.message ?? "The certification is incomplete";+ }+ export type ChangelogPanelEntry = {+ guid: string;+ slug: string;+ title: string;+ description: string | null;+ };++ // The newest entry in the dispatch ledger (service-role only). `slug` is the+ // last segment of the guid permalink and keys the dismissal flag.+ export async function getChangelogPanelEntry(+ serviceRole: SupabaseClient<Database>+ ): Promise<ChangelogPanelEntry | null> {+ const latest = await serviceRole+ .from("changelogDispatch")+ .select("guid, title, description")+ .order("dispatchedAt", { ascending: false })+ .limit(1)+ .maybeSingle();+ if (!latest.data?.title) return null;+ const slug = latest.data.guid.split("/").filter(Boolean).pop() ?? "";+ if (!slug) return null;+ return {+ guid: latest.data.guid,+ slug,+ title: latest.data.title,+ description: latest.data.description+ };+ }++ export async function getNotificationPreferences(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return client+ .from("notificationPreference")+ .select("topic, channel, enabled")+ .eq("userId", userId)+ .eq("companyId", companyId);+ }++ export async function upsertNotificationPreference(+ client: SupabaseClient<Database>,+ preference: {+ userId: string;+ companyId: string;+ topic: string;+ channel: NotificationPreferenceChannel;+ enabled: boolean;+ }+ ) {+ return client.from("notificationPreference").upsert(+ {+ ...preference,+ updatedAt: new Date().toISOString()+ },+ { onConflict: "userId,companyId,channel,topic" }+ );+ }++ /** Reads this browser's push subscription for the user. */+ export async function getPushSubscription(+ client: SupabaseClient<Database>,+ args: { userId: string; endpoint: string }+ ) {+ return client+ .from("pushSubscription")+ .select("id")+ .eq("userId", args.userId)+ .eq("endpoint", args.endpoint)+ .maybeSingle();+ }++ /** Saves this browser's push subscription for the user. One row per browser;+ * companyId is the company it was enabled from. */+ export async function upsertPushSubscription(+ client: SupabaseClient<Database>,+ subscription: {+ userId: string;+ companyId: string;+ endpoint: string;+ p256dh: string;+ auth: string;+ userAgent: string | null;+ }+ ) {+ return client+ .from("pushSubscription")+ .upsert(+ { ...subscription, updatedAt: datetime.timestamp() },+ { onConflict: "endpoint" }+ )+ .select("id")+ .single();+ }++ /** Removes every user's push subscription for a browser endpoint, or every+ * user's but one with `exceptUserId`. Pass the service-role client: RLS shows+ * a user only their own rows. */+ export async function deleteBrowserPushSubscriptions(+ client: SupabaseClient<Database>,+ args: { endpoint: string; exceptUserId?: string }+ ) {+ const query = client+ .from("pushSubscription")+ .delete()+ .eq("endpoint", args.endpoint);+ return args.exceptUserId ? query.neq("userId", args.exceptUserId) : query;+ }++ /** Removes this browser's push subscription for the user. */+ export async function deletePushSubscription(+ client: SupabaseClient<Database>,+ args: { userId: string; endpoint: string }+ ) {+ return client+ .from("pushSubscription")+ .delete()+ .eq("userId", args.userId)+ .eq("endpoint", args.endpoint);+ }++ /** Values are removed through `deleteAttributeValue`, which checks who may. */+ export async function deleteUserAttributeValue(+ client: SupabaseClient<Database>,+ args: {+ userId: string;+ userAttributeId: string;+ userAttributeValueId: string;+ }+ ) {+ return client+ .from("userAttributeValue")+ .delete()+ .eq("id", args.userAttributeValueId)+ .eq("userAttributeId", args.userAttributeId)+ .eq("userId", args.userId);+ }++ export async function getAccount(client: SupabaseClient<Database>, id: string) {+ return client.from("user").select("*").eq("id", id).single();+ }++ /**+ * Return the connected user's own profile (id, email, name). `userId` is injected by the MCP+ * 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).+ */+ export async function getCurrentUser(+ client: SupabaseClient<Database>,+ userId: string+ ) {+ return client+ .from("user")+ .select("id, email, firstName, lastName, fullName, avatarUrl")+ .eq("id", userId)+ .single();+ }++ export async function getAttributes(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string,+ isPublic: boolean+ ) {+ return client+ .from("userAttributeCategory")+ .select(+ `id, name, emoji, companyId,+ userAttribute(id, name, listOptions, canSelfManage,+ attributeDataType(id, isBoolean, isDate, isNumeric, isText, isUser, isFile),+ userAttributeValue(+ id, valueBoolean, valueDate, valueNumeric, valueText, valueUser, valueFile+ )+ )`+ )+ .eq("companyId", companyId)+ .eq("public", isPublic)+ .eq("active", true)+ .eq("userAttribute.active", true)+ .eq("userAttribute.userAttributeValue.userId", userId)+ .order("sortOrder", { foreignTable: "userAttribute", ascending: true });+ }++ export async function getPrivateAttributes(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return getAttributes(client, userId, companyId, false);+ }++ export async function getPublicAttributes(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return getAttributes(client, userId, companyId, true);+ }++ export async function getAllAttributeCategories(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: string+ ) {+ return client+ .from("userAttributeCategory")+ .select(+ `id, name, emoji, companyId,+ userAttribute(id, name, listOptions, canSelfManage,+ attributeDataType(id, isBoolean, isDate, isNumeric, isText, isUser, isFile),+ userAttributeValue(+ id, valueBoolean, valueDate, valueNumeric, valueText, valueUser, valueFile+ )+ )`+ )+ .eq("companyId", companyId)+ .eq("active", true)+ .eq("userAttribute.active", true)+ .eq("userAttribute.userAttributeValue.userId", userId)+ .order("sortOrder", { foreignTable: "userAttribute", ascending: true });+ }++ export async function getAttributeCategoryWithValues(+ client: SupabaseClient<Database>,+ categoryId: string,+ userId: string,+ companyId: string+ ) {+ return client+ .from("userAttributeCategory")+ .select(+ `id, name, emoji, companyId, public,+ userAttribute(id, name, listOptions, canSelfManage,+ attributeDataType(id, isBoolean, isDate, isNumeric, isText, isUser, isFile),+ userAttributeValue(+ id, valueBoolean, valueDate, valueNumeric, valueText, valueUser, valueFile+ )+ )`+ )+ .eq("id", categoryId)+ .eq("companyId", companyId)+ .eq("active", true)+ .eq("userAttribute.active", true)+ .eq("userAttribute.userAttributeValue.userId", userId)+ .order("sortOrder", { foreignTable: "userAttribute", ascending: true })+ .single();+ }++ /** Avatars are changed through `account.avatar.update`, which checks the path. */+ export async function updateAvatar(+ client: SupabaseClient<Database>,+ userId: string,+ avatarUrl: string | null+ ) {+ return client+ .from("user")+ .update(+ sanitize({+ avatarUrl+ })+ )+ .eq("id", userId);+ }++ export async function updatePublicAccount(+ client: SupabaseClient<Database>,+ account: {+ id: string;+ firstName: string;+ lastName: string;+ about?: string;+ phone?: string;+ }+ ) {+ return client.from("user").update(sanitize(account)).eq("id", account.id);+ }++ /** Values are set through `upsertAttributeValue`, which checks who may. */+ export async function upsertUserAttributeValue(+ client: SupabaseClient<Database>,+ update: {+ userAttributeValueId?: string | undefined;+ userAttributeId: string;+ value: boolean | string | number;+ type: string;+ userId: string;+ updatedBy: string;+ }+ ) {+ const {+ userAttributeValueId,+ userAttributeId,+ value,+ type,+ userId,+ updatedBy+ } = update;++ let valueUpdate: Record<string, number | string | boolean> = {};++ if (type === "boolean" && typeof value === "boolean") {+ valueUpdate = { valueBoolean: value };+ }++ if (type === "date" && typeof value === "string") {+ valueUpdate = { valueDate: value };+ }++ if (type === "list" && typeof value === "string") {+ valueUpdate = { valueText: value };+ }++ if (type === "numeric" && typeof value === "number") {+ valueUpdate = { valueNumeric: value };+ }++ if (type === "text" && typeof value === "string") {+ valueUpdate = { valueText: value };+ }++ if (type === "user" && typeof value === "string") {+ valueUpdate = { valueUser: value };+ }++ if (type === "customer" && typeof value === "string") {+ valueUpdate = { valueText: value };+ }++ if (type === "supplier" && typeof value === "string") {+ valueUpdate = { valueText: value };+ }++ if (type === "file" && typeof value === "string") {+ valueUpdate = { valueFile: value };+ }++ if (userAttributeValueId) {+ return client+ .from("userAttributeValue")+ .update({+ ...valueUpdate,+ updatedBy+ })+ .eq("id", userAttributeValueId)+ .select("id")+ .single();+ } else {+ return client+ .from("userAttributeValue")+ .insert({+ userAttributeId,+ ...valueUpdate,+ userId,+ createdBy: updatedBy+ })+ .select("id")+ .single();+ }+ }++ const CHANGELOG_CACHE_KEY = "changelog:latest";++ const CHANGELOG_CACHE_TTL_SECONDS = 300;++ export async function getCachedChangelogPanelEntry(): Promise<ChangelogPanelEntry | null> {+ const cached = await redis.get(CHANGELOG_CACHE_KEY);+ if (cached) return JSON.parse(cached) as ChangelogPanelEntry;++ const entry = await getChangelogPanelEntry(getCarbonServiceRole());+ if (entry) {+ await redis.set(+ CHANGELOG_CACHE_KEY,+ JSON.stringify(entry),+ "EX",+ CHANGELOG_CACHE_TTL_SECONDS+ );+ }+ return entry;+ }++ /**+ * Whether the caller may change `userId`'s value of an attribute: anyone with+ * resources update may change anyone's; others only their own, of an+ * attribute people manage themselves.+ */+ export async function refuseAttributeValueChange(+ ctx: ServiceContext,+ userId: string,+ userAttributeId: string,+ refusal: string+ ) {+ if (ctx.can({ update: "resources" })) return null;+ if (ctx.auditUserId !== userId) return ctx.error("forbidden", refusal);++ const attribute = await getAttribute(ctx.asCaller.supabase, userAttributeId);+ if (attribute.error) {+ return ctx.error("internal", "Failed to get attribute", attribute.error);+ }+ if (!attribute.data?.canSelfManage) return ctx.error("forbidden", refusal);+ return null;+ }++++// --- Bulk actions of the Employees table --------------------------------++// The action routes call the `queue*` functions with the selected users; the++// background bulk-action job (`~/utils/table-jobs.server`) first narrows each++// chunk of matching users with `selectUsersForBulkAction`, then calls them.++++/** Queues the `user-admin` deactivate job for each user. */++export async function queueUserDeactivations(args: {++ userIds: string[];++ companyId: string;++ actorId: string;++ ip?: string;++}) {++ await batchTrigger(++ "user-admin",++ args.userIds.map((id) => ({++ payload: {++ id,++ type: "deactivate" as const,++ companyId: args.companyId,++ actorId: args.actorId,++ ip: args.ip++ }++ }))++ );++}++++/** Queues the `user-admin` resend-invite job for each user. */++export async function queueInviteResends(args: {++ userIds: string[];++ companyId: string;++ location: string;++ ip: string;++}) {++ await batchTrigger(++ "user-admin",++ args.userIds.map((id) => ({++ payload: {++ id,++ type: "resend" as const,++ companyId: args.companyId,++ location: args.location,++ ip: args.ip++ }++ }))++ );++}++++/** Queues the `update-permissions` job for each user. */++export async function queuePermissionUpdates(args: {++ userIds: string[];++ companyId: string;++ actorId: string;++ permissions: Record<++ string,++ { view: boolean; create: boolean; update: boolean; delete: boolean }++ >;++ addOnly: boolean;++ ip?: string;++}) {++ await batchTrigger(++ "update-permissions",++ args.userIds.map((id) => ({++ payload: {++ id,++ permissions: args.permissions,++ addOnly: args.addOnly,++ companyId: args.companyId,++ actorId: args.actorId,++ ip: args.ip++ }++ }))++ );++}++++/**++ * The users a bulk action on the Employees table may act on, from the ids++ * the background job read from the list: employees of the company only, by++ * the table's own rule (`canBulkActOnUser`). Reads with the service role, as++ * the action routes and the jobs they queue do, always scoped to the company.++ */++export async function selectUsersForBulkAction(args: {++ action: BulkUserAction;++ userIds: string[];++ companyId: string;++ actorId: string;++}): Promise<{ allowed: string[]; skipped: number }> {++ const serviceRole = getCarbonServiceRole();++ const ids = [...new Set(args.userIds)];++ const rows: {++ id: string | null;++ active: boolean | null;++ email: string | null;++ }[] = [];++ for (const chunk of chunkArray(ids, 100)) {++ const employees = await serviceRole++ .from("employees")++ .select("id, active, email")++ .in("id", chunk)++ .eq("companyId", args.companyId);++ if (employees.error) {++ logger.error("Failed to load the users of a bulk action", {++ companyId: args.companyId,++ error: employees.error++ });++ throw new Error("Failed to load the users of a bulk action");++ }++ rows.push(...employees.data);++ }++++ let unrevokedInviteEmails = new Set<string>();++ if (args.action === "invite") {++ const emails = rows.flatMap((row) => (row.email ? [row.email] : []));++ for (const chunk of chunkArray(emails, 100)) {++ const invites = await serviceRole++ .from("invite")++ .select("email")++ .in("email", chunk)++ .eq("companyId", args.companyId)++ .is("acceptedAt", null)++ .is("revokedAt", null);++ if (invites.error) {++ logger.error("Failed to load the invites of a bulk action", {++ companyId: args.companyId,++ error: invites.error++ });++ throw new Error("Failed to load the invites of a bulk action");++ }++ unrevokedInviteEmails = new Set([++ ...unrevokedInviteEmails,++ ...invites.data.map((invite) => invite.email)++ ]);++ }++ }++++ const context = { actorId: args.actorId, unrevokedInviteEmails };++ const allowed = rows++ .filter((row) => canBulkActOnUser(args.action, row, context))++ .flatMap((row) => (row.id ? [row.id] : []));++ return { allowed, skipped: ids.length - allowed.length };++}diff --cc apps/erp/app/modules/workflows/workflows.service.tsindex 561b94ca7e,87dd1105fe..14b5cfc99f--- a/apps/erp/app/modules/workflows/workflows.service.ts+++ b/apps/erp/app/modules/workflows/workflows.service.ts@@@ -2,20 -2,31 +2,36 @@@// 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 { ServiceContext } from "@carbon/api/service-fn.server";import type { Database, Json } from "@carbon/database";+import { fetchAllByIds } from "@carbon/database";import { fkDisplayRegistry } from "@carbon/database/audit.config";+ import type { Kysely, KyselyDatabase } from "@carbon/database/client";+ import { defaultUpgradeMessage, resolveRequirement } from "@carbon/ee/plan";+ import { companyHasFeature } from "@carbon/ee/plan.server";+ import type { CompanyLock, WorkflowIssue } from "@carbon/ee/workflows";+ import {+ createWorkflowCatalog,+ readWorkflowVersion,+ syncWorkflowTriggers,+ validateDefinition+ } from "@carbon/ee/workflows";+ import { requireWorkflowsEntitlement } from "@carbon/ee/workflows.server";+ import { trigger } from "@carbon/jobs";+ import { getLogger } from "@carbon/logger";import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+ import { sql } from "kysely";import type { z } from "zod";-import type { Filter, GenericQueryFilters } from "~/utils/query";-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";+import type { Filter, GenericQueryFilters, Paging } from "~/utils/query";+import { listCount, setGenericQueryFilters } from "~/utils/query";import type { workflowValidator } from "./workflows.models";+ import { MAX_RUN_STEPS } from "./workflows.utils";+export const WORKFLOWS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+export async function getWorkflows(client: SupabaseClient<Database>,companyId: string,diff --cc apps/erp/app/routes/api+/inngest.tsindex af2a77e80e,2406881b30..2ec96d891b--- a/apps/erp/app/routes/api+/inngest.ts+++ b/apps/erp/app/routes/api+/inngest.ts@@@ -17,7 -12,7 +17,8 @@@ import} from "@carbon/logger/tracing.server";import { serve } from "inngest/remix";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { tableJobHandlers } from "~/utils/table-jobs.server";+ import { scopesFromPermissions } from "./v1+/lib/base.server";import { callOperation } from "./v1+/lib/call.server";const logger = getLogger("erp", "inngest");@@@ -46,12 -40,19 +47,20 @@@ const functionIds = new Setlet dispatchWired = false;function wireWorkflowDispatch() {if (dispatchWired) return;- // A running workflow acts as its already-authorized owner; the per-operation- // scope gate applies to API keys only.- setWorkflowDispatch((name, context, args) =>- callOperation(name, { ...context, authKind: "session", scopes: {} }, args)+ // A running workflow acts as its owner, so the operation's permission is+ // checked against the owner's permissions, read for this run.+ setWorkflowDispatch((name, { permissions, ...context }, args) =>+ callOperation(+ name,+ {+ ...context,+ authKind: "session",+ scopes: scopesFromPermissions(permissions, context.companyId)+ },+ args+ ));+ setTableJobHandlers(tableJobHandlers);dispatchWired = true;}diff --cc apps/erp/app/routes/api+/integrations.$id.sync-activity.tsindex 09690e5ed5,0000000000..84d48464ffmode 100644,000000..100644--- a/apps/erp/app/routes/api+/integrations.$id.sync-activity.ts+++ b/apps/erp/app/routes/api+/integrations.$id.sync-activity.ts@@@ -1,79 -1,0 +1,79 @@@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { requirePermissions } from "@carbon/auth/auth.server";+import { integrations as availableIntegrations } from "@carbon/ee";+import {+ getSyncOperations,+ SyncOperationStatusSchema+} from "@carbon/ee/accounting";+import { getLogger } from "@carbon/logger";+import type { LoaderFunctionArgs } from "react-router";- import { withSyncOperationReferences } from "~/modules/settings/settings.server";++import { withSyncOperationReferences } from "~/modules/settings/settings.service";+import { SYNC_ACTIVITY_SORTS } from "~/modules/settings/ui/Integrations/SyncActivity";+import { decodeCursor, toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/list-error";+import { PAGE_SIZE } from "~/utils/pagination";++const logger = getLogger("erp", "integrations-sync-activity");++/**+ * GET — the Sync Activity rows after `?after=` (the previous page's last row),+ * under the tab's status filter (`?status=`). The Sync Activity tab loads+ * them as it scrolls (`useInfiniteRows` with this URL as its `pageUrl`), and+ * re-reads the loaded pages after a revalidation. Gated like the tab itself.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const integration = availableIntegrations.find(+ (candidate) => candidate.id === params.id+ );+ if (!integration) {+ throw new Response("Integration not found", { status: 404 });+ }++ const searchParams = new URL(request.url).searchParams;+ const status = SyncOperationStatusSchema.safeParse(+ searchParams.get("status")+ );+ const cursor = decodeCursor(searchParams.get("after"));+ const createdAt = cursor?.values[0];+ if (!cursor || typeof createdAt !== "string") {+ // A failed page, not a thrown response: the tab shows its own retry+ // row, where a thrown response would replace the page.+ logger.warn("Sync activity page cursor is not valid", { companyId });+ return listErrorPage("operations");+ }++ // One extra row tells whether a next page exists.+ const operations = await getSyncOperations(client, {+ companyId,+ integration: integration.id,+ status: status.success ? status.data : undefined,+ after: { createdAt, id: cursor.id },+ limit: PAGE_SIZE + 1+ });++ if (operations.error) {+ logger.error("Failed to load sync operations", {+ companyId,+ integration: integration.id,+ error: operations.error+ });+ return listErrorPage("operations");+ }++ const page = toPage(operations.data, {+ limit: PAGE_SIZE,+ sorts: SYNC_ACTIVITY_SORTS+ });++ return {+ operations: await withSyncOperationReferences(client, companyId, page.rows),+ nextCursor: page.nextCursor+ };+}diff --cc apps/erp/app/routes/api+/link.tsindex 69cc60965d,6226532f18..12a94c83a1--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@@ -5,16 -5,131 +5,16 @@@import { requirePermissions } from "@carbon/auth/auth.server";import { getCompanyId, setCompanyId } from "@carbon/auth/company.server";import { updateCompanySession } from "@carbon/auth/session.server";-import type { Database } from "@carbon/database";-import {- NotificationEvent,- type RecurringInvoicingDocumentType-} from "@carbon/notifications";+import type { NotificationEvent } from "@carbon/notifications";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";- import { getCompanies } from "~/modules/settings";+ import { getCompanies } from "~/modules/settings/settings.service";-import { getRecordPath } from "~/utils/entity";+import {+ type NotificationDocumentType,+ notificationTarget+} from "~/utils/notification-target";import { path } from "~/utils/path";-type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];-/** The approvable document of an Approval* event, or what a Recurring- * invoicing notification lists. */-type NotificationDocumentType =- | ApprovalDocumentType- | RecurringInvoicingDocumentType;--function resolve(- event: NotificationEvent,- documentId: string,- documentType?: NotificationDocumentType-): string | null {- switch (event) {- case NotificationEvent.TrainingAssignment:- case NotificationEvent.TrainingReminder: {- // documentId is a trainingAssignment id; the recipient is the trainee,- // so land on the completion page (same target as the topbar row).- return path.to.completeTrainingAssignment(documentId);- }- case NotificationEvent.ResourceTrainingAssignment: {- // documentId is a training id; land on the training viewer (same- // target as the topbar row).- return path.to.training(documentId);- }- case NotificationEvent.JobAssignment:- case NotificationEvent.JobCompleted:- case NotificationEvent.JobsProjectedLate:- return path.to.job(documentId);- case NotificationEvent.JobOperationAssignment:- case NotificationEvent.JobOperationMessage: {- const [jobId, operationId, makeMethodId, materialId] =- documentId.split(":");- if (!jobId || !operationId || !makeMethodId) return null;- const link = materialId- ? path.to.jobMakeMethod(jobId, makeMethodId)- : path.to.jobMethod(jobId, makeMethodId);- return `${link}?selectedOperation=${operationId}`;- }- case NotificationEvent.PurchaseInvoiceAssignment:- return path.to.purchaseInvoice(documentId);- case NotificationEvent.PurchaseOrderAssignment:- return path.to.purchaseOrder(documentId);- case NotificationEvent.QuoteAssignment:- case NotificationEvent.QuoteExpired:- case NotificationEvent.DigitalQuoteResponse:- return path.to.quote(documentId);- case NotificationEvent.SupplierQuoteAssignment:- case NotificationEvent.SupplierQuoteResponse:- return path.to.supplierQuote(documentId);- case NotificationEvent.SalesOrderAssignment:- return path.to.salesOrder(documentId);- case NotificationEvent.PurchasingRfqAssignment:- return path.to.purchasingRfq(documentId);- case NotificationEvent.SalesRfqAssignment:- case NotificationEvent.SalesRfqReady:- return path.to.salesRfq(documentId);- case NotificationEvent.SalesRuleViolation: {- // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"- const [docType, docId] = documentId.split(":");- if (!docId) return null;- return docType === "salesInvoice"- ? path.to.salesInvoice(docId)- : docType === "salesOrder"- ? path.to.salesOrder(docId)- : path.to.quote(docId);- }- case NotificationEvent.MaintenanceDispatchAssignment:- case NotificationEvent.MaintenanceDispatchCreated:- return path.to.maintenanceDispatch(documentId);- case NotificationEvent.GaugeCalibrationExpired:- return path.to.gauge(documentId);- case NotificationEvent.NonConformanceAssignment:- return path.to.issue(documentId);- case NotificationEvent.ChangeNoticeStarted:- case NotificationEvent.ChangeNoticeImplementation:- case NotificationEvent.ChangeNoticeDone:- return path.to.changeNoticeDetails(documentId);- case NotificationEvent.RiskAssignment:- return path.to.risk(documentId);- case NotificationEvent.ProcedureAssignment:- return path.to.procedure(documentId);- case NotificationEvent.StockTransferAssignment:- return path.to.stockTransfer(documentId);- case NotificationEvent.PickingListAssignment:- return path.to.pickingList(documentId);- case NotificationEvent.SuggestionResponse:- return path.to.suggestion(documentId);- case NotificationEvent.RecurringInvoicing:- // documentId is only the digest's first invoice; land on the list it- // is about (same target as the topbar row): the lease drafts waiting- // for the buyer, else the sales invoices that need review.- return documentType === "purchaseInvoice"- ? `${path.to.invoicingPurchasing}?filter=status:eq:Draft`- : `${path.to.invoicingSales}?filter=needsReview:eq:true`;- case NotificationEvent.LeaseCriticalDate:- return path.to.leaseDetails(documentId);- case NotificationEvent.Workflow:- return getRecordPath(documentType, documentId);- case NotificationEvent.ApprovalApproved:- case NotificationEvent.ApprovalRejected:- case NotificationEvent.ApprovalRequested:- if (documentType === "purchaseOrder")- return path.to.purchaseOrder(documentId);- if (documentType === "qualityDocument")- return path.to.qualityDocument(documentId);- if (documentType === "supplier") return path.to.supplier(documentId);- if (documentType === "changeOrder")- return path.to.changeNoticeDetails(documentId);- return null;- default:- return null;- }-}-export async function loader({ request }: LoaderFunctionArgs) {const {client,diff --cc apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex cf590b961c,9851b4fb9e..73ba4960b6--- 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,1561 -1,1622 +1,1622 @@@{- "totalTools": 1555,- "modules": 15,+ "totalTools": 1616,+ "modules": 14,"tools": [- {"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},- {"name":"account_getAccount","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"8adb0e14ee10","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAllAttributeCategories","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAttributeCategoryWithValues","classification":"READ","paramCount":1,"schema":"34d65afdb82e","response":"32112b6759f8","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAttributes","classification":"READ","paramCount":1,"schema":"f69289b8004c","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getCurrentUser","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ddc730821e71","injectAuth":"companyId","permission":"none","paginates":false},- {"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","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_closePeriodWithChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyGroupId+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},- {"name":"accounting_createIntercompanyTransaction","classification":"WRITE","paramCount":8,"schema":"9c3c11f4059c","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"accounting_createJournalEntry","classification":"WRITE","paramCount":5,"schema":"64ec8566cc56","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_deleteAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"ecb746f60913","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteAccountingPeriod","classification":"DESTRUCTIVE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteCostCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"f8a3e6fec03f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteDepreciationRun","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteDimension","classification":"DESTRUCTIVE","paramCount":1,"schema":"96e5d0fb89ae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteExchangeRateOverride","classification":"DESTRUCTIVE","paramCount":1,"schema":"cc2bce783cc5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"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_deletePaymentTerm","classification":"DESTRUCTIVE","paramCount":1,"schema":"5386fbcf056f","response":"bcde375ebd4c","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,"context":"updatedBy=userId"},- {"name":"accounting_deleteReportView","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","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},- {"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"35b79c87221a","response":"faf531dd8b9a","injectAuth":"companyId","permission":"accounting:view","paginates":true},- {"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getAccountsInScope","classification":"READ","paramCount":2,"schema":"44ea072844d3","response":"4c52cef1b6ab","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountsList","classification":"READ","paramCount":3,"schema":"7592bd05f71d","response":"05b2ffc4c3d4","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getActiveDimensionsWithValues","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1bfc101ae1de","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAssetDepreciationHistory","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"00c2fc9fdb8b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getBaseCurrency","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"11af3b92d80f","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getBaseCurrencyDecimalPlaces","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"cddf8275afa1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getChartOfAccounts","classification":"READ","paramCount":3,"schema":"b3b2e96654e5","response":"f561243f144b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCompaniesInGroup","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"032bba337af7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getConsolidatedBalances","classification":"READ","paramCount":4,"schema":"966a7b50605d","response":"a74dd3597c00","injectAuth":"companyId","permission":"accounting:view","paginates":false,"context":"eliminationClient=client"},- {"name":"accounting_getConsolidatedPeriodSeries","classification":"READ","paramCount":3,"schema":"2e20e5d2d7f5","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false,"context":"eliminationClient=client"},- {"name":"accounting_getCostCenter","classification":"READ","paramCount":1,"schema":"f8a3e6fec03f","response":"f7b898d20847","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCostCenters","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a27593ffa2de","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getCostCentersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCostCentersTree","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b4505b9334e6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrencies","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1d6055ff487c","injectAuth":"companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getCurrenciesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"01628a6ebd21","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrency","classification":"READ","paramCount":1,"schema":"0e98c276626d","response":"6d5bae3dafd5","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrencyByCode","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"300e136d14d0","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrentAccountingPeriod","classification":"READ","paramCount":1,"schema":"2f19cae7bae1","response":"923d00cf55d7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDefaultAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8460f8427611","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDeferredRevenueWaterfall","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"6ba817c304ae","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"22ccbb1556ab","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRunLines","classification":"READ","paramCount":1,"schema":"e83946bf5ea7","response":"9c31ce726755","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRuns","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"8896184e60b3","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getDimension","classification":"READ","paramCount":1,"schema":"96e5d0fb89ae","response":"e869e1d37e76","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDimensionPivot","classification":"READ","paramCount":6,"schema":"4dc617d84588","response":"c7069f830357","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getDimensionPivotLines","classification":"READ","paramCount":17,"schema":"6f74597ffe85","response":"100f0689af3e","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDimensions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9beb5210c60e","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getExchangeRate","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"cddf8275afa1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getExchangeRateHistory","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"ab784d246338","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getExchangeRates","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7089bfe7df7a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFinancialStatementBalances","classification":"READ","paramCount":3,"schema":"267691af8c66","response":"f561243f144b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFinancialStatementPeriodSeries","classification":"READ","paramCount":3,"schema":"27a6e6386ed2","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFiscalCalendarCommitted","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"854b90f7a9d3","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFiscalYearSettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a18729ffcd7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAsset","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"faea7eb49dc8","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetCipCosts","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"03707172e0ba","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetClass","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"8442dd4440a1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetClasses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"03a52bf94953","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getFixedAssetClassesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"123f9f4a60f8","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetDisposal","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"4b37a6513b87","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssets","classification":"READ","paramCount":4,"schema":"98a82364580e","response":"883d15b0ec6d","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getFixedAssetsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetsListForSale","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetTransfers","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"e88320352e28","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetUsageLogs","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"517f4c28c365","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFleetAssets","classification":"READ","paramCount":4,"schema":"e83739fdf2bc","response":"8735b01a7188","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getGroupAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a9a2c5be8164","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyBalance","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f2f76b33a3df","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyEliminationLines","classification":"READ","paramCount":1,"schema":"b9efe4d053a7","response":"eb31d414081e","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"db142abe3913","response":"2c3abae21f4b","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"85098b9cb044","response":"80e3b322d07f","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f3fc6aeda32d","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_getLeaseLiabilities","classification":"READ","paramCount":3,"schema":"a9d65afee96d","response":"none","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getLeaseNetInvestment","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"93c82b571cea","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getOrCreateAccountingPeriod","classification":"WRITE","paramCount":2,"schema":"ced53a5f76ed","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":"c61cae75d189","response":"7e3500d5e372","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getPaymentTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodCloseChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"032d2a02eff5","injectAuth":"companyGroupId+companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_getPeriodCloseReadiness","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"d8b254beff31","injectAuth":"companyGroupId+companyId+userId","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},- {"name":"accounting_getPeriodRunRelatedItems","classification":"READ","paramCount":2,"schema":"533dc47fe01c","response":"311f6360747c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getProject","classification":"READ","paramCount":1,"schema":"8e1d73142851","response":"b9294ccc5a24","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getProjects","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"48b654f2a9fa","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getPurchaseLinePivot","classification":"READ","paramCount":4,"schema":"53729b2674ee","response":"c7069f830357","injectAuth":"companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getPurchaseLinePivotLines","classification":"READ","paramCount":10,"schema":"d23c9f2398a4","response":"a12b8efe2d62","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRentalUtilization","classification":"READ","paramCount":3,"schema":"696a375a604f","response":"80fa6e3c40ad","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getReportPins","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3536c9c9a314","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getReportViews","classification":"READ","paramCount":1,"schema":"f60ae5d8a496","response":"7f6aad3009db","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fb8cbba30867","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRunLines","classification":"READ","paramCount":1,"schema":"8245d2d4cee4","response":"beb79b629050","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRuns","classification":"READ","paramCount":2,"schema":"cde27bc67b4d","response":"2c5b3de7d4b3","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getRevenueSchedules","classification":"READ","paramCount":4,"schema":"a9a93466d158","response":"029139d6955a","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getScrapAccountIds","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getTrialBalance","classification":"READ","paramCount":2,"schema":"3eb7f553b21b","response":"e782cb2b76dc","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getUnderConstructionAssets","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b6f3d669374f","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getWorkCenterCapitalCost","classification":"READ","paramCount":1,"schema":"7f43ff7a4fc5","response":"e74388b72851","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_insertDepreciationRun","classification":"DESTRUCTIVE","paramCount":3,"schema":"9d4a1dd5e184","response":"70d7ca41be81","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_insertFixedAsset","classification":"WRITE","paramCount":18,"schema":"c3e581918995","response":"e0e9c463a967","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_invokeAssetTransfer","classification":"WRITE","paramCount":1,"schema":"1b261cefaeea","response":"c84f5bab4f4d","injectAuth":"companyId+userId","permission":"accounting:update","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_returnFixedAssetToService","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","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":"c1d59a9ba1ff","response":"8394fbabd845","injectAuth":"companyGroupId+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_setFixedAssetOutOfService","classification":"WRITE","paramCount":3,"schema":"5e6414b4286b","response":"3797626bd17e","injectAuth":"companyId+updatedBy","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_unlockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_updateDefaultAccounts","classification":"WRITE","paramCount":65,"schema":"82c94cd371e9","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":17,"schema":"9f8fa39b1799","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_upsertAccount","classification":"WRITE","paramCount":10,"schema":"0b4871d25164","response":"3797626bd17e","injectAuth":"companyGroupId+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":"companyGroupId+companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertDimension","classification":"DESTRUCTIVE","paramCount":2,"schema":"820eea627efe","response":"660c8bead643","injectAuth":"companyGroupId+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_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":"394fe1eaa481","response":"b8ded59f5c56","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"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_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":"a07a74ca3dd1","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":"8f9f1309d9dd","response":"806ff23e9acc","injectAuth":"companyId","permission":"documents:view","paginates":true,"defaults":"always"},- {"name":"documents_insertDocumentExtraction","classification":"WRITE","paramCount":4,"schema":"790f2b883984","response":"d181256b2684","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+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":"baa524ddff70","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"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_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},- {"name":"inventory_deleteShipmentLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"84320a09c1ac","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteShippingMethod","classification":"DESTRUCTIVE","paramCount":1,"schema":"493e990b5f3d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStockTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"38111ae0fa2a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStockTransferLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"0bbd6a946791","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"210a2a62676d","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageUnitCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteWarehouseTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"d51f098ead24","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteWarehouseTransferLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"d99fddf5e39e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_expandStorageUnitIdsWithDescendants","classification":"WRITE","paramCount":1,"schema":"f413382980a7","response":"681004346c78","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_generateInventoryCountLines","classification":"DESTRUCTIVE","paramCount":4,"schema":"7cf62698d5f8","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_generatePickingList","classification":"DESTRUCTIVE","paramCount":4,"schema":"412bd8dbff31","response":"81802516b555","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_getAvailableTrackedEntities","classification":"READ","paramCount":6,"schema":"6a561d222e27","response":"723554a256de","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getBatchNumbersForItem","classification":"READ","paramCount":2,"schema":"786c6e7af03b","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getBatchProperties","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"9a2b986c906d","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getDefaultStorageUnitForJob","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"174e29b899b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getDefaultStorageUnitOrStorageUnitWithHighestQuantity","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"174e29b899b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getEffectiveWorkCenterId","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"00404e686415","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCount","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b707251b11c4","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCountLines","classification":"READ","paramCount":2,"schema":"65abbb307e1c","response":"e4219573b12b","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryCountLineSummary","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"7a06e37fcf2a","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCountMovements","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"eba78a8fe017","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"43536f2bda72","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryItems","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"5baddb3a890c","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryItemsCount","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"8394fbabd845","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"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":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerBalance","classification":"READ","paramCount":3,"schema":"33e76470e057","response":"cddf8275afa1","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"7ef5489d0abf","response":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":true},- {"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"2fd5e28a7273","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getKanbanProjectedQuantities","classification":"READ","paramCount":1,"schema":"eb1d8d941f5f","response":"98903cc375ce","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"87bc6f56aff6","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"none","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"b3ab0a2018d9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListRecommendations","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"24283057a15d","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListRelatedItems","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"74c025dd5c02","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingLists","classification":"READ","paramCount":6,"schema":"c17334a443b6","response":"2112d9a1ea1d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getPickingSchedule","classification":"READ","paramCount":2,"schema":"b3a9deeaf0d0","response":"19467666efcd","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickOrder","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"7fa0311f0d0a","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPicksByJobMaterial","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b53992cb5f0c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceipt","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"b7c00288df9c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"15b7b17f7652","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptLineTracking","classification":"READ","paramCount":1,"schema":"17337505bb69","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptRelatedItems","classification":"READ","paramCount":2,"schema":"bc54dac2bca6","response":"0f4d8e489d1b","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceipts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4aa48aba067d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getReceiptTracking","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getRentalReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"2e9dfef414a9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getRentalShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1ab616adb2e0","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getSerialNumbersForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShelfLifeForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"4c5d680d898e","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipment","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"cf99c31d666e","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1b1f740f30c6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLinesWithDetails","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c158915aa9b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLineTracking","classification":"READ","paramCount":1,"schema":"84320a09c1ac","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentRelatedItems","classification":"READ","paramCount":2,"schema":"f81a81d39efa","response":"0e975679737c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92c56e0fa40a","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getShipmentTracking","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingMethod","classification":"READ","paramCount":1,"schema":"493e990b5f3d","response":"65413dd34c52","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingMethods","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"104aa0df039d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getShippingMethodsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","paramCount":1,"schema":"a40494d32d29","response":"2e1967d88231","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockMovements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"eba78a8fe017","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStockTransfer","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"69c0eeefc47c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransferLine","classification":"READ","paramCount":1,"schema":"0bbd6a946791","response":"a34287fc1477","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransferLines","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"bcb01288cc29","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransfers","classification":"READ","paramCount":4,"schema":"acb88488ed54","response":"a0e62ff2e059","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStockTransferTracking","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"20f8627b948f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4bbb50609deb","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"28837d034643","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageTypeUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnit","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"a5bf237a9aeb","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitChildren","classification":"READ","paramCount":1,"schema":"06f6e8f8f9f5","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitDescendants","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"3bae190e2656","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitParentIdsWithChildren","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"681004346c78","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitRoots","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageUnits","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageUnitsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitsListForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitsTreeForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ecdf2c570468","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitSubtrees","classification":"READ","paramCount":3,"schema":"c5258b49b1b9","response":"2b4ed272b37a","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitTree","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"3bae190e2656","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntities","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getTrackedEntitiesByMakeMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntitiesByOperationId","classification":"READ","paramCount":1,"schema":"c407a9edb930","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntity","classification":"READ","paramCount":1,"schema":"5d58d420052a","response":"d485710baf81","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntityExpirations","classification":"READ","paramCount":1,"schema":"2d3f4e6f5875","response":"fff84b1ee888","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getUnresolvedPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"ce45e49e333f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransfer","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"2234f62ec519","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferLine","classification":"READ","paramCount":2,"schema":"31f24bda931b","response":"945dc2c1255f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferLines","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"8a92aaed64aa","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferRelatedItems","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"4f08c7c15b92","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransfers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"66ec9f5f0ca8","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_insertInventoryCount","classification":"WRITE","paramCount":6,"schema":"f9ea90011f9a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertManualInventoryAdjustment","classification":"WRITE","paramCount":12,"schema":"dc3fda774cf4","response":"baa524ddff70","injectAuth":"companyId+createdBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertStockTransfer","classification":"DESTRUCTIVE","paramCount":4,"schema":"623ca286b237","response":"910187eb9b58","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertWarehouseTransfer","classification":"WRITE","paramCount":9,"schema":"b92377ee6a4f","response":"8e9431d157a2","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_mergeTrackedEntities","classification":"WRITE","paramCount":2,"schema":"b12fee74a91e","response":"none","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_pickPickingListLine","classification":"WRITE","paramCount":3,"schema":"0371c6fecc9c","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_reconcileReceiptSerialEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"317d393d5b4a","response":"none","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","paramCount":2,"schema":"bf8906da76a5","response":"1ef4111538b5","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_setPickingListLineTrackedEntity","classification":"WRITE","paramCount":5,"schema":"a628dabab831","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_updateBatchPropertyOrder","classification":"WRITE","paramCount":3,"schema":"ed0f513719d1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"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,"context":"updatedBy=userId"},- {"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,"context":"updatedBy=userId"},- {"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":15,"schema":"bda2d2c1b9ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"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":"fd0848682b0b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"efe95221a775","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},- {"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"7e387955a4f8","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_createSalesInvoiceFromShipment","classification":"WRITE","paramCount":1,"schema":"2e39a760a5ca","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","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_getApAging","classification":"READ","paramCount":2,"schema":"9db366ef805c","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":"9db366ef805c","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},- {"name":"invoicing_getAvailableOnAccountCredit","classification":"READ","paramCount":1,"schema":"2bfa7d907171","response":"cddf8275afa1","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getAvailableOnAccountCreditSources","classification":"READ","paramCount":2,"schema":"b09149f439eb","response":"ec53cb4aa76b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getCharge","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4d45de90549b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getCharges","classification":"READ","paramCount":5,"schema":"3b1a78f3ef00","response":"a1c047af8dd8","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getCompanyHasOpenCredits","classification":"READ","paramCount":1,"schema":"ffed91643c1d","response":"7cb541e84f22","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getInvoiceSettlements","classification":"READ","paramCount":1,"schema":"bd163ca304cd","response":"5483e69d7515","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","paramCount":2,"schema":"9d6509fa2229","response":"a334c4e05d56","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemo","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"98fffe52edef","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemoApplications","classification":"READ","paramCount":1,"schema":"188417093a55","response":"8b54c25de723","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemos","classification":"READ","paramCount":7,"schema":"8f6810d90c81","response":"f38bef4be63d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":2,"schema":"da8678ca28c2","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getOpenReimbursementsForEmployee","classification":"READ","paramCount":2,"schema":"8c83e701c013","response":"84fe5db303b4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":2,"schema":"2d555b8aaf06","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPayment","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"300aea1db7cb","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"35b15cbf37ce","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPayments","classification":"READ","paramCount":8,"schema":"fc068ce64697","response":"e786785f266d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getPurchaseInvoice","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"656b64f44b73","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceDelivery","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"57af27aeef3b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceLine","classification":"READ","paramCount":1,"schema":"af656ed8709f","response":"3592330c8f34","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceLines","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"f8ce78976cce","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoices","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"e14efcf49a89","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getReimbursement","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c1191896ef6c","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getReimbursementRelatedItems","classification":"READ","paramCount":1,"schema":"1440dbb5599d","response":"b44573ee4608","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getReimbursements","classification":"READ","paramCount":5,"schema":"45f5b7cdee07","response":"9bad0fb8b063","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getSalesInvoice","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"9cd55ec5019e","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceCustomerDetails","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"d592e414f201","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceLine","classification":"READ","paramCount":1,"schema":"352db7d38a15","response":"b6cb6eeff636","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceLines","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"5b10b31c425e","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoices","classification":"READ","paramCount":4,"schema":"03a6ebc93561","response":"5b1a09dc9fa5","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getSalesInvoiceShipment","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"47c40e51a6e4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","paramCount":2,"schema":"d67008f41829","response":"5a23b05562f4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_insertPurchaseInvoice","classification":"DESTRUCTIVE","paramCount":15,"schema":"15dc8b208ca1","response":"24b4b1602470","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_insertSalesInvoice","classification":"DESTRUCTIVE","paramCount":14,"schema":"56c402cfa5a8","response":"24b4b1602470","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","paramCount":2,"schema":"66ab03790336","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false,"defaults":"always"},- {"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","paramCount":15,"schema":"304bf354aa67","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateReimbursement","classification":"WRITE","paramCount":8,"schema":"ff96110da3d7","response":"def495be96e6","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoice","classification":"WRITE","paramCount":15,"schema":"71a9939b9245","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"0369e0154c99","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertPayment","classification":"WRITE","paramCount":16,"schema":"f8f2180d8a3b","response":"1a922c685a61","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","paramCount":8,"schema":"02d98a1b8952","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_upsertPurchaseInvoiceLine","classification":"WRITE","paramCount":25,"schema":"e11776875976","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertReimbursementLines","classification":"DESTRUCTIVE","paramCount":2,"schema":"96f11ef83729","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertSalesInvoiceLine","classification":"WRITE","paramCount":24,"schema":"7cc1d479ebe7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertSalesInvoiceShipment","classification":"WRITE","paramCount":9,"schema":"9e9d7e8b568d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"items_activateMethodVersion","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"ec9aaaf82857","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},- {"name":"items_addChangeNoticeAffectedItem","classification":"DESTRUCTIVE","paramCount":5,"schema":"183209667024","response":"3cc309ba4541","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"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":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_copyMakeMethod","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"4e1a8f1febce","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":"59340adc1219","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},- {"name":"items_deleteChangeNoticeAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteChangeNoticeRequiredAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteChangeNoticeType","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationParameterGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationRule","classification":"DESTRUCTIVE","paramCount":2,"schema":"4eaf102cddd9","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItemCustomerPart","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItemPostingGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialDimension","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialFinish","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialForm","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialGrade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"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_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":"READ","paramCount":1,"schema":"2531dd68049b","response":"fab3ac9dac53","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},- {"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"none","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeDiff","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"4da0de080834","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeRequiredAction","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a76ce814b1b8","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeRequiredActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4c8439fedd7e","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticeRequiredActionsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNotices","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef2c88bb20cc","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticesForNonConformance","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"47b99abee3a5","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"d15ce193a0df","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4d341af72c49","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticeTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConfigurationParameters","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c36ad21b447b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConfigurationRules","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"530f6f787ce7","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConsumable","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"105e334bcf5b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConsumables","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"9302fcd8ff2d","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getConsumablesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getDemandForecastSources","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"4ef1c000e70f","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItem","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"87a9b87208d5","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemChangeNoticeData","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a9f8d291a4dd","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCost","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"38fa8e41fdd1","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"792b7c55b52e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"20b38721b145","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"ffefd03548aa","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemManufacturing","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemMpnsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3ff28fd20707","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPlanning","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"435390ae7550","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPostingGroup","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"d38ff3570b60","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPostingGroups","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5019b8dab137","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getItemPostingGroupsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"9fc7a6c9f2e3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemReplenishment","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemShelfLife","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a406f3a83a89","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemStockQuantitiesByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"96915ea19193","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemStorageUnitQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"880fa3aa7279","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersededBy","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8e2ea57c0664","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersession","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"0c693c4f3dcb","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersessionsForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"e06b6534cfe9","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupply","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"696523b54f52","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemUnitSalePrice","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"7281903c959e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getJobMaterialUsageForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"67faac8214ed","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMakeMethodById","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"cb9ae031b551","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMakeMethods","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"6cdfe33178ce","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterial","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"fce6ec47472d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimension","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"5a634d31e2f3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimensionList","classification":"READ","paramCount":2,"schema":"f614c4ca7d64","response":"b72364e0a391","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimensions","classification":"READ","paramCount":4,"schema":"9136faf13c9c","response":"98486ac80bcc","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFinish","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"07a225161151","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialFinishes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"04cf1f4f7909","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFinishList","classification":"READ","paramCount":1,"schema":"069f6f1436cd","response":"b57774d02b4d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialForm","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f69bdbb31d76","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialForms","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ca926bd97ca1","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFormsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a59b0ccd150e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGrade","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"07a225161151","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGradeList","classification":"READ","paramCount":1,"schema":"069f6f1436cd","response":"b57774d02b4d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGrades","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"04cf1f4f7909","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterials","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"5a10e7f3c854","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialSubstance","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f69bdbb31d76","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialSubstances","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ca926bd97ca1","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialSubstancesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a59b0ccd150e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0cc848ca86e3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialTypeList","classification":"READ","paramCount":2,"schema":"babec8528804","response":"c3dfbc0fdf89","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cbbbd5d9c38d","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"5bc3cafcb138","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"4f986471aaee","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodMaterials","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"16cb0357007c","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMethodMaterialsByMakeMethod","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"ed99eb62f33c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodOperations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"44cb9313b74c","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMethodOperationsByMakeMethodId","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"4ec7d6bf5468","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodTree","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"18cc03a418b4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodTreeArray","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"6481a47cef6d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getNextRevision","classification":"READ","paramCount":1,"schema":"96527a3bce32","response":"00404e686415","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenJobMaterials","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"3df5c33eb3a4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenProductionOrders","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"0de1519216f7","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"c53a83bc1272","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenSalesOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPart","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getParts","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"b134f22017b9","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getPartsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPartUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"e205f0dd9382","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPickMethod","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"781e7f3fc24f","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPickMethods","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f1260811ebd4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getRecipeProcessIdsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"681004346c78","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getService","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getServices","classification":"READ","paramCount":5,"schema":"4b3bc8e78cef","response":"0bc4d668f038","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getServicesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupersessionChain","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"57cd7c34e332","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartPriceBreaks","classification":"READ","paramCount":1,"schema":"0b5fc4acf371","response":"f4acc38f3c75","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartPricing","classification":"READ","paramCount":3,"schema":"12f5a9bff481","response":"6cefe4692145","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierParts","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"77be6c5a4141","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartsBySupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"8acf1878d779","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPriceBreaksForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc0d300695e0","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTool","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTools","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"2b6244653ec7","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getToolsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTopLevelProductsForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"b56efd7a527e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getUnitOfMeasure","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"124234df769c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getUnitOfMeasures","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e19fb7f07a6a","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"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":"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_resolveItemIdFromExtractedText","classification":"WRITE","paramCount":2,"schema":"a36b576f2400","response":"174e29b899b9","injectAuth":"companyId","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","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},- {"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","paramCount":2,"schema":"122c17a83964","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"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","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},- {"name":"items_updateItemCost","classification":"WRITE","paramCount":2,"schema":"c55de757a7e4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateItemMethodAndSourcing","classification":"WRITE","paramCount":3,"schema":"1165eb54378a","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},- {"name":"items_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"82322ed42796","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},- {"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":"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","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","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":14,"schema":"df41fcd1ce4f","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_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":"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":"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":"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":"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":"6be3bd248d68","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":"e780e7384b56","response":"87c54a97c0fa","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":11,"schema":"b7fbcd164308","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":"85315f99e855","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"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},- {"name":"people_createTimeCardEntry","classification":"WRITE","paramCount":4,"schema":"d88eff32bf40","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},- {"name":"people_deleteAttribute","classification":"DESTRUCTIVE","paramCount":1,"schema":"437fb5c5c303","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteAttributeCategory","classification":"DESTRUCTIVE","paramCount":1,"schema":"b773edae357b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteDepartment","classification":"DESTRUCTIVE","paramCount":1,"schema":"01883d2055a5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteHoliday","classification":"DESTRUCTIVE","paramCount":1,"schema":"9189cc10f756","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteShift","classification":"DESTRUCTIVE","paramCount":1,"schema":"fbdb1fa56a88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteTimeCardEntry","classification":"DESTRUCTIVE","paramCount":1,"schema":"c53dc26677e4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_getAttribute","classification":"READ","paramCount":1,"schema":"437fb5c5c303","response":"9c635d811516","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getAttributeCategories","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"64bbb296aaa1","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getAttributeCategory","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a52b87433b3b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getAttributeDataTypes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"dd6f3a6f89d0","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getClockedInEmployees","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getContacts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"de41996ed14c","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getDepartment","classification":"READ","paramCount":1,"schema":"01883d2055a5","response":"10600fcaa49e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getDepartments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"f483d2bc2259","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getDepartmentsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getDepartmentsTree","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8476e48a3c04","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeDepartments","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"94b797b98edf","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeJob","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"4a3b9b98079b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeShifts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"68279ed68276","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f3764070545e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view","paginates":false,"defaults":"always"},- {"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c429622c953e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShift","classification":"READ","paramCount":1,"schema":"fbdb1fa56a88","response":"86e4039d95bd","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShifts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92fec9db1b7e","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getShiftsList","classification":"READ","paramCount":1,"schema":"b76e1039273f","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShiftsWithTimes","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"5b99e0634dc7","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getTimecardEntries","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getTimeCardEntries","classification":"READ","paramCount":3,"schema":"bcbe153859d6","response":"f6358cdc55d3","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getTimeCardEntry","classification":"READ","paramCount":1,"schema":"c53dc26677e4","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},- {"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+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":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false,"result":"envelopes"},- {"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":"3d8ae1409b6a","response":"10600fcaa49e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},- {"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_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_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":"318d19f6a05c","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+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":"9e056a59d695","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},- {"name":"production_deleteAssemblyInstruction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblySubAssembly","classification":"DESTRUCTIVE","paramCount":2,"schema":"4bb5885b787b","response":"none","injectAuth":"companyId+userId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"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_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},- {"name":"production_deleteJobOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"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_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","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},- {"name":"production_deleteProcedureStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"6b6d6162de02","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProductionEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"e749b308e49d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProductionQuantity","classification":"DESTRUCTIVE","paramCount":1,"schema":"6b2dd7541ea3","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteScrapReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"a5f822fb0806","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_duplicateJobOperationStep","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_generateAssemblyStepsFromPlan","classification":"DESTRUCTIVE","paramCount":2,"schema":"80eeb7b6dd7c","response":"6a32a10b17d9","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false,"result":"flag"},- {"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":"e1b255975233","response":"6c3ab1d1c098","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},- {"name":"production_getAssemblyInstructions","classification":"READ","paramCount":5,"schema":"902de08eaf06","response":"845b5a451089","injectAuth":"companyId","permission":"production:view","paginates":true},- {"name":"production_getAssemblyInstructionsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c881f4ef7d23","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"89a5f52bebf8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionSteps","classification":"READ","paramCount":1,"schema":"f9ddf194f67e","response":"65fd94da8279","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepSlides","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"60aa9b57a118","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepTools","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"d771814f7578","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionVersions","classification":"READ","paramCount":2,"schema":"0c21424ecd86","response":"81c6e04c54bd","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyPlanJson","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"d73d9f72bafb","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyUnits","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"7224ef8546c1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchableOperations","classification":"READ","paramCount":2,"schema":"4cebb10b56d4","response":"3d084de5e690","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchableProcesses","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b0ab8957f96e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchOutputLots","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"7783e113d7a1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCapacityReservationsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"8ea855e0971b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCapacityReservationsForResources","classification":"READ","paramCount":2,"schema":"c0f9784197a0","response":"2ab92ef0d6d4","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCompletionJobs","classification":"READ","paramCount":4,"schema":"205595d8458d","response":"c0d783b97b99","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getDemandForecasts","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"21892ee9e3b8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getDemandProjections","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"f963e0e91868","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFlattenedBomMaterials","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7f3fb0d1aeb3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJob","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"1e59878bcf47","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobByOperationId","classification":"READ","paramCount":1,"schema":"c407a9edb930","response":"07382c86b3b8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobDocuments","classification":"READ","paramCount":4,"schema":"f41144061088","response":"5483e69d7515","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobDocumentsWithItemId","classification":"READ","paramCount":2,"schema":"337cb78c5606","response":"5483e69d7515","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobExpediteForecast","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"d377dc3a1fd5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMakeMethodById","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"96389acf0c72","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"7cdf48a49d7f","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialItemIds","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"32068a500dfe","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"b12e99320d04","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"562cd876b859","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialShortfallByItem","classification":"READ","paramCount":4,"schema":"644b4df6515a","response":"8a62dcc3c7f9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialSupplyJobLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"acbcf89b1800","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","paramCount":3,"schema":"ef9bf176c913","response":"be0a4b3c547b","injectAuth":"companyId","permission":"production:view","paginates":false,"defaults":"always"},- {"name":"production_getJobMethodTree","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"a0e7ca5d166e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMethodTreeArray","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"74f0f766ca05","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperation","classification":"READ","paramCount":1,"schema":"6889e2589fdc","response":"ac4a3201b981","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationAttachments","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"9a8b9c571a6b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatches","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e4a233e30c55","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOperationBatchEvents","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"8feaefdf02c8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchMembers","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"66bcdc105c00","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchMemberStats","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"03aaee65a70b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"97fc58623359","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationDependencies","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"9214ed6d51dd","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperations","classification":"READ","paramCount":2,"schema":"05cbfcbf7494","response":"720a58fe2501","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOperationsAssignedToEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"20f7748935c7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"3c7b7b51dac3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsForTimeline","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"6f0169823721","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsList","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"4e5425835530","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationStepRecords","classification":"READ","paramCount":2,"schema":"08f98a38ea9d","response":"272548978b28","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOrderStatusMap","classification":"READ","paramCount":5,"schema":"2b87b9cde70f","response":"6b4f76e71d08","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"bd69f777e8e9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobReleaseReadiness","classification":"READ","paramCount":1,"schema":"267b4780c1d3","response":"9712d0076586","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobs","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"847ba339f22a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobsList","classification":"READ","paramCount":1,"schema":"6168fc8fbdbe","response":"232ee7305e73","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLatestAssemblyPlan","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"6b38ef1e4ead","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLatestAssemblyPlanJob","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"d45b1cde8dd5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLocationEmployees","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"72ccccdcfc21","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"f0addd41ad4e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchComments","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7df6d6b7ba88","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatches","classification":"READ","paramCount":4,"schema":"c19d6a6c007b","response":"8cdb79a1ff07","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getMaintenanceDispatchEvents","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"fc0af15629d8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchItems","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7d22c1b8235d","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchWorkCenters","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"245d61ef36d3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","paramCount":1,"schema":"935cc20961b6","response":"c9ce440846e1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceSchedule","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"c9d71a024473","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceScheduleItems","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"6e7c564b202a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceSchedules","classification":"READ","paramCount":4,"schema":"d55eeae51beb","response":"69ee71e3d5a8","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getModelForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a64658053ae5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getOutsideOperationsByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b75ab9ed0211","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAbsences","classification":"READ","paramCount":1,"schema":"2f19cae7bae1","response":"f98df1954626","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAbsencesRange","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"90f4a38d3460","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAssignments","classification":"READ","paramCount":2,"schema":"0a3119f1e6d7","response":"6bf01853c73a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAssignmentsRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"ba9f9d495de9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleCapacityOperations","classification":"READ","paramCount":3,"schema":"19f229146b3b","response":"9bbc101347c4","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedure","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"54f86be1acc6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureParameters","classification":"READ","paramCount":1,"schema":"0611728fa5e0","response":"07629bf64853","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedures","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"ba57bd0be81d","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProceduresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fe6a24448aaa","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureSteps","classification":"READ","paramCount":1,"schema":"0611728fa5e0","response":"fd4f59b40560","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureVersions","classification":"READ","paramCount":2,"schema":"89111eab017d","response":"f97efca67bd3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionDataByOperations","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"9664edfb7c53","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEvent","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b1799639bb8d","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEvents","classification":"READ","paramCount":2,"schema":"91c6f90c1d2d","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"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":"d3ce152358d0","response":"d82d26b306e9","injectAuth":"companyId","permission":"production:view","paginates":true},- {"name":"production_getProductionPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"70236c14db92","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionProjections","classification":"READ","paramCount":3,"schema":"c3afb01f3040","response":"4973a62dfd1b","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionQuantities","classification":"READ","paramCount":2,"schema":"91c6f90c1d2d","response":"3b4cf7a6bc87","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionQuantity","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c506c8c71d8f","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getRootMakeMethod","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"96389acf0c72","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getScrapReason","classification":"READ","paramCount":1,"schema":"a5f822fb0806","response":"4bbb50609deb","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getScrapReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a5e736373756","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getScrapReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getTrackedEntitiesByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"c20d7cb06756","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getTrackedEntityByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"d485710baf81","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getUnbatchedBatchableOperationCount","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce387c10b075","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getUnscheduledJobs","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"807e503150d6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterRequiredAbilities","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"7418ea1fc0a7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterReservationsRange","classification":"READ","paramCount":2,"schema":"99ea73b8e7a1","response":"a7e9bc09d2ab","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterShifts","classification":"READ","paramCount":1,"schema":"e94892850934","response":"2b4835f80e6c","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"f14d1689b7f8","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},- {"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"231e1d7f0444","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_makeAssemblySubAssembly","classification":"WRITE","paramCount":2,"schema":"e39572ccf46c","response":"00404e686415","injectAuth":"companyId+userId","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_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":"9e056a59d695","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":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_releaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","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","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},- {"name":"production_setPeopleAssignmentHours","classification":"WRITE","paramCount":2,"schema":"29aa7bdf6d50","response":"3ca729812149","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleDay","classification":"DESTRUCTIVE","paramCount":7,"schema":"e5c972d7b8c3","response":"b4c094a53e37","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleOvertimeBulk","classification":"WRITE","paramCount":6,"schema":"8f082483561d","response":"577d7088b794","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_syncAssemblyInstructionToOperation","classification":"DESTRUCTIVE","paramCount":2,"schema":"8160f8d92b1b","response":"4348d3bad80b","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_syncAssemblyStepMaterialsFromMappings","classification":"WRITE","paramCount":4,"schema":"7f7346bb3bd0","response":"5815c4dbf43d","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"29ac1466e693","response":"af67df1e83ed","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_unassignPeopleWeek","classification":"DESTRUCTIVE","paramCount":4,"schema":"06ead5d3d9ce","response":"9658926b2cd2","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_ungroupAssemblySubAssembly","classification":"DESTRUCTIVE","paramCount":2,"schema":"4bb5885b787b","response":"none","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_unreleaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"9e056a59d695","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","paramCount":2,"schema":"e43955681d7c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","paramCount":2,"schema":"5a4d7dc208a5","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":2,"schema":"86adf519c2e9","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","paramCount":2,"schema":"9291eed55a4a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepComponents","classification":"WRITE","paramCount":2,"schema":"d7ea6b1800f7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","paramCount":3,"schema":"3ac4e88c4df0","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":5,"schema":"aa7dfb67132e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblySubAssembly","classification":"WRITE","paramCount":4,"schema":"0f0cbf9e32e1","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateJob","classification":"WRITE","paramCount":22,"schema":"fc37d97579b2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobBatchNumber","classification":"WRITE","paramCount":2,"schema":"a4c2a31bb8a6","response":"f7a40899c090","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobOperationBatch","classification":"WRITE","paramCount":4,"schema":"6aa26c8c9567","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateJobOperationDueDate","classification":"WRITE","paramCount":2,"schema":"e04478fc58f7","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},- {"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobOperationStatus","classification":"WRITE","paramCount":2,"schema":"b22654081076","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},- {"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobStatus","classification":"WRITE","paramCount":4,"schema":"458fa5786030","response":"8394fbabd845","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"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":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"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":1,"schema":"28bd332a0905","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":"6be3bd248d68","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":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"2a177dc982bb","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":"9e056a59d695","injectAuth":"companyId+createdBy+updatedBy+userId","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":"6be3bd248d68","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":"4e1a8f1febce","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":"d4a8e99e0523","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProcedureParameter","classification":"WRITE","paramCount":4,"schema":"3ec6c5dece78","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProcedureStep","classification":"WRITE","paramCount":10,"schema":"af47a3cf4652","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"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_confirmPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"16be78b08a8f","response":"ec9aaaf82857","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":"invoicing:create","paginates":false},- {"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"11b028f16d94","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},- {"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"a424256cbe29","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_deleteLease","classification":"DESTRUCTIVE","paramCount":1,"schema":"9fb51372ff53","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteLeaseLine","classification":"DESTRUCTIVE","paramCount":2,"schema":"bb4487ea3e25","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteLeasePayment","classification":"DESTRUCTIVE","paramCount":2,"schema":"ae1ccfbfd489","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"28cffcd9d6e8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"ed69a5b8e424","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseReturnOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"11b028f16d94","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseReturnOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"063a6777d378","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","paramCount":1,"schema":"4e16cef99961","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchasingRFQLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"943916e70d0b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplier","classification":"DESTRUCTIVE","paramCount":1,"schema":"67043a31b1b5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"purchasing_deleteSupplierContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"041a4bd97ec8","response":"700b93baa3ef","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierLocation","classification":"DESTRUCTIVE","paramCount":2,"schema":"dad5decd6951","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierProcess","classification":"DESTRUCTIVE","paramCount":1,"schema":"fe73a000b6f7","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierQuote","classification":"DESTRUCTIVE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierQuoteLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierType","classification":"DESTRUCTIVE","paramCount":1,"schema":"900045091850","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_duplicatePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"b6bf3abf506d","response":"f5212679d580","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},- {"name":"purchasing_finalizePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_finalizePurchasingRfq","classification":"WRITE","paramCount":1,"schema":"9531e4360acd","response":"e2e56b5a6c0a","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_finalizeSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_getCreditableQuantitiesForPurchaseReturn","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"1e97e6c72b1d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getDefaultAttachmentsForPO","classification":"READ","paramCount":2,"schema":"17cccb0ea3ef","response":"4a42c6b9da80","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLease","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"088b0a26be2c","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseEvents","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"d33db68815b5","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseLines","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"c67039919353","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeasePayments","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"73152bc44605","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseRelatedDocuments","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"c999fc505e07","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeases","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"2492d3f8f118","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getLeaseSchedule","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"033eb326814e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqs","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"9c82bc9ce35e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqsForInteraction","classification":"READ","paramCount":1,"schema":"6e2899e1731e","response":"c7f7518e09d1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqsForOrder","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"9c82bc9ce35e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedSupplierQuotes","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"cb143b1fe761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrder","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"3797db2be7c6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderDelivery","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"0564bac29ef5","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLine","classification":"READ","paramCount":1,"schema":"ed69a5b8e424","response":"56c9d7ca858b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"4e2a81139b3b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLocations","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"d4d4c42eb761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderPayment","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"c7a62e53e09b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrders","classification":"READ","paramCount":5,"schema":"f3468ea9b0a6","response":"fbaa9ca23142","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchaseOrderSuppliers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrder","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"8cb2133c047e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderCredits","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"49639d091139","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderIssues","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"a81c998e95a3","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"6e3bf67c7a97","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLines","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"1f58312907d8","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLineTrackedEntities","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"75ed48edf5c1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrders","classification":"READ","paramCount":5,"schema":"f3468ea9b0a6","response":"de438833d869","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchaseReturnOrderShipments","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"08e1b6f03862","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"cb047e0da459","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"e09989d16685","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchasingRFQ","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"08cb90c207da","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"045f66457f11","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQLines","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"24a761144b4a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQs","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a2661a189775","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchasingRFQSuppliers","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"5483e69d7515","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQSuppliersWithLinks","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"5483e69d7515","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"91b7924d48bd","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableEntitiesForReceiptLine","classification":"READ","paramCount":2,"schema":"0d233758ff1f","response":"5c104e265494","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableEntitiesForSupplier","classification":"READ","paramCount":2,"schema":"3700a887762e","response":"4e436e8a6f98","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableLinesForSupplier","classification":"READ","paramCount":2,"schema":"7a1204db0d90","response":"24dd6c0d1c55","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSiblingQuotesForQuote","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"cb143b1fe761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"10c7209cc38a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierBankAccounts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"f2b09b60b722","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"purchasing_getSupplierContact","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"6d2aa722b1ce","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierContacts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"e28ccbd2c417","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteraction","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"e933ede17ac0","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierLocation","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"4603d06d1055","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierLocations","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"6dad1063175d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierPayment","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"24b286adf1ff","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessById","classification":"READ","paramCount":1,"schema":"fe73a000b6f7","response":"7d3e895a1991","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessesByProcess","classification":"READ","paramCount":1,"schema":"01edb53077b2","response":"c2eb609c8ad1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessesBySupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"c2eb609c8ad1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuote","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"f998bf4f97dc","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteByExternalLinkId","classification":"READ","paramCount":1,"schema":"feb52bb98a20","response":"8c242582e5e6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteByInteractionId","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"f998bf4f97dc","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLine","classification":"READ","paramCount":1,"schema":"88823065a537","response":"549f0e57572d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLinePrices","classification":"READ","paramCount":1,"schema":"88823065a537","response":"22abc40c4789","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLinePricesByQuoteId","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"22abc40c4789","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLines","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"50759a9c2b79","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuotes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9e311e59b82e","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierQuotesForComparison","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"540207b2c74e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"967dcad15168","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierReportContacts","classification":"READ","paramCount":1,"schema":"f6d6276b4996","response":"a07965e69b81","injectAuth":"companyId","permission":"purchasing:view","paginates":false,"result":"envelopes"},- {"name":"purchasing_getSuppliers","classification":"READ","paramCount":5,"schema":"fe4524096cbe","response":"947b627d845e","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierShipping","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"17117a952d24","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSuppliersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierTax","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"303387b4fc28","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierType","classification":"READ","paramCount":1,"schema":"900045091850","response":"8b3eca34dbfd","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7c6550dea5b1","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_insertLease","classification":"WRITE","paramCount":19,"schema":"b7cf150e300e","response":"f6631a819d19","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false,"defaults":"always"},- {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","paramCount":15,"schema":"27513cc48e8d","response":"73785d310369","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","paramCount":12,"schema":"d3253380f7e2","response":"d53d13c89312","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"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_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":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_reopenPurchaseOrderAsRevision","classification":"WRITE","paramCount":2,"schema":"ffa38ce5274f","response":"cddf8275afa1","injectAuth":"companyId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_reopenPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_sendSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_setPurchaseReturnOrderLineTrackedEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"f3f13d81cd8c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_shortClosePurchaseOrderLine","classification":"WRITE","paramCount":3,"schema":"fc9c2f370fc5","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_shortClosePurchaseReturnOrderLine","classification":"WRITE","paramCount":3,"schema":"a21cfee98b1a","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateLeaseDetails","classification":"WRITE","paramCount":5,"schema":"a42727e2a52e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","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+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":"d55cadd232ef","response":"bcde375ebd4c","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_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},- {"name":"purchasing_updateSupplierQuote","classification":"WRITE","paramCount":8,"schema":"64e0b2d29d98","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"7bf10894875d","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteStatus","classification":"WRITE","paramCount":3,"schema":"856b61886f1f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierShipping","classification":"WRITE","paramCount":8,"schema":"ac0c2133e800","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierTax","classification":"WRITE","paramCount":8,"schema":"7e31a89af103","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_upsertLeasePayment","classification":"WRITE","paramCount":8,"schema":"341b1b86d9c9","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_upsertPurchaseOrder","classification":"WRITE","paramCount":2,"schema":"d458b7f2c10f","response":"1b33aad6f934","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"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":"ca0929113e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"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":"66adf4b67af2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa459fc25bca","response":"5c9ba5bee3f1","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"context":"createdBy=userId"},- {"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":"accounting: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":"3c9810ea1df4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"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},- {"name":"quality_deleteGaugeCalibrationRecord","classification":"DESTRUCTIVE","paramCount":1,"schema":"81eca1e58f6e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteGaugeType","classification":"DESTRUCTIVE","paramCount":1,"schema":"24fb90489cd4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteInspectionDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"e92dda062549","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssue","classification":"DESTRUCTIVE","paramCount":1,"schema":"a78c6c21c084","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssueAssociation","classification":"DESTRUCTIVE","paramCount":2,"schema":"5e9621fb955d","response":"none","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"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_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},- {"name":"quality_getGauge","classification":"READ","paramCount":1,"schema":"f65da45a1155","response":"19d84b9bffdb","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeCalibrationRecord","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"90fb86d6af14","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeCalibrationRecords","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7ed9f83a9f0f","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugeCalibrationRecordsByGaugeId","classification":"READ","paramCount":1,"schema":"f65da45a1155","response":"7ed9f83a9f0f","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGauges","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7d2b6ae79d59","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"34b9a5801676","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeType","classification":"READ","paramCount":1,"schema":"24fb90489cd4","response":"63b5b3f8f143","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"95195653f3fc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugeTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspection","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocument","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a82889f583de","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"daa253e3c540","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getInspectionDocumentsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"cfa5f1f7b8aa","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionFeatures","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"1e8d8f002f21","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionGauges","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"d5c3ebb5ddd2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionMeasurements","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"c6a90b70c17b","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionPlan","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"83a9b3640e41","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspections","classification":"READ","paramCount":5,"schema":"81ca1d9d2144","response":"b942685a303b","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getInspectionSamplingPlans","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"5b3237ad5668","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionTrackedEntities","classification":"READ","paramCount":1,"schema":"17337505bb69","response":"c20d7cb06756","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssue","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"1a2ca8014c88","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueActionTasks","classification":"READ","paramCount":2,"schema":"989a1bef3af7","response":"0f3a25ff459d","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueApprovalTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"60bd02d2af2c","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueAssociations","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"ebdefbd901a7","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueFromExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"81ecd90279ab","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueItems","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ca2b3990f2f7","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueReviewers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fa7631f38515","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssues","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e08ce0758580","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueSuppliers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a7e42e2f8c2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"28fce89961bd","injectAuth":"companyId","permission":"quality:view","paginates":false,"result":"envelopes"},- {"name":"quality_getIssueType","classification":"READ","paramCount":1,"schema":"bb6b04f68710","response":"63b5b3f8f143","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTypeByName","classification":"READ","paramCount":2,"schema":"858a6cb73bbb","response":"3797626bd17e","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"95195653f3fc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueWorkflow","classification":"READ","paramCount":1,"schema":"15a80db054e6","response":"3272b87b8442","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueWorkflows","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"38608ae87f0d","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueWorkflowsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"38608ae87f0d","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getItemInspectionDocumentAssignments","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"9bedeef9a12b","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"76d10ad61a21","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getQualityDocument","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a8b2d87af029","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"8bb4ab685129","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getQualityDocumentsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f0df86b695e6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocumentSteps","classification":"READ","paramCount":1,"schema":"6d79e6870690","response":"55202747c3b2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocumentVersions","classification":"READ","paramCount":2,"schema":"89111eab017d","response":"63e52c70cbef","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityFiles","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ffefd03548aa","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getReceiptInspections","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"e30d015c0242","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRequiredAction","classification":"READ","paramCount":1,"schema":"cca3bf9f3ebb","response":"00f7e228e469","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRequiredActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"477e4aa9ac3b","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getRequiredActionsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRisk","classification":"READ","paramCount":1,"schema":"7002f7ae1c58","response":"f0e54ff68cc5","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRisks","classification":"READ","paramCount":6,"schema":"edf9ecb3ea7f","response":"72f8ffc765cc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_insertGauge","classification":"WRITE","paramCount":15,"schema":"f067ee95ad2f","response":"3269d4609ad2","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_insertIssue","classification":"WRITE","paramCount":20,"schema":"308033845426","response":"bf12cbd0f560","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_insertIssueReviewer","classification":"WRITE","paramCount":2,"schema":"fdfb09172931","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_saveInspectionDocumentAtomic","classification":"WRITE","paramCount":7,"schema":"302bbaaf5d0c","response":"none","injectAuth":"companyId+userId","permission":"quality:update","paginates":false},- {"name":"quality_updateGauge","classification":"WRITE","paramCount":16,"schema":"d62e872469a5","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateInspectionDocumentSampling","classification":"WRITE","paramCount":7,"schema":"e85058fba971","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"quality:update","paginates":false},- {"name":"quality_updateIssue","classification":"WRITE","paramCount":16,"schema":"93bb71a6bcdc","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueActionProcesses","classification":"DESTRUCTIVE","paramCount":2,"schema":"9dbd38e74ee8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueStatus","classification":"WRITE","paramCount":4,"schema":"71469c92601d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueTaskContent","classification":"WRITE","paramCount":3,"schema":"4475ba505172","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_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_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":"acd2ed0af051","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"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":"980470d15320","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"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},- {"name":"resources_deleteAbility","classification":"DESTRUCTIVE","paramCount":2,"schema":"f642be0f483d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"c178e4a4c21e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteEmployeeAbility","classification":"DESTRUCTIVE","paramCount":1,"schema":"5ccac46fc41e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteFailureMode","classification":"DESTRUCTIVE","paramCount":1,"schema":"4a3e0384d72f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteLocation","classification":"DESTRUCTIVE","paramCount":1,"schema":"de371a276a58","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"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_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","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},- {"name":"resources_deleteSuggestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"3a7f44ccb395","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTraining","classification":"DESTRUCTIVE","paramCount":1,"schema":"3f6f0a410b0f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTrainingAssignment","classification":"DESTRUCTIVE","paramCount":1,"schema":"7d3fe60cc8ed","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTrainingQuestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"b4f48c09ba9f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteWorkCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_ensureProcessAbility","classification":"WRITE","paramCount":2,"schema":"6381d05a75ce","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"resources:update","paginates":false},- {"name":"resources_getAbilities","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"53c80a9d1965","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getAbilitiesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getAbility","classification":"READ","paramCount":1,"schema":"5133c0e3b586","response":"d98eac986c97","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getContractor","classification":"READ","paramCount":1,"schema":"c178e4a4c21e","response":"995cb2d28a3e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getContractors","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"155b783e2512","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getEmployeeAbilities","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"328aa0024967","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getEmployeeAbility","classification":"READ","paramCount":1,"schema":"5ccac46fc41e","response":"f0d72cd0ea38","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"99dfd44b4c2e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cf3608cc2732","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getLocationsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e19c89c1e8a0","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"5547ae49213e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchComments","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7df6d6b7ba88","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatches","classification":"READ","paramCount":4,"schema":"c19d6a6c007b","response":"8cdb79a1ff07","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceDispatchesByLocation","classification":"READ","paramCount":2,"schema":"5ccae51b79d8","response":"774cad94afc0","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceDispatchEvents","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"fc0af15629d8","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchItems","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"595d666b79ec","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchItemTrackedEntities","classification":"READ","paramCount":1,"schema":"63ddd4fe05c0","response":"0ae53e4d5350","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchWorkCenters","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"245d61ef36d3","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceSchedule","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"c9d71a024473","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceScheduleItems","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"6e7c564b202a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceSchedules","classification":"READ","paramCount":4,"schema":"d55eeae51beb","response":"69ee71e3d5a8","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceSchedulesByLocation","classification":"READ","paramCount":2,"schema":"68aa9154c497","response":"71889eb4641f","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getOutstandingTrainingsForUser","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"2b901764b425","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartner","classification":"READ","paramCount":2,"schema":"7a4efbb751fd","response":"690aa589fb9c","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartnerBySupplierId","classification":"READ","paramCount":1,"schema":"74d289586b4f","response":"690aa589fb9c","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartners","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"f1a7446bd053","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getProcess","classification":"READ","paramCount":1,"schema":"01edb53077b2","response":"d981fcf79885","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getProcesses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e2daca4791c0","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getProcessesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getProcessesWithoutAbility","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getSuggestion","classification":"READ","paramCount":1,"schema":"3a7f44ccb395","response":"77bb66a1249a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getSuggestions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9e90aae0404b","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getTraining","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"84c264919a14","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignment","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"cb917b5ce4eb","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"41a2c00f121a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignments","classification":"READ","paramCount":1,"schema":"d541f0a7e11f","response":"bb328cb9e34a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentStatus","classification":"READ","paramCount":3,"schema":"4b28f853e5b7","response":"2b901764b425","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentStatusForEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"2b901764b425","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentSummary","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c3f55a28a4ac","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingGrantedAbilityId","classification":"READ","paramCount":1,"schema":"fbebd108a3c4","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingQuestions","classification":"READ","paramCount":1,"schema":"3f6f0a410b0f","response":"cbc84076fe3b","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainings","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"cc28f2dfe36f","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getTrainingsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8a9d99ad8810","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCenter","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"e5193d0e2978","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCenters","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getWorkCentersByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"f602591e2bf5","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCentersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fcb9583f02e0","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_insertMaintenanceDispatch","classification":"WRITE","paramCount":14,"schema":"b192bab74c65","response":"ede36af7307d","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create","paginates":false},- {"name":"resources_processDeactivate","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"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","permission":"resources:update","paginates":false},- {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false,"result":"envelopes"},- {"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":"5771361986b6","response":"99dfd44b4c2e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"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":"bfa604f1eeb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"resources_upsertTraining","classification":"WRITE","paramCount":4,"schema":"385fb9c5d8d1","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"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":"1c336cac9dc8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"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,"result":"flag"},- {"name":"sales_cancelSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","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":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},- {"name":"sales_convertSalesRfqToQuote","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},- {"name":"sales_copyQuote","classification":"WRITE","paramCount":2,"schema":"174cbee1fad4","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_copyQuoteLine","classification":"WRITE","paramCount":9,"schema":"692ceb74fe3d","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"45722937a7bb","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_createPricingRule","classification":"WRITE","paramCount":17,"schema":"8a6a210cb492","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false,"defaults":"always"},- {"name":"sales_createReplacementSalesOrder","classification":"WRITE","paramCount":1,"schema":"f41daa12b05a","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"invoicing:create","paginates":false},- {"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","paramCount":1,"schema":"09e48c79fb16","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"3fd22b0165d4","response":"700b93baa3ef","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerItemRentalRate","classification":"DESTRUCTIVE","paramCount":1,"schema":"ee5e30c7b358","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerLocation","classification":"DESTRUCTIVE","paramCount":2,"schema":"1786ebad8e35","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerStatus","classification":"DESTRUCTIVE","paramCount":1,"schema":"d9fee396ed8f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerType","classification":"DESTRUCTIVE","paramCount":1,"schema":"b79bc02c5595","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteNoQuoteReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"a37352ef51ef","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"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_deleteQuoteMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"5718812a5810","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},- {"name":"sales_deleteRentalAgreement","classification":"DESTRUCTIVE","paramCount":1,"schema":"ac265594426e","response":"3797626bd17e","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteRentalAgreementCharge","classification":"DESTRUCTIVE","paramCount":1,"schema":"42fbbc48ae45","response":"3797626bd17e","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteRentalAgreementLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"9729319c460e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteReturnReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"937e7a95a060","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"58e3c9762923","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesReturnOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"f41daa12b05a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesReturnOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"063a6777d378","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesRFQ","classification":"DESTRUCTIVE","paramCount":1,"schema":"1f7e47a99145","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"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":"746e975d6c8f","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getBaseCatalog","classification":"READ","paramCount":3,"schema":"b00172859bab","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"c36ad21b447b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContract","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"61ce667abaa8","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractAmendments","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"d9f1b6608c99","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractInvoiceSchedule","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"194d22065482","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractLine","classification":"READ","paramCount":1,"schema":"3d08011d330a","response":"557e5390f61f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractLines","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"69f1c97ee590","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContracts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"fc8b89e1366e","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCreditableQuantities","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"da2f02c5bdac","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"8642159293c2","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerBankAccounts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"d8173b9c2e54","injectAuth":"companyId","permission":"accounting: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_getCustomerContractStatuses","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"b4542ed3da5e","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":"1e549e10e0a2","response":"bae32978787b","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerItemRentalRate","classification":"READ","paramCount":1,"schema":"ee5e30c7b358","response":"b3b8ce0eaba0","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemRentalRates","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8b9441c41a32","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerLocation","classification":"READ","paramCount":1,"schema":"339ac15c3167","response":"be52ec9b4436","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerLocations","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"bcf222d6d73a","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerPayment","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"4357e4e42177","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"07fbe06b66b8","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerShipping","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"68f579c7eb78","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerStatus","classification":"READ","paramCount":1,"schema":"d9fee396ed8f","response":"9203566a8ab4","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerStatuses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a5e736373756","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"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":"e4596e241f82","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7c6550dea5b1","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getDefaultRentalRates","classification":"READ","paramCount":4,"schema":"9ccf2aa2b622","response":"c30d2e6a59d6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getExternalSalesOrderLines","classification":"READ","paramCount":2,"schema":"ddc644088147","response":"93fb8fa8e058","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getItemRentalRate","classification":"READ","paramCount":2,"schema":"fdb1e4807b11","response":"d1badca592c6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getModelByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"none","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getNoQuoteReason","classification":"READ","paramCount":1,"schema":"a37352ef51ef","response":"4bbb50609deb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getNoQuoteReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"28837d034643","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getNoQuoteReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOnRentLineForAsset","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"3d1ddb71d505","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"2c3da47e06b1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunity","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"b203af1d4a1e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a1e20313f8b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"b00172859bab","response":"f3613d31804a","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getQuote","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"bf6f646d5145","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteAssemblies","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteAssembliesByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteByExternalId","classification":"READ","paramCount":1,"schema":"21801463053a","response":"960e90f367ef","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteCustomerDetails","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"7656953707c3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"2e0476c17730","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePrices","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"b380070f2ac3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByItemId","classification":"READ","paramCount":2,"schema":"17311e00ca6f","response":"2d479ad29d1f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByItemIds","classification":"READ","paramCount":2,"schema":"64b602e1a6e4","response":"2d479ad29d1f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByQuoteId","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"b380070f2ac3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePriceTraces","classification":"READ","paramCount":2,"schema":"55ee981d3d94","response":"898c52004ae5","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLines","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"31ca07c6139c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinesList","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"5ebff9af923d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMakeMethod","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"9bc4f5e58344","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"1600eb794a06","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterials","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"d8257d5ecd6b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByOperation","classification":"READ","paramCount":1,"schema":"9d2e26473601","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMethodTreeArray","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"37f28086fadc","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMethodTrees","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"5cf44f338f23","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperation","classification":"READ","paramCount":1,"schema":"9d2e26473601","response":"cc467608e48d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperations","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"9e17db1d5582","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperationsByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9e17db1d5582","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperationsByMethodId","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"0ee46500fe67","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotePayment","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"c94b5d1f2b47","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef1a8a2074f8","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getQuoteShipment","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee2ac29cff92","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0ff25946068c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","paramCount":2,"schema":"71f31780bb98","response":"935691b285a7","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentableFleetAssets","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"18707409983d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreement","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"bab51585fc7b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementCharges","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"49b56d3a2f77","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementDeposits","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"d1712908bacb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementLine","classification":"READ","paramCount":1,"schema":"9729319c460e","response":"241639dc09ac","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementLines","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"3ed7f3538cc6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementRelatedDocuments","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"e6faf3cc340a","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e6c6ed5e084e","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getRentalBillingPeriods","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"10915ab32ad5","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnableLinesForCustomer","classification":"READ","paramCount":2,"schema":"e9ef772b4706","response":"8b3d2e7917fd","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnReason","classification":"READ","paramCount":1,"schema":"937e7a95a060","response":"784c9ecc581f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1367348aaf16","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getReturnReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"152e0efd7e28","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRootQuoteMakeMethod","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9bc4f5e58344","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"74270bb8ea95","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrder","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"c95639a37a20","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderCustomerDetails","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"141326b70f84","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderCustomers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoiceLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"1ff852ae9154","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"397cd2bf218b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"cd5bcdc964de","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"5bd9ba5f7ba2","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLinesByItemIds","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLineShipments","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"2414f4b5bcaf","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderPayment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"e52a6a8beddf","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderRelatedItems","classification":"READ","paramCount":2,"schema":"651e9f51b36d","response":"de3f79e02cdb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrders","classification":"READ","paramCount":5,"schema":"ef4d06fef47e","response":"f397c1f3b176","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesOrdersByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"5cc20a44d4fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderShipment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"0f0a39ddefae","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrdersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5cc20a44d4fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrder","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"a2cca2d13294","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderCredits","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"49639d091139","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderIssues","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"7cc200ea4b26","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"06aa29fc6b50","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLines","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"580ee4dec9d4","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLineTrackedEntities","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"71f9ff6abcae","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderReceipts","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"71de851646a8","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrders","classification":"READ","paramCount":5,"schema":"ef4d06fef47e","response":"31090a014afa","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesRFQ","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"be949b1d682b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"a53064f9e7fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQLines","classification":"READ","paramCount":1,"schema":"1f7e47a99145","response":"17f5b7f57e4c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQs","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cb436531316b","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"9819ae68df9b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getShippedTrackedEntitiesForCustomer","classification":"READ","paramCount":2,"schema":"03d6f7a5e605","response":"1eabdd9a5634","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_insertContract","classification":"WRITE","paramCount":29,"schema":"2ce74f76bcb5","response":"b0da0d6d41c1","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertCustomerContact","classification":"WRITE","paramCount":4,"schema":"c5775e935035","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertCustomerLocation","classification":"WRITE","paramCount":4,"schema":"c30fcaea26e0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertQuote","classification":"WRITE","paramCount":16,"schema":"a6c40455c9f1","response":"9e29b49e1dc8","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertRentalAgreement","classification":"WRITE","paramCount":22,"schema":"ebd937b5bb2c","response":"83a132e7dfec","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesOrder","classification":"WRITE","paramCount":17,"schema":"b76b79d52d88","response":"dbfc22813350","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesReturnOrder","classification":"WRITE","paramCount":12,"schema":"307356313ba5","response":"c32485518acd","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesRFQ","classification":"WRITE","paramCount":13,"schema":"5a54a12e500f","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bef3efeea4ce","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_releaseSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_reopenSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_repriceQuoteLineFromRules","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_resolvePrice","classification":"WRITE","paramCount":1,"schema":"e21d9e9b3005","response":"eb12029769da","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_resolvePriceList","classification":"WRITE","paramCount":6,"schema":"aa4cc3b4c9e6","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:update","paginates":true,"defaults":"always"},- {"name":"sales_resolvePurchaseToOrderPrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"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_updateContract","classification":"WRITE","paramCount":29,"schema":"2d479c6cdf33","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateContractNotes","classification":"WRITE","paramCount":2,"schema":"2ab51d0b91d5","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateContractType","classification":"WRITE","paramCount":2,"schema":"9a1390515c73","response":"3797626bd17e","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},- {"name":"sales_updateCustomerShipping","classification":"WRITE","paramCount":7,"schema":"1c4be8a465fb","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerTax","classification":"WRITE","paramCount":8,"schema":"adc033566bc5","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updatePricingRule","classification":"WRITE","paramCount":2,"schema":"d8ff12f7ca7a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuote","classification":"WRITE","paramCount":17,"schema":"ad5fc3f2a158","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"fce9a5d72ad3","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteLinePrecision","classification":"WRITE","paramCount":3,"schema":"90f52ec96806","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false,"result":"envelopes"},- {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false,"result":"envelopes"},- {"name":"sales_updateQuoteStatus","classification":"WRITE","paramCount":3,"schema":"db2529b2f9b5","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateRentalAgreement","classification":"WRITE","paramCount":22,"schema":"ea42378f3633","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateRentalAgreementInvoiceAutomation","classification":"WRITE","paramCount":2,"schema":"321dd5c5e689","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrder","classification":"WRITE","paramCount":9,"schema":"d9b815fe7f4c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"fc73ab432ad8","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderStatus","classification":"WRITE","paramCount":3,"schema":"4d2e908ca09f","response":"bcde375ebd4c","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":"edf30d1c08da","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_upsertContractLine","classification":"WRITE","paramCount":18,"schema":"7a649c12168f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"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":"accounting: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_upsertCustomerItemRentalRate","classification":"WRITE","paramCount":11,"schema":"d9f007b1b5e5","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","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_upsertItemRentalRate","classification":"WRITE","paramCount":5,"schema":"f4cb0467e3dc","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","paramCount":4,"schema":"ca78a9869ff2","response":"4e1a8f1febce","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":"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":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteLine","classification":"WRITE","paramCount":19,"schema":"0418d6bec04a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","paramCount":2,"schema":"af3d9c81e1c3","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteLineMethod","classification":"WRITE","paramCount":5,"schema":"5f94e8a4cbf6","response":"4e1a8f1febce","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":"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":"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_upsertRentalAgreementCharge","classification":"WRITE","paramCount":7,"schema":"a914e37d74f4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertRentalAgreementLine","classification":"WRITE","paramCount":9,"schema":"cb7e4d4579e2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"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":"9d987dd63daf","response":"5cc20a44d4fe","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesOrderLine","classification":"WRITE","paramCount":27,"schema":"cf0093721ce3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"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},- {"name":"settings_getAccountsReceivableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getApiKeys","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"eec810be5b96","injectAuth":"companyId","permission":"users:update","paginates":true,"defaults":"always"},- {"name":"settings_getCompanies","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"207f0b849926","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompany","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"81a93f0029ec","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanyIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a98b34db51d","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanyPlan","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"689a7e333d99","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getConfig","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"aa1021ff34cf","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCurrentSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomField","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a533a796c094","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomFields","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"4dd4a7dca597","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomFieldsTables","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4d68a1d346ce","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getDocumentSection","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"955f14940530","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentSections","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentSectionsByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentTemplate","classification":"READ","paramCount":1,"schema":"66ed1f5ba422","response":"99cae633d7cb","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentTemplateConfig","classification":"READ","paramCount":1,"schema":"66ed1f5ba422","response":"b6618b8c597f","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getEmployeeCompanies","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"207f0b849926","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIndustries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5dcce0f224dd","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIntegration","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"099545249106","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"66d5dad6d7fc","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequence","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"16afb36e5f82","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequenceByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"1a875b64a77f","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequences","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef60889e0cf5","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getKanbanOutputSetting","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ca53dc098fc8","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getNextSequence","classification":"WRITE","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_getPlanById","classification":"READ","paramCount":1,"schema":"a77c6a03353f","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getPlans","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5483e69d7515","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"ef17e2453ded","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSequences","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"395e5a595aba","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getSequencesList","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"8394fbabd845","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSubsidiaries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"577bb278c46e","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSubsidiary","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ac5d56a91ae0","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"deb82bb77180","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"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":"c61cae75d189","response":"f236afae1a37","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getWebhookTables","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"633f9f3bffc6","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_resolveSections","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"59781d2a00b3","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,"context":"updatedBy=userId"},- {"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,"context":"updatedBy=userId"},- {"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_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","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_updateInvoiceAutomationSetting","classification":"WRITE","paramCount":1,"schema":"58ff6b5b2f88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateInvoiceNotificationSetting","classification":"WRITE","paramCount":1,"schema":"e1f0172b7519","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_updateLeasePolicySettings","classification":"WRITE","paramCount":6,"schema":"73eeba3e8660","response":"bcde375ebd4c","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","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_updateMrpRunTimeSetting","classification":"WRITE","paramCount":1,"schema":"7e0d8d6dda56","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":"64b05764105a","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","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":"68db6a083683","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false,"upsert":"documentSection(id)"},- {"name":"settings_upsertDocumentTemplate","classification":"WRITE","paramCount":6,"schema":"46782204d1c1","response":"bcde375ebd4c","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_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},- {"name":"shared_getCustomerPortals","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"fbffc4ca5fac","injectAuth":"companyId","permission":"none","paginates":true,"defaults":"always"},- {"name":"shared_getEnforcementRule","classification":"READ","paramCount":2,"schema":"fa9ceafd871f","response":"55286a46f24b","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","paramCount":1,"schema":"47af2b550d52","response":"ab5d5774b961","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getEnforcementRules","classification":"READ","paramCount":2,"schema":"f7fab064142e","response":"a58a59f02a18","injectAuth":"companyId","permission":"none","paginates":true,"defaults":"always"},- {"name":"shared_getExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0f7860db4299","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getModelByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"none","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getNotes","classification":"READ","paramCount":1,"schema":"e7617eb689c8","response":"1a052a4417b5","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getPeriods","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"e635c6c77f6d","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getSavedViews","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"be2b0aada3eb","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getTagsList","classification":"READ","paramCount":1,"schema":"43c92414cb2f","response":"b837740e18f4","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getTimezoneNames","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"93968ed2dcdb","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_importCsv","classification":"WRITE","paramCount":4,"schema":"8f2d77f74ffb","response":"fe3f36b94f53","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":"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":"READ","paramCount":4,"schema":"cb376986b1ab","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"none","paginates":false,"result":"envelopes"},- {"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},- {"name":"users_getConsoleOperators","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"42c3353a5284","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getCustomers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"79cad34eb92a","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getEmployee","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fddbdf17260d","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getEmployees","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"42c3353a5284","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getEmployeeType","classification":"READ","paramCount":1,"schema":"dba2936b2a4e","response":"02c4f766f388","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getEmployeeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"2851c6c5b230","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getGroup","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"f06d2d858884","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroupEmails","classification":"READ","paramCount":1,"schema":"ab09ef9264af","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroupMembers","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"f218e882144b","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroups","classification":"READ","paramCount":4,"schema":"f382292e4c25","response":"878696d68be4","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getInvitable","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3173c3a99146","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarCertificationReport","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"203ea6eb1a16","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarCertificationStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"6afd62a22e82","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarEntityCertification","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c5ae95ca48db","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getModules","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3f7ca035e170","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getPermissionsByEmployeeType","classification":"READ","paramCount":1,"schema":"dba2936b2a4e","response":"9b77a39f3bec","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getSuppliers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"c096e3fa1fac","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getUnrevokedInviteEmails","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a6b0124b4410","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUserEmails","classification":"READ","paramCount":1,"schema":"e0b0d488de80","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUsers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e2e6268ff023","injectAuth":"companyId","permission":"users:view","paginates":false},- {"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","permission":"users:create","paginates":false},- {"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"7fdfa4c9e77e","injectAuth":"companyId","permission":"users:update","paginates":false},- {"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"c9c1df9c3e28","injectAuth":"companyId+userId","permission":"users:view","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}+ {"name":"accounting_closePeriod","classification":"WRITE","schema":"7e5905ac5974","response":"7e5905ac5974","permission":"accounting:update","paginates":false},+ {"name":"accounting_closeTaskComplete","classification":"WRITE","schema":"5d2e9a90637b","response":"48f7f6d71e5b","permission":"accounting:update","paginates":false},+ {"name":"accounting_closeTaskSkip","classification":"WRITE","schema":"8d4ab2b60f5f","response":"d53c8b4f27a6","permission":"accounting:update","paginates":false},+ {"name":"accounting_createAccount","classification":"WRITE","schema":"3bc75269b2b8","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createCostCenter","classification":"WRITE","schema":"4f2a7b7e1601","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createDepreciationRun","classification":"WRITE","schema":"9401c1cd4d61","response":"20eda0d52ae4","permission":"accounting:create","paginates":false},+ {"name":"accounting_createDimension","classification":"DESTRUCTIVE","schema":"9fe9f795f35e","response":"660c8bead643","permission":"accounting:create","paginates":false},+ {"name":"accounting_createFiscalYearPeriods","classification":"WRITE","schema":"96bc1e1d05f5","response":"none","permission":"accounting:create","paginates":false},+ {"name":"accounting_createFixedAssetClass","classification":"WRITE","schema":"8889fba12746","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createIntercompanyTransaction","classification":"WRITE","schema":"dc8b65b9e82b","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createJournalEntry","classification":"WRITE","schema":"31b84d65b2ac","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createPaymentTerm","classification":"WRITE","schema":"7f289a52d7a3","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createProject","classification":"WRITE","schema":"cc11e09ab2f2","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createReportView","classification":"WRITE","schema":"4889a27f1969","response":"47a0e7255225","permission":"accounting:create","paginates":false},+ {"name":"accounting_createRevenueRecognitionRun","classification":"WRITE","schema":"a02c6a31de72","response":"8de1454829be","permission":"accounting:create","paginates":false},+ {"name":"accounting_createRunForPeriod","classification":"WRITE","schema":"28912dee175b","response":"1ce13dc8733f","permission":"accounting:create+update","paginates":false},+ {"name":"accounting_deleteAccount","classification":"DESTRUCTIVE","schema":"222849c8127a","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteAccountingPeriod","classification":"DESTRUCTIVE","schema":"5d9d38de5f83","response":"none","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteCostCenter","classification":"DESTRUCTIVE","schema":"478605fd0ab8","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteDepreciationRun","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteDimension","classification":"DESTRUCTIVE","schema":"b616d16ebae0","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteFixedAsset","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteFixedAssetClass","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteJournalEntry","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deletePaymentTerm","classification":"DESTRUCTIVE","schema":"e6ee32931e18","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteProject","classification":"DESTRUCTIVE","schema":"2f03472509a0","response":"3797626bd17e","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteReportView","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteRevenueRecognitionRun","classification":"DESTRUCTIVE","schema":"8245d2d4cee4","response":"061737c09176","permission":"accounting:delete","paginates":false},+ {"name":"accounting_disposeFixedAsset","classification":"DESTRUCTIVE","schema":"3e2c8c66ce93","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_generateEliminations","classification":"WRITE","schema":"27e39011ce14","response":"cddf8275afa1","permission":"accounting:create","paginates":false},+ {"name":"accounting_getAccount","classification":"READ","schema":"222849c8127a","response":"dc3cb968a42d","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingPeriodDeletability","classification":"READ","schema":"5d9d38de5f83","response":"79634239b4bc","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingPeriods","classification":"READ","schema":"31b84d65b2ac","response":"5de8ace458f4","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingSyncTieOut","classification":"READ","schema":"640626a59ffa","response":"5483e69d7515","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","schema":"a520387e09b1","response":"a5febf12f4bd","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountLedger","classification":"READ","schema":"87322609d2e6","response":"ba2b28ce7bfa","permission":"accounting:view","paginates":true},++ {"name":"accounting_getAccountLedger","classification":"READ","schema":"499320a6edfa","response":"ba2b28ce7bfa","permission":"accounting:view","paginates":true},+ {"name":"accounting_getAccountLedgerSummary","classification":"READ","schema":"758332a33a48","response":"0a28a92b28ff","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountsInScope","classification":"READ","schema":"cbb92564d684","response":"4c52cef1b6ab","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountsList","classification":"READ","schema":"8d4134f63d41","response":"814d9b75e8f1","permission":"accounting:view","paginates":false},+ {"name":"accounting_getActiveDimensionsWithValues","classification":"READ","schema":"31b84d65b2ac","response":"5dd5adb8dbbf","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAssetDepreciationHistory","classification":"READ","schema":"61a61364de24","response":"00c2fc9fdb8b","permission":"accounting:view","paginates":false},+ {"name":"accounting_getBaseCurrency","classification":"READ","schema":"31b84d65b2ac","response":"11af3b92d80f","permission":"accounting:view","paginates":false},+ {"name":"accounting_getChartOfAccounts","classification":"READ","schema":"760cd5349e96","response":"bba294781cb0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCompaniesInGroup","classification":"READ","schema":"31b84d65b2ac","response":"032bba337af7","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCenter","classification":"READ","schema":"478605fd0ab8","response":"f7b898d20847","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCentersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCentersTree","classification":"READ","schema":"31b84d65b2ac","response":"b4505b9334e6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrencies","classification":"READ","schema":"3180b86756b2","response":"1d6055ff487c","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrenciesList","classification":"READ","schema":"31b84d65b2ac","response":"01628a6ebd21","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrency","classification":"READ","schema":"c5a03b3ef7c2","response":"6d5bae3dafd5","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrencyByCode","classification":"READ","schema":"8775a38b3ca9","response":"300e136d14d0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDefaultAccounts","classification":"READ","schema":"31b84d65b2ac","response":"8460f8427611","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDeferredRevenueWaterfall","classification":"READ","schema":"c26b9971346c","response":"b51e2e003282","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDepreciationRun","classification":"READ","schema":"7f8214d1083f","response":"22ccbb1556ab","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDepreciationRunLines","classification":"READ","schema":"f440962f839e","response":"9c31ce726755","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRuns","classification":"READ","schema":"cd40ae40fad5","response":"a5ca776abeec","permission":"accounting:view","paginates":true},++ {"name":"accounting_getDepreciationRuns","classification":"READ","schema":"cd40ae40fad5","response":"aebdcfa38601","permission":"accounting:view","paginates":true},+ {"name":"accounting_getDimension","classification":"READ","schema":"b616d16ebae0","response":"86872741fb27","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensionPivot","classification":"READ","schema":"5c152cd0e76b","response":"c7069f830357","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensionPivotLines","classification":"READ","schema":"9047d926f652","response":"100f0689af3e","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensions","classification":"READ","schema":"cd40ae40fad5","response":"ca259fd73665","permission":"accounting:view","paginates":true},+ {"name":"accounting_getExchangeRate","classification":"READ","schema":"8775a38b3ca9","response":"cddf8275afa1","permission":"accounting:view","paginates":false},+ {"name":"accounting_getExchangeRateHistory","classification":"READ","schema":"8775a38b3ca9","response":"ab784d246338","permission":"accounting:view","paginates":false},+ {"name":"accounting_getExchangeRates","classification":"READ","schema":"31b84d65b2ac","response":"7089bfe7df7a","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFinancialStatementBalances","classification":"READ","schema":"031a3bd9c34e","response":"bba294781cb0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFinancialStatementPeriodSeries","classification":"READ","schema":"2fa2b0df3ab1","response":"5483e69d7515","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFiscalCalendarCommitted","classification":"READ","schema":"31b84d65b2ac","response":"854b90f7a9d3","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFiscalYearSettings","classification":"READ","schema":"31b84d65b2ac","response":"b9513b822ab3","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAsset","classification":"READ","schema":"7f8214d1083f","response":"cb32d8b6885b","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetCipCosts","classification":"READ","schema":"61a61364de24","response":"03707172e0ba","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetClass","classification":"READ","schema":"7f8214d1083f","response":"a74e56b11f76","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetClasses","classification":"READ","schema":"cd40ae40fad5","response":"458d93060a99","permission":"accounting:view","paginates":true},+ {"name":"accounting_getFixedAssetClassesList","classification":"READ","schema":"31b84d65b2ac","response":"626546da6867","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetDisposal","classification":"READ","schema":"61a61364de24","response":"4b37a6513b87","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssets","classification":"READ","schema":"082e00a00256","response":"8a1d12afa935","permission":"accounting:view","paginates":true},++ {"name":"accounting_getFixedAssets","classification":"READ","schema":"082e00a00256","response":"c1c8aa88f147","permission":"accounting:view","paginates":true},+ {"name":"accounting_getFixedAssetTransfers","classification":"READ","schema":"61a61364de24","response":"42e9b68a4dcb","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFleetAssets","classification":"READ","schema":"4a69a20d62a7","response":"a1d2b71b7a6b","permission":"accounting:view","paginates":true},+ {"name":"accounting_getGroupAccounts","classification":"READ","schema":"31b84d65b2ac","response":"35cdc3cd0949","permission":"accounting:view","paginates":false},+ {"name":"accounting_getIntercompanyTransactions","classification":"READ","schema":"ec1adf416124","response":"37a244ba1bd0","permission":"accounting:view","paginates":true},+ {"name":"accounting_getJournalEntries","classification":"READ","schema":"2e7d46bd3904","response":"94203365d86c","permission":"accounting:view","paginates":true},+ {"name":"accounting_getJournalEntry","classification":"READ","schema":"7f8214d1083f","response":"37370aa756c4","permission":"accounting:view","paginates":false},+ {"name":"accounting_getJournalLineDimensions","classification":"READ","schema":"49b26fe1c26e","response":"b731368c1d3c","permission":"accounting:view","paginates":false},+ {"name":"accounting_getLeaseLiabilities","classification":"READ","schema":"bae0cdb5c2a5","response":"none","permission":"accounting:view","paginates":false},+ {"name":"accounting_getLeaseNetInvestment","classification":"READ","schema":"c26b9971346c","response":"8de1c4536c37","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPaymentTerm","classification":"READ","schema":"e6ee32931e18","response":"3cf7f3f31dc2","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPaymentTerms","classification":"READ","schema":"cd40ae40fad5","response":"fb989e3bd774","permission":"accounting:view","paginates":true},+ {"name":"accounting_getPaymentTermsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPeriodCloseChecklist","classification":"WRITE","schema":"5d9d38de5f83","response":"6e4603e62d91","permission":"accounting:update","paginates":false},+ {"name":"accounting_getPeriodRunRelatedItems","classification":"READ","schema":"fc10f96fcd01","response":"523a70af9ece","permission":"accounting:view","paginates":false},+ {"name":"accounting_getProject","classification":"READ","schema":"2f03472509a0","response":"b9294ccc5a24","permission":"accounting:view","paginates":false},+ {"name":"accounting_getProjects","classification":"READ","schema":"cd40ae40fad5","response":"22648003a5b3","permission":"accounting:view","paginates":true},+ {"name":"accounting_getPurchaseLinePivot","classification":"READ","schema":"1a8c8fa33252","response":"c7069f830357","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPurchaseLinePivotLines","classification":"READ","schema":"e65393fd70a5","response":"a12b8efe2d62","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRentalUtilization","classification":"READ","schema":"ed2c56398ce1","response":"80fa6e3c40ad","permission":"accounting:view","paginates":false},+ {"name":"accounting_getReportPins","classification":"READ","schema":"31b84d65b2ac","response":"3536c9c9a314","permission":"accounting:view","paginates":false},+ {"name":"accounting_getReportViews","classification":"READ","schema":"a7dc8d549b08","response":"67772a9f686d","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRevenueRecognitionRun","classification":"READ","schema":"7f8214d1083f","response":"fb8cbba30867","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRevenueRecognitionRunLines","classification":"READ","schema":"60d79fe0873e","response":"5622278817dc","permission":"accounting:view","paginates":false},+ {"name":"accounting_getScrapAccountIds","classification":"READ","schema":"31b84d65b2ac","response":"681004346c78","permission":"accounting:view","paginates":false},+ {"name":"accounting_getWorkCenterCapitalCost","classification":"READ","schema":"f1e2fb0e86e7","response":"8bd5c08050f0","permission":"accounting:view","paginates":false},+ {"name":"accounting_insertFixedAsset","classification":"WRITE","schema":"bc3b9496277a","response":"e0e9c463a967","permission":"accounting:create","paginates":false},+ {"name":"accounting_invokeAssetTransfer","classification":"WRITE","schema":"840df8cd1746","response":"c84f5bab4f4d","permission":"accounting:update","paginates":false},+ {"name":"accounting_lockPeriod","classification":"WRITE","schema":"7e5905ac5974","response":"225369d393b0","permission":"accounting:update","paginates":false},+ {"name":"accounting_moveAccount","classification":"WRITE","schema":"58f5301405fc","response":"ecb746f60913","permission":"accounting:update","paginates":false},+ {"name":"accounting_overrideExchangeRate","classification":"WRITE","schema":"4576f689f2fa","response":"4576f689f2fa","permission":"accounting:update","paginates":false},+ {"name":"accounting_postDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:update","paginates":false},+ {"name":"accounting_postJournalEntry","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_postRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_purchaseFixedAsset","classification":"WRITE","schema":"0ef013992fdf","response":"28cffcd9d6e8","permission":"purchasing:create","paginates":false},+ {"name":"accounting_recalculateDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"d325c86b5677","permission":"accounting:update","paginates":false},+ {"name":"accounting_recalculateRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"1be43fc6832f","permission":"accounting:update","paginates":false},+ {"name":"accounting_registerFixedAsset","classification":"WRITE","schema":"ec5d79eeaeca","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_repeatDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:create","paginates":false},+ {"name":"accounting_repeatRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"8de1454829be","permission":"accounting:create","paginates":false},+ {"name":"accounting_resetExchangeRate","classification":"DESTRUCTIVE","schema":"cc2bce783cc5","response":"cc2bce783cc5","permission":"accounting:update","paginates":false},+ {"name":"accounting_returnFixedAssetToService","classification":"WRITE","schema":"91f483e6fee8","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseDepreciationRun","classification":"DESTRUCTIVE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseJournalEntry","classification":"WRITE","schema":"399fe1b9a54f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseRevenueRecognitionRun","classification":"DESTRUCTIVE","schema":"8245d2d4cee4","response":"898100ba0a91","permission":"accounting:update","paginates":false},+ {"name":"accounting_runIntercompanyMatching","classification":"WRITE","schema":"31b84d65b2ac","response":"c07d47c6ac75","permission":"accounting:update","paginates":false},+ {"name":"accounting_saveJournalEntry","classification":"DESTRUCTIVE","schema":"dbc95bc1ed8a","response":"072fdafde3d3","permission":"accounting:update","paginates":false},+ {"name":"accounting_saveJournalLineDimensions","classification":"DESTRUCTIVE","schema":"7c44a0e2c058","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_sellFixedAsset","classification":"WRITE","schema":"120c7048d1d4","response":"d160a49d6787","permission":"sales:create","paginates":false},+ {"name":"accounting_takeFixedAssetOutOfService","classification":"WRITE","schema":"f83b81b1e0ba","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_translateCompanyBalances","classification":"WRITE","schema":"3ee2ef8fce02","response":"be5b093fb6e6","permission":"accounting:update","paginates":false},+ {"name":"accounting_unlockPeriod","classification":"WRITE","schema":"7e5905ac5974","response":"be1ed439f12a","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateAccount","classification":"WRITE","schema":"d810ef7c1f8c","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateCostCenter","classification":"WRITE","schema":"d3ac6d2d2bb9","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateCurrency","classification":"WRITE","schema":"7f4f47859592","response":"0e98c276626d","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateDefaultAccounts","classification":"WRITE","schema":"7eafac321195","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateDimension","classification":"DESTRUCTIVE","schema":"bc296a45be9e","response":"660c8bead643","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFiscalYearSettings","classification":"WRITE","schema":"fb433e35b233","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFixedAsset","classification":"WRITE","schema":"7cf19679ef1c","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFixedAssetClass","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updatePaymentTerm","classification":"WRITE","schema":"c587f43c70ec","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateProject","classification":"WRITE","schema":"a7f9ae38f142","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateReportView","classification":"WRITE","schema":"1a8d77edd96c","response":"47a0e7255225","permission":"accounting:update","paginates":false},+ {"name":"accounting_upsertReportPin","classification":"WRITE","schema":"5451b17c4b2c","response":"bcde375ebd4c","permission":"accounting:create+update","paginates":false},+ {"name":"documents_createDocument","classification":"WRITE","schema":"6bdbd3c91adf","response":"1fd372019111","permission":"documents:create","paginates":false},+ {"name":"documents_createDocumentUploadUrl","classification":"WRITE","schema":"01e8421410da","response":"4ad76afe0777","permission":"documents:create","paginates":false},+ {"name":"documents_deleteDocument","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:delete","paginates":false},+ {"name":"documents_getDocument","classification":"READ","schema":"1a362ab8a372","response":"985e02706d13","permission":"documents:view","paginates":false},+ {"name":"documents_getDocumentExtensions","classification":"READ","schema":"31b84d65b2ac","response":"a07a74ca3dd1","permission":"documents:view","paginates":false},+ {"name":"documents_getDocumentLabels","classification":"READ","schema":"31b84d65b2ac","response":"7e2eeb0066ab","permission":"documents:view","paginates":false},+ {"name":"documents_getDocuments","classification":"READ","schema":"40f5b9564fa8","response":"236702fe3f96","permission":"documents:view","paginates":true},+ {"name":"documents_insertDocumentExtraction","classification":"WRITE","schema":"2d09a729f243","response":"d181256b2684","permission":"documents:create","paginates":false},+ {"name":"documents_insertUploadedDocument","classification":"WRITE","schema":"593f625cc9b6","response":"1fd372019111","permission":"documents:create","paginates":false},+ {"name":"documents_moveDocumentToTrash","classification":"WRITE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_restoreDocument","classification":"WRITE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocument","classification":"WRITE","schema":"de7ba932aaf3","response":"1fd372019111","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocumentFavorite","classification":"WRITE","schema":"ff73dc321969","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","schema":"b97e2ad30e97","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"inventory_adjustInventory","classification":"WRITE","schema":"6bea071798b4","response":"637aa3a8adf9","permission":"inventory:create+update","paginates":false},+ {"name":"inventory_assignReceiptReturnEntity","classification":"WRITE","schema":"82c3b94b252f","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_assignShipmentLineEntity","classification":"WRITE","schema":"ef225f89d1f1","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_correctStockMovement","classification":"WRITE","schema":"11e4a2d8d923","response":"baa524ddff70","permission":"inventory:update","paginates":false},+ {"name":"inventory_createInventoryCount","classification":"WRITE","schema":"2657c9ab7b5b","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","schema":"0f10306ad40d","response":"a9f23ceb9dc1","permission":"accounting:create","paginates":false},+ {"name":"inventory_createKanban","classification":"WRITE","schema":"1c14c201bb53","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createReceipt","classification":"WRITE","schema":"12978f9841f2","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createShipment","classification":"WRITE","schema":"40665d54c304","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createShippingMethod","classification":"WRITE","schema":"35c841d658b9","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStockTransfer","classification":"WRITE","schema":"d2eae4a05698","response":"8db339addf8f","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStockTransferLine","classification":"WRITE","schema":"61a124703a26","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStorageType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"inventory_createStorageUnit","classification":"WRITE","schema":"8dc350e360ad","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createWarehouseTransferLine","classification":"WRITE","schema":"1c4aec41902a","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteInventoryCount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteKanban","classification":"DESTRUCTIVE","schema":"84ad7166f1d7","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deletePickingList","classification":"DESTRUCTIVE","schema":"06ea967dd6ad","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteReceipt","classification":"DESTRUCTIVE","schema":"85cf4fd2917f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteReceiptLine","classification":"DESTRUCTIVE","schema":"76ee331dd860","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShipment","classification":"DESTRUCTIVE","schema":"42e517e4587d","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShipmentLine","classification":"DESTRUCTIVE","schema":"dc59afd93e49","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShippingMethod","classification":"DESTRUCTIVE","schema":"b1c3932e1f43","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStockTransfer","classification":"DESTRUCTIVE","schema":"948b16d8b971","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStockTransferLine","classification":"DESTRUCTIVE","schema":"eed9b4ba65ee","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","schema":"684fb584dd36","response":"3797626bd17e","permission":"parts:delete","paginates":false},+ {"name":"inventory_deleteWarehouseTransfer","classification":"DESTRUCTIVE","schema":"e5cf2745c429","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_expandStorageUnitIdsWithDescendants","classification":"READ","schema":"5faaa8568e95","response":"681004346c78","permission":"inventory:view","paginates":false},+ {"name":"inventory_generatePickingList","classification":"DESTRUCTIVE","schema":"3af73486ff99","response":"81802516b555","permission":"inventory:create","paginates":false},+ {"name":"inventory_getAvailableTrackedEntities","classification":"READ","schema":"c77d0fdb7e5d","response":"723554a256de","permission":"inventory:view","paginates":false},+ {"name":"inventory_getBatchNumbersForItem","classification":"READ","schema":"c7f807b08655","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getBatchProperties","classification":"READ","schema":"fb8f0e541b3e","response":"549cd4e15464","permission":"inventory:view","paginates":false},+ {"name":"inventory_getEffectiveWorkCenterId","classification":"READ","schema":"cdcc95c01599","response":"00404e686415","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCount","classification":"READ","schema":"7f8214d1083f","response":"635fd5c7963f","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCountLines","classification":"READ","schema":"3aee3496423b","response":"8f948fe95e1e","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryCountLineSummary","classification":"READ","schema":"bb4fa87fa88a","response":"7a06e37fcf2a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCountMovements","classification":"READ","schema":"bb4fa87fa88a","response":"ef7ba4828665","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCounts","classification":"READ","schema":"cd40ae40fad5","response":"257241cd106b","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryItems","classification":"READ","schema":"a135d0d54fd9","response":"0ea3e86b6ae1","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryValuation","classification":"READ","schema":"4affbce60a61","response":"d2c7dd5f845a","permission":"accounting:view","paginates":false},+ {"name":"inventory_getInventoryValuationTieOut","classification":"READ","schema":"70fbe1224878","response":"20aee38c95a3","permission":"accounting:view","paginates":false},+ {"name":"inventory_getItemLedgerActivity","classification":"READ","schema":"019d7d34869e","response":"855f6c444e56","permission":"inventory:view","paginates":false},+ {"name":"inventory_getItemLedgerBalance","classification":"READ","schema":"798c87d1101b","response":"cddf8275afa1","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanban","classification":"READ","schema":"84ad7166f1d7","response":"a4f312fff33a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanbanProjectedQuantities","classification":"READ","schema":"333fb45d8bc5","response":"98903cc375ce","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanbans","classification":"READ","schema":"a135d0d54fd9","response":"10c63802d01c","permission":"inventory:view","paginates":true},+ {"name":"inventory_getPickingList","classification":"READ","schema":"06ea967dd6ad","response":"bdbdc3b12cd7","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListAvailability","classification":"READ","schema":"06ea967dd6ad","response":"a2c799262a3c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListLine","classification":"READ","schema":"e2b1df794940","response":"58364897e03b","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListLines","classification":"READ","schema":"06ea967dd6ad","response":"eb327ca3ae07","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListRecommendations","classification":"READ","schema":"06ea967dd6ad","response":"24283057a15d","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListRelatedItems","classification":"READ","schema":"06ea967dd6ad","response":"97b485f3b5e3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingLists","classification":"READ","schema":"e0cc1a02c61f","response":"143c1acfb4cd","permission":"inventory:view","paginates":true},+ {"name":"inventory_getPickingSchedule","classification":"READ","schema":"bfb3c1ae0982","response":"ce619e8c4917","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickOrder","classification":"READ","schema":"624646b5f0ec","response":"9f5ba8273e4a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPicksByJobMaterial","classification":"READ","schema":"ca49bc65b712","response":"b53992cb5f0c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceipt","classification":"READ","schema":"85cf4fd2917f","response":"32c1c823ab1f","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptFiles","classification":"READ","schema":"72a93572f55f","response":"5483e69d7515","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptLines","classification":"READ","schema":"85cf4fd2917f","response":"15b7b17f7652","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptRelatedItems","classification":"READ","schema":"8a3528c62244","response":"2f7d31c914c3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceipts","classification":"READ","schema":"cd40ae40fad5","response":"c0e9f6bbdcad","permission":"inventory:view","paginates":true},+ {"name":"inventory_getReceiptTracking","classification":"READ","schema":"85cf4fd2917f","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getRentalReceiptLines","classification":"READ","schema":"85cf4fd2917f","response":"7fb4d944b992","permission":"inventory:view","paginates":false},+ {"name":"inventory_getRentalShipmentLines","classification":"READ","schema":"42e517e4587d","response":"81dce2e81f32","permission":"inventory:view","paginates":false},+ {"name":"inventory_getSerialNumbersForItem","classification":"READ","schema":"30ab89ff5be9","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getSerialUnitCosts","classification":"READ","schema":"d8cb61960dff","response":"97d1e7eb3966","permission":"accounting:view","paginates":false},+ {"name":"inventory_getShelfLifeForItems","classification":"READ","schema":"fb8f0e541b3e","response":"89287a5cd5c2","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipment","classification":"READ","schema":"42e517e4587d","response":"cf4ab10c35e3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipmentLines","classification":"READ","schema":"42e517e4587d","response":"a8d2ad5b9993","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipmentRelatedItems","classification":"READ","schema":"d8f45c9e7f04","response":"ced6a1949e63","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipments","classification":"READ","schema":"cd40ae40fad5","response":"496419b3de9a","permission":"inventory:view","paginates":true},+ {"name":"inventory_getShipmentTracking","classification":"READ","schema":"42e517e4587d","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingMethod","classification":"READ","schema":"b1c3932e1f43","response":"21907ace7452","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingMethods","classification":"READ","schema":"cd40ae40fad5","response":"3b04f1c33636","permission":"inventory:view","paginates":true},+ {"name":"inventory_getShippingMethodsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingTermsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","schema":"be17c4d58a6a","response":"2e1967d88231","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockMovements","classification":"READ","schema":"cd40ae40fad5","response":"5a637523d776","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStockTransfer","classification":"READ","schema":"948b16d8b971","response":"69c0eeefc47c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockTransferLines","classification":"READ","schema":"948b16d8b971","response":"bcb01288cc29","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockTransfers","classification":"READ","schema":"595681c48d73","response":"b4c0b46b39b5","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStorageType","classification":"READ","schema":"7f8214d1083f","response":"4bbb50609deb","permission":"parts:view","paginates":false},+ {"name":"inventory_getStorageTypes","classification":"READ","schema":"cd40ae40fad5","response":"f6f55833db42","permission":"parts:view","paginates":true},+ {"name":"inventory_getStorageTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageTypeUsage","classification":"READ","schema":"7f8214d1083f","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"inventory_getStorageUnit","classification":"READ","schema":"cdcc95c01599","response":"a5bf237a9aeb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitChildren","classification":"READ","schema":"a3bb93ab688c","response":"7eea15677f40","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitDescendants","classification":"READ","schema":"cdcc95c01599","response":"3bae190e2656","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitParentIdsWithChildren","classification":"READ","schema":"75b90f67d533","response":"681004346c78","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitRoots","classification":"READ","schema":"a135d0d54fd9","response":"dd81c689cce6","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStorageUnitsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitsListForLocation","classification":"READ","schema":"75b90f67d533","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitsTreeForLocation","classification":"READ","schema":"75b90f67d533","response":"ecdf2c570468","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitSubtrees","classification":"READ","schema":"b9bea08b8fcd","response":"10e6a05f40e5","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntities","classification":"READ","schema":"cd40ae40fad5","response":"15f4dee0e3cd","permission":"inventory:view","paginates":true},+ {"name":"inventory_getTrackedEntitiesByMakeMethodId","classification":"READ","schema":"7679db37b5f9","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntity","classification":"READ","schema":"461bb7f6bafb","response":"1007059c8406","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntityExpirations","classification":"READ","schema":"518b9dee6f55","response":"fff84b1ee888","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransfer","classification":"READ","schema":"e5cf2745c429","response":"97efc7703189","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferLine","classification":"READ","schema":"e22f9f5a0cc9","response":"ff87020af237","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferLines","classification":"READ","schema":"e5cf2745c429","response":"4cdf01fbc41c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferRelatedItems","classification":"READ","schema":"e5cf2745c429","response":"d866112ded31","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransfers","classification":"READ","schema":"cd40ae40fad5","response":"66af9aaf6283","permission":"inventory:view","paginates":true},+ {"name":"inventory_insertWarehouseTransfer","classification":"WRITE","schema":"82ec35c02526","response":"8e9431d157a2","permission":"inventory:create","paginates":false},+ {"name":"inventory_mergeTrackedEntities","classification":"WRITE","schema":"b12fee74a91e","response":"none","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickPickingListLineChecked","classification":"WRITE","schema":"f50f15524edc","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickPickingListLineEntity","classification":"WRITE","schema":"5a008770ac64","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickStockTransferLine","classification":"WRITE","schema":"0d3ec0c22afe","response":"7ad8a3f49853","permission":"inventory:create","paginates":false},+ {"name":"inventory_pickStockTransferLineEntity","classification":"WRITE","schema":"d077ae617fd9","response":"7ad8a3f49853","permission":"inventory:update","paginates":false},+ {"name":"inventory_postInventoryCount","classification":"WRITE","schema":"e354150046fe","response":"c65e556842f4","permission":"inventory:update","paginates":false},+ {"name":"inventory_postReceipt","classification":"WRITE","schema":"748c476fdf2b","response":"727cf771e24b","permission":"inventory:update","paginates":false},+ {"name":"inventory_postShipment","classification":"WRITE","schema":"c5945bba6ca6","response":"d2fbdd9c8de9","permission":"inventory:update","paginates":false},+ {"name":"inventory_recostSerialUnit","classification":"WRITE","schema":"c3f4c85c02d3","response":"1791201245a6","permission":"accounting:update","paginates":false},+ {"name":"inventory_removeReceiptReturnEntity","classification":"WRITE","schema":"727806547880","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_removeStorageUnit","classification":"DESTRUCTIVE","schema":"35393c22f425","response":"2483090811c4","permission":"inventory:delete","paginates":false},+ {"name":"inventory_removeWarehouseTransferLine","classification":"DESTRUCTIVE","schema":"e969960c72a3","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","schema":"60d210afc3c8","response":"bcde375ebd4c","permission":"inventory:view","paginates":false},+ {"name":"inventory_setPickingListStatus","classification":"WRITE","schema":"ccde50ab0ad1","response":"f08c04238f16","permission":"inventory:update","paginates":false},+ {"name":"inventory_setReceiptLineBatch","classification":"WRITE","schema":"9e81223e8999","response":"17337505bb69","permission":"inventory:create","paginates":false},+ {"name":"inventory_setReceiptLineSerial","classification":"WRITE","schema":"0993bde06f1d","response":"535137f2982a","permission":"inventory:create","paginates":false},+ {"name":"inventory_setStockTransferStatus","classification":"WRITE","schema":"afbc91bb3596","response":"734f52cb2f24","permission":"inventory:update","paginates":false},+ {"name":"inventory_setWarehouseTransferStatus","classification":"WRITE","schema":"9a60ace036e6","response":"5ca40ef79448","permission":"inventory:update","paginates":false},+ {"name":"inventory_splitReceiptLine","classification":"WRITE","schema":"9530619bf74b","response":"17337505bb69","permission":"inventory:update","paginates":false},+ {"name":"inventory_splitShipmentLine","classification":"WRITE","schema":"34f9c93ce7da","response":"84320a09c1ac","permission":"inventory:update","paginates":false},+ {"name":"inventory_unpickStockTransferLine","classification":"WRITE","schema":"9caff79be87e","response":"7ad8a3f49853","permission":"inventory:create","paginates":false},+ {"name":"inventory_updateBatchPropertyOrder","classification":"WRITE","schema":"12f0062fbf60","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateInventoryCountLine","classification":"WRITE","schema":"e59c475ac625","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateInventoryCountStatus","classification":"WRITE","schema":"7ef2505ff688","response":"7ef2505ff688","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateKanban","classification":"WRITE","schema":"78797e4ff232","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updatePickingList","classification":"WRITE","schema":"cb8e9e110bfa","response":"0a4ec3e7319b","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceipt","classification":"WRITE","schema":"02e274bc337e","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceiptFixedAssetLine","classification":"WRITE","schema":"a7515d002c5d","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceiptLines","classification":"WRITE","schema":"3a91317efcce","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipment","classification":"WRITE","schema":"14ecca1fc57d","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipmentFixedAssetLine","classification":"WRITE","schema":"ab168f9d9366","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipmentLines","classification":"WRITE","schema":"3a4fe03b9c85","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShippingMethod","classification":"WRITE","schema":"1b5e5991be6c","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateStockTransferLine","classification":"WRITE","schema":"3577763da43f","response":"3797626bd17e","permission":"inventory:create+update","paginates":false},+ {"name":"inventory_updateStockTransferLines","classification":"WRITE","schema":"17ef89b7d868","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateStorageType","classification":"WRITE","schema":"7b9e512cc925","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"inventory_updateStorageUnit","classification":"WRITE","schema":"62405012c8e5","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateTrackedEntityExpiry","classification":"WRITE","schema":"80b2e16440b3","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateWarehouseTransfer","classification":"WRITE","schema":"34bffa7fa259","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateWarehouseTransferLine","classification":"WRITE","schema":"83d5ec885100","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_upsertBatchProperty","classification":"WRITE","schema":"f0713a3f9fb4","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_voidReceipt","classification":"DESTRUCTIVE","schema":"e00a9764517d","response":"e00a9764517d","permission":"inventory:update","paginates":false},+ {"name":"inventory_voidShipment","classification":"DESTRUCTIVE","schema":"2e39a760a5ca","response":"2e39a760a5ca","permission":"inventory:update","paginates":false},+ {"name":"invoicing_adjustPayables","classification":"WRITE","schema":"783894538b85","response":"7e2279b19577","permission":"accounting:create","paginates":false},+ {"name":"invoicing_adjustReceivables","classification":"WRITE","schema":"783894538b85","response":"7e2279b19577","permission":"accounting:create","paginates":false},+ {"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","schema":"44fe03d8575b","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_createMemo","classification":"WRITE","schema":"dcabfad9d03c","response":"1e0d0fa1a854","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPayment","classification":"WRITE","schema":"655768d847ef","response":"9afa42aa85f3","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoice","classification":"WRITE","schema":"9de21d765491","response":"24b4b1602470","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","schema":"47850e9f092b","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoiceLine","classification":"WRITE","schema":"d8628a901bbc","response":"3797626bd17e","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","schema":"6e4655763b3f","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceFromShipment","classification":"WRITE","schema":"42e517e4587d","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceLine","classification":"WRITE","schema":"7cf0f0de23bd","response":"2f2c2a380211","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_deleteDraftMemo","classification":"DESTRUCTIVE","schema":"188417093a55","response":"dc19b5347651","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftPurchaseInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftPurchaseInvoiceLine","classification":"DESTRUCTIVE","schema":"97778f2244c8","response":"97778f2244c8","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftSalesInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftSalesInvoiceLine","classification":"DESTRUCTIVE","schema":"97778f2244c8","response":"97778f2244c8","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deletePayment","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_getApAging","classification":"READ","schema":"022511e83f02","response":"eca97da3238d","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getApOpenBySupplier","classification":"READ","schema":"0f10306ad40d","response":"cfaa2af435c0","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getApTieOut","classification":"READ","schema":"0f10306ad40d","response":"194f80599d96","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArAging","classification":"READ","schema":"022511e83f02","response":"10729e9f1c72","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArOpenByCustomer","classification":"READ","schema":"0f10306ad40d","response":"8cd731dddf0d","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArTieOut","classification":"READ","schema":"0f10306ad40d","response":"194f80599d96","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getAvailableCreditsForParty","classification":"READ","schema":"1724f4d913e4","response":"f8e7a5443d43","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getAvailableOnAccountCreditSources","classification":"READ","schema":"0da34ef6d281","response":"6d10888c4cf8","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getCharge","classification":"READ","schema":"7f8214d1083f","response":"9429143db43f","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getCharges","classification":"READ","schema":"afddaef7228a","response":"8b1485171a5a","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getCompanyHasOpenCredits","classification":"READ","schema":"75e0842dae15","response":"4a5fff977a84","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getInvoiceSettlements","classification":"READ","schema":"b4184c2c9476","response":"5483e69d7515","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","schema":"3ec6c9a760cc","response":"a334c4e05d56","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemo","classification":"READ","schema":"7f8214d1083f","response":"98fffe52edef","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemoApplications","classification":"READ","schema":"b41339a8c21f","response":"8b54c25de723","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemos","classification":"READ","schema":"5c12cebcdff5","response":"ec5a471a7216","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","schema":"eeadc5002c42","response":"a16080b3cb31","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenReimbursementsForEmployee","classification":"READ","schema":"3cea1230c460","response":"84fe5db303b4","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","schema":"0de5d59cc116","response":"a16080b3cb31","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPayment","classification":"READ","schema":"7f8214d1083f","response":"f122ccd210ed","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","schema":"8775a38b3ca9","response":"35b15cbf37ce","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPayments","classification":"READ","schema":"e33a51df175c","response":"ba894f328d1f","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getPurchaseInvoice","classification":"READ","schema":"0f5da439c637","response":"b6cde92056ff","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceDelivery","classification":"READ","schema":"0f5da439c637","response":"cf43c4365a30","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceLine","classification":"READ","schema":"103b0006e8d5","response":"8c0b6537bf26","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceLines","classification":"READ","schema":"0f5da439c637","response":"34789e863e7e","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoices","classification":"READ","schema":"d2546c625ab2","response":"1f74efb3e9eb","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getReimbursement","classification":"READ","schema":"7f8214d1083f","response":"c1191896ef6c","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getReimbursementRelatedItems","classification":"READ","schema":"a4fa008a9ff4","response":"b44573ee4608","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getReimbursements","classification":"READ","schema":"408db1ecae6d","response":"15d72f6aca0c","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getSalesInvoice","classification":"READ","schema":"881060cc8281","response":"3fd5b06e1335","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoiceLine","classification":"READ","schema":"943ed3109227","response":"94dbec26018a","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoiceLines","classification":"READ","schema":"881060cc8281","response":"e5d8bd13c859","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoices","classification":"READ","schema":"0f73f70d24d4","response":"2713f6338edb","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getSalesInvoiceShipment","classification":"READ","schema":"881060cc8281","response":"64ebc394caae","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","schema":"2d0fe8b55e39","response":"5a23b05562f4","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_insertSalesInvoice","classification":"DESTRUCTIVE","schema":"bfaa3332658d","response":"24b4b1602470","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_mapPurchaseInvoiceLines","classification":"WRITE","schema":"f92e77ef6854","response":"2132422b3a2d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_payReimbursement","classification":"WRITE","schema":"d5ace743aeb9","response":"6abc9e87bdd2","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_postMemo","classification":"WRITE","schema":"188417093a55","response":"188417093a55","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postPayment","classification":"WRITE","schema":"bd163ca304cd","response":"bd163ca304cd","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postPurchaseInvoice","classification":"WRITE","schema":"5710b96a8949","response":"2d07f638a2bb","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postReimbursement","classification":"WRITE","schema":"1440dbb5599d","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postSalesInvoice","classification":"WRITE","schema":"4b9809c93c34","response":"aa004f6905a5","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","schema":"e0be02846a7a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_saveAndPostReimbursement","classification":"WRITE","schema":"f7e0727ee74c","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_saveReimbursement","classification":"WRITE","schema":"f7e0727ee74c","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_sendSalesInvoice","classification":"WRITE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateMemo","classification":"WRITE","schema":"4439c29367fb","response":"1e0d0fa1a854","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePayment","classification":"WRITE","schema":"84b8cdf04b9a","response":"1a922c685a61","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","schema":"c797b53746b5","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceLine","classification":"WRITE","schema":"5889b70522aa","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","schema":"536a93fbc84a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateSalesInvoiceLine","classification":"WRITE","schema":"2dbb4b6a4ebe","response":"2f2c2a380211","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","schema":"536a93fbc84a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","schema":"3f1b55f12045","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_upsertSalesInvoiceShipment","classification":"WRITE","schema":"f786af7dbb23","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidCharge","classification":"DESTRUCTIVE","schema":"e766b8931d7d","response":"e766b8931d7d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidMemo","classification":"DESTRUCTIVE","schema":"188417093a55","response":"188417093a55","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidPayment","classification":"DESTRUCTIVE","schema":"bd163ca304cd","response":"bd163ca304cd","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidPurchaseInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidReimbursement","classification":"DESTRUCTIVE","schema":"1440dbb5599d","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidSalesInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"items_activateMethodVersion","classification":"WRITE","schema":"7f8214d1083f","response":"873673b16fc8","permission":"parts:update","paginates":false},+ {"name":"items_addChangeNoticeAffectedItem","classification":"DESTRUCTIVE","schema":"624f956839eb","response":"3cc309ba4541","permission":"parts:create","paginates":false},+ {"name":"items_addItemPredecessor","classification":"WRITE","schema":"62c99356d14b","response":"c838ffde6390","permission":"parts:update","paginates":false},+ {"name":"items_assertMethodOperationIsDraft","classification":"WRITE","schema":"3561ad8e0d42","response":"c407a9edb930","permission":"parts:update","paginates":false},+ {"name":"items_copyMethod","classification":"DESTRUCTIVE","schema":"149990a9b059","response":"d12019e0a561","permission":"parts:update","paginates":false},+ {"name":"items_createChangeNotice","classification":"WRITE","schema":"4ba09c051d82","response":"8e58a21e4c94","permission":"parts:create","paginates":false},+ {"name":"items_createChangeNoticeForItem","classification":"WRITE","schema":"4fe1ddc95e07","response":"a443ac9aa1f1","permission":"parts:create","paginates":false},+ {"name":"items_createChangeNoticeType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createConsumable","classification":"WRITE","schema":"e0ed6a5c0e19","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createItemDocumentUploadUrl","classification":"WRITE","schema":"c99d2620a4f0","response":"4ad76afe0777","permission":"parts:create","paginates":false},+ {"name":"items_createItemPostingGroup","classification":"WRITE","schema":"056e8f8d8194","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createItemThumbnailUploadUrl","classification":"WRITE","schema":"6dcd390c3681","response":"e7dd9ea63165","permission":"parts:update","paginates":false},+ {"name":"items_createMaterial","classification":"WRITE","schema":"822977f984eb","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createMaterialForm","classification":"WRITE","schema":"67eb529210df","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMaterialSubstance","classification":"WRITE","schema":"67eb529210df","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodMaterial","classification":"WRITE","schema":"85baff25f028","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperation","classification":"WRITE","schema":"62965bbd75c5","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodVersion","classification":"WRITE","schema":"cd53dc57847a","response":"e83987f24b08","permission":"parts:create","paginates":false},+ {"name":"items_createModelUploadUrl","classification":"WRITE","schema":"098974972159","response":"56f546fd3bc7","permission":"parts:create+update","paginates":false},+ {"name":"items_createPart","classification":"WRITE","schema":"4206b71c74bb","response":"baa524ddff70","permission":"parts:create","paginates":false},+ {"name":"items_createPickMethod","classification":"WRITE","schema":"dbe3b3c9dd58","response":"bcde375ebd4c","permission":"parts:create","paginates":false},+ {"name":"items_createRevision","classification":"WRITE","schema":"3488d3b3792b","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createService","classification":"WRITE","schema":"8cf44c6e12d3","response":"9b123283f2f8","permission":"parts:create","paginates":false},+ {"name":"items_createSupplierPart","classification":"WRITE","schema":"7581bda3d7fb","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createTool","classification":"WRITE","schema":"3ba80371e321","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createUnitOfMeasure","classification":"WRITE","schema":"b1e51cc5e9b8","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_decideChangeNoticeApproval","classification":"WRITE","schema":"b9b5aeddd8c9","response":"7656db048f90","permission":"parts:update","paginates":false},+ {"name":"items_deleteChangeNotice","classification":"DESTRUCTIVE","schema":"ceb3bf7aba37","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeAction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeRequiredAction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeType","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationParameterGroup","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationRule","classification":"DESTRUCTIVE","schema":"5f4af67f6096","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItem","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItemCustomerPart","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItemPostingGroup","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialDimension","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialFinish","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialForm","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialGrade","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialSubstance","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialType","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodMaterial","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperation","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"c3ca3a3cb7fc","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteSupplierPart","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteUnitOfMeasure","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_duplicateMethodOperationStep","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","schema":"30ab89ff5be9","response":"4a5fff977a84","permission":"parts:view","paginates":false},+ {"name":"items_getBomItemAttributes","classification":"READ","schema":"fb8f0e541b3e","response":"a2c799262a3c","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNotice","classification":"READ","schema":"ceb3bf7aba37","response":"1a1262d4cc54","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeActions","classification":"READ","schema":"ceb3bf7aba37","response":"b7e9332382ae","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeAffectedItems","classification":"READ","schema":"ceb3bf7aba37","response":"5483e69d7515","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeDiff","classification":"READ","schema":"ceb3bf7aba37","response":"e8b6cfecb257","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeRequiredAction","classification":"READ","schema":"7f8214d1083f","response":"a76ce814b1b8","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeRequiredActions","classification":"READ","schema":"cd40ae40fad5","response":"02b33c1a9497","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticeRequiredActionsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNotices","classification":"READ","schema":"cd40ae40fad5","response":"6421ab92a21e","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticesForNonConformance","classification":"READ","schema":"9a315debddd5","response":"f1df16d41df5","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeType","classification":"READ","schema":"7f8214d1083f","response":"d15ce193a0df","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeTypes","classification":"READ","schema":"cd40ae40fad5","response":"336d9d3523bb","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticeTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getConfigurationParameters","classification":"READ","schema":"30ab89ff5be9","response":"4dc7e9b6cbc3","permission":"parts:view","paginates":false},+ {"name":"items_getConfigurationRules","classification":"READ","schema":"30ab89ff5be9","response":"530f6f787ce7","permission":"parts:view","paginates":false},+ {"name":"items_getConsumable","classification":"READ","schema":"30ab89ff5be9","response":"7cef8bd2c0a7","permission":"parts:view","paginates":false},+ {"name":"items_getConsumables","classification":"READ","schema":"d2546c625ab2","response":"ae2e9a889c25","permission":"parts:view","paginates":true},+ {"name":"items_getDemandForecastSources","classification":"READ","schema":"fb1a8cd5199a","response":"dcd470bf07a6","permission":"parts:view","paginates":false},+ {"name":"items_getItem","classification":"READ","schema":"7f8214d1083f","response":"6a9155217648","permission":"parts:view","paginates":false},+ {"name":"items_getItemCost","classification":"READ","schema":"30ab89ff5be9","response":"10e413636da7","permission":"parts:view","paginates":false},+ {"name":"items_getItemCostHistory","classification":"READ","schema":"30ab89ff5be9","response":"082f2602a5cd","permission":"parts:view","paginates":false},+ {"name":"items_getItemCustomerPart","classification":"READ","schema":"7f8214d1083f","response":"4c6e08919580","permission":"parts:view","paginates":false},+ {"name":"items_getItemCustomerParts","classification":"READ","schema":"30ab89ff5be9","response":"458a8cdb47f2","permission":"parts:view","paginates":false},+ {"name":"items_getItemDemand","classification":"READ","schema":"fb1a8cd5199a","response":"bcde375ebd4c","permission":"parts:view","paginates":false},+ {"name":"items_getItemFiles","classification":"READ","schema":"30ab89ff5be9","response":"6351756c9816","permission":"parts:view","paginates":false},+ {"name":"items_getItemManufacturing","classification":"READ","schema":"7f8214d1083f","response":"f399bb7eda67","permission":"parts:view","paginates":false},+ {"name":"items_getItemMpnsList","classification":"READ","schema":"31b84d65b2ac","response":"3ff28fd20707","permission":"parts:view","paginates":false},+ {"name":"items_getItemPlanning","classification":"READ","schema":"624646b5f0ec","response":"41dfd5d2df83","permission":"parts:view","paginates":false},+ {"name":"items_getItemPostingGroup","classification":"READ","schema":"7f8214d1083f","response":"d38ff3570b60","permission":"parts:view","paginates":false},+ {"name":"items_getItemPostingGroups","classification":"READ","schema":"cd40ae40fad5","response":"7e71cc335d29","permission":"parts:view","paginates":true},+ {"name":"items_getItemPostingGroupsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getItemQuantities","classification":"READ","schema":"624646b5f0ec","response":"3ea7d7161a8d","permission":"parts:view","paginates":false},+ {"name":"items_getItemReplenishment","classification":"READ","schema":"30ab89ff5be9","response":"f399bb7eda67","permission":"parts:view","paginates":false},+ {"name":"items_getItemShelfLife","classification":"READ","schema":"30ab89ff5be9","response":"7382c0121cdc","permission":"parts:view","paginates":false},+ {"name":"items_getItemStockQuantitiesByLocation","classification":"READ","schema":"75b90f67d533","response":"96915ea19193","permission":"parts:view","paginates":false},+ {"name":"items_getItemStorageUnitQuantities","classification":"READ","schema":"624646b5f0ec","response":"880fa3aa7279","permission":"parts:view","paginates":false},+ {"name":"items_getItemSupersession","classification":"READ","schema":"30ab89ff5be9","response":"ef0e933fa9cc","permission":"parts:view","paginates":false},+ {"name":"items_getItemSupersessionsForItems","classification":"READ","schema":"fb8f0e541b3e","response":"d8065aede59f","permission":"parts:view","paginates":false},+ {"name":"items_getItemUnitSalePrice","classification":"READ","schema":"7f8214d1083f","response":"7281903c959e","permission":"parts:view","paginates":false},+ {"name":"items_getMakeMethodById","classification":"READ","schema":"16229db592c2","response":"7a9bf3834cea","permission":"parts:view","paginates":false},+ {"name":"items_getMakeMethods","classification":"READ","schema":"30ab89ff5be9","response":"f51c646717be","permission":"parts:view","paginates":false},+ {"name":"items_getMaterial","classification":"READ","schema":"30ab89ff5be9","response":"533d0f3a68ac","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimension","classification":"READ","schema":"7f8214d1083f","response":"5a634d31e2f3","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimensionList","classification":"READ","schema":"f70b4501b7f5","response":"b72364e0a391","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimensions","classification":"READ","schema":"0189382efb78","response":"aae4fbda0883","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFinish","classification":"READ","schema":"7f8214d1083f","response":"07a225161151","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialFinishes","classification":"READ","schema":"cd40ae40fad5","response":"2cf1f67d0e1d","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFinishList","classification":"READ","schema":"5d07d00bcb2e","response":"b57774d02b4d","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialForm","classification":"READ","schema":"7f8214d1083f","response":"f69bdbb31d76","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialForms","classification":"READ","schema":"cd40ae40fad5","response":"2918b7c99162","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFormsList","classification":"READ","schema":"31b84d65b2ac","response":"a59b0ccd150e","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGrade","classification":"READ","schema":"7f8214d1083f","response":"07a225161151","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGradeList","classification":"READ","schema":"5d07d00bcb2e","response":"b57774d02b4d","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGrades","classification":"READ","schema":"cd40ae40fad5","response":"2cf1f67d0e1d","permission":"parts:view","paginates":true},+ {"name":"items_getMaterials","classification":"READ","schema":"d2546c625ab2","response":"0bbba9542e45","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialSubstance","classification":"READ","schema":"7f8214d1083f","response":"f69bdbb31d76","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialSubstances","classification":"READ","schema":"cd40ae40fad5","response":"2918b7c99162","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialSubstancesList","classification":"READ","schema":"31b84d65b2ac","response":"a59b0ccd150e","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialType","classification":"READ","schema":"7f8214d1083f","response":"0cc848ca86e3","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialTypeList","classification":"READ","schema":"7b7914a63732","response":"c3dfbc0fdf89","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialTypes","classification":"READ","schema":"cd40ae40fad5","response":"2b35eb66c27c","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialUsedIn","classification":"READ","schema":"30ab89ff5be9","response":"5bc3cafcb138","permission":"parts:view","paginates":false},+ {"name":"items_getMethodMaterials","classification":"READ","schema":"cd40ae40fad5","response":"beed367b0416","permission":"parts:view","paginates":true},+ {"name":"items_getMethodMaterialsByMakeMethod","classification":"READ","schema":"16229db592c2","response":"ad8b0c4300d6","permission":"parts:view","paginates":false},+ {"name":"items_getMethodOperations","classification":"READ","schema":"cd40ae40fad5","response":"4241b530a8a2","permission":"parts:view","paginates":true},+ {"name":"items_getMethodOperationsByMakeMethodId","classification":"READ","schema":"16229db592c2","response":"5ecfa08f9596","permission":"parts:view","paginates":false},+ {"name":"items_getMethodTree","classification":"READ","schema":"16229db592c2","response":"a3500aed1d64","permission":"parts:view","paginates":false},+ {"name":"items_getOpenJobMaterials","classification":"READ","schema":"624646b5f0ec","response":"3df5c33eb3a4","permission":"parts:view","paginates":false},+ {"name":"items_getOpenProductionOrders","classification":"READ","schema":"624646b5f0ec","response":"e19f7b8a489c","permission":"parts:view","paginates":false},+ {"name":"items_getOpenPurchaseOrderLines","classification":"READ","schema":"624646b5f0ec","response":"c53a83bc1272","permission":"parts:view","paginates":false},+ {"name":"items_getOpenSalesOrderLines","classification":"READ","schema":"624646b5f0ec","response":"ee9244a3a03b","permission":"parts:view","paginates":false},+ {"name":"items_getPart","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getParts","classification":"READ","schema":"d2546c625ab2","response":"a53fabc5de22","permission":"parts:view","paginates":true},+ {"name":"items_getPartsList","classification":"READ","schema":"31b84d65b2ac","response":"f674f76b8278","permission":"parts:view","paginates":false},+ {"name":"items_getPartUsedIn","classification":"READ","schema":"30ab89ff5be9","response":"e205f0dd9382","permission":"parts:view","paginates":false},+ {"name":"items_getPickMethod","classification":"READ","schema":"624646b5f0ec","response":"34ef9a32bf3f","permission":"parts:view","paginates":false},+ {"name":"items_getPickMethods","classification":"READ","schema":"30ab89ff5be9","response":"d3eda5bbd434","permission":"parts:view","paginates":false},+ {"name":"items_getRecipeProcessIdsForItem","classification":"READ","schema":"30ab89ff5be9","response":"681004346c78","permission":"parts:view","paginates":false},+ {"name":"items_getService","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getServices","classification":"READ","schema":"fefa6db545ee","response":"c4e137bd4e22","permission":"parts:view","paginates":true},+ {"name":"items_getServicesList","classification":"READ","schema":"31b84d65b2ac","response":"f674f76b8278","permission":"parts:view","paginates":false},+ {"name":"items_getSupersessionChain","classification":"READ","schema":"30ab89ff5be9","response":"2897bd7c0865","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierParts","classification":"READ","schema":"7f8214d1083f","response":"77be6c5a4141","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPartsBySupplier","classification":"READ","schema":"47ea6a43aa68","response":"3b8b6029196a","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPriceBreaksForItems","classification":"READ","schema":"fb8f0e541b3e","response":"dc0d300695e0","permission":"parts:view","paginates":false},+ {"name":"items_getTool","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getTools","classification":"READ","schema":"d2546c625ab2","response":"12037af61162","permission":"parts:view","paginates":true},+ {"name":"items_getUnitOfMeasure","classification":"READ","schema":"7f8214d1083f","response":"124234df769c","permission":"parts:view","paginates":false},+ {"name":"items_getUnitOfMeasures","classification":"READ","schema":"cd40ae40fad5","response":"52562a2400a4","permission":"parts:view","paginates":true},+ {"name":"items_getUnitOfMeasuresList","classification":"READ","schema":"31b84d65b2ac","response":"1333b6f93ca5","permission":"parts:view","paginates":false},+ {"name":"items_getUnitOfMeasureUsage","classification":"READ","schema":"7f8214d1083f","response":"bf91be568e5a","permission":"parts:view","paginates":false},+ {"name":"items_insertModelUpload","classification":"WRITE","schema":"22ea49929c8c","response":"277f7d872d8c","permission":"parts:create+update","paginates":false},+ {"name":"items_recalculateItemCost","classification":"WRITE","schema":"623ca47a6c74","response":"c7c3dd8e466d","permission":"parts:update","paginates":false},+ {"name":"items_removeChangeNoticeAffectedItem","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_renameService","classification":"WRITE","schema":"6dcd390c3681","response":"6680d0e1a37f","permission":"parts:update","paginates":false},+ {"name":"items_resolveItemIdFromExtractedText","classification":"WRITE","schema":"1ec7a4a4f756","response":"00404e686415","permission":"parts:update","paginates":false},+ {"name":"items_setChangeNoticeActionTasks","classification":"DESTRUCTIVE","schema":"d253fbec6a67","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_setChangeNoticeStatus","classification":"WRITE","schema":"402b7d406dcf","response":"3e0f6db57d1a","permission":"parts:update","paginates":false},+ {"name":"items_setItemActive","classification":"WRITE","schema":"c6b56d22bedc","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemFields","classification":"WRITE","schema":"6e9bb11463fb","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemPostingGroup","classification":"WRITE","schema":"bba153a62986","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemReadableId","classification":"WRITE","schema":"3c4b03c24337","response":"20eda0d52ae4","permission":"parts:update","paginates":false},+ {"name":"items_setItemSourcing","classification":"WRITE","schema":"5a836bc5d9a8","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemSupersession","classification":"DESTRUCTIVE","schema":"1b0546d69db3","response":"623ca47a6c74","permission":"parts:update","paginates":false},+ {"name":"items_setItemTrackingType","classification":"WRITE","schema":"6ac655073ce2","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setMaterialProperties","classification":"WRITE","schema":"b768c3d49572","response":"94b3f717a27e","permission":"parts:update","paginates":false},+ {"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","schema":"17d57d014843","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","schema":"0205115c2a9c","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_setMethodOperationWorkInstruction","classification":"WRITE","schema":"cd227d437f44","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNotice","classification":"WRITE","schema":"bc0a8bcfbdb8","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","schema":"582d2c771eaa","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","schema":"7f9d94960d15","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeAffectedItemChangeType","classification":"WRITE","schema":"fd1f74726c79","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeAffectedItemCutover","classification":"WRITE","schema":"9e6fed8b61dc","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeType","classification":"WRITE","schema":"cf1d57f4963e","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateConfigurationParameterGroupOrder","classification":"WRITE","schema":"29eba0ee8062","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateConfigurationParameterOrder","classification":"WRITE","schema":"b4f1f31e0f60","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateConsumable","classification":"WRITE","schema":"e0ed6a5c0e19","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateDefaultRevision","classification":"WRITE","schema":"7f8214d1083f","response":"d02966b20664","permission":"parts:update","paginates":false},+ {"name":"items_updateItem","classification":"WRITE","schema":"ce8e8f42c401","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateItemCost","classification":"WRITE","schema":"77edb4dfa70e","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateItemManufacturing","classification":"WRITE","schema":"8f541b0237ee","response":"623ca47a6c74","permission":"parts:update","paginates":false},+ {"name":"items_updateItemPlanning","classification":"WRITE","schema":"45e5182283f4","response":"ade4704d7338","permission":"parts:update","paginates":false},+ {"name":"items_updateItemPostingGroup","classification":"WRITE","schema":"5d31403ddf55","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateItemThumbnail","classification":"WRITE","schema":"023aafe5b1be","response":"f806de8159c8","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterial","classification":"WRITE","schema":"822977f984eb","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialForm","classification":"WRITE","schema":"3b325222ac99","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialSubstance","classification":"WRITE","schema":"3b325222ac99","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodMaterial","classification":"WRITE","schema":"85baff25f028","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_updateMethodOperation","classification":"WRITE","schema":"051b779ed99c","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_updateMethodOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationStepSlide","classification":"WRITE","schema":"c64f09e0594b","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},+ {"name":"items_updatePart","classification":"WRITE","schema":"4206b71c74bb","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updatePickMethod","classification":"WRITE","schema":"dbe3b3c9dd58","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateRevision","classification":"WRITE","schema":"959ca7bb400f","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateService","classification":"WRITE","schema":"c7e9c9249d9e","response":"9b123283f2f8","permission":"parts:update","paginates":false},+ {"name":"items_updateSupplierPart","classification":"WRITE","schema":"da1b4d36d0d8","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateTool","classification":"WRITE","schema":"5d9952d97f09","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateUnitOfMeasure","classification":"WRITE","schema":"26238fb01c1b","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","schema":"10095195c05f","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationParameter","classification":"WRITE","schema":"afbee02c34bb","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationParameterGroup","classification":"WRITE","schema":"30ab89ff5be9","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationRule","classification":"WRITE","schema":"2161bfd2d936","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemCost","classification":"WRITE","schema":"26926957800b","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemCustomerPart","classification":"WRITE","schema":"e27e2f57458a","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemPurchasing","classification":"WRITE","schema":"48133cff6c95","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemUnitSalePrice","classification":"WRITE","schema":"6e0097529573","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialDimension","classification":"WRITE","schema":"fe4a810d30fa","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialFinish","classification":"WRITE","schema":"3986f5cee7dd","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialGrade","classification":"WRITE","schema":"3986f5cee7dd","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialType","classification":"WRITE","schema":"941d8e132060","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","schema":"75ae61cf2fb5","response":"none","permission":"parts:create+update","paginates":false},+ {"name":"people_createDepartment","classification":"WRITE","schema":"dd61994ec3e1","response":"10600fcaa49e","permission":"people:create","paginates":false},+ {"name":"people_createHoliday","classification":"WRITE","schema":"b9a239b57635","response":"8d2b62b6a13b","permission":"people:create","paginates":false},+ {"name":"people_createShift","classification":"WRITE","schema":"8cf7a72c369e","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_createTimeCardEntry","classification":"WRITE","schema":"2d56564c17f3","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_deleteAttribute","classification":"DESTRUCTIVE","schema":"f94e117ebbcc","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteAttributeCategory","classification":"DESTRUCTIVE","schema":"f621bbe3888e","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteDepartment","classification":"DESTRUCTIVE","schema":"2374948818e7","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteHoliday","classification":"DESTRUCTIVE","schema":"19ad69e7168b","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteShift","classification":"DESTRUCTIVE","schema":"7830c71fa7a3","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteTimeCardEntry","classification":"DESTRUCTIVE","schema":"137e8d26e1e1","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_getAttribute","classification":"READ","schema":"f94e117ebbcc","response":"9c635d811516","permission":"people:view","paginates":false},+ {"name":"people_getAttributeCategories","classification":"READ","schema":"cd40ae40fad5","response":"58a57d3f8d71","permission":"people:view","paginates":true},+ {"name":"people_getAttributeCategory","classification":"READ","schema":"7f8214d1083f","response":"a52b87433b3b","permission":"people:view","paginates":false},+ {"name":"people_getAttributeDataTypes","classification":"READ","schema":"31b84d65b2ac","response":"dd6f3a6f89d0","permission":"people:view","paginates":false},+ {"name":"people_getDepartment","classification":"READ","schema":"2374948818e7","response":"10600fcaa49e","permission":"people:view","paginates":false},+ {"name":"people_getDepartmentsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"people:view","paginates":false},+ {"name":"people_getDepartmentsTree","classification":"READ","schema":"31b84d65b2ac","response":"8476e48a3c04","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeDepartments","classification":"READ","schema":"31b84d65b2ac","response":"94b797b98edf","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeJob","classification":"READ","schema":"f77d5ceb3fe7","response":"4a3b9b98079b","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeShifts","classification":"READ","schema":"31b84d65b2ac","response":"68279ed68276","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeSummary","classification":"READ","schema":"f77d5ceb3fe7","response":"afd28b3efe9e","permission":"people:view","paginates":false},+ {"name":"people_getHoliday","classification":"READ","schema":"19ad69e7168b","response":"8d2b62b6a13b","permission":"people:view","paginates":false},+ {"name":"people_getHolidays","classification":"READ","schema":"cd40ae40fad5","response":"1444dd4d5bec","permission":"people:view","paginates":true},+ {"name":"people_getHolidayYears","classification":"READ","schema":"31b84d65b2ac","response":"5aa0e0e1a152","permission":"people:view","paginates":false},+ {"name":"people_getOpenClockEntry","classification":"READ","schema":"f77d5ceb3fe7","response":"48d1ac3381b4","permission":"people:view","paginates":false},+ {"name":"people_getPeople","classification":"READ","schema":"3180b86756b2","response":"5483e69d7515","permission":"people:view","paginates":false},+ {"name":"people_getShift","classification":"READ","schema":"7830c71fa7a3","response":"86e4039d95bd","permission":"people:view","paginates":false},+ {"name":"people_getShifts","classification":"READ","schema":"cd40ae40fad5","response":"393deb9a5a59","permission":"people:view","paginates":true},+ {"name":"people_getShiftsList","classification":"READ","schema":"3b0300fd8f72","response":"ce08332e0ce6","permission":"people:view","paginates":false},+ {"name":"people_getShiftsWithTimes","classification":"READ","schema":"75b90f67d533","response":"5b99e0634dc7","permission":"people:view","paginates":false},+ {"name":"people_getTimecardEntries","classification":"READ","schema":"cd40ae40fad5","response":"eaf533dd012a","permission":"people:view","paginates":true},+ {"name":"people_getTimeCardEntries","classification":"READ","schema":"2ea54a2d0332","response":"f6358cdc55d3","permission":"people:view","paginates":false},+ {"name":"people_getTimeCardEntry","classification":"READ","schema":"137e8d26e1e1","response":"48d1ac3381b4","permission":"people:view","paginates":false},+ {"name":"people_insertAttribute","classification":"WRITE","schema":"f4fd141332d9","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_insertAttributeCategory","classification":"WRITE","schema":"98fdf8fdc426","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_insertEmployeeJob","classification":"WRITE","schema":"6a5f82638b72","response":"4a3b9b98079b","permission":"people:create","paginates":false},+ {"name":"people_updateAttribute","classification":"WRITE","schema":"1618edb64e98","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"people_updateAttributeCategory","classification":"WRITE","schema":"4b94432e3f1e","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"people_updateAttributeSortOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"people:update","paginates":false},+ {"name":"people_updateDepartment","classification":"WRITE","schema":"9de281569d69","response":"10600fcaa49e","permission":"people:update","paginates":false},+ {"name":"people_updateHoliday","classification":"WRITE","schema":"b7553e2ce20a","response":"8d2b62b6a13b","permission":"people:update","paginates":false},+ {"name":"people_updatePersonJob","classification":"WRITE","schema":"446acac592dd","response":"3d90cb5d0437","permission":"people:update","paginates":false},+ {"name":"people_updateShift","classification":"WRITE","schema":"838190f4ad9e","response":"3797626bd17e","permission":"people:create+update","paginates":false},+ {"name":"people_updateTimeCardEntry","classification":"WRITE","schema":"bdc65b281270","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"production_activateAssemblyInstructionVersion","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_applyPlanningActions","classification":"WRITE","schema":"79dab5513239","response":"a217bafc5309","permission":"production:update","paginates":false},+ {"name":"production_assignPerson","classification":"WRITE","schema":"1e2fd21c16fd","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_assignPersonWeek","classification":"WRITE","schema":"6e0908453d4b","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_assignProductionPlanningActions","classification":"WRITE","schema":"a18b4088f112","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_cancelAssemblyJob","classification":"DESTRUCTIVE","schema":"0812c2c1736b","response":"fee5c53bb83d","permission":"production:update","paginates":false},+ {"name":"production_cancelJob","classification":"WRITE","schema":"e9ad3b418621","response":"6d52a19440e7","permission":"production:update","paginates":false},+ {"name":"production_clearPersonAbsence","classification":"DESTRUCTIVE","schema":"6e16b6a2487f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_closeJob","classification":"WRITE","schema":"4999bd4be598","response":"eecc1bc3f4f6","permission":"production:update","paginates":false},+ {"name":"production_completeJob","classification":"WRITE","schema":"6cc84af4993e","response":"6d52a19440e7","permission":"production:update","paginates":false},+ {"name":"production_completeOperation","classification":"WRITE","schema":"92c192733c55","response":"665690c509e5","permission":"production:create+update","paginates":false},+ {"name":"production_configureJob","classification":"WRITE","schema":"d7a30b2c4e67","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_convertAssemblyModel","classification":"WRITE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},+ {"name":"production_convertSalesOrderLinesToJobs","classification":"WRITE","schema":"94c4cbf5579d","response":"94c4cbf5579d","permission":"production:create","paginates":false},+ {"name":"production_copyAssemblyInstructionAsVersion","classification":"WRITE","schema":"a4568aa19857","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_copyMethodToJob","classification":"WRITE","schema":"398de2ffb61a","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_copyMethodToMaterial","classification":"WRITE","schema":"d184c854f615","response":"c32158774ba3","permission":"production:update","paginates":false},+ {"name":"production_copyPeopleDay","classification":"WRITE","schema":"eab08fa3c9e8","response":"cbf943bfb8ed","permission":"production:update","paginates":false},+ {"name":"production_copyPeopleWeekBoard","classification":"WRITE","schema":"adb62afbceb4","response":"cbf943bfb8ed","permission":"production:update","paginates":false},+ {"name":"production_createAssemblyInstruction","classification":"WRITE","schema":"b4c98ec19282","response":"baecc665b224","permission":"production:create","paginates":false},+ {"name":"production_createAssemblyInstructionStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createBatch","classification":"WRITE","schema":"e4cb11866b3a","response":"d6f069964d23","permission":"production:update","paginates":false},+ {"name":"production_createFailureMode","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"production:create","paginates":false},+ {"name":"production_createJob","classification":"WRITE","schema":"841ed7f7a528","response":"4999bd4be598","permission":"production:create","paginates":false},+ {"name":"production_createJobDocumentUploadUrl","classification":"WRITE","schema":"685f6d6e5714","response":"4ad76afe0777","permission":"production:create","paginates":false},+ {"name":"production_createJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationStepSlide","classification":"WRITE","schema":"079dafff0e23","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobs","classification":"WRITE","schema":"d12e26631b3e","response":"267b4780c1d3","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchComment","classification":"WRITE","schema":"0c205f004651","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchEvent","classification":"WRITE","schema":"882b42caf30c","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchItem","classification":"WRITE","schema":"c9df2d5b631f","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceSchedule","classification":"WRITE","schema":"2541e4f50141","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedure","classification":"WRITE","schema":"020550cf414d","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedureParameter","classification":"WRITE","schema":"0ea0375d7dd6","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedureStep","classification":"WRITE","schema":"928df9e1694b","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProductionEvent","classification":"WRITE","schema":"d55db96dfe94","response":"acb6e3edad0f","permission":"production:create","paginates":false},+ {"name":"production_createProductionQuantity","classification":"WRITE","schema":"aeaea19fd65e","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createScrapReason","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"production:create","paginates":false},+ {"name":"production_deleteAssemblyComponentMapping","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstruction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepMaterial","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblySubAssembly","classification":"DESTRUCTIVE","schema":"bffc08aa14a9","response":"none","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyUnit","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteFailureMode","classification":"DESTRUCTIVE","schema":"2557649b1a5e","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobMaterial","classification":"DESTRUCTIVE","schema":"c8cc308934ba","response":"3797626bd17e","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperation","classification":"DESTRUCTIVE","schema":"c8cc308934ba","response":"3797626bd17e","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobs","classification":"DESTRUCTIVE","schema":"0eb0c2be01ed","response":"0eb0c2be01ed","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","schema":"74a8a528c9d8","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","schema":"8dc062233861","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","schema":"093d449cdac0","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedure","classification":"DESTRUCTIVE","schema":"0392041512ee","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedureParameter","classification":"DESTRUCTIVE","schema":"c91ee8fbe23a","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedureStep","classification":"DESTRUCTIVE","schema":"58f4f51fca4d","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProductionEvent","classification":"DESTRUCTIVE","schema":"b8e23d6f34f4","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProductionQuantity","classification":"DESTRUCTIVE","schema":"2808b0bf7a67","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteScrapReason","classification":"DESTRUCTIVE","schema":"d925769fba07","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_dismissProductionPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_duplicateJobOperationStep","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_generateAssemblySteps","classification":"DESTRUCTIVE","schema":"47b83ea765a6","response":"ce107c5cf849","permission":"production:update","paginates":false},+ {"name":"production_getActiveEmployeeAbilities","classification":"READ","schema":"31b84d65b2ac","response":"123f68c94eac","permission":"production:view","paginates":false},+ {"name":"production_getActiveJobOperationByJobId","classification":"READ","schema":"ca49bc65b712","response":"d1d76189e471","permission":"production:view","paginates":false},+ {"name":"production_getActiveJobOperationsByLocation","classification":"READ","schema":"98cf602352a0","response":"a3fa2c06d591","permission":"production:view","paginates":false},+ {"name":"production_getActiveProductionEvents","classification":"READ","schema":"31b84d65b2ac","response":"9d447facd100","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyComponentMappings","classification":"READ","schema":"dfce1b9bc52e","response":"da74e5f4208a","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstruction","classification":"READ","schema":"7f8214d1083f","response":"6c2955045911","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructions","classification":"READ","schema":"ad4033782f45","response":"79381095f84d","permission":"production:view","paginates":true},++ {"name":"production_getAssemblyInstructions","classification":"READ","schema":"0f79ceab9ddb","response":"79381095f84d","permission":"production:view","paginates":true},+ {"name":"production_getAssemblyInstructionsForItem","classification":"READ","schema":"30ab89ff5be9","response":"89a844d50556","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","schema":"c478d26d5ff3","response":"89a5f52bebf8","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionSteps","classification":"READ","schema":"bb717127b6f6","response":"c63a220ac834","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepSlides","classification":"READ","schema":"c478d26d5ff3","response":"60aa9b57a118","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepTools","classification":"READ","schema":"c478d26d5ff3","response":"d771814f7578","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionVersions","classification":"READ","schema":"f58b3e337974","response":"d6491c78edc9","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyPlanJson","classification":"READ","schema":"dfce1b9bc52e","response":"5708d3b25e58","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyUnits","classification":"READ","schema":"dfce1b9bc52e","response":"7224ef8546c1","permission":"production:view","paginates":false},+ {"name":"production_getBatchableOperations","classification":"READ","schema":"45d95a2d3af4","response":"1c2a1e7a3a05","permission":"production:view","paginates":false},+ {"name":"production_getBatchableProcesses","classification":"READ","schema":"31b84d65b2ac","response":"b0ab8957f96e","permission":"production:view","paginates":false},+ {"name":"production_getBatchOutputLots","classification":"READ","schema":"1a62d6c430a5","response":"7783e113d7a1","permission":"production:view","paginates":false},+ {"name":"production_getCapacityReservationsForResources","classification":"READ","schema":"be3a7444e5b1","response":"a491299c2657","permission":"production:view","paginates":false},+ {"name":"production_getCompletionJobs","classification":"READ","schema":"a7b47bee6c23","response":"7bef4749f130","permission":"production:view","paginates":false},+ {"name":"production_getDemandProjections","classification":"READ","schema":"1f5f7428664d","response":"f963e0e91868","permission":"production:view","paginates":false},+ {"name":"production_getFailureMode","classification":"READ","schema":"2557649b1a5e","response":"412854326fc3","permission":"production:view","paginates":false},+ {"name":"production_getFailureModes","classification":"READ","schema":"cd40ae40fad5","response":"b5d9b684eccd","permission":"production:view","paginates":true},+ {"name":"production_getFailureModesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"production:view","paginates":false},+ {"name":"production_getFlattenedBomMaterials","classification":"READ","schema":"30ab89ff5be9","response":"7f3fb0d1aeb3","permission":"production:view","paginates":false},+ {"name":"production_getJob","classification":"READ","schema":"7f8214d1083f","response":"30608e61a4dd","permission":"production:view","paginates":false},+ {"name":"production_getJobByOperationId","classification":"READ","schema":"3561ad8e0d42","response":"07382c86b3b8","permission":"production:view","paginates":false},+ {"name":"production_getJobDocuments","classification":"READ","schema":"39628e1613b1","response":"5483e69d7515","permission":"production:view","paginates":false},+ {"name":"production_getJobDocumentsWithItemId","classification":"READ","schema":"655ace094495","response":"5483e69d7515","permission":"production:view","paginates":false},+ {"name":"production_getJobExpediteForecast","classification":"READ","schema":"ca49bc65b712","response":"d377dc3a1fd5","permission":"production:view","paginates":false},+ {"name":"production_getJobMakeMethodById","classification":"READ","schema":"7679db37b5f9","response":"ec2dc329264c","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialItemIds","classification":"READ","schema":"ca49bc65b712","response":"32068a500dfe","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialsByMethodId","classification":"READ","schema":"7679db37b5f9","response":"08d673090a5e","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","schema":"f0c0b4958cf1","response":"839ec8fc28ff","permission":"production:view","paginates":false},+ {"name":"production_getJobMethodTree","classification":"READ","schema":"ca49bc65b712","response":"b65b4600c0ec","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationAttachments","classification":"READ","schema":"cf62af6a7d5a","response":"9a8b9c571a6b","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatches","classification":"READ","schema":"cd40ae40fad5","response":"505156d91e5d","permission":"production:view","paginates":true},+ {"name":"production_getJobOperationBatchEvents","classification":"READ","schema":"1a62d6c430a5","response":"031cdafdafbd","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchMembers","classification":"READ","schema":"d429e4a46057","response":"66bcdc105c00","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchMemberStats","classification":"READ","schema":"d429e4a46057","response":"03aaee65a70b","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchWithMembers","classification":"READ","schema":"1a62d6c430a5","response":"520bac578dba","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationDependencies","classification":"READ","schema":"ca49bc65b712","response":"9214ed6d51dd","permission":"production:view","paginates":false},+ {"name":"production_getJobOperations","classification":"READ","schema":"f67274205e12","response":"7f24f7881568","permission":"production:view","paginates":true},+ {"name":"production_getJobOperationsByMethodId","classification":"READ","schema":"7679db37b5f9","response":"db1f7927f373","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationsList","classification":"READ","schema":"ca49bc65b712","response":"4e5425835530","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationStepRecords","classification":"READ","schema":"f67274205e12","response":"7bd4e5876d03","permission":"production:view","paginates":true},+ {"name":"production_getJobOrderStatusMap","classification":"READ","schema":"cc93d4900988","response":"5a380f81ad00","permission":"production:view","paginates":false},+ {"name":"production_getJobPurchaseOrderLines","classification":"READ","schema":"ca49bc65b712","response":"f0dff75b384d","permission":"production:view","paginates":false},+ {"name":"production_getJobReceiptSnapshot","classification":"READ","schema":"ca49bc65b712","response":"60e9609498b0","permission":"production:view","paginates":false},+ {"name":"production_getJobReleaseReadiness","classification":"READ","schema":"bd58e48cf49b","response":"f5f114b3f417","permission":"production:view","paginates":false},+ {"name":"production_getJobs","classification":"READ","schema":"cd40ae40fad5","response":"418c2732d3b9","permission":"production:view","paginates":true},+ {"name":"production_getJobsByDateRange","classification":"READ","schema":"c4a3c6cdab79","response":"94688560d7de","permission":"production:view","paginates":false},+ {"name":"production_getJobsBySalesOrderLine","classification":"READ","schema":"fbe78064dbd7","response":"70526fffc19e","permission":"production:view","paginates":false},+ {"name":"production_getJobsList","classification":"READ","schema":"c47cc3e0c427","response":"232ee7305e73","permission":"production:view","paginates":false},+ {"name":"production_getLatestAssemblyPlanJob","classification":"READ","schema":"dfce1b9bc52e","response":"50ae0e7e58d9","permission":"production:view","paginates":false},+ {"name":"production_getLocationEmployees","classification":"READ","schema":"75b90f67d533","response":"72ccccdcfc21","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatch","classification":"READ","schema":"74a8a528c9d8","response":"df5a8ae945c2","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchComments","classification":"READ","schema":"74a8a528c9d8","response":"7df6d6b7ba88","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchEvents","classification":"READ","schema":"74a8a528c9d8","response":"fc0af15629d8","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchItems","classification":"READ","schema":"74a8a528c9d8","response":"7d22c1b8235d","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","schema":"74adac8c0e6d","response":"c9ce440846e1","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceSchedule","classification":"READ","schema":"093d449cdac0","response":"2ea53f4f72d0","permission":"production:view","paginates":false},+ {"name":"production_getOutsideOperationsByJobId","classification":"READ","schema":"ca49bc65b712","response":"b75ab9ed0211","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAbsences","classification":"READ","schema":"be8ac1c6fb6c","response":"f98df1954626","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAbsencesRange","classification":"READ","schema":"1474d371d593","response":"90f4a38d3460","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAssignments","classification":"READ","schema":"b8f638bb77e8","response":"6bf01853c73a","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAssignmentsRange","classification":"READ","schema":"c4a3c6cdab79","response":"ba9f9d495de9","permission":"production:view","paginates":false},+ {"name":"production_getPeopleCapacityOperations","classification":"READ","schema":"60e910dcc131","response":"9bbc101347c4","permission":"production:view","paginates":false},+ {"name":"production_getProcedure","classification":"READ","schema":"7f8214d1083f","response":"034de4441d04","permission":"production:view","paginates":false},+ {"name":"production_getProcedures","classification":"READ","schema":"cd40ae40fad5","response":"419cf56f7e7d","permission":"production:view","paginates":true},+ {"name":"production_getProceduresList","classification":"READ","schema":"31b84d65b2ac","response":"fe6a24448aaa","permission":"production:view","paginates":false},+ {"name":"production_getProcedureVersions","classification":"READ","schema":"b6064496c216","response":"eb2d49754db3","permission":"production:view","paginates":false},+ {"name":"production_getProductionDataByOperations","classification":"READ","schema":"cf62af6a7d5a","response":"59e4b3d639e6","permission":"production:view","paginates":false},+ {"name":"production_getProductionEvent","classification":"READ","schema":"7f8214d1083f","response":"d9f9d9fcef6a","permission":"production:view","paginates":false},+ {"name":"production_getProductionEvents","classification":"READ","schema":"ba541e465d28","response":"6a1dd7219526","permission":"production:view","paginates":true},+ {"name":"production_getProductionPlanning","classification":"READ","schema":"fc88f1909ce3","response":"f537e33d5ca9","permission":"production:view","paginates":true},+ {"name":"production_getProductionProjections","classification":"READ","schema":"8e9427a2fa1e","response":"9d7a2b5ba76f","permission":"production:view","paginates":true},+ {"name":"production_getProductionQuantities","classification":"READ","schema":"ba541e465d28","response":"3328b61208d3","permission":"production:view","paginates":true},+ {"name":"production_getProductionQuantity","classification":"READ","schema":"7f8214d1083f","response":"8d4e9959e193","permission":"production:view","paginates":false},+ {"name":"production_getRootMakeMethod","classification":"READ","schema":"ca49bc65b712","response":"ec2dc329264c","permission":"production:view","paginates":false},+ {"name":"production_getScrapReason","classification":"READ","schema":"d925769fba07","response":"4bbb50609deb","permission":"production:view","paginates":false},+ {"name":"production_getScrapReasons","classification":"READ","schema":"cd40ae40fad5","response":"254774c57849","permission":"production:view","paginates":true},+ {"name":"production_getScrapReasonsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"production:view","paginates":false},+ {"name":"production_getTrackedEntitiesByJobId","classification":"READ","schema":"ca49bc65b712","response":"ec54684c77fb","permission":"production:view","paginates":false},+ {"name":"production_getTrackedEntityByJobId","classification":"READ","schema":"ca49bc65b712","response":"1007059c8406","permission":"production:view","paginates":false},+ {"name":"production_getUnbatchedBatchableOperationCount","classification":"READ","schema":"31b84d65b2ac","response":"683e4ed05232","permission":"production:view","paginates":false},+ {"name":"production_getUnscheduledJobs","classification":"READ","schema":"75b90f67d533","response":"eb77a38acf19","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterRequiredAbilities","classification":"READ","schema":"75b90f67d533","response":"7418ea1fc0a7","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterReservationsRange","classification":"READ","schema":"c310a7ca038d","response":"a7e9bc09d2ab","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterShifts","classification":"READ","schema":"ef138c43c92c","response":"2b4835f80e6c","permission":"production:view","paginates":false},+ {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","schema":"bf4512d170cc","response":"00404e686415","permission":"production:create","paginates":false},+ {"name":"production_insertJob","classification":"WRITE","schema":"f450754aacd3","response":"ad63dfd9d877","permission":"production:create","paginates":false},+ {"name":"production_makeAssemblySubAssembly","classification":"WRITE","schema":"bd69d909a2e4","response":"00404e686415","permission":"production:update","paginates":false},+ {"name":"production_mapAssemblyComponent","classification":"WRITE","schema":"4b0e8ad9fe70","response":"3189c67145d5","permission":"production:update","paginates":false},+ {"name":"production_markPersonAbsent","classification":"WRITE","schema":"16a1cd418a2e","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_markPersonAbsentRange","classification":"WRITE","schema":"d83feea8f8c7","response":"9859df3143fe","permission":"production:update","paginates":false},+ {"name":"production_matchAssemblyBom","classification":"WRITE","schema":"3797626bd17e","response":"7d2129b72e71","permission":"production:update","paginates":false},+ {"name":"production_mergeBatchOutputs","classification":"WRITE","schema":"49385ebfc807","response":"305ef06ceb72","permission":"production:update","paginates":false},+ {"name":"production_movePerson","classification":"WRITE","schema":"a726aa587ccc","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_movePersonWeek","classification":"WRITE","schema":"c790955c93cc","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_moveScheduleJob","classification":"WRITE","schema":"6e18ba72229f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_notifyScheduleInputsChanged","classification":"WRITE","schema":"a2cb3b753e9c","response":"b520ca8e3ab4","permission":"production:update","paginates":false},+ {"name":"production_orderPlannedJobs","classification":"WRITE","schema":"145543a6765b","response":"2519eb8f6e46","permission":"production:create","paginates":false},+ {"name":"production_pauseJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_planJobFromPlanning","classification":"WRITE","schema":"863c89f4ad8e","response":"8e58a21e4c94","permission":"production:update","paginates":false},+ {"name":"production_reassignAssemblyComponents","classification":"DESTRUCTIVE","schema":"71d135315dea","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_recalculateJobRequirements","classification":"WRITE","schema":"7f8214d1083f","response":"9e056a59d695","permission":"production:update","paginates":false},+ {"name":"production_reconvertAssemblyModel","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},+ {"name":"production_releaseBatches","classification":"WRITE","schema":"cdc90750ed35","response":"3c7bc982eae0","permission":"production:update","paginates":false},+ {"name":"production_releaseJobs","classification":"WRITE","schema":"9d50f93189c8","response":"9655f6ea4d0d","permission":"production:update","paginates":false},+ {"name":"production_reopenJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_reopenProductionPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_reorderJobOperations","classification":"WRITE","schema":"c25fc63725f5","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_reorderScheduleOperations","classification":"WRITE","schema":"6c26805d2cdb","response":"2ad56d1b8c6e","permission":"production:update","paginates":false},+ {"name":"production_replanAssembly","classification":"WRITE","schema":"6e2c068fb7ee","response":"03b7f8cb8bd5","permission":"production:update","paginates":false},+ {"name":"production_reprioritizeBatch","classification":"WRITE","schema":"fac2b7e1e76b","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_resumeJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_runMRP","classification":"WRITE","schema":"20590ee6ce3b","response":"9e056a59d695","permission":"inventory:update","paginates":false},+ {"name":"production_setAssemblyStepComponents","classification":"WRITE","schema":"1a4ba7a541ab","response":"e3fc07878bc9","permission":"production:update","paginates":false},+ {"name":"production_setJobDeadline","classification":"WRITE","schema":"e616bfea48ce","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobFields","classification":"WRITE","schema":"ed7f018b035c","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobItem","classification":"WRITE","schema":"8d049fdf053e","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobMaterialStepLink","classification":"DESTRUCTIVE","schema":"58cc0a5390d5","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationDueDate","classification":"WRITE","schema":"e04478fc58f7","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationStatus","classification":"WRITE","schema":"c7c4e9005478","response":"a443ac9aa1f1","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationToolStepLink","classification":"DESTRUCTIVE","schema":"b48f94032fe6","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationWorkInstruction","classification":"WRITE","schema":"1bede8f4a4f5","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setJobQuantity","classification":"WRITE","schema":"14db87743cc7","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobSalesOrderLine","classification":"WRITE","schema":"9b91d34f8382","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setPeopleOvertime","classification":"WRITE","schema":"89851b04ba54","response":"393a0d83325c","permission":"production:update","paginates":false},+ {"name":"production_setPersonDay","classification":"WRITE","schema":"b2bcad277f44","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_setPersonHours","classification":"WRITE","schema":"c99328071885","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setProcedureFields","classification":"WRITE","schema":"e76f126b5b16","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_syncAssemblyToOperation","classification":"DESTRUCTIVE","schema":"da43bcac38a0","response":"4348d3bad80b","permission":"production:update","paginates":false},+ {"name":"production_syncJobOperationProcedure","classification":"WRITE","schema":"4db296880a62","response":"c407a9edb930","permission":"production:update","paginates":false},+ {"name":"production_unassignPerson","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_unassignPersonWeek","classification":"DESTRUCTIVE","schema":"890a7a5b9f83","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_ungroupAssemblySubAssembly","classification":"DESTRUCTIVE","schema":"bffc08aa14a9","response":"none","permission":"production:update","paginates":false},+ {"name":"production_unreleaseBatch","classification":"WRITE","schema":"979f64cb9229","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","schema":"8bc986702703","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","schema":"cbc4567c4881","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","schema":"c46e7002c837","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepSlide","classification":"WRITE","schema":"c64f09e0594b","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","schema":"aa7e8ba34a64","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","schema":"e76e43cb8530","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyStepMotion","classification":"WRITE","schema":"c70122f65e35","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblySubAssembly","classification":"WRITE","schema":"c5f26f0d922a","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateBatch","classification":"WRITE","schema":"c54fb480a6d1","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_updateFailureMode","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"production:update","paginates":false},+ {"name":"production_updateJobBatchNumber","classification":"WRITE","schema":"6e1e7ec3a9f5","response":"f7a40899c090","permission":"production:update","paginates":false},+ {"name":"production_updateJobDetails","classification":"WRITE","schema":"bcbce6ae7798","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"4ea32bd70246","permission":"production:create","paginates":false},+ {"name":"production_updateJobMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_updateJobOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStepSlide","classification":"WRITE","schema":"c64f09e0594b","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateKanbanJob","classification":"WRITE","schema":"9c2f9da91736","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchComment","classification":"WRITE","schema":"0175e4c01377","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchEvent","classification":"WRITE","schema":"213edef85a25","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchItem","classification":"WRITE","schema":"cedce5d0537b","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceSchedule","classification":"WRITE","schema":"a71abb3e6290","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMethodOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},+ {"name":"production_updatePlannedJob","classification":"WRITE","schema":"36a2dd1a51c5","response":"8e58a21e4c94","permission":"production:update","paginates":false},+ {"name":"production_updateProcedure","classification":"WRITE","schema":"edb9af57e01a","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureParameter","classification":"WRITE","schema":"fbaaaf15b2b3","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureStep","classification":"WRITE","schema":"549be9a0a0d9","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateProductionEvent","classification":"WRITE","schema":"5ae7126208e7","response":"acb6e3edad0f","permission":"production:update","paginates":false},+ {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},+ {"name":"production_updateScrapReason","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"production:update","paginates":false},+ {"name":"production_upsertAssemblyInstruction","classification":"WRITE","schema":"140b31338c4e","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","schema":"69932a4f176d","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","schema":"cec21b948809","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","schema":"f7254eb12e98","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyUnit","classification":"WRITE","schema":"6755e4574f31","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertMakeMethodFromJob","classification":"DESTRUCTIVE","schema":"32b3a0f5efa0","response":"4e1a8f1febce","permission":"none","paginates":false},+ {"name":"production_upsertMakeMethodFromJobMethod","classification":"DESTRUCTIVE","schema":"32b3a0f5efa0","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"purchasing_activateLease","classification":"WRITE","schema":"9fb51372ff53","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_addReturnOrderLine","classification":"WRITE","schema":"64ba603aba2d","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_applyPlanningActions","classification":"WRITE","schema":"97c5a5a85a8d","response":"1fcb7549b33d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_assignPurchasingPlanningActions","classification":"WRITE","schema":"a18b4088f112","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelLease","classification":"DESTRUCTIVE","schema":"9fb51372ff53","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelPurchasingRfq","classification":"DESTRUCTIVE","schema":"9531e4360acd","response":"9531e4360acd","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelReturnOrder","classification":"DESTRUCTIVE","schema":"11b028f16d94","response":"11b028f16d94","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_closePurchaseOrderAndApprovals","classification":"DESTRUCTIVE","schema":"28cffcd9d6e8","response":"28cffcd9d6e8","permission":"purchasing:delete+update","paginates":false},+ {"name":"purchasing_confirmReturnOrder","classification":"WRITE","schema":"e4d2372c370b","response":"bd154a7a199c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","schema":"ed4c93e2b28c","response":"873673b16fc8","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_createPurchaseOrderLine","classification":"WRITE","schema":"f8a134954e41","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","schema":"71e626ec2145","response":"00404e686415","permission":"invoicing:create","paginates":false},+ {"name":"purchasing_createPurchasingRfq","classification":"WRITE","schema":"6c41ec826827","response":"0c1a1b93cca3","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createPurchasingRFQLine","classification":"WRITE","schema":"5fa277599ba0","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","schema":"ceebeb4f9cac","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplier","classification":"WRITE","schema":"114245a01fe7","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierBankAccount","classification":"WRITE","schema":"8abf4777b900","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","schema":"a1e758f60479","response":"4ad76afe0777","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","schema":"89370e60a3e7","response":"4ad76afe0777","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierProcess","classification":"WRITE","schema":"d9e192bdbb43","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierQuoteLine","classification":"WRITE","schema":"a7eb142b411e","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierType","classification":"WRITE","schema":"f51d093840b8","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_deactivateSupplier","classification":"DESTRUCTIVE","schema":"67043a31b1b5","response":"67043a31b1b5","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_decidePurchaseOrderApproval","classification":"WRITE","schema":"03b37ea9315e","response":"5d541df0c1a6","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_decideSupplierApproval","classification":"WRITE","schema":"7fc37bfd72cb","response":"3420a9ad965d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_deleteLease","classification":"DESTRUCTIVE","schema":"dc3a69d0ccf7","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteLeaseLine","classification":"DESTRUCTIVE","schema":"2cf0099ceecf","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteLeasePayment","classification":"DESTRUCTIVE","schema":"08b90ec76499","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseOrderLine","classification":"DESTRUCTIVE","schema":"555dd21fcbd0","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseOrders","classification":"DESTRUCTIVE","schema":"56451bca9438","response":"56451bca9438","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseReturnOrder","classification":"DESTRUCTIVE","schema":"ceebeb4f9cac","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseReturnOrderLine","classification":"DESTRUCTIVE","schema":"e2b1df794940","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","schema":"a03ea9b74e8a","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchasingRFQLine","classification":"DESTRUCTIVE","schema":"79a5f4500bbf","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplier","classification":"DESTRUCTIVE","schema":"47ea6a43aa68","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"purchasing_deleteSupplierContact","classification":"DESTRUCTIVE","schema":"aa6e2dd10410","response":"700b93baa3ef","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierLocation","classification":"DESTRUCTIVE","schema":"4c735b01a149","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierProcess","classification":"DESTRUCTIVE","schema":"aac871c2c83c","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierQuote","classification":"DESTRUCTIVE","schema":"bb086c35d51f","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierQuoteLine","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierType","classification":"DESTRUCTIVE","schema":"c798505e510b","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_dismissPurchasingPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_duplicatePurchaseOrder","classification":"WRITE","schema":"95bc69935968","response":"f5212679d580","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_finalizePurchaseOrderAndNotify","classification":"WRITE","schema":"9f1cc7c6b5b5","response":"309570ef92a9","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_finalizePurchasingRfqAndNotify","classification":"WRITE","schema":"8bb952a2b85c","response":"094107e7128f","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_finalizeSupplierQuoteWithLink","classification":"WRITE","schema":"5db39f9abf41","response":"5db39f9abf41","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_getCreditableQuantitiesForPurchaseReturn","classification":"READ","schema":"ceebeb4f9cac","response":"1e97e6c72b1d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getDefaultAttachmentsForPO","classification":"READ","schema":"9474713c78d5","response":"6568f0b88496","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLease","classification":"READ","schema":"dc3a69d0ccf7","response":"fc0e61ea3215","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseEvents","classification":"READ","schema":"dc3a69d0ccf7","response":"d6ca448f2de1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseLines","classification":"READ","schema":"dc3a69d0ccf7","response":"ac478377b901","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeasePayments","classification":"READ","schema":"dc3a69d0ccf7","response":"e8667e0adeb6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseRelatedDocuments","classification":"READ","schema":"dc3a69d0ccf7","response":"281a385d45a6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeases","classification":"READ","schema":"cd40ae40fad5","response":"5ea4c94909de","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getLeaseSchedule","classification":"READ","schema":"dc3a69d0ccf7","response":"8c06f01ac6f1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLinkedSupplierQuotes","classification":"READ","schema":"a03ea9b74e8a","response":"cb143b1fe761","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrder","classification":"READ","schema":"47850e9f092b","response":"259ccf5593fd","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderDelivery","classification":"READ","schema":"47850e9f092b","response":"1b814db8a608","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderLine","classification":"READ","schema":"555dd21fcbd0","response":"d1fd90a42c26","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderLines","classification":"READ","schema":"47850e9f092b","response":"085f671f872c","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderPayment","classification":"READ","schema":"47850e9f092b","response":"c7a62e53e09b","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrders","classification":"READ","schema":"089f70bab038","response":"2dc249e54e3c","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchaseReturnOrder","classification":"READ","schema":"ceebeb4f9cac","response":"96bcc73f6a1e","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderCredits","classification":"READ","schema":"ceebeb4f9cac","response":"49639d091139","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderIssues","classification":"READ","schema":"ceebeb4f9cac","response":"a81c998e95a3","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLine","classification":"READ","schema":"e2b1df794940","response":"6e3bf67c7a97","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLines","classification":"READ","schema":"ceebeb4f9cac","response":"96a37b74bd9d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLineTrackedEntities","classification":"READ","schema":"72a93572f55f","response":"7c681886c392","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrders","classification":"READ","schema":"c70a80cf081d","response":"248fa6073d74","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchaseReturnOrderShipments","classification":"READ","schema":"ceebeb4f9cac","response":"fcf875f84b9b","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","schema":"31b84d65b2ac","response":"da511db6b83a","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingPlanning","classification":"READ","schema":"fc88f1909ce3","response":"2853f93ce584","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchasingRFQ","classification":"READ","schema":"7f8214d1083f","response":"08cb90c207da","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQLine","classification":"READ","schema":"e2b1df794940","response":"453aec159c67","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQLines","classification":"READ","schema":"a03ea9b74e8a","response":"9507bd698de0","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQs","classification":"READ","schema":"cd40ae40fad5","response":"a17f64c1d9c6","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchasingRFQSuppliersWithLinks","classification":"READ","schema":"a03ea9b74e8a","response":"5483e69d7515","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getReturnableEntitiesForSupplier","classification":"READ","schema":"f4032bf993a4","response":"80bf661fb053","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getReturnableLinesForSupplier","classification":"READ","schema":"9ce2623b4864","response":"24dd6c0d1c55","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSiblingQuotesForQuote","classification":"READ","schema":"bb086c35d51f","response":"cb143b1fe761","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplier","classification":"READ","schema":"47ea6a43aa68","response":"e1446596b250","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierBankAccounts","classification":"READ","schema":"47ea6a43aa68","response":"f2b09b60b722","permission":"accounting:view","paginates":false},+ {"name":"purchasing_getSupplierContact","classification":"READ","schema":"23bff787ec5d","response":"6d2aa722b1ce","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierContacts","classification":"READ","schema":"47ea6a43aa68","response":"e28ccbd2c417","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteraction","classification":"READ","schema":"1ee597897662","response":"f674b3eb0acb","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","schema":"a99e7a244595","response":"1c34622130cc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","schema":"e2b1df794940","response":"1c34622130cc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierLocation","classification":"READ","schema":"23bff787ec5d","response":"4603d06d1055","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierLocations","classification":"READ","schema":"47ea6a43aa68","response":"6dad1063175d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierPayment","classification":"READ","schema":"47ea6a43aa68","response":"24b286adf1ff","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierProcessesByProcess","classification":"READ","schema":"5631e53ea64f","response":"c2eb609c8ad1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierProcessesBySupplier","classification":"READ","schema":"47ea6a43aa68","response":"c2eb609c8ad1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuote","classification":"READ","schema":"bb086c35d51f","response":"903106f4ab48","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteByExternalLinkId","classification":"READ","schema":"61d80c989426","response":"0276bbe00656","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLine","classification":"READ","schema":"fe9f25e9881e","response":"8274b1f62041","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLinePrices","classification":"READ","schema":"fe9f25e9881e","response":"22abc40c4789","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLinePricesByQuoteId","classification":"READ","schema":"bb086c35d51f","response":"22abc40c4789","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLines","classification":"READ","schema":"bb086c35d51f","response":"fb8d2333a3dc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuotes","classification":"READ","schema":"cd40ae40fad5","response":"a8ea39a27fdf","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierQuotesForComparison","classification":"READ","schema":"a03ea9b74e8a","response":"aa927eec99a0","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierReportContacts","classification":"READ","schema":"4e3d74ecb68e","response":"753cb51d6d41","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSuppliers","classification":"READ","schema":"ac5f51b3adab","response":"1dd9d01eeb5f","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierShipping","classification":"READ","schema":"47ea6a43aa68","response":"673f4f400833","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSuppliersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierTax","classification":"READ","schema":"47ea6a43aa68","response":"89b4ff5c4012","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierType","classification":"READ","schema":"c798505e510b","response":"8b3eca34dbfd","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierTypes","classification":"READ","schema":"cd40ae40fad5","response":"e0001a83b60b","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_insertLease","classification":"WRITE","schema":"55753efdb84c","response":"f6631a819d19","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","schema":"b7f7ea3824d5","response":"73785d310369","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","schema":"8faa8981ada0","response":"d53d13c89312","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierContact","classification":"WRITE","schema":"442dcf7c63d4","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierLocation","classification":"WRITE","schema":"e401ef4fb9c3","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierQuote","classification":"WRITE","schema":"6b9d616bd5ca","response":"77e21c1e2e32","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_modifyLease","classification":"WRITE","schema":"36fa257d377a","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_orderPlannedPurchases","classification":"WRITE","schema":"075bf940d96b","response":"783cfed7484c","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_overrideLeaseLineClassification","classification":"WRITE","schema":"1fe629e754c9","response":"b75a6f5aff44","permission":"accounting:update","paginates":false},+ {"name":"purchasing_purchaseLeaseLine","classification":"WRITE","schema":"38acf7de6118","response":"bb4487ea3e25","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_removeLeaseLineClassificationOverride","classification":"WRITE","schema":"bb4487ea3e25","response":"58ef28d4f5cf","permission":"accounting:update","paginates":false},+ {"name":"purchasing_reopenPurchaseOrder","classification":"WRITE","schema":"ede13800cd39","response":"e703c553a33e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_reopenPurchasingPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_reopenReturnOrder","classification":"WRITE","schema":"11b028f16d94","response":"11b028f16d94","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_requestSupplierApproval","classification":"WRITE","schema":"67043a31b1b5","response":"67043a31b1b5","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_sendSupplierQuoteToSupplier","classification":"WRITE","schema":"216a3e92c06c","response":"5db39f9abf41","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_shortClosePurchaseOrderLine","classification":"WRITE","schema":"de3ac14cd9f4","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_shortClosePurchaseReturnOrderLine","classification":"WRITE","schema":"2a627b0c4264","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_terminateLeaseLine","classification":"DESTRUCTIVE","schema":"cb77a6b7f416","response":"bb4487ea3e25","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateLeaseDetails","classification":"WRITE","schema":"58766088a3e6","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePlanningPurchaseOrderLine","classification":"WRITE","schema":"f9f036f80ca3","response":"2d9389fd413d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrder","classification":"WRITE","schema":"be711f3a1c77","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderFavorite","classification":"WRITE","schema":"ff73dc321969","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderLine","classification":"WRITE","schema":"1b3bb1270d43","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","schema":"33aad0d0c2bb","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrders","classification":"WRITE","schema":"c182f3099a0b","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQLine","classification":"WRITE","schema":"886a79ee22a8","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","schema":"913042cdd55f","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRfqs","classification":"WRITE","schema":"e7babf8c0f84","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","schema":"947842502cae","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateReturnOrderLine","classification":"WRITE","schema":"390645da3aea","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateReturnOrders","classification":"WRITE","schema":"98f12a4ce2ea","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplier","classification":"WRITE","schema":"a60eb2c7bcb5","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierBankAccount","classification":"WRITE","schema":"5fb57a51d684","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"purchasing_updateSupplierContact","classification":"WRITE","schema":"327a6ef8e7b5","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierLocation","classification":"WRITE","schema":"6afc03cf515f","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierPayment","classification":"WRITE","schema":"35582b0e7de4","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierProcess","classification":"WRITE","schema":"5c2afd5382fe","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuote","classification":"WRITE","schema":"b775ec1375c3","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteLine","classification":"WRITE","schema":"61e56a680e85","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","schema":"248d2ba4c421","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuotes","classification":"WRITE","schema":"aee40ae8e095","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteStatus","classification":"WRITE","schema":"b6ed6e3f17e0","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierShipping","classification":"WRITE","schema":"4da28c918b78","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierTax","classification":"WRITE","schema":"fc0cfcd24aeb","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierType","classification":"WRITE","schema":"afedffe2be69","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_upsertLeasePayment","classification":"WRITE","schema":"c0ed999b5813","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderDelivery","classification":"WRITE","schema":"8bdd908f85bd","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderPayment","classification":"WRITE","schema":"a4b89c399504","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchasingRFQ","classification":"WRITE","schema":"56cc1ae7fa75","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","schema":"769394a6f909","response":"5c9ba5bee3f1","permission":"purchasing:create+update","paginates":false},+ {"name":"quality_activateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},+ {"name":"quality_completeIssue","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_createGaugeCalibrationRecord","classification":"WRITE","schema":"9fd203fd91da","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createGaugeType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_createIssue","classification":"WRITE","schema":"98e94090cc53","response":"67030fdab724","permission":"quality:create","paginates":false},+ {"name":"quality_createIssueAssociation","classification":"WRITE","schema":"6abd32611fef","response":"f16bdda80515","permission":"quality:update","paginates":false},+ {"name":"quality_createIssueType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_createIssueWorkflow","classification":"WRITE","schema":"2ee341acc3e0","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createQualityDocument","classification":"WRITE","schema":"9614a292c98d","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createRequiredAction","classification":"WRITE","schema":"f6f70a91c352","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_deactivateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},+ {"name":"quality_decideQualityDocumentApproval","classification":"WRITE","schema":"03770b06d8f1","response":"febf01bee291","permission":"quality:update","paginates":false},+ {"name":"quality_deleteGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteGaugeCalibrationRecord","classification":"DESTRUCTIVE","schema":"4e3f6158526a","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteGaugeType","classification":"DESTRUCTIVE","schema":"f53d2343f254","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteInspectionDocument","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"e92dda062549","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssue","classification":"DESTRUCTIVE","schema":"9a315debddd5","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueAssociation","classification":"DESTRUCTIVE","schema":"df77e85ac07f","response":"none","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueType","classification":"DESTRUCTIVE","schema":"8e7960fd6070","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueWorkflow","classification":"DESTRUCTIVE","schema":"85f1fd269377","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteQualityDocument","classification":"DESTRUCTIVE","schema":"3dc73fe900b8","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteRequiredAction","classification":"DESTRUCTIVE","schema":"d65e071deff9","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteRisk","classification":"DESTRUCTIVE","schema":"f1db6acfa864","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_draftIssueSupplierReturn","classification":"WRITE","schema":"927d79b82bc1","response":"b54823969d01","permission":"purchasing:create","paginates":false},+ {"name":"quality_getBalloons","classification":"READ","schema":"b6a25994639a","response":"3fec0abbc97d","permission":"quality:view","paginates":false},+ {"name":"quality_getGauge","classification":"READ","schema":"059138c6b8da","response":"e991e480f76c","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeCalibrationRecord","classification":"READ","schema":"7f8214d1083f","response":"2b11fefda0c1","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeCalibrationRecords","classification":"READ","schema":"cd40ae40fad5","response":"3b6339a8e722","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugeCalibrationRecordsByGaugeId","classification":"READ","schema":"059138c6b8da","response":"47dc08537d57","permission":"quality:view","paginates":false},+ {"name":"quality_getGauges","classification":"READ","schema":"cd40ae40fad5","response":"ef3b7f672ff5","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugesList","classification":"READ","schema":"31b84d65b2ac","response":"34b9a5801676","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeType","classification":"READ","schema":"f53d2343f254","response":"63b5b3f8f143","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeTypes","classification":"READ","schema":"cd40ae40fad5","response":"31ad065cdc4a","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugeTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getInspection","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionDocument","classification":"READ","schema":"7f8214d1083f","response":"a82889f583de","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocuments","classification":"READ","schema":"cd40ae40fad5","response":"0daf2106401c","permission":"quality:view","paginates":true},++ {"name":"quality_getInspectionDocuments","classification":"READ","schema":"cd40ae40fad5","response":"daa253e3c540","permission":"quality:view","paginates":true},+ {"name":"quality_getInspectionDocumentsForItem","classification":"READ","schema":"30ab89ff5be9","response":"cfa5f1f7b8aa","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionFeatures","classification":"READ","schema":"b6a25994639a","response":"1e8d8f002f21","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionGauges","classification":"READ","schema":"162c842697ab","response":"68597e017f0d","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionMeasurements","classification":"READ","schema":"162c842697ab","response":"c743640a210d","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionPlan","classification":"READ","schema":"b6a25994639a","response":"83a9b3640e41","permission":"quality:view","paginates":false},+ {"name":"quality_getInspections","classification":"READ","schema":"c51c4913cfa1","response":"8c1809e97180","permission":"quality:view","paginates":true},+ {"name":"quality_getInspectionSamplingPlans","classification":"READ","schema":"162c842697ab","response":"fccb92d930f6","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionTrackedEntities","classification":"READ","schema":"76ee331dd860","response":"ec54684c77fb","permission":"quality:view","paginates":false},+ {"name":"quality_getIssue","classification":"READ","schema":"9a315debddd5","response":"a1e666efa89c","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueActionTasks","classification":"READ","schema":"3c597e8cd46b","response":"7a21aafdb718","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueApprovalTasks","classification":"READ","schema":"7f8214d1083f","response":"c8b12eeadf05","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueAssociations","classification":"READ","schema":"9a315debddd5","response":"ebdefbd901a7","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueFromExternalLink","classification":"READ","schema":"7f8214d1083f","response":"7d8ae32223a1","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueItems","classification":"READ","schema":"7f8214d1083f","response":"8e532cfdc47f","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueReviewers","classification":"READ","schema":"7f8214d1083f","response":"7cfc99a45933","permission":"quality:view","paginates":false},+ {"name":"quality_getIssues","classification":"READ","schema":"cd40ae40fad5","response":"37768f573675","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueSuppliers","classification":"READ","schema":"7f8214d1083f","response":"2a7e42e2f8c2","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueType","classification":"READ","schema":"8e7960fd6070","response":"63b5b3f8f143","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueTypeByName","classification":"READ","schema":"3728a862815e","response":"3797626bd17e","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueTypes","classification":"READ","schema":"cd40ae40fad5","response":"31ad065cdc4a","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueWorkflow","classification":"READ","schema":"85f1fd269377","response":"f88698228931","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueWorkflows","classification":"READ","schema":"cd40ae40fad5","response":"2669c312ddb8","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueWorkflowsList","classification":"READ","schema":"31b84d65b2ac","response":"078f43165541","permission":"quality:view","paginates":false},+ {"name":"quality_getItemInspectionDocumentAssignments","classification":"READ","schema":"30ab89ff5be9","response":"9bedeef9a12b","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityActions","classification":"READ","schema":"cd40ae40fad5","response":"5a45675f1097","permission":"quality:view","paginates":true},+ {"name":"quality_getQualityDocument","classification":"READ","schema":"7f8214d1083f","response":"695de208baac","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityDocuments","classification":"READ","schema":"cd40ae40fad5","response":"4afca05d1d27","permission":"quality:view","paginates":true},+ {"name":"quality_getQualityDocumentVersions","classification":"READ","schema":"b6064496c216","response":"81dd83c56231","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityFiles","classification":"READ","schema":"7f8214d1083f","response":"6351756c9816","permission":"quality:view","paginates":false},+ {"name":"quality_getReceiptInspections","classification":"READ","schema":"85cf4fd2917f","response":"83d5d10abb6a","permission":"quality:view","paginates":false},+ {"name":"quality_getRequiredAction","classification":"READ","schema":"d65e071deff9","response":"58c7a89fdc1f","permission":"quality:view","paginates":false},+ {"name":"quality_getRequiredActions","classification":"READ","schema":"cd40ae40fad5","response":"bb4170f94792","permission":"quality:view","paginates":true},+ {"name":"quality_getRequiredActionsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getRisk","classification":"READ","schema":"f1db6acfa864","response":"25996e7756ac","permission":"quality:view","paginates":false},+ {"name":"quality_getRisks","classification":"READ","schema":"01150b344856","response":"97a932a15ee2","permission":"quality:view","paginates":true},+ {"name":"quality_insertGauge","classification":"WRITE","schema":"8d2ada8f5f52","response":"3269d4609ad2","permission":"quality:create","paginates":false},+ {"name":"quality_insertIssue","classification":"WRITE","schema":"ea632d40582e","response":"bf12cbd0f560","permission":"quality:create","paginates":false},+ {"name":"quality_insertIssueReviewer","classification":"WRITE","schema":"83d8aaae61eb","response":"bcde375ebd4c","permission":"quality:create","paginates":false},+ {"name":"quality_rejectInspection","classification":"WRITE","schema":"d7fc4d660b91","response":"c1beaadbde90","permission":"quality:update","paginates":false},+ {"name":"quality_reorderIssueActionTasks","classification":"WRITE","schema":"e27ca9c14dfd","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_saveInspectionDocument","classification":"WRITE","schema":"ce666421c179","response":"f67a43378af0","permission":"quality:update","paginates":false},+ {"name":"quality_saveInspectionDocumentAtomic","classification":"WRITE","schema":"7a3138ccf220","response":"none","permission":"quality:update","paginates":false},+ {"name":"quality_seedQualityDocuments","classification":"WRITE","schema":"31b84d65b2ac","response":"85c82e9f9d11","permission":"quality:create","paginates":false},+ {"name":"quality_setInspectionDocumentDrawingNumber","classification":"WRITE","schema":"b70d7fc9aa08","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueActionDueDate","classification":"WRITE","schema":"226732b41ef5","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueStatus","classification":"WRITE","schema":"1a25bfc1a327","response":"1a25bfc1a327","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueTaskStatus","classification":"WRITE","schema":"4b9a245ad2cf","response":"6857d1b1a4e8","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueTaskSupplier","classification":"WRITE","schema":"b6b0275e1616","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateGauge","classification":"WRITE","schema":"d26a7f29a929","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateGaugeCalibrationRecord","classification":"WRITE","schema":"780ab591e1b5","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_updateGaugeType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateInspectionDocumentSampling","classification":"WRITE","schema":"42714a7976eb","response":"bcde375ebd4c","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssue","classification":"WRITE","schema":"336ea2add45b","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueActionProcesses","classification":"DESTRUCTIVE","schema":"4ddcbb8d1ac6","response":"bcde375ebd4c","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueField","classification":"WRITE","schema":"8712a26ffddc","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueItemField","classification":"WRITE","schema":"32444013b5c4","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueWorkflow","classification":"WRITE","schema":"1f02dc4f3e49","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_updateQualityDocument","classification":"WRITE","schema":"7f1d2f8ce693","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateQualityDocumentField","classification":"WRITE","schema":"241fb5b89617","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_updateRequiredAction","classification":"WRITE","schema":"84851898a6e5","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateRisk","classification":"WRITE","schema":"059e5e53b44b","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_upsertInspectionDocument","classification":"WRITE","schema":"11b9bba59419","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_upsertItemInspectionDocumentAssignment","classification":"DESTRUCTIVE","schema":"4948a99b7a53","response":"bcde375ebd4c","permission":"quality:create+update","paginates":false},+ {"name":"resources_activateProcess","classification":"WRITE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_addEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_createAbility","classification":"WRITE","schema":"df2e6ccff2a4","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createContractor","classification":"DESTRUCTIVE","schema":"11891191bd97","response":"bcde375ebd4c","permission":"resources:create","paginates":false},+ {"name":"resources_createFailureMode","classification":"WRITE","schema":"c922337b313e","response":"8394fbabd845","permission":"resources:create","paginates":false},+ {"name":"resources_createLocation","classification":"WRITE","schema":"140095be5d68","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatch","classification":"WRITE","schema":"629d474dc047","response":"ede36af7307d","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatchComment","classification":"WRITE","schema":"0c205f004651","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatchItem","classification":"WRITE","schema":"bb6dfef16ca0","response":"31c4f3f69c9a","permission":"resources:update","paginates":false},+ {"name":"resources_createMaintenanceEvent","classification":"WRITE","schema":"6e76bd1f09c1","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_createMaintenanceSchedule","classification":"WRITE","schema":"b84710917cca","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createPartner","classification":"WRITE","schema":"376ead8bb039","response":"bcde375ebd4c","permission":"resources:create","paginates":false},+ {"name":"resources_createProcess","classification":"WRITE","schema":"aee880893829","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTraining","classification":"WRITE","schema":"627644497b66","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTrainingAssignment","classification":"WRITE","schema":"70b3c1aa623e","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTrainingQuestion","classification":"WRITE","schema":"8ec2c941ed74","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createWorkCenter","classification":"WRITE","schema":"fd853b10d45a","response":"3797626bd17e","permission":"resources:create+update","paginates":false},+ {"name":"resources_deactivateAbility","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_deactivateWorkCenter","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteContractor","classification":"DESTRUCTIVE","schema":"050d2aeb4e9a","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteFailureMode","classification":"DESTRUCTIVE","schema":"2557649b1a5e","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteLocation","classification":"DESTRUCTIVE","schema":"75b90f67d533","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","schema":"74a8a528c9d8","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceEvent","classification":"DESTRUCTIVE","schema":"a5eeac694397","response":"8e58a21e4c94","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","schema":"093d449cdac0","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deletePartner","classification":"DESTRUCTIVE","schema":"48d3fd6edb53","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteProcess","classification":"DESTRUCTIVE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteShift","classification":"DESTRUCTIVE","schema":"7830c71fa7a3","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteSuggestion","classification":"DESTRUCTIVE","schema":"7e2e609c39b4","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTraining","classification":"DESTRUCTIVE","schema":"ad4ee6c278a0","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTrainingAssignment","classification":"DESTRUCTIVE","schema":"9ee4c244585a","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTrainingQuestion","classification":"DESTRUCTIVE","schema":"3a46a4c5c924","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_getAbilities","classification":"READ","schema":"cd40ae40fad5","response":"b306c2cb1888","permission":"resources:view","paginates":true},+ {"name":"resources_getAbilitiesList","classification":"READ","schema":"31b84d65b2ac","response":"fc7a0345fc53","permission":"resources:view","paginates":false},+ {"name":"resources_getAbility","classification":"READ","schema":"18c5e48c0ea4","response":"d98eac986c97","permission":"resources:view","paginates":false},+ {"name":"resources_getContractor","classification":"READ","schema":"050d2aeb4e9a","response":"995cb2d28a3e","permission":"resources:view","paginates":false},+ {"name":"resources_getContractors","classification":"READ","schema":"cd40ae40fad5","response":"ccd6066a170d","permission":"resources:view","paginates":true},+ {"name":"resources_getEmployeeAbilities","classification":"READ","schema":"f77d5ceb3fe7","response":"328aa0024967","permission":"resources:view","paginates":false},+ {"name":"resources_getEmployeeAbility","classification":"READ","schema":"71c585bd9df0","response":"f0d72cd0ea38","permission":"resources:view","paginates":false},+ {"name":"resources_getFailureMode","classification":"READ","schema":"2557649b1a5e","response":"412854326fc3","permission":"resources:view","paginates":false},+ {"name":"resources_getFailureModes","classification":"READ","schema":"cd40ae40fad5","response":"b5d9b684eccd","permission":"resources:view","paginates":true},+ {"name":"resources_getFailureModesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getLocation","classification":"READ","schema":"75b90f67d533","response":"99dfd44b4c2e","permission":"resources:view","paginates":false},+ {"name":"resources_getLocations","classification":"READ","schema":"cd40ae40fad5","response":"73aefed94223","permission":"resources:view","paginates":true},+ {"name":"resources_getLocationsList","classification":"READ","schema":"31b84d65b2ac","response":"e19c89c1e8a0","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatch","classification":"READ","schema":"74a8a528c9d8","response":"083fee6ab76b","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchComments","classification":"READ","schema":"74a8a528c9d8","response":"7df6d6b7ba88","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchesByLocation","classification":"READ","schema":"3204ae8b38a6","response":"6bb3f549dc61","permission":"resources:view","paginates":true},+ {"name":"resources_getMaintenanceDispatchEvents","classification":"READ","schema":"74a8a528c9d8","response":"fc0af15629d8","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchItems","classification":"READ","schema":"74a8a528c9d8","response":"4e3a00f00ee6","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceSchedule","classification":"READ","schema":"093d449cdac0","response":"2ea53f4f72d0","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceSchedulesByLocation","classification":"READ","schema":"10a203fb00ae","response":"4c005030a48e","permission":"resources:view","paginates":true},+ {"name":"resources_getOutstandingTrainingsForUser","classification":"READ","schema":"f77d5ceb3fe7","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getPartner","classification":"READ","schema":"fedfa0da6447","response":"690aa589fb9c","permission":"resources:view","paginates":false},+ {"name":"resources_getPartnerBySupplierId","classification":"READ","schema":"48d3fd6edb53","response":"690aa589fb9c","permission":"resources:view","paginates":false},+ {"name":"resources_getPartners","classification":"READ","schema":"cd40ae40fad5","response":"6c9a4233e834","permission":"resources:view","paginates":true},+ {"name":"resources_getProcess","classification":"READ","schema":"5631e53ea64f","response":"1dcef23b2416","permission":"resources:view","paginates":false},+ {"name":"resources_getProcesses","classification":"READ","schema":"cd40ae40fad5","response":"cd79fe552b97","permission":"resources:view","paginates":true},+ {"name":"resources_getProcessesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getProcessesWithoutAbility","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getSuggestion","classification":"READ","schema":"7e2e609c39b4","response":"77bb66a1249a","permission":"resources:view","paginates":false},+ {"name":"resources_getSuggestions","classification":"READ","schema":"cd40ae40fad5","response":"de6c6fa956e3","permission":"resources:view","paginates":true},+ {"name":"resources_getTraining","classification":"READ","schema":"7f8214d1083f","response":"49bd32630132","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignment","classification":"READ","schema":"9ee4c244585a","response":"d992354bd0fd","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","schema":"9ee4c244585a","response":"cc0e3d2cf77a","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignments","classification":"READ","schema":"27aced930989","response":"03daf9b26033","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentStatus","classification":"READ","schema":"f8ae9324ff87","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentStatusForEmployee","classification":"READ","schema":"f77d5ceb3fe7","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentSummary","classification":"READ","schema":"31b84d65b2ac","response":"64abd6a67dfa","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainings","classification":"READ","schema":"cd40ae40fad5","response":"304498b26d10","permission":"resources:view","paginates":true},+ {"name":"resources_getTrainingsList","classification":"READ","schema":"31b84d65b2ac","response":"22f58f9494b3","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCenter","classification":"READ","schema":"7f8214d1083f","response":"af7e30751616","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCenters","classification":"READ","schema":"cd40ae40fad5","response":"7e12337d863b","permission":"resources:view","paginates":true},+ {"name":"resources_getWorkCentersByLocation","classification":"READ","schema":"75b90f67d533","response":"3aa9b7ccf523","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCentersList","classification":"READ","schema":"31b84d65b2ac","response":"d1a122ea7f19","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","schema":"31b84d65b2ac","response":"628a610a980e","permission":"resources:view","paginates":false},+ {"name":"resources_issueMaintenancePart","classification":"WRITE","schema":"af0751f3105f","response":"cf78aa7da634","permission":"resources:update","paginates":false},+ {"name":"resources_processDeactivate","classification":"WRITE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_reactivateWorkCenter","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_removeEmployeeAbility","classification":"DESTRUCTIVE","schema":"10092409622c","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_setMaintenanceDispatchStatus","classification":"WRITE","schema":"1bd67c7106fd","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_startMaintenanceEvent","classification":"WRITE","schema":"34cb412f1fae","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_stopMaintenanceEvent","classification":"WRITE","schema":"a5eeac694397","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_uncompleteTrainingAssignment","classification":"DESTRUCTIVE","schema":"d520f70388c9","response":"d520f70388c9","permission":"resources:delete","paginates":false},+ {"name":"resources_unissueMaintenancePart","classification":"DESTRUCTIVE","schema":"be5a1d978dcc","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_updateAbility","classification":"WRITE","schema":"9fa76da0d27e","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateContractor","classification":"DESTRUCTIVE","schema":"11891191bd97","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateFailureMode","classification":"WRITE","schema":"ac1031d30650","response":"8394fbabd845","permission":"resources:update","paginates":false},+ {"name":"resources_updateLocation","classification":"WRITE","schema":"ce189a85ea7e","response":"3797626bd17e","permission":"resources:create+update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchComment","classification":"WRITE","schema":"0175e4c01377","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchField","classification":"WRITE","schema":"29f2399f61fc","response":"6a884dc1da07","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchItem","classification":"WRITE","schema":"cedce5d0537b","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceEvent","classification":"WRITE","schema":"bf8266758b63","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceSchedule","classification":"WRITE","schema":"af63079aefd4","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updatePartner","classification":"WRITE","schema":"376ead8bb039","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateProcess","classification":"DESTRUCTIVE","schema":"d33f66716674","response":"3797626bd17e","permission":"resources:create+delete+update","paginates":false},+ {"name":"resources_updateSuggestionEmoji","classification":"WRITE","schema":"5f9afdcc2556","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateTraining","classification":"WRITE","schema":"6097fcf86545","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingAssignment","classification":"WRITE","schema":"c787b54127d0","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingField","classification":"WRITE","schema":"89d3447a10b3","response":"0eb0c2be01ed","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingQuestion","classification":"WRITE","schema":"f029f3fda91d","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"resources:update","paginates":false},+ {"name":"resources_updateWorkCenter","classification":"WRITE","schema":"ae0789f2b0ea","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"sales_activateRentalAgreement","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_amendContract","classification":"WRITE","schema":"04dc5f3d37f7","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_cancelContract","classification":"WRITE","schema":"ced608188030","response":"f4c9785b5239","permission":"sales:update","paginates":false},+ {"name":"sales_cancelSalesReturnOrder","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_classifyRentalUnit","classification":"WRITE","schema":"0130929837e0","response":"c2c8ef2bbef1","permission":"accounting:update","paginates":false},+ {"name":"sales_confirmContract","classification":"WRITE","schema":"a806875e8efc","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_confirmReturnOrder","classification":"WRITE","schema":"22c6386df9f2","response":"b01f3bbdd0f8","permission":"sales:update","paginates":false},+ {"name":"sales_confirmSalesOrder","classification":"WRITE","schema":"ac08a54cf72b","response":"61c982753707","permission":"sales:create","paginates":false},+ {"name":"sales_convertQuote","classification":"WRITE","schema":"2f9ce4892f8e","response":"b3c62fcb92ac","permission":"sales:create","paginates":false},+ {"name":"sales_convertSalesRfq","classification":"WRITE","schema":"e74b45db7021","response":"8f3a111d6dd7","permission":"sales:create","paginates":false},+ {"name":"sales_copyItemMethodToQuoteLine","classification":"WRITE","schema":"c415fa75351b","response":"e0050938a2c8","permission":"sales:update","paginates":false},+ {"name":"sales_copyItemMethodToQuoteMaterial","classification":"WRITE","schema":"c9fd44bf9a70","response":"bfcaa45eb18e","permission":"sales:update","paginates":false},+ {"name":"sales_copyQuote","classification":"WRITE","schema":"06f2835dfed0","response":"4e1a8f1febce","permission":"sales:create","paginates":false},+ {"name":"sales_copyQuoteLineMethod","classification":"WRITE","schema":"e2d617e47e0a","response":"e0050938a2c8","permission":"sales:update","paginates":false},+ {"name":"sales_createContract","classification":"WRITE","schema":"249368eaeb19","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createContractLine","classification":"WRITE","schema":"e2eb6d46f182","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomer","classification":"WRITE","schema":"1169094678e4","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomerBankAccount","classification":"WRITE","schema":"c5394895361c","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"sales_createCustomerStatus","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomerType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createNoQuoteReason","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","schema":"9d023be224ef","response":"4ad76afe0777","permission":"sales:create","paginates":false},+ {"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","schema":"89370e60a3e7","response":"4ad76afe0777","permission":"sales:create","paginates":false},+ {"name":"sales_createPricingRule","classification":"WRITE","schema":"6b9956ef81b3","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteLine","classification":"WRITE","schema":"f490cabfaa4e","response":"bb48df81da15","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"8e58a21e4c94","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationParameter","classification":"WRITE","schema":"e05336a75e66","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationStep","classification":"WRITE","schema":"8e97b59e9ee0","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationTool","classification":"WRITE","schema":"60a5d239cf03","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreement","classification":"WRITE","schema":"3d2ec5205417","response":"a443ac9aa1f1","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreementCharge","classification":"WRITE","schema":"2084581f9746","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreementLine","classification":"WRITE","schema":"b384f7650913","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createReplacementSalesOrder","classification":"WRITE","schema":"3fdcd215dc22","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createReturnOrderLine","classification":"WRITE","schema":"f0f787b6d728","response":"f9d1513a44f3","permission":"sales:create","paginates":false},+ {"name":"sales_createReturnReason","classification":"WRITE","schema":"5607534c1255","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"91896427de3a","response":"8f061af39e95","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","schema":"a752775acc57","response":"00404e686415","permission":"invoicing:create","paginates":false},+ {"name":"sales_createSalesRfq","classification":"WRITE","schema":"ef914612528f","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRFQ","classification":"WRITE","schema":"782bcc5a7778","response":"2e56e1180d37","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRFQLine","classification":"WRITE","schema":"c5b3b3cfaa0d","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","schema":"9671bf9bdd53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","schema":"0a2c14c75652","response":"700b93baa3ef","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerItemPriceOverride","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerItemRentalRate","classification":"DESTRUCTIVE","schema":"fa2fb5ff991b","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerLocation","classification":"DESTRUCTIVE","schema":"fac9952916a4","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerStatus","classification":"DESTRUCTIVE","schema":"52bec6d3e5bd","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerType","classification":"DESTRUCTIVE","schema":"2a8659f88eca","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteNoQuoteReason","classification":"DESTRUCTIVE","schema":"3b4691733f86","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deletePricingRule","classification":"DESTRUCTIVE","schema":"954531f020b9","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuote","classification":"DESTRUCTIVE","schema":"8087dc4f5248","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteLine","classification":"DESTRUCTIVE","schema":"40e11ca73a53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteMaterialAndReprice","classification":"DESTRUCTIVE","schema":"92adb5e77c44","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationAndReprice","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreement","classification":"DESTRUCTIVE","schema":"7e41fc1a1e08","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreementCharge","classification":"DESTRUCTIVE","schema":"2d825d87bc47","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreementLine","classification":"DESTRUCTIVE","schema":"4249190735aa","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteReturnReason","classification":"DESTRUCTIVE","schema":"9db6b9d7003b","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesOrder","classification":"DESTRUCTIVE","schema":"6e4655763b3f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesOrderLine","classification":"DESTRUCTIVE","schema":"fbe78064dbd7","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesReturnOrder","classification":"DESTRUCTIVE","schema":"3fdcd215dc22","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesReturnOrderLine","classification":"DESTRUCTIVE","schema":"e2b1df794940","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesRFQ","classification":"DESTRUCTIVE","schema":"c32128ec72f8","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesRFQLine","classification":"DESTRUCTIVE","schema":"7201248a5292","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deliverRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"2e39a760a5ca","permission":"none","paginates":false},+ {"name":"sales_duplicatePricingRule","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_escalateReturnOrderLine","classification":"WRITE","schema":"b207270e6864","response":"a3013ba5cdbb","permission":"none","paginates":false},+ {"name":"sales_finalizeAndSendQuote","classification":"WRITE","schema":"ca18e9270f18","response":"c1e125e7d8af","permission":"sales:create","paginates":false},+ {"name":"sales_getBaseCatalog","classification":"READ","schema":"81c745eee0bd","response":"965c08b897d0","permission":"sales:view","paginates":false},+ {"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","schema":"40e11ca73a53","response":"4dc7e9b6cbc3","permission":"sales:view","paginates":false},+ {"name":"sales_getContract","classification":"READ","schema":"d1a753b63ac7","response":"1375deebd9f6","permission":"sales:view","paginates":false},+ {"name":"sales_getContractAmendments","classification":"READ","schema":"d1a753b63ac7","response":"70b301a95120","permission":"sales:view","paginates":false},+ {"name":"sales_getContractInvoiceSchedule","classification":"READ","schema":"d1a753b63ac7","response":"4a793f5433cd","permission":"sales:view","paginates":false},+ {"name":"sales_getContractLine","classification":"READ","schema":"f4d3dbaa8bfd","response":"49583c612441","permission":"sales:view","paginates":false},+ {"name":"sales_getContractLines","classification":"READ","schema":"d1a753b63ac7","response":"8c2832f17e6d","permission":"sales:view","paginates":false},+ {"name":"sales_getContracts","classification":"READ","schema":"cd40ae40fad5","response":"9bb0c1fac394","permission":"sales:view","paginates":true},+ {"name":"sales_getCreditableQuantities","classification":"READ","schema":"3fdcd215dc22","response":"da2f02c5bdac","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomer","classification":"READ","schema":"9671bf9bdd53","response":"8642159293c2","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerBankAccounts","classification":"READ","schema":"9671bf9bdd53","response":"d8173b9c2e54","permission":"accounting:view","paginates":false},+ {"name":"sales_getCustomerContact","classification":"READ","schema":"bfd196306256","response":"d16ba475ee9a","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerContacts","classification":"READ","schema":"9671bf9bdd53","response":"acc29dbe9746","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerContractStatuses","classification":"READ","schema":"9671bf9bdd53","response":"b4542ed3da5e","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemPriceOverride","classification":"READ","schema":"75fd8400560d","response":"2dfcd06e591d","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemPriceOverrideById","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemRentalRate","classification":"READ","schema":"fa2fb5ff991b","response":"b3b8ce0eaba0","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemRentalRates","classification":"READ","schema":"30ab89ff5be9","response":"8b9441c41a32","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerLocation","classification":"READ","schema":"e0df27278d11","response":"be52ec9b4436","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerLocations","classification":"READ","schema":"9671bf9bdd53","response":"bcf222d6d73a","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerPayment","classification":"READ","schema":"9671bf9bdd53","response":"4357e4e42177","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomers","classification":"READ","schema":"cd40ae40fad5","response":"e16ee6870826","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerShipping","classification":"READ","schema":"9671bf9bdd53","response":"d9e04e1cc364","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerStatus","classification":"READ","schema":"52bec6d3e5bd","response":"9203566a8ab4","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerStatuses","classification":"READ","schema":"cd40ae40fad5","response":"254774c57849","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerStatusesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerTax","classification":"READ","schema":"9671bf9bdd53","response":"1d92e9e0b01d","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerType","classification":"READ","schema":"2a8659f88eca","response":"8b3eca34dbfd","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerTypes","classification":"READ","schema":"cd40ae40fad5","response":"e0001a83b60b","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getDefaultRentalRates","classification":"READ","schema":"e1fbd2f519d4","response":"aebd7c76789d","permission":"sales:view","paginates":false},+ {"name":"sales_getExternalSalesOrderLines","classification":"READ","schema":"2147341bd4ab","response":"7b8bd29508cd","permission":"sales:view","paginates":true},+ {"name":"sales_getItemRentalRate","classification":"READ","schema":"ddd591f1b7ad","response":"d1badca592c6","permission":"sales:view","paginates":false},+ {"name":"sales_getModelByQuoteLineId","classification":"READ","schema":"40e11ca73a53","response":"none","permission":"sales:view","paginates":false},+ {"name":"sales_getNoQuoteReason","classification":"READ","schema":"3b4691733f86","response":"4bbb50609deb","permission":"sales:view","paginates":false},+ {"name":"sales_getNoQuoteReasons","classification":"READ","schema":"cd40ae40fad5","response":"f6f55833db42","permission":"sales:view","paginates":true},+ {"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","schema":"30ab89ff5be9","response":"2942b53dfd95","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunity","classification":"READ","schema":"1ee597897662","response":"03abafe9fa9f","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityDocuments","classification":"READ","schema":"6dc274c5c3da","response":"1c34622130cc","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityLineDocuments","classification":"READ","schema":"e11598873908","response":"1c34622130cc","permission":"sales:view","paginates":false},+ {"name":"sales_getPricingRule","classification":"READ","schema":"7f8214d1083f","response":"50720f6e5f2a","permission":"sales:view","paginates":false},+ {"name":"sales_getPricingRules","classification":"READ","schema":"81c745eee0bd","response":"f83b909b7fb0","permission":"sales:view","paginates":true},+ {"name":"sales_getQuote","classification":"READ","schema":"8087dc4f5248","response":"5b7ae632c481","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteByExternalId","classification":"READ","schema":"b8b14c07d2f0","response":"e1c8d7e62b7d","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteCustomerDetails","classification":"READ","schema":"8087dc4f5248","response":"7656953707c3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLine","classification":"READ","schema":"40e11ca73a53","response":"a37f940eb1fa","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePrices","classification":"READ","schema":"40e11ca73a53","response":"b380070f2ac3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePricesByQuoteId","classification":"READ","schema":"8087dc4f5248","response":"b380070f2ac3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePriceTraces","classification":"READ","schema":"ffca7e5c29c1","response":"36a0683de042","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLines","classification":"READ","schema":"8087dc4f5248","response":"947e5b11c1ee","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinesList","classification":"READ","schema":"8087dc4f5248","response":"5ebff9af923d","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMakeMethod","classification":"READ","schema":"d12e0ae9a70b","response":"f6ec0930d3af","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMaterialsByMethodId","classification":"READ","schema":"d12e0ae9a70b","response":"34d1789c595a","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMethodTrees","classification":"READ","schema":"8087dc4f5248","response":"abdc8a7e0541","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteOperationsByLine","classification":"READ","schema":"40e11ca73a53","response":"17a8edc27947","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteOperationsByMethodId","classification":"READ","schema":"d12e0ae9a70b","response":"68487e902368","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotePayment","classification":"READ","schema":"8087dc4f5248","response":"c94b5d1f2b47","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotes","classification":"READ","schema":"cd40ae40fad5","response":"7c5302da1e9d","permission":"sales:view","paginates":true},+ {"name":"sales_getQuoteShipment","classification":"READ","schema":"8087dc4f5248","response":"9022fbc076f4","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotesList","classification":"READ","schema":"31b84d65b2ac","response":"0ff25946068c","permission":"sales:view","paginates":false},+ {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","schema":"5fd8e97dfc3d","response":"72aab90423c2","permission":"sales:view","paginates":false},+ {"name":"sales_getRentableFleetAssets","classification":"READ","schema":"31b84d65b2ac","response":"18707409983d","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreement","classification":"READ","schema":"7e41fc1a1e08","response":"db7705c96e45","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementCharges","classification":"READ","schema":"7e41fc1a1e08","response":"20b5cadac79e","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementDeposits","classification":"READ","schema":"7e41fc1a1e08","response":"b905a3be4ed2","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementLine","classification":"READ","schema":"4249190735aa","response":"117c34a19a98","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementLines","classification":"READ","schema":"7e41fc1a1e08","response":"f65cfafe2da1","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementRelatedDocuments","classification":"READ","schema":"7e41fc1a1e08","response":"bec1149b52c7","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreements","classification":"READ","schema":"cd40ae40fad5","response":"b03dff63849f","permission":"sales:view","paginates":true},+ {"name":"sales_getRentalBillingPeriods","classification":"READ","schema":"7e41fc1a1e08","response":"be6d8cd76aac","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnableLinesForCustomer","classification":"READ","schema":"b8b343f19f4f","response":"8b3d2e7917fd","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnReason","classification":"READ","schema":"9db6b9d7003b","response":"784c9ecc581f","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnReasons","classification":"READ","schema":"cd40ae40fad5","response":"8a4afca236fd","permission":"sales:view","paginates":true},+ {"name":"sales_getReturnReasonsList","classification":"READ","schema":"31b84d65b2ac","response":"152e0efd7e28","permission":"sales:view","paginates":false},+ {"name":"sales_getRootQuoteMakeMethod","classification":"READ","schema":"40e11ca73a53","response":"f6ec0930d3af","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesDocumentsAssignedToMe","classification":"READ","schema":"31b84d65b2ac","response":"79cc01ae0450","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrder","classification":"READ","schema":"6e4655763b3f","response":"8f0db58fa8de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoiceLines","classification":"READ","schema":"6e4655763b3f","response":"1ff852ae9154","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","schema":"c9445aed4a17","response":"397cd2bf218b","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","schema":"c9445aed4a17","response":"cd5bcdc964de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLine","classification":"READ","schema":"fbe78064dbd7","response":"29aeab62ea0c","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLines","classification":"READ","schema":"6e4655763b3f","response":"f904c1837ab8","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLineShipments","classification":"READ","schema":"fbe78064dbd7","response":"57f078948fed","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderPayment","classification":"READ","schema":"6e4655763b3f","response":"e52a6a8beddf","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderRelatedItems","classification":"READ","schema":"73e5a8561a17","response":"7368e76f2238","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrders","classification":"READ","schema":"01edbec4cd66","response":"0e723cce3b7f","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesOrderShipment","classification":"READ","schema":"6e4655763b3f","response":"c3b2536756de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrdersList","classification":"READ","schema":"31b84d65b2ac","response":"5cc20a44d4fe","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrder","classification":"READ","schema":"3fdcd215dc22","response":"e1d9d94aa958","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderCredits","classification":"READ","schema":"3fdcd215dc22","response":"49639d091139","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderIssues","classification":"READ","schema":"3fdcd215dc22","response":"7cc200ea4b26","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderLine","classification":"READ","schema":"e2b1df794940","response":"6a8842161fed","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderLines","classification":"READ","schema":"3fdcd215dc22","response":"76501c9a66f1","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderReceipts","classification":"READ","schema":"3fdcd215dc22","response":"184a88ad855b","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrders","classification":"READ","schema":"6fdb647c5b76","response":"90d6fe03373c","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesRFQ","classification":"READ","schema":"7f8214d1083f","response":"976840e1df1f","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQLine","classification":"READ","schema":"e2b1df794940","response":"6a8f94e9ad4f","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQLines","classification":"READ","schema":"c32128ec72f8","response":"9d27e3810b86","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQs","classification":"READ","schema":"cd40ae40fad5","response":"19578401a4c3","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesTerms","classification":"READ","schema":"31b84d65b2ac","response":"9819ae68df9b","permission":"sales:view","paginates":false},+ {"name":"sales_getShippedTrackedEntitiesForCustomer","classification":"READ","schema":"a25c9a6913ae","response":"a1e8810dc49a","permission":"sales:view","paginates":false},+ {"name":"sales_insertCustomerContact","classification":"WRITE","schema":"bc32d3cd1b75","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_insertCustomerLocation","classification":"WRITE","schema":"59180d724919","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_insertQuote","classification":"WRITE","schema":"bf0bba77b42f","response":"9e29b49e1dc8","permission":"sales:create","paginates":false},+ {"name":"sales_insertSalesOrder","classification":"WRITE","schema":"1e78cc5e252c","response":"dbfc22813350","permission":"sales:create","paginates":false},+ {"name":"sales_insertSalesReturnOrder","classification":"WRITE","schema":"d94a35f05cf8","response":"c32485518acd","permission":"sales:create","paginates":false},+ {"name":"sales_mapSalesRfqLines","classification":"WRITE","schema":"02bac31af170","response":"2132422b3a2d","permission":"sales:update","paginates":false},+ {"name":"sales_previewContractAmendment","classification":"WRITE","schema":"d957db5d561f","response":"351679e8ebb2","permission":"sales:update","paginates":false},+ {"name":"sales_previewContractCancellation","classification":"WRITE","schema":"0ef6e4e693de","response":"3ce9eb1c5d28","permission":"sales:update","paginates":false},+ {"name":"sales_releaseRentalUnit","classification":"WRITE","schema":"45909d441c37","response":"9729319c460e","permission":"sales:update","paginates":false},+ {"name":"sales_reopenSalesReturnOrder","classification":"WRITE","schema":"7f8214d1083f","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_repriceQuoteLineFromRules","classification":"WRITE","schema":"ffca7e5c29c1","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_resolvePrice","classification":"WRITE","schema":"f5fcab444c97","response":"eb12029769da","permission":"sales:update","paginates":false},+ {"name":"sales_resolvePriceList","classification":"WRITE","schema":"bca2332502db","response":"965c08b897d0","permission":"sales:update","paginates":false},+ {"name":"sales_returnRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"e00a9764517d","permission":"none","paginates":false},+ {"name":"sales_revertContractCancellation","classification":"WRITE","schema":"a18bd6ac2fe5","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_sellRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"d51ae9969843","permission":"none","paginates":false},+ {"name":"sales_setContractInvoiceAutomation","classification":"WRITE","schema":"321dd5c5e689","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setContractTerm","classification":"WRITE","schema":"3db861398453","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setContractType","classification":"WRITE","schema":"4899de777529","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setQuoteOperationWorkInstruction","classification":"WRITE","schema":"85f02e862122","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setQuoteStatus","classification":"WRITE","schema":"1ea4822e0e18","response":"1ea4822e0e18","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalAgreementStatus","classification":"WRITE","schema":"18addd891e4a","response":"18addd891e4a","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalAgreementTerm","classification":"WRITE","schema":"2aff228d5443","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalInvoiceAutomation","classification":"WRITE","schema":"321dd5c5e689","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesOrderStatus","classification":"WRITE","schema":"2c6a4f982ec9","response":"54a0554d39e6","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesReturnOrderLineDisposition","classification":"WRITE","schema":"eea359b826f8","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesRfqStatus","classification":"WRITE","schema":"068bf0995415","response":"7b9686b50055","permission":"sales:update","paginates":false},+ {"name":"sales_shipSalesOrderLine","classification":"WRITE","schema":"58e3c9762923","response":"2e39a760a5ca","permission":"inventory:create","paginates":false},+ {"name":"sales_shortCloseSalesReturnOrderLine","classification":"WRITE","schema":"b212fe8e50fb","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateContractLine","classification":"WRITE","schema":"c6d281a5793a","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateContractTerms","classification":"WRITE","schema":"7cdb0bcfea29","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomer","classification":"WRITE","schema":"6d8f73c8814f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerBankAccount","classification":"WRITE","schema":"8bd701af67a3","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"sales_updateCustomerContact","classification":"WRITE","schema":"713c7de4f8a2","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerLocation","classification":"WRITE","schema":"6afc03cf515f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerPayment","classification":"WRITE","schema":"d3366ce33e7a","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerShipping","classification":"WRITE","schema":"32775010b257","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerStatus","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerTax","classification":"WRITE","schema":"17d9248d9345","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updateNoQuoteReason","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updatePricingRule","classification":"WRITE","schema":"a558835d70d7","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteDetails","classification":"WRITE","schema":"97e47673eb0b","response":"c726ae407913","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteLine","classification":"WRITE","schema":"29659b4ffe67","response":"8529f8fc63c9","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteLineOrder","classification":"WRITE","schema":"323824b4392c","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteLinePrecision","classification":"WRITE","schema":"cf30feb01e5c","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"4ea32bd70246","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationParameter","classification":"WRITE","schema":"7ab14ae5050b","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationStep","classification":"WRITE","schema":"2a34a54df226","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationTool","classification":"WRITE","schema":"2285dc35c71d","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateRentalAgreementCharge","classification":"WRITE","schema":"438676fd9225","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateRentalAgreementLine","classification":"WRITE","schema":"194674afe1af","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateReturnOrderLine","classification":"WRITE","schema":"9707b1beaf57","response":"f9d1513a44f3","permission":"sales:update","paginates":false},+ {"name":"sales_updateReturnReason","classification":"WRITE","schema":"03734363977f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderDetails","classification":"WRITE","schema":"cdfda47dd459","response":"d160a49d6787","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"1f7aae174849","response":"8f061af39e95","permission":"sales:create","paginates":false},+ {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","schema":"bc4baf1732ad","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"00ea9309a858","response":"2e56e1180d37","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQLine","classification":"WRITE","schema":"827ecf864e53","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","schema":"fa6fee3c7515","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","schema":"c74a2a58d6cf","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertCustomerItemRentalRate","classification":"WRITE","schema":"36aacd353983","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertItemRentalRate","classification":"WRITE","schema":"69671ac2dab6","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","schema":"605368c2b9bd","response":"4e1a8f1febce","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertMakeMethodFromQuoteMethod","classification":"WRITE","schema":"dc9ff7a4d939","response":"bcde375ebd4c","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","schema":"18f385f95d04","response":"bcde375ebd4c","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteLinePrices","classification":"DESTRUCTIVE","schema":"01ec343190bf","response":"none","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuotePayment","classification":"WRITE","schema":"41842b4f8a7e","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteShipment","classification":"WRITE","schema":"9f413dd10f89","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderPayment","classification":"WRITE","schema":"d637b4fad42f","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderShipment","classification":"WRITE","schema":"c91b5d79606d","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"settings_assignPrinter","classification":"WRITE","schema":"e396a6d7690b","response":"de371a276a58","permission":"settings:update","paginates":false},+ {"name":"settings_createItemSerialSequence","classification":"WRITE","schema":"4a1a00848a52","response":"3797626bd17e","permission":"settings:create","paginates":false},+ {"name":"settings_deactivateCompanyIntegration","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"f06d2d858884","permission":"settings:update","paginates":false},+ {"name":"settings_deleteItemSerialSequence","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"settings:delete","paginates":false},+ {"name":"settings_deletePrintJob","classification":"DESTRUCTIVE","schema":"d46f637367f8","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_disableCompanyAuditLog","classification":"DESTRUCTIVE","schema":"31b84d65b2ac","response":"a369dbcd055c","permission":"settings:update","paginates":false},+ {"name":"settings_enableCompanyAuditLog","classification":"WRITE","schema":"31b84d65b2ac","response":"a369dbcd055c","permission":"settings:update","paginates":false},+ {"name":"settings_getAccountsPayableBillingAddress","classification":"READ","schema":"31b84d65b2ac","response":"7c0b9dc6d441","permission":"settings:view","paginates":false},+ {"name":"settings_getAccountsReceivableBillingAddress","classification":"READ","schema":"31b84d65b2ac","response":"7c0b9dc6d441","permission":"settings:view","paginates":false},+ {"name":"settings_getApiKeys","classification":"WRITE","schema":"cd40ae40fad5","response":"14fbafc2ddf8","permission":"users:update","paginates":true},+ {"name":"settings_getCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},+ {"name":"settings_getCompany","classification":"READ","schema":"31b84d65b2ac","response":"81a93f0029ec","permission":"settings:view","paginates":false},+ {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"dfb93f1739df","permission":"settings:view","paginates":false},+ {"name":"settings_getConfig","classification":"READ","schema":"31b84d65b2ac","response":"aa1021ff34cf","permission":"settings:view","paginates":false},+ {"name":"settings_getCurrentSequence","classification":"READ","schema":"31018ffa701d","response":"00404e686415","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomField","classification":"READ","schema":"7f8214d1083f","response":"a533a796c094","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomFields","classification":"READ","schema":"31018ffa701d","response":"2dad5e1497d3","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomFieldsTables","classification":"READ","schema":"cd40ae40fad5","response":"b1e2b7dc7754","permission":"settings:view","paginates":true},+ {"name":"settings_getDocumentSections","classification":"READ","schema":"31b84d65b2ac","response":"d8b65982e0d9","permission":"settings:view","paginates":false},+ {"name":"settings_getDocumentTemplate","classification":"READ","schema":"2a2940399e72","response":"99cae633d7cb","permission":"settings:view","paginates":false},+ {"name":"settings_getDocumentTemplateConfig","classification":"READ","schema":"2a2940399e72","response":"b41fea20c407","permission":"settings:view","paginates":false},+ {"name":"settings_getEmployeeCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},+ {"name":"settings_getIndustries","classification":"READ","schema":"31b84d65b2ac","response":"5dcce0f224dd","permission":"settings:view","paginates":false},+ {"name":"settings_getIntegration","classification":"READ","schema":"7f8214d1083f","response":"099545249106","permission":"settings:view","paginates":false},+ {"name":"settings_getItemSerialSequence","classification":"READ","schema":"7f8214d1083f","response":"be8519536044","permission":"settings:view","paginates":false},+ {"name":"settings_getItemSerialSequences","classification":"READ","schema":"cd40ae40fad5","response":"1caa1f035e17","permission":"settings:view","paginates":true},+ {"name":"settings_getKanbanOutputSetting","classification":"READ","schema":"31b84d65b2ac","response":"ca53dc098fc8","permission":"settings:view","paginates":false},+ {"name":"settings_getNextSequence","classification":"WRITE","schema":"31018ffa701d","response":"00404e686415","permission":"settings:update","paginates":false},+ {"name":"settings_getPlans","classification":"READ","schema":"31b84d65b2ac","response":"5483e69d7515","permission":"settings:view","paginates":false},+ {"name":"settings_getSequence","classification":"READ","schema":"31018ffa701d","response":"ef17e2453ded","permission":"settings:view","paginates":false},+ {"name":"settings_getSequences","classification":"READ","schema":"cd40ae40fad5","response":"9f334247353f","permission":"settings:view","paginates":true},+ {"name":"settings_getSequencesList","classification":"READ","schema":"31018ffa701d","response":"8394fbabd845","permission":"settings:view","paginates":false},+ {"name":"settings_getSubsidiaries","classification":"READ","schema":"31b84d65b2ac","response":"577bb278c46e","permission":"settings:view","paginates":false},+ {"name":"settings_getSubsidiary","classification":"READ","schema":"31b84d65b2ac","response":"ac5d56a91ae0","permission":"settings:view","paginates":false},+ {"name":"settings_getTerms","classification":"READ","schema":"31b84d65b2ac","response":"deb82bb77180","permission":"settings:view","paginates":false},+ {"name":"settings_getWebhook","classification":"READ","schema":"7f8214d1083f","response":"cb2b17a3252e","permission":"settings:view","paginates":false},+ {"name":"settings_getWebhooks","classification":"READ","schema":"cd40ae40fad5","response":"6a21799f60dd","permission":"settings:view","paginates":true},+ {"name":"settings_getWebhookTables","classification":"READ","schema":"31b84d65b2ac","response":"4417f117cc34","permission":"settings:view","paginates":false},+ {"name":"settings_removeDocumentSection","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_removePrinterRoute","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_resolveSections","classification":"WRITE","schema":"1ddda22ecba8","response":"32e51b029d79","permission":"settings:update","paginates":false},+ {"name":"settings_saveDocumentSection","classification":"WRITE","schema":"8a0f21626132","response":"d77a04e8c53e","permission":"settings:update","paginates":false},+ {"name":"settings_saveDocumentTemplate","classification":"WRITE","schema":"af049b32ee8d","response":"f1822dd9c8ab","permission":"settings:update","paginates":false},+ {"name":"settings_setIntegrationSyncEnabled","classification":"WRITE","schema":"fa07001f8501","response":"4111dc6445bb","permission":"settings:update","paginates":false},+ {"name":"settings_transitionSyncOperations","classification":"WRITE","schema":"c5a1f2594d65","response":"401e1aae225f","permission":"settings:update","paginates":false},+ {"name":"settings_updateAccountingSettings","classification":"WRITE","schema":"ecf0d5091645","response":"70bcf2b87ee3","permission":"settings:update","paginates":false},+ {"name":"settings_updateCompanyDetails","classification":"WRITE","schema":"f48dad39eb59","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_updateDimensionSync","classification":"WRITE","schema":"42c99362fccd","response":"f95fa90d0071","permission":"settings:update","paginates":false},+ {"name":"settings_updateInventorySettings","classification":"WRITE","schema":"a76084d47705","response":"d62a56ef4842","permission":"settings:update","paginates":false},+ {"name":"settings_updateInvoicingSettings","classification":"WRITE","schema":"48fd9aba9ea8","response":"a32ee5ad2099","permission":"settings:update","paginates":false},+ {"name":"settings_updateItemSerialSequence","classification":"WRITE","schema":"8e65da365dcb","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_updateItemsSettings","classification":"WRITE","schema":"b4f7e7addad9","response":"03604adb2677","permission":"settings:update","paginates":false},+ {"name":"settings_updatePlanningSettings","classification":"WRITE","schema":"0c543ed217a3","response":"0b9572e63423","permission":"settings:update","paginates":false},+ {"name":"settings_updatePostingSync","classification":"WRITE","schema":"a545e3ef8da3","response":"f95fa90d0071","permission":"settings:update","paginates":false},+ {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"aab377266e08","response":"be6b8045779d","permission":"settings:update","paginates":false},+ {"name":"settings_updatePurchasingSettings","classification":"WRITE","schema":"bac40d77d38a","response":"b3fda8ac0d5f","permission":"settings:update","paginates":false},+ {"name":"settings_updateQualitySettings","classification":"WRITE","schema":"1bcfa3043aa1","response":"e87697c359ae","permission":"settings:update","paginates":false},+ {"name":"settings_updateResourcesSettings","classification":"WRITE","schema":"ba1b98fe944a","response":"ec0f37163627","permission":"settings:update","paginates":false},+ {"name":"settings_updateSalesSettings","classification":"WRITE","schema":"b200fc3300ac","response":"8becbd99be1d","permission":"settings:update","paginates":false},+ {"name":"settings_updateSecuritySettings","classification":"WRITE","schema":"1a5429a80ff2","response":"1a5429a80ff2","permission":"settings:update","paginates":false},+ {"name":"settings_updateSequence","classification":"WRITE","schema":"4f2efa805950","response":"bcde375ebd4c","permission":"settings:update","paginates":false},+ {"name":"shared_assignRecord","classification":"WRITE","schema":"fc5741825100","response":"3797626bd17e","permission":"none","paginates":false},+ {"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","schema":"785f497635a2","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"shared_enrollImplementationHub","classification":"WRITE","schema":"31b84d65b2ac","response":"a8f082a96841","permission":"settings:update","paginates":false},+ {"name":"shared_getBase64ImageFromSupabase","classification":"READ","schema":"e7450d4b5827","response":"00404e686415","permission":"none","paginates":false},+ {"name":"shared_getCountries","classification":"READ","schema":"31b84d65b2ac","response":"0e8a11b4e81c","permission":"none","paginates":false},+ {"name":"shared_getCustomerPortal","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"none","paginates":false},+ {"name":"shared_getCustomerPortals","classification":"READ","schema":"cd40ae40fad5","response":"a53103528f4a","permission":"none","paginates":true},+ {"name":"shared_getEnforcementRule","classification":"READ","schema":"1345cc9e3507","response":"5d98bf9ad216","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","schema":"3d06fc9d6384","response":"979bf79974f2","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRules","classification":"READ","schema":"8527ac646a22","response":"4c883b774887","permission":"none","paginates":true},+ {"name":"shared_getExternalLink","classification":"READ","schema":"7f8214d1083f","response":"11128e5c07f9","permission":"none","paginates":false},+ {"name":"shared_getModelByItemId","classification":"READ","schema":"30ab89ff5be9","response":"none","permission":"none","paginates":false},+ {"name":"shared_getNotes","classification":"READ","schema":"1a362ab8a372","response":"1a052a4417b5","permission":"none","paginates":false},+ {"name":"shared_getTagsList","classification":"READ","schema":"af4eca956117","response":"b837740e18f4","permission":"none","paginates":false},+ {"name":"shared_insertNote","classification":"WRITE","schema":"6b735d93fae1","response":"c2fb0e5225f8","permission":"none","paginates":false},+ {"name":"shared_insertTag","classification":"WRITE","schema":"9fd690c21fa5","response":"27f67ae1958c","permission":"none","paginates":false},+ {"name":"shared_updateSavedViewOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"393a0d83325c","permission":"none","paginates":false},+ {"name":"shared_upsertSavedView","classification":"WRITE","schema":"0bfaff189d21","response":"3797626bd17e","permission":"none","paginates":false},+ {"name":"users_deleteGroup","classification":"DESTRUCTIVE","schema":"6624f3863074","response":"bcde375ebd4c","permission":"users:delete","paginates":false},+ {"name":"users_getAccount","classification":"READ","schema":"7f8214d1083f","response":"8adb0e14ee10","permission":"none","paginates":false},+ {"name":"users_getAllAttributeCategories","classification":"READ","schema":"31b84d65b2ac","response":"e93d76f694fe","permission":"none","paginates":false},+ {"name":"users_getAttributeCategoryWithValues","classification":"READ","schema":"ac8b9e1ae260","response":"32112b6759f8","permission":"none","paginates":false},+ {"name":"users_getConsoleOperators","classification":"READ","schema":"cd40ae40fad5","response":"9823b01639fc","permission":"users:view","paginates":true},+ {"name":"users_getCurrentUser","classification":"READ","schema":"31b84d65b2ac","response":"ddc730821e71","permission":"none","paginates":false},+ {"name":"users_getCustomers","classification":"READ","schema":"cd40ae40fad5","response":"01865d2b41ff","permission":"users:view","paginates":true},+ {"name":"users_getEmployee","classification":"READ","schema":"7f8214d1083f","response":"fddbdf17260d","permission":"users:view","paginates":false},+ {"name":"users_getEmployees","classification":"READ","schema":"cd40ae40fad5","response":"9823b01639fc","permission":"users:view","paginates":true},+ {"name":"users_getEmployeeType","classification":"READ","schema":"6e5e68777065","response":"02c4f766f388","permission":"users:view","paginates":false},+ {"name":"users_getEmployeeTypes","classification":"READ","schema":"cd40ae40fad5","response":"1546a93f061d","permission":"users:view","paginates":true},+ {"name":"users_getGroup","classification":"READ","schema":"6624f3863074","response":"f06d2d858884","permission":"users:view","paginates":false},+ {"name":"users_getGroupEmails","classification":"READ","schema":"99198903a0f2","response":"681004346c78","permission":"users:view","paginates":false},+ {"name":"users_getGroupMembers","classification":"READ","schema":"6624f3863074","response":"f218e882144b","permission":"users:view","paginates":false},+ {"name":"users_getGroups","classification":"READ","schema":"ec5a8a97b830","response":"14a0c805bf0d","permission":"users:view","paginates":true},+ {"name":"users_getInvitable","classification":"READ","schema":"31b84d65b2ac","response":"3173c3a99146","permission":"users:view","paginates":false},+ {"name":"users_getItarCertificationReport","classification":"READ","schema":"31b84d65b2ac","response":"203ea6eb1a16","permission":"users:view","paginates":false},+ {"name":"users_getItarCertificationStatus","classification":"READ","schema":"31b84d65b2ac","response":"6afd62a22e82","permission":"users:view","paginates":false},+ {"name":"users_getItarEntityCertification","classification":"READ","schema":"31b84d65b2ac","response":"c5ae95ca48db","permission":"users:view","paginates":false},+ {"name":"users_getModules","classification":"READ","schema":"31b84d65b2ac","response":"df0e311a0baf","permission":"users:view","paginates":false},+ {"name":"users_getNotificationPreferences","classification":"READ","schema":"31b84d65b2ac","response":"0486649779fc","permission":"none","paginates":false},+ {"name":"users_getPermissionsByEmployeeType","classification":"READ","schema":"6e5e68777065","response":"9273cec17683","permission":"users:view","paginates":false},+ {"name":"users_getSuppliers","classification":"READ","schema":"cd40ae40fad5","response":"92e8a9c9df02","permission":"users:view","paginates":true},+ {"name":"users_getUnrevokedInviteEmails","classification":"READ","schema":"31b84d65b2ac","response":"a6b0124b4410","permission":"users:view","paginates":false},+ {"name":"users_getUserSelectGroupMembers","classification":"READ","schema":"6624f3863074","response":"b754519017cb","permission":"users:view","paginates":false},+ {"name":"users_getUserSelectGroups","classification":"READ","schema":"f802932716af","response":"51b54791b40a","permission":"users:view","paginates":false},+ {"name":"users_getUsersWithVerifiedMfa","classification":"READ","schema":"31b84d65b2ac","response":"4c1fdc714231","permission":"users:view","paginates":false},+ {"name":"users_resolveUserSelectIds","classification":"WRITE","schema":"1ddda22ecba8","response":"7fdfa4c9e77e","permission":"users:update","paginates":false},+ {"name":"users_searchUsersForSelect","classification":"READ","schema":"b9c0b50026a7","response":"c9c1df9c3e28","permission":"users:view","paginates":false},+ {"name":"users_updatePublicAccount","classification":"WRITE","schema":"1ce670a17890","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"users_upsertNotificationPreference","classification":"WRITE","schema":"537337e9e9aa","response":"bcde375ebd4c","permission":"none","paginates":false}]}diff --cc apps/erp/app/routes/x+/accounting+/asset-classes.tsxindex 6a54a4ede2,10e0dc3aa2..3a9dd10a09--- a/apps/erp/app/routes/x+/accounting+/asset-classes.tsx+++ b/apps/erp/app/routes/x+/accounting+/asset-classes.tsx@@@ -10,12 -11,12 +10,12 @@@ import type { LoaderFunctionArgs } froimport { useLoaderData, useNavigate } from "react-router";import { NewAction } from "~/components/New";import { usePermissions } from "~/hooks";-import { getFixedAssetClasses } from "~/modules/accounting/accounting.service";import { AssetClassesTable } from "~/modules/accounting/ui/FixedAssets";- import { getCompanySettings } from "~/modules/settings";+ import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";+import { assetClassesList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Asset Classes`,diff --cc apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsxindex 7ef96dcf65,59dcec006c..eec698194d--- a/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx@@@ -9,8 -9,11 +9,10 @@@ import { getLogger } from "@carbon/loggimport { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAccount } from "~/modules/accounting";- import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";+ import {+ getAccount,- getAccountLedger,- getAccountLedgerSummary++ getAccountLedgerPage+ } from "~/modules/accounting/accounting.service";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";diff --cc apps/erp/app/routes/x+/accounting+/charts.tsxindex cbef659b82,098a85587c..726254f774--- a/apps/erp/app/routes/x+/accounting+/charts.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.tsx@@@ -14,14 -14,14 +14,14 @@@ import { useLoaderData } from "react-roimport {getChartOfAccounts,getFiscalYearSettings- } from "~/modules/accounting";+ } from "~/modules/accounting/accounting.service";+ import type { Chart } from "~/modules/accounting/types";import { ChartOfAccountsTree } from "~/modules/accounting/ui/ChartOfAccounts";import ChartOfAccountsTableFilters from "~/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters";- import { months } from "~/modules/shared";+ import { months } from "~/modules/shared/shared.models";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Chart of Accounts`,diff --cc apps/erp/app/routes/x+/accounting+/fixed-assets.tsxindex cf94b8ec74,cb223bde1f..9931f6de08--- a/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx+++ b/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx@@@ -10,12 -11,14 +10,12 @@@ import type { LoaderFunctionArgs } froimport { useLoaderData, useNavigate } from "react-router";import { NewAction } from "~/components/New";import { usePermissions } from "~/hooks";- import { getFixedAssetClassesList } from "~/modules/accounting";-import {- getFixedAssetClassesList,- getFixedAssets-} from "~/modules/accounting/accounting.service";++import { getFixedAssetClassesList } from "~/modules/accounting/accounting.service";import { FixedAssetsTable } from "~/modules/accounting/ui/FixedAssets";import type { Handle } from "~/utils/handle";+import { fixedAssetsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Fixed Assets`,diff --cc apps/erp/app/routes/x+/accounting+/period-runs.server.tsindex 0000000000,49239bd5f6..653e3b6524mode 000000,100644..100644--- a/apps/erp/app/routes/x+/accounting+/period-runs.server.ts+++ b/apps/erp/app/routes/x+/accounting+/period-runs.server.ts@@@ -1,0 -1,98 +1,76 @@@+ // 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 two period runs on one engine — revenue recognition and lease runs+ // (spec `.ai/specs/2026-10-11-lessee-leases.md` §6) — share their list loader+ // and their "New run" action. Each takes the run type.++ import { carbon, respond } from "@carbon/api/carbon.server";-import { requirePermissions } from "@carbon/auth/auth.server";+ import type { RunType } from "@carbon/database/run-type";+ import { runLabelSentence } from "@carbon/database/run-type";+ import { validator } from "@carbon/form";+ import { datetime } from "@carbon/utils";+ import type { ActionFunctionArgs } from "react-router";+ import { z } from "zod";-import {- existingDraftRunId,- getRevenueRecognitionRuns-} from "~/modules/accounting/accounting.service";++import { existingDraftRunId } from "~/modules/accounting/accounting.service";+ import { getNextRevenueRecognitionPeriodEnd } from "~/modules/accounting/accounting.utils";+ import { RUN_PAGES } from "~/modules/accounting/ui/RevenueRecognition/runPages";+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";++import { periodRunsLists } from "~/utils/list-registry/accounting.server";++import { loadListPage } from "~/utils/list-registry/load.server";+ import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++ const newRunForm = z.object({ periodEnd: z.string().optional() });++ export async function loadPeriodRuns(request: Request, type: RunType) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);++ return loadListPage(request, periodRunsLists[type], {++ dataKey: "data",++ firstPage: async ({ client, companyId }) => {++ const lastRun = await client++ .from("revenueRecognitionRun")++ .select("periodEnd, status")++ .eq("companyId", companyId)++ .eq("type", type)++ .order("periodEnd", { ascending: false })++ .limit(1);+- const [runs, lastRun] = await Promise.all([- getRevenueRecognitionRuns(client, companyId, type, {- search,- limit,- offset,- sorts,- filters- }),- client- .from("revenueRecognitionRun")- .select("periodEnd, status")- .eq("companyId", companyId)- .eq("type", type)- .order("periodEnd", { ascending: false })- .limit(1)- ]);-- const lastRunData =- lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;- // The proposed period: the month after the last run, or the month just- // closed in the company's calendar when there is no run yet.- const nextPeriodEnd = getNextRevenueRecognitionPeriodEnd(- lastRunData?.periodEnd ?? null,- datetime.today(await getCompanyTimeZone(client, companyId)).toString()- );- const hasDraftBlocking = lastRunData?.status === "Draft";-- return {- data: runs.data ?? [],- count: runs.count ?? 0,- nextPeriodEnd,- hasDraftBlocking- };++ const lastRunData =++ lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;++ // The proposed period: the month after the last run, or the month just++ // closed in the company's calendar when there is no run yet.++ const nextPeriodEnd = getNextRevenueRecognitionPeriodEnd(++ lastRunData?.periodEnd ?? null,++ datetime.today(await getCompanyTimeZone(client, companyId)).toString()++ );++ return {++ nextPeriodEnd,++ hasDraftBlocking: lastRunData?.status === "Draft"++ };++ }++ });+ }++ /** The list pages' New Run: the period the page showed, or with a bare POST+ * the month after the last run of the type. */+ export async function createPeriodRun(args: ActionFunctionArgs, type: RunType) {+ const input = await validator(newRunForm).request(args);+ if ("invalid" in input) return input.invalid;+ const api = await carbon(args.request);+ const result = await api.accounting.createRevenueRecognitionRun({+ type,+ periodEnd: input.data.periodEnd || undefined+ });+ const draftRunId = existingDraftRunId(result.error);+ return respond(args.request, result).redirect(+ result.data+ ? path.to.revenueRecognitionRun(result.data.id)+ : RUN_PAGES[type].listPath,+ {+ message: `${runLabelSentence(type)} created`,+ onError: draftRunId+ ? path.to.revenueRecognitionRun(draftRunId)+ : undefined+ }+ );+ }diff --cc apps/erp/app/routes/x+/documents+/search.tsxindex 757348a6e4,03935d2b41..d7a2c1ed66--- a/apps/erp/app/routes/x+/documents+/search.tsx+++ b/apps/erp/app/routes/x+/documents+/search.tsx@@@ -12,60 -15,85 +12,60 @@@ importimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { useResolved } from "~/hooks/useResolved";- import type { Document } from "~/modules/documents";import {- DocumentsTable,getDocumentExtensions,- getDocumentLabels,- getDocuments+ getDocumentLabels- } from "~/modules/documents";+ } from "~/modules/documents/documents.service";+ import type { Document } from "~/modules/documents/types";+ import { DocumentsTable } from "~/modules/documents/ui";+import {+ documentsList,+ recentDocumentsList+} from "~/utils/list-registry/documents.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- view: "documents"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const filter = searchParams.get("q");-- const createdBy = filter === "my" ? userId : undefined;- const favorite = filter === "starred" ? true : undefined;- const recent = filter === "recent" ? true : undefined;- const active = filter === "trash" ? false : true;-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- // Only the file-type filter needs this, so it streams rather than holding- // the page.- const extensions = getDocumentExtensions(client, companyId).then(- (result) => result.data?.map(({ extension }) => extension) ?? []- );+ // The "Recent" view orders by the last activity, so it is its own list.+ const list =+ new URL(request.url).searchParams.get("q") === "recent"+ ? recentDocumentsList+ : documentsList;- const [documents, labels] = await Promise.all([- getDocuments(client, companyId, {- search,- favorite,- recent,- createdBy,- active,- limit,- offset,- sorts,- filters+ return loadListPage(request, list, {+ dataKey: "documents",+ firstPage: async ({ client, companyId, userId }) => ({+ listKey: list.key,+ labels: (await getDocumentLabels(client, userId)).data ?? [],+ // Only the file-type filter needs this, so it streams rather than+ // holding the page.+ extensions: getDocumentExtensions(client, companyId).then(+ (result) => result.data?.map(({ extension }) => extension) ?? []+ )}),- getDocumentLabels(client, userId)- ]);-- if (documents.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(documents.error, "Failed to fetch documents"))- );- }-- // Mint a signed download token per file-backed row. Signing is a server-only- // HS256 op over the current result set (the same set the CSV exports).- const documentsWithDownloadTokens: Document[] = await Promise.all(- (documents.data ?? []).map(async (document) => ({- ...document,- downloadToken:- document.id && document.path- ? await generateDownloadToken({- userId,- companyId,- documentId: document.id- })- : undefined- }))- );-- return {- count: documents.count ?? 0,- documents: documentsWithDownloadTokens,- labels: labels.data ?? [],- extensions- };+ // A signed download token per file-backed row. Signing is a server-only+ // HS256 op. Each page mints its own, so every loaded row carries one.+ mapRows: (documents, { companyId, userId }) =>+ Promise.all(+ (documents as Document[]).map(+ async (document): Promise<Document> => ({+ ...document,+ downloadToken:+ document.id && document.path+ ? await generateDownloadToken({+ userId,+ companyId,+ documentId: document.id+ })+ : undefined+ })+ )+ ),+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch documents"+ }+ });}export default function DocumentsAllRoute() {diff --cc apps/erp/app/routes/x+/inventory+/inventory-count.tsxindex 891d90c02f,102559d5ba..404fca96b4--- a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx+++ b/apps/erp/app/routes/x+/inventory+/inventory-count.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { InventoryCountsTable } from "~/modules/inventory";- import { getLocationsList } from "~/modules/resources";-import { getInventoryCounts } from "~/modules/inventory/inventory.service";+ import { InventoryCountsTable } from "~/modules/inventory/ui";+ import { getLocationsList } from "~/modules/resources/resources.service";import type { Handle } from "~/utils/handle";+import { inventoryCountsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["inventoryCount"],diff --cc apps/erp/app/routes/x+/inventory+/kanbans.tsxindex 903d7d74ec,7301bc51bf..b3a19605bf--- a/apps/erp/app/routes/x+/inventory+/kanbans.tsx+++ b/apps/erp/app/routes/x+/inventory+/kanbans.tsx@@@ -13,16 -13,13 +13,16 @@@ import type { LoaderFunctionArgs } froimport { useLoaderData } from "react-router";import {getKanbanProjectedQuantities,- getKanbans+ getKanbans,+ KANBANS_PAGING- } from "~/modules/inventory";+ } from "~/modules/inventory/inventory.service";import KanbansTable from "~/modules/inventory/ui/Kanbans/KanbansTable";- import { getLocationsList } from "~/modules/resources";- import { getKanbanOutputSetting } from "~/modules/settings";- import { getUserDefaults } from "~/modules/users/users.server";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import { getKanbanOutputSetting } from "~/modules/settings/settings.service";+ import { getUserDefaults } from "~/modules/users/users.service";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/inventory+/quantities.tsxindex d37f4ce3c7,f52d95c3eb..b44356c94f--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx@@@ -20,20 -18,18 +19,21 @@@ importexpandStorageUnitIdsWithDescendants,getInventoryItems,getStorageTypesList,- getStorageUnitsList+ getStorageUnitsList,+ INVENTORY_ITEMS_PAGING- } from "~/modules/inventory";+ } from "~/modules/inventory/inventory.service";+ import type { InventoryItem } from "~/modules/inventory/types";import InventoryTable from "~/modules/inventory/ui/Inventory/InventoryTable";import {getMaterialFormsList,getMaterialSubstancesList- } from "~/modules/items";- import { getLocationsList } from "~/modules/resources";- import { getTagsList } from "~/modules/shared";- import { getUserDefaults } from "~/modules/users/users.server";+ } from "~/modules/items/items.service";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import { getTagsList } from "~/modules/shared/shared.service";+ import { getUserDefaults } from "~/modules/users/users.service";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/inventory+/receipts.tsxindex 85651fdd1c,2109b9e024..b4970179a9--- a/apps/erp/app/routes/x+/inventory+/receipts.tsx+++ b/apps/erp/app/routes/x+/inventory+/receipts.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ReceiptsTable } from "~/modules/inventory";-import { getReceipts } from "~/modules/inventory/inventory.service";+ import { ReceiptsTable } from "~/modules/inventory/ui";import type { Handle } from "~/utils/handle";+import { receiptsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["receipt"],diff --cc apps/erp/app/routes/x+/inventory+/shipping-methods.tsxindex 572f37a462,534872521b..8fe9b5f9e9--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx@@@ -6,11 -9,13 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ShippingMethodsTable } from "~/modules/inventory";-import { getAccountsList } from "~/modules/accounting/accounting.service";-import { getShippingMethods } from "~/modules/inventory/inventory.service";+ import { ShippingMethodsTable } from "~/modules/inventory/ui";import type { Handle } from "~/utils/handle";+import { shippingMethodsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Shipping Methods`,diff --cc apps/erp/app/routes/x+/inventory+/stock-transfers.tsxindex dc00f1483d,ce6238c6f3..30d52fd41c--- a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx+++ b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx@@@ -11,13 -11,11 +11,16 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getStockTransfers, STOCK_TRANSFERS_PAGING } from "~/modules/inventory";-import { getStockTransfers } from "~/modules/inventory/inventory.service";++import {++ getStockTransfers,++ STOCK_TRANSFERS_PAGING++} from "~/modules/inventory/inventory.service";import StockTransfersTable from "~/modules/inventory/ui/StockTransfers/StockTransfersTable";- import { getLocationsList } from "~/modules/resources";- import { getUserDefaults } from "~/modules/users/users.server";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import { getUserDefaults } from "~/modules/users/users.service";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/inventory+/storage-rules.tsxindex 573dfc52c2,34ddaf21e6..4954863c89--- a/apps/erp/app/routes/x+/inventory+/storage-rules.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.tsx@@@ -16,9 -16,8 +16,9 @@@ import StorageRulesUpgradeOverlay fromimport {getEnforcementRuleAssignmentCounts,getEnforcementRules- } from "~/modules/shared";+ } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export const handle: Handle = {diff --cc apps/erp/app/routes/x+/inventory+/storage-units.tsxindex a059e1f8bd,b479064654..7cfdf31d3f--- a/apps/erp/app/routes/x+/inventory+/storage-units.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.tsx@@@ -16,12 -16,11 +16,12 @@@ importgetStorageUnitRoots,getStorageUnitSubtrees,searchStorageUnitsWithAncestors- } from "~/modules/inventory";+ } from "~/modules/inventory/inventory.service";import StorageUnitsTable from "~/modules/inventory/ui/StorageUnits/StorageUnitsTable";- import { getLocationsList } from "~/modules/resources";- import { getUserDefaults } from "~/modules/users/users.server";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import { getUserDefaults } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/inventory+/tracked-entities.tsxindex 89110655fa,12bcb704ad..ae93980603--- a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx+++ b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx@@@ -6,12 -9,13 +6,12 @@@ import { VStack } from "@carbon/react"import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTrackedEntities } from "~/modules/inventory/inventory.service";import TrackedEntitiesTable from "~/modules/inventory/ui/Traceability/TrackedEntitiesTable";- import { getCompanySettings } from "~/modules/settings";+ import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";+import { trackedEntitiesList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["trackedEntity"],diff --cc apps/erp/app/routes/x+/inventory-count+/$id.tsxindex 6dfb6086b3,6bff6e4c44..0dc540d45f--- a/apps/erp/app/routes/x+/inventory-count+/$id.tsx+++ b/apps/erp/app/routes/x+/inventory-count+/$id.tsx@@@ -17,18 -16,15 +17,18 @@@ importgetInventoryCountLines,getInventoryCountMovements,getStorageTypesList,- getStorageUnitsListForLocation+ getStorageUnitsListForLocation,- INVENTORY_COUNT_LINES_PAGING,- InventoryCountDetails- } from "~/modules/inventory";++ INVENTORY_COUNT_LINES_PAGING+ } from "~/modules/inventory/inventory.service";+ import { InventoryCountDetails } from "~/modules/inventory/ui";import {getMaterialFormsList,getMaterialSubstancesList- } from "~/modules/items";- import { getTagsList } from "~/modules/shared";+ } from "~/modules/items/items.service";+ import { getTagsList } from "~/modules/shared/shared.service";+import { toPage } from "~/utils/cursor";import { detailBreadcrumb, type Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/invoicing+/charges.tsxindex 13fbaf8edc,bf226871ae..b8748dcb99--- a/apps/erp/app/routes/x+/invoicing+/charges.tsx+++ b/apps/erp/app/routes/x+/invoicing+/charges.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ChargesTable } from "~/modules/invoicing";-import { getCharges } from "~/modules/invoicing/invoicing.service";+ import { ChargesTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { chargesList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Charges`,diff --cc apps/erp/app/routes/x+/invoicing+/credit-memos.tsxindex 977ca91400,a5c9dd9ca5..611a1e18fd--- a/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx+++ b/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx@@@ -5,11 -5,15 +5,11 @@@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { MemosTable } from "~/modules/invoicing";-import { getMemos } from "~/modules/invoicing/invoicing.service";+ import { MemosTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { creditMemosList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";// Accounts Receivable — customer credit/debit memos. The supplier side lives in// supplier-credits.tsx; both read the same `memo` table, scoped by party.diff --cc apps/erp/app/routes/x+/invoicing+/payments.tsxindex 5a658942d8,a38874a59b..f37ea48970--- a/apps/erp/app/routes/x+/invoicing+/payments.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payments.tsx@@@ -5,11 -5,15 +5,11 @@@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { PaymentsTable } from "~/modules/invoicing";-import { getPayments } from "~/modules/invoicing/invoicing.service";+ import { PaymentsTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { paymentsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["payment"],diff --cc apps/erp/app/routes/x+/invoicing+/purchasing.tsxindex 88e560a71e,2feddfa924..c897eeb00b--- a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx+++ b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { PurchaseInvoicesTable } from "~/modules/invoicing";-import { getPurchaseInvoices } from "~/modules/invoicing/invoicing.service";+ import { PurchaseInvoicesTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { purchaseInvoicesList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["purchaseInvoice"],diff --cc apps/erp/app/routes/x+/invoicing+/reimbursements.tsxindex ee4118279e,082dc22c20..c3e6a02714--- a/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx+++ b/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx@@@ -6,11 -9,12 +6,11 @@@ import { VStack } from "@carbon/react"import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ReimbursementsTable } from "~/modules/invoicing";-import { getReimbursements } from "~/modules/invoicing/invoicing.service";+ import { ReimbursementsTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { reimbursementsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Reimbursements`,diff --cc apps/erp/app/routes/x+/invoicing+/supplier-credits.tsxindex 178a422e6b,98aecf7525..2bd0fe2424--- a/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx+++ b/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx@@@ -5,11 -5,15 +5,11 @@@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { MemosTable } from "~/modules/invoicing";-import { getMemos } from "~/modules/invoicing/invoicing.service";+ import { MemosTable } from "~/modules/invoicing/ui";import type { Handle } from "~/utils/handle";+import { supplierCreditsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";// Accounts Payable — supplier credit/debit memos. The customer side lives in// credit-memos.tsx; both read the same `memo` table, scoped by party.diff --cc apps/erp/app/routes/x+/items+/change-notices+/_index.tsxindex 7d6806fe7b,d56cab39fe..0bfb85a62e--- a/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx+++ b/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx@@@ -2,26 -2,59 +2,26 @@@// 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 { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getChangeNoticeTypesList } from "~/modules/items";-import {- getChangeNotices,- getChangeNoticeTypesList-} from "~/modules/items/items.service";++import { getChangeNoticeTypesList } from "~/modules/items/items.service";import { ChangeNoticesTable } from "~/modules/items/ui/ChangeNotice";+import { changeNoticesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [changeNotices, types] = await Promise.all([- getChangeNotices(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, changeNoticesList, {+ dataKey: "changeNotices",+ firstPage: async ({ client, companyId }) => ({+ types: (await getChangeNoticeTypesList(client, companyId)).data ?? []}),- getChangeNoticeTypesList(client, companyId)- ]);-- if (changeNotices.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(changeNotices.error, "Error loading change notices")- )- );- }-- return {- changeNotices: changeNotices.data ?? [],- count: changeNotices.count ?? 0,- types: types.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading change notices"+ }+ });}export default function ChangeNoticesIndexRoute() {diff --cc apps/erp/app/routes/x+/items+/consumables.tsxindex ea31936940,8d633f8c3f..e98e06a3b4--- a/apps/erp/app/routes/x+/items+/consumables.tsx+++ b/apps/erp/app/routes/x+/items+/consumables.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getConsumables } from "~/modules/items/items.service";import { ConsumablesTable } from "~/modules/items/ui/Consumables";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { consumablesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],diff --cc apps/erp/app/routes/x+/items+/groups.tsxindex 255862a4a0,7b14a96deb..504774d15c--- a/apps/erp/app/routes/x+/items+/groups.tsx+++ b/apps/erp/app/routes/x+/items+/groups.tsx@@@ -9,12 -10,12 +9,12 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAccountsList } from "~/modules/accounting";+ import { getAccountsList } from "~/modules/accounting/accounting.service";-import { getItemPostingGroups } from "~/modules/items/items.service";import { ItemPostingGroupsTable } from "~/modules/items/ui/ItemPostingGroups";import type { Handle } from "~/utils/handle";+import { itemPostingGroupsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Item Groups`,diff --cc apps/erp/app/routes/x+/items+/materials.tsxindex 5ec63666a2,073ae592af..2e135bab88--- a/apps/erp/app/routes/x+/items+/materials.tsx+++ b/apps/erp/app/routes/x+/items+/materials.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterials } from "~/modules/items/items.service";import { MaterialsTable } from "~/modules/items/ui/Materials";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { materialsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],diff --cc apps/erp/app/routes/x+/items+/parts.tsxindex 50adafd4d5,024f6d0c04..2cf5b0eb69--- a/apps/erp/app/routes/x+/items+/parts.tsx+++ b/apps/erp/app/routes/x+/items+/parts.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getParts } from "~/modules/items/items.service";import { PartsTable } from "~/modules/items/ui/Parts";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { partsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";import { useRealtime } from "../../../hooks";export const handle: Handle = {diff --cc apps/erp/app/routes/x+/items+/services.tsxindex edc08885ad,e5f053913f..02130d7e57--- a/apps/erp/app/routes/x+/items+/services.tsx+++ b/apps/erp/app/routes/x+/items+/services.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getServices } from "~/modules/items/items.service";import { ServicesTable } from "~/modules/items/ui/Services";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { servicesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],diff --cc apps/erp/app/routes/x+/items+/tools.tsxindex 88c11e767d,4d3f14828b..ab3879482b--- a/apps/erp/app/routes/x+/items+/tools.tsx+++ b/apps/erp/app/routes/x+/items+/tools.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTools } from "~/modules/items/items.service";import { ToolsTable } from "~/modules/items/ui/Tools";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { toolsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],diff --cc apps/erp/app/routes/x+/items+/update.tsxindex d8b788a549,9c3f82e8b5..1e9f9e2d31--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@@ -2,70 -2,65 +2,89 @@@// 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 { carbon } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { getCarbonServiceRole } from "@carbon/auth/client.server";- import { getLogger } from "@carbon/logger";- import { unchecked } from "@carbon/utils";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { isItemBulkUpdateField } from "~/modules/items";- import { bulkUpdateItems } from "~/modules/items/bulk-actions.server";+ import { z } from "zod";+ import { zfd } from "zod-form-data";-import type { itemTrackingTypes } from "~/modules/items/items.models";+import {- getUnreleasedChangeOrderItems,- unreleasedChangeOrderItemsMessage- } from "~/modules/items/items.server";- import {- updateMaterialProperties,- updateServiceName- } from "~/modules/items/items.service";- import { getDatabaseClient } from "~/services/database.server";++ isItemBulkUpdateField,++ type itemTrackingTypes++} from "~/modules/items/items.models";+ import type { methodType, sourcingType } from "~/modules/shared/shared.models";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";- const logger = getLogger("erp", "update");-- export async function action({ request }: ActionFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- update: "parts"- });-- const formData = await request.formData();- const items = formData.getAll("items");- const field = formData.get("field");- const value = formData.get("value");-- if (typeof field !== "string" || typeof value !== "string") {- return { error: { message: "Invalid form data" }, data: null };- }-- // The item tables' bulk Update: every matching row runs in the background,- // a selection runs here. Both go through bulkUpdateItems.- if (isItemBulkUpdateField(field)) {- const started = await startAllMatchingBulkAction(- formData.get("allMatching"),- { companyId, userId, actionKey: "items.update", params: { field, value } }- );- if (started) return bulkStartFormResponse(started);-- // Each chunk of 100 commits on its own, so a failure can follow applied- // chunks: the counts let the table say what was done.- const result = await bulkUpdateItems(client, getDatabaseClient(), {- itemIds: items as string[],- field,- value,+ // The items tables' bulk actions and the item properties panels: one field of-// one or more items per post.++// one or more items per post. The tables' Update posts `allMatching` in++// place of the ids for every matching item.+ const updateForm = z.object({+ items: zfd.repeatableOfType(z.string()),+ field: z.enum([+ "itemTrackingType",+ "name",+ "description",+ "mpn",+ "unitOfMeasureCode",+ "replenishmentSystem",+ "defaultMethodType",+ "sourcingType",+ "gradeId",+ "dimensionId",+ "finishId",+ "materialFormId",+ "materialSubstanceId",+ "materialTypeId",+ "active",+ "itemPostingGroupId",+ "partId",+ "consumableId",+ "materialId",+ "toolId",+ "serviceName"+ ]),- value: z.string()++ value: z.string(),++ allMatching: zfd.text(z.string().optional())+ });++ const invalid = (message: string) => ({ data: null, error: { message } });++ const renumberType = {+ partId: "Part",+ consumableId: "Consumable",+ materialId: "Material",+ toolId: "Tool"+ } as const;++ export async function action(args: ActionFunctionArgs) {+ const input = await validator(updateForm).request(args);+ if ("invalid" in input) return input.invalid;- const { items: ids, field, value } = input.data;++ const { items: ids, field, value, allMatching } = input.data;++++ // Every matching row: the background job updates them 100 at a time++ // (bulkUpdateItems).++ if (allMatching && isItemBulkUpdateField(field)) {++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "parts"++ });++ const started = await startAllMatchingBulkAction(allMatching, {+ companyId,- userId++ userId,++ actionKey: "items.update",++ params: { field, value }+ });- return result.error- ? {- error: { message: result.error },- data: null,- done: result.done,- failed: result.failed- }- : { data: null, error: null };++ if (started) return bulkStartFormResponse(started);+ }++ const api = (await carbon(args.request)).items;+switch (field) {+ case "itemTrackingType":+ return api.setItemTrackingType({+ ids,+ itemTrackingType: value as (typeof itemTrackingTypes)[number]+ });case "name":case "description":case "mpn":diff --cc apps/erp/app/routes/x+/job+/$jobId.events.tsxindex e1888975fd,d3137878bc..1bf5109f92--- a/apps/erp/app/routes/x+/job+/$jobId.events.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.events.tsx@@@ -13,13 -12,10 +13,13 @@@ import { useLoaderData } from "react-roimport { usePanels } from "~/components/Layout";import {getJobOperationsList,- getProductionEvents+ getProductionEvents,+ PRODUCTION_EVENTS_PAGING- } from "~/modules/production";+ } from "~/modules/production/production.service";import { ProductionEventsTable } from "~/modules/production/ui/Jobs";- import { getWorkCentersList } from "~/modules/resources";+ import { getWorkCentersList } from "~/modules/resources/resources.service";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path, requestReferrer } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/job+/$jobId.operations.tsxindex 288dc804ad,3839450cb9..748032280f--- a/apps/erp/app/routes/x+/job+/$jobId.operations.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.operations.tsx@@@ -13,12 -12,9 +13,12 @@@ import { useLoaderData } from "react-roimport { usePanels } from "~/components/Layout";import {getJob,- getJobOperations+ getJobOperations,+ JOB_OPERATIONS_PAGING- } from "~/modules/production";+ } from "~/modules/production/production.service";import { JobOperationsTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/job+/$jobId.quantities.tsxindex 9882c6c585,9570f74bf3..edc43d3492--- a/apps/erp/app/routes/x+/job+/$jobId.quantities.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.quantities.tsx@@@ -14,12 -13,9 +14,12 @@@ import { usePanels } from "~/componentsimport {getJobOperationsList,getProductionQuantities,- getScrapReasons+ getScrapReasons,+ PRODUCTION_QUANTITIES_PAGING- } from "~/modules/production";+ } from "~/modules/production/production.service";import { ProductionQuantitiesTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path, requestReferrer } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/job+/$jobId.steps.tsxindex 6e5ca0ffb7,a0bde37e7d..535f78f0a3--- a/apps/erp/app/routes/x+/job+/$jobId.steps.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.steps.tsx@@@ -11,13 -10,8 +11,13 @@@ import { redirect } from "@carbon/utilsimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";-import { getJobOperationStepRecords } from "~/modules/production/production.service";+import {+ getJobOperationStepRecords,+ JOB_OPERATION_STEP_RECORDS_PAGING- } from "~/modules/production";++} from "~/modules/production/production.service";import { JobOperationStepRecordsTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/job+/release.tsxindex 51556b74b7,8a64eb4785..843cf1eecd--- a/apps/erp/app/routes/x+/job+/release.tsx+++ b/apps/erp/app/routes/x+/job+/release.tsx@@@ -2,70 -2,18 +2,60 @@@// 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 { assertIsPost } from "@carbon/auth";+ import { carbon } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { z } from "zod";- import { bulkReleaseJobs } from "~/modules/production/bulk-actions.server";- import { getDatabaseClient } from "~/services/database.server";- import { fitsOneRequest } from "~/utils/table-jobs";+ import { releaseJobs } from "~/modules/production/production.server";++import { bulkStartFormResponse, fitsOneRequest } from "~/utils/table-jobs";+import {+ startAllMatchingBulkAction,+ startSelectedBulkAction+} from "~/utils/table-jobs.server";- const bodySchema = z.object({ jobIds: z.array(z.string()) });-- // Bulk release — the jobs table's "Release Jobs" action. Each selected Draft /- // Planned job goes through the job page's release path (bulkReleaseJobs) on- // its own: a job that is not ready is reported in `failed` while the rest- // still release. A job in any other status (a stale selection) is skipped.+ // The jobs table's Release Jobs: no dialog, so a job with a choice to make is+ // refused and named rather than released with a guess.+// `{ allMatching: { listKey, search } }` in place of `jobIds` releases every+// matching job in the background job instead, up to 2,000 jobs. More than 25+// selected jobs also go to the background job: each runs MRP, and one request+// must end before the load balancer's 600 s.- // Fetcher-driven; the table toasts the summary and the loader revalidates.- export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- update: "production"- });-- // A body that is not JSON, or not the shape the table sends, is a plain- // refusal rather than a 500.- const json = await request.json().catch(() => null);- const started = await startAllMatchingBulkAction(json?.allMatching, {- companyId,- userId,- actionKey: "jobs.release",- params: {}- });- if (started) return started;+ const selection = releaseJobs.input.pick({ jobIds: true });- const body = bodySchema.safeParse(json);- if (!body.success) {- return { success: false as const, message: "Invalid request" };- }- const ids = [...new Set(body.data.jobIds.filter(Boolean))];- if (ids.length === 0) {- return { success: false as const, message: "No jobs selected" };- }- if (!fitsOneRequest("jobs.release", ids.length)) {- return startSelectedBulkAction({+ export async function action(args: ActionFunctionArgs) {++ const json = await args.request++ .clone()++ .json()++ .catch(() => null);++ if (json?.allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "production"++ });++ const started = await startAllMatchingBulkAction(json.allMatching, {+ companyId,+ userId,+ actionKey: "jobs.release",- params: {},- listKey: "jobs",- ids++ params: {}+ });++ if (started) return bulkStartFormResponse(started);+ }+- return bulkReleaseJobs({- client,- db: getDatabaseClient(),- jobIds: ids,- companyId,- userId- });+ const input = await validator(selection).request(args);+ if ("invalid" in input) return input.invalid;++ if (!fitsOneRequest("jobs.release", input.data.jobIds.length)) {++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "production"++ });++ return bulkStartFormResponse(++ await startSelectedBulkAction({++ companyId,++ userId,++ actionKey: "jobs.release",++ params: {},++ listKey: "jobs",++ ids: input.data.jobIds++ })++ );++ }+ const api = await carbon(args.request);+ return api.production.releaseJobs(input.data);}diff --cc apps/erp/app/routes/x+/job+/update.tsxindex 1378a60abb,7754156dfa..7313eb2b74--- a/apps/erp/app/routes/x+/job+/update.tsx+++ b/apps/erp/app/routes/x+/job+/update.tsx@@@ -2,364 -2,69 +2,91 @@@// 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 { carbon } from "@carbon/api/carbon.server";+ import { CarbonError, toResult } from "@carbon/api/service-fn.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { getCarbonServiceRole } from "@carbon/auth/client.server";- import { trigger } from "@carbon/jobs";- import { getLogger } from "@carbon/logger";- import { scrapAllowance, unchecked } from "@carbon/utils";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import {- calculateJobPriority,- isJobLocked,- makeToAssetItemError,- recalculateJobRequirements,- upsertJobMethod- } from "~/modules/production";- import { bulkDeleteJobs } from "~/modules/production/bulk-actions.server";- import { isSalesOrderClosed } from "~/modules/sales";- import { getDatabaseClient } from "~/services/database.server";- import { requireUnlockedBulk } from "~/utils/lockedGuard.server";+ import { z } from "zod";+ import { zfd } from "zod-form-data";+ import type { deadlineTypes } from "~/modules/production/production.models";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";- const logger = getLogger("erp", "update");-- export async function action({ request }: ActionFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- update: "production"- });-- const formData = await request.formData();- const ids = formData.getAll("ids");- const field = formData.get("field");- const value = formData.get("value");-- if (typeof field !== "string") {- return { error: { message: "Invalid form data" }, data: null };- }-- // The jobs table's bulk Delete. It deletes Draft, Planned, Due Today and- // Overdue jobs only (bulkDeleteJobs skips the rest), and needs the delete- // permission as well as update.- if (field === "delete") {- await requirePermissions(request, {+ // The jobs table's bulk actions and the job properties panel: one field of-// one or more jobs per post.++// one or more jobs per post. The table's Delete posts `allMatching` in place++// of the ids for every matching job.+ const updateForm = z.object({+ ids: zfd.repeatableOfType(z.string()),+ field: z.enum([+ "delete",+ "itemId",+ "deadlineType",+ "dueDate",+ "quantity",+ "scrapQuantity",+ "salesOrderId",+ "salesOrderLineId",+ "customerId",+ "jobId",+ "locationId",+ "storageUnitId",+ "startDate",+ "unitOfMeasureCode"+ ]),- value: zfd.text(z.string().optional())++ value: zfd.text(z.string().optional()),++ allMatching: zfd.text(z.string().optional())+ });++ const invalid = (message: string) =>+ toResult({ data: null, error: new CarbonError("validation", message) });++ export async function action(args: ActionFunctionArgs) {+ const input = await validator(updateForm).request(args);+ if ("invalid" in input) return input.invalid;- const { ids, field, value } = input.data;++ const { ids, field, value, allMatching } = input.data;++++ // Every matching row: the background job deletes the Draft, Planned, Due++ // Today and Overdue jobs (bulkDeleteJobs) and skips the rest.++ if (field === "delete" && allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {+ update: "production",+ delete: "production"+ });- const started = await startAllMatchingBulkAction(- formData.get("allMatching"),- { companyId, userId, actionKey: "jobs.delete", params: {} }- );- if (started) return bulkStartFormResponse(started);-- const result = await bulkDeleteJobs({- client,- jobIds: ids as string[],- companyId++ const started = await startAllMatchingBulkAction(allMatching, {++ companyId,++ userId,++ actionKey: "jobs.delete",++ params: {}+ });- return result.error- ? { error: { message: result.error }, data: null }- : { data: null, error: null };++ if (started) return bulkStartFormResponse(started);+ }+- // Per-ID locked check- const jobs = await client- .from("job")- .select("id, status, quantity, fixedAssetClassId, fixedAssetId")- .in("id", ids as string[])- .eq("companyId", companyId);-- const lockedError = requireUnlockedBulk({- statuses: (jobs.data ?? []).map((j) => j.status),- checkFn: isJobLocked,- message: "Cannot modify a locked job. Reopen it first."- });- if (lockedError) return lockedError;-- const serviceRole = await getCarbonServiceRole();-- if (typeof value !== "string" && value !== null) {- return { error: { message: "Invalid form data" }, data: null };- }+ const job = (await carbon(args.request)).production;switch (field) {+ case "delete":+ return job.deleteJobs({ ids });case "itemId":- if (!value) {- return { error: { message: "Invalid form data" }, data: null };- }-- const [item, manufacturing] = await Promise.all([- client- .from("item")- .select(- "name, readableIdWithRevision, defaultMethodType, unitOfMeasureCode, modelUploadId, itemTrackingType"- )- .eq("id", value)- .eq("companyId", companyId)- .single(),- client- .from("itemReplenishment")- .select("lotSize, scrapPercentage")- .eq("itemId", value)- .single()- ]);-- // A Make to Asset job keeps the item rule its form and release apply.- const lotSize = manufacturing?.data?.lotSize ?? 0;- for (const job of jobs.data ?? []) {- const itemError = makeToAssetItemError({- ...job,- itemTrackingType: item.data?.itemTrackingType,- quantity: lotSize === 0 ? job.quantity : lotSize- });- if (itemError) {- return { error: { message: itemError }, data: null };- }- }-- const [itemUpdate, makeMethodUpdate] = await Promise.all([- client- .from("job")- .update({- itemId: value,- unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",- quantity:- (manufacturing?.data?.lotSize ?? 0) === 0- ? undefined- : (manufacturing?.data?.lotSize ?? 0),- modelUploadId: item.data?.modelUploadId ?? null,- scrapQuantity: scrapAllowance(- manufacturing?.data?.lotSize ?? 0,- manufacturing?.data?.scrapPercentage ?? 0- ),- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[])- .eq("companyId", companyId),-- client- .from("jobMakeMethod")- .update({- itemId: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("jobId", ids as string[])- .is("parentMaterialId", null)- .eq("companyId", companyId)- ]);-- if (itemUpdate.error) {- return itemUpdate;- }-- if (makeMethodUpdate.error) {- return makeMethodUpdate;- }-- for await (const id of ids) {- const upsertMethod = await upsertJobMethod(- serviceRole,- getDatabaseClient(),- "itemToJob",- {- sourceId: value,- targetId: id as string,- companyId,- userId- }- );-- if (upsertMethod.error) {- upsertMethod.error;- }-- await trigger("recalculate", {- type: "jobRequirements",- id: id as string,- companyId,- userId- });- }-- return itemUpdate;- case "deadlineType":+ if (!value) return invalid("Invalid form data");+ return job.setJobItem({ ids, itemId: value });case "dueDate":- // When dueDate or deadlineType changes, recalculate priority- for await (const id of ids) {- // Get the current job to access its data- const currentJob = await client- .from("job")- .select("dueDate, deadlineType, locationId")- .eq("id", id as string)- .eq("companyId", companyId)- .single();-- if (currentJob.error || !currentJob.data) {- return currentJob;- }-- // Determine the new dueDate and deadlineType after this update- const newDueDate =- field === "dueDate" ? (value ?? null) : currentJob.data.dueDate;- const newDeadlineType =- field === "deadlineType" ? value : currentJob.data.deadlineType;-- if (!newDeadlineType) {- return {- error: { message: "Invalid deadline type" },- data: null- };- }-- // Calculate new priority- const priority = await calculateJobPriority(client, {- jobId: id as string,- dueDate: newDueDate,- deadlineType: newDeadlineType as- | "ASAP"- | "Hard Deadline"- | "Soft Deadline"- | "No Deadline",- companyId,- locationId: currentJob.data.locationId- });-- // Update the job with new field value and priority- const updateResult = await client- .from("job")- .update(- unchecked({- [field]: value ? value : null,- priority,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .eq("id", id as string)- .eq("companyId", companyId);-- if (updateResult.error) {- return updateResult;- }- }-- return { error: null, data: null };- case "customerId":- case "jobId":- case "locationId":- case "storageUnitId":- case "startDate":- case "unitOfMeasureCode":- return await client- .from("job")- .update(- unchecked({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .in("id", ids as string[])- .eq("companyId", companyId);+ return job.setJobDeadline({ ids, dueDate: value ?? null });+ case "deadlineType":+ return job.setJobDeadline({+ ids,+ deadlineType: value as (typeof deadlineTypes)[number]+ });case "quantity":case "scrapQuantity":- const quantityUpdate = await client- .from("job")- .update(- unchecked({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .in("id", ids as string[])- .eq("companyId", companyId);-- if (quantityUpdate.error) {- return quantityUpdate;- }-- for await (const id of ids) {- const recalculate = await recalculateJobRequirements(- serviceRole,- getDatabaseClient(),- {- id: id as string,- companyId,- userId- }- );- if (recalculate.error) {- logger.error(recalculate.error);- return recalculate;- }- }-- return quantityUpdate;+ return job.setJobQuantity({ ids, [field]: Number(value) });case "salesOrderId":+ // Linking goes through the line; the order alone can only be cleared.+ if (value) return invalid(`Invalid value: ${value} for field: ${field}`);+ return job.setJobSalesOrderLine({ ids, salesOrderLineId: null });case "salesOrderLineId":- if (!value) {- // Unlink: clear the sales order + line (customerId is left as-is).- return await client- .from("job")- .update({- salesOrderId: null,- salesOrderLineId: null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[])- .eq("companyId", companyId);- }-- // Linking is done via the line — resolve its order + customer from it.- if (field !== "salesOrderLineId") {- return {- error: { message: `Invalid value: ${value} for field: ${field}` },- data: null- };- }-- const salesOrderLine = await client- .from("salesOrderLine")- .select("id, salesOrderId, salesOrder(customerId, status)")- .eq("id", value)- .eq("companyId", companyId)- .single();-- if (salesOrderLine.error || !salesOrderLine.data) {- return {- error: { message: "Sales order line not found" },- data: null- };- }-- if (isSalesOrderClosed(salesOrderLine.data.salesOrder?.status)) {- return {- error: {- message: "Cannot link a job to a completed or cancelled sales order"- },- data: null- };- }-- return await client- .from("job")- .update({- salesOrderId: salesOrderLine.data.salesOrderId,- salesOrderLineId: salesOrderLine.data.id,- customerId: salesOrderLine.data.salesOrder?.customerId ?? null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[])- .eq("companyId", companyId);+ return job.setJobSalesOrderLine({ ids, salesOrderLineId: value ?? null });default:- return {- error: { message: `Invalid field: ${field}` },- data: null- };+ return job.setJobFields({ ids, [field]: value ?? null });}}diff --cc apps/erp/app/routes/x+/people+/attributes.tsxindex b0f68126c5,2e138f9d47..929cb67501--- a/apps/erp/app/routes/x+/people+/attributes.tsx+++ b/apps/erp/app/routes/x+/people+/attributes.tsx@@@ -6,12 -9,15 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAttributeDataTypes } from "~/modules/people";-import {- getAttributeCategories,- getAttributeDataTypes-} from "~/modules/people/people.service";++import { getAttributeDataTypes } from "~/modules/people/people.service";import { AttributeCategoriesTable } from "~/modules/people/ui/Attributes";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { attributeCategoriesList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Attributes`,diff --cc apps/erp/app/routes/x+/people+/employee.tsxindex c4cc71deb4,15e5764438..b94f94df34--- a/apps/erp/app/routes/x+/people+/employee.tsx+++ b/apps/erp/app/routes/x+/people+/employee.tsx@@@ -8,55 -9,69 +8,58 @@@ import { RecordOutlet, VStack } from "@import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAttributeCategories, getShiftsList } from "~/modules/people";+ import {+ getAttributeCategories,- getPeople,+ getShiftsList+ } from "~/modules/people/people.service";import { PeopleTable } from "~/modules/people/ui/People";- import { getEmployeeTypes } from "~/modules/users";+ import { getEmployeeTypes } from "~/modules/users/users.service";+import { loadListPage } from "~/utils/list-registry/load.server";+import { peopleList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people",- role: "employee",- bypassRls: true+ return loadListPage(request, peopleList, {+ dataKey: "people",+ bypassRls: true,+ firstPage: async ({ client, companyId, request }) => {+ const [attributeCategories, employeeTypes, shifts] = await Promise.all([+ getAttributeCategories(client, companyId),+ getEmployeeTypes(client, companyId),+ getShiftsList(client, companyId, null)+ ]);+ if (attributeCategories.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(+ request,+ error(+ attributeCategories.error,+ "Error loading attribute categories"+ )+ )+ );+ }+ if (employeeTypes.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(+ request,+ error(employeeTypes.error, "Error loading employee types")+ )+ );+ }+ return {+ attributeCategories: attributeCategories.data ?? [],+ employeeTypes: employeeTypes.data ?? [],+ shifts: shifts.data ?? []+ };+ },+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading people"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("name");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [attributeCategories, employeeTypes, people, shifts] =- await Promise.all([- getAttributeCategories(client, companyId),- getEmployeeTypes(client, companyId),- getPeople(client, companyId, { search, limit, offset, sorts, filters }),- getShiftsList(client, companyId, null)- ]);- if (attributeCategories.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(attributeCategories.error, "Error loading attribute categories")- )- );- }- if (employeeTypes.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(employeeTypes.error, "Error loading employee types")- )- );- }- if (people.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(people.error, "Error loading people"))- );- }-- return {- attributeCategories: attributeCategories.data,- employeeTypes: employeeTypes.data ?? [],- people: people.data ?? [],- shifts: shifts.data ?? [],- count: people.count ?? 0- };}export default function ResourcesPeopleRoute() {diff --cc apps/erp/app/routes/x+/people+/holidays.tsxindex 8dd266d076,e3311e4474..7ef15f3ac3--- a/apps/erp/app/routes/x+/people+/holidays.tsx+++ b/apps/erp/app/routes/x+/people+/holidays.tsx@@@ -6,12 -9,12 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getHolidayYears } from "~/modules/people";-import { getHolidays, getHolidayYears } from "~/modules/people/people.service";++import { getHolidayYears } from "~/modules/people/people.service";import { HolidaysTable } from "~/modules/people/ui/Holidays";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { holidaysList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Holidays`,diff --cc apps/erp/app/routes/x+/people+/timecard.tsxindex c43a3aa0f6,22889d171c..60dd1a63c5--- a/apps/erp/app/routes/x+/people+/timecard.tsx+++ b/apps/erp/app/routes/x+/people+/timecard.tsx@@@ -9,12 -10,12 +9,12 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTimecardEntries } from "~/modules/people/people.service";import { TimecardsTable } from "~/modules/people/ui/Timecards";- import { getCompanySettings } from "~/modules/settings";+ import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { timecardEntriesList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Timecards`,diff --cc apps/erp/app/routes/x+/production+/batches.dissolve.tsxindex c9c82c50b2,5dda76deb3..e40ba07fdf--- a/apps/erp/app/routes/x+/production+/batches.dissolve.tsx+++ b/apps/erp/app/routes/x+/production+/batches.dissolve.tsx@@@ -4,59 -4,55 +4,54 @@@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getErrorMessage } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";- import { bulkDissolveBatches } from "~/modules/production/bulk-actions.server";-import { updateJobOperationBatch } from "~/modules/production/production.service";--import { getDatabaseClient } from "~/services/database.server";++import { serviceContext } from "~/modules/service-context.server";++import { bulkDissolveBatches } from "~/utils/production-bulk-actions.server";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";-// Bulk dissolve — one server-fn dissolve per selected batch. Each is independent:-// a batch that has recorded production is refused (the server fn's own guard) and-// reported in `failed` while the rest still dissolve. Fetcher-driven; the table-// toasts the summary and the loader revalidates.+// Bulk dissolve — one server-fn dissolve per selected Planned or Active batch.+// Each is independent: a batch that has recorded production is refused (the+// server fn's own guard) and reported in `failed` while the rest still+// dissolve; a Completing or Completed batch is skipped. `{ allMatching }` in+// place of `batchIds` dissolves every matching batch in the background job+// instead. Fetcher-driven; the table toasts the summary and the loader+// revalidates.export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);-- const { client, companyId, userId } = await requirePermissions(request, {-- update: "production"- });++ const auth = await requirePermissions(request, { update: "production" });++ const { companyId, userId } = auth;++ const json = (await request.json().catch(() => null)) as {+ batchIds?: string[];+ allMatching?: unknown;+ } | null;+ const started = await startAllMatchingBulkAction(json?.allMatching, {+ companyId,+ userId,+ actionKey: "batches.dissolve",+ params: {}});+ if (started) return started;- const { batchIds } = (await request.json()) as { batchIds?: string[] };- const ids = [...new Set((batchIds ?? []).filter(Boolean))];+ const ids = [+ ...new Set(+ (Array.isArray(json?.batchIds) ? json.batchIds : []).filter(+ (id): id is string => typeof id === "string" && id.length > 0+ )+ )+ ];if (ids.length === 0) {return { success: false, message: "No batches selected" };}- const result = await bulkDissolveBatches({- client,- db: getDatabaseClient(),- batchIds: ids,- companyId,- userId- // Resolve readable ids up front so failures name the batch, not its nanoid.- const rows = await client- .from("jobOperationBatch")- .select("id, readableId")- .in("id", ids)- .eq("companyId", companyId);- const readableById = new Map(- (rows.data ?? []).map((r) => [r.id, r.readableId] as const)- );-- let dissolved = 0;- const failed: { readableId: string; message: string }[] = [];- for (const batchId of ids) {- const result = await updateJobOperationBatch(client, getDatabaseClient(), {- type: "dissolve",- batchId,- companyId,- userId- });- if (result.error) {- failed.push({- readableId: readableById.get(batchId) ?? batchId,- message: getErrorMessage(result.error, "Failed to dissolve")- });- } else {- dissolved += 1;- }- }-- return { success: true, dissolved, failed };++ const result = await bulkDissolveBatches(serviceContext(auth), {++ batchIds: ids+ });+ if (!result.success) return result;+ return {+ success: true,+ dissolved: result.done,+ failed: result.failed,+ skipped: result.skipped+ };}diff --cc apps/erp/app/routes/x+/production+/batches.release.tsxindex d192bb299a,be1c1767db..656db9db7f--- a/apps/erp/app/routes/x+/production+/batches.release.tsx+++ b/apps/erp/app/routes/x+/production+/batches.release.tsx@@@ -2,78 -2,18 +2,60 @@@// 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 { assertIsPost } from "@carbon/auth";+ import { carbon } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { z } from "zod";- import { bulkReleaseBatches } from "~/modules/production/bulk-actions.server";- import { getDatabaseClient } from "~/services/database.server";- import { fitsOneRequest } from "~/utils/table-jobs";+ import { releaseBatches } from "~/modules/production/production.server";++import { bulkStartFormResponse, fitsOneRequest } from "~/utils/table-jobs";+import {+ startAllMatchingBulkAction,+ startSelectedBulkAction+} from "~/utils/table-jobs.server";- // Bulk release — one release per selected Planned batch. Each is independent:- // a batch the server fn refuses (no members, already recorded production) is- // reported in `failed` while the rest still release. Only Planned batches are- // released — the caller filters, and bulkReleaseBatches skips any other status- // too, so a stale selection can't flip an Active/Completing batch.+ // The batches table's bulk Release: no dialog, so a batch with a purchase+ // order choice to make is refused and named.+// `{ allMatching: { listKey, search } }` in place of `batchIds` releases every+// matching batch in the background job instead, up to 2,000 batches. More+// than 10 selected batches also go to the background job: each releases its+// member jobs with MRP, and one request must end before the 600 s cutoff.- // Fetcher-driven; the table toasts the summary and the loader revalidates.- const bodySchema = z.object({ batchIds: z.array(z.string()) });+ const selection = releaseBatches.input.pick({ batchIds: true });- export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- update: "production"- });-- // A body that is not JSON, or not the shape the table sends, is a plain- // refusal rather than a 500.- const json = await request.json().catch(() => null);- const started = await startAllMatchingBulkAction(json?.allMatching, {- companyId,- userId,- actionKey: "batches.release",- params: {}- });- if (started) return started;-- const body = bodySchema.safeParse(json);- if (!body.success) {- return { success: false, message: "Invalid request" };- }- const ids = [...new Set(body.data.batchIds.filter(Boolean))];- if (ids.length === 0) {- return { success: false, message: "No batches selected" };- }- if (!fitsOneRequest("batches.release", ids.length)) {- return startSelectedBulkAction({+ export async function action(args: ActionFunctionArgs) {++ const json = await args.request++ .clone()++ .json()++ .catch(() => null);++ if (json?.allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "production"++ });++ const started = await startAllMatchingBulkAction(json.allMatching, {+ companyId,+ userId,+ actionKey: "batches.release",- params: {},- listKey: "operation-batches",- ids++ params: {}+ });++ if (started) return bulkStartFormResponse(started);+ }+- const result = await bulkReleaseBatches({- client,- db: getDatabaseClient(),- batchIds: ids,- companyId,- userId- });- if (!result.success) return result;- return {- success: true,- released: result.done,- failed: result.failed,- skipped: result.skipped- };+ const input = await validator(selection).request(args);+ if ("invalid" in input) return input.invalid;++ if (!fitsOneRequest("batches.release", input.data.batchIds.length)) {++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "production"++ });++ return bulkStartFormResponse(++ await startSelectedBulkAction({++ companyId,++ userId,++ actionKey: "batches.release",++ params: {},++ listKey: "operation-batches",++ ids: input.data.batchIds++ })++ );++ }+ const api = await carbon(args.request);+ return api.production.releaseBatches(input.data);}diff --cc apps/erp/app/routes/x+/production+/batches.tsxindex 4f8f2d6514,0513a0ea4c..8dcc9c9c81--- a/apps/erp/app/routes/x+/production+/batches.tsx+++ b/apps/erp/app/routes/x+/production+/batches.tsx@@@ -9,17 -8,14 +9,17 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {- getJobOperationBatches,getJobOperationBatchMemberStats,getJobOperationBatchMembers- } from "~/modules/production";+ } from "~/modules/production/production.service";import BatchesTable from "~/modules/production/ui/Batches/BatchesTable";import type { Handle } from "~/utils/handle";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { operationBatchesList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "batches");export const handle: Handle = {breadcrumb: msg`Batches`,diff --cc apps/erp/app/routes/x+/production+/demand-forecasts.tsxindex 7f263d0b56,f47db22e57..8c7f7dd93a--- a/apps/erp/app/routes/x+/production+/demand-forecasts.tsx+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.tsx@@@ -13,18 -12,16 +13,21 @@@ import { Trans } from "@lingui/react/maimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import { getProductionProjections } from "~/modules/production/production.service";+import {+ getProductionProjections,+ PRODUCTION_PROJECTIONS_PAGING- } from "~/modules/production";++} from "~/modules/production/production.service";import DemandProjectionsTable from "~/modules/production/ui/DemandProjection/DemandProjectionTable";import ForecastUpgradeOverlay from "~/modules/production/ui/ForecastUpgradeOverlay";- import { resolveLocationId } from "~/modules/shared/location.server";- import { getOrCreatePeriods } from "~/modules/shared/shared.server";- import { getLocationTimeZone } from "~/modules/shared/timezone.server";+ import {+ getLocationTimeZone,+ getOrCreatePeriods,+ resolveLocationId+ } from "~/modules/shared/shared.service";+ import { getDatabaseClient } from "~/services/database.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/production+/jobs.tsxindex 148924ac41,bbfd745970..4454c290b2--- a/apps/erp/app/routes/x+/production+/jobs.tsx+++ b/apps/erp/app/routes/x+/production+/jobs.tsx@@@ -6,16 -9,14 +6,16 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getJobs } from "~/modules/production/production.service";import { JobsTable } from "~/modules/production/ui/Jobs";- import { getLocationsList } from "~/modules/resources";- import { getTagsList } from "~/modules/shared";+ import { getLocationsList } from "~/modules/resources/resources.service";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import {+ jobsList,+ withJobListExtras+} from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["job"],diff --cc apps/erp/app/routes/x+/production+/machine-time.tsxindex 29f3af5226,ccc4ee56d4..e8658394ed--- a/apps/erp/app/routes/x+/production+/machine-time.tsx+++ b/apps/erp/app/routes/x+/production+/machine-time.tsx@@@ -12,17 -11,15 +12,20 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import { getUnattributedMachineTimes } from "~/modules/production/production.service";+import {+ getUnattributedMachineTimes,+ UNATTRIBUTED_MACHINE_TIMES_PAGING- } from "~/modules/production";++} from "~/modules/production/production.service";import MachineTimeTable from "~/modules/production/ui/MachineTime/MachineTimeTable.ee";import MachineTimeUpgradeOverlay from "~/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee";import { parseMachineTimeListFilters } from "~/modules/production/ui/MachineTime/machine-time-filters.ee";- import { getLocationsList, getWorkCentersList } from "~/modules/resources";+ import {+ getLocationsList,+ getWorkCentersList+ } from "~/modules/resources/resources.service";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/production+/planning.tsxindex ca6bc5f1c4,e292cdfbb0..5786191111--- a/apps/erp/app/routes/x+/production+/planning.tsx+++ b/apps/erp/app/routes/x+/production+/planning.tsx@@@ -16,22 -16,23 +16,27 @@@ import { datetime, redirect } from "@caimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import type { ProductionPlanningItem } from "~/modules/production";+ import {+ PLANNING_DRAWER_PARAM,+ resolvePlanningActionScope+ } from "~/modules/production/production.models";import {getPlanningActions,- getProductionPlanning+ getProductionPlanning,- PLANNING_DRAWER_PARAM,- PRODUCTION_PLANNING_PAGING,- resolvePlanningActionScope,- withPlanningActions- } from "~/modules/production";++ PRODUCTION_PLANNING_PAGING+ } from "~/modules/production/production.service";+ import type { ProductionPlanningItem } from "~/modules/production/types";import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";- import { resolveLocationId } from "~/modules/shared/location.server";- import { getOrCreatePeriods } from "~/modules/shared/shared.server";- import { getLocationTimeZone } from "~/modules/shared/timezone.server";++import { withPlanningActions } from "~/modules/production/ui/Planning/planning-action-scope";+ import {+ getLocationTimeZone,+ getOrCreatePeriods,+ resolveLocationId+ } from "~/modules/shared/shared.service";+ import { getDatabaseClient } from "~/services/database.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/list-error";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/production+/procedures.tsxindex 840a6324d7,7d0f7906ed..221dda5809--- a/apps/erp/app/routes/x+/production+/procedures.tsx+++ b/apps/erp/app/routes/x+/production+/procedures.tsx@@@ -6,12 -7,12 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getProcedures } from "~/modules/production/production.service";import ProceduresTable from "~/modules/production/ui/Procedures/ProceduresTable";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { proceduresList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Procedures`,diff --cc apps/erp/app/routes/x+/purchase-order+/update.tsxindex 1dd34500d7,cef254dfb2..fdbd8dbe78--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx@@@ -2,179 -2,27 +2,49 @@@// 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 { carbon } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { unchecked } from "@carbon/utils";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { getExchangeRate } from "~/modules/accounting";- import { isPurchaseOrderLocked } from "~/modules/purchasing";- import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.server";- import { requireUnlockedBulk } from "~/utils/lockedGuard.server";+ import { z } from "zod";+ import { zfd } from "zod-form-data";+ import { updatePurchaseOrders } from "~/modules/purchasing/purchasing.server";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";- export async function action({ request }: ActionFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- update: "purchasing"- });-- const formData = await request.formData();- const ids = formData.getAll("ids");- const field = formData.get("field");- const value = formData.get("value");-- if (typeof field !== "string") {- return { error: { message: "Invalid form data" }, data: null };- }-- // The purchase orders table's bulk Delete. It deletes the company's Draft- // and Planned orders only (bulkDeletePurchaseOrders skips the rest), and- // needs the delete permission as well as update, as the table does.- if (field === "delete") {- await requirePermissions(request, {+ // The properties panel posts one field (`ids`, `field`, `value`); the orders-// table posts `field=delete` for the selected rows.++// table posts `field=delete` for the selected rows, or `allMatching` in place++// of the ids for every matching row.+ const form = z.object({+ ids: zfd.repeatableOfType(z.string()),+ field: z.union([z.literal("delete"), updatePurchaseOrders.input.shape.field]),- value: z.string().optional()++ value: z.string().optional(),++ allMatching: zfd.text(z.string().optional())+ });++ export async function action(args: ActionFunctionArgs) {+ const input = await validator(form).request(args);+ if ("invalid" in input) return input.invalid;- const { ids, field, value } = input.data;++ const { ids, field, value, allMatching } = input.data;++++ // Every matching row: the background job deletes the Draft and Planned++ // orders (bulkDeletePurchaseOrders) and skips the rest.++ if (field === "delete" && allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {+ update: "purchasing",+ delete: "purchasing"+ });- const started = await startAllMatchingBulkAction(- formData.get("allMatching"),- { companyId, userId, actionKey: "purchase-orders.delete", params: {} }- );- if (started) return bulkStartFormResponse(started);-- const result = await bulkDeletePurchaseOrders(client, {- purchaseOrderIds: ids as string[],- companyId- });- return result.error- ? { error: { message: result.error }, data: null }- : { data: null, error: null };- }-- // Check if any of the POs are locked except for deliveryDate- if (field !== "deliveryDate") {- const purchaseOrders = await client- .from("purchaseOrder")- .select("status")- .in("id", ids as string[]);- const lockedError = requireUnlockedBulk({- statuses: (purchaseOrders.data ?? []).map((d) => d.status),- checkFn: isPurchaseOrderLocked,- message: "Cannot modify a confirmed purchase order."++ const started = await startAllMatchingBulkAction(allMatching, {++ companyId,++ userId,++ actionKey: "purchase-orders.delete",++ params: {}+ });- if (lockedError) {- return lockedError;- }- }-- if (typeof value !== "string" && value !== null) {- return { error: { message: "Invalid form data" }, data: null };++ if (started) return bulkStartFormResponse(started);+ }+- switch (field) {- case "supplierId":- let currencyCode: string | undefined;- if (value && ids.length === 1) {- const supplier = await client- ?.from("supplier")- .select("currencyCode")- .eq("id", value)- .single();-- if (supplier.data?.currencyCode) {- currencyCode = supplier.data.currencyCode;- const rate = await getExchangeRate(client, companyId, currencyCode);- if (rate.error) {- return { error: rate.error, data: null };- }- return await client- .from("purchaseOrder")- .update({- supplierId: value ?? undefined,- currencyCode: currencyCode ?? undefined,- exchangeRate: rate.data,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }- }-- return await client- .from("purchaseOrder")- .update({- supplierId: value ?? undefined,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- case "receiptRequestedDate":- case "locationId":- case "deliveryDate":- return await client- .from("purchaseOrderDelivery")- .update(- unchecked({- [field]: value ?? undefined,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .in("id", ids as string[]);- case "receiptPromisedDate":- const lineUpdates = await client- .from("purchaseOrderLine")- .update({- promisedDate: value ?? undefined,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("purchaseOrderId", ids as string[])- .is("promisedDate", null);-- if (lineUpdates.error) {- return lineUpdates;- }-- return await client- .from("purchaseOrderDelivery")- .update({- [field]: value ?? undefined,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- case "currencyCode":- if (value) {- const rate = await getExchangeRate(client, companyId, value as string);- if (rate.error) {- return { error: rate.error, data: null };- }- return await client- .from("purchaseOrder")- .update({- currencyCode: value as string,- exchangeRate: rate.data,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }- // don't break -- just let it catch the next case- case "supplierContactId":- case "supplierLocationId":- case "supplierReference":- case "exchangeRate":- case "orderDate":- return await client- .from("purchaseOrder")- .update(- unchecked({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .in("id", ids as string[]);- default:- return { error: { message: "Invalid field" }, data: null };- }+ const api = await carbon(args.request);+ return field === "delete"+ ? api.purchasing.deletePurchaseOrders({ purchaseOrderIds: ids })+ : api.purchasing.updatePurchaseOrders({ ids, field, value: value || null });}diff --cc apps/erp/app/routes/x+/purchasing+/planning.tsxindex 1408900fc3,1bc6578be9..22abad2d0f--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx@@@ -17,23 -17,20 +17,26 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {- getPlanningActions,PLANNING_DRAWER_PARAM,- resolvePlanningActionScope,- withPlanningActions- } from "~/modules/production";- import type { PurchasingPlanningItem } from "~/modules/purchasing";+ resolvePlanningActionScope+ } from "~/modules/production/production.models";+ import { getPlanningActions } from "~/modules/production/production.service";-import { getPurchasingPlanning } from "~/modules/purchasing/purchasing.service";++import { withPlanningActions } from "~/modules/production/ui/Planning/planning-action-scope";+import {+ getPurchasingPlanning,+ PURCHASING_PLANNING_PAGING- } from "~/modules/purchasing";++} from "~/modules/purchasing/purchasing.service";+ import type { PurchasingPlanningItem } from "~/modules/purchasing/types";import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";- import { resolveLocationId } from "~/modules/shared/location.server";- import { getOrCreatePeriods } from "~/modules/shared/shared.server";- import { getLocationTimeZone } from "~/modules/shared/timezone.server";+ import {+ getLocationTimeZone,+ getOrCreatePeriods,+ resolveLocationId+ } from "~/modules/shared/shared.service";+ import { getDatabaseClient } from "~/services/database.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/list-error";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/purchasing+/suppliers.tsxindex 4bde12eb0f,b56142afde..95c911fa37--- a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx+++ b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx@@@ -6,15 -9,17 +6,15 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getSupplierReportContacts,- getSuppliers-} from "~/modules/purchasing/purchasing.service";-import type { SupplierReportContactsBySupplierId } from "~/modules/purchasing/types";import { SuppliersTable } from "~/modules/purchasing/ui/Supplier";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import {+ suppliersList,+ withSupplierReportContacts+} from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["supplier"],diff --cc apps/erp/app/routes/x+/quality+/actions.tsxindex 2cfd77c546,51ed947b91..1a7e5ca0cf--- a/apps/erp/app/routes/x+/quality+/actions.tsx+++ b/apps/erp/app/routes/x+/quality+/actions.tsx@@@ -6,12 -8,17 +6,15 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getIssueTypesList, getRequiredActionsList } from "~/modules/quality";+ import {+ getIssueTypesList,- getQualityActions,+ getRequiredActionsList+ } from "~/modules/quality/quality.service";import ActionsTable from "~/modules/quality/ui/Actions/ActionsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { qualityActionsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "actions");export const handle: Handle = {breadcrumb: msg`Actions`,diff --cc apps/erp/app/routes/x+/quality+/calibrations.tsxindex 9a917a0550,4834ab1573..47a1888e96--- a/apps/erp/app/routes/x+/quality+/calibrations.tsx+++ b/apps/erp/app/routes/x+/quality+/calibrations.tsx@@@ -6,13 -7,15 +6,13 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getGaugeTypesList } from "~/modules/quality";-import {- getGaugeCalibrationRecords,- getGaugeTypesList-} from "~/modules/quality/quality.service";++import { getGaugeTypesList } from "~/modules/quality/quality.service";import GaugeCalibrationRecordsTable from "~/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable";- import { getCompanySettings } from "~/modules/settings";+ import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { gaugeCalibrationRecordsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Calibrations`,diff --cc apps/erp/app/routes/x+/quality+/documents.tsxindex ea07a8f432,b82e6c4aa7..56db00900b--- a/apps/erp/app/routes/x+/quality+/documents.tsx+++ b/apps/erp/app/routes/x+/quality+/documents.tsx@@@ -6,12 -7,12 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getQualityDocuments } from "~/modules/quality/quality.service";import QualityDocumentsTable from "~/modules/quality/ui/Documents/QualityDocumentsTable";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { qualityDocumentsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Quality Documents`,diff --cc apps/erp/app/routes/x+/quality+/gauges.tsxindex 30ca9ba6e5,18b97416f3..f29080f839--- a/apps/erp/app/routes/x+/quality+/gauges.tsx+++ b/apps/erp/app/routes/x+/quality+/gauges.tsx@@@ -6,12 -7,14 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getGaugeTypesList } from "~/modules/quality";-import {- getGauges,- getGaugeTypesList-} from "~/modules/quality/quality.service";++import { getGaugeTypesList } from "~/modules/quality/quality.service";import GaugesTable from "~/modules/quality/ui/Gauge/GaugesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { gaugesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Gauges`,diff --cc apps/erp/app/routes/x+/quality+/issues.tsxindex 43a9688a6b,299e2e0f60..091a1e26d3--- a/apps/erp/app/routes/x+/quality+/issues.tsx+++ b/apps/erp/app/routes/x+/quality+/issues.tsx@@@ -6,12 -10,17 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getIssueTypesList } from "~/modules/quality";-import {- getIssues,- getIssueTypesList-} from "~/modules/quality/quality.service";++import { getIssueTypesList } from "~/modules/quality/quality.service";import IssuesTable from "~/modules/quality/ui/Issue/IssuesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { issuesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "issues");export const handle: Handle = {realtime: ["nonConformance"],diff --cc apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsxindex dedd039ab4,83af16d288..222daf5d2e--- a/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx@@@ -8,8 -8,12 +8,10 @@@ import { flash } from "@carbon/auth/sesimport { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAccount } from "~/modules/accounting";- import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";+ import {+ getAccount,- getAccountLedger,- getAccountLedgerSummary,- getConsolidatedAccountLedger++ getAccountLedgerPage+ } from "~/modules/accounting/accounting.service";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";diff --cc apps/erp/app/routes/x+/reports+/balance-sheet.tsxindex 7ce4158b5d,3dc7917cd5..ad7ee9107e--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx@@@ -33,11 -31,11 +31,11 @@@ importMultiPeriodStatementTree,ReportFilters} from "~/modules/accounting/ui/Reports";- import { months } from "~/modules/shared";- import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+ import { months } from "~/modules/shared/shared.models";+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Balance Sheet`,diff --cc apps/erp/app/routes/x+/reports+/executive-pnl.tsxindex 581b7c7e67,9fdbf82183..b03260d0f6--- a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx+++ b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx@@@ -31,11 -31,11 +31,11 @@@ importgetPeriodColumnLabel,ReportFilters} from "~/modules/accounting/ui/Reports";- import { months } from "~/modules/shared";- import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+ import { months } from "~/modules/shared/shared.models";+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Executive P&L`,diff --cc apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsxindex 150a46e894,12848c1c68..6560a5f385--- a/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx@@@ -8,8 -8,12 +8,10 @@@ import { flash } from "@carbon/auth/sesimport { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAccount } from "~/modules/accounting";- import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";+ import {+ getAccount,- getAccountLedger,- getAccountLedgerSummary,- getConsolidatedAccountLedger++ getAccountLedgerPage+ } from "~/modules/accounting/accounting.service";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";diff --cc apps/erp/app/routes/x+/reports+/income-statement.tsxindex 3ea9bd003e,029439ba1c..76065125b6--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx@@@ -30,11 -30,11 +30,11 @@@ importMultiPeriodStatementTree,ReportFilters} from "~/modules/accounting/ui/Reports";- import { months } from "~/modules/shared";- import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+ import { months } from "~/modules/shared/shared.models";+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Income Statement`,diff --cc apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsxindex 7fcf6aeb7b,f92cb6a9d3..05b7c1621b--- a/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx@@@ -8,8 -8,12 +8,10 @@@ import { flash } from "@carbon/auth/sesimport { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAccount } from "~/modules/accounting";- import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";+ import {+ getAccount,- getAccountLedger,- getAccountLedgerSummary,- getConsolidatedAccountLedger++ getAccountLedgerPage+ } from "~/modules/accounting/accounting.service";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";diff --cc apps/erp/app/routes/x+/reports+/trial-balance.tsxindex 439d71166c,108653e8e8..a725194827--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx@@@ -25,11 -25,11 +25,11 @@@ importReportFilters,TrialBalanceTree} from "~/modules/accounting/ui/Reports";- import { months } from "~/modules/shared";- import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+ import { months } from "~/modules/shared/shared.models";+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Trial Balance`,diff --cc apps/erp/app/routes/x+/resources+/abilities.tsxindex b39e90d7c9,39eb52e818..cd0d2c26b1--- a/apps/erp/app/routes/x+/resources+/abilities.tsx+++ b/apps/erp/app/routes/x+/resources+/abilities.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { AbilitiesTable } from "~/modules/resources";-import { getAbilities } from "~/modules/resources/resources.service";+ import { AbilitiesTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { abilitiesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Abilities`,diff --cc apps/erp/app/routes/x+/resources+/assignments.$assignmentId.tsxindex 7d159f63f9,dad13ae5d9..8cd1a1111d--- a/apps/erp/app/routes/x+/resources+/assignments.$assignmentId.tsx+++ b/apps/erp/app/routes/x+/resources+/assignments.$assignmentId.tsx@@@ -29,18 -38,25 +38,26 @@@ importLuCalendar,LuCircleCheck,LuClock,+ LuFileCheck,LuSearch,- LuTriangleAlert+ LuTriangleAlert,+ LuUndo2} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";- import { useFetcher, useLoaderData, useNavigate } from "react-router";- import { DateTime, EmployeeAvatar, Empty } from "~/components";+ import { useLoaderData, useNavigate } from "react-router";+ import { DateTime, EmployeeAvatar, Empty, FileDropzone } from "~/components";+ import { Confirm } from "~/components/Modals";import { usePermissions } from "~/hooks";- import { getTraining, getTrainingAssignmentStatus } from "~/modules/resources";+ import { trainingCertificateAccept } from "~/modules/resources/resources.models";+ import {+ getTrainingAssignment,+ getTrainingAssignmentStatus+ } from "~/modules/resources/resources.service";import type { TrainingAssignmentStatusItem } from "~/modules/resources/types";+ import type { action as completeAction } from "~/routes/x+/resources+/assignments.complete";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";- import { path } from "~/utils/path";+ import { getPrivateUrl, path } from "~/utils/path";export const handle: Handle = {breadcrumb: msg`Detail`,@@@ -61,13 -77,13 +78,13 @@@ export async function loader({ request);}- const [training, assignmentStatus] = await Promise.all([- getTraining(client, trainingId),+ const [assignment, assignmentStatus] = await Promise.all([+ getTrainingAssignment(client, assignmentId),getTrainingAssignmentStatus(client, companyId, {- trainingId,+ trainingAssignmentId: assignmentId,status: undefined,search: undefined,- limit: 10000,+ limit: SINGLE_LOAD_LIMIT,offset: 0,sorts: [],filters: []diff --cc apps/erp/app/routes/x+/resources+/contractors.tsxindex dd5cdde63b,cfe608a540..f80e17dfb9--- a/apps/erp/app/routes/x+/resources+/contractors.tsx+++ b/apps/erp/app/routes/x+/resources+/contractors.tsx@@@ -6,11 -9,15 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ContractorsTable, getAbilitiesList } from "~/modules/resources";-import {- getAbilitiesList,- getContractors-} from "~/modules/resources/resources.service";++import { getAbilitiesList } from "~/modules/resources/resources.service";+ import { ContractorsTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { contractorsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Contractors`,diff --cc apps/erp/app/routes/x+/resources+/locations.tsxindex e53f5e40b0,beb2c405d1..29ea3d4960--- a/apps/erp/app/routes/x+/resources+/locations.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { LocationsTable } from "~/modules/resources";-import { getLocations } from "~/modules/resources/resources.service";+ import { LocationsTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { locationsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Locations`,diff --cc apps/erp/app/routes/x+/resources+/maintenance.tsxindex 81ed117b90,c229e19ed9..c1f40cbffc--- a/apps/erp/app/routes/x+/resources+/maintenance.tsx+++ b/apps/erp/app/routes/x+/resources+/maintenance.tsx@@@ -6,12 -7,15 +6,15 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getFailureModesList, getLocationsList } from "~/modules/resources";+ import {+ getFailureModesList,- getLocationsList,- getMaintenanceDispatchesByLocation++ getLocationsList+ } from "~/modules/resources/resources.service";import MaintenanceDispatchesTable from "~/modules/resources/ui/Maintenance/MaintenanceDispatchesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { maintenanceDispatchesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Maintenance`,diff --cc apps/erp/app/routes/x+/resources+/partners.tsxindex 75fd251b79,4b16310ebf..b3e460f54d--- a/apps/erp/app/routes/x+/resources+/partners.tsx+++ b/apps/erp/app/routes/x+/resources+/partners.tsx@@@ -12,11 -12,10 +12,11 @@@ import type { LoaderFunctionArgs } froimport { useLoaderData } from "react-router";import {getAbilitiesList,- getPartners,- PartnersTable- } from "~/modules/resources";+ getPartners+ } from "~/modules/resources/resources.service";+ import { PartnersTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/resources+/processes.tsxindex a601363b36,774758059b..6107ce5bde--- a/apps/erp/app/routes/x+/resources+/processes.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.tsx@@@ -6,11 -9,12 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ProcessesTable } from "~/modules/resources";-import { getProcesses } from "~/modules/resources/resources.service";+ import { ProcessesTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { processesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Processes`,diff --cc apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsxindex 93403bd22d,42c31ea760..21695fd1ea--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx@@@ -10,16 -9,15 +10,16 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";- import type { MaintenanceSchedule } from "~/modules/resources";- import { getLocationsList } from "~/modules/resources";-import {- getLocationsList,- getMaintenanceSchedulesByLocation-} from "~/modules/resources/resources.service";++import { getLocationsList } from "~/modules/resources/resources.service";+ import type { MaintenanceSchedule } from "~/modules/resources/types";import MaintenanceSchedulesTable from "~/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable";import type { Handle } from "~/utils/handle";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { maintenanceSchedulesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "maintenance-schedules");export const handle: Handle = {breadcrumb: msg`Scheduled Maintenances`,diff --cc apps/erp/app/routes/x+/resources+/suggestions.tsxindex c02a0b7833,8b9e9c2459..c3cbce0923--- a/apps/erp/app/routes/x+/resources+/suggestions.tsx+++ b/apps/erp/app/routes/x+/resources+/suggestions.tsx@@@ -6,12 -9,13 +6,12 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { SuggestionsTable } from "~/modules/resources";- import { getTagsList } from "~/modules/shared";-import { getSuggestions } from "~/modules/resources/resources.service";+ import { SuggestionsTable } from "~/modules/resources/ui";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { suggestionsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Suggestions`,diff --cc apps/erp/app/routes/x+/resources+/training.tsxindex af6d8430f1,196f433fc7..56bf92c388--- a/apps/erp/app/routes/x+/resources+/training.tsx+++ b/apps/erp/app/routes/x+/resources+/training.tsx@@@ -9,12 -10,12 +9,12 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { TrainingsTable } from "~/modules/resources";- import { getTagsList } from "~/modules/shared";-import { getTrainings } from "~/modules/resources/resources.service";+ import { TrainingsTable } from "~/modules/resources/ui";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { trainingsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Training`,diff --cc apps/erp/app/routes/x+/resources+/work-centers.tsxindex 78391b2e62,40525b4877..dace10de97--- a/apps/erp/app/routes/x+/resources+/work-centers.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.tsx@@@ -6,12 -9,16 +6,13 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getDepartmentsList } from "~/modules/people";- import { getLocationsList, WorkCentersTable } from "~/modules/resources";+ import { getDepartmentsList } from "~/modules/people/people.service";-import {- getLocationsList,- getWorkCenters-} from "~/modules/resources/resources.service";++import { getLocationsList } from "~/modules/resources/resources.service";+ import { WorkCentersTable } from "~/modules/resources/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { workCentersList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Work Centers`,diff --cc apps/erp/app/routes/x+/sales+/customers.tsxindex 29bc09620e,c908a32632..7c7c8e1013--- a/apps/erp/app/routes/x+/sales+/customers.tsx+++ b/apps/erp/app/routes/x+/sales+/customers.tsx@@@ -6,13 -9,16 +6,13 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getCustomerStatuses } from "~/modules/sales";-import {- getCustomerStatuses,- getCustomers-} from "~/modules/sales/sales.service";++import { getCustomerStatuses } from "~/modules/sales/sales.service";import { CustomersTable } from "~/modules/sales/ui/Customers";- import { getTagsList } from "~/modules/shared";+ import { getTagsList } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customersList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["customer"],diff --cc apps/erp/app/routes/x+/sales+/sales-rules.tsxindex dbef3599d3,9e7819703d..1617cf1d61--- a/apps/erp/app/routes/x+/sales+/sales-rules.tsx+++ b/apps/erp/app/routes/x+/sales+/sales-rules.tsx@@@ -18,9 -18,8 +18,9 @@@ importimport {getEnforcementRuleAssignmentCounts,getEnforcementRules- } from "~/modules/shared";+ } from "~/modules/shared/shared.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export const handle: Handle = {diff --cc apps/erp/app/routes/x+/settings+/api-keys.$id.tsxindex c60bbd4cae,9bb014968b..2da9b2962b--- a/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx@@@ -2,92 -2,33 +2,56 @@@// 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 { assertIsPost, error, success } from "@carbon/auth";+ import { carbon, respond } from "@carbon/api/carbon.server";++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";- import { upsertApiKey } from "@carbon/ee/api-keys.server";- import { requireFeature } from "@carbon/ee/plan.server";- import { validationError, validator } from "@carbon/form";+ import { validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";-import type { ActionFunctionArgs } from "react-router";-import { useParams } from "react-router";-import { useRouteData } from "~/hooks";+import { redirect } from "@carbon/utils";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";- import { data, useLoaderData } from "react-router";- import { ApiKeyForm, apiKeyValidator, getApiKey } from "~/modules/settings";- import { invalidateApiKeyCache } from "~/modules/settings/settings.server";++import { useLoaderData } from "react-router";+ import {+ apiKeyFields,+ apiKeyValidator+ } from "~/modules/settings/settings.models";-import type { ApiKey } from "~/modules/settings/types";++import { getApiKey } from "~/modules/settings/settings.service";+ import { ApiKeyForm } from "~/modules/settings/ui";import { getParams, path } from "~/utils/path";+// The list holds only the rows scrolled so far, so the drawer reads its own key.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "users"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const apiKey = await getApiKey(client, id, companyId);+ if (apiKey.error) {+ throw redirect(+ `${path.to.apiKeys}?${getParams(request)}`,+ await flash(request, error(apiKey.error, "Failed to load API key"))+ );+ }++ return { apiKey: apiKey.data, companyId };+}+- export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId } = await requirePermissions(request, {- update: "users"+ export async function action(args: ActionFunctionArgs) {+ const input = await validator(apiKeyValidator).request(args, {+ params: ["id"]});-- await requireFeature({- request,- client,- companyId,- feature: "API_KEYS",- redirectTo: path.to.apiKeys- });-- const { id } = params;- if (!id) throw new Error("Could not find id");-- const formData = await request.formData();- const validation = await validator(apiKeyValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- const { id: _id, scopes: scopesJson, expiresAt, ...d } = validation.data;-- // Parse scopes from JSON string- const scopes = scopesJson ? JSON.parse(scopesJson) : {};-- const updateApiKey = await upsertApiKey(client, {- id,- ...d,- scopes,- expiresAt: expiresAt || undefined+ if ("invalid" in input) return input.invalid;+ const api = await carbon(args.request);+ const result = await api.settings.updateApiKey({+ ...apiKeyFields(input.data),+ id: input.params.id});-- if (updateApiKey.error) {- return data(- {},- await flash(- request,- error(updateApiKey.error, "Failed to update API key")- )- );- }-- // A scope/expiry edit must not keep authenticating from the 30s auth cache.- await invalidateApiKeyCache(id, companyId);-- throw redirect(- `${path.to.apiKeys}?${getParams(request)}`,- await flash(request, success("Updated API key"))+ return respond(args.request, result).redirect(+ `${path.to.apiKeys}?${getParams(args.request)}`,+ { message: "Updated API key" });}diff --cc apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsxindex f576deed80,fa88a778ec..bdcf60e2d7--- a/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx@@@ -2,80 -2,25 +2,48 @@@// 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 { error, success } from "@carbon/auth";- import { bustApiKeyCache, requirePermissions } from "@carbon/auth/auth.server";+ import { carbon, respond } from "@carbon/api/carbon.server";++import { error } from "@carbon/auth";++import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";- import { deleteApiKey } from "@carbon/ee/api-keys.server";- import { requireFeature } from "@carbon/ee/plan.server";+ import { validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";+import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type { ActionFunctionArgs } from "react-router";-import { useParams } from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { useLoaderData, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";- import { getApiKey } from "~/modules/settings";- import { invalidateApiKeyCache } from "~/modules/settings/settings.server";-import { useRouteData } from "~/hooks";-import type { ApiKey } from "~/modules/settings/types";++import { getApiKey } from "~/modules/settings/settings.service";import { getParams, path } from "~/utils/path";+// The list holds only the rows scrolled so far, so the modal reads its own key.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "users"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const apiKey = await getApiKey(client, id, companyId);+ if (apiKey.error) {+ throw redirect(+ `${path.to.apiKeys}?${getParams(request)}`,+ await flash(request, error(apiKey.error, "Failed to load API key"))+ );+ }++ return { apiKey: { name: apiKey.data.name } };+}+- export async function action({ request, params }: ActionFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- update: "users"- });-- await requireFeature({- request,- client,- companyId,- feature: "API_KEYS",- redirectTo: path.to.apiKeys- });-- const { id } = params;- if (!id) {- throw redirect(- path.to.itemPostingGroups,- await flash(request, error(params, "Failed to get an id"))- );- }-- // Bust BEFORE the delete — the keyHash is unreadable once the row is gone.- const keyHash = await invalidateApiKeyCache(id, companyId);-- const { error: deleteApiKeyError } = await deleteApiKey(client, id);- if (deleteApiKeyError) {- throw redirect(- `${path.to.apiKeys}?${getParams(request)}`,- await flash(request, error(deleteApiKeyError, "Failed to delete API key"))- );- }-- // Bust again now the row is gone: an auth read racing the first bust could- // have re-primed the cache with the still-live row.- if (keyHash) await bustApiKeyCache(keyHash);-- throw redirect(- `${path.to.apiKeys}?${getParams(request)}`,- await flash(request, success("Successfully deleted API key"))+ export async function action(args: ActionFunctionArgs) {+ const input = await validator().request(args, { params: ["id"] });+ if ("invalid" in input) return input.invalid;+ const api = await carbon(args.request);+ const result = await api.settings.revokeApiKey({ id: input.params.id });+ return respond(args.request, result).redirect(+ `${path.to.apiKeys}?${getParams(args.request)}`,+ { message: "Successfully deleted API key" });}diff --cc apps/erp/app/routes/x+/settings+/api-keys.tsxindex 8d7a542929,1c4f221c45..b97a834cf1--- a/apps/erp/app/routes/x+/settings+/api-keys.tsx+++ b/apps/erp/app/routes/x+/settings+/api-keys.tsx@@@ -7,11 -11,11 +7,11 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";- import { ApiKeysTable, ApiKeysUpgradeOverlay } from "~/modules/settings";-import { getApiKeys } from "~/modules/settings/settings.service";+ import { ApiKeysTable, ApiKeysUpgradeOverlay } from "~/modules/settings/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { apiKeysList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`API Keys`,diff --cc apps/erp/app/routes/x+/settings+/audit-logs.details.tsxindex 7a793eea88,4c756b5e35..b432a3a272--- a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx+++ b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx@@@ -15,10 -14,7 +15,10 @@@ importimport { Trans } from "@lingui/react/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";- import { AuditLogTable } from "~/modules/settings";+ import { AuditLogTable } from "~/modules/settings/ui";+import { decodeOffsetToken, encodeOffsetToken } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { PAGE_SIZE } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/settings+/custom-fields.tsxindex 3e3bde8303,99055cc57d..b3feb0195d--- a/apps/erp/app/routes/x+/settings+/custom-fields.tsx+++ b/apps/erp/app/routes/x+/settings+/custom-fields.tsx@@@ -2,18 -2,24 +2,20 @@@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.- import { requirePermissions } from "@carbon/auth/auth.server";+ import { carbon } from "@carbon/api/carbon.server";-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";+ import { validator } from "@carbon/form";import { RecordOutlet, VStack } from "@carbon/react";- import { unchecked } from "@carbon/utils";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getAttributeDataTypes } from "~/modules/people";- import { CustomFieldsTable } from "~/modules/settings";+ import { z } from "zod";+ import { zfd } from "zod-form-data";+ import { getAttributeDataTypes } from "~/modules/people/people.service";-import { getCustomFieldsTables } from "~/modules/settings/settings.service";+ import { CustomFieldsTable } from "~/modules/settings/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customFieldTablesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Custom Fields`,@@@ -21,56 -27,60 +23,37 @@@};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "settings",- role: "employee"+ return loadListPage(request, customFieldTablesList, {+ dataKey: "tables",+ firstPage: async ({ client }) => {+ const dataTypes = await getAttributeDataTypes(client);+ return { dataTypes: dataTypes.data ?? [] };+ },+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch custom fields"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [tables, dataTypes] = await Promise.all([- getCustomFieldsTables(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getAttributeDataTypes(client)- ]);-- if (tables.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(tables.error, "Failed to fetch custom fields"))- );- }-- return {- count: tables.count ?? 0,- tables: tables.data ?? [],- dataTypes: dataTypes.data ?? []- };}- export async function action({ request }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {});+ // Any record's properties panel posts here: the record ids, its table and+ // the custom field values as one JSON string.+ const customFieldsForm = z.object({+ ids: zfd.repeatable(z.array(z.string())),+ table: z.string().min(1, { message: "Invalid table" }),+ value: zfd.json(z.record(z.string(), z.unknown()))+ });- const formData = await request.formData();- const ids = formData.getAll("ids");- const table = formData.get("table");- const value = formData.get("value");-- if (typeof value !== "string" || typeof table !== "string") {- return { error: { message: "Invalid table" }, data: null };- }-- const result = await client- // @ts-expect-error- .from(table)- .update(- unchecked({- customFields: JSON.parse(value),- updatedBy: userId,- updatedAt: new Date().toISOString()- })- )- .in(getIdField(table), ids as string[]);-- return result;- }-- function getIdField(table: string) {- switch (table) {- case "part":- case "material":- case "consumable":- case "tool":- case "fixture":- default:- return "id";- }+ export async function action(args: ActionFunctionArgs) {+ const input = await validator(customFieldsForm).request(args);+ if ("invalid" in input) return input.invalid;+ const api = await carbon(args.request);+ const { ids, table, value } = input.data;+ return api.settings.setRecordCustomFields({+ table,+ ids,+ customFields: value+ });}export default function CustomFieldsRoute() {diff --cc apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 4fa36345aa,5a874c415e..869e487679--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@@ -125,13 -101,20 +101,20 @@@ importdimensionValueMappingBulkUpsertValidator,dimensionValueMappingUpsertValidator,postingSyncSettingsValidator,- syncEnabledValidator+ syncEnabledValidator,+ syncOperationTransitionValidator,+ workCenterDeviceUpsertValidator} from "~/modules/settings/settings.models";import {+ getIntegration,+ getOeeDevicesTabData,+ getProviderDimensionTargets,- getSyncOperationReadableIds,invalidateIntegrationHealthCache,+ isIntegrationInstallWithheld,- upsertCompanyIntegration+ upsertCompanyIntegration,+ withSyncOperationReferences- } from "~/modules/settings/settings.server";+ } from "~/modules/settings/settings.service";+ import { IntegrationForm, SyncActivity } from "~/modules/settings/ui";import { AccountingSyncControl } from "~/modules/settings/ui/Integrations/AccountingSyncControl";import { AccountMapping } from "~/modules/settings/ui/Integrations/AccountMapping";import { DimensionMapping } from "~/modules/settings/ui/Integrations/DimensionMapping";diff --cc apps/erp/app/routes/x+/settings+/printing.jobs.tsxindex e8f1ef32d1,aa305ff29c..cf2b811681--- a/apps/erp/app/routes/x+/settings+/printing.jobs.tsx+++ b/apps/erp/app/routes/x+/settings+/printing.jobs.tsx@@@ -2,15 -2,10 +2,11 @@@// 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 { assertIsPost, error, success } from "@carbon/auth";+ import { carbon } from "@carbon/api/carbon.server";import { requirePermissions } from "@carbon/auth/auth.server";- import { flash } from "@carbon/auth/session.server";- import { trigger } from "@carbon/jobs";+ import { validator } from "@carbon/form";+import { getLogger } from "@carbon/logger";import {- createPrintJob,- getPrintJob,- getPrintJobContent,getPrintJobs,type PrintJob,reprintValidator@@@ -24,12 -19,10 +20,13 @@@ import} from "@carbon/react";import { Trans } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";- import { data, useLoaderData, useNavigate } from "react-router";+ import { useLoaderData, useNavigate } from "react-router";+ import { z } from "zod";import { useRealtime } from "~/hooks";- import { PrintJobsTable } from "~/modules/settings";+ import { PrintJobsTable } from "~/modules/settings/ui";+import { decodeOffsetToken, encodeOffsetToken } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { PAGE_SIZE } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/settings+/sequences.tsxindex 8fa0e49800,fad8d4e340..f726ee645f--- a/apps/erp/app/routes/x+/settings+/sequences.tsx+++ b/apps/erp/app/routes/x+/settings+/sequences.tsx@@@ -6,11 -7,11 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { SequencesTable } from "~/modules/settings";-import { getSequences } from "~/modules/settings/settings.service";+ import { SequencesTable } from "~/modules/settings/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { sequencesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Sequences`,diff --cc apps/erp/app/routes/x+/settings+/serial-numbers.new.tsxindex 2c225d53fa,9639067f85..eb217d3d2b--- a/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx@@@ -9,13 -9,12 +9,13 @@@ import { validationError, validator } fimport { redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";+ import { itemSerialSequenceValidator } from "~/modules/settings/settings.models";import {getItemSerialSequences,- ItemSerialSequenceForm,- itemSerialSequenceValidator,upsertItemSerialSequence- } from "~/modules/settings";+ } from "~/modules/settings/settings.service";+ import { ItemSerialSequenceForm } from "~/modules/settings/ui";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {diff --cc apps/erp/app/routes/x+/settings+/serial-numbers.tsxindex 50d1f7360f,966393a1cf..f093919679--- a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx@@@ -6,11 -7,11 +6,11 @@@ import { RecordOutlet, VStack } from "@import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { ItemSerialSequencesTable } from "~/modules/settings";-import { getItemSerialSequences } from "~/modules/settings/settings.service";+ import { ItemSerialSequencesTable } from "~/modules/settings/ui";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { itemSerialSequencesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Serial Numbers`,diff --cc apps/erp/app/routes/x+/settings+/webhooks.tsxindex 015885776b,ae9cfc170a..69d2cc2237--- a/apps/erp/app/routes/x+/settings+/webhooks.tsx+++ b/apps/erp/app/routes/x+/settings+/webhooks.tsx@@@ -10,7 -11,7 +10,7 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";- import { getConfig } from "~/modules/settings";-import { getConfig, getWebhooks } from "~/modules/settings/settings.service";++import { getConfig } from "~/modules/settings/settings.service";import {WebhooksTable,WebhooksUpgradeOverlaydiff --cc apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsxindex 1c5f60d7e8,c97535c299..4565c4f551--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx@@@ -2,149 -2,26 +2,74 @@@// 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 { assertIsPost, error, success } from "@carbon/auth";+ import { carbon, respond } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { getCarbonServiceRole } from "@carbon/auth/client.server";- import { flash } from "@carbon/auth/session.server";- import { requireFeature } from "@carbon/ee/plan.server";- import { validationError, validator } from "@carbon/form";- import { getLogger } from "@carbon/logger";- import { getClientIp, redirect } from "@carbon/utils";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { data } from "react-router";-import { bulkPermissionsValidator } from "~/modules/users/users.models";++import { z } from "zod";+import {+ bulkPermissionsAllMatchingValidator,+ bulkPermissionsValidator,+ userPermissionsValidator- } from "~/modules/users";- import { queuePermissionUpdates } from "~/modules/users/users.server";++} from "~/modules/users/users.models";+ import { originOf } from "~/modules/users/users.service";import { getParams, path } from "~/utils/path";+import { parseAllMatching } from "~/utils/table-jobs";+import { startTableBulkAction } from "~/utils/table-jobs.server";+- const logger = getLogger("erp", "users-bulk-edit-permissions");-- type ModulePermissions = Record<- string,- { view: boolean; create: boolean; update: boolean; delete: boolean }- >;-- /** The form's permissions JSON, or null when it is not valid. */- function parsePermissions(json: string): ModulePermissions | null {- let permissions: unknown;- try {- permissions = JSON.parse(json);- } catch {- return null;- }- if (permissions === null || typeof permissions !== "object") return null;- return Object.values(permissions).every(- (permission) => userPermissionsValidator.safeParse(permission).success- )- ? (permissions as ModulePermissions)- : null;- }-- export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- update: "users"- });-- await requireFeature({- request,- client,- companyId,- redirectTo: path.to.employeeAccounts,- feature: "PERMISSIONS"- });-- const formData = await request.formData();++const modulePermissions = z.record(z.string(), userPermissionsValidator);+ export async function action(args: ActionFunctionArgs) {+ // Every matching user of the Employees list: the background job picks the- // active users and queues their permission update.- const allMatching = parseAllMatching(formData.get("allMatching"));++ // active users and queues their permission update. The job checks the++ // PERMISSIONS feature (`canRunBulkAction`).++ const allMatching = parseAllMatching(++ (await args.request.clone().formData()).get("allMatching")++ );+ if (allMatching) {- const matching = await validator(- bulkPermissionsAllMatchingValidator- ).validate(formData);- if (matching.error) {- return validationError(matching.error);++ const { companyId, userId } = await requirePermissions(args.request, {++ update: "users"++ });++ const input = await validator(bulkPermissionsAllMatchingValidator).request(++ args++ );++ if ("invalid" in input) return input.invalid;++ let parsed: unknown = null;++ try {++ parsed = JSON.parse(input.data.data);++ } catch {++ parsed = null;+ }- const permissions = parsePermissions(matching.data.data);- if (!permissions) {- return data({ success: false, message: "Failed to parse permissions" });++ const permissions = modulePermissions.safeParse(parsed);++ if (!permissions.success) {++ return { success: false, message: "Failed to parse permissions" };+ }- const ip = getClientIp(request) ?? undefined;- const started = await startTableBulkAction({++ const { ip } = originOf(args.request);++ return startTableBulkAction({+ companyId,+ userId,+ actionKey: "users.permissions",+ params: {- permissions,- addOnly: matching.data.editType === "add",++ permissions: permissions.data,++ addOnly: input.data.editType === "add",+ ...(ip ? { ip } : {})+ },+ allMatching+ });- return started;+ }+- const validation = await validator(bulkPermissionsValidator).validate(- formData- );-- if (validation.error) {- return validationError(validation.error);- }-- const { editType, userIds } = validation.data;- const addOnly = editType === "add";- const permissions = parsePermissions(validation.data.data);-- if (!permissions) {- throw redirect(- path.to.employeeAccounts,- await flash(- request,- error(validation.data.data, "Failed to parse permissions")- )- );- }-- // The job writes these users' grants as the service role: every id must be- // an employee of this company. One batched read.- const uniqueUserIds = [...new Set(userIds)];- const members = await getCarbonServiceRole()- .from("employee")- .select("id")- .in("id", uniqueUserIds)- .eq("companyId", companyId);- if (members.error || (members.data ?? []).length !== uniqueUserIds.length) {- logger.error("Bulk permission edit names users outside the company", {- companyId,- userIds: uniqueUserIds,- error: members.error- });- throw redirect(- path.to.employeeAccounts,- await flash(request, error(members.error, "Employee not found"))- );- }-- const ip = getClientIp(request) ?? undefined;-- await queuePermissionUpdates({+ const input = await validator(bulkPermissionsValidator).request(args);+ if ("invalid" in input) return input.invalid;+ const { editType, userIds, data } = input.data;+ const api = await carbon(args.request);+ const result = await api.users.bulkUpdatePermissions({+ editType,userIds,- companyId,- actorId: userId,- permissions,- addOnly,- ip+ permissions: JSON.parse(data),+ ip: originOf(args.request).ip});-- throw redirect(- `${path.to.employeeAccounts}?${getParams(request)}`,- await flash(request, success("Updating user permissions"))+ return respond(args.request, result).redirect(+ `${path.to.employeeAccounts}?${getParams(args.request)}`,+ { message: "Updating user permissions", onError: path.to.employeeAccounts });}diff --cc apps/erp/app/routes/x+/users+/customers.tsxindex 77748f6ba8,a072c43fc0..9d509a98ee--- a/apps/erp/app/routes/x+/users+/customers.tsx+++ b/apps/erp/app/routes/x+/users+/customers.tsx@@@ -10,14 -10,13 +10,14 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getCustomerTypes } from "~/modules/sales";+ import { getCustomerTypes } from "~/modules/sales/sales.service";+ import { CustomerAccountsTable } from "~/modules/users/ui";import {- CustomerAccountsTable,getCustomers,getUnrevokedInviteEmails- } from "~/modules/users";+ } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/users+/deactivate.tsxindex 0bd74bd079,400daf0c9d..3c30461e9f--- a/apps/erp/app/routes/x+/users+/deactivate.tsx+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx@@@ -2,96 -2,22 +2,43 @@@// 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 { error, success } from "@carbon/auth";+ import { carbon, respond } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { flash } from "@carbon/auth/session.server";- import { deactivateUser } from "@carbon/auth/users.server";- import { validationError, validator } from "@carbon/form";- import { getLogger } from "@carbon/logger";- import { getClientIp, redirect } from "@carbon/utils";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { deactivateUsersValidator } from "~/modules/users";- import { queueUserDeactivations } from "~/modules/users/users.server";+ import { deactivateUsersValidator } from "~/modules/users/users.models";+ import { originOf } from "~/modules/users/users.service";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";- const logger = getLogger("erp", "users-deactivate");-- export async function action({ request }: ActionFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- delete: "users"- });-- const formData = await request.formData();- const ip = getClientIp(request) ?? undefined;-+ export async function action(args: ActionFunctionArgs) {+ // Every matching user of the Employees list: the background job picks the+ // active users other than the actor and queues their deactivation.- const started = await startAllMatchingBulkAction(- formData.get("allMatching"),- {++ const allMatching = (await args.request.clone().formData()).get(++ "allMatching"++ );++ if (allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {++ delete: "users"++ });++ const { ip } = originOf(args.request);++ const started = await startAllMatchingBulkAction(allMatching, {+ companyId,+ userId,+ actionKey: "users.deactivate",+ params: ip ? { ip } : {}- }- );- if (started) return started;-- const validation = await validator(deactivateUsersValidator).validate(- formData- );-- if (validation.error) {- return validationError(validation.error);- }-- const { users, redirectTo } = validation.data;-- if (users.includes(userId)) {- throw redirect(- redirectTo,- await flash(request, error(null, "You cannot deactivate yourself"))- );- }-- if (users.length === 1) {- const [targetUserId] = users;- // deactivateUser() handles Stripe subscription quantity update internally- const result = await deactivateUser(- client,- targetUserId,- companyId,- userId,- ip- );-- throw redirect(redirectTo, await flash(request, result));- }-- // The success redirect stays outside the try: a thrown redirect is caught- // like an error, and every deactivation then reported a failure.- try {- await queueUserDeactivations({- userIds: users,- companyId,- actorId: userId,- ip+ });- } catch (e) {- logger.error("Failed to queue user deactivations", {- companyId,- error: e- });- throw redirect(- redirectTo,- await flash(request, error(e, "Failed to deactivate users"))- );++ if (started) return started;+ }- throw redirect(- redirectTo,- await flash(- request,- success("Success. Please check back in a few moments.")- )- );+++ const input = await validator(deactivateUsersValidator).request(args);+ if ("invalid" in input) return input.invalid;+ const { users, redirectTo } = input.data;+ const api = await carbon(args.request);+ const result = await api.users.deactivateUsers({+ userIds: users,+ ip: originOf(args.request).ip+ });+ return respond(args.request, result).redirect(redirectTo, {+ message: result.data?.message+ });}diff --cc apps/erp/app/routes/x+/users+/employee-types.tsxindex e7c08b34f0,fc1fedfdc7..79ecf0b32f--- a/apps/erp/app/routes/x+/users+/employee-types.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.tsx@@@ -10,11 -11,11 +10,11 @@@ import { usePlanGate } from "~/hooks/usimport {EmployeeTypesTable,EmployeeTypesUpgradeOverlay- } from "~/modules/users";+ } from "~/modules/users/ui";-import { getEmployeeTypes } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { employeeTypesList } from "~/utils/list-registry/users.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Employee Types`,diff --cc apps/erp/app/routes/x+/users+/employees.tsxindex c54303405b,32a7824fe7..018fdba3a6--- a/apps/erp/app/routes/x+/users+/employees.tsx+++ b/apps/erp/app/routes/x+/users+/employees.tsx@@@ -10,16 -11,16 +10,16 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";+ import { EmployeesTable } from "~/modules/users/ui";import {- EmployeesTable,- getEmployees,getEmployeeTypes,getUnrevokedInviteEmails,getUsersWithVerifiedMfa- } from "~/modules/users";+ } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { employeeAccountsList } from "~/utils/list-registry/users.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Employees`,diff --cc apps/erp/app/routes/x+/users+/groups.tsxindex 7b142d9b3d,c2b7bbe1c9..5f9d6b5c12--- a/apps/erp/app/routes/x+/users+/groups.tsx+++ b/apps/erp/app/routes/x+/users+/groups.tsx@@@ -10,10 -10,10 +10,11 @@@ import { msg } from "@lingui/core/macroimport { arrayToTree } from "performant-array-to-tree";import type { LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";- import type { Group } from "~/modules/users";- import { GroupsTable, getGroups } from "~/modules/users";+ import type { Group } from "~/modules/users/types";+ import { GroupsTable } from "~/modules/users/ui";+ import { getGroups } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/users+/resend-invite.tsxindex f0a239c40b,d8bacd27b8..b8ba454347--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx@@@ -2,164 -2,16 +2,37 @@@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.- import { CONTROLLED_ENVIRONMENT, error, success } from "@carbon/auth";+ import { carbon } from "@carbon/api/carbon.server";+import { requirePermissions } from "@carbon/auth/auth.server";- import { getCarbonServiceRole } from "@carbon/auth/client.server";- import { flash } from "@carbon/auth/session.server";- import { InviteEmail } from "@carbon/documents/email";- import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";- import { validationError, validator } from "@carbon/form";- import { sendEmail } from "@carbon/lib/email.server";- import { datetime, getClientIp } from "@carbon/utils";- import { render } from "@react-email/components";- import { nanoid } from "nanoid";+ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";- import { data } from "react-router";- import { resendInviteValidator } from "~/modules/users";- import { queueInviteResends } from "~/modules/users/users.server";+ import { resendInviteValidator } from "~/modules/users/users.models";+ import { originOf } from "~/modules/users/users.service";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";- export async function action({ request }: ActionFunctionArgs) {- const { companyId, userId: actorId } = await requirePermissions(request, {- create: "users"- });-- const formData = await request.formData();+ export async function action(args: ActionFunctionArgs) {++ const { ip, city } = originOf(args.request);++ // Every matching user of the Employees list: the background job picks the+ // inactive users with an email and no unrevoked invite and queues a resend.- const started = await startAllMatchingBulkAction(- formData.get("allMatching"),- {++ const allMatching = (await args.request.clone().formData()).get(++ "allMatching"++ );++ if (allMatching) {++ const { companyId, userId } = await requirePermissions(args.request, {++ create: "users"++ });++ const started = await startAllMatchingBulkAction(allMatching, {+ companyId,- userId: actorId,++ userId,+ actionKey: "users.invite",- params: {- location: request.headers.get("x-vercel-ip-city") ?? "Unknown",- ip: getClientIp(request) ?? "127.0.0.1"- }- }- );- if (started) return started;-- const validation = await validator(resendInviteValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- const { users } = validation.data;-- const serviceRole = getCarbonServiceRole();- if (users.length === 1) {- const [userId] = users;- const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = getClientIp(request) ?? "127.0.0.1";- const [company, user] = await Promise.all([- serviceRole.from("company").select("name").eq("id", companyId).single(),- serviceRole- .from("user")- .select("email, fullName")- .eq("id", userId)- .single()- ]);-- if (!company.data || !user.data) {- throw new Error("Failed to load company or user");- }-- const existingInvite = await serviceRole- .from("invite")- .select("createdBy")- .eq("email", user.data.email)- .eq("companyId", companyId)- .maybeSingle();-- if (existingInvite.error || !existingInvite.data) {- return data(- {},- await flash(- request,- error(existingInvite.error, "No invite record found for user")- )- );- }-- const newCode = nanoid();- const refreshed = await serviceRole- .from("invite")- // Reset createdAt so the controlled-environment 7-day expiry window- // restarts from this resend.- .update({- code: newCode,- acceptedAt: null,- revokedAt: null,- createdAt: datetime.timestamp()- })- .eq("email", user.data.email)- .eq("companyId", companyId)- .select("code")- .single();-- if (refreshed.error || !refreshed.data) {- return data(- {},- await flash(request, error(refreshed.error, "Failed to refresh invite"))- );- }-- const inviter = await serviceRole- .from("user")- .select("email, fullName")- .eq("id", existingInvite.data.createdBy)- .single();-- const inviteLink = await getSsoAwareInviteLink(- serviceRole,- user.data.email,- refreshed.data.code,- companyId- );-- await sendEmail({- to: user.data.email,- subject: `You have been invited to join ${company.data?.name} on Carbon`,- headers: {- "X-Entity-Ref-ID": nanoid()- },- html: await render(- InviteEmail({- invitedByEmail: inviter.data?.email ?? user.data.email,- invitedByName: inviter.data?.fullName ?? "",- email: user.data.email,- name: user.data.fullName ?? "",- companyName: company.data.name,- inviteLink,- ip,- location,- controlledEnvironment: CONTROLLED_ENVIRONMENT- })- )++ params: { location: city ?? "Unknown", ip: ip ?? "127.0.0.1" }+ });-- return data(- {},- await flash(request, success("Successfully resent invite"))- );- } else {- const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";- const ip = getClientIp(request) ?? "127.0.0.1";- try {- await queueInviteResends({ userIds: users, companyId, location, ip });- return data(- {},- await flash(request, success("Successfully added invites to queue"))- );- } catch (e) {- return data(- {},- await flash(request, error(e, "Failed to reinvite users"))- );- }++ if (started) return started;+ }+++ const input = await validator(resendInviteValidator).request(args);+ if ("invalid" in input) return input.invalid;- const { ip, city } = originOf(args.request);+ const api = await carbon(args.request);+ return api.users.resendInvites({ userIds: input.data.users, ip, city });}diff --cc apps/erp/app/routes/x+/users+/suppliers.tsxindex d8556dbcd5,7c39e7cfbc..36760ed910--- a/apps/erp/app/routes/x+/users+/suppliers.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.tsx@@@ -10,14 -10,13 +10,14 @@@ import { redirect } from "@carbon/utilsimport { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getSupplierTypes } from "~/modules/purchasing";+ import { getSupplierTypes } from "~/modules/purchasing/purchasing.service";+ import { SupplierAccountsTable } from "~/modules/users/ui";import {getSuppliers,- getUnrevokedInviteEmails,- SupplierAccountsTable- } from "~/modules/users";+ getUnrevokedInviteEmails+ } from "~/modules/users/users.service";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --cc apps/erp/app/routes/x+/workflows+/runs.tsxindex 082bd09f3b,e9889299cf..eaeb1e5ce4--- a/apps/erp/app/routes/x+/workflows+/runs.tsx+++ b/apps/erp/app/routes/x+/workflows+/runs.tsx@@@ -8,20 -7,19 +8,20 @@@ import { getLogger } from "@carbon/loggimport { RecordOutlet, VStack } from "@carbon/react";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";- import { getWorkflowRunRecordNames } from "~/modules/workflows";import WorkflowRunsTable from "~/modules/workflows/ui/Runs/WorkflowRunsTable";-import {- getWorkflowRunRecordNames,- getWorkflowRuns-} from "~/modules/workflows/workflows.service";++import { getWorkflowRunRecordNames } from "~/modules/workflows/workflows.service";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { workflowRunsList } from "~/utils/list-registry/workflows.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "workflow-runs");export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "workflows",- role: "employee"- });+ const { client, companyId } = await requirePermissions(+ request,+ workflowRunsList.permission+ );await requireFeature({request,client,diff --cc apps/erp/app/utils/list-registry/accounting.server.tsindex 5b775448b0,0000000000..33312c0f76mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/accounting.server.ts+++ b/apps/erp/app/utils/list-registry/accounting.server.ts@@@ -1,189 -1,0 +1,189 @@@+// 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 { RunType } from "@carbon/database/run-type";+import {+ DEPRECIATION_RUNS_PAGING,+ DIMENSIONS_PAGING,+ FIXED_ASSET_CLASSES_PAGING,+ FIXED_ASSETS_PAGING,+ FLEET_ASSETS_PAGING,+ getDepreciationRuns,+ getDimensions,+ getFixedAssetClasses,+ getFixedAssets,+ getFleetAssets,+ getIntercompanyTransactions,+ getJournalEntries,+ getPaymentTerms,+ getProjects,+ getRevenueRecognitionRuns,+ INTERCOMPANY_TRANSACTIONS_PAGING,+ JOURNAL_ENTRIES_PAGING,+ PAYMENT_TERMS_PAGING,+ PERIOD_RUNS_PAGING,+ PROJECTS_PAGING- } from "~/modules/accounting";++} from "~/modules/accounting/accounting.service";+import type { ListDefinition } from "./index.server";+import { resolveCompanyGroupId, searchList } from "./index.server";++const ACCOUNTING_PERMISSION = {+ view: "accounting",+ role: "employee"+} satisfies ListDefinition["permission"];++// Dimensions and intercompany transactions belong to the company group: the+// loader passes its group, and a background job's query reads it.++export const journalEntriesList = searchList({+ key: "journal-entries",+ permission: ACCOUNTING_PERMISSION,+ paging: JOURNAL_ENTRIES_PAGING,+ service: getJournalEntries,+ params: { status: "status" }+});++export const fixedAssetsList = searchList({+ key: "fixed-assets",+ permission: ACCOUNTING_PERMISSION,+ paging: FIXED_ASSETS_PAGING,+ service: getFixedAssets,+ params: { status: "status" }+});++export const assetClassesList = searchList({+ key: "asset-classes",+ permission: ACCOUNTING_PERMISSION,+ paging: FIXED_ASSET_CLASSES_PAGING,+ service: getFixedAssetClasses+});++export const depreciationRunsList = searchList({+ key: "depreciation-runs",+ permission: ACCOUNTING_PERMISSION,+ paging: DEPRECIATION_RUNS_PAGING,+ service: getDepreciationRuns+});++export const fleetAssetsList = searchList({+ key: "fleet-assets",+ permission: ACCOUNTING_PERMISSION,+ paging: FLEET_ASSETS_PAGING,+ service: getFleetAssets,+ params: { fleetStatus: "fleetStatus" }+});++export const dimensionsList = {+ key: "accounting-dimensions",+ permission: ACCOUNTING_PERMISSION,+ ...DIMENSIONS_PAGING,+ query: async (client, companyId, context) => {+ const { companyGroupId, error } = await resolveCompanyGroupId(+ client,+ companyId,+ context+ );+ if (!companyGroupId) return { data: null, error };+ const { params, limit, cursor, exactCount, sorts, filters } = context;+ return getDimensions(client, companyGroupId, {+ search: params.get("search"),+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const intercompanyTransactionsList = {+ key: "intercompany-transactions",+ permission: ACCOUNTING_PERMISSION,+ ...INTERCOMPANY_TRANSACTIONS_PAGING,+ query: async (client, companyId, context) => {+ const { companyGroupId, error } = await resolveCompanyGroupId(+ client,+ companyId,+ context+ );+ if (!companyGroupId) return { data: null, error };+ const { params, limit, cursor, exactCount, sorts, filters } = context;+ return getIntercompanyTransactions(client, companyGroupId, {+ status: params.get("status"),+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const paymentTermsList = searchList({+ key: "payment-terms",+ permission: ACCOUNTING_PERMISSION,+ paging: PAYMENT_TERMS_PAGING,+ service: getPaymentTerms+});++export const projectsList = searchList({+ key: "projects",+ permission: ACCOUNTING_PERMISSION,+ paging: PROJECTS_PAGING,+ service: getProjects+});++// Revenue recognition runs and lease runs share one engine and one list query+// (`period-runs.server.ts`); each run type is its own list.+function periodRunsQuery(type: RunType) {+ return (+ ...[+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ]: Parameters<ListDefinition["query"]>+ ) =>+ getRevenueRecognitionRuns(client, companyId, type, {+ search: params.get("search"),+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ });+}++export const revenueRecognitionRunsList = {+ key: "revenue-recognition-runs",+ permission: ACCOUNTING_PERMISSION,+ ...PERIOD_RUNS_PAGING,+ query: periodRunsQuery("Revenue Recognition")+} satisfies ListDefinition;++export const leaseRunsList = {+ key: "lease-runs",+ permission: ACCOUNTING_PERMISSION,+ ...PERIOD_RUNS_PAGING,+ query: periodRunsQuery("Lease")+} satisfies ListDefinition;++export const periodRunsLists = {+ "Revenue Recognition": revenueRecognitionRunsList,+ Lease: leaseRunsList+} satisfies Record<RunType, ListDefinition>;++// The accounting lists. Each entry follows `sales.server.ts`.+export const accountingLists: Record<string, ListDefinition> = {+ [journalEntriesList.key]: journalEntriesList,+ [fixedAssetsList.key]: fixedAssetsList,+ [assetClassesList.key]: assetClassesList,+ [depreciationRunsList.key]: depreciationRunsList,+ [fleetAssetsList.key]: fleetAssetsList,+ [dimensionsList.key]: dimensionsList,+ [intercompanyTransactionsList.key]: intercompanyTransactionsList,+ [paymentTermsList.key]: paymentTermsList,+ [projectsList.key]: projectsList,+ [revenueRecognitionRunsList.key]: revenueRecognitionRunsList,+ [leaseRunsList.key]: leaseRunsList+};diff --cc apps/erp/app/utils/list-registry/inventory.server.tsindex ea83df0255,0000000000..d6cce76a17mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/inventory.server.ts+++ b/apps/erp/app/utils/list-registry/inventory.server.ts@@@ -1,107 -1,0 +1,107 @@@+// 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 {+ getInventoryCounts,+ getPickingLists,+ getReceipts,+ getShipments,+ getShippingMethods,+ getStockMovements,+ getStorageTypes,+ getTrackedEntities,+ getWarehouseTransfers,+ INVENTORY_COUNTS_PAGING,+ PICKING_LISTS_PAGING,+ RECEIPTS_PAGING,+ SHIPMENTS_PAGING,+ SHIPPING_METHODS_PAGING,+ STOCK_MOVEMENTS_PAGING,+ STORAGE_TYPES_PAGING,+ TRACKED_ENTITIES_PAGING,+ WAREHOUSE_TRANSFERS_PAGING- } from "~/modules/inventory";++} from "~/modules/inventory/inventory.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The inventory lists. Each entry follows `sales.server.ts`. The quantities,+// kanbans, stock transfers and storage units lists have no entry: their+// loaders read the location from the user's defaults, which a registry query+// cannot see.++export const inventoryCountsList = searchList({+ key: "inventory-counts",+ permission: { view: "inventory" },+ paging: INVENTORY_COUNTS_PAGING,+ service: getInventoryCounts+});++export const pickingListsList = searchList({+ key: "picking-lists",+ permission: { view: "inventory" },+ paging: PICKING_LISTS_PAGING,+ service: getPickingLists,+ params: { status: "status", assignee: "assignee", locationId: () => null }+});++export const receiptsList = searchList({+ key: "receipts",+ permission: { view: "inventory" },+ paging: RECEIPTS_PAGING,+ service: getReceipts+});++export const shipmentsList = searchList({+ key: "shipments",+ permission: { view: "inventory" },+ paging: SHIPMENTS_PAGING,+ service: getShipments+});++export const shippingMethodsList = searchList({+ key: "shipping-methods",+ permission: { view: "inventory", role: "employee" },+ paging: SHIPPING_METHODS_PAGING,+ service: getShippingMethods+});++export const stockMovementsList = searchList({+ key: "stock-movements",+ permission: { view: "inventory" },+ paging: STOCK_MOVEMENTS_PAGING,+ service: getStockMovements+});++export const storageTypesList = searchList({+ key: "storage-types",+ permission: { view: "parts", role: "employee" },+ paging: STORAGE_TYPES_PAGING,+ service: getStorageTypes+});++export const trackedEntitiesList = searchList({+ key: "tracked-entities",+ permission: { view: "inventory", role: "employee" },+ paging: TRACKED_ENTITIES_PAGING,+ service: getTrackedEntities+});++export const warehouseTransfersList = searchList({+ key: "warehouse-transfers",+ permission: { view: "inventory" },+ paging: WAREHOUSE_TRANSFERS_PAGING,+ service: getWarehouseTransfers+});++export const inventoryLists: Record<string, ListDefinition> = {+ [inventoryCountsList.key]: inventoryCountsList,+ [pickingListsList.key]: pickingListsList,+ [receiptsList.key]: receiptsList,+ [shipmentsList.key]: shipmentsList,+ [shippingMethodsList.key]: shippingMethodsList,+ [stockMovementsList.key]: stockMovementsList,+ [storageTypesList.key]: storageTypesList,+ [trackedEntitiesList.key]: trackedEntitiesList,+ [warehouseTransfersList.key]: warehouseTransfersList+};diff --cc apps/erp/app/utils/list-registry/invoicing.server.tsindex 7d848be468,0000000000..50efc55e31mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/invoicing.server.ts+++ b/apps/erp/app/utils/list-registry/invoicing.server.ts@@@ -1,150 -1,0 +1,150 @@@+// 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 {+ CHARGES_PAGING,+ getCharges,+ getMemos,+ getPayments,+ getPurchaseInvoices,+ getReimbursements,+ getSalesInvoices,+ MEMOS_PAGING,+ PAYMENTS_PAGING,+ PURCHASE_INVOICES_PAGING,+ REIMBURSEMENTS_PAGING,+ SALES_INVOICES_PAGING- } from "~/modules/invoicing";++} from "~/modules/invoicing/invoicing.service";+import type { Filter } from "../query";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The "Counterparty" column filter spans two columns (customerId OR+// supplierId), so the payments and memos lists take it out of the generic+// filters and hand it to the service, which applies it as an OR.+function splitCounterpartyFilter(filters: Filter[] = []) {+ const counterpartyIds = filters+ .filter((f) => f.column === "counterparty")+ .flatMap((f) => (f.value ?? "").split(","))+ .filter(Boolean);+ return {+ counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,+ filters: filters.filter((f) => f.column !== "counterparty")+ };+}++// The status filter of the payment, memo, charge and reimbursement lists.+type DocumentStatus = "Draft" | "Posted" | "Voided";++export const salesInvoicesList = searchList({+ key: "sales-invoices",+ permission: { view: "invoicing" },+ paging: SALES_INVOICES_PAGING,+ service: getSalesInvoices,+ params: { customerId: "customerId" }+});++export const purchaseInvoicesList = searchList({+ key: "purchase-invoices",+ permission: { view: "invoicing" },+ paging: PURCHASE_INVOICES_PAGING,+ service: getPurchaseInvoices,+ params: { supplierId: "supplierId" }+});++export const paymentsList = {+ key: "payments",+ permission: { view: "invoicing" },+ ...PAYMENTS_PAGING,+ query: (+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ) => {+ const split = splitCounterpartyFilter(filters);+ return getPayments(client, companyId, {+ search: params.get("search"),+ paymentType: params.get("paymentType") as+ | "Receipt"+ | "Disbursement"+ | null,+ status: params.get("status") as DocumentStatus | null,+ customerId: params.get("customerId"),+ supplierId: params.get("supplierId"),+ counterpartyIds: split.counterpartyIds,+ limit,+ cursor,+ exactCount,+ sorts,+ filters: split.filters+ });+ }+} satisfies ListDefinition;++// Accounts Receivable (customer memos) and Accounts Payable (supplier memos)+// read the same `memo` table, scoped by party.+function memosQuery(party: "customer" | "supplier") {+ return (+ ...[+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ]: Parameters<ListDefinition["query"]>+ ) => {+ const split = splitCounterpartyFilter(filters);+ return getMemos(client, companyId, {+ search: params.get("search"),+ direction: params.get("direction") as "Credit" | "Debit" | null,+ status: params.get("status") as DocumentStatus | null,+ party,+ counterpartyIds: split.counterpartyIds,+ limit,+ cursor,+ exactCount,+ sorts,+ filters: split.filters+ });+ };+}++export const creditMemosList = {+ key: "credit-memos",+ permission: { view: "invoicing" },+ ...MEMOS_PAGING,+ query: memosQuery("customer")+} satisfies ListDefinition;++export const supplierCreditsList = {+ key: "supplier-credits",+ permission: { view: "invoicing" },+ ...MEMOS_PAGING,+ query: memosQuery("supplier")+} satisfies ListDefinition;++export const chargesList = searchList({+ key: "charges",+ permission: { view: "invoicing" },+ paging: CHARGES_PAGING,+ service: getCharges,+ params: { type: "type", status: "status" }+});++export const reimbursementsList = searchList({+ key: "reimbursements",+ permission: { view: "invoicing" },+ paging: REIMBURSEMENTS_PAGING,+ service: getReimbursements,+ params: { status: "status", employeeId: "employeeId" }+});++// The invoicing lists. Each entry follows `sales.server.ts`.+export const invoicingLists: Record<string, ListDefinition> = {+ [salesInvoicesList.key]: salesInvoicesList,+ [purchaseInvoicesList.key]: purchaseInvoicesList,+ [paymentsList.key]: paymentsList,+ [creditMemosList.key]: creditMemosList,+ [supplierCreditsList.key]: supplierCreditsList,+ [chargesList.key]: chargesList,+ [reimbursementsList.key]: reimbursementsList+};diff --cc apps/erp/app/utils/list-registry/items.server.tsindex 2a0f490dca,0000000000..50fd8ecfafmode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/items.server.ts+++ b/apps/erp/app/utils/list-registry/items.server.ts@@@ -1,213 -1,0 +1,213 @@@+// 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 {+ CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING,+ CHANGE_NOTICE_TYPES_PAGING,+ CHANGE_NOTICES_PAGING,+ CONSUMABLES_PAGING,+ getChangeNoticeRequiredActions,+ getChangeNotices,+ getChangeNoticeTypes,+ getConsumables,+ getItemPostingGroups,+ getMaterialDimensions,+ getMaterialFinishes,+ getMaterialForms,+ getMaterialGrades,+ getMaterialSubstances,+ getMaterials,+ getMaterialTypes,+ getMethodMaterials,+ getMethodOperations,+ getParts,+ getServices,+ getTools,+ getUnitOfMeasures,+ ITEM_POSTING_GROUPS_PAGING,+ MATERIAL_DIMENSIONS_PAGING,+ MATERIAL_FINISHES_PAGING,+ MATERIAL_FORMS_PAGING,+ MATERIAL_GRADES_PAGING,+ MATERIAL_SUBSTANCES_PAGING,+ MATERIAL_TYPES_PAGING,+ MATERIALS_PAGING,+ METHOD_MATERIALS_PAGING,+ METHOD_OPERATIONS_PAGING,+ PARTS_PAGING,+ SERVICES_PAGING,+ TOOLS_PAGING,+ UNIT_OF_MEASURES_PAGING- } from "~/modules/items";++} from "~/modules/items/items.service";+import { getCompanySettings } from "~/modules/settings/settings.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const partsList = searchList({+ key: "parts",+ permission: { view: "parts" },+ paging: PARTS_PAGING,+ service: getParts,+ params: { supplierId: "supplierId" }+});++export const materialsList = searchList({+ key: "materials",+ permission: { view: "parts" },+ paging: MATERIALS_PAGING,+ service: getMaterials,+ params: { supplierId: "supplierId" }+});++export const toolsList = searchList({+ key: "tools",+ permission: { view: "parts" },+ paging: TOOLS_PAGING,+ service: getTools,+ params: { supplierId: "supplierId" }+});++export const consumablesList = searchList({+ key: "consumables",+ permission: { view: "parts" },+ paging: CONSUMABLES_PAGING,+ service: getConsumables,+ params: { supplierId: "supplierId" }+});++export const servicesList = searchList({+ key: "services",+ permission: { view: "parts" },+ paging: SERVICES_PAGING,+ service: getServices,+ params: { supplierId: "supplierId", group: "group" }+});++export const changeNoticesList = searchList({+ key: "change-notices",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICES_PAGING,+ service: getChangeNotices+});++export const changeNoticeRequiredActionsList = searchList({+ key: "change-notice-actions",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING,+ service: getChangeNoticeRequiredActions+});++export const changeNoticeTypesList = searchList({+ key: "change-notice-types",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICE_TYPES_PAGING,+ service: getChangeNoticeTypes+});++export const materialDimensionsList = {+ key: "material-dimensions",+ permission: { view: "parts", role: "employee" },+ ...MATERIAL_DIMENSIONS_PAGING,+ // The list shows the dimensions of the company's unit system only.+ query: async (+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ) => {+ const settings = await getCompanySettings(client, companyId);+ return getMaterialDimensions(client, companyId, {+ search: params.get("search"),+ isMetric: settings?.data?.useMetric ?? false,+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const materialFinishesList = searchList({+ key: "material-finishes",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_FINISHES_PAGING,+ service: getMaterialFinishes+});++export const materialFormsList = searchList({+ key: "material-forms",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_FORMS_PAGING,+ service: getMaterialForms+});++export const materialGradesList = searchList({+ key: "material-grades",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_GRADES_PAGING,+ service: getMaterialGrades+});++export const itemPostingGroupsList = searchList({+ key: "item-posting-groups",+ permission: { view: "parts", role: "employee" },+ paging: ITEM_POSTING_GROUPS_PAGING,+ service: getItemPostingGroups+});++export const materialSubstancesList = searchList({+ key: "material-substances",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_SUBSTANCES_PAGING,+ service: getMaterialSubstances+});++export const materialTypesList = searchList({+ key: "material-types",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_TYPES_PAGING,+ service: getMaterialTypes+});++export const unitOfMeasuresList = searchList({+ key: "units-of-measure",+ permission: { view: "parts", role: "employee" },+ paging: UNIT_OF_MEASURES_PAGING,+ service: getUnitOfMeasures+});++export const methodMaterialsList = searchList({+ key: "method-materials",+ permission: { view: "production", role: "employee" },+ paging: METHOD_MATERIALS_PAGING,+ service: getMethodMaterials+});++export const methodOperationsList = searchList({+ key: "method-operations",+ permission: { view: "production", role: "employee" },+ paging: METHOD_OPERATIONS_PAGING,+ service: getMethodOperations+});++export const itemsLists: Record<string, ListDefinition> = {+ [partsList.key]: partsList,+ [materialsList.key]: materialsList,+ [toolsList.key]: toolsList,+ [consumablesList.key]: consumablesList,+ [servicesList.key]: servicesList,+ [changeNoticesList.key]: changeNoticesList,+ [changeNoticeRequiredActionsList.key]: changeNoticeRequiredActionsList,+ [changeNoticeTypesList.key]: changeNoticeTypesList,+ [materialDimensionsList.key]: materialDimensionsList,+ [materialFinishesList.key]: materialFinishesList,+ [materialFormsList.key]: materialFormsList,+ [materialGradesList.key]: materialGradesList,+ [itemPostingGroupsList.key]: itemPostingGroupsList,+ [materialSubstancesList.key]: materialSubstancesList,+ [materialTypesList.key]: materialTypesList,+ [unitOfMeasuresList.key]: unitOfMeasuresList,+ [methodMaterialsList.key]: methodMaterialsList,+ [methodOperationsList.key]: methodOperationsList+};diff --cc apps/erp/app/utils/list-registry/people.server.tsindex 02bf74aaed,0000000000..77cac2d3abmode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/people.server.ts+++ b/apps/erp/app/utils/list-registry/people.server.ts@@@ -1,64 -1,0 +1,64 @@@+// 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 {+ ATTRIBUTE_CATEGORIES_PAGING,+ getAttributeCategories,+ getHolidays,+ getPeople,+ getShifts,+ getTimecardEntries,+ HOLIDAYS_PAGING,+ SHIFTS_PAGING,+ TIMECARD_ENTRIES_PAGING- } from "~/modules/people";++} from "~/modules/people/people.service";+import { EMPLOYEES_PAGING } from "~/modules/users/users.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The people list searches with `?name=`, not `?search=`.+export const peopleList = searchList({+ key: "people",+ permission: { view: "people", role: "employee" },+ paging: EMPLOYEES_PAGING,+ service: getPeople,+ params: { search: "name" }+});++export const attributeCategoriesList = searchList({+ key: "attribute-categories",+ permission: { view: "people", role: "employee" },+ paging: ATTRIBUTE_CATEGORIES_PAGING,+ service: getAttributeCategories+});++export const holidaysList = searchList({+ key: "holidays",+ permission: { view: "people", role: "employee" },+ paging: HOLIDAYS_PAGING,+ service: getHolidays+});++export const shiftsList = searchList({+ key: "shifts",+ permission: { view: "people", role: "employee" },+ paging: SHIFTS_PAGING,+ service: getShifts+});++export const timecardEntriesList = searchList({+ key: "timecards",+ permission: { view: "people" },+ paging: TIMECARD_ENTRIES_PAGING,+ service: getTimecardEntries+});++// The people lists. Each entry follows `sales.server.ts`.+export const peopleLists: Record<string, ListDefinition> = {+ [peopleList.key]: peopleList,+ [attributeCategoriesList.key]: attributeCategoriesList,+ [holidaysList.key]: holidaysList,+ [shiftsList.key]: shiftsList,+ [timecardEntriesList.key]: timecardEntriesList+};diff --cc apps/erp/app/utils/list-registry/production.server.tsindex 37c3da4644,0000000000..7f3da9c710mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/production.server.ts+++ b/apps/erp/app/utils/list-registry/production.server.ts@@@ -1,154 -1,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.++import { fetchAllByIds } from "@carbon/database";+import {+ ASSEMBLY_INSTRUCTIONS_PAGING,+ getAssemblyInstructionsPage,+ getJobOperationBatches,+ getJobs,+ getProcedures,+ getScrapReasons,+ JOB_OPERATION_BATCHES_PAGING,+ JOBS_PAGING,+ PROCEDURES_PAGING,+ SCRAP_REASONS_PAGING- } from "~/modules/production";++} from "~/modules/production/production.service";+import { JOB_LIST_EXPORT_VALUES } from "~/modules/production/ui/Jobs/job-list-export";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++/**+ * The live batches and the tracked entity of each job: the jobs view has+ * neither. The loader adds them to every page (`mapRows`); the background+ * export adds them through `exportRows`.+ */+export async function withJobListExtras<+ T extends { id: string | null; jobMakeMethodId: string | null }+>(jobs: T[], { client, companyId }: ListRowsContext) {+ const jobIds = jobs.map((job) => job.id!).filter(Boolean);+ const makeMethodIds = jobs+ .map((job) => job.jobMakeMethodId)+ .filter((id): id is string => !!id);+ const [batchedOps, trackedEntities] = await Promise.all([+ // The jobs view carries no batch column (batching is per operation),+ // so one lookup finds the live (Active/Completing) batches of each job.+ fetchAllByIds(jobIds, (batch) =>+ client+ .from("jobOperation")+ .select("jobId, jobOperationBatch(id, readableId, status)")+ .in("jobId", batch)+ .eq("companyId", companyId)+ .not("jobOperationBatchId", "is", null)+ .order("id", { ascending: true })+ ),+ fetchAllByIds(makeMethodIds, (batch) =>+ client+ .from("trackedEntity")+ .select("readableId, attributes")+ .in("attributes->>Job Make Method", batch)+ .eq("companyId", companyId)+ .order("id", { ascending: true })+ )+ ]);+ // A failed lookup fails the page: a blank Batches or Tracking column would+ // read as "none".+ if (batchedOps.error) throw batchedOps.error;+ if (trackedEntities.error) throw trackedEntities.error;++ const batchesByJobId: Record<string, string[]> = {};+ for (const op of batchedOps.data ?? []) {+ const batch = op.jobOperationBatch;+ if (!batch || (batch.status !== "Active" && batch.status !== "Completing"))+ continue;+ if (!op.jobId || !batch.readableId) continue;+ const list = (batchesByJobId[op.jobId] ??= []);+ if (!list.includes(batch.readableId)) list.push(batch.readableId);+ }++ const trackedEntityByMakeMethodId: Record<string, string> = {};+ for (const entity of trackedEntities.data ?? []) {+ const makeMethodId = readJobMakeMethodId(entity.attributes);+ if (makeMethodId && entity.readableId) {+ trackedEntityByMakeMethodId[makeMethodId] = entity.readableId;+ }+ }++ return jobs.map((job) => ({+ ...job,+ batchReadableIds: (job.id && batchesByJobId[job.id]) || [],+ trackedEntityReadableId:+ (job.jobMakeMethodId &&+ trackedEntityByMakeMethodId[job.jobMakeMethodId]) ||+ null+ }));+}++function readJobMakeMethodId(attributes: unknown): string | null {+ if (!attributes || typeof attributes !== "object") return null;+ const value = (attributes as Record<string, unknown>)["Job Make Method"];+ return typeof value === "string" ? value : null;+}++export const jobsList = searchList({+ key: "jobs",+ permission: { view: "production", role: "employee" },+ paging: JOBS_PAGING,+ service: getJobs,+ exportRows: async (rows, context) =>+ withExportValues(+ await withJobListExtras(rows, context),+ JOB_LIST_EXPORT_VALUES+ )+});++export const assemblyInstructionsList = {+ key: "assembly-instructions",+ permission: { view: "production", role: "employee" },+ ...ASSEMBLY_INSTRUCTIONS_PAGING,+ query: (+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ) =>+ getAssemblyInstructionsPage(client, {+ companyId,+ search: params.get("search") ?? undefined,+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ })+} satisfies ListDefinition;++export const operationBatchesList = searchList({+ key: "operation-batches",+ permission: { view: "production", role: "employee" },+ paging: JOB_OPERATION_BATCHES_PAGING,+ service: getJobOperationBatches+});++export const proceduresList = searchList({+ key: "procedures",+ permission: { view: "production", role: "employee" },+ paging: PROCEDURES_PAGING,+ service: getProcedures+});++export const scrapReasonsList = searchList({+ key: "scrap-reasons",+ permission: { view: "production", role: "employee" },+ paging: SCRAP_REASONS_PAGING,+ service: getScrapReasons+});++export const productionLists: Record<string, ListDefinition> = {+ [jobsList.key]: jobsList,+ [assemblyInstructionsList.key]: assemblyInstructionsList,+ [operationBatchesList.key]: operationBatchesList,+ [proceduresList.key]: proceduresList,+ [scrapReasonsList.key]: scrapReasonsList+};diff --cc apps/erp/app/utils/list-registry/purchasing.server.tsindex b8b01c7494,0000000000..c0f99b919emode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/purchasing.server.ts+++ b/apps/erp/app/utils/list-registry/purchasing.server.ts@@@ -1,141 -1,0 +1,141 @@@+// 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 { indexBy, indexByMapped, pluckUnique } from "@carbon/utils";- import type { SupplierReportContacts } from "~/modules/purchasing";+import {+ getLeases,+ getPurchaseOrders,+ getPurchaseReturnOrders,+ getPurchasingRFQs,+ getSupplierQuotes,+ getSupplierReportContacts,+ getSuppliers,+ getSupplierTypes,+ LEASES_PAGING,+ PURCHASE_ORDERS_PAGING,+ PURCHASE_RETURN_ORDERS_PAGING,+ PURCHASING_RFQS_PAGING,+ SUPPLIER_QUOTES_PAGING,+ SUPPLIER_TYPES_PAGING,+ SUPPLIERS_PAGING- } from "~/modules/purchasing";++} from "~/modules/purchasing/purchasing.service";++import type { SupplierReportContacts } from "~/modules/purchasing/types";+import { SUPPLIER_CONTACT_VALUES } from "~/modules/purchasing/ui/Supplier/supplier-list-export";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++// The purchasing lists. Each entry follows `sales.server.ts`.+// Material Planning (`purchasing+/planning`) is not registered: its query+// needs the location the loader resolves from the user's defaults.++export const purchaseOrdersList = searchList({+ key: "purchase-orders",+ permission: { view: "purchasing" },+ paging: PURCHASE_ORDERS_PAGING,+ service: getPurchaseOrders,+ params: { status: "status", supplierId: "supplierId" }+});++export const supplierQuotesList = searchList({+ key: "supplier-quotes",+ permission: { view: "purchasing" },+ paging: SUPPLIER_QUOTES_PAGING,+ service: getSupplierQuotes+});++export const purchasingRfqsList = searchList({+ key: "purchasing-rfqs",+ permission: { view: "purchasing" },+ paging: PURCHASING_RFQS_PAGING,+ service: getPurchasingRFQs+});++export const purchaseReturnOrdersList = searchList({+ key: "purchase-return-orders",+ permission: { view: "purchasing" },+ paging: PURCHASE_RETURN_ORDERS_PAGING,+ service: getPurchaseReturnOrders,+ params: { status: "status", supplierId: "supplierId" }+});++export const supplierTypesList = {+ key: "supplier-types",+ permission: { view: "purchasing", role: "employee" },+ ...SUPPLIER_TYPES_PAGING,+ // The list has no column filters: the loader never passed them.+ query: (client, companyId, { params, limit, cursor, exactCount, sorts }) =>+ getSupplierTypes(client, companyId, {+ search: params.get("search"),+ limit,+ cursor,+ exactCount,+ sorts+ })+} satisfies ListDefinition;++/**+ * The report contacts (purchasing, invoice, shipping) of each supplier: the+ * suppliers view has none. The loader adds them to every page (`mapRows`);+ * the background export adds them through `exportRows`.+ */+export async function withSupplierReportContacts<+ T extends { id: string | null }+>(suppliers: T[], { client, companyId }: ListRowsContext) {+ const supplierIds = pluckUnique(suppliers, (s) => s.id);+ const [purchasingRes, paymentRes, shippingRes] =+ await getSupplierReportContacts(client, companyId, supplierIds);+ // A failed lookup fails the page: a blank contact column would read as+ // "none".+ for (const result of [purchasingRes, paymentRes, shippingRes]) {+ if (result.error) throw result.error;+ }++ const purchasingBySupplierId = indexByMapped(+ purchasingRes.data,+ (r) => r.id,+ (r) => r.purchasingContact+ );+ const paymentBySupplierId = indexBy(paymentRes.data, (r) => r.supplierId);+ const shippingBySupplierId = indexBy(shippingRes.data, (r) => r.supplierId);++ return suppliers.map((supplier) => {+ const reportContacts: SupplierReportContacts = {+ purchasingContact: purchasingBySupplierId.get(supplier.id!) ?? null,+ payment: paymentBySupplierId.get(supplier.id!) ?? null,+ shipping: shippingBySupplierId.get(supplier.id!) ?? null+ };+ return { ...supplier, reportContacts };+ });+}++export const suppliersList = searchList({+ key: "suppliers",+ permission: { view: "purchasing" },+ paging: SUPPLIERS_PAGING,+ service: getSuppliers,+ params: { type: "type", status: "status" },+ exportRows: async (rows, context) =>+ withExportValues(+ await withSupplierReportContacts(rows, context),+ SUPPLIER_CONTACT_VALUES+ )+});++export const leasesList = searchList({+ key: "leases",+ permission: { view: "purchasing" },+ paging: LEASES_PAGING,+ service: getLeases+});++export const purchasingLists: Record<string, ListDefinition> = {+ [purchaseOrdersList.key]: purchaseOrdersList,+ [supplierQuotesList.key]: supplierQuotesList,+ [purchasingRfqsList.key]: purchasingRfqsList,+ [purchaseReturnOrdersList.key]: purchaseReturnOrdersList,+ [supplierTypesList.key]: supplierTypesList,+ [suppliersList.key]: suppliersList,+ [leasesList.key]: leasesList+};diff --cc apps/erp/app/utils/list-registry/quality.server.tsindex 3d9404d567,0000000000..6f57cf625bmode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/quality.server.ts+++ b/apps/erp/app/utils/list-registry/quality.server.ts@@@ -1,135 -1,0 +1,135 @@@+// 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 {+ GAUGE_CALIBRATION_RECORDS_PAGING,+ GAUGE_TYPES_PAGING,+ GAUGES_PAGING,+ getGaugeCalibrationRecords,+ getGauges,+ getGaugeTypes,+ getInspectionDocuments,+ getInspections,+ getIssues,+ getIssueTypes,+ getIssueWorkflows,+ getQualityActions,+ getQualityDocuments,+ getRequiredActions,+ getRisks,+ INSPECTION_DOCUMENTS_PAGING,+ INSPECTIONS_PAGING,+ ISSUE_TYPES_PAGING,+ ISSUE_WORKFLOWS_PAGING,+ ISSUES_PAGING,+ QUALITY_ACTIONS_PAGING,+ QUALITY_DOCUMENTS_PAGING,+ REQUIRED_ACTIONS_PAGING,+ RISKS_PAGING- } from "~/modules/quality";++} from "~/modules/quality/quality.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The quality loaders do not bypass RLS, so their lists keep the RLS client+// and `role: "employee"`.++export const issuesList = searchList({+ key: "issues",+ permission: { view: "quality", role: "employee" },+ paging: ISSUES_PAGING,+ service: getIssues+});++export const qualityActionsList = searchList({+ key: "quality-actions",+ permission: { view: "quality", role: "employee" },+ paging: QUALITY_ACTIONS_PAGING,+ service: getQualityActions+});++export const gaugeCalibrationRecordsList = searchList({+ key: "gauge-calibration-records",+ permission: { view: "quality", role: "employee" },+ paging: GAUGE_CALIBRATION_RECORDS_PAGING,+ service: getGaugeCalibrationRecords+});++export const qualityDocumentsList = searchList({+ key: "quality-documents",+ permission: { view: "quality", role: "employee" },+ paging: QUALITY_DOCUMENTS_PAGING,+ service: getQualityDocuments+});++export const gaugesList = searchList({+ key: "gauges",+ permission: { view: "quality", role: "employee" },+ paging: GAUGES_PAGING,+ service: getGauges+});++export const gaugeTypesList = searchList({+ key: "gauge-types",+ permission: { view: "quality", role: "employee" },+ paging: GAUGE_TYPES_PAGING,+ service: getGaugeTypes+});++export const inspectionPlansList = searchList({+ key: "inspection-plans",+ permission: { view: "quality", role: "employee" },+ paging: INSPECTION_DOCUMENTS_PAGING,+ service: getInspectionDocuments+});++export const inspectionsList = searchList({+ key: "inspections",+ permission: { view: "quality", role: "employee" },+ paging: INSPECTIONS_PAGING,+ service: getInspections,+ params: { status: "status", source: "source" }+});++export const issueTypesList = searchList({+ key: "issue-types",+ permission: { view: "quality", role: "employee" },+ paging: ISSUE_TYPES_PAGING,+ service: getIssueTypes+});++export const issueWorkflowsList = searchList({+ key: "issue-workflows",+ permission: { view: "quality", role: "employee" },+ paging: ISSUE_WORKFLOWS_PAGING,+ service: getIssueWorkflows+});++export const requiredActionsList = searchList({+ key: "required-actions",+ permission: { view: "quality", role: "employee" },+ paging: REQUIRED_ACTIONS_PAGING,+ service: getRequiredActions+});++export const risksList = searchList({+ key: "risks",+ permission: { view: "quality", role: "employee" },+ paging: RISKS_PAGING,+ service: getRisks+});++export const qualityLists: Record<string, ListDefinition> = {+ [issuesList.key]: issuesList,+ [qualityActionsList.key]: qualityActionsList,+ [gaugeCalibrationRecordsList.key]: gaugeCalibrationRecordsList,+ [qualityDocumentsList.key]: qualityDocumentsList,+ [gaugesList.key]: gaugesList,+ [gaugeTypesList.key]: gaugeTypesList,+ [inspectionPlansList.key]: inspectionPlansList,+ [inspectionsList.key]: inspectionsList,+ [issueTypesList.key]: issueTypesList,+ [issueWorkflowsList.key]: issueWorkflowsList,+ [requiredActionsList.key]: requiredActionsList,+ [risksList.key]: risksList+};diff --cc apps/erp/app/utils/list-registry/sales.server.tsindex 529fc2cf64,0000000000..ab1467d331mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/sales.server.ts+++ b/apps/erp/app/utils/list-registry/sales.server.ts@@@ -1,191 -1,0 +1,194 @@@+// 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 {+ CONTRACTS_PAGING,+ CUSTOMER_STATUSES_PAGING,+ CUSTOMER_TYPES_PAGING,+ CUSTOMERS_PAGING,+ getBaseCatalog,+ getContracts,+ getCustomerStatuses,+ getCustomers,+ getCustomerTypes,+ getNoQuoteReasons,+ getPricingRules,+ getQuotes,+ getRentalAgreements,+ getReturnReasons,+ getSalesOrders,+ getSalesReturnOrders,+ getSalesRFQs,+ NO_QUOTE_REASONS_PAGING,+ PRICE_LIST_PAGING,+ PRICING_RULES_PAGING,+ QUOTES_PAGING,+ RENTAL_AGREEMENTS_PAGING,+ RETURN_REASONS_PAGING,+ resolvePriceList,+ SALES_ORDERS_PAGING,+ SALES_RETURN_ORDERS_PAGING,+ SALES_RFQS_PAGING- } from "~/modules/sales";- import { CUSTOMER_PORTALS_PAGING, getCustomerPortals } from "~/modules/shared";++} from "~/modules/sales/sales.service";++import {++ CUSTOMER_PORTALS_PAGING,++ getCustomerPortals++} from "~/modules/shared/shared.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const salesOrdersList = searchList({+ key: "sales-orders",+ permission: { view: "sales" },+ paging: SALES_ORDERS_PAGING,+ service: getSalesOrders,+ params: { status: "status", customerId: "customerId" }+});++export const quotesList = searchList({+ key: "quotes",+ permission: { view: "sales" },+ paging: QUOTES_PAGING,+ service: getQuotes+});++export const salesRfqsList = searchList({+ key: "sales-rfqs",+ permission: { view: "sales" },+ paging: SALES_RFQS_PAGING,+ service: getSalesRFQs+});++export const salesReturnOrdersList = searchList({+ key: "sales-return-orders",+ permission: { view: "sales" },+ paging: SALES_RETURN_ORDERS_PAGING,+ service: getSalesReturnOrders,+ params: { status: "status", customerId: "customerId" }+});++export const customersList = searchList({+ key: "customers",+ permission: { view: "sales" },+ paging: CUSTOMERS_PAGING,+ service: getCustomers+});++export const contractsList = searchList({+ key: "contracts",+ permission: { view: "sales" },+ paging: CONTRACTS_PAGING,+ service: getContracts+});++export const rentalAgreementsList = searchList({+ key: "rental-agreements",+ permission: { view: "sales" },+ paging: RENTAL_AGREEMENTS_PAGING,+ service: getRentalAgreements+});++// With a customer or a customer type in the URL, the list resolves that+// scope's prices; without one, it shows the base catalog.+export const priceListList = {+ key: "price-list",+ permission: { view: "sales", role: "employee" },+ ...PRICE_LIST_PAGING,+ query: async (+ client,+ companyId,+ { params, limit, cursor, exactCount, sorts, filters }+ ) => {+ const search = params.get("search") ?? undefined;+ const customerId = params.get("customerId") ?? undefined;+ const customerTypeId = params.get("customerTypeId") ?? undefined;+ const rawQuantity = Number(params.get("quantity") ?? "1");+ const quantity =+ Number.isFinite(rawQuantity) && rawQuantity >= 0 ? rawQuantity : 1;++ const result =+ customerId || customerTypeId+ ? await resolvePriceList(client, companyId, {+ customerId,+ customerTypeId,+ quantity,+ search,+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ })+ : await getBaseCatalog(client, companyId, {+ search,+ limit,+ cursor,+ exactCount,+ sorts,+ filters+ });++ return { ...result, error: null };+ }+} satisfies ListDefinition;++export const pricingRulesList = searchList({+ key: "pricing-rules",+ permission: { view: "sales", role: "employee" },+ paging: PRICING_RULES_PAGING,+ service: getPricingRules,+ params: { search: (params) => params.get("search") ?? undefined }+});++export const customerPortalsList = searchList({+ key: "customer-portals",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_PORTALS_PAGING,+ service: getCustomerPortals+});++export const customerStatusesList = searchList({+ key: "customer-statuses",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_STATUSES_PAGING,+ service: getCustomerStatuses+});++export const customerTypesList = searchList({+ key: "customer-types",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_TYPES_PAGING,+ service: getCustomerTypes+});++export const noQuoteReasonsList = searchList({+ key: "no-quote-reasons",+ permission: { view: "sales", role: "employee" },+ paging: NO_QUOTE_REASONS_PAGING,+ service: getNoQuoteReasons+});++export const returnReasonsList = searchList({+ key: "return-reasons",+ permission: { view: "sales", role: "employee" },+ paging: RETURN_REASONS_PAGING,+ service: getReturnReasons+});++export const salesLists: Record<string, ListDefinition> = {+ [salesOrdersList.key]: salesOrdersList,+ [quotesList.key]: quotesList,+ [salesRfqsList.key]: salesRfqsList,+ [salesReturnOrdersList.key]: salesReturnOrdersList,+ [customersList.key]: customersList,+ [contractsList.key]: contractsList,+ [rentalAgreementsList.key]: rentalAgreementsList,+ [priceListList.key]: priceListList,+ [pricingRulesList.key]: pricingRulesList,+ [customerPortalsList.key]: customerPortalsList,+ [customerStatusesList.key]: customerStatusesList,+ [customerTypesList.key]: customerTypesList,+ [noQuoteReasonsList.key]: noQuoteReasonsList,+ [returnReasonsList.key]: returnReasonsList+};diff --cc apps/erp/app/utils/list-registry/workflows.server.tsindex e833204003,0000000000..405eaf92c0mode 100644,000000..100644--- a/apps/erp/app/utils/list-registry/workflows.server.ts+++ b/apps/erp/app/utils/list-registry/workflows.server.ts@@@ -1,84 -1,0 +1,84 @@@+// 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 { WorkflowLastRun } from "~/modules/workflows";++import { WORKFLOW_LIST_EXPORT_VALUES } from "~/modules/workflows/ui/workflow-list-export";++import type { WorkflowLastRun } from "~/modules/workflows/workflows.service";+import {+ getWorkflowLastRuns,+ getWorkflowRuns,+ getWorkflows,+ getWorkflowVersionNumbers,+ WORKFLOW_RUNS_PAGING,+ WORKFLOWS_PAGING- } from "~/modules/workflows";- import { WORKFLOW_LIST_EXPORT_VALUES } from "~/modules/workflows/ui/workflow-list-export";++} from "~/modules/workflows/workflows.service";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++/**+ * The published version number and the last run of each workflow. The loader+ * adds them to every page (`mapRows`); the background export adds them+ * through `exportRows`.+ */+export async function withWorkflowListExtras<+ T extends { id: string; publishedVersionId: string | null }+>(rows: T[], { client, companyId }: ListRowsContext) {+ const publishedVersionIds = rows+ .map((row) => row.publishedVersionId)+ .filter((id): id is string => id !== null);+ const workflowIds = rows.map((row) => row.id);+ const [versions, runs] = await Promise.all([+ publishedVersionIds.length+ ? getWorkflowVersionNumbers(client, publishedVersionIds, companyId)+ : null,+ workflowIds.length+ ? getWorkflowLastRuns(client, workflowIds, companyId)+ : null+ ]);+ // A failed lookup fails the page: a blank Version or Last Run column would+ // read as "none".+ if (versions?.error) throw versions.error;+ if (runs?.error) throw runs.error;++ const versionNumbers = new Map(+ (versions?.data ?? []).map((version) => [version.id, version.versionNumber])+ );+ const lastRuns = new Map<string, WorkflowLastRun>();+ for (const run of runs?.data ?? []) {+ if (run.workflowId) lastRuns.set(run.workflowId, run);+ }++ return rows.map((row) => ({+ ...row,+ publishedVersionNumber: row.publishedVersionId+ ? (versionNumbers.get(row.publishedVersionId) ?? null)+ : null,+ lastRun: lastRuns.get(row.id) ?? null+ }));+}++export const workflowsList = searchList({+ key: "workflows",+ permission: { view: "workflows", role: "employee" },+ paging: WORKFLOWS_PAGING,+ service: getWorkflows,+ exportRows: async (rows, context) =>+ withExportValues(+ await withWorkflowListExtras(rows, context),+ WORKFLOW_LIST_EXPORT_VALUES+ )+});++export const workflowRunsList = searchList({+ key: "workflow-runs",+ permission: { view: "workflows", role: "employee" },+ paging: WORKFLOW_RUNS_PAGING,+ service: getWorkflowRuns+});++// The workflows lists. Each entry follows `sales.server.ts`.+export const workflowsLists: Record<string, ListDefinition> = {+ [workflowsList.key]: workflowsList,+ [workflowRunsList.key]: workflowRunsList+};diff --cc apps/erp/app/utils/path.tsindex c20ccc6cd1,5a5e24b3d3..d890da2257--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@@ -379,7 -387,7 +392,8 @@@ export const path =supplierProcesses: (id: string) =>generatePath(`${api}/purchasing/supplier-processes/${id}`),supplierTypes: `${api}/purchasing/supplier-types`,+ systemStatus: `${api}/system-status`,+ tableExport: `${api}/table/export`,tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),timecard: `${api}/people/timecard`,diff --cc apps/erp/app/utils/production-bulk-actions.server.tsindex 0000000000,0000000000..ada486e1ccnew file mode 100644--- /dev/null+++ b/apps/erp/app/utils/production-bulk-actions.server.ts@@@ -1,0 -1,0 +1,300 @@@++// 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 { ServiceContext } from "@carbon/api/service-fn.server";++import { getLogger } from "@carbon/logger";++import { runLocationSchedule } from "@carbon/planning";++import { chunkArray } from "@carbon/utils";++import {++ isBatchDissolvable,++ isJobBulkReleasable++} from "~/modules/production/production.models";++import {++ releaseBatches,++ releaseCheckedJobs,++ updateBatch++} from "~/modules/production/production.server";++import { getJobReleaseReadiness } from "~/modules/production/production.service";++import {++ bulkReleaseStartingPurchaseOrders,++ jobReleaseProblems++} from "~/modules/production/ui/Jobs/job-release-logic";++import { splitIdsByStatus } from "./table-jobs";++++/**++ * The background bulk-action job's slices of the jobs and batches tables'++ * Release and Dissolve (`~/utils/table-jobs.server`). Each runs the++ * production service functions the in-request actions run, in the context++ * the job builds; a row the action may not act on is skipped.++ */++++const logger = getLogger("erp", "production-bulk-actions");++++/** An `.in()` filter rides in the request URL, so ids are read 100 at a time. */++const IN_CHUNK = 100;++++type Problem = { readableId: string; message: string };++++export type BulkReleaseJobsResult =++ | {++ success: true;++ released: number;++ /** Released, with something left to fix on the job (its POs). */++ warnings: Problem[];++ failed: Problem[];++ /** Jobs that are not Draft or Planned (a stale selection). */++ skipped: number;++ scheduled: boolean;++ /** The PO each supplier's outside operations went on. The next slice++ * of the same release takes it. */++ purchaseOrdersBySupplierId: Record<string, string>;++ }++ | { success: false; message: string };++++/**++ * Releases each Draft / Planned job on its own (`releaseCheckedJobs`): a job++ * that is not ready is reported in `failed` while the rest still release.++ * There is no dialog, so a job with something to fix or a purchase order to++ * choose is skipped and named. Then each location is scheduled once.++ *++ * A background release runs in slices of 25 jobs. `purchaseOrdersBySupplierId`++ * is the map the previous slice returned: a supplier keeps the PO an earlier++ * slice created instead of being asked to choose (`bulkReleaseStartingPurchaseOrders`).++ */++export async function bulkReleaseJobs(++ ctx: ServiceContext,++ {++ jobIds,++ purchaseOrdersBySupplierId++ }: {++ jobIds: string[];++ purchaseOrdersBySupplierId?: Record<string, string>;++ }++): Promise<BulkReleaseJobsResult> {++ const companyId = ctx.company.id;++ const client = ctx.asCaller.supabase;++ const ids = [...new Set(jobIds.filter(Boolean))];++ const jobs = [];++ for (const batch of chunkArray(ids, IN_CHUNK)) {++ const page = await client++ .from("job")++ .select("id, jobId, status, quantity, scrapQuantity, locationId")++ .in("id", batch)++ .eq("companyId", companyId);++ if (page.error) {++ logger.error("Failed to load the selected jobs", {++ companyId,++ error: page.error++ });++ return { success: false, message: "Failed to load the selected jobs" };++ }++ jobs.push(...page.data);++ }++++ const releasable = jobs++ .filter((job) => isJobBulkReleasable(job.status))++ .sort((a, b) => a.jobId.localeCompare(b.jobId));++ const skipped = ids.length - releasable.length;++ const readiness = await getJobReleaseReadiness(++ client,++ releasable.map((job) => job.id),++ companyId++ );++ if (readiness.error || !readiness.data) {++ logger.error("Failed to validate the selected jobs", {++ companyId,++ error: readiness.error++ });++ return { success: false, message: "Failed to validate the selected jobs" };++ }++++ const readinessByJobId = new Map(++ readiness.data.jobs.map((job) => [job.id, job] as const)++ );++ // Every supplier starts on a new PO, or on the one an earlier slice of this++ // release created; a PO a job creates is reused by the jobs after it, so the++ // selection lands on one PO per supplier.++ const starting = bulkReleaseStartingPurchaseOrders(++ readiness.data.suppliers,++ purchaseOrdersBySupplierId++ );++ let purchaseOrders = starting.purchaseOrders;++++ let released = 0;++ const failed: Problem[] = [];++ const warnings: Problem[] = [];++ const locationIds = new Set<string>();++ for (const job of releasable) {++ const ready = readinessByJobId.get(job.id);++ const problems = ready++ ? [++ // The job page disables Release for the same job.++ ...(job.quantity === 0 && job.scrapQuantity === 0++ ? ["nothing to make"]++ : []),++ ...jobReleaseProblems(ready),++ ...(ready.supplierIds.some((id) => starting.suppliersToChoose.has(id))++ ? ["choose a purchase order for its outside operations on the job"]++ : [])++ ]++ : ["could not be validated"];++ if (problems.length > 0) {++ failed.push({ readableId: job.jobId, message: problems.join("; ") });++ continue;++ }++++ const result = await releaseCheckedJobs(ctx, {++ jobIds: [job.id],++ purchaseOrdersBySupplierId: purchaseOrders++ });++ const failure = result.error ?? result.data.failure;++ if (result.data) purchaseOrders = result.data.purchaseOrdersBySupplierId;++ if (failure) {++ logger.error("Failed to release job", {++ companyId,++ jobId: job.id,++ error: failure++ });++ }++ // The job is Ready when its id came back released, error or not; a job++ // that is Ready must be scheduled and counted, whatever failed after.++ if (!result.data?.releasedJobIds.includes(job.id)) {++ failed.push({ readableId: job.jobId, message: failure?.message ?? "" });++ continue;++ }++ if (failure) {++ warnings.push({ readableId: job.jobId, message: failure.message });++ }++++ if (job.locationId) locationIds.add(job.locationId);++ released += 1;++ }++++ // After every status flip is persisted: the scheduler only places jobs that++ // are already released. One run per location, as on the job page.++ let scheduled = true;++ for (const locationId of locationIds) {++ try {++ await runLocationSchedule({++ db: ctx.asSystem.pg,++ client: ctx.asSystem.supabase,++ locationId,++ companyId,++ userId: ctx.auditUserId++ });++ } catch (error) {++ logger.error("Failed to schedule released jobs", {++ companyId,++ locationId,++ error++ });++ scheduled = false;++ }++ }++++ return {++ success: true,++ released,++ warnings,++ failed,++ skipped,++ scheduled,++ purchaseOrdersBySupplierId: {++ ...purchaseOrdersBySupplierId,++ ...purchaseOrders++ }++ };++}++++export type BulkBatchResult =++ | {++ success: true;++ /** Batches released or dissolved. */++ done: number;++ failed: Problem[];++ /** Batches whose status the action does not accept, or not found. */++ skipped: number;++ }++ | { success: false; message: string };++++/**++ * Releases the Planned batches (`releaseBatches`): a batch whose member jobs++ * fail their checks, or that has a PO to choose, is reported in `failed`++ * while the rest still release. Any other status is skipped.++ */++export async function bulkReleaseBatches(++ ctx: ServiceContext,++ { batchIds }: { batchIds: string[] }++): Promise<BulkBatchResult> {++ const ids = [...new Set(batchIds.filter(Boolean))];++ if (ids.length === 0) {++ return { success: true, done: 0, failed: [], skipped: 0 };++ }++ const result = await releaseBatches(ctx, { batchIds: ids });++ if (result.error) {++ logger.error("Failed to release batches", {++ companyId: ctx.company.id,++ error: result.error++ });++ return { success: false, message: result.error.message };++ }++ return {++ success: true,++ done: result.data.released.length,++ failed: result.data.failed.map(({ readableId, message }) => ({++ readableId,++ message++ })),++ skipped: result.data.skipped.length++ };++}++++/**++ * Dissolves each Planned or Active batch on its own (`updateBatch`): a batch++ * that has recorded production is refused and reported in `failed`. A++ * Completing or Completed batch is skipped.++ */++export async function bulkDissolveBatches(++ ctx: ServiceContext,++ { batchIds }: { batchIds: string[] }++): Promise<BulkBatchResult> {++ const companyId = ctx.company.id;++ const ids = [...new Set(batchIds.filter(Boolean))];++ const rows: { id: string; readableId: string; status: string }[] = [];++ for (const chunk of chunkArray(ids, IN_CHUNK)) {++ const page = await ctx.asCaller.supabase++ .from("jobOperationBatch")++ .select("id, readableId, status")++ .in("id", chunk)++ .eq("companyId", companyId);++ if (page.error) {++ logger.error("Failed to load the batches to dissolve", {++ companyId,++ error: page.error++ });++ return { success: false, message: "Failed to load the selected batches" };++ }++ rows.push(...page.data);++ }++ const readableById = new Map(++ rows.map((row) => [row.id, row.readableId] as const)++ );++ const { allowed, skipped } = splitIdsByStatus(ids, rows, isBatchDissolvable);++++ let dissolved = 0;++ const failed: Problem[] = [];++ for (const batchId of allowed) {++ const result = await updateBatch(ctx, { batchId, type: "dissolve" });++ if (result.error) {++ failed.push({++ readableId: readableById.get(batchId) ?? batchId,++ message: result.error.message || "Failed to dissolve"++ });++ } else {++ dissolved += 1;++ }++ }++++ return { success: true, done: dissolved, failed, skipped };++}diff --cc apps/erp/app/utils/query.tsindex af92e7bd79,a6426901fe..0e5f91ec21--- a/apps/erp/app/utils/query.ts+++ b/apps/erp/app/utils/query.ts@@@ -3,17 -3,9 +3,18 @@@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { badRequest } from "@carbon/auth";+ import { searchFilter } from "@carbon/utils";import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";-import { getPageOffset, getPageSize } from "./pagination";+import type { Cursor, DefaultSort, KeysetSort, Paging, Sort } from "./cursor";+import {+ buildKeysetFilter,+ cursorMatchesSorts,+ decodeCursor,+ resolveSorts+} from "./cursor";+import { PAGE_SIZE } from "./pagination";++export type { DefaultSort, Paging, Sort } from "./cursor";type GenericSchema = {Tables: Record<string, unknown>;@@@ -339,3 -255,44 +336,51 @@@ export const filterOperatorLabels = Objlabel: value}));++ // Array values sort by their first entry.+ export function pageInMemory<T extends Record<string, unknown>>(+ rows: T[],+ searchParams: URLSearchParams,+ searchable: (row: T) => (string | null | undefined)[]+ ): { rows: T[]; count: number } {+ const search = searchParams.get("search")?.trim().toLowerCase() ?? "";- const { limit, offset, sorts } = getGenericQueryFilters(searchParams);++ const { sorts } = getGenericQueryFilters(searchParams);++ // The drawers that use this have no pager: without `limit` every match is++ // one page (the Table renders only the rows in view).++ const offset = Math.max(0, Number(searchParams.get("offset")) || 0);++ const requestedLimit = Number(searchParams.get("limit"));++ const matching = search+ ? rows.filter((row) =>+ searchable(row).some((value) =>+ (value ?? "").toLowerCase().includes(search)+ )+ )+ : [...rows];++ const sortValue = (row: T, key: string) => {+ const value = row[key];+ return Array.isArray(value) ? value[0] : value;+ };+ for (const { sortBy, sortAsc } of [...(sorts ?? [])].reverse()) {+ matching.sort((a, b) => {+ const left = sortValue(a, sortBy);+ const right = sortValue(b, sortBy);+ const order =+ typeof left === "number" && typeof right === "number"+ ? left - right+ : String(left ?? "").localeCompare(String(right ?? ""), undefined, {+ numeric: true+ });+ return sortAsc ? order : -order;+ });+ }++ return {- rows: matching.slice(offset, offset + limit),++ rows: matching.slice(++ offset,++ requestedLimit > 0 ? offset + requestedLimit : undefined++ ),+ count: matching.length+ };+ }diff --cc apps/erp/app/utils/table-jobs.server.tsindex d70f077e45,0000000000..b226b5dafcmode 100644,000000..100644--- a/apps/erp/app/utils/table-jobs.server.ts+++ b/apps/erp/app/utils/table-jobs.server.ts@@@ -1,669 -1,0 +1,684 @@@+// 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 { getClaims, makePermissionsFromClaims } from "@carbon/auth";+import {+ getCarbonServiceRole,+ getUserScopedClient+} from "@carbon/auth/client.server";+import type { Json } from "@carbon/database";+import { companyHasFeature } from "@carbon/ee/plan.server";+import { trigger } from "@carbon/jobs";+import {+ MAX_BULK_PROBLEMS,+ releaseTableJobLock,+ type TableBulkAction,+ type TableBulkActionCarry,+ type TableBulkActionResult,+ type TableJobContext,+ type TableJobHandlers,+ takeTableJobLock+} from "@carbon/jobs/inngest";+import { getLogger } from "@carbon/logger";+import { nanoid } from "nanoid";- import { isItemBulkUpdateField } from "~/modules/items";- import { bulkUpdateItems } from "~/modules/items/bulk-actions.server";- import {- bulkDeleteJobs,- bulkDissolveBatches,- bulkReleaseBatches,- bulkReleaseJobs- } from "~/modules/production/bulk-actions.server";- import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.server";- import { userPermissionsValidator } from "~/modules/users";++import { isItemBulkUpdateField } from "~/modules/items/items.models";++import { bulkUpdateItems } from "~/modules/items/items.service";++import { bulkDeleteJobs } from "~/modules/production/production.service";++import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.service";++import { systemContext } from "~/modules/service-context.server";++import { userPermissionsValidator } from "~/modules/users/users.models";+import {+ queueInviteResends,+ queuePermissionUpdates,+ queueUserDeactivations,+ selectUsersForBulkAction- } from "~/modules/users/users.server";++} from "~/modules/users/users.service";+import { getDatabaseClient } from "~/services/database.server";+import { decodeCursor } from "./cursor";+import { fetchListPage, getListDefinition } from "./list-registry/index.server";++import {++ bulkDissolveBatches,++ bulkReleaseBatches,++ bulkReleaseJobs++} from "./production-bulk-actions.server";+import {+ type AllMatchingRequest,+ type BulkActionStart,+ bulkActionServesList,+ getBulkActionMeta,+ hasListPermission,+ parseAllMatching,+ refreshingClientFactory,+ rowLimitRefusal,+ TABLE_JOBS_FULL_MESSAGE,+ type TableBulkActionKey,+ type TableJobClaims,+ tableJobBusyMessage,+ tableJobBusyRefusal+} from "./table-jobs";++const logger = getLogger("erp", "table-jobs");++/**+ * Every table job reads as the requesting user (`getUserScopedClient`), so RLS+ * applies as it does to a loader that keeps the RLS client. A loader that+ * bypasses RLS checks the same permission first (`hasListPermission`), so the+ * user client returns the same rows unless a policy is stricter than the+ * permission. A service-role read would rely on every list query to filter by+ * `companyId` itself, and the queries of the RLS-client lists were never+ * written or reviewed for that.+ */+async function canReadList(+ listKey: string,+ context: TableJobContext+): Promise<boolean> {+ const definition = getListDefinition(listKey);+ if (!definition) return false;++ const claims = await readClaims(context);+ if (!claims) return false;+ return hasListPermission(claims, definition.permission, context.companyId);+}++/** The user's claims for the company, read fresh as the user (not through+ * the permission cache, which can hold a revoked permission for an hour).+ * Null when the user has none. Throws when the read fails, so a job step+ * retries or fails instead of telling the user they lost access. */+async function readClaims({+ companyId,+ userId+}: TableJobContext): Promise<TableJobClaims | null> {+ const client = await getUserScopedClient(userId);+ const claims = await getClaims(client, userId, companyId);+ if (claims.error) {+ logger.error("Failed to read the claims of a table job's user", {+ companyId,+ userId,+ error: claims.error+ });+ throw new Error("Failed to read the claims of a table job's user");+ }+ if (claims.data === null) return null;+ return makePermissionsFromClaims(claims.data as Json[]) ?? null;+}++async function fetchPage(+ listKey: string,+ { companyId, userId }: TableJobContext,+ search: string,+ page: { cursor: string | null; limit: number; forExport?: boolean }+) {+ const definition = getListDefinition(listKey);+ if (!definition) {+ return { rows: [], nextCursor: null, error: `Unknown list "${listKey}"` };+ }+ const params = new URLSearchParams(search);+ // The job pages with its own cursor; a cursor in the saved search is stale.+ params.delete("after");++ // One token per page: it lives five minutes, and a page is one query.+ const client = await getUserScopedClient(userId);+ const result = await fetchListPage(definition, client, companyId, params, {+ limit: page.limit,+ cursor: decodeCursor(page.cursor)+ });+ if (result.error || !page.forExport || !definition.exportRows) {+ return {+ rows: result.rows,+ nextCursor: result.nextCursor,+ error: result.error ?? undefined+ };+ }+ // The values the list's loader adds per page, so the export's columns+ // match the table's. A failed lookup fails the page, not a blank column.+ try {+ return {+ rows: await definition.exportRows(result.rows, { client, companyId }),+ nextCursor: result.nextCursor+ };+ } catch (error) {+ logger.error("Failed to add the export values of a list page", {+ companyId,+ listKey,+ error+ });+ return { rows: [], nextCursor: null, error };+ }+}++type BulkActionRunContext = TableJobContext & {+ /** The user's client, signed again when its token is four minutes old:+ * RLS applies as it does to the action route. */+ getClient: ReturnType<typeof userClientFactory>;+ db: ReturnType<typeof getDatabaseClient>;+};++/** What a bulk action does to one chunk of ids (at most 100); throws only+ * when nothing ran. Its metadata is `BULK_ACTIONS` in `./table-jobs`.+ * `carry` is what the previous chunk of the same run returned. */+type BulkActionRun = (+ ids: string[],+ params: Record<string, unknown>,+ context: BulkActionRunContext,+ carry?: TableBulkActionCarry+) => Promise<TableBulkActionResult>;++/** The supplier → PO map a Jobs Release chunk carries to the next one. */+function carriedPurchaseOrders(+ carry: TableBulkActionCarry | undefined+): Record<string, string> {+ const value = carry?.purchaseOrdersBySupplierId;+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ return Object.fromEntries(+ Object.entries(value).filter(+ (entry): entry is [string, string] => typeof entry[1] === "string"+ )+ );+}++type RowProblem = { readableId: string; message: string };++/** The notification's line per failed row, then per row done with a warning. */+function problemLines(+ failed: RowProblem[],+ warnings: RowProblem[] = []+): Pick<TableBulkActionResult, "problems" | "problemCount"> {+ const lines = [+ ...failed.map((p) => `${p.readableId}: ${p.message}`),+ ...warnings.map((p) => `${p.readableId} (done): ${p.message}`)+ ];+ if (lines.length === 0) return {};+ return {+ problems: lines.slice(0, MAX_BULK_PROBLEMS),+ problemCount: lines.length+ };+}++function userClientFactory(userId: string) {+ return refreshingClientFactory(() => getUserScopedClient(userId));+}++/**+ * Each bulk action with a background path runs the same server function as+ * its action route, so the per-row checks are the same on both paths.+ */+const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {+ "items.update": async (ids, { field, value }, context) => {+ if (!isItemBulkUpdateField(field) || typeof value !== "string") {+ throw new Error("The item update is not valid");+ }+ const result = await bulkUpdateItems(+ await context.getClient(),+ context.db,+ {+ itemIds: ids,+ field,+ value,+ companyId: context.companyId,+ userId: context.userId+ }+ );+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "jobs.release": async (ids, _params, context, carry) => {- const result = await bulkReleaseJobs({- client: context.getClient,- db: context.db,++ const result = await bulkReleaseJobs(await jobServiceContext(context), {+ jobIds: ids,- companyId: context.companyId,- userId: context.userId,+ // A PO an earlier chunk created is this run's own, not a Draft to+ // choose from: the jobs after it go on the same PO.+ purchaseOrdersBySupplierId: carriedPurchaseOrders(carry)+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.released,+ skipped: result.skipped,+ failed: result.failed.length,+ // Released jobs with something left to fix (a PO that failed) are named+ // too: the in-request release shows them, and so must the notification.+ ...problemLines(result.failed, result.warnings),+ carry: { purchaseOrdersBySupplierId: result.purchaseOrdersBySupplierId }+ };+ },+ "jobs.delete": async (ids, _params, context) => {+ const result = await bulkDeleteJobs({+ client: await context.getClient(),+ jobIds: ids,+ companyId: context.companyId+ });+ return {+ done: result.deleted,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "purchase-orders.delete": async (ids, _params, context) => {+ const result = await bulkDeletePurchaseOrders(await context.getClient(), {+ purchaseOrderIds: ids,+ companyId: context.companyId+ });+ return {+ done: result.deleted,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "batches.release": async (ids, _params, context) => {- const result = await bulkReleaseBatches({- client: context.getClient,- db: context.db,- batchIds: ids,- companyId: context.companyId,- userId: context.userId++ const result = await bulkReleaseBatches(await jobServiceContext(context), {++ batchIds: ids+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed.length,+ ...problemLines(result.failed)+ };+ },+ "batches.dissolve": async (ids, _params, context) => {- const result = await bulkDissolveBatches({- client: context.getClient,- db: context.db,- batchIds: ids,- companyId: context.companyId,- userId: context.userId++ const result = await bulkDissolveBatches(await jobServiceContext(context), {++ batchIds: ids+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed.length,+ ...problemLines(result.failed)+ };+ },+ "users.deactivate": async (ids, { ip }, { companyId, userId }) => {+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "deactivate",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queueUserDeactivations({+ userIds: allowed,+ companyId,+ actorId: userId,+ ip: typeof ip === "string" ? ip : undefined+ });+ }+ // Done = queued: the user-admin job deactivates each user.+ return { done: allowed.length, skipped, failed: 0 };+ },+ "users.invite": async (ids, { location, ip }, { companyId, userId }) => {+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "invite",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queueInviteResends({+ userIds: allowed,+ companyId,+ location: typeof location === "string" ? location : "Unknown",+ ip: typeof ip === "string" ? ip : "127.0.0.1"+ });+ }+ return { done: allowed.length, skipped, failed: 0 };+ },+ "users.permissions": async (+ ids,+ { permissions, addOnly, ip },+ { companyId, userId }+ ) => {+ if (!isModulePermissions(permissions) || typeof addOnly !== "boolean") {+ throw new Error("The permission update is not valid");+ }+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "permissions",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queuePermissionUpdates({+ userIds: allowed,+ companyId,+ actorId: userId,+ permissions,+ addOnly,+ ip: typeof ip === "string" ? ip : undefined+ });+ }+ return { done: allowed.length, skipped, failed: 0 };+ }+};+++/**++ * The context the production service functions run in for a bulk-action job:++ * the system, on behalf of the requesting user. The job checked the user's++ * permissions before it ran (`canRunBulkAction`); the service role's client++ * never expires mid-run, as a five-minute user token would.++ */++async function jobServiceContext({ companyId, userId }: TableJobContext) {++ const company = await getCarbonServiceRole()++ .from("company")++ .select("companyGroupId")++ .eq("id", companyId)++ .single();++ if (company.error || !company.data?.companyGroupId) {++ logger.error("Failed to read the company of a table job", {++ companyId,++ error: company.error++ });++ throw new Error("Failed to read the company of a table job");++ }++ return systemContext({++ companyId,++ companyGroupId: company.data.companyGroupId,++ onBehalfOf: userId++ });++}+++/** The `permissions` param of `users.permissions`, checked again in the job:+ * a module name to its four switches, as the route validated it. */+function isModulePermissions(+ value: unknown+): value is Record<+ string,+ { view: boolean; create: boolean; update: boolean; delete: boolean }+> {+ return (+ value !== null &&+ typeof value === "object" &&+ Object.values(value).every(+ (permission) => userPermissionsValidator.safeParse(permission).success+ )+ );+}++/** Whether the user may still run the action on the list: an employee with+ * the list's view permission and the action's own permission, in a company+ * whose plan has the action's feature. */+async function canRunBulkAction(+ listKey: string,+ action: TableBulkAction,+ context: TableJobContext+): Promise<boolean> {+ const bulkAction = getBulkActionMeta(action.key);+ const list = getListDefinition(listKey);+ if (!bulkAction || !list || !bulkActionServesList(action.key, listKey)) {+ return false;+ }+ const claims = await readClaims(context);+ if (!claims) return false;+ if (+ !hasListPermission(claims, list.permission, context.companyId) ||+ !hasListPermission(claims, bulkAction.permission, context.companyId)+ ) {+ return false;+ }+ return bulkAction.feature+ ? companyHasFeature(getCarbonServiceRole(), context.companyId, {+ feature: bulkAction.feature+ })+ : true;+}++async function runBulkAction(+ action: TableBulkAction,+ ids: string[],+ context: TableJobContext,+ carry?: TableBulkActionCarry+): Promise<TableBulkActionResult> {+ const run = getBulkActionMeta(action.key)+ ? BULK_ACTION_RUNS[action.key as TableBulkActionKey]+ : undefined;+ if (!run) throw new Error(`Unknown bulk action "${action.key}"`);+ return run(+ ids,+ action.params,+ {+ ...context,+ getClient: userClientFactory(context.userId),+ db: getDatabaseClient()+ },+ carry+ );+}++/** The ERP side of the table jobs, handed to packages/jobs by api+/inngest.ts. */+export const tableJobHandlers: TableJobHandlers = {+ canReadList,+ fetchListPage: fetchPage,+ listIdColumn: (listKey) => getListDefinition(listKey)?.idColumn ?? "id",+ canRunBulkAction,+ runBulkAction+};++/** The list's matching rows as its header counts them: exact up to 1,000,+ * the planner's estimate above. Null when the count cannot be read. */+async function countMatchingRows(+ listKey: string,+ { companyId, userId }: TableJobContext,+ search: string+): Promise<number | null> {+ const definition = getListDefinition(listKey);+ if (!definition) return null;+ const params = new URLSearchParams(search);+ params.delete("after");+ const result = await fetchListPage(+ definition,+ await getUserScopedClient(userId),+ companyId,+ params,+ { limit: 1, cursor: null }+ );+ if (result.error) {+ logger.error("Failed to count the rows of a bulk action", {+ companyId,+ listKey,+ error: result.error+ });+ return null;+ }+ return result.count;+}++/**+ * Starts the background bulk action on every row of the list that matches its+ * URL search: the action routes call it when the request holds `allMatching`+ * in place of ids. The route has already checked the action's permission; this+ * checks the list's too, the action's row limit, takes the company's bulk lock+ * and sends the event.+ */+export function startTableBulkAction({+ allMatching,+ ...args+}: BulkRunArgs & {+ allMatching: AllMatchingRequest;+}): Promise<BulkActionStart> {+ return startBulkRun({+ ...args,+ listKey: allMatching.listKey,+ search: allMatching.search+ });+}++/**+ * Starts the background bulk action on rows the user selected, when there are+ * too many for one request (`fitsOneRequest`). The job acts on these ids and+ * reads no list pages; the per-row checks are the same as on the route.+ */+export function startSelectedBulkAction({+ listKey,+ ids,+ ...args+}: BulkRunArgs & { listKey: string; ids: string[] }): Promise<BulkActionStart> {+ return startBulkRun({ ...args, listKey, search: "", ids });+}++type BulkRunArgs = {+ companyId: string;+ userId: string;+ actionKey: TableBulkActionKey;+ params: Record<string, unknown>;+};++async function startBulkRun({+ companyId,+ userId,+ actionKey,+ params,+ listKey,+ search,+ ids+}: BulkRunArgs & {+ listKey: string;+ search: string;+ ids?: string[];+}): Promise<BulkActionStart> {+ const bulkAction = getBulkActionMeta(actionKey);+ if (+ !bulkAction ||+ !bulkActionServesList(actionKey, listKey) ||+ !getListDefinition(listKey)+ ) {+ logger.error("A bulk action was requested for a list it does not serve", {+ companyId,+ actionKey,+ listKey+ });+ return {+ success: false,+ message: "This action cannot run on this list",+ refusal: { code: "not-supported" }+ };+ }++ const context = { companyId, userId };+ let allowed: boolean;+ try {+ allowed = await canRunBulkAction(+ listKey,+ { key: actionKey, params },+ context+ );+ } catch {+ // `readClaims` logged it.+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };+ }+ if (!allowed) {+ return {+ success: false,+ message: "You do not have permission to do this on every matching row",+ refusal: { code: "no-permission" }+ };+ }++ if (bulkAction.maxRows !== undefined) {+ const matching = ids+ ? ids.length+ : await countMatchingRows(listKey, context, search);+ if (matching === null) {+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };+ }+ const refusal = rowLimitRefusal(bulkAction, matching);+ if (refusal) {+ return {+ success: false,+ message: refusal,+ refusal: { code: "row-limit", maxRows: bulkAction.maxRows }+ };+ }+ }++ const bulkActionId = nanoid();+ const lock = await takeTableJobLock("bulk", companyId, bulkActionId);+ if (lock.status === "busy") {+ return {+ success: false,+ message: tableJobBusyMessage("bulk", lock.retryAfterSeconds),+ refusal: tableJobBusyRefusal("bulk", lock.retryAfterSeconds)+ };+ }+ if (lock.status === "full") {+ logger.warn("Refused a table bulk action: every table-job slot is taken", {+ companyId,+ actionKey+ });+ return {+ success: false,+ message: TABLE_JOBS_FULL_MESSAGE,+ refusal: { code: "full" }+ };+ }+ if (lock.status === "unavailable") {+ // Fail-open: Inngest's per-company concurrency still runs one at a time.+ logger.warn("Starting a table bulk action without the Redis lock", {+ companyId,+ actionKey+ });+ }++ try {+ await trigger("table-bulk-action", {+ companyId,+ userId,+ bulkActionId,+ actionKey,+ actionLabel: bulkAction.label,+ params,+ listKey,+ search,+ ...(bulkAction.maxRows !== undefined+ ? { maxRows: bulkAction.maxRows }+ : {}),+ ...(bulkAction.idsPerStep !== undefined+ ? { idsPerStep: bulkAction.idsPerStep }+ : {}),+ ...(ids ? { ids } : {})+ });+ } catch (error) {+ logger.error("Failed to start a table bulk action", {+ companyId,+ actionKey,+ error+ });+ await releaseTableJobLock("bulk", companyId, bulkActionId);+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };+ }+ return { success: true, background: true };+}++/**+ * The `allMatching` branch every bulk action route shares: when the request+ * names every matching row (`allMatching` in a form field or a JSON body), it+ * starts the background job and answers what the route returns. Null when the+ * request names ids instead, so the route goes on with its own path.+ */+export async function startAllMatchingBulkAction(+ allMatching: unknown,+ args: {+ companyId: string;+ userId: string;+ actionKey: TableBulkActionKey;+ params: Record<string, unknown>;+ }+): Promise<BulkActionStart | null> {+ const request = parseAllMatching(allMatching);+ return request+ ? startTableBulkAction({ ...args, allMatching: request })+ : null;+}diff --cc apps/erp/test/job-release-logic.test.tsindex 7828cb3b2e,1aac58ae9b..bc86d1b560--- a/apps/erp/test/job-release-logic.test.ts+++ b/apps/erp/test/job-release-logic.test.ts@@@ -2,10 -2,15 +2,16 @@@// 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 { describe, expect, it, vi } from "vitest";++ // The models import the glossary, whose `msg` macro only runs compiled.+ vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })+ }));import {+ bulkReleaseStartingPurchaseOrders,jobReleaseProblems,+ materialsWithoutStorageUnit,makeMethodsMissingOperations,outsideOperationsNeedingPurchaseOrders,resolveOperationSupplier,@@@ -138,32 -150,106 +151,136 @@@ describe("jobReleaseProblems", () =>});});+describe("bulkReleaseStartingPurchaseOrders", () => {+ it("starts every supplier on a new PO and asks for a choice when Drafts exist", () => {+ const result = bulkReleaseStartingPurchaseOrders([+ { supplierId: "s1", draftPurchaseOrders: [] },+ { supplierId: "s2", draftPurchaseOrders: [{ id: "po-a" }] }+ ]);+ expect(result.purchaseOrders).toEqual({ s1: "new", s2: "new" });+ expect([...result.suppliersToChoose]).toEqual(["s2"]);+ });++ it("keeps the PO an earlier slice created, with no choice to make", () => {+ // Slice 1 created po-1 for s1; slice 2 now reads it as a Draft of s1.+ const result = bulkReleaseStartingPurchaseOrders(+ [{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-1" }] }],+ { s1: "po-1" }+ );+ expect(result.purchaseOrders).toEqual({ s1: "po-1" });+ expect(result.suppliersToChoose.size).toBe(0);+ });++ it("ignores a carried PO that is no longer a Draft of the supplier", () => {+ const result = bulkReleaseStartingPurchaseOrders(+ [{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-other" }] }],+ { s1: "po-1" }+ );+ expect(result.purchaseOrders).toEqual({ s1: "new" });+ expect([...result.suppliersToChoose]).toEqual(["s1"]);+ });+});+++ describe("jobReleaseProblems with a long BoM", () => {+ it("names the first five parts and counts the rest", () => {+ expect(+ jobReleaseProblems({+ manufacturingBlocked: false,+ missingAssemblies: [],+ outsideOperationsWithoutSupplier: [],+ materialsWithoutStorageUnit: Array.from({ length: 40 }, (_, i) => ({+ description: `PART-${i + 1}`+ }))+ })+ ).toEqual([+ "set a Pull From storage unit on PART-1; PART-2; PART-3; PART-4; PART-5; and 35 more"+ ]);+ });+ });++ describe("jobReleaseProblems: what the job page also refuses", () => {+ const base = {+ manufacturingBlocked: false,+ missingAssemblies: [],+ outsideOperationsWithoutSupplier: [],+ materialsWithoutStorageUnit: []+ };++ it("names a job with nothing to make and one that cannot complete to its asset", () => {+ expect(+ jobReleaseProblems({+ ...base,+ nothingToMake: true,+ makeToAssetError: "Make to Asset needs a serialized item or a quantity of one"+ })+ ).toEqual([+ "nothing to make",+ "Make to Asset needs a serialized item or a quantity of one"+ ]);+ });+ });++ describe("materialsWithoutStorageUnit", () => {+ const line = {+ methodType: "Pull from Inventory",+ itemType: "Part",+ storageUnitId: null,+ item: { itemTrackingType: "Inventory", readableIdWithRevision: "BOLT-10" }+ };++ it("names each part once, even when it is on several lines", () => {+ expect(+ materialsWithoutStorageUnit([+ { ...line, id: "jm-1", description: "Bolt" },+ { ...line, id: "jm-2", description: "Bolt" }+ ])+ ).toEqual([{ id: "jm-1", description: "BOLT-10" }]);+ });++ it("skips lines with a storage unit, built lines and non-stock items", () => {+ expect(+ materialsWithoutStorageUnit([+ { ...line, id: "jm-1", description: "Bolt", storageUnitId: "bin-1" },+ {+ ...line,+ id: "jm-2",+ description: "Bracket",+ methodType: "Make to Order"+ },+ {+ ...line,+ id: "jm-3",+ description: "Paint",+ item: { itemTrackingType: "Non-Inventory", readableIdWithRevision: "PAINT" }+ }+ ])+ ).toEqual([]);+ });++ it("falls back to the line description when the item has no readable id", () => {+ expect(+ materialsWithoutStorageUnit([+ { ...line, id: "jm-1", description: "Bolt", item: null }+ ])+ ).toEqual([{ id: "jm-1", description: "Bolt" }]);+ });+ });++ describe("makeToAssetReleaseError", () => {+ it("is null for a job that does not complete to an asset", () => {+ expect(makeToAssetReleaseError({ quantity: 3 })).toBeNull();+ });++ it("refuses an asset job on a sales order line, after the item rule", () => {+ expect(+ makeToAssetReleaseError({+ fixedAssetId: "fa-1",+ itemTrackingType: "Serial",+ salesOrderLineId: "sol-1"+ })+ ).toBe("A job linked to a sales order line cannot complete to a fixed asset");+ expect(+ makeToAssetReleaseError({ fixedAssetClassId: "fac-1", salesOrderLineId: "sol-1" })+ ).toBe("A job that completes to a fixed asset class needs a serialized item");+ });+ });diff --cc packages/jobs/AGENTS.mdindex 8b05714c29,6761c51f52..3391841a96--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@@ -70,20 -73,18 +73,21 @@@ pnpm --filter @carbon/jobs plan:compan| `send-push` | `carbon/send-push` (one per `pushSubscription` row, fanned out by `notify` for every notification, like in-app, when `isPushConfigured()`) | Send one Web Push with `web-push`; deletes the row on 404/410, logs a warning and keeps it on 401/403 (another VAPID key, or Apple refusing our token), retries 429/5xx, fails other 4xx (`pushDeliveryOutcome`) || `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic || `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers |- | `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls the `kanban-replenish` server function in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |+ | `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls `postingOrThrow("kanban-replenish", …)` in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |+ | `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, and the thumbnail. Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created || `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |+| `table-export` | `carbon/table-export` (`api+/table.export.ts`) | Background CSV export of a registered ERP list past 1,000 rows. One run per company. Steps of at most 10,000 rows write part files to `temp-staging`; `compose` streams them into `{companyId}/exports/{userId}/{exportId}.csv`. Stops at 100,000 rows or 200 MB. Step bodies in `src/table-jobs/export-run.ts` |+| `table-bulk-action` | `carbon/table-bulk-action` (`startTableBulkAction`, ERP `utils/table-jobs.server.ts`) | A bulk action on every matching row of a registered list, or on selected rows too many for one request (`ids` in the event, `startSelectedBulkAction`). One run per company, `retries: 0`. Collect steps store the ids (10,000 rows per step) in `temp-staging`; a selected-rows run stores its ids in one step instead. Apply steps run the action on one slice each, 100 ids per call, passing each call's `carry` to the next. Step bodies in `src/table-jobs/bulk-run.ts` || `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |## Safety Notes- `src/inngest/functions/events/queue.ts` archives unknown handler types to `pgmq.a_event_system`; a poison message must not wedge the drain.- `src/inngest/functions/events/embedding.ts` (`embedding-queue`) deletes embedded messages and archives (`pgmq.archive`) permanent failures (unknown table, no text) and any message read `MAX_READS` (5) times; other failures become visible again after the 300 s visibility timeout.- - Jobs that post or recalculate (`tasks/post-transaction.ts`, `tasks/recalculate.ts`, the Ramp families, the invoice automation in `src/invoicing/automate-invoice.ts`) call `@carbon/server-functions` directly, in-process — not over HTTP.+ - Jobs that post (`tasks/post-transaction.ts`, the Ramp families, the invoice automation in `src/invoicing/automate-invoice.ts`, `recurring-billing`, `revenue-recognition-proposal`, `kanban-level-check`, `tasks/recalculate.ts`) call `posting` / `postingOrThrow` (`@carbon/api/postings.server`): the ERP registers each posting at start (`apps/erp/app/modules/postings.server.ts`), in-process, not over HTTP. A posting with a `client` runs as the caller behind it, else as the system.- `src/inngest/functions/events/sync-tables.ts` is the import-light table→accounting-entity map. `subscriptions-mapping.test.ts` pins it to provider subscriptions/syncers.- `src/inngest/functions/integrations/ramp-sync.ts` owns step ids, ordering, result aggregation, and notification only; changing a family module must preserve that durable public shape.+- `src/table-jobs/` holds what both table jobs share: paging (`paging.ts`), the per-company Redis lock as Lua scripts (`lock.ts`), storage keys (`storage.ts`) and `notifyTableJobUser` with an Inngest event id per outcome (`notify.ts`). `packages/jobs` cannot import `~/modules`, so the ERP fills `TableJobHandlers` with `setTableJobHandlers` in `api+/inngest.ts`. See `.claude/rules/table-csv-export.md` and `.claude/rules/table-infinite-scroll.md`.- `src/workflows/actions/dispatcher.ts` is filled by `apps/erp/app/routes/api+/inngest.ts` with the canonical `callOperation` seam. Missing registration fails cleanly.- `src/workflows/engine/log.ts` redacts secret/token/password/header values before persisting step input.- Bare `tsx` scripts cannot rely on Vite's CJS/ESM interop. Keep runtime imports from packages without `"type":"module"` out of script dependency chains; type-only imports are safe.diff --cc packages/lib/src/events.tsindex d0a1d929be,80cece16e6..04c1360d47--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@@ -666,59 -668,77 +668,130 @@@ export type Events =};};+ // A table's CSV export past the browser's 1,000-row limit. The ERP route+ // (api+/table.export.ts) takes the per-company lock and sends it; the job+ // pages the list's registry query as the user and notifies them with the file.+ "carbon/table-export": {+ data: {+ companyId: string;+ userId: string;+ // The file's id, `{listKey}.{random}`: the file is+ // `{companyId}/exports/{userId}/{exportId}.csv` in temp-staging, served+ // to this user only by the ERP's export download route.+ exportId: string;+ // A key of the ERP's list registry (`utils/list-registry`).+ listKey: string;+ // The list's URL search (filters, sorts, search), with or without "?".+ search: string;+ // The visible columns in display order, with their translated headers.+ columns: Array<{ key: string; label: string }>;+ };+ };++ // A table's bulk action on every row that matches the list's URL search,+ // past the browser's 1,000-row limit. The ERP action route takes the+ // per-company lock and sends it; the job pages the list's ids as the user+ // (10,000 rows per step, stored in temp-staging), runs the action one slice+ // per step, 100 ids per call, and notifies the user with the counts.+ "carbon/table-bulk-action": {+ data: {+ companyId: string;+ userId: string;+ // The run's id; also the value of the per-company Redis lock.+ bulkActionId: string;+ // A key of the ERP's bulk actions (`utils/table-jobs.server.ts`).+ actionKey: string;+ // The action's English name for the notification ("Release jobs").+ actionLabel: string;+ // The action's own values, for example `{ field, value }`.+ params: Record<string, unknown>;+ // A key of the ERP's list registry (`utils/list-registry`).+ listKey: string;+ // The list's URL search (filters, sorts, search), with or without "?".+ search: string;+ // The most rows the run acts on (default 100,000). Jobs Release and+ // Batches Release stop at 2,000.+ maxRows?: number;+ // Ids per apply step (default 1,000); an action that does more per+ // row sets fewer, so one step stays well below 600 s.+ idsPerStep?: number;+ // The rows the user selected, when there are too many for one request.+ // The run acts on these ids and reads no list pages; `search` is "".+ ids?: string[];+ };+ };++ // Panel push: export one element's assets onto the item the push linked.+ "carbon/onshape-panel-sync": {+ data: {+ companyId: string;+ userId: string;+ itemId: string;+ documentId: string;+ wvm: "w" | "v";+ wvmId: string;+ elementId: string;+ elementKind: "partstudio" | "assembly" | "drawing";+ partId?: string;+ /** Non-default configuration to export; absent = default. */+ configuration?: string;+ assetBaseName?: string;+ /** Workspace pushes: the part microversion the review saw. */+ microversionId?: string;+ };+ };++ // One Onshape element's export onto an item (step.invoked by the backfill)+ "carbon/onshape-element-sync": {+ data: {+ companyId: string;+ userId: string;+ integrationId?: string;+ itemId: string;+ sourceDocument: "Part";+ documentId: string;+ versionId: string;+ sourceWvm?: "w" | "v";+ sourceMicroversionId?: string;+ modelElementId: string;+ modelElementKind: "partstudio" | "assembly";+ partId?: string | null;+ configuration?: string | null;+ drawingElementIds?: string[];+ assetBaseName?: string;+ };+ };++ // One released Onshape drawing's PDF onto an item (step.invoked by the backfill)+ "carbon/onshape-drawing-sync": {+ data: {+ companyId: string;+ userId: string;+ integrationId?: string;+ itemId: string;+ sourceDocument: "Part";+ documentId: string;+ versionId: string;+ drawingElementId: string;+ assetBaseName?: string;+ sourceWvm?: "w" | "v";+ };+ };++ // The assembler copies one finished Onshape translation into staging+ // (step.invoked by the element sync)+ "carbon/onshape-fetch": {+ data: {+ companyId: string;+ userId: string;+ integrationId?: string;+ translationId: string;+ documentId: string;+ foreignId: string;+ stagedPath: string;+ };+ };+// Onshape released-asset backfill / reconcile"carbon/onshape-backfill": {data: {diff --cc packages/locale/locales/de/erp.poindex cfeead82fc,de4704f5b9..cf3a42e2d7--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Ausstellungsdatummsgid "Issues"msgstr "Probleme"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Sie ist bald verfügbar. Wenden Sie sich an Carbon, um sie für Ihr Unternehmen einrichten zu lassen."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Es wird nicht mehr ausgeführt, bis Sie erneut eine Version veröffentlichen. Nichts wird gelöscht."diff --cc packages/locale/locales/en/erp.poindex 2b5306c10b,5eef1d1d13..6503131258--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Issued Datemsgid "Issues"msgstr "Issues"+msgid "It could not start. Try again."+msgstr "It could not start. Try again."++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "It is coming soon. Contact Carbon to have it set up for your company."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "It will stop running until you publish a version again. Nothing is deleted."diff --cc packages/locale/locales/es/erp.poindex c43b214a71,3e67a3a822..17499663b0--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Fecha de Emisiónmsgid "Issues"msgstr "Problemas"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Estará disponible pronto. Contacta con Carbon para que la configuren para tu empresa."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Se detendrá hasta que publique una Versión nuevamente. Nada se elimina."diff --cc packages/locale/locales/fr/erp.poindex e51356d291,8af07373f8..7ab495f8dc--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Date d'émissionmsgid "Issues"msgstr "Problèmes"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Elle sera bientôt disponible. Contactez Carbon pour la faire configurer pour votre entreprise."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Elle s'arrêtera d'être exécutée jusqu'à ce que vous publiiez une nouvelle version. Rien n'est supprimé."diff --cc packages/locale/locales/hi/erp.poindex da40c58d47,a84cd16a2f..6bf62d8a70--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "जारी तारीखmsgid "Issues"msgstr "समस्याएं"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "यह जल्द ही आ रहा है। इसे अपनी कंपनी के लिए सेट अप करवाने के लिए Carbon से संपर्क करें।"+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "यह तब तक चलना बंद कर देगा जब तक आप फिर से एक संस्करण प्रकाशित नहीं करते। कुछ भी हटाया नहीं गया है।"diff --cc packages/locale/locales/it/erp.poindex 367d4ffec1,dc8fa7789b..03ed366d4a--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Data di Emissionemsgid "Issues"msgstr "Problemi"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Sarà disponibile presto. Contatta Carbon per farla configurare per la tua azienda."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Si interromperà fino a quando non pubblichi di nuovo una versione. Nulla viene eliminato."diff --cc packages/locale/locales/ja/erp.poindex 07689dce11,25572248d4..89e45caeb4--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "発行日msgid "Issues"msgstr "問題"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "近日公開予定です。会社向けに設定するには Carbon にお問い合わせください。"+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "バージョンを再度公開するまで実行は停止します。削除されるものはありません。"diff --cc packages/locale/locales/ko/erp.poindex 4a50c86b00,21aa3ea4cd..48e15a4d8e--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "출고일msgid "Issues"msgstr "이슈"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "곧 제공될 예정입니다. 회사에 설정하려면 Carbon에 문의하세요."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "다시 버전을 게시할 때까지 실행이 중지됩니다. 삭제된 내용은 없습니다."diff --cc packages/locale/locales/pl/erp.poindex bf13fb6f29,2bc77be862..b4bb94fcdc--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Data wystawieniamsgid "Issues"msgstr "Problemy"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Wkrótce będzie dostępna. Skontaktuj się z Carbon, aby skonfigurować ją dla Twojej firmy."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "To przestanie działać, dopóki nie opublikujesz wersji ponownie. Nic nie jest usunięte."diff --cc packages/locale/locales/pt/erp.poindex a20d5cedb7,5171af5032..35e82c4b33--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Data de Emissãomsgid "Issues"msgstr "Problemas"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Ela estará disponível em breve. Entre em contato com a Carbon para configurá-la para sua empresa."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Ele parará de ser executado até que você publique uma versão novamente. Nada é excluído."diff --cc packages/locale/locales/ru/erp.poindex 0d28ab77ba,f86d12edcc..2d3eda3ad1--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Дата выпускаmsgid "Issues"msgstr "Проблемы"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Скоро она станет доступна. Свяжитесь с Carbon, чтобы её настроили для вашей компании."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Он перестанет работать, пока вы не опубликуете версию снова. Ничего не удаляется."diff --cc packages/locale/locales/tr/erp.poindex 2a3df2df98,d110ececf0..acbe90e467--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "Düzenlenme Tarihimsgid "Issues"msgstr "Sorunlar"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "Yakında kullanıma sunulacak. Şirketiniz için kurulması için Carbon ile iletişime geçin."+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "Yeniden bir sürüm yayınlayana kadar çalışmayı durdurur. Hiçbir şey silinmez."diff --cc packages/locale/locales/zh/erp.poindex 8a977bf7bc,7f83b9f0e6..09ea7ccac3--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@@ -11915,9 -12107,9 +12173,12 @@@ msgstr "签发日期msgid "Issues"msgstr "问题"+msgid "It could not start. Try again."+msgstr ""++ msgid "It is coming soon. Contact Carbon to have it set up for your company."+ msgstr "即将推出。请联系 Carbon 为您的公司进行设置。"+msgid "It will stop running until you publish a version again. Nothing is deleted."msgstr "它将停止运行,直到您再次发布版本。不会删除任何内容。"