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
feat:change notice approval rules and history CSV download
aashu445eea90ca8b
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex f02c115eb9..c488f9e2de 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3333,3 +3333,13 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf**Rule:** A writer that turns triggers off does both halves itself: a null-`rowId` row per `CHANGE_LOGGED_TABLES` entry, and a null-`ids` broadcast on every `REALTIME_TABLES` topic of the company, inside the same transaction. When a stale client list is suspected, compare the ids in `window.clientCache.getQueryData(["live", companyId, name])` with the database before reading code.**Applies to:** `packages/jobs/src/inngest/functions/tasks/company-restore.ts` (`wipeAndLoad`); any new job that sets `session_replication_role`.++## An entity in `audit.config.ts` records nothing until its tables have `events: true`++**Context:** Change notice history (the `changeOrder` audit entity) was empty in the History drawer even with audit logging on (2026-10-08).++**Problem:** `auditConfig.entities.changeOrder` listed its 4 tables, and `syncAuditSubscriptions` created AUDIT subscriptions for them. But `packages/database/src/event-system/attachments.ts` gave `changeOrder` only a statement broadcast and the 3 child tables no entry at all, so no async event trigger existed and nothing reached the event queue. Every check looked green: subscriptions present, sweeper succeeding, queue empty.++**Rule:** When you add an entity to `audit.config.ts`, give each of its tables `events: true` in `attachments.ts` and ship it with `pnpm --filter @carbon/database authz migration <name>`. To debug an empty audit log, first check `pg_trigger` for `trg_event_async_*` on the table.++**Applies to:** `packages/database/src/audit.config.ts`, `packages/database/src/event-system/attachments.ts`.diff --git a/.ai/plans/2026-10-08-change-notice-history-download-and-approvals.md b/.ai/plans/2026-10-08-change-notice-history-download-and-approvals.mdnew file mode 100644index 0000000000..1bb7dc076b--- /dev/null+++ b/.ai/plans/2026-10-08-change-notice-history-download-and-approvals.md@@ -0,0 +1,187 @@+# Change Notice History Download and Approval Rules — implementation plan++**Spec / source:** `.ai/specs/2026-10-08-change-notice-history-download-and-approvals.md`+**Branch:** `feat/download-changenotice-and-approval-rule`++> Note: the 2026-10-09 review refactor replaced the per-feature helpers named in Tasks 7–10 (`changeNoticeApprovalValidator`, `isChangeNoticeAwaitingApproval`, `getChangeNoticeApprovalContext`, `ChangeNoticeApprovalModal`) with the shared `@carbon/ee/approvals/document.server` helpers, `approvalDecisionValidator` and the `ApprovalDecision` modal. The spec is the current description.++## Progress+- [x] Task 1: Add the `changeOrder` approval document type (migration)+- [x] Task 2: Apply the migration and regenerate DB types+- [x] Task 3: Approval engine and models support `changeOrder`+- [x] Task 4: Dataset validator exception+- [x] Task 5: Settings → Approval Rules shows a Change Notices card+- [x] Task 6: Approval notifications route and describe change notices+- [x] Task 7: Change notice server helpers (pending lock, validator, path)+- [x] Task 8: Change notice routes (submit, approve/reject, cancel, delete, loader)+- [x] Task 9: Change notice UI (header buttons, modal, edit lock)+- [x] Task 10: History CSV download+- [x] Task 11: End-to-end verification (browser walk-through passed; added change notice audit event triggers found during the test)++## Dependencies+- Task 2 needs Task 1. Tasks 3–10 need Task 2 (generated enum type).+- Tasks 3, 4, 6 and 10 are independent of each other.+- Task 5 needs Task 3 (labels). Task 8 needs Tasks 3 and 7. Task 9 needs Task 8.+- Task 11 needs all.++---++## Task 1: Add the `changeOrder` approval document type (migration)++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/{timestamp}_change-order-approvals.sql`+- Copy from (precedent): `packages/database/supabase/migrations/20260310005407_supplier-approvals.sql:2-3,78-109`++**Steps:**+1. Run `pnpm db:migrate:new change-order-approvals`.+2. Write this SQL into the new file:++```sql+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'changeOrder';+COMMIT;++DROP VIEW IF EXISTS "approvalRequests";+CREATE OR REPLACE VIEW "approvalRequests" WITH (SECURITY_INVOKER=true) AS+SELECT+ ar."id", ar."documentType", ar."documentId", ar."status",+ ar."requestedBy", ar."requestedAt", ar."decisionBy", ar."decisionAt",+ ar."decisionNotes", ar."companyId", ar."createdAt",+ CASE+ WHEN ar."documentType" = 'purchaseOrder' THEN po."purchaseOrderId"+ WHEN ar."documentType" = 'qualityDocument' THEN qd."name"+ WHEN ar."documentType" = 'supplier' THEN sup."name"+ WHEN ar."documentType" = 'changeOrder' THEN co."changeOrderId"+ ELSE NULL+ END AS "documentReadableId",+ CASE+ WHEN ar."documentType" = 'purchaseOrder' THEN s."name"+ WHEN ar."documentType" = 'qualityDocument' THEN qd."description"+ WHEN ar."documentType" = 'supplier' THEN NULL+ WHEN ar."documentType" = 'changeOrder' THEN co."name"+ ELSE NULL+ END AS "documentDescription"+FROM "approvalRequest" ar+LEFT JOIN "purchaseOrder" po ON ar."documentType" = 'purchaseOrder' AND ar."documentId" = po."id"+LEFT JOIN "supplier" s ON po."supplierId" = s."id"+LEFT JOIN "qualityDocument" qd ON ar."documentType" = 'qualityDocument' AND ar."documentId" = qd."id"+LEFT JOIN "supplier" sup ON ar."documentType" = 'supplier' AND ar."documentId" = sup."id"+LEFT JOIN "changeOrder" co ON ar."documentType" = 'changeOrder' AND ar."documentId" = co."id" AND ar."companyId" = co."companyId";+```++**Verify:** file exists; `grep -c changeOrder` on it returns 5.+**Out of scope:** RLS, functions, triggers (approval logic lives in TypeScript).++## Task 2: Apply the migration and regenerate DB types++**Depends on:** 1+**Steps:**+1. Run `pnpm db:migrate`.+2. Run `pnpm db:types`.++**Verify:**+```bash+grep -n '"changeOrder"' packages/database/src/types.ts | grep -i approval | head+# Expected: approvalDocumentType union contains "changeOrder"+```+If `pnpm db:migrate` fails because the local DB is down, STOP and report.++## Task 3: Approval engine and models support `changeOrder`++**Depends on:** 2+**Files:**+- Modify: `packages/ee/src/approvals/models.ts` — add `"changeOrder"` to `approvalDocumentType`; add `changeOrder: "Change Notice"` to `approvalDocumentTypeLabel`.+- Modify: `packages/ee/src/approvals/service.ts` — `approveRequest`: add an `else if (documentType === "changeOrder")` branch after `supplier`. It updates `changeOrder` with `status: "Implementation"`, `updatedBy`, `updatedAt`, where `id = documentId`, `companyId = companyId`, `status = "Engineering Complete"`, returns `id`, and throws `"Failed to update change notice status - it may no longer be in 'Engineering Complete' state"` when no row comes back. `rejectRequest`: add a comment that `changeOrder` rejection does not change the status.++**Verify:** `pnpm --filter @carbon/ee typecheck` exits 0.++## Task 4: Dataset validator exception++**Depends on:** 2+**Files:** Modify `packages/database/src/datasets/validate.ts:251-256` — add `changeOrder: "the seed does not create change notice approval requests"` to the `enumValues("approvalDocumentType", {...})` map.+**Verify:** `pnpm db:check:datasets` passes (or reports only failures that exist on `main`; compare if it fails).++## Task 5: Settings → Approval Rules shows a Change Notices card++**Depends on:** 3+**Files:**+- Modify: `apps/erp/app/routes/x+/settings+/approval-rules.tsx` — `changeOrderRules` bucket; pass it to `ApprovalRules`.+- Modify: `apps/erp/app/routes/x+/settings+/approval-rules.new.tsx` — accept `typeParam === "changeOrder"`.+- Modify: `apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx` — new `changeOrderRules` prop and a 4th card "Change Notices", description "Require approval before change notices move to Implementation". Copy the Suppliers card (New Rule only when `changeOrderRules.length === 0`).+- Modify: `apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx` — replace `approvalDocumentTypeLabel[documentType]` and the delete-name ternary with a Lingui map: `{ purchaseOrder: t\`Purchase Order\`, qualityDocument: t\`Quality Document\`, supplier: t\`Supplier\`, changeOrder: t\`Change Notice\` }`; delete name is `t\`${label} approval rule\``.++**Verify:** `pnpm --filter erp typecheck` exits 0.++## Task 6: Approval notifications route and describe change notices++**Depends on:** 2+**Files:**+- Modify: `packages/jobs/src/inngest/functions/notifications/content.ts` — in the approval case, add a `changeOrder` branch before the generic return: read `changeOrder` (`changeOrderId, name, status`) by `id` + `companyId`; description `Change notice ${changeOrderId} ${docPhrase}`, reference `changeOrderId`, details Name + Status. Fallback description `Change notice ${docPhrase}`.+- Modify: `apps/erp/app/routes/api+/link.ts` — `if (documentType === "changeOrder") return path.to.changeNoticeDetails(documentId);`+- Modify: `apps/erp/app/components/Layout/Topbar/Notifications.tsx` — approval `to` by `documentType`: qualityDocument → `path.to.qualityDocument(id)`, supplier → `path.to.supplierApproval(id)`, changeOrder → `path.to.changeNoticeDetails(id)`, else `path.to.purchaseOrderDetails(id)`.+- Modify: `packages/notifications/src/index.ts:15` — drop "no approval flow in v1" from the comment.++**Verify:** `pnpm --filter @carbon/jobs typecheck` and `pnpm --filter erp typecheck` exit 0.++## Task 7: Change notice server helpers (pending lock, validator, path)++**Depends on:** 3+**Files:**+- Modify: `apps/erp/app/modules/items/items.models.ts` — add `changeNoticeApprovalValidator` (copy `qualityDocumentApprovalValidator`, `quality.models.ts:394-399`) and `changeNoticeAwaitingApprovalMessage = "This change notice is waiting for approval. Engineering changes are locked until it is approved or rejected."`.+- Modify: `apps/erp/app/utils/path.ts` — `changeNoticeApproval: (id) => generatePath(\`${x}/items/change-notice/${id}/approval\`)` (alphabetical, after `changeNoticeAffectedItem`).+- Modify: `apps/erp/app/modules/items/items.server.ts`:+ - `isChangeNoticeAwaitingApproval(changeNoticeId: string): Promise<boolean>` → `hasPendingApproval(getCarbonServiceRole(), "changeOrder", changeNoticeId)`.+ - `METHOD_LOCK_SOURCE` → `"changeOrder(id, status), item(revisionStatus)"`; `MethodLock` gets `changeNoticeId`; `resolveMethodLock` fills it.+ - `checkRevisionLock`: after the existing hard block, if `lock.changeNoticeStatus === "Engineering Complete"` and `lock.changeNoticeId` and the helper returns true → `{ ok: false, warn: false, message: changeNoticeAwaitingApprovalMessage }`.+ - `requireChangeNoticeEditable`: if scope is `engineering`, status is `Engineering Complete`, and the helper returns true → `{ error: { message: changeNoticeAwaitingApprovalMessage }, data: null }`.++**Verify:** `pnpm --filter erp typecheck` exits 0.+If `MethodLockRow` typing does not allow the extra `id`, widen that local type only.++## Task 8: Change notice routes++**Depends on:** 3, 7+**Files:**+- Modify: `apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx`:+ 1. If `fromStatus === "Engineering Complete" && toStatus === "Implementation"`: service role; pending → flash error "This change notice is already waiting for approval"; `isApprovalRequired(serviceRole, "changeOrder", companyId)` → `createApprovalRequest`, notify approvers (copy `quality-document+/update.tsx:58-104`), flash success "Submitted for approval", redirect. No status change.+ 2. If `toStatus === "Cancelled"`: after a successful update, set any pending `changeOrder` request for `id` to `Cancelled` with the service role (copy the update in `quality-document+/update.tsx:178-187`).+- Create: `apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx` — action only. Copy `quality-document+/$id.tsx:114-230`; use `update: "parts"`, `changeNoticeApprovalValidator`, `"changeOrder"`, redirect to `path.to.changeNoticeDetails(id)`. After an Approved result call `notifyChangeNoticeTransition({ client, event: changeNoticeStageEvent.Implementation, changeNoticeId: id, companyId, userId })`.+- Modify: `apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx` — before the delete, cancel pending `changeOrder` requests for `id` with the service role.+- Modify: `apps/erp/app/routes/x+/items+/change-notice+/$id.tsx` — loader returns `approval` from new `getChangeNoticeApprovalContext` (in `items.server.ts`, copy `quality-document+/$id.tsx:52-104`): `{ requestId, isPending, canApprove, isApprovalRequired, lastRejection: { notes, decisionAt } | null }`; only queries when status is `Engineering Complete`.++**Verify:** `pnpm --filter erp typecheck` exits 0.++## Task 9: Change notice UI++**Depends on:** 8+**Files:**+- Create: `apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeApprovalModal.tsx` — copy `modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx`; action `path.to.changeNoticeApproval(id)`; all copy Lingui; approve text "This moves the change notice to Implementation."; reject text "The change notice stays at Engineering Complete."+- Modify: `apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx` (precedent `QualityDocumentHeader.tsx:72-200`):+ - At Engineering Complete + `isApprovalRequired` + not pending: Advance label `t\`Submit for Approval\``.+ - Pending: hide Advance; show `Pending Approval` badge; if `canApprove`, Approve + Reject buttons opening the modal.+ - `lastRejection` at Engineering Complete and not pending: `Approval Rejected` badge with tooltip (notes + date).+- Modify: `$id.details.tsx`, `$id.$affectedId.details.tsx`, `ChangeNoticeExplorer.tsx` — `isDisabled ||= approval?.isPending`; affected-item disabled reason gets the pending message (Lingui).++**Verify:** `pnpm --filter erp typecheck` exits 0.++## Task 10: History CSV download++**Depends on:** 2+**Files:**+- Modify: `apps/erp/app/routes/api+/audit-log.ts` — if `all === "true"`, loop `getEntityAuditLog` with `limit: 500` and growing `offset` until a page has fewer than 500 rows or 10,000 entries are collected.+- Modify: `apps/erp/app/components/AuditLog/useAuditLog.tsx` — optional `downloadable?: boolean`, `downloadName?: string`; pass to the drawer.+- Modify: `apps/erp/app/components/AuditLog/AuditLogDrawer.tsx` — `AuditLogFeed` gets `onEntryCountChange?(count)`; the drawer keeps the count in state and, when `downloadable && count > 0`, renders a Download button in `DrawerHeader`. On click: `fetch('/api/audit-log?...&all=true')`, build rows (columns per spec: Date, Changed By via `usePeople()`, Action, Record via `getTableLabel`, Record ID, Field, Old Value, New Value), `downloadCsv(rows, \`${downloadName ?? entityType}-history-${YYYY-MM-DD}.csv\`, { fields })`. Precedent: `components/Table/components/Download.tsx`.+- Modify: `ChangeNoticeHeader.tsx` — pass `downloadable: true`, `downloadName: changeOrderId`.++**Verify:** `pnpm --filter erp typecheck` exits 0.+**Out of scope:** other `useAuditLog` callers.++## Task 11: End-to-end verification++**Depends on:** all+**Steps:**+1. `pnpm --filter erp typecheck`, `pnpm --filter @carbon/ee typecheck`, `pnpm --filter @carbon/jobs typecheck` — exit 0.+2. `pnpm exec biome check` on every changed file — no errors.+3. `pnpm lingui:extract` — new strings extracted.+4. `pnpm db:check:datasets`.+5. Run the ERP app and walk the spec's acceptance criteria (approval flow + download).diff --git a/.ai/specs/2026-10-08-change-notice-history-download-and-approvals.md b/.ai/specs/2026-10-08-change-notice-history-download-and-approvals.mdnew file mode 100644index 0000000000..64cd863763--- /dev/null+++ b/.ai/specs/2026-10-08-change-notice-history-download-and-approvals.md@@ -0,0 +1,247 @@+# Change Notice History Download and Approval Rules++> Status: implemented+> Author: Aashu+> Date: 2026-10-08++## TLDR++- The History drawer of a change notice gets a **Download** button. It exports the full history as a CSV file.+- Change notices become an **approval document type**. An admin sets a rule in Settings → Approval Rules.+- When a rule is on, **Engineering Complete → Implementation** needs approval. "Advance" becomes "Submit for Approval".+- While approval is pending, the change notice stays at Engineering Complete and engineering edits are locked.+- Approve moves the change notice to Implementation. Reject keeps it at Engineering Complete, with the approver's notes.+- No new change notice status. No change to other History drawers or to other approval document types.++## Overview diagram++```mermaid+flowchart LR+ EC["Engineering Complete"] -->|"no rule"| IMP["Implementation"]+ EC -->|"rule on: Submit for Approval"| PEND["Pending approval<br/>(status stays Engineering Complete,<br/>engineering edits locked)"]:::new+ PEND -->|"Approve"| IMP+ PEND -->|"Reject + notes"| EC+ PEND -->|"Cancel change notice"| CAN["Cancelled<br/>(request cancelled)"]+ HIST["History drawer"] -->|"Download"| CSV["{changeOrderId}-history.csv"]:::new+ classDef new stroke-dasharray:4 3+```++## Problem Statement++1. **No export of change notice history.** The History drawer shows the audit log of one change notice. It shows only the newest 50 entries (`apps/erp/app/routes/api+/audit-log.ts:60`) and has no export. A quality or engineering user cannot give an auditor a record of who changed what on a change notice.+2. **No approval step for change notices.** Any user with `update` on `parts` can advance a change notice to Implementation. Purchase orders, quality documents and suppliers already have approval rules (`packages/ee/src/approvals/`). Change notices do not (`packages/notifications/src/index.ts:15` says "no approval flow in v1").++## Proposed Solution++### Part A: History download++1. `useAuditLog` and `AuditLogDrawer` get two optional props: `downloadable` (boolean) and `downloadName` (string, used in the file name). The default is off. `ChangeNoticeHeader` and the 5 item headers (part, tool, material, consumable, service) turn it on.+2. When `downloadable` is on and the feed shows at least one entry, the drawer header shows a **Download** button.+3. On click, the drawer fetches `/api/audit-log?entityType&entityId&companyId&all=true`.+4. The loader in `api+/audit-log.ts` reads `all=true`. It then pages through `getEntityAuditLog` in pages of 500, up to a cap of 10,000 entries. Without `all`, the loader keeps the current `limit: 50`.+5. The client builds one CSV row for each changed field (`buildAuditLogCsvRows`, `components/AuditLog/utils.ts`) and calls `downloadCsv` from `@carbon/files/csv`. This is the same encoder the shared Table export uses. It strips formula prefixes.+6. The file name is `{downloadName}-history-{YYYY-MM-DD}.csv`, for example `CN-000042-history-2026-10-08.csv`.++CSV columns (headers are Lingui-translated on the client):++| Column | Source |+|--------|--------|+| Date | `createdAt` (ISO 8601, UTC) |+| Changed By | `actorId` mapped to a name with `usePeople()`; `system` → "System"; unknown id → the raw id |+| Action | `operation` → Created / Updated / Deleted (same labels as the drawer) |+| Record | `getTableLabel(tableName)` (for example "Affected Item") |+| Record ID | `recordId` |+| Field | the diff key |+| Old Value | `diff[field].old` |+| New Value | `diff[field].new` |++Value rules: `null` and `undefined` become an empty cell. A string stays as it is. A number or boolean becomes its text. An object or array becomes JSON. Fields in `skipFields` are already removed by `sanitizeAuditEntries`. An entry with an empty diff gives one row with an empty Field, Old Value and New Value.++Access is the same as the drawer: `view: "settings"`, the `AUDIT_LOG` plan feature, and audit logging enabled for the company. The drawer already hides its feed in each of these cases, so the button does not show.++### Part B: Change notice approvals++#### Settings++1. Add `changeOrder` to `approvalDocumentType` (DB enum and `packages/ee/src/approvals/models.ts`). The label is "Change Notice".+2. `changeOrder` is amount-less. It is not in `approvalDocumentTypesWithAmounts`. A company has at most one change notice rule, the same as quality documents.+3. Settings → Approval Rules shows a fourth card, **Change Notices**, after Suppliers.++#### Submit (Engineering Complete → Implementation)++In `routes/x+/items+/change-notice+/$id.status.tsx`, if `fromStatus` is `Engineering Complete` and `toStatus` is `Implementation`:++1. Get the service role client.+2. If `hasPendingApproval(serviceRole, "changeOrder", id)` is true, flash "This change notice is already waiting for approval" and redirect.+3. If `isApprovalRequired(serviceRole, "changeOrder", companyId)` is false, continue with the current transition code.+4. Otherwise call `createApprovalRequest` with `documentType: "changeOrder"`, `documentId: id` and `requestedBy: userId`.+5. Trigger `notify` with `ApprovalRequested` to the rule's approvers (`getApproverUserIdsForRule`).+6. Do not change the status. Flash "Submitted for approval" and redirect.++#### Approve and reject++New route `routes/x+/items+/change-notice+/$id.approval.tsx` (action only, `update: "parts"`). It copies the quality document action (`routes/x+/quality-document+/$id.tsx:114-230`):++1. Validate `{ approvalRequestId, decision, notes }`.+2. Read the latest request for the change notice with the service role. Prove its id and `companyId` match the caller.+3. Check `canApproveRequest`. If false, flash an error.+4. Call `approveRequest` or `rejectRequest` with `getDatabaseClient()`.+5. Notify the requester with `ApprovalApproved` or `ApprovalRejected`, if the requester is not the approver.+6. If the decision is Approved, call `notifyChangeNoticeTransition` with the Implementation event. A normal advance to Implementation does the same.++Engine change in `packages/ee/src/approvals/service.ts`:++- `approveRequest`: add a `changeOrder` branch. It updates `changeOrder` to `status = 'Implementation'` where `id`, `companyId` match and `status = 'Engineering Complete'`. If no row changes, it throws, and the transaction rolls back.+- `rejectRequest`: no document change for `changeOrder` (the same as quality documents). The notes stay in `approvalRequest.decisionNotes`.++#### Pending requests when the change notice closes++- Engineering Complete → Cancelled: `$id.status.tsx` sets any pending `changeOrder` request to `Cancelled` with the service role. Any user with `update` on `parts` can cancel, the same as archiving a quality document (`quality-document+/update.tsx:144-190`). Do not use `cancelApprovalRequest`: it lets only the requester cancel (`service.ts:309`).+- Delete: `delete.$id.tsx` cancels any pending request before the delete, so no orphan request stays in approver lists.++#### Engineering edit lock while pending++Engineering edits are locked while a request is pending. Action tasks (workflow scope) stay editable.++- Server, `apps/erp/app/modules/items/items.server.ts`:+ - One helper, `getChangeNoticeEngineeringLock(changeNoticeId, status)`, returns the lock message or null: the closed / Implementation message from `canEditChangeNoticeEngineering`, else, at `Engineering Complete`, the waiting-for-approval message when `hasPendingApproval` (service role, because `approvalRequest` has no RLS policies) is true.+ - `requireChangeNoticeEditable` (scope `engineering`) and `checkRevisionLock` (`METHOD_LOCK_SOURCE` also selects `changeOrder(id)`) both call it.+ - The helper runs only when the status is `Engineering Complete`. Other statuses add no query.+- Message: "This change notice is waiting for approval. Engineering changes are locked until it is approved or rejected."+- UI: `$id.details.tsx`, `$id.$affectedId.details.tsx` and `ChangeNoticeExplorer.tsx` read `useChangeNoticeEngineeringLock` (`ui/ChangeNotice/lock-ui.tsx`), the UI half of the same helper, with a translated reason.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| What "history" means | The audit-log History drawer of one change notice | No other change notice history exists. User answer, Q1. |+| Export format | CSV, one row for each changed field | Readable in a spreadsheet. The archive JSONL is for machines. User answer, Q1. |+| Where the CSV is built | Client, with `downloadCsv` | Same as the Table export precedent (`Table/components/Download.tsx`). Lingui headers and `usePeople()` names work only on the client. |+| Size of the export | All entries in the live log, cap 10,000 | The live log keeps 30 days (365 in a controlled environment). One change notice stays far below the cap. |+| Download scope | Change notices and the 5 item pages, through an opt-in prop | User answer, Q5; item pages added 2026-10-09. Other drawers can turn it on with one prop later. |+| Download access | Same as the drawer | No new access path to audit data. User answer, Q4. |+| Gated transition | Engineering Complete → Implementation | The engineering work is signed off before the shop floor acts on it. User answer, Q2. |+| Pending state | No new status; a pending request at Engineering Complete | No change to `changeOrderStatus`, the transition map or the progress bar. User answer, Q3. |+| Enum value name | `changeOrder` | Matches the DB table and the audit entity type. The UI label stays "Change Notice". |+| Amount tiers | None; at most one rule | A change notice has no money value. Same as quality documents. |+| Approve route | New `$id.approval.tsx` | The layout loader `$id.tsx` has no action today. The supplier precedent uses a separate `approval` route. |+| Approve permission | `update: "parts"` plus `canApproveRequest` | Same shape as quality documents (`update: "quality"` plus the rule check). |+| Lock scope while pending | Engineering scope only | The approver reviews the engineering content. Action tasks are workflow, not the content under review. |+| Withdraw a request | Not in v1 | The approver can reject, and the user can cancel the change notice. |+| Reopen after approval | A new advance needs a new approval | Implementation → Engineering Complete unlocks engineering edits, so the old approval no longer covers the content. |+| Card heading label | Lingui label map in the ERP card | `approvalDocumentTypeLabel` is plain English. New UI copy must be translatable. This also fixes the supplier delete-confirm name. |++## Data Model Changes++Two migrations. They add no table and no column.++- `20261008171101_change-order-audit-events.sql` (generated): sets `events: true` on `changeOrder`, `changeOrderActionTask`, `changeOrderAffectedItem` and `changeOrderSupersession`, so their changes reach the audit log.+- The approval document type migration below.++```sql+ALTER TYPE "approvalDocumentType" ADD VALUE 'changeOrder';+COMMIT;++-- Recreate "approvalRequests" from its current definition+-- (20260310005407_supplier-approvals.sql:78-109), with one new branch each:+-- documentReadableId: WHEN ar."documentType" = 'changeOrder' THEN co."changeOrderId"+-- documentDescription: WHEN ar."documentType" = 'changeOrder' THEN co."name"+-- LEFT JOIN "changeOrder" co+-- ON ar."documentType" = 'changeOrder'+-- AND ar."documentId" = co."id"+-- AND ar."companyId" = co."companyId"+```++After the migration:++- Regenerate the generated DB types: `packages/database/src/types.ts` and `packages/database/src/swagger-docs-schema.ts`.+- Add `changeOrder` to the `except` map of `approvalRequestType` in `packages/database/src/datasets/validate.ts:251-256`. The seed does not create a change notice approval request.++## API / Service Changes++| File | Change |+|------|--------|+| `packages/ee/src/approvals/models.ts` | Add `changeOrder` to `approvalDocumentType` and `approvalDocumentTypeLabel`. |+| `packages/ee/src/approvals/service.ts` | `approveRequest`: `changeOrder` branch (compare-and-swap Engineering Complete → Implementation). `rejectRequest`: no document change. |+| `apps/erp/app/routes/api+/audit-log.ts` | `all=true` pages through all entries, up to 10,000. A failed read answers 500, so the download shows an error instead of saving an empty file. |+| `apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx` | Submit for approval (`openApprovalRequests`), after checking the stored status is still Engineering Complete. Cancel any pending request on Cancelled, and on a plain advance past the gate (the rule was turned off after the request was opened). |+| `apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx` | New. Approve and reject action. |+| `apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx` | Cancel the pending request before the delete. |+| `packages/ee/src/approvals/document.server.ts` | New, `@carbon/ee/approvals/document.server`: `getDocumentApprovalState`, `openApprovalRequests`, `cancelPendingApprovals`, `decideApprovalRequest`. Shared by change notices, quality documents and suppliers. |+| `apps/erp/app/routes/x+/items+/change-notice+/$id.tsx` | Loader returns `approval: DocumentApprovalState` (`getDocumentApprovalState`), only at Engineering Complete. |+| `apps/erp/app/modules/items/items.server.ts` | `getChangeNoticeEngineeringLock`, used by `requireChangeNoticeEditable` and `checkRevisionLock`. |+| `apps/erp/app/modules/items/items.models.ts` | `changeNoticeAwaitingApprovalMessage`. The form validator is the shared `approvalDecisionValidator` (`@carbon/ee/approvals`). |+| `apps/erp/app/utils/path.ts` | `path.to.changeNoticeApproval(id)`. |+| `apps/erp/app/routes/x+/settings+/approval-rules.tsx`, `approval-rules.new.tsx` | `changeOrderRules` bucket; `changeOrder` in the `?type` allow-list. |+| `packages/jobs/.../notifications/content.ts` | `changeOrder` text for the 3 approval events, with the readable id. |+| `apps/erp/app/routes/api+/link.ts` | `changeOrder` → `path.to.changeNoticeDetails(id)`; `supplier` → `path.to.supplier(id)` (it pointed at the action-only approval route). |+| `packages/notifications/src/index.ts` | Remove the "no approval flow in v1" comment. |++## UI Changes++- **History drawer** (`AuditLogDrawer.tsx`, `useAuditLog.tsx`): opt-in Download button in the header, with a loading state while the fetch runs.+- **ChangeNoticeHeader.tsx**:+ - At Engineering Complete with a rule on and no pending request: the primary button reads **Submit for Approval**.+ - With a pending request: a **Pending Approval** badge. The Advance button does not show.+ - With a pending request and `canApprove`: **Approve** and **Reject** buttons. Each opens the shared `ApprovalDecision` modal (`~/components/Modals/ApprovalDecision`, notes field).+ - At Engineering Complete, if the latest request is Rejected: an **Approval Rejected** badge. Its tooltip shows the notes and the decision date.+ - Turn on `downloadable` and pass `changeOrderId` as `downloadName`.+- **Settings → Approval Rules** (`ApprovalRules.ee.tsx`): a **Change Notices** card. It shows "New Rule" only when no rule exists.+- **ApprovalRuleCard.ee.tsx**: heading and delete-confirm name come from a Lingui label map for all 4 types.+- **Topbar `Notifications.tsx`**: approval links go by `documentType`: purchase order, quality document, supplier, change notice.+- All new copy uses Lingui (`t`, `Trans`, `msg`).++## Acceptance Criteria++Download:++- [ ] A user with `view` on `settings`, on a plan with Audit Log and with audit logging on, opens History on a change notice with 120 entries. The Download button shows. The CSV has rows for all 120 entries, not 50.+- [ ] An Updated entry that changed `status` and `dueDate` gives 2 rows, with old and new values in their own columns.+- [ ] The Changed By column shows the person's name, and "System" for system changes.+- [ ] A value that starts with `=` opens in a spreadsheet as text, not as a formula.+- [ ] The History drawer on a customer or supplier shows no Download button. The 5 item pages do show it.+- [ ] With audit logging off, the drawer shows the "not enabled" state and no Download button.++Approvals:++- [ ] Settings → Approval Rules shows a Change Notices card. An admin creates one rule with an approver. A second "New Rule" button does not show.+- [ ] With no rule, Advance to Implementation works as it does today.+- [ ] With a rule on, a user clicks Submit for Approval at Engineering Complete. The status stays Engineering Complete, a Pending Approval badge shows, and the approver gets a notification that opens the change notice.+- [ ] While pending, adding an affected item or editing a BOM line of an affected item fails with the waiting-for-approval message. Editing an action task works.+- [ ] A second submit while pending fails with "already waiting for approval".+- [ ] A user who is not an approver sees no Approve or Reject button. A direct POST to the approval route fails.+- [ ] The approver approves. The change notice moves to Implementation, the requester gets ApprovalApproved, and the Implementation stage notification goes out.+- [ ] The approver rejects with notes. The status stays Engineering Complete, the Approval Rejected badge shows the notes, edits unlock, and a new submit creates a new request.+- [ ] Cancelling or deleting a change notice with a pending request sets that request to Cancelled.+- [ ] Reopen from Implementation, then advance again: a new approval is needed.+- [ ] `pnpm db:check:datasets` passes.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| History older than 30 days is not in the file (it is in the daily archives). | Low | Same window as the drawer. The archives stay downloadable in Settings → Audit Logs. |+| The pending check adds a service-role query to engineering mutations. | Low | It runs only when the status is Engineering Complete. |+| `ADD VALUE` in a transaction with later use of the value fails. | Med | Put `COMMIT;` after `ADD VALUE`, as `9034475a18` did for `supplier`. |+| An approver without `update` on `parts` cannot approve. | Low | Same shape as quality documents. The admin picks approvers who can edit parts. |+| A company with a rule has change notices pending at deploy time. | None | No request exists before the rule, and status values do not change. |++## Open Questions++> HARD STOP: Do not proceed with implementation until these are answered.++- [x] Q1. What does "download change notice history" export? — **Answer:** The History drawer of one change notice, as a CSV with all entries (not 50). Columns: when, who (name), action, record, field, old, new. One row for each changed field.+- [x] Q2. Which step needs approval? — **Answer:** Engineering Complete → Implementation, so the engineering work is signed off before the shop floor acts on it.+- [x] Q3. What does a pending change notice look like? — **Answer:** It stays at Engineering Complete with no new status. "Advance" becomes "Submit for Approval". While pending: a badge, engineering edits locked, Approve and Reject for approvers. Approve → Implementation. Reject → stays at Engineering Complete with notes.+- [x] Q4. Who can download? — **Answer:** The same users who can see the History drawer (`view` on `settings`, Audit Log plan feature, audit logging on).+- [x] Q5. Download on change notices only, or on all History drawers? — **Answer:** Change notices only, through an opt-in prop. The file covers the live log (30 days), the same as the drawer.++## Changelog++- 2026-10-08: Created. Q1–Q5 resolved with the user before writing.+- 2026-10-08: Implemented. The topbar approval link now also routes supplier requests correctly (same ternary).+- 2026-10-09: Quality documents and suppliers moved onto the same shared approval helpers (state, bulk open, bulk cancel with a requester-or-approver guard, decide), the shared modal and the shared validator. Their own context builders, modals, validators and `purchasing.server.ts` are deleted. Purchase orders keep their amount-tiered flow. Behavior change: a supplier approval request is refused when no supplier rule is enabled (it used to create a request with no approvers).+- 2026-10-09: Scope widened at the user's request: the History drawer on the 5 item pages (part, tool, material, consumable, service headers) also offers Download, file name `{readableIdWithRevision}-history-{date}.csv`. Other History drawers stay without it.+- 2026-10-09: Review refactor. The approval lifecycle moved into shared `@carbon/ee/approvals/document.server` helpers (`getDocumentApprovalState`, `openApprovalRequests`, `cancelPendingApprovals`, `decideApprovalRequest`), plus one `approvalDecisionValidator` and one `ApprovalDecision` modal. The change notice code is now wiring only. One engineering-lock helper backs both server guards, and one hook backs the UI.+- 2026-10-08: Browser test found that change notice history was always empty: the 4 change notice tables had no `events: true` in `packages/database/src/event-system/attachments.ts`, so no change reached the audit log. With the user's approval, this branch adds them (migration `20261008171101_change-order-audit-events.sql`, generated by `authz migration`). Browser walk-through passed.+- 2026-10-09: Self-review fixes. The status route checks the stored status before it opens a request, and cancels a stale pending request on a plain advance. The `all=true` audit-log read answers 500 on failure. The CSV rows come from the pure `buildAuditLogCsvRows` (unit-tested), which no longer re-filters skip fields (`sanitizeAuditEntries` already does). Supplier approval links (topbar and `api+/link.ts`) go to the supplier page.diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.mdindex 616dc217cd..15354ba4da 100644--- a/.claude/rules/audit-log-system.md+++ b/.claude/rules/audit-log-system.md@@ -175,7 +175,7 @@ than from config.- `apps/erp/app/routes/x+/settings+/audit-logs.tsx` — settings (enable/disable, download), syncs subscriptions.- `apps/erp/app/routes/x+/settings+/audit-logs.details.tsx` — full-screen filtered table (`getGlobalAuditLog`).-- `apps/erp/app/routes/api+/audit-log.ts` — entity-scoped entries endpoint.+- `apps/erp/app/routes/api+/audit-log.ts` — entity-scoped entries endpoint (50 newest; `all=true` pages through every live entry, capped at 10,000, for the drawer's opt-in CSV Download — `useAuditLog({ downloadable, downloadName })`, built client-side by `components/AuditLog/useAuditLogDownload.ts` with the pure row builder `buildAuditLogCsvRows` in `components/AuditLog/utils.ts`; a failed `all=true` read answers 500).## Key migrations (newest = truth)diff --git a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsxindex 923f428a8e..35b30030cf 100644--- a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx+++ b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx@@ -23,6 +23,7 @@ import {import { Trans } from "@lingui/react/macro";import { memo, useEffect, useRef, useState } from "react";import {+ LuDownload,LuFilePen,LuFilePlus,LuFileX,@@ -43,6 +44,7 @@ import {import { usePermissions, useRouteData } from "~/hooks";import { useResolved } from "~/hooks/useResolved";import { path } from "~/utils/path";+import { useAuditLogDownload } from "./useAuditLogDownload";import { isEmptyDiffValue } from "./utils";type AuditLogDrawerProps = {@@ -59,6 +61,10 @@ type AuditLogDrawerProps = {recordId?: string;/** When true, shows an upgrade prompt instead of fetching audit data */planRestricted?: boolean;+ /** When true, the header offers a CSV download of the full history. */+ downloadable?: boolean;+ /** Leads the downloaded file's name, e.g. the record's readable id. */+ downloadName?: string;};/** How long after a change its audit rows typically take to be written. */@@ -107,6 +113,8 @@ type AuditLogFeedProps = {* so an always-mounted feed refetches after the record is saved.*/refreshKey?: string | null;+ /** Reports how many entries are shown (null while nothing is loaded). */+ onEntryCountChange?: (count: number | null) => void;};/**@@ -121,7 +129,8 @@ export function AuditLogFeed({recordId,planRestricted = false,isActive,- refreshKey+ refreshKey,+ onEntryCountChange}: AuditLogFeedProps) {const fetcher = useFetcher<AuditLogFetcherData>();// Held in a ref so a re-render (a new fetcher object) never re-runs the@@ -199,6 +208,14 @@ export function AuditLogFeed({const hasCurrentData = Boolean(fetcher.data) && dataEntity === entityKey;const entries = hasCurrentData ? (fetcher.data?.entries ?? []) : [];const isLoading = !hasCurrentData;+ const shownCount =+ hasCurrentData && canViewHistory && !planRestricted && auditLogEnabled+ ? entries.length+ : null;++ useEffect(() => {+ onEntryCountChange?.(shownCount);+ }, [onEntryCountChange, shownCount]);if (!canViewHistory) {return (@@ -294,8 +311,19 @@ const AuditLogDrawer = memo(companyId,title,recordId,- planRestricted = false+ planRestricted = false,+ downloadable = false,+ downloadName}: AuditLogDrawerProps) => {+ const [entryCount, setEntryCount] = useState<number | null>(null);+ const { download, isDownloading } = useAuditLogDownload({+ entityType,+ entityId,+ companyId,+ recordId,+ downloadName+ });+return (<Draweropen={isOpen}@@ -305,10 +333,23 @@ const AuditLogDrawer = memo(><DrawerContent size="lg" position="left"><DrawerHeader>- <DrawerTitle className="flex items-center gap-2">- <LuHistory className="size-5" />- {title ?? <Trans>History</Trans>}- </DrawerTitle>+ <HStack className="justify-between pr-12">+ <DrawerTitle className="flex items-center gap-2">+ <LuHistory className="size-5" />+ {title ?? <Trans>History</Trans>}+ </DrawerTitle>+ {downloadable && (entryCount ?? 0) > 0 && (+ <Button+ variant="secondary"+ leftIcon={<LuDownload />}+ isLoading={isDownloading}+ isDisabled={isDownloading}+ onClick={download}+ >+ <Trans>Download</Trans>+ </Button>+ )}+ </HStack></DrawerHeader><DrawerBody><AuditLogFeed@@ -318,6 +359,7 @@ const AuditLogDrawer = memo(recordId={recordId}planRestricted={planRestricted}isActive={isOpen}+ onEntryCountChange={downloadable ? setEntryCount : undefined}/></DrawerBody></DrawerContent>diff --git a/apps/erp/app/components/AuditLog/useAuditLog.tsx b/apps/erp/app/components/AuditLog/useAuditLog.tsxindex 0a20d67c59..6cd7ed6e0b 100644--- a/apps/erp/app/components/AuditLog/useAuditLog.tsx+++ b/apps/erp/app/components/AuditLog/useAuditLog.tsx@@ -20,6 +20,10 @@ type UseAuditLogOptions = {variant: "dropdown" | "card-action";triggerLabel?: React.ReactNode;drawerTitle?: React.ReactNode;+ /** Opt-in: offer a CSV download of the full history in the drawer. */+ downloadable?: boolean;+ /** Leads the downloaded file's name, e.g. the record's readable id. */+ downloadName?: string;};/**@@ -37,7 +41,9 @@ export function useAuditLog({companyId,variant,triggerLabel = "History",- drawerTitle+ drawerTitle,+ downloadable,+ downloadName}: UseAuditLogOptions) {const disclosure = useDisclosure();const { isGated } = usePlanGate({ feature: "AUDIT_LOG" });@@ -69,6 +75,8 @@ export function useAuditLog({companyId={companyId}title={drawerTitle}planRestricted={isGated}+ downloadable={downloadable}+ downloadName={downloadName}/>);diff --git a/apps/erp/app/components/AuditLog/useAuditLogDownload.ts b/apps/erp/app/components/AuditLog/useAuditLogDownload.tsnew file mode 100644index 0000000000..9f63e66b48--- /dev/null+++ b/apps/erp/app/components/AuditLog/useAuditLogDownload.ts@@ -0,0 +1,96 @@+// 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 { getTableLabel } from "@carbon/database/audit.config";+import type { AuditLogEntry } from "@carbon/database/audit.types";+import { downloadCsv } from "@carbon/files/csv";+import { toast } from "@carbon/react";+import { getLocalTimeZone, today } from "@internationalized/date";+import { useLingui } from "@lingui/react/macro";+import { useCallback, useState } from "react";+import { usePeople } from "~/stores";+import { type AuditLogCsvLabels, buildAuditLogCsvRows } from "./utils";++type UseAuditLogDownloadOptions = {+ entityType: string;+ entityId: string;+ companyId: string;+ recordId?: string;+ /** Leads the file name, e.g. the record's readable id. */+ downloadName?: string;+};++/**+ * Downloads an entity's full audit history (everything still in the live log,+ * not just the 50 entries the drawer shows) as a CSV, one row per changed field.+ * Built on the client, like the Table export, so headers are translated and+ * actors resolve to names.+ */+export function useAuditLogDownload({+ entityType,+ entityId,+ companyId,+ recordId,+ downloadName+}: UseAuditLogDownloadOptions) {+ const { t } = useLingui();+ const [people] = usePeople();+ const [isDownloading, setIsDownloading] = useState(false);++ const download = useCallback(async () => {+ setIsDownloading(true);+ try {+ const params = new URLSearchParams({+ entityType,+ entityId,+ companyId,+ all: "true"+ });+ if (recordId) params.set("recordId", recordId);++ const response = await fetch(`/api/audit-log?${params.toString()}`);+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ const { entries } = (await response.json()) as {+ entries: AuditLogEntry[];+ };++ const labels: AuditLogCsvLabels = {+ columns: {+ date: t`Date`,+ changedBy: t`Changed By`,+ action: t`Action`,+ record: t`Record`,+ recordId: t`Record ID`,+ field: t`Field`,+ oldValue: t`Old Value`,+ newValue: t`New Value`+ },+ actions: {+ INSERT: t`Created`,+ UPDATE: t`Updated`,+ DELETE: t`Deleted`+ },+ system: t`System`+ };+ const rows = buildAuditLogCsvRows(entries, {+ labels,+ nameById: new Map(people.map((p) => [p.id, p.name.trim()])),+ getRecordLabel: getTableLabel+ });++ const name = (downloadName || entityType).replace(/[^\w.-]+/g, "-");+ downloadCsv(+ rows,+ `${name}-history-${today(getLocalTimeZone()).toString()}.csv`,+ { fields: Object.values(labels.columns) }+ );+ } catch {+ toast.error(t`Failed to download history`);+ } finally {+ setIsDownloading(false);+ }+ }, [companyId, downloadName, entityId, entityType, people, recordId, t]);++ return { download, isDownloading };+}diff --git a/apps/erp/app/components/AuditLog/utils.test.ts b/apps/erp/app/components/AuditLog/utils.test.tsnew file mode 100644index 0000000000..887362ec42--- /dev/null+++ b/apps/erp/app/components/AuditLog/utils.test.ts@@ -0,0 +1,121 @@+// 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 { AuditLogEntry } from "@carbon/database/audit.types";+import { describe, expect, it } from "vitest";+import { type AuditLogCsvLabels, buildAuditLogCsvRows } from "./utils";++const labels: AuditLogCsvLabels = {+ columns: {+ date: "Date",+ changedBy: "Changed By",+ action: "Action",+ record: "Record",+ recordId: "Record ID",+ field: "Field",+ oldValue: "Old Value",+ newValue: "New Value"+ },+ actions: { INSERT: "Created", UPDATE: "Updated", DELETE: "Deleted" },+ system: "System"+};++function entry(overrides: Partial<AuditLogEntry>): AuditLogEntry {+ return {+ id: "aud_1",+ companyId: "c1",+ tableName: "changeOrder",+ entityType: "changeOrder",+ entityId: "co_1",+ recordId: "co_1",+ operation: "UPDATE",+ actorId: "u1",+ diff: null,+ metadata: null,+ createdAt: "2026-10-08T10:00:00Z",+ ...overrides+ } as AuditLogEntry;+}++const build = (entries: AuditLogEntry[]) =>+ buildAuditLogCsvRows(entries, {+ labels,+ nameById: new Map([["u1", "Ada Lovelace"]]),+ getRecordLabel: (table) => `label:${table}`+ });++describe("buildAuditLogCsvRows", () => {+ it("gives one row per changed field", () => {+ const rows = build([+ entry({+ diff: {+ status: { old: "Start", new: "Engineering Complete" },+ dueDate: { old: null, new: "2026-10-20" }+ }+ })+ ]);++ expect(rows).toHaveLength(2);+ expect(rows[0]).toEqual({+ Date: "2026-10-08T10:00:00Z",+ "Changed By": "Ada Lovelace",+ Action: "Updated",+ Record: "label:changeOrder",+ "Record ID": "co_1",+ Field: "status",+ "Old Value": "Start",+ "New Value": "Engineering Complete"+ });+ expect(rows[1]).toMatchObject({+ Field: "dueDate",+ "Old Value": "",+ "New Value": "2026-10-20"+ });+ });++ it("gives one row with empty field cells when nothing changed", () => {+ const rows = build([entry({ operation: "DELETE", diff: {} })]);++ expect(rows).toEqual([+ expect.objectContaining({+ Action: "Deleted",+ Field: "",+ "Old Value": "",+ "New Value": ""+ })+ ]);+ });++ it("names system changes and keeps an unknown actor's id", () => {+ const rows = build([+ entry({ actorId: null, diff: {} }),+ entry({ actorId: "system", diff: {} }),+ entry({ actorId: "u-gone", diff: {} })+ ]);++ expect(rows.map((r) => r["Changed By"])).toEqual([+ "System",+ "System",+ "u-gone"+ ]);+ });++ it("writes numbers, booleans and objects as text", () => {+ const rows = build([+ entry({+ diff: {+ quantity: { old: 1, new: 2.5 },+ active: { old: false, new: true },+ tags: { old: [], new: ["a"] }+ }+ })+ ]);++ expect(rows.map((r) => [r["Old Value"], r["New Value"]])).toEqual([+ ["1", "2.5"],+ ["false", "true"],+ ["[]", '["a"]']+ ]);+ });+});diff --git a/apps/erp/app/components/AuditLog/utils.ts b/apps/erp/app/components/AuditLog/utils.tsindex d4d183e18c..463bee5639 100644--- a/apps/erp/app/components/AuditLog/utils.ts+++ b/apps/erp/app/components/AuditLog/utils.ts@@ -2,6 +2,8 @@// 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 { AuditLogEntry } from "@carbon/database/audit.types";+/*** Whether a diff side holds no real value (null/undefined, empty string,* empty object/array). Rendered as a muted "Empty" pill instead of the@@ -14,3 +16,81 @@ export function isEmptyDiffValue(value: unknown): boolean {if (typeof value === "object") return Object.keys(value).length === 0;return false;}++export type AuditLogCsvLabels = {+ columns: {+ date: string;+ changedBy: string;+ action: string;+ record: string;+ recordId: string;+ field: string;+ oldValue: string;+ newValue: string;+ };+ actions: Record<string, string>;+ system: string;+};++type AuditLogCsvEntry = Pick<+ AuditLogEntry,+ "createdAt" | "actorId" | "operation" | "tableName" | "recordId" | "diff"+>;++function toCsvCell(value: unknown): string {+ if (value === null || value === undefined) return "";+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") {+ return String(value);+ }+ return JSON.stringify(value);+}++/**+ * One CSV row per changed field of each entry (an entry with no changed field+ * gives one row with empty Field / Old / New). Skipped fields are already+ * removed server-side by `sanitizeAuditEntries`.+ */+export function buildAuditLogCsvRows(+ entries: AuditLogCsvEntry[],+ {+ labels,+ nameById,+ getRecordLabel+ }: {+ labels: AuditLogCsvLabels;+ nameById: Map<string, string>;+ getRecordLabel: (tableName: string) => string;+ }+): Record<string, string>[] {+ const { columns, actions, system } = labels;+ return entries.flatMap((entry) => {+ const base = {+ [columns.date]: entry.createdAt,+ [columns.changedBy]:+ !entry.actorId || entry.actorId === "system"+ ? system+ : (nameById.get(entry.actorId) ?? entry.actorId),+ [columns.action]: actions[entry.operation] ?? entry.operation,+ [columns.record]: getRecordLabel(entry.tableName),+ [columns.recordId]: entry.recordId ?? ""+ };+ const fields = Object.keys(entry.diff ?? {});+ if (fields.length === 0) {+ return [+ {+ ...base,+ [columns.field]: "",+ [columns.oldValue]: "",+ [columns.newValue]: ""+ }+ ];+ }+ return fields.map((field) => ({+ ...base,+ [columns.field]: field,+ [columns.oldValue]: toCsvCell(entry.diff?.[field]?.old),+ [columns.newValue]: toCsvCell(entry.diff?.[field]?.new)+ }));+ });+}diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 533cf40b09..7f11e31171 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -291,7 +291,11 @@ function GenericNotification({to={documentType === "qualityDocument"? path.to.qualityDocument(id)- : path.to.purchaseOrderDetails(id)+ : documentType === "supplier"+ ? path.to.supplier(id)+ : documentType === "changeOrder"+ ? path.to.changeNoticeDetails(id)+ : path.to.purchaseOrderDetails(id)}{...props}/>diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx b/apps/erp/app/components/Modals/ApprovalDecision/ApprovalDecision.tsxsimilarity index 55%rename from apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsxrename to apps/erp/app/components/Modals/ApprovalDecision/ApprovalDecision.tsxindex 1ea93ce21e..7f880114bf 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx+++ b/apps/erp/app/components/Modals/ApprovalDecision/ApprovalDecision.tsx@@ -2,7 +2,8 @@// 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 { ApprovalDecision } from "@carbon/ee/approvals";+import type { ApprovalDecision as Decision } from "@carbon/ee/approvals";+import { approvalDecisionValidator } from "@carbon/ee/approvals";import { Hidden, TextArea, ValidatedForm } from "@carbon/form";import {Button,@@ -14,63 +15,56 @@ import {ModalTitle} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useParams } from "react-router";-import { supplierApprovalDecisionValidator } from "~/modules/purchasing";-import { path } from "~/utils/path";+import type { ReactNode } from "react";+import type { FetcherWithComponents } from "react-router";-type SupplierApprovalModalProps = {- supplierName?: string;+type ApprovalDecisionProps = {+ /** The route action that decides the request (posts `approvalDecisionValidator`). */+ action: string;approvalRequestId: string;- decision: ApprovalDecision;+ decision: Decision;+ title: ReactNode;+ /** What this decision does to the document. */+ description: ReactNode;+ fetcher: FetcherWithComponents<unknown>;onClose: () => void;};-const SupplierApprovalModal = ({- supplierName,+const ApprovalDecision = ({+ action,approvalRequestId,decision,+ title,+ description,+ fetcher,onClose-}: SupplierApprovalModalProps) => {+}: ApprovalDecisionProps) => {const { t } = useLingui();- const { supplierId } = useParams();- if (!supplierId) throw new Error("supplierId not found");-const isApproving = decision === "Approved";return (<ModalopenonOpenChange={(open) => {- if (!open) {- onClose();- }+ if (!open) onClose();}}><ModalContent><ValidatedFormmethod="post"- validator={supplierApprovalDecisionValidator}- action={path.to.supplierApproval(supplierId)}+ validator={approvalDecisionValidator}+ action={action}onSubmit={onClose}- defaultValues={{- approvalRequestId,- decision,- notes: undefined- }}+ defaultValues={{ approvalRequestId, decision, notes: undefined }}+ fetcher={fetcher}><ModalHeader>- <ModalTitle>- {isApproving ? "Approve" : "Reject"} {supplierName}- </ModalTitle>+ <ModalTitle>{title}</ModalTitle></ModalHeader><ModalBody><Hidden name="approvalRequestId" /><Hidden name="decision" />- <p className="text-sm text-muted-foreground mb-4">- {isApproving- ? "Are you sure you want to approve this supplier? This will make it active."- : "Are you sure you want to reject this supplier?"}- </p>+ <p className="text-sm text-muted-foreground mb-4">{description}</p><TextAreaname="notes"label={t`Notes (optional)`}@@ -85,7 +79,7 @@ const SupplierApprovalModal = ({type="submit"variant={isApproving ? "primary" : "destructive"}>- {isApproving ? "Approve" : "Reject"}+ {isApproving ? t`Approve` : t`Reject`}</Button></ModalFooter></ValidatedForm>@@ -94,4 +88,4 @@ const SupplierApprovalModal = ({);};-export default SupplierApprovalModal;+export default ApprovalDecision;diff --git a/apps/erp/app/components/Modals/ApprovalDecision/index.ts b/apps/erp/app/components/Modals/ApprovalDecision/index.tsnew file mode 100644index 0000000000..ba69bce8d4--- /dev/null+++ b/apps/erp/app/components/Modals/ApprovalDecision/index.ts@@ -0,0 +1,7 @@+// 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 ApprovalDecision from "./ApprovalDecision";++export default ApprovalDecision;diff --git a/apps/erp/app/components/Modals/index.ts b/apps/erp/app/components/Modals/index.tsindex 1c5992f7ef..67abb747fb 100644--- a/apps/erp/app/components/Modals/index.ts+++ b/apps/erp/app/components/Modals/index.ts@@ -2,7 +2,8 @@// 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 ApprovalDecision from "./ApprovalDecision";import Confirm from "./Confirm";import ConfirmDelete from "./ConfirmDelete";-export { Confirm, ConfirmDelete };+export { ApprovalDecision, Confirm, ConfirmDelete };diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 32e02d8b83..dd77ebde66 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -90,7 +90,7 @@ Engineering-change-order (ECO) workflow — a **top-to-bottom**, affected-items-Change-order code follows the one-service/models/server-per-module convention — it lives in the module's canonical files, NOT separate `changeNotice.*` files: `items.service.ts` holds header CRUD + guarded stage transition + Types config + affected-item CRUD + the CO-owned Draft orchestration (`createChangeNoticeDraftMethod` / `addChangeNoticeAffectedItem` / `updateChangeNoticeAffectedItemChangeType` / cutover + `mintPlaceholderPart` + `getTopLevelProductsForItems` rollup) + the `diffMethod` pure engine + `getChangeNoticeDiff` authoring-diff wrapper + item↔CO traceability reads (`findChangeNoticesForItem`, linked-NCR reverse) + freeform action-task CRUD; `items.server.ts` holds the server-only release path (`applyChangeNotice` orchestration + `releaseAffectedItem` + notifications); `items.models.ts` holds the validators + state machine + `changeNoticeChangeTypes` + diff types. Non-server exports come through the Items barrel — import from `~/modules/items`; the server file is imported directly from `~/modules/items/items.server`.-**Approvals are not in V1.** No approval gate, reviewer/approval-task machinery, or toggle — stages advance freely; a CO reaches Done via `applyChangeNotice`. **Same-part parallel COs are now allowed** — the one-open-CO-per-part guard was dropped; `findOtherOpenChangeNoticesForItem` still exists but is advisory (no route/service enforces it).+**Approval gate (optional, `APPROVAL_RULES` plan feature).** When the company has an enabled `changeOrder` approval rule (Settings → Approval Rules → Change Notices; amount-less, at most one rule), `Engineering Complete → Implementation` is gated. The CO code is wiring only; the lifecycle lives in the shared `@carbon/ee/approvals/document.server` helpers. `$id.status.tsx` calls `openApprovalRequests` and notifies the approvers instead of moving the status. `$id.approval.tsx` calls `decideApprovalRequest`; approving runs the CAS `Engineering Complete → Implementation` inside `approveRequest`, rejecting leaves the status. Cancel and delete call `cancelPendingApprovals`. The `$id` loader returns `approval` (`getDocumentApprovalState`, only at Engineering Complete). While a request is pending, engineering-scope edits are locked: `getChangeNoticeEngineeringLock` (items.server.ts) backs both `requireChangeNoticeEditable` and `checkRevisionLock`, and `useChangeNoticeEngineeringLock` (`ui/ChangeNotice/lock-ui.tsx`) is the UI half. Workflow scope stays editable. Without a rule, stages advance freely; a CO reaches Done via `applyChangeNotice`. **Same-part parallel COs are now allowed** — the one-open-CO-per-part guard was dropped; `findOtherOpenChangeNoticesForItem` still exists but is advisory (no route/service enforces it).### Key CO conceptsdiff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex aca28c5c18..ff05ed4f00 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1198,6 +1198,11 @@ export function changeNoticeLockedMessage(status: string | null | undefined) {: "This change notice is closed, so its changes are read-only.";}+// Engineering content is also frozen while an approval request is pending: the+// approver signs off on exactly what they reviewed.+export const changeNoticeAwaitingApprovalMessage =+ "This change notice is waiting for approval. Engineering changes are locked until it is approved or rejected.";+// Workflow content — action tasks, assignee, dates, priority. Editable until closed.export function canEditChangeNoticeWorkflow(status: string | null | undefineddiff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex d44299f46a..ded0e8cf74 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -3,9 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { hasPendingApproval } from "@carbon/ee/approvals.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";@@ -24,11 +26,11 @@ import {upsertItemSupersession} from "~/modules/items";import { getCompanySettings } from "~/modules/settings";-import { requireUnlockedBulk } from "~/utils/lockedGuard.server";import type { plmReleaseControl } from "./items.models";import {canEditChangeNoticeEngineering,canEditChangeNoticeWorkflow,+ changeNoticeAwaitingApprovalMessage,changeNoticeLockedMessage,changeNoticeOpenStatuses,supersessionModes@@ -127,10 +129,15 @@ export function getLockVerdict(lock: {type MethodLock = {revisionStatus: ItemRevisionStatus | null;+ changeNoticeId: string | null;changeNoticeStatus: string | null;};-const NO_LOCK: MethodLock = { revisionStatus: null, changeNoticeStatus: 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@@ -138,7 +145,7 @@ const NO_LOCK: MethodLock = { revisionStatus: null, changeNoticeStatus: null };// 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(status), item(revisionStatus)";+const METHOD_LOCK_SOURCE = "changeOrder(id, status), item(revisionStatus)";const methodLockQueries = {makeMethod: ["makeMethod", METHOD_LOCK_SOURCE],@@ -193,12 +200,13 @@ async function resolveMethodLock(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: { status: string | null } | null;+ changeOrder: { id: string; status: string | null } | null;item: { revisionStatus: ItemRevisionStatus | null } | null;};@@ -267,15 +275,14 @@ export async function checkRevisionLock(// Hard block, independent of releaseControl — releaseControl only governs the// revision lock.- if (- lock.changeNoticeStatus &&- !canEditChangeNoticeEngineering(lock.changeNoticeStatus)- ) {- return {- ok: false,- warn: false,- message: changeNoticeLockedMessage(lock.changeNoticeStatus)- };+ const changeNoticeLock = lock.changeNoticeId+ ? await getChangeNoticeEngineeringLock(+ lock.changeNoticeId,+ lock.changeNoticeStatus+ )+ : null;+ if (changeNoticeLock) {+ return { ok: false, warn: false, message: changeNoticeLock };}return getLockVerdict({@@ -290,6 +297,30 @@ export async function checkRevisionLock(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(@@ -311,16 +342,15 @@ export async function requireChangeNoticeEditable(return { error: { message: "Could not find change notice" }, data: null };}- const canEdit =+ const { status } = existing.data;+ const message =args.scope === "engineering"- ? canEditChangeNoticeEngineering- : canEditChangeNoticeWorkflow;+ ? await getChangeNoticeEngineeringLock(args.changeNoticeId, status)+ : canEditChangeNoticeWorkflow(status)+ ? null+ : changeNoticeLockedMessage(status);- return requireUnlockedBulk({- statuses: [existing.data.status],- checkFn: (status) => !canEdit(status),- message: changeNoticeLockedMessage(existing.data.status)- });+ return message ? { error: { message }, data: null } : null;}// The inverse gate: an item owned by an open change notice must not get a manualdiff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeExplorer.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeExplorer.tsxindex 6297004910..4b046a87a1 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeExplorer.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeExplorer.tsx@@ -22,7 +22,6 @@ import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";import { Link, useFetcher, useParams } from "react-router";import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";import { useRouteData } from "~/hooks";-import { canEditChangeNoticeEngineering } from "~/modules/items";import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";import type { ItemType } from "~/modules/shared";import { useItems } from "~/stores";@@ -30,6 +29,7 @@ import { path } from "~/utils/path";import type { ChangeNotice } from "../../types";import AffectedItemForm from "./AffectedItemForm";import type { AffectedItemDraft } from "./affectedItem.types";+import { useChangeNoticeEngineeringLock } from "./lock-ui";// Explorer (left panel) of the change-order workspace — deliberately the same// layout as the Purchase Order explorer (PurchaseOrderExplorer /@@ -49,9 +49,7 @@ export default function ChangeNoticeExplorer() {}>(path.to.changeNotice(id));const affectedItems = routeData?.affectedItems ?? [];- const isDisabled = !canEditChangeNoticeEngineering(- routeData?.changeNotice?.status- );+ const { isDisabled } = useChangeNoticeEngineeringLock(id);const disclosure = useDisclosure();diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsxindex dd8fbe4674..7fbe65956b 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx@@ -2,6 +2,10 @@// 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 {+ ApprovalDecision,+ DocumentApprovalState+} from "@carbon/ee/approvals";import {Button,Copy,@@ -15,20 +19,28 @@ import {HStack,IconButton,MENU_ITEM_SHORTCUTS,+ Status,useDisclosure,VStack} from "@carbon/react";-import { useLingui } from "@lingui/react/macro";+import { formatDateTime } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { useState } from "react";import {+ LuCheckCheck,LuCircleCheck,LuCircleStop,+ LuClipboardCheck,LuEllipsisVertical,LuLoaderCircle,LuStepForward,- LuTrash+ LuTrash,+ LuX} from "react-icons/lu";import { Link, useFetcher, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";+import ApprovalDecisionModal from "~/components/Modals/ApprovalDecision";import Confirm from "~/components/Modals/Confirm/Confirm";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";@@ -46,15 +58,20 @@ const ChangeNoticeHeader = () => {const { id } = useParams();if (!id) throw new Error("id not found");- const routeData = useRouteData<{ changeNotice: ChangeNotice }>(- path.to.changeNotice(id)- );+ const routeData = useRouteData<{+ changeNotice: ChangeNotice;+ approval: DocumentApprovalState | null;+ }>(path.to.changeNotice(id));const status = routeData?.changeNotice?.status ?? "Draft";const { t } = useLingui();const permissions = usePermissions();const { company } = useUser();+ const { locale } = useLocale();const statusFetcher = useFetcher<{}>();+ const approvalFetcher = useFetcher<unknown>();+ const [approvalDecision, setApprovalDecision] =+ useState<ApprovalDecision | null>(null);const deleteModal = useDisclosure();const cancelModal = useDisclosure();@@ -62,9 +79,22 @@ const ChangeNoticeHeader = () => {entityType: "changeOrder",entityId: id,companyId: company.id,- variant: "dropdown"+ variant: "dropdown",+ downloadable: true,+ downloadName: routeData?.changeNotice?.changeOrderId ?? undefined});+ const approval = routeData?.approval;+ const pendingRequestId = approval?.pendingRequestId ?? null;+ // The loader only reads approval state at Engineering Complete, the gated+ // step: with a rule on, advancing submits for approval instead.+ const submitsForApproval = approval?.isRequired ?? false;+ const lastRejection =+ approval?.lastDecision?.status === "Rejected"+ ? approval.lastDecision+ : null;++ const changeOrderId = routeData?.changeNotice?.changeOrderId ?? "";const isLocked = isChangeNoticeLocked(status);const nextStatus =changeNoticeStatusTransitions[@@ -84,6 +114,30 @@ const ChangeNoticeHeader = () => {<span className={cn(isLocked && "line-through")}><ChangeNoticeStatus status={routeData?.changeNotice?.status} /></span>+ {pendingRequestId && (+ <Status color="yellow">+ <Trans>Pending Approval</Trans>+ </Status>+ )}+ {lastRejection && (+ <Status+ color="red"+ tooltip={+ <VStack spacing={1} className="max-w-xs">+ {lastRejection.decisionAt && (+ <span className="text-xs text-muted-foreground">+ {formatDateTime(lastRejection.decisionAt, locale)}+ </span>+ )}+ <span>+ {lastRejection.notes || t`No notes were given.`}+ </span>+ </VStack>+ }+ >+ <Trans>Approval Rejected</Trans>+ </Status>+ )}<Copy text={routeData?.changeNotice?.changeOrderId ?? ""} /><DropdownMenu><DropdownMenuTrigger asChild>@@ -181,29 +235,61 @@ const ChangeNoticeHeader = () => {{/* Implementation → Done is a release: it opens the review + confirmdialog (which carries the merge resolution), not a one-click stageadvance. The header only auto-advances the earlier stages. */}- {nextStatus && nextStatus !== "Done" && !isLocked && (- <statusFetcher.Form- method="post"- action={path.to.changeNoticeStatus(id)}- >- <input type="hidden" name="id" value={id} />- <input type="hidden" name="fromStatus" value={status} />- <input type="hidden" name="status" value={nextStatus} />+ {pendingRequestId && approval?.canApprove && (+ <><Button- type="submit"- rightIcon={<LuStepForward />}+ leftIcon={<LuCheckCheck />}variant="primary"- isDisabled={- statusFetcher.state !== "idle" ||- !permissions.can("update", "parts")- }- isLoading={statusFetcher.state !== "idle"}+ isDisabled={approvalFetcher.state !== "idle"}+ onClick={() => setApprovalDecision("Approved")}+ >+ {t`Approve`}+ </Button>+ <Button+ leftIcon={<LuX />}+ variant="destructive"+ isDisabled={approvalFetcher.state !== "idle"}+ onClick={() => setApprovalDecision("Rejected")}>- {t`Advance to ${nextStatus}`}+ {t`Reject`}</Button>- </statusFetcher.Form>+ </>)}+ {nextStatus &&+ nextStatus !== "Done" &&+ !isLocked &&+ !pendingRequestId && (+ <statusFetcher.Form+ method="post"+ action={path.to.changeNoticeStatus(id)}+ >+ <input type="hidden" name="id" value={id} />+ <input type="hidden" name="fromStatus" value={status} />+ <input type="hidden" name="status" value={nextStatus} />+ <Button+ type="submit"+ rightIcon={+ submitsForApproval ? (+ <LuClipboardCheck />+ ) : (+ <LuStepForward />+ )+ }+ variant="primary"+ isDisabled={+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "parts")+ }+ isLoading={statusFetcher.state !== "idle"}+ >+ {submitsForApproval+ ? t`Submit for Approval`+ : t`Advance to ${nextStatus}`}+ </Button>+ </statusFetcher.Form>+ )}+{status === "Implementation" && !isLocked && (<ButtonleftIcon={<LuCircleCheck />}@@ -246,6 +332,25 @@ const ChangeNoticeHeader = () => {<input type="hidden" name="status" value="Cancelled" /></Confirm>)}+ {approvalDecision && pendingRequestId && (+ <ApprovalDecisionModal+ action={path.to.changeNoticeApproval(id)}+ approvalRequestId={pendingRequestId}+ decision={approvalDecision}+ title={+ approvalDecision === "Approved"+ ? t`Approve ${changeOrderId}`+ : t`Reject ${changeOrderId}`+ }+ description={+ approvalDecision === "Approved"+ ? t`Are you sure you want to approve this change notice? This moves it to Implementation.`+ : t`Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again.`+ }+ fetcher={approvalFetcher}+ onClose={() => setApprovalDecision(null)}+ />+ )}{auditLogDrawer}</>);diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/lock-ui.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/lock-ui.tsxindex a6bd3ac930..4a78fa34db 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/lock-ui.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/lock-ui.tsx@@ -2,13 +2,17 @@// 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 { DocumentApprovalState } from "@carbon/ee/approvals";import { Tooltip, TooltipContent, TooltipTrigger } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";import { LuLock } from "react-icons/lu";import { Link } from "react-router";+import { useRouteData } from "~/hooks";import { path } from "~/utils/path";+import { canEditChangeNoticeEngineering } from "../../items.models";import type { ChangeNoticeForItem } from "../../items.service";+import type { ChangeNotice } from "../../types";// -----------------------------------------------------------------------------// Shared Change Notice lock UI.@@ -39,6 +43,30 @@ export function LockedHint({ reason }: { reason?: ReactNode }) {);}+// The engineering-edit lock of the open change notice workspace, read from the+// $id loader: closed, being implemented, or waiting for approval. The UI half of+// the server's getChangeNoticeEngineeringLock; `reason` is translated here+// because macros cannot run server-side.+export function useChangeNoticeEngineeringLock(changeNoticeId: string) {+ const { t } = useLingui();+ const routeData = useRouteData<{+ changeNotice: ChangeNotice;+ approval: DocumentApprovalState | null;+ }>(path.to.changeNotice(changeNoticeId));++ const status = routeData?.changeNotice?.status;+ const isPendingApproval = Boolean(routeData?.approval?.pendingRequestId);++ return {+ isDisabled: !canEditChangeNoticeEngineering(status) || isPendingApproval,+ reason: isPendingApproval+ ? t`This change notice is waiting for approval. Its changes are locked until it is approved or rejected.`+ : status === "Implementation"+ ? t`This change notice is being implemented, so its changes are locked. Reopen it to edit.`+ : t`This change notice is closed, so its changes are read-only.`+ };+}+export type ChangeNoticeDraftLock = {id: string;readableId: string;diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsxindex e84024a96d..0c5b1fb1c5 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx@@ -40,13 +40,6 @@ const ConsumableHeader = () => {const permissions = usePermissions();const { t } = useLingui();const deleteModal = useDisclosure();- const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({- entityType: "item",- entityId: itemId,- companyId: company.id,- variant: "dropdown"- });-const routeData = useRouteData<{consumableSummary: Consumable;supersession: Promise<{@@ -58,6 +51,16 @@ const ConsumableHeader = () => {} | null>;}>(path.to.consumable(itemId));+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,+ variant: "dropdown",+ downloadable: true,+ downloadName:+ routeData?.consumableSummary?.readableIdWithRevision ?? undefined+ });+const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionModediff --git a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsxindex fb27f1d049..e8ab16682a 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx@@ -40,13 +40,6 @@ const MaterialHeader = () => {const { company } = useUser();const permissions = usePermissions();const deleteModal = useDisclosure();- const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({- entityType: "item",- entityId: itemId,- companyId: company.id,- variant: "dropdown"- });-const routeData = useRouteData<{materialSummary: Material;supersession: Promise<{@@ -58,6 +51,16 @@ const MaterialHeader = () => {} | null>;}>(path.to.material(itemId));+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,+ variant: "dropdown",+ downloadable: true,+ downloadName:+ routeData?.materialSummary?.readableIdWithRevision ?? undefined+ });+const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionModediff --git a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsxindex a77558da66..e78a1802f7 100644--- a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx@@ -46,13 +46,6 @@ const PartHeader = () => {const permissions = usePermissions();const deleteModal = useDisclosure();const changeNoticeModal = useDisclosure();- const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({- entityType: "item",- entityId: itemId,- companyId: company.id,- variant: "dropdown"- });-const routeData = useRouteData<{partSummary: PartSummary;supersession: Promise<{@@ -64,6 +57,15 @@ const PartHeader = () => {} | null>;}>(path.to.part(itemId));+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,+ variant: "dropdown",+ downloadable: true,+ downloadName: routeData?.partSummary?.readableIdWithRevision ?? undefined+ });+const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionModediff --git a/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsxindex 58240fd466..5e5a5a46b5 100644--- a/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx@@ -40,13 +40,6 @@ const ServiceHeader = () => {const { company } = useUser();const permissions = usePermissions();const deleteModal = useDisclosure();- const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({- entityType: "item",- entityId: itemId,- companyId: company.id,- variant: "dropdown"- });-const routeData = useRouteData<{serviceSummary: Service;supersession: Promise<{@@ -58,6 +51,15 @@ const ServiceHeader = () => {} | null>;}>(path.to.service(itemId));+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,+ variant: "dropdown",+ downloadable: true,+ downloadName: routeData?.serviceSummary?.readableIdWithRevision ?? undefined+ });+const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionModediff --git a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsxindex f12e550893..d90eefa08f 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx@@ -46,13 +46,6 @@ const ToolHeader = () => {const permissions = usePermissions();const deleteModal = useDisclosure();const changeNoticeModal = useDisclosure();- const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({- entityType: "item",- entityId: itemId,- companyId: company.id,- variant: "dropdown"- });-const routeData = useRouteData<{toolSummary: Tool;supersession: Promise<{@@ -64,6 +57,15 @@ const ToolHeader = () => {} | null>;}>(path.to.tool(itemId));+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,+ variant: "dropdown",+ downloadable: true,+ downloadName: routeData?.toolSummary?.readableIdWithRevision ?? undefined+ });+const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionModediff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.mdindex 200b4cdb13..e497753f42 100644--- a/apps/erp/app/modules/purchasing/AGENTS.md+++ b/apps/erp/app/modules/purchasing/AGENTS.md@@ -69,7 +69,7 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing- `getPurchasingPlanning` — MRP-driven planned order view (RPC `get_purchasing_planning_grid`)- `applyPurchasingPlanningActions(db, { companyId, userId, actions })` — one Kysely transaction for a batch of planning actions on PO lines: the claim (Open → Actioned, returning each action's suggested quantity and date, which are what gets written), one `UPDATE … FROM (VALUES …)` for dates and one for quantities (`taxPairForQuantity` restates the tax pair), one `DELETE` for Cancels (Draft / Planned PO, nothing received or invoiced), then the refused claims are released. Returns `{ applied, alreadyApplied, refused, failed }`- `updatePurchaseOrderLineSchedule(client, db, args)` — planning's single-line write (the order drawer's inline edit): `requiredDate` or `purchaseQuantity` on a line of a Draft / Planned PO, the guard inside the UPDATE; returns `{ updated, error }`-- `getSupplierApprovalContext` — reads approval workflow state+- Supplier approval — wiring only: the `$supplierId` loader reads `getDocumentApprovalState` and `$supplierId.approval.tsx` uses `openApprovalRequests` / `decideApprovalRequest` (`@carbon/ee/approvals/document.server`)- `getPurchasingRFQ` / `getPurchasingRFQs` / `upsertPurchasingRFQ` — RFQ management- `getSupplierQuotesForComparison` — side-by-side quote comparison- `getDefaultAttachmentsForPO` — default document attachments for PO creationdiff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex 6351597933..1b6e687305 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -406,14 +406,6 @@ export const supplierTaxValidator = z});-export const supplierApprovalDecisionValidator = z.object({- approvalRequestId: z- .string()- .min(1, { message: "Approval request is required" }),- decision: z.enum(["Approved", "Rejected"]),- notes: zfd.text(z.string().optional())-});-export const supplierContactValidator = z.object({id: zfd.text(z.string().optional()),...contact,diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.tsdeleted file mode 100644index ff0b23f619..0000000000--- a/apps/erp/app/modules/purchasing/purchasing.server.ts+++ /dev/null@@ -1,92 +0,0 @@-// 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 { Database } from "@carbon/database";-import {- canApproveRequest,- getLatestApprovalRequestForDocument-} from "@carbon/ee/approvals.server";-import type { SupabaseClient } from "@supabase/supabase-js";--/**- * Server-only purchasing helpers. Lives in a `.server.ts` (NOT the barrel-exported- * `purchasing.service.ts`) because it imports the commercial, server-only approval- * engine `@carbon/ee/approvals.server`; a `.server` import reaching the client- * graph via the module barrel is rejected by the React Router build.- */--type ApprovalContext = {- approvalRequest: { id: string } | null;- canApprove: boolean;- decision: {- status: "Approved" | "Rejected";- decisionBy: string;- decisionAt: string;- } | null;-};--export async function getSupplierApprovalContext(- serviceRole: SupabaseClient<Database>,- supplierId: string,- status: string | null,- companyId: string,- userId: string-): Promise<ApprovalContext> {- const latest = await getLatestApprovalRequestForDocument(- serviceRole,- "supplier",- supplierId- );-- const req = latest.data;-- const canApprove = await canApproveRequest(- serviceRole,- {- amount: req?.amount ?? null,- documentType: "supplier",- companyId- },- userId- );-- // Look for the latest terminal decision (Approved or Rejected)- let decision: ApprovalContext["decision"] = null;- const terminalRequest = await serviceRole- .from("approvalRequest")- .select("status, decisionBy, decisionAt")- .eq("documentType", "supplier")- .eq("documentId", supplierId)- .in("status", ["Approved", "Rejected"])- .order("decisionAt", { ascending: false })- .limit(1)- .maybeSingle();-- if (- terminalRequest.data?.decisionBy &&- terminalRequest.data?.decisionAt &&- (terminalRequest.data.status === "Approved" ||- terminalRequest.data.status === "Rejected")- ) {- decision = {- status: terminalRequest.data.status,- decisionBy: terminalRequest.data.decisionBy,- decisionAt: terminalRequest.data.decisionAt- };- }-- if (!req || req.status !== "Pending" || !req.requestedBy || !req.id) {- return {- approvalRequest: null,- canApprove,- decision- };- }-- return {- approvalRequest: { id: req.id },- canApprove,- decision- };-}diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsxindex fc2c5c3e62..8244938351 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx@@ -2,7 +2,10 @@// 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 { ApprovalDecision } from "@carbon/ee/approvals";+import type {+ ApprovalDecision,+ DocumentApprovalState+} from "@carbon/ee/approvals";import { ValidatedForm } from "@carbon/form";import {Button,@@ -53,7 +56,10 @@ import { useAuditLog } from "~/components/AuditLog";import { Enumerable } from "~/components/Enumerable";import { Tags } from "~/components/Form";import { useSupplierTypes } from "~/components/Form/SupplierType";-import { ConfirmDelete } from "~/components/Modals";+import {+ ApprovalDecision as ApprovalDecisionModal,+ ConfirmDelete+} from "~/components/Modals";import {usePermissions,useRouteData,@@ -64,7 +70,6 @@ import type { SupplierDetail } from "~/modules/purchasing";import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";import type { action } from "~/routes/x+/settings+/tags";import { path } from "~/utils/path";-import SupplierApprovalModal from "./SupplierApprovalModal";const SupplierHeader = () => {const { supplierId } = useParams();@@ -83,13 +88,7 @@ const SupplierHeader = () => {const routeData = useRouteData<{supplier: SupplierDetail;tags: { name: string }[];- approvalRequest: { id: string } | null;- canApprove: boolean;- decision: {- status: "Approved" | "Rejected";- decisionBy: string;- decisionAt: string;- } | null;+ approval: DocumentApprovalState;supplierTax: { taxExempt: boolean } | null;}>(path.to.supplier(supplierId));@@ -107,9 +106,11 @@ const SupplierHeader = () => {const status = routeData?.supplier?.status ?? null;const isPending = status === "Pending";- const approvalRequestId = routeData?.approvalRequest?.id;+ const approvalRequestId = routeData?.approval?.pendingRequestId;const hasApprovalRequest = !!approvalRequestId;- const canApprove = routeData?.canApprove ?? false;+ const canApprove = routeData?.approval?.canApprove ?? false;+ const decision = routeData?.approval?.lastDecision;+ const approvalFetcher = useFetcher();const submitRequestApproval = () => {const formData = new FormData();@@ -293,58 +294,46 @@ const SupplierHeader = () => {)}</CardAttributeValue></CardAttribute>- {routeData?.decision?.status === "Approved" &&- status === "Active" && (- <>- <CardAttribute>- <CardAttributeLabel>- <Trans>Approved By</Trans>- </CardAttributeLabel>- <CardAttributeValue>- <EmployeeAvatar- employeeId={routeData.decision.decisionBy}- />- </CardAttributeValue>- </CardAttribute>- <CardAttribute>- <CardAttributeLabel>- <Trans>Approval Date</Trans>- </CardAttributeLabel>- <CardAttributeValue>- <DateTime- value={routeData.decision.decisionAt}- variant="date"- />- </CardAttributeValue>- </CardAttribute>- </>- )}- {routeData?.decision?.status === "Rejected" &&- status === "Rejected" && (- <>- <CardAttribute>- <CardAttributeLabel>- <Trans>Rejected By</Trans>- </CardAttributeLabel>- <CardAttributeValue>- <EmployeeAvatar- employeeId={routeData.decision.decisionBy}- />- </CardAttributeValue>- </CardAttribute>- <CardAttribute>- <CardAttributeLabel>- <Trans>Rejected Date</Trans>- </CardAttributeLabel>- <CardAttributeValue>- <DateTime- value={routeData.decision.decisionAt}- variant="date"- />- </CardAttributeValue>- </CardAttribute>- </>- )}+ {decision?.status === "Approved" && status === "Active" && (+ <>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Approved By</Trans>+ </CardAttributeLabel>+ <CardAttributeValue>+ <EmployeeAvatar employeeId={decision.decisionBy} />+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Approval Date</Trans>+ </CardAttributeLabel>+ <CardAttributeValue>+ <DateTime value={decision.decisionAt} variant="date" />+ </CardAttributeValue>+ </CardAttribute>+ </>+ )}+ {decision?.status === "Rejected" && status === "Rejected" && (+ <>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Rejected By</Trans>+ </CardAttributeLabel>+ <CardAttributeValue>+ <EmployeeAvatar employeeId={decision.decisionBy} />+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Rejected Date</Trans>+ </CardAttributeLabel>+ <CardAttributeValue>+ <DateTime value={decision.decisionAt} variant="date" />+ </CardAttributeValue>+ </CardAttribute>+ </>+ )}<CardAttribute><CardAttributeValue><ValidatedForm@@ -420,10 +409,21 @@ const SupplierHeader = () => {)}{auditLogDrawer}{approvalDecision && approvalRequestId && (- <SupplierApprovalModal- supplierName={routeData?.supplier?.name ?? undefined}+ <ApprovalDecisionModal+ action={path.to.supplierApproval(supplierId)}approvalRequestId={approvalRequestId}decision={approvalDecision}+ title={+ approvalDecision === "Approved"+ ? t`Approve ${routeData?.supplier?.name ?? ""}`+ : t`Reject ${routeData?.supplier?.name ?? ""}`+ }+ description={+ approvalDecision === "Approved"+ ? t`Are you sure you want to approve this supplier? This will make it active.`+ : t`Are you sure you want to reject this supplier?`+ }+ fetcher={approvalFetcher}onClose={() => setApprovalDecision(null)}/>)}diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.tsindex 4135952a1f..56864533dc 100644--- a/apps/erp/app/modules/quality/quality.models.ts+++ b/apps/erp/app/modules/quality/quality.models.ts@@ -391,14 +391,6 @@ export const requiredActionValidator = z.object({active: zfd.checkbox()});-export const qualityDocumentApprovalValidator = z.object({- approvalRequestId: z- .string()- .min(1, { message: "Approval request is required" }),- decision: z.enum(["Approved", "Rejected"]),- notes: zfd.text(z.string().optional())-});-export const QualityKPIs = [{ key: "weeklyTracking", label: "Issue Trend" },{ key: "statusDistribution", label: "Status Distribution" },diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsxdeleted file mode 100644index 5e427295e5..0000000000--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx+++ /dev/null@@ -1,102 +0,0 @@-// 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 { ApprovalDecision } from "@carbon/ee/approvals";-import { Hidden, TextArea, ValidatedForm } from "@carbon/form";-import {- Button,- Modal,- ModalBody,- ModalContent,- ModalFooter,- ModalHeader,- ModalTitle-} from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";-import type { FetcherWithComponents } from "react-router";-import { useParams } from "react-router";-import { path } from "~/utils/path";-import { qualityDocumentApprovalValidator } from "../../quality.models";-import type { QualityDocument } from "../../types";--type QualityDocumentApprovalModalProps = {- qualityDocument?: QualityDocument;- approvalRequestId: string;- decision: ApprovalDecision;- fetcher: FetcherWithComponents<unknown>;- onClose: () => void;-};--const QualityDocumentApprovalModal = ({- qualityDocument,- approvalRequestId,- decision,- onClose,- fetcher-}: QualityDocumentApprovalModalProps) => {- const { t } = useLingui();- const { id } = useParams();- if (!id) throw new Error("id not found");-- const isApproving = decision === "Approved";-- return (- <Modal- open- onOpenChange={(open) => {- if (!open) {- onClose();- }- }}- >- <ModalContent>- <ValidatedForm- method="post"- validator={qualityDocumentApprovalValidator}- action={path.to.qualityDocument(id)}- onSubmit={onClose}- defaultValues={{- approvalRequestId,- decision,- notes: undefined- }}- fetcher={fetcher}- >- <ModalHeader>- <ModalTitle>- {isApproving ? "Approve" : "Reject"} {qualityDocument?.name}- </ModalTitle>- </ModalHeader>- <ModalBody>- <Hidden name="approvalRequestId" />- <Hidden name="decision" />- <p className="text-sm text-muted-foreground mb-4">- {isApproving- ? "Are you sure you want to approve this quality document? This will make it active."- : "Are you sure you want to reject this quality document? The document will remain in draft status."}- </p>- <TextArea- name="notes"- label={t`Notes (optional)`}- placeholder={t`Add any notes about your decision...`}- />- </ModalBody>- <ModalFooter>- <Button variant="secondary" onClick={onClose}>- <Trans>Cancel</Trans>- </Button>- <Button- type="submit"- variant={isApproving ? "primary" : "destructive"}- >- {isApproving ? "Approve" : "Reject"}- </Button>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- );-};--export default QualityDocumentApprovalModal;diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsxindex 5e1ffa69aa..4bc2fed453 100644--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx@@ -2,7 +2,10 @@// 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 { ApprovalDecision } from "@carbon/ee/approvals";+import type {+ ApprovalDecision,+ DocumentApprovalState+} from "@carbon/ee/approvals";import {Badge,Button,@@ -36,12 +39,12 @@ import {import { Await, useFetcher, useParams } from "react-router";import { VersionMenu } from "~/components";import { usePanels } from "~/components/Layout";+import ApprovalDecisionModal from "~/components/Modals/ApprovalDecision";import ConfirmDelete from "~/components/Modals/ConfirmDelete";-import { usePermissions, useRouteData } from "~/hooks";+import { usePermissions, useRouteData, useUser } from "~/hooks";import { useDocumentStore } from "~/stores";import { path } from "~/utils/path";import type { QualityDocument } from "../../types";-import QualityDocumentApprovalModal from "./QualityDocumentApprovalModal";import QualityDocumentForm from "./QualityDocumentForm";import QualityDocumentStatus from "./QualityDocumentStatus";@@ -52,12 +55,9 @@ const QualityDocumentHeader = () => {const routeData = useRouteData<{document: QualityDocument;versions: PostgrestResponse<QualityDocument>;- approvalRequest: { id: string } | null;- canApprove: boolean;- canReopen: boolean;- canDelete: boolean;- isApprovalRequired: boolean;+ approval: DocumentApprovalState | null;}>(path.to.qualityDocument(id));+ const user = useUser();const { t } = useLingui();const permissions = usePermissions();@@ -80,11 +80,14 @@ const QualityDocumentHeader = () => {const isDraft = status === "Draft";const isArchived = status === "Archived";const canActivate = isDraft || isArchived;- const approvalRequestId = routeData?.approvalRequest?.id;+ const approval = routeData?.approval;+ const approvalRequestId = approval?.pendingRequestId;const hasApprovalRequest = !!approvalRequestId;- const canApprove = routeData?.canApprove ?? false;- const canDelete = routeData?.canDelete ?? true;- const isApprovalRequired = routeData?.isApprovalRequired ?? false;+ const canApprove = approval?.canApprove ?? false;+ // While a request is pending only its requester may delete the document.+ const canDelete =+ !hasApprovalRequest || approval?.pendingRequestedBy === user.id;+ const isApprovalRequired = approval?.isRequired ?? false;const statusIdle = statusFetcher.state === "idle";const submitLoading =@@ -269,10 +272,20 @@ const QualityDocumentHeader = () => {/>)}{approvalDecision && approvalRequestId && (- <QualityDocumentApprovalModal- qualityDocument={routeData?.document}+ <ApprovalDecisionModal+ action={path.to.qualityDocument(id)}approvalRequestId={approvalRequestId}decision={approvalDecision}+ title={+ approvalDecision === "Approved"+ ? t`Approve ${displayName}`+ : t`Reject ${displayName}`+ }+ description={+ approvalDecision === "Approved"+ ? t`Are you sure you want to approve this quality document? This will make it active.`+ : t`Are you sure you want to reject this quality document? The document will remain in draft status.`+ }fetcher={approvalFetcher}onClose={() => setApprovalDecision(null)}/>diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentProperties.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentProperties.tsxindex 11e0d0631a..304fb60379 100644--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentProperties.tsx+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentProperties.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { DocumentApprovalState } from "@carbon/ee/approvals";import { Select, ValidatedForm } from "@carbon/form";import {Button,@@ -20,7 +21,7 @@ import { useFetcher, useParams } from "react-router";import { z } from "zod";import Assignee, { useOptimisticAssignment } from "~/components/Assignee";import { Tags } from "~/components/Form";-import { usePermissions, useRouteData } from "~/hooks";+import { usePermissions, useRouteData, useUser } from "~/hooks";import { useTags } from "~/hooks/useTags";import type { action } from "~/routes/x+/quality-document+/update";import { path } from "~/utils/path";@@ -52,12 +53,17 @@ const QualityDocumentProperties = () => {const routeData = useRouteData<{document: QualityDocument;tags: Array<{ name: string }>;- approvalRequest: { id: string } | null;- canReopen: boolean;+ approval: DocumentApprovalState | null;}>(path.to.qualityDocument(id));+ const user = useUser();- const hasPendingApproval = !!routeData?.approvalRequest;- const canReopen = routeData?.canReopen ?? true;+ const approval = routeData?.approval;+ const hasPendingApproval = !!approval?.pendingRequestId;+ // Withdrawing a pending request (back to Draft) is for its requester or an approver.+ const canReopen =+ !hasPendingApproval ||+ approval?.pendingRequestedBy === user.id ||+ (approval?.canApprove ?? false);const currentStatus = routeData?.document?.status ?? null;const isArchived = currentStatus === "Archived";const statusOptions = hasPendingApprovaldiff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsxindex 5aa924fe11..24b8bb42aa 100644--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx@@ -5,7 +5,6 @@import {type ApprovalDocumentType,type ApprovalRule,- approvalDocumentTypeLabel,approvalDocumentTypesWithAmounts} from "@carbon/ee/approvals";import {@@ -50,6 +49,14 @@ const ApprovalRuleCard = memo(const currencyFormatter = useCurrencyFormatter({ compact: true });const deleteDisclosure = useDisclosure();+ const documentTypeLabels: Record<ApprovalDocumentType, string> = {+ purchaseOrder: t`Purchase Order`,+ qualityDocument: t`Quality Document`,+ supplier: t`Supplier`,+ changeOrder: t`Change Notice`+ };+ const documentTypeLabel = documentTypeLabels[documentType];+const canEdit = permissions.can("update", "settings");const canDelete = permissions.can("update", "settings");@@ -77,7 +84,7 @@ const ApprovalRuleCard = memo(<AccordionTrigger className="px-6 py-8 hover:no-underline w-full"><HStack spacing={4} className="flex-1 justify-between pr-12"><Heading size="h4" as="h3">- {approvalDocumentTypeLabel[documentType]}+ {documentTypeLabel}{approvalDocumentTypesWithAmounts.includes(documentType) &&@@ -149,11 +156,7 @@ const ApprovalRuleCard = memo(<ConfirmDeleteaction={path.to.deleteApprovalRule(rule.id)}isOpen={deleteDisclosure.isOpen}- name={- documentType === "purchaseOrder"- ? t`Purchase Order approval rule`- : t`Quality Document approval rule`- }+ name={t`${documentTypeLabel} approval rule`}text={t`Are you sure you want to delete this approval rule? This cannot be undone.`}onCancel={deleteDisclosure.onClose}onSubmit={handleDeleteConfirm}diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsxindex d5d067ec02..1ad1601fca 100644--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx@@ -30,10 +30,16 @@ type ApprovalRulesProps = {poRules: ApprovalRule[];qdRules: ApprovalRule[];supplierRules: ApprovalRule[];+ changeOrderRules: ApprovalRule[];};const ApprovalRules = memo(- ({ poRules, qdRules, supplierRules }: ApprovalRulesProps) => {+ ({+ poRules,+ qdRules,+ supplierRules,+ changeOrderRules+ }: ApprovalRulesProps) => {const permissions = usePermissions();const canCreate = permissions.can("update", "settings");@@ -184,6 +190,48 @@ const ApprovalRules = memo()}</CardContent></Card>++ <Card>+ <CardHeader>+ <div className="flex items-center justify-between">+ <div>+ <CardTitle className="text-lg">+ <Trans>Change Notices</Trans>+ </CardTitle>+ <CardDescription className="text-sm">+ <Trans>+ Require approval before change notices move to+ Implementation+ </Trans>+ </CardDescription>+ </div>+ {canCreate && changeOrderRules.length === 0 && (+ <Button variant="primary" leftIcon={<LuPlus />} asChild>+ <Link to={path.to.newApprovalRule("changeOrder")}>+ <Trans>New Rule</Trans>+ </Link>+ </Button>+ )}+ </div>+ </CardHeader>+ <CardContent>+ {changeOrderRules.length === 0 ? (+ <Empty className="my-4" />+ ) : (+ <VStack spacing={3} className="items-stretch">+ {changeOrderRules+ .filter((r) => r.id)+ .map((rule) => (+ <ApprovalRuleCard+ key={rule.id}+ rule={rule}+ documentType="changeOrder"+ />+ ))}+ </VStack>+ )}+ </CardContent>+ </Card></VStack></div></ScrollArea>diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsxindex 37613a6539..616e0def87 100644--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx@@ -49,13 +49,19 @@ export default function ApprovalRulesUpgradeOverlay() {return (<RulesUpgradeOverlaypreview={- <ApprovalRules poRules={mockPoRules} qdRules={[]} supplierRules={[]} />+ <ApprovalRules+ poRules={mockPoRules}+ qdRules={[]}+ supplierRules={[]}+ changeOrderRules={[]}+ />}title={<Trans>Approval Rules</Trans>}description={<Trans>- Require tiered sign-off on purchase orders, quality documents, and- suppliers based on amount thresholds and approver groups.+ Require tiered sign-off on purchase orders, quality documents,+ suppliers, and change notices based on amount thresholds and approver+ groups.</Trans>}/>diff --git a/apps/erp/app/routes/api+/audit-log.ts b/apps/erp/app/routes/api+/audit-log.tsindex 8a9df8d2a4..9059d45455 100644--- a/apps/erp/app/routes/api+/audit-log.ts+++ b/apps/erp/app/routes/api+/audit-log.ts@@ -13,6 +13,11 @@ import type { LoaderFunctionArgs } from "react-router";const logger = getLogger("erp", "audit-log");+// `all=true` (the History drawer's Download) pages through every entry still in+// the live log, up to a hard cap.+const DOWNLOAD_PAGE_SIZE = 500;+const DOWNLOAD_MAX_ENTRIES = 10_000;+export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "settings"@@ -22,6 +27,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const entityType = url.searchParams.get("entityType");const entityId = url.searchParams.get("entityId");const recordId = url.searchParams.get("recordId");+ const all = url.searchParams.get("all") === "true";if (!entityType || !entityId) {return Response.json(@@ -51,16 +57,46 @@ export async function loader({ request }: LoaderFunctionArgs) {// Get audit log entries for this entitytry {- const entries = await getEntityAuditLog(- client,+ if (!all) {+ const entries = await getEntityAuditLog(+ client,+ companyId,+ entityType,+ entityId,+ { limit: 50, offset: 0, recordId: recordId ?? undefined }+ );+ return Response.json({ entries });+ }++ const entries: Awaited<ReturnType<typeof getEntityAuditLog>> = [];+ while (entries.length < DOWNLOAD_MAX_ENTRIES) {+ const page = await getEntityAuditLog(+ client,+ companyId,+ entityType,+ entityId,+ {+ limit: DOWNLOAD_PAGE_SIZE,+ offset: entries.length,+ recordId: recordId ?? undefined+ }+ );+ entries.push(...page);+ if (page.length < DOWNLOAD_PAGE_SIZE) break;+ }+ return Response.json({ entries: entries.slice(0, DOWNLOAD_MAX_ENTRIES) });+ } catch (err) {+ logger.error("Failed to fetch audit log", {companyId,entityType,entityId,- { limit: 50, offset: 0, recordId: recordId ?? undefined }- );- return Response.json({ entries });- } catch (err) {- logger.error("Failed to fetch audit log", { error: err });- return Response.json({ entries: [] });+ all,+ error: err+ });+ // A download must fail visibly: an empty list would save a file with no+ // history in it.+ return all+ ? Response.json({ entries: [] }, { status: 500 })+ : Response.json({ entries: [] });}}diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex 072240b088..d5f9788e7a 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -108,8 +108,9 @@ function resolve(return path.to.purchaseOrder(documentId);if (documentType === "qualityDocument")return path.to.qualityDocument(documentId);- if (documentType === "supplier")- return path.to.supplierApproval(documentId);+ if (documentType === "supplier") return path.to.supplier(documentId);+ if (documentType === "changeOrder")+ return path.to.changeNoticeDetails(documentId);return null;default:return null;diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.tsxindex 12d21c4755..7ca20dc22c 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.tsx@@ -3,12 +3,12 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { VStack } from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";+import { Trans } from "@lingui/react/macro";import { useParams } from "react-router";import { useRouteData } from "~/hooks";import type { ChangeNotice } from "~/modules/items";-import { canEditChangeNoticeEngineering } from "~/modules/items";import type { AffectedItemDraft } from "~/modules/items/ui/ChangeNotice";+import { useChangeNoticeEngineeringLock } from "~/modules/items/ui/ChangeNotice";import AffectedItemDetail from "~/modules/items/ui/ChangeNotice/AffectedItemDetail";import { path } from "~/utils/path";@@ -18,13 +18,14 @@ import { path } from "~/utils/path";// which affected item to show, so refresh + back/forward reselect it.export default function ChangeNoticeAffectedItemRoute() {const { id, affectedId } = useParams();- const { t } = useLingui();if (!id) throw new Error("Could not find id");const routeData = useRouteData<{changeNotice: ChangeNotice;affectedItems: AffectedItemDraft[];}>(path.to.changeNotice(id));+ const { isDisabled, reason: disabledReason } =+ useChangeNoticeEngineeringLock(id);const changeNotice = routeData?.changeNotice;if (!changeNotice) throw new Error("Could not find change notice data");@@ -41,15 +42,6 @@ export default function ChangeNoticeAffectedItemRoute() {);}- const isDisabled = !canEditChangeNoticeEngineering(changeNotice.status);- // UI copy is kept separate from the server guard's flash text (same split as- // ReleaseLockAlert) — React macros can't run server-side, so this is the- // translated half of the same condition.- const disabledReason =- changeNotice.status === "Implementation"- ? t`This change notice is being implemented, so its changes are locked. Reopen it to edit.`- : t`This change notice is closed, so its changes are read-only.`;-return (<VStack spacing={4} className="p-4"><AffectedItemDetaildiff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsxnew file mode 100644index 0000000000..d8bcb6897c--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.approval.tsx@@ -0,0 +1,111 @@+// 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 { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import { approvalDecisionValidator } from "@carbon/ee/approvals";+import { decideApprovalRequest } from "@carbon/ee/approvals/document.server";+import { validationError, validator } from "@carbon/form";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";+import { redirect } from "@carbon/utils";+import type { ActionFunctionArgs } from "react-router";+import {+ changeNoticeStageEvent,+ notifyChangeNoticeTransition+} from "~/modules/items/items.server";+import { getDatabaseClient } from "~/services/database.server";+import { path } from "~/utils/path";++const logger = getLogger("erp", "change-notice-approval");++// Approving performs Engineering Complete → Implementation inside+// approveRequest's transaction; rejecting leaves the status alone.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const validation = await validator(approvalDecisionValidator).validate(+ await request.formData()+ );+ if (validation.error) {+ return validationError(validation.error);+ }++ const { approvalRequestId, decision, notes } = validation.data;+ const result = await decideApprovalRequest(+ getCarbonServiceRole(),+ getDatabaseClient(),+ {+ documentType: "changeOrder",+ documentId: id,+ companyId,+ userId,+ approvalRequestId,+ decision,+ notes+ }+ );++ if (result.error) {+ logger.error("Change notice approval decision failed", {+ companyId,+ changeNoticeId: id,+ approvalRequestId,+ error: result.error+ });+ throw redirect(+ path.to.changeNoticeDetails(id),+ await flash(request, error(result.error, result.error.message))+ );+ }++ if (result.requestedBy !== userId) {+ await trigger("notify", {+ event:+ decision === "Approved"+ ? NotificationEvent.ApprovalApproved+ : NotificationEvent.ApprovalRejected,+ companyId,+ documentId: id,+ documentType: "changeOrder",+ recipient: { type: "user", userId: result.requestedBy },+ from: userId+ }).catch((e) =>+ logger.error("Failed to notify the approval requester", {+ companyId,+ changeNoticeId: id,+ error: e+ })+ );+ }++ // The notice just entered Implementation: notify the same people a plain+ // advance would.+ if (decision === "Approved") {+ await notifyChangeNoticeTransition({+ client,+ event: changeNoticeStageEvent.Implementation,+ changeNoticeId: id,+ companyId,+ userId+ });+ }++ throw redirect(+ path.to.changeNoticeDetails(id),+ await flash(+ request,+ success(`Approval request ${decision.toLowerCase()} successfully`)+ )+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.details.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.details.tsxindex e97884606f..4da8f07d45 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.details.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.details.tsx@@ -7,15 +7,13 @@ import { VStack } from "@carbon/react";import { useParams } from "react-router";import { useRouteData } from "~/hooks";import type { ChangeNotice, ChangeNoticeActionTask } from "~/modules/items";-import {- canEditChangeNoticeEngineering,- canEditChangeNoticeWorkflow-} from "~/modules/items";+import { canEditChangeNoticeWorkflow } from "~/modules/items";import type { AffectedItemDraft } from "~/modules/items/ui/ChangeNotice";import {ChangeNoticeActions,ChangeNoticeChanges,- ChangeNoticeContent+ ChangeNoticeContent,+ useChangeNoticeEngineeringLock} from "~/modules/items/ui/ChangeNotice";import ChangeNoticeStatusFlow from "~/modules/items/ui/ChangeNotice/ChangeNoticeStatusFlow";import { path } from "~/utils/path";@@ -36,11 +34,11 @@ export default function ChangeNoticeDetailsRoute() {actions: ChangeNoticeActionTask[];affectedItems: AffectedItemDraft[];}>(path.to.changeNotice(id));+ const { isDisabled } = useChangeNoticeEngineeringLock(id);const changeNotice = routeData?.changeNotice;if (!changeNotice) throw new Error("Could not find change notice data");- const isDisabled = !canEditChangeNoticeEngineering(changeNotice.status);// Action tasks are workflow content — executing them is what Implementation is for.const isWorkflowDisabled = !canEditChangeNoticeWorkflow(changeNotice.status);diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsxindex c2c1657381..8803e7a76a 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.status.tsx@@ -4,8 +4,16 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import {+ cancelPendingApprovals,+ openApprovalRequests+} from "@carbon/ee/approvals/document.server";import { validationError, validator } from "@carbon/form";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import {@@ -21,6 +29,17 @@ import {import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";+const logger = getLogger("erp", "change-notice-status");++const approvalOutcomeFlash = {+ requested: success("Submitted for approval"),+ "already-pending": error(+ null,+ "This change notice is already waiting for approval"+ ),+ failed: error(null, "Failed to submit for approval")+};+export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);const { client, userId, companyId } = await requirePermissions(request, {@@ -41,6 +60,71 @@ export async function action({ request, params }: ActionFunctionArgs) {const { fromStatus, status: toStatus, assignee } = validation.data;+ // An approval rule gates Engineering Complete → Implementation: submitting+ // opens a request and leaves the status alone; approving it performs the+ // transition (approveRequest). Without a rule the advance proceeds as usual.+ const isGatedAdvance =+ fromStatus === "Engineering Complete" && toStatus === "Implementation";+ if (isGatedAdvance) {+ // fromStatus comes from the form: a stale page must not open a request for+ // a notice that is no longer at Engineering Complete.+ const current = await client+ .from("changeOrder")+ .select("status")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (current.data?.status !== fromStatus) {+ throw redirect(+ requestReferrer(request) ?? path.to.changeNoticeDetails(id),+ await flash(+ request,+ error(+ current.error,+ "The change notice was updated by someone else. Refresh and try again."+ )+ )+ );+ }++ const opened = await openApprovalRequests(getCarbonServiceRole(), {+ documentType: "changeOrder",+ documentIds: [id],+ companyId,+ userId+ });++ if (opened.status === "opened" && opened.approverIds.length > 0) {+ await trigger("notify", {+ event: NotificationEvent.ApprovalRequested,+ companyId,+ documentId: id,+ documentType: "changeOrder",+ recipient: { type: "users", userIds: opened.approverIds },+ from: userId+ }).catch((e) =>+ logger.error("Failed to notify change notice approvers", {+ companyId,+ changeNoticeId: id,+ error: e+ })+ );+ }++ if (opened.status !== "not-required") {+ const outcome =+ opened.status === "failed"+ ? "failed"+ : opened.requested.length > 0+ ? "requested"+ : "already-pending";+ throw redirect(+ requestReferrer(request) ?? path.to.changeNoticeDetails(id),+ await flash(request, approvalOutcomeFlash[outcome])+ );+ }+ }+// Implementation → Done IS the apply: applyChangeNotice activates each affected// item's CO-owned Draft make method and performs the final CAS flip to Done// (G1/G2). All other transitions go through the plain guarded status writer.@@ -80,6 +164,25 @@ export async function action({ request, params }: ActionFunctionArgs) {}}+ // Cancelling withdraws a pending request; so does a plain advance past the+ // gate, which only happens when the rule was turned off after the request+ // was opened.+ if (toStatus === "Cancelled" || isGatedAdvance) {+ const cancelled = await cancelPendingApprovals(getCarbonServiceRole(), {+ documentType: "changeOrder",+ documentIds: [id],+ companyId,+ userId+ });+ if (cancelled.error) {+ logger.error("Failed to cancel change notice approval requests", {+ companyId,+ changeNoticeId: id,+ error: cancelled.error+ });+ }+ }+// Notify the CO assignee + action-task assignees only on the stages that// notify on entry (Start / Implementation / Done). Best-effort; never blocks// the redirect.diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.tsxindex 84a7df655f..dbafa28e43 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.tsx@@ -4,7 +4,9 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { getDocumentApprovalState } from "@carbon/ee/approvals/document.server";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";import { RecordOutlet } from "@carbon/react";@@ -63,7 +65,7 @@ export const handle: Handle = {};export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {view: "parts"});@@ -291,7 +293,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {: []);- const linkedNonConformance = await linkedNonConformancePromise;+ // Approval only gates Engineering Complete → Implementation.+ const [linkedNonConformance, approval] = await Promise.all([+ linkedNonConformancePromise,+ changeNotice.data?.status === "Engineering Complete"+ ? getDocumentApprovalState(getCarbonServiceRole(), {+ documentType: "changeOrder",+ documentId: id,+ companyId,+ userId+ })+ : null+ ]);return {changeNotice: changeNotice.data,@@ -302,6 +315,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {requiredActions,impactUsedIn,nonConformanceOptions,+ approval,linkedNonConformance: linkedNonConformance? {id: linkedNonConformance.id,diff --git a/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsxindex a4ab1977d9..1dbe236526 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx@@ -4,7 +4,10 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { cancelPendingApprovals } from "@carbon/ee/approvals/document.server";+import { getLogger } from "@carbon/logger";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -12,8 +15,10 @@ import { deleteChangeNotice } from "~/modules/items";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";+const logger = getLogger("erp", "change-notice-delete");+export async function action({ request, params }: ActionFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {delete: "parts"});@@ -36,6 +41,22 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // approvalRequest.documentId has no FK, so the request would outlive the+ // notice in approvers' lists.+ const cancelled = await cancelPendingApprovals(getCarbonServiceRole(), {+ documentType: "changeOrder",+ documentIds: [id],+ companyId,+ userId+ });+ if (cancelled.error) {+ logger.error("Failed to cancel change notice approval requests", {+ companyId,+ changeNoticeId: id,+ error: cancelled.error+ });+ }+throw redirect(path.to.changeNotices,await flash(request, success("Successfully deleted change notice"))diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsxindex 76480c9573..2096a7fc30 100644--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx@@ -6,15 +6,11 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";-import type { Database } from "@carbon/database";+import { approvalDecisionValidator } from "@carbon/ee/approvals";import {- approveRequest,- canApproveRequest,- canCancelRequest,- getLatestApprovalRequestForDocument,- isApprovalRequired,- rejectRequest-} from "@carbon/ee/approvals.server";+ decideApprovalRequest,+ getDocumentApprovalState+} from "@carbon/ee/approvals/document.server";import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";@@ -22,14 +18,12 @@ import { NotificationEvent } from "@carbon/notifications";import { RecordOutlet } from "@carbon/react";import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";-import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";import {getQualityDocument,- getQualityDocumentVersions,- qualityDocumentApprovalValidator+ getQualityDocumentVersions} from "~/modules/quality";import QualityDocumentEditor from "~/modules/quality/ui/Documents/QualityDocumentEditor";import QualityDocumentHeader from "~/modules/quality/ui/Documents/QualityDocumentHeader";@@ -41,70 +35,6 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "id");-type ApprovalContext = {- approvalRequest: { id: string } | null;- canApprove: boolean;- canReopen: boolean;- canDelete: boolean;- isApprovalRequired: boolean;-};--async function getQualityDocumentApprovalContext(- serviceRole: SupabaseClient<Database>,- documentId: string,- status: string | null,- companyId: string,- userId: string-): Promise<ApprovalContext> {- const defaultContext: ApprovalContext = {- approvalRequest: null,- canApprove: false,- canReopen: true,- canDelete: true,- isApprovalRequired: false- };-- if (status !== "Draft" && status !== "Archived") {- return defaultContext;- }-- const [latest, approvalRequired] = await Promise.all([- getLatestApprovalRequestForDocument(- serviceRole,- "qualityDocument",- documentId- ),- isApprovalRequired(serviceRole, "qualityDocument", companyId, undefined)- ]);-- const req = latest.data;- if (!req || req.status !== "Pending" || !req.requestedBy || !req.id) {- return { ...defaultContext, isApprovalRequired: approvalRequired };- }-- const canApprove = await canApproveRequest(- serviceRole,- {- amount: req.amount,- documentType: req.documentType,- companyId: req.companyId- },- userId- );- const isRequester = canCancelRequest(- { requestedBy: req.requestedBy, status: req.status },- userId- );-- return {- approvalRequest: { id: req.id },- canApprove,- canReopen: isRequester || canApprove,- canDelete: isRequester,- isApprovalRequired: approvalRequired- };-}-export const handle: Handle = {breadcrumb: detailBreadcrumb({ breadcrumb: msg`Policy & Procedure`, to: path.to.qualityDocuments },@@ -113,115 +43,70 @@ export const handle: Handle = {module: "quality"};+// Approving makes the document Active inside approveRequest's transaction;+// rejecting leaves it in Draft.export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { companyId: callerCompanyId, userId } = await requirePermissions(- request,- {- update: "quality"- }- );+ const { companyId, userId } = await requirePermissions(request, {+ update: "quality"+ });const { id } = params;if (!id) throw new Error("Could not find id");- const validation = await validator(qualityDocumentApprovalValidator).validate(+ const validation = await validator(approvalDecisionValidator).validate(await request.formData());-if (validation.error) {return validationError(validation.error);}const { approvalRequestId, decision, notes } = validation.data;-- const serviceRole = getCarbonServiceRole();-- // Verify user can approve this request- const approvalRequest = await getLatestApprovalRequestForDocument(- serviceRole,- "qualityDocument",- id- );-- // The request is read through the service role by a URL id, so it must be- // proven to be this company's before anything acts on it.- if (- !approvalRequest.data ||- approvalRequest.data.id !== approvalRequestId ||- approvalRequest.data.companyId !== callerCompanyId- ) {- logger.error("Quality document approval request not found", {- companyId: callerCompanyId,- documentId: id,- approvalRequestId- });- throw redirect(- path.to.qualityDocument(id),- await flash(request, error(null, "Approval request not found"))- );- }-- const canApprove = await canApproveRequest(- serviceRole,+ const result = await decideApprovalRequest(+ getCarbonServiceRole(),+ getDatabaseClient(),{- amount: approvalRequest.data.amount,- documentType: approvalRequest.data.documentType,- companyId: approvalRequest.data.companyId- },- userId+ documentType: "qualityDocument",+ documentId: id,+ companyId,+ userId,+ approvalRequestId,+ decision,+ notes+ });- if (!canApprove) {- throw redirect(- path.to.qualityDocument(id),- await flash(- request,- error(null, "You do not have permission to approve this request")- )- );- }-- // Process approval decision- const db = getDatabaseClient();- const result =- decision === "Approved"- ? await approveRequest(db, approvalRequestId, userId, notes || undefined)- : await rejectRequest(db, approvalRequestId, userId, notes || undefined);-if (result.error) {+ logger.error("Quality document approval decision failed", {+ companyId,+ documentId: id,+ approvalRequestId,+ error: result.error+ });throw redirect(path.to.qualityDocument(id),- await flash(- request,- error(- result.error,- result.error?.message ?? "Failed to process approval decision"- )- )+ await flash(request, error(result.error, result.error.message)));}- const requestedBy = approvalRequest.data?.requestedBy;- const companyId = approvalRequest.data?.companyId;- if (requestedBy && companyId && requestedBy !== userId) {- try {- await trigger("notify", {- event:- decision === "Approved"- ? NotificationEvent.ApprovalApproved- : NotificationEvent.ApprovalRejected,+ if (result.requestedBy !== userId) {+ await trigger("notify", {+ event:+ decision === "Approved"+ ? NotificationEvent.ApprovalApproved+ : NotificationEvent.ApprovalRejected,+ companyId,+ documentId: id,+ documentType: "qualityDocument",+ recipient: { type: "user", userId: result.requestedBy },+ from: userId+ }).catch((e) =>+ logger.error("Failed to trigger approval decision notification", {companyId,documentId: id,- documentType: "qualityDocument",- recipient: { type: "user", userId: requestedBy },- from: userId- });- } catch (e) {- logger.error("Failed to trigger approval decision notification", {error: e- });- }+ })+ );}throw redirect(@@ -242,21 +127,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");- const serviceRole = getCarbonServiceRole();// Kick off approval in parallel — it only needs document.status, so we chain// off the document fetch rather than waiting for Promise.all to settle.+ // Approval only gates Draft / Archived → Active.const documentPromise = getQualityDocument(client, id);const [document, tags, approval] = await Promise.all([documentPromise,getTagsList(client, companyId, "qualityDocument"),documentPromise.then((d) =>- getQualityDocumentApprovalContext(- serviceRole,- id,- d.data?.status ?? null,- companyId,- userId- )+ d.data?.status === "Draft" || d.data?.status === "Archived"+ ? getDocumentApprovalState(getCarbonServiceRole(), {+ documentType: "qualityDocument",+ documentId: id,+ companyId,+ userId+ })+ : null)]);@@ -281,7 +167,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {document: document.data,versions: getQualityDocumentVersions(client, document.data, companyId),tags: tags.data ?? [],- ...approval+ approval};}diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsxindex 99e44ee01c..a4a3735849 100644--- a/apps/erp/app/routes/x+/quality-document+/update.tsx+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx@@ -6,14 +6,9 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import {- canApproveRequest,- createApprovalRequest,- getApprovalRuleByAmount,- getApproverUserIdsForRule,- getLatestApprovalRequestForDocument,- hasPendingApproval,- isApprovalRequired-} from "@carbon/ee/approvals.server";+ cancelPendingApprovals,+ openApprovalRequests+} from "@carbon/ee/approvals/document.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";@@ -27,11 +22,9 @@ const logger = getLogger("erp", "update");type DocRow = { id: string; status: string | null };/**- * Process transition to Active from Draft or Archived.- * When approval rules apply: create request and use Draft as "in progress".- * - Draft → submit: stay Draft until approved, then Draft → Active.- * - Archived → submit: move to Draft, create request; when approved, Draft → Active.- * Otherwise: update to Active immediately.+ * Draft or Archived → Active. With an approval rule, each document opens a+ * request and waits in Draft (an Archived one moves to Draft) until it is+ * approved; without one it goes Active at once.*/async function processToActive(client: SupabaseClient<Database>,@@ -41,87 +34,69 @@ async function processToActive(docList: DocRow[],ids: string[]) {- const idsToSkipActive: string[] = [];- const archivedIdsToMoveToDraft: string[] = [];- const canTransitionToActive = (s: string | null) =>- s === "Draft" || s === "Archived";- // The same answer for every document: read once, and only when one needs it.- const transitioning = docList.filter((doc) =>- canTransitionToActive(doc.status)+ const transitioning = docList.filter(+ (doc) => doc.status === "Draft" || doc.status === "Archived");- const approvalRequired =- transitioning.length > 0 &&- (await isApprovalRequired(- serviceRole,- "qualityDocument",- companyId,- undefined- ));- let approvers: Promise<string[]> | undefined;- const getApprovers = () => {- approvers ??= getApprovalRuleByAmount(- serviceRole,- "qualityDocument",- companyId,- undefined- ).then((rule) =>- rule.data ? getApproverUserIdsForRule(serviceRole, rule.data) : []- );- return approvers;- };- for (const doc of approvalRequired ? transitioning : []) {- const hasPending = await hasPendingApproval(- serviceRole,- "qualityDocument",- doc.id- );- if (hasPending) {- idsToSkipActive.push(doc.id);- continue;- }- await createApprovalRequest(serviceRole, {- documentType: "qualityDocument",- documentId: doc.id,- companyId,- requestedBy: userId,- createdBy: userId,- amount: undefined- });+ const opened =+ transitioning.length > 0+ ? await openApprovalRequests(serviceRole, {+ documentType: "qualityDocument",+ documentIds: transitioning.map((doc) => doc.id),+ companyId,+ userId+ })+ : ({ status: "not-required" } as const);- const approverIds = await getApprovers();+ if (opened.status === "failed") {+ return {+ data: null,+ error: { message: "Failed to submit for approval" }+ } as const;+ }- if (approverIds.length > 0) {- try {+ const awaitingApproval = new Set(+ opened.status === "opened" ? transitioning.map((doc) => doc.id) : []+ );++ if (opened.status === "opened" && opened.requested.length > 0) {+ if (opened.approverIds.length > 0) {+ for (const documentId of opened.requested) {await trigger("notify", {event: NotificationEvent.ApprovalRequested,companyId,- documentId: doc.id,+ documentId,documentType: "qualityDocument",- recipient: { type: "users", userIds: approverIds },+ recipient: { type: "users", userIds: opened.approverIds },from: userId- });- } catch (e) {- logger.error("Failed to trigger approval notification", { error: e });+ }).catch((e) =>+ logger.error("Failed to trigger approval notification", {+ companyId,+ documentId,+ error: e+ })+ );}}- idsToSkipActive.push(doc.id);- if (doc.status === "Archived") {- archivedIdsToMoveToDraft.push(doc.id);+ const archivedToDraft = transitioning+ .filter(+ (doc) => doc.status === "Archived" && opened.requested.includes(doc.id)+ )+ .map((doc) => doc.id);+ if (archivedToDraft.length > 0) {+ await client+ .from("qualityDocument")+ .update({+ status: "Draft",+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", archivedToDraft)+ .eq("companyId", companyId);}}- for (const docId of archivedIdsToMoveToDraft) {- await client- .from("qualityDocument")- .update({- status: "Draft",- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .eq("id", docId)- .eq("companyId", companyId);- }- const idsToUpdateToActive = ids.filter((id) => !idsToSkipActive.includes(id));++ const idsToUpdateToActive = ids.filter((id) => !awaitingApproval.has(id));if (idsToUpdateToActive.length === 0) {return { data: null, error: null } as const;}@@ -136,59 +111,6 @@ async function processToActive(.eq("companyId", companyId);}-/**- * Cancels pending approval requests when changing status to Archived or Draft.- * - Archived: any user with update quality may archive; pending requests are cancelled.- * - Draft: only the requester or an approver may change to Draft (withdraw); others get an error.- */-async function cancelPendingApprovalsForArchiveOrDraft(- serviceRole: SupabaseClient<Database>,- userId: string,- docList: DocRow[],- allowAnyUpdater: boolean-): Promise<{ message: string } | null> {- const toCancel: { id: string }[] = [];- for (const doc of docList) {- const latest = await getLatestApprovalRequestForDocument(- serviceRole,- "qualityDocument",- doc.id- );- const req = latest.data;- if (!req || req.status !== "Pending") continue;- if (!allowAnyUpdater) {- const isRequester = req.requestedBy === userId;- const isApprover = await canApproveRequest(- serviceRole,- {- amount: req.amount,- documentType: req.documentType,- companyId: req.companyId- },- userId- );- if (!isRequester && !isApprover) {- return {- message:- "Only the requester or an approver can change status to Draft when there is a pending approval request"- };- }- }- if (req.id) toCancel.push({ id: req.id });- }- for (const { id: reqId } of toCancel) {- await serviceRole- .from("approvalRequest")- .update({- status: "Cancelled",- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .eq("id", reqId);- }- return null;-}-export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {update: "quality"@@ -250,15 +172,23 @@ export async function action({ request }: ActionFunctionArgs) {);}- if (statusValue === "Archived" || statusValue === "Draft") {- const allowAnyUpdater = statusValue === "Archived";- const err = await cancelPendingApprovalsForArchiveOrDraft(- serviceRole,+ // Archiving withdraws a pending request for anyone who may update the+ // document; sending it back to Draft is a withdrawal only the requester+ // or an approver may make.+ if (+ (statusValue === "Archived" || statusValue === "Draft") &&+ docList.length > 0+ ) {+ const cancelled = await cancelPendingApprovals(serviceRole, {+ documentType: "qualityDocument",+ documentIds: docList.map((doc) => doc.id),+ companyId,userId,- docList,- allowAnyUpdater- );- if (err) return { error: { message: err.message }, data: null };+ onlyRequesterOrApprover: statusValue === "Draft"+ });+ if (cancelled.error) {+ return { error: { message: cancelled.error.message }, data: null };+ }}return await clientdiff --git a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsxindex 3301a7e21d..e2638fcae6 100644--- a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx+++ b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx@@ -38,7 +38,8 @@ export async function loader({ request }: LoaderFunctionArgs) {const documentType: ApprovalDocumentType | null =typeParam === "purchaseOrder" ||typeParam === "qualityDocument" ||- typeParam === "supplier"+ typeParam === "supplier" ||+ typeParam === "changeOrder"? typeParam: null;diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.tsxindex 1025921603..f89c56c129 100644--- a/apps/erp/app/routes/x+/settings+/approval-rules.tsx+++ b/apps/erp/app/routes/x+/settings+/approval-rules.tsx@@ -74,15 +74,21 @@ export async function loader({ request }: LoaderFunctionArgs) {(r) => r.documentType === "supplier");+ const changeOrderRules = enrichedRules.filter(+ (r) => r.documentType === "changeOrder"+ );+return {poRules,qdRules,- supplierRules+ supplierRules,+ changeOrderRules};}export default function ApprovalSettingsRoute() {- const { poRules, qdRules, supplierRules } = useLoaderData<typeof loader>();+ const { poRules, qdRules, supplierRules, changeOrderRules } =+ useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "APPROVAL_RULES" });if (isGated) {@@ -95,6 +101,7 @@ export default function ApprovalSettingsRoute() {poRules={poRules}qdRules={qdRules}supplierRules={supplierRules}+ changeOrderRules={changeOrderRules}/><RecordOutlet /></>diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsxindex 468575be72..111d5b2640 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx@@ -6,23 +6,18 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { approvalDecisionValidator } from "@carbon/ee/approvals";import {- approveRequest,- canApproveRequest,- createApprovalRequest,- getApprovalRuleByAmount,- getApproverUserIdsForRule,- getLatestApprovalRequestForDocument,- hasPendingApproval,- rejectRequest-} from "@carbon/ee/approvals.server";+ decideApprovalRequest,+ openApprovalRequests+} from "@carbon/ee/approvals/document.server";+import { canApproveRequest } from "@carbon/ee/approvals.server";import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";import { datetime, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import { supplierApprovalDecisionValidator } from "~/modules/purchasing";import { requireCompanyRecord } from "~/modules/shared/shared.server";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";@@ -48,34 +43,30 @@ export async function action({ request, params }: ActionFunctionArgs) {const intent = formData.get("intent");if (intent === "request-approval") {- const serviceRole = getCarbonServiceRole();-- const pending = await hasPendingApproval(- serviceRole,- "supplier",- supplierId- );+ const opened = await openApprovalRequests(getCarbonServiceRole(), {+ documentType: "supplier",+ documentIds: [supplierId],+ companyId,+ userId+ });- if (pending) {+ if (opened.status !== "opened" || opened.requested.length === 0) {throw redirect(path.to.supplier(supplierId),await flash(request,- error(null, "An approval request already exists for this supplier")+ error(+ null,+ opened.status === "opened"+ ? "An approval request already exists for this supplier"+ : opened.status === "not-required"+ ? "Suppliers do not require approval"+ : "Failed to submit for approval"+ )));}- await createApprovalRequest(serviceRole, {- documentType: "supplier",- documentId: supplierId,- companyId,- requestedBy: userId,- createdBy: userId,- amount: undefined- });-- // Update supplier status to Pendingawait client.from("supplier").update({@@ -85,29 +76,17 @@ export async function action({ request, params }: ActionFunctionArgs) {}).eq("id", supplierId);- const rule = await getApprovalRuleByAmount(- serviceRole,- "supplier",- companyId,- undefined- );- const approverIds = rule.data- ? await getApproverUserIdsForRule(serviceRole, rule.data)- : [];-- if (approverIds.length > 0) {- try {- await trigger("notify", {- event: NotificationEvent.ApprovalRequested,- companyId,- documentId: supplierId,- documentType: "supplier",- recipient: { type: "users", userIds: approverIds },- from: userId- });- } catch (e) {- logger.error("Failed to trigger approval notification", { error: e });- }+ if (opened.approverIds.length > 0) {+ await trigger("notify", {+ event: NotificationEvent.ApprovalRequested,+ companyId,+ documentId: supplierId,+ documentType: "supplier",+ recipient: { type: "users", userIds: opened.approverIds },+ from: userId+ }).catch((e) =>+ logger.error("Failed to trigger approval notification", { error: e })+ );}throw redirect(@@ -155,94 +134,57 @@ export async function action({ request, params }: ActionFunctionArgs) {}// Handle approve/reject intents- const validation = await validator(- supplierApprovalDecisionValidator- ).validate(formData);-+ const validation = await validator(approvalDecisionValidator).validate(+ formData+ );if (validation.error) {return validationError(validation.error);}const { approvalRequestId, decision, notes } = validation.data;-- const serviceRole = getCarbonServiceRole();-- const approvalRequest = await getLatestApprovalRequestForDocument(- serviceRole,- "supplier",- supplierId- );-- if (- !approvalRequest.data ||- approvalRequest.data.id !== approvalRequestId ||- approvalRequest.data.companyId !== companyId- ) {- throw redirect(- path.to.supplier(supplierId),- await flash(request, error(null, "Approval request not found"))- );- }-- const canApprove = await canApproveRequest(- serviceRole,+ const result = await decideApprovalRequest(+ getCarbonServiceRole(),+ getDatabaseClient(),{- amount: approvalRequest.data.amount,- documentType: approvalRequest.data.documentType,- companyId: approvalRequest.data.companyId- },- userId+ documentType: "supplier",+ documentId: supplierId,+ companyId,+ userId,+ approvalRequestId,+ decision,+ notes+ });- if (!canApprove) {- throw redirect(- path.to.supplier(supplierId),- await flash(- request,- error(null, "You do not have permission to approve this request")- )- );- }-- const db = getDatabaseClient();- const result =- decision === "Approved"- ? await approveRequest(db, approvalRequestId, userId, notes || undefined)- : await rejectRequest(db, approvalRequestId, userId, notes || undefined);-if (result.error) {+ logger.error("Supplier approval decision failed", {+ companyId,+ supplierId,+ approvalRequestId,+ error: result.error+ });throw redirect(path.to.supplier(supplierId),- await flash(- request,- error(- result.error,- result.error?.message ?? "Failed to process approval decision"- )- )+ await flash(request, error(result.error, result.error.message)));}- const requestedBy = approvalRequest.data?.requestedBy;- const requestCompanyId = approvalRequest.data?.companyId;- if (requestedBy && requestCompanyId && requestedBy !== userId) {- try {- await trigger("notify", {- event:- decision === "Approved"- ? NotificationEvent.ApprovalApproved- : NotificationEvent.ApprovalRejected,- companyId: requestCompanyId,- documentId: supplierId,- documentType: "supplier",- recipient: { type: "user", userId: requestedBy },- from: userId- });- } catch (e) {+ if (result.requestedBy !== userId) {+ await trigger("notify", {+ event:+ decision === "Approved"+ ? NotificationEvent.ApprovalApproved+ : NotificationEvent.ApprovalRejected,+ companyId,+ documentId: supplierId,+ documentType: "supplier",+ recipient: { type: "user", userId: result.requestedBy },+ from: userId+ }).catch((e) =>logger.error("Failed to trigger approval decision notification", {error: e- });- }+ })+ );}throw redirect(diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.tsxindex fe6b398f91..4bb7dca430 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.tsx@@ -6,6 +6,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { getDocumentApprovalState } from "@carbon/ee/approvals/document.server";import { RecordOutlet } from "@carbon/react";import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";@@ -17,7 +18,6 @@ import {getSupplierLocations,getSupplierTax} from "~/modules/purchasing";-import { getSupplierApprovalContext } from "~/modules/purchasing/purchasing.server";import SupplierHeader from "~/modules/purchasing/ui/Supplier/SupplierHeader";import SupplierSidebar from "~/modules/purchasing/ui/Supplier/SupplierSidebar";import { getTagsList } from "~/modules/shared";@@ -40,10 +40,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierId } = params;if (!supplierId) throw new Error("Could not find supplierId");- const serviceRole = getCarbonServiceRole();- // Kick off approval in parallel — it only needs supplier.status, so we chain- // off the supplier fetch rather than waiting for the whole Promise.all to- // settle.const supplierPromise = getSupplier(client, supplierId);const [supplier, contacts, locations, tags, supplierTax, approval] =await Promise.all([@@ -52,15 +48,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getSupplierLocations(client, supplierId),getTagsList(client, companyId, "supplier"),getSupplierTax(client, supplierId),- supplierPromise.then((s) =>- getSupplierApprovalContext(- serviceRole,- supplierId,- s.data?.status ?? null,- companyId,- userId- )- )+ getDocumentApprovalState(getCarbonServiceRole(), {+ documentType: "supplier",+ documentId: supplierId,+ companyId,+ userId+ })]);if (supplier.error) {@@ -79,7 +72,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locations: locations.data ?? [],tags: tags.data ?? [],supplierTax: supplierTax.data,- ...approval+ approval};}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 2bf6529a89..1fe61dd558 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -514,6 +514,8 @@ export const path = {// drives selection — refresh + back/forward reselect it.changeNoticeAffectedItem: (id: string, affectedId: string) =>generatePath(`${x}/items/change-notice/${id}/${affectedId}/details`),+ changeNoticeApproval: (id: string) =>+ generatePath(`${x}/items/change-notice/${id}/approval`),changeNoticeContent: (id: string) =>generatePath(`${x}/items/change-notice/${id}/content`),// Delete action for a supplier part managed on a CO line (Buy Revision/Newdiff --git a/packages/database/src/datasets/validate.ts b/packages/database/src/datasets/validate.tsindex c2d512d947..c070583977 100644--- a/packages/database/src/datasets/validate.ts+++ b/packages/database/src/datasets/validate.ts@@ -250,7 +250,8 @@ export const COVERAGE = {},approvalRequestType: {values: enumValues("approvalDocumentType", {- qualityDocument: "the seed requests approval for orders and suppliers"+ qualityDocument: "the seed requests approval for orders and suppliers",+ changeOrder: "the seed does not create change notice approval requests"}),missing: (type) => `purchasing.approvalRequests: no ${type} request`},diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.tsindex 7eda3edecf..17ea7e7d36 100644--- a/packages/database/src/event-system/attachments.ts+++ b/packages/database/src/event-system/attachments.ts@@ -36,7 +36,10 @@ export const attachments = {ability: { statement: ["broadcast_reference_changes"] },address: { before: ["sync_address_to_parent"], events: true },assemblyPlanJob: { statement: ["broadcast_table_changes"] },- changeOrder: { statement: ["broadcast_table_changes"] },+ changeOrder: { events: true, statement: ["broadcast_table_changes"] },+ changeOrderActionTask: { events: true },+ changeOrderAffectedItem: { events: true },+ changeOrderSupersession: { events: true },charge: { events: true },company: { after: ["sync_insert_company_related_records"] },companyIntegration: { before: ["sync_verify_integration"], events: true },diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 9d83f8195c..d894169bcf 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -117656,7 +117656,7 @@ export default {type: "string"},documentType: {- enum: ["purchaseOrder", "qualityDocument", "supplier"],+ enum: ["purchaseOrder", "qualityDocument", "supplier", "changeOrder"],format: 'public."approvalDocumentType"',type: "string"},@@ -145215,7 +145215,7 @@ export default {type: "string"},documentType: {- enum: ["purchaseOrder", "qualityDocument", "supplier"],+ enum: ["purchaseOrder", "qualityDocument", "supplier", "changeOrder"],format: 'public."approvalDocumentType"',type: "string"},@@ -162371,7 +162371,7 @@ export default {type: "string"},documentType: {- enum: ["purchaseOrder", "qualityDocument", "supplier"],+ enum: ["purchaseOrder", "qualityDocument", "supplier", "changeOrder"],format: 'public."approvalDocumentType"',type: "string"},diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 984387dae7..8099f1ac02 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -92238,7 +92238,11 @@ export type Database = {| "Other Expense"| "Tax"| "Investments"- approvalDocumentType: "purchaseOrder" | "qualityDocument" | "supplier"+ approvalDocumentType:+ | "purchaseOrder"+ | "qualityDocument"+ | "supplier"+ | "changeOrder"approvalStatus: "Pending" | "Approved" | "Rejected" | "Cancelled"assemblyInstructionStatus: "Draft" | "Published" | "Archived"assemblyStepStatus: "Todo" | "Review" | "Done"@@ -93710,7 +93714,12 @@ export const Constants = {"Tax","Investments",],- approvalDocumentType: ["purchaseOrder", "qualityDocument", "supplier"],+ approvalDocumentType: [+ "purchaseOrder",+ "qualityDocument",+ "supplier",+ "changeOrder",+ ],approvalStatus: ["Pending", "Approved", "Rejected", "Cancelled"],assemblyInstructionStatus: ["Draft", "Published", "Archived"],assemblyStepStatus: ["Todo", "Review", "Done"],diff --git a/packages/database/supabase/migrations/20261008164140_change-order-approvals.sql b/packages/database/supabase/migrations/20261008164140_change-order-approvals.sqlnew file mode 100644index 0000000000..0c7c6ec6b3--- /dev/null+++ b/packages/database/supabase/migrations/20261008164140_change-order-approvals.sql@@ -0,0 +1,40 @@+-- Change notices (table "changeOrder") become an approval document type: an+-- approval rule gates Engineering Complete -> Implementation. Approval logic+-- lives in TypeScript, so this only adds the enum value and the view branch.+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'changeOrder';+COMMIT;++DROP VIEW IF EXISTS "approvalRequests";+CREATE OR REPLACE VIEW "approvalRequests" WITH (SECURITY_INVOKER=true) AS+SELECT+ ar."id",+ ar."documentType",+ ar."documentId",+ ar."status",+ ar."requestedBy",+ ar."requestedAt",+ ar."decisionBy",+ ar."decisionAt",+ ar."decisionNotes",+ ar."companyId",+ ar."createdAt",+ CASE+ WHEN ar."documentType" = 'purchaseOrder' THEN po."purchaseOrderId"+ WHEN ar."documentType" = 'qualityDocument' THEN qd."name"+ WHEN ar."documentType" = 'supplier' THEN sup."name"+ WHEN ar."documentType" = 'changeOrder' THEN co."changeOrderId"+ ELSE NULL+ END AS "documentReadableId",+ CASE+ WHEN ar."documentType" = 'purchaseOrder' THEN s."name"+ WHEN ar."documentType" = 'qualityDocument' THEN qd."description"+ WHEN ar."documentType" = 'supplier' THEN NULL+ WHEN ar."documentType" = 'changeOrder' THEN co."name"+ ELSE NULL+ END AS "documentDescription"+FROM "approvalRequest" ar+LEFT JOIN "purchaseOrder" po ON ar."documentType" = 'purchaseOrder' AND ar."documentId" = po."id"+LEFT JOIN "supplier" s ON po."supplierId" = s."id"+LEFT JOIN "qualityDocument" qd ON ar."documentType" = 'qualityDocument' AND ar."documentId" = qd."id"+LEFT JOIN "supplier" sup ON ar."documentType" = 'supplier' AND ar."documentId" = sup."id"+LEFT JOIN "changeOrder" co ON ar."documentType" = 'changeOrder' AND ar."documentId" = co."id" AND ar."companyId" = co."companyId";diff --git a/packages/database/supabase/migrations/20261008171101_change-order-audit-events.sql b/packages/database/supabase/migrations/20261008171101_change-order-audit-events.sqlnew file mode 100644index 0000000000..d8b0bcf2ff--- /dev/null+++ b/packages/database/supabase/migrations/20261008171101_change-order-audit-events.sql@@ -0,0 +1,11 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('changeOrder', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('changeOrderActionTask', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('changeOrderAffectedItem', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('changeOrderSupersession', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+RESET lock_timeout;diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex d826f1e420..203006f562 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -41,6 +41,7 @@ pnpm --filter @carbon/ee typecheck| `./ramp.server` | Ramp client, schemas, service operations, money/coding helpers, and key-owned state patches || `./ramp/hooks.server` | `rampOnInstall`, `rampOnUpdate`, `rampOnUninstall`, `rampHealthcheck` || `./hooks.server` | `getIntegrationServerHooks()` registry |+| `./approvals/document.server` | The document-level approval lifecycle shared by every approval document type: `getDocumentApprovalState`, `openApprovalRequests` (bulk; caller sends the notification), `cancelPendingApprovals` (bulk, optional requester-or-approver guard), `decideApprovalRequest`. Form validator: `approvalDecisionValidator` in `./approvals`; modal: `~/components/Modals/ApprovalDecision` in the ERP. Used by change notices, quality documents and suppliers; purchase orders keep their own amount-tiered flow || `./plan`, `./plan.server` | Client/server edition and feature-plan gates || `./sso.server` | SAML connection, domain verification, session, and provisioning helpers || `./storage-rules`, `./storage-rules.server` | Storage-rule schemas and server operations |diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex e21a1a9f83..03e8225356 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -8,6 +8,7 @@"./api-keys.server": "./src/api-keys.server.ts","./approvals": "./src/approvals/index.ts","./approvals.server": "./src/approvals/service.ts",+ "./approvals/document.server": "./src/approvals/document.server.ts","./audit.server": "./src/audit/audit.ts","./backups.server": "./src/backups.server.ts","./console.server": "./src/console.server.ts",diff --git a/packages/ee/src/approvals/document.server.ts b/packages/ee/src/approvals/document.server.tsnew file mode 100644index 0000000000..34e78dc5f9--- /dev/null+++ b/packages/ee/src/approvals/document.server.ts@@ -0,0 +1,279 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { datetime } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ approveRequest,+ canApproveRequest,+ getApprovalRuleByAmount,+ getApproverUserIdsForRule,+ isApprovalRequired,+ rejectRequest+} from "./service";+import type {+ ApprovalDecision,+ ApprovalDocumentRef,+ ApprovalDocumentsRef,+ DocumentApprovalState+} from "./types";++// The document-level approval lifecycle (state, open, cancel, decide), shared by+// every approval document type. Each takes the service role: approvalRequest has+// no RLS policies. Notifications stay with the caller, because @carbon/ee must+// not depend on @carbon/jobs.++export async function getDocumentApprovalState(+ serviceRole: SupabaseClient<Database>,+ doc: ApprovalDocumentRef & { userId: string; amount?: number }+): Promise<DocumentApprovalState> {+ const [latest, isRequired, canApprove] = await Promise.all([+ serviceRole+ .from("approvalRequest")+ .select("id, status, requestedBy, decisionBy, decisionNotes, decisionAt")+ .eq("documentType", doc.documentType)+ .eq("documentId", doc.documentId)+ .eq("companyId", doc.companyId)+ .order("requestedAt", { ascending: false })+ .limit(1)+ .maybeSingle(),+ isApprovalRequired(+ serviceRole,+ doc.documentType,+ doc.companyId,+ doc.amount+ ),+ canApproveRequest(+ serviceRole,+ {+ amount: doc.amount ?? null,+ documentType: doc.documentType,+ companyId: doc.companyId+ },+ doc.userId+ )+ ]);++ const request = latest.data;+ const isPending = request?.status === "Pending";++ return {+ pendingRequestId: isPending ? request.id : null,+ pendingRequestedBy: isPending ? request.requestedBy : null,+ canApprove,+ isRequired,+ // The latest request's decision only: a newer pending or cancelled request+ // supersedes an older approval or rejection.+ lastDecision:+ request?.status === "Approved" || request?.status === "Rejected"+ ? {+ status: request.status,+ decisionBy: request.decisionBy,+ notes: request.decisionNotes,+ decisionAt: request.decisionAt+ }+ : null+ };+}++export type OpenApprovalResult =+ | { status: "not-required" }+ | { status: "failed" }+ | {+ status: "opened";+ /** Documents that got a new request. */+ requested: string[];+ /** Documents skipped because a request was already pending. */+ alreadyPending: string[];+ approverIds: string[];+ };++/**+ * Opens one request per document when an enabled rule applies. Takes several+ * documents because some screens change status in bulk; the rule, the pending+ * check and the insert are one query each. The caller notifies `approverIds`.+ */+export async function openApprovalRequests(+ serviceRole: SupabaseClient<Database>,+ docs: ApprovalDocumentsRef & { userId: string; amount?: number }+): Promise<OpenApprovalResult> {+ const rule = await getApprovalRuleByAmount(+ serviceRole,+ docs.documentType,+ docs.companyId,+ docs.amount+ );+ if (!rule.data) return { status: "not-required" };++ const pending = await serviceRole+ .from("approvalRequest")+ .select("documentId")+ .eq("documentType", docs.documentType)+ .in("documentId", docs.documentIds)+ .eq("companyId", docs.companyId)+ .eq("status", "Pending");+ if (pending.error) return { status: "failed" };++ const pendingIds = new Set((pending.data ?? []).map((r) => r.documentId));+ const requested = docs.documentIds.filter((id) => !pendingIds.has(id));++ if (requested.length > 0) {+ const created = await serviceRole.from("approvalRequest").insert(+ requested.map((documentId) => ({+ documentType: docs.documentType,+ documentId,+ companyId: docs.companyId,+ requestedBy: docs.userId,+ createdBy: docs.userId,+ amount: docs.amount ?? null+ }))+ );+ if (created.error) return { status: "failed" };+ }++ return {+ status: "opened",+ requested,+ alreadyPending: docs.documentIds.filter((id) => pendingIds.has(id)),+ approverIds:+ requested.length > 0+ ? await getApproverUserIdsForRule(serviceRole, rule.data)+ : []+ };+}++export type CancelApprovalsResult =+ | { error: null }+ | { error: { code: "forbidden" | "failed"; message: string } };++/**+ * Withdraws the pending requests of documents that were closed, deleted or sent+ * back. With `onlyRequesterOrApprover`, a user who neither asked for nor can+ * decide a request may not withdraw it.+ */+export async function cancelPendingApprovals(+ serviceRole: SupabaseClient<Database>,+ docs: ApprovalDocumentsRef & {+ userId: string;+ onlyRequesterOrApprover?: boolean;+ }+): Promise<CancelApprovalsResult> {+ if (docs.onlyRequesterOrApprover) {+ const [pending, canApprove] = await Promise.all([+ serviceRole+ .from("approvalRequest")+ .select("requestedBy")+ .eq("documentType", docs.documentType)+ .in("documentId", docs.documentIds)+ .eq("companyId", docs.companyId)+ .eq("status", "Pending"),+ canApproveRequest(+ serviceRole,+ {+ amount: null,+ documentType: docs.documentType,+ companyId: docs.companyId+ },+ docs.userId+ )+ ]);+ const othersRequests = (pending.data ?? []).some(+ (r) => r.requestedBy !== docs.userId+ );+ if (othersRequests && !canApprove) {+ return {+ error: {+ code: "forbidden",+ message:+ "Only the requester or an approver can withdraw a pending approval request"+ }+ };+ }+ }++ const cancelled = await serviceRole+ .from("approvalRequest")+ .update({+ status: "Cancelled",+ updatedBy: docs.userId,+ updatedAt: datetime.timestamp()+ })+ .eq("documentType", docs.documentType)+ .in("documentId", docs.documentIds)+ .eq("companyId", docs.companyId)+ .eq("status", "Pending");++ return cancelled.error+ ? { error: { code: "failed", message: cancelled.error.message } }+ : { error: null };+}++export type DecideApprovalResult =+ | { error: null; requestedBy: string }+ | { error: { code: "not-found" | "forbidden" | "failed"; message: string } };++/**+ * Approves or rejects the document's pending request. The request id comes from+ * a form, so it must match the document's pending request and the caller's+ * company before `canApproveRequest` and the decision run.+ */+export async function decideApprovalRequest(+ serviceRole: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ doc: ApprovalDocumentRef & {+ userId: string;+ approvalRequestId: string;+ decision: ApprovalDecision;+ notes?: string;+ }+): Promise<DecideApprovalResult> {+ const pending = await serviceRole+ .from("approvalRequest")+ .select("id, amount, requestedBy")+ .eq("documentType", doc.documentType)+ .eq("documentId", doc.documentId)+ .eq("companyId", doc.companyId)+ .eq("status", "Pending")+ .eq("id", doc.approvalRequestId)+ .maybeSingle();++ if (!pending.data) {+ return {+ error: { code: "not-found", message: "Approval request not found" }+ };+ }++ const canApprove = await canApproveRequest(+ serviceRole,+ {+ amount: pending.data.amount,+ documentType: doc.documentType,+ companyId: doc.companyId+ },+ doc.userId+ );+ if (!canApprove) {+ return {+ error: {+ code: "forbidden",+ message: "You do not have permission to approve this request"+ }+ };+ }++ const decide = doc.decision === "Approved" ? approveRequest : rejectRequest;+ const result = await decide(+ db,+ doc.approvalRequestId,+ doc.userId,+ doc.notes || undefined+ );+ if (result.error) {+ return { error: { code: "failed", message: result.error.message } };+ }++ return { error: null, requestedBy: pending.data.requestedBy };+}diff --git a/packages/ee/src/approvals/models.ts b/packages/ee/src/approvals/models.tsindex a7e3e7cbeb..7b45a3615e 100644--- a/packages/ee/src/approvals/models.ts+++ b/packages/ee/src/approvals/models.ts@@ -6,18 +6,22 @@ import type { Database } from "@carbon/database";import { z } from "zod";import { zfd } from "zod-form-data";+// The approve / reject form every approval document type posts.export const approvalDecisionValidator = z.object({- id: zfd.text(z.string().optional()),+ approvalRequestId: z+ .string()+ .min(1, { message: "Approval request is required" }),decision: z.enum(["Approved", "Rejected"], {error: "Decision is required"}),- decisionNotes: zfd.text(z.string().optional())+ notes: zfd.text(z.string().optional())});export const approvalDocumentType = ["purchaseOrder","qualityDocument",- "supplier"+ "supplier",+ "changeOrder"] as const;export type ApprovalDocumentType =@@ -26,7 +30,8 @@ export type ApprovalDocumentType =export const approvalDocumentTypeLabel: Record<ApprovalDocumentType, string> = {purchaseOrder: "Purchase Order",qualityDocument: "Quality Document",- supplier: "Supplier"+ supplier: "Supplier",+ changeOrder: "Change Notice"};export const approvalDocumentTypesWithAmounts: ApprovalDocumentType[] = [diff --git a/packages/ee/src/approvals/service.ts b/packages/ee/src/approvals/service.tsindex adc661f443..f4b0f73951 100644--- a/packages/ee/src/approvals/service.ts+++ b/packages/ee/src/approvals/service.ts@@ -144,6 +144,27 @@ export async function approveRequest(if (!supplierUpdate) {throw new Error("Failed to update supplier status");}+ } else if (documentType === "changeOrder") {+ // Approval is the gate on Engineering Complete -> Implementation, so+ // approving performs that transition (only from the gated stage).+ const changeOrderUpdate = await trx+ .updateTable("changeOrder")+ .set({+ status: "Implementation",+ updatedBy: userId,+ updatedAt: now+ })+ .where("id", "=", documentId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Engineering Complete")+ .returning(["id"])+ .executeTakeFirst();++ if (!changeOrderUpdate) {+ throw new Error(+ "Failed to update change notice status - it may no longer be in 'Engineering Complete' state"+ );+ }}return updatedApproval;@@ -882,7 +903,8 @@ export async function rejectRequest();}}- // Note: qualityDocument rejection doesn't change status (stays Draft)+ // Note: qualityDocument rejection doesn't change status (stays Draft),+ // and neither does changeOrder (stays Engineering Complete)if (documentType === "supplier") {const supplierUpdate = await trxdiff --git a/packages/ee/src/approvals/types.ts b/packages/ee/src/approvals/types.tsindex b0056249bf..5f9a064302 100644--- a/packages/ee/src/approvals/types.ts+++ b/packages/ee/src/approvals/types.ts@@ -50,6 +50,33 @@ export type ApprovalRule = Database["public"]["Tables"]["approvalRule"]["Row"];export type ApprovalDecision = "Approved" | "Rejected";+/** One document under approval; every `document.server` helper takes this. */+export type ApprovalDocumentRef = {+ documentType: ApprovalDocumentType;+ documentId: string;+ companyId: string;+};++/** Several documents of one type, for the bulk helpers. */+export type ApprovalDocumentsRef = Omit<ApprovalDocumentRef, "documentId"> & {+ documentIds: string[];+};++/** What a document page needs to render its approval controls. */+export type DocumentApprovalState = {+ pendingRequestId: string | null;+ pendingRequestedBy: string | null;+ /** Whether the user is an approver under the rule, pending request or not. */+ canApprove: boolean;+ isRequired: boolean;+ lastDecision: {+ status: ApprovalDecision;+ decisionBy: string | null;+ notes: string | null;+ decisionAt: string | null;+ } | null;+};+export type ApprovalStatus = Database["public"]["Enums"]["approvalStatus"];export type CreateApprovalRequestInput = Omit<diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 7b568f4b1a..7d7cb23b48 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261007171726",+ "schemaVersion": "20261008171101","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-07T18:06:45.508Z",+ "exportedAt": "2026-10-09T04:43:53.337Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex adc43006b3..164237ee50 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -1265,6 +1265,35 @@ async function buildEventContent(};}+ if (opts.documentType === "changeOrder") {+ const co = await client+ .from("changeOrder")+ .select("changeOrderId, name, status")+ .eq("id", documentId)+ .eq("companyId", opts.companyId)+ .single();++ if (co.error || !co.data) {+ console.error(+ "Failed to retrieve change notice for approval notification",+ co.error+ );+ return {+ description: `Change notice ${docPhrase}`,+ details: []+ };+ }++ return {+ description: `Change notice ${co.data.changeOrderId} ${docPhrase}`,+ reference: co.data.changeOrderId ?? undefined,+ details: buildDetails([+ { label: "Name", value: co.data.name },+ { label: "Status", value: co.data.status }+ ])+ };+ }+return {description:outcome === "requested"diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 2d56019f6d..6a03a7d326 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} Rabatt"msgid "{dismissed} dismissed"msgstr "{dismissed} zurückgewiesen"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} von {total} Phasen abgeschlossen"@@ -2538,6 +2541,9 @@ msgstr "Genehmigungsdatum"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Genehmigung ist erforderlich bei oder über diesem Betrag, bis zum Minimum der nächsten Regel"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Genehmigungsanforderungen"@@ -2553,6 +2559,16 @@ msgstr "Genehmigungen"msgid "Approve"msgstr "Genehmigen"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Genehmigt von"@@ -2612,6 +2628,15 @@ msgstr "Sind Sie sicher, dass Sie den Prozess aktivieren möchten: {name}? Er wimsgid "Are you sure you want to activate this gauge?."msgstr "Möchten Sie dieses Prüfmittel wirklich aktivieren?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Möchten Sie {0} wirklich stornieren? Es wird geschlossen und schreibgeschützt, bis Sie es wieder öffnen."@@ -3013,9 +3038,18 @@ msgstr "Sind Sie sicher, dass Sie diesen Beleg buchen möchten?"msgid "Are you sure you want to post this shipment?"msgstr "Sind Sie sicher, dass Sie diese Lieferung buchen möchten?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Sind Sie sicher, dass Sie dieses Angebot ablehnen möchten?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Sind Sie sicher, dass Sie diesen Auftrag freigeben möchten? Er wird auf der Werkstatt verfügbar und treibt Einkauf und Produktion an."@@ -6949,6 +6983,9 @@ msgstr "Webhook löschen"msgid "Delete Workflow"msgstr "Workflow löschen"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Liefern"@@ -8950,6 +8987,9 @@ msgstr "Fehler beim Löschen der Datei vom alten Speicherort"msgid "Failed to download file for moving"msgstr "Fehler beim Herunterladen der Datei zum Verschieben"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Fehler beim Abrufen der Artikelkosten"@@ -12994,6 +13034,9 @@ msgstr "Neue Umlagerungsposition"msgid "New Unit of Measure"msgstr "Neue Mengeneinheit"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Neue Version"@@ -13427,6 +13470,9 @@ msgstr "Keine neuen Benachrichtigungen"msgid "No notes"msgstr "Keine Notizen"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Niemand besetzt"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Älteste zuerst"@@ -14906,6 +14955,9 @@ msgstr "PDF-Wasserzeichen"msgid "Pending"msgstr "Ausstehend"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "Personal"@@ -15856,9 +15908,6 @@ msgstr "Bestellmenge"msgid "Purchase Order Approval"msgstr "Bestellungsgenehmigung"-msgid "Purchase Order approval rule"-msgstr "Genehmigungsregel für Bestellung"-msgid "Purchase Order ID"msgstr "Bestellnummer"@@ -16025,8 +16074,8 @@ msgstr "qualität"msgid "Quality"msgstr "Qualität"-msgid "Quality Document approval rule"-msgstr "Genehmigungsregel für Qualitätsdokument"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Qualitätsdokumente"@@ -16523,6 +16572,9 @@ msgstr "Datensatz gelöscht"msgid "Record Deposit"msgstr "Anzahlung erfassen"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Erfassen Sie Prüfungen, die an einen Teil und einen Fertigungsauftrag gebunden sind"@@ -16643,6 +16695,16 @@ msgstr "Erstattungen"msgid "Reject"msgstr "Ablehnen"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Los ablehnen"@@ -17034,6 +17096,9 @@ msgstr "Erfordert einen zugewiesenen Werker, bevor der Planer Arbeiten an einemmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Erfordert eine Authentifizierungs-App, bevor jemand dieses Unternehmen öffnen kann. Ihre anderen Unternehmen sind nicht betroffen. Besuchen Sie die <0>Seite mit den Mitarbeiterkonten</0>, um den Status jeder Person zu sehen."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Genehmigung erforderlich, bevor Lieferanten auf Aktiv gesetzt werden können"@@ -17049,8 +17114,8 @@ msgstr "Abgleich erforderlich"msgid "Require SAML SSO"msgstr "SAML SSO erforderlich"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Erfordern Sie mehrstufige Genehmigungen für Bestellungen, Qualitätsdokumente und Lieferanten basierend auf Schwellenwertbeträgen und Genehmigungsgruppen."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Zwei-Faktor-Authentifizierung erforderlich"@@ -19683,6 +19748,9 @@ msgstr "Anonym einreichen"msgid "Submit for approval"msgstr "Zur Genehmigung einreichen"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Prüfung einreichen"@@ -21340,6 +21408,9 @@ msgstr "Diese Änderungsmitteilung wird gerade umgesetzt, daher sind ihre Ändermsgid "This change notice is closed, so its changes are read-only."msgstr "Diese Änderungsmitteilung ist geschlossen, daher sind ihre Änderungen schreibgeschützt."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Die Daten dieses Unternehmens werden durch den Inhalt dieser Sicherung ersetzt. Die heutigen Daten werden zuerst gespeichert, damit Sie rückgängig machen können."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 47d70cc63c..65cd2c55d3 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} off"msgid "{dismissed} dismissed"msgstr "{dismissed} dismissed"+msgid "{documentTypeLabel} approval rule"+msgstr "{documentTypeLabel} approval rule"+msgid "{done} of {total} phases complete"msgstr "{done} of {total} phases complete"@@ -2538,6 +2541,9 @@ msgstr "Approval Date"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Approval is required at or above this amount, up to the next rule's minimum"+msgid "Approval Rejected"+msgstr "Approval Rejected"+msgid "Approval requirements"msgstr "Approval requirements"@@ -2553,6 +2559,16 @@ msgstr "Approvals"msgid "Approve"msgstr "Approve"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr "Approve {0}"++msgid "Approve {changeOrderId}"+msgstr "Approve {changeOrderId}"++msgid "Approve {displayName}"+msgstr "Approve {displayName}"+msgid "Approved By"msgstr "Approved By"@@ -2612,6 +2628,15 @@ msgstr "Are you sure you want to activate the process: {name}? It will appear inmsgid "Are you sure you want to activate this gauge?."msgstr "Are you sure you want to activate this gauge?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr "Are you sure you want to approve this change notice? This moves it to Implementation."++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr "Are you sure you want to approve this quality document? This will make it active."++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr "Are you sure you want to approve this supplier? This will make it active."+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."@@ -3013,9 +3038,18 @@ msgstr "Are you sure you want to post this receipt?"msgid "Are you sure you want to post this shipment?"msgstr "Are you sure you want to post this shipment?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr "Are you sure you want to reject this quality document? The document will remain in draft status."+msgid "Are you sure you want to reject this quote?"msgstr "Are you sure you want to reject this quote?"+msgid "Are you sure you want to reject this supplier?"+msgstr "Are you sure you want to reject this supplier?"+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."@@ -6949,6 +6983,9 @@ msgstr "Delete Webhook"msgid "Delete Workflow"msgstr "Delete Workflow"+msgid "Deleted"+msgstr "Deleted"+msgid "Deliver"msgstr "Deliver"@@ -8950,6 +8987,9 @@ msgstr "Failed to delete file from old location"msgid "Failed to download file for moving"msgstr "Failed to download file for moving"+msgid "Failed to download history"+msgstr "Failed to download history"+msgid "Failed to fetch item costs"msgstr "Failed to fetch item costs"@@ -12994,6 +13034,9 @@ msgstr "New Transfer Line"msgid "New Unit of Measure"msgstr "New Unit of Measure"+msgid "New Value"+msgstr "New Value"+msgid "New Version"msgstr "New Version"@@ -13427,6 +13470,9 @@ msgstr "No new notifications"msgid "No notes"msgstr "No notes"+msgid "No notes were given."+msgstr "No notes were given."+msgid "No one assigned"msgstr "No one assigned"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr "Old Value"+msgid "Oldest first"msgstr "Oldest first"@@ -14906,6 +14955,9 @@ msgstr "PDF Watermark"msgid "Pending"msgstr "Pending"+msgid "Pending Approval"+msgstr "Pending Approval"+msgid "people"msgstr "people"@@ -15856,9 +15908,6 @@ msgstr "Purchase Order Amount"msgid "Purchase Order Approval"msgstr "Purchase Order Approval"-msgid "Purchase Order approval rule"-msgstr "Purchase Order approval rule"-msgid "Purchase Order ID"msgstr "Purchase Order ID"@@ -16025,8 +16074,8 @@ msgstr "quality"msgid "Quality"msgstr "Quality"-msgid "Quality Document approval rule"-msgstr "Quality Document approval rule"+msgid "Quality Document"+msgstr "Quality Document"msgid "Quality Documents"msgstr "Quality Documents"@@ -16523,6 +16572,9 @@ msgstr "Record deleted"msgid "Record Deposit"msgstr "Record Deposit"+msgid "Record ID"+msgstr "Record ID"+msgid "Record inspections tied to a part and a job"msgstr "Record inspections tied to a part and a job"@@ -16643,6 +16695,16 @@ msgstr "Reimbursements"msgid "Reject"msgstr "Reject"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr "Reject {0}"++msgid "Reject {changeOrderId}"+msgstr "Reject {changeOrderId}"++msgid "Reject {displayName}"+msgstr "Reject {displayName}"+msgid "Reject Lot"msgstr "Reject Lot"@@ -17034,6 +17096,9 @@ msgstr "Require an assigned operator before the scheduler places work at a locatmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."+msgid "Require approval before change notices move to Implementation"+msgstr "Require approval before change notices move to Implementation"+msgid "Require approval before suppliers can be set to Active"msgstr "Require approval before suppliers can be set to Active"@@ -17049,8 +17114,8 @@ msgstr "Require Match"msgid "Require SAML SSO"msgstr "Require SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."msgid "Require two-factor authentication"msgstr "Require two-factor authentication"@@ -19683,6 +19748,9 @@ msgstr "Submit anonymously"msgid "Submit for approval"msgstr "Submit for approval"+msgid "Submit for Approval"+msgstr "Submit for Approval"+msgid "Submit Inspection"msgstr "Submit Inspection"@@ -21340,6 +21408,9 @@ msgstr "This change notice is being implemented, so its changes are locked. Reopmsgid "This change notice is closed, so its changes are read-only."msgstr "This change notice is closed, so its changes are read-only."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex d111428d81..ddce930e51 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} descuento"msgid "{dismissed} dismissed"msgstr "{dismissed} descartado"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} de {total} fases completadas"@@ -2538,6 +2541,9 @@ msgstr "Fecha de Aprobación"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Se requiere aprobación en o por encima de este monto, hasta el mínimo de la siguiente regla"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Requisitos de aprobación"@@ -2553,6 +2559,16 @@ msgstr "Aprobaciones"msgid "Approve"msgstr "Aprobar"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Aprobado por"@@ -2612,6 +2628,15 @@ msgstr "¿Estás seguro de que deseas activar el proceso: {name}? Volverá a apamsgid "Are you sure you want to activate this gauge?."msgstr "¿Está seguro de que desea activar este instrumento de medición?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "¿Está seguro de que desea cancelar {0}? Será cerrado y de solo lectura hasta que lo reabra."@@ -3013,9 +3038,18 @@ msgstr "¿Estás seguro de que deseas publicar este recibo?"msgid "Are you sure you want to post this shipment?"msgstr "¿Estás seguro de que deseas publicar este envío?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "¿Estás seguro de que deseas rechazar esta cotización?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "¿Está seguro de que desea liberar esta orden de trabajo? Estará disponible para la planta e impulsará las compras y la producción."@@ -6949,6 +6983,9 @@ msgstr "Eliminar Webhook"msgid "Delete Workflow"msgstr "Eliminar flujo de trabajo"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Entregar"@@ -8950,6 +8987,9 @@ msgstr "Error al eliminar el archivo de la ubicación anterior"msgid "Failed to download file for moving"msgstr "Error al descargar el archivo para mover"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Error al obtener costos de artículos"@@ -12994,6 +13034,9 @@ msgstr "Nueva Línea de Transferencia"msgid "New Unit of Measure"msgstr "Nueva Unidad de Medida"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Nueva Versión"@@ -13427,6 +13470,9 @@ msgstr "Sin notificaciones nuevas"msgid "No notes"msgstr "Sin notas"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Nadie asignado"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "Aceptar"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Más antiguo primero"@@ -14906,6 +14955,9 @@ msgstr "Marca de agua PDF"msgid "Pending"msgstr "Pendiente"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "personal"@@ -15856,9 +15908,6 @@ msgstr "Monto de Orden de Compra"msgid "Purchase Order Approval"msgstr "Aprobación de Orden de Compra"-msgid "Purchase Order approval rule"-msgstr "Regla de aprobación de orden de compra"-msgid "Purchase Order ID"msgstr "ID de Orden de Compra"@@ -16025,8 +16074,8 @@ msgstr "Calidad"msgid "Quality"msgstr "Calidad"-msgid "Quality Document approval rule"-msgstr "Regla de aprobación de documento de calidad"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Documentos de Calidad"@@ -16523,6 +16572,9 @@ msgstr "Registro eliminado"msgid "Record Deposit"msgstr "Registrar Depósito"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Registrar inspecciones vinculadas a una parte y un trabajo"@@ -16643,6 +16695,16 @@ msgstr "Reembolsos"msgid "Reject"msgstr "Rechazar"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Rechazar Lote"@@ -17034,6 +17096,9 @@ msgstr "Requerir un operario asignado antes de que el programador coloque trabajmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Requiere una aplicación autenticadora antes de que alguien pueda abrir esta empresa. Sus otras empresas no se ven afectadas. Visita la <0>página de cuentas de empleados</0> para ver el estado de cada persona."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Requerir aprobación antes de que los proveedores puedan establecerse como Activos"@@ -17049,8 +17114,8 @@ msgstr "Requiere Coincidencia"msgid "Require SAML SSO"msgstr "Requerir SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Requiere aprobación escalonada en órdenes de compra, documentos de calidad y proveedores según umbrales de monto y grupos de aprobadores."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Requerir autenticación de dos factores"@@ -19683,6 +19748,9 @@ msgstr "Enviar anónimamente"msgid "Submit for approval"msgstr "Enviar para aprobación"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Enviar Inspección"@@ -21340,6 +21408,9 @@ msgstr "Este aviso de cambio se está implementando, por lo que sus cambios estmsgid "This change notice is closed, so its changes are read-only."msgstr "Este aviso de cambio está cerrado, por lo que sus cambios son de solo lectura."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Los datos de esta empresa se reemplazan con el contenido de esta copia de seguridad. Primero se guardan los datos de hoy para que pueda revertir."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex fce339504b..cf3c1b8989 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} de réduction"msgid "{dismissed} dismissed"msgstr "{dismissed} écartés"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} sur {total} phases terminées"@@ -2538,6 +2541,9 @@ msgstr "Date d'approbation"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "L'approbation est requise à partir de ce montant ou au-delà, jusqu'au minimum de la règle suivante"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Exigences d'approbation"@@ -2553,6 +2559,16 @@ msgstr "Approbations"msgid "Approve"msgstr "Approuver"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Approuvé par"@@ -2612,6 +2628,15 @@ msgstr "Êtes-vous sûr de vouloir activer le processus : {name} ? Il réapparamsgid "Are you sure you want to activate this gauge?."msgstr "Êtes-vous sûr de vouloir activer cet instrument de mesure ?"+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Êtes-vous sûr de vouloir annuler {0} ? Il sera fermé et en lecture seule jusqu'à ce que vous le rouvriez."@@ -3013,9 +3038,18 @@ msgstr "Êtes-vous sûr de vouloir valider ce reçu ?"msgid "Are you sure you want to post this shipment?"msgstr "Êtes-vous sûr de vouloir comptabiliser cette expédition ?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Êtes-vous sûr de vouloir rejeter ce devis ?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Êtes-vous sûr de vouloir lancer cet ordre de fabrication ? Il deviendra disponible à l'atelier et pilotera les achats et la production."@@ -6949,6 +6983,9 @@ msgstr "Supprimer le Webhook"msgid "Delete Workflow"msgstr "Supprimer le flux de travail"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Livrer"@@ -8950,6 +8987,9 @@ msgstr "Impossible de supprimer le fichier de l'ancien emplacement"msgid "Failed to download file for moving"msgstr "Échec du téléchargement du fichier pour le déplacement"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Échec de la récupération des coûts des articles"@@ -12994,6 +13034,9 @@ msgstr "Nouvelle Ligne de Transfert"msgid "New Unit of Measure"msgstr "Nouvelle Unité de Mesure"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Nouvelle Version"@@ -13427,6 +13470,9 @@ msgstr "Aucune nouvelle notification"msgid "No notes"msgstr "Aucune note"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Aucun membre d'équipe"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Le plus ancien en premier"@@ -14906,6 +14955,9 @@ msgstr "Filigrane PDF"msgid "Pending"msgstr "En attente"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "personnel"@@ -15856,9 +15908,6 @@ msgstr "Montant du bon de commande"msgid "Purchase Order Approval"msgstr "Approbation du bon de commande"-msgid "Purchase Order approval rule"-msgstr "Règle d'approbation de bon de commande"-msgid "Purchase Order ID"msgstr "Numéro de bon de commande"@@ -16025,8 +16074,8 @@ msgstr "qualité"msgid "Quality"msgstr "Qualité"-msgid "Quality Document approval rule"-msgstr "Règle d'approbation des documents de qualité"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Documents de Qualité"@@ -16523,6 +16572,9 @@ msgstr "Enregistrement supprimé"msgid "Record Deposit"msgstr "Enregistrer le dépôt"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Enregistrer les contrôles liés à une pièce et à un ordre de fabrication"@@ -16643,6 +16695,16 @@ msgstr "Remboursements"msgid "Reject"msgstr "Rejeter"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Rejeter le lot"@@ -17034,6 +17096,9 @@ msgstr "Exiger un opérateur assigné avant que le planificateur ne place le tramsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Exiger une application d'authentification avant que quiconque puisse ouvrir cette société. Leurs autres sociétés ne sont pas affectées. Visitez la <0>page des comptes employé</0> pour voir le statut de chaque personne."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Exiger une approbation avant que les fournisseurs puissent être définis comme Actifs"@@ -17049,8 +17114,8 @@ msgstr "Correspondance obligatoire"msgid "Require SAML SSO"msgstr "Exiger SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Exiger une approbation étagée sur les bons de commande, les documents de qualité et les fournisseurs en fonction des seuils de montant et des groupes d'approbateurs."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Exiger l'authentification à deux facteurs"@@ -19683,6 +19748,9 @@ msgstr "Soumettre anonymement"msgid "Submit for approval"msgstr "Soumettre pour approbation"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Soumettre le contrôle"@@ -21340,6 +21408,9 @@ msgstr "Cet avis de modification est en cours de mise en œuvre, donc ses modifimsgid "This change notice is closed, so its changes are read-only."msgstr "Cet avis de modification est clôturé, donc ses modifications sont en lecture seule."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Les données de cette société sont remplacées par le contenu de cette sauvegarde. Les données d'aujourd'hui sont d'abord enregistrées, afin que vous puissiez revenir en arrière."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 1bc3f1181c..9e0d575335 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} छूट"msgid "{dismissed} dismissed"msgstr "{dismissed} खारिज किया गया"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} में से {total} चरण पूर्ण"@@ -2538,6 +2541,9 @@ msgstr "अनुमोदन तारीख"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "इस राशि पर या इससे अधिक पर अनुमोदन आवश्यक है, अगले नियम की न्यूनतम राशि तक"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "अनुमोदन आवश्यकताएं"@@ -2553,6 +2559,16 @@ msgstr "अनुमोदन"msgid "Approve"msgstr "अनुमोदित करें"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "द्वारा अनुमोदित"@@ -2612,6 +2628,15 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to activate this gauge?."msgstr "क्या आप सुनिश्चित हैं कि आप इस गेज को सक्रिय करना चाहते हैं?"+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "क्या आप {0} को रद्द करना चाहते हैं? यह बंद हो जाएगी और पढ़ने के लिए केवल तब तक होगी जब तक आप इसे फिर से खोलेंगे।"@@ -3013,9 +3038,18 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to post this shipment?"msgstr "क्या आप सुनिश्चित हैं कि आप इस शिपमेंट को पोस्ट करना चाहते हैं?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "क्या आप निश्चित हैं कि आप इस कोटेशन को अस्वीकार करना चाहते हैं?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "क्या आप निश्चित हैं कि आप इस जॉब को जारी करना चाहते हैं? यह शॉप फ्लोर के लिए उपलब्ध हो जाएगा, और क्रय और उत्पादन को चलाएगा।"@@ -6949,6 +6983,9 @@ msgstr "वेबहुक हटाएं"msgid "Delete Workflow"msgstr "वर्कफ़्लो हटाएँ"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "डिलीवर करें"@@ -8950,6 +8987,9 @@ msgstr "पुराने स्थान से फ़ाइल हटानmsgid "Failed to download file for moving"msgstr "स्थानांतरण के लिए फ़ाइल डाउनलोड करने में विफल"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "आइटम लागत प्राप्त करने में विफल"@@ -12994,6 +13034,9 @@ msgstr "नई स्थानांतरण पंक्ति"msgid "New Unit of Measure"msgstr "नई माप की इकाई"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "नया संस्करण"@@ -13427,6 +13470,9 @@ msgstr "कोई नई सूचनाएं नहीं"msgid "No notes"msgstr "कोई नोट नहीं"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "कोई क्रू नहीं"@@ -13952,6 +13998,9 @@ msgstr "ठीक"msgid "OK"msgstr "ठीक है"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "सबसे पुराना पहले"@@ -14906,6 +14955,9 @@ msgstr "PDF वॉटरमार्क"msgid "Pending"msgstr "लंबित"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "लोग"@@ -15856,9 +15908,6 @@ msgstr "क्रय आदेश राशि"msgid "Purchase Order Approval"msgstr "क्रय आदेश अनुमोदन"-msgid "Purchase Order approval rule"-msgstr "क्रय आदेश अनुमोदन नियम"-msgid "Purchase Order ID"msgstr "क्रय आदेश ID"@@ -16025,8 +16074,8 @@ msgstr "गुणवत्ता"msgid "Quality"msgstr "गुणवत्ता"-msgid "Quality Document approval rule"-msgstr "गुणवत्ता दस्तावेज़ अनुमोदन नियम"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "गुणवत्ता दस्तावेज़"@@ -16523,6 +16572,9 @@ msgstr "रिकॉर्ड हटाया गया"msgid "Record Deposit"msgstr "जमा राशि रिकॉर्ड करें"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "एक भाग और एक कार्य से जुड़े निरीक्षण रिकॉर्ड करें"@@ -16643,6 +16695,16 @@ msgstr "प्रतिपूर्ति"msgid "Reject"msgstr "अस्वीकार करें"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "लॉट को अस्वीकार करें"@@ -17034,6 +17096,9 @@ msgstr "शेड्यूलर किसी स्थान पर कामmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "किसी को भी इस कंपनी को खोलने से पहले एक प्रमाणकर्ता ऐप की आवश्यकता है। उनकी अन्य कंपनियां प्रभावित नहीं हैं। प्रत्येक व्यक्ति की स्थिति देखने के लिए <0>कर्मचारी खातों पृष्ठ</0> पर जाएं।"+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "आपूर्तिकर्ताओं को सक्रिय पर सेट करने से पहले अनुमोदन की आवश्यकता है"@@ -17049,8 +17114,8 @@ msgstr "मिलान आवश्यक है"msgid "Require SAML SSO"msgstr "SAML SSO आवश्यक करें"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "राशि की सीमा और अनुमोदनकर्ता समूहों के आधार पर क्रय आदेशों, गुणवत्ता दस्तावेज़ों और आपूर्तिकर्ताओं पर स्तरीय अनुमोदन की आवश्यकता है।"+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "दो-कारक प्रमाणीकरण की आवश्यकता"@@ -19683,6 +19748,9 @@ msgstr "गुमनाम रूप से सबमिट करें"msgid "Submit for approval"msgstr "अनुमोदन के लिए सबमिट करें"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "निरीक्षण सबमिट करें"@@ -21340,6 +21408,9 @@ msgstr "यह परिवर्तन सूचना लागू की जmsgid "This change notice is closed, so its changes are read-only."msgstr "यह परिवर्तन सूचना बंद है, इसलिए इसके परिवर्तन केवल पढ़ने के लिए हैं।"+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "इस कंपनी का डेटा इस बैकअप की सामग्री के साथ प्रतिस्थापित किया जाता है। आज का डेटा पहले सहेजा जाता है, इसलिए आप पूर्ववत कर सकते हैं।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex d390932526..901a48dfa0 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} di sconto"msgid "{dismissed} dismissed"msgstr "{dismissed} scartati"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} di {total} fasi completate"@@ -2538,6 +2541,9 @@ msgstr "Data di approvazione"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "L'approvazione è richiesta a questo importo o superiore, fino al minimo della regola successiva"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Requisiti di approvazione"@@ -2553,6 +2559,16 @@ msgstr "Approvazioni"msgid "Approve"msgstr "Approva"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Approvato da"@@ -2612,6 +2628,15 @@ msgstr "Sei sicuro di voler attivare il processo: {name}? Apparirà di nuovo neimsgid "Are you sure you want to activate this gauge?."msgstr "Sei sicuro di voler attivare questo strumento di misura?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Sei sicuro di voler cancellare {0}? Sarà chiuso e in sola lettura fino a quando non lo riapri."@@ -3013,9 +3038,18 @@ msgstr "Sei sicuro di voler registrare questa ricevuta?"msgid "Are you sure you want to post this shipment?"msgstr "Sei sicuro di voler registrare questa spedizione?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Sei sicuro di voler rifiutare questa offerta?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Sei sicuro di voler rilasciare questo ordine di produzione? Sarà disponibile per l'officina e avvierà gli acquisti e la produzione."@@ -6949,6 +6983,9 @@ msgstr "Elimina Webhook"msgid "Delete Workflow"msgstr "Elimina flusso di lavoro"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Consegna"@@ -8950,6 +8987,9 @@ msgstr "Impossibile eliminare il file dalla posizione precedente"msgid "Failed to download file for moving"msgstr "Impossibile scaricare il file per lo spostamento"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Impossibile recuperare i costi degli articoli"@@ -12994,6 +13034,9 @@ msgstr "Nuova Riga di Trasferimento"msgid "New Unit of Measure"msgstr "Nuova Unità di Misura"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Nuova Versione"@@ -13427,6 +13470,9 @@ msgstr "Nessuna nuova notifica"msgid "No notes"msgstr "Nessuna nota"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Nessuno assegnato"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Più vecchio prima"@@ -14906,6 +14955,9 @@ msgstr "Filigrana PDF"msgid "Pending"msgstr "In attesa"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "personale"@@ -15856,9 +15908,6 @@ msgstr "Importo Ordine di Acquisto"msgid "Purchase Order Approval"msgstr "Approvazione ordine di acquisto"-msgid "Purchase Order approval rule"-msgstr "Regola di approvazione dell'ordine di acquisto"-msgid "Purchase Order ID"msgstr "ID Ordine di Acquisto"@@ -16025,8 +16074,8 @@ msgstr "qualità"msgid "Quality"msgstr "Qualità"-msgid "Quality Document approval rule"-msgstr "Regola di approvazione documento di qualità"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Documenti di Qualità"@@ -16523,6 +16572,9 @@ msgstr "Record eliminato"msgid "Record Deposit"msgstr "Registra acconto"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Registra i controlli legati a un componente e a un ordine di produzione"@@ -16643,6 +16695,16 @@ msgstr "Rimborsi"msgid "Reject"msgstr "Rifiuta"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Rifiuta Lotto"@@ -17034,6 +17096,9 @@ msgstr "Richiedi un operatore assegnato prima che lo scheduler assegni il lavoromsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Richiedi un'app autenticatore prima che chiunque possa aprire questa azienda. Le loro altre aziende non sono interessate. Visita la <0>pagina degli account dei dipendenti</0> per vedere lo stato di ogni persona."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Richiedi approvazione prima che i fornitori possano essere impostati su Attivo"@@ -17049,8 +17114,8 @@ msgstr "Richiedi Corrispondenza"msgid "Require SAML SSO"msgstr "Richiedi SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Richiedi approvazione per livelli su ordini di acquisto, documenti di qualità e fornitori in base a soglie di importo e gruppi di approvatori."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Richiedi autenticazione a due fattori"@@ -19683,6 +19748,9 @@ msgstr "Invia in modo anonimo"msgid "Submit for approval"msgstr "Invia per approvazione"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Invia controllo"@@ -21340,6 +21408,9 @@ msgstr "Questo avviso di modifica è in corso di implementazione, quindi le suemsgid "This change notice is closed, so its changes are read-only."msgstr "Questo avviso di modifica è chiuso, quindi le sue modifiche sono di sola lettura."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "I dati di questa azienda vengono sostituiti con il contenuto di questo backup. I dati di oggi vengono salvati per primi, quindi puoi ripristinare."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex e422c8ca14..137e25fcf3 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} 割引"msgid "{dismissed} dismissed"msgstr "{dismissed}件却下済み"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} / {total} フェーズ完了"@@ -2538,6 +2541,9 @@ msgstr "承認日"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "この金額以上で次のルールの最小値までの承認が必要です"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "承認要求事項"@@ -2553,6 +2559,16 @@ msgstr "承認"msgid "Approve"msgstr "承認"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "承認者"@@ -2612,6 +2628,15 @@ msgstr "プロセス「{name}」を有効化してもよろしいですか?ドmsgid "Are you sure you want to activate this gauge?."msgstr "この測定器を有効にしてもよろしいですか?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "{0} をキャンセルしてもよろしいですか?クローズ済になり、再オープンするまで読み取り専用になります。"@@ -3013,9 +3038,18 @@ msgstr "このレシートを転記してもよろしいですか?"msgid "Are you sure you want to post this shipment?"msgstr "この出荷を転記してもよろしいですか?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "この見積を却下してもよろしいですか?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "この製造指図をリリースしてもよろしいですか?これは製造現場で利用可能になり、購買と生産を推進します。"@@ -6949,6 +6983,9 @@ msgstr "Webhookを削除"msgid "Delete Workflow"msgstr "ワークフローを削除"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "配送"@@ -8950,6 +8987,9 @@ msgstr "古い場所からファイルを削除できませんでした"msgid "Failed to download file for moving"msgstr "ファイルの移動用ダウンロードに失敗しました"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "品目の原価を取得できませんでした"@@ -12994,6 +13034,9 @@ msgstr "新規転送明細"msgid "New Unit of Measure"msgstr "新しい測定単位"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "新しいバージョン"@@ -13427,6 +13470,9 @@ msgstr "新しい通知はありません"msgid "No notes"msgstr "メモなし"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "クルーなし"@@ -13952,6 +13998,9 @@ msgstr "OK"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "最も古いものから"@@ -14906,6 +14955,9 @@ msgstr "PDF透かし"msgid "Pending"msgstr "待機中"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "人員"@@ -15856,9 +15908,6 @@ msgstr "発注書金額"msgid "Purchase Order Approval"msgstr "発注書承認"-msgid "Purchase Order approval rule"-msgstr "発注書承認ルール"-msgid "Purchase Order ID"msgstr "発注書ID"@@ -16025,8 +16074,8 @@ msgstr "品質"msgid "Quality"msgstr "品質"-msgid "Quality Document approval rule"-msgstr "品質文書承認ルール"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "品質ドキュメント"@@ -16523,6 +16572,9 @@ msgstr "レコード削除済み"msgid "Record Deposit"msgstr "入金を記録"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "部品とジョブに関連付けられた検査を記録する"@@ -16643,6 +16695,16 @@ msgstr "払戻"msgid "Reject"msgstr "却下"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "ロットを却下"@@ -17034,6 +17096,9 @@ msgstr "スケジューラがある拠点に作業を配置する前に、割当msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "このアプリケーション認証器を要求して、誰もがこの会社を開く前に認証を要求します。他の会社は影響を受けません。<0>従業員アカウントページ</0>にアクセスして、各個人のステータスを確認してください。"+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "仕入先を有効に設定する前に承認が必要です"@@ -17049,8 +17114,8 @@ msgstr "照合が必須"msgid "Require SAML SSO"msgstr "SAML SSOを必須にする"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "金額閾値と承認者グループに基づいて、発注書、品質ドキュメント、および仕入先に対する段階的な承認を要求します。"+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "二要素認証が必要です"@@ -19683,6 +19748,9 @@ msgstr "匿名で提出"msgid "Submit for approval"msgstr "承認のため提出"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "検査を提出"@@ -21340,6 +21408,9 @@ msgstr "この変更通知は実施中のため、その変更はロック中でmsgid "This change notice is closed, so its changes are read-only."msgstr "この変更通知は閉じられているため、変更は読み取り専用です。"+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "この会社のデータはこのバックアップの内容に置き換えられます。今日のデータが最初に保存されるため、元に戻すことができます。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 54f06767ab..3c767a7d18 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} 할인"msgid "{dismissed} dismissed"msgstr "{dismissed} 무시됨"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done}개 중 {total}개 단계 완료"@@ -2538,6 +2541,9 @@ msgstr "승인일"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "이 금액 이상부터 다음 규칙의 최소값 미만까지는 승인이 필요합니다"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "승인 요구사항"@@ -2553,6 +2559,16 @@ msgstr "승인"msgid "Approve"msgstr "승인"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "승인자"@@ -2612,6 +2628,15 @@ msgstr "공정 {name}을(를) 활성화하시겠습니까? 드롭다운에 다msgid "Are you sure you want to activate this gauge?."msgstr "이 계측기를 활성화하시겠습니까?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "{0}를 취소하시겠습니까? 다시 열기할 때까지 마감되고 읽기 전용이 됩니다."@@ -3013,9 +3038,18 @@ msgstr "이 입고를 전기하시겠습니까?"msgid "Are you sure you want to post this shipment?"msgstr "이 출하를 전기하시겠습니까?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "이 견적서를 거부하시겠습니까?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "이 작업 지시를 릴리스하시겠습니까? 현장에서 가용하게 되며 구매 및 생산을 드라이브합니다."@@ -6949,6 +6983,9 @@ msgstr "웹훅 삭제"msgid "Delete Workflow"msgstr "워크플로우 삭제"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "배송"@@ -8950,6 +8987,9 @@ msgstr "이전 위치에서 파일 삭제 실패"msgid "Failed to download file for moving"msgstr "이동을 위한 파일 다운로드 실패"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "품목 원가 조회 실패"@@ -12994,6 +13034,9 @@ msgstr "신규 이송 라인"msgid "New Unit of Measure"msgstr "새 측정 단위"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "새 버전"@@ -13427,6 +13470,9 @@ msgstr "새 알림이 없습니다"msgid "No notes"msgstr "메모 없음"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "배치된 사람이 없습니다"@@ -13952,6 +13998,9 @@ msgstr "확인"msgid "OK"msgstr "확인"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "오래된순"@@ -14906,6 +14955,9 @@ msgstr "PDF 워터마크"msgid "Pending"msgstr "대기 중"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "인원"@@ -15856,9 +15908,6 @@ msgstr "발주서 금액"msgid "Purchase Order Approval"msgstr "발주서 승인"-msgid "Purchase Order approval rule"-msgstr "발주서 승인 규칙"-msgid "Purchase Order ID"msgstr "발주서 ID"@@ -16025,8 +16074,8 @@ msgstr "품질"msgid "Quality"msgstr "품질"-msgid "Quality Document approval rule"-msgstr "품질 문서 승인 규칙"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "품질 문서"@@ -16523,6 +16572,9 @@ msgstr "레코드가 삭제됨"msgid "Record Deposit"msgstr "선금 기록"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "품목과 작업에 연결된 검사를 기록"@@ -16643,6 +16695,16 @@ msgstr "환급금"msgid "Reject"msgstr "거부"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "로트 거부"@@ -17034,6 +17096,9 @@ msgstr "스케줄러가 사업장에 작업을 배치하기 전에 할당된 작msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "이 회사를 열기 전에 인증자 앱을 요구합니다. 다른 회사는 영향을 받지 않습니다. <0>직원 계정 페이지</0>를 방문하여 각 사람의 상태를 확인하세요."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "공급업체를 활성 상태로 설정하기 전에 승인 필요"@@ -17049,8 +17114,8 @@ msgstr "필수 일치"msgid "Require SAML SSO"msgstr "SAML SSO 필수"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "금액 한계 및 승인자 그룹을 기준으로 발주서, 품질 문서, 공급업체에 대한 단계별 승인을 요구합니다."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "2단계 인증 필수"@@ -19683,6 +19748,9 @@ msgstr "익명으로 제출"msgid "Submit for approval"msgstr "승인을 위해 제출"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "검사 제출"@@ -21340,6 +21408,9 @@ msgstr "이 변경 통지가 구현 중이므로 변경 사항이 잠겨 있습msgid "This change notice is closed, so its changes are read-only."msgstr "이 변경 통지는 마감되었으므로 변경 사항은 읽기 전용입니다."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "이 회사의 데이터는 이 백업의 내용으로 바뀝니다. 오늘의 데이터가 먼저 저장되므로 되돌릴 수 있습니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 104f51c811..50b59d019c 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} rabatu"msgid "{dismissed} dismissed"msgstr "{dismissed} odrzucone"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} z {total} faz ukończonych"@@ -2538,6 +2541,9 @@ msgstr "Data zatwierdzenia"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Zatwierdzenie jest wymagane przy tej kwocie lub wyższej, aż do minimum następnej reguły"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Wymagania dotyczące zatwierdzenia"@@ -2553,6 +2559,16 @@ msgstr "Zatwierdzenia"msgid "Approve"msgstr "Zatwierdź"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Zatwierdzone przez"@@ -2612,6 +2628,15 @@ msgstr "Czy na pewno chcesz aktywować proces: {name}? Pojawi się ponownie w limsgid "Are you sure you want to activate this gauge?."msgstr "Czy chcesz aktywować ten przyrząd pomiarowy?"+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Czy na pewno chcesz anulować {0}? Będzie zamknięte i tylko do odczytu do momentu, gdy je ponownie otworzysz."@@ -3013,9 +3038,18 @@ msgstr "Czy na pewno chcesz zaksięgować ten dokument przyjęcia?"msgid "Are you sure you want to post this shipment?"msgstr "Czy chcesz zaksięgować tę wysyłkę?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Czy na pewno chcesz odrzucić tę ofertę?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Czy na pewno chcesz zwolnić to zlecenie produkcyjne? Stanie się dostępne dla hali produkcyjnej i uruchomi procesy zakupów i produkcji."@@ -6949,6 +6983,9 @@ msgstr "Usuń Webhook"msgid "Delete Workflow"msgstr "Usuń przepływ pracy"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Dostarcz"@@ -8950,6 +8987,9 @@ msgstr "Nie udało się usunąć pliku ze starej lokalizacji"msgid "Failed to download file for moving"msgstr "Nie udało się pobrać pliku do przeniesienia."+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Nie udało się pobrać kosztów pozycji"@@ -12994,6 +13034,9 @@ msgstr "Nowa Pozycja przesunięcia"msgid "New Unit of Measure"msgstr "Nowa jednostka miary"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Nowa wersja"@@ -13427,6 +13470,9 @@ msgstr "Brak nowych powiadomień"msgid "No notes"msgstr "Brak notatek"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Nikogo nie przydzielono"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Najstarsze najpierw"@@ -14906,6 +14955,9 @@ msgstr "Znak wodny PDF"msgid "Pending"msgstr "Oczekujące"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "pracownicy"@@ -15856,9 +15908,6 @@ msgstr "Kwota Zamówienia Zakupu"msgid "Purchase Order Approval"msgstr "Zatwierdzenie zamówienia zakupu"-msgid "Purchase Order approval rule"-msgstr "Reguła zatwierdzania zamówienia zakupu"-msgid "Purchase Order ID"msgstr "Numer zamówienia zakupu"@@ -16025,8 +16074,8 @@ msgstr "jakość"msgid "Quality"msgstr "Jakość"-msgid "Quality Document approval rule"-msgstr "Reguła zatwierdzania dokumentu jakości"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Dokumenty Jakości"@@ -16523,6 +16572,9 @@ msgstr "Rekord usunięty"msgid "Record Deposit"msgstr "Zarejestruj depozyt"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Zarejestruj kontrole powiązane z częścią i zleceniem produkcyjnym"@@ -16643,6 +16695,16 @@ msgstr "Zwroty"msgid "Reject"msgstr "Odrzuć"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Odrzuć partię"@@ -17034,6 +17096,9 @@ msgstr "Wymagaj przypisanego operatora, zanim harmonogram umieści pracę w lokamsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Wymagaj aplikacji authenticator przed otwarciem tej firmy. Pozostałe firmy danej osoby nie są objęte. Odwiedź <0>stronę kont pracowników</0>, aby zobaczyć status każdej osoby."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Wymagaj zatwierdzenia zanim dostawcy będą mogli być ustawieni na Aktywny"@@ -17049,8 +17114,8 @@ msgstr "Wymaga dopasowania"msgid "Require SAML SSO"msgstr "Wymagaj SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Wymagaj wielopoziomowego zatwierdzenia zamówień zakupu, dokumentów jakości i dostawców na podstawie limitów kwot i grup zatwierdzających."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Wymagaj uwierzytelniania dwuskładnikowego"@@ -19683,6 +19748,9 @@ msgstr "Prześlij anonimowo"msgid "Submit for approval"msgstr "Prześlij do zatwierdzenia"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Prześlij kontrolę"@@ -21340,6 +21408,9 @@ msgstr "To zawiadomienie o zmianie jest wdrażane, więc jego zmiany są zablokomsgid "This change notice is closed, so its changes are read-only."msgstr "To zawiadomienie o zmianie jest zamknięte, dlatego jego zmiany są tylko do odczytu."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Dane tej firmy są zastępowane zawartością tej kopii zapasowej. Dane z dzisiaj są najpierw zapisywane, aby można było cofnąć."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 6e30e40234..4deba2b895 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} de desconto"msgid "{dismissed} dismissed"msgstr "{dismissed} dispensados"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} de {total} fases concluídas"@@ -2538,6 +2541,9 @@ msgstr "Data de Aprovação"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "A aprovação é necessária neste valor ou acima dele, até o mínimo da próxima regra"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Requisitos de aprovação"@@ -2553,6 +2559,16 @@ msgstr "Aprovações"msgid "Approve"msgstr "Aprovar"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Aprovado Por"@@ -2612,6 +2628,15 @@ msgstr "Tem a certeza de que deseja ativar o processo: {name}? Ele aparecerá nomsgid "Are you sure you want to activate this gauge?."msgstr "Tem certeza de que deseja ativar este instrumento de medição?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Tem certeza de que deseja cancelar {0}? Será fechado e somente leitura até que você o reabra."@@ -3013,9 +3038,18 @@ msgstr "Tem a certeza de que deseja publicar este recibo?"msgid "Are you sure you want to post this shipment?"msgstr "Tem certeza de que deseja contabilizar esta remessa?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Tem a certeza de que deseja rejeitar esta cotação?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Tem a certeza de que deseja liberar este trabalho? Ele ficará disponível para o chão de fábrica e impulsionará compras e produção."@@ -6949,6 +6983,9 @@ msgstr "Excluir Webhook"msgid "Delete Workflow"msgstr "Excluir Fluxo de trabalho"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Entregar"@@ -8950,6 +8987,9 @@ msgstr "Falha ao excluir arquivo do local anterior"msgid "Failed to download file for moving"msgstr "Falha ao baixar arquivo para mover"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Falha ao buscar custos de itens"@@ -12994,6 +13034,9 @@ msgstr "Nova Linha de Transferência"msgid "New Unit of Measure"msgstr "Nova Unidade de Medida"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Nova Versão"@@ -13427,6 +13470,9 @@ msgstr "Sem notificações novas"msgid "No notes"msgstr "Nenhuma observação"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Ninguém na equipe"@@ -13952,6 +13998,9 @@ msgstr "ok"msgid "OK"msgstr "OK"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Mais antigos primeiro"@@ -14906,6 +14955,9 @@ msgstr "Marca d'água do PDF"msgid "Pending"msgstr "Pendente"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "pessoas"@@ -15856,9 +15908,6 @@ msgstr "Valor do Pedido de Compra"msgid "Purchase Order Approval"msgstr "Aprovação de pedido de compra"-msgid "Purchase Order approval rule"-msgstr "Regra de aprovação de pedido de compra"-msgid "Purchase Order ID"msgstr "ID do pedido de compra"@@ -16025,8 +16074,8 @@ msgstr "qualidade"msgid "Quality"msgstr "Qualidade"-msgid "Quality Document approval rule"-msgstr "Regra de aprovação de Documento de Qualidade"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Documentos de Qualidade"@@ -16523,6 +16572,9 @@ msgstr "Registro eliminado"msgid "Record Deposit"msgstr "Registrar Depósito"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Registar inspeções vinculadas a uma peça e um trabalho"@@ -16643,6 +16695,16 @@ msgstr "Reembolsos"msgid "Reject"msgstr "Rejeitar"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Rejeitar Lote"@@ -17034,6 +17096,9 @@ msgstr "Exigir um operador atribuído antes que o programador coloque trabalho emsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Requer um aplicativo autenticador antes de qualquer pessoa poder abrir esta empresa. Suas outras empresas não são afetadas. Visite a <0>página de contas de funcionários</0> para ver o status de cada pessoa."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Exigir aprovação antes que fornecedores possam ser definidos como Ativos"@@ -17049,8 +17114,8 @@ msgstr "Exigir Correspondência"msgid "Require SAML SSO"msgstr "Exigir SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Exija aprovação em camadas em pedidos de compra, documentos de qualidade e fornecedores com base em limites de valor e grupos de aprovadores."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Requerer autenticação de dois fatores"@@ -19683,6 +19748,9 @@ msgstr "Enviar anonimamente"msgid "Submit for approval"msgstr "Enviar para aprovação"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Enviar Inspeção"@@ -21340,6 +21408,9 @@ msgstr "Este aviso de mudança está sendo implementado, portanto suas alteraçmsgid "This change notice is closed, so its changes are read-only."msgstr "Este aviso de mudança está fechado, portanto suas alterações são somente leitura."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Os dados desta empresa são substituídos pelo conteúdo deste backup. Os dados de hoje são salvos primeiro, para que você possa reverter."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 83854fd9dd..d5eb5672bb 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} скидка"msgid "{dismissed} dismissed"msgstr "{dismissed} отклонено"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} из {total} этапов завершено"@@ -2538,6 +2541,9 @@ msgstr "Дата утверждения"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Утверждение требуется для сумм, равных этой сумме или выше, вплоть до минимума следующего правила"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Требования утверждения"@@ -2553,6 +2559,16 @@ msgstr "Утверждения"msgid "Approve"msgstr "Утвердить"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Одобрено"@@ -2612,6 +2628,15 @@ msgstr "Вы уверены, что хотите активировать проmsgid "Are you sure you want to activate this gauge?."msgstr "Вы уверены, что хотите активировать это средство измерения?"+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "Вы уверены, что хотите отменить {0}? Он будет закрыт и доступен только для чтения, пока вы его не откроете заново."@@ -3013,9 +3038,18 @@ msgstr "Вы уверены, что хотите провести этот прmsgid "Are you sure you want to post this shipment?"msgstr "Вы уверены, что хотите провести эту отгрузку?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Вы уверены, что хотите отклонить это предложение?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Вы уверены, что хотите запустить в работу этот производственный заказ? Он станет доступен цеху и начнет управлять закупками и производством."@@ -6949,6 +6983,9 @@ msgstr "Удалить вебхук"msgid "Delete Workflow"msgstr "Удалить рабочий процесс"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Доставить"@@ -8950,6 +8987,9 @@ msgstr "Не удалось удалить файл из старого местmsgid "Failed to download file for moving"msgstr "Не удалось скачать файл для перемещения"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Ошибка при получении себестоимости номенклатуры"@@ -12994,6 +13034,9 @@ msgstr "Новая Строка перемещения"msgid "New Unit of Measure"msgstr "Новая единица измерения"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Новая версия"@@ -13427,6 +13470,9 @@ msgstr "Нет новых уведомлений"msgid "No notes"msgstr "Нет примечаний"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Никто не назначен"@@ -13952,6 +13998,9 @@ msgstr "хорошо"msgid "OK"msgstr "ОК"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "Сначала самые старые"@@ -14906,6 +14955,9 @@ msgstr "Водяной знак PDF"msgid "Pending"msgstr "Ожидание"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "сотрудники"@@ -15856,9 +15908,6 @@ msgstr "Сумма заказа поставщику"msgid "Purchase Order Approval"msgstr "Утверждение заказа поставщику"-msgid "Purchase Order approval rule"-msgstr "Правило утверждения заказа поставщику"-msgid "Purchase Order ID"msgstr "ID Заказа поставщику"@@ -16025,8 +16074,8 @@ msgstr "качество"msgid "Quality"msgstr "Качество"-msgid "Quality Document approval rule"-msgstr "Правило утверждения документа качества"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Документы качества"@@ -16523,6 +16572,9 @@ msgstr "Запись удалена"msgid "Record Deposit"msgstr "Учесть авансовый платеж"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Зарегистрировать контроль, связанный с деталью и производственным заказом"@@ -16643,6 +16695,16 @@ msgstr "Возмещения"msgid "Reject"msgstr "Отклонить"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Отклонить партию"@@ -17034,6 +17096,9 @@ msgstr "Требовать назначенного оператора переmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Требовать приложение аутентификатора перед тем как кто-либо сможет открыть эту организацию. Их другие организации не затронуты. Посетите страницу <0>учетных записей сотрудников</0>, чтобы увидеть статус каждого человека."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Требовать утверждение перед установкой статуса «Активный» для поставщиков"@@ -17049,8 +17114,8 @@ msgstr "Требовать совпадение"msgid "Require SAML SSO"msgstr "Требовать SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Требовать многоуровневого одобрения заказов поставщикам, документов качества и поставщиков на основе пороговых сумм и групп утверждающих."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "Требовать двухфакторную аутентификацию"@@ -19683,6 +19748,9 @@ msgstr "Отправить анонимно"msgid "Submit for approval"msgstr "Отправить на утверждение"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Отправить контроль"@@ -21340,6 +21408,9 @@ msgstr "Это извещение об изменении внедряется,msgid "This change notice is closed, so its changes are read-only."msgstr "Это извещение об изменении закрыто, поэтому его изменения доступны только для чтения."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Данные этой Организации заменяются содержимым этой резервной копии. Данные сегодня сохраняются первыми, поэтому вы можете вернуться."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 4be6997c99..565fd37247 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} indirim"msgid "{dismissed} dismissed"msgstr "{dismissed} reddedildi"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done} / {total} aşama tamamlandı"@@ -2538,6 +2541,9 @@ msgstr "Onay Tarihi"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "Onay, bu tutar veya daha yüksek bir tutarda ve sonraki kuralın minimumuna kadar gereklidir"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "Onay gereklilikleri"@@ -2553,6 +2559,16 @@ msgstr "Onaylar"msgid "Approve"msgstr "Onayla"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "Onaylayan"@@ -2612,6 +2628,15 @@ msgstr "İş akışını etkinleştirmek istediğinizden emin misiniz: {name}? Tmsgid "Are you sure you want to activate this gauge?."msgstr "Bu ölçüm aletini etkinleştirmek istediğinizden emin misiniz?."+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "{0} öğesini iptal etmek istediğinizden emin misiniz? Yeniden açana kadar kapalı ve salt okunur durumda olacaktır."@@ -3013,9 +3038,18 @@ msgstr "Bu makbuzu yayınlamak istediğinizden emin misiniz?"msgid "Are you sure you want to post this shipment?"msgstr "Bu sevkiyatı yayınlamak istediğinizden emin misiniz?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "Bu teklifi reddetmek istediğinizden emin misiniz?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "Bu iş emrini serbest bırakmak istediğinizden emin misiniz? Atölyede kullanılabilir hale gelecek ve satın almayı ve üretimi yönlendirecektir."@@ -6949,6 +6983,9 @@ msgstr "Webhook'u Sil"msgid "Delete Workflow"msgstr "İş Akışını Sil"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "Teslim Et"@@ -8950,6 +8987,9 @@ msgstr "Eski konumdan dosya silinemedi"msgid "Failed to download file for moving"msgstr "Taşınacak dosya indirilemedi"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "Ürün maliyetleri alınamadı"@@ -12994,6 +13034,9 @@ msgstr "Yeni Transfer Satırı"msgid "New Unit of Measure"msgstr "Yeni Bir Ölçü Birimi"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "Yeni Sürüm"@@ -13427,6 +13470,9 @@ msgstr "Yeni bildirim yok"msgid "No notes"msgstr "Notlar yok"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "Hiç kimse ekiplendirilmedi"@@ -13952,6 +13998,9 @@ msgstr "tamam"msgid "OK"msgstr "Tamam"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "En eski önce"@@ -14906,6 +14955,9 @@ msgstr "PDF Filigranı"msgid "Pending"msgstr "Beklemede"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "personel"@@ -15856,9 +15908,6 @@ msgstr "Satın Alma Siparişi Tutarı"msgid "Purchase Order Approval"msgstr "Satın Alma Siparişi Onayı"-msgid "Purchase Order approval rule"-msgstr "Satın Alma Siparişi onay kuralı"-msgid "Purchase Order ID"msgstr "Satın Alma Siparişi Numarası"@@ -16025,8 +16074,8 @@ msgstr "kalite"msgid "Quality"msgstr "Kalite"-msgid "Quality Document approval rule"-msgstr "Kalite Belgesi onay kuralı"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "Kalite Belgeleri"@@ -16523,6 +16572,9 @@ msgstr "Kayıt silindi"msgid "Record Deposit"msgstr "Depozitoyu Kaydet"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "Bir parça ve bir işe bağlı muayeneleri kaydedin"@@ -16643,6 +16695,16 @@ msgstr "Geri Ödemeler"msgid "Reject"msgstr "Reddet"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "Lotu Reddet"@@ -17034,6 +17096,9 @@ msgstr "Çizelgeleme sistemi bir lokasyon'da iş yerleştirmeden önce atanmışmsgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "Bu şirketi açabilmek için doğrulayıcı uygulamayı gerektir. Diğer şirketleri etkilenmez. Her kişinin durumunu görmek için <0>çalışan hesapları sayfasını</0> ziyaret edin."+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "Tedarikçilerin Aktif olarak ayarlanabilmesi için onay gerektirir"@@ -17049,8 +17114,8 @@ msgstr "Eşleştirme Gerekli"msgid "Require SAML SSO"msgstr "SAML SSO Gerekli"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "Satın alma siparişleri, kalite belgeler ve tedarikçiler için tutar eşikleri ve onaylayan gruplarına göre katmanlı imzayı talep edin."+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "İki faktörlü kimlik doğrulamayı gerektir"@@ -19683,6 +19748,9 @@ msgstr "Anonim olarak gönder"msgid "Submit for approval"msgstr "Onay için gönder"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "Muayeneyi Gönder"@@ -21340,6 +21408,9 @@ msgstr "Bu değişiklik bildirimi uygulanmakta olduğundan, değişiklikleri kilmsgid "This change notice is closed, so its changes are read-only."msgstr "Bu değişiklik bildirimi kapalı olduğundan, değişiklikleri salt okunurdur."+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "Bu şirketin verileri bu yedeklemenin içeriği ile değiştirilir. Bugünün verileri önce kaydedilir, bu nedenle geri alabilirsiniz."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex d53521dfca..e8e0cfece0 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -412,6 +412,9 @@ msgstr "{discount} 折扣"msgid "{dismissed} dismissed"msgstr "{dismissed} 已忽略"+msgid "{documentTypeLabel} approval rule"+msgstr ""+msgid "{done} of {total} phases complete"msgstr "{done}个/{total}个阶段已完成"@@ -2538,6 +2541,9 @@ msgstr "审批日期"msgid "Approval is required at or above this amount, up to the next rule's minimum"msgstr "此金额及以上需要审批,直到下一规则的最小值"+msgid "Approval Rejected"+msgstr ""+msgid "Approval requirements"msgstr "审批要求"@@ -2553,6 +2559,16 @@ msgstr "审批"msgid "Approve"msgstr "审批"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Approve {0}"+msgstr ""++msgid "Approve {changeOrderId}"+msgstr ""++msgid "Approve {displayName}"+msgstr ""+msgid "Approved By"msgstr "批准人"@@ -2612,6 +2628,15 @@ msgstr "您确定要激活流程:{name}?它将再次出现在下拉菜单中msgid "Are you sure you want to activate this gauge?."msgstr "确定要启用此量具吗?"+msgid "Are you sure you want to approve this change notice? This moves it to Implementation."+msgstr ""++msgid "Are you sure you want to approve this quality document? This will make it active."+msgstr ""++msgid "Are you sure you want to approve this supplier? This will make it active."+msgstr ""+#. placeholder {0}: routeData?.changeNotice?.changeOrderId ?? ""msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."msgstr "您确定要取消{0}吗?在您重新打开之前,它将被已关闭且只读。"@@ -3013,9 +3038,18 @@ msgstr "你确定要过账此收据吗?"msgid "Are you sure you want to post this shipment?"msgstr "你确定要过账此发货单吗?"+msgid "Are you sure you want to reject this change notice? It stays at Engineering Complete so it can be changed and submitted again."+msgstr ""++msgid "Are you sure you want to reject this quality document? The document will remain in draft status."+msgstr ""+msgid "Are you sure you want to reject this quote?"msgstr "你确定要拒绝此报价吗?"+msgid "Are you sure you want to reject this supplier?"+msgstr ""+msgid "Are you sure you want to release this job? It will become available to the shop floor, and drive purchasing and production."msgstr "确定要下达此工单吗?它将对车间可用,并驱动采购和生产。"@@ -6949,6 +6983,9 @@ msgstr "删除 Webhook"msgid "Delete Workflow"msgstr "删除工作流"+msgid "Deleted"+msgstr ""+msgid "Deliver"msgstr "交付"@@ -8950,6 +8987,9 @@ msgstr "删除旧位置的文件失败"msgid "Failed to download file for moving"msgstr "无法下载文件以进行移动"+msgid "Failed to download history"+msgstr ""+msgid "Failed to fetch item costs"msgstr "获取物料成本失败"@@ -12994,6 +13034,9 @@ msgstr "新建调拨行"msgid "New Unit of Measure"msgstr "新计量单位"+msgid "New Value"+msgstr ""+msgid "New Version"msgstr "新版本"@@ -13427,6 +13470,9 @@ msgstr "没有新通知"msgid "No notes"msgstr "没有备注"+msgid "No notes were given."+msgstr ""+msgid "No one assigned"msgstr "没有人员配备"@@ -13952,6 +13998,9 @@ msgstr "确定"msgid "OK"msgstr "确定"+msgid "Old Value"+msgstr ""+msgid "Oldest first"msgstr "最早优先"@@ -14906,6 +14955,9 @@ msgstr "PDF 水印"msgid "Pending"msgstr "待处理"+msgid "Pending Approval"+msgstr ""+msgid "people"msgstr "人员"@@ -15856,9 +15908,6 @@ msgstr "采购订单金额"msgid "Purchase Order Approval"msgstr "采购订单审批"-msgid "Purchase Order approval rule"-msgstr "采购订单审批规则"-msgid "Purchase Order ID"msgstr "采购订单ID"@@ -16025,8 +16074,8 @@ msgstr "质量"msgid "Quality"msgstr "质量"-msgid "Quality Document approval rule"-msgstr "质量文件审批规则"+msgid "Quality Document"+msgstr ""msgid "Quality Documents"msgstr "质量文档"@@ -16523,6 +16572,9 @@ msgstr "记录已删除"msgid "Record Deposit"msgstr "记录押金"+msgid "Record ID"+msgstr ""+msgid "Record inspections tied to a part and a job"msgstr "记录与零件和工作相关的检验"@@ -16643,6 +16695,16 @@ msgstr "报销"msgid "Reject"msgstr "拒绝"+#. placeholder {0}: routeData?.supplier?.name ?? ""+msgid "Reject {0}"+msgstr ""++msgid "Reject {changeOrderId}"+msgstr ""++msgid "Reject {displayName}"+msgstr ""+msgid "Reject Lot"msgstr "拒绝批次"@@ -17034,6 +17096,9 @@ msgstr "排程前需要已分配的操作员才能在地点安排工作。启用msgid "Require an authenticator app before anyone can open this company. Their other companies are unaffected. Visit the <0>employee accounts page</0> to see each person's status."msgstr "需要身份验证应用程序才能打开此公司。他们的其他公司不受影响。访问<0>员工账户页面</0>以查看每个人的状态。"+msgid "Require approval before change notices move to Implementation"+msgstr ""+msgid "Require approval before suppliers can be set to Active"msgstr "供应商设置为启用前需要审批"@@ -17049,8 +17114,8 @@ msgstr "必需匹配"msgid "Require SAML SSO"msgstr "需要 SAML SSO"-msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."-msgstr "根据金额阈值和批准人组,对采购订单、质量文档和供应商要求分级批准。"+msgid "Require tiered sign-off on purchase orders, quality documents, suppliers, and change notices based on amount thresholds and approver groups."+msgstr ""msgid "Require two-factor authentication"msgstr "需要双因素认证"@@ -19683,6 +19748,9 @@ msgstr "匿名提交"msgid "Submit for approval"msgstr "提交以审批"+msgid "Submit for Approval"+msgstr ""+msgid "Submit Inspection"msgstr "提交检验"@@ -21340,6 +21408,9 @@ msgstr "此变更通知正在实施中,因此其更改已锁定。重新打开msgid "This change notice is closed, so its changes are read-only."msgstr "此变更通知已关闭,因此其更改为只读。"+msgid "This change notice is waiting for approval. Its changes are locked until it is approved or rejected."+msgstr ""+msgid "This company's data is replaced with the contents of this backup. Today's data is saved first, so you can revert."msgstr "此公司的数据将替换为此备份的内容。首先保存今天的数据,以便您可以恢复。"diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 10face956e..16ff3f450e 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -12,7 +12,8 @@ export enum NotificationEvent {ApprovalApproved = "approval-approved",ApprovalRejected = "approval-rejected",ApprovalRequested = "approval-requested",- // Change-notice stage broadcasts (the only CN events; no approval flow in v1).+ // Change-notice stage broadcasts. Change notice approvals use the Approval*+ // events above with documentType "changeOrder".// Values are persisted in `notification.event`, so they keep the legacy// "change-order" spelling.ChangeNoticeStarted = "change-order-started",