Compare commits

...

7 Commits

Author SHA1 Message Date
93d0baa178 fix(tasks): keep case header names readable on mobile
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 5m21s
Production — tag build, push, deploy / deploy (push) Successful in 2m5s
2026-09-22 02:52:42 +03:30
50daac44e3 Merge pull request 'bugfix: cases critical bugs fixed.' (#89) from bugfix/pre-release into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 19m39s
Registry — build, push, deploy / deploy (push) Successful in 1m24s
Reviewed-on: #89
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-09-21 01:57:13 +03:30
705ea92da7 bugfix: cases critical bugs fixed.
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 4m54s
Production — tag build, push, deploy / deploy (push) Successful in 13m25s
2026-09-21 01:44:55 +03:30
b42adecd71 Merge pull request 'fix(ci): prod nginx re-resolves backend via Docker DNS; deploy starts nginx last' (#88) from bug/ci-cd into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 1m14s
Registry — build, push, deploy / deploy (push) Successful in 1m7s
Reviewed-on: #88
Reviewed-by: admin <admin@localhost>
2026-09-20 23:36:40 +03:30
fae7e0cd53 fix(ci): prod nginx re-resolves backend via Docker DNS; deploy starts nginx last
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 58s
Production — tag build, push, deploy / deploy (push) Successful in 46s
2026-09-19 09:26:06 +03:30
0324589928 Merge pull request 'improvement: Build and Push error fixed.' (#87) from feature/billing into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 5m6s
Registry — build, push, deploy / deploy (push) Successful in 1m20s
Reviewed-on: #87
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-09-19 06:23:43 +03:30
851d4a1546 Merge pull request 'feature/billing' (#86) from feature/billing into master
Some checks failed
Registry — build, push, deploy / build-and-push (push) Failing after 25m50s
Registry — build, push, deploy / deploy (push) Has been skipped
Reviewed-on: #86
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-09-19 05:38:12 +03:30
56 changed files with 1223 additions and 579 deletions

View File

@@ -17,13 +17,15 @@ Ops panel at `/admin` (`backend/src/admin/`). Resources are a **manual allowlist
3. **Renamed / removed model** → update or remove the matching resource (broken `getModelByName` breaks `/admin` boot). 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). 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`. 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. 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. 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`. 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. 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`. `passwordHash`, session `token`/`refreshToken`, invite/OTP `tokenHash`/`codeHash`, `LabCase.accessToken`.
`LabCase.listedAt` is `COALESCE(startedAt, sentAt)` via trigger `lab_cases_listed_at_sync` — **not** `GENERATED ALWAYS` (heap rewrite + AdminJS/Prisma update 500). List/filter/show only; `omitListedAt` on new/edit. Never write it from app or AdminJS.

View File

@@ -35,7 +35,7 @@ throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
- Schema: `backend/prisma/schema.prisma` - Schema: `backend/prisma/schema.prisma`
- Always add a migration for schema changes (`npm run prisma:migrate` in backend). - 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`. - 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 ## API responses

View File

@@ -13,3 +13,4 @@ alwaysApply: false
- **Clinic transactions:** RECEIPT → patient cash; PAYMENT → linked lab. **Lab:** RECEIPT/PAYMENT → linked clinic only (no patient ledger). - **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. - 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. - **This publish:** hide Billing for CLINIC orgs via `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` (`hidden-tabs.ts`); lab keeps it.
- Lab case pickers sort by `listedAt` desc (same COALESCE as Cases — never `sentAt` then `startedAt`).

View File

@@ -6,12 +6,12 @@ alwaysApply: false
# Lab case share link # 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. - **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. - **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. - **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). - **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. - **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). - **Auth redirect:** `postAuthRedirect.ts`; dashboard stores path on logout redirect; login stores `?from=` **then** `useEnterAppWhenAuthenticated` consumes **once** after org ready — ❌ do not consume in `useAuth.login()` / `registerTrial`. Invites (join + `password_setup`): `login()` then `navigateIntoAppIfOrgSelected` (no enter-app hook on invite pages).
- **Login page:** wrap `useSearchParams` in `<Suspense>` for `next build`. - **Login page:** wrap `useSearchParams` in `<Suspense>` for `next build`.

View File

@@ -1,6 +1,6 @@
--- ---
description: Lab Cases tab — prosthesis filter, auto-select, list cards, Case Sheet PDF 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 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. - **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`. - **List cards:** `LabCaseProsthesisGroupsList` (catalog color + teeth); same component as Treatment shipments rail; no patient mobile on card. Same-type teeth in one detail share a group; extra type on some teeth is its own group. Job/task lines are `ProsthesisJobLineLabel` everywhere (Treatment dispatch, Cases cards/detail/sheet, Tasks): `13 · Pontic - 14 · PFZ Crown`. No picker category. Colored Pontic + leaf (`prosthesisTypeLabelStyleFromCatalog`; print hex). Inherit the parent font size. Indirect keeps subcategory + leaf (Inlay · Layered ceramic). Join with `PROSTHESIS_JOB_PATH_SEP`.
- **Assignment** in detail only (`TAB_CASES_EDIT`); task status changes on Tasks tab. - **Assignment** in detail only (`TAB_CASES_EDIT`); 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`. - **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`; print layout must stay **hex-only** (Tailwind `lab()`/`oklch` breaks capture). Optional `externalCode` replaces PDF order number when set. - **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). - **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` Skill: `.cursor/skills/lab-cases/SKILL.md`

View File

@@ -1,12 +1,12 @@
--- ---
description: Lab Tasks tab — sort, grouping, filters, prosthesis colors 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 alwaysApply: false
--- ---
# Lab Tasks # 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. - **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. - **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). - **Important first:** `pinImportant=true` (sort pin, not filter).

View File

@@ -10,7 +10,7 @@ Shipped cases get a stable **access token** and share URL. QR + link open a focu
## Data & token lifecycle ## Data & token lifecycle
- **Schema:** `LabCase.accessToken` (`String?`, `@unique`). - **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. - **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`. - **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 | | 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) | | Clinic + `TAB_TREATMENT_EDIT` + **treatment provider** | ✅ | ❌ read-only | Post only (no visibility toggle) |
| Everyone else | ❌ `LAB_CASE_ACCESS_DENIED` | | | | 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 UI | `LabCaseShareQrCode`, `LabCaseShareQrDialog`, thumb in `CaseDetailPanel` **and** Treatment `LabCasesDispatchPanel` |
| QR package | `react-qr-code` (frontend only — no backend QR generation) | | 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). **Treatment lab dispatch:** after send, the same thumb + dialog (same `shareUrl` / token) so the dentist can scan to the focus page. Dest/jobs share a row with the QR; tracker + comments span the card **below** it (not beside it).

View File

@@ -7,11 +7,12 @@ description: Lab Cases tab — list, filters, detail panel, assignment, share QR
**UI:** [`frontend/src/components/ui/lab/CasesPage.tsx`](frontend/src/components/ui/lab/CasesPage.tsx) **UI:** [`frontend/src/components/ui/lab/CasesPage.tsx`](frontend/src/components/ui/lab/CasesPage.tsx)
**Backend:** [`backend/src/modules/cases/`](backend/src/modules/cases/) **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) **Shared prosthesis rows:** [`LabCaseProsthesisGroupsList.tsx`](frontend/src/components/ui/lab/LabCaseProsthesisGroupsList.tsx) (also used in Treatment lab shipments rail)
## List behavior ## 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. - **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`. - **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. - **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. 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`) ## Filters (`GET /cases`)
@@ -52,7 +53,7 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
## Case Sheet PDF ## Case Sheet PDF
**Entry:** Download PDF beside Comments on `CaseDetailPanel`. **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) ### html2canvas + Tailwind v4 (required)

View File

@@ -6,18 +6,19 @@ description: Lab Tasks tab — list, sort, filters, case grouping, prosthesis co
# Lab Tasks # Lab Tasks
Main UI: [`frontend/src/components/ui/lab/TasksPage.tsx`](frontend/src/components/ui/lab/TasksPage.tsx) 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) ## 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) 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) 3. `stepOrder` asc (steps 1→N within that pipeline)
4. `id` asc 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) ## Case grouping (frontend)
@@ -59,10 +60,10 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
- **Important first:** `pinImportant=true` prepends important cases in sort order. - **Important first:** `pinImportant=true` prepends important cases in sort order.
- **Assigned to me:** `assignedToMe=true` filters to current user's assigned tasks only. - **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. - **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`. - **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). - **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. - **Complete animation:** when marking done under in-progress filter, row plays exit animation + success toast before refetch.
## APIs ## APIs
@@ -70,7 +71,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
- `GET /tasks` — paginated flat task list (grouping is client-side when `sortBy=date`) - `GET /tasks` — paginated flat task list (grouping is client-side when `sortBy=date`)
- `PATCH /tasks/:taskId` — update status (only assignee or unassigned task). Completing **`intraoral_scan`** also completes every other `intraoral_scan` task in the same case (case-scoped; catalog first step for all prosthesis types). - `PATCH /tasks/:taskId` — update status (only assignee or unassigned task). 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/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 - `GET /cases/assignable-staff` — staff eligible for task assignment
- `PATCH /cases/:caseId/tasks/:taskId/assign` — assign or unassign (`assigneeUserId` nullable) - `PATCH /cases/:caseId/tasks/:taskId/assign` — assign or unassign (`assigneeUserId` nullable)

View File

@@ -70,13 +70,13 @@ frontend/src/
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Partner list is a **shared** ledger (both orgs see both sides’ rows; always `CONFIRMED`). Money inputs: `AppMoneyInput`. **This publish:** Billing is hidden for CLINIC via `hidden-tabs.ts` (`billingOrgTypes: ['CLINIC']`). See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`. **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):** **Lab case share link (quick ref):**
- Token on first ship → `/{locale}/lab-case/{token}` after login. - Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login.
- **Lab:** view/edit tasks (assignee rules), comments + visibility toggle. - **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). - **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`. - 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. 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 ## 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/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/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-tasks/` | Lab Tasks tab: `listedAt` sort (same as Cases), 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-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/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/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 | | `.cursor/skills/notifications-inbox/` | Header bell inbox: UserNotification fan-out, Socket.IO realtime |

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,6 +2,8 @@ import type { Prisma } from '@prisma/client';
import type { PrismaService } from '../../prisma/prisma.service'; import type { PrismaService } from '../../prisma/prisma.service';
export const WALK_IN_MOBILE_PREFIX = '__walkin__:'; 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 { export function walkInMobileForOrganization(organizationId: string): string {
return `${WALK_IN_MOBILE_PREFIX}${organizationId}`; return `${WALK_IN_MOBILE_PREFIX}${organizationId}`;
@@ -11,6 +13,51 @@ export function isWalkInMobile(mobile: string): boolean {
return mobile.startsWith(WALK_IN_MOBILE_PREFIX); 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; type PrismaClientLike = PrismaService | Prisma.TransactionClient;
/** One sentinel Patient per clinic for treatments without a named patient. */ /** One sentinel Patient per clinic for treatments without a named patient. */
@@ -29,8 +76,8 @@ export async function ensureWalkInPatient(
const walkInKey = walkInMobileForOrganization(organizationId); const walkInKey = walkInMobileForOrganization(organizationId);
const created = await prisma.patient.create({ const created = await prisma.patient.create({
data: { data: {
firstName: 'Walk-in', firstName: WALK_IN_STORED_NAME,
lastName: 'Walk-in', lastName: WALK_IN_STORED_NAME,
identification: walkInKey, identification: walkInKey,
mobile: walkInKey, mobile: walkInKey,
isWalkIn: true, isWalkIn: true,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,10 +5,42 @@ import type { FdiToothId } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import { toothJobRowsForDetail } from '@/components/treatment/prosthesisTree'; 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(); 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) { export function formatCaseDateTime(value: string | null, locale: string) {
if (!value) return '—'; if (!value) return '—';
return formatAppDateTime(value, locale, { dateStyle: 'medium', timeStyle: 'short' }); return formatAppDateTime(value, locale, { dateStyle: 'medium', timeStyle: 'short' });

View File

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

View File

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

View File

@@ -127,12 +127,6 @@ export function isLabCaseCompleted(progress: LabCaseTaskProgress | null | undefi
return progress.completed >= progress.total; 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 * 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. * helpers that build a draft (see `voiceApply.ts`) can call them without importing JSX.

View File

@@ -96,6 +96,7 @@ function linesFromDetail(labCase: LabCaseDetail): LineDraft[] {
interface CaseCreatePanelProps { interface CaseCreatePanelProps {
labCase: LabCaseDetail; labCase: LabCaseDetail;
canEdit: boolean; canEdit: boolean;
prosthesisCatalog?: ProsthesisCatalogEntry[];
onSaved: (detail: LabCaseDetail) => void; onSaved: (detail: LabCaseDetail) => void;
onStarted: (detail: LabCaseDetail) => void; onStarted: (detail: LabCaseDetail) => void;
onDeleted: () => void; onDeleted: () => void;
@@ -105,6 +106,7 @@ interface CaseCreatePanelProps {
export function CaseCreatePanel({ export function CaseCreatePanel({
labCase, labCase,
canEdit, canEdit,
prosthesisCatalog,
onSaved, onSaved,
onStarted, onStarted,
onDeleted, onDeleted,
@@ -132,11 +134,11 @@ export function CaseCreatePanel({
); );
const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate)); const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate));
const [lines, setLines] = useState<LineDraft[]>(() => linesFromDetail(labCase)); const [lines, setLines] = useState<LineDraft[]>(() => linesFromDetail(labCase));
const [activeLineId, setActiveLineId] = useState( const [activeLineId, setActiveLineId] = useState(() => lines[0]?.clientId ?? '');
() => linesFromDetail(labCase)[0]?.clientId ?? '',
);
const [partners, setPartners] = useState<LinkedOrganizationOption[]>([]); const [partners, setPartners] = useState<LinkedOrganizationOption[]>([]);
const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>([]); const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>(
prosthesisCatalog ?? [],
);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [starting, setStarting] = useState(false); const [starting, setStarting] = useState(false);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
@@ -146,6 +148,7 @@ export function CaseCreatePanel({
const startingRef = useRef(false); const startingRef = useRef(false);
const deletingRef = useRef(false); const deletingRef = useRef(false);
const allowPersistWhileStartingRef = useRef(false); const allowPersistWhileStartingRef = useRef(false);
const persistInFlightRef = useRef<Promise<LabCaseDetail | null> | null>(null);
const attachmentInputRef = useRef<HTMLInputElement>(null); const attachmentInputRef = useRef<HTMLInputElement>(null);
useEffect(() => { useEffect(() => {
@@ -161,13 +164,22 @@ export function CaseCreatePanel({
setDueDate(toDateInputValue(labCase.dueDate)); setDueDate(toDateInputValue(labCase.dueDate));
setLines(nextLines); setLines(nextLines);
setActiveLineId(nextLines[0]?.clientId ?? ''); 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(() => { useEffect(() => {
void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined); 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 activeLine = lines.find((l) => l.clientId === activeLineId) ?? lines[0];
const groups = const groups =
activeLine?.toothSelectionGroups.length activeLine?.toothSelectionGroups.length
@@ -223,22 +235,46 @@ export function CaseCreatePanel({
if (startingRef.current && !allowPersistWhileStartingRef.current) { if (startingRef.current && !allowPersistWhileStartingRef.current) {
return null; 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 { try {
const response = await casesApi.update(labCase.id, buildPayload()); return await pending;
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;
} finally { } finally {
setSaving(false); if (persistInFlightRef.current === pending) {
persistInFlightRef.current = null;
}
} }
}, [buildPayload, labCase.id, onError, onSaved, t, tErrors]); }, [buildPayload, labCase.id, onError, onSaved, t, tErrors]);

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,16 +6,29 @@ interface LabCaseShareQrCodeProps {
value: string; value: string;
size?: number; size?: number;
className?: string; 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 ( return (
<QRCode <QRCode
value={value} value={value}
size={size} size={size}
level="M" level="M"
className={className} className={className}
style={{ height: 'auto', maxWidth: '100%', width: '100%' }} fgColor={fgColor}
bgColor={bgColor}
style={fill ? { height: 'auto', maxWidth: '100%', width: '100%' } : undefined}
/> />
); );
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -472,7 +472,18 @@ cd /opt/dyolink/infrastructure
./scripts/prod-remote-deploy.sh v1.0.2 ./scripts/prod-remote-deploy.sh v1.0.2
``` ```
`prod-remote-deploy.sh` pulls backend then frontend with retries. If every attempt RSTs, check Gitea is up and `insecure-registries` includes `wixur.ir:3000`. `prod-remote-deploy.sh` starts backend/frontend, waits until they are healthy, then recreates nginx. SSL nginx uses Docker DNS (`resolver 127.0.0.11 ipv6=off`) so `/api` and `/admin` follow new container IPs.
### `/api` or `/admin` 502 after a tag while the landing page works
Nginx still has a stale backend IP (old SSL config) or started before Nest listened. Recreate nginx only:
```bash
cd /opt/dyolink/infrastructure
docker compose -f docker-compose.prod.yml --env-file .env up -d --force-recreate nginx
```
Then `https://nudentic.ir/api/health` should return JSON.
### View logs ### View logs

View File

@@ -101,6 +101,8 @@ services:
nginx: nginx:
image: ${NGINX_IMAGE:-nginx:alpine} image: ${NGINX_IMAGE:-nginx:alpine}
container_name: dyolink_nginx_prod container_name: dyolink_nginx_prod
# No depends_on: nginx must serve the ACME challenge and the landing page even
# when the backend is down. Deploy ordering lives in the deploy scripts.
ports: ports:
- "80:80" - "80:80"
- "443:443" - "443:443"

View File

@@ -1,15 +1,11 @@
# Generated from nginx.ssl.conf.template — do not edit nginx/generated/default.conf by hand. # Generated from nginx.ssl.conf.template — do not edit nginx/generated/default.conf by hand.
# Re-run: ./scripts/render-nginx-ssl.sh # Re-run: ./scripts/render-nginx-ssl.sh
#
# Dynamic proxy_pass via Docker DNS (127.0.0.11) so nginx keeps working after
# backend/frontend containers get new IPs on a tag deploy. Static `upstream`
# blocks cache the old IP → 502 on /api and /admin. Staging: http-only.conf.
upstream dyolink_backend { resolver 127.0.0.11 valid=10s ipv6=off;
server backend:3000;
keepalive 32;
}
upstream dyolink_frontend {
server frontend:3000;
keepalive 32;
}
server { server {
listen 80; listen 80;
@@ -56,7 +52,8 @@ server {
send_timeout 10; send_timeout 10;
location / { location / {
proxy_pass http://dyolink_frontend; set $frontend_upstream http://frontend:3000;
proxy_pass $frontend_upstream;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection 'upgrade';
@@ -70,7 +67,8 @@ server {
} }
location /api { location /api {
proxy_pass http://dyolink_backend; set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection 'upgrade';
@@ -85,7 +83,8 @@ server {
# AdminJS (Nest, not under /api) — https://nudentic.ir/admin # AdminJS (Nest, not under /api) — https://nudentic.ir/admin
location /admin { location /admin {
proxy_pass http://dyolink_backend; set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection 'upgrade';

View File

@@ -45,6 +45,25 @@ else
echo -e "${YELLOW}Pulling images...${NC}" echo -e "${YELLOW}Pulling images...${NC}"
"${COMPOSE[@]}" pull backend frontend "${COMPOSE[@]}" pull backend frontend
echo -e "${YELLOW}Starting stack...${NC}" echo -e "${YELLOW}Starting stack...${NC}"
"${COMPOSE[@]}" up -d postgres backend frontend
echo -e "${YELLOW}Waiting for backend/frontend healthy before nginx...${NC}"
elapsed=0
backend_status="missing"
frontend_status="missing"
while [ "$elapsed" -lt 300 ]; do
backend_status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' dyolink_backend_prod 2>/dev/null || echo missing)"
frontend_status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' dyolink_frontend_prod 2>/dev/null || echo missing)"
if [ "$backend_status" = "healthy" ] && [ "$frontend_status" = "healthy" ]; then
break
fi
sleep 3
elapsed=$((elapsed + 3))
done
if [ "$backend_status" != "healthy" ] || [ "$frontend_status" != "healthy" ]; then
echo -e "${RED}backend=${backend_status} frontend=${frontend_status} — not healthy in 300s${NC}"
docker logs dyolink_backend_prod --tail 50 || true
exit 1
fi
"${COMPOSE[@]}" up -d --force-recreate nginx "${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d "${COMPOSE[@]}" up -d
fi fi

View File

@@ -66,9 +66,37 @@ if [ -f nginx/nginx.ssl.conf.template ]; then
./scripts/render-nginx-ssl.sh ./scripts/render-nginx-ssl.sh
fi fi
docker compose -f docker-compose.prod.yml --env-file .env up -d --force-recreate nginx COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)
docker compose -f docker-compose.prod.yml --env-file .env up -d
wait_healthy() {
local name="$1"
local seconds="${2:-300}"
local elapsed=0
local status="missing"
echo "Waiting for $name healthy (up to ${seconds}s)..."
while [ "$elapsed" -lt "$seconds" ]; do
status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$name" 2>/dev/null || echo missing)"
if [ "$status" = "healthy" ]; then
echo "$name is healthy"
return 0
fi
sleep 3
elapsed=$((elapsed + 3))
done
echo "$name not healthy after ${seconds}s (last status=${status})"
docker logs "$name" --tail 50 || true
return 1
}
# Backend/frontend first so nginx never caches a dead upstream IP (502 on /api and /admin).
echo "Starting postgres, backend, frontend..."
"${COMPOSE[@]}" up -d postgres backend frontend
wait_healthy dyolink_backend_prod 300
wait_healthy dyolink_frontend_prod 180
echo "Recreating nginx after backends are reachable"
"${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d
echo "=== Status ===" echo "=== Status ==="
docker compose -f docker-compose.prod.yml --env-file .env ps "${COMPOSE[@]}" ps
echo "Health: https://nudentic.ir/api/health" echo "Health: https://nudentic.ir/api/health"
echo "AdminJS: https://nudentic.ir/admin" echo "AdminJS: https://nudentic.ir/admin"