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(training): PDF guides and external certifications completed by certificate upload
aashud6566179bf50
diff --git a/.ai/plans/2026-10-14-training-pdf-guides-and-external-certificates.md b/.ai/plans/2026-10-14-training-pdf-guides-and-external-certificates.mdnew file mode 100644index 0000000000..398a084f14--- /dev/null+++ b/.ai/plans/2026-10-14-training-pdf-guides-and-external-certificates.md@@ -0,0 +1,324 @@+# Training PDF Guides and External Certificates — implementation plan++**Spec / source:** `.ai/specs/2026-10-14-training-pdf-guides-and-external-certificates.md`+**Branch:** `feat/external-training-certificates`++## Progress+- [x] Task 1: Install dependencies+- [x] Task 2: Add the migration+- [x] Task 3: Apply the migration and regenerate types+- [x] Task 4: Validators, path check and services+- [x] Task 5: Bulk update route accepts the new fields+- [x] Task 6: Training page — PDF guide and External switch+- [x] Task 7: Employee wizard — guide viewer and certificate step+- [x] Task 8: Assignments page — certificate modal, view link, remove completion+- [x] Task 9: Person trainings card — view link+- [x] Task 10: Lingui, MCP digest, module docs+- [x] Task 11: Lint, typecheck, tests+- [x] Task 12: End-to-end check in the browser++## Execution notes+- Certificates upload through the server (`uploadTrainingCertificate`), not from the browser: `/share` has no browser storage client. Tasks 7 and 8 post the file, not a key.+- Removing a completion needs `delete: resources` (the `trainingCompletion` rule in `authz/manifest.ts`), not `delete: people`.++- After review: one `recordTrainingCompletion` helper replaces the three completion copies; the training page became a card stack with header-only status changes.++## Dependencies+Task 2 needs Task 1. Task 3 needs Task 2. Task 4 needs Task 3. Tasks 5–9 need Task 4 and are independent of each other. Task 10 needs Tasks 5–9. Task 11 needs Task 10. Task 12 needs Task 11.++## Shared facts++- The private file URL for a storage key is `getPrivateUrl(path)` from `@carbon/files/media`. It returns `/file/preview/private/{path}`.+- Uploads use `storage(carbon).company(companyId).upload(key, file)` from `@carbon/files`. Precedent: `apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx:54-75`.+- `FileDropzone` (`apps/erp/app/components/FileDropzone.tsx`) converts HEIC to JPEG before `onDrop`. Use it for every dropzone.+- `PdfViewer` (`apps/erp/app/modules/documents/ui/Documents/PdfViewer.tsx`) is a default export. Load it with `lazy(() => import(...))` inside `<Suspense>`, as `DocumentView.tsx:21,55` does.+- Every new user-facing string uses `useLingui().t` or `<Trans>`.++---++## Task 1: Install dependencies++**Depends on:** none+**Files:** none++**Steps:**+1. Check free memory with `vm_stat`. Run nothing else heavy at the same time.+2. Run `pnpm install` in the worktree root.++**Verify:**+```bash+ls node_modules/.pnpm | head -1+# Expected: one directory name+```++**Out of scope:** dependency upgrades.++## Task 2: Add the migration++**Depends on:** 1+**Files:**+- Create: `packages/database/supabase/migrations/{timestamp}_training-guides-and-certificates.sql` (made by the command)++**Steps:**+1. Run `pnpm db:migrate:new training-guides-and-certificates`.+2. Write this SQL into the new file:++```sql+ALTER TABLE "training"+ ADD COLUMN "guidePath" TEXT,+ ADD COLUMN "isExternal" BOOLEAN NOT NULL DEFAULT false;++ALTER TABLE "trainingCompletion"+ ADD COLUMN "certificatePath" TEXT;+```++**Verify:**+```bash+ls packages/database/supabase/migrations | grep training-guides-and-certificates+# Expected: one file name+```++**Out of scope:** RPC functions, RLS policies.++## Task 3: Apply the migration and regenerate types++**Depends on:** 2+**Files:**+- Modify (generated): `packages/database/src/types.ts` and the other files `generate:types` writes++**Steps:**+1. If the local stack for this worktree is not running, STOP and ask the user. Do not rebuild the database.+2. Run `pnpm db:migrate`.+3. Run `pnpm run generate:types`.++**Verify:**+```bash+grep -c "certificatePath\|guidePath\|isExternal" packages/database/src/types.ts+# Expected: a number of 6 or more+```++**Out of scope:** hand edits to generated types.++## Task 4: Validators, path check and services++**Depends on:** 3+**Files:**+- Modify: `apps/erp/app/modules/resources/resources.models.ts`+- Modify: `apps/erp/app/modules/resources/resources.service.ts`+- Modify: `apps/erp/app/modules/resources/resources.models.test.ts`++**Steps:**+1. In `resources.models.ts`, add `certificatePath: zfd.text(z.string().optional())` to `trainingCompletionValidator`.+2. Add these helpers next to it:++```ts+export function trainingGuideKeyPrefix(companyId: string, trainingId: string) {+ return `${companyId}/training/${trainingId}/`;+}++export function trainingCertificateKeyPrefix(+ companyId: string,+ trainingAssignmentId: string,+ employeeId: string+) {+ return `${companyId}/training-certificates/${trainingAssignmentId}/${employeeId}/`;+}++export function isValidTrainingFileKey(key: string, prefix: string) {+ return (+ key.startsWith(prefix) &&+ key.length > prefix.length &&+ !key.slice(prefix.length).includes("/") &&+ !isUnsafeStoragePath(key)+ );+}+```++ Import `isUnsafeStoragePath` from `@carbon/files`.+3. In `resources.service.ts`:+ 1. Add `certificatePath?: string | null` to the `insertTrainingCompletion` argument type.+ 2. Add `guidePath, isExternal` to the `training(...)` select in `getTrainingAssignmentForCompletion`.+ 3. Add `deleteTrainingCompletion(client, id: number, companyId)`: delete from `trainingCompletion` where `id` and `companyId` match. Mark it `/** @mcp delete */`.+ 4. Add `getTrainingCertificatePaths(client, companyId, completionIds: number[])`. If the list is empty, return `{ data: {}, error: null }`. Else select `id, certificatePath` with `.in("id", completionIds)` and `.eq("companyId", companyId)`. Return `{ data: Record<number, string>, error }` with only the rows that have a path.+4. In `resources.models.test.ts`, add tests for `isValidTrainingFileKey`: accepts `c1/training-certificates/a1/u1/x.pdf`; refuses a different company, a nested folder, `..` segments, and the bare prefix.++**Verify:**+```bash+cd apps/erp && pnpm exec vitest run app/modules/resources/resources.models.test.ts+# Expected: all tests pass+```++**Out of scope:** the RPC functions.++## Task 5: Bulk update route accepts the new fields++**Depends on:** 4+**Files:**+- Modify: `apps/erp/app/routes/x+/training+/update.tsx`++**Steps:**+1. Add `case "isExternal"`: write `value === "on"` to `isExternal`.+2. Add `case "guidePath"`:+ 1. Read the training rows for `ids` with `status, companyId`.+ 2. If any row is not Draft, return `{ error: { message: "The guide can only change on a Draft training" }, data: null }`.+ 3. If `value` is not empty and fails `isValidTrainingFileKey(value, trainingGuideKeyPrefix(companyId, id))`, return an error. Only allow one id for this field.+ 4. Write `guidePath: value === "" ? null : value`.+3. Use `companyId` from `requirePermissions`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors in update.tsx+```++**Out of scope:** the other fields.++## Task 6: Training page — PDF guide and External switch++**Depends on:** 4+**Files:**+- Create: `apps/erp/app/modules/resources/ui/Training/TrainingGuide.tsx`+- Modify: `apps/erp/app/modules/resources/ui/Training/index.ts` — export `TrainingGuide`+- Modify: `apps/erp/app/routes/x+/training+/$id.tsx` — render `TrainingGuide` above `TrainingEditor`; pass `explorer` only when `!training.isExternal`+- Modify: `apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx` — External switch+- Copy from (precedent): `apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx` (upload), `apps/erp/app/modules/items/ui/Parts/PartProperties.tsx:780` (`Boolean` property)++**Steps:**+1. `TrainingGuide` props: `trainingId`, `guidePath`, `canEdit`.+ 1. If `guidePath` is set, show `PdfViewer` with `getPrivateUrl(guidePath)` in a horizontally scrollable box.+ 2. If `canEdit`, show a `FileDropzone` with `accept={{ "application/pdf": [".pdf"] }}` and `multiple={false}`.+ 3. On drop, upload to `trainingGuideKeyPrefix(companyId, trainingId) + nanoid() + ".pdf"`. Then post `field=guidePath` to `path.to.bulkUpdateTraining` with `useAction`.+ 4. If `canEdit` and a guide exists, show a **Remove PDF** button. It posts `guidePath` with an empty value.+2. `canEdit` = `permissions.can("update", "people") && training.status === "Draft"`. This is the editor's rule (`$id.tsx`).+3. In `TrainingProperties`, add `"isExternal"` to the `onUpdate` field union. Add a `Boolean` named `isExternal`, label `t\`External\``, after Frequency. `onChange` calls `onUpdate("isExternal", value ? "on" : "off")`. Read-only without `update: people`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** multiple PDFs, a PDF block inside the editor.++## Task 7: Employee wizard — guide viewer and certificate step++**Depends on:** 4+**Files:**+- Modify: `apps/erp/app/routes/share+/training.$id.tsx`++**Steps:**+1. Loader: return `guidePath`, `isExternal` and `companyId` of the assignment in `training`. If `isExternal`, return `questions: []`.+2. `ContentStep`: if `guidePath` is set, show the lazy `PdfViewer` above the typed content. Change the empty text to show only when there is no guide and no typed content.+3. Wizard: if `training.isExternal`:+ 1. Total steps = 2: reading step, then a `CertificateStep`.+ 2. `CertificateStep` shows a `FileDropzone` with PDF and image types (copy the `accept` map from `CustomerTaxForm.tsx:153-156`) and `multiple={false}`.+ 3. On drop, upload to `trainingCertificateKeyPrefix(companyId, assignmentId, userId) + nanoid() + "." + ext`. Keep the key in state. Show the file name with a **Change file** option before submit.+ 4. The last button is **Submit Certificate**, disabled until a key exists and while the submit runs. It posts `intent=certificate` and `certificatePath`.+4. Action: if `intent === "certificate"`:+ 1. Load the authorized assignment (`getAuthorizedAssignment`). If the training is not External, return 400.+ 2. If `isValidTrainingFileKey(certificatePath, trainingCertificateKeyPrefix(assignment.companyId, id, userId))` is false, log and return 400.+ 3. Get the period with `get_current_training_period`. Insert the completion with `certificatePath`. If the insert fails, log and return 500.+ 4. Run the same ability restamp as the quiz path.+ 5. Return `{ passed: true, score: 1, totalQuestions: 0, userAnswers: {}, correctAnswers: 0 }` so `ResultsView` shows the success state.+5. The quiz action refuses an External training with 400.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** existing untranslated strings in this file.++## Task 8: Assignments page — certificate modal, view link, remove completion++**Depends on:** 4+**Files:**+- Modify: `apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx`+- Modify: `apps/erp/app/routes/x+/resources+/assignments.complete.tsx`+- Create: `apps/erp/app/routes/x+/resources+/assignments.uncomplete.tsx`+- Modify: `apps/erp/app/utils/path.ts` — add `markTrainingIncomplete: \`${x}/resources/assignments/uncomplete\``+- Copy from (precedent): `apps/erp/app/routes/x+/resources+/assignments.complete.tsx`++**Steps:**+1. Loader: collect `completionId` values. Call `getTrainingCertificatePaths` once. Return `certificatePaths`.+2. `AssignmentListItem` gets `isExternal`, `certificatePath`, `canRemove` props.+ 1. If `isExternal` and the row can be completed, **Mark Complete** opens a `Modal` with a `FileDropzone` (same types as Task 7). On upload it submits the existing form with `certificatePath`. The submit button disables while the fetcher runs.+ 2. If `certificatePath` is set, show a **View Certificate** link to `getPrivateUrl(certificatePath)` with `target="_blank"`.+ 3. If the row is Completed and `canRemove`, show **Remove Completion**. It opens a `Confirm` that says: "The employee keeps any ability this training granted. Remove it on their Abilities page if needed." On confirm it posts `completionId` to `path.to.markTrainingIncomplete`.+ 4. `canRemove` = `permissions.can("delete", "people")`.+3. `assignments.complete.tsx`: read `certificatePath`. Read the training's `isExternal` through the assignment. If External and the key fails `isValidTrainingFileKey(...)`, return 400 with a flash error. Pass `certificatePath` to `insertTrainingCompletion`.+4. `assignments.uncomplete.tsx`: `assertIsPost`. `requirePermissions(request, { delete: "people" })`. Call `deleteTrainingCompletion`. Flash success or error. Log the error first.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** removing the granted ability.++## Task 9: Person trainings card — view link++**Depends on:** 4+**Files:**+- Modify: `apps/erp/app/routes/x+/person+/$personId.abilities.tsx`+- Modify: `apps/erp/app/modules/people/ui/Person/PersonTrainings.tsx`++**Steps:**+1. Loader: after the trainings load, call `getTrainingCertificatePaths` with their `completionId` values. Return `certificatePaths`.+2. `PersonTrainings` takes `certificatePaths`. If a row has a path, show a **View Certificate** link next to the date.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++**Out of scope:** other person tabs.++## Task 10: Lingui, MCP digest, module docs++**Depends on:** 5, 6, 7, 8, 9+**Files:**+- Modify: `packages/locale/locales/*/erp.po` (generated)+- Modify: MCP generated files (generated)+- Modify: `apps/erp/app/modules/resources/AGENTS.md` — Training concept, data model and service list++**Steps:**+1. Run `pnpm lingui:extract`.+2. Run `pnpm lingui:clean`.+3. Run `pnpm run generate:mcp`.+4. Update the Training line in `AGENTS.md`: PDF guide, External trainings, certificate keys, the two new services.++**Verify:**+```bash+grep -c "Submit Certificate" packages/locale/locales/en/erp.po+# Expected: 1+```++**Out of scope:** `pnpm translate`.++## Task 11: Lint, typecheck, tests++**Depends on:** 10+**Steps:**+1. Run `pnpm exec turbo run typecheck --filter=erp`.+2. Run `pnpm exec biome check` on the changed files.+3. Run `cd apps/erp && pnpm exec vitest run app/modules/resources`.+4. Run `pnpm --filter @carbon/checks license-headers` for the new files.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++## Task 12: End-to-end check in the browser++**Depends on:** 11+**Steps:**+1. Ask the user before you drive the browser.+2. Walk the 12 acceptance criteria in the spec. Record each result.++**Verify:** every acceptance criterion passes, or the failure is reported.diff --git a/.ai/specs/2026-10-14-training-pdf-guides-and-external-certificates.md b/.ai/specs/2026-10-14-training-pdf-guides-and-external-certificates.mdnew file mode 100644index 0000000000..f8dcaad7c4--- /dev/null+++ b/.ai/specs/2026-10-14-training-pdf-guides-and-external-certificates.md@@ -0,0 +1,188 @@+# Training PDF Guides and External Training Certificates++> Status: in-progress+> Author: Aashu+> Date: 2026-10-14++## TLDR++- A training can carry one PDF guide. Employees read it on the reading step, next to the typed content.+- A training can be marked External. An employee completes it by uploading a certificate, not by a quiz.+- A manager can upload the certificate for an employee from the assignments page.+- A certificate is a PDF or an image. Upload completes the training at once. A manager can remove a wrong completion.+- Assignments, recurrence, status and ability grants work as they do today. Video is out of scope.++## Overview diagram++```mermaid+flowchart LR+ A["Employee opens assignment"] --> B["Reading step"]:::hot+ B --> C{"External?"}:::new+ C -->|No| D["Quiz questions"]+ C -->|Yes| E["Upload certificate"]:::new+ D --> F["trainingCompletion row"]+ E --> F+ G["Manager: Mark Complete"]:::hot --> F+ F --> H["Ability grant trigger"]+ classDef hot stroke-width:3px+ classDef new stroke-dasharray:4 3+```++## Problem Statement++1. An author can only type training content in the rich-text editor. Many shops already have training guides as PDF files, for example a machine operating guide. The author must retype the guide.+2. Carbon has no way to record training that a person takes outside Carbon, for example a vendor welding course. The proof of that training is a certificate file. Carbon has nowhere to store the certificate.++Today a completion row stores only the employee, the assignment, the time and the period (`20251205021915_training.sql:156`, `20251206000000_training_assignments.sql:2`). It has no file column.++## Proposed Solution++### Part 1 — PDF guide on a training++1. The author uploads one PDF on a Draft training. The training stores its storage path in `training.guidePath`.+2. The training page shows the PDF in the existing `PdfViewer` (`modules/documents/ui/Documents/PdfViewer.tsx`) above the typed content.+3. The employee wizard (`share+/training.$id.tsx`, `ContentStep`) shows the same viewer above the typed content.+4. The author can replace or remove the PDF while the training is Draft.++### Part 2 — External training++1. The author turns on **External** in the training properties panel.+2. For an External training, the employee wizard shows the reading step, then a certificate upload step. It shows no questions.+3. The employee drops one file: PDF, PNG or JPG, 10 MB or less. The form posts the file to the route action.+4. The route action builds the storage key, uploads the file and inserts the `trainingCompletion` row with `certificatePath`. The training is complete at once.+5. On the assignments page, **Mark Complete** on an External training opens a modal. The manager must upload the certificate there.+6. A completed External assignment shows **View Certificate** on the assignments page and on the person's Trainings card.+7. A manager can **Remove Completion** on a completed assignment. This deletes the completion row. The assignment returns to Pending or Overdue.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| PDF count per training | One PDF, `training.guidePath` | User choice. Smallest change; no attachment list UI. |+| PDF placement | Above the typed content, on the reading step | The guide is the main content. Typed text stays optional. |+| When the author can change the PDF | Draft only | Matches the content editor, which edits only in Draft (`x+/training+/$id.tsx`, `canEdit`). |+| How to mark a training External | New column `training.isExternal BOOLEAN NOT NULL DEFAULT false` | `trainingType` (Mandatory / Optional) answers a different question. A boolean is enough for one alternative completion path. |+| Questions on an External training | Kept in the table, hidden and not graded | Turning External off brings them back with no data loss. |+| Completion on certificate upload | Complete at once, no review step | User choice. A manager can remove a wrong completion. |+| Certificate fields | File only | User choice. `completedAt` is the upload time. Renewal follows `training.frequency`. |+| Certificate file types | Employee wizard: PDF, PNG, JPG. Manager modal: also HEIC, which `FileDropzone` converts to JPEG. | The share page has no browser storage client (`CarbonProvider` mounts only under `/x`), so it cannot run the HEIC converter. A phone browser hands a JPEG to a file input that does not list HEIC. HEIC is never stored (`packages/files/AGENTS.md`). |+| Certificate size | 10 MB or less | Same limit as the suggestion upload (`Suggestion.tsx:46`). |+| Manager completion of an External training | Certificate required | Every External completion then has proof. |+| Storage location | Company private bucket through `storage(client).company(companyId)` | Writes go to the company bucket only (`packages/files/AGENTS.md`). Any employee can write there (`20260929153242_storage-private-prefixes.sql:4`). |+| Storage keys | Guide: `{companyId}/training/{trainingId}/{nanoid}.pdf`. Certificate: `{companyId}/training-certificates/{trainingAssignmentId}/{employeeId}/{nanoid}.{ext}` | Keys sit under `{companyId}/`, so `/file/preview/private/...` authorizes them (`file+/preview+/$bucket.$.tsx:66`). |+| Who builds the certificate key | The server (`recordTrainingCompletion`, `resources.server.ts`). The form posts the file, not a key. | A caller can never point a completion at another person's file. The guide still uploads from the browser; `isValidTrainingGuideKey` checks that key. |+| Undo a completion | New service `deleteTrainingCompletion`, `delete: resources` | The completion DELETE policy needs `resources_delete` (`packages/database/src/authz/manifest.ts`, `trainingCompletion`). |+| Ability after an undo | The employee keeps the ability. The confirm dialog tells the manager. | User choice. The trigger `grant_ability_on_training_completion` only adds abilities. A person can hold the ability for another reason. |+| Certificate path on assignment rows | New service `getTrainingCertificatePaths(client, completionIds)` | Avoids a drop and recreate of 2 RPC functions. One query, no N+1. |+| Video | Out of scope for v1 | User choice. |+| Domain research | N/A | This is an internal feature with codebase precedent (customer tax certificate upload, `PdfViewer`). No ERP domain logic changes. |++Heuristics checklist:++| # | Heuristic | Result |+|---|-----------|--------|+| 1 | Multi-tenancy | No new table. New columns sit on `training` and `trainingCompletion`, which already carry `companyId`. |+| 2 | Service shape | `deleteTrainingCompletion` takes `client` first and returns `{ data, error }`. `insertTrainingCompletion` and `upsertTraining` gain fields only. |+| 3 | RLS coverage | Existing policies cover the new columns. No change. |+| 4 | Permission scoping | Upload guide: `update: people` (as the editor). Employee certificate: `role: employee` plus assignment check (as the wizard). Manager complete: `update: resources` (as `assignments.complete.tsx`). Remove completion: `delete: resources`. |+| 5 | Form pattern | Certificate modal and remove action use `ValidatedForm` + zod validators in `resources.models.ts`. |+| 6 | Module layout | All code stays in `~/modules/resources`. No new module. |+| 7 | Backward compatibility | New columns are nullable or defaulted. No RPC function changes. MCP tool digests for the changed service functions regenerate. |++### Part 3 — Training page layout (added after review)++1. The header owns the status. Draft shows **Publish**. Active shows **Archive**. The ⋯ menu has **Reopen**, which moves the training back to Draft. Each one asks for confirmation. Properties has no Status field.+2. The center pane is a stack of two cards: **PDF Guide**, then **Content**. The Content card holds the rich-text editor with its toolbar flush at the top (`Editor` prop `toolbarClassName`).+3. The author edits the name in Properties. The editor has no title block.+4. For an External training, the questions explorer explains why there is no quiz.+5. The shared editor loads the Color and Highlight extensions, so the color menu works in every editor.++## Data Model Changes++```sql+ALTER TABLE "training"+ ADD COLUMN "guidePath" TEXT,+ ADD COLUMN "isExternal" BOOLEAN NOT NULL DEFAULT false;++ALTER TABLE "trainingCompletion"+ ADD COLUMN "certificatePath" TEXT;+```++`get_training_assignment_status` does not change. `get_training_assignment_summary` reads from it (`20260925121735_rpc-function-guards.sql:2007`), so a new output column would force a drop of both functions. Instead, the new service `getTrainingCertificatePaths` reads `certificatePath` for a list of `completionId` values in one `.in()` query.++## API / Service Changes++| Item | Change |+|------|--------|+| `trainingValidator` | Adds `isExternal` (`zfd.checkbox()`) and `guidePath` (optional text). |+| `trainingCompletionValidator` | Adds optional `certificatePath`. |+| New `recordTrainingCompletion` (`resources.server.ts`) | The one completion path. Refuses a training that is not Active. For an External training, checks the certificate (`validateTrainingCertificate`), builds the key and uploads it. Works out the period, inserts the row, removes the file if the insert fails, and restamps the scheduler for a granted ability. |+| `insertTrainingCompletion` | Accepts `certificatePath`. |+| New `deleteTrainingCompletion(client, id, companyId)` | Deletes one completion row. |+| New `getTrainingCertificatePaths(client, companyId, completionIds)` | Returns a map from completion id to `certificatePath`. |+| `x+/training+/update.tsx` (bulk update) | Accepts `isExternal` and `guidePath`. Refuses `guidePath` when the training is not Draft. |+| `share+/training.$id.tsx` loader | Returns `guidePath` and `isExternal`. |+| `share+/training.$id.tsx` action | New intent `certificate`. It checks the training is External, then calls `recordTrainingCompletion` with the posted file. The quiz path calls the same helper. |+| `x+/resources+/assignments.complete.tsx` | Requires a posted certificate file when the training is External. |+| New `x+/resources+/assignments.uncomplete.tsx` | Calls `deleteTrainingCompletion`. |++## Closest Sibling++N/A for a record type: this feature adds fields to the existing training record. The upload pattern copies the customer tax certificate: `modules/sales/ui/Customer/CustomerTaxForm.tsx` (dropzone, `storage(...).company(...)`, `/file/preview/private/...` link). The guide viewer reuses `modules/documents/ui/Documents/PdfViewer.tsx`.++## UI Changes++| Page | Change |+|------|--------|+| Training detail (`x+/training+/$id.tsx`, record page with editor) | PDF guide dropzone above the editor while Draft. PDF viewer above the content when a guide exists. |+| Training properties panel (`TrainingProperties.tsx`) | **External** switch. |+| Training explorer and questions routes | Hidden for an External training. |+| Employee wizard (`share+/training.$id.tsx`) | PDF viewer on the reading step. For External: certificate upload step instead of questions. |+| Assignments (`x+/resources+/assignments.$trainingId.tsx`) | **Mark Complete** opens a certificate modal for External. **View Certificate** link. **Remove Completion** action. |+| Person trainings card (`PersonTrainings.tsx`) | **View Certificate** link on completed External trainings. |++Every new string uses Lingui (`useLingui().t` or `<Trans>`).++## Acceptance Criteria++- [ ] An author uploads a PDF on a Draft training. The training page shows the PDF in a viewer above the typed content.+- [ ] An author cannot upload, replace or remove the PDF on an Active training.+- [ ] An employee opens an assigned training with a PDF guide. The reading step shows the PDF.+- [ ] An author turns on External. The questions explorer is hidden. The employee wizard shows an upload step and no questions.+- [ ] An employee uploads a PDF certificate on an External training. The assignment shows Completed. **View Certificate** opens the file.+- [ ] A manager uploads a HEIC photo in the certificate modal. The stored file is a JPEG.+- [ ] An employee cannot complete an External training without a file.+- [ ] A manager clicks **Mark Complete** on an External training. The modal requires a certificate. After upload the assignment shows Completed.+- [ ] A manager clicks **Remove Completion**. The assignment shows Pending (or Overdue when the period has ended).+- [ ] An External training that grants an ability adds the qualification on certificate upload, as the quiz path does.+- [ ] Every stored certificate key starts with `{companyId}/training-certificates/{trainingAssignmentId}/{employeeId}/`.+- [ ] A file over 10 MB, or of another type, is refused with a message.+- [ ] All new UI strings appear in the extracted Lingui catalog.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| An employee uploads a certificate that is not real | Med | A manager can view every certificate and remove the completion. |+| A dropped or replaced file stays in storage with no row pointing at it | Low | Same as the tax certificate upload today. Out of scope for v1. |+| A large PDF loads slowly on a phone | Low | The viewer loads one file on demand. |+| A removed completion leaves the granted ability in place | Low | The confirm dialog says so. The manager removes the ability on the person's Abilities panel. |++## Open Questions++> All resolved before this spec was written.++- [x] What does v1 include? — **Answer:** PDF guide on a training, plus External training completed by certificate upload. Video is later.+- [x] How does a PDF guide attach to a training? — **Answer:** One PDF per training, shown on the reading step with any typed text.+- [x] How does an External training get marked complete? — **Answer:** The certificate upload completes it at once. A manager can upload on an employee's behalf and can remove a wrong completion. No quiz.+- [x] What does the uploader enter with the certificate? — **Answer:** The file only. Completed date is the upload time. Renewal follows the training frequency.+- [x] Does Carbon check that the file is a real certificate? — **Answer:** No. Any accepted file type completes the training. A manager reviews the file and removes a wrong completion.+- [x] When a manager removes a completion, what happens to the granted ability? — **Answer:** The employee keeps it. The confirm dialog tells the manager to remove it by hand if needed.+- [x] Can a person replace the certificate after upload? — **Answer:** No. To fix a wrong file, a manager removes the completion and the employee uploads a new file.++## Changelog++- 2026-10-14: Created+- 2026-10-14: Certificate paths come from a new service, not from the status RPC. Removing a completion keeps the ability.+- 2026-10-14: Implemented. The server builds the certificate key. The employee wizard takes PDF, PNG and JPG; the manager modal also takes HEIC. Removing a completion needs `delete: resources`.+- 2026-10-14: Page layout (Part 3). Every completion goes through `recordTrainingCompletion`: it refuses a training that is not Active, works out the period on the server and removes an orphaned certificate. `isExternal` changes only while Draft. Guide keys are `{uploadId}/{file name}`.diff --git a/apps/erp/app/components/Empty.tsx b/apps/erp/app/components/Empty.tsxindex ed2b3da90f..8068b638d0 100644--- a/apps/erp/app/components/Empty.tsx+++ b/apps/erp/app/components/Empty.tsx@@ -4,13 +4,18 @@import { cn, VStack } from "@carbon/react";import { Trans } from "@lingui/react/macro";-import type { ComponentProps } from "react";+import type { ComponentProps, ReactNode } from "react";export default function Empty({className,children,+ title,+ description,...props-}: ComponentProps<"div">) {+}: Omit<ComponentProps<"div">, "title"> & {+ title?: ReactNode;+ description?: ReactNode;+}) {return (<VStackclassName={cn(@@ -35,13 +40,15 @@ export default function Empty({/></svg><h3 className="text-lg font-medium tracking-tight text-foreground max-md:text-[17px] max-md:font-semibold">- <Trans>No data yet</Trans>+ {title ?? <Trans>No data yet</Trans>}</h3><p className="max-w-56 text-center text-xs text-muted-foreground text-balance">- <Trans>- Your data will appear here once you create or import your first- records- </Trans>+ {description ?? (+ <Trans>+ Your data will appear here once you create or import your first+ records+ </Trans>+ )}</p>{children}</VStack>diff --git a/apps/erp/app/modules/people/ui/Person/PersonTrainings.tsx b/apps/erp/app/modules/people/ui/Person/PersonTrainings.tsxindex 779cab3a97..d2a6a6dcfc 100644--- a/apps/erp/app/modules/people/ui/Person/PersonTrainings.tsx+++ b/apps/erp/app/modules/people/ui/Person/PersonTrainings.tsx@@ -11,14 +11,20 @@ import {HStack} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { LuCircleCheck, LuClock, LuTriangleAlert } from "react-icons/lu";+import {+ LuCircleCheck,+ LuClock,+ LuFileCheck,+ LuTriangleAlert+} from "react-icons/lu";import { Link } from "react-router";import { DateTime } from "~/components";import type { TrainingAssignmentStatusItem } from "~/modules/resources/types";-import { path } from "~/utils/path";+import { getPrivateUrl, path } from "~/utils/path";type PersonTrainingsProps = {trainings: TrainingAssignmentStatusItem[];+ certificatePaths?: Record<number, string>;};function TrainingStatusBadge({ status }: { status: string }) {@@ -55,7 +61,10 @@ function TrainingStatusBadge({ status }: { status: string }) {}}-const PersonTrainings = ({ trainings }: PersonTrainingsProps) => {+const PersonTrainings = ({+ trainings,+ certificatePaths = {}+}: PersonTrainingsProps) => {return (<Card><CardHeader>@@ -78,18 +87,34 @@ const PersonTrainings = ({ trainings }: PersonTrainingsProps) => {</Link><TrainingStatusBadge status={training.status} /></HStack>- {training.completedAt && (- <p className="text-sm text-muted-foreground">- <DateTime- value={training.completedAt}- variant="date"- dateOptions={{- month: "short",- year: "numeric"- }}- />- </p>- )}+ <HStack spacing={3}>+ {training.completionId &&+ certificatePaths[training.completionId] && (+ <a+ className="flex items-center gap-1 text-sm"+ href={getPrivateUrl(+ certificatePaths[training.completionId]+ )}+ target="_blank"+ rel="noreferrer"+ >+ <LuFileCheck />+ <Trans>View Certificate</Trans>+ </a>+ )}+ {training.completedAt && (+ <p className="text-sm text-muted-foreground">+ <DateTime+ value={training.completedAt}+ variant="date"+ dateOptions={{+ month: "short",+ year: "numeric"+ }}+ />+ </p>+ )}+ </HStack></HStack></li>))}diff --git a/apps/erp/app/modules/resources/AGENTS.md b/apps/erp/app/modules/resources/AGENTS.mdindex 3fcda6817c..317e90039e 100644--- a/apps/erp/app/modules/resources/AGENTS.md+++ b/apps/erp/app/modules/resources/AGENTS.md@@ -13,7 +13,7 @@ Locations, work centers, processes, abilities (skills), partners, contractors, e- **Maintenance Dispatch** — reactive or scheduled work order for equipment. Statuses: Open → Assigned → In Progress → Completed / Cancelled. Tracks time events, consumed parts, and affected work centers.- **Maintenance Schedule** — preventive maintenance plan with frequency, priority, estimated duration, and required spare parts. `takesWorkCenterOffline` marks the PM as blocking the machine; the nightly generator (`packages/jobs/.../scheduled/dispatch.ts`) copies it onto each generated dispatch and sets `plannedEndTime = plannedStartTime + estimatedDuration` (so the offline window is bounded — the validator requires a duration when offline is on).- **Failure Mode** — categorized failure type used by maintenance dispatches and quality NCRs.-- **Training** — training programs with assignments, quiz questions, and frequency-based recertification. Completion tracked via `trainingCompletion`.+- **Training** — training programs with assignments, quiz questions, and frequency-based recertification. Completion tracked via `trainingCompletion`. **Status changes only from the header** (`TrainingHeader`): Draft shows Publish, Active shows Archive, and Reopen (back to Draft) is in the ⋯ menu — each through a `Confirm` posting `field=status` to `x+/training+/update.tsx`; Properties has no Status field. The name is edited in Properties (the content editor has no title block). The center pane is a card stack: **PDF Guide** (`TrainingGuide`) then **Content** (card-contained `Editor` with a flush toolbar). A training can carry one PDF guide (`training.guidePath`, key `{companyId}/training/{trainingId}/{uploadId}/{file name}`, checked by `isValidTrainingGuideKey`). An **External** training (`training.isExternal`) has no quiz: the questions explorer explains that instead of listing questions. `guidePath` and `isExternal` change only while Draft (`refuseUnlessDraft` in `update.tsx`). Every completion — the employee's quiz and certificate upload (`share/training.$id`) and a manager's Mark Complete (`assignments.complete`) — goes through `recordTrainingCompletion` (`resources.server.ts`): it refuses a training that is not Active, uploads and requires the certificate of an External training (`validateTrainingCertificate`: PDF/PNG/JPG, 10 MB; key `{companyId}/training-certificates/{assignmentId}/{employeeId}/…` built on the server), works out the period on the server, removes the uploaded file when the insert fails, treats a duplicate completion as already recorded, and restamps the scheduler for a granted ability. `assignments.uncomplete` (`delete: resources`) removes a wrong completion; the granted ability stays (the grant trigger only adds). The assignment status RPC does not return the certificate: read it with `getTrainingCertificatePaths` (one `.in()` query).## Safety@@ -73,7 +73,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=resources- `getMaintenanceDispatchEvents` / `getMaintenanceDispatchComments` / `getMaintenanceDispatchItems` — dispatch details- `getMaintenanceSchedule(s)` / `upsertMaintenanceSchedule` — PM plans- `getFailureModes` / `upsertFailureMode` — failure categorization-- `getTraining(s)` / `getTrainingAssignment(s)` / `getTrainingAssignmentStatus` / `getOutstandingTrainingsForUser` / `getTrainingGrantedAbilityId` — training management (`getTrainingGrantedAbilityId` returns the ability a completion grants, so the completion routes can `notifyScheduleInputsChanged` for that operator pool)+- `getTraining(s)` / `getTrainingAssignment(s)` / `getTrainingAssignmentStatus` / `getOutstandingTrainingsForUser` / `getTrainingGrantedAbilityId` / `getTrainingCertificatePaths` / `deleteTrainingCompletion` — training management (`getTrainingGrantedAbilityId` returns the ability a completion grants, so the completion routes can `notifyScheduleInputsChanged` for that operator pool)- `getSuggestion(s)` — suggestion management## Key Exportsdiff --git a/apps/erp/app/modules/resources/resources.models.test.ts b/apps/erp/app/modules/resources/resources.models.test.tsindex 8d33a0a07b..d1bda91c7a 100644--- a/apps/erp/app/modules/resources/resources.models.test.ts+++ b/apps/erp/app/modules/resources/resources.models.test.ts@@ -46,3 +46,82 @@ describe("abilityValidator", () => {}});});++describe("isValidTrainingGuideKey", async () => {+ const { isValidTrainingGuideKey, trainingGuideKeyPrefix } = await import(+ "./resources.models"+ );+ const prefix = trainingGuideKeyPrefix("c1", "t1");++ it("accepts one upload folder and one file", () => {+ expect(+ isValidTrainingGuideKey("c1/training/t1/abc/Welder Guide.pdf", prefix)+ ).toBe(true);+ });++ it("refuses another company's or training's key", () => {+ expect(+ isValidTrainingGuideKey("c2/training/t1/abc/guide.pdf", prefix)+ ).toBe(false);+ expect(+ isValidTrainingGuideKey("c1/training/t2/abc/guide.pdf", prefix)+ ).toBe(false);+ });++ it("refuses a file with no upload folder, or a deeper path", () => {+ expect(isValidTrainingGuideKey("c1/training/t1/guide.pdf", prefix)).toBe(+ false+ );+ expect(+ isValidTrainingGuideKey("c1/training/t1/abc/d/guide.pdf", prefix)+ ).toBe(false);+ });++ it("refuses dot segments and empty segments", () => {+ expect(isValidTrainingGuideKey("c1/training/t1/../x.pdf", prefix)).toBe(+ false+ );+ expect(isValidTrainingGuideKey("c1/training/t1/abc/", prefix)).toBe(false);+ });+});++describe("validateTrainingCertificate", async () => {+ const { TRAINING_CERTIFICATE_MAX_BYTES, validateTrainingCertificate } =+ await import("./resources.models");+ const file = (name: string, size = 10) =>+ new File([new Uint8Array(size)], name);++ it("accepts a PDF, PNG or JPG and returns its extension", () => {+ expect(validateTrainingCertificate(file("cert.PDF")).extension).toBe("pdf");+ expect(validateTrainingCertificate(file("photo.jpeg")).extension).toBe(+ "jpeg"+ );+ expect(validateTrainingCertificate(file("scan.png")).error).toBeNull();+ });++ it("refuses a missing or empty file", () => {+ expect(validateTrainingCertificate(null).error).toBe(+ "Upload a certificate file"+ );+ expect(validateTrainingCertificate(file("cert.pdf", 0)).error).toBe(+ "Upload a certificate file"+ );+ });++ it("refuses another type", () => {+ expect(validateTrainingCertificate(file("notes.txt")).error).toBe(+ "The certificate must be a PDF, PNG or JPG"+ );+ expect(validateTrainingCertificate(file("photo.heic")).error).toBe(+ "The certificate must be a PDF, PNG or JPG"+ );+ });++ it("refuses a file over the size limit", () => {+ expect(+ validateTrainingCertificate(+ file("cert.pdf", TRAINING_CERTIFICATE_MAX_BYTES + 1)+ ).error+ ).toBe("The certificate must be 10 MB or smaller");+ });+});diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.tsindex ce23976b7c..6f867538fa 100644--- a/apps/erp/app/modules/resources/resources.models.ts+++ b/apps/erp/app/modules/resources/resources.models.ts@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { isUnsafeStoragePath } from "@carbon/files";import {type BatchRules,isValidTimeZone,@@ -400,6 +401,68 @@ export const trainingCompletionValidator = z.object({period: zfd.text(z.string().optional())});+// Guide key: `{companyId}/training/{trainingId}/{uploadId}/{file name}` — the+// last segment is the name the author uploaded.+export function trainingGuideKeyPrefix(companyId: string, trainingId: string) {+ return `${companyId}/training/${trainingId}/`;+}++// The browser posts the guide's key, so the server must not trust its shape.+export function isValidTrainingGuideKey(key: string, prefix: string) {+ if (!key.startsWith(prefix) || isUnsafeStoragePath(key)) return false;+ const segments = key.slice(prefix.length).split("/");+ return segments.length === 2 && segments.every((segment) => segment !== "");+}++export function trainingCertificateKeyPrefix(+ companyId: string,+ trainingAssignmentId: string,+ employeeId: string+) {+ return `${companyId}/training-certificates/${trainingAssignmentId}/${employeeId}/`;+}++// A certificate is a PDF or a photo of one. HEIC is never stored: the ERP+// dropzone converts it to JPEG first, and phone browsers hand a JPEG to a file+// input that does not list HEIC.+export const trainingCertificateAccept = {+ "application/pdf": [".pdf"],+ "image/png": [".png"],+ "image/jpeg": [".jpg", ".jpeg"]+};++export const TRAINING_CERTIFICATE_MAX_BYTES = 10 * 1024 * 1024;++const trainingCertificateExtensions = Object.values(trainingCertificateAccept)+ .flat()+ .map((extension) => extension.slice(1));++export function validateTrainingCertificate(+ file: FormDataEntryValue | null+):+ | { file: File; extension: string; error: null }+ | { file: null; extension: null; error: string } {+ if (!(file instanceof File) || file.size === 0) {+ return { file: null, extension: null, error: "Upload a certificate file" };+ }+ const extension = file.name.split(".").pop()?.toLowerCase() ?? "";+ if (!trainingCertificateExtensions.includes(extension)) {+ return {+ file: null,+ extension: null,+ error: "The certificate must be a PDF, PNG or JPG"+ };+ }+ if (file.size > TRAINING_CERTIFICATE_MAX_BYTES) {+ return {+ file: null,+ extension: null,+ error: "The certificate must be 10 MB or smaller"+ };+ }+ return { file, extension, error: null };+}+export const trainingFrequency = ["Once", "Quarterly", "Annual"] as const;export const trainingQuestionType = [diff --git a/apps/erp/app/modules/resources/resources.server.ts b/apps/erp/app/modules/resources/resources.server.tsindex 1e5191698d..52a2ff1c65 100644--- a/apps/erp/app/modules/resources/resources.server.ts+++ b/apps/erp/app/modules/resources/resources.server.ts@@ -2,9 +2,22 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { Database } from "@carbon/database";+import { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";+import type { SupabaseClient } from "@supabase/supabase-js";+import { nanoid } from "nanoid";+import { notifyScheduleInputsChanged } from "~/modules/production";import { getDatabaseClient } from "~/services/database.server";+import {+ trainingCertificateKeyPrefix,+ validateTrainingCertificate+} from "./resources.models";+import {+ getTrainingGrantedAbilityId,+ insertTrainingCompletion+} from "./resources.service";const logger = getLogger("erp", "maintenance-labor");@@ -35,3 +48,118 @@ export async function postMaintenanceLabor(args: {}return null;}++const trainingLogger = getLogger("erp", "training-completion");++type TrainingForCompletion = {+ status: string;+ frequency: Database["public"]["Enums"]["trainingFrequency"];+ isExternal: boolean;+};++// The only completion path (quiz, certificate upload, manager Mark Complete).+// The server builds the certificate key, so a caller cannot point a completion+// at another person's file.+export async function recordTrainingCompletion(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ trainingAssignmentId: string;+ employeeId: string;+ completedBy: string;+ training: TrainingForCompletion;+ certificate?: FormDataEntryValue | null;+ }+): Promise<{ error: null } | { error: string; status: 400 | 500 }> {+ const { companyId, trainingAssignmentId, employeeId, completedBy, training } =+ args;++ if (training.status !== "Active") {+ return { error: "This training is not currently active", status: 400 };+ }++ let certificatePath: string | null = null;+ if (training.isExternal) {+ const certificate = validateTrainingCertificate(args.certificate ?? null);+ if (certificate.error !== null) {+ return { error: certificate.error, status: 400 };+ }+ const key = `${trainingCertificateKeyPrefix(+ companyId,+ trainingAssignmentId,+ employeeId+ )}${nanoid()}.${certificate.extension}`;+ const upload = await storage(client)+ .company(companyId)+ .upload(key, certificate.file);+ if (upload.error) {+ trainingLogger.error("Failed to upload training certificate", {+ companyId,+ trainingAssignmentId,+ error: upload.error+ });+ return { error: "Failed to upload the certificate", status: 500 };+ }+ certificatePath = key;+ }++ const period = await client.rpc("get_current_training_period", {+ frequency: training.frequency+ });++ const completion = await insertTrainingCompletion(client, {+ trainingAssignmentId,+ employeeId,+ period: period.data ?? null,+ companyId,+ completedBy,+ createdBy: completedBy,+ certificatePath+ });+ if (completion.error) {+ // The unique indexes allow one completion per employee and period: a+ // second submit means it is already recorded, which is what was asked.+ const alreadyRecorded = completion.error.code === "23505";+ if (!alreadyRecorded) {+ trainingLogger.error("Failed to record training completion", {+ companyId,+ trainingAssignmentId,+ error: completion.error+ });+ }+ // Nothing points at the new file now.+ if (certificatePath) {+ const removed = await storage(client)+ .company(companyId)+ .remove([certificatePath]);+ if (removed.error) {+ trainingLogger.error("Failed to remove orphaned certificate", {+ companyId,+ certificatePath,+ error: removed.error+ });+ }+ }+ return alreadyRecorded+ ? { error: null }+ : { error: "Failed to record the training as complete", status: 500 };+ }++ // Completing a training that grants an ability adds a qualification (via the+ // grant trigger) — restamp the scheduler for that ability's operator pool.+ const grantedAbilityId = await getTrainingGrantedAbilityId(+ client,+ trainingAssignmentId,+ companyId+ );+ if (grantedAbilityId) {+ await notifyScheduleInputsChanged(+ companyId,+ "ability",+ "Operator qualified via training",+ grantedAbilityId+ );+ }++ return { error: null };+}diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex f8aaa61197..79742b813c 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -948,7 +948,7 @@ export async function getTrainingAssignment() {return client.from("trainingAssignment")- .select("*, training(id, name, frequency, type, status)")+ .select("*, training(id, name, frequency, type, status, isExternal)").eq("id", assignmentId).single();}@@ -971,6 +971,8 @@ export async function getTrainingAssignmentForCompletion(type,status,estimatedDuration,+ guidePath,+ isExternal,trainingQuestion(*))`)@@ -1286,6 +1288,7 @@ export async function insertTrainingCompletion(companyId: string;completedBy: string;createdBy: string;+ certificatePath?: string | null;}) {return client@@ -1298,6 +1301,47 @@ export async function insertTrainingCompletion(.single();}+/** @mcp delete */+export async function deleteTrainingCompletion(+ client: SupabaseClient<Database>,+ id: number,+ companyId: string+) {+ return client+ .from("trainingCompletion")+ .delete()+ .eq("id", id)+ .eq("companyId", companyId);+}++/**+ * The assignment status RPC does not return the certificate path.+ * @mcp read+ */+export async function getTrainingCertificatePaths(+ client: SupabaseClient<Database>,+ companyId: string,+ completionIds: number[]+) {+ if (completionIds.length === 0) {+ return { data: {} as Record<number, string>, error: null };+ }++ const { data, error } = await client+ .from("trainingCompletion")+ .select("id, certificatePath")+ .eq("companyId", companyId)+ .in("id", completionIds);++ if (error) return { data: null, error };++ const paths: Record<number, string> = {};+ for (const row of data ?? []) {+ if (row.certificatePath) paths[row.id] = row.certificatePath;+ }+ return { data: paths, error: null };+}+/*** The ability a training assignment's training grants on completion, or null.* Completing training upserts an `employeeAbility` via thediff --git a/apps/erp/app/modules/resources/ui/Training/TrainingCertificateStep.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingCertificateStep.tsxnew file mode 100644index 0000000000..bf958b27eb--- /dev/null+++ b/apps/erp/app/modules/resources/ui/Training/TrainingCertificateStep.tsx@@ -0,0 +1,100 @@+// 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 { Alert, AlertDescription, AlertTitle, cn, VStack } from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { useDropzone } from "react-dropzone";+import { LuCircleX, LuCloudUpload, LuFileCheck } from "react-icons/lu";+import {+ TRAINING_CERTIFICATE_MAX_BYTES,+ trainingCertificateAccept+} from "../../resources.models";++// The employee's certificate upload for an External training. It runs on the+// share page, outside the app shell, so it cannot use FileDropzone (that needs+// the signed-in storage client); the file is posted to the route action.+export default function TrainingCertificateStep({+ file,+ onFileChange,+ error,+ isDisabled+}: {+ file: File | null;+ onFileChange: (file: File | null) => void;+ error?: string;+ isDisabled: boolean;+}) {+ const { t } = useLingui();+ const [rejection, setRejection] = useState<string | null>(null);+ const { getRootProps, getInputProps, isDragActive } = useDropzone({+ accept: trainingCertificateAccept,+ multiple: false,+ maxSize: TRAINING_CERTIFICATE_MAX_BYTES,+ disabled: isDisabled,+ onDrop: (accepted, rejected) => {+ if (rejected.length > 0) {+ setRejection(t`Upload one PDF, PNG or JPG file of 10 MB or less.`);+ return;+ }+ setRejection(null);+ onFileChange(accepted[0] ?? null);+ }+ });++ const message = rejection ?? error;++ return (+ <VStack spacing={4} className="w-full">+ <p className="text-muted-foreground">+ <Trans>+ Upload the certificate you received for this training. Uploading it+ marks the training as complete.+ </Trans>+ </p>+ <div+ {...getRootProps()}+ className={cn(+ "w-full border-2 border-dashed rounded-md p-8 text-center transition-colors",+ isDisabled+ ? "cursor-not-allowed opacity-60"+ : "cursor-pointer hover:border-primary hover:bg-primary/10",+ isDragActive ? "border-primary bg-primary/10" : "border-border"+ )}+ >+ <input {...getInputProps()} />+ {file ? (+ <div className="flex flex-col items-center gap-2">+ <LuFileCheck className="size-10 text-emerald-500" />+ <span className="font-medium break-all">{file.name}</span>+ <span className="text-xs text-muted-foreground">+ <Trans>Click or drop to choose a different file</Trans>+ </span>+ </div>+ ) : (+ <div className="flex flex-col items-center gap-2">+ <LuCloudUpload className="size-10 text-muted-foreground" />+ <span>+ <Trans>+ Drop your certificate here, or click to choose a file+ </Trans>+ </span>+ <span className="text-xs text-muted-foreground">+ <Trans>PDF, PNG or JPG, up to 10 MB</Trans>+ </span>+ </div>+ )}+ </div>+ {message && (+ <Alert variant="destructive">+ <LuCircleX className="h-4 w-4" />+ <AlertTitle>+ <Trans>Certificate not accepted</Trans>+ </AlertTitle>+ <AlertDescription>{message}</AlertDescription>+ </Alert>+ )}+ </VStack>+ );+}diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingExplorer.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingExplorer.tsxindex 8246a7ed94..f8e0153bf7 100644--- a/apps/erp/app/modules/resources/ui/Training/TrainingExplorer.tsx+++ b/apps/erp/app/modules/resources/ui/Training/TrainingExplorer.tsx@@ -114,7 +114,9 @@ export default function TrainingExplorer() {tolerance: selectedQuestion?.tolerance ?? undefined};- const isDisabled = trainingData?.training?.status !== "Draft";+ // External trainings have no quiz; the panel explains why instead of hiding.+ const isExternal = trainingData?.training?.isExternal ?? false;+ const isDisabled = trainingData?.training?.status !== "Draft" || isExternal;const [sortOrder, setSortOrder] = useState<string[]>(Array.isArray(questions)@@ -203,7 +205,19 @@ export default function TrainingExplorer() {className="w-full flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"spacing={0}>- {questions && questions.length > 0 ? (+ {isExternal ? (+ <Empty+ className="px-4 text-center"+ title={<Trans>No quiz for external certifications</Trans>}+ description={+ <Trans>+ Employees complete this training by uploading their+ certificate. Turn off External Certification in Properties to+ use questions.+ </Trans>+ }+ />+ ) : questions && questions.length > 0 ? (<Reorder.Groupaxis="y"values={sortOrder}@@ -266,7 +280,7 @@ export default function TrainingExplorer() {questionDisclosure.onOpen();}}>- Add Question+ <Trans>Add Question</Trans></Button></TooltipTrigger><TooltipContent>diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingGuide.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingGuide.tsxnew file mode 100644index 0000000000..9511655c6c--- /dev/null+++ b/apps/erp/app/modules/resources/ui/Training/TrainingGuide.tsx@@ -0,0 +1,178 @@+// 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 { useCarbon } from "@carbon/auth";+import { safeStorageFileName, storage } from "@carbon/files";+import { useAction } from "@carbon/query";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ File as FileButton,+ HStack,+ Skeleton,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { nanoid } from "nanoid";+import type { ChangeEvent } from "react";+import { lazy, Suspense, useState } from "react";+import { LuFileText, LuTrash, LuUpload } from "react-icons/lu";+import { FileDropzone } from "~/components";+import { Confirm } from "~/components/Modals";+import { useUser } from "~/hooks";+import type { action } from "~/routes/x+/training+/update";+import { getPrivateUrl, path } from "~/utils/path";+import { trainingGuideKeyPrefix } from "../../resources.models";++const PdfViewer = lazy(+ () => import("~/modules/documents/ui/Documents/PdfViewer")+);++type TrainingGuideProps = {+ trainingId: string;+ guidePath: string | null;+ canEdit: boolean;+};++export function TrainingGuideViewer({ guidePath }: { guidePath: string }) {+ return (+ <div className="w-full overflow-x-auto rounded-lg border border-border bg-background">+ <Suspense fallback={<Skeleton className="h-120 w-full" />}>+ <PdfViewer file={getPrivateUrl(guidePath)} />+ </Suspense>+ </div>+ );+}++const TrainingGuide = ({+ trainingId,+ guidePath,+ canEdit+}: TrainingGuideProps) => {+ const { t } = useLingui();+ const { carbon } = useCarbon();+ const { company } = useUser();+ const [isUploading, setIsUploading] = useState(false);+ const [isRemoveOpen, setIsRemoveOpen] = useState(false);++ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) toast.error(data.error.message);+ }+ });+ const isBusy = isUploading || fetcher.state !== "idle";++ const upload = async (file: File | undefined) => {+ if (!file || !carbon) return;++ const name = safeStorageFileName(file.name) ?? "guide.pdf";+ const fileName = name.toLowerCase().endsWith(".pdf") ? name : `${name}.pdf`;++ setIsUploading(true);+ const key = `${trainingGuideKeyPrefix(company.id, trainingId)}${nanoid()}/${fileName}`;+ const result = await storage(carbon).company(company.id).upload(key, file);+ setIsUploading(false);++ if (result.error) {+ toast.error(t`Failed to upload PDF`);+ return;+ }++ const formData = new FormData();+ formData.append("ids", trainingId);+ formData.append("field", "guidePath");+ formData.append("value", result.data.path);+ fetcher.submit(formData, {+ method: "post",+ action: path.to.bulkUpdateTraining+ });+ };++ const fileName = guidePath?.split("/").pop();++ return (+ <Card>+ <HStack className="w-full justify-between items-start">+ <CardHeader>+ <CardTitle>+ <Trans>PDF Guide</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>Employees read it before the questions</Trans>+ </CardDescription>+ </CardHeader>+ {guidePath && (+ <CardAction>+ <HStack spacing={2}>+ <FileButton+ accept="application/pdf"+ variant="secondary"+ leftIcon={<LuUpload />}+ isDisabled={!canEdit || isBusy}+ onChange={async (e: ChangeEvent<HTMLInputElement>) => {+ await upload(e.target.files?.[0]);+ }}+ >+ <Trans>Replace</Trans>+ </FileButton>+ <Button+ variant="secondary"+ leftIcon={<LuTrash />}+ isDisabled={!canEdit || isBusy}+ onClick={() => setIsRemoveOpen(true)}+ >+ <Trans>Remove</Trans>+ </Button>+ </HStack>+ </CardAction>+ )}+ </HStack>+ <CardContent>+ {guidePath ? (+ <div className="flex flex-col gap-3 w-full">+ <HStack spacing={2} className="text-sm min-w-0">+ <LuFileText className="shrink-0 text-muted-foreground" />+ <span className="truncate">{fileName}</span>+ </HStack>+ <TrainingGuideViewer guidePath={guidePath} />+ </div>+ ) : canEdit ? (+ <FileDropzone+ onDrop={(files) => upload(files[0])}+ accept={{ "application/pdf": [".pdf"] }}+ multiple={false}+ disabled={isBusy}+ className="mt-0"+ />+ ) : (+ <p className="text-sm text-muted-foreground">+ <Trans>No PDF guide</Trans>+ </p>+ )}+ </CardContent>+ {isRemoveOpen && (+ <Confirm+ action={path.to.bulkUpdateTraining}+ title={t`Remove PDF Guide`}+ text={t`Employees will no longer see this PDF. You can upload a new one while the training is Draft.`}+ confirmText={t`Remove`}+ confirmVariant="destructive"+ onCancel={() => setIsRemoveOpen(false)}+ onSubmit={() => setIsRemoveOpen(false)}+ >+ <input type="hidden" name="ids" value={trainingId} />+ <input type="hidden" name="field" value="guidePath" />+ <input type="hidden" name="value" value="" />+ </Confirm>+ )}+ </Card>+ );+};++export default TrainingGuide;diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingHeader.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingHeader.tsxindex e838d85f01..13c1899956 100644--- a/apps/erp/app/modules/resources/ui/Training/TrainingHeader.tsx+++ b/apps/erp/app/modules/resources/ui/Training/TrainingHeader.tsx@@ -10,14 +10,15 @@ import {useDisclosure} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { LuTrash } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useState } from "react";+import { LuArchive, LuLoaderCircle, LuTrash } from "react-icons/lu";+import { useParams } from "react-router";import { usePanels } from "~/components/Layout";import { RecordAction, RecordHeader } from "~/components/Layout/RecordHeader";+import { Confirm } from "~/components/Modals";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData } from "~/hooks";import type { Training } from "~/modules/resources";-import { useDocumentStore } from "~/stores";import { path } from "~/utils/path";import TrainingStatus from "./TrainingStatus";@@ -32,26 +33,32 @@ const TrainingHeader = () => {const { t } = useLingui();const permissions = usePermissions();const { toggleExplorer, toggleProperties } = usePanels();- // Live title from the editor's locked title block, so the header updates as- // the user types (before the loader revalidates).- const liveTitle = useDocumentStore((s) => s.liveTitle);- const displayName = liveTitle ?? routeData?.training?.name ?? "";+ const displayName = routeData?.training?.name ?? "";const deleteDisclosure = useDisclosure();- const publishFetcher = useFetcher<{}>();const status = routeData?.training?.status;const isDraft = status === "Draft";- const isPublishing = publishFetcher.state !== "idle";+ const canUpdate = permissions.can("update", "people");+ const [nextStatus, setNextStatus] = useState<+ "Active" | "Archived" | "Draft" | null+ >(null);- const onPublish = () => {- const formData = new FormData();- formData.append("ids", id);- formData.append("field", "status");- formData.append("value", "Active");- publishFetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateTraining- });+ const statusDialog = {+ Active: {+ title: t`Publish Training`,+ text: t`Employees assigned to this training can open it. The content, guide and questions can no longer change.`,+ confirmText: t`Publish`+ },+ Archived: {+ title: t`Archive Training`,+ text: t`Employees can no longer open this training.`,+ confirmText: t`Archive`+ },+ Draft: {+ title: t`Reopen Training`,+ text: t`The training goes back to Draft so you can change it. Employees cannot open it until you publish it again.`,+ confirmText: t`Reopen`+ }};const statusBadge = (@@ -59,17 +66,26 @@ const TrainingHeader = () => {<TrainingStatus status={routeData?.training?.status} />);const menuItems = (- <DropdownMenuItem- shortcut={MENU_ITEM_SHORTCUTS.delete}- disabled={- !permissions.can("delete", "resources") || !permissions.is("employee")- }- destructive- onClick={deleteDisclosure.onOpen}- >- <DropdownMenuIcon icon={<LuTrash />} />- <Trans>Delete Training</Trans>- </DropdownMenuItem>+ <>+ <DropdownMenuItem+ disabled={isDraft || !canUpdate}+ onClick={() => setNextStatus("Draft")}+ >+ <DropdownMenuIcon icon={<LuLoaderCircle />} />+ <Trans>Reopen</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.delete}+ disabled={+ !permissions.can("delete", "resources") || !permissions.is("employee")+ }+ destructive+ onClick={deleteDisclosure.onOpen}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ <Trans>Delete Training</Trans>+ </DropdownMenuItem>+ </>);return (@@ -83,14 +99,24 @@ const TrainingHeader = () => {onToggleProperties={toggleProperties}actions={<>+ {status === "Active" && (+ <RecordAction slot="overflow">+ <Button+ variant="secondary"+ leftIcon={<LuArchive />}+ isDisabled={!canUpdate}+ onClick={() => setNextStatus("Archived")}+ >+ <Trans>Archive</Trans>+ </Button>+ </RecordAction>+ )}{isDraft && (<RecordAction slot="primary"><Button- isDisabled={- !permissions.can("update", "people") || isPublishing- }- isLoading={isPublishing}- onClick={onPublish}+ variant="primary"+ isDisabled={!canUpdate}+ onClick={() => setNextStatus("Active")}><Trans>Publish</Trans></Button>@@ -99,6 +125,21 @@ const TrainingHeader = () => {</>}/>+ {nextStatus && (+ <Confirm+ action={path.to.bulkUpdateTraining}+ title={statusDialog[nextStatus].title}+ text={statusDialog[nextStatus].text}+ confirmText={statusDialog[nextStatus].confirmText}+ confirmVariant={nextStatus === "Archived" ? "destructive" : undefined}+ onCancel={() => setNextStatus(null)}+ onSubmit={() => setNextStatus(null)}+ >+ <input type="hidden" name="ids" value={id} />+ <input type="hidden" name="field" value="status" />+ <input type="hidden" name="value" value={nextStatus} />+ </Confirm>+ )}{deleteDisclosure.isOpen && (<ConfirmDeleteaction={path.to.deleteTraining(id)}diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsxindex e936eff8ff..f3f929737f 100644--- a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx+++ b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx@@ -23,19 +23,14 @@ import { useParams } from "react-router";import { z } from "zod";import Assignee, { useOptimisticAssignment } from "~/components/Assignee";import { Enumerable } from "~/components/Enumerable";-import { Ability, InputControlled, Tags } from "~/components/Form";+import { Ability, Boolean, InputControlled, Tags } from "~/components/Form";import { usePermissions, useRouteData } from "~/hooks";import { useTags } from "~/hooks/useTags";import type { Training } from "~/modules/resources";-import {- trainingFrequency,- trainingStatus,- trainingType-} from "~/modules/resources";-import type { action } from "~/routes/x+/items+/update";+import { trainingFrequency, trainingType } from "~/modules/resources";+import type { action } from "~/routes/x+/training+/update";import { path } from "~/utils/path";import { copyToClipboard } from "~/utils/string";-import TrainingStatus from "./TrainingStatus";const TrainingProperties = () => {const { t } = useLingui();@@ -64,7 +59,8 @@ const TrainingProperties = () => {| "frequency"| "estimatedDuration"| "description"- | "grantsAbilityId",+ | "grantsAbilityId"+ | "isExternal",value: string | null) => {const formData = new FormData();@@ -159,49 +155,41 @@ const TrainingProperties = () => {</Tooltip></HStack></HStack>- <span className="text-sm tracking-tight">- {routeData?.training?.name}- </span></VStack>- <Assignee- id={id}- table="training"- value={assignee ?? ""}- variant="inline"- isReadOnly={!permissions.can("update", "resources")}- />-<ValidatedFormdefaultValues={{- status: routeData?.training?.status ?? undefined+ name: routeData?.training?.name ?? ""}}validator={z.object({- status: z.string().min(1, { message: "Status is required" })+ name: z.string()})}className="w-full"+ isReadOnly={!permissions.can("update", "people")}>- <span className="text-sm tracking-tight">- <Select- label={t`Status`}- name="status"- inline={(value) => (- <TrainingStatus- status={value as "Draft" | "Active" | "Archived"}- />- )}- options={trainingStatus.map((status) => ({- value: status,- label: <TrainingStatus status={status} />- }))}- value={routeData?.training?.status ?? ""}- onChange={(value) => {- onUpdate("status", value?.value ?? null);- }}- />- </span>+ <InputControlled+ label={t`Name`}+ name="name"+ inline+ size="sm"+ value={routeData?.training?.name ?? ""}+ onBlur={(e) => {+ const name = e.target.value.trim();+ if (name && name !== routeData?.training?.name) {+ onUpdate("name", name);+ }+ }}+ /></ValidatedForm>+ <Assignee+ id={id}+ table="training"+ value={assignee ?? ""}+ variant="inline"+ isReadOnly={!permissions.can("update", "resources")}+ />+<ValidatedFormdefaultValues={{type: routeData?.training?.type ?? undefined@@ -262,6 +250,31 @@ const TrainingProperties = () => {</span></ValidatedForm>+ <ValidatedForm+ defaultValues={{+ isExternal: routeData?.training?.isExternal ?? false+ }}+ validator={z.object({+ isExternal: z.boolean()+ })}+ className="w-full"+ // Changes how employees take the training: Draft only, like the content.+ isReadOnly={+ !permissions.can("update", "people") ||+ routeData?.training?.status !== "Draft"+ }+ >+ <Boolean+ label={t`External Certification`}+ termId="external-certification"+ name="isExternal"+ variant="small"+ onChange={(value) => {+ onUpdate("isExternal", value ? "on" : "off");+ }}+ />+ </ValidatedForm>+<ValidatedFormdefaultValues={{estimatedDuration: routeData?.training?.estimatedDuration ?? undefineddiff --git a/apps/erp/app/modules/resources/ui/Training/index.ts b/apps/erp/app/modules/resources/ui/Training/index.tsindex 4919535e83..ef860b47cb 100644--- a/apps/erp/app/modules/resources/ui/Training/index.ts+++ b/apps/erp/app/modules/resources/ui/Training/index.ts@@ -3,8 +3,13 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.export { default as TrainingAssignmentForm } from "./TrainingAssignmentForm";+export { default as TrainingCertificateStep } from "./TrainingCertificateStep";export { default as TrainingExplorer } from "./TrainingExplorer";export { default as TrainingForm } from "./TrainingForm";+export {+ default as TrainingGuide,+ TrainingGuideViewer+} from "./TrainingGuide";export { default as TrainingHeader } from "./TrainingHeader";export { default as TrainingProperties } from "./TrainingProperties";export { default as TrainingStatus } from "./TrainingStatus";diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex da390980ec..76fa99c869 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1555,+ "totalTools": 1557,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -1092,6 +1092,7 @@{"name":"resources_deleteSuggestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"3a7f44ccb395","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteTraining","classification":"DESTRUCTIVE","paramCount":1,"schema":"3f6f0a410b0f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteTrainingAssignment","classification":"DESTRUCTIVE","paramCount":1,"schema":"7d3fe60cc8ed","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTrainingCompletion","classification":"DESTRUCTIVE","paramCount":1,"schema":"656576baec15","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteTrainingQuestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"b4f48c09ba9f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_deleteWorkCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},{"name":"resources_ensureProcessAbility","classification":"WRITE","paramCount":2,"schema":"6381d05a75ce","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"resources:update","paginates":false},@@ -1130,13 +1131,14 @@{"name":"resources_getProcessesWithoutAbility","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getSuggestion","classification":"READ","paramCount":1,"schema":"3a7f44ccb395","response":"77bb66a1249a","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getSuggestions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9e90aae0404b","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getTraining","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"84c264919a14","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignment","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"cb917b5ce4eb","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"41a2c00f121a","injectAuth":"companyId","permission":"resources:view","paginates":false},+ {"name":"resources_getTraining","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"df1853257bb5","injectAuth":"companyId","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignment","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"6f232f75558d","injectAuth":"companyId","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"cbe5832eecbc","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingAssignments","classification":"READ","paramCount":1,"schema":"d541f0a7e11f","response":"bb328cb9e34a","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingAssignmentStatus","classification":"READ","paramCount":3,"schema":"4b28f853e5b7","response":"2b901764b425","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingAssignmentStatusForEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"2b901764b425","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingAssignmentSummary","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c3f55a28a4ac","injectAuth":"companyId","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingCertificatePaths","classification":"READ","paramCount":1,"schema":"2cc02431606f","response":"3f161562db4a","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingGrantedAbilityId","classification":"READ","paramCount":1,"schema":"fbebd108a3c4","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainingQuestions","classification":"READ","paramCount":1,"schema":"3f6f0a410b0f","response":"cbc84076fe3b","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getTrainings","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"cc28f2dfe36f","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},diff --git a/apps/erp/app/routes/share+/training.$id.tsx b/apps/erp/app/routes/share+/training.$id.tsxindex 3e2a22cc5f..9507ded56e 100644--- a/apps/erp/app/routes/share+/training.$id.tsx+++ b/apps/erp/app/routes/share+/training.$id.tsx@@ -31,6 +31,7 @@ import {SelectValue,VStack} from "@carbon/react";+import { Trans } from "@lingui/react/macro";import { useEffect, useMemo, useRef, useState } from "react";import ConfettiExplosion from "react-confetti-explosion";import {@@ -40,6 +41,7 @@ import {LuCircleCheck,LuCircleX,LuClock,+ LuFileCheck,LuFlag,LuHouse,LuRefreshCcw@@ -50,14 +52,15 @@ import {Link,useActionData,useLoaderData,+ useNavigation,useSubmit} from "react-router";-import { notifyScheduleInputsChanged } from "~/modules/production";import {getTrainingAssignmentForCompletion,- getTrainingGrantedAbilityId,- insertTrainingCompletion+ TrainingCertificateStep,+ TrainingGuideViewer} from "~/modules/resources";+import { recordTrainingCompletion } from "~/modules/resources/resources.server";import type { TrainingQuestion } from "~/modules/resources/types";const logger = getLogger("erp", "share", "training");@@ -65,6 +68,9 @@ const logger = getLogger("erp", "share", "training");const PASSING_THRESHOLD = 0.8;interface ActionData {+ /** Set when an External training was completed by certificate upload. */+ certificate?: boolean;+ error?: string;passed: boolean;score: number;totalQuestions: number;@@ -133,7 +139,10 @@ export async function loader({ params, request }: LoaderFunctionArgs) {});}- const questions = (training.trainingQuestion ?? []) as TrainingQuestion[];+ // An External training is completed by certificate upload, not by quiz.+ const questions = training.isExternal+ ? []+ : ((training.trainingQuestion ?? []) as TrainingQuestion[]);const sortedQuestions = questions.sort((a, b) => a.sortOrder - b.sortOrder);return {@@ -145,7 +154,9 @@ export async function loader({ params, request }: LoaderFunctionArgs) {content: training.content,frequency: training.frequency,type: training.type,- estimatedDuration: training.estimatedDuration+ estimatedDuration: training.estimatedDuration,+ guidePath: training.guidePath,+ isExternal: training.isExternal},questions: sortedQuestions,userId,@@ -170,6 +181,14 @@ export async function action({ request, params }: ActionFunctionArgs) {return null;}+ if (formData.get("intent") === "certificate") {+ return completeWithCertificate({+ assignmentId: id,+ userId,+ file: formData.get("certificate")+ });+ }+const answersJson = formData.get("answers") as string;if (!answersJson) {@@ -193,6 +212,13 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ error: "Training not found" }, { status: 404 });}+ if (training.isExternal) {+ return data(+ { error: "This training is completed by uploading a certificate" },+ { status: 400 }+ );+ }+const questions = (training.trainingQuestion ?? []) as TrainingQuestion[];let correctAnswers = 0;@@ -269,36 +295,15 @@ export async function action({ request, params }: ActionFunctionArgs) {const passed = score >= PASSING_THRESHOLD;if (passed) {- const { data: period } = await serviceRole.rpc(- "get_current_training_period",- {- frequency: training.frequency- }- );-- await insertTrainingCompletion(serviceRole, {+ const recorded = await recordTrainingCompletion(serviceRole, {+ companyId: assignment.companyId,trainingAssignmentId: id,employeeId: userId,- period: period ?? null,- companyId: assignment.companyId,completedBy: userId,- createdBy: userId+ training});-- // Passing the training grants an ability (via the grant trigger) — restamp- // the scheduler for that ability's operator pool.- const grantedAbilityId = await getTrainingGrantedAbilityId(- serviceRole,- id,- assignment.companyId- );- if (grantedAbilityId) {- await notifyScheduleInputsChanged(- assignment.companyId,- "ability",- "Operator qualified via training",- grantedAbilityId- );+ if (recorded.error !== null) {+ return data({ error: recorded.error }, { status: recorded.status });}}@@ -311,24 +316,82 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+async function completeWithCertificate({+ assignmentId,+ userId,+ file+}: {+ assignmentId: string;+ userId: string;+ file: FormDataEntryValue | null;+}) {+ const serviceRole = getCarbonServiceRole();+ const assignment = await getAuthorizedAssignment(+ serviceRole,+ assignmentId,+ userId+ );++ const training = assignment.training;+ if (!training || Array.isArray(training)) {+ logger.error("Training not found for assignment", {+ companyId: assignment.companyId,+ trainingAssignmentId: assignmentId+ });+ return data({ error: "Training not found" }, { status: 404 });+ }+ if (!training.isExternal) {+ return data(+ { error: "This training is completed by answering its questions" },+ { status: 400 }+ );+ }++ const recorded = await recordTrainingCompletion(serviceRole, {+ companyId: assignment.companyId,+ trainingAssignmentId: assignmentId,+ employeeId: userId,+ completedBy: userId,+ training,+ certificate: file+ });+ if (recorded.error !== null) {+ return data({ error: recorded.error }, { status: recorded.status });+ }++ return {+ certificate: true,+ passed: true,+ score: 1,+ totalQuestions: 0,+ userAnswers: {},+ correctAnswers: 0+ } satisfies ActionData;+}+export default function TrainingWizard() {const { training, questions } = useLoaderData<typeof loader>();const actionData = useActionData<ActionData>();const submit = useSubmit();const audioRef = useRef<HTMLAudioElement | null>(null);+ const navigation = useNavigation();+ const isSubmitting = navigation.state === "submitting";+const [currentStep, setCurrentStep] = useState(0);const [answers, setAnswers] = useState<Record<string, UserAnswer>>({});const [isSubmitted, setIsSubmitted] = useState(false);+ const [certificate, setCertificate] = useState<File | null>(null);- const totalSteps = questions.length + 1;+ const isExternal = training.isExternal;+ const totalSteps = isExternal ? 2 : questions.length + 1;const isContentStep = currentStep === 0;const currentQuestionIndex = currentStep - 1;const currentQuestion = questions[currentQuestionIndex];const isLastStep = currentStep === totalSteps - 1;useEffect(() => {- if (actionData) {+ if (actionData && !actionData.error) {setIsSubmitted(true);if (actionData.passed && audioRef.current) {// biome-ignore lint/suspicious/noEmptyBlockStatements: suppressed due to migration@@ -364,6 +427,14 @@ export default function TrainingWizard() {submit(formData, { method: "post" });};+ const handleSubmitCertificate = () => {+ if (!certificate) return;+ const formData = new FormData();+ formData.append("intent", "certificate");+ formData.append("certificate", certificate);+ submit(formData, { method: "post", encType: "multipart/form-data" });+ };+const handleRetry = () => {setIsSubmitted(false);setAnswers({});@@ -461,6 +532,13 @@ export default function TrainingWizard() {<CardContent>{isContentStep ? (<ContentStep training={training} />+ ) : isExternal ? (+ <TrainingCertificateStep+ file={certificate}+ onFileChange={setCertificate}+ error={actionData?.error}+ isDisabled={isSubmitting}+ />) : (<QuestionStepquestion={currentQuestion}@@ -473,6 +551,16 @@ export default function TrainingWizard() {</CardContent></Card>+ {actionData?.error && !isExternal && (+ <Alert variant="destructive">+ <LuCircleX className="h-4 w-4" />+ <AlertTitle>+ <Trans>Training not recorded</Trans>+ </AlertTitle>+ <AlertDescription>{actionData.error}</AlertDescription>+ </Alert>+ )}+<div className="flex justify-between w-full gap-4"><ButtonisRound@@ -485,7 +573,31 @@ export default function TrainingWizard() {Previous</Button>- {isLastStep && questions.length > 0 ? (+ {isExternal ? (+ isContentStep ? (+ <Button+ isRound+ variant="primary"+ size="lg"+ rightIcon={<LuChevronRight />}+ onClick={handleNext}+ >+ <Trans>Upload Certificate</Trans>+ </Button>+ ) : (+ <Button+ isRound+ variant="primary"+ size="lg"+ rightIcon={<LuCircleCheck />}+ onClick={handleSubmitCertificate}+ isDisabled={!certificate || isSubmitting}+ isLoading={isSubmitting}+ >+ <Trans>Submit Certificate</Trans>+ </Button>+ )+ ) : isLastStep && questions.length > 0 ? (<ButtonisRoundvariant="primary"@@ -537,6 +649,8 @@ function ContentStep({description: string | null;content: unknown;estimatedDuration: string | null;+ guidePath: string | null;+ isExternal: boolean;};}) {const hasContent =@@ -565,6 +679,10 @@ function ContentStep({</div>)}+ {training.guidePath && (+ <TrainingGuideViewer guidePath={training.guidePath} />+ )}+{htmlContent ? (<divclassName="prose dark:prose-invert max-w-none w-full"@@ -572,6 +690,10 @@ function ContentStep({__html: htmlContent}}/>+ ) : training.guidePath ? null : training.isExternal ? (+ <p className="text-muted-foreground italic">+ <Trans>Upload your certificate on the next step.</Trans>+ </p>) : (<p className="text-muted-foreground italic">No training content available. Please proceed to the questions.@@ -798,31 +920,40 @@ function ResultsView({</CardHeader><CardContent><div className="grid grid-cols-1 md:grid-cols-2 gap-8">- <div className="flex flex-col items-center justify-center gap-2">- <span- className={cn(- "text-xl uppercase font-mono font-semibold tracking-tight",- actionData.passed ? "text-emerald-500" : "text-red-500"- )}- >- {actionData.passed ? "Passed" : "Failed"}- </span>- <div- className={cn(- "text-6xl font-mono font-semibold",- actionData.passed ? "text-emerald-500" : "text-red-500"- )}- >- {scorePercent}%+ {actionData.certificate ? (+ <div className="flex flex-col items-center justify-center gap-2">+ <LuFileCheck className="size-16 text-emerald-500" />+ <span className="text-xl uppercase font-mono font-semibold tracking-tight text-emerald-500">+ <Trans>Certificate Submitted</Trans>+ </span></div>- <p className="text-sm text-muted-foreground">- {actionData.correctAnswers} of {actionData.totalQuestions}{" "}- correct- </p>- <p className="text-sm text-muted-foreground">- (Passing score: {Math.round(PASSING_THRESHOLD * 100)}%)- </p>- </div>+ ) : (+ <div className="flex flex-col items-center justify-center gap-2">+ <span+ className={cn(+ "text-xl uppercase font-mono font-semibold tracking-tight",+ actionData.passed ? "text-emerald-500" : "text-red-500"+ )}+ >+ {actionData.passed ? "Passed" : "Failed"}+ </span>+ <div+ className={cn(+ "text-6xl font-mono font-semibold",+ actionData.passed ? "text-emerald-500" : "text-red-500"+ )}+ >+ {scorePercent}%+ </div>+ <p className="text-sm text-muted-foreground">+ {actionData.correctAnswers} of {actionData.totalQuestions}{" "}+ correct+ </p>+ <p className="text-sm text-muted-foreground">+ (Passing score: {Math.round(PASSING_THRESHOLD * 100)}%)+ </p>+ </div>+ )}<div className="flex flex-col gap-4">{actionData.passed ? (diff --git a/apps/erp/app/routes/x+/person+/$personId.abilities.tsx b/apps/erp/app/routes/x+/person+/$personId.abilities.tsxindex 342ca3fe7f..7b85a6460a 100644--- a/apps/erp/app/routes/x+/person+/$personId.abilities.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.abilities.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";@@ -12,11 +13,14 @@ import { useLoaderData, useParams } from "react-router";import { PersonAbilities, PersonTrainings } from "~/modules/people/ui/Person";import {getEmployeeAbilities,- getTrainingAssignmentStatusForEmployee+ getTrainingAssignmentStatusForEmployee,+ getTrainingCertificatePaths} from "~/modules/resources";import type { TrainingAssignmentStatusItem } from "~/modules/resources/types";import { path } from "~/utils/path";+const logger = getLogger("erp", "person-trainings");+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "people"@@ -40,21 +44,41 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const trainingRows = (trainings.data ?? []) as TrainingAssignmentStatusItem[];+ const certificatePaths = await getTrainingCertificatePaths(+ client,+ companyId,+ trainingRows.flatMap((t) => (t.completionId ? [t.completionId] : []))+ );++ // The certificate links are optional: the page still loads without them.+ if (certificatePaths.error) {+ logger.error("Failed to load training certificate paths", {+ companyId,+ error: certificatePaths.error+ });+ }+return {abilities: employeeAbilities.data ?? [],- trainings: (trainings.data ?? []) as TrainingAssignmentStatusItem[]+ trainings: trainingRows,+ certificatePaths: certificatePaths.data ?? {}};}export default function PersonAbilitiesRoute() {- const { abilities, trainings } = useLoaderData<typeof loader>();+ const { abilities, trainings, certificatePaths } =+ useLoaderData<typeof loader>();const { personId } = useParams();if (!personId) throw new Error("Could not find personId");return (<VStack spacing={4}><PersonAbilities personId={personId} abilities={abilities} />- <PersonTrainings trainings={trainings} />+ <PersonTrainings+ trainings={trainings}+ certificatePaths={certificatePaths}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx b/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsxindex 5f8f1c24a8..a9ae735460 100644--- a/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx+++ b/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx@@ -5,6 +5,8 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -17,6 +19,13 @@ import {DrawerTitle,HStack,Input,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalTitle,ToggleGroup,ToggleGroupItem,VStack@@ -29,17 +38,28 @@ import {LuCalendar,LuCircleCheck,LuClock,+ LuFileCheck,LuSearch,- LuTriangleAlert+ LuTriangleAlert,+ LuUndo2} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { useFetcher, useLoaderData, useNavigate } from "react-router";-import { DateTime, EmployeeAvatar, Empty } from "~/components";+import { DateTime, EmployeeAvatar, Empty, FileDropzone } from "~/components";+import { Confirm } from "~/components/Modals";import { usePermissions } from "~/hooks";-import { getTraining, getTrainingAssignmentStatus } from "~/modules/resources";+import {+ getTraining,+ getTrainingAssignmentStatus,+ getTrainingCertificatePaths,+ trainingCertificateAccept+} from "~/modules/resources";import type { TrainingAssignmentStatusItem } from "~/modules/resources/types";+import type { action as completeAction } from "~/routes/x+/resources+/assignments.complete";import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";+import { getPrivateUrl, path } from "~/utils/path";++const logger = getLogger("erp", "training-assignments");export const handle: Handle = {breadcrumb: msg`Detail`,@@ -90,9 +110,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const assignments = (assignmentStatus.data ??+ []) as TrainingAssignmentStatusItem[];++ const certificatePaths = await getTrainingCertificatePaths(+ client,+ companyId,+ assignments.flatMap((a) => (a.completionId ? [a.completionId] : []))+ );++ // The certificate links are optional: the page still loads without them.+ if (certificatePaths.error) {+ logger.error("Failed to load training certificate paths", {+ companyId,+ error: certificatePaths.error+ });+ }+return {training: training.data,- assignments: (assignmentStatus.data ?? []) as TrainingAssignmentStatusItem[]+ assignments,+ certificatePaths: certificatePaths.data ?? {}};}@@ -137,21 +175,118 @@ type StatusFilter =| "Overdue"| "Not Required";+function CertificateCompleteModal({+ assignment,+ onClose+}: {+ assignment: TrainingAssignmentStatusItem;+ onClose: () => void;+}) {+ const { t } = useLingui();+ const fetcher = useAction<typeof completeAction>({+ onSuccess: () => onClose()+ });+ const isSubmitting = fetcher.state !== "idle";+ const [file, setFile] = useState<File | null>(null);++ const onSubmit = () => {+ if (!file) return;+ const formData = new FormData();+ formData.append("trainingAssignmentId", assignment.trainingAssignmentId);+ formData.append("employeeId", assignment.employeeId);+ formData.append("certificate", file);+ fetcher.submit(formData, {+ method: "post",+ action: path.to.markTrainingComplete,+ encType: "multipart/form-data"+ });+ };++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>{t`Upload Certificate`}</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ <p className="text-sm text-muted-foreground">+ <Trans>+ This training is external. Upload{" "}+ {assignment.employeeName?.trim()}'s certificate to mark it+ complete.+ </Trans>+ </p>+ <FileDropzone+ onDrop={(files) => setFile(files[0] ?? null)}+ accept={{+ ...trainingCertificateAccept,+ "image/heic": [".heic", ".heif"]+ }}+ multiple={false}+ disabled={isSubmitting}+ className="mt-0 w-full"+ />+ {file && (+ <HStack spacing={2} className="text-sm">+ <LuFileCheck className="text-emerald-500" />+ <span className="break-all">{file.name}</span>+ </HStack>+ )}+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ onClick={onSubmit}+ isDisabled={!file || isSubmitting}+ isLoading={isSubmitting}+ leftIcon={<LuCircleCheck />}+ >+ <Trans>Mark Complete</Trans>+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}+function AssignmentListItem({assignment,- currentPeriod,+ certificatePath,+ isExternal,+ canRemove,disabled,isLast}: {assignment: TrainingAssignmentStatusItem;- currentPeriod: string | null;+ certificatePath: string | null;+ isExternal: boolean;+ canRemove: boolean;disabled: boolean;isLast: boolean;}) {+ const { t } = useLingui();const fetcher = useFetcher();const isSubmitting = fetcher.state !== "idle";+ const employeeName = assignment.employeeName?.trim() ?? "";const canMarkComplete =assignment.status !== "Completed" && assignment.status !== "Not Required";+ const [isCertificateOpen, setIsCertificateOpen] = useState(false);+ // Hold the completion id from when the dialog opened: the row loses its+ // completionId as soon as the removal revalidates, and the dialog must stay+ // mounted until its submission settles so it can close itself.+ const [removeCompletionId, setRemoveCompletionId] = useState<number | null>(+ null+ );return (<div className={cn("p-4", !isLast && "border-b w-full")}>@@ -181,7 +316,46 @@ function AssignmentListItem({<DateTime value={assignment.completedAt} variant="date" /></span>)}- {canMarkComplete && (+ {certificatePath && (+ <Button+ variant="secondary"+ size="sm"+ leftIcon={<LuFileCheck />}+ asChild+ >+ <a+ href={getPrivateUrl(certificatePath)}+ target="_blank"+ rel="noreferrer"+ >+ <Trans>View Certificate</Trans>+ </a>+ </Button>+ )}+ {assignment.status === "Completed" &&+ assignment.completionId &&+ canRemove && (+ <Button+ variant="secondary"+ size="sm"+ leftIcon={<LuUndo2 />}+ onClick={() => setRemoveCompletionId(assignment.completionId)}+ >+ <Trans>Remove Completion</Trans>+ </Button>+ )}+ {canMarkComplete && isExternal && (+ <Button+ variant="secondary"+ size="sm"+ isDisabled={disabled}+ leftIcon={<LuCircleCheck />}+ onClick={() => setIsCertificateOpen(true)}+ >+ <Trans>Mark Complete</Trans>+ </Button>+ )}+ {canMarkComplete && !isExternal && (<fetcher.Form method="post" action={path.to.markTrainingComplete}><inputtype="hidden"@@ -193,7 +367,6 @@ function AssignmentListItem({name="employeeId"value={assignment.employeeId}/>- <input type="hidden" name="period" value={currentPeriod ?? ""} /><Buttontype="submit"variant="secondary"@@ -208,13 +381,33 @@ function AssignmentListItem({)}</HStack></div>+ {isCertificateOpen && (+ <CertificateCompleteModal+ assignment={assignment}+ onClose={() => setIsCertificateOpen(false)}+ />+ )}+ {removeCompletionId !== null && (+ <Confirm+ action={path.to.markTrainingIncomplete}+ title={t`Remove Completion`}+ text={t`The training goes back to Pending for ${employeeName}. The employee keeps any ability this training granted. Remove it on their Abilities page if needed.`}+ confirmText={t`Remove`}+ confirmVariant="destructive"+ onCancel={() => setRemoveCompletionId(null)}+ onSubmit={() => setRemoveCompletionId(null)}+ >+ <input type="hidden" name="completionId" value={removeCompletionId} />+ </Confirm>+ )}</div>);}export default function TrainingAssignmentDetailRoute() {const { t } = useLingui();- const { training, assignments } = useLoaderData<typeof loader>();+ const { training, assignments, certificatePaths } =+ useLoaderData<typeof loader>();const permissions = usePermissions();const navigate = useNavigate();const [search, setSearch] = useState("");@@ -336,7 +529,13 @@ export default function TrainingAssignmentDetailRoute() {<AssignmentListItemkey={`${assignment.employeeId}-${assignment.trainingAssignmentId}`}assignment={assignment}- currentPeriod={currentPeriod}+ certificatePath={+ assignment.completionId+ ? (certificatePaths[assignment.completionId] ?? null)+ : null+ }+ isExternal={training.isExternal}+ canRemove={permissions.can("delete", "resources")}disabled={!permissions.can("update", "resources")}isLast={index === filteredAssignments.length - 1}/>diff --git a/apps/erp/app/routes/x+/resources+/assignments.complete.tsx b/apps/erp/app/routes/x+/resources+/assignments.complete.tsxindex 300608a9fe..6354805f73 100644--- a/apps/erp/app/routes/x+/resources+/assignments.complete.tsx+++ b/apps/erp/app/routes/x+/resources+/assignments.complete.tsx@@ -5,16 +5,16 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";-import { notifyScheduleInputsChanged } from "~/modules/production";-import {- getTrainingGrantedAbilityId,- insertTrainingCompletion-} from "~/modules/resources";+import { getTrainingAssignment } from "~/modules/resources";+import { recordTrainingCompletion } from "~/modules/resources/resources.server";import { path } from "~/utils/path";+const logger = getLogger("erp", "training-assignment-complete");+export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {update: "resources",@@ -24,7 +24,6 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const trainingAssignmentId = formData.get("trainingAssignmentId");const employeeId = formData.get("employeeId");- const period = formData.get("period");if (!trainingAssignmentId || !employeeId) {return data(@@ -37,42 +36,61 @@ export async function action({ request }: ActionFunctionArgs) {);}- const result = await insertTrainingCompletion(client, {- trainingAssignmentId: trainingAssignmentId.toString(),- employeeId: employeeId.toString(),- period: period?.toString() || null,- companyId,- completedBy: userId,- createdBy: userId- });-- if (result.error) {+ const assignment = await getTrainingAssignment(+ client,+ trainingAssignmentId.toString()+ );+ if (assignment.error || assignment.data.companyId !== companyId) {+ logger.error("Training assignment not found", {+ companyId,+ trainingAssignmentId: trainingAssignmentId.toString(),+ error: assignment.error+ });return data(- { error: result.error.message },+ { error: "Training assignment not found" },{- status: 500,+ status: 404,// @ts-expect-error TS2322 - TODO: fix typeheaders: await flash(request,- error(result.error, "Failed to mark training complete")+ error(null, "Training assignment not found"))});}- // Completing training that grants an ability adds a qualification (via the- // grant trigger) — restamp the scheduler for that ability's operator pool.- const grantedAbilityId = await getTrainingGrantedAbilityId(- client,- trainingAssignmentId.toString(),- companyId- );- if (grantedAbilityId) {- await notifyScheduleInputsChanged(+ const training = assignment.data.training;+ if (!training || Array.isArray(training)) {+ logger.error("Training not found for assignment", {companyId,- "ability",- "Operator qualified via training",- grantedAbilityId+ trainingAssignmentId: trainingAssignmentId.toString()+ });+ return data(+ { error: "Training not found" },+ {+ status: 404,+ // @ts-expect-error TS2322 - TODO: fix type+ headers: await flash(request, error(null, "Training not found"))+ }+ );+ }++ const recorded = await recordTrainingCompletion(client, {+ companyId,+ trainingAssignmentId: trainingAssignmentId.toString(),+ employeeId: employeeId.toString(),+ completedBy: userId,+ training,+ certificate: formData.get("certificate")+ });+ if (recorded.error !== null) {+ return data(+ { error: recorded.error },+ {+ status: recorded.status,+ // @ts-expect-error TS2322 - TODO: fix type+ headers: await flash(request, error(null, recorded.error))+ });}diff --git a/apps/erp/app/routes/x+/resources+/assignments.uncomplete.tsx b/apps/erp/app/routes/x+/resources+/assignments.uncomplete.tsxnew file mode 100644index 0000000000..fb54d7f2a7--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/assignments.uncomplete.tsx@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";+import { redirect } from "@carbon/utils";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { deleteTrainingCompletion } from "~/modules/resources";+import { path } from "~/utils/path";++const logger = getLogger("erp", "training-assignment-uncomplete");++// Removes a wrong completion. The employee keeps any ability the completion+// granted: the grant trigger only adds abilities, and the person may hold the+// ability for another reason.+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ delete: "resources"+ });++ const formData = await request.formData();+ const completionId = Number(formData.get("completionId"));++ if (!Number.isInteger(completionId) || completionId <= 0) {+ return data(+ { error: "Missing completion" },+ {+ status: 400,+ // @ts-expect-error TS2322 - TODO: fix type+ headers: await flash(request, error(null, "Missing completion"))+ }+ );+ }++ const result = await deleteTrainingCompletion(+ client,+ completionId,+ companyId+ );++ if (result.error) {+ logger.error("Failed to remove training completion", {+ companyId,+ completionId,+ error: result.error+ });+ return data(+ { error: result.error.message },+ {+ status: 500,+ // @ts-expect-error TS2322 - TODO: fix type+ headers: await flash(+ request,+ error(result.error, "Failed to remove the completion")+ )+ }+ );+ }++ return data(+ { success: true },+ {+ // @ts-expect-error TS2322 - TODO: fix type+ headers: await flash(request, success("Completion removed"))+ }+ );+}++export async function loader() {+ return redirect(path.to.trainingAssignments);+}diff --git a/apps/erp/app/routes/x+/training+/$id.tsx b/apps/erp/app/routes/x+/training+/$id.tsxindex 9b380d860b..94c1ee339b 100644--- a/apps/erp/app/routes/x+/training+/$id.tsx+++ b/apps/erp/app/routes/x+/training+/$id.tsx@@ -7,26 +7,36 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";-import { generateHTML, RecordOutlet, useDebounce } from "@carbon/react";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ isRichTextEmpty,+ RecordOutlet,+ RichTextView,+ useDebounce,+ VStack+} from "@carbon/react";import { Editor } from "@carbon/react/Editor";import { redirect } from "@carbon/utils";import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";-import { useLingui } from "@lingui/react/macro";-import { useEffect, useState } from "react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";import type { LoaderFunctionArgs } from "react-router";-import { useFetcher, useLoaderData, useParams } from "react-router";+import { useLoaderData, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";import { useImageUpload, usePermissions, useUser } from "~/hooks";import {getTraining,TrainingExplorer,+ TrainingGuide,TrainingHeader,TrainingProperties} from "~/modules/resources";import { getTagsList } from "~/modules/shared";-import type { action } from "~/routes/x+/training+/update";-import { useDocumentStore } from "~/stores";import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -82,6 +92,11 @@ export default function TrainingRoute() {const { id } = useParams();if (!id) throw new Error("Could not find id");+ const { training } = useLoaderData<typeof loader>();+ const permissions = usePermissions();+ const canEditGuide =+ permissions.can("update", "people") && training.status === "Draft";+return (<PanelProvider key={id}><div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">@@ -93,8 +108,16 @@ export default function TrainingRoute() {explorer={<TrainingExplorer key={`explorer-${id}`} />}content={<div className="bg-card h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">- <TrainingEditor />- <RecordOutlet />+ <VStack spacing={4} className="p-4">+ <TrainingGuide+ key={`guide-${id}`}+ trainingId={id}+ guidePath={training.guidePath}+ canEdit={canEditGuide}+ />+ <TrainingContent key={`content-${id}`} />+ <RecordOutlet />+ </VStack></div>}properties={<TrainingProperties key={`properties-${id}`} />}@@ -106,19 +129,13 @@ export default function TrainingRoute() {);}-function TrainingEditor() {+function TrainingContent() {const { id } = useParams();if (!id) throw new Error("Could not find id");- const { t } = useLingui();const permissions = usePermissions();-const loaderData = useLoaderData<typeof loader>();- const [trainingName, setTrainingName] = useState(- loaderData?.training?.name ?? ""- );-const [content, setContent] = useState<JSONContent>((loaderData?.training?.content ?? {}) as JSONContent);@@ -141,74 +158,49 @@ function TrainingEditor() {true);- const fetcher = useFetcher<typeof action>();- const setLiveTitle = useDocumentStore((s) => s.setLiveTitle);-- const updateTrainingName = useDebounce(- async (name: string) => {- const formData = new FormData();-- formData.append("ids", id);- formData.append("field", "name");- formData.append("value", name);-- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateTraining- });- },- 500,- true- );-const onUploadImage = useImageUpload("training");const canEdit =permissions.can("update", "people") &&loaderData?.training?.status === "Draft";- // Mirror the live title only while editing; clear it when editing ends (e.g.- // a Draft→Active transition that doesn't remount the route) or on unmount, so- // the header title bar can never show a stale edited title.- useEffect(() => {- if (!canEdit) setLiveTitle(null);- return () => setLiveTitle(null);- }, [canEdit, setLiveTitle]);-return (- <div className="flex flex-col w-full h-full">- {canEdit ? (- <Editor- toolbar- title={{- value: trainingName,- placeholder: t`Untitled`,- onChange: (name) => {- setTrainingName(name);- setLiveTitle(name);- updateTrainingName(name);- }- }}- initialValue={content}- onUpload={onUploadImage}- onChange={(value) => {- setContent(value);- updateTraining(value);- }}- />- ) : (- <div className="flex flex-col gap-6 w-full h-full p-8">- <h1 className="md:text-3xl text-2xl font-semibold leading-tight tracking-tight text-foreground">- {trainingName}- </h1>- <div- className="prose dark:prose-invert"- dangerouslySetInnerHTML={{- __html: generateHTML(content)+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Content</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>Shown to employees below the PDF guide</Trans>+ </CardDescription>+ </CardHeader>+ <CardContent className={canEdit ? "p-0 overflow-hidden" : undefined}>+ {canEdit ? (+ // Flush toolbar: pad the text, not the panel.+ <Editor+ toolbar+ toolbarClassName="static bg-transparent px-4"+ className="w-full [&_.ProseMirror]:min-h-[240px] [&_.ProseMirror]:px-6 [&_.ProseMirror]:py-4 max-md:[&_.ProseMirror]:px-4"+ initialValue={content}+ onUpload={onUploadImage}+ onChange={(value) => {+ setContent(value);+ updateTraining(value);}}/>- </div>- )}- </div>+ ) : // RichTextView shows its empty text on phones only, so say it here.+ isRichTextEmpty(content) ? (+ <p className="text-sm text-muted-foreground">+ <Trans>No content</Trans>+ </p>+ ) : (+ <RichTextView+ content={content}+ empty={<Trans>No content</Trans>}+ className="prose dark:prose-invert max-w-none"+ />+ )}+ </CardContent>+ </Card>);}diff --git a/apps/erp/app/routes/x+/training+/update.tsx b/apps/erp/app/routes/x+/training+/update.tsxindex 3e90cd7e34..d75587d16a 100644--- a/apps/erp/app/routes/x+/training+/update.tsx+++ b/apps/erp/app/routes/x+/training+/update.tsx@@ -3,11 +3,17 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";import { unchecked } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";+import {+ isValidTrainingGuideKey,+ trainingGuideKeyPrefix+} from "~/modules/resources";export async function action({ request }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "people"});@@ -47,6 +53,45 @@ export async function action({ request }: ActionFunctionArgs) {updatedAt: new Date().toISOString()}).in("id", ids as string[]);+ case "isExternal":+ case "guidePath": {+ // These change how employees take the training, so Draft only.+ const refusal = await refuseUnlessDraft(client, companyId, ids);+ if (refusal) return refusal;++ if (field === "isExternal") {+ return await client+ .from("training")+ .update({+ isExternal: value === "on",+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[])+ .eq("companyId", companyId);+ }++ const trainingId = ids[0] as string;+ if (+ ids.length !== 1 ||+ (value !== "" &&+ !isValidTrainingGuideKey(+ value,+ trainingGuideKeyPrefix(companyId, trainingId)+ ))+ ) {+ return { error: { message: "Invalid guide file" }, data: null };+ }+ return await client+ .from("training")+ .update({+ guidePath: value === "" ? null : value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", trainingId)+ .eq("companyId", companyId);+ }case "tags":return await client.from("training")@@ -61,3 +106,25 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: "Invalid field" }, data: null };}}++async function refuseUnlessDraft(+ client: SupabaseClient<Database>,+ companyId: string,+ ids: FormDataEntryValue[]+) {+ const trainings = await client+ .from("training")+ .select("status")+ .in("id", ids as string[])+ .eq("companyId", companyId);+ if (trainings.error || trainings.data.length !== ids.length) {+ return { error: { message: "Training not found" }, data: null };+ }+ if (trainings.data.some((training) => training.status !== "Draft")) {+ return {+ error: { message: "This can only change while the training is Draft" },+ data: null+ };+ }+ return null;+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 2ac1aeef02..9f7437a172 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1587,6 +1587,7 @@ export const path = {makeMethodSave: `${x}/items/methods/save`,manualPrint: `${x}/print`,markTrainingComplete: `${x}/resources/assignments/complete`,+ markTrainingIncomplete: `${x}/resources/assignments/uncomplete`,material: (id: string) => generatePath(`${x}/material/${id}`),materialCosting: (id: string) =>generatePath(`${x}/material/${id}/costing`),diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.tsindex db7f6228e3..d07022ca6c 100644--- a/docs/content/src/glossary/terms.ts+++ b/docs/content/src/glossary/terms.ts@@ -2317,5 +2317,9 @@ export const terms = {"swift-bic": {term: msg`SWIFT / BIC`,definition: msg`The code that identifies a bank internationally, 8 or 11 characters. A cross-border payment will not route without it, while a domestic transfer usually travels on the local routing code instead.`+ },+ "external-certification": {+ term: msg`External certification`,+ definition: msg`Training taken outside Carbon, such as a vendor course. Employees complete it by uploading the certificate they received instead of answering a quiz.`}} as const satisfies Record<string, GlossaryEntry>;diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 2c9d610619..9e32315b0f 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -31113,6 +31113,9 @@ export default {{$ref: "#/parameters/rowFilter.trainingCompletion.period"},+ {+ $ref: "#/parameters/rowFilter.trainingCompletion.certificatePath"+ },{$ref: "#/parameters/select"},@@ -31205,6 +31208,9 @@ export default {{$ref: "#/parameters/rowFilter.trainingCompletion.period"},+ {+ $ref: "#/parameters/rowFilter.trainingCompletion.certificatePath"+ },{$ref: "#/parameters/preferReturn"}@@ -31251,6 +31257,9 @@ export default {{$ref: "#/parameters/rowFilter.trainingCompletion.period"},+ {+ $ref: "#/parameters/rowFilter.trainingCompletion.certificatePath"+ },{$ref: "#/parameters/body.trainingCompletion"},@@ -96768,6 +96777,12 @@ export default {{$ref: "#/parameters/rowFilter.training.grantsAbilityId"},+ {+ $ref: "#/parameters/rowFilter.training.guidePath"+ },+ {+ $ref: "#/parameters/rowFilter.training.isExternal"+ },{$ref: "#/parameters/select"},@@ -96881,6 +96896,12 @@ export default {{$ref: "#/parameters/rowFilter.training.grantsAbilityId"},+ {+ $ref: "#/parameters/rowFilter.training.guidePath"+ },+ {+ $ref: "#/parameters/rowFilter.training.isExternal"+ },{$ref: "#/parameters/preferReturn"}@@ -96948,6 +96969,12 @@ export default {{$ref: "#/parameters/rowFilter.training.grantsAbilityId"},+ {+ $ref: "#/parameters/rowFilter.training.guidePath"+ },+ {+ $ref: "#/parameters/rowFilter.training.isExternal"+ },{$ref: "#/parameters/body.training"},@@ -132660,6 +132687,10 @@ export default {period: {format: "text",type: "string"+ },+ certificatePath: {+ format: "text",+ type: "string"}},type: "object"@@ -164079,7 +164110,8 @@ export default {"frequency","type","createdAt",- "createdBy"+ "createdBy",+ "isExternal"],properties: {id: {@@ -164177,6 +164209,15 @@ export default {"Note:\nThis is a Foreign Key to `ability.id`.<fk table='ability' column='id'/>",format: "text",type: "string"+ },+ guidePath: {+ format: "text",+ type: "string"+ },+ isExternal: {+ default: false,+ format: "boolean",+ type: "boolean"}},type: "object"@@ -184314,6 +184355,12 @@ export default {in: "query",type: "string"},+ "rowFilter.trainingCompletion.certificatePath": {+ name: "certificatePath",+ required: false,+ in: "query",+ type: "string"+ },"body.nonConformanceCustomer": {name: "nonConformanceCustomer",description: "nonConformanceCustomer",@@ -219495,6 +219542,18 @@ export default {in: "query",type: "string"},+ "rowFilter.training.guidePath": {+ name: "guidePath",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.training.isExternal": {+ name: "isExternal",+ required: false,+ in: "query",+ type: "string"+ },"body.gauge": {name: "gauge",description: "gauge",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex e2c62832b1..5d5085b537 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -69349,7 +69349,9 @@ export type Database = {estimatedDuration: string | nullfrequency: Database["public"]["Enums"]["trainingFrequency"]grantsAbilityId: string | null+ guidePath: string | nullid: string+ isExternal: booleanname: stringprocessId: string | nullstatus: Database["public"]["Enums"]["trainingStatus"]@@ -69369,7 +69371,9 @@ export type Database = {estimatedDuration?: string | nullfrequency?: Database["public"]["Enums"]["trainingFrequency"]grantsAbilityId?: string | null+ guidePath?: string | nullid?: string+ isExternal?: booleanname: stringprocessId?: string | nullstatus?: Database["public"]["Enums"]["trainingStatus"]@@ -69389,7 +69393,9 @@ export type Database = {estimatedDuration?: string | nullfrequency?: Database["public"]["Enums"]["trainingFrequency"]grantsAbilityId?: string | null+ guidePath?: string | nullid?: string+ isExternal?: booleanname?: stringprocessId?: string | nullstatus?: Database["public"]["Enums"]["trainingStatus"]@@ -69711,6 +69717,7 @@ export type Database = {}trainingCompletion: {Row: {+ certificatePath: string | nullcompanyId: stringcompletedAt: stringcompletedBy: string@@ -69724,6 +69731,7 @@ export type Database = {updatedBy: string | null}Insert: {+ certificatePath?: string | nullcompanyId: stringcompletedAt?: stringcompletedBy: string@@ -69737,6 +69745,7 @@ export type Database = {updatedBy?: string | null}Update: {+ certificatePath?: string | nullcompanyId?: stringcompletedAt?: stringcompletedBy?: stringdiff --git a/packages/database/supabase/migrations/20261014085812_training-guides-and-certificates.sql b/packages/database/supabase/migrations/20261014085812_training-guides-and-certificates.sqlnew file mode 100644index 0000000000..a49a9b60f0--- /dev/null+++ b/packages/database/supabase/migrations/20261014085812_training-guides-and-certificates.sql@@ -0,0 +1,8 @@+-- A training can carry one PDF guide, and an External training is completed by+-- uploading a certificate instead of passing the quiz.+ALTER TABLE "training"+ ADD COLUMN "guidePath" TEXT,+ ADD COLUMN "isExternal" BOOLEAN NOT NULL DEFAULT false;++ALTER TABLE "trainingCompletion"+ ADD COLUMN "certificatePath" TEXT;diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex aa71a473e5..8101a98588 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261014030025",+ "schemaVersion": "20261014085812","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-14T03:20:40.736Z",+ "exportedAt": "2026-10-14T16:04:53.034Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -2441,7 +2441,9 @@"createdBy","updatedAt","updatedBy",- "grantsAbilityId"+ "grantsAbilityId",+ "guidePath",+ "isExternal"]},{@@ -2472,7 +2474,8 @@"createdBy","updatedAt","updatedBy",- "period"+ "period",+ "certificatePath"]},{diff --git a/packages/react/src/Editor/Editor.tsx b/packages/react/src/Editor/Editor.tsxindex f060d5819e..f0a78ef83e 100644--- a/packages/react/src/Editor/Editor.tsx+++ b/packages/react/src/Editor/Editor.tsx@@ -86,6 +86,7 @@ interface EditorProp {* options as the bubble menu — no new capabilities.*/toolbar?: boolean;+ toolbarClassName?: string;/*** Full-screen "document" mode. When provided, the editor's first block is a* locked H1 title seeded from `title.value`; the title text is streamed back@@ -118,6 +119,7 @@ const Editor = ({mentions,highlightTokens,toolbar,+ toolbarClassName,title}: EditorProp) => {const { t } = useLingui();@@ -318,7 +320,9 @@ const Editor = ({onChange(editor.getJSON());}}}- slotBefore={toolbar ? <Toolbar /> : undefined}+ slotBefore={+ toolbar ? <Toolbar className={toolbarClassName} /> : undefined+ }slotAfter={<ImageResizer />}><EditorCommand className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-md border border-muted bg-background px-1 py-2 shadow-md transition-[opacity,transform]">