Compare commits

...

4 Commits

Author SHA1 Message Date
93d0baa178 fix(tasks): keep case header names readable on mobile
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 5m21s
Production — tag build, push, deploy / deploy (push) Successful in 2m5s
2026-09-22 02:52:42 +03:30
50daac44e3 Merge pull request 'bugfix: cases critical bugs fixed.' (#89) from bugfix/pre-release into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 19m39s
Registry — build, push, deploy / deploy (push) Successful in 1m24s
Reviewed-on: #89
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-09-21 01:57:13 +03:30
705ea92da7 bugfix: cases critical bugs fixed.
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 4m54s
Production — tag build, push, deploy / deploy (push) Successful in 13m25s
2026-09-21 01:44:55 +03:30
b42adecd71 Merge pull request 'fix(ci): prod nginx re-resolves backend via Docker DNS; deploy starts nginx last' (#88) from bug/ci-cd into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 1m14s
Registry — build, push, deploy / deploy (push) Successful in 1m7s
Reviewed-on: #88
Reviewed-by: admin <admin@localhost>
2026-09-20 23:36:40 +03:30
51 changed files with 1148 additions and 563 deletions

View File

@@ -17,13 +17,15 @@ Ops panel at `/admin` (`backend/src/admin/`). Resources are a **manual allowlist
3. **Renamed / removed model** → update or remove the matching resource (broken `getModelByName` breaks `/admin` boot).
4. **New secret fields** (hashes, tokens, share tokens) → hide via `isVisible: false` (list/filter/show/edit).
5. **Catalog-like reference data** → list/show/edit only; disable `new` / `delete` / `bulkDelete`.
6. **Composite `@@id` only** (no single `@id`) → **do not register** — AdminJS list returns 500 (`Resource does not have an id property`). Examples: `LabCaseDetail`, `MembershipPermission`, read-cursor tables.
7. Skip pure join/cursor tables unless ops need them and they have a single id.
6. **Composite `@@id` only** (no single `@id`) → **do not register** — AdminJS list returns 500 (`Resource does not have an id property`). Examples: `LabCaseDetail`, `LabCaseAttachment`, `MembershipPermission`, read-cursor tables.
7. Skip pure join/cursor tables unless ops need them and they have a single id. **Do register** single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock`.
Auth: `ADMINJS_EMAIL` / `ADMINJS_PASSWORD` — production login disabled if password missing or still `admin123`.
Production Docker: `ADMIN_JS_TMP_DIR=/app/adminjs-tmp` (not `.adminjs`) so `components.bundle.js` can be written/served.
## Secrets to hide
## Secrets and computed fields
`passwordHash`, session `token`/`refreshToken`, invite/OTP `tokenHash`/`codeHash`, `LabCase.accessToken`.
`LabCase.listedAt` is `COALESCE(startedAt, sentAt)` via trigger `lab_cases_listed_at_sync` — **not** `GENERATED ALWAYS` (heap rewrite + AdminJS/Prisma update 500). List/filter/show only; `omitListedAt` on new/edit. Never write it from app or AdminJS.

View File

@@ -35,7 +35,7 @@ throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
- Schema: `backend/prisma/schema.prisma`
- Always add a migration for schema changes (`npm run prisma:migrate` in backend).
- Seed permissions stay in sync with `ALL_TAB_PERMISSIONS` in `common/permissions.ts`.
- **Schema change ⇒ AdminJS:** update `backend/src/admin/resources.ts` in the same change (add/rename/remove resources, hide new secrets). See `.cursor/rules/adminjs.mdc`.
- **Schema change ⇒ AdminJS:** update `backend/src/admin/resources.ts` in the same change (add/rename/remove resources, hide new secrets). Trigger-maintained fields such as `LabCase.listedAt` must not be `GENERATED ALWAYS`. See `.cursor/rules/adminjs.mdc`.
## API responses

View File

@@ -13,3 +13,4 @@ alwaysApply: false
- **Clinic transactions:** RECEIPT → patient cash; PAYMENT → linked lab. **Lab:** RECEIPT/PAYMENT → linked clinic only (no patient ledger).
- Money UI: `AppMoneyInput`; list chrome: `BillingListToolbar` + shared `Table` (`table-fixed`). Labels: **Price**, not Amount.
- **This publish:** hide Billing for CLINIC orgs via `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` (`hidden-tabs.ts`); lab keeps it.
- Lab case pickers sort by `listedAt` desc (same COALESCE as Cases — never `sentAt` then `startedAt`).

View File

@@ -6,12 +6,12 @@ alwaysApply: false
# Lab case share link
- **Token:** `LabCase.accessToken` on first ship; `shareUrl` on lab case detail **and** clinic treatment lab-case drafts when sent.
- **Token:** `LabCase.accessToken` on first ship **or** lab-origin Start; `shareUrl` on case detail when sent or started (`LAB_INTERNAL`).
- **QR:** client-side `react-qr-code` in frontend — ❌ no backend QR endpoint.
- **Cases panel:** attachment preview left, QR thumb right, one row; dialog for QR + copy link.
- **Treatment dispatch:** same thumb + dialog on sent cases (`LabCasesDispatchPanel`). Dest/jobs share a row with the QR; tracker + comments are full width below.
- **Route:** `/lab-case/[token]` → `CaseTasksFocusView` (dashboard layout, auth required).
- **Access:** lab (`TAB_TASKS_*`) or clinic treatment **provider** (`TAB_TREATMENT_EDIT` + `isActorTreatmentProvider`); else `LAB_CASE_ACCESS_DENIED`.
- **Access:** lab (`TAB_CASES_*` or `TAB_TASKS_*`) or clinic treatment **provider** (`TAB_TREATMENT_EDIT` + `isActorTreatmentProvider`); else `LAB_CASE_ACCESS_DENIED`.
- **Task status on link page:** same assignee rule as Tasks — `canEditLabTaskStatus`; backend `PATCH /tasks/:id` enforces assignee.
- **Auth redirect:** `postAuthRedirect.ts`; dashboard stores path on logout redirect; login stores `?from=` **then** `useEnterAppWhenAuthenticated` consumes **once** after org ready — ❌ do not consume in `useAuth.login()` / `registerTrial`. Invites (join + `password_setup`): `login()` then `navigateIntoAppIfOrgSelected` (no enter-app hook on invite pages).
- **Login page:** wrap `useSearchParams` in `<Suspense>` for `next build`.

View File

@@ -1,6 +1,6 @@
---
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/**
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
alwaysApply: false
---
@@ -10,9 +10,10 @@ alwaysApply: false
- **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.
- **Share link:** QR + URL when case is sent; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Case Sheet PDF:** client A4 via `jspdf` + `html2canvas`; print layout must stay **hex-only** (Tailwind `lab()`/`oklch` breaks capture). Optional `externalCode` replaces PDF order number when set.
- **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).
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`).
- **Drafts rail:** unstarted lab-origin cases sit in a collapsed `TreatmentRailSection`; expands on click or **Add case**. Main list is received + started cases (`drafts=exclude` / `drafts=only`), newest first by `listedAt` (`LAB_CASE_LIST_ORDER_BY`; trigger `lab_cases_listed_at_sync` = `COALESCE(startedAt, sentAt)`). Never `orderBy startedAt, sentAt` and never a `GENERATED ALWAYS` `listedAt`.
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`). Comments on Cases accept `TAB_CASES_*` (owners are not blocked by Tasks opt-in).
Skill: `.cursor/skills/lab-cases/SKILL.md`

View File

@@ -1,12 +1,12 @@
---
description: Lab Tasks tab — sort, grouping, filters, prosthesis colors
globs: frontend/src/components/ui/lab/TasksPage.tsx,frontend/src/components/ui/lab/Task*.tsx,frontend/src/components/ui/lab/Case*.tsx,frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx,frontend/src/components/ui/lab/ProsthesisStackedTypeLabel.tsx,frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx,frontend/src/components/lab/taskListGrouping.ts,frontend/src/components/lab/labCaseDueDateDisplay.ts,frontend/src/components/shared/formSelectStyles.ts,frontend/src/components/treatment/prosthesisTypeDisplay.ts,frontend/src/components/treatment/prosthesisJobPath.ts,frontend/src/components/shared/catalog-type-colors.ts,backend/src/modules/tasks/**,backend/src/common/lab-case-due-date.ts,backend/src/modules/treatments/**
globs: frontend/src/components/ui/lab/TasksPage.tsx,frontend/src/components/ui/lab/Task*.tsx,frontend/src/components/ui/lab/Case*.tsx,frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx,frontend/src/components/ui/lab/ProsthesisStackedTypeLabel.tsx,frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx,frontend/src/components/lab/taskListGrouping.ts,frontend/src/components/lab/labCaseDueDateDisplay.ts,frontend/src/components/shared/formSelectStyles.ts,frontend/src/components/treatment/prosthesisTypeDisplay.ts,frontend/src/components/treatment/prosthesisJobPath.ts,frontend/src/components/shared/catalog-type-colors.ts,backend/src/modules/tasks/**,backend/src/common/lab-case-due-date.ts,backend/src/common/lab-case-listed-at.ts,backend/src/modules/treatments/**
alwaysApply: false
---
# Lab Tasks
- **Default sort:** newest `labCase.sentAt` first; `stepOrder` asc within prosthesis group (backend `buildOrderBy`).
- **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.
- **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).

View File

@@ -10,7 +10,7 @@ Shipped cases get a stable **access token** and share URL. QR + link open a focu
## Data & token lifecycle
- **Schema:** `LabCase.accessToken` (`String?`, `@unique`).
- **On first ship:** `treatments.service` sets `accessToken` + `sentAt` in the same update.
- **On first ship or lab-origin Start:** `treatments.service` / `cases.service` sets `accessToken` (`ensureAccessToken` for sent **or** started `LAB_INTERNAL`).
- **Backfill:** `LabCaseAccessService.ensureAccessToken()` for older sent cases when building case detail `shareUrl`; clinic drafts use `TreatmentsService.ensureSentLabCaseAccessTokens()` on getDraft.
- **URL:** `buildLabCaseShareUrl(token, locale)` → `{FRONTEND_URL}/{locale}/lab-case/{token}` (`backend/src/common/lab-case-access-token.ts`). Clinic lab-case payloads include the same `shareUrl`.
@@ -29,7 +29,7 @@ Base path: `/lab-cases/access/:token` (JWT + selected org required).
| Actor | View | Edit task status | Comments |
|-------|------|------------------|----------|
| Lab + `TAB_TASKS_READ`/`EDIT` | ✅ | ✅ if `TAB_TASKS_EDIT` + assignee rules | Post/toggle if `TAB_TASKS_EDIT` |
| Lab + `TAB_CASES_*` or `TAB_TASKS_*` | ✅ | ✅ if `TAB_TASKS_EDIT` + assignee rules | Post/toggle if Cases **or** Tasks **EDIT** |
| Clinic + `TAB_TREATMENT_EDIT` + **treatment provider** | ✅ | ❌ read-only | Post only (no visibility toggle) |
| Everyone else | ❌ `LAB_CASE_ACCESS_DENIED` | | |
@@ -44,7 +44,7 @@ Task status updates use **`PATCH /tasks/:id`** (not token routes) — same assig
| QR UI | `LabCaseShareQrCode`, `LabCaseShareQrDialog`, thumb in `CaseDetailPanel` **and** Treatment `LabCasesDispatchPanel` |
| QR package | `react-qr-code` (frontend only — no backend QR generation) |
**Cases detail header:** attachment preview **left**, QR thumb **right**, same row (`w-24 sm:w-32`). QR opens dialog (large QR + URL + copy); no inline copy on panel. Only when `shareUrl` present (sent case).
**Cases detail header:** attachment preview **left**, QR thumb **right**, same row (`w-24 sm:w-32`). QR opens dialog (large QR + URL + copy); no inline copy on panel. Shown when `shareUrl` is present (sent clinic case **or** started lab-origin case).
**Treatment lab dispatch:** after send, the same thumb + dialog (same `shareUrl` / token) so the dentist can scan to the focus page. Dest/jobs share a row with the QR; tracker + comments span the card **below** it (not beside it).

View File

@@ -7,11 +7,12 @@ description: Lab Cases tab — list, filters, detail panel, assignment, share QR
**UI:** [`frontend/src/components/ui/lab/CasesPage.tsx`](frontend/src/components/ui/lab/CasesPage.tsx)
**Backend:** [`backend/src/modules/cases/`](backend/src/modules/cases/)
**List order:** [`backend/src/common/lab-case-listed-at.ts`](backend/src/common/lab-case-listed-at.ts) (`LAB_CASE_LIST_ORDER_BY`)
**Shared prosthesis rows:** [`LabCaseProsthesisGroupsList.tsx`](frontend/src/components/ui/lab/LabCaseProsthesisGroupsList.tsx) (also used in Treatment lab shipments rail)
## List behavior
- **Default sort:** `startedAt` / `sentAt` desc (newest first). Lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`) show a **Draft** badge. All list/detail cards also show **Received** (`CLINIC_DISPATCH`) or **Generated** (`LAB_INTERNAL`) via `LabCaseOriginBadge`.
- **Default sort:** `listedAt` desc via `LAB_CASE_LIST_ORDER_BY`. `listedAt` is `COALESCE(startedAt, sentAt)`, kept by trigger `lab_cases_listed_at_sync` (do **not** use `GENERATED ALWAYS` — heap rewrite and AdminJS/Prisma writes 500). Do **not** `orderBy` `startedAt` then `sentAt` — PostgreSQL DESC is NULLS FIRST, so clinic-sent rows bury started lab-origin cases. Tasks grouped-by-date uses this same key. Unstarted lab-origin drafts live in a **Drafts** rail section (`TreatmentRailSection`, collapsed by default; expands on click or **Add case**). Main list is received + started cases only (`GET /cases?drafts=exclude`). Drafts: `GET /cases?drafts=only`. List/detail cards also show **Received** (`CLINIC_DISPATCH`) or **Generated** (`LAB_INTERNAL`) via `LabCaseOriginBadge`.
- **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.
@@ -21,7 +22,7 @@ description: Lab Cases tab — list, filters, detail panel, assignment, share QR
List `where`: received clinic cases (`sends` + `sentAt`) **OR** `origin = LAB_INTERNAL` and `destinationOrganizationId = lab`. Map clinic/patient from `treatment` **or** snapshots / partner org. Search includes snapshot names.
Share QR remains clinic-sent only (`sentAt` / `shareUrl`). Lab-origin has no share link in this pass. Clinic Treatment **Lab dispatch** shows the same QR after send (see lab-case-share-link skill).
Share QR is issued when a case is **sent** (`sentAt`) **or** a lab-origin case is **started** (`startedAt`). Clinic Treatment **Lab dispatch** shows the same QR after send (see lab-case-share-link skill). Lab comments on Cases use **`TAB_CASES_*` or `TAB_TASKS_*`** — lab owners have Cases by default and must not be blocked by Tasks opt-in.
## Filters (`GET /cases`)
@@ -52,7 +53,7 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
## Case Sheet PDF
**Entry:** Download PDF beside Comments on `CaseDetailPanel`.
**Builder:** [`caseSheetPdf.ts`](frontend/src/components/lab/caseSheetPdf.ts) → off-screen [`CaseSheetPrintLayout.tsx`](frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx) → `html2canvas` → `jspdf` A4 (ISO √2 — prints cleanly onto A3–A6).
**Builder:** [`caseSheetPdf.ts`](frontend/src/components/lab/caseSheetPdf.ts) → off-screen [`CaseSheetPrintLayout.tsx`](frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx) wrapped in `NextIntlClientProvider` → `html2canvas` → `jspdf` A4 (ISO √2 — prints cleanly onto A3–A6).
### html2canvas + Tailwind v4 (required)

