forked from admin/dyolink
improvement: generating tasks and their related steps improved.
This commit is contained in:
@@ -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).
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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[] = [
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
|
||||
@@ -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' },
|
||||
}),
|
||||
|
||||
@@ -177,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',
|
||||
|
||||
@@ -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 } } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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' }],
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 })),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -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 } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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",
|
||||
@@ -1432,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.",
|
||||
|
||||
@@ -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": "کانتور کامل",
|
||||
@@ -1433,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": "نام کلینیک یا نام بیمار را وارد کنید.",
|
||||
|
||||
@@ -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",
|
||||
@@ -1432,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.",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ 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 {
|
||||
@@ -689,6 +690,16 @@ export function CaseCreatePanel({
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
77
frontend/src/components/ui/lab/CaseHistoryRounds.tsx
Normal file
77
frontend/src/components/ui/lab/CaseHistoryRounds.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user