From 705ea92da71136bf40b7bb79ddf1dd54739b54ab Mon Sep 17 00:00:00 2001 From: Admin Date: Mon, 21 Sep 2026 01:44:55 +0330 Subject: [PATCH] bugfix: cases critical bugs fixed. --- .cursor/rules/adminjs.mdc | 8 +- .cursor/rules/backend-nestjs.mdc | 2 +- .cursor/rules/billing.mdc | 1 + .cursor/rules/lab-case-share-link.mdc | 4 +- .cursor/rules/lab-cases.mdc | 9 +- .cursor/rules/lab-tasks.mdc | 4 +- .cursor/skills/lab-case-share-link/SKILL.md | 6 +- .cursor/skills/lab-cases/SKILL.md | 7 +- .cursor/skills/lab-tasks/SKILL.md | 15 +- AGENTS.md | 14 +- .../migration.sql | 32 ++ backend/prisma/schema.prisma | 3 + backend/src/admin/resources.ts | 47 +- backend/src/common/lab-case-listed-at.spec.ts | 16 + backend/src/common/lab-case-listed-at.ts | 20 + backend/src/common/walk-in-patient.spec.ts | 72 +++ backend/src/common/walk-in-patient.ts | 51 +- .../src/modules/billing/billing.service.ts | 3 +- backend/src/modules/cases/cases.controller.ts | 2 +- backend/src/modules/cases/cases.service.ts | 100 ++-- backend/src/modules/cases/dto/cases.dto.ts | 6 + .../modules/cases/lab-case-access.service.ts | 88 +++- .../lab-case-comments.service.ts | 66 ++- .../user-notification.service.ts | 10 +- backend/src/modules/tasks/tasks.service.ts | 70 ++- frontend/messages/en.json | 8 +- frontend/messages/fa.json | 8 +- frontend/messages/nl.json | 8 +- .../components/lab/caseDetailUtils.spec.ts | 50 ++ .../src/components/lab/caseDetailUtils.ts | 34 +- frontend/src/components/lab/caseSheetPdf.ts | 16 +- frontend/src/components/lab/labCaseOrigin.ts | 7 + .../treatment/treatmentDetailRules.ts | 6 - .../src/components/ui/lab/CaseCreatePanel.tsx | 76 ++- .../src/components/ui/lab/CaseDetailPanel.tsx | 51 +- .../ui/lab/CaseSheetPrintLayout.tsx | 19 +- .../components/ui/lab/CaseTasksFocusView.tsx | 5 +- frontend/src/components/ui/lab/CasesPage.tsx | 440 ++++++++++++------ .../components/ui/lab/LabCaseShareQrCode.tsx | 17 +- .../ui/lab/LabCaseShareQrDialog.tsx | 22 + .../components/ui/lab/TaskCaseGroupHeader.tsx | 7 +- frontend/src/components/ui/lab/TaskRow.tsx | 15 +- frontend/src/components/ui/lab/TasksPage.tsx | 7 +- .../treatment/CaseLatestAttachmentPreview.tsx | 72 --- .../ui/treatment/LabCasesDispatchPanel.tsx | 25 +- .../ui/treatment/TreatmentRailSection.tsx | 19 +- frontend/src/lib/api/case-comments.ts | 27 ++ frontend/src/lib/api/lab-case-access.ts | 4 +- frontend/src/lib/api/organization.ts | 23 - frontend/src/lib/api/tasks.ts | 26 -- frontend/src/types/cases.ts | 5 +- 51 files changed, 1119 insertions(+), 534 deletions(-) create mode 100644 backend/prisma/migrations/20260921010000_lab_case_listed_at/migration.sql create mode 100644 backend/src/common/lab-case-listed-at.spec.ts create mode 100644 backend/src/common/lab-case-listed-at.ts create mode 100644 backend/src/common/walk-in-patient.spec.ts create mode 100644 frontend/src/components/lab/caseDetailUtils.spec.ts delete mode 100644 frontend/src/components/ui/treatment/CaseLatestAttachmentPreview.tsx create mode 100644 frontend/src/lib/api/case-comments.ts diff --git a/.cursor/rules/adminjs.mdc b/.cursor/rules/adminjs.mdc index 075e843..3579910 100644 --- a/.cursor/rules/adminjs.mdc +++ b/.cursor/rules/adminjs.mdc @@ -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. diff --git a/.cursor/rules/backend-nestjs.mdc b/.cursor/rules/backend-nestjs.mdc index 9fd02c4..de536e0 100644 --- a/.cursor/rules/backend-nestjs.mdc +++ b/.cursor/rules/backend-nestjs.mdc @@ -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 diff --git a/.cursor/rules/billing.mdc b/.cursor/rules/billing.mdc index 7ebdb20..9e76562 100644 --- a/.cursor/rules/billing.mdc +++ b/.cursor/rules/billing.mdc @@ -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`). diff --git a/.cursor/rules/lab-case-share-link.mdc b/.cursor/rules/lab-case-share-link.mdc index e66ad8b..eadfaf9 100644 --- a/.cursor/rules/lab-case-share-link.mdc +++ b/.cursor/rules/lab-case-share-link.mdc @@ -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 `` for `next build`. diff --git a/.cursor/rules/lab-cases.mdc b/.cursor/rules/lab-cases.mdc index b72480c..ae287d2 100644 --- a/.cursor/rules/lab-cases.mdc +++ b/.cursor/rules/lab-cases.mdc @@ -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` diff --git a/.cursor/rules/lab-tasks.mdc b/.cursor/rules/lab-tasks.mdc index 8812227..06aedce 100644 --- a/.cursor/rules/lab-tasks.mdc +++ b/.cursor/rules/lab-tasks.mdc @@ -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). diff --git a/.cursor/skills/lab-case-share-link/SKILL.md b/.cursor/skills/lab-case-share-link/SKILL.md index 4514f2d..e4fe1f9 100644 --- a/.cursor/skills/lab-case-share-link/SKILL.md +++ b/.cursor/skills/lab-case-share-link/SKILL.md @@ -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). diff --git a/.cursor/skills/lab-cases/SKILL.md b/.cursor/skills/lab-cases/SKILL.md index 3c19eaa..f8660ee 100644 --- a/.cursor/skills/lab-cases/SKILL.md +++ b/.cursor/skills/lab-cases/SKILL.md @@ -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) diff --git a/.cursor/skills/lab-tasks/SKILL.md b/.cursor/skills/lab-tasks/SKILL.md index e750d41..cac2dd7 100644 --- a/.cursor/skills/lab-tasks/SKILL.md +++ b/.cursor/skills/lab-tasks/SKILL.md @@ -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) diff --git a/AGENTS.md b/AGENTS.md index 3888fb7..7b84331 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 | diff --git a/backend/prisma/migrations/20260921010000_lab_case_listed_at/migration.sql b/backend/prisma/migrations/20260921010000_lab_case_listed_at/migration.sql new file mode 100644 index 0000000..5b06af5 --- /dev/null +++ b/backend/prisma/migrations/20260921010000_lab_case_listed_at/migration.sql @@ -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"); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 32c036d..6e79d5e 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") } diff --git a/backend/src/admin/resources.ts b/backend/src/admin/resources.ts index 1a6035c..9a49837 100644 --- a/backend/src/admin/resources.ts +++ b/backend/src/admin/resources.ts @@ -1,12 +1,25 @@ import { getModelByName } from '@adminjs/prisma'; import type { PrismaService } from '../../prisma/prisma.service'; +type AdminActionRequest = { + payload?: Record | null; +}; + type ResourceOptions = { navigation?: { name: string; icon?: string }; - properties?: Record; + 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; + } >; }; @@ -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' }, }), diff --git a/backend/src/common/lab-case-listed-at.spec.ts b/backend/src/common/lab-case-listed-at.spec.ts new file mode 100644 index 0000000..03eb798 --- /dev/null +++ b/backend/src/common/lab-case-listed-at.spec.ts @@ -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' } }, + }); + }); +}); diff --git a/backend/src/common/lab-case-listed-at.ts b/backend/src/common/lab-case-listed-at.ts new file mode 100644 index 0000000..e2e4775 --- /dev/null +++ b/backend/src/common/lab-case-listed-at.ts @@ -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' } } }; +} diff --git a/backend/src/common/walk-in-patient.spec.ts b/backend/src/common/walk-in-patient.spec.ts new file mode 100644 index 0000000..161fb47 --- /dev/null +++ b/backend/src/common/walk-in-patient.spec.ts @@ -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, + }); + }); +}); diff --git a/backend/src/common/walk-in-patient.ts b/backend/src/common/walk-in-patient.ts index 1f79ec4..698d1ae 100644 --- a/backend/src/common/walk-in-patient.ts +++ b/backend/src/common/walk-in-patient.ts @@ -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, diff --git a/backend/src/modules/billing/billing.service.ts b/backend/src/modules/billing/billing.service.ts index 55ed021..3da3513 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -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 { diff --git a/backend/src/modules/cases/cases.controller.ts b/backend/src/modules/cases/cases.controller.ts index 00c02e0..e4a8f84 100644 --- a/backend/src/modules/cases/cases.controller.ts +++ b/backend/src/modules/cases/cases.controller.ts @@ -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); diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index 821efd0..b08976d 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -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; diff --git a/backend/src/modules/cases/dto/cases.dto.ts b/backend/src/modules/cases/dto/cases.dto.ts index 380b325..837aeb4 100644 --- a/backend/src/modules/cases/dto/cases.dto.ts +++ b/backend/src/modules/cases/dto/cases.dto.ts @@ -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() diff --git a/backend/src/modules/cases/lab-case-access.service.ts b/backend/src/modules/cases/lab-case-access.service.ts index 6f623b5..e4a8ae0 100644 --- a/backend/src/modules/cases/lab-case-access.service.ts +++ b/backend/src/modules/cases/lab-case-access.service.ts @@ -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 { 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: { diff --git a/backend/src/modules/lab-case-comments/lab-case-comments.service.ts b/backend/src/modules/lab-case-comments/lab-case-comments.service.ts index 9c994bc..9da87fc 100644 --- a/backend/src/modules/lab-case-comments/lab-case-comments.service.ts +++ b/backend/src/modules/lab-case-comments/lab-case-comments.service.ts @@ -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 { - 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[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[0]) { + return ( + hasEffectivePermission(membership, 'TAB_CASES_EDIT') || + hasEffectivePermission(membership, 'TAB_TASKS_EDIT') + ); + } + + private labAccessDeniedCode(membership: Parameters[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 { diff --git a/backend/src/modules/notifications/user-notification.service.ts b/backend/src/modules/notifications/user-notification.service.ts index 48c7f57..faecdd1 100644 --- a/backend/src/modules/notifications/user-notification.service.ts +++ b/backend/src/modules/notifications/user-notification.service.ts @@ -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 { - 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); diff --git a/backend/src/modules/tasks/tasks.service.ts b/backend/src/modules/tasks/tasks.service.ts index 2e8a71f..ca83424 100644 --- a/backend/src/modules/tasks/tasks.service.ts +++ b/backend/src/modules/tasks/tasks.service.ts @@ -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); diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 8a3f7f6..b144db1 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -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…", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index a6bdd31..6771170 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -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": "در حال بارگذاری وظایف…", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index b7a98fb..b180d9f 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -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…", diff --git a/frontend/src/components/lab/caseDetailUtils.spec.ts b/frontend/src/components/lab/caseDetailUtils.spec.ts new file mode 100644 index 0000000..5420808 --- /dev/null +++ b/frontend/src/components/lab/caseDetailUtils.spec.ts @@ -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', + ); + }); +}); diff --git a/frontend/src/components/lab/caseDetailUtils.ts b/frontend/src/components/lab/caseDetailUtils.ts index 62bdf79..274cb9c 100644 --- a/frontend/src/components/lab/caseDetailUtils.ts +++ b/frontend/src/components/lab/caseDetailUtils.ts @@ -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' }); diff --git a/frontend/src/components/lab/caseSheetPdf.ts b/frontend/src/components/lab/caseSheetPdf.ts index 4ffdf0b..814c4d3 100644 --- a/frontend/src/components/lab/caseSheetPdf.ts +++ b/frontend/src/components/lab/caseSheetPdf.ts @@ -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 { 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(); diff --git a/frontend/src/components/lab/labCaseOrigin.ts b/frontend/src/components/lab/labCaseOrigin.ts index 0fe2a6c..4ac0980 100644 --- a/frontend/src/components/lab/labCaseOrigin.ts +++ b/frontend/src/components/lab/labCaseOrigin.ts @@ -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; +} diff --git a/frontend/src/components/treatment/treatmentDetailRules.ts b/frontend/src/components/treatment/treatmentDetailRules.ts index b86e7c0..6caed1f 100644 --- a/frontend/src/components/treatment/treatmentDetailRules.ts +++ b/frontend/src/components/treatment/treatmentDetailRules.ts @@ -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. diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 5e34c56..8fecaf4 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -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(() => linesFromDetail(labCase)); - const [activeLineId, setActiveLineId] = useState( - () => linesFromDetail(labCase)[0]?.clientId ?? '', - ); + const [activeLineId, setActiveLineId] = useState(() => lines[0]?.clientId ?? ''); const [partners, setPartners] = useState([]); - const [prosthesisOptions, setProsthesisOptions] = useState([]); + const [prosthesisOptions, setProsthesisOptions] = useState( + 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 | null>(null); const attachmentInputRef = useRef(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]); diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index 797d65a..613e001 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -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([]); + const [prosthesisCatalog, setProsthesisCatalog] = useState( + 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({

