Compare commits

...

13 Commits

Author SHA1 Message Date
ca488cb602 improvement: generating tasks and their related steps improved.
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 5m8s
Production — tag build, push, deploy / deploy (push) Successful in 13m23s
2026-09-25 23:11:04 +03:30
e70f806ee6 Merge pull request 'fix(tasks): keep case header names readable on mobile' (#90) from bug/responsive-task-header into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 19m30s
Registry — build, push, deploy / deploy (push) Successful in 1m9s
Reviewed-on: #90
Reviewed-by: admin <admin@localhost>
2026-09-22 14:13:09 +03:30
26ed5b4512 Merge pull request 'feat/cases/add-voice-input-for-lab-case-line' (#82) from feat/cases/add-voice-input-for-lab-case-line into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 7m16s
Registry — build, push, deploy / deploy (push) Successful in 1m42s
Reviewed-on: #82
Reviewed-by: admin <admin@localhost>
2026-09-22 14:12:20 +03:30
af10e7f1a0 fix(docs): correct link path for voice treatment entry spec 2026-09-21 13:01:49 +08:00
39bfec1d3f docs(voice): one flat spec file, no progress note
Amin's call: specs live at docs/specs/<slug>.md, and the repo does not carry a
progress ledger. The ledger was an /orchestrate requirement, not something the
codebase needs to keep.

The link to voice-treatment-entry is repointed — that spec still sits in its own
folder on master.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:01:49 +08:00
c3d6581d2a fix(cases): tell an edit denial from an access denial
assertCanEditCases checks TAB_CASES_EDIT but threw PERMISSION_ACCESS_CASES —
"you do not have access to cases" — at a member who holds TAB_CASES_READ and can
open and read every case. It sent them to the wrong setting. Nine call sites:
start, delete, assign, external code, important flag and the rest.

assertCanReadCases (:1378) keeps PERMISSION_ACCESS_CASES, which is accurate
there, and so do both lab-case-activity.service.ts sites — those check READ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:01:49 +08:00
5565dba604 feat(errors): add PERMISSION_EDIT_CASES and use it for the lab voice denial
Cases was the one feature with no edit-specific error code, so cases.service.ts
throws PERMISSION_ACCESS_CASES for a failed read check (:1375) and for a failed
edit check (:1391) alike. The lab voice branch checks TAB_CASES_EDIT, so reusing
it told a member holding TAB_CASES_READ "you do not have access to cases" — false,
and it points them at the wrong setting.

All three layers: the code in error-codes.ts, the throw in assertCanDictate, and
errors.PERMISSION_EDIT_CASES in en, fa and nl.

The two voice.service.spec cases asserting the old code failed on the change and
were updated — they are the guard that caught it.

cases.service.ts:1391 has the same mismatch and is left alone; it is an existing
endpoint's message, not this task's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:01:49 +08:00
b2f2825beb fix(voice): say so when a dictation lands nothing on the line
buildLabLineFromVoice returns null whenever no prosthesis job survives — bare
teeth with no material, an out-of-catalog code, every code refused by the stack
rules. applyVoice then closed the sheet and returned in silence.

Dictate "دندون ۱۲ و ۱۴" with no material: lab mode forces labDependent, so the
merged row is available and ticked and the button reads Apply (1). Tapping it
changed nothing and said nothing.

It now raises voiceNothingExtracted through the panel's existing toast, unless a
due date landed — a due-date-only dictation did do something and must stay quiet.

Found by /code-review.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:00:45 +08:00
beba7bb4d4 docs(voice): record the blank-line fix and the decision to leave lint red
Amin's call: the repo-wide lint gate stays red. Both commands fail identically
on origin/master and no error is in a file this branch touched. The repair means
restructuring auth, realtime and toast effects with no component tests to catch
a regression, so it is its own attended task.

Notes the consequence: the Stop guard blocks on this ledger and every future
/orchestrate here inherits the same red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:00:45 +08:00
0584b79472 fix(voice): never append a blank line from a dictation that built none
Found by the /orchestrate correctness critic, verified by hand.

applyVoice checked isBlankLine on the TARGET line but never on the line it had
just built. A dictation carrying no line content — a due date on its own, or one
whose codes were all refused — returned a blank newLine(), fell past the
blank-target branch and appended it. The panel then made it active and autosaved
it, and start only requires that SOME line carries jobs (cases.service.ts:549),
so the empty line shipped to the lab floor. That is what decision 9 exists to
prevent; the decision only covered filling a blank target, not appending one.

The spec's own manual step 7 triggers it: dictate «تا پنجشنبه» with line 1
already filled.

buildLabLineFromVoice now returns line: null for a blank line, so the rule sits
in the pure function a test can reach rather than in a component nothing renders.
The due date still lands — it belongs to the case header, not the line.

Six tests that asserted an empty line now assert null, and one new test covers a
due date riding along with real work. Reverting the guard fails five of them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:00:45 +08:00
d557d92669 feat(voice): extend voice extraction to lab case line entry
Adds a lab-mode narrowing of the catalog for voice extraction,
lab case line draft/apply helpers, and a shared review sheet reused
by both treatment and lab case flows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 13:00:45 +08:00
54044e44e6 docs(voice): add the lab-case-entry progress ledger
Every /orchestrate stop path writes here, and preflight aborts without it.
Records the two preflight blockers: no merge request template, and the repo
being on Gitea while /orchestrate ends in GitLab-shaped merge requests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:00:01 +08:00
6bfa5ade78 docs(voice): spec voice entry for a lab case line
One dictation fills one case line — teeth, prosthesis stack, comment — plus the
case due date. The header's identity fields stay typed, which is what keeps every
extracted field free of a patient name and leaves the transcript decision in
voice-treatment-entry §10 closed.

Lab mode is an empty treatmentTypes and labs catalog, not a second prompt. The
prompt already renders both as empty, so the model cannot emit a field it has no
list for and no prompt text changes.

Four findings from reading the code shaped it:

- voice.controller.ts:22 puts ClinicOrgGuard on the whole controller, so a LAB
  org gets 403 on both voice routes today.
- listLinkedLabs (voice.service.ts:272) does not filter by org type. For a LAB
  org it returns the linked CLINICS, and the prompt labels them "LABS THIS CLINIC
  CAN SEND TO". Emptying the list is what stops a referring clinic coming back as
  labId.
- The lab write validates only the prosthesis code (cases.service.ts:481) because
  the line and its jobs arrive in one transaction. Nothing rejects a teeth/jobs
  mismatch, so the apply keeps decision 40 itself.
- TAB_TREATMENT_EDIT is clinic-only (organization-type.ts:14), so reusing it for
  the lab side would 403 every lab member including the owner. TAB_CASES_EDIT is
  the one that already gates Add Case.

Mode is derived from the org type, never sent by the client. The save model needs
no refs: CaseCreatePanel autosaves one PUT carrying header, lines and jobs
together, so the ref coupling behind three of the five clinic defects cannot
occur here.

14 decisions and a verification list in §10. No code yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:00:01 +08:00
48 changed files with 2689 additions and 247 deletions

View File

@@ -1,15 +1,16 @@
---
description: Lab Cases tab — prosthesis filter, auto-select, list cards, Case Sheet PDF
globs: frontend/src/components/ui/lab/CasesPage.tsx,frontend/src/components/ui/lab/CaseDetailPanel.tsx,frontend/src/components/ui/lab/LabCaseProsthesisGroupsList.tsx,frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx,frontend/src/components/ui/lab/ProsthesisStackedTypeLabel.tsx,frontend/src/components/ui/lab/LabCaseShareQr*.tsx,frontend/src/components/ui/lab/CaseSheet*.tsx,frontend/src/components/lab/caseSheetPdf.ts,frontend/src/components/lab/caseDetailUtils.ts,frontend/src/components/treatment/prosthesisJobPath.ts,backend/src/modules/cases/**,backend/src/common/lab-case-listed-at.ts
globs: frontend/src/components/ui/lab/CasesPage.tsx,frontend/src/components/ui/lab/CaseDetailPanel.tsx,frontend/src/components/ui/lab/CaseCreatePanel.tsx,frontend/src/components/ui/lab/CaseHistoryRounds.tsx,frontend/src/components/ui/lab/LabCaseProsthesisGroupsList.tsx,frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx,frontend/src/components/ui/lab/ProsthesisStackedTypeLabel.tsx,frontend/src/components/ui/lab/LabCaseShareQr*.tsx,frontend/src/components/ui/lab/CaseSheet*.tsx,frontend/src/components/lab/caseSheetPdf.ts,frontend/src/components/lab/caseDetailUtils.ts,frontend/src/components/treatment/prosthesisJobPath.ts,backend/src/modules/cases/**,backend/src/common/lab-case-listed-at.ts
alwaysApply: false
---
# Lab Cases
- **Filter by prosthesis**, not treatment type — `prosthesisTypeCode`; matches cases with **any task** of that type.
- **Filter by prosthesis**, not treatment type — `prosthesisTypeCode`; matches cases with **any current-round task** of that type (or a live prosthesis line).
- **Auto-select** newest case on tab open; right panel never empty when list has items; `?caseId=` deep link overrides.
- **List cards:** `LabCaseProsthesisGroupsList` (catalog color + teeth); same component as Treatment shipments rail; no patient mobile on card. Same-type teeth in one detail share a group; extra type on some teeth is its own group. Job/task lines are `ProsthesisJobLineLabel` everywhere (Treatment dispatch, Cases cards/detail/sheet, Tasks): `13 · Pontic - 14 · PFZ Crown`. No picker category. Colored Pontic + leaf (`prosthesisTypeLabelStyleFromCatalog`; print hex). Inherit the parent font size. Indirect keeps subcategory + leaf (Inlay · Layered ceramic). Join with `PROSTHESIS_JOB_PATH_SEP`.
- **Assignment** in detail only (`TAB_CASES_EDIT`); task status changes on Tasks tab.
- **Assignment** in detail only (`TAB_CASES_EDIT`). Completing a step stays on Tasks. Reopening a completed current-round step is Cases only (`PATCH /cases/:id/tasks/:taskId/reopen`); it removes that step’s commission. Tasks and the share link show a completed step as a badge.
- **Stop** (`POST /cases/:id/stop`, `TAB_CASES_EDIT`): started lab-origin cases only. Completed steps and the prosthesis plan become a history round; in-progress steps are removed. `startedAt` clears so the case returns to the drafts rail and can be edited, then started again. History steps are read-only. Clinic-sent cases and unstarted drafts cannot be stopped.
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Case Sheet PDF:** client A4 via `jspdf` + `html2canvas`; wrap the off-screen print tree in `NextIntlClientProvider` (job labels use `useTranslations`). Print layout must stay **hex-only** (Tailwind `lab()`/`oklch` breaks capture). Optional `externalCode` replaces PDF order number when set.
- **Detail chrome:** Important Case checkbox (`labelPosition="start"`) then external-code input (no field title; placeholder only).

View File

@@ -7,16 +7,17 @@ alwaysApply: false
# Lab Tasks
- **Default sort:** same as Cases — `labCaseTaskListedAtOrder` / `listedAt` desc (`COALESCE(startedAt, sentAt)`); `stepOrder` asc within prosthesis group. Do not sort `startedAt` then `sentAt`. `GET /tasks/locate-page` uses `listedAt` too. `sortBy=dueDate` tiebreaker is `listedAt` desc.
- **Grouping:** only when `sortBy=date`; flat list + hint for other sorts. Same prosthesis type in one detail is one pipeline (Connected badge only for a real bridge); `partial_denture` is one pipeline for all selected teeth.
- **Grouping:** only when `sortBy=date`; flat list + hint for other sorts. Teeth in one line with the same prosthesis-type set share a pipeline. A stacked tooth is its own set; steps shared by two or more types in that set are one combined section after the single-type sections. Connected badge only for a real bridge.
- **Prosthesis colors:** family pastels via `prosthesisTypeColorFromCatalog`. Job/task lines are `ProsthesisJobLineLabel` (same as Treatment/Cases): `13 · Pontic - 14 · PFZ Crown`, no category, colored Pontic + leaf, inherit font size, print hex. Indirect keeps subcategory + leaf. Joins use `PROSTHESIS_JOB_PATH_SEP`. No type pills, never row index.
- **Important first:** `pinImportant=true` (sort pin, not filter).
- **Task assignment:** assign in Cases (`TAB_CASES_EDIT`); status edit on Tasks only for assignee or unassigned tasks; others see “Assigned to {name}”.
- **Task assignment:** assign in Cases (`TAB_CASES_EDIT`). Status edit on Tasks only for an in-progress task that is unassigned or assigned to you; a completed step is a badge. Reopening that step is Cases edit only. Others see “Assigned to {name}”.
- **Grouped comments:** when `sortBy=date`, one comments icon on **case header** (not per row); flat sort keeps per-row comments.
- **Share link page** (`/lab-case/[token]`): reuses `TaskRow` + assignee rules; comments via token API — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Case due dates:** clinic sets in Treatment lab dispatch; lab sees on Cases/Tasks; `overdue` filter + `sortBy=dueDate` on Tasks.
- **Mobile UX:** `LAB_TASK_STATUS_SELECT_CLASS` (44px tap target on small screens); `TaskCaseGroupHeader` sticky while scrolling grouped tasks; filter selects use same touch sizing on Tasks.
- **Show in case:** `GET /tasks/locate-page` finds page in full list; highlight + scroll.
- **Today deep links:** `parseTasksSearchParams` + `prosthesisTypeCode` / `unassignedOnly` / `overdueOnly` query params on Tasks.
- **Case-level steps (new cases only):** `intraoral_scan`, then job rows, then `packing` and `shipping`. Stored as `LabCaseTask` with `__case__`. Existing cases keep those steps on each row; scan completion still fans out across that case’s scan tasks. `CASE_COMPLETED` includes the case-level tasks.
- **Inbox / tab badges:** completing a step writes timeline `TASK_COMPLETED` only; inbox + Tasks/Treatment badges fire on `CASE_COMPLETED` when no in-progress tasks remain.
Full map: `.cursor/skills/lab-tasks/SKILL.md`

View File

@@ -16,7 +16,7 @@ description: Lab Cases tab — list, filters, detail panel, assignment, share QR
- **Task group headers / list cards / Case Sheet:** one mill-ticket line via [`ProsthesisJobLineLabel`](frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx) — `13 · Pontic - 14 · PFZ Crown`. No picker category. Colored Pontic + leaf (`prosthesisTypeLabelStyleFromCatalog`; print hex). Inherit the parent font size. Indirect keeps subcategory + leaf (Inlay · Layered ceramic). FDI chart paints pontic color on those teeth.
- **Page size:** `PAGE_SIZE = 10` in `CasesPage.tsx`.
- **Auto-select:** On tab open / after filter reload, select first list item if none selected; keep selection when still in list; `?caseId=` URL wins.
- **Add case:** `TAB_CASES_EDIT` — `POST /cases` then replace the **right pane** with `CaseCreatePanel` (inline wizard, not a modal). Prosthesis-only lines, `ProsthesisAssignChart` (same picker/stacking as Treatment). Summary rows: `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same mill-ticket line as Treatment/Cases/Tasks). Header: referring clinic/dentist, patient name/mobile, optional ACTIVE partner clinic, due date (`AppDateInput`). **Start** (`POST /cases/:id/start`) generates tasks; no `LabCaseSend`, no clinic inbox/`CASE_SENT`. Start also rejects illegal stacks (`PROSTHESIS_STACK_INVALID`) and un-bridged or mixed pontics (`PONTIC_BRIDGE_INVALID`). **Delete** (`DELETE /cases/:id`) only for unstarted lab-origin drafts (`LAB_INTERNAL` && `!startedAt`); confirm in the create-panel header next to Start. Received clinic cases and started generated cases cannot be deleted.
- **Add case:** `TAB_CASES_EDIT` — `POST /cases` then replace the **right pane** with `CaseCreatePanel` (inline wizard, not a modal). Prosthesis-only lines, `ProsthesisAssignChart` (same picker/stacking as Treatment). Summary rows: `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same mill-ticket line as Treatment/Cases/Tasks). Header: referring clinic/dentist, patient name/mobile, optional ACTIVE partner clinic, due date (`AppDateInput`). **Start** (`POST /cases/:id/start`) generates tasks; no `LabCaseSend`, no clinic inbox/`CASE_SENT`. Start also rejects illegal stacks (`PROSTHESIS_STACK_INVALID`) and un-bridged or mixed pontics (`PONTIC_BRIDGE_INVALID`). **Stop** (`POST /cases/:id/stop`) is only a started lab-origin case: completed tasks and a copy of the prosthesis lines go on `LabCaseRound` (`roundId` set; in-progress tasks are deleted), `startedAt` clears, commissions and the stamped price stay. The case returns to the drafts rail and can be edited; the next **Start** generates only the new round (`generateLabCaseTasks` ignores tasks that already have `roundId`). Active lists, progress, and Today counts use `roundId` null. Case detail and the draft editor show past rounds under **Previous work** (plan, then completed steps only). **Delete** (`DELETE /cases/:id`) only for unstarted lab-origin drafts (`LAB_INTERNAL` && `!startedAt`); confirm in the create-panel header next to Start. Received clinic cases and started generated cases cannot be deleted.
- **Right panel:** Draft lab-origin → wizard; started/received → `CaseDetailPanel`.
- **Left rail layout:** section is `flex flex-col` + `lg:min-h-[420px]` / `h-full` with `lg:items-stretch` on the grid; case list wrapper is `flex-1 min-h-0 overflow-y-auto` (do **not** use a fixed `max-h-[55vh]` — that leaves empty space above pagination).
@@ -42,7 +42,8 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
## Detail panel
- Task assignment: `PATCH /cases/:caseId/tasks/:taskId/assign` (`TAB_CASES_EDIT`)
- Task assignment: `PATCH /cases/:caseId/tasks/:taskId/assign` (`TAB_CASES_EDIT`). Current-round tasks only.
- Reopen: `PATCH /cases/:id/tasks/:taskId/reopen` (`TAB_CASES_EDIT`) sets a completed current-round task back to `IN_PROGRESS` and revokes that step’s commission. In-progress steps on the case stay a badge (Cases cannot complete a step). `PATCH /tasks/:id` rejects uncomplete with `TASK_REOPEN_REQUIRES_CASE_EDIT`. History tasks (`roundId` set) cannot be reopened or assigned.
- Comments: shared `LabCaseCommentsPanel` + `tasksApi` comment routes (`viewerSide="LAB"`). Newest-first; sent/received use logical start/end alignment (RTL-safe). Compact `h-9` composer with primary send + visibility controls. Lab-origin cases (`LAB_INTERNAL`, including after Start) are visible to lab comments/mark-read — do not require `sentAt` / `LabCaseSend`. Generated cases hide clinic-visibility controls (`clinicVisibility={false}`) — there is no clinic inbox.
- Mark read: `POST /notifications/mark-case-read` on select (Cases tab badge)
- FDI chart (`CaseToothChartPanel`): prosthesis colors + **connected bridge dots** from `selectionGroupId` (`buildCaseConnectedTeeth` / `buildCaseProsthesisRows` in `caseDetailUtils.ts`).

View File

@@ -22,7 +22,7 @@ Other sorts use flat list on the frontend; `stepOrder asc` is still a tiebreaker
## Case grouping (frontend)
- **`sortBy === 'date'`** → grouped view via [`taskListGrouping.ts`](frontend/src/components/lab/taskListGrouping.ts): case header → prosthesis sub-header (one per type pipeline: all teeth of that type in the detail, or a connected crown+pontic span) → task rows (`treatmentDetailId:teeth:prosthesisTypeCode`). Headers use `ProsthesisJobLineLabel` (`13 · Pontic - 14 · PFZ Crown`).
- **`sortBy === 'date'`** → grouped view via [`taskListGrouping.ts`](frontend/src/components/lab/taskListGrouping.ts): case header → case-level scan (new cases, `__case__`) → prosthesis sub-header → task rows → a tinted break, then case-level packing and shipping (not another row of the job). Teeth in one line that share the **same set of prosthesis types** share pipelines. A tooth with an extra type is its own set. Steps that two or more types in that set share are one combined section (`pfz_crown+ti_base_abutment`) after the single-type sections. Headers use `ProsthesisJobLineLabel`. Older cases still show scan/pack/ship inside each prosthesis group.
- **Other sorts** → flat list; show muted hint (`groupingOff*` i18n keys). Each row keeps clinic/patient plus the same mill-ticket line (`ProsthesisJobLineLabel`).
Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
@@ -53,7 +53,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
**Task assignment:** Managed in **Cases** (`TAB_CASES_EDIT`), not on Tasks tab. `PATCH /cases/:caseId/tasks/:taskId/assign`; assignable staff via `GET /cases/assignable-staff` (members with `TAB_TASKS_EDIT`, including participating owner). Case detail task row: step label, status badge, assign dropdown, and last-updated line on one compact row.
**Tasks visibility & status edit:** All tasks remain visible to every user with task access (no hiding assigned tasks). **Unassigned** tasks or tasks **assigned to you** → status dropdown when `TAB_TASKS_EDIT`. **Assigned to someone else** → read-only “Assigned to {name}” badge instead of the dropdown (backend rejects status PATCH). Same rules on **lab case share link** page (`CaseTasksFocusView` + `canEditLabTaskStatus`). Managers assign/monitor in Cases.
**Tasks visibility & status edit:** All current-round tasks remain visible to every user with task access (no hiding assigned tasks; `roundId` null only — stopped-round tasks are history on the case). **Unassigned** in-progress tasks or in-progress tasks **assigned to you** → status dropdown when `TAB_TASKS_EDIT`. **Completed** steps are a badge on Tasks and the share link. **Assigned to someone else** → read-only “Assigned to {name}” badge instead of the dropdown (backend rejects status PATCH). Same rules on **lab case share link** page (`CaseTasksFocusView` + `canEditLabTaskStatus`). Setting a completed step back to in progress is **Cases** edit only.
**Step completed filter:** Restricts to prosthesis groups `(labCaseId, treatmentDetailId, prosthesisTypeCode)` where that `workflowStepCode` task is `COMPLETED`. Combined with `status=IN_PROGRESS`, returns only in-progress tasks in those groups (completed step row hidden).
@@ -69,7 +69,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
## APIs
- `GET /tasks` — paginated flat task list (grouping is client-side when `sortBy=date`)
- `PATCH /tasks/:taskId` — update status (only assignee or unassigned task). Completing **`intraoral_scan`** also completes every other `intraoral_scan` task in the same case (case-scoped; catalog first step for all prosthesis types).
- `PATCH /tasks/:taskId` — update status (only assignee or unassigned task, and only while `IN_PROGRESS`). Completed steps cannot be reopened here. **New cases** store one `intraoral_scan`, one `packing`, and one `shipping` task with `sourceKey` / `prosthesisTypeCode` `__case__` (row pipelines omit them; `smile_design` still skips pack/ship). **Existing cases** keep per-row copies; completing one `intraoral_scan` still completes the other current-round scan tasks in that case. Lists ignore tasks with `roundId` set.
- `GET /tasks/filter-options` — clinics + workflow steps (localized)
- `GET /tasks/locate-page` — page number for a task in the sorted filtered list (date sort position is `listedAt`, not separate `sentAt`/`startedAt` compares)
- `GET /cases/assignable-staff` — staff eligible for task assignment

View File

@@ -70,9 +70,9 @@ frontend/src/
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Partner list is a **shared** ledger (both orgs see both sides’ rows; always `CONFIRMED`). Money inputs: `AppMoneyInput`. **This publish:** Billing is hidden for CLINIC via `hidden-tabs.ts` (`billingOrgTypes: ['CLINIC']`). See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Lab Tasks tab:** Newest case first (same `listedAt` as Cases); steps ordered 1→N; case grouping when sorted by date; `stepCompleted` filter; filter by case source (`origin`: received vs generated); prosthesis colors from catalog; job titles use `ProsthesisJobLineLabel` (`13 · Pontic - 14 · PFZ Crown`, subcategory/leaf only, same coloring everywhere, inherit font size); task assignment in **Cases** (compact row: status + assignee + last update); on **Tasks**, all staff see every task but only assignee (or unassigned pool) can change status — others see “Assigned to {name}” instead of the status dropdown; **case due dates** set/edited in clinic Treatment lab dispatch, shown on lab Cases/Tasks with overdue filter + sort; completing **`intraoral_scan`** completes every scan task in that case (case-scoped; catalog first step for all prosthesis types); **mobile:** larger task status controls, sticky case header when grouped; **tab badges / inbox:** Tasks + Treatment badges and the header bell increment on **`CASE_COMPLETED`** (all tasks in the case done), not each step — the case timeline still lists `TASK_COMPLETED` per step; live via inbox Socket.IO → `notifyTabBadgesChanged()` + soft list refresh — see `.cursor/skills/lab-tasks/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`, `.cursor/skills/notifications-inbox/SKILL.md`.
**Lab Tasks tab:** Newest case first (same `listedAt` as Cases); steps ordered 1→N; case grouping when sorted by date; `stepCompleted` filter; filter by case source (`origin`: received vs generated); prosthesis colors from catalog; job titles use `ProsthesisJobLineLabel` (`13 · Pontic - 14 · PFZ Crown`, subcategory/leaf only, same coloring everywhere, inherit font size); task assignment in **Cases** (compact row: status + assignee + last update); on **Tasks**, all staff see every task but only assignee (or unassigned pool) can change status — others see “Assigned to {name}” instead of the status dropdown; a completed step is a badge (reopen is Cases edit only); **case due dates** set/edited in clinic Treatment lab dispatch, shown on lab Cases/Tasks with overdue filter + sort; completing **`intraoral_scan`** completes every scan task in that case (case-scoped; catalog first step for all prosthesis types); **mobile:** larger task status controls, sticky case header when grouped; **tab badges / inbox:** Tasks + Treatment badges and the header bell increment on **`CASE_COMPLETED`** (all tasks in the case done), not each step — the case timeline still lists `TASK_COMPLETED` per step; live via inbox Socket.IO → `notifyTabBadgesChanged()` + soft list refresh — see `.cursor/skills/lab-tasks/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`, `.cursor/skills/notifications-inbox/SKILL.md`.
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **Received** / **Generated** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** client A4 (`jspdf`/`html2canvas`); wrap print tree in `NextIntlClientProvider`; hex-only print layout; optional `externalCode` replaces order number. Lab-origin Start has no clinic send; comments use Cases **or** Tasks permission (no clinic-visibility toggle). Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **Received** / **Generated** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** client A4 (`jspdf`/`html2canvas`); wrap print tree in `NextIntlClientProvider`; hex-only print layout; optional `externalCode` replaces order number. Lab-origin Start has no clinic send; comments use Cases **or** Tasks permission (no clinic-visibility toggle). Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Stop** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Lab case share link (quick ref):**
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login.

View File

@@ -55,19 +55,23 @@ export const LAB_WORKFLOW_STEPS = [
{ code: 'intraoral_scan', sortOrder: 1 },
{ code: 'choosing_abutment', sortOrder: 2 },
{ code: 'design', sortOrder: 3 },
{ code: 'model_create', sortOrder: 4 },
{ code: 'milling_dry', sortOrder: 5 },
{ code: 'milling_wet', sortOrder: 6 },
{ code: 'printer_resin', sortOrder: 7 },
{ code: 'printer_metal', sortOrder: 8 },
{ code: 'pressing', sortOrder: 9 },
{ code: 'sinter', sortOrder: 10 },
{ code: 'build_up', sortOrder: 11 },
{ code: 'stain', sortOrder: 12 },
{ code: 'glaze', sortOrder: 13 },
{ code: 'polish_prep', sortOrder: 14 },
{ code: 'packing', sortOrder: 15 },
{ code: 'shipping', sortOrder: 16 },
{ code: 'design_customized_abutment', sortOrder: 4 },
{ code: 'model_design', sortOrder: 5 },
{ code: 'model_create', sortOrder: 6 },
{ code: 'milling_dry', sortOrder: 7 },
{ code: 'milling_wet', sortOrder: 8 },
{ code: 'printer_resin', sortOrder: 9 },
{ code: 'printer_metal', sortOrder: 10 },
{ code: 'pressing', sortOrder: 11 },
{ code: 'sinter', sortOrder: 12 },
{ code: 'build_up', sortOrder: 13 },
{ code: 'build_up_crown', sortOrder: 14 },
{ code: 'build_up_laminate', sortOrder: 15 },
{ code: 'stain', sortOrder: 16 },
{ code: 'glaze', sortOrder: 17 },
{ code: 'polish_prep', sortOrder: 18 },
{ code: 'packing', sortOrder: 19 },
{ code: 'shipping', sortOrder: 20 },
] as const;
export type ProsthesisChartRegion = 'crown' | 'root' | 'arch';
@@ -90,7 +94,18 @@ export type ProsthesisTypeSeed = {
manufacturingSteps: readonly string[];
};
const SCAN_DESIGN_MODEL = ['intraoral_scan', 'design', 'model_create'] as const;
const SCAN_DESIGN_MODEL = [
'intraoral_scan',
'design',
'model_design',
'model_create',
] as const;
const SCAN_CUSTOM_ABUTMENT_MODEL = [
'intraoral_scan',
'design_customized_abutment',
'model_design',
'model_create',
] as const;
const INDIRECT_FULL = [
...SCAN_DESIGN_MODEL,
'milling_wet',
@@ -102,7 +117,7 @@ const INDIRECT_LAYERED = [
...SCAN_DESIGN_MODEL,
'milling_wet',
'sinter',
'build_up',
'build_up_laminate',
'stain',
'glaze',
] as const;
@@ -200,7 +215,7 @@ export const PROSTHESIS_TYPES: ProsthesisTypeSeed[] = [
...SCAN_DESIGN_MODEL,
'milling_wet',
'sinter',
'build_up',
'build_up_crown',
'stain',
'glaze',
]),
@@ -208,7 +223,7 @@ export const PROSTHESIS_TYPES: ProsthesisTypeSeed[] = [
...SCAN_DESIGN_MODEL,
'milling_dry',
'sinter',
'build_up',
'build_up_crown',
'stain',
'glaze',
]),
@@ -289,34 +304,37 @@ export const PROSTHESIS_TYPES: ProsthesisTypeSeed[] = [
implant('prefabricated_abutment', 40, [
'intraoral_scan',
'choosing_abutment',
'model_design',
'model_create',
'polish_prep',
]),
implant('ti_base_abutment', 41, [
'intraoral_scan',
'model_design',
'model_create',
'polish_prep',
]),
implant('multi_unit_abutment', 42, [
'intraoral_scan',
'choosing_abutment',
'model_design',
'model_create',
'polish_prep',
]),
implant('customized_abutment', 43, [
...SCAN_DESIGN_MODEL,
...SCAN_CUSTOM_ABUTMENT_MODEL,
'milling_wet',
'polish_prep',
]),
implant('zirconia_abutment', 44, [
...SCAN_DESIGN_MODEL,
...SCAN_CUSTOM_ABUTMENT_MODEL,
'milling_dry',
'sinter',
]),
implant(
'screw_retained',
45,
[...SCAN_DESIGN_MODEL, 'milling_wet', 'polish_prep'],
[...SCAN_CUSTOM_ABUTMENT_MODEL, 'milling_wet', 'polish_prep'],
{ chartRegion: 'crown' },
),
{
@@ -417,7 +435,7 @@ export const PROSTHESIS_TYPES: ProsthesisTypeSeed[] = [
category: 'digital',
chartRegion: 'arch',
stackGroup: 'arch',
manufacturingSteps: ['intraoral_scan', 'design', 'model_create'],
manufacturingSteps: ['intraoral_scan', 'design', 'model_design', 'model_create'],
},
// Legacy leaves — labels for historical cases; hidden from the picker.
{
@@ -658,17 +676,17 @@ export const PROSTHESIS_LABELS: Record<string, Record<string, string>> = {
night_guard_soft: {
en: 'Night Guard · Soft',
fa: 'نایت گارد · نرم',
nl: 'Nachtbeugel · Zacht',
nl: 'Knarsplaat · Zacht',
},
night_guard_hard: {
en: 'Night Guard · Hard',
fa: 'نایت گارد · سخت',
nl: 'Nachtbeugel · Hard',
nl: 'Knarsplaat · Hard',
},
night_guard_dual: {
en: 'Night Guard · Dual laminate',
fa: 'نایت گارد · دو لایه',
nl: 'Nachtbeugel · Dual laminate',
nl: 'Knarsplaat · Dual laminate',
},
bleaching_tray: { en: 'Bleaching Tray', fa: 'تری بلیچینگ', nl: 'Bleeklepel' },
clear_aligner: {
@@ -714,28 +732,44 @@ export const PROSTHESIS_LABELS: Record<string, Record<string, string>> = {
export const WORKFLOW_STEP_LABELS: Record<string, Record<string, string>> = {
intraoral_scan: {
en: 'Intraoral Scan',
fa: 'اسکن داخل دهان',
fa: 'اسکن داخل دهانی',
nl: 'Intraorale Scan',
},
choosing_abutment: {
en: 'Choosing Abutment',
en: 'Abutment selection',
fa: 'انتخاب اباتمنت',
nl: 'Abutment kiezen',
},
design: { en: 'Design', fa: 'طراحی', nl: 'Ontwerp' },
model_create: { en: 'Model Create', fa: 'ساخت مدل', nl: 'Model maken' },
milling_dry: { en: 'Milling Dry', fa: 'فرز خشک', nl: 'Droog Frezen' },
milling_wet: { en: 'Milling Wet', fa: 'فرز تر', nl: 'Nat Frezen' },
printer_resin: { en: 'Printer Resin', fa: 'پرینتر رزین', nl: 'Harsprinter' },
printer_metal: { en: 'Printer Metal', fa: 'پرینتر فلز', nl: 'Metaalprinter' },
sinter: { en: 'Sinter', fa: 'سینتر', nl: 'Sinteren' },
design_customized_abutment: {
en: 'Design (custom abutment)',
fa: 'طراحی (اباتمنت سفارشی)',
nl: 'Ontwerp (aangepast abutment)',
},
model_design: { en: 'Model design', fa: 'طراحی مدل', nl: 'Modelontwerp' },
model_create: { en: 'Model creation', fa: 'ساخت مدل', nl: 'Model maken' },
milling_dry: { en: 'Dry milling', fa: 'میلینگ خشک', nl: 'Droogfrezen' },
milling_wet: { en: 'Wet milling', fa: 'میلینگ تر', nl: 'Natfrezen' },
printer_resin: { en: 'Resin printing', fa: 'پرینت رزین', nl: 'Harsprinten' },
printer_metal: { en: 'Metal printing', fa: 'پرینت فلز', nl: 'Metaalprinten' },
sinter: { en: 'Sintering', fa: 'سینترینگ', nl: 'Sinteren' },
build_up: { en: 'Build Up', fa: 'بیلدآپ', nl: 'Opbouw' },
stain: { en: 'Stain', fa: 'رنگ‌آمیزی', nl: 'Kleuren' },
build_up_crown: {
en: 'Build-up (crown)',
fa: 'بیلداپ (روکش)',
nl: 'Opbouw (kroon)',
},
build_up_laminate: {
en: 'Build-up (laminate)',
fa: 'بیلداپ (لمینت)',
nl: 'Opbouw (laminaat)',
},
stain: { en: 'Stain', fa: 'استین', nl: 'Kleuren' },
glaze: { en: 'Glaze', fa: 'گلیز', nl: 'Glazuur' },
polish_prep: {
en: 'Prep/Polish',
fa: 'آماده‌سازی/پولیش',
nl: 'Voorbereiding/Polijsten',
en: 'Polish',
fa: 'پولیش',
nl: 'Polijsten',
},
packing: { en: 'Packing', fa: 'بسته‌بندی', nl: 'Verpakken' },
shipping: { en: 'Shipping', fa: 'ارسال', nl: 'Verzending' },
@@ -775,7 +809,7 @@ export const PROSTHESIS_CATEGORY_LABELS: Record<
implant: { en: 'Implants', fa: 'ایمپلنت', nl: 'Implantaten' },
post_core: { en: 'Post & core', fa: 'پست و کور', nl: 'Stiftopbouw' },
removable: { en: 'Removable', fa: 'متحرک', nl: 'Uitneembaar' },
appliance: { en: 'Appliances', fa: 'اپلاینس‌ها', nl: 'Apparatuur' },
appliance: { en: 'Appliances', fa: 'اپلاینس', nl: 'Apparatuur' },
digital: { en: 'Digital', fa: 'دیجیتال', nl: 'Digitaal' },
pontic: { en: 'Pontic', fa: 'پونتیک', nl: 'Pontic' },
};
@@ -792,7 +826,7 @@ export const PROSTHESIS_SUBCATEGORY_LABELS: Record<
inlay: { en: 'Inlay', fa: 'اینلی', nl: 'Inlay' },
onlay: { en: 'Onlay', fa: 'آنلی', nl: 'Onlay' },
overlay: { en: 'Overlay', fa: 'اورلی', nl: 'Overlay' },
night_guard: { en: 'Night guard', fa: 'نایت گارد', nl: 'Nachtbeugel' },
night_guard: { en: 'Night guard', fa: 'نایت گارد', nl: 'Knarsplaat' },
};
export const CATALOG_TRANSLATIONS: CatalogTranslationSeed[] = [

View File

@@ -0,0 +1,28 @@
-- Stopped lab-origin rounds keep the prosthesis plan and tasks as history.
CREATE TABLE "lab_case_rounds" (
"id" TEXT NOT NULL,
"labCaseId" TEXT NOT NULL,
"stoppedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "lab_case_rounds_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "lab_case_round_lines" (
"id" TEXT NOT NULL,
"roundId" TEXT NOT NULL,
"tooth" TEXT NOT NULL,
"prosthesisTypeCode" TEXT NOT NULL,
"selectionGroupId" TEXT NOT NULL DEFAULT '',
CONSTRAINT "lab_case_round_lines_pkey" PRIMARY KEY ("id")
);
ALTER TABLE "lab_case_tasks" ADD COLUMN "roundId" TEXT;
CREATE INDEX "lab_case_rounds_labCaseId_stoppedAt_idx" ON "lab_case_rounds"("labCaseId", "stoppedAt");
CREATE INDEX "lab_case_round_lines_roundId_idx" ON "lab_case_round_lines"("roundId");
CREATE INDEX "lab_case_tasks_roundId_idx" ON "lab_case_tasks"("roundId");
ALTER TABLE "lab_case_rounds" ADD CONSTRAINT "lab_case_rounds_labCaseId_fkey" FOREIGN KEY ("labCaseId") REFERENCES "lab_cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "lab_case_round_lines" ADD CONSTRAINT "lab_case_round_lines_roundId_fkey" FOREIGN KEY ("roundId") REFERENCES "lab_case_rounds"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "lab_case_tasks" ADD CONSTRAINT "lab_case_tasks_roundId_fkey" FOREIGN KEY ("roundId") REFERENCES "lab_case_rounds"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -0,0 +1,13 @@
-- History tasks share the case key with a later round. Include roundId so Start can insert the new round.
-- PostgreSQL treats NULL roundId as distinct, so the current round keeps its own partial unique index.
DELETE FROM "lab_case_tasks" WHERE "roundId" IS NOT NULL AND "status" = 'IN_PROGRESS';
ALTER TABLE "lab_case_tasks" DROP CONSTRAINT IF EXISTS "lab_case_tasks_case_source_tooth_prosthesis_step_key";
DROP INDEX IF EXISTS "lab_case_tasks_case_source_tooth_prosthesis_step_key";
CREATE UNIQUE INDEX "lab_case_tasks_case_source_tooth_prosthesis_step_round_key"
ON "lab_case_tasks"("labCaseId", "sourceKey", "tooth", "prosthesisTypeCode", "stepOrder", "roundId");
CREATE UNIQUE INDEX "lab_case_tasks_current_round_key"
ON "lab_case_tasks"("labCaseId", "sourceKey", "tooth", "prosthesisTypeCode", "stepOrder")
WHERE "roundId" IS NULL;

View File

@@ -272,6 +272,7 @@ model LabCase {
lines LabCaseLine[]
sends LabCaseSend[]
tasks LabCaseTask[]
rounds LabCaseRound[]
toothProsthesis LabCaseToothProsthesis[]
comments LabCaseComment[]
attachments LabCaseAttachment[]
@@ -345,6 +346,33 @@ model LabCaseSend {
@@map("lab_case_sends")
}
/// Closed work round after a lab-origin case is stopped. Tasks and the prosthesis plan stay here.
model LabCaseRound {
id String @id @default(uuid())
labCaseId String
stoppedAt DateTime @default(now())
labCase LabCase @relation(fields: [labCaseId], references: [id], onDelete: Cascade)
lines LabCaseRoundLine[]
tasks LabCaseTask[]
@@index([labCaseId, stoppedAt])
@@map("lab_case_rounds")
}
model LabCaseRoundLine {
id String @id @default(uuid())
roundId String
tooth String
prosthesisTypeCode String
selectionGroupId String @default("")
round LabCaseRound @relation(fields: [roundId], references: [id], onDelete: Cascade)
@@index([roundId])
@@map("lab_case_round_lines")
}
model TreatmentType {
id String @id @default(uuid())
code String @unique
@@ -463,8 +491,11 @@ model LabCaseTask {
assignedAt DateTime?
lastStatusChangedByUserId String?
lastStatusChangedAt DateTime?
/// Set when the round is stopped. Null means the current started round.
roundId String?
labCase LabCase @relation(fields: [labCaseId], references: [id], onDelete: Cascade)
round LabCaseRound? @relation(fields: [roundId], references: [id], onDelete: SetNull)
detail TreatmentDetail? @relation(fields: [treatmentDetailId], references: [id], onDelete: Cascade)
line LabCaseLine? @relation(fields: [lineId], references: [id], onDelete: Cascade)
assignee User? @relation("LabCaseTaskAssignee", fields: [assigneeUserId], references: [id], onDelete: SetNull)
@@ -475,9 +506,12 @@ model LabCaseTask {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([labCaseId, sourceKey, tooth, prosthesisTypeCode, stepOrder], map: "lab_case_tasks_case_source_tooth_prosthesis_step_key")
/// History rows share this key with a later round, so roundId is part of it.
/// Current-round rows (roundId null) are also unique via partial index lab_case_tasks_current_round_key.
@@unique([labCaseId, sourceKey, tooth, prosthesisTypeCode, stepOrder, roundId], map: "lab_case_tasks_case_source_tooth_prosthesis_step_round_key")
@@index([labCaseId, status])
@@index([assigneeUserId])
@@index([roundId])
@@map("lab_case_tasks")
}

View File

@@ -165,6 +165,24 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
resource(prisma, 'LabCaseTask', {
navigation: { name: 'Lab', icon: 'Archive' },
}),
resource(prisma, 'LabCaseRound', {
navigation: { name: 'Lab', icon: 'Archive' },
actions: {
new: { isAccessible: false },
edit: { isAccessible: false },
delete: { isAccessible: false },
bulkDelete: { isAccessible: false },
},
}),
resource(prisma, 'LabCaseRoundLine', {
navigation: { name: 'Lab', icon: 'Archive' },
actions: {
new: { isAccessible: false },
edit: { isAccessible: false },
delete: { isAccessible: false },
bulkDelete: { isAccessible: false },
},
}),
resource(prisma, 'LabCaseTaskStatusEvent', {
navigation: { name: 'Lab', icon: 'Archive' },
}),

View File

@@ -41,6 +41,7 @@ export const ErrorCode = {
PERMISSION_ACCESS_TASKS: 'PERMISSION_ACCESS_TASKS',
PERMISSION_EDIT_TASKS: 'PERMISSION_EDIT_TASKS',
PERMISSION_ACCESS_CASES: 'PERMISSION_ACCESS_CASES',
PERMISSION_EDIT_CASES: 'PERMISSION_EDIT_CASES',
PERMISSION_ACCESS_BILLING: 'PERMISSION_ACCESS_BILLING',
PERMISSION_EDIT_BILLING: 'PERMISSION_EDIT_BILLING',
PERMISSION_ACCESS_STAFF: 'PERMISSION_ACCESS_STAFF',
@@ -176,9 +177,11 @@ export const ErrorCode = {
LAB_CASE_LINES_REQUIRED: 'LAB_CASE_LINES_REQUIRED',
LAB_CASE_START_INCOMPLETE: 'LAB_CASE_START_INCOMPLETE',
LAB_CASE_CLIENT_REQUIRED: 'LAB_CASE_CLIENT_REQUIRED',
LAB_CASE_STOP_NOT_ALLOWED: 'LAB_CASE_STOP_NOT_ALLOWED',
TASK_ASSIGNEE_INVALID: 'TASK_ASSIGNEE_INVALID',
TASK_ASSIGNED_TO_OTHER: 'TASK_ASSIGNED_TO_OTHER',
TASK_REOPEN_REQUIRES_CASE_EDIT: 'TASK_REOPEN_REQUIRES_CASE_EDIT',
TASK_PAGE_DATE_SORT_ONLY: 'TASK_PAGE_DATE_SORT_ONLY',
INVALID_SENT_FROM: 'INVALID_SENT_FROM',
INVALID_SENT_TO: 'INVALID_SENT_TO',

View File

@@ -4,9 +4,29 @@ const UNION_PINNED_PREFIX = [
'intraoral_scan',
'choosing_abutment',
'design',
'design_customized_abutment',
'model_design',
'model_create',
] as const;
/** One task per case for these steps. Row pipelines omit them on newly generated cases. */
export const CASE_LEVEL_STEP_CODES = ['intraoral_scan', 'packing', 'shipping'] as const;
export const CASE_TASK_SCOPE = '__case__';
const CASE_LEVEL_STEP_SET = new Set<string>(CASE_LEVEL_STEP_CODES);
export function isCaseLevelStepCode(code: string): boolean {
return CASE_LEVEL_STEP_SET.has(code);
}
export function isCaseLevelTask(task: {
sourceKey?: string | null;
prosthesisTypeCode?: string | null;
}): boolean {
return task.sourceKey === CASE_TASK_SCOPE || task.prosthesisTypeCode === CASE_TASK_SCOPE;
}
const UNION_SUFFIX = ['packing', 'shipping'] as const;
const UNION_PINNED = new Set<string>(UNION_PINNED_PREFIX);
@@ -21,9 +41,11 @@ const UNION_MIDDLE_ORDER: Record<string, number> = {
pressing: 5,
sinter: 6,
build_up: 7,
stain: 8,
glaze: 9,
polish_prep: 10,
build_up_crown: 8,
build_up_laminate: 9,
stain: 10,
glaze: 11,
polish_prep: 12,
};
/** Union stacked workflows: pin scan → abutment → design → model, then catalog order, pack/ship last. */
@@ -78,7 +100,7 @@ export function prosthesisTypeCaseWhere(code: string): Prisma.LabCaseWhereInput
return {
OR: [
{ toothProsthesis: { some: { prosthesisTypeCode: code } } },
{ tasks: { some: prosthesisTypeTaskWhere(code) } },
{ tasks: { some: { ...prosthesisTypeTaskWhere(code), roundId: null } } },
],
};
}

View File

@@ -774,6 +774,7 @@ export class BillingService {
const remaining = await db.labCaseTask.count({
where: {
labCaseId: task.labCaseId,
roundId: null,
workflowStepCode: INTRAORAL_SCAN_STEP,
status: 'COMPLETED',
id: { not: taskId },
@@ -783,6 +784,7 @@ export class BillingService {
const sibling = await db.labCaseTask.findFirst({
where: {
labCaseId: task.labCaseId,
roundId: null,
workflowStepCode: INTRAORAL_SCAN_STEP,
status: 'COMPLETED',
id: { not: taskId },

View File

@@ -93,6 +93,26 @@ export class CasesController {
return this.casesService.startInternal(id, organizationId, req.user.id, req.user.language);
}
@Post(':id/stop')
@ApiOperation({ summary: 'Stop a started lab-origin case and keep its work as history' })
stop(@Param('id') id: string, @Req() req) {
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
return this.casesService.stopInternal(id, organizationId, req.user.id, req.user.language);
}
@Patch(':id/tasks/:taskId/reopen')
@ApiOperation({ summary: 'Set a completed current-round task back to in progress' })
reopenTask(@Param('id') id: string, @Param('taskId') taskId: string, @Req() req) {
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
return this.casesService.reopenTask(
id,
taskId,
organizationId,
req.user.id,
req.user.language,
);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete an unstarted lab-origin draft (TAB_CASES_EDIT)' })
deleteDraft(@Param('id') id: string, @Req() req) {

View File

@@ -68,6 +68,7 @@ const labCaseListInclude = {
include: { organization: { select: { id: true, name: true } } },
},
tasks: {
where: { roundId: null },
orderBy: [
{ treatmentDetailId: 'asc' as const },
{ prosthesisTypeCode: 'asc' as const },
@@ -82,6 +83,16 @@ const labCaseListInclude = {
},
},
},
rounds: {
orderBy: [{ stoppedAt: 'desc' as const }],
include: {
lines: true,
tasks: {
where: { status: LabTaskStatus.COMPLETED },
orderBy: [{ prosthesisTypeCode: 'asc' as const }, { stepOrder: 'asc' as const }],
},
},
},
toothProsthesis: true,
attachments: {
include: {
@@ -155,6 +166,7 @@ export class CasesService {
},
partnerClinic: { select: { id: true, name: true } },
tasks: {
where: { roundId: null },
select: {
id: true,
status: true,
@@ -216,6 +228,7 @@ export class CasesService {
}),
this.prisma.labCaseTask.findMany({
where: {
roundId: null,
labCase: this.visibleStartedToLabWhere(labOrganizationId),
},
select: { prosthesisTypeCode: true },
@@ -279,6 +292,7 @@ export class CasesService {
},
},
tasks: {
where: { roundId: null },
select: {
id: true,
status: true,
@@ -659,6 +673,111 @@ export class CasesService {
return { success: true };
}
async stopInternal(
labCaseId: string,
labOrganizationId: string,
actorUserId: string,
localeInput?: string | null,
) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
const existing = await this.prisma.labCase.findFirst({
where: {
id: labCaseId,
origin: LabCaseOrigin.LAB_INTERNAL,
destinationOrganizationId: labOrganizationId,
},
include: { toothProsthesis: true },
});
if (!existing) {
throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
if (!existing.startedAt) {
throw new AppException(ErrorCode.LAB_CASE_STOP_NOT_ALLOWED, HttpStatus.CONFLICT);
}
await this.prisma.$transaction(async (tx) => {
const round = await tx.labCaseRound.create({
data: {
labCaseId,
lines: {
create: existing.toothProsthesis.map((row) => ({
tooth: row.tooth,
prosthesisTypeCode: row.prosthesisTypeCode,
selectionGroupId: row.selectionGroupId,
})),
},
},
});
await tx.labCaseTask.updateMany({
where: { labCaseId, roundId: null, status: LabTaskStatus.COMPLETED },
data: { roundId: round.id },
});
await tx.labCaseTask.deleteMany({
where: { labCaseId, roundId: null, status: LabTaskStatus.IN_PROGRESS },
});
await tx.labCase.update({
where: { id: labCaseId },
data: { startedAt: null },
});
});
const refreshed = await this.prisma.labCase.findFirstOrThrow({
where: { id: labCaseId },
include: labCaseListInclude,
});
return { success: true, data: await this.mapLabCaseDetail(refreshed, localeInput) };
}
async reopenTask(
labCaseId: string,
taskId: string,
labOrganizationId: string,
actorUserId: string,
localeInput?: string | null,
) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
const task = await this.prisma.labCaseTask.findFirst({
where: {
id: taskId,
labCaseId,
roundId: null,
labCase: { destinationOrganizationId: labOrganizationId },
},
});
if (!task) {
throw new AppException(ErrorCode.CASE_TASK_NOT_FOUND, HttpStatus.NOT_FOUND);
}
if (task.status !== LabTaskStatus.COMPLETED) {
throw new AppException(ErrorCode.LAB_CASE_NOT_EDITABLE, HttpStatus.CONFLICT);
}
await this.prisma.$transaction(async (tx) => {
await tx.labCaseTask.update({
where: { id: taskId },
data: {
status: LabTaskStatus.IN_PROGRESS,
lastStatusChangedByUserId: actorUserId,
lastStatusChangedAt: new Date(),
},
});
await tx.labCaseTaskStatusEvent.create({
data: {
taskId,
fromStatus: LabTaskStatus.COMPLETED,
toStatus: LabTaskStatus.IN_PROGRESS,
changedByUserId: actorUserId,
},
});
await this.billing.revokeCommissionOnUncomplete(tx, taskId);
});
const refreshed = await this.prisma.labCase.findFirstOrThrow({
where: { id: labCaseId },
include: labCaseListInclude,
});
return { success: true, data: await this.mapLabCaseDetail(refreshed, localeInput) };
}
async uploadInternalAttachments(
labCaseId: string,
lineClientKey: string,
@@ -913,6 +1032,7 @@ export class CasesService {
where: {
id: taskId,
labCaseId,
roundId: null,
labCase: this.visibleStartedToLabWhere(labOrganizationId),
},
select: { id: true },
@@ -1147,14 +1267,16 @@ export class CasesService {
status: LabTaskStatus;
prosthesisTypeCode: string;
teeth: Prisma.JsonValue;
roundId?: string | null;
}>;
toothProsthesis?: Array<{ tooth: string; prosthesisTypeCode: string }>;
}) {
const currentTasks = lc.tasks.filter((task) => !task.roundId);
const prosthesisGroups = this.buildProsthesisGroupsFromTasks(
lc.tasks,
currentTasks,
lc.toothProsthesis ?? [],
);
const completedTasks = lc.tasks.filter((t) => t.status === LabTaskStatus.COMPLETED).length;
const completedTasks = currentTasks.filter((t) => t.status === LabTaskStatus.COMPLETED).length;
const { clinic, patient } = this.resolveClinicAndPatient(lc);
return {
@@ -1163,14 +1285,14 @@ export class CasesService {
startedAt: lc.startedAt?.toISOString() ?? null,
origin: lc.origin ?? LabCaseOrigin.CLINIC_DISPATCH,
dueDate: lc.dueDate?.toISOString() ?? null,
isOverdue: isLabCaseOverdue(lc.dueDate, lc.tasks),
isOverdue: isLabCaseOverdue(lc.dueDate, currentTasks),
isImportant: lc.isImportant,
clinic,
patient,
prosthesisGroups,
taskProgress: {
completed: completedTasks,
total: lc.tasks.length,
total: currentTasks.length,
},
};
}
@@ -1184,13 +1306,17 @@ export class CasesService {
lc.details[0]?.detail?.treatmentType ?? lc.lines[0]?.treatmentType ?? null;
const link = lc.details[0];
const { clinic, patient } = this.resolveClinicAndPatient(lc);
const prosthesisCodes = atomicProsthesisCodes(lc.tasks.map((t) => t.prosthesisTypeCode));
const currentTasks = lc.tasks.filter((task) => !task.roundId);
const prosthesisCodes = atomicProsthesisCodes([
...currentTasks.map((t) => t.prosthesisTypeCode),
...lc.rounds.flatMap((round) => round.lines.map((line) => line.prosthesisTypeCode)),
]);
const prosthesisLabels = await this.catalogLabels.resolveLabels(
CatalogEntityKind.PROSTHESIS_TYPE,
prosthesisCodes,
locale,
);
const tasksByTooth = this.groupTasks(lc.tasks, prosthesisLabels, lc.toothProsthesis);
const tasksByTooth = this.groupTasks(currentTasks, prosthesisLabels, lc.toothProsthesis);
const accessToken = await this.labCaseAccess.ensureAccessToken(lc.id);
const shareUrl = accessToken
? this.labCaseAccess.buildShareUrl(accessToken, locale)
@@ -1200,7 +1326,7 @@ export class CasesService {
id: lc.id,
sentAt: lc.sentAt?.toISOString() ?? null,
dueDate: lc.dueDate?.toISOString() ?? null,
isOverdue: isLabCaseOverdue(lc.dueDate, lc.tasks),
isOverdue: isLabCaseOverdue(lc.dueDate, currentTasks),
isImportant: lc.isImportant,
externalCode: lc.externalCode ?? null,
origin: lc.origin,
@@ -1261,11 +1387,30 @@ export class CasesService {
organizationName: s.organization.name,
sentAt: s.sentAt.toISOString(),
})),
tasks: lc.tasks.map((t) => this.mapTask(t, prosthesisLabels, lc.toothProsthesis)),
tasks: currentTasks.map((t) => this.mapTask(t, prosthesisLabels, lc.toothProsthesis)),
tasksByTooth,
historyRounds: lc.rounds.map((round) => ({
id: round.id,
stoppedAt: round.stoppedAt.toISOString(),
lines: round.lines.map((line) => ({
tooth: line.tooth,
prosthesisTypeCode: line.prosthesisTypeCode,
prosthesisTypeLabel:
prosthesisLabels.get(line.prosthesisTypeCode) ?? line.prosthesisTypeCode,
selectionGroupId: line.selectionGroupId || undefined,
})),
tasks: round.tasks.map((task) => ({
id: task.id,
stepOrder: task.stepOrder,
stepLabel: task.stepLabel,
status: task.status,
prosthesisTypeCode: task.prosthesisTypeCode,
teeth: normalizeTaskTeeth(task.teeth),
})),
})),
taskProgress: {
completed: lc.tasks.filter((t) => t.status === LabTaskStatus.COMPLETED).length,
total: lc.tasks.length,
completed: currentTasks.filter((t) => t.status === LabTaskStatus.COMPLETED).length,
total: currentTasks.length,
},
};
}
@@ -1331,7 +1476,12 @@ export class CasesService {
groups.set(key, entry);
}
return [...groups.values()].map((group) => ({
return [...groups.values()]
.sort(
(a, b) =>
Number(a.prosthesisTypeCode.includes('+')) - Number(b.prosthesisTypeCode.includes('+')),
)
.map((group) => ({
treatmentDetailId: group.treatmentDetailId,
teeth: [...new Set(group.teeth)],
treatmentType: group.treatmentType,
@@ -1474,7 +1624,7 @@ export class CasesService {
if (names.includes('TAB_CASES_EDIT')) {
return;
}
throw new AppException(ErrorCode.PERMISSION_ACCESS_CASES, HttpStatus.FORBIDDEN);
throw new AppException(ErrorCode.PERMISSION_EDIT_CASES, HttpStatus.FORBIDDEN);
}
private async getMembership(userId: string, organizationId: string) {

View File

@@ -40,7 +40,7 @@ const accessCaseInclude = {
orderBy: [{ sentAt: 'asc' as const }],
include: { organization: { select: { id: true, name: true } } },
},
tasks: { select: { status: true } },
tasks: { where: { roundId: null }, select: { status: true } },
} satisfies Prisma.LabCaseInclude;
type ResolvedAccess =
@@ -104,7 +104,7 @@ export class LabCaseAccessService {
const prosthesisCodes = atomicProsthesisCodes(
(
await this.prisma.labCaseTask.findMany({
where: { labCaseId: labCase.id },
where: { labCaseId: labCase.id, roundId: null },
select: { prosthesisTypeCode: true },
})
).map((t) => t.prosthesisTypeCode),
@@ -320,7 +320,7 @@ export class LabCaseAccessService {
prosthesisLabels: Map<string, string>,
) {
const tasks = await this.prisma.labCaseTask.findMany({
where: { labCaseId },
where: { labCaseId, roundId: null },
select: { prosthesisTypeCode: true, teeth: true, selectionGroupId: true },
orderBy: [{ prosthesisTypeCode: 'asc' }],
});

View File

@@ -92,6 +92,13 @@ function buildMockTx(options: {
return { tx, created };
}
const CASE_SCOPE = '__case__';
const CASE_LEVEL = new Set(['intraoral_scan', 'packing', 'shipping']);
function rowStepCodes(steps: Array<{ workflowStepCode: string }>): string[] {
return steps.map((step) => step.workflowStepCode).filter((code) => !CASE_LEVEL.has(code));
}
function stepsFromSeed(code: string) {
const seed = PROSTHESIS_TYPES.find((type) => type.code === code);
if (!seed) {
@@ -122,20 +129,39 @@ describe('generateLabCaseTasks', () => {
expect(count).toBe(pfmSteps.length);
expect(created).toHaveLength(pfmSteps.length);
expect(created[0]).toMatchObject({
const rows = created as Array<{
teeth: string[];
prosthesisTypeCode: string;
workflowStepCode: string;
stepLabel: string;
status: string;
sourceKey: string;
}>;
const pipeline = rows.filter((row) => row.prosthesisTypeCode !== CASE_SCOPE);
const caseLevel = rows.filter((row) => row.prosthesisTypeCode === CASE_SCOPE);
expect(pipeline[0]).toMatchObject({
teeth: ['14'],
prosthesisTypeCode: 'pfm_crown',
workflowStepCode: 'intraoral_scan',
stepLabel: 'Intraoral Scan',
status: 'IN_PROGRESS',
});
const stepCodes = (created as Array<{ workflowStepCode: string }>).map(
(row) => row.workflowStepCode,
expect(pipeline.map((row) => row.workflowStepCode)).toEqual(rowStepCodes(pfmSteps));
expect(pipeline.map((row) => row.workflowStepCode)).toEqual(
expect.arrayContaining(['model_design', 'model_create', 'build_up_crown', 'milling_wet']),
);
expect(stepCodes).toEqual(pfmSteps.map((step) => step.workflowStepCode));
expect(stepCodes).toContain('packing');
expect(stepCodes).toContain('shipping');
expect(stepCodes).toContain('milling_wet');
expect(caseLevel.map((row) => row.workflowStepCode)).toEqual([
'intraoral_scan',
'packing',
'shipping',
]);
expect(caseLevel[0]).toMatchObject({
stepLabel: 'Intraoral Scan',
sourceKey: CASE_SCOPE,
teeth: [],
});
const modelDesign = pipeline.findIndex((row) => row.workflowStepCode === 'model_design');
const modelCreate = pipeline.findIndex((row) => row.workflowStepCode === 'model_create');
expect(modelDesign).toBeGreaterThanOrEqual(0);
expect(modelDesign).toBeLessThan(modelCreate);
});
it('merges same-type teeth in one detail into one task set without a bridge', async () => {
@@ -155,7 +181,7 @@ describe('generateLabCaseTasks', () => {
const count = await generateLabCaseTasks(tx as never, 'lab-case-group', 'en');
expect(count).toBe(pfmSteps.length + zirconiaSteps.length);
expect(count).toBe(rowStepCodes(pfmSteps).length + rowStepCodes(zirconiaSteps).length + 3);
const rows = created as Array<{
teeth: string[];
prosthesisTypeCode: string;
@@ -164,13 +190,15 @@ describe('generateLabCaseTasks', () => {
const pfmRows = rows.filter((r) => r.prosthesisTypeCode === 'pfm_crown');
const zirconiaRows = rows.filter((r) => r.prosthesisTypeCode === 'monolithic_zirconia');
expect(pfmRows).toHaveLength(pfmSteps.length);
expect(pfmRows).toHaveLength(rowStepCodes(pfmSteps).length);
expect(pfmRows.every((r) => r.teeth.join(',') === '14,15')).toBe(true);
expect(pfmRows.every((r) => r.selectionGroupId === '')).toBe(true);
expect(zirconiaRows).toHaveLength(zirconiaSteps.length);
expect(zirconiaRows).toHaveLength(rowStepCodes(zirconiaSteps).length);
expect(zirconiaRows.every((r) => r.teeth.join(',') === '16')).toBe(true);
const uniqueKeys = new Set(
rows.map((r) => `${r.teeth.join()}:${r.prosthesisTypeCode}`),
rows
.filter((r) => r.prosthesisTypeCode !== CASE_SCOPE)
.map((r) => `${r.teeth.join()}:${r.prosthesisTypeCode}`),
);
expect(uniqueKeys.size).toBe(2);
});
@@ -194,7 +222,7 @@ describe('generateLabCaseTasks', () => {
const stepCodes = (created as Array<{ workflowStepCode: string }>).map(
(row) => row.workflowStepCode,
);
expect(stepCodes).toEqual(['intraoral_scan', 'design']);
expect(stepCodes).toEqual(['design', 'intraoral_scan']);
expect(stepCodes).not.toContain('packing');
expect(stepCodes).not.toContain('shipping');
});
@@ -232,9 +260,10 @@ describe('generateLabCaseTasks', () => {
prosthesisTypeCode: string;
selectionGroupId: string;
}>;
const teethSets = new Set(rows.map((r) => r.teeth.join(',')));
const pipeline = rows.filter((r) => r.prosthesisTypeCode !== CASE_SCOPE);
const teethSets = new Set(pipeline.map((r) => r.teeth.join(',')));
expect(teethSets).toEqual(new Set(['14,15,21']));
expect(rows.every((r) => r.selectionGroupId === '')).toBe(true);
expect(pipeline.every((r) => r.selectionGroupId === '')).toBe(true);
});
it('keeps the connected group id when every tooth of that type is the same bridge', async () => {
@@ -258,7 +287,11 @@ describe('generateLabCaseTasks', () => {
});
await generateLabCaseTasks(tx as never, 'lab-case-bridge-only', 'en');
const rows = created as Array<{ teeth: string[]; selectionGroupId: string }>;
const rows = (created as Array<{
teeth: string[];
selectionGroupId: string;
prosthesisTypeCode: string;
}>).filter((r) => r.prosthesisTypeCode !== CASE_SCOPE);
expect(rows.every((r) => r.teeth.join(',') === '14,15')).toBe(true);
expect(rows.every((r) => r.selectionGroupId === 'connected-1')).toBe(true);
});
@@ -308,8 +341,11 @@ describe('generateLabCaseTasks', () => {
for (const row of rows) {
byType.set(row.prosthesisTypeCode, row.teeth.join(','));
}
expect(byType.get('pfm_crown')).toBe('14,15,16');
expect(byType.get('pfm_crown')).toBe('15,16');
expect(byType.get('fiber_post_core')).toBe('14');
expect(byType.has('fiber_post_core+pfm_crown') || byType.has('pfm_crown+fiber_post_core')).toBe(
true,
);
});
it('skips generation when tasks already exist', async () => {
@@ -347,8 +383,14 @@ describe('generateLabCaseTasks', () => {
const count = await generateLabCaseTasks(tx as never, 'lab-internal-1', 'en');
expect(count).toBe(pfmSteps.length);
const rows = created as Array<{ teeth: string[]; lineId: string }>;
const teethSets = new Set(rows.map((r) => r.teeth.join(',')));
const rows = created as Array<{
teeth: string[];
lineId: string;
prosthesisTypeCode: string;
}>;
const teethSets = new Set(
rows.filter((r) => r.prosthesisTypeCode !== CASE_SCOPE).map((r) => r.teeth.join(',')),
);
expect(teethSets).toEqual(new Set(['11,21']));
expect(created[0]).toMatchObject({
lineId: 'line-1',
@@ -385,17 +427,28 @@ describe('generateLabCaseTasks', () => {
prosthesisTypeCode: string;
teeth: string[];
}>;
expect(count).toBe(tiSteps.length + zrSteps.length);
expect(rows.every((r) => r.teeth.join() === '46')).toBe(true);
const shared = rowStepCodes(tiSteps).filter((code) => rowStepCodes(zrSteps).includes(code));
expect(count).toBe(
rowStepCodes(tiSteps).length + rowStepCodes(zrSteps).length - shared.length + 3,
);
const pipeline = rows.filter((row) => row.prosthesisTypeCode !== CASE_SCOPE);
expect(pipeline.every((r) => r.teeth.join() === '46')).toBe(true);
const byType = new Map<string, string[]>();
for (const row of rows) {
for (const row of pipeline) {
const list = byType.get(row.prosthesisTypeCode) ?? [];
list.push(row.workflowStepCode);
byType.set(row.prosthesisTypeCode, list);
}
expect([...byType.keys()].sort()).toEqual(['monolithic_zirconia', 'ti_base_abutment']);
expect(byType.get('ti_base_abutment')).toEqual(tiSteps.map((s) => s.workflowStepCode));
expect(byType.get('monolithic_zirconia')).toEqual(zrSteps.map((s) => s.workflowStepCode));
expect(byType.get('ti_base_abutment')).toEqual(
rowStepCodes(tiSteps).filter((code) => !shared.includes(code)),
);
expect(byType.get('monolithic_zirconia')).toEqual(
rowStepCodes(zrSteps).filter((code) => !shared.includes(code)),
);
expect(byType.get('monolithic_zirconia+ti_base_abutment')).toEqual(shared);
expect(
rows.filter((row) => row.workflowStepCode === 'intraoral_scan'),
).toHaveLength(1);
});
it('omits design for prefab abutments and inserts choosing_abutment before model_create', async () => {
@@ -416,10 +469,11 @@ describe('generateLabCaseTasks', () => {
(row) => row.workflowStepCode,
);
expect(stepCodes).toEqual([
'intraoral_scan',
'choosing_abutment',
'model_design',
'model_create',
'polish_prep',
'intraoral_scan',
'packing',
'shipping',
]);
@@ -463,8 +517,16 @@ describe('generateLabCaseTasks', () => {
expect(prefabStepsOut).not.toContain('design');
expect(crownStepsOut).toContain('design');
expect(crownStepsOut).not.toContain('choosing_abutment');
expect(prefabStepsOut.filter((c) => c === 'intraoral_scan')).toHaveLength(1);
expect(crownStepsOut.filter((c) => c === 'intraoral_scan')).toHaveLength(1);
expect(prefabStepsOut).not.toContain('intraoral_scan');
expect(crownStepsOut).not.toContain('intraoral_scan');
expect(rows.filter((row) => row.workflowStepCode === 'intraoral_scan')).toHaveLength(1);
const sharedKey = 'monolithic_zirconia+prefabricated_abutment';
const sharedSteps = rows
.filter((row) => row.prosthesisTypeCode === sharedKey)
.map((row) => row.workflowStepCode);
expect(sharedSteps).toEqual(['model_design', 'model_create']);
expect(prefabStepsOut).not.toContain('model_design');
expect(crownStepsOut).not.toContain('model_design');
});
it('merges partial_denture rows on the same sourceKey into one task set', async () => {
@@ -487,9 +549,10 @@ describe('generateLabCaseTasks', () => {
tooth: string;
prosthesisTypeCode: string;
}>;
expect(rows.every((r) => r.prosthesisTypeCode === 'partial_denture')).toBe(true);
expect(rows.every((r) => r.teeth.join(',') === '14,15,16,17,18')).toBe(true);
expect(new Set(rows.map((r) => r.tooth)).size).toBe(1);
const pipeline = rows.filter((r) => r.prosthesisTypeCode !== CASE_SCOPE);
expect(pipeline.every((r) => r.prosthesisTypeCode === 'partial_denture')).toBe(true);
expect(pipeline.every((r) => r.teeth.join(',') === '14,15,16,17,18')).toBe(true);
expect(new Set(pipeline.map((r) => r.tooth)).size).toBe(1);
});
it('keeps crowns on abutment teeth as separate per-tooth jobs beside a merged partial', async () => {
@@ -512,12 +575,11 @@ describe('generateLabCaseTasks', () => {
teeth: string[];
prosthesisTypeCode: string;
}>;
const partialRows = rows.filter((r) => r.prosthesisTypeCode === 'partial_denture');
const crownRows = rows.filter((r) => r.prosthesisTypeCode === 'pfm_crown');
expect(partialRows).toHaveLength(partialSteps.length);
expect(partialRows.every((r) => r.teeth.join(',') === '14,15')).toBe(true);
expect(crownRows).toHaveLength(pfmSteps.length);
expect(crownRows.every((r) => r.teeth.join(',') === '14')).toBe(true);
const teethSets = (code: string) =>
[...new Set(rows.filter((row) => row.prosthesisTypeCode === code).map((row) => row.teeth.join(',')))];
expect(teethSets('partial_denture').sort()).toEqual(['14', '15']);
expect(teethSets('pfm_crown')).toEqual(['14']);
expect(teethSets('partial_denture+pfm_crown')).toEqual(['14']);
});
it('folds connected pontic teeth into the abutment crown pipeline', async () => {
@@ -552,8 +614,9 @@ describe('generateLabCaseTasks', () => {
const count = await generateLabCaseTasks(tx as never, 'lab-case-pontic', 'en');
expect(count).toBe(pfmSteps.length);
const rows = created as Array<{ teeth: string[]; prosthesisTypeCode: string }>;
expect(rows.every((r) => r.prosthesisTypeCode === 'pfm_crown')).toBe(true);
expect(rows.every((r) => r.teeth.join(',') === '14,15,16')).toBe(true);
const pipeline = rows.filter((r) => r.prosthesisTypeCode !== CASE_SCOPE);
expect(pipeline.every((r) => r.prosthesisTypeCode === 'pfm_crown')).toBe(true);
expect(pipeline.every((r) => r.teeth.join(',') === '14,15,16')).toBe(true);
});
it('does not create a mill pipeline for an unattached pontic', async () => {
@@ -572,4 +635,83 @@ describe('generateLabCaseTasks', () => {
expect(count).toBe(0);
expect(created).toHaveLength(0);
});
it('uses laminate buildup and custom-abutment design on the matching types', async () => {
const veneerSteps = stepsFromSeed('veneer_layered');
const abutmentSteps = stepsFromSeed('customized_abutment');
const { tx, created } = buildMockTx({
toothProsthesisRows: [
{ treatmentDetailId: 'detail-1', tooth: '11', prosthesisTypeCode: 'veneer_layered' },
{ treatmentDetailId: 'detail-1', tooth: '21', prosthesisTypeCode: 'customized_abutment' },
],
prosthesisTypes: [
{ code: 'veneer_layered', steps: veneerSteps },
{ code: 'customized_abutment', steps: abutmentSteps },
],
});
await generateLabCaseTasks(tx as never, 'lab-case-split-steps', 'en');
const rows = created as Array<{ prosthesisTypeCode: string; workflowStepCode: string }>;
const veneer = rows
.filter((row) => row.prosthesisTypeCode === 'veneer_layered')
.map((row) => row.workflowStepCode);
const abutment = rows
.filter((row) => row.prosthesisTypeCode === 'customized_abutment')
.map((row) => row.workflowStepCode);
expect(veneer).toContain('build_up_laminate');
expect(veneer).not.toContain('build_up_crown');
expect(veneer).not.toContain('build_up');
expect(abutment).toContain('design_customized_abutment');
expect(abutment).not.toContain('design');
expect(abutment).toContain('model_design');
expect(rows.filter((row) => row.workflowStepCode === 'packing')).toHaveLength(1);
expect(rows.filter((row) => row.workflowStepCode === 'shipping')).toHaveLength(1);
});
it('moves a step shared by two types on the same teeth into one combined section', async () => {
const prefabSteps = stepsFromSeed('prefabricated_abutment');
const pressSteps = stepsFromSeed('press_ceramic');
const { tx, created } = buildMockTx({
toothProsthesisRows: [
{ treatmentDetailId: 'detail-1', tooth: '21', prosthesisTypeCode: 'prefabricated_abutment' },
{ treatmentDetailId: 'detail-1', tooth: '21', prosthesisTypeCode: 'press_ceramic' },
],
prosthesisTypes: [
{ code: 'prefabricated_abutment', steps: prefabSteps },
{ code: 'press_ceramic', steps: pressSteps },
],
});
await generateLabCaseTasks(tx as never, 'lab-case-shared-polish', 'en');
const rows = created as Array<{ prosthesisTypeCode: string; workflowStepCode: string }>;
const codes = (type: string) =>
rows.filter((row) => row.prosthesisTypeCode === type).map((row) => row.workflowStepCode);
expect(codes('prefabricated_abutment')).not.toContain('polish_prep');
expect(codes('press_ceramic')).not.toContain('polish_prep');
expect(codes('prefabricated_abutment+press_ceramic')).toEqual(['polish_prep']);
});
it('keeps unstacked teeth of a type together and stacks the tooth that has an extra type', async () => {
const crownSteps = stepsFromSeed('pfz_crown');
const tiSteps = stepsFromSeed('ti_base_abutment');
const { tx, created } = buildMockTx({
toothProsthesisRows: [
{ treatmentDetailId: 'detail-1', tooth: '11', prosthesisTypeCode: 'pfz_crown' },
{ treatmentDetailId: 'detail-1', tooth: '21', prosthesisTypeCode: 'pfz_crown' },
{ treatmentDetailId: 'detail-1', tooth: '21', prosthesisTypeCode: 'ti_base_abutment' },
],
prosthesisTypes: [
{ code: 'pfz_crown', steps: crownSteps },
{ code: 'ti_base_abutment', steps: tiSteps },
],
});
await generateLabCaseTasks(tx as never, 'lab-case-split-stack', 'en');
const rows = created as Array<{ prosthesisTypeCode: string; teeth: string[] }>;
const teethFor = (code: string) =>
rows.find((row) => row.prosthesisTypeCode === code)?.teeth.join(',');
expect(teethFor('pfz_crown')).toBe('11');
expect(teethFor('ti_base_abutment')).toBe('21');
expect(teethFor('pfz_crown+ti_base_abutment')).toBe('21');
});
});

View File

@@ -4,6 +4,9 @@ import {
prosthesisGroupKey,
unionWorkflowStepCodes,
PONTIC_CODE,
CASE_LEVEL_STEP_CODES,
CASE_TASK_SCOPE,
isCaseLevelStepCode,
} from '../../common/prosthesis-group';
import { sortProsthesisTeeth } from './lab-case-task.util';
@@ -24,7 +27,9 @@ export async function generateLabCaseTasks(
labCaseId: string,
localeInput?: string | null,
): Promise<number> {
const existingCount = await tx.labCaseTask.count({ where: { labCaseId } });
const existingCount = await tx.labCaseTask.count({
where: { labCaseId, roundId: null },
});
if (existingCount > 0) {
return 0;
}
@@ -112,38 +117,90 @@ export async function generateLabCaseTasks(
foldPonticIntoCrownTypeMerges(merges, categoryByCode);
const taskRows: Prisma.LabCaseTaskCreateManyInput[] = [];
const caseLevelPresent = new Set<string>();
const rowStepsByCode = new Map<string, string[]>();
for (const [code, steps] of stepsByProsthesisCode) {
const unioned = unionWorkflowStepCodes([steps.map((step) => step.workflowStepCode)]);
for (const stepCode of unioned) {
if (isCaseLevelStepCode(stepCode)) caseLevelPresent.add(stepCode);
}
rowStepsByCode.set(
code,
unioned.filter((stepCode) => !isCaseLevelStepCode(stepCode)),
);
}
for (const merge of merges.values()) {
if (merge.code === PONTIC_CODE) continue;
const lists = [
(stepsByProsthesisCode.get(merge.code) ?? []).map((s) => s.workflowStepCode),
];
const unioned = unionWorkflowStepCodes(lists);
if (unioned.length === 0) {
continue;
for (const stack of stackGroupsFromMerges(merges)) {
const ownersByStep = new Map<string, string[]>();
for (const code of stack.codes) {
for (const stepCode of rowStepsByCode.get(code) ?? []) {
const owners = ownersByStep.get(stepCode) ?? [];
owners.push(code);
ownersByStep.set(stepCode, owners);
}
}
const teeth = sortProsthesisTeeth(merge.teeth);
const selectionGroupId = exclusiveBridgeSelectionGroupId(merge);
const groupCode = prosthesisGroupKey([merge.code]);
const stepsBySection = new Map<string, string[]>();
for (const [stepCode, owners] of ownersByStep) {
const sectionKey = prosthesisGroupKey(owners);
const list = stepsBySection.get(sectionKey) ?? [];
list.push(stepCode);
stepsBySection.set(sectionKey, list);
}
unioned.forEach((workflowStepCode, index) => {
taskRows.push({
labCaseId,
treatmentDetailId: merge.treatmentDetailId,
lineId: merge.lineId,
sourceKey: merge.sourceKey,
tooth: teeth[0] ?? '',
teeth,
treatmentType: merge.treatmentType,
prosthesisTypeCode: groupCode,
selectionGroupId,
workflowStepCode,
stepOrder: index + 1,
stepLabel: stepLabels.get(workflowStepCode) ?? workflowStepCode,
status: LabTaskStatus.IN_PROGRESS,
});
const sections = [...stepsBySection.entries()].sort((a, b) => {
const shared = Number(a[0].includes('+')) - Number(b[0].includes('+'));
if (shared !== 0) return shared;
return a[0].localeCompare(b[0]);
});
for (const [sectionKey, stepCodes] of sections) {
const ordered = unionWorkflowStepCodes([stepCodes]);
if (ordered.length === 0) continue;
const teeth = sortProsthesisTeeth(stack.teeth);
const selectionGroupId = exclusiveBridgeSelectionGroupId({
teeth,
groupByTooth: stack.groupByTooth,
});
ordered.forEach((workflowStepCode, index) => {
taskRows.push({
labCaseId,
treatmentDetailId: stack.treatmentDetailId,
lineId: stack.lineId,
sourceKey: stack.sourceKey,
tooth: teeth[0] ?? '',
teeth,
treatmentType: stack.treatmentType,
prosthesisTypeCode: sectionKey,
selectionGroupId,
workflowStepCode,
stepOrder: index + 1,
stepLabel: stepLabels.get(workflowStepCode) ?? workflowStepCode,
status: LabTaskStatus.IN_PROGRESS,
});
});
}
}
let caseStepOrder = 1;
for (const workflowStepCode of CASE_LEVEL_STEP_CODES) {
if (!caseLevelPresent.has(workflowStepCode)) continue;
taskRows.push({
labCaseId,
treatmentDetailId: null,
lineId: null,
sourceKey: CASE_TASK_SCOPE,
tooth: '',
teeth: [],
treatmentType: '',
prosthesisTypeCode: CASE_TASK_SCOPE,
selectionGroupId: '',
workflowStepCode,
stepOrder: caseStepOrder,
stepLabel: stepLabels.get(workflowStepCode) ?? workflowStepCode,
status: LabTaskStatus.IN_PROGRESS,
});
caseStepOrder += 1;
}
if (taskRows.length === 0) {
@@ -195,8 +252,76 @@ function addToothToMerge(merge: TypeMerge, tooth: string, selectionGroupId: stri
}
}
type StackGroup = {
sourceKey: string;
treatmentDetailId: string | null;
lineId: string | null;
treatmentType: string;
teeth: string[];
codes: string[];
groupByTooth: Map<string, string>;
};
/** Teeth with the same prosthesis-type set share pipelines. A stacked tooth is its own set. */
function stackGroupsFromMerges(merges: Map<string, TypeMerge>): StackGroup[] {
const byTooth = new Map<
string,
{
sourceKey: string;
tooth: string;
treatmentDetailId: string | null;
lineId: string | null;
treatmentType: string;
codes: Set<string>;
selectionGroupId: string;
}
>();
for (const merge of merges.values()) {
if (merge.code === PONTIC_CODE) continue;
for (const tooth of merge.teeth) {
const key = `${merge.sourceKey}::${tooth}`;
const entry = byTooth.get(key) ?? {
sourceKey: merge.sourceKey,
tooth,
treatmentDetailId: merge.treatmentDetailId,
lineId: merge.lineId,
treatmentType: merge.treatmentType,
codes: new Set<string>(),
selectionGroupId: '',
};
entry.codes.add(merge.code);
const groupId = merge.groupByTooth.get(tooth)?.trim() || '';
if (groupId) entry.selectionGroupId = groupId;
byTooth.set(key, entry);
}
}
const stacks = new Map<string, StackGroup>();
for (const entry of byTooth.values()) {
const codes = [...entry.codes].sort();
const stackKey = `${entry.sourceKey}::${codes.join('+')}`;
const stack = stacks.get(stackKey) ?? {
sourceKey: entry.sourceKey,
treatmentDetailId: entry.treatmentDetailId,
lineId: entry.lineId,
treatmentType: entry.treatmentType,
teeth: [],
codes,
groupByTooth: new Map<string, string>(),
};
stack.teeth.push(entry.tooth);
if (entry.selectionGroupId) stack.groupByTooth.set(entry.tooth, entry.selectionGroupId);
stacks.set(stackKey, stack);
}
return [...stacks.values()];
}
/** Connected badge only when every tooth in the pipeline is that one bridge. */
function exclusiveBridgeSelectionGroupId(merge: TypeMerge): string {
function exclusiveBridgeSelectionGroupId(merge: {
teeth: string[];
groupByTooth: Map<string, string>;
}): string {
if (merge.teeth.length < 2) return '';
const teethByGroup = new Map<string, Set<string>>();
for (const tooth of merge.teeth) {

View File

@@ -16,6 +16,7 @@ import { labCaseTaskListedAtOrder } from '../../common/lab-case-listed-at';
import { ListLabTasksDto, LocateTaskPageDto, UpdateLabTaskDto } from './dto/tasks.dto';
import {
atomicProsthesisCodes,
isCaseLevelTask,
ponticTeethAmong,
prosthesisGroupLabel,
prosthesisTypeTaskWhere,
@@ -245,6 +246,14 @@ export class TasksService {
throw new AppException(ErrorCode.CASE_TASK_NOT_FOUND, HttpStatus.NOT_FOUND);
}
if (task.roundId) {
throw new AppException(ErrorCode.CASE_TASK_NOT_FOUND, HttpStatus.NOT_FOUND);
}
if (task.status === LabTaskStatus.COMPLETED && dto.status !== LabTaskStatus.COMPLETED) {
throw new AppException(ErrorCode.TASK_REOPEN_REQUIRES_CASE_EDIT, HttpStatus.FORBIDDEN);
}
if (task.assigneeUserId && task.assigneeUserId !== actorUserId) {
throw new AppException(ErrorCode.TASK_ASSIGNED_TO_OTHER, HttpStatus.FORBIDDEN);
}
@@ -281,6 +290,7 @@ export class TasksService {
const siblingScans = await tx.labCaseTask.findMany({
where: {
labCaseId: task.labCaseId,
roundId: null,
workflowStepCode: CASE_SCOPED_SCAN_STEP_CODE,
status: { not: LabTaskStatus.COMPLETED },
id: { not: taskId },
@@ -345,6 +355,7 @@ export class TasksService {
const remainingIncomplete = await tx.labCaseTask.count({
where: {
labCaseId: task.labCaseId,
roundId: null,
status: { not: LabTaskStatus.COMPLETED },
},
});
@@ -517,13 +528,14 @@ export class TasksService {
};
const base: Prisma.LabCaseTaskWhereInput = {
roundId: null,
...(query.labCaseId ? { labCaseId: query.labCaseId } : {}),
labCase: {
...labCaseScope,
...(query.overdue
? {
dueDate: { not: null, lt: startOfUtcDay() },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS } },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS, roundId: null } },
}
: {}),
},
@@ -543,6 +555,7 @@ export class TasksService {
const completedGroups = await this.prisma.labCaseTask.groupBy({
by: ['labCaseId', 'sourceKey', 'tooth', 'prosthesisTypeCode'],
where: {
roundId: null,
workflowStepCode: stepCompleted,
status: LabTaskStatus.COMPLETED,
labCase: labCaseScope,
@@ -553,16 +566,28 @@ export class TasksService {
return { id: { in: [] } };
}
const caseLevelCaseIds = new Set<string>();
const rowGroups = completedGroups.filter((group) => {
if (isCaseLevelTask(group)) {
caseLevelCaseIds.add(group.labCaseId);
return false;
}
return true;
});
return {
AND: [
base,
{
OR: completedGroups.map((group) => ({
labCaseId: group.labCaseId,
sourceKey: group.sourceKey,
tooth: group.tooth,
prosthesisTypeCode: group.prosthesisTypeCode,
})),
OR: [
...rowGroups.map((group) => ({
labCaseId: group.labCaseId,
sourceKey: group.sourceKey,
tooth: group.tooth,
prosthesisTypeCode: group.prosthesisTypeCode,
})),
...[...caseLevelCaseIds].map((labCaseId) => ({ labCaseId })),
],
},
],
};

View File

@@ -411,6 +411,7 @@ export class TodayService {
by: ['prosthesisTypeCode'],
where: {
status: LabTaskStatus.IN_PROGRESS,
roundId: null,
labCase: {
sentAt: { not: null },
sends: { some: { organizationId: labOrganizationId } },
@@ -575,6 +576,7 @@ export class TodayService {
const count = await this.prisma.labCaseTask.count({
where: {
status: LabTaskStatus.IN_PROGRESS,
roundId: null,
labCase: {
sentAt: { not: null },
sends: { some: { organizationId: labOrganizationId } },
@@ -588,6 +590,7 @@ export class TodayService {
const count = await this.prisma.labCaseTask.count({
where: {
status: LabTaskStatus.IN_PROGRESS,
roundId: null,
labCase: {
isImportant: true,
sentAt: { not: null },
@@ -604,7 +607,7 @@ export class TodayService {
sentAt: { not: null },
dueDate: { not: null, lt: startOfUtcDay() },
sends: { some: { organizationId: labOrganizationId } },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS } },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS, roundId: null } },
},
});
widgets.overdueCases = { count };
@@ -614,6 +617,7 @@ export class TodayService {
const count = await this.prisma.labCaseTask.count({
where: {
status: LabTaskStatus.IN_PROGRESS,
roundId: null,
assigneeUserId: null,
labCase: {
sentAt: { not: null },
@@ -946,7 +950,7 @@ export class TodayService {
dueDate: { not: null, gte: weekStart, lt: weekEnd },
sentAt: { not: null },
sends: { some: { organizationId: labOrganizationId } },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS } },
tasks: { some: { status: LabTaskStatus.IN_PROGRESS, roundId: null } },
},
select: { dueDate: true },
});
@@ -973,7 +977,7 @@ export class TodayService {
sends: { some: { organizationId: labOrganizationId } },
},
include: {
tasks: { select: { status: true } },
tasks: { where: { roundId: null }, select: { status: true } },
},
});
@@ -991,6 +995,7 @@ export class TodayService {
private async loadCaseCompletion(labOrganizationId: string, charts: TodayCharts) {
const tasks = await this.prisma.labCaseTask.findMany({
where: {
roundId: null,
labCase: {
sentAt: { not: null },
sends: { some: { organizationId: labOrganizationId } },
@@ -1141,6 +1146,7 @@ export class TodayService {
const completedTasks = await this.prisma.labCaseTask.findMany({
where: {
status: LabTaskStatus.COMPLETED,
roundId: null,
lastStatusChangedAt: { gte: weekStart, lt: weekEnd },
labCase: {
sends: { some: { organizationId: labOrganizationId } },
@@ -1216,7 +1222,7 @@ export class TodayService {
select: {
destinationOrganizationId: true,
partnerClinicOrganizationId: true,
tasks: { select: { status: true } },
tasks: { where: { roundId: null }, select: { status: true } },
treatment: { select: { organizationId: true } },
},
});

View File

@@ -0,0 +1,64 @@
import { narrowCatalogForOrgType } from './narrowCatalogForOrgType';
import type { ExtractionCatalog } from './voice.providers';
const catalog = (): ExtractionCatalog => ({
treatmentTypes: [
{ code: 'prosthesis', label: 'Prosthesis' },
{ code: 'restoration', label: 'Restoration' },
],
prosthesisTypes: [
{
code: 'pfm_crown',
label: 'PFM Crown',
category: 'crown',
subcategory: '',
chartRegion: 'crown',
stackGroup: 'restoration',
},
{
code: 'complete_denture',
label: 'Complete Denture',
category: 'denture',
subcategory: '',
chartRegion: 'arch',
stackGroup: 'arch',
},
],
prosthesisCategories: [
{ code: 'crown', label: 'Crown' },
{ code: 'denture', label: 'Denture' },
],
prosthesisSubcategories: [{ code: 'veneer', label: 'Veneer' }],
labs: [{ id: 'org-lab-1', name: 'Some Lab' }],
});
describe('narrowCatalogForOrgType', () => {
it('drops the treatment types and the linked labs for a LAB org', () => {
const narrowed = narrowCatalogForOrgType(catalog(), 'LAB');
expect(narrowed.treatmentTypes).toEqual([]);
expect(narrowed.labs).toEqual([]);
});
it('keeps the prosthesis tree, its categories and its subcategories intact for a LAB org', () => {
const full = catalog();
const narrowed = narrowCatalogForOrgType(full, 'LAB');
expect(narrowed.prosthesisTypes).toEqual(full.prosthesisTypes);
expect(narrowed.prosthesisCategories).toEqual(full.prosthesisCategories);
expect(narrowed.prosthesisSubcategories).toEqual(
full.prosthesisSubcategories,
);
});
it('returns the catalog unchanged for a CLINIC org', () => {
const full = catalog();
expect(narrowCatalogForOrgType(full, 'CLINIC')).toEqual(catalog());
expect(narrowCatalogForOrgType(full, 'CLINIC').labs).toHaveLength(1);
});
it('does not mutate the catalog it was given', () => {
const full = catalog();
narrowCatalogForOrgType(full, 'LAB');
expect(full.treatmentTypes).toHaveLength(2);
expect(full.labs).toHaveLength(1);
});
});

View File

@@ -0,0 +1,20 @@
import type { OrganizationTypeName } from '../../common/organization-type';
import type { ExtractionCatalog } from './voice.providers';
/**
* A LAB org dictates into a case line: the treatment type is always `prosthesis` (written
* server-side) and the lab is the destination itself. Emptying both lists is the whole of lab
* mode — the prompt already renders an empty list as "(none available)", so the model has no
* code left to emit for either field.
*
* It also closes a hole: `listLinkedLabs` does not filter by organisation type, so for a LAB
* org it returns the linked *clinics*, and a lab owner naming their referring clinic would get
* that clinic's id back as `labId`.
*/
export function narrowCatalogForOrgType(
catalog: ExtractionCatalog,
orgType: OrganizationTypeName,
): ExtractionCatalog {
if (orgType !== 'LAB') return catalog;
return { ...catalog, treatmentTypes: [], labs: [] };
}

View File

@@ -9,7 +9,6 @@ import {
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import type { Request, Response } from 'express';
import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ExtractVoiceDto } from './dto/voice.dto';
import { VoiceThrottlerGuard } from './voice-throttler.guard';
@@ -19,7 +18,9 @@ type VoiceRequestUser = { id: string; organizationId?: string };
@ApiTags('voice')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard, ClinicOrgGuard)
// No org-type guard: both org types dictate, and the service branches on the selected org's
// type for the permission it asserts and for the catalog it hands the model.
@UseGuards(JwtAuthGuard)
@Controller('voice')
export class VoiceController {
constructor(private readonly voiceService: VoiceService) {}
@@ -41,7 +42,7 @@ export class VoiceController {
@UseGuards(VoiceThrottlerGuard)
@ApiOperation({
summary:
'Transcribe a recording and extract treatment detail intents (TAB_TREATMENT_EDIT)',
'Transcribe a recording and extract entry intents (CLINIC: TAB_TREATMENT_EDIT, LAB: TAB_CASES_EDIT)',
})
async extract(
@Req() req: Request & { user: VoiceRequestUser },

View File

@@ -0,0 +1,218 @@
import { AppException, ErrorCode } from '../../common/errors';
import { VoiceService } from './voice.service';
import type { ExtractionCatalog, ExtractionResult } from './voice.providers';
import type { ExtractVoiceDto } from './dto/voice.dto';
const mockExtract = jest.fn<
Promise<ExtractionResult>,
[string, ExtractionCatalog, string]
>();
jest.mock('./openrouter.provider', () => ({
OpenRouterAsrProvider: jest.fn().mockImplementation(() => ({
transcribe: () =>
Promise.resolve({
text: 'tooth twelve, pfm crown',
usage: { costUsd: 0.001, seconds: 3 },
}),
})),
OpenRouterExtractionProvider: jest.fn().mockImplementation(() => ({
extract: (transcript: string, catalog: ExtractionCatalog, locale: string) =>
mockExtract(transcript, catalog, locale),
})),
}));
const EMPTY_INTENT = {
treatmentType: null,
teeth: [],
connectedSpans: [],
comment: null,
commentTrigger: null,
prosthesis: [],
labId: null,
labMatchExact: false,
due: null,
};
const DTO: ExtractVoiceDto = {
audio: 'AAAA',
format: 'webm',
timeZone: 'UTC',
durationMs: 3_000,
locale: 'en',
};
function buildService(opts: {
orgType: 'CLINIC' | 'LAB';
permissions: string[];
}): VoiceService {
const prisma = {
organization: {
findUnique: jest.fn().mockResolvedValue({ type: { name: opts.orgType } }),
},
membership: {
findFirst: jest.fn().mockResolvedValue({
isOwner: false,
organization: { type: { name: opts.orgType }, plan: { name: 'pro' } },
permissions: opts.permissions.map((name) => ({
permission: { name },
})),
}),
},
// The counterpart link a lab org has: `listLinkedLabs` does not filter by org type, so
// for a LAB org this row is a linked *clinic*.
organizationLink: {
findMany: jest
.fn()
.mockResolvedValueOnce([
{ organizationB: { id: 'org-counterpart', name: 'Counterpart' } },
])
.mockResolvedValue([]),
},
};
const config = {
get: () => ({
openRouter: { apiKey: 'test-key', baseUrl: 'https://example.invalid' },
profiles: {
en: {
asr: { provider: 'openrouter', model: 'asr-model' },
llm: { provider: 'openrouter', model: 'llm-model' },
},
},
maxRecordingMs: 120_000,
throttle: { ttl: 60, limit: 10 },
}),
};
const treatmentCatalog = {
list: jest.fn().mockResolvedValue([
{ code: 'prosthesis', label: 'Prosthesis', availableInTreatment: true },
{ code: 'restoration', label: 'Restoration', availableInTreatment: true },
]),
};
const prosthesisCatalog = {
list: jest.fn().mockResolvedValue([
{
code: 'pfm_crown',
label: 'PFM Crown',
category: 'crown',
subcategory: '',
chartRegion: 'crown',
stackGroup: 'restoration',
},
]),
listCategories: jest
.fn()
.mockResolvedValue([{ code: 'crown', label: 'Crown' }]),
listSubcategories: jest
.fn()
.mockResolvedValue([{ code: 'veneer', label: 'Veneer' }]),
};
return new VoiceService(
prisma as never,
config as never,
treatmentCatalog as never,
prosthesisCatalog as never,
);
}
async function codeOfThrown(promise: Promise<unknown>): Promise<string> {
try {
await promise;
return 'NO_THROW';
} catch (error) {
return error instanceof AppException
? (error.getResponse() as { code: string }).code
: `UNEXPECTED:${String(error)}`;
}
}
describe('VoiceService.extract — the org type decides the permission and the catalog', () => {
beforeEach(() => {
mockExtract.mockReset();
mockExtract.mockResolvedValue({ intent: EMPTY_INTENT, costUsd: 0.002 });
});
const user = { id: 'user-1', organizationId: 'org-1' };
it('C01 CLINIC granted: TAB_TREATMENT_EDIT passes, and the model gets the full catalog', async () => {
const service = buildService({
orgType: 'CLINIC',
permissions: ['TAB_TREATMENT_EDIT'],
});
await service.extract(user, DTO, 'en');
const catalog = mockExtract.mock.calls[0][1];
expect(catalog.treatmentTypes.map((t) => t.code)).toEqual([
'prosthesis',
'restoration',
]);
expect(catalog.labs).toHaveLength(1);
});
it('C02 CLINIC denied: no TAB_TREATMENT_EDIT is 403 and never reaches the model', async () => {
const service = buildService({
orgType: 'CLINIC',
permissions: ['TAB_TREATMENT_READ'],
});
expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe(
ErrorCode.PERMISSION_EDIT_TREATMENTS,
);
expect(mockExtract).not.toHaveBeenCalled();
});
it('C03 LAB granted: TAB_CASES_EDIT passes, and the model gets no treatment types and no labs', async () => {
const service = buildService({
orgType: 'LAB',
permissions: ['TAB_CASES_EDIT'],
});
await service.extract(user, DTO, 'en');
const catalog = mockExtract.mock.calls[0][1];
expect(catalog.treatmentTypes).toEqual([]);
expect(catalog.labs).toEqual([]);
expect(catalog.prosthesisTypes.map((p) => p.code)).toEqual(['pfm_crown']);
});
it('C04 LAB denied: no TAB_CASES_EDIT is 403 and never reaches the model', async () => {
const service = buildService({
orgType: 'LAB',
permissions: ['TAB_CASES_READ'],
});
expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe(
ErrorCode.PERMISSION_EDIT_CASES,
);
expect(mockExtract).not.toHaveBeenCalled();
});
it('denies a LAB member holding the clinic-side edit permission', async () => {
// TAB_TREATMENT_EDIT is clinic-only, so it must not open the lab route.
const service = buildService({
orgType: 'LAB',
permissions: ['TAB_TREATMENT_EDIT'],
});
expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe(
ErrorCode.PERMISSION_EDIT_CASES,
);
});
it('rejects a request with no selected organisation before any vendor call', async () => {
const service = buildService({
orgType: 'LAB',
permissions: ['TAB_CASES_EDIT'],
});
expect(
await codeOfThrown(service.extract({ id: 'user-1' }, DTO, 'en')),
).toBe(ErrorCode.AUTH_ORG_NOT_SELECTED);
expect(mockExtract).not.toHaveBeenCalled();
});
});

View File

@@ -9,6 +9,11 @@ import {
} from '../../common/zoned-civil-time';
import type { VoiceConfig, VoiceProfile } from '../../configs/configurations';
import { hasEffectivePermission } from '../../common/membership-permissions';
import {
getOrganizationTypeName,
type OrganizationTypeName,
} from '../../common/organization-type';
import { narrowCatalogForOrgType } from './narrowCatalogForOrgType';
import { normalizeCatalogLocale } from '../catalog/catalog-label.service';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service';
@@ -80,7 +85,7 @@ export class VoiceService {
): Promise<VoiceExtractionResponse> {
const startedAt = Date.now();
const organizationId = this.assertOrganization(user);
await this.assertCanEditTreatment(user.id, organizationId);
const orgType = await this.assertCanDictate(user.id, organizationId);
const catalogLocale = normalizeCatalogLocale(locale);
const profile = this.resolveProfile(catalogLocale);
@@ -136,7 +141,10 @@ export class VoiceService {
try {
// Inside the try: a catalog/DB failure here must surface as VOICE_EXTRACT_FAILED, which
// the clinician can act on, rather than a generic 500.
const catalog = await this.buildCatalog(organizationId, catalogLocale);
const catalog = narrowCatalogForOrgType(
await this.buildCatalog(organizationId, catalogLocale),
orgType,
);
const result = await extraction.extract(
transcript,
catalog,
@@ -183,7 +191,27 @@ export class VoiceService {
return user.organizationId;
}
private async assertCanEditTreatment(userId: string, organizationId: string) {
/**
* The one gate on dictation, and the source of the extraction mode: the selected org's type
* decides both the permission asserted and — through the returned type — the catalog the
* model is handed. It is never taken from the request body.
*
* `TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it on
* the lab side would deny every lab member including the owner.
*/
private async assertCanDictate(
userId: string,
organizationId: string,
): Promise<OrganizationTypeName> {
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
const [permission, deniedCode] =
orgType === 'LAB'
? (['TAB_CASES_EDIT', ErrorCode.PERMISSION_EDIT_CASES] as const)
: ([
'TAB_TREATMENT_EDIT',
ErrorCode.PERMISSION_EDIT_TREATMENTS,
] as const);
const membership = await this.prisma.membership.findFirst({
where: {
userId,
@@ -201,12 +229,10 @@ export class VoiceService {
HttpStatus.FORBIDDEN,
);
}
if (!hasEffectivePermission(membership, 'TAB_TREATMENT_EDIT')) {
throw new AppException(
ErrorCode.PERMISSION_EDIT_TREATMENTS,
HttpStatus.FORBIDDEN,
);
if (!hasEffectivePermission(membership, permission)) {
throw new AppException(deniedCode, HttpStatus.FORBIDDEN);
}
return orgType;
}
private resolveProfile(locale: string): VoiceProfile {

View File

@@ -0,0 +1,378 @@
---
type: task
status: active
created: 2026-09-16
repos:
- repo: dyolink
path: ~/PersonalProjects/dyolink
branch: feat/cases/add-voice-input-for-lab-case-line
base: origin/master
role: lab-mode extraction catalog + lab line apply + shared review sheet
spec_slug: voice-lab-case-entry
merge_after: []
aliases: [voice lab case, lab dictation, case line voice, lab mic]
---
# Voice entry for a lab case line
**Area:** Cases tab (LAB orgs) — `CaseCreatePanel`
**Created:** 2026-09-16
**Depends on:** [`voice-treatment-entry`](voice-treatment-entry/spec.md), already merged
to `master`. Every resolver, the prompt, the review sheet and the stack rules come from
there unchanged. This spec records only what differs.
A lab owner entering their own work fills a case draft by hand: Add Line, tap the FDI
chart, open the prosthesis popover, pick a leaf, repeat. The clinic side already replaced
that with a microphone. The same dictation describes the same thing on the lab side — the
teeth and the job — so the same contract should fill it.
---
## 1. Scope
**In:** one dictation fills **one case line** — its teeth, its prosthesis stack, its
comment — plus the case's due date.
**Out:** the case header's identity fields. Patient name, patient mobile, referring
dentist, referring clinic and the partner-clinic dropdown stay typed by hand (§9).
The header is where a case carries a person's name. Keeping the mic away from it is what
lets this ship without reopening the transcript decision in `voice-treatment-entry` §10.
---
## 2. What a lab line is
`LineDraft` (`CaseCreatePanel.tsx:35`) is already the shape the extraction produces:
```ts
type LineDraft = {
clientId: string;
id?: string;
teeth: FdiToothId[];
toothSelectionGroups: ToothSelectionGroup[];
comment: string;
toothProsthesis: Array<{ tooth; prosthesisTypeCode; selectionGroupId?; detailClientId }>;
attachments: LabCaseAttachmentMeta[];
};
```
Against a clinic `TreatmentDetailDraft` it has no `treatmentType` — on the lab side that is
always `prosthesis`, written server-side at `cases.service.ts:488` — and it folds the
clinic's separate `LabCaseDraft` rows into `toothProsthesis` on the line itself.
Attachments are out of scope: dictation cannot produce one.
### The save model is simpler than the clinic's, and that matters
`CaseCreatePanel` autosaves through **one** `PUT /cases/:id` carrying the header, the lines
and their `toothProsthesis` together. `buildPayload` (`:177`) reads React **state**; the
debounced effect (`:239`) fires 500 ms after any state change; `persist` (`:210`) sends it.
Two consequences, both load-bearing:
1. **No ref dance.** The clinic side reads `detailsRef.current` and `labCaseDraftsRef.current`
because a save runs before the re-render. Here nothing saves inside the handler, so
`setLines` is the whole apply. Three of the five defects found in clinic live use were in
that ref coupling; they cannot occur here.
2. **No cross-request validation.** The clinic's lab rows go in a second request that
re-reads the saved detail and rejects a tooth the detail does not carry
(`TREATMENT_TOOTH_NOT_ON_DETAIL`, `treatments.service.ts:806`). The lab write validates
only the prosthesis code (`cases.service.ts:481`) because the line and its jobs arrive in
one transaction from one payload and cannot disagree.
Point 2 cuts both ways: nothing *rejects* a mismatch either. A line whose `teeth` and
`toothProsthesis` disagree would be written silently, and the case chart would then show
something the generated tasks do not. §6 keeps the clinic's invariant for that reason.
---
## 3. User flow
```
Cases tab → Add Case → draft opens in the right pane (CaseCreatePanel)
┌──────────────────────────────────┐
│ Patient [ typed ] │
│ Dentist [ typed ] │
│ Clinic [ dropdown / typed ] │
│ Due [ AppDateInput ] │ ← the mic may write this
├──────────────────────────────────┤
│ Lines [+ Add Line][🎤]│ ← the mic lives here
│ · Line 1 12,13 · PFM crown │
└──────────────────────────────────┘
```
1. Tap the mic. `VoiceRecordingBar` shows elapsed time and the level meter, exactly as on
the clinic side.
2. Tap stop. The clip goes to `POST /voice/extract`.
3. `VoiceReviewSheet` opens in lab mode with at most three rows (§5).
4. Confirm. The line lands, the autosave effect picks it up 500 ms later.
The mic sits beside **Add Line** (`CaseCreatePanel.tsx:412-426`), built the same way
`AddDetailWithVoice` builds the clinic's split button, and shares its `disabled` state.
**No new i18n keys.** Every voice string is under `treatment.*`, and `CaseCreatePanel`
already holds `tTreatment = useTranslations('treatment')` at `:110`.
---
## 4. Lab mode is an empty catalog, not a second prompt
`buildExtractionPrompt` renders whatever catalog it is handed. It already prints
`(none available)` for an empty code list and `(none linked — labId must be null)` for an
empty lab list. So lab mode needs **no prompt text change at all**:
| Catalog field | CLINIC | LAB | Why |
|---|---|---|---|
| `treatmentTypes` | full list | `[]` | the type is always `prosthesis`, written server-side |
| `labs` | linked labs | `[]` | the lab *is* the destination |
| `prosthesisTypes` / categories / subcategories | full tree | full tree | unchanged |
The model cannot emit a `treatmentType` or a `labId` because neither list has anything in
it. The resolver needs no change; the two fields simply come back null.
### The bug this avoids
`listLinkedLabs` (`voice.service.ts:272`) does **not** filter by organisation type. For a
LAB org it returns the linked **clinics**, and the prompt would present them under the
heading `LABS THIS CLINIC CAN SEND TO`. A lab owner naming their referring clinic would get
that clinic's id back as `labId`. Emptying the list is what stops it.
### The narrowing is a pure function
`buildCatalog` (`:257`) stays untested I/O. The decision comes out:
```ts
export function narrowCatalogForOrgType(
catalog: ExtractionCatalog,
orgType: OrganizationTypeName,
): ExtractionCatalog;
```
`LAB` returns the catalog with `treatmentTypes: []` and `labs: []`. `CLINIC` returns it
untouched. It has its own spec (§10) because it is the one place a future change to
`listLinkedLabs` could silently reach lab callers again.
---
## 5. Gating and permissions
`voice.controller.ts:22` carries `@UseGuards(JwtAuthGuard, ClinicOrgGuard)`, so a LAB org
gets 403 on both voice routes today. That guard comes off the controller.
Mode is **derived from the organisation, never sent by the client.** The selected org is
already in the JWT and is already the authority for every other service in this repo.
```
extract(user, dto, locale)
│
├─ getOrganizationTypeName(orgId) organization-type.ts:76
│
├─ CLINIC → assert TAB_TREATMENT_EDIT (voice.service.ts:186, unchanged)
│ catalog: full
│
└─ LAB → assert TAB_CASES_EDIT
catalog: narrowed
```
A `mode` field on the DTO was rejected: it can only ever hold one correct value per org, and
a body field deciding authorisation is a hole to guard rather than a fact to read.
`assertCanEditTreatment` (`:186`) is renamed and generalised to take the permission code;
the clinic call site keeps `TAB_TREATMENT_EDIT`.
`TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it for the
lab side would 403 every lab member including the owner. `TAB_CASES_EDIT` is the permission
that already gates Add Case.
The denial code is **`PERMISSION_EDIT_CASES`**, added by this task. Cases was the one feature
with no edit-specific code, so `cases.service.ts` throws `PERMISSION_ACCESS_CASES` for both a
failed read check (`:1375`) and a failed edit check (`:1391`). Reusing it here would tell a lab
member who holds `TAB_CASES_READ` that they have no access to cases, which is false — they can
read every case, they just cannot edit one. All three layers of the error contract carry the new
code (§11 decision 15).
**Availability** (`GET /voice/availability`) is one config for both sides. A separate lab
toggle is speculative — if voice is on, it is on.
---
## 6. Review sheet: one component, one `mode` prop
`voiceRowAvailability` takes a third argument. Three rows disappear on their own once the
catalog is empty; one has to be forced.
| Row | CLINIC | LAB |
|---|---|---|
| Treatment type | when heard | never |
| Teeth (plain) | when not lab-dependent | never |
| Teeth and prosthesis | when lab-dependent | **always** |
| Note | when heard | when heard |
| Lab | when heard | never |
| Due date | when heard | when heard |
The one that breaks without a change: `voiceRowAvailability` derives `labDependent` from the
treatment type. In lab mode the type is null, so `labDependent` would be **false** — showing
the plain teeth row and hiding the prosthesis row, exactly backwards. In lab mode it is
forced true.
Everything else is identical, because a lab line and a prosthesis detail hold the same data:
the mini FDI chart, the target list, the stack preview through `applyLeafToJobs`, the struck
-through refused codes, the jobless targets, the candidate chips.
That shared surface is the point. Five defects were fixed in this component over the last
week. A forked lab sheet would have needed all five fixed twice.
---
## 7. Apply
`buildLabLineFromVoice` in `frontend/src/components/lab/voiceLine.ts`, pure, its own spec.
```ts
export function buildLabLineFromVoice(
result: VoiceExtractionResult,
selection: VoiceApplySelection,
ctx: { prosthesisCatalog: readonly ProsthesisCatalogEntry[] },
): { line: LineDraft; dueDate: string | null };
```
A sibling of `buildVoiceApplyPlan`, not a mode on it: the return shapes have nothing in
common, and a union return would recreate the thing that made the original callback hard to
test. Both call the same `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the stack
rules and the bridge splitting stay in one place.
### Rules it keeps from the clinic side
- **Decision 40 — a tooth is on the line only by carrying a job.** The plain `teeth` list is
never copied across. Nothing on the lab side enforces this (§2), which is exactly why the
apply must; otherwise the case chart and the generated tasks disagree and neither is wrong
enough to throw.
- **Decision 39 — teeth and prosthesis apply together**, as one row.
- A code the stack rules refuse is not applied, and the sheet already said so.
- Non-adjacent teeth never share a `selectionGroupId` (`splitDisconnectedRuns`). On this side
a shared group id tells the lab's own task generator to build a bridge, so the consequence
is more direct than on the clinic side.
### Where the line goes
Fill the active line when it is **blank** — no teeth, no jobs, no comment, no attachments,
the exact state `newLine()` produces (`:50`) — otherwise append and make the new line active.
A fresh draft opens with one blank line (`linesFromDetail` returns `[newLine()]`), so
always-append would leave a blank line above the dictated one on every first use. Nothing
rejects it: `start` only requires that *some* line has jobs (`cases.service.ts:551`), so the
blank line would ship to the floor.
### One dictation is one line
Whatever the dictation held goes into one line, even when it names several different jobs.
A line's `id` becomes the `sourceKey` (`cases.service.ts:487`) that `generateLabCaseTasks`
groups by, so this is a real choice, not a display one — but "one utterance, one line" is the
rule a lab owner can predict without knowing how tasks are grouped. Two lines means dictating
twice.
### The due date
The row stays, and ticking it calls the panel's `setDueDate` — the same state the
`AppDateInput` writes (`:129`). This is the single field outside the line that the mic
touches. A date is a resolved value with no identity in it, the resolver already handles
Jalali and per-locale week starts, and a lab owner will say "تا پنجشنبه" whether or not the
design planned for it. The sheet shows it before it lands and it can be unticked.
---
## 8. Data handling
Nothing changes. The transcript never leaves the server and is logged there at info level
(`voice-treatment-entry` §10). `logTelemetry` stays patient-free.
The lab side does not weaken that: no extracted field carries a name, because the header is
out of scope (§1) and the catalog is narrowed (§4).
---
## 9. Known gaps
Recorded so the first manual pass does not read them as bugs.
1. **A dictated referring clinic is dropped, with no mention.** "از مطب دکتر احمدی" produces
nothing and the sheet says nothing about it. Matching it would mean handing the model the
linked organisations again — the list §4 deliberately empties — and the result is a name.
Revisit only if it proves annoying in use.
2. **Patient name and mobile are typed.** Same reason, more sharply: these are the fields the
transcript decision exists to protect.
3. **Attachments are not dictatable.** Nothing to extract.
4. **`VoiceThrottlerGuard` limits are tuned for a dentist**, who dictates a few times per
visit. A lab owner entering a morning's cases will dictate far more often. Watch it in the
manual pass; do not retune it blind.
---
## 10. Verification
### Automated
- `cd backend && npm test -- narrowCatalogForOrgType` — **new**:
- LAB drops `treatmentTypes` and `labs`;
- LAB keeps the prosthesis tree, its categories and its subcategories intact;
- CLINIC is returned unchanged.
- `cd backend && npm test` — the existing 220 must stay green. The resolver is untouched.
- `cd backend && npm run build`.
- `cd frontend && npx vitest run` — **new** `voiceLine.spec.ts`:
- a tooth reaches `line.teeth` only by carrying a job;
- every `toothProsthesis` row naming a real tooth is in `line.teeth` (the invariant
nothing enforces server-side);
- a jaw sentinel is in `toothProsthesis` with an empty `selectionGroupId` and is not a
tooth on the line;
- two non-adjacent teeth never share a `selectionGroupId`;
- an unticked note row leaves `comment` empty;
- the due date comes back separately and is null when its row is unticked.
- Plus `voiceReviewRows.spec.ts`: lab mode forces the prosthesis row on and the type, plain
teeth and lab rows off.
- Each new test must be shown to fail with its rule reverted, not merely to pass.
- `cd frontend && npx tsc --noEmit` — the cross-cutting gate.
- `cd frontend && npm run build`.
- ESLint on every touched file, no new warnings.
### Manual — `fa`, LAB org, a linked clinic present
1. Cases → Add Case. The mic is enabled beside Add Line.
2. «برای دندون ۱۲ و ۱۳ روکش پی‌اف‌ام میخوام» → the sheet shows one row, both teeth, the
crown on each. No treatment-type row. No lab row.
3. Confirm → line 1 is filled, **not** line 2. Wait 1 s, reload the case: it persisted.
4. Dictate again, «۲۶ زیرکونیا» → line 2 appears and becomes active.
5. «یه کامپلیت دنچر برای فک بالا» → the jaw is selected, no tooth is invented, and the chart
shows the arch highlight.
6. «توی یادداشت‌ها بنویس رنگ A2» → the note row appears with `رنگ A2` and nothing else.
7. «تا پنجشنبه» → the due date row appears; ticking it fills the header field.
8. «از مطب دکتر احمدی، ۱۲ روکش» → the crown lands, the clinic field stays empty, nothing is
said about it (§9 item 1).
9. Start the case → tasks generate, and the task groups match the lines.
10. As a lab member **without** `TAB_CASES_EDIT`: the mic is disabled, and a forced request
returns 403.
11. As a clinic user: the treatment workspace mic still behaves exactly as before.
12. Safari and iPad, since that is where the original recording defects appeared.
---
## 11. Decision log
| # | Decision | Why |
|---|---|---|
| 1 | One dictation fills one line; the header is typed | Keeps names out of every extracted field, so `voice-treatment-entry` §10 does not reopen (§1) |
| 2 | Lab mode is an empty `treatmentTypes` + `labs` catalog | The prompt already renders both as empty; zero prompt text changes, and the model cannot emit a field it has no list for (§4) |
| 3 | Mode is derived from the org type, never sent | The JWT's org is already the authority; a body field deciding authorisation is a hole to guard (§5) |
| 4 | `ClinicOrgGuard` off the controller; `TAB_CASES_EDIT` for LAB | `TAB_TREATMENT_EDIT` is clinic-only, so reusing it would 403 every lab member (§5) |
| 5 | Reuse `VoiceReviewSheet` with a `mode` prop | Five fixes landed in it this week; a fork would need all five twice (§6) |
| 6 | Force `labDependent` true in lab mode | A null treatment type would otherwise show the plain teeth row and hide the prosthesis row (§6) |
| 7 | `buildLabLineFromVoice` is a sibling, not a mode | The return shapes share nothing; a union return recreates the untestable callback (§7) |
| 8 | Keep decision 40 even though nothing enforces it | The lab write validates only the prosthesis code, so a mismatch is written silently rather than rejected (§2, §7) |
| 9 | Fill a blank active line, otherwise append | A fresh draft already holds one blank line, and `start` would ship it (§7) |
| 10 | One dictation is one line | `sourceKey` groups tasks by line, so splitting is a real choice — but predictability wins (§7) |
| 11 | The due date row stays and writes the header | The one non-line field; a date carries no identity, and it will be dictated anyway (§7) |
| 12 | The referring clinic is dropped silently | Matching it needs the org list §4 empties, and the result is a name (§9) |
| 13 | `narrowCatalogForOrgType` is extracted and unit tested | `voice.service` has never been unit tested; this is the one decision in it worth pinning (§4, §10) |
| 14 | No new i18n keys | Every voice string is under `treatment.*`, and `CaseCreatePanel` already holds that namespace (§3) |
| 15 | `PERMISSION_EDIT_CASES` is added rather than reusing `PERMISSION_ACCESS_CASES` | The check is on an edit permission; "no access to cases" is false for a `TAB_CASES_READ` holder and points them at the wrong setting (§5) |

View File

@@ -519,6 +519,12 @@
"addCaseTitle": "New case",
"addCaseSubtitle": "Enter the referring clinic or patient, then add prosthesis lines. Start when the case is ready.",
"startCase": "Start",
"stopCase": "Stop",
"confirmStopCase": "Stop this case? Finished work and the current prosthesis plan stay as history, and you can edit the case again.",
"historyTitle": "Previous work",
"historyStoppedAt": "Stopped {date}",
"errorStopCase": "Could not stop the case.",
"errorReopenTask": "Could not set this step back to in progress.",
"draftBadge": "Draft",
"receivedBadge": "Received",
"generatedBadge": "Generated",
@@ -1299,6 +1305,7 @@
"PERMISSION_ACCESS_TASKS": "You do not have access to tasks.",
"PERMISSION_EDIT_TASKS": "You cannot edit tasks.",
"PERMISSION_ACCESS_CASES": "You do not have access to cases.",
"PERMISSION_EDIT_CASES": "You cannot edit cases.",
"PERMISSION_ACCESS_BILLING": "You do not have access to billing.",
"PERMISSION_EDIT_BILLING": "You cannot edit billing for this organization.",
"LAB_CASE_ACCESS_DENIED": "You do not have permission to view this shared case.",
@@ -1431,6 +1438,8 @@
"TREATMENT_HAS_DETAILS": "This treatment has details and cannot be deleted.",
"LAB_CASE_NOT_EDITABLE": "This case can no longer be edited.",
"LAB_CASE_ALREADY_STARTED": "This case has already been started.",
"LAB_CASE_STOP_NOT_ALLOWED": "This case cannot be stopped.",
"TASK_REOPEN_REQUIRES_CASE_EDIT": "Only someone who can edit cases can set a completed step back to in progress.",
"LAB_CASE_LINES_REQUIRED": "Add at least one work line with teeth and a prosthesis type.",
"LAB_CASE_START_INCOMPLETE": "Complete teeth and prosthesis types before starting this case.",
"LAB_CASE_CLIENT_REQUIRED": "Enter a clinic name or a patient name for this case.",

View File

@@ -520,6 +520,12 @@
"addCaseTitle": "پرونده جدید",
"addCaseSubtitle": "کلینیک ارجاع‌دهنده یا بیمار را وارد کنید و خطوط پروتز را اضافه کنید. وقتی آماده بود، شروع کنید.",
"startCase": "شروع",
"stopCase": "توقف",
"confirmStopCase": "این پرونده متوقف شود؟ کار انجام‌شده و طرح پروتز فعلی به‌عنوان سابقه می‌ماند و می‌توانید پرونده را دوباره ویرایش کنید.",
"historyTitle": "کار قبلی",
"historyStoppedAt": "متوقف‌شده {date}",
"errorStopCase": "توقف پرونده انجام نشد.",
"errorReopenTask": "بازگرداندن این مرحله به در حال انجام انجام نشد.",
"draftBadge": "پیش‌نویس",
"receivedBadge": "دریافتی",
"generatedBadge": "ایجادشده",
@@ -1154,7 +1160,7 @@
"category_implant": "ایمپلنت",
"category_post_core": "پست و کور",
"category_removable": "متحرک",
"category_appliance": "اپلاینس‌ها",
"category_appliance": "اپلاینس",
"category_digital": "دیجیتال",
"category_pontic": "پونتیک",
"sub_full_contour": "کانتور کامل",
@@ -1300,6 +1306,7 @@
"PERMISSION_ACCESS_TASKS": "به وظایف دسترسی ندارید.",
"PERMISSION_EDIT_TASKS": "نمی‌توانید وظایف را ویرایش کنید.",
"PERMISSION_ACCESS_CASES": "به پرونده‌ها دسترسی ندارید.",
"PERMISSION_EDIT_CASES": "نمی‌توانید پرونده‌ها را ویرایش کنید.",
"PERMISSION_ACCESS_BILLING": "به صورتحساب دسترسی ندارید.",
"PERMISSION_EDIT_BILLING": "نمی‌توانید صورتحساب این سازمان را ویرایش کنید.",
"LAB_CASE_ACCESS_DENIED": "اجازه مشاهده این پرونده اشتراک‌گذاری‌شده را ندارید.",
@@ -1432,6 +1439,8 @@
"TREATMENT_HAS_DETAILS": "این درمان جزئیات دارد و قابل حذف نیست.",
"LAB_CASE_NOT_EDITABLE": "این پرونده دیگر قابل ویرایش نیست.",
"LAB_CASE_ALREADY_STARTED": "این پرونده قبلاً شروع شده است.",
"LAB_CASE_STOP_NOT_ALLOWED": "این پرونده را نمی‌توان متوقف کرد.",
"TASK_REOPEN_REQUIRES_CASE_EDIT": "فقط کسی که پرونده‌ها را ویرایش می‌کند می‌تواند مرحلهٔ تکمیل‌شده را به در حال انجام برگرداند.",
"LAB_CASE_LINES_REQUIRED": "حداقل یک خط کار با دندان و نوع پروتز اضافه کنید.",
"LAB_CASE_START_INCOMPLETE": "قبل از شروع پرونده، دندان‌ها و نوع پروتز را کامل کنید.",
"LAB_CASE_CLIENT_REQUIRED": "نام کلینیک یا نام بیمار را وارد کنید.",

View File

@@ -520,6 +520,12 @@
"addCaseTitle": "Nieuwe case",
"addCaseSubtitle": "Vul de verwijzende kliniek of patiënt in en voeg protheselijnen toe. Start wanneer de case klaar is.",
"startCase": "Starten",
"stopCase": "Stoppen",
"confirmStopCase": "Deze case stoppen? Afgerond werk en het huidige protheseplan blijven als geschiedenis, en u kunt de case opnieuw bewerken.",
"historyTitle": "Eerder werk",
"historyStoppedAt": "Gestopt {date}",
"errorStopCase": "De case kon niet worden gestopt.",
"errorReopenTask": "Deze stap kon niet terug naar bezig worden gezet.",
"draftBadge": "Concept",
"receivedBadge": "Ontvangen",
"generatedBadge": "Aangemaakt",
@@ -1164,7 +1170,7 @@
"sub_overlay": "Overlay",
"sub_complete_denture": "Volledige prothese",
"sub_partial_denture": "Partiële prothese",
"sub_night_guard": "Nachtbeugel",
"sub_night_guard": "Knarsplaat",
"addonNone": "Geen",
"addonCrownCanBeAdded": "Kroon kan worden toegevoegd",
"addonPonticCanBeAdded": "Pontic kan worden toegevoegd",
@@ -1299,6 +1305,7 @@
"PERMISSION_ACCESS_TASKS": "U hebt geen toegang tot taken.",
"PERMISSION_EDIT_TASKS": "U kunt taken niet bewerken.",
"PERMISSION_ACCESS_CASES": "U hebt geen toegang tot dossiers.",
"PERMISSION_EDIT_CASES": "U kunt dossiers niet bewerken.",
"PERMISSION_ACCESS_BILLING": "U hebt geen toegang tot facturatie.",
"PERMISSION_EDIT_BILLING": "U kunt facturatie voor deze organisatie niet bewerken.",
"LAB_CASE_ACCESS_DENIED": "U hebt geen toestemming om dit gedeelde dossier te bekijken.",
@@ -1431,6 +1438,8 @@
"TREATMENT_HAS_DETAILS": "Deze behandeling heeft details en kan niet worden verwijderd.",
"LAB_CASE_NOT_EDITABLE": "Deze case kan niet meer worden bewerkt.",
"LAB_CASE_ALREADY_STARTED": "Deze case is al gestart.",
"LAB_CASE_STOP_NOT_ALLOWED": "Deze case kan niet worden gestopt.",
"TASK_REOPEN_REQUIRES_CASE_EDIT": "Alleen iemand die cases mag bewerken kan een voltooide stap terugzetten naar bezig.",
"LAB_CASE_LINES_REQUIRED": "Voeg minstens één werkregel toe met tanden en een prothesetype.",
"LAB_CASE_START_INCOMPLETE": "Vul tanden en prothesetypes in voordat u deze case start.",
"LAB_CASE_CLIENT_REQUIRED": "Voer een klinieknaam of een patiëntnaam in voor deze case.",

View File

@@ -67,7 +67,7 @@ export function buildCaseProsthesisRows(
})),
);
}
return labCase.tasksByTooth.map((g) => ({
return labCase.tasksByTooth.filter((g) => g.prosthesisTypeCode !== '__case__').map((g) => ({
prosthesisTypeCode: g.prosthesisTypeCode,
teeth: g.teeth,
selectionGroupId: g.selectionGroupId,

View File

@@ -0,0 +1,48 @@
import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups';
import type { LabCaseAttachmentMeta } from '@/types/cases';
import type { FdiToothId } from '@/types/treatment';
/**
* One editable case line. Against a clinic `TreatmentDetailDraft` it carries no treatment type
* — the lab side is always `prosthesis`, written server-side — and folds the clinic's separate
* lab-case rows into `toothProsthesis` on the line itself.
*/
export type LineDraft = {
clientId: string;
id?: string;
teeth: FdiToothId[];
toothSelectionGroups: ToothSelectionGroup[];
comment: string;
toothProsthesis: Array<{
tooth: string;
prosthesisTypeCode: string;
selectionGroupId?: string;
detailClientId: string;
}>;
attachments: LabCaseAttachmentMeta[];
};
export function newLine(): LineDraft {
const clientId =
typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `line-${Date.now()}`;
return {
clientId,
teeth: [],
toothSelectionGroups: [],
comment: '',
toothProsthesis: [],
attachments: [],
};
}
/** Exactly the state `newLine` produces — what a dictation may overwrite instead of appending. */
export function isBlankLine(line: LineDraft): boolean {
return (
line.teeth.length === 0 &&
line.toothProsthesis.length === 0 &&
line.comment.trim() === '' &&
line.attachments.length === 0
);
}

View File

@@ -3,11 +3,12 @@ import type { BadgeVariant } from '@/components/ui/shared/Badge';
import type { LabTaskListItem, LabTaskStatus } from '@/types/cases';
export function canEditLabTaskStatus(
task: Pick<LabTaskListItem, 'assignee'>,
task: Pick<LabTaskListItem, 'assignee' | 'status'>,
currentUserId: string | undefined,
canEditTasks: boolean,
): boolean {
if (!canEditTasks || !currentUserId) return false;
if (task.status === 'COMPLETED') return false;
if (!task.assignee) return true;
return task.assignee.id === currentUserId;
}

View File

@@ -10,6 +10,19 @@ export type ProsthesisTaskGroup = {
tasks: LabTaskListItem[];
};
/** Matches backend `CASE_TASK_SCOPE` on newly generated case-level tasks. */
export const CASE_TASK_SCOPE = '__case__';
const CASE_LEVEL_LEADING = new Set(['intraoral_scan']);
const CASE_LEVEL_TRAILING = ['packing', 'shipping'];
export function isCaseLevelTask(task: {
sourceKey?: string | null;
prosthesisTypeCode?: string | null;
}): boolean {
return task.sourceKey === CASE_TASK_SCOPE || task.prosthesisTypeCode === CASE_TASK_SCOPE;
}
export type CaseTaskGroup = {
labCaseId: string;
clinic: LabTaskListItem['clinic'];
@@ -19,7 +32,9 @@ export type CaseTaskGroup = {
isCaseOverdue: boolean;
isImportant: boolean;
origin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL';
leadingTasks: LabTaskListItem[];
prosthesisGroups: ProsthesisTaskGroup[];
trailingTasks: LabTaskListItem[];
};
export type TaskDisplayModel =
@@ -55,11 +70,21 @@ export function groupTasksForDisplay(
isCaseOverdue: task.isCaseOverdue,
isImportant: task.isImportant,
origin: task.origin,
leadingTasks: [],
prosthesisGroups: [],
trailingTasks: [],
});
}
const caseGroup = cases[caseIdx];
if (isCaseLevelTask(task)) {
if (CASE_LEVEL_LEADING.has(task.workflowStepCode)) {
caseGroup.leadingTasks.push(task);
} else {
caseGroup.trailingTasks.push(task);
}
continue;
}
const pgKey = prosthesisGroupKey(task);
let prosthesisGroup = caseGroup.prosthesisGroups.find((g) => g.key === pgKey);
if (!prosthesisGroup) {
@@ -78,6 +103,17 @@ export function groupTasksForDisplay(
prosthesisGroup.tasks.push(task);
}
for (const caseGroup of cases) {
caseGroup.prosthesisGroups.sort(
(a, b) => Number(a.prosthesisTypeCode.includes('+')) - Number(b.prosthesisTypeCode.includes('+')),
);
caseGroup.trailingTasks.sort(
(a, b) =>
CASE_LEVEL_TRAILING.indexOf(a.workflowStepCode) -
CASE_LEVEL_TRAILING.indexOf(b.workflowStepCode),
);
}
return { mode: 'grouped', cases };
}
@@ -87,11 +123,14 @@ export function countCaseTaskProgress(caseGroup: CaseTaskGroup): {
} {
let completed = 0;
let total = 0;
for (const group of caseGroup.prosthesisGroups) {
for (const task of group.tasks) {
total += 1;
if (task.status === 'COMPLETED') completed += 1;
}
const all = [
...caseGroup.leadingTasks,
...caseGroup.prosthesisGroups.flatMap((group) => group.tasks),
...caseGroup.trailingTasks,
];
for (const task of all) {
total += 1;
if (task.status === 'COMPLETED') completed += 1;
}
return { completed, total };
}

View File

@@ -0,0 +1,300 @@
import { describe, expect, it } from 'vitest';
import { ARCH_TOOTH_UPPER, isArchSentinel } from '@/components/treatment/prosthesisTree';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice';
import { isBlankLine, newLine } from './caseLineDraft';
import { buildLabLineFromVoice } from './voiceLine';
const CATALOG: ProsthesisCatalogEntry[] = [
{
code: 'pfm_crown',
sortOrder: 1,
label: 'PFM Crown',
category: 'crown',
subcategory: '',
chartRegion: 'crown',
stackGroup: 'restoration',
},
{
code: 'cast_post_core',
sortOrder: 2,
label: 'Cast Post & Core',
category: 'post_core',
subcategory: '',
chartRegion: 'root',
stackGroup: 'post_core',
},
{
code: 'complete_denture',
sortOrder: 3,
label: 'Complete Denture',
category: 'denture',
subcategory: '',
chartRegion: 'arch',
stackGroup: 'arch',
},
];
const ctx = { prosthesisCatalog: CATALOG };
const result = (overrides: Partial<VoiceExtractionResult> = {}): VoiceExtractionResult => ({
treatmentType: null,
teeth: [],
toothSelectionGroups: [],
comment: null,
prosthesisAssignments: [],
labId: null,
labMatchExact: false,
dueDate: null,
unresolved: [],
...overrides,
});
const allTicked: VoiceApplySelection = {
treatmentType: true,
teeth: true,
comment: true,
prosthesis: true,
lab: true,
dueDate: true,
};
const tick = (overrides: Partial<VoiceApplySelection> = {}): VoiceApplySelection => ({
...allTicked,
...overrides,
});
/** Narrows the nullable line and fails loudly when the dictation produced nothing. */
function built(out: ReturnType<typeof buildLabLineFromVoice>) {
if (!out.line) throw new Error('expected a line, got null');
return out.line;
}
describe('buildLabLineFromVoice — which teeth reach the line', () => {
it('puts a tooth on the line only when it carries a job', () => {
const line = built(buildLabLineFromVoice(
result({
teeth: ['12', '14', '16'],
prosthesisAssignments: [{ targets: ['12', '14'], types: ['pfm_crown'], spoken: '' }],
}),
tick(),
ctx,
));
expect(line.teeth).toEqual(['12', '14']);
});
it('never copies the plain teeth list across, so bare teeth build no line', () => {
const out = buildLabLineFromVoice(result({ teeth: ['21', '22'] }), tick(), ctx);
expect(out.line).toBeNull();
});
it('leaves a target off the line when every code it named was refused', () => {
const out = buildLabLineFromVoice(
result({
teeth: ['12'],
// Not in the catalog, so the stack rules refuse it and nothing lands.
prosthesisAssignments: [{ targets: ['12'], types: ['not_in_catalog'], spoken: '' }],
}),
tick(),
ctx,
);
expect(out.line).toBeNull();
});
it('keeps the invariant nothing enforces server-side: every job names a tooth on the line', () => {
const line = built(buildLabLineFromVoice(
result({
teeth: ['16'],
prosthesisAssignments: [
{ targets: ['12', '13'], types: ['pfm_crown'], spoken: '' },
{ targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' },
],
}),
tick(),
ctx,
));
const onTeeth = line.toothProsthesis
.filter((row) => !isArchSentinel(row.tooth))
.map((row) => row.tooth);
expect(onTeeth.length).toBeGreaterThan(0);
for (const tooth of onTeeth) {
expect(line.teeth).toContain(tooth);
}
});
});
describe('buildLabLineFromVoice — prosthesis rows', () => {
it('applies a stack in landing order and drops a code the stack rules refuse', () => {
const line = built(buildLabLineFromVoice(
result({
prosthesisAssignments: [
// A post & core cannot go under a crown that is already there.
{ targets: ['12'], types: ['pfm_crown', 'cast_post_core'], spoken: '' },
],
}),
tick(),
ctx,
));
expect(line.toothProsthesis.map((row) => row.prosthesisTypeCode)).toEqual(['pfm_crown']);
});
it('carries a jaw appliance with an empty selection group and adds no tooth', () => {
const line = built(buildLabLineFromVoice(
result({
prosthesisAssignments: [
{ targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' },
],
}),
tick(),
ctx,
));
expect(line.toothProsthesis).toEqual([
{
detailClientId: line.clientId,
tooth: ARCH_TOOTH_UPPER,
prosthesisTypeCode: 'complete_denture',
selectionGroupId: '',
},
]);
expect(line.teeth).toEqual([]);
});
it('never gives two non-adjacent teeth the same selection group', () => {
const line = built(buildLabLineFromVoice(
result({
// Dictated as one connected span, but 12 and 16 are not neighbours: a shared group id
// would tell the task generator to build a bridge across the gap.
toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '16'] }],
prosthesisAssignments: [{ targets: ['12', '16'], types: ['pfm_crown'], spoken: '' }],
}),
tick(),
ctx,
));
const groupOf = (tooth: string) =>
line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId;
expect(groupOf('12')).toBeTruthy();
expect(groupOf('16')).toBeTruthy();
expect(groupOf('12')).not.toBe(groupOf('16'));
});
it('keeps adjacent teeth dictated as a bridge in one selection group', () => {
const line = built(buildLabLineFromVoice(
result({
toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '13'] }],
prosthesisAssignments: [{ targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }],
}),
tick(),
ctx,
));
const groupOf = (tooth: string) =>
line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId;
expect(groupOf('12')).toBe(groupOf('13'));
});
it('builds no line at all when the prosthesis row is unticked', () => {
const out = buildLabLineFromVoice(
result({
prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }],
}),
tick({ prosthesis: false }),
ctx,
);
expect(out.line).toBeNull();
});
});
describe('buildLabLineFromVoice — the note and the due date', () => {
it('takes the note when its row is ticked', () => {
const line = built(buildLabLineFromVoice(result({ comment: 'shade A2' }), tick(), ctx));
expect(line.comment).toBe('shade A2');
});
it('builds no line when the note row is unticked and nothing else was dictated', () => {
const out = buildLabLineFromVoice(
result({ comment: 'shade A2' }),
tick({ comment: false }),
ctx,
);
expect(out.line).toBeNull();
});
it('returns a due-date-only dictation as a date and NO line', () => {
// The bug the correctness critic found: this used to return a blank line, which the
// panel appended and autosaved. `start` only requires that *some* line carries jobs,
// so the empty line shipped to the floor (decision 9).
const out = buildLabLineFromVoice(result({ dueDate: '2026-09-24' }), tick(), ctx);
expect(out.dueDate).toBe('2026-09-24');
expect(out.line).toBeNull();
});
it('still returns the line when a due date rides along with real work', () => {
const out = buildLabLineFromVoice(
result({
dueDate: '2026-09-24',
prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }],
}),
tick(),
ctx,
);
expect(out.dueDate).toBe('2026-09-24');
expect(out.line?.teeth).toEqual(['12']);
});
it('returns a null due date when its row is unticked', () => {
const out = buildLabLineFromVoice(
result({ dueDate: '2026-09-24' }),
tick({ dueDate: false }),
ctx,
);
expect(out.dueDate).toBeNull();
});
it('writes no lab destination anywhere, even with a labId and its row ticked', () => {
const out = buildLabLineFromVoice(
result({
labId: 'org-clinic-1',
labMatchExact: true,
prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }],
}),
tick(),
ctx,
);
expect(JSON.stringify(out)).not.toContain('org-clinic-1');
});
});
describe('isBlankLine — whether a dictation fills the active line or appends', () => {
it('is true for the exact state newLine produces', () => {
expect(isBlankLine(newLine())).toBe(true);
});
it('is false once the line carries teeth, a job, a comment or an attachment', () => {
expect(isBlankLine({ ...newLine(), teeth: ['12'] })).toBe(false);
expect(
isBlankLine({
...newLine(),
toothProsthesis: [
{ tooth: '12', prosthesisTypeCode: 'pfm_crown', detailClientId: 'x' },
],
}),
).toBe(false);
expect(isBlankLine({ ...newLine(), comment: 'shade A2' })).toBe(false);
expect(
isBlankLine({
...newLine(),
attachments: [
{
id: 'a1',
fileName: 'x.png',
mimeType: 'image/png',
sizeBytes: 1,
createdAt: '2026-09-16',
} as never,
],
}),
).toBe(false);
});
it('is true for a line whose only content is whitespace', () => {
expect(isBlankLine({ ...newLine(), comment: ' ' })).toBe(true);
});
});

View File

@@ -0,0 +1,74 @@
import { groupsFromFlatTeeth } from '@/components/treatment/toothSelectionGroups';
import { prosthesisTargetLines } from '@/components/treatment/voiceReviewRows';
import type { FdiToothId } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice';
import { isBlankLine, newLine, type LineDraft } from './caseLineDraft';
export interface VoiceLineContext {
prosthesisCatalog: readonly ProsthesisCatalogEntry[];
}
/**
* Turns a confirmed review sheet into one case line, plus the case's due date.
*
* A sibling of `buildVoiceApplyPlan` rather than a mode on it — the return shapes share
* nothing — but both go through `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the
* stack rules and the bridge splitting stay in one place.
*
* The due date comes back separately because it belongs to the case header, not to the line.
*
* `line` is null when the dictation produced no line content. A due-date-only dictation, or one
* whose codes were all refused, must not append an empty line: `start` only requires that *some*
* line carries jobs, so an empty one ships to the floor (decision 9).
*/
export function buildLabLineFromVoice(
result: VoiceExtractionResult,
selection: VoiceApplySelection,
ctx: VoiceLineContext,
): { line: LineDraft | null; dueDate: string | null } {
const line = newLine();
if (selection.comment && result.comment) {
line.comment = result.comment;
}
// The stack that will actually land, built through the same `applyLeafToJobs` the manual
// chart writes through — a code the stack rules refuse is not applied.
const targetLines = selection.prosthesis
? prosthesisTargetLines(result.prosthesisAssignments, ctx.prosthesisCatalog)
: [];
// A tooth is on the line only by carrying a job (decision 40). The plain `teeth` list is
// never copied across: the lab write validates only the prosthesis code, so a line whose
// teeth and jobs disagree would be saved silently and the generated tasks would not match
// the chart.
const teeth = targetLines
.filter((target) => !target.isJaw && target.applied.length > 0)
.map((target) => target.target as FdiToothId);
line.teeth = teeth;
// Seeded from the dictated groups, so `splitDisconnectedRuns` runs: on this side a shared
// group id tells the task generator to build a bridge across the gap.
line.toothSelectionGroups = groupsFromFlatTeeth(teeth, result.toothSelectionGroups);
line.toothProsthesis = targetLines.flatMap((target) => {
// A jaw appliance belongs to no selection group; a tooth takes the group it landed in.
const selectionGroupId = target.isJaw
? ''
: (line.toothSelectionGroups.find((group) =>
(group.teeth as readonly string[]).includes(target.target),
)?.groupId ?? '');
return target.applied.map((prosthesisTypeCode) => ({
detailClientId: line.clientId,
tooth: target.target,
prosthesisTypeCode,
selectionGroupId,
}));
});
return {
line: isBlankLine(line) ? null : line,
dueDate: selection.dueDate && result.dueDate ? result.dueDate : null,
};
}

View File

@@ -425,3 +425,59 @@ describe('hasAnythingToApply', () => {
expect(hasAnythingToApply(baseResult({ teeth: ['14'] }), LAB_DEPENDENT)).toBe(true);
});
});
describe('voiceRowAvailability in lab mode', () => {
// A lab line has no treatment type at all, so the derived labDependent flag would be false
// and the rows would come out exactly backwards.
const labResult = baseResult({
treatmentType: null,
teeth: ['12'],
prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }],
});
it('shows the merged teeth-and-prosthesis row even with no treatment type', () => {
const available = voiceRowAvailability(labResult, LAB_DEPENDENT, 'lab');
expect(available.prosthesis).toBe(true);
expect(available.teeth).toBe(false);
});
it('never shows the treatment type row, even when one was resolved', () => {
const forced = baseResult({ treatmentType: 'prosthesis' });
expect(voiceRowAvailability(forced, LAB_DEPENDENT, 'lab').treatmentType).toBe(false);
expect(voiceRowAvailability(forced, LAB_DEPENDENT).treatmentType).toBe(true);
});
it('never shows the lab row, even when a labId came back', () => {
const withLab = baseResult({ labId: 'org-1' });
expect(voiceRowAvailability(withLab, LAB_DEPENDENT, 'lab').lab).toBe(false);
expect(voiceRowAvailability(withLab, LAB_DEPENDENT).lab).toBe(true);
});
it('keeps the note and due date rows on the same when-heard rule', () => {
const heard = baseResult({ comment: 'shade A2', dueDate: '2026-09-24' });
const available = voiceRowAvailability(heard, LAB_DEPENDENT, 'lab');
expect(available.comment).toBe(true);
expect(available.dueDate).toBe(true);
const silent = voiceRowAvailability(baseResult(), LAB_DEPENDENT, 'lab');
expect(silent.comment).toBe(false);
expect(silent.dueDate).toBe(false);
});
it('ticks the prosthesis row and nothing clinic-only by default', () => {
const selection = initialVoiceSelection(labResult, LAB_DEPENDENT, 'lab');
expect(selection.prosthesis).toBe(true);
expect(selection.treatmentType).toBe(false);
expect(selection.teeth).toBe(false);
expect(selection.lab).toBe(false);
});
it('still reports a recording that produced nothing usable', () => {
expect(hasAnythingToApply(baseResult(), LAB_DEPENDENT, 'lab')).toBe(false);
});
it('defaults to clinic mode when no mode is given', () => {
expect(voiceRowAvailability(labResult, LAB_DEPENDENT)).toEqual(
voiceRowAvailability(labResult, LAB_DEPENDENT, 'clinic'),
);
});
});

View File

@@ -25,6 +25,7 @@ import type { FdiToothId } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type {
VoiceApplySelection,
VoiceEntryMode,
VoiceExtractionResult,
VoiceProsthesisAssignment,
VoiceUnresolvedItem,
@@ -52,14 +53,19 @@ function hasProsthesisWork(result: VoiceExtractionResult): boolean {
export function voiceRowAvailability(
result: VoiceExtractionResult,
labDependentCodes: ReadonlySet<string>,
mode: VoiceEntryMode = 'clinic',
) {
const labDependent = isLabDependentResult(result, labDependentCodes);
const isLab = mode === 'lab';
// A lab line is always prosthesis work, and the catalog it was extracted against carries no
// treatment types at all — so the derived flag would be false and the rows exactly backwards:
// the plain teeth row shown, the merged prosthesis row hidden (decision 6).
const labDependent = isLab || isLabDependentResult(result, labDependentCodes);
return {
treatmentType: result.treatmentType != null,
treatmentType: !isLab && result.treatmentType != null,
teeth: !labDependent && result.teeth.length > 0,
prosthesis: labDependent && (result.teeth.length > 0 || hasProsthesisWork(result)),
comment: Boolean(result.comment?.trim()),
lab: result.labId != null,
lab: !isLab && result.labId != null,
dueDate: result.dueDate != null,
};
}
@@ -72,8 +78,9 @@ export function voiceRowAvailability(
export function initialVoiceSelection(
result: VoiceExtractionResult,
labDependentCodes: ReadonlySet<string>,
mode: VoiceEntryMode = 'clinic',
): VoiceApplySelection {
const available = voiceRowAvailability(result, labDependentCodes);
const available = voiceRowAvailability(result, labDependentCodes, mode);
return {
treatmentType: available.treatmentType,
teeth: available.teeth,
@@ -399,8 +406,9 @@ export function unresolvedForAssignment(
export function hasAnythingToApply(
result: VoiceExtractionResult,
labDependentCodes: ReadonlySet<string>,
mode: VoiceEntryMode = 'clinic',
): boolean {
return Object.values(voiceRowAvailability(result, labDependentCodes)).some(Boolean);
return Object.values(voiceRowAvailability(result, labDependentCodes, mode)).some(Boolean);
}
export { archSentinels, allAssignmentTargets };

View File

@@ -1,14 +1,15 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Trash2 } from 'lucide-react';
import { useLocale, useTranslations } from 'next-intl';
import { Mic, Square, Trash2 } from 'lucide-react';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import {
invalidPonticTeethOnDetail,
toothJobRowsForDetail,
} from '@/components/treatment/prosthesisTree';
import { CaseHistoryRounds } from '@/components/ui/lab/CaseHistoryRounds';
import { LabCaseToothJobsList } from '@/components/ui/lab/LabCaseProsthesisGroupsList';
import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles';
import {
@@ -20,52 +21,33 @@ import {
pruneToothProsthesisForGroups,
toothEdgeKey,
unlinkAdjacentTeeth,
type ToothSelectionGroup,
} from '@/components/treatment/toothSelectionGroups';
import { AppDateInput } from '@/components/ui/shared/AppDateInput';
import { Button } from '@/components/ui/shared/Button';
import { ProsthesisAssignChart } from '@/components/ui/treatment/ProsthesisAssignChart';
import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar';
import { VoiceReviewSheet } from '@/components/ui/treatment/VoiceReviewSheet';
import { isBlankLine, newLine, type LineDraft } from '@/components/lab/caseLineDraft';
import { toDateInputValue } from '@/components/lab/labCaseDueDateDisplay';
import { buildLabLineFromVoice } from '@/components/lab/voiceLine';
import { casesApi } from '@/lib/api/cases';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import type { LabCaseAttachmentMeta, LabCaseDetail } from '@/types/cases';
import { voiceApi } from '@/lib/api/voice';
import { isMediaRecorderSupported } from '@/lib/voice/audioFormat';
import { useVoiceCapture, type VoiceCaptureState } from '@/lib/voice/useVoiceCapture';
import type { LabCaseDetail } from '@/types/cases';
import type { FdiToothId } from '@/types/treatment';
import type { LinkedOrganizationOption } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type {
VoiceApplySelection,
VoiceAvailability,
VoiceExtractionResult,
} from '@/types/voice';
const INPUT_CLASS =
'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35';
type LineDraft = {
clientId: string;
id?: string;
teeth: FdiToothId[];
toothSelectionGroups: ToothSelectionGroup[];
comment: string;
toothProsthesis: Array<{
tooth: string;
prosthesisTypeCode: string;
selectionGroupId?: string;
detailClientId: string;
}>;
attachments: LabCaseAttachmentMeta[];
};
function newLine(): LineDraft {
const clientId =
typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `line-${Date.now()}`;
return {
clientId,
teeth: [],
toothSelectionGroups: [],
comment: '',
toothProsthesis: [],
attachments: [],
};
}
function linesFromDetail(labCase: LabCaseDetail): LineDraft[] {
const source = labCase.lines ?? [];
if (source.length === 0) return [newLine()];
@@ -116,6 +98,7 @@ export function CaseCreatePanel({
const tTreatment = useTranslations('treatment');
const tErrors = useTranslations('errors');
const tCommon = useTranslations('common');
const locale = useLocale();
const [referringClinicName, setReferringClinicName] = useState(
labCase.referringClinicName ?? '',
@@ -139,6 +122,8 @@ export function CaseCreatePanel({
const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>(
prosthesisCatalog ?? [],
);
const [voiceAvailability, setVoiceAvailability] = useState<VoiceAvailability | null>(null);
const [voiceResult, setVoiceResult] = useState<VoiceExtractionResult | null>(null);
const [saving, setSaving] = useState(false);
const [starting, setStarting] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -170,6 +155,7 @@ export function CaseCreatePanel({
useEffect(() => {
void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined);
void voiceApi.availability().then((r) => setVoiceAvailability(r.data)).catch(() => undefined);
}, []);
useEffect(() => {
@@ -180,6 +166,24 @@ export function CaseCreatePanel({
void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined);
}, [prosthesisCatalog]);
const voice = useVoiceCapture({
// The locale the lab owner is reading and speaking in, so the ASR hint, the catalog labels
// and the week start all match what the microphone was offered for.
locale,
maxMs: voiceAvailability?.maxRecordingMs ?? null,
onExtracted: setVoiceResult,
onError: (error) =>
onError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))),
});
// Absence renders the Add Line button unsplit. Gated on the browser's own recording support
// as well as the server config: without it the control appears on a browser that cannot
// record and fails on tap.
const voiceEnabled =
Boolean(voiceAvailability?.enabled) &&
(voiceAvailability?.locales.includes(locale) ?? false) &&
isMediaRecorderSupported();
const activeLine = lines.find((l) => l.clientId === activeLineId) ?? lines[0];
const groups =
activeLine?.toothSelectionGroups.length
@@ -293,12 +297,60 @@ export function CaseCreatePanel({
return () => clearTimeout(timeout);
}, [buildPayload, canEdit]);
function addLine() {
const line = newLine();
setLines((prev) => [...prev, line]);
setActiveLineId(line.clientId);
}
function updateActiveLine(patch: (line: LineDraft) => LineDraft) {
setLines((prev) =>
prev.map((line) => (line.clientId === activeLine?.clientId ? patch(line) : line)),
);
}
/**
* One dictation is one line. It fills the active line while that line is still blank — a
* fresh draft opens with one, and always appending would leave it above the dictated line
* and ship it to the floor, since `start` only requires that *some* line carries jobs.
*/
function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) {
const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, {
prosthesisCatalog: prosthesisOptions,
});
setVoiceResult(null);
if (dictatedDueDate) setDueDate(dictatedDueDate);
// Null when the dictation carried no line content — a due date on its own still lands.
// Without the notice, Apply on a row that lands no job closes the sheet and changes nothing.
if (!line) {
if (!dictatedDueDate) onError(tTreatment('voiceNothingExtracted'));
return;
}
const target = activeLine;
if (target && isBlankLine(target)) {
setLines((prev) =>
prev.map((l) =>
l.clientId === target.clientId
? {
...line,
// Keep the line's identity: it may already have been saved once.
clientId: target.clientId,
id: target.id,
toothProsthesis: line.toothProsthesis.map((tp) => ({
...tp,
detailClientId: target.clientId,
})),
}
: l,
),
);
return;
}
setLines((prev) => [...prev, line]);
setActiveLineId(line.clientId);
}
async function handleDelete() {
if (!canEdit) return;
if (!window.confirm(t('confirmDeleteDraftCase'))) return;
@@ -463,20 +515,25 @@ export function CaseCreatePanel({
</label>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-semibold text-text-primary">{t('caseLinesTitle')}</p>
<Button
type="button"
variant="primary"
disabled={disabled}
onClick={() => {
const line = newLine();
setLines((prev) => [...prev, line]);
setActiveLineId(line.clientId);
}}
>
{t('addLine')}
</Button>
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-semibold text-text-primary">{t('caseLinesTitle')}</p>
{voiceEnabled ? (
<AddLineWithVoice
addLabel={t('addLine')}
startLabel={tTreatment('voiceStart')}
stopLabel={tTreatment('voiceStop')}
disabled={disabled}
onAddLine={addLine}
voice={voice}
/>
) : (
<Button type="button" variant="primary" disabled={disabled} onClick={addLine}>
{t('addLine')}
</Button>
)}
</div>
{voiceEnabled ? <VoiceRecordingBar voice={voice} /> : null}
</div>
<div className="flex flex-wrap gap-2">
@@ -623,6 +680,84 @@ export function CaseCreatePanel({
</div>
</>
) : null}
{voiceResult ? (
<VoiceReviewSheet
mode="lab"
result={voiceResult}
prosthesisCatalog={prosthesisOptions}
onApply={(selection, applied) => applyVoice(selection, applied)}
onDiscard={() => setVoiceResult(null)}
/>
) : null}
<CaseHistoryRounds
rounds={labCase.historyRounds ?? []}
locale={locale}
prosthesisCatalog={prosthesisOptions}
statusOptions={[
{ value: 'IN_PROGRESS', label: t('statusInProgress') },
{ value: 'COMPLETED', label: t('statusCompleted') },
]}
/>
</div>
);
}
/**
* "Add line", split into two segments with the microphone at the logical end — built like the
* clinic's `AddDetailWithVoice`, out of two raw buttons rather than two shared `Button`s, which
* hardcode their own rounding and would fight a segmented control.
*/
function AddLineWithVoice({
addLabel,
startLabel,
stopLabel,
disabled,
onAddLine,
voice,
}: {
addLabel: string;
startLabel: string;
stopLabel: string;
disabled: boolean;
onAddLine: () => void;
voice: VoiceCaptureState;
}) {
const isRecording = voice.phase === 'recording';
const isBusy = voice.phase !== 'idle';
const micLabel = isRecording ? stopLabel : startLabel;
return (
<div
className={`inline-flex items-stretch overflow-hidden rounded-[var(--radius-md)] bg-primary text-white shrink-0 ${
disabled ? 'opacity-60' : ''
}`}
>
<button
type="button"
onClick={onAddLine}
disabled={disabled || isBusy}
className="px-4 py-2 text-sm font-medium transition-all duration-200 hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-white/60 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:opacity-60"
>
{addLabel}
</button>
<button
type="button"
onClick={isRecording ? voice.onStop : voice.onStart}
disabled={disabled || voice.phase === 'processing'}
title={micLabel}
aria-label={micLabel}
className={`inline-flex items-center justify-center border-s border-white/25 px-3 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-white/60 disabled:cursor-not-allowed disabled:opacity-60 ${
isRecording ? 'bg-red-600 hover:bg-red-700' : 'hover:opacity-90'
}`}
>
{isRecording ? (
<Square className="h-4 w-4 fill-current" aria-hidden />
) : (
<Mic className="h-4 w-4" aria-hidden />
)}
</button>
</div>
);
}

View File

@@ -29,9 +29,118 @@ import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge';
import { useToast } from '@/lib/hooks/useToast';
import { formatAppMoney } from '@/lib/i18n/format';
import type { AssignableTaskStaff, LabCaseDetail, LabTaskStatus } from '@/types/cases';
import { CASE_TASK_SCOPE } from '@/components/lab/taskListGrouping';
import { CaseHistoryRounds } from '@/components/ui/lab/CaseHistoryRounds';
import type { AssignableTaskStaff, LabCaseDetail, LabCaseTask, LabTaskStatus } from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
function CurrentRoundTaskStatus({
task,
statusOptions,
canReopenTasks,
reopeningTaskId,
onReopenTask,
}: {
task: LabCaseTask;
statusOptions: { value: LabTaskStatus; label: string }[];
canReopenTasks?: boolean;
reopeningTaskId?: string | null;
onReopenTask?: (taskId: string) => void;
}) {
const t = useTranslations('cases');
if (canReopenTasks && task.status === 'COMPLETED' && onReopenTask) {
return (
<Button
type="button"
variant="outline"
size="sm"
isLoading={reopeningTaskId === task.id}
onClick={() => onReopenTask(task.id)}
>
{t('statusInProgress')}
</Button>
);
}
return (
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ?? task.status}
</Badge>
);
}
function CaseLevelTaskList({
tasks,
statusOptions,
canAssignTasks,
assigningTaskId,
onAssignTask,
assignableStaff,
canReopenTasks,
reopeningTaskId,
onReopenTask,
}: {
tasks: LabCaseTask[];
statusOptions: { value: LabTaskStatus; label: string }[];
canAssignTasks: boolean;
assigningTaskId: string | null;
onAssignTask?: (taskId: string, assigneeUserId: string | null) => void;
assignableStaff: AssignableTaskStaff[];
canReopenTasks?: boolean;
reopeningTaskId?: string | null;
onReopenTask?: (taskId: string) => void;
}) {
const t = useTranslations('cases');
const locale = useLocale();
if (tasks.length === 0) return null;
return (
<ul className="space-y-2">
{tasks.map((task) => (
<li key={task.id} className="rounded-md border border-border bg-background px-2 py-1.5 text-sm">
<div className="flex flex-col gap-1.5 sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-2 sm:gap-y-1">
<span className="min-w-0 flex-1 font-medium text-text-primary">
{task.stepOrder}. {task.stepLabel}
</span>
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-text-muted shrink-0">
{task.lastStatusChangedBy
? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
: t('lastUpdatedUnknown')}
{task.lastStatusChangedAt
? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
: ''}
</span>
{canAssignTasks && onAssignTask ? (
<select
value={task.assignee?.id ?? ''}
disabled={assigningTaskId === task.id}
onChange={(e) => onAssignTask(task.id, e.target.value ? e.target.value : null)}
aria-label={t('assigneeLabel')}
className={`${FORM_SELECT_CLASS} max-w-[9.5rem] rounded-md py-0.5 text-xs`}
>
<option value="">{t('assigneeUnassigned')}</option>
{assignableStaff.map((staff) => (
<option key={staff.id} value={staff.id}>
{staff.name}
</option>
))}
</select>
) : null}
<CurrentRoundTaskStatus
task={task}
statusOptions={statusOptions}
canReopenTasks={canReopenTasks}
reopeningTaskId={reopeningTaskId}
onReopenTask={onReopenTask}
/>
</div>
</div>
</li>
))}
</ul>
);
}
function CaseTaskProgressBar({ completed, total }: { completed: number; total: number }) {
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
@@ -74,6 +183,12 @@ export interface CaseDetailPanelProps {
canAssignTasks?: boolean;
assigningTaskId?: string | null;
onAssignTask?: (taskId: string, assigneeUserId: string | null) => void;
canReopenTasks?: boolean;
reopeningTaskId?: string | null;
onReopenTask?: (taskId: string) => void;
canStop?: boolean;
stopping?: boolean;
onStop?: () => void;
prosthesisCatalog?: ProsthesisCatalogEntry[];
}
@@ -97,6 +212,12 @@ export function CaseDetailPanel({
canAssignTasks = false,
assigningTaskId = null,
onAssignTask,
canReopenTasks = false,
reopeningTaskId = null,
onReopenTask,
canStop = false,
stopping = false,
onStop,
prosthesisCatalog: prosthesisCatalogProp,
}: CaseDetailPanelProps) {
const t = useTranslations('cases');
@@ -260,6 +381,11 @@ export function CaseDetailPanel({
: t('showComments')}
</Button>
) : null}
{canStop && onStop ? (
<Button type="button" variant="danger" size="sm" isLoading={stopping} onClick={onStop}>
{t('stopCase')}
</Button>
) : null}
<Button
type="button"
variant="outline"
@@ -328,7 +454,25 @@ export function CaseDetailPanel({
{labCase.tasksByTooth.length === 0 ? (
<p className="text-sm text-text-muted">{t('noTasks')}</p>
) : (
labCase.tasksByTooth.map((group) => (
<>
<CaseLevelTaskList
tasks={
labCase.tasksByTooth
.find((group) => group.prosthesisTypeCode === CASE_TASK_SCOPE)
?.tasks.filter((task) => task.workflowStepCode === 'intraoral_scan') ?? []
}
statusOptions={statusOptions}
canAssignTasks={canAssignTasks}
assigningTaskId={assigningTaskId}
onAssignTask={onAssignTask}
assignableStaff={assignableStaff}
canReopenTasks={canReopenTasks}
reopeningTaskId={reopeningTaskId}
onReopenTask={onReopenTask}
/>
{labCase.tasksByTooth
.filter((group) => group.prosthesisTypeCode !== CASE_TASK_SCOPE)
.map((group) => (
<div
key={`${group.treatmentDetailId}-${group.selectionGroupId ?? ''}-${group.prosthesisTypeCode}`}
className="rounded-md border border-border p-3 space-y-2"
@@ -377,20 +521,50 @@ export function CaseDetailPanel({
))}
</select>
) : null}
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
<CurrentRoundTaskStatus
task={task}
statusOptions={statusOptions}
canReopenTasks={canReopenTasks}
reopeningTaskId={reopeningTaskId}
onReopenTask={onReopenTask}
/>
</div>
</div>
</li>
))}
</ul>
</div>
))
))}
<CaseLevelTaskList
tasks={(
labCase.tasksByTooth
.find((group) => group.prosthesisTypeCode === CASE_TASK_SCOPE)
?.tasks.filter((task) => task.workflowStepCode !== 'intraoral_scan') ?? []
).sort(
(a, b) =>
['packing', 'shipping'].indexOf(a.workflowStepCode ?? '') -
['packing', 'shipping'].indexOf(b.workflowStepCode ?? ''),
)}
statusOptions={statusOptions}
canAssignTasks={canAssignTasks}
assigningTaskId={assigningTaskId}
onAssignTask={onAssignTask}
assignableStaff={assignableStaff}
canReopenTasks={canReopenTasks}
reopeningTaskId={reopeningTaskId}
onReopenTask={onReopenTask}
/>
</>
)}
</div>
<CaseHistoryRounds
rounds={labCase.historyRounds ?? []}
locale={locale}
prosthesisCatalog={prosthesisCatalog}
statusOptions={statusOptions}
/>
{commentsSection}
<LabCaseAttachmentsDialog

View File

@@ -0,0 +1,77 @@
'use client';
import { useTranslations } from 'next-intl';
import { Badge } from '@/components/ui/shared/Badge';
import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
import { formatCaseDateTime } from '@/components/lab/caseDetailUtils';
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
import type { LabCaseHistoryRound, LabTaskStatus } from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
function historyLineGroups(round: LabCaseHistoryRound) {
const groups = new Map<string, { code: string; teeth: string[] }>();
for (const line of round.lines) {
const key = `${line.selectionGroupId ?? ''}\0${line.prosthesisTypeCode}`;
const existing = groups.get(key);
if (existing) existing.teeth.push(line.tooth);
else groups.set(key, { code: line.prosthesisTypeCode, teeth: [line.tooth] });
}
return [...groups.values()];
}
export function CaseHistoryRounds({
rounds,
locale,
prosthesisCatalog,
statusOptions,
}: {
rounds: LabCaseHistoryRound[];
locale: string;
prosthesisCatalog: ProsthesisCatalogEntry[];
statusOptions: { value: LabTaskStatus; label: string }[];
}) {
const t = useTranslations('cases');
if (rounds.length === 0) return null;
return (
<section className="space-y-3 border-t border-border pt-4">
<h3 className="text-sm font-medium text-text-primary">{t('historyTitle')}</h3>
{rounds.map((round) => (
<div key={round.id} className="space-y-2 rounded-md border border-border p-3">
<p className="text-xs text-text-muted">
{t('historyStoppedAt', { date: formatCaseDateTime(round.stoppedAt, locale) })}
</p>
<ul className="space-y-1">
{historyLineGroups(round).map((group) => (
<li key={`${group.code}-${group.teeth.join(',')}`}>
<ProsthesisJobLineLabel
className="text-sm"
teeth={group.teeth}
codes={[group.code]}
catalog={prosthesisCatalog}
/>
</li>
))}
</ul>
<ul className="space-y-1">
{[...round.tasks]
.sort((a, b) => a.stepOrder - b.stepOrder)
.map((task) => (
<li
key={task.id}
className="flex flex-wrap items-center justify-between gap-2 text-sm"
>
<span className="text-text-secondary">
{task.stepOrder}. {task.stepLabel}
</span>
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ?? task.status}
</Badge>
</li>
))}
</ul>
</div>
))}
</section>
);
}

View File

@@ -150,6 +150,28 @@ export function CaseTasksFocusView({ token }: CaseTasksFocusViewProps) {
<section className="surface-card min-h-[280px] min-w-0 overflow-x-hidden">
<section className="border-b border-border last:border-b-0">
<TaskCaseGroupHeader caseGroup={caseGroup} locale={locale} />
{caseGroup.leadingTasks.length > 0 ? (
<ul className="border-t border-border/50">
{caseGroup.leadingTasks.map((task) => (
<TaskRow
key={task.id}
task={task}
locale={locale}
flatMode={false}
canEdit={canEditTasks}
currentUserId={user?.id}
statusOptions={statusOptions}
updatingTaskId={updatingTaskId}
commentsOpen={false}
showCommentsButton={false}
prosthesisCatalog={prosthesisCatalog}
onStatusUpdate={(id, status) => void handleStatusUpdate(id, status)}
onToggleComments={() => {}}
onCommentError={showError}
/>
))}
</ul>
) : null}
{caseGroup.prosthesisGroups.map((prosthesisGroup) => (
<div key={prosthesisGroup.key} className="border-t border-border/50 first:border-t-0">
<TaskProsthesisGroupHeader
@@ -178,6 +200,31 @@ export function CaseTasksFocusView({ token }: CaseTasksFocusViewProps) {
</ul>
</div>
))}
{caseGroup.trailingTasks.length > 0 ? (
<div className="border-t border-border">
<div className="h-2 bg-background-secondary/40" aria-hidden />
<ul>
{caseGroup.trailingTasks.map((task) => (
<TaskRow
key={task.id}
task={task}
locale={locale}
flatMode={false}
canEdit={canEditTasks}
currentUserId={user?.id}
statusOptions={statusOptions}
updatingTaskId={updatingTaskId}
commentsOpen={false}
showCommentsButton={false}
prosthesisCatalog={prosthesisCatalog}
onStatusUpdate={(id, status) => void handleStatusUpdate(id, status)}
onToggleComments={() => {}}
onCommentError={showError}
/>
))}
</ul>
</div>
) : null}
</section>
</section>

View File

@@ -103,6 +103,8 @@ export function CasesPage() {
const [updatingExternalCode, setUpdatingExternalCode] = useState(false);
const [assignableStaff, setAssignableStaff] = useState<AssignableTaskStaff[]>([]);
const [assigningTaskId, setAssigningTaskId] = useState<string | null>(null);
const [reopeningTaskId, setReopeningTaskId] = useState<string | null>(null);
const [stoppingCase, setStoppingCase] = useState(false);
const [commentCount, setCommentCount] = useState(0);
const [creatingCase, setCreatingCase] = useState(false);
const selectedCaseIdRef = useRef<string | null>(null);
@@ -426,6 +428,51 @@ export function CasesPage() {
setPage(1);
}
async function handleReopenTask(taskId: string) {
if (!selectedCaseId || !canEdit) return;
setReopeningTaskId(taskId);
toast.setError('');
try {
const response = await casesApi.reopenTask(selectedCaseId, taskId);
setSelectedCase(response.data);
setCases((prev) =>
prev.map((item) =>
item.id === selectedCaseId
? { ...item, taskProgress: response.data.taskProgress, isOverdue: response.data.isOverdue }
: item,
),
);
notifyTabBadgesChanged();
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorReopenTask')));
} finally {
setReopeningTaskId(null);
}
}
async function handleStopCase() {
if (!selectedCaseId || !canEdit || !selectedCase) return;
if (!window.confirm(t('confirmStopCase'))) return;
setStoppingCase(true);
toast.setError('');
try {
const response = await casesApi.stop(selectedCaseId);
const detail = response.data;
setSelectedCase(detail);
setCases((prev) => prev.filter((item) => item.id !== detail.id));
setDrafts((prev) => [
draftListItemFromDetail(detail),
...prev.filter((item) => item.id !== detail.id),
]);
setDraftsExpanded(true);
notifyTabBadgesChanged();
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorStopCase')));
} finally {
setStoppingCase(false);
}
}
async function handleAssignTask(taskId: string, assigneeUserId: string | null) {
if (!selectedCaseId || !canEdit) return;
@@ -836,6 +883,16 @@ export function CasesPage() {
onAssignTask={(taskId, assigneeUserId) =>
void handleAssignTask(taskId, assigneeUserId)
}
canReopenTasks={canEdit}
reopeningTaskId={reopeningTaskId}
onReopenTask={(taskId) => void handleReopenTask(taskId)}
canStop={
canEdit &&
isLabGeneratedCase(selectedCase.origin) &&
Boolean(selectedCase.startedAt)
}
stopping={stoppingCase}
onStop={() => void handleStopCase()}
prosthesisCatalog={prosthesisCatalog}
headerMetaLines={
<p className="text-sm text-text-muted">

View File

@@ -18,6 +18,7 @@ import { formatAppDate, APP_DATE } from '@/lib/i18n/format';
import { notifyTabBadgesChanged } from '@/lib/tabBadgeUtils';
import { formatPatientName } from '@/components/lab/caseDetailUtils';
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
import { isCaseLevelTask } from '@/components/lab/taskListGrouping';
import { caseCommentsApi } from '@/lib/api/case-comments';
import type { LabTaskListItem, LabTaskStatus } from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
@@ -195,13 +196,15 @@ export function TaskRow({
{t('showInCase')}
</Button>
) : null}
<ProsthesisJobLineLabel
className="min-w-0 max-w-full whitespace-normal break-words text-xs sm:max-w-[16rem] sm:text-end"
teeth={task.teeth}
ponticTeeth={task.ponticTeeth}
codes={[task.prosthesisTypeCode]}
catalog={prosthesisCatalog}
/>
{isCaseLevelTask(task) ? null : (
<ProsthesisJobLineLabel
className="min-w-0 max-w-full whitespace-normal break-words text-xs sm:max-w-[16rem] sm:text-end"
teeth={task.teeth}
ponticTeeth={task.ponticTeeth}
codes={[task.prosthesisTypeCode]}
catalog={prosthesisCatalog}
/>
)}
</div>
) : null}
</div>

View File

@@ -627,6 +627,11 @@ export function TasksPage() {
/>
</div>
) : null}
{caseGroup.leadingTasks.length > 0 ? (
<ul className="border-t border-border/50">
{caseGroup.leadingTasks.map((task) => renderTaskRow(task, false))}
</ul>
) : null}
{caseGroup.prosthesisGroups.map((prosthesisGroup) => (
<div
key={prosthesisGroup.key}
@@ -641,6 +646,14 @@ export function TasksPage() {
</ul>
</div>
))}
{caseGroup.trailingTasks.length > 0 ? (
<div className="border-t border-border">
<div className="h-2 bg-background-secondary/40" aria-hidden />
<ul>
{caseGroup.trailingTasks.map((task) => renderTaskRow(task, false))}
</ul>
</div>
) : null}
</section>
))}
</div>

View File

@@ -34,17 +34,21 @@ import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { FdiToothId, LinkedOrganizationOption } from '@/types/treatment';
import type {
VoiceApplySelection,
VoiceEntryMode,
VoiceExtractionResult,
VoiceUnresolvedItem,
} from '@/types/voice';
interface VoiceReviewSheetProps {
result: VoiceExtractionResult;
treatmentCatalog: TreatmentCatalogEntry[];
/** `lab` hides the treatment type, plain teeth and lab rows — see `voiceRowAvailability`. */
mode?: VoiceEntryMode;
/** Unused in lab mode: the type row never renders, so no catalog is needed to label it. */
treatmentCatalog?: TreatmentCatalogEntry[];
prosthesisCatalog: ProsthesisCatalogEntry[];
/** `prosthesis` today, but kept generic — the same set the workspace already tracks. */
labDependentCodes: ReadonlySet<string>;
labs: LinkedOrganizationOption[];
labDependentCodes?: ReadonlySet<string>;
labs?: LinkedOrganizationOption[];
/** The result is handed back because the sheet may have added teeth or jobs the model missed. */
onApply: (selection: VoiceApplySelection, result: VoiceExtractionResult) => void;
onDiscard: () => void;
@@ -52,6 +56,9 @@ interface VoiceReviewSheetProps {
type ArchPick = 'upper' | 'lower';
/** Module-level so the default prop is referentially stable across renders. */
const NO_LAB_DEPENDENT_CODES: ReadonlySet<string> = new Set();
/**
* Confirmation step between the model's output and the form.
*
@@ -60,10 +67,11 @@ type ArchPick = 'upper' | 'lower';
*/
export function VoiceReviewSheet({
result,
treatmentCatalog,
mode = 'clinic',
treatmentCatalog = [],
prosthesisCatalog,
labDependentCodes,
labs,
labDependentCodes = NO_LAB_DEPENDENT_CODES,
labs = [],
onApply,
onDiscard,
}: VoiceReviewSheetProps) {
@@ -71,7 +79,7 @@ export function VoiceReviewSheet({
const tProsthesis = useTranslations('prosthesis');
const { formatDate } = useAppFormatters();
const [selection, setSelection] = useState<VoiceApplySelection>(() =>
initialVoiceSelection(result, labDependentCodes),
initialVoiceSelection(result, labDependentCodes, mode),
);
// Every kind of candidate chip the sheet can offer, tracked separately because each folds
@@ -101,8 +109,8 @@ export function VoiceReviewSheet({
}, [result, chosenTeeth, chosenAssignmentTeeth, chosenArches, chosenLeaves]);
const available = useMemo(
() => voiceRowAvailability(effective, labDependentCodes),
[effective, labDependentCodes],
() => voiceRowAvailability(effective, labDependentCodes, mode),
[effective, labDependentCodes, mode],
);
const connectedTeeth = useMemo(() => connectedTeethFromResult(effective), [effective]);
const selectedTeeth = useMemo(() => new Set(effective.teeth), [effective.teeth]);
@@ -142,7 +150,7 @@ export function VoiceReviewSheet({
? { ...selection, treatmentType: true }
: selection;
const nothingToApply = !hasAnythingToApply(effective, labDependentCodes);
const nothingToApply = !hasAnythingToApply(effective, labDependentCodes, mode);
const selectedCount = countSelected(effectiveSelection, available);
const targetLabel = (target: string): string => {

View File

@@ -61,6 +61,19 @@ export const casesApi = {
return response.data;
},
stop: async (id: string): Promise<{ success: boolean; data: LabCaseDetail }> => {
const response = await apiClient.post(`/cases/${id}/stop`);
return response.data;
},
reopenTask: async (
caseId: string,
taskId: string,
): Promise<{ success: boolean; data: LabCaseDetail }> => {
const response = await apiClient.patch(`/cases/${caseId}/tasks/${taskId}/reopen`);
return response.data;
},
deleteDraft: async (id: string): Promise<{ success: boolean }> => {
const response = await apiClient.delete(`/cases/${id}`);
return response.data;

View File

@@ -62,6 +62,29 @@ export interface LabCaseTask {
timeline: LabTaskTimelineEvent[];
}
export interface LabCaseHistoryLine {
tooth: string;
prosthesisTypeCode: string;
prosthesisTypeLabel: string;
selectionGroupId?: string;
}
export interface LabCaseHistoryTask {
id: string;
stepOrder: number;
stepLabel: string;
status: LabTaskStatus;
prosthesisTypeCode: string;
teeth: string[];
}
export interface LabCaseHistoryRound {
id: string;
stoppedAt: string;
lines: LabCaseHistoryLine[];
tasks: LabCaseHistoryTask[];
}
export interface LabCaseTaskGroup {
treatmentDetailId: string;
teeth: string[];
@@ -151,6 +174,7 @@ export interface LabCaseDetail {
}>;
tasks: LabCaseTask[];
tasksByTooth: LabCaseTaskGroup[];
historyRounds?: LabCaseHistoryRound[];
taskProgress: { completed: number; total: number };
shareUrl?: string | null;
calculatedAmount?: string | null;

View File

@@ -80,3 +80,9 @@ export interface VoiceApplySelection {
}
export type VoicePhase = 'idle' | 'recording' | 'processing';
/**
* Which side dictated. Derived from the organisation on the server; on the client it only
* picks which review rows exist, since a lab line has no treatment type and no destination.
*/
export type VoiceEntryMode = 'clinic' | 'lab';