View File

@@ -6,18 +6,19 @@ description: Lab Tasks tab — list, sort, filters, case grouping, prosthesis co
# Lab Tasks
Main UI: [`frontend/src/components/ui/lab/TasksPage.tsx`](frontend/src/components/ui/lab/TasksPage.tsx)
Backend: [`backend/src/modules/tasks/`](backend/src/modules/tasks/)
Backend: [`backend/src/modules/tasks/`](backend/src/modules/tasks/)
List order: [`backend/src/common/lab-case-listed-at.ts`](backend/src/common/lab-case-listed-at.ts) (`labCaseTaskListedAtOrder`)
## Default sort (backend)
`sortBy=date` + `sortDir=desc`:
`sortBy=date` + `sortDir=desc` (same newest-first key as Cases):
1. `labCase.sentAt` desc (newest case first)
1. `labCase.listedAt` desc via `labCaseTaskListedAtOrder` (`COALESCE(startedAt, sentAt)` from trigger `lab_cases_listed_at_sync` — not lexicographic `startedAt` then `sentAt`)
2. `labCaseId`, `sourceKey`, `tooth`, `prosthesisTypeCode` asc (one pipeline per prosthesis type in a detail/line — same-type teeth share it, including unconnected; `partial_denture` is one pipeline for all selected teeth)
3. `stepOrder` asc (steps 1→N within that pipeline)
4. `id` asc
Other sorts use flat list on the frontend; `stepOrder asc` is still a tiebreaker.
Other sorts use flat list on the frontend; `stepOrder asc` is still a tiebreaker. `sortBy=dueDate` is flat; after `dueDate` the tiebreaker is `listedAt` desc then the same pipeline keys as date sort.
## Case grouping (frontend)
@@ -59,10 +60,10 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
- **Important first:** `pinImportant=true` prepends important cases in sort order.
- **Assigned to me:** `assignedToMe=true` filters to current user's assigned tasks only.
- **Overdue cases:** `overdue=true` — `LabCase.dueDate` before start of UTC day **and** at least one task still `IN_PROGRESS`. Shown with error badge on Cases list/detail and task case headers.
- **Sort by due date:** `sortBy=dueDate` — flat list (grouping off); tiebreakers match other non-date sorts.
- **Sort by due date:** `sortBy=dueDate` — flat list (grouping off); after `dueDate`, tiebreak with `listedAt` desc then the date-sort pipeline keys (`labCaseId` / `sourceKey` / tooth / type / `stepOrder` / `id`).
- **Reset view:** `resetView` restores `DEFAULT_TASKS_VIEW` from `tasksViewDefaults.ts`.
- **URL state:** `parseTasksSearchParams` applies Today deep-link query params on mount (`importantOnly`, `overdueOnly`, `unassignedOnly`, `prosthesisTypeCode`, `status`, sort).
- **Show in case:** flat-sort rows only; resets filters/sort, calls `GET /tasks/locate-page` to find the correct page in the full default-sorted list, then highlights + scrolls to the task.
- **Show in case:** flat-sort rows only; resets filters/sort, calls `GET /tasks/locate-page` (position uses `listedAt`, same as date sort) to find the correct page in the full default-sorted list, then highlights + scrolls to the task.
- **Complete animation:** when marking done under in-progress filter, row plays exit animation + success toast before refetch.
## APIs
@@ -70,7 +71,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
- `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).
- `GET /tasks/filter-options` — clinics + workflow steps (localized)
- `GET /tasks/locate-page` — page number for a task in the sorted filtered list
- `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
- `PATCH /cases/:caseId/tasks/:taskId/assign` — assign or unassign (`assigneeUserId` nullable)

View File