- {formatPatientName(labCase.patient)} + {formatPatientName(labCase.patient, t('walkIn'))}

@@ -177,12 +185,16 @@ export function CaseDetailPanel({ ) : null}

- {t('patientMobile')}: {labCase.patient.mobile} + {t('patientMobile')}: {formatPatientMobile(labCase.patient)}

{headerMetaLines} -

- {t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })} -

+ {(labCase.sentAt || labCase.startedAt) ? ( +

+ {labCase.sentAt + ? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) }) + : t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })} +

+ ) : null}

{t('taskProgressLabel', { @@ -278,10 +290,7 @@ export function CaseDetailPanel({ ) : null} {labCase.shareUrl ? ( - setShareQrDialogOpen(true)} - /> + ) : null}

) : null} @@ -391,14 +400,6 @@ export function CaseDetailPanel({ attachments={labCase.attachments} loadBlob={loadAttachmentBlob} /> - - {labCase.shareUrl ? ( - setShareQrDialogOpen(false)} - shareUrl={labCase.shareUrl} - /> - ) : null}
); } diff --git a/frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx b/frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx index e0590b2..b39ca21 100644 --- a/frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx +++ b/frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx @@ -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 (
- +
) : null} @@ -128,7 +137,7 @@ export function CaseSheetPrintLayout({ }} > - + @@ -144,8 +153,8 @@ export function CaseSheetPrintLayout({ diff --git a/frontend/src/components/ui/lab/CaseTasksFocusView.tsx b/frontend/src/components/ui/lab/CaseTasksFocusView.tsx index 9e656e3..1b9ba4d 100644 --- a/frontend/src/components/ui/lab/CaseTasksFocusView.tsx +++ b/frontend/src/components/ui/lab/CaseTasksFocusView.tsx @@ -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) {

{t('caseSummary', { clinic: session.clinic.name, - patient: `${session.patient.firstName} ${session.patient.lastName}`.trim(), + patient: formatPatientName(session.patient, tTasks('walkIn')), })}

{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; diff --git a/frontend/src/components/ui/lab/CasesPage.tsx b/frontend/src/components/ui/lab/CasesPage.tsx index 0d67b92..08227a3 100644 --- a/frontend/src/components/ui/lab/CasesPage.tsx +++ b/frontend/src/components/ui/lab/CasesPage.tsx @@ -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([]); + const [drafts, setDrafts] = useState([]); + const [draftsExpanded, setDraftsExpanded] = useState(false); const [pagination, setPagination] = useState({ page: 1, limit: PAGE_SIZE, @@ -85,9 +105,18 @@ export function CasesPage() { const [assigningTaskId, setAssigningTaskId] = useState(null); const [commentCount, setCommentCount] = useState(0); const [creatingCase, setCreatingCase] = useState(false); + const selectedCaseIdRef = useRef(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 ( +
  • + +
  • + ); + } + return (
    @@ -492,82 +665,29 @@ export function CasesPage() { ) : null} -
    +
    + {canEdit || drafts.length > 0 ? ( + + {drafts.length === 0 ? ( +

    {t('draftsEmpty')}

    + ) : ( +
      {drafts.map(renderCaseCard)}
    + )} +
    + ) : null} + {loadingList ? (

    {tCommon('loading')}

    ) : cases.length === 0 ? (

    {t('emptyList')}

    ) : ( -
      - {cases.map((item) => { - const isActive = item.id === selectedCaseId; - - return ( -
    • - -
    • - ); - })} -
    +
      {cases.map(renderCaseCard)}
    )}
    @@ -608,65 +728,74 @@ export function CasesPage() { {mobileDetailOpen && selectedCaseId ? ( setMobileDetailOpen(false)} /> ) : null} - {!selectedCaseId && !loadingList && cases.length === 0 ? ( + {!selectedCaseId && !loadingList && cases.length === 0 && drafts.length === 0 ? (

    {t('emptyList')}

    - ) : loadingDetail || !selectedCase ? ( + ) : !selectedCase || (loadingDetail && selectedCase.id !== selectedCaseId) ? (

    {tCommon('loading')}

    - ) : isDraftCase(selectedCase) ? ( + ) : isDraftLabCase(selectedCase) ? ( { 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={

    {t('fromClinic', { name: selectedCase.clinic.name })} @@ -714,16 +848,16 @@ export function CasesPage() { { - 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} diff --git a/frontend/src/components/ui/lab/LabCaseShareQrCode.tsx b/frontend/src/components/ui/lab/LabCaseShareQrCode.tsx index 389d935..844f6a6 100644 --- a/frontend/src/components/ui/lab/LabCaseShareQrCode.tsx +++ b/frontend/src/components/ui/lab/LabCaseShareQrCode.tsx @@ -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 ( ); } diff --git a/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx b/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx index b10ff77..7676911 100644 --- a/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx +++ b/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx @@ -99,3 +99,25 @@ export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbPr ); } + +/** 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 ( + <> +

    + setOpen(true)} /> +
    + setOpen(false)} shareUrl={url} /> + + ); +} diff --git a/frontend/src/components/ui/lab/TaskCaseGroupHeader.tsx b/frontend/src/components/ui/lab/TaskCaseGroupHeader.tsx index 4c51e1d..0a53586 100644 --- a/frontend/src/components/ui/lab/TaskCaseGroupHeader.tsx +++ b/frontend/src/components/ui/lab/TaskCaseGroupHeader.tsx @@ -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; @@ -41,7 +38,7 @@ export function TaskCaseGroupHeader({

    {t('fromClinic', { name: caseGroup.clinic.name })} ·{' '} - {formatPatientName(caseGroup.patient)} + {formatPatientName(caseGroup.patient, t('walkIn'))}

    void | Promise; } -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({
    {flatMode ? (

    - {t('fromClinic', { name: task.clinic.name })} · {formatPatientName(task.patient)} + {t('fromClinic', { name: task.clinic.name })} · {formatPatientName(task.patient, t('walkIn'))}

    ) : null}

    @@ -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} diff --git a/frontend/src/components/ui/lab/TasksPage.tsx b/frontend/src/components/ui/lab/TasksPage.tsx index e4b7625..4041425 100644 --- a/frontend/src/components/ui/lab/TasksPage.tsx +++ b/frontend/src/components/ui/lab/TasksPage.tsx @@ -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} diff --git a/frontend/src/components/ui/treatment/CaseLatestAttachmentPreview.tsx b/frontend/src/components/ui/treatment/CaseLatestAttachmentPreview.tsx deleted file mode 100644 index c9f363d..0000000 --- a/frontend/src/components/ui/treatment/CaseLatestAttachmentPreview.tsx +++ /dev/null @@ -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(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 ( -

    - {url && isImage ? ( - {attachment.fileName} - ) : url && isPdf ? ( -