@@ -70,13 +70,13 @@ 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; 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; **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`); 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 (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** client A4 (`jspdf`/`html2canvas`); hex-only print layout; optional `externalCode` replaces order number. Lab-origin Start has no clinic send; comments and mark-read still work (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`). **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 → `/{locale}/lab-case/{token}` after login.
- **Lab:** view/edit tasks (assignee rules), comments + visibility toggle.
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login.
- **Lab:** view with Cases or Tasks access; edit task status only with Tasks edit + assignee rules; comments if Cases or Tasks edit.
- **Clinic:** treatment **provider** with `TAB_TREATMENT_EDIT` — read-only tasks, can comment. Same QR as lab Cases appears on Treatment **Lab dispatch** after send (dest/jobs beside the thumb; tracker + comments full width below).
- Logged out → login with `?from=` → `storeAuthRedirectFromPath` then `useEnterAppWhenAuthenticated` (`consumeAuthRedirect` once after org ready — not inside `useAuth.login()` / `registerTrial`). Trial register uses the same hook; staff/org invite (including `password_setup`) then `login()` + `navigateIntoAppIfOrgSelected`. See `.cursor/rules/post-auth-navigation.mdc`.
@@ -94,7 +94,7 @@ backend/src/
Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpected 500s: GlitchTip (`SENTRY_DSN`). Never throw raw strings for user-facing failures.
**AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500). Rule: `.cursor/rules/adminjs.mdc`.
**AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500) — including `LabCaseAttachment`. Single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock` **are** registered. `LabCase.listedAt` is trigger-maintained (list/filter/show only; never write). Rule: `.cursor/rules/adminjs.mdc`.
## Git & commits
@@ -107,8 +107,8 @@ Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpe
|-------|-------------|
| `.cursor/skills/add-feature/` | New tab, API module, or end-to-end feature |
| `.cursor/skills/treatment-workspace/` | Treatment tab: preview vs form, history, load flow, drafts, type-first entry, connected teeth |
| `.cursor/skills/lab-tasks/` | Lab Tasks tab: sort, case grouping, step-completed filter, prosthesis colors |
| `.cursor/skills/lab-cases/` | Lab Cases tab: prosthesis filter, auto-select, Case Sheet PDF, external code |
| `.cursor/skills/lab-tasks/` | Lab Tasks tab: `listedAt` sort (same as Cases), case grouping, step-completed filter, prosthesis colors |
| `.cursor/skills/lab-cases/` | Lab Cases tab: `listedAt` newest-first, prosthesis filter, auto-select, Case Sheet PDF, external code |
| `.cursor/skills/lab-case-share-link/` | Case QR share link: access token, focus page, auth redirect, access rules |
| `.cursor/skills/tab-badges/` | Sidebar tab badges: Cases/Tasks/Treatment, LabCaseActivity, tab-counts API, read cursors |
| `.cursor/skills/notifications-inbox/` | Header bell inbox: UserNotification fan-out, Socket.IO realtime |

View File

@@ -0,0 +1,32 @@
-- Newest-first Cases/Tasks sort key: COALESCE(startedAt, sentAt).
--
-- Not GENERATED ALWAYS AS STORED: that rewrites the whole heap under ACCESS
-- EXCLUSIVE, and AdminJS/Prisma updates that send listedAt fail with
-- "cannot insert a non-DEFAULT value into a generated column".
--
-- ADD COLUMN with no default is catalog-only on PostgreSQL 15 (no rewrite).
-- A BEFORE INSERT OR UPDATE trigger keeps listedAt in sync for clinic send,
-- lab Start, and AdminJS edits of startedAt/sentAt. Backfill fills existing rows.
-- Production backend runs this via `prisma migrate deploy` on container start,
-- before the API listens.
ALTER TABLE "lab_cases" ADD COLUMN "listedAt" TIMESTAMP(3);
CREATE OR REPLACE FUNCTION lab_cases_set_listed_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW."listedAt" := COALESCE(NEW."startedAt", NEW."sentAt");
RETURN NEW;
END;
$$;
CREATE TRIGGER lab_cases_listed_at_sync
BEFORE INSERT OR UPDATE ON "lab_cases"
FOR EACH ROW
EXECUTE FUNCTION lab_cases_set_listed_at();
UPDATE "lab_cases" SET "listedAt" = COALESCE("startedAt", "sentAt");
CREATE INDEX "lab_cases_listedAt_idx" ON "lab_cases"("listedAt");

View File

@@ -252,6 +252,8 @@ model LabCase {
destinationOrganizationId String?
sentAt DateTime?
startedAt DateTime?
/// COALESCE(startedAt, sentAt). Maintained by PG trigger lab_cases_listed_at_sync — do not write.
listedAt DateTime?
dueDate DateTime?
isImportant Boolean @default(false)
origin LabCaseOrigin @default(CLINIC_DISPATCH)
@@ -284,6 +286,7 @@ model LabCase {
@@index([treatmentId, sortOrder])
@@index([destinationOrganizationId, origin])
@@index([partnerClinicOrganizationId])
@@index([listedAt])
@@map("lab_cases")
}

View File

@@ -1,12 +1,25 @@
import { getModelByName } from '@adminjs/prisma';
import type { PrismaService } from '../../prisma/prisma.service';
type AdminActionRequest = {
payload?: Record<string, unknown> | null;
};
type ResourceOptions = {
navigation?: { name: string; icon?: string };
properties?: Record<string, { isVisible?: boolean | { list?: boolean; filter?: boolean; show?: boolean; edit?: boolean } }>;
properties?: Record<
string,
{
isVisible?: boolean | { list?: boolean; filter?: boolean; show?: boolean; edit?: boolean };
isDisabled?: boolean;
}
>;
actions?: Record<
string,
{ isAccessible?: boolean }
{
isAccessible?: boolean;
before?: (request: AdminActionRequest) => AdminActionRequest | Promise<AdminActionRequest>;
}
>;
};
@@ -29,6 +42,14 @@ const catalogActions: ResourceOptions['actions'] = {
bulkDelete: { isAccessible: false },
};
/** listedAt is trigger-maintained; never send it on AdminJS writes. */
const omitListedAt = (request: AdminActionRequest): AdminActionRequest => {
if (request.payload && 'listedAt' in request.payload) {
delete request.payload.listedAt;
}
return request;
};
function resource(
client: PrismaService,
modelName: string,
@@ -73,6 +94,12 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
resource(prisma, 'Membership', {
navigation: { name: 'Orgs & access', icon: 'Settings' },
}),
resource(prisma, 'StaffWorkingHoursSchedule', {
navigation: { name: 'Orgs & access', icon: 'Settings' },
}),
resource(prisma, 'StaffWorkingHoursBlock', {
navigation: { name: 'Orgs & access', icon: 'Settings' },
}),
resource(prisma, 'Permission', {
navigation: { name: 'Orgs & access', icon: 'Settings' },
}),
@@ -112,13 +139,23 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
// Lab
resource(prisma, 'LabCase', {
navigation: { name: 'Lab', icon: 'Archive' },
properties: hide('accessToken'),
properties: {
...hide('accessToken'),
listedAt: {
isDisabled: true,
isVisible: { list: true, filter: true, show: true, edit: false },
},
},
actions: {
new: { before: omitListedAt },
edit: { before: omitListedAt },
},
}),
resource(prisma, 'LabCaseLine', {
navigation: { name: 'Lab', icon: 'Archive' },
}),
// LabCaseDetail omitted: composite @@id — AdminJS list 500s without a single id
// (inspect LabCase + TreatmentDetail instead)
// LabCaseDetail / LabCaseAttachment omitted: composite @@id — AdminJS list 500s without a single id
// (inspect LabCase + TreatmentDetail / TreatmentDetailAttachment instead)
resource(prisma, 'LabCaseSend', {
navigation: { name: 'Lab', icon: 'Archive' },
}),

View File

@@ -0,0 +1,16 @@
import { LAB_CASE_LIST_ORDER_BY, labCaseTaskListedAtOrder } from './lab-case-listed-at';
describe('lab case list sort', () => {
it('orders Cases by listedAt desc (not startedAt then sentAt)', () => {
expect(LAB_CASE_LIST_ORDER_BY[0]).toEqual({
listedAt: { sort: 'desc', nulls: 'last' },
});
expect(LAB_CASE_LIST_ORDER_BY.some((clause) => 'startedAt' in clause)).toBe(false);
});
it('orders date-sorted Tasks by the same listedAt key', () => {
expect(labCaseTaskListedAtOrder('desc')).toEqual({
labCase: { listedAt: { sort: 'desc', nulls: 'last' } },
});
});
});

View File

@@ -0,0 +1,20 @@
import { Prisma } from '@prisma/client';
/**
* Newest-first Cases / grouped-Tasks order.
*
* Do not `orderBy: [{ startedAt: 'desc' }, { sentAt: 'desc' }]`. That is
* lexicographic, and PostgreSQL DESC is NULLS FIRST, so clinic-sent rows
* (`startedAt` null) always rank above lab-origin rows that only have
* `startedAt`. Use `LabCase.listedAt` (COALESCE(startedAt, sentAt), PG trigger).
*/
export const LAB_CASE_LIST_ORDER_BY: Prisma.LabCaseOrderByWithRelationInput[] = [
{ listedAt: { sort: 'desc', nulls: 'last' } },
{ id: 'desc' },
];
export function labCaseTaskListedAtOrder(
dir: Prisma.SortOrder,
): Prisma.LabCaseTaskOrderByWithRelationInput {
return { labCase: { listedAt: { sort: dir, nulls: 'last' } } };
}

View File

@@ -0,0 +1,72 @@
import {
isWalkInPatient,
toPublicPatient,
WALK_IN_MOBILE_PREFIX,
WALK_IN_STORED_NAME,
} from './walk-in-patient';
describe('isWalkInPatient', () => {
it('matches the isWalkIn flag', () => {
expect(isWalkInPatient({ isWalkIn: true, firstName: 'Ada', lastName: 'Lovelace' })).toBe(true);
});
it('matches the sentinel mobile', () => {
expect(
isWalkInPatient({
firstName: WALK_IN_STORED_NAME,
lastName: WALK_IN_STORED_NAME,
mobile: `${WALK_IN_MOBILE_PREFIX}org-1`,
}),
).toBe(true);
});
it('matches stored Walk-in Walk-in names', () => {
expect(
isWalkInPatient({ firstName: WALK_IN_STORED_NAME, lastName: WALK_IN_STORED_NAME }),
).toBe(true);
});
it('does not match a named patient', () => {
expect(
isWalkInPatient({ firstName: 'Ada', lastName: 'Lovelace', mobile: '+989121234567' }),
).toBe(false);
});
});
describe('toPublicPatient', () => {
it('strips sentinel mobile and duplicated last name', () => {
expect(
toPublicPatient({
id: 'p1',
firstName: WALK_IN_STORED_NAME,
lastName: WALK_IN_STORED_NAME,
mobile: `${WALK_IN_MOBILE_PREFIX}83c493d2-fbbc-4b0f-b8bc-1442305cfb2f`,
isWalkIn: true,
}),
).toEqual({
id: 'p1',
firstName: WALK_IN_STORED_NAME,
lastName: '',
mobile: '',
isWalkIn: true,
});
});
it('passes through named patients', () => {
expect(
toPublicPatient({
id: 'p2',
firstName: 'Ada',
lastName: 'Lovelace',
mobile: '+989121234567',
isWalkIn: false,
}),
).toEqual({
id: 'p2',
firstName: 'Ada',
lastName: 'Lovelace',
mobile: '+989121234567',
isWalkIn: false,
});
});
});

View File

@@ -2,6 +2,8 @@ import type { Prisma } from '@prisma/client';
import type { PrismaService } from '../../prisma/prisma.service';
export const WALK_IN_MOBILE_PREFIX = '__walkin__:';
/** Stored English first/last name on the sentinel Patient row. */
export const WALK_IN_STORED_NAME = 'Walk-in';
export function walkInMobileForOrganization(organizationId: string): string {
return `${WALK_IN_MOBILE_PREFIX}${organizationId}`;
@@ -11,6 +13,51 @@ export function isWalkInMobile(mobile: string): boolean {
return mobile.startsWith(WALK_IN_MOBILE_PREFIX);
}
export function isWalkInPatient(patient: {
isWalkIn?: boolean | null;
mobile?: string | null;
firstName?: string | null;
lastName?: string | null;
}): boolean {
if (patient.isWalkIn) return true;
if (patient.mobile && isWalkInMobile(patient.mobile)) return true;
const first = patient.firstName?.trim() ?? '';
const last = patient.lastName?.trim() ?? '';
return first === WALK_IN_STORED_NAME && (last === WALK_IN_STORED_NAME || last === '');
}
/** Fields safe to return on lab case/task APIs — never leak the sentinel mobile. */
export function toPublicPatient(patient: {
id: string;
firstName: string;
lastName: string;
mobile?: string | null;
isWalkIn?: boolean | null;
}): {
id: string;
firstName: string;
lastName: string;
mobile: string;
isWalkIn: boolean;
} {
if (isWalkInPatient(patient)) {
return {
id: patient.id,
firstName: patient.firstName,
lastName: '',
mobile: '',
isWalkIn: true,
};
}
return {
id: patient.id,
firstName: patient.firstName,
lastName: patient.lastName,
mobile: patient.mobile?.trim() ?? '',
isWalkIn: false,
};
}
type PrismaClientLike = PrismaService | Prisma.TransactionClient;
/** One sentinel Patient per clinic for treatments without a named patient. */
@@ -29,8 +76,8 @@ export async function ensureWalkInPatient(
const walkInKey = walkInMobileForOrganization(organizationId);
const created = await prisma.patient.create({
data: {
firstName: 'Walk-in',
lastName: 'Walk-in',
firstName: WALK_IN_STORED_NAME,
lastName: WALK_IN_STORED_NAME,
identification: walkInKey,
mobile: walkInKey,
isWalkIn: true,

View File

@@ -36,6 +36,7 @@ import {
type BillingPriceLine,
type ProsthesisQtyMeta,
} from './calculate-amounts';
import { LAB_CASE_LIST_ORDER_BY } from '../../common/lab-case-listed-at';
import { CreatePaymentDto } from './dto/billing-payment.dto';
import {
resolveBillingSheet,
@@ -649,7 +650,7 @@ export class BillingService {
},
partnerClinic: { select: { name: true } },
},
orderBy: [{ sentAt: 'desc' }, { startedAt: 'desc' }],
orderBy: LAB_CASE_LIST_ORDER_BY,
take: 30,
});
return {

View File

@@ -59,7 +59,7 @@ export class CasesController {
}
@Get('filter-options')
@ApiOperation({ summary: 'Clinics and treatment types for inbox filters' })
@ApiOperation({ summary: 'Clinics and prosthesis types for inbox filters' })
listFilterOptions(@Req() req) {
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
return this.casesService.listFilterOptions(organizationId, req.user.id);

View File

@@ -20,11 +20,13 @@ import { generateLabCaseTasks } from './lab-case-task.generator';
import {
isLabCaseOverdue,
} from '../../common/lab-case-due-date';
import { LAB_CASE_LIST_ORDER_BY } from '../../common/lab-case-listed-at';
import {
aggregateProsthesisGroupsFromTasks,
connectedSelectionGroupIds,
normalizeTaskTeeth,
} from './lab-case-task.util';
import { toPublicPatient } from '../../common/walk-in-patient';
import { hasEffectivePermission } from '../../common/membership-permissions';
import { LAB_CASES_TAB_ACTIVITY_TYPES } from '../../common/lab-case-activity';
import { LabCaseActivityService } from '../notifications/lab-case-activity.service';
@@ -43,7 +45,7 @@ const labCaseListInclude = {
treatment: {
include: {
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true, isWalkIn: true } },
appointment: { select: { startAt: true } },
},
},
@@ -148,7 +150,7 @@ export class CasesService {
treatment: {
include: {
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true, isWalkIn: true } },
},
},
partnerClinic: { select: { id: true, name: true } },
@@ -165,7 +167,7 @@ export class CasesService {
select: { tooth: true, prosthesisTypeCode: true },
},
},
orderBy: [{ startedAt: 'desc' }, { sentAt: 'desc' }, { id: 'desc' }],
orderBy: LAB_CASE_LIST_ORDER_BY,
skip,
take: limit,
}),
@@ -273,7 +275,7 @@ export class CasesService {
treatment: {
include: {
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true, isWalkIn: true } },
},
},
tasks: {
@@ -440,18 +442,31 @@ export class CasesService {
});
if (dto.lines) {
const keepIds = dto.lines.map((l) => l.id).filter(Boolean) as string[];
const existingLines = await tx.labCaseLine.findMany({
where: { labCaseId },
select: { id: true, clientKey: true },
});
const resolvedIds = dto.lines.map((line) => {
if (line.id) return line.id;
return existingLines.find((row) => row.clientKey === line.clientId)?.id ?? null;
});
const keepIds = resolvedIds.filter((id): id is string => Boolean(id));
await tx.labCaseLine.deleteMany({
where: {
labCaseId,
...(keepIds.length ? { id: { notIn: keepIds } } : {}),
...(keepIds.length
? { id: { notIn: keepIds } }
: existingLines.length
? { id: { in: existingLines.map((row) => row.id) } }
: { id: { in: [] } }),
},
});
for (const [index, line] of dto.lines.entries()) {
if (line.id) {
const lineId = resolvedIds[index];
if (lineId) {
const owned = await tx.labCaseLine.findFirst({
where: { id: line.id, labCaseId },
where: { id: lineId, labCaseId },
select: { id: true },
});
if (!owned) {
@@ -460,9 +475,9 @@ export class CasesService {
}
const teeth = normalizeTeeth(line.teeth);
const row = line.id
const row = lineId
? await tx.labCaseLine.update({
where: { id: line.id },
where: { id: lineId },
data: {
clientKey: line.clientId,
sortOrder: index,
@@ -966,6 +981,24 @@ export class CasesService {
labOrganizationId: string,
query: ListLabCasesDto,
): Prisma.LabCaseWhereInput {
const clinicInternal = query.clinicOrganizationId
? { partnerClinicOrganizationId: query.clinicOrganizationId }
: {};
if (query.drafts === 'only') {
return {
AND: [
{
origin: LabCaseOrigin.LAB_INTERNAL,
destinationOrganizationId: labOrganizationId,
startedAt: null,
...clinicInternal,
},
...(query.q?.trim() ? [this.buildSearchWhere(query.q.trim())] : []),
],
};
}
const sentAtFilter: Prisma.DateTimeNullableFilter = { not: null };
if (query.sentFrom) {
@@ -996,15 +1029,13 @@ export class CasesService {
const ownedInternal: Prisma.LabCaseWhereInput = {
origin: LabCaseOrigin.LAB_INTERNAL,
destinationOrganizationId: labOrganizationId,
...(query.clinicOrganizationId
? {
OR: [
{ partnerClinicOrganizationId: query.clinicOrganizationId },
],
}
: {}),
...clinicInternal,
};
if (query.drafts === 'exclude') {
ownedInternal.startedAt = { not: null };
}
if (query.sentFrom || query.sentTo) {
ownedInternal.startedAt = { ...sentAtFilter };
}
@@ -1061,7 +1092,13 @@ export class CasesService {
partnerClinic?: { id: string; name: string } | null;
treatment?: {
organization: { id: string; name: string };
patient: { id: string; firstName: string; lastName: string; mobile: string };
patient: {
id: string;
firstName: string;
lastName: string;
mobile: string;
isWalkIn: boolean;
};
} | null;
}) {
const clinic =
@@ -1072,12 +1109,15 @@ export class CasesService {
};
const displayName = lc.patientDisplayName?.trim() || '';
const [firstName, ...rest] = displayName.split(/\s+/);
const patient = lc.treatment?.patient ?? {
id: '',
firstName: firstName || displayName || clinic.name || '—',
lastName: rest.join(' '),
mobile: lc.patientDisplayMobile?.trim() || '',
};
const patient = lc.treatment?.patient
? toPublicPatient(lc.treatment.patient)
: {
id: '',
firstName: firstName || displayName || clinic.name || '—',
lastName: rest.join(' '),
mobile: lc.patientDisplayMobile?.trim() || '',
isWalkIn: false,
};
return { clinic, patient };
}
@@ -1094,7 +1134,13 @@ export class CasesService {
partnerClinic?: { id: string; name: string } | null;
treatment: {
organization: { id: string; name: string };
patient: { id: string; firstName: string; lastName: string; mobile: string };
patient: {
id: string;
firstName: string;
lastName: string;
mobile: string;
isWalkIn: boolean;
};
} | null;
tasks: Array<{
id: string;
@@ -1145,9 +1191,7 @@ export class CasesService {
locale,
);
const tasksByTooth = this.groupTasks(lc.tasks, prosthesisLabels, lc.toothProsthesis);
const accessToken = lc.sentAt
? await this.labCaseAccess.ensureAccessToken(lc.id)
: null;
const accessToken = await this.labCaseAccess.ensureAccessToken(lc.id);
const shareUrl = accessToken
? this.labCaseAccess.buildShareUrl(accessToken, locale)
: null;

View File

@@ -4,6 +4,7 @@ import {
IsArray,
IsBoolean,
IsDateString,
IsIn,
IsInt,
IsOptional,
IsString,
@@ -53,6 +54,11 @@ export class ListLabCasesDto {
@IsDateString()
sentTo?: string;
/** `only` = unstarted lab-origin drafts; `exclude` = received + started cases. */
@IsOptional()
@IsIn(['only', 'exclude'])
drafts?: 'only' | 'exclude';
@IsOptional()
@Transform(({ value }) => Number(value))
@IsInt()

View File

@@ -2,7 +2,7 @@ import {
HttpStatus,
Injectable,
} from '@nestjs/common';
import { CatalogEntityKind, Prisma } from '@prisma/client';
import { CatalogEntityKind, LabCaseOrigin, Prisma } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import {
buildLabCaseShareUrl,
@@ -10,6 +10,7 @@ import {
} from '../../common/lab-case-access-token';
import { AppException, ErrorCode } from '../../common/errors';
import { hasEffectivePermission } from '../../common/membership-permissions';
import { toPublicPatient } from '../../common/walk-in-patient';
import {
CatalogLabelService,
normalizeCatalogLocale,
@@ -31,7 +32,7 @@ const accessCaseInclude = {
select: {
providerUserId: true,
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true, isWalkIn: true } },
appointment: { select: { providerUserId: true } },
},
},
@@ -69,9 +70,9 @@ export class LabCaseAccessService {
async ensureAccessToken(labCaseId: string): Promise<string | null> {
const labCase = await this.prisma.labCase.findUnique({
where: { id: labCaseId },
select: { sentAt: true, accessToken: true },
select: { sentAt: true, startedAt: true, origin: true, accessToken: true },
});
if (!labCase?.sentAt) return null;
if (!labCase || !this.isShareable(labCase)) return null;
if (labCase.accessToken) return labCase.accessToken;
const accessToken = generateLabCaseAccessToken();
@@ -115,6 +116,7 @@ export class LabCaseAccessService {
);
const prosthesisGroups = await this.buildProsthesisGroups(labCase.id, prosthesisLabels);
const lab = await this.resolveLabOrganization(labCase);
return {
success: true,
@@ -126,19 +128,25 @@ export class LabCaseAccessService {
canToggleCommentVisibility: access.canToggleCommentVisibility,
shareUrl: this.buildShareUrl(token, locale),
sentAt: labCase.sentAt?.toISOString() ?? null,
startedAt: labCase.startedAt?.toISOString() ?? null,
origin: labCase.origin,
dueDate: labCase.dueDate?.toISOString() ?? null,
isOverdue: isLabCaseOverdue(labCase.dueDate, labCase.tasks),
isImportant: labCase.isImportant,
clinic: labCase.treatment?.organization ?? {
id: '',
name: '',
},
lab: labCase.sends[0]?.organization ?? null,
patient: labCase.treatment?.patient ?? {
id: '',
firstName: '',
lastName: '',
name: labCase.referringClinicName?.trim() || '',
},
lab,
patient: labCase.treatment?.patient
? toPublicPatient(labCase.treatment.patient)
: {
id: '',
firstName: '',
lastName: '',
mobile: '',
isWalkIn: false,
},
prosthesisGroups,
},
};
@@ -232,7 +240,16 @@ export class LabCaseAccessService {
private async findCaseByToken(token: string) {
const labCase = await this.prisma.labCase.findFirst({
where: { accessToken: token, sentAt: { not: null } },
where: {
accessToken: token,
OR: [
{ sentAt: { not: null } },
{
origin: LabCaseOrigin.LAB_INTERNAL,
startedAt: { not: null },
},
],
},
include: accessCaseInclude,
});
@@ -259,19 +276,23 @@ export class LabCaseAccessService {
if (organizationId === labOrgId) {
const membership = await this.getMembership(actorUserId, labOrgId);
if (!membership) return { kind: 'denied' };
if (
const canViewCases =
hasEffectivePermission(membership, 'TAB_CASES_READ') ||
hasEffectivePermission(membership, 'TAB_CASES_EDIT');
const canViewTasks =
hasEffectivePermission(membership, 'TAB_TASKS_READ') ||
hasEffectivePermission(membership, 'TAB_TASKS_EDIT')
) {
const canEdit = hasEffectivePermission(membership, 'TAB_TASKS_EDIT');
return {
kind: 'lab',
canEditTaskStatus: canEdit,
canPostComments: canEdit,
canToggleCommentVisibility: canEdit,
};
hasEffectivePermission(membership, 'TAB_TASKS_EDIT');
if (!canViewCases && !canViewTasks) {
return { kind: 'denied' };
}
return { kind: 'denied' };
const canEditTasks = hasEffectivePermission(membership, 'TAB_TASKS_EDIT');
const canEditCases = hasEffectivePermission(membership, 'TAB_CASES_EDIT');
return {
kind: 'lab',
canEditTaskStatus: canEditTasks,
canPostComments: canEditTasks || canEditCases,
canToggleCommentVisibility: canEditTasks || canEditCases,
};
}
if (clinicOrgId && organizationId === clinicOrgId) {
@@ -319,6 +340,27 @@ export class LabCaseAccessService {
});
}
private isShareable(labCase: {
sentAt: Date | null;
startedAt: Date | null;
origin: LabCaseOrigin;
}): boolean {
if (labCase.sentAt) return true;
return labCase.origin === LabCaseOrigin.LAB_INTERNAL && labCase.startedAt != null;
}
private async resolveLabOrganization(labCase: {
destinationOrganizationId: string | null;
sends: Array<{ organization: { id: string; name: string } }>;
}): Promise<{ id: string; name: string } | null> {
if (labCase.sends[0]?.organization) return labCase.sends[0].organization;
if (!labCase.destinationOrganizationId) return null;
return this.prisma.organization.findUnique({
where: { id: labCase.destinationOrganizationId },
select: { id: true, name: true },
});
}
private async getMembership(userId: string, organizationId: string) {
return this.prisma.membership.findFirst({
where: {

View File

@@ -28,13 +28,7 @@ export class LabCaseCommentsService {
private readonly userNotifications: UserNotificationService,
) {}
// ---------- Lab side (TAB_TASKS_EDIT) ----------
async listForLab(caseId: string, labOrganizationId: string, actorUserId: string) {
await this.assertLabCanComment(caseId, labOrganizationId, actorUserId);
const comments = await this.fetchComments(caseId);
return { success: true, data: comments.map((c) => this.mapComment(c, LabCaseCommentSide.LAB)) };
}
// ---------- Lab side (TAB_CASES_* or TAB_TASKS_*) ----------
async listForLabViewer(caseId: string, labOrganizationId: string, actorUserId: string) {
await this.assertLabCanViewCase(caseId, labOrganizationId, actorUserId);
@@ -76,7 +70,7 @@ export class LabCaseCommentsService {
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
actorUserId,
payload: { labCaseId: caseId, commentId: created.id },
requiredPermission: 'TAB_TASKS_READ',
requiredPermissions: ['TAB_CASES_READ', 'TAB_TASKS_READ'],
});
if (created.visibleToClinic) {
@@ -277,8 +271,8 @@ export class LabCaseCommentsService {
) {
await this.assertLabCanViewCase(caseId, labOrganizationId, actorUserId);
const membership = await this.getLabMembership(actorUserId, labOrganizationId);
if (!hasEffectivePermission(membership, 'TAB_TASKS_EDIT')) {
throw new AppException(ErrorCode.PERMISSION_ACCESS_TASKS, HttpStatus.FORBIDDEN);
if (!this.hasLabCasesOrTasksEdit(membership)) {
throw new AppException(this.labAccessDeniedCode(membership), HttpStatus.FORBIDDEN);
}
}
@@ -308,11 +302,8 @@ export class LabCaseCommentsService {
}
const membership = await this.getLabMembership(actorUserId, labOrganizationId);
if (
!hasEffectivePermission(membership, 'TAB_TASKS_READ') &&
!hasEffectivePermission(membership, 'TAB_TASKS_EDIT')
) {
throw new AppException(ErrorCode.PERMISSION_ACCESS_TASKS, HttpStatus.FORBIDDEN);
if (!this.hasLabCasesOrTasksRead(membership)) {
throw new AppException(this.labAccessDeniedCode(membership), HttpStatus.FORBIDDEN);
}
}
@@ -395,12 +386,47 @@ export class LabCaseCommentsService {
}
private async labOrgIdForCase(caseId: string): Promise<string | null> {
const send = await this.prisma.labCaseSend.findFirst({
where: { labCaseId: caseId },
orderBy: { sentAt: 'asc' },
select: { organizationId: true },
const labCase = await this.prisma.labCase.findUnique({
where: { id: caseId },
select: {
destinationOrganizationId: true,
sends: {
orderBy: { sentAt: 'asc' },
take: 1,
select: { organizationId: true },
},
},
});
return send?.organizationId ?? null;
return labCase?.sends[0]?.organizationId ?? labCase?.destinationOrganizationId ?? null;
}
private hasLabCasesOrTasksRead(membership: Parameters<typeof hasEffectivePermission>[0]) {
return (
hasEffectivePermission(membership, 'TAB_CASES_READ') ||
hasEffectivePermission(membership, 'TAB_CASES_EDIT') ||
hasEffectivePermission(membership, 'TAB_TASKS_READ') ||
hasEffectivePermission(membership, 'TAB_TASKS_EDIT')
);
}
private hasLabCasesOrTasksEdit(membership: Parameters<typeof hasEffectivePermission>[0]) {
return (
hasEffectivePermission(membership, 'TAB_CASES_EDIT') ||
hasEffectivePermission(membership, 'TAB_TASKS_EDIT')
);
}
private labAccessDeniedCode(membership: Parameters<typeof hasEffectivePermission>[0]) {
const canViewTasks =
hasEffectivePermission(membership, 'TAB_TASKS_READ') ||
hasEffectivePermission(membership, 'TAB_TASKS_EDIT');
const canViewCases =
hasEffectivePermission(membership, 'TAB_CASES_READ') ||
hasEffectivePermission(membership, 'TAB_CASES_EDIT');
if (canViewTasks && !canViewCases) {
return ErrorCode.PERMISSION_ACCESS_TASKS;
}
return ErrorCode.PERMISSION_ACCESS_CASES;
}
private async clinicOrgIdForCase(caseId: string): Promise<string | null> {

View File

@@ -30,6 +30,8 @@ type FanoutInput = {
recipientUserIds?: string[];
/** Required tab permission when resolving org members. */
requiredPermission?: string;
/** Any-of tab permissions (OR) when resolving org members. */
requiredPermissions?: string[];
/** When set, only clinic members who are the treatment provider for this case. */
labCaseIdForProviderScope?: string;
};
@@ -321,7 +323,11 @@ export class UserNotificationService {
}
private async resolveRecipients(input: FanoutInput): Promise<string[]> {
if (!input.requiredPermission) return [];
const requiredPermissions = [
...(input.requiredPermissions ?? []),
...(input.requiredPermission ? [input.requiredPermission] : []),
];
if (requiredPermissions.length === 0) return [];
const memberships = await this.prisma.membership.findMany({
where: {
@@ -332,7 +338,7 @@ export class UserNotificationService {
});
let userIds = memberships
.filter((m) => hasEffectivePermission(m, input.requiredPermission!))
.filter((m) => requiredPermissions.some((permission) => hasEffectivePermission(m, permission)))
.map((m) => m.userId)
.filter((id) => id !== input.actorUserId);

View File

@@ -12,6 +12,7 @@ import {
} from '../catalog/catalog-label.service';
import { normalizeTaskTeeth } from '../cases/lab-case-task.util';
import { isLabCaseOverdue, startOfUtcDay } from '../../common/lab-case-due-date';
import { labCaseTaskListedAtOrder } from '../../common/lab-case-listed-at';
import { ListLabTasksDto, LocateTaskPageDto, UpdateLabTaskDto } from './dto/tasks.dto';
import {
atomicProsthesisCodes,
@@ -19,6 +20,7 @@ import {
prosthesisGroupLabel,
prosthesisTypeTaskWhere,
} from '../../common/prosthesis-group';
import { toPublicPatient } from '../../common/walk-in-patient';
import { hasEffectivePermission } from '../../common/membership-permissions';
import { LabCaseActivityService } from '../notifications/lab-case-activity.service';
import { UserNotificationService } from '../notifications/user-notification.service';
@@ -35,7 +37,7 @@ const taskListInclude = {
treatment: {
include: {
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true } },
patient: { select: { id: true, firstName: true, lastName: true, isWalkIn: true } },
},
},
},
@@ -177,12 +179,12 @@ export class TasksService {
labCase: this.visibleStartedToLabWhere(labOrganizationId),
},
include: {
labCase: { select: { sentAt: true, startedAt: true } },
labCase: { select: { listedAt: true } },
},
});
const effectiveAt = target?.labCase.sentAt ?? target?.labCase.startedAt;
if (!target || !effectiveAt) {
const listedAt = target?.labCase.listedAt;
if (!target || !listedAt) {
throw new AppException(ErrorCode.CASE_TASK_NOT_FOUND, HttpStatus.NOT_FOUND);
}
@@ -202,7 +204,7 @@ export class TasksService {
where,
listQuery,
{
sentAt: effectiveAt,
listedAt,
labCaseId: target.labCaseId,
sourceKey: target.sourceKey,
tooth: target.tooth,
@@ -593,7 +595,7 @@ export class TasksService {
where: Prisma.LabCaseTaskWhereInput,
query: ListLabTasksDto,
target: {
sentAt: Date;
listedAt: Date;
labCaseId: string;
sourceKey: string;
tooth: string;
@@ -609,26 +611,24 @@ export class TasksService {
throw new AppException(ErrorCode.TASK_PAGE_DATE_SORT_ONLY, HttpStatus.BAD_REQUEST);
}
const sentAt = target.sentAt;
const sameSentAt = {
labCase: {
OR: [{ sentAt }, { AND: [{ sentAt: null }, { startedAt: sentAt }] }],
},
const listedAt = target.listedAt;
const sameListedAt = {
labCase: { listedAt },
};
const tupleBefore: Prisma.LabCaseTaskWhereInput[] = [
{
AND: [sameSentAt, { labCaseId: { lt: target.labCaseId } }],
AND: [sameListedAt, { labCaseId: { lt: target.labCaseId } }],
},
{
AND: [
sameSentAt,
sameListedAt,
{ labCaseId: target.labCaseId },
{ sourceKey: { lt: target.sourceKey } },
],
},
{
AND: [
sameSentAt,
sameListedAt,
{ labCaseId: target.labCaseId },
{ sourceKey: target.sourceKey },
{ tooth: { lt: target.tooth } },
@@ -636,7 +636,7 @@ export class TasksService {
},
{
AND: [
sameSentAt,
sameListedAt,
{ labCaseId: target.labCaseId },
{ sourceKey: target.sourceKey },
{ tooth: target.tooth },
@@ -645,7 +645,7 @@ export class TasksService {
},
{
AND: [
sameSentAt,
sameListedAt,
{ labCaseId: target.labCaseId },
{ sourceKey: target.sourceKey },
{ tooth: target.tooth },
@@ -655,7 +655,7 @@ export class TasksService {
},
{
AND: [
sameSentAt,
sameListedAt,
{ labCaseId: target.labCaseId },
{ sourceKey: target.sourceKey },
{ tooth: target.tooth },
@@ -666,22 +666,14 @@ export class TasksService {
},
];
const sentAtBefore: Prisma.LabCaseTaskWhereInput =
const listedAtBefore: Prisma.LabCaseTaskWhereInput =
dir === 'desc'
? {
labCase: {
OR: [{ sentAt: { gt: sentAt } }, { startedAt: { gt: sentAt } }],
},
}
: {
labCase: {
OR: [{ sentAt: { lt: sentAt } }, { startedAt: { lt: sentAt } }],
},
};
? { labCase: { listedAt: { gt: listedAt } } }
: { labCase: { listedAt: { lt: listedAt } } };
return this.prisma.labCaseTask.count({
where: {
AND: [where, { OR: [sentAtBefore, ...tupleBefore] }],
AND: [where, { OR: [listedAtBefore, ...tupleBefore] }],
},
});
}
@@ -781,8 +773,7 @@ export class TasksService {
case 'dueDate':
orderBy = [
{ labCase: { dueDate: dir } },
{ labCase: { startedAt: 'desc' } },
{ labCase: { sentAt: 'desc' } },
labCaseTaskListedAtOrder('desc'),
{ labCaseId: 'asc' },
{ sourceKey: 'asc' },
{ tooth: 'asc' },
@@ -794,8 +785,7 @@ export class TasksService {
case 'date':
default:
orderBy = [
{ labCase: { startedAt: dir } },
{ labCase: { sentAt: dir } },
labCaseTaskListedAtOrder(dir),
{ labCaseId: 'asc' },
{ sourceKey: 'asc' },
{ tooth: 'asc' },
@@ -825,11 +815,15 @@ export class TasksService {
};
const displayName = task.labCase.patientDisplayName?.trim() || '';
const [firstName, ...rest] = displayName.split(/\s+/);
const patient = task.labCase.treatment?.patient ?? {
id: '',
firstName: firstName || displayName || clinic.name || '—',
lastName: rest.join(' '),
};
const patient = task.labCase.treatment?.patient
? toPublicPatient(task.labCase.treatment.patient)
: {
id: '',
firstName: firstName || displayName || clinic.name || '—',
lastName: rest.join(' '),
mobile: '',
isWalkIn: false,
};
const teeth = normalizeTaskTeeth(task.teeth);
const ponticTeeth = ponticTeethAmong(teeth, task.labCase.toothProsthesis);

View File

@@ -439,9 +439,11 @@
"subtitle": "Lab cases sent from linked clinics. Track progress and flag important tasks.",
"searchPlaceholder": "Search by patient name or mobile…",
"emptyList": "No cases received yet.",
"walkIn": "Walk-in",
"selectCaseHint": "Select a case from the list to view tasks.",
"fromClinic": "From {name}",
"sentAt": "Sent {date}",
"startedAt": "Started {date}",
"dueDateLabel": "Due {date}",
"overdueBadge": "Overdue",
"taskProgressLabel": "Tasks: {completed} of {total} completed",
@@ -534,7 +536,10 @@
"errorSaveCase": "Could not save the case.",
"errorStartCase": "Could not start the case.",
"confirmDeleteDraftCase": "Delete this draft case? This cannot be undone.",
"errorDeleteCase": "Could not delete the case."
"errorDeleteCase": "Could not delete the case.",
"draftsTitle": "Drafts",
"draftsSubtitle": "Unstarted cases you created. Start a draft to add it to the case list.",
"draftsEmpty": "No drafts."
},
"labCaseAccess": {
"pageTitle": "Case tasks",
@@ -547,6 +552,7 @@
},
"tasks": {
"title": "Tasks",
"walkIn": "Walk-in",
"subtitle": "All lab tasks from connected clinics. Filter, sort, and update the status of each step.",
"subtitleOwner": "All lab tasks from connected clinics. Filter, sort, and update the status of each step.",
"loading": "Loading tasks…",

View File

@@ -439,9 +439,11 @@
"subtitle": "پرونده‌های ارسالی از کلینیک‌های متصل. پیشرفت را پیگیری کنید و وظایف مهم را علامت بزنید.",
"searchPlaceholder": "جستجو با نام یا موبایل بیمار…",
"emptyList": "هنوز پرونده‌ای دریافت نشده است.",
"walkIn": "بدون نوبت",
"selectCaseHint": "برای مشاهده وظایف، یک پرونده از فهرست انتخاب کنید.",
"fromClinic": "از {name}",
"sentAt": "ارسال {date}",
"startedAt": "شروع {date}",
"dueDateLabel": "موعد {date}",
"overdueBadge": "عقب‌افتاده",
"taskProgressLabel": "وظایف: {completed} از {total} انجام شده",
@@ -535,7 +537,10 @@
"errorSaveCase": "ذخیره پرونده ممکن نشد.",
"errorStartCase": "شروع پرونده ممکن نشد.",
"confirmDeleteDraftCase": "این پیش‌نویس پرونده حذف شود؟ این کار قابل بازگشت نیست.",
"errorDeleteCase": "حذف پرونده ممکن نشد."
"errorDeleteCase": "حذف پرونده ممکن نشد.",
"draftsTitle": "پیش‌نویس‌ها",
"draftsSubtitle": "پرونده‌های شروع‌نشده‌ای که ساخته‌اید. با شروع پیش‌نویس، به فهرست پرونده‌ها اضافه می‌شود.",
"draftsEmpty": "پیش‌نویسی نیست."
},
"labCaseAccess": {
"pageTitle": "وظایف پرونده",
@@ -548,6 +553,7 @@
},
"tasks": {
"title": "وظایف",
"walkIn": "بدون نوبت",
"subtitle": "همه وظایف لاب از کلینیک‌های متصل. فیلتر، مرتب‌سازی و به‌روزرسانی وضعیت هر مرحله.",
"subtitleOwner": "همه وظایف لاب از کلینیک‌های متصل. فیلتر، مرتب‌سازی و به‌روزرسانی وضعیت هر مرحله.",
"loading": "در حال بارگذاری وظایف…",

View File

@@ -439,9 +439,11 @@
"subtitle": "Labdossiers van gekoppelde klinieken. Volg de voortgang en markeer belangrijke taken.",
"searchPlaceholder": "Zoeken op patiëntnaam of mobiel…",
"emptyList": "Nog geen dossiers ontvangen.",
"walkIn": "Inloop",
"selectCaseHint": "Selecteer een dossier uit de lijst om taken te bekijken.",
"fromClinic": "Van {name}",
"sentAt": "Verzonden {date}",
"startedAt": "Gestart {date}",
"dueDateLabel": "Vervaldatum {date}",
"overdueBadge": "Te laat",
"taskProgressLabel": "Taken: {completed} van {total} voltooid",
@@ -535,7 +537,10 @@
"errorSaveCase": "Case kon niet worden opgeslagen.",
"errorStartCase": "Case kon niet worden gestart.",
"confirmDeleteDraftCase": "Dit concept verwijderen? Dit kan niet ongedaan worden gemaakt.",
"errorDeleteCase": "Case kon niet worden verwijderd."
"errorDeleteCase": "Case kon niet worden verwijderd.",
"draftsTitle": "Concepten",
"draftsSubtitle": "Niet-gestarte cases die u hebt gemaakt. Start een concept om het in de caselijst te zetten.",
"draftsEmpty": "Geen concepten."
},
"labCaseAccess": {
"pageTitle": "Dossiertaken",
@@ -548,6 +553,7 @@
},
"tasks": {
"title": "Taken",
"walkIn": "Inloop",
"subtitle": "Alle labtaken van gekoppelde klinieken. Filter, sorteer en werk de status van elke stap bij.",
"subtitleOwner": "Alle labtaken van gekoppelde klinieken. Filter, sorteer en werk de status van elke stap bij.",
"loading": "Taken laden…",

View File

@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import { formatPatientMobile, formatPatientName } from './caseDetailUtils';
const SENTINEL_MOBILE = '__walkin__:83c493d2-fbbc-4b0f-b8bc-1442305cfb2f';
describe('formatPatientName', () => {
it('uses the localized walk-in label instead of Walk-in Walk-in', () => {
expect(
formatPatientName(
{ firstName: 'Walk-in', lastName: 'Walk-in', mobile: SENTINEL_MOBILE, isWalkIn: true },
'Walk-in',
),
).toBe('Walk-in');
});
it('does not concatenate first and last for a walk-in', () => {
expect(
formatPatientName({ firstName: 'Walk-in', lastName: 'Walk-in', mobile: SENTINEL_MOBILE }),
).toBe('Walk-in');
});
it('joins named patient first and last', () => {
expect(formatPatientName({ firstName: 'Ada', lastName: 'Lovelace', mobile: '+98912' })).toBe(
'Ada Lovelace',
);
});
});
describe('formatPatientMobile', () => {
it('shows a dash for the walk-in sentinel mobile', () => {
expect(
formatPatientMobile({
firstName: 'Walk-in',
lastName: 'Walk-in',
mobile: SENTINEL_MOBILE,
isWalkIn: true,
}),
).toBe('-');
});
it('hides the sentinel even without isWalkIn', () => {
expect(formatPatientMobile({ mobile: SENTINEL_MOBILE })).toBe('-');
});
it('returns the real mobile', () => {
expect(formatPatientMobile({ firstName: 'Ada', lastName: 'Lovelace', mobile: '+98912' })).toBe(
'+98912',
);
});
});

View File

@@ -5,10 +5,42 @@ import type { FdiToothId } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import { toothJobRowsForDetail } from '@/components/treatment/prosthesisTree';
export function formatPatientName(patient: { firstName: string; lastName: string }) {
const WALK_IN_MOBILE_PREFIX = '__walkin__:';
const WALK_IN_STORED_NAME = 'Walk-in';
export function formatPatientName(
patient: { firstName: string; lastName: string; mobile?: string | null; isWalkIn?: boolean },
walkInLabel?: string,
) {
if (isWalkInPatient(patient)) {
return walkInLabel?.trim() || 'Walk-in';
}
return `${patient.firstName} ${patient.lastName}`.trim();
}
export function formatPatientMobile(
patient: { firstName?: string; lastName?: string; mobile?: string | null; isWalkIn?: boolean },
empty = '-',
) {
if (isWalkInPatient(patient)) return empty;
const mobile = patient.mobile?.trim() ?? '';
if (!mobile || mobile.startsWith(WALK_IN_MOBILE_PREFIX)) return empty;
return mobile;
}
function isWalkInPatient(patient: {
isWalkIn?: boolean;
mobile?: string | null;
firstName?: string | null;
lastName?: string | null;
}): boolean {
if (patient.isWalkIn) return true;
if (patient.mobile?.startsWith(WALK_IN_MOBILE_PREFIX)) return true;
const first = patient.firstName?.trim() ?? '';
const last = patient.lastName?.trim() ?? '';
return first === WALK_IN_STORED_NAME && (last === WALK_IN_STORED_NAME || last === '');
}
export function formatCaseDateTime(value: string | null, locale: string) {
if (!value) return '—';
return formatAppDateTime(value, locale, { dateStyle: 'medium', timeStyle: 'short' });

View File

@@ -1,5 +1,7 @@
import { createRoot } from 'react-dom/client';
import { createElement } from 'react';
import { NextIntlClientProvider } from 'next-intl';
import type { AbstractIntlMessages } from 'next-intl';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
import {
@@ -12,6 +14,7 @@ import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
type DownloadCaseSheetPdfArgs = {
labCase: LabCaseDetail;
locale: string;
messages: AbstractIntlMessages;
labels: CaseSheetLabels;
prosthesisCatalog: readonly ProsthesisCatalogEntry[];
fileName?: string;
@@ -35,6 +38,7 @@ function waitForPaint(): Promise<void> {
export async function downloadCaseSheetPdf({
labCase,
locale,
messages,
labels,
prosthesisCatalog,
fileName,
@@ -48,11 +52,15 @@ export async function downloadCaseSheetPdf({
const root = createRoot(host);
try {
root.render(
createElement(CaseSheetPrintLayout, {
labCase,
createElement(NextIntlClientProvider, {
locale,
labels,
prosthesisCatalog,
messages,
children: createElement(CaseSheetPrintLayout, {
labCase,
locale,
labels,
prosthesisCatalog,
}),
}),
);
await waitForPaint();

View File

@@ -3,3 +3,10 @@ export type LabCaseOriginCode = 'CLINIC_DISPATCH' | 'LAB_INTERNAL';
export function isLabGeneratedCase(origin?: string | null): boolean {
return origin === 'LAB_INTERNAL';
}
export function isDraftLabCase(item: {
origin?: string | null;
startedAt?: string | null;
}): boolean {
return item.origin === 'LAB_INTERNAL' && !item.startedAt;
}

View File

@@ -127,12 +127,6 @@ export function isLabCaseCompleted(progress: LabCaseTaskProgress | null | undefi
return progress.completed >= progress.total;
}
/** Detail was sent to lab and the lab case still has open tasks. */
export function canCommentOnDetailLabCase(detail: DetailLike): boolean {
if (!detail.sentAt || !detail.labCaseId) return false;
return !isLabCaseCompleted(detail.taskProgress);
}
/**
* Fresh-draft factories. They live here rather than in the workspace component so the pure
* helpers that build a draft (see `voiceApply.ts`) can call them without importing JSX.

View File

@@ -96,6 +96,7 @@ function linesFromDetail(labCase: LabCaseDetail): LineDraft[] {
interface CaseCreatePanelProps {
labCase: LabCaseDetail;
canEdit: boolean;
prosthesisCatalog?: ProsthesisCatalogEntry[];
onSaved: (detail: LabCaseDetail) => void;
onStarted: (detail: LabCaseDetail) => void;
onDeleted: () => void;
@@ -105,6 +106,7 @@ interface CaseCreatePanelProps {
export function CaseCreatePanel({
labCase,
canEdit,
prosthesisCatalog,
onSaved,
onStarted,
onDeleted,
@@ -132,11 +134,11 @@ export function CaseCreatePanel({
);
const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate));
const [lines, setLines] = useState<LineDraft[]>(() => linesFromDetail(labCase));
const [activeLineId, setActiveLineId] = useState(
() => linesFromDetail(labCase)[0]?.clientId ?? '',
);
const [activeLineId, setActiveLineId] = useState(() => lines[0]?.clientId ?? '');
const [partners, setPartners] = useState<LinkedOrganizationOption[]>([]);
const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>([]);
const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>(
prosthesisCatalog ?? [],
);
const [saving, setSaving] = useState(false);
const [starting, setStarting] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -146,6 +148,7 @@ export function CaseCreatePanel({
const startingRef = useRef(false);
const deletingRef = useRef(false);
const allowPersistWhileStartingRef = useRef(false);
const persistInFlightRef = useRef<Promise<LabCaseDetail | null> | null>(null);
const attachmentInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
@@ -161,13 +164,22 @@ export function CaseCreatePanel({
setDueDate(toDateInputValue(labCase.dueDate));
setLines(nextLines);
setActiveLineId(nextLines[0]?.clientId ?? '');
}, [labCase]);
// Hydrate only when switching drafts — never re-apply the same id after autosave.
// eslint-disable-next-line react-hooks/exhaustive-deps -- labCase.id is the switch key
}, [labCase.id]);
useEffect(() => {
void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined);
void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined);
}, []);
useEffect(() => {
if (prosthesisCatalog?.length) {
setProsthesisOptions(prosthesisCatalog);
return;
}
void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined);
}, [prosthesisCatalog]);
const activeLine = lines.find((l) => l.clientId === activeLineId) ?? lines[0];
const groups =
activeLine?.toothSelectionGroups.length
@@ -223,22 +235,46 @@ export function CaseCreatePanel({
if (startingRef.current && !allowPersistWhileStartingRef.current) {
return null;
}
setSaving(true);
if (persistInFlightRef.current) {
await persistInFlightRef.current;
if (deletingRef.current) return null;
if (startingRef.current && !allowPersistWhileStartingRef.current) return null;
}
const pending = (async () => {
setSaving(true);
try {
const response = await casesApi.update(labCase.id, buildPayload());
setLines((prev) => {
let changed = false;
const next = prev.map((line) => {
const saved = response.data.lines?.find((l) => l.clientId === line.clientId);
if (saved?.id && saved.id !== line.id) {
changed = true;
return { ...line, id: saved.id };
}
return line;
});
if (changed) skipSaveRef.current = true;
return changed ? next : prev;
});
onSaved(response.data);
return response.data;
} catch (error: unknown) {
onError(getUserFacingError(error, tErrors, t('errorSaveCase')));
return null;
} finally {
setSaving(false);
}
})();
persistInFlightRef.current = pending;
try {
const response = await casesApi.update(labCase.id, buildPayload());
setLines((prev) =>
prev.map((line) => {
const saved = response.data.lines?.find((l) => l.clientId === line.clientId);
return saved ? { ...line, id: saved.id } : line;
}),
);
onSaved(response.data);
return response.data;
} catch (error: unknown) {
onError(getUserFacingError(error, tErrors, t('errorSaveCase')));
return null;
return await pending;
} finally {
setSaving(false);
if (persistInFlightRef.current === pending) {
persistInFlightRef.current = null;
}
}
}, [buildPayload, labCase.id, onError, onSaved, t, tErrors]);

View File

@@ -1,7 +1,7 @@
'use client';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useLocale, useMessages, useTranslations } from 'next-intl';
import { Download, MessageSquare } from 'lucide-react';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
@@ -11,10 +11,7 @@ import { CaseToothChartPanel } from '@/components/ui/lab/CaseToothChartPanel';
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import { LabCaseAttachmentPreview } from '@/components/ui/lab/LabCaseAttachmentPreview';
import { LabCaseAttachmentsDialog } from '@/components/ui/lab/LabCaseAttachmentsDialog';
import {
LabCaseShareQrDialog,
LabCaseShareQrThumb,
} from '@/components/ui/lab/LabCaseShareQrDialog';
import { LabCaseShareQr } from '@/components/ui/lab/LabCaseShareQrDialog';
import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
@@ -24,6 +21,7 @@ import {
buildCaseConnectedTeeth,
buildCaseProsthesisRows,
formatCaseDateTime,
formatPatientMobile,
formatPatientName,
latestCaseAttachment,
} from '@/components/lab/caseDetailUtils';
@@ -76,6 +74,7 @@ export interface CaseDetailPanelProps {
canAssignTasks?: boolean;
assigningTaskId?: string | null;
onAssignTask?: (taskId: string, assigneeUserId: string | null) => void;
prosthesisCatalog?: ProsthesisCatalogEntry[];
}
export function CaseDetailPanel({
@@ -98,14 +97,17 @@ export function CaseDetailPanel({
canAssignTasks = false,
assigningTaskId = null,
onAssignTask,
prosthesisCatalog: prosthesisCatalogProp,
}: CaseDetailPanelProps) {
const t = useTranslations('cases');
const tTreatment = useTranslations('treatment');
const intlLocale = useLocale();
const messages = useMessages();
const toast = useToast();
const [attachmentsDialogOpen, setAttachmentsDialogOpen] = useState(false);
const [shareQrDialogOpen, setShareQrDialogOpen] = useState(false);
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>(
prosthesisCatalogProp ?? [],
);
const [downloadingPdf, setDownloadingPdf] = useState(false);
const [externalCodeDraft, setExternalCodeDraft] = useState(labCase.externalCode ?? '');
@@ -114,11 +116,15 @@ export function CaseDetailPanel({
}, [labCase.id, labCase.externalCode]);
useEffect(() => {
if (prosthesisCatalogProp?.length) {
setProsthesisCatalog(prosthesisCatalogProp);
return;
}
void prosthesisCatalogApi
.list()
.then((response) => setProsthesisCatalog(response.data))
.catch(() => {});
}, []);
}, [prosthesisCatalogProp]);
const prosthesisRows = useMemo(
() => buildCaseProsthesisRows(labCase, prosthesisCatalog),
@@ -136,6 +142,7 @@ export function CaseDetailPanel({
await downloadCaseSheetPdf({
labCase,
locale: intlLocale,
messages,
prosthesisCatalog,
labels: {
title: t('caseSheetTitle'),
@@ -151,6 +158,7 @@ export function CaseDetailPanel({
connected: tTreatment('connectedBadge'),
comments: t('caseSheetComments'),
noComments: t('caseSheetNoComments'),
walkIn: t('walkIn'),
},
});
} catch {
@@ -166,7 +174,7 @@ export function CaseDetailPanel({
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold text-text-primary">
{formatPatientName(labCase.patient)}
{formatPatientName(labCase.patient, t('walkIn'))}
</h2>
<LabCaseDueDateBadge dueDate={labCase.dueDate} locale={locale} />
<LabCaseOriginBadge origin={labCase.origin} />
@@ -177,12 +185,16 @@ export function CaseDetailPanel({
</Badge>
) : null}
<p className="text-sm text-text-muted">
{t('patientMobile')}: {labCase.patient.mobile}
{t('patientMobile')}: {formatPatientMobile(labCase.patient)}
</p>
{headerMetaLines}
<p className="text-sm text-text-muted">
{t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })}
</p>
{(labCase.sentAt || labCase.startedAt) ? (
<p className="text-sm text-text-muted">
{labCase.sentAt
? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })
: t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })}
</p>
) : null}
<div className="pt-1 max-w-xs">
<p className="text-sm text-text-muted mb-1">
{t('taskProgressLabel', {
@@ -278,10 +290,7 @@ export function CaseDetailPanel({
</button>
) : null}
{labCase.shareUrl ? (
<LabCaseShareQrThumb
shareUrl={labCase.shareUrl}
onClick={() => setShareQrDialogOpen(true)}
/>
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />
) : null}
</div>
) : null}
@@ -391,14 +400,6 @@ export function CaseDetailPanel({
attachments={labCase.attachments}
loadBlob={loadAttachmentBlob}
/>
{labCase.shareUrl ? (
<LabCaseShareQrDialog
open={shareQrDialogOpen}
onClose={() => setShareQrDialogOpen(false)}
shareUrl={labCase.shareUrl}
/>
) : null}
</div>
);
}

View File

@@ -1,11 +1,12 @@
'use client';
import QRCode from 'react-qr-code';
import { CaseSheetFdiChart } from '@/components/ui/lab/CaseSheetFdiChart';
import { LabCaseShareQrCode } from '@/components/ui/lab/LabCaseShareQrCode';
import {
buildCaseConnectedTeeth,
buildCaseProsthesisRows,
formatCaseDateTime,
formatPatientMobile,
formatPatientName,
} from '@/components/lab/caseDetailUtils';
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
@@ -28,6 +29,7 @@ export type CaseSheetLabels = {
connected: string;
comments: string;
noComments: string;
walkIn: string;
};
type CaseSheetPrintLayoutProps = {
@@ -65,6 +67,7 @@ export function CaseSheetPrintLayout({
(labCase.sends.map((s) => s.organizationName).filter(Boolean).join(', ') || '—');
const fallbackOrder = labCase.id.replace(/-/g, '').slice(0, 8).toUpperCase();
const orderNumber = labCase.externalCode?.trim() || fallbackOrder;
const orderDate = labCase.sentAt ?? labCase.startedAt ?? null;
return (
<div
@@ -114,7 +117,13 @@ export function CaseSheetPrintLayout({
padding: 6,
}}
>
<QRCode value={labCase.shareUrl} size={72} level="M" fgColor="#0f172a" bgColor="#ffffff" />
<LabCaseShareQrCode
value={labCase.shareUrl}
size={72}
fill={false}
fgColor="#0f172a"
bgColor="#ffffff"
/>
</div>
) : null}
</header>
@@ -128,7 +137,7 @@ export function CaseSheetPrintLayout({
}}
>
<MetaBlock label={labels.orderNumber} value={orderNumber} />
<MetaBlock label={labels.orderDate} value={formatCaseDateTime(labCase.sentAt, locale)} />
<MetaBlock label={labels.orderDate} value={formatCaseDateTime(orderDate, locale)} />
<MetaBlock label={labels.dateDue} value={formatCaseDateTime(labCase.dueDate, locale)} />
</section>
@@ -144,8 +153,8 @@ export function CaseSheetPrintLayout({
<PartyBlock label={labels.recipient} title={labName} />
<PartyBlock
label={labels.patient}
title={formatPatientName(labCase.patient)}
subtitle={`${labels.patientId}: ${labCase.patient.mobile}`}
title={formatPatientName(labCase.patient, labels.walkIn)}
subtitle={`${labels.patientId}: ${formatPatientMobile(labCase.patient)}`}
/>
</section>

View File

@@ -6,7 +6,9 @@ import { TaskCaseGroupHeader } from '@/components/ui/lab/TaskCaseGroupHeader';
import { TaskProsthesisGroupHeader } from '@/components/ui/lab/TaskProsthesisGroupHeader';
import { TaskRow } from '@/components/ui/lab/TaskRow';
import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
import { formatPatientName } from '@/components/lab/caseDetailUtils';
import { groupTasksForDisplay } from '@/components/lab/taskListGrouping';
import { isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
import { canEditLabTaskStatus } from '@/components/lab/labTaskStatusDisplay';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { asApiError } from '@/types/api';
@@ -135,7 +137,7 @@ export function CaseTasksFocusView({ token }: CaseTasksFocusViewProps) {
<p className="text-sm text-text-muted break-words">
{t('caseSummary', {
clinic: session.clinic.name,
patient: `${session.patient.firstName} ${session.patient.lastName}`.trim(),
patient: formatPatientName(session.patient, tTasks('walkIn')),
})}
</p>
{session.lab ? (
@@ -185,6 +187,7 @@ export function CaseTasksFocusView({ token }: CaseTasksFocusViewProps) {
viewerSide={session.accessMode === 'lab' ? 'LAB' : 'CLINIC'}
canPost={canPostComments}
canToggleVisibility={canToggleCommentVisibility}
clinicVisibility={!isLabGeneratedCase(session.origin)}
loadComments={async () => {
const r = await labCaseAccessApi.listComments(token);
return r.data;

View File

@@ -1,27 +1,28 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { canEditCases, canEditTasks } from '@/components/shared/permissions';
import { canEditCases } from '@/components/shared/permissions';
import { CaseDetailPanel, CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
import { CaseCreatePanel } from '@/components/ui/lab/CaseCreatePanel';
import { LabCaseProsthesisGroupsList } from '@/components/ui/lab/LabCaseProsthesisGroupsList';
import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
import { TreatmentRailSection } from '@/components/ui/treatment/TreatmentRailSection';
import {
formatCaseDateTime,
formatPatientName,
} from '@/components/lab/caseDetailUtils';
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import { isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
import { isDraftLabCase, isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
import { notificationsApi } from '@/lib/api/notifications';
import { notifyTabBadgesChanged, tabBadgesChangedEventName } from '@/lib/tabBadgeUtils';
import { casesApi } from '@/lib/api/cases';
import { tasksApi } from '@/lib/api/tasks';
import { caseCommentsApi } from '@/lib/api/case-comments';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
@@ -44,6 +45,23 @@ import type {
const PAGE_SIZE = 10;
function draftListItemFromDetail(detail: LabCaseDetail): LabCaseListItem {
return {
id: detail.id,
sentAt: detail.sentAt,
startedAt: detail.startedAt ?? null,
origin: detail.origin ?? 'LAB_INTERNAL',
dueDate: detail.dueDate,
isOverdue: detail.isOverdue,
isImportant: detail.isImportant,
hasUnread: false,
clinic: detail.clinic,
patient: detail.patient,
prosthesisGroups: [],
taskProgress: detail.taskProgress ?? { completed: 0, total: 0 },
};
}
export function CasesPage() {
const t = useTranslations('cases');
const tProsthesis = useTranslations('prosthesis');
@@ -61,6 +79,8 @@ export function CasesPage() {
const [page, setPage] = useState(1);
const [cases, setCases] = useState<LabCaseListItem[]>([]);
const [drafts, setDrafts] = useState<LabCaseListItem[]>([]);
const [draftsExpanded, setDraftsExpanded] = useState(false);
const [pagination, setPagination] = useState<PaginatedLabCases['pagination']>({
page: 1,
limit: PAGE_SIZE,
@@ -85,9 +105,18 @@ export function CasesPage() {
const [assigningTaskId, setAssigningTaskId] = useState<string | null>(null);
const [commentCount, setCommentCount] = useState(0);
const [creatingCase, setCreatingCase] = useState(false);
const selectedCaseIdRef = useRef<string | null>(null);
selectedCaseIdRef.current = selectedCaseId;
const draftsFetchGen = useRef(0);
const detailFetchGen = useRef(0);
const selectedIsDraftRef = useRef(false);
selectedIsDraftRef.current =
(selectedCase != null &&
selectedCase.id === selectedCaseId &&
isDraftLabCase(selectedCase)) ||
drafts.some((item) => item.id === selectedCaseId);
const canEdit = canEditCases(currentOrganization);
const canEditComments = canEditTasks(currentOrganization);
const locale = user?.language ?? 'en';
const prosthesisLabel = useCallback(
@@ -136,6 +165,7 @@ export function CasesPage() {
prosthesisTypeCode: params.prosthesisTypeCode || undefined,
sentFrom: params.sentFrom || undefined,
sentTo: params.sentTo || undefined,
drafts: 'exclude',
page: params.page,
limit: PAGE_SIZE,
});
@@ -150,21 +180,58 @@ export function CasesPage() {
}
};
const loadDetail = async (caseId: string, options?: { silent?: boolean }) => {
if (!options?.silent) {
setLoadingDetail(true);
const loadDrafts = async (
params: { q: string; clinicOrganizationId: string },
options?: { silent?: boolean; keepId?: string },
) => {
const gen = ++draftsFetchGen.current;
try {
const response = await casesApi.list({
q: params.q.trim() || undefined,
clinicOrganizationId: params.clinicOrganizationId || undefined,
drafts: 'only',
page: 1,
limit: 100,
});
if (gen !== draftsFetchGen.current) return;
setDrafts((prev) => {
const items = response.data.items;
const keepId = options?.keepId;
if (keepId && !items.some((item) => item.id === keepId)) {
const kept = prev.find((item) => item.id === keepId);
return kept ? [kept, ...items] : items;
}
return items;
});
} catch (error: unknown) {
if (gen !== draftsFetchGen.current) return;
if (!options?.silent) {
toast.showError(getUserFacingError(error, tErrors, t('errorLoadList')));
}
}
};
const loadDetail = async (caseId: string, options?: { silent?: boolean }) => {
const silent = options?.silent ?? false;
// Silent refreshes must not bump gen — that cancelled the visible load and left
// the workspace stuck on the loading placeholder.
const gen = silent ? detailFetchGen.current : ++detailFetchGen.current;
if (!silent) {
setLoadingDetail(true);
toast.setError('');
}
toast.setError('');
try {
const response = await casesApi.getOne(caseId);
if (gen !== detailFetchGen.current || selectedCaseIdRef.current !== caseId) return;
setSelectedCase(response.data);
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorLoadDetail')));
if (!options?.silent) {
if (gen !== detailFetchGen.current || selectedCaseIdRef.current !== caseId) return;
if (!silent) {
toast.showError(getUserFacingError(error, tErrors, t('errorLoadDetail')));
setSelectedCase(null);
}
} finally {
if (!options?.silent) {
if (!silent && selectedCaseIdRef.current === caseId) {
setLoadingDetail(false);
}
}
@@ -190,28 +257,42 @@ export function CasesPage() {
useEffect(() => {
if (loadingList) return;
if (cases.length === 0) {
if (selectedCaseId !== null) {
setSelectedCaseId(null);
}
return;
}
const urlCaseId = searchParams.get('caseId');
if (urlCaseId && cases.some((item) => item.id === urlCaseId)) {
const visibleIds = new Set([...cases, ...drafts].map((item) => item.id));
const selectionStillOpen =
Boolean(selectedCaseId) &&
(visibleIds.has(selectedCaseId!) || selectedCase?.id === selectedCaseId);
if (urlCaseId && visibleIds.has(urlCaseId)) {
if (selectedCaseId !== urlCaseId) {
setSelectedCaseId(urlCaseId);
setMobileDetailOpen(true);
}
if (drafts.some((item) => item.id === urlCaseId)) {
setDraftsExpanded(true);
}
return;
}
if (selectedCaseId && cases.some((item) => item.id === selectedCaseId)) {
if (selectionStillOpen) {
return;
}
setSelectedCaseId(cases[0].id);
}, [cases, loadingList, searchParams, selectedCaseId]);
if (cases.length > 0) {
setSelectedCaseId(cases[0].id);
return;
}
if (drafts.length > 0) {
setSelectedCaseId(drafts[0].id);
setDraftsExpanded(true);
return;
}
if (selectedCaseId !== null) {
setSelectedCaseId(null);
}
}, [cases, drafts, loadingList, searchParams, selectedCase, selectedCaseId]);
useEffect(() => {
const timeout = setTimeout(() => {
@@ -223,6 +304,10 @@ export function CasesPage() {
sentTo,
page,
});
void loadDrafts({
q: search,
clinicOrganizationId: clinicId,
}, { keepId: selectedCaseIdRef.current ?? undefined });
}, search ? 300 : 0);
return () => clearTimeout(timeout);
// eslint-disable-next-line react-hooks/exhaustive-deps -- debounced search + filter reload
@@ -241,7 +326,11 @@ export function CasesPage() {
},
{ silent: true },
);
if (selectedCaseId) {
void loadDrafts(
{ q: search, clinicOrganizationId: clinicId },
{ silent: true, keepId: selectedCaseIdRef.current ?? undefined },
);
if (selectedCaseId && !selectedIsDraftRef.current) {
void loadDetail(selectedCaseId, { silent: true });
}
};
@@ -258,7 +347,9 @@ export function CasesPage() {
useEffect(() => {
if (selectedCaseId) {
void loadDetail(selectedCaseId);
if (selectedCase?.id !== selectedCaseId) {
void loadDetail(selectedCaseId);
}
void notificationsApi.markCaseRead(selectedCaseId).then(() => {
notifyTabBadgesChanged();
setCases((prev) =>
@@ -267,10 +358,17 @@ export function CasesPage() {
),
);
}).catch(() => undefined);
void tasksApi
.listComments(selectedCaseId)
.then((r) => setCommentCount(r.data.length))
.catch(() => setCommentCount(0));
const selectedIsDraft =
drafts.some((item) => item.id === selectedCaseId) ||
(selectedCase?.id === selectedCaseId && isDraftLabCase(selectedCase));
if (selectedIsDraft) {
setCommentCount(0);
} else {
void caseCommentsApi
.list(selectedCaseId)
.then((r) => setCommentCount(r.data.length))
.catch(() => setCommentCount(0));
}
} else {
setSelectedCase(null);
setCommentCount(0);
@@ -281,21 +379,28 @@ export function CasesPage() {
async function handleAddCase() {
if (!canEdit || creatingCase) return;
setCreatingCase(true);
setDraftsExpanded(true);
toast.setError('');
try {
draftsFetchGen.current += 1;
detailFetchGen.current += 1;
const response = await casesApi.create();
setSelectedCase(response.data);
setSelectedCaseId(response.data.id);
const created = response.data;
const railItem = draftListItemFromDetail(created);
selectedCaseIdRef.current = created.id;
setDrafts((prev) => [railItem, ...prev.filter((item) => item.id !== created.id)]);
setSelectedCase(created);
setSelectedCaseId(created.id);
setMobileDetailOpen(true);
setPage(1);
await loadCases({
q: search,
clinicOrganizationId: clinicId,
prosthesisTypeCode,
sentFrom,
sentTo,
page: 1,
});
setDraftsExpanded(true);
setLoadingDetail(false);
await loadDrafts(
{ q: search, clinicOrganizationId: clinicId },
{ silent: true, keepId: created.id },
);
selectedCaseIdRef.current = created.id;
setSelectedCaseId(created.id);
setDraftsExpanded(true);
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorCreateCase')));
} finally {
@@ -303,9 +408,6 @@ export function CasesPage() {
}
}
const isDraftCase = (item: { origin?: string; startedAt?: string | null }) =>
item.origin === 'LAB_INTERNAL' && !item.startedAt;
function scrollToComments() {
document.getElementById('case-comments')?.scrollIntoView({ behavior: 'smooth' });
}
@@ -386,6 +488,77 @@ export function CasesPage() {
const filterSelectClass = `${FORM_SELECT_CLASS} w-full min-w-0 rounded-md py-1.5 text-xs sm:py-2 sm:text-sm`;
function renderCaseCard(item: LabCaseListItem) {
const isActive = item.id === selectedCaseId;
const draft = isDraftLabCase(item);
return (
<li key={item.id}>
<button
type="button"
onClick={() => {
setSelectedCaseId(item.id);
setMobileDetailOpen(true);
if (draft) setDraftsExpanded(true);
}}
className={`w-full rounded-md border px-3 py-2.5 text-start transition-colors ${
isActive
? 'border-primary bg-primary/5'
: 'border-border hover:border-primary/40'
}`}
>
<div className="flex items-center gap-2">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
<div className="font-medium text-text-primary">
{formatPatientName(item.patient, t('walkIn'))}
</div>
<LabCaseDueDateBadge
dueDate={item.dueDate}
locale={locale}
className="text-[10px]"
/>
{item.isImportant ? (
<Badge variant="warning" fixedWidth={false}>
{t('importantLabel')}
</Badge>
) : null}
<LabCaseOriginBadge origin={item.origin} className="text-[10px]" />
{draft ? (
<Badge variant="default" fixedWidth={false}>
{t('draftBadge')}
</Badge>
) : null}
</div>
{item.hasUnread ? (
<span
className="h-2 w-2 shrink-0 rounded-full bg-badge-warning-fg"
aria-label={t('unreadCase')}
/>
) : null}
</div>
<div className="text-xs text-text-muted mt-0.5">{item.clinic.name}</div>
<div className="mt-1">
<LabCaseProsthesisGroupsList
groups={item.prosthesisGroups}
prosthesisCatalog={prosthesisCatalog}
/>
</div>
<div className="text-[10px] text-text-muted mt-1">
{draft ? t('draftBadge') : formatCaseDateTime(item.startedAt ?? item.sentAt, locale)}
</div>
{draft ? null : (
<div className="mt-1.5">
<CaseTaskProgressBar
completed={item.taskProgress.completed}
total={item.taskProgress.total}
/>
</div>
)}
</button>
</li>
);
}
return (
<div className="space-y-4 min-w-0 overflow-x-hidden">
<div>
@@ -492,82 +665,29 @@ export function CasesPage() {
</Button>
) : null}
<div className="flex-1 min-h-0 overflow-y-auto">
<div className="flex-1 min-h-0 overflow-y-auto space-y-3">
{canEdit || drafts.length > 0 ? (
<TreatmentRailSection
title={t('draftsTitle')}
subtitle={t('draftsSubtitle')}
count={drafts.length}
expanded={draftsExpanded}
onExpandedChange={setDraftsExpanded}
>
{drafts.length === 0 ? (
<p className="text-xs text-text-muted pt-2">{t('draftsEmpty')}</p>
) : (
<ul className="space-y-2 pt-2">{drafts.map(renderCaseCard)}</ul>
)}
</TreatmentRailSection>
) : null}
{loadingList ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : cases.length === 0 ? (
<p className="text-sm text-text-muted">{t('emptyList')}</p>
) : (
<ul className="space-y-2 pr-1">
{cases.map((item) => {
const isActive = item.id === selectedCaseId;
return (
<li key={item.id}>
<button
type="button"
onClick={() => {
setSelectedCaseId(item.id);
setMobileDetailOpen(true);
}}
className={`w-full rounded-md border px-3 py-2.5 text-start transition-colors ${
isActive
? 'border-primary bg-primary/5'
: 'border-border hover:border-primary/40'
}`}
>
<div className="flex items-center gap-2">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
<div className="font-medium text-text-primary">
{formatPatientName(item.patient)}
</div>
<LabCaseDueDateBadge
dueDate={item.dueDate}
locale={locale}
className="text-[10px]"
/>
{item.isImportant ? (
<Badge variant="warning" fixedWidth={false}>
{t('importantLabel')}
</Badge>
) : null}
<LabCaseOriginBadge origin={item.origin} className="text-[10px]" />
{isDraftCase(item) ? (
<Badge variant="default" fixedWidth={false}>
{t('draftBadge')}
</Badge>
) : null}
</div>
{item.hasUnread ? (
<span
className="h-2 w-2 shrink-0 rounded-full bg-badge-warning-fg"
aria-label={t('unreadCase')}
/>
) : null}
</div>
<div className="text-xs text-text-muted mt-0.5">{item.clinic.name}</div>
<div className="mt-1">
<LabCaseProsthesisGroupsList
groups={item.prosthesisGroups}
prosthesisCatalog={prosthesisCatalog}
/>
</div>
<div className="text-[10px] text-text-muted mt-1">
{isDraftCase(item)
? t('draftBadge')
: formatCaseDateTime(item.startedAt ?? item.sentAt, locale)}
</div>
<div className="mt-1.5">
<CaseTaskProgressBar
completed={item.taskProgress.completed}
total={item.taskProgress.total}
/>
</div>
</button>
</li>
);
})}
</ul>
<ul className="space-y-2 pr-1">{cases.map(renderCaseCard)}</ul>
)}
</div>
@@ -608,65 +728,74 @@ export function CasesPage() {
{mobileDetailOpen && selectedCaseId ? (
<MobileDetailBackButton onClick={() => setMobileDetailOpen(false)} />
) : null}
{!selectedCaseId && !loadingList && cases.length === 0 ? (
{!selectedCaseId && !loadingList && cases.length === 0 && drafts.length === 0 ? (
<p className="text-sm text-text-muted">{t('emptyList')}</p>
) : loadingDetail || !selectedCase ? (
) : !selectedCase || (loadingDetail && selectedCase.id !== selectedCaseId) ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : isDraftCase(selectedCase) ? (
) : isDraftLabCase(selectedCase) ? (
<CaseCreatePanel
key={selectedCase.id}
labCase={selectedCase}
canEdit={canEdit}
prosthesisCatalog={prosthesisCatalog}
onSaved={(detail) => {
setSelectedCase(detail);
setCases((prev) =>
prev.map((item) =>
item.id === detail.id
? {
...item,
startedAt: detail.startedAt,
origin: detail.origin,
dueDate: detail.dueDate,
clinic: detail.clinic,
patient: detail.patient,
}
: item,
),
);
const patchItem = (item: LabCaseListItem): LabCaseListItem =>
item.id === detail.id
? {
...item,
startedAt: detail.startedAt,
origin: detail.origin,
dueDate: detail.dueDate,
clinic: detail.clinic,
patient: detail.patient,
}
: item;
setCases((prev) => prev.map(patchItem));
setDrafts((prev) => prev.map(patchItem));
}}
onStarted={(detail) => {
setSelectedCase(detail);
setCases((prev) =>
prev.map((item) =>
item.id === detail.id
? {
...item,
startedAt: detail.startedAt,
origin: detail.origin,
dueDate: detail.dueDate,
clinic: detail.clinic,
patient: detail.patient,
prosthesisGroups: item.prosthesisGroups,
taskProgress: detail.taskProgress,
}
: item,
),
);
setDrafts((prev) => prev.filter((item) => item.id !== detail.id));
setCases((prev) => {
const existing = prev.find((item) => item.id === detail.id);
const item: LabCaseListItem = {
...(existing ?? draftListItemFromDetail(detail)),
startedAt: detail.startedAt ?? null,
origin: detail.origin ?? existing?.origin ?? 'LAB_INTERNAL',
dueDate: detail.dueDate,
isOverdue: detail.isOverdue,
isImportant: detail.isImportant,
clinic: detail.clinic,
patient: detail.patient,
taskProgress:
detail.taskProgress ??
existing?.taskProgress ?? { completed: 0, total: 0 },
};
return [item, ...prev.filter((row) => row.id !== detail.id)];
});
if (page !== 1) setPage(1);
void loadCases({
q: search,
clinicOrganizationId: clinicId,
prosthesisTypeCode,
sentFrom,
sentTo,
page,
page: 1,
});
void loadDrafts({
q: search,
clinicOrganizationId: clinicId,
});
}}
onDeleted={() => {
const remainingOnPage = cases.filter((item) => item.id !== selectedCase.id);
const remainingDrafts = drafts.filter((item) => item.id !== selectedCase.id);
const nextPage = remainingOnPage.length === 0 && page > 1 ? page - 1 : page;
setSelectedCaseId(null);
setSelectedCase(null);
setMobileDetailOpen(false);
setDrafts(remainingDrafts);
if (nextPage !== page) {
setPage(nextPage);
return;
@@ -679,6 +808,10 @@ export function CasesPage() {
sentTo,
page: nextPage,
});
void loadDrafts({
q: search,
clinicOrganizationId: clinicId,
});
}}
onError={toast.showError}
/>
@@ -703,6 +836,7 @@ export function CasesPage() {
onAssignTask={(taskId, assigneeUserId) =>
void handleAssignTask(taskId, assigneeUserId)
}
prosthesisCatalog={prosthesisCatalog}
headerMetaLines={
<p className="text-sm text-text-muted">
{t('fromClinic', { name: selectedCase.clinic.name })}
@@ -714,16 +848,16 @@ export function CasesPage() {
<LabCaseCommentsPanel
caseId={selectedCaseId}
viewerSide="LAB"
canPost={canEditComments}
canToggleVisibility={canEditComments}
canPost={canEdit}
canToggleVisibility={canEdit}
clinicVisibility={!isLabGeneratedCase(selectedCase.origin)}
loadComments={async () => {
const r = await tasksApi.listComments(selectedCaseId);
const r = await caseCommentsApi.list(selectedCaseId);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await tasksApi.addComment(selectedCaseId, {
const r = await caseCommentsApi.add(selectedCaseId, {
body,
visibleToClinic,
});
@@ -732,7 +866,7 @@ export function CasesPage() {
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await tasksApi.setCommentVisibility(commentId, visible);
const r = await caseCommentsApi.setVisibility(commentId, visible);
return r.data;
}}
onError={toast.showError}

View File

@@ -6,16 +6,29 @@ interface LabCaseShareQrCodeProps {
value: string;
size?: number;
className?: string;
fgColor?: string;
bgColor?: string;
/** Stretch to the parent box (thumbs/dialog). Off for fixed-size print capture. */
fill?: boolean;
}
export function LabCaseShareQrCode({ value, size = 128, className }: LabCaseShareQrCodeProps) {
export function LabCaseShareQrCode({
value,
size = 128,
className,
fgColor,
bgColor,
fill = true,
}: LabCaseShareQrCodeProps) {
return (
<QRCode
value={value}
size={size}
level="M"
className={className}
style={{ height: 'auto', maxWidth: '100%', width: '100%' }}
fgColor={fgColor}
bgColor={bgColor}
style={fill ? { height: 'auto', maxWidth: '100%', width: '100%' } : undefined}
/>
);
}

View File

@@ -99,3 +99,25 @@ export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbPr
</button>
);
}
/** Thumb + dialog used on Treatment dispatch, Cases detail, and lab-origin started cases. */
export function LabCaseShareQr({
shareUrl,
className,
}: {
shareUrl: string;
className?: string;
}) {
const [open, setOpen] = useState(false);
const url = shareUrl.trim();
if (!url) return null;
return (
<>
<div className={className}>
<LabCaseShareQrThumb shareUrl={url} onClick={() => setOpen(true)} />
</div>
<LabCaseShareQrDialog open={open} onClose={() => setOpen(false)} shareUrl={url} />
</>
);
}

View File

@@ -7,12 +7,9 @@ import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import type { CaseTaskGroup } from '@/components/lab/taskListGrouping';
import { countCaseTaskProgress } from '@/components/lab/taskListGrouping';
import { formatPatientName } from '@/components/lab/caseDetailUtils';
import { formatAppDate, APP_DATE } from '@/lib/i18n/format';
function formatPatientName(patient: { firstName: string; lastName: string }) {
return `${patient.firstName} ${patient.lastName}`.trim();
}
interface TaskCaseGroupHeaderProps {
caseGroup: CaseTaskGroup;
locale: string;
@@ -36,13 +33,13 @@ export function TaskCaseGroupHeader({
: null;
return (
<div className="sticky top-0 z-10 flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-background-secondary/95 px-3 py-2.5 backdrop-blur-sm supports-[backdrop-filter]:bg-background-secondary/80">
<div className="min-w-0 space-y-0.5 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<p className="text-sm font-semibold text-text-primary truncate">
{t('fromClinic', { name: caseGroup.clinic.name })} ·{' '}
{formatPatientName(caseGroup.patient)}
</p>
<div className="sticky top-0 z-10 space-y-1.5 border-b border-border/80 bg-background-secondary/95 px-3 py-2.5 backdrop-blur-sm supports-[backdrop-filter]:bg-background-secondary/80">
<p className="min-w-0 text-sm font-semibold text-text-primary whitespace-normal break-words">
{t('fromClinic', { name: caseGroup.clinic.name })} ·{' '}
{formatPatientName(caseGroup.patient, t('walkIn'))}
</p>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<LabCaseDueDateBadge
dueDate={caseGroup.caseDueDate}
locale={locale}
@@ -55,32 +52,32 @@ export function TaskCaseGroupHeader({
) : null}
<LabCaseOriginBadge origin={caseGroup.origin} className="text-[10px]" />
</div>
{sentLabel ? (
<p className="text-[11px] text-text-muted">
{t('caseReceivedAt', { date: sentLabel })}
<div className="flex items-center gap-2 shrink-0">
{showCommentsButton && onToggleComments ? (
<button
type="button"
onClick={onToggleComments}
className={`inline-flex h-9 w-9 items-center justify-center rounded-md border ${
commentsOpen
? 'border-primary bg-primary/10 text-primary'
: 'border-border text-text-muted hover:border-primary/40'
}`}
title={t('commentsButton')}
aria-label={t('commentsButton')}
>
<MessageSquare className="h-4 w-4" />
</button>
) : null}
<p className="text-xs text-text-muted tabular-nums">
{t('caseTaskProgress', { completed: progress.completed, total: progress.total })}
</p>
) : null}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{showCommentsButton && onToggleComments ? (
<button
type="button"
onClick={onToggleComments}
className={`inline-flex h-9 w-9 items-center justify-center rounded-md border ${
commentsOpen
? 'border-primary bg-primary/10 text-primary'
: 'border-border text-text-muted hover:border-primary/40'
}`}
title={t('commentsButton')}
aria-label={t('commentsButton')}
>
<MessageSquare className="h-4 w-4" />
</button>
) : null}
<p className="text-xs text-text-muted tabular-nums">
{t('caseTaskProgress', { completed: progress.completed, total: progress.total })}
{sentLabel ? (
<p className="text-[11px] text-text-muted">
{t('caseReceivedAt', { date: sentLabel })}
</p>
</div>
) : null}
</div>
);
}

View File

@@ -16,8 +16,9 @@ import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import { isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
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 { tasksApi } from '@/lib/api/tasks';
import { caseCommentsApi } from '@/lib/api/case-comments';
import type { LabTaskListItem, LabTaskStatus } from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
@@ -40,10 +41,6 @@ interface TaskRowProps {
onShowInCase?: (task: LabTaskListItem) => void | Promise<void>;
}
function formatPatientName(patient: { firstName: string; lastName: string }) {
return `${patient.firstName} ${patient.lastName}`.trim();
}
export function TaskRow({
task,
locale,
@@ -165,7 +162,7 @@ export function TaskRow({
</div>
{flatMode ? (
<p className="text-[11px] text-text-secondary truncate">
{t('fromClinic', { name: task.clinic.name })} · {formatPatientName(task.patient)}
{t('fromClinic', { name: task.clinic.name })} · {formatPatientName(task.patient, t('walkIn'))}
</p>
) : null}
<p className="text-[11px] text-text-muted truncate">
@@ -218,11 +215,11 @@ export function TaskRow({
canToggleVisibility
clinicVisibility={!isLabGeneratedCase(task.origin)}
loadComments={async () => {
const r = await tasksApi.listComments(task.labCaseId);
const r = await caseCommentsApi.list(task.labCaseId);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await tasksApi.addComment(task.labCaseId, {
const r = await caseCommentsApi.add(task.labCaseId, {
body,
visibleToClinic,
});
@@ -230,7 +227,7 @@ export function TaskRow({
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await tasksApi.setCommentVisibility(commentId, visible);
const r = await caseCommentsApi.setVisibility(commentId, visible);
return r.data;
}}
onError={onCommentError}

View File

@@ -28,6 +28,7 @@ import { canEditTasks, canViewTasks } from '@/components/shared/permissions';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { caseCommentsApi } from '@/lib/api/case-comments';
import { tasksApi } from '@/lib/api/tasks';
import type {
LabTaskListItem,
@@ -607,11 +608,11 @@ export function TasksPage() {
canToggleVisibility
clinicVisibility={!isLabGeneratedCase(caseGroup.origin)}
loadComments={async () => {
const r = await tasksApi.listComments(caseGroup.labCaseId);
const r = await caseCommentsApi.list(caseGroup.labCaseId);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await tasksApi.addComment(caseGroup.labCaseId, {
const r = await caseCommentsApi.add(caseGroup.labCaseId, {
body,
visibleToClinic,
});
@@ -619,7 +620,7 @@ export function TasksPage() {
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await tasksApi.setCommentVisibility(commentId, visible);
const r = await caseCommentsApi.setVisibility(commentId, visible);
return r.data;
}}
onError={showError}

View File

@@ -1,72 +0,0 @@
'use client';
import { useEffect, useState } from 'react';
import { FileText } from 'lucide-react';
import { treatmentsApi } from '@/lib/api/treatments';
import type { TreatmentAttachmentMeta } from '@/types/treatment';
interface CaseLatestAttachmentPreviewProps {
attachment: TreatmentAttachmentMeta;
className?: string;
}
export function CaseLatestAttachmentPreview({
attachment,
className = 'aspect-square w-full max-w-[11rem]',
}: CaseLatestAttachmentPreviewProps) {
const [url, setUrl] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
let objectUrl: string | null = null;
void (async () => {
try {
const blob = await treatmentsApi.getAttachmentFileBlob(attachment.id);
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
setUrl(objectUrl);
setFailed(false);
} catch {
if (!cancelled) setFailed(true);
}
})();
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [attachment.id]);
const isImage = attachment.mimeType.startsWith('image/');
const isPdf = attachment.mimeType === 'application/pdf';
return (
<div
className={`${className} rounded-[var(--radius-md)] border border-border/60 bg-background-secondary overflow-hidden`}
title={attachment.fileName}
>
{url && isImage ? (
<img
src={url}
alt={attachment.fileName}
className="h-full w-full object-fill"
/>
) : url && isPdf ? (
<iframe
src={url}
title={attachment.fileName}
className="h-full w-full border-0"
/>
) : (
<div className="flex h-full w-full flex-col items-center justify-center gap-1.5 p-2 text-text-muted">
<FileText className="h-8 w-8 shrink-0 icon-flat" aria-hidden />
<span className="line-clamp-2 text-center text-[10px] leading-tight">
{failed ? 'Preview unavailable' : attachment.fileName}
</span>
</div>
)}
</div>
);
}

View File

@@ -25,10 +25,7 @@ import {
toothJobRowsForDetail,
} from '@/components/treatment/prosthesisTree';
import { LabCaseToothJobsList } from '@/components/ui/lab/LabCaseProsthesisGroupsList';
import {
LabCaseShareQrDialog,
LabCaseShareQrThumb,
} from '@/components/ui/lab/LabCaseShareQrDialog';
import { LabCaseShareQr } from '@/components/ui/lab/LabCaseShareQrDialog';
interface LabCasesDispatchPanelProps {
details: TreatmentDetailDraft[];
@@ -110,7 +107,6 @@ export function LabCasesDispatchPanel({
const tErrors = useTranslations('errors');
const [fetchedCatalog, setFetchedCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [pendingComment, setPendingComment] = useState('');
const [shareQrOpen, setShareQrOpen] = useState(false);
const hasTrackerSummary = Boolean(labCaseSummary && labCaseSummary.labCaseId);
const activeLinkedOrganizations = orgs.filter((o) => o.active);
@@ -179,7 +175,6 @@ export function LabCasesDispatchPanel({
useEffect(() => {
setPendingComment('');
setShareQrOpen(false);
}, [activeLabCase?.clientId]);
function updateActiveLabCase(patch: Partial<LabCaseDraft>) {
@@ -323,12 +318,11 @@ export function LabCasesDispatchPanel({
) : null}
</div>
{shareUrl ? (
<div className="shrink-0 self-start">
<LabCaseShareQrThumb
shareUrl={shareUrl}
onClick={() => setShareQrOpen(true)}
/>
</div>
<LabCaseShareQr
key={shareUrl}
shareUrl={shareUrl}
className="shrink-0 self-start"
/>
) : null}
</div>
@@ -464,13 +458,6 @@ export function LabCasesDispatchPanel({
)}
</div>
) : null}
{shareUrl ? (
<LabCaseShareQrDialog
open={shareQrOpen}
onClose={() => setShareQrOpen(false)}
shareUrl={shareUrl}
/>
) : null}
</div>
);
}

View File

@@ -8,6 +8,8 @@ interface TreatmentRailSectionProps {
subtitle?: string;
count?: number;
defaultExpanded?: boolean;
expanded?: boolean;
onExpandedChange?: (expanded: boolean) => void;
variant?: 'default' | 'attention';
children: React.ReactNode;
}
@@ -17,10 +19,21 @@ export function TreatmentRailSection({
subtitle,
count,
defaultExpanded = false,
expanded: expandedProp,
onExpandedChange,
variant = 'default',
children,
}: TreatmentRailSectionProps) {
const [expanded, setExpanded] = useState(defaultExpanded);
const [uncontrolledExpanded, setUncontrolledExpanded] = useState(defaultExpanded);
const expanded = expandedProp ?? uncontrolledExpanded;
function toggle() {
const next = !expanded;
onExpandedChange?.(next);
if (expandedProp === undefined) {
setUncontrolledExpanded(next);
}
}
const shellClass =
variant === 'attention'
@@ -31,8 +44,8 @@ export function TreatmentRailSection({
<section className={`treatment-rail-section ${shellClass} overflow-hidden`}>
<button
type="button"
onClick={() => setExpanded((open) => !open)}
className="flex w-full items-start gap-2 px-3 py-2.5 text-left hover:bg-background-secondary/30 transition-colors"
onClick={toggle}
className="flex w-full items-start gap-2 px-3 py-2.5 text-start hover:bg-background-secondary/30 transition-colors"
aria-expanded={expanded}
>
<ChevronDown

View File

@@ -0,0 +1,27 @@
import { apiClient } from './client';
import type { LabCaseComment } from '@/types/cases';
export const caseCommentsApi = {
list: async (caseId: string): Promise<{ success: boolean; data: LabCaseComment[] }> => {
const response = await apiClient.get(`/case-comments/${caseId}`);
return response.data;
},
add: async (
caseId: string,
payload: { body: string; visibleToClinic?: boolean },
): Promise<{ success: boolean; data: LabCaseComment }> => {
const response = await apiClient.post(`/case-comments/${caseId}`, payload);
return response.data;
},
setVisibility: async (
commentId: string,
visibleToClinic: boolean,
): Promise<{ success: boolean; data: LabCaseComment }> => {
const response = await apiClient.patch(`/case-comments/item/${commentId}/visibility`, {
visibleToClinic,
});
return response.data;
},
};

View File

@@ -18,12 +18,14 @@ export interface LabCaseAccessSession {
canToggleCommentVisibility: boolean;
shareUrl: string;
sentAt: string | null;
startedAt?: string | null;
origin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL';
dueDate: string | null;
isOverdue: boolean;
isImportant: boolean;
clinic: { id: string; name: string };
lab: { id: string; name: string } | null;
patient: { id: string; firstName: string; lastName: string };
patient: { id: string; firstName: string; lastName: string; isWalkIn?: boolean };
prosthesisGroups: LabCaseAccessProsthesisGroup[];
}

View File

@@ -1,6 +1,5 @@
import { apiClient } from './client';
import type {
LabCaseComment,
LabCaseDetail,
ListLabCasesParams,
PaginatedLabCases,
@@ -159,26 +158,4 @@ export const organizationApi = {
);
return response.data;
},
listConnectionCaseComments: async (
connectionId: string,
caseId: string,
): Promise<{ success: boolean; data: LabCaseComment[] }> => {
const response = await apiClient.get(
`/organizations/connections/${connectionId}/cases/${caseId}/comments`,
);
return response.data;
},
addConnectionCaseComment: async (
connectionId: string,
caseId: string,
body: string,
): Promise<{ success: boolean; data: LabCaseComment }> => {
const response = await apiClient.post(
`/organizations/connections/${connectionId}/cases/${caseId}/comments`,
{ body },
);
return response.data;
},
};

View File

@@ -1,6 +1,5 @@
import { apiClient } from './client';
import type {
LabCaseComment,
LabTaskListItem,
LabTaskStatus,
ListLabTasksParams,
@@ -37,29 +36,4 @@ export const tasksApi = {
const response = await apiClient.patch(`/tasks/${taskId}`, { status });
return response.data;
},
listComments: async (
caseId: string,
): Promise<{ success: boolean; data: LabCaseComment[] }> => {
const response = await apiClient.get(`/case-comments/${caseId}`);
return response.data;
},
addComment: async (
caseId: string,
payload: { body: string; visibleToClinic?: boolean },
): Promise<{ success: boolean; data: LabCaseComment }> => {
const response = await apiClient.post(`/case-comments/${caseId}`, payload);
return response.data;
},
setCommentVisibility: async (
commentId: string,
visibleToClinic: boolean,
): Promise<{ success: boolean; data: LabCaseComment }> => {
const response = await apiClient.patch(`/case-comments/item/${commentId}/visibility`, {
visibleToClinic,
});
return response.data;
},
};

View File

@@ -23,6 +23,7 @@ export interface LabCaseListItem {
firstName: string;
lastName: string;
mobile: string;
isWalkIn?: boolean;
};
prosthesisGroups: LabCaseProsthesisGroup[];
taskProgress: { completed: number; total: number };
@@ -124,6 +125,7 @@ export interface LabCaseDetail {
firstName: string;
lastName: string;
mobile: string;
isWalkIn?: boolean;
};
appointmentStartAt: string | null;
treatmentType: string | null;
@@ -164,6 +166,7 @@ export interface ListLabCasesParams {
prosthesisTypeCode?: string;
sentFrom?: string;
sentTo?: string;
drafts?: 'only' | 'exclude';
}
export interface CasesFilterOptions {
@@ -261,7 +264,7 @@ export interface LabTaskListItem {
caseSentAt: string | null;
origin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL';
clinic: { id: string; name: string };
patient: { id: string; firstName: string; lastName: string };
patient: { id: string; firstName: string; lastName: string; isWalkIn?: boolean };
}
export interface TaskFilterOptions {