Compare commits
8 Commits
feature/em
...
improvemen
| Author | SHA1 | Date | |
|---|---|---|---|
| 5b17aa4115 | |||
| 3a851fb11f | |||
| e17d08dbe0 | |||
| c025022574 | |||
| 3cb579eaac | |||
| f465523991 | |||
| f9eddb4275 | |||
| acb61f2934 |
@@ -17,7 +17,7 @@ Ops panel at `/admin` (`backend/src/admin/`). Resources are a **manual allowlist
|
||||
3. **Renamed / removed model** → update or remove the matching resource (broken `getModelByName` breaks `/admin` boot).
|
||||
4. **New secret fields** (hashes, tokens, share tokens) → hide via `isVisible: false` (list/filter/show/edit).
|
||||
5. **Catalog-like reference data** → list/show/edit only; disable `new` / `delete` / `bulkDelete`.
|
||||
6. **Composite `@@id` only** (no single `@id`) → **do not register** — AdminJS list returns 500 (`Resource does not have an id property`). Examples: `LabCaseDetail`, `LabCaseAttachment`, `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`, `LabCaseSectionReadState`, `MembershipPermission`, read-cursor tables.
|
||||
7. Skip pure join/cursor tables unless ops need them and they have a single id. **Do register** single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock`.
|
||||
|
||||
Auth: `ADMINJS_EMAIL` / `ADMINJS_PASSWORD` — production login disabled if password missing or still `admin123`.
|
||||
|
||||
@@ -47,4 +47,4 @@ Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `g
|
||||
|
||||
## Notifications (inbox + live tabs)
|
||||
|
||||
Header bell: `UserNotification` + Socket.IO. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`.
|
||||
Header bell: `UserNotification` + Socket.IO. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. A case file upload emits `case-section.changed` on that socket (no inbox row) for the case Files/Messages counts. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`.
|
||||
|
||||
@@ -14,10 +14,11 @@ alwaysApply: false
|
||||
- **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
|
||||
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge. Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Case-level steps stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
|
||||
- **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`.
|
||||
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
|
||||
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 48px line box so html2canvas does not clip the glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the order number.
|
||||
- **Detail chrome:** **Mark as important** is centered in the header. Edit and Outsource are at the top of the end column. External code sits under the progress bar in the start column, same width as the bar; billed price is under that. Get PDF, Add case, and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. The sent-date line reads “Outsource {date}”.
|
||||
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Files and Messages show unread counts (`LabCaseSectionReadState`); opening Details does not clear them. `ATTACHMENT_ADDED` is not a sidebar badge. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
|
||||
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 56px line box so html2canvas does not clip the 28px glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print root top padding is 16px portrait / 24px landscape so the QR is not clipped; `html2canvas` `scrollY` is 0. The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). Section rules keep a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename.
|
||||
- **Detail chrome:** **Mark as important** is centered in the header on `lg`. Below that, the header is one compact stack: name and the same QR thumb as desktop (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, the progress bar without a separate “tasks completed” sentence, important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`responsiveFill`). External code sits under the progress bar in the start column, same width as the bar; billed price is under important on `lg`. Get PDF and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource from `lg` up. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
|
||||
- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. The upload queue sits with the toast, so leaving Files or Cases does not cancel it and does not refetch the case; the open case patches from the response. A draft flushes once, then keeps the new file id so autosave does not unlink it. Nginx `/api` uses `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. JSON bodies stay on the Express limit; only multipart is unlimited. Production must recreate nginx from the SSL template. Staging also needs the Windows host nginx reloaded. Do not set `Content-Type: multipart/form-data` by hand.
|
||||
- **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).
|
||||
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. The rail button is full width. Its mic uses the existing lab voice apply on that case’s one plan (blank plan replaced, existing jobs merged). No draft yet → create the draft, then record. 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`
|
||||
|
||||
@@ -47,13 +47,15 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
|
||||
- Comments: shared `LabCaseCommentsPanel` + `tasksApi` comment routes (`viewerSide="LAB"`). Newest-first; sent/received use logical start/end alignment (RTL-safe). Compact `h-9` composer with primary send + visibility controls. Lab-origin cases (`LAB_INTERNAL`, including after Start) are visible to lab comments/mark-read — do not require `sentAt` / `LabCaseSend`. Generated cases hide the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. Received cases use it for the clinic. Lab-to-lab cases use the same eye button for the sending lab: off keeps the comment on this lab, on shows it in that lab's handoff and notifies them. Comments that already existed on a lab-to-lab case stay shared.
|
||||
- Mark read: `POST /notifications/mark-case-read` on select (Cases tab badge)
|
||||
- FDI chart (`CaseToothChartPanel`): prosthesis colors + **connected bridge dots** from `selectionGroupId` (`buildCaseConnectedTeeth` / `buildCaseProsthesisRows` in `caseDetailUtils.ts`).
|
||||
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header. External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under that. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, Add case, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width). There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use that same width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end.
|
||||
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header on `lg`. Below `lg` the header is one compact stack: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width from `lg` up). **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end. Each file being uploaded is its own card with a progress bar (one request per file). The job lives above the page, so leaving Files or Cases does not cancel it; coming back shows the same card. Finishing patches the open case from the upload response. It does not fetch the case again. A draft flushes once before the batch, then keeps the new file id locally so a later autosave does not unlink it. Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only.
|
||||
- **Section badges:** Files counts `ATTACHMENT_ADDED` and Messages counts `LAB_COMMENT` / `CLINIC_COMMENT`, after `LabCaseSectionReadState`, excluding the actor. `GET /cases/:id/section-counts`. `POST /cases/:id/sections/:section/read` only when that tab is open and its count is greater than 0. Opening Details does not clear them. Uploads emit `case-section.changed` to other lab members who can read Cases or Tasks (no inbox card). The existing socket turns that into `tab-badges-changed`. `ATTACHMENT_ADDED` is not a sidebar Cases/Tasks/Treatment count. `LabCaseSectionReadState` has a composite id and stays off the AdminJS allowlist.
|
||||
- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `send_timeout 3600s`, `proxy_request_buffering off`, proxy read/send 3600s). The server-level `send_timeout 10` would cut a paused download, so `/api` overrides it. JSON and urlencoded bodies stay on the Express limits; only multipart is unlimited. Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). The attachment row and the case link are one transaction; the disk file is removed only after that transaction commits on delete, and only for a lab-owned upload. A failed activity row does not fail the upload. Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. Releasing this needs `prisma migrate deploy` (the backend container runs it on start; Postgres 15) and a nginx recreate from `nginx.ssl.conf.template`. Staging’s Windows host nginx is a separate paste-and-reload of `windows-edge-http.conf`; Docker alone leaves the 50MB edge. Uploaded bytes live on the backend container disk (`/app/uploads`, no volume) and can fill that disk.
|
||||
- **Case Sheet PDF** — see below.
|
||||
- **Share link (sent cases):** `shareUrl` on detail; attachment preview left + QR thumb right; `LabCaseShareQrDialog` (`react-qr-code`). Full flow: `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
## Case Sheet PDF
|
||||
|
||||
**Entry:** Get PDF on `CaseDetailPanel` (primary, same width as Outsource, no icon) — menu chooses portrait or landscape. Organization name uses a 48px line box so the glyphs are not clipped. The page stays LTR in every locale. On the Persian sheet that name is a shrink-wrapped `inline-block` (`data-case-sheet-org-text`, `direction: ltr` unless the name itself contains Arabic script, `letter-spacing` and `word-spacing` `0px`) so html2canvas does not stretch the words across the header column. Party and meta values use `printRtlValueStyle`: Arabic script stays RTL; Latin stays LTR, isolated, and right-aligned under the Persian label. `FA_RULE_DROP` (6px) is the only extra rule margin, so Persian descenders clear the line.
|
||||
**Entry:** Get PDF on `CaseDetailPanel` (primary, same width as Outsource, no icon) — menu chooses portrait or landscape. Organization name uses a 56px line box so the 28px glyphs are not clipped. The print root has top padding (16px portrait, 24px landscape) so the header QR is not clipped at the page edge. `html2canvas` uses `scrollY: 0` (the host is `position: fixed`). The page stays LTR in every locale. On the Persian sheet that name is a shrink-wrapped `inline-block` (`data-case-sheet-org-text`, `direction: ltr` unless the name itself contains Arabic script, `letter-spacing` and `word-spacing` `0px`) so html2canvas does not stretch the words across the header column. Party and meta values use `printRtlValueStyle`: Arabic script stays RTL; Latin stays LTR, isolated, and right-aligned under the Persian label. Section rules use a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) is the only extra margin, for Persian descenders.
|
||||
**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)
|
||||
@@ -70,12 +72,12 @@ Stock `html2canvas` **cannot** parse `lab()` / `oklch()` from app CSS. Do **not*
|
||||
### Layout conventions
|
||||
|
||||
- Portrait and landscape use this same tree; only the page pixel size changes. One A4 page, scaled to fit — never slice the canvas.
|
||||
- Header is a **flex** row: title at the start, Nudentic lockup centered, share QR at the end (same row when there is no QR). The QR is `LabCaseShareQrCode` `fill={false}` inside the padded frame. Do not put that SVG in a table cell — html2canvas then paints an empty box.
|
||||
- Header is a **flex** row: title at the start, Nudentic lockup centered, share QR at the end (same row when there is no QR). The QR is `LabCaseShareQrCode` `fill={false}` inside the padded frame. Do not put that SVG in a table cell — html2canvas then paints an empty box. Print-root top padding (16px portrait, 24px landscape) keeps the QR off the page edge.
|
||||
- Sections: meta → parties → **Tooth Chart** heading *above* the horizontal rule → chart → **Prosthesis** rows (SVG rect + text, so the border stays on the label; the chart stays above a long job list) → Comments.
|
||||
- Prosthesis print ink and selected teeth use the heaviest family swatch (`prosthesisTypePrintColorFromCatalog`), not `prosthesisTypeLabelColorFromCatalog`. Persian print labels and values use `letter-spacing` and `word-spacing` `0px` (not `normal`). Positive letter-spacing makes html2canvas draw each letter alone, so the script stops joining. A full-width `direction: rtl` box also inserts gaps between Latin words — keep RTL only on text that itself contains Arabic script. Prosthesis SVG text is anchored on the inline start for the locale (`fa` starts at the right padding with `direction: rtl`).
|
||||
- Chart is [`CaseSheetFdiChart`](frontend/src/components/ui/lab/CaseSheetFdiChart.tsx): realistic FDI paths, hex fills, always-on Upper/Lower arch captions. An arch-level job (`UA`/`LA`) boxes that arch with a light tint and a border in the same swatch. Unselected teeth are outline only; a root prosthesis colors the root and a crown prosthesis colors the crown. Width is 85% of the page; glyph height stays capped; both arches share the upper column widths. The upper caption has a larger gap above the teeth. Tooth-to-number and number-to-midline gaps match on both arches. A bridge is the chart’s read-only mark: a 10px `#009cae` dot on the column boundary in that tooth-to-number gap, plus a primary line across a middle tooth.
|
||||
- Connected badge: bold + underline inside the prosthesis SVG, with a gap (`dx`) before the word so it does not sit on the job text.
|
||||
- Order number: `externalCode.trim()` when set, else short case id (`id` without hyphens, first 8, uppercased).
|
||||
- Order number: `externalCode.trim()` when set, else short case id (`id` without hyphens, first 8, uppercased). Download name is `case-sheet-{orderNumber}.pdf` (`caseSheetPdfFileName`); filesystem-unsafe characters in the code are replaced with `-`.
|
||||
- Share QR when `shareUrl` present.
|
||||
|
||||
### API
|
||||
|
||||
@@ -19,6 +19,8 @@ Do **not** clear tab badges when marking an inbox card read.
|
||||
|
||||
## Live cascade (one socket)
|
||||
|
||||
`case-section.changed` is the same socket and the same `notifyTabBadgesChanged()` call, for a case file upload. It does **not** write a `UserNotification` row and does not change the bell.
|
||||
|
||||
On `notification.created`, [`RealtimeProvider`](frontend/src/lib/realtime/RealtimeProvider.tsx):
|
||||
|
||||
1. Updates inbox state (bell list + unread).
|
||||
|
||||
@@ -13,9 +13,10 @@ Frontend hook: [`frontend/src/lib/hooks/useTabBadgeCounts.ts`](frontend/src/lib/
|
||||
|
||||
## Models
|
||||
|
||||
- **`LabCaseActivity`** — append-only events: `CASE_SENT`, `CLINIC_COMMENT`, `LAB_COMMENT`, `CASE_IMPORTANT`, `CASE_AMENDED` (stub for Step 7), `TASK_COMPLETED` (timeline only), `TASK_ASSIGNED`, `CASE_COMPLETED`
|
||||
- **`LabCaseActivity`** — append-only events: `CASE_SENT`, `CLINIC_COMMENT`, `LAB_COMMENT`, `CASE_IMPORTANT`, `CASE_AMENDED` (stub for Step 7), `TASK_COMPLETED` (timeline only), `TASK_ASSIGNED`, `CASE_COMPLETED`, `ATTACHMENT_ADDED` (case Files tab only — **not** a sidebar count)
|
||||
- **`LabCaseUserTabReadState`** — per user/org/tab cursor (`TASKS`) for sidebar badge clearing on tab visit.
|
||||
- **`LabCaseUserReadState`** — per user/org/labCase cursor; drives Cases tab count and `hasUnread` on case list cards
|
||||
- **`LabCaseSectionReadState`** — per user/org/case/section cursor (`FILES`, `MESSAGES`) for the counts on a case’s own tabs. Composite `@@id`; do not register it in AdminJS. Opening Details does not move these cursors. `ATTACHMENT_ADDED` feeds Files only.
|
||||
|
||||
## Tab badge buckets (Option B)
|
||||
|
||||
@@ -49,7 +50,7 @@ Counts exclude events where `actorUserId === current user`. Clinic `LAB_COMMENT`
|
||||
|
||||
After mutations, frontend calls `notifyTabBadgesChanged()` (window event).
|
||||
|
||||
**Live path:** inbox Socket.IO `notification.created` also dispatches that event so sidebar counts refresh without navigation. **Only currently mounted** feature pages soft-reload list data on the same event (silent; Treatment form/draft untouched). Unmounted tabs do not fetch list data until the user opens them. See `.cursor/skills/notifications-inbox/SKILL.md`.
|
||||
**Live path:** inbox Socket.IO `notification.created` also dispatches that event so sidebar counts refresh without navigation. Case file uploads emit `case-section.changed` (no `UserNotification` row) and the client turns that into the same event. The open Files or Messages tab marks itself read only when its count is greater than 0. **Only currently mounted** feature pages soft-reload list data on the same event (silent; Treatment form/draft untouched). Unmounted tabs do not fetch list data until the user opens them. See `.cursor/skills/notifications-inbox/SKILL.md`.
|
||||
|
||||
## Frontend pattern (same as org connections)
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ Right-column entry is **not** a three-step wizard. Type dropdown + `TreatmentDet
|
||||
| **Lab** | `LabCasesDispatchPanel` in the chart slot | Lab-dependent type + user clicks **Lab dispatch** (or rail / Go to dispatch). Auto-ensures a shipment draft (teeth/arch not required to create the draft). **No default lab or prosthesis type** on a new detail (including siblings in the same plan). Last **3 sent** labs appear as chips under search — pick is explicit. Comments stay on the dispatch panel. After send, the same case QR as lab Cases is shown (`shareUrl`): dest/jobs share a row with the thumb; tracker + comments are full width below. |
|
||||
|
||||
- Prosthesis types are assigned on the chart (`ProsthesisAssignChart` + `ProsthesisJobPopover`; stacking / disable / suggestion slots in `pickerPolicy()` in `prosthesisTree.ts`). The picker is two columns (`4fr` wrapping category grid / `1fr` add-ons) with a vertical `border-e` divider. Category and subcategory tiles (and matching leaves) show SVGs from `src/assets/prosthesis-catalog` (served from `public/prosthesis-catalog`) via `ProsthesisCatalogIcon` + `prosthesisCatalogIcons.ts`. Production Docker must copy `public/` into the standalone image (see `.cursor/rules/frontend-assets.mdc`). **Category / filled addon** tiles use `md` icons on a shared `items-end` stage and a reserved two-line label (`/` wraps with `<wbr>`). **Subcategory / leaf** tiles use `sm` icons, one-line ellipsis labels, and vertically center icon+label (`min-h-[4.25rem]`); implant/post-core use a taller box so they stay inside the card. Family pastels: `PROSTHESIS_CATEGORY_COLORS` (indirect/veneer sky, implant green, pontic orange, removable pink, appliance aqua). Screen type names: `prosthesisTypeLabelStyleFromCatalog`; Case Sheet print hex: `prosthesisTypeLabelColorFromCatalog`. Category tiles keep the wrapping `minmax(8rem, 1fr)` grid and stretch to fill the overlay; expanded children use `minmax(10.2rem, 1fr)` with a parent-colored **L** rail sized to the first child card (not a per-card tree). Parent-bar back arrow is black. Child labels stay one line and ellipsize (`…`) when they overflow. **Add detail**, Lab dispatch, and Chart share one control width (`WorkspaceActionLabel` in `TreatmentDetailsEditor`). Indirect children are **Veneer → Inlay → Onlay → Overlay** (same order as the category title). Crown leaves without a dedicated SVG use the monolithic zirconia drawing, not the Crown parent icon. Empty crown suggestion: plus + dashed chip (`addonCrownCanBeAdded`) inside a full-height slot; after a crown is picked the slot stays as the filled type chip. **Pontic** uses that same column whenever `pickerPolicy()` enables the Pontic tile (`addonPonticCanBeAdded`; filled chip after apply; click applies immediately). Arch Upper/Lower/Both is a compact `h-8` segmented control at half the tree column width — it **is** the assignment (`retargetArchJobs`): Both→Upper/Lower drops the other jaw; Upper/Lower→Both copies the type onto the empty jaw; Upper↔Lower moves the job. Chart Upper/Lower arch labels are dashed outline buttons with plus (open the picker; control shows current jobs, or the clicked jaw if none). Category parents use the heaviest family pastel; children only lighten. One **restoration** per tooth (crown / veneer-inlay-onlay-overlay). **Screw-retained** is implant (`stackGroup: implant`, paints the crown) and is itself the restoration — no crown suggestion slot, and Crown / Indirect are disabled. Implant or post & core (without a non-crown restoration) shows a **crown** suggestion slot. A veneer/inlay/onlay/overlay hides the suggestion slot. **Post & core** category is visible but disabled when a restoration or implant is on the tooth. **Implant** category is disabled when post & core is on the tooth. Complete denture / overdenture / appliances / digital use **Upper arch / Lower arch** (`UA`/`LA`). **Partial denture** is tooth-level (select FDI teeth, Removable in the tooth picker); after send it is **one lab job** for all those teeth. Picker leaves are filtered by `chartRegion` so Removable appears in both tooth and arch pickers. Prosthesis FDI teeth **must** have jobs — never persist selected teeth without `toothProsthesis` (`pruneDetailTeethToJobs`). Catalog has no `addonKind` — stacking uses `stackGroup` plus `pickerPolicy()` suggestion slots.
|
||||
- Detail chips show **type + teeth**, not “Detail N”. Lab-dependent chips use colored sent/unsent text (same size as the label); sent date stays on Lab dispatch.
|
||||
- Detail chips show **type + teeth**, not “Detail N”. Lab-dependent chips use colored sent/unsent text (same size as the label). **Sent** means the linked lab case has `sentAt`. The edit lock is separate: the line stays editable until a lab step is completed. Sent date stays on Lab dispatch.
|
||||
- Detail type may differ from appointment purpose. Purpose seeds the first line of an empty **appointment** draft (first open, and **Add detail** when the plan is `[]`). Later **Add detail** starts with an empty type. Unscheduled / New treatment still seeds a blank first line.
|
||||
- Lab shipments rail / “Go to dispatch” / load-with-focus **opens the dispatch view** in the chart slot (`pendingScrollToLabRef` + `labPanelRef`).
|
||||
- Live draft is **not** duplicated in the left rail preview; preview is for history browse only.
|
||||
@@ -151,6 +151,8 @@ On today: in-progress slot first, else nearest start time to `now`. Other days:
|
||||
|
||||
**Today checkbox** (`ScheduleDayPicker`, including `compact` on the Treatment strip and Appointments page headers): unchecked when `selectedDay` is not today (e.g. after loading a historical treatment). Checking Today calls `onSelectDay(today)` which unlocks selection (`selectionLocked = false`) and resets browse/historical context; appointments reload and auto-select nearest to now.
|
||||
|
||||
**Day arrows:** `onSelectDay` flushes, switches to live mode, and clears the selected visit before the new day loads. When that day has no appointment and no standalone treatment, the getDraft effect resets the form to one `newDetail()` (no patient, no leftover chart, notes, or lab drafts) unless it is already that blank line. A day that has a visit still auto-selects and loads it. Historical mode is left alone.
|
||||
|
||||
|
||||
|
||||
## Lab org search (dispatch)
|
||||
@@ -224,7 +226,7 @@ canEditTreatmentForDay = canEdit && hasLiveContext && !isViewingPastDay && works
|
||||
### Add / remove details
|
||||
|
||||
- **Add detail** stays enabled whenever `canEditTreatmentForDay` — even if sibling details are already sent.
|
||||
- **Remove detail:** trash icon on each **detail chip** in chrome (`TreatmentDetailsEditor` `showChrome`), including the last remaining line. Disabled when `!canEdit`, day/workspace `disabled`, detail sent (`isDetailLocked`), or `uploadBusy`. Confirm via `confirmRemoveDetail`. Drop linked unsent lab drafts with the detail. Empty details persist as `[]` (`SaveTreatmentDraftDto` has no `@ArrayMinSize`; `areDetailsPersistable` is `details.every(isDetailTypeSelected)` so `[]` saves). Unscheduled strip-card trash uses `areUnscheduledDetailsStripDeletable` (blank lines), then `PUT` `{ details: [] }` and `DELETE /treatments/:id` (backend still refuses when any detail row remains — `TREATMENT_HAS_DETAILS`). **Do not** put a delete control in the type/notes fields.
|
||||
- **Remove detail:** trash icon on each **detail chip** in chrome (`TreatmentDetailsEditor` `showChrome`), including the last remaining line. Disabled when `!canEdit`, day/workspace `disabled`, the line is sent (`isDetailSent`), or `uploadBusy`. The chip’s Sent label uses that same check. `isDetailLocked` is only the later edit lock (a completed lab step). Confirm via `confirmRemoveDetail`. Drop linked unsent lab drafts with the detail. Empty details persist as `[]` (`SaveTreatmentDraftDto` has no `@ArrayMinSize`; `areDetailsPersistable` is `details.every(isDetailTypeSelected)` so `[]` saves). Unscheduled strip-card trash uses `areUnscheduledDetailsStripDeletable` (blank lines), then `PUT` `{ details: [] }` and `DELETE /treatments/:id` (backend still refuses when any detail row remains — `TREATMENT_HAS_DETAILS`). **Do not** put a delete control in the type/notes fields.
|
||||
|
||||
### Sent lab shipment fields (vs detail)
|
||||
|
||||
|
||||
@@ -44,10 +44,10 @@ frontend/src/
|
||||
**Treatment tab:** Preview and editable form are **separate** until the user clicks **Load into workspace** on a history item. See `.cursor/skills/treatment-workspace/SKILL.md` before changing that flow.
|
||||
|
||||
**Treatment edit / details (quick ref):**
|
||||
- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** in the rail — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add.
|
||||
- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. Day arrows that land on a day with no visit reset the workspace to one blank detail and no patient, the same as opening Treatment with nothing selected. A day that has a visit still opens it. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** in the rail — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add.
|
||||
- **Unscheduled strip cards** use the same treatment-type banner as appointments from the **first detail’s type only** (`unscheduledStripColorCode`; live draft for the open card). Empty first line → chip theming even if later lines are typed. Strip trash only when every line is blank (no type/teeth/notes/attachments, including `[]`); typed cards need chip-delete first. Backend `DELETE /treatments/:id` is empty-only (`TREATMENT_HAS_DETAILS`).
|
||||
- A sent line stays editable until any lab task is completed, including a step finished by a further lab. Then the line locks (`TREATMENT_DETAIL_SENT`). **Add detail** still OK same day; **Remove detail** = trash on chip (unsent, including last line; day/edit gates apply). A sent line cannot be removed. Empty details persist as `[]`.
|
||||
- **Entry:** Type dropdown + compact attachments strip (`TreatmentDetailAttachmentsStrip`) on one row (plus **Lab dispatch** / **Chart** toggle when the type is lab-dependent; dispatch is primary, Chart is outline; **Add detail** uses the same width), then bordered FDI chart (Cases chrome/scale) **or** the lab dispatch panel in that same slot, then full-width auto-growing **Notes**. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existing `UA`/`LA` jobs (Both→Upper clears lower). Picker: `4fr` wrapping category grid / `1fr` add-ons with a vertical divider; tiles use `ProsthesisCatalogIcon` (`md` + two-line labels on category/addon; `sm` + centered icon/label on child cards); expanded children use a parent-colored **L** rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names use `prosthesisTypeLabelStyleFromCatalog`. Implant/post & core show a **crown** suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty **Pontic** suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch **opens the dispatch view** (`pendingScrollToLabRef`). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text (sent date on dispatch). Lab dispatch keeps comments.
|
||||
- **Entry:** Type dropdown + compact attachments strip (`TreatmentDetailAttachmentsStrip`) on one row (plus **Lab dispatch** / **Chart** toggle when the type is lab-dependent; dispatch is primary, Chart is outline; **Add detail** uses the same width), then bordered FDI chart (Cases chrome/scale) **or** the lab dispatch panel in that same slot, then full-width auto-growing **Notes**. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existing `UA`/`LA` jobs (Both→Upper clears lower). Picker: `4fr` wrapping category grid / `1fr` add-ons with a vertical divider; tiles use `ProsthesisCatalogIcon` (`md` + two-line labels on category/addon; `sm` + centered icon/label on child cards); expanded children use a parent-colored **L** rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names use `prosthesisTypeLabelStyleFromCatalog`. Implant/post & core show a **crown** suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty **Pontic** suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch **opens the dispatch view** (`pendingScrollToLabRef`). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text. Sent follows the linked lab case `sentAt` (or the detail’s own `sentAt`); editing stays open until a lab step is completed. The sent date stays on dispatch. Lab dispatch keeps comments.
|
||||
- **Tooth selection:** Hit target is the unrotated cell (`pointerdown` only — do not also bind `click`). Glyph is `pointer-events-none`; nest hover/selected scale inside the rotate wrapper. Neighbor circles connect/disconnect adjacent selected teeth; midline 11–21 / 41–31 is allowed; never keep a 1-tooth connected group. Prosthesis plain click opens the picker; Done stores the jobs copy brush; **Clear this tooth** stores a clear brush. Ctrl/Cmd+click or drag replays either action on one tooth; Shift+click replays it across an inclusive same-arch range as singles. Brushes reset when the active detail/line changes. Pontic is a no-child tile for pontic-first entry. A tooth immediately beside Pontic initially enables Crown, Indirect, and Pontic, allowing Pontic chains; assigning a Crown immediately enables Implant without reopening the picker (Indirect does not). Choosing a new restoration leaf on one connected abutment updates every restoration abutment in that span while preserving each tooth’s implant/post-core jobs. Orphan/mixed Pontics remain drafts with amber warning but block Send/Start (`PONTIC_BRIDGE_INVALID`). Helpers live in `prosthesisTree.ts`. Same-type teeth in one detail are one display job; stacked types remain distinct. A connected crown/indirect + Pontic span uses the abutment leaf’s steps and renders `13 · Pontic - 14 · PFZ Crown`; Pontic adds none. `UA`/`LA` are arch jobs; partial denture is one tooth-selected job across all selected FDI teeth.
|
||||
- **Lab dispatch layout:** due date beside title (`justify-between`, logical start/end for RTL); job rows from `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same-type teeth in one detail share a row; Connected badge only for a real bridge). Sent cases: dest/jobs share a row with the Cases **QR** thumb; tracker + comments are full width below.
|
||||
- **Schedule date:** Treatment strip and Appointments page headers use `ScheduleDayPicker` `compact` (date centered in a 3-col header; no “Schedule date” label; Today on the navigator).
|
||||
@@ -72,7 +72,7 @@ frontend/src/
|
||||
|
||||
**Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable and non-outsourceable; historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/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 **From clinic** / **Generated** / **From lab** 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:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **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 **From clinic** / **Generated** / **From lab** 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:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
**Lab case share link (quick ref):**
|
||||
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Case Files / Messages badges. ATTACHMENT_ADDED is not a sidebar tab count.
|
||||
|
||||
ALTER TYPE "LabCaseActivityType" ADD VALUE 'ATTACHMENT_ADDED';
|
||||
|
||||
CREATE TYPE "LabCaseSection" AS ENUM ('FILES', 'MESSAGES');
|
||||
|
||||
CREATE TABLE "lab_case_section_read_states" (
|
||||
"userId" TEXT NOT NULL,
|
||||
"organizationId" TEXT NOT NULL,
|
||||
"labCaseId" TEXT NOT NULL,
|
||||
"section" "LabCaseSection" NOT NULL,
|
||||
"lastReadAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "lab_case_section_read_states_pkey" PRIMARY KEY ("userId","organizationId","labCaseId","section")
|
||||
);
|
||||
|
||||
CREATE INDEX "lab_case_section_read_states_userId_organizationId_idx" ON "lab_case_section_read_states"("userId", "organizationId");
|
||||
|
||||
ALTER TABLE "lab_case_section_read_states" ADD CONSTRAINT "lab_case_section_read_states_labCaseId_fkey" FOREIGN KEY ("labCaseId") REFERENCES "lab_cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -300,8 +300,9 @@ model LabCase {
|
||||
toothProsthesis LabCaseToothProsthesis[]
|
||||
comments LabCaseComment[]
|
||||
attachments LabCaseAttachment[]
|
||||
activities LabCaseActivity[]
|
||||
userReadStates LabCaseUserReadState[]
|
||||
activities LabCaseActivity[]
|
||||
userReadStates LabCaseUserReadState[]
|
||||
sectionReadStates LabCaseSectionReadState[]
|
||||
calculatedAmount Decimal? @db.Decimal(14, 2)
|
||||
billedAmount Decimal? @db.Decimal(14, 2)
|
||||
billedAmountManual Boolean @default(false)
|
||||
@@ -572,6 +573,12 @@ enum LabCaseActivityType {
|
||||
TASK_COMPLETED
|
||||
TASK_ASSIGNED
|
||||
CASE_COMPLETED
|
||||
ATTACHMENT_ADDED
|
||||
}
|
||||
|
||||
enum LabCaseSection {
|
||||
FILES
|
||||
MESSAGES
|
||||
}
|
||||
|
||||
enum LabCaseTabReadTarget {
|
||||
@@ -653,6 +660,21 @@ model LabCaseUserTabReadState {
|
||||
@@map("lab_case_user_tab_read_states")
|
||||
}
|
||||
|
||||
/// Per-user cursor for the Files and Messages tabs on one case. Not a sidebar badge.
|
||||
model LabCaseSectionReadState {
|
||||
userId String
|
||||
organizationId String
|
||||
labCaseId String
|
||||
section LabCaseSection
|
||||
lastReadAt DateTime
|
||||
|
||||
labCase LabCase @relation(fields: [labCaseId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([userId, organizationId, labCaseId, section])
|
||||
@@index([userId, organizationId])
|
||||
@@map("lab_case_section_read_states")
|
||||
}
|
||||
|
||||
model Plan {
|
||||
id String @id @default(uuid())
|
||||
name String @unique // "Solo", "Small", "Medium", "Large", "Enterprise"
|
||||
|
||||
@@ -14,6 +14,8 @@ export const LAB_TASKS_TAB_ACTIVITY_TYPES: LabCaseActivityType[] = [
|
||||
LabCaseActivityType.TASK_ASSIGNED,
|
||||
];
|
||||
|
||||
/** `ATTACHMENT_ADDED` is a case Files badge only. It is not a sidebar count. */
|
||||
|
||||
/** Clinic Treatment tab — visible lab comments and case fully completed. */
|
||||
export const CLINIC_TREATMENT_TAB_ACTIVITY_TYPES: LabCaseActivityType[] = [
|
||||
LabCaseActivityType.LAB_COMMENT,
|
||||
|
||||
30
backend/src/common/org-disk-storage.ts
Normal file
30
backend/src/common/org-disk-storage.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { Request } from 'express';
|
||||
import { diskStorage } from 'multer';
|
||||
|
||||
/**
|
||||
* Stream an upload onto disk under uploads/{folder}/{organizationId}.
|
||||
* There is no file-size cap. Memory storage was holding the whole file in RAM,
|
||||
* which dropped large scans once the process ran out of memory.
|
||||
*/
|
||||
export function orgDiskStorage(folder: 'lab-cases' | 'treatments') {
|
||||
return diskStorage({
|
||||
destination(req, _file, cb) {
|
||||
const orgId = (req as Request & { user?: { organizationId?: string } }).user
|
||||
?.organizationId;
|
||||
if (!orgId) {
|
||||
cb(new Error('missing organization'), '');
|
||||
return;
|
||||
}
|
||||
const dir = join(process.cwd(), 'uploads', folder, orgId);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
cb(null, dir);
|
||||
},
|
||||
filename(_req, file, cb) {
|
||||
const safe = file.originalname.replace(/[^\w.\-()+]/g, '_');
|
||||
cb(null, `${randomUUID()}-${safe}`);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FilesInterceptor } from '@nestjs/platform-express';
|
||||
import { memoryStorage } from 'multer';
|
||||
import { orgDiskStorage } from '../../common/org-disk-storage';
|
||||
import type { Response } from 'express';
|
||||
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { LabOrgGuard } from '../../common/guards/lab-org.guard';
|
||||
@@ -157,7 +157,7 @@ export class CasesController {
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(
|
||||
FilesInterceptor('files', 20, {
|
||||
storage: memoryStorage(),
|
||||
storage: orgDiskStorage('lab-cases'),
|
||||
}),
|
||||
)
|
||||
uploadAttachments(
|
||||
@@ -169,6 +169,40 @@ export class CasesController {
|
||||
return this.casesService.uploadCaseAttachments(id, files, organizationId, req.user.id);
|
||||
}
|
||||
|
||||
@Delete(':id/attachments/:attachmentId')
|
||||
@ApiOperation({ summary: 'Remove one file from a lab case (TAB_CASES_EDIT)' })
|
||||
removeAttachment(
|
||||
@Param('id') id: string,
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
@Req() req,
|
||||
) {
|
||||
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
|
||||
return this.casesService.removeCaseAttachment(
|
||||
id,
|
||||
attachmentId,
|
||||
organizationId,
|
||||
req.user.id,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id/section-counts')
|
||||
@ApiOperation({ summary: 'Unread Files and Messages counts for the current user' })
|
||||
sectionCounts(@Param('id') id: string, @Req() req) {
|
||||
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
|
||||
return this.casesService.sectionCounts(id, organizationId, req.user.id);
|
||||
}
|
||||
|
||||
@Post(':id/sections/:section/read')
|
||||
@ApiOperation({ summary: 'Mark the Files or Messages tab read for the current user' })
|
||||
markSectionRead(
|
||||
@Param('id') id: string,
|
||||
@Param('section') section: string,
|
||||
@Req() req,
|
||||
) {
|
||||
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
|
||||
return this.casesService.markSectionRead(id, section, organizationId, req.user.id);
|
||||
}
|
||||
|
||||
@Get(':id/attachments')
|
||||
@ApiOperation({ summary: 'List files on a lab case (cases or tasks read)' })
|
||||
listAttachments(@Param('id') id: string, @Req() req) {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import {
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { createReadStream, existsSync, mkdirSync, unlinkSync } from 'fs';
|
||||
import { createReadStream, existsSync, unlinkSync } from 'fs';
|
||||
import { join, resolve, sep } from 'path';
|
||||
import { CatalogEntityKind, LabCaseActivityType, LabCaseOrigin, LabTaskStatus, LinkStatus, Prisma, UserNotificationType } from '@prisma/client';
|
||||
import {
|
||||
CatalogEntityKind,
|
||||
LabCaseActivityType,
|
||||
LabCaseOrigin,
|
||||
LabCaseSection,
|
||||
LabTaskStatus,
|
||||
LinkStatus,
|
||||
Prisma,
|
||||
UserNotificationType,
|
||||
} from '@prisma/client';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { normalizeMobile } from '../../common/phone';
|
||||
import {
|
||||
@@ -147,6 +152,7 @@ type LabCaseTaskWithRelations = Prisma.LabCaseTaskGetPayload<{
|
||||
|
||||
@Injectable()
|
||||
export class CasesService {
|
||||
private readonly logger = new Logger(CasesService.name);
|
||||
private readonly uploadRoot = join(process.cwd(), 'uploads', 'lab-cases');
|
||||
|
||||
constructor(
|
||||
@@ -1032,6 +1038,196 @@ export class CasesService {
|
||||
actorUserId: string,
|
||||
) {
|
||||
await this.assertCanEditCases(actorUserId, labOrganizationId);
|
||||
await this.requireVisibleCase(labCaseId, labOrganizationId);
|
||||
if (!files?.length) {
|
||||
throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
const created: {
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
createdAt: string;
|
||||
}[] = [];
|
||||
|
||||
try {
|
||||
for (const file of files) {
|
||||
const storagePath = file.path;
|
||||
if (!storagePath) {
|
||||
throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
let attachmentId = '';
|
||||
try {
|
||||
const attachment = await this.prisma.$transaction(async (tx) => {
|
||||
const row = await tx.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
detailClientKey: null,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
await tx.labCaseAttachment.create({
|
||||
data: { labCaseId, attachmentId: row.id },
|
||||
});
|
||||
return row;
|
||||
});
|
||||
attachmentId = attachment.id;
|
||||
created.push({
|
||||
id: attachment.id,
|
||||
fileName: attachment.fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
createdAt: attachment.createdAt.toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
this.removeStoredFiles([storagePath]);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// The file is already stored. A badge-row failure must not make the client retry and upload it again.
|
||||
try {
|
||||
await this.labCaseActivity.record({
|
||||
labCaseId,
|
||||
type: LabCaseActivityType.ATTACHMENT_ADDED,
|
||||
actorUserId,
|
||||
payload: { attachmentId },
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Failed to record ATTACHMENT_ADDED for case ${labCaseId}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (created.length > 0) {
|
||||
void this.userNotifications.emitCaseSectionChanged({
|
||||
organizationId: labOrganizationId,
|
||||
actorUserId,
|
||||
labCaseId,
|
||||
requiredPermissions: ['TAB_CASES_READ', 'TAB_TASKS_READ'],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: created };
|
||||
}
|
||||
|
||||
async removeCaseAttachment(
|
||||
labCaseId: string,
|
||||
attachmentId: string,
|
||||
labOrganizationId: string,
|
||||
actorUserId: string,
|
||||
) {
|
||||
await this.assertCanEditCases(actorUserId, labOrganizationId);
|
||||
await this.requireVisibleCase(labCaseId, labOrganizationId);
|
||||
|
||||
const link = await this.prisma.labCaseAttachment.findUnique({
|
||||
where: { labCaseId_attachmentId: { labCaseId, attachmentId } },
|
||||
include: {
|
||||
attachment: { select: { id: true, detailId: true, storagePath: true } },
|
||||
},
|
||||
});
|
||||
if (!link) {
|
||||
throw new AppException(ErrorCode.CASE_ATTACHMENT_NOT_FOUND, HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
const file = link.attachment;
|
||||
const deleteDisk = await this.prisma.$transaction(async (tx) => {
|
||||
await tx.labCaseAttachment.delete({
|
||||
where: { labCaseId_attachmentId: { labCaseId, attachmentId } },
|
||||
});
|
||||
|
||||
// A clinic file that still belongs to a treatment is unlinked from this case only.
|
||||
if (file.detailId != null) return false;
|
||||
|
||||
const stillLinked = await tx.labCaseAttachment.count({
|
||||
where: { attachmentId },
|
||||
});
|
||||
if (stillLinked > 0) return false;
|
||||
|
||||
await tx.treatmentDetailAttachment.delete({ where: { id: attachmentId } });
|
||||
return this.isLabOwnedUpload(file.storagePath, labOrganizationId);
|
||||
});
|
||||
if (deleteDisk) {
|
||||
this.removeStoredFiles([file.storagePath]);
|
||||
}
|
||||
return { success: true as const };
|
||||
}
|
||||
|
||||
async sectionCounts(labCaseId: string, labOrganizationId: string, actorUserId: string) {
|
||||
await this.assertCanReadCases(actorUserId, labOrganizationId);
|
||||
await this.requireVisibleCase(labCaseId, labOrganizationId);
|
||||
|
||||
const cursors = await this.prisma.labCaseSectionReadState.findMany({
|
||||
where: { userId: actorUserId, organizationId: labOrganizationId, labCaseId },
|
||||
});
|
||||
const since = (section: LabCaseSection) =>
|
||||
cursors.find((row) => row.section === section)?.lastReadAt ?? new Date(0);
|
||||
|
||||
const notOwn = {
|
||||
OR: [{ actorUserId: null }, { actorUserId: { not: actorUserId } }],
|
||||
};
|
||||
const [files, messages] = await Promise.all([
|
||||
this.prisma.labCaseActivity.count({
|
||||
where: {
|
||||
labCaseId,
|
||||
type: LabCaseActivityType.ATTACHMENT_ADDED,
|
||||
createdAt: { gt: since(LabCaseSection.FILES) },
|
||||
...notOwn,
|
||||
},
|
||||
}),
|
||||
this.prisma.labCaseActivity.count({
|
||||
where: {
|
||||
labCaseId,
|
||||
type: { in: [LabCaseActivityType.LAB_COMMENT, LabCaseActivityType.CLINIC_COMMENT] },
|
||||
createdAt: { gt: since(LabCaseSection.MESSAGES) },
|
||||
...notOwn,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return { success: true as const, data: { files, messages } };
|
||||
}
|
||||
|
||||
async markSectionRead(
|
||||
labCaseId: string,
|
||||
section: string,
|
||||
labOrganizationId: string,
|
||||
actorUserId: string,
|
||||
) {
|
||||
await this.assertCanReadCases(actorUserId, labOrganizationId);
|
||||
await this.requireVisibleCase(labCaseId, labOrganizationId);
|
||||
if (section !== LabCaseSection.FILES && section !== LabCaseSection.MESSAGES) {
|
||||
throw new AppException(ErrorCode.VALIDATION_INVALID_REQUEST, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
await this.prisma.labCaseSectionReadState.upsert({
|
||||
where: {
|
||||
userId_organizationId_labCaseId_section: {
|
||||
userId: actorUserId,
|
||||
organizationId: labOrganizationId,
|
||||
labCaseId,
|
||||
section,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId: actorUserId,
|
||||
organizationId: labOrganizationId,
|
||||
labCaseId,
|
||||
section,
|
||||
lastReadAt: new Date(),
|
||||
},
|
||||
update: { lastReadAt: new Date() },
|
||||
});
|
||||
return { success: true as const };
|
||||
}
|
||||
|
||||
private async requireVisibleCase(labCaseId: string, labOrganizationId: string) {
|
||||
const existing = await this.prisma.labCase.findFirst({
|
||||
where: {
|
||||
id: labCaseId,
|
||||
@@ -1042,47 +1238,6 @@ export class CasesService {
|
||||
if (!existing) {
|
||||
throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
|
||||
}
|
||||
if (!files?.length) {
|
||||
throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
const orgDir = join(this.uploadRoot, labOrganizationId);
|
||||
mkdirSync(orgDir, { recursive: true });
|
||||
|
||||
const created: {
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`;
|
||||
const storagePath = join(orgDir, storageName);
|
||||
const { writeFileSync } = await import('fs');
|
||||
writeFileSync(storagePath, file.buffer);
|
||||
|
||||
const attachment = await this.prisma.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
detailClientKey: null,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
await this.prisma.labCaseAttachment.create({
|
||||
data: { labCaseId, attachmentId: attachment.id },
|
||||
});
|
||||
created.push({
|
||||
id: attachment.id,
|
||||
fileName: attachment.fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
});
|
||||
}
|
||||
|
||||
return { success: true, data: created };
|
||||
}
|
||||
|
||||
async getOne(
|
||||
|
||||
@@ -20,14 +20,9 @@ export type UserNotificationDto = {
|
||||
actorUserId: string | null;
|
||||
};
|
||||
|
||||
type FanoutInput = {
|
||||
type RecipientQuery = {
|
||||
organizationId: string;
|
||||
type: UserNotificationType;
|
||||
href: string;
|
||||
actorUserId?: string | null;
|
||||
payload?: Record<string, unknown> | null;
|
||||
/** Explicit recipient user ids (e.g. task assignee). Skips permission fan-out. */
|
||||
recipientUserIds?: string[];
|
||||
/** Required tab permission when resolving org members. */
|
||||
requiredPermission?: string;
|
||||
/** Any-of tab permissions (OR) when resolving org members. */
|
||||
@@ -36,6 +31,14 @@ type FanoutInput = {
|
||||
labCaseIdForProviderScope?: string;
|
||||
};
|
||||
|
||||
type FanoutInput = RecipientQuery & {
|
||||
type: UserNotificationType;
|
||||
href: string;
|
||||
payload?: Record<string, unknown> | null;
|
||||
/** Explicit recipient user ids (e.g. task assignee). Skips permission fan-out. */
|
||||
recipientUserIds?: string[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class UserNotificationService {
|
||||
constructor(
|
||||
@@ -192,6 +195,28 @@ export class UserNotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell other lab members a case section changed, without writing an inbox row.
|
||||
* The client treats `case-section.changed` like a tab-badge refresh.
|
||||
*/
|
||||
async emitCaseSectionChanged(input: {
|
||||
organizationId: string;
|
||||
actorUserId: string;
|
||||
labCaseId: string;
|
||||
requiredPermissions: string[];
|
||||
}): Promise<void> {
|
||||
const recipientIds = await this.resolveRecipients({
|
||||
organizationId: input.organizationId,
|
||||
actorUserId: input.actorUserId,
|
||||
requiredPermissions: input.requiredPermissions,
|
||||
});
|
||||
for (const userId of recipientIds) {
|
||||
this.realtime.emitToUserOrg(userId, input.organizationId, 'case-section.changed', {
|
||||
labCaseId: input.labCaseId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async notify(input: FanoutInput): Promise<void> {
|
||||
// Explicit recipients keep the actor (e.g. self-assign). Fan-out still skips the actor.
|
||||
const recipientIds = input.recipientUserIds?.length
|
||||
@@ -322,7 +347,7 @@ export class UserNotificationService {
|
||||
};
|
||||
}
|
||||
|
||||
private async resolveRecipients(input: FanoutInput): Promise<string[]> {
|
||||
private async resolveRecipients(input: RecipientQuery): Promise<string[]> {
|
||||
const requiredPermissions = [
|
||||
...(input.requiredPermissions ?? []),
|
||||
...(input.requiredPermission ? [input.requiredPermission] : []),
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { FilesInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { memoryStorage } from 'multer';
|
||||
import { orgDiskStorage } from '../../common/org-disk-storage';
|
||||
import type { Response } from 'express';
|
||||
import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
@@ -177,7 +177,7 @@ export class TreatmentsController {
|
||||
})
|
||||
@UseInterceptors(
|
||||
FilesInterceptor('files', 20, {
|
||||
storage: memoryStorage(),
|
||||
storage: orgDiskStorage('treatments'),
|
||||
}),
|
||||
)
|
||||
uploadDetailAttachments(
|
||||
@@ -202,7 +202,7 @@ export class TreatmentsController {
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(
|
||||
FilesInterceptor('files', 20, {
|
||||
storage: memoryStorage(),
|
||||
storage: orgDiskStorage('treatments'),
|
||||
}),
|
||||
)
|
||||
uploadDetailAttachmentsLegacy(
|
||||
@@ -372,7 +372,7 @@ export class TreatmentsController {
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(
|
||||
FilesInterceptor('files', 20, {
|
||||
storage: memoryStorage(),
|
||||
storage: orgDiskStorage('treatments'),
|
||||
}),
|
||||
)
|
||||
uploadDetailAttachmentsByTreatment(
|
||||
|
||||
@@ -4,9 +4,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { LabCaseActivityType, LabTaskStatus, LinkStatus, Prisma, UserNotificationType } from '@prisma/client';
|
||||
import { createReadStream, existsSync, mkdirSync } from 'fs';
|
||||
import { createReadStream, existsSync, unlinkSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import {
|
||||
buildLabCaseShareUrl,
|
||||
generateLabCaseAccessToken,
|
||||
@@ -1349,9 +1348,6 @@ export class TreatmentsService {
|
||||
throw new AppException(ErrorCode.TREATMENT_DETAIL_SENT, HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
const orgDir = join(this.uploadRoot, organizationId);
|
||||
mkdirSync(orgDir, { recursive: true });
|
||||
|
||||
const created: {
|
||||
id: string;
|
||||
fileName: string;
|
||||
@@ -1360,23 +1356,27 @@ export class TreatmentsService {
|
||||
}[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`;
|
||||
const storagePath = join(orgDir, storageName);
|
||||
const { writeFileSync } = await import('fs');
|
||||
writeFileSync(storagePath, file.buffer);
|
||||
const storagePath = file.path;
|
||||
if (!storagePath) {
|
||||
throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
const attachment = await this.prisma.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
appointmentId,
|
||||
detailClientKey,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
|
||||
created.push(this.mapAttachment(attachment));
|
||||
try {
|
||||
const attachment = await this.prisma.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
appointmentId,
|
||||
detailClientKey,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
created.push(this.mapAttachment(attachment));
|
||||
} catch (error) {
|
||||
if (existsSync(storagePath)) unlinkSync(storagePath);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: created };
|
||||
@@ -1419,9 +1419,6 @@ export class TreatmentsService {
|
||||
throw new AppException(ErrorCode.TREATMENT_DETAIL_SENT, HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
const orgDir = join(this.uploadRoot, organizationId);
|
||||
mkdirSync(orgDir, { recursive: true });
|
||||
|
||||
const created: {
|
||||
id: string;
|
||||
fileName: string;
|
||||
@@ -1430,23 +1427,27 @@ export class TreatmentsService {
|
||||
}[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`;
|
||||
const storagePath = join(orgDir, storageName);
|
||||
const { writeFileSync } = await import('fs');
|
||||
writeFileSync(storagePath, file.buffer);
|
||||
const storagePath = file.path;
|
||||
if (!storagePath) {
|
||||
throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
const attachment = await this.prisma.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
treatmentId,
|
||||
detailClientKey,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
|
||||
created.push(this.mapAttachment(attachment));
|
||||
try {
|
||||
const attachment = await this.prisma.treatmentDetailAttachment.create({
|
||||
data: {
|
||||
treatmentId,
|
||||
detailClientKey,
|
||||
fileName: file.originalname,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
sizeBytes: file.size,
|
||||
storagePath,
|
||||
},
|
||||
});
|
||||
created.push(this.mapAttachment(attachment));
|
||||
} catch (error) {
|
||||
if (existsSync(storagePath)) unlinkSync(storagePath);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: created };
|
||||
|
||||
@@ -574,9 +574,12 @@
|
||||
"filesAdd": "Add files",
|
||||
"filesEmpty": "No files on this case.",
|
||||
"filesRemove": "Remove",
|
||||
"filesRemoveConfirm": "Remove this file from the case?",
|
||||
"filesView": "View",
|
||||
"filesMenu": "File actions",
|
||||
"filesPreviewUnavailable": "This file cannot be previewed.",
|
||||
"filesUploadProgress": "Uploading",
|
||||
"filesUploadFailed": "Upload failed",
|
||||
"partnerClinicNone": "None",
|
||||
"dueDateField": "Due date",
|
||||
"caseLinesTitle": "Work lines",
|
||||
@@ -929,6 +932,7 @@
|
||||
"activityCaseImportant": "Marked important by {actor} · {date}",
|
||||
"activityCaseCompleted": "All lab work completed by {actor} · {date}",
|
||||
"activityCaseAmended": "Case updated by {actor} · {date}",
|
||||
"activityAttachmentAdded": "File added by {actor} · {date}",
|
||||
"activityGeneric": "Update · {date}",
|
||||
"loadingHistory": "Loading history…",
|
||||
"historyEmpty": "No other treatments recorded for this patient yet.",
|
||||
|
||||
@@ -575,9 +575,12 @@
|
||||
"filesAdd": "افزودن فایل",
|
||||
"filesEmpty": "فایلی روی این پرونده نیست.",
|
||||
"filesRemove": "حذف",
|
||||
"filesRemoveConfirm": "این فایل از پرونده حذف شود؟",
|
||||
"filesView": "مشاهده",
|
||||
"filesMenu": "عملیات فایل",
|
||||
"filesPreviewUnavailable": "پیشنمایش این فایل ممکن نیست.",
|
||||
"filesUploadProgress": "در حال بارگذاری",
|
||||
"filesUploadFailed": "بارگذاری انجام نشد",
|
||||
"partnerClinicNone": "هیچکدام",
|
||||
"dueDateField": "موعد",
|
||||
"caseLinesTitle": "خطوط کار",
|
||||
@@ -930,6 +933,7 @@
|
||||
"activityCaseImportant": "مهم علامتگذاری شد توسط {actor} · {date}",
|
||||
"activityCaseCompleted": "تمام کارهای لابراتوار توسط {actor} تکمیل شد · {date}",
|
||||
"activityCaseAmended": "پرونده بهروزرسانی شد توسط {actor} · {date}",
|
||||
"activityAttachmentAdded": "فایل توسط {actor} افزوده شد · {date}",
|
||||
"activityGeneric": "بهروزرسانی · {date}",
|
||||
"loadingHistory": "در حال بارگذاری تاریخچه...",
|
||||
"historyEmpty": "هیچ درمان دیگری برای این بیمار ثبت نشده است.",
|
||||
|
||||
@@ -575,9 +575,12 @@
|
||||
"filesAdd": "Bestanden toevoegen",
|
||||
"filesEmpty": "Geen bestanden bij deze case.",
|
||||
"filesRemove": "Verwijderen",
|
||||
"filesRemoveConfirm": "Dit bestand uit de case verwijderen?",
|
||||
"filesView": "Bekijken",
|
||||
"filesMenu": "Bestandsacties",
|
||||
"filesPreviewUnavailable": "Dit bestand kan niet worden bekeken.",
|
||||
"filesUploadProgress": "Uploaden",
|
||||
"filesUploadFailed": "Uploaden mislukt",
|
||||
"partnerClinicNone": "Geen",
|
||||
"dueDateField": "Vervaldatum",
|
||||
"caseLinesTitle": "Werklijnen",
|
||||
@@ -929,6 +932,7 @@
|
||||
"activityCaseImportant": "Als belangrijk gemarkeerd door {actor} · {date}",
|
||||
"activityCaseCompleted": "Al het labwerk voltooid door {actor} · {date}",
|
||||
"activityCaseAmended": "Case bijgewerkt door {actor} · {date}",
|
||||
"activityAttachmentAdded": "Bestand toegevoegd door {actor} · {date}",
|
||||
"activityGeneric": "Update · {date}",
|
||||
"loadingHistory": "Geschiedenis laden...",
|
||||
"historyEmpty": "Geen andere behandelingen voor deze patiënt geregistreerd.",
|
||||
|
||||
@@ -12,6 +12,7 @@ import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccount
|
||||
import { NotificationBell } from '@/components/ui/notifications/NotificationBell';
|
||||
import { ConfirmProvider } from '@/components/ui/shared/ConfirmProvider';
|
||||
import { ToastProvider } from '@/components/ui/shared/ToastProvider';
|
||||
import { CaseUploadFailureReporter } from '@/components/ui/lab/CaseUploadFailureReporter';
|
||||
import { RealtimeProvider } from '@/lib/realtime/RealtimeProvider';
|
||||
import {
|
||||
canAccessDashboardRoute,
|
||||
@@ -90,6 +91,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
<CaseUploadFailureReporter />
|
||||
<ConfirmProvider>
|
||||
<RealtimeProvider>
|
||||
<div className="app-dashboard-shell flex h-[100dvh] app-web-bg text-text-primary">
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatPatientMobile, formatPatientName } from './caseDetailUtils';
|
||||
import {
|
||||
caseSheetOrderNumber,
|
||||
caseSheetPdfFileName,
|
||||
formatPatientMobile,
|
||||
formatPatientName,
|
||||
} from './caseDetailUtils';
|
||||
|
||||
const SENTINEL_MOBILE = '__walkin__:83c493d2-fbbc-4b0f-b8bc-1442305cfb2f';
|
||||
|
||||
@@ -48,3 +53,35 @@ describe('formatPatientMobile', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('caseSheetOrderNumber', () => {
|
||||
it('uses the trimmed external code when set', () => {
|
||||
expect(
|
||||
caseSheetOrderNumber({ id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', externalCode: ' EXO-123 ' }),
|
||||
).toBe('EXO-123');
|
||||
});
|
||||
|
||||
it('falls back to the short uppercased case id', () => {
|
||||
expect(caseSheetOrderNumber({ id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' })).toBe('A1B2C3D4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('caseSheetPdfFileName', () => {
|
||||
it('prefixes the printed external code', () => {
|
||||
expect(
|
||||
caseSheetPdfFileName({ id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', externalCode: 'EXO-123' }),
|
||||
).toBe('case-sheet-EXO-123.pdf');
|
||||
});
|
||||
|
||||
it('replaces filesystem-unsafe characters in the code', () => {
|
||||
expect(
|
||||
caseSheetPdfFileName({ id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', externalCode: 'EXO/12:3' }),
|
||||
).toBe('case-sheet-EXO-12-3.pdf');
|
||||
});
|
||||
|
||||
it('uses the short case id when there is no external code', () => {
|
||||
expect(caseSheetPdfFileName({ id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' })).toBe(
|
||||
'case-sheet-A1B2C3D4.pdf',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -122,3 +122,25 @@ export function latestCaseAttachment(labCase: LabCaseDetail) {
|
||||
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
|
||||
)[0];
|
||||
}
|
||||
|
||||
const CASE_SHEET_UNSAFE_FILENAME = /[/\\:*?"<>|]/g;
|
||||
|
||||
/** Printed order number: external code when set, else short case id. */
|
||||
export function caseSheetOrderNumber(labCase: {
|
||||
id: string;
|
||||
externalCode?: string | null;
|
||||
}): string {
|
||||
const external = labCase.externalCode?.trim();
|
||||
if (external) return external;
|
||||
return labCase.id.replace(/-/g, '').slice(0, 8).toUpperCase();
|
||||
}
|
||||
|
||||
/** Download name uses the same order number as the printed sheet. */
|
||||
export function caseSheetPdfFileName(labCase: {
|
||||
id: string;
|
||||
externalCode?: string | null;
|
||||
}): string {
|
||||
const order = caseSheetOrderNumber(labCase).replace(CASE_SHEET_UNSAFE_FILENAME, '-').trim();
|
||||
const fallback = labCase.id.replace(/-/g, '').slice(0, 8).toUpperCase();
|
||||
return `case-sheet-${order || fallback}.pdf`;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type CaseSheetOrientation,
|
||||
type CaseSheetPrintedComment,
|
||||
} from '@/components/ui/lab/CaseSheetPrintLayout';
|
||||
import { caseSheetPdfFileName } from '@/components/lab/caseDetailUtils';
|
||||
import type { LabCaseDetail } from '@/types/cases';
|
||||
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
|
||||
|
||||
@@ -102,7 +103,7 @@ export async function downloadCaseSheetPdf({
|
||||
useCORS: true,
|
||||
logging: false,
|
||||
scrollX: 0,
|
||||
scrollY: -window.scrollY,
|
||||
scrollY: 0,
|
||||
// Drop app stylesheets so parsers never see lab()/oklch() from Tailwind.
|
||||
onclone: (clonedDoc) => {
|
||||
clonedDoc.querySelectorAll('style, link[rel="stylesheet"]').forEach((node) => {
|
||||
@@ -117,8 +118,8 @@ export async function downloadCaseSheetPdf({
|
||||
node.style.display = 'flex';
|
||||
node.style.alignItems = 'center';
|
||||
node.style.justifyContent = 'flex-start';
|
||||
node.style.height = '48px';
|
||||
node.style.lineHeight = '48px';
|
||||
node.style.height = '56px';
|
||||
node.style.lineHeight = '56px';
|
||||
node.style.overflow = 'hidden';
|
||||
node.style.direction = 'ltr';
|
||||
node.style.letterSpacing = '0px';
|
||||
@@ -128,7 +129,7 @@ export async function downloadCaseSheetPdf({
|
||||
text.style.display = 'inline-block';
|
||||
text.style.maxWidth = '100%';
|
||||
text.style.overflow = 'visible';
|
||||
text.style.lineHeight = '48px';
|
||||
text.style.lineHeight = '56px';
|
||||
text.style.paddingTop = '0';
|
||||
text.style.paddingBottom = '0';
|
||||
text.style.letterSpacing = '0px';
|
||||
@@ -138,8 +139,8 @@ export async function downloadCaseSheetPdf({
|
||||
});
|
||||
clonedDoc.querySelectorAll('[data-case-sheet-lockup]').forEach((node) => {
|
||||
if (!(node instanceof HTMLElement)) return;
|
||||
node.style.height = '28px';
|
||||
node.style.lineHeight = '28px';
|
||||
node.style.height = '32px';
|
||||
node.style.lineHeight = '32px';
|
||||
node.style.overflow = 'hidden';
|
||||
});
|
||||
clonedDoc.querySelectorAll('[data-case-sheet-lockup] svg').forEach((node) => {
|
||||
@@ -148,7 +149,7 @@ export async function downloadCaseSheetPdf({
|
||||
const vbW = parts[2];
|
||||
const vbH = parts[3];
|
||||
if (!vbW || !vbH) return;
|
||||
const height = 22;
|
||||
const height = 26;
|
||||
const width = Math.max(1, Math.round(height * (vbW / vbH)));
|
||||
node.setAttribute('width', String(width));
|
||||
node.setAttribute('height', String(height));
|
||||
@@ -181,9 +182,7 @@ export async function downloadCaseSheetPdf({
|
||||
const x = margin + (usableWidth - drawWidth) / 2;
|
||||
pdf.addImage(imgData, 'PNG', x, margin, drawWidth, drawHeight);
|
||||
|
||||
const safeName =
|
||||
fileName ??
|
||||
`case-sheet-${labCase.id.replace(/-/g, '').slice(0, 8)}.pdf`;
|
||||
const safeName = fileName ?? caseSheetPdfFileName(labCase);
|
||||
pdf.save(safeName);
|
||||
} finally {
|
||||
root.unmount();
|
||||
|
||||
80
frontend/src/components/ui/lab/AddCaseWithVoice.tsx
Normal file
80
frontend/src/components/ui/lab/AddCaseWithVoice.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import { Mic, Square } from 'lucide-react';
|
||||
import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar';
|
||||
import type { VoiceCaptureState } from '@/lib/voice/useVoiceCapture';
|
||||
|
||||
/**
|
||||
* Full-width Add case control. Same height and type size as New treatment
|
||||
* (`px-6 py-3 text-base`), split like Add detail when voice is available.
|
||||
*/
|
||||
export function AddCaseWithVoice({
|
||||
label,
|
||||
startLabel,
|
||||
stopLabel,
|
||||
disabled,
|
||||
voice,
|
||||
onAdd,
|
||||
onVoice,
|
||||
}: {
|
||||
label: string;
|
||||
startLabel: string;
|
||||
stopLabel: string;
|
||||
disabled: boolean;
|
||||
voice: VoiceCaptureState | null;
|
||||
onAdd: () => void;
|
||||
onVoice: () => void;
|
||||
}) {
|
||||
if (!voice) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
disabled={disabled}
|
||||
className="w-full rounded-[var(--radius-md)] bg-primary px-6 py-3 text-base font-medium text-white transition-all duration-200 hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const isRecording = voice.phase === 'recording';
|
||||
const isBusy = voice.phase !== 'idle';
|
||||
const micLabel = isRecording ? stopLabel : startLabel;
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-2">
|
||||
<div
|
||||
className={`relative w-full overflow-hidden rounded-[var(--radius-md)] bg-primary text-base font-medium text-white ${
|
||||
disabled ? 'opacity-60' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
disabled={disabled || isBusy}
|
||||
className="w-full px-14 py-3 text-center transition-all duration-200 hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-white/60 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onVoice}
|
||||
disabled={disabled || voice.phase === 'processing'}
|
||||
title={micLabel}
|
||||
aria-label={micLabel}
|
||||
className={`absolute inset-y-0 end-0 inline-flex items-center justify-center border-s border-white/25 px-4 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-white/60 disabled:cursor-not-allowed disabled:opacity-60 ${
|
||||
isRecording ? 'bg-red-600 hover:bg-red-700' : 'hover:opacity-90'
|
||||
}`}
|
||||
>
|
||||
{isRecording ? (
|
||||
<Square className="h-4 w-4 fill-current" aria-hidden />
|
||||
) : (
|
||||
<Mic className="h-4 w-4" aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<VoiceRecordingBar voice={voice} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import { Mic, Square } from 'lucide-react';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import {
|
||||
invalidPonticTeethOnDetail,
|
||||
@@ -29,7 +28,6 @@ import { AppDateInput } from '@/components/ui/shared/AppDateInput';
|
||||
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
|
||||
import { UnderlineTabs } from '@/components/ui/shared/UnderlineTabs';
|
||||
import { ProsthesisAssignChart } from '@/components/ui/treatment/ProsthesisAssignChart';
|
||||
import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar';
|
||||
import { VoiceReviewSheet } from '@/components/ui/treatment/VoiceReviewSheet';
|
||||
import { isBlankLine, type LineDraft } from '@/components/lab/caseLineDraft';
|
||||
import { commentVisibilityProps } from '@/components/lab/labCaseOrigin';
|
||||
@@ -38,19 +36,21 @@ import { buildLabLineFromVoice } from '@/components/lab/voiceLine';
|
||||
import { caseCommentsApi } from '@/lib/api/case-comments';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
|
||||
import { voiceApi } from '@/lib/api/voice';
|
||||
import { isMediaRecorderSupported } from '@/lib/voice/audioFormat';
|
||||
import { useVoiceCapture, type VoiceCaptureState } from '@/lib/voice/useVoiceCapture';
|
||||
import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts';
|
||||
import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils';
|
||||
import {
|
||||
caseHasActiveUpload,
|
||||
forgetKnownCaseFile,
|
||||
knownAttachmentIds,
|
||||
registerDraftUploadBridge,
|
||||
whenCaseUploadsIdle,
|
||||
} from '@/lib/uploads/caseUploadQueue';
|
||||
import type { LabCaseDetail } from '@/types/cases';
|
||||
import type { FdiToothId } from '@/types/treatment';
|
||||
import type { LinkedOrganizationOption } from '@/types/treatment';
|
||||
import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups';
|
||||
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
|
||||
import type {
|
||||
VoiceApplySelection,
|
||||
VoiceAvailability,
|
||||
VoiceExtractionResult,
|
||||
} from '@/types/voice';
|
||||
import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice';
|
||||
|
||||
const INPUT_CLASS =
|
||||
'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35';
|
||||
@@ -138,6 +138,9 @@ interface CaseCreatePanelProps {
|
||||
labCase: LabCaseDetail;
|
||||
canEdit: boolean;
|
||||
prosthesisCatalog?: ProsthesisCatalogEntry[];
|
||||
/** Dictation owned by the Add case control. Applied onto this case's single plan. */
|
||||
voiceResult?: VoiceExtractionResult | null;
|
||||
onVoiceResultHandled?: () => void;
|
||||
onSaved: (detail: LabCaseDetail) => void;
|
||||
onStarted: (detail: LabCaseDetail) => void;
|
||||
onDeleted: () => void;
|
||||
@@ -148,6 +151,8 @@ export function CaseCreatePanel({
|
||||
labCase,
|
||||
canEdit,
|
||||
prosthesisCatalog,
|
||||
voiceResult = null,
|
||||
onVoiceResultHandled,
|
||||
onSaved,
|
||||
onStarted,
|
||||
onDeleted,
|
||||
@@ -178,16 +183,14 @@ export function CaseCreatePanel({
|
||||
const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate));
|
||||
const [plan, setPlan] = useState<LineDraft>(() => planFromDetail(labCase));
|
||||
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
|
||||
const sectionCounts = useCaseSectionCounts(labCase.id, section);
|
||||
const [partners, setPartners] = useState<LinkedOrganizationOption[]>([]);
|
||||
const [prosthesisOptions, setProsthesisOptions] = useState<ProsthesisCatalogEntry[]>(
|
||||
prosthesisCatalog ?? [],
|
||||
);
|
||||
const [voiceAvailability, setVoiceAvailability] = useState<VoiceAvailability | null>(null);
|
||||
const [voiceResult, setVoiceResult] = useState<VoiceExtractionResult | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [uploadBusy, setUploadBusy] = useState(false);
|
||||
const hydratedIdRef = useRef(labCase.id);
|
||||
const skipSaveRef = useRef(true);
|
||||
const startingRef = useRef(false);
|
||||
@@ -195,10 +198,14 @@ export function CaseCreatePanel({
|
||||
const allowPersistWhileStartingRef = useRef(false);
|
||||
const persistInFlightRef = useRef<Promise<LabCaseDetail | null> | null>(null);
|
||||
const uploadLockRef = useRef(false);
|
||||
const persistAfterUploadRef = useRef(false);
|
||||
const dirtyDuringUploadRef = useRef(false);
|
||||
const startRequestedRef = useRef(false);
|
||||
const deleteRequestedRef = useRef(false);
|
||||
const mountedRef = useRef(true);
|
||||
const cancelScheduledPersistRef = useRef<() => void>(() => {});
|
||||
const attachmentIdsRef = useRef<string[]>(labCase.attachments.map((file) => file.id));
|
||||
attachmentIdsRef.current = plan.attachments.map((file) => file.id);
|
||||
const filesListEpoch = useRef(0);
|
||||
const filesListRequest = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (hydratedIdRef.current === labCase.id) return;
|
||||
@@ -218,7 +225,6 @@ export function CaseCreatePanel({
|
||||
|
||||
useEffect(() => {
|
||||
void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined);
|
||||
void voiceApi.availability().then((r) => setVoiceAvailability(r.data)).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -229,24 +235,6 @@ export function CaseCreatePanel({
|
||||
void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined);
|
||||
}, [prosthesisCatalog]);
|
||||
|
||||
const voice = useVoiceCapture({
|
||||
// The locale the lab owner is reading and speaking in, so the ASR hint, the catalog labels
|
||||
// and the week start all match what the microphone was offered for.
|
||||
locale,
|
||||
maxMs: voiceAvailability?.maxRecordingMs ?? null,
|
||||
onExtracted: setVoiceResult,
|
||||
onError: (error) =>
|
||||
onError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))),
|
||||
});
|
||||
|
||||
// Absence renders the Add Line button unsplit. Gated on the browser's own recording support
|
||||
// as well as the server config: without it the control appears on a browser that cannot
|
||||
// record and fails on tap.
|
||||
const voiceEnabled =
|
||||
Boolean(voiceAvailability?.enabled) &&
|
||||
(voiceAvailability?.locales.includes(locale) ?? false) &&
|
||||
isMediaRecorderSupported();
|
||||
|
||||
const groups =
|
||||
plan.toothSelectionGroups.length > 0
|
||||
? plan.toothSelectionGroups
|
||||
@@ -322,13 +310,34 @@ export function CaseCreatePanel({
|
||||
|
||||
const persistRef = useRef(persist);
|
||||
persistRef.current = persist;
|
||||
const lockedPayloadRef = useRef(buildPayload);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const planIds = plan.attachments.map((file) => file.id);
|
||||
const posted = knownAttachmentIds(labCase.id);
|
||||
const pending = attachmentIdsRef.current.filter((id) => !planIds.includes(id) && posted.has(id));
|
||||
attachmentIdsRef.current = pending.length > 0 ? [...planIds, ...pending] : planIds;
|
||||
}, [labCase.id, plan]);
|
||||
|
||||
useEffect(() => {
|
||||
if (skipSaveRef.current) {
|
||||
skipSaveRef.current = false;
|
||||
lockedPayloadRef.current = buildPayload;
|
||||
return;
|
||||
}
|
||||
if (!canEdit || startingRef.current || deletingRef.current || uploadLockRef.current) return;
|
||||
if (uploadLockRef.current) {
|
||||
if (buildPayload !== lockedPayloadRef.current) dirtyDuringUploadRef.current = true;
|
||||
return;
|
||||
}
|
||||
lockedPayloadRef.current = buildPayload;
|
||||
if (!canEdit || startingRef.current || deletingRef.current) return;
|
||||
const timeout = setTimeout(() => {
|
||||
void persistRef.current();
|
||||
}, 500);
|
||||
@@ -337,25 +346,99 @@ export function CaseCreatePanel({
|
||||
}, [buildPayload, canEdit]);
|
||||
|
||||
useEffect(() => {
|
||||
if (uploadBusy || !persistAfterUploadRef.current) return;
|
||||
persistAfterUploadRef.current = false;
|
||||
void persistRef.current();
|
||||
}, [uploadBusy, plan]);
|
||||
if (caseHasActiveUpload(labCase.id)) uploadLockRef.current = true;
|
||||
return registerDraftUploadBridge(labCase.id, {
|
||||
prepare: async () => {
|
||||
filesListEpoch.current += 1;
|
||||
uploadLockRef.current = true;
|
||||
dirtyDuringUploadRef.current = false;
|
||||
cancelScheduledPersistRef.current();
|
||||
if (persistInFlightRef.current) {
|
||||
await persistInFlightRef.current.catch(() => null);
|
||||
}
|
||||
const saved = await persistRef.current();
|
||||
return saved != null;
|
||||
},
|
||||
commit: (attachment) => {
|
||||
filesListEpoch.current += 1;
|
||||
if (!attachmentIdsRef.current.includes(attachment.id)) {
|
||||
attachmentIdsRef.current = [...attachmentIdsRef.current, attachment.id];
|
||||
skipSaveRef.current = true;
|
||||
}
|
||||
setPlan((current) => {
|
||||
if (current.attachments.some((file) => file.id === attachment.id)) return current;
|
||||
return { ...current, attachments: [...current.attachments, attachment] };
|
||||
});
|
||||
},
|
||||
settle: () => {
|
||||
uploadLockRef.current = false;
|
||||
if (!dirtyDuringUploadRef.current) return;
|
||||
dirtyDuringUploadRef.current = false;
|
||||
void persistRef.current();
|
||||
},
|
||||
});
|
||||
}, [labCase.id]);
|
||||
|
||||
function updatePlan(patch: (line: LineDraft) => LineDraft) {
|
||||
setPlan((prev) => patch(prev));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (section !== 'files') return;
|
||||
const onChanged = () => {
|
||||
const epoch = filesListEpoch.current;
|
||||
const request = ++filesListRequest.current;
|
||||
void casesApi.listAttachments(labCase.id).then((response) => {
|
||||
if (epoch !== filesListEpoch.current || request !== filesListRequest.current) return;
|
||||
setPlan((current) => {
|
||||
const currentIds = new Set(current.attachments.map((file) => file.id));
|
||||
const extra = response.data.filter((file) => !currentIds.has(file.id));
|
||||
if (extra.length === 0) return current;
|
||||
return { ...current, attachments: [...current.attachments, ...extra] };
|
||||
});
|
||||
}).catch(() => undefined);
|
||||
};
|
||||
window.addEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
return () => window.removeEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
}, [labCase.id, section]);
|
||||
|
||||
async function handleRemoveAttachment(attachmentId: string) {
|
||||
const accepted = await confirm({
|
||||
title: tCommon('confirmTitle'),
|
||||
message: t('filesRemoveConfirm'),
|
||||
confirmLabel: t('filesRemove'),
|
||||
cancelLabel: tCommon('cancel'),
|
||||
tone: 'danger',
|
||||
});
|
||||
if (!accepted) return;
|
||||
filesListEpoch.current += 1;
|
||||
cancelScheduledPersistRef.current();
|
||||
if (persistInFlightRef.current) {
|
||||
await persistInFlightRef.current.catch(() => null);
|
||||
}
|
||||
try {
|
||||
await casesApi.removeAttachment(labCase.id, attachmentId);
|
||||
forgetKnownCaseFile(labCase.id, attachmentId);
|
||||
attachmentIdsRef.current = attachmentIdsRef.current.filter((id) => id !== attachmentId);
|
||||
updatePlan((line) => ({
|
||||
...line,
|
||||
attachments: line.attachments.filter((file) => file.id !== attachmentId),
|
||||
}));
|
||||
filesListEpoch.current += 1;
|
||||
} catch (error: unknown) {
|
||||
onError(getUserFacingError(error, tErrors, t('errorSaveCase')));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One dictation is one line. It fills the active line while that line is still blank — a
|
||||
* fresh draft opens with one, and always appending would leave it above the dictated line
|
||||
* and ship it to the floor, since `start` only requires that *some* line carries jobs.
|
||||
* One dictation fills this case's single plan. A blank plan is replaced; a plan that
|
||||
* already has jobs is merged. A dictated due date and comment still land.
|
||||
*/
|
||||
function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) {
|
||||
const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, {
|
||||
prosthesisCatalog: prosthesisOptions,
|
||||
});
|
||||
setVoiceResult(null);
|
||||
onVoiceResultHandled?.();
|
||||
if (dictatedDueDate) setDueDate(dictatedDueDate);
|
||||
// Null when the dictation carried no line content — a due date on its own still lands.
|
||||
// Without the notice, Apply on a row that lands no job closes the sheet and changes nothing.
|
||||
@@ -387,7 +470,7 @@ export function CaseCreatePanel({
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!canEdit) return;
|
||||
if (!canEdit || deleting || deleteRequestedRef.current) return;
|
||||
if (
|
||||
!(await confirm({
|
||||
message: t('confirmDeleteDraftCase'),
|
||||
@@ -397,26 +480,43 @@ export function CaseCreatePanel({
|
||||
) {
|
||||
return;
|
||||
}
|
||||
deletingRef.current = true;
|
||||
skipSaveRef.current = true;
|
||||
deleteRequestedRef.current = true;
|
||||
setDeleting(true);
|
||||
try {
|
||||
// Let the posted file land before the draft disappears, or the upload fails closed.
|
||||
await whenCaseUploadsIdle(labCase.id);
|
||||
if (!mountedRef.current) return;
|
||||
if (persistInFlightRef.current) {
|
||||
await persistInFlightRef.current.catch(() => null);
|
||||
}
|
||||
if (!mountedRef.current) return;
|
||||
deletingRef.current = true;
|
||||
skipSaveRef.current = true;
|
||||
await casesApi.deleteDraft(labCase.id);
|
||||
onDeleted();
|
||||
} catch (error: unknown) {
|
||||
deletingRef.current = false;
|
||||
deleteRequestedRef.current = false;
|
||||
setDeleting(false);
|
||||
onError(getUserFacingError(error, tErrors, t('errorDeleteCase')));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStart() {
|
||||
if (!canEdit) return;
|
||||
if (!canEdit || startRequestedRef.current || deleting || deleteRequestedRef.current) return;
|
||||
startRequestedRef.current = true;
|
||||
setStarting(true);
|
||||
startingRef.current = true;
|
||||
skipSaveRef.current = true;
|
||||
allowPersistWhileStartingRef.current = true;
|
||||
try {
|
||||
// A save with the pre-upload id list would unlink and delete the new file.
|
||||
await whenCaseUploadsIdle(labCase.id);
|
||||
if (!mountedRef.current) return;
|
||||
if (persistInFlightRef.current) {
|
||||
await persistInFlightRef.current.catch(() => null);
|
||||
}
|
||||
if (!mountedRef.current) return;
|
||||
startingRef.current = true;
|
||||
skipSaveRef.current = true;
|
||||
allowPersistWhileStartingRef.current = true;
|
||||
const saved = await persist();
|
||||
allowPersistWhileStartingRef.current = false;
|
||||
if (!saved) {
|
||||
@@ -431,32 +531,8 @@ export function CaseCreatePanel({
|
||||
onError(getUserFacingError(error, tErrors, t('errorStartCase')));
|
||||
} finally {
|
||||
allowPersistWhileStartingRef.current = false;
|
||||
setStarting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpload(files: File[]) {
|
||||
if (!files.length || !canEdit) return;
|
||||
uploadLockRef.current = true;
|
||||
cancelScheduledPersistRef.current();
|
||||
setUploadBusy(true);
|
||||
try {
|
||||
await persist();
|
||||
const response = await casesApi.uploadAttachments(labCase.id, files);
|
||||
attachmentIdsRef.current = [
|
||||
...attachmentIdsRef.current,
|
||||
...response.data.map((file) => file.id),
|
||||
];
|
||||
persistAfterUploadRef.current = true;
|
||||
updatePlan((line) => ({
|
||||
...line,
|
||||
attachments: [...line.attachments, ...response.data],
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
onError(getUserFacingError(error, tErrors, t('errorSaveCase')));
|
||||
} finally {
|
||||
uploadLockRef.current = false;
|
||||
setUploadBusy(false);
|
||||
startRequestedRef.current = false;
|
||||
if (mountedRef.current) setStarting(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,24 +630,13 @@ export function CaseCreatePanel({
|
||||
onChange={setSection}
|
||||
tabs={[
|
||||
{ id: 'details', label: t('tabDetails') },
|
||||
{ id: 'files', label: t('tabFiles') },
|
||||
{ id: 'messages', label: t('tabMessages') },
|
||||
{ id: 'files', label: t('tabFiles'), count: sectionCounts.files },
|
||||
{ id: 'messages', label: t('tabMessages'), count: sectionCounts.messages },
|
||||
]}
|
||||
/>
|
||||
|
||||
{section === 'details' ? (
|
||||
<div className="space-y-4">
|
||||
{voiceEnabled ? (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<VoiceCaptureButton
|
||||
startLabel={tTreatment('voiceStart')}
|
||||
stopLabel={tTreatment('voiceStop')}
|
||||
disabled={disabled}
|
||||
voice={voice}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{voiceEnabled ? <VoiceRecordingBar voice={voice} /> : null}
|
||||
<ProsthesisAssignChart
|
||||
groups={groups}
|
||||
toothProsthesis={plan.toothProsthesis}
|
||||
@@ -630,23 +695,14 @@ export function CaseCreatePanel({
|
||||
|
||||
{section === 'files' ? (
|
||||
<CaseFilesPanel
|
||||
caseId={labCase.id}
|
||||
attachments={plan.attachments}
|
||||
canAdd={canEdit}
|
||||
adding={uploadBusy}
|
||||
onAdd={(files) => void handleUpload(files)}
|
||||
canAdd={canEdit && !starting && !deleting}
|
||||
onDownload={(file) => casesApi.getAttachmentFileBlob(labCase.id, file.id)}
|
||||
onDownloadError={(error) =>
|
||||
onError(getUserFacingError(error, tErrors, t('errorDownloadFile')))
|
||||
}
|
||||
onRemove={
|
||||
canEdit
|
||||
? (attachmentId) =>
|
||||
updatePlan((line) => ({
|
||||
...line,
|
||||
attachments: line.attachments.filter((file) => file.id !== attachmentId),
|
||||
}))
|
||||
: undefined
|
||||
}
|
||||
onRemove={canEdit ? (attachmentId) => void handleRemoveAttachment(attachmentId) : undefined}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -681,7 +737,7 @@ export function CaseCreatePanel({
|
||||
result={voiceResult}
|
||||
prosthesisCatalog={prosthesisOptions}
|
||||
onApply={(selection, applied) => applyVoice(selection, applied)}
|
||||
onDiscard={() => setVoiceResult(null)}
|
||||
onDiscard={() => onVoiceResultHandled?.()}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -697,37 +753,3 @@ export function CaseCreatePanel({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VoiceCaptureButton({
|
||||
startLabel,
|
||||
stopLabel,
|
||||
disabled,
|
||||
voice,
|
||||
}: {
|
||||
startLabel: string;
|
||||
stopLabel: string;
|
||||
disabled: boolean;
|
||||
voice: VoiceCaptureState;
|
||||
}) {
|
||||
const isRecording = voice.phase === 'recording';
|
||||
const micLabel = isRecording ? stopLabel : startLabel;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={isRecording ? voice.onStop : voice.onStart}
|
||||
disabled={disabled || voice.phase === 'processing'}
|
||||
title={micLabel}
|
||||
aria-label={micLabel}
|
||||
className={`inline-flex items-center gap-2 rounded-[var(--radius-md)] px-3 py-2 text-sm font-medium text-white ${
|
||||
isRecording ? 'bg-red-600 hover:bg-red-700' : 'bg-primary hover:opacity-90'
|
||||
} disabled:cursor-not-allowed disabled:opacity-60`}
|
||||
>
|
||||
{isRecording ? (
|
||||
<Square className="h-4 w-4 fill-current" aria-hidden />
|
||||
) : (
|
||||
<Mic className="h-4 w-4" aria-hidden />
|
||||
)}
|
||||
{micLabel}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { useLocale, useMessages, useTranslations } from 'next-intl';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import { Badge } from '@/components/ui/shared/Badge';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
|
||||
@@ -29,6 +30,9 @@ import type { CaseSheetOrientation } from '@/components/ui/lab/CaseSheetPrintLay
|
||||
import { caseCommentsApi } from '@/lib/api/case-comments';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import { UnderlineTabs } from '@/components/ui/shared/UnderlineTabs';
|
||||
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
|
||||
import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts';
|
||||
import { forgetKnownCaseFile, withKnownCaseFiles } from '@/lib/uploads/caseUploadQueue';
|
||||
import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import { formatAppMoney } from '@/lib/i18n/format';
|
||||
@@ -256,11 +260,14 @@ export function CaseDetailPanel({
|
||||
const t = useTranslations('cases');
|
||||
const tTreatment = useTranslations('treatment');
|
||||
const tComments = useTranslations('caseComments');
|
||||
const tErrors = useTranslations('errors');
|
||||
const tCommon = useTranslations('common');
|
||||
const intlLocale = useLocale();
|
||||
const messages = useMessages();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
|
||||
const [uploadingFiles, setUploadingFiles] = useState(false);
|
||||
const sectionCounts = useCaseSectionCounts(labCase.id, section);
|
||||
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>(
|
||||
prosthesisCatalogProp ?? [],
|
||||
);
|
||||
@@ -316,17 +323,23 @@ export function CaseDetailPanel({
|
||||
},
|
||||
);
|
||||
|
||||
async function handleAddFiles(files: File[]) {
|
||||
if (!files.length || !canAddFiles) return;
|
||||
setUploadingFiles(true);
|
||||
async function handleRemoveFile(attachmentId: string) {
|
||||
if (!canAddFiles) return;
|
||||
const accepted = await confirm({
|
||||
title: tCommon('confirmTitle'),
|
||||
message: t('filesRemoveConfirm'),
|
||||
confirmLabel: t('filesRemove'),
|
||||
cancelLabel: tCommon('cancel'),
|
||||
tone: 'danger',
|
||||
});
|
||||
if (!accepted) return;
|
||||
try {
|
||||
await casesApi.uploadAttachments(labCase.id, files);
|
||||
await casesApi.removeAttachment(labCase.id, attachmentId);
|
||||
forgetKnownCaseFile(labCase.id, attachmentId);
|
||||
const refreshed = await casesApi.getOne(labCase.id);
|
||||
onCaseUpdated?.(refreshed.data);
|
||||
} catch {
|
||||
toast.showError(t('errorSaveCase'));
|
||||
} finally {
|
||||
setUploadingFiles(false);
|
||||
onCaseUpdated?.(withKnownCaseFiles(refreshed.data));
|
||||
} catch (error: unknown) {
|
||||
toast.showError(getUserFacingError(error, tErrors, t('errorSaveCase')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,39 +425,50 @@ export function CaseDetailPanel({
|
||||
|
||||
return (
|
||||
<div className="space-y-4 min-w-0">
|
||||
<header className="grid grid-cols-1 items-start gap-4 border-b border-border pb-3 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] lg:items-stretch">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="text-lg font-semibold text-text-primary">
|
||||
{formatPatientName(labCase.patient, t('walkIn'))}
|
||||
</h2>
|
||||
<LabCaseDueDateBadge dueDate={labCase.dueDate} locale={locale} />
|
||||
<LabCaseOriginBadge origin={labCase.origin} />
|
||||
</div>
|
||||
<p className="text-sm text-text-muted">
|
||||
{t('patientMobile')}: {formatPatientMobile(labCase.patient)}
|
||||
</p>
|
||||
{headerMetaLines}
|
||||
{(labCase.sentAt || labCase.startedAt) ? (
|
||||
<p className="text-sm text-text-muted">
|
||||
{labCase.sentAt
|
||||
? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })
|
||||
: t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="max-w-xs space-y-2 pt-1">
|
||||
<div>
|
||||
<p className="text-sm text-text-muted mb-1">
|
||||
{t('taskProgressLabel', {
|
||||
completed: labCase.taskProgress.completed,
|
||||
total: labCase.taskProgress.total,
|
||||
})}
|
||||
</p>
|
||||
<CaseTaskProgressBar
|
||||
completed={labCase.taskProgress.completed}
|
||||
total={labCase.taskProgress.total}
|
||||
/>
|
||||
<header className="grid grid-cols-1 items-start gap-2 border-b border-border pb-3 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] lg:items-stretch lg:gap-4">
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<h2 className="text-base font-semibold text-text-primary sm:text-lg">
|
||||
{formatPatientName(labCase.patient, t('walkIn'))}
|
||||
</h2>
|
||||
<LabCaseDueDateBadge dueDate={labCase.dueDate} locale={locale} />
|
||||
<LabCaseOriginBadge origin={labCase.origin} />
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-text-muted sm:text-sm">
|
||||
<span>
|
||||
{t('patientMobile')}: {formatPatientMobile(labCase.patient)}
|
||||
</span>
|
||||
{headerMetaLines ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
{headerMetaLines}
|
||||
</>
|
||||
) : null}
|
||||
{labCase.sentAt || labCase.startedAt ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>
|
||||
{labCase.sentAt
|
||||
? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })
|
||||
: t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{labCase.shareUrl ? (
|
||||
<div className="shrink-0 lg:hidden">
|
||||
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="max-w-xs space-y-1.5">
|
||||
<CaseTaskProgressBar
|
||||
completed={labCase.taskProgress.completed}
|
||||
total={labCase.taskProgress.total}
|
||||
/>
|
||||
{canEditImportant ? (
|
||||
<Input
|
||||
value={externalCodeDraft}
|
||||
@@ -466,7 +490,7 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center gap-2 lg:h-full">
|
||||
<div className="flex flex-row flex-wrap items-center justify-between gap-x-3 gap-y-1 lg:h-full lg:flex-col lg:items-center lg:justify-start">
|
||||
{canEditImportant ? (
|
||||
<Checkbox
|
||||
checked={labCase.isImportant ?? false}
|
||||
@@ -480,7 +504,7 @@ export function CaseDetailPanel({
|
||||
</Badge>
|
||||
) : null}
|
||||
{labCase.billedAmount != null || labCase.calculatedAmount != null ? (
|
||||
<p className="text-center text-sm text-text-secondary lg:mt-auto">
|
||||
<p className="text-xs text-text-secondary sm:text-sm lg:mt-auto lg:text-center">
|
||||
<span className="font-bold text-text-primary">{t('billedLead')}</span>
|
||||
{' '}
|
||||
{t('billedCurrencyNote')}
|
||||
@@ -493,31 +517,34 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
|
||||
<div className="flex w-full shrink-0 flex-col items-stretch gap-2 lg:items-end">
|
||||
{canStop || canSend ? (
|
||||
<div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
|
||||
{canStop && onStop ? (
|
||||
<div className="flex w-full flex-wrap items-center gap-2 lg:w-auto lg:justify-end">
|
||||
{canStop && onStop ? (
|
||||
<div className="min-w-0 flex-1 lg:flex-none">
|
||||
<CaseLifecycleButton
|
||||
variant="danger"
|
||||
label={t('stopCase')}
|
||||
isLoading={stopping}
|
||||
responsiveFill
|
||||
onClick={onStop}
|
||||
/>
|
||||
) : null}
|
||||
{canSend && onSend ? (
|
||||
</div>
|
||||
) : null}
|
||||
{canSend && onSend ? (
|
||||
<div className="min-w-0 flex-1 lg:flex-none">
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={t('sendCase')}
|
||||
responsiveFill
|
||||
onClick={onSend}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
|
||||
<div ref={sheetMenuRef} className="relative">
|
||||
</div>
|
||||
) : null}
|
||||
<div ref={sheetMenuRef} className="relative min-w-0 flex-1 lg:flex-none">
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={pdfLabel}
|
||||
isLoading={downloadingPdf}
|
||||
responsiveFill
|
||||
ariaExpanded={sheetMenuOpen}
|
||||
ariaHaspopup="menu"
|
||||
onClick={() => setSheetMenuOpen((open) => !open)}
|
||||
@@ -543,7 +570,7 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
</div>
|
||||
{labCase.shareUrl ? (
|
||||
<div className="flex flex-wrap items-center gap-2 shrink-0">
|
||||
<div className="hidden shrink-0 lg:block">
|
||||
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />
|
||||
</div>
|
||||
) : null}
|
||||
@@ -556,19 +583,19 @@ export function CaseDetailPanel({
|
||||
onChange={setSection}
|
||||
tabs={[
|
||||
{ id: 'details', label: t('tabDetails') },
|
||||
{ id: 'files', label: t('tabFiles') },
|
||||
{ id: 'messages', label: t('tabMessages') },
|
||||
{ id: 'files', label: t('tabFiles'), count: sectionCounts.files },
|
||||
{ id: 'messages', label: t('tabMessages'), count: sectionCounts.messages },
|
||||
]}
|
||||
/>
|
||||
|
||||
{section === 'files' ? (
|
||||
<CaseFilesPanel
|
||||
caseId={labCase.id}
|
||||
attachments={labCase.attachments}
|
||||
canAdd={canAddFiles}
|
||||
adding={uploadingFiles}
|
||||
onAdd={(files) => void handleAddFiles(files)}
|
||||
onDownload={(file) => loadAttachmentBlob(labCase.id, file.id)}
|
||||
onDownloadError={() => toast.showError(t('errorDownloadFile'))}
|
||||
onRemove={canAddFiles ? (attachmentId) => void handleRemoveFile(attachmentId) : undefined}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ import {
|
||||
type CaseFilePreviewKind,
|
||||
} from '@/components/lab/caseFilePreview';
|
||||
import { formatAppDateTime, formatAppNumber } from '@/lib/i18n/format';
|
||||
import { useCaseUploadJobs } from '@/lib/hooks/useCaseUploadJobs';
|
||||
import {
|
||||
dismissCaseUploadJob,
|
||||
enqueueCaseFileUpload,
|
||||
} from '@/lib/uploads/caseUploadQueue';
|
||||
import type { LabCaseAttachmentMeta } from '@/types/cases';
|
||||
|
||||
/** Skip automatic thumbnails above this size. View still loads the file on demand. */
|
||||
@@ -70,20 +75,18 @@ function blobForKind(blob: Blob, file: LabCaseAttachmentMeta, kind: CaseFilePrev
|
||||
}
|
||||
|
||||
export function CaseFilesPanel({
|
||||
caseId,
|
||||
attachments,
|
||||
canAdd,
|
||||
adding = false,
|
||||
downloading = false,
|
||||
onAdd,
|
||||
onDownload,
|
||||
onDownloadError,
|
||||
onRemove,
|
||||
}: {
|
||||
caseId: string;
|
||||
attachments: LabCaseAttachmentMeta[];
|
||||
canAdd: boolean;
|
||||
adding?: boolean;
|
||||
downloading?: boolean;
|
||||
onAdd: (files: File[]) => void;
|
||||
onDownload: (attachment: LabCaseAttachmentMeta) => Promise<Blob>;
|
||||
onDownloadError?: (error: unknown) => void;
|
||||
onRemove?: (attachmentId: string) => void;
|
||||
@@ -101,6 +104,7 @@ export function CaseFilesPanel({
|
||||
const [menuId, setMenuId] = useState<string | null>(null);
|
||||
const [previews, setPreviews] = useState<Record<string, CardPreview>>({});
|
||||
const [viewer, setViewer] = useState<ViewerState | null>(null);
|
||||
const uploads = useCaseUploadJobs(caseId);
|
||||
const attachmentKey = attachments.map((file) => file.id).join('\n');
|
||||
|
||||
useEffect(() => {
|
||||
@@ -288,7 +292,13 @@ export function CaseFilesPanel({
|
||||
}
|
||||
}
|
||||
|
||||
const working = busy || downloading || adding;
|
||||
const uploading = uploads.some((item) => !item.failed);
|
||||
const working = busy || downloading || uploading;
|
||||
|
||||
function enqueueUploads(files: File[]) {
|
||||
if (!canAdd || files.length === 0) return;
|
||||
for (const file of files) enqueueCaseFileUpload(caseId, file);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
@@ -313,8 +323,7 @@ export function CaseFilesPanel({
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={t('filesAdd')}
|
||||
isLoading={adding}
|
||||
disabled={working}
|
||||
disabled={busy || downloading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
/>
|
||||
<input
|
||||
@@ -324,7 +333,7 @@ export function CaseFilesPanel({
|
||||
className="hidden"
|
||||
onChange={(event) => {
|
||||
const files = event.target.files ? Array.from(event.target.files) : [];
|
||||
if (files.length) onAdd(files);
|
||||
if (files.length) void enqueueUploads(files);
|
||||
event.target.value = '';
|
||||
}}
|
||||
/>
|
||||
@@ -332,10 +341,63 @@ export function CaseFilesPanel({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{attachments.length === 0 ? (
|
||||
{attachments.length === 0 && uploads.length === 0 ? (
|
||||
<p className="text-sm text-text-muted">{t('filesEmpty')}</p>
|
||||
) : (
|
||||
<ul className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(220px,1fr))]">
|
||||
{uploads.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className={`flex min-w-0 flex-col overflow-hidden rounded-xl border bg-background-card ${item.failed ? 'border-red-300' : 'border-border'}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 px-3 py-2">
|
||||
<p
|
||||
className="min-w-0 flex-1 truncate text-start text-sm font-medium text-text-primary"
|
||||
title={item.fileName}
|
||||
>
|
||||
{shortFileName(item.fileName)}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className="flex h-40 shrink-0 flex-col items-center justify-center gap-3 bg-background-secondary px-4"
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={item.failed ? 0 : item.percent}
|
||||
aria-label={item.failed ? t('filesUploadFailed') : t('filesUploadProgress')}
|
||||
>
|
||||
{item.failed ? (
|
||||
<p className="text-center text-sm text-red-600">{t('filesUploadFailed')}</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-border">
|
||||
<div
|
||||
className={`h-full rounded-full bg-primary ${item.percent ? 'transition-[width]' : 'animate-pulse'}`}
|
||||
style={{ width: `${Math.max(item.percent, 8)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-text-secondary">
|
||||
{formatAppNumber(item.percent, locale)}%
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 px-3 py-2">
|
||||
<p className="min-w-0 flex-1 truncate text-start text-xs text-text-secondary">
|
||||
{formatFileSize(item.sizeBytes)}
|
||||
</p>
|
||||
{item.failed ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 text-xs text-text-secondary hover:text-text-primary"
|
||||
onClick={() => dismissCaseUploadJob(item.id)}
|
||||
>
|
||||
{t('filesRemove')}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
{attachments.map((file) => {
|
||||
const checked = selected.includes(file.id);
|
||||
const preview = previews[file.id];
|
||||
|
||||
@@ -15,6 +15,8 @@ type CaseLifecycleButtonProps = {
|
||||
isLoading?: boolean;
|
||||
ariaExpanded?: boolean;
|
||||
ariaHaspopup?: 'menu';
|
||||
/** Fill the row below the lg breakpoint. Desktop keeps the shared label width. */
|
||||
responsiveFill?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
@@ -27,6 +29,7 @@ export function CaseLifecycleButton({
|
||||
isLoading,
|
||||
ariaExpanded,
|
||||
ariaHaspopup,
|
||||
responsiveFill = false,
|
||||
onClick,
|
||||
}: CaseLifecycleButtonProps) {
|
||||
const t = useTranslations('cases');
|
||||
@@ -48,7 +51,7 @@ export function CaseLifecycleButton({
|
||||
type="button"
|
||||
variant={variant}
|
||||
size="sm"
|
||||
className={WORKSPACE_ACTION_BTN_CLASS}
|
||||
className={`${WORKSPACE_ACTION_BTN_CLASS}${responsiveFill ? ' w-full min-w-0 lg:w-auto' : ''}`}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
aria-expanded={ariaExpanded}
|
||||
@@ -61,13 +64,17 @@ export function CaseLifecycleButton({
|
||||
{widthLabels.map((text, index) => (
|
||||
<span
|
||||
key={`${index}-${text}`}
|
||||
className="invisible col-start-1 row-start-1 whitespace-nowrap"
|
||||
className={`invisible col-start-1 row-start-1 whitespace-nowrap${responsiveFill ? ' hidden lg:block' : ''}`}
|
||||
aria-hidden
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
))}
|
||||
<span className="col-start-1 row-start-1 whitespace-nowrap">{label}</span>
|
||||
<span
|
||||
className={`col-start-1 row-start-1 whitespace-nowrap${responsiveFill ? ' max-lg:truncate' : ''}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
@@ -346,9 +346,9 @@ function ArchCaption({
|
||||
style={{
|
||||
margin: 0,
|
||||
textAlign: 'center',
|
||||
fontSize: 11,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
lineHeight: '13px',
|
||||
lineHeight: '16px',
|
||||
color: color ?? PLAIN_CAPTION,
|
||||
...(rtl
|
||||
? { direction: 'rtl' as const, letterSpacing: 'normal' as const, textTransform: 'none' as const }
|
||||
@@ -391,7 +391,7 @@ function NumberRow({
|
||||
columnWidths: readonly number[];
|
||||
}) {
|
||||
const width = columnWidths.reduce((sum, column) => sum + column, 0);
|
||||
const height = 12;
|
||||
const height = 16;
|
||||
let cursor = 0;
|
||||
return (
|
||||
<svg
|
||||
@@ -414,7 +414,7 @@ function NumberRow({
|
||||
dominantBaseline="central"
|
||||
fill={NUMBER_INK}
|
||||
fontFamily="system-ui, Segoe UI, sans-serif"
|
||||
fontSize={11}
|
||||
fontSize={14}
|
||||
fontWeight={600}
|
||||
>
|
||||
{fdi}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LabCaseShareQrCode } from '@/components/ui/lab/LabCaseShareQrCode';
|
||||
import {
|
||||
buildCaseConnectedTeeth,
|
||||
buildCaseProsthesisRows,
|
||||
caseSheetOrderNumber,
|
||||
formatCaseDateTime,
|
||||
formatPatientMobile,
|
||||
formatPatientName,
|
||||
@@ -77,8 +78,9 @@ const PAGE_SIZE: Record<CaseSheetOrientation, { width: number; height: number }>
|
||||
function printLabelStyle(rtl: boolean) {
|
||||
return {
|
||||
color: '#64748b',
|
||||
fontSize: 11,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
lineHeight: '18px',
|
||||
...(rtl
|
||||
? {
|
||||
direction: 'rtl' as const,
|
||||
@@ -94,9 +96,9 @@ function printLabelStyle(rtl: boolean) {
|
||||
function printHeadingStyle(rtl: boolean) {
|
||||
return {
|
||||
margin: 0,
|
||||
fontSize: 15,
|
||||
fontSize: 20,
|
||||
fontWeight: 600,
|
||||
lineHeight: '18px',
|
||||
lineHeight: '26px',
|
||||
...(rtl
|
||||
? {
|
||||
direction: 'rtl' as const,
|
||||
@@ -108,9 +110,11 @@ function printHeadingStyle(rtl: boolean) {
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
const body = { color: '#0f172a', fontSize: 13, lineHeight: '16px' };
|
||||
const body = { color: '#0f172a', fontSize: 17, lineHeight: '22px' };
|
||||
|
||||
/** Extra drop so Farsi descenders clear the rule. Latin layouts stay put. */
|
||||
/** Gap above a section rule so the line sits clear of the values above it. */
|
||||
const RULE_GAP = 12;
|
||||
/** Extra drop so Farsi descenders clear the rule. */
|
||||
const FA_RULE_DROP = 6;
|
||||
|
||||
const ARABIC_SCRIPT = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]/;
|
||||
@@ -134,8 +138,8 @@ function printRtlValueStyle(value: string) {
|
||||
function printRule(rtl: boolean) {
|
||||
return {
|
||||
borderTop: '1px solid #cbd5e1',
|
||||
marginTop: rtl ? 8 + FA_RULE_DROP : 8,
|
||||
paddingTop: 6,
|
||||
marginTop: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
|
||||
paddingTop: 8,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -159,8 +163,7 @@ export function CaseSheetPrintLayout({
|
||||
const labName =
|
||||
labCase.sends[0]?.organizationName ??
|
||||
(labCase.sends.map((s) => s.organizationName).filter(Boolean).join(', ') || '—');
|
||||
const fallbackOrder = labCase.id.replace(/-/g, '').slice(0, 8).toUpperCase();
|
||||
const orderNumber = labCase.externalCode?.trim() || fallbackOrder;
|
||||
const orderNumber = caseSheetOrderNumber(labCase);
|
||||
const orderDate = labCase.sentAt ?? labCase.startedAt ?? null;
|
||||
const page = PAGE_SIZE[orientation];
|
||||
const contentWidth = page.width - 48;
|
||||
@@ -180,12 +183,15 @@ export function CaseSheetPrintLayout({
|
||||
style={{
|
||||
boxSizing: 'border-box',
|
||||
width: page.width,
|
||||
padding: rtl ? '0 24px 20px' : '0 24px 8px',
|
||||
paddingTop: orientation === 'landscape' ? 24 : 16,
|
||||
paddingRight: 24,
|
||||
paddingBottom: rtl ? 20 : 8,
|
||||
paddingLeft: 24,
|
||||
backgroundColor: '#ffffff',
|
||||
color: '#0f172a',
|
||||
fontFamily: printFont,
|
||||
fontSize: '13px',
|
||||
lineHeight: '16px',
|
||||
fontSize: '17px',
|
||||
lineHeight: '22px',
|
||||
direction: 'ltr',
|
||||
...(rtl ? { letterSpacing: '0px' as const, wordSpacing: '0px' as const } : {}),
|
||||
}}
|
||||
@@ -196,7 +202,7 @@ export function CaseSheetPrintLayout({
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
borderBottom: '1px solid #cbd5e1',
|
||||
paddingBottom: rtl ? 8 + FA_RULE_DROP : 8,
|
||||
paddingBottom: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -209,13 +215,13 @@ export function CaseSheetPrintLayout({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'flex-start',
|
||||
// Taller than the 22px glyphs. html2canvas clips the bottoms of
|
||||
// letters when this box is only as tall as the lockup (28px).
|
||||
height: 48,
|
||||
// Taller than the 28px glyphs. html2canvas clips the bottoms of
|
||||
// letters when this box is only as tall as the lockup (32px).
|
||||
height: 56,
|
||||
overflow: 'hidden',
|
||||
fontSize: 22,
|
||||
fontSize: 28,
|
||||
fontWeight: 600,
|
||||
lineHeight: '48px',
|
||||
lineHeight: '56px',
|
||||
direction: 'ltr',
|
||||
letterSpacing: '0px',
|
||||
wordSpacing: '0px',
|
||||
@@ -227,7 +233,7 @@ export function CaseSheetPrintLayout({
|
||||
display: 'inline-block',
|
||||
maxWidth: '100%',
|
||||
overflow: 'visible',
|
||||
lineHeight: '48px',
|
||||
lineHeight: '56px',
|
||||
whiteSpace: 'nowrap',
|
||||
verticalAlign: 'middle',
|
||||
letterSpacing: '0px',
|
||||
@@ -247,13 +253,13 @@ export function CaseSheetPrintLayout({
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
alignSelf: 'center',
|
||||
height: 28,
|
||||
height: 32,
|
||||
color: '#0f172a',
|
||||
fontSize: 22,
|
||||
lineHeight: '28px',
|
||||
fontSize: 26,
|
||||
lineHeight: '32px',
|
||||
}}
|
||||
>
|
||||
<BrandLockup style={{ display: 'inline-flex', alignItems: 'center', height: 28, verticalAlign: 'middle' }} />
|
||||
<BrandLockup style={{ display: 'inline-flex', alignItems: 'center', height: 32, verticalAlign: 'middle' }} />
|
||||
</div>
|
||||
<div style={{ flex: 1, display: 'flex', justifyContent: 'flex-end', minWidth: 0 }}>
|
||||
{labCase.shareUrl ? (
|
||||
@@ -286,8 +292,9 @@ export function CaseSheetPrintLayout({
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '1fr 1fr 1fr',
|
||||
alignItems: 'start',
|
||||
gap: 12,
|
||||
marginTop: 8,
|
||||
marginTop: RULE_GAP,
|
||||
}}
|
||||
>
|
||||
<MetaBlock label={labels.orderNumber} value={orderNumber} rtl={rtl} />
|
||||
@@ -299,6 +306,7 @@ export function CaseSheetPrintLayout({
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '1fr 1fr 1fr',
|
||||
alignItems: 'start',
|
||||
gap: 12,
|
||||
...printRule(rtl),
|
||||
}}
|
||||
@@ -313,7 +321,7 @@ export function CaseSheetPrintLayout({
|
||||
/>
|
||||
</section>
|
||||
|
||||
<h2 style={{ ...printHeadingStyle(rtl), marginTop: 8 }}>{labels.toothChart}</h2>
|
||||
<h2 style={{ ...printHeadingStyle(rtl), marginTop: RULE_GAP }}>{labels.toothChart}</h2>
|
||||
<section style={{ ...printRule(rtl), direction: 'ltr' }}>
|
||||
<CaseSheetFdiChart
|
||||
connectedTeeth={connectedTeeth}
|
||||
@@ -325,9 +333,9 @@ export function CaseSheetPrintLayout({
|
||||
|
||||
<section style={printRule(rtl)}>
|
||||
<h2 style={printHeadingStyle(rtl)}>{labels.prosthesis}</h2>
|
||||
<div style={{ marginTop: 10 }}>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
{prosthesisRows.length === 0 ? (
|
||||
<div style={{ color: '#64748b', fontSize: 13, lineHeight: '16px' }}>—</div>
|
||||
<div style={{ color: '#64748b', fontSize: 17, lineHeight: '22px' }}>—</div>
|
||||
) : (
|
||||
prosthesisRows.map((row) => (
|
||||
<ProsthesisPrintBox
|
||||
@@ -366,12 +374,13 @@ export function CaseSheetPrintLayout({
|
||||
</p>
|
||||
))}
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} style={{ marginTop: 8, letterSpacing: 'normal' }}>
|
||||
<div key={comment.id} style={{ marginTop: 6, letterSpacing: 'normal' }}>
|
||||
<p
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: 11,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
lineHeight: '18px',
|
||||
color: '#64748b',
|
||||
letterSpacing: 'normal',
|
||||
textTransform: 'none',
|
||||
@@ -391,7 +400,7 @@ export function CaseSheetPrintLayout({
|
||||
);
|
||||
}
|
||||
|
||||
const BOX_HEIGHT = 28;
|
||||
const BOX_HEIGHT = 40;
|
||||
|
||||
type PrintRun = {
|
||||
text: string;
|
||||
@@ -440,7 +449,7 @@ function ProsthesisPrintBox({
|
||||
text: prosthesisJobLineSeparator(previous.kind),
|
||||
fill: '#64748b',
|
||||
weight: 400,
|
||||
size: 13,
|
||||
size: 18,
|
||||
});
|
||||
}
|
||||
if (segment.kind === 'teeth') {
|
||||
@@ -449,19 +458,19 @@ function ProsthesisPrintBox({
|
||||
text: segment.text,
|
||||
fill: typeCode ? prosthesisTypePrintColorFromCatalog(typeCode, catalog) : '#0f172a',
|
||||
weight: 600,
|
||||
size: 13,
|
||||
size: 18,
|
||||
});
|
||||
} else if (segment.kind === 'pontic') {
|
||||
runs.push({
|
||||
text: segment.text,
|
||||
fill: prosthesisTypePrintColorFromCatalog(PONTIC_CODE, catalog),
|
||||
weight: 500,
|
||||
size: 13,
|
||||
size: 18,
|
||||
});
|
||||
} else {
|
||||
splitProsthesisGroupCode(segment.code).forEach((part, partIndex) => {
|
||||
if (partIndex > 0) {
|
||||
runs.push({ text: ' + ', fill: '#64748b', weight: 400, size: 13 });
|
||||
runs.push({ text: ' + ', fill: '#64748b', weight: 400, size: 18 });
|
||||
}
|
||||
const path = prosthesisJobPathParts(part, catalog, tr);
|
||||
const fill = prosthesisTypePrintColorFromCatalog(part, catalog);
|
||||
@@ -470,10 +479,10 @@ function ProsthesisPrintBox({
|
||||
text: `${path.ancestors.join(PROSTHESIS_JOB_PATH_SEP)}${PROSTHESIS_JOB_PATH_SEP}`,
|
||||
fill,
|
||||
weight: 400,
|
||||
size: 13,
|
||||
size: 18,
|
||||
});
|
||||
}
|
||||
runs.push({ text: path.leaf, fill, weight: 600, size: 13 });
|
||||
runs.push({ text: path.leaf, fill, weight: 600, size: 18 });
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -482,7 +491,7 @@ function ProsthesisPrintBox({
|
||||
text: connectedLabel.toUpperCase(),
|
||||
fill: '#334155',
|
||||
weight: 700,
|
||||
size: 11,
|
||||
size: 14,
|
||||
underline: true,
|
||||
dx: rtl ? -16 : 16,
|
||||
});
|
||||
@@ -513,7 +522,7 @@ function ProsthesisPrintBox({
|
||||
textAnchor="start"
|
||||
dominantBaseline="central"
|
||||
fontFamily={fontFamily}
|
||||
fontSize={13}
|
||||
fontSize={18}
|
||||
style={
|
||||
rtl
|
||||
? { direction: 'rtl', unicodeBidi: 'embed' }
|
||||
@@ -572,9 +581,10 @@ function PartyBlock({
|
||||
<p style={{ ...printLabelStyle(rtl), margin: 0 }}>{label}</p>
|
||||
<p
|
||||
style={{
|
||||
margin: '4px 0 0',
|
||||
fontSize: 15,
|
||||
margin: '2px 0 0',
|
||||
fontSize: 20,
|
||||
fontWeight: 600,
|
||||
lineHeight: '26px',
|
||||
...(rtl ? printRtlValueStyle(title) : {}),
|
||||
}}
|
||||
>
|
||||
@@ -584,7 +594,8 @@ function PartyBlock({
|
||||
<p
|
||||
style={{
|
||||
margin: '2px 0 0',
|
||||
fontSize: 12,
|
||||
fontSize: 15,
|
||||
lineHeight: '20px',
|
||||
color: '#475569',
|
||||
...(rtl ? printRtlValueStyle(subtitle) : {}),
|
||||
}}
|
||||
|
||||
22
frontend/src/components/ui/lab/CaseUploadFailureReporter.tsx
Normal file
22
frontend/src/components/ui/lab/CaseUploadFailureReporter.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import { useToast } from '@/components/ui/shared/ToastProvider';
|
||||
import { onCaseUploadFailure } from '@/lib/uploads/caseUploadQueue';
|
||||
|
||||
/** Upload errors outlive the Cases page. The toast host is already above the tabs. */
|
||||
export function CaseUploadFailureReporter() {
|
||||
const toast = useToast();
|
||||
const t = useTranslations('cases');
|
||||
const tErrors = useTranslations('errors');
|
||||
|
||||
useEffect(() => {
|
||||
return onCaseUploadFailure((error) => {
|
||||
toast.showError(getUserFacingError(error, tErrors, t('errorSaveCase')));
|
||||
});
|
||||
}, [t, tErrors, toast]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import { canEditCases } from '@/components/shared/permissions';
|
||||
import { AddCaseWithVoice } from '@/components/ui/lab/AddCaseWithVoice';
|
||||
import { CaseDetailPanel, CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
|
||||
import { CaseSendDialog } from '@/components/ui/lab/CaseSendDialog';
|
||||
import { CaseCreatePanel } from '@/components/ui/lab/CaseCreatePanel';
|
||||
@@ -23,13 +24,20 @@ import { commentVisibilityProps, isDraftLabCase, isLabGeneratedCase } from '@/co
|
||||
import { notificationsApi } from '@/lib/api/notifications';
|
||||
import { notifyTabBadgesChanged, tabBadgesChangedEventName } from '@/lib/tabBadgeUtils';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import {
|
||||
registerCaseFileStored,
|
||||
withKnownCaseFiles,
|
||||
} from '@/lib/uploads/caseUploadQueue';
|
||||
import { caseCommentsApi } from '@/lib/api/case-comments';
|
||||
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
|
||||
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
|
||||
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
|
||||
import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
|
||||
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
|
||||
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
|
||||
import { voiceApi } from '@/lib/api/voice';
|
||||
import { isMediaRecorderSupported } from '@/lib/voice/audioFormat';
|
||||
import { useVoiceCapture } from '@/lib/voice/useVoiceCapture';
|
||||
import type { VoiceAvailability, VoiceExtractionResult } from '@/types/voice';
|
||||
import { Badge } from '@/components/ui/shared/Badge';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton';
|
||||
@@ -128,6 +136,39 @@ export function CasesPage() {
|
||||
|
||||
const canEdit = canEditCases(currentOrganization);
|
||||
const locale = user?.language ?? 'en';
|
||||
const pageLocale = useLocale();
|
||||
const tTreatment = useTranslations('treatment');
|
||||
const [voiceAvailability, setVoiceAvailability] = useState<VoiceAvailability | null>(null);
|
||||
const [voiceResult, setVoiceResult] = useState<VoiceExtractionResult | null>(null);
|
||||
const voiceCaseIdRef = useRef<string | null>(null);
|
||||
const onVoiceExtractedRef = useRef<(result: VoiceExtractionResult) => void>(() => {});
|
||||
onVoiceExtractedRef.current = (result) => {
|
||||
if (voiceCaseIdRef.current && voiceCaseIdRef.current === selectedCaseIdRef.current) {
|
||||
setVoiceResult(result);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void voiceApi.availability().then((response) => setVoiceAvailability(response.data)).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const voice = useVoiceCapture({
|
||||
locale: pageLocale,
|
||||
maxMs: voiceAvailability?.maxRecordingMs ?? null,
|
||||
onExtracted: (result) => onVoiceExtractedRef.current(result),
|
||||
onError: (error) =>
|
||||
toast.showError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))),
|
||||
});
|
||||
const voiceEnabled =
|
||||
Boolean(voiceAvailability?.enabled) &&
|
||||
(voiceAvailability?.locales.includes(pageLocale) ?? false) &&
|
||||
isMediaRecorderSupported();
|
||||
|
||||
useEffect(() => {
|
||||
if (voiceCaseIdRef.current && selectedCaseId !== voiceCaseIdRef.current) {
|
||||
setVoiceResult(null);
|
||||
}
|
||||
}, [selectedCaseId]);
|
||||
|
||||
const prosthesisLabel = useCallback(
|
||||
(code: string) =>
|
||||
@@ -233,7 +274,7 @@ export function CasesPage() {
|
||||
try {
|
||||
const response = await casesApi.getOne(caseId);
|
||||
if (gen !== detailFetchGen.current || selectedCaseIdRef.current !== caseId) return;
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
} catch (error: unknown) {
|
||||
if (gen !== detailFetchGen.current || selectedCaseIdRef.current !== caseId) return;
|
||||
if (!silent) {
|
||||
@@ -247,6 +288,16 @@ export function CasesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return registerCaseFileStored((caseId, attachment) => {
|
||||
setSelectedCase((current) => {
|
||||
if (!current || current.id !== caseId) return current;
|
||||
if (current.attachments.some((file) => file.id === attachment.id)) return current;
|
||||
return { ...current, attachments: [...current.attachments, attachment] };
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void casesApi.listFilterOptions().then((r) => setFilterOptions(r.data)).catch(() => {});
|
||||
void prosthesisCatalogApi.list().then((r) => setProsthesisCatalog(r.data)).catch(() => {});
|
||||
@@ -374,8 +425,8 @@ export function CasesPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload when selection changes
|
||||
}, [selectedCaseId]);
|
||||
|
||||
async function handleAddCase() {
|
||||
if (!canEdit || creatingCase) return;
|
||||
async function handleAddCase(): Promise<string | null> {
|
||||
if (!canEdit || creatingCase) return null;
|
||||
setCreatingCase(true);
|
||||
setDraftsExpanded(true);
|
||||
toast.setError('');
|
||||
@@ -399,13 +450,29 @@ export function CasesPage() {
|
||||
selectedCaseIdRef.current = created.id;
|
||||
setSelectedCaseId(created.id);
|
||||
setDraftsExpanded(true);
|
||||
return created.id;
|
||||
} catch (error: unknown) {
|
||||
toast.showError(getUserFacingError(error, tErrors, t('errorCreateCase')));
|
||||
return null;
|
||||
} finally {
|
||||
setCreatingCase(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAddCaseVoice() {
|
||||
if (voice.phase === 'recording') {
|
||||
voice.onStop();
|
||||
return;
|
||||
}
|
||||
if (voice.phase !== 'idle' || creatingCase) return;
|
||||
const openDraftId =
|
||||
selectedCase && isDraftLabCase(selectedCase) ? selectedCase.id : null;
|
||||
const caseId = openDraftId ?? (await handleAddCase());
|
||||
if (!caseId) return;
|
||||
voiceCaseIdRef.current = caseId;
|
||||
voice.onStart();
|
||||
}
|
||||
|
||||
const loadCaseAttachmentBlob = useCallback(
|
||||
(caseId: string, attachmentId: string) => casesApi.getAttachmentFileBlob(caseId, attachmentId),
|
||||
[],
|
||||
@@ -426,7 +493,7 @@ export function CasesPage() {
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await casesApi.reopenTask(selectedCaseId, taskId);
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
setCases((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === selectedCaseId
|
||||
@@ -457,7 +524,7 @@ export function CasesPage() {
|
||||
try {
|
||||
const response = await casesApi.stop(selectedCaseId);
|
||||
const detail = response.data;
|
||||
setSelectedCase(detail);
|
||||
setSelectedCase(withKnownCaseFiles(detail));
|
||||
setCases((prev) => prev.filter((item) => item.id !== detail.id));
|
||||
setDrafts((prev) => [
|
||||
draftListItemFromDetail(detail),
|
||||
@@ -496,7 +563,7 @@ export function CasesPage() {
|
||||
destinationOrganizationId,
|
||||
taskIds,
|
||||
});
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
setSendOpen(false);
|
||||
toast.showSuccess(t('successSendCase'));
|
||||
notifyTabBadgesChanged();
|
||||
@@ -521,7 +588,7 @@ export function CasesPage() {
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await casesApi.recallOutsource(selectedCaseId, childCaseId);
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
toast.showSuccess(t('successRecallOutsource'));
|
||||
notifyTabBadgesChanged();
|
||||
} catch (error: unknown) {
|
||||
@@ -538,7 +605,7 @@ export function CasesPage() {
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await casesApi.assignTask(selectedCaseId, taskId, assigneeUserId);
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
notifyTabBadgesChanged();
|
||||
} catch (error: unknown) {
|
||||
toast.showError(getUserFacingError(error, tErrors, t('errorAssignTask')));
|
||||
@@ -557,7 +624,7 @@ export function CasesPage() {
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await casesApi.setCaseImportant(selectedCaseId, isImportant);
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
setCases((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === selectedCaseId ? { ...item, isImportant: response.data.isImportant } : item,
|
||||
@@ -582,7 +649,7 @@ export function CasesPage() {
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await casesApi.setCaseExternalCode(selectedCaseId, externalCode);
|
||||
setSelectedCase(response.data);
|
||||
setSelectedCase(withKnownCaseFiles(response.data));
|
||||
} catch (error: unknown) {
|
||||
setSelectedCase(previousCase);
|
||||
toast.showError(getUserFacingError(error, tErrors, t('errorUpdateExternalCode')));
|
||||
@@ -678,15 +745,15 @@ export function CasesPage() {
|
||||
}`}
|
||||
>
|
||||
{canEdit ? (
|
||||
<div className="self-start">
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={t('addCase')}
|
||||
isLoading={creatingCase}
|
||||
disabled={creatingCase}
|
||||
onClick={() => void handleAddCase()}
|
||||
/>
|
||||
</div>
|
||||
<AddCaseWithVoice
|
||||
label={t('addCase')}
|
||||
startLabel={tTreatment('voiceStart')}
|
||||
stopLabel={tTreatment('voiceStop')}
|
||||
disabled={creatingCase}
|
||||
voice={voiceEnabled ? voice : null}
|
||||
onAdd={() => void handleAddCase()}
|
||||
onVoice={() => void handleAddCaseVoice()}
|
||||
/>
|
||||
) : null}
|
||||
<SearchBar
|
||||
embedded
|
||||
@@ -843,8 +910,17 @@ export function CasesPage() {
|
||||
labCase={selectedCase}
|
||||
canEdit={canEdit}
|
||||
prosthesisCatalog={prosthesisCatalog}
|
||||
voiceResult={
|
||||
voiceResult && voiceCaseIdRef.current === selectedCase.id ? voiceResult : null
|
||||
}
|
||||
onVoiceResultHandled={() => {
|
||||
setVoiceResult(null);
|
||||
voiceCaseIdRef.current = null;
|
||||
}}
|
||||
onSaved={(detail) => {
|
||||
setSelectedCase(detail);
|
||||
if (selectedCaseIdRef.current === detail.id) {
|
||||
setSelectedCase(withKnownCaseFiles(detail));
|
||||
}
|
||||
const patchItem = (item: LabCaseListItem): LabCaseListItem =>
|
||||
item.id === detail.id
|
||||
? {
|
||||
@@ -860,7 +936,7 @@ export function CasesPage() {
|
||||
setDrafts((prev) => prev.map(patchItem));
|
||||
}}
|
||||
onStarted={(detail) => {
|
||||
setSelectedCase(detail);
|
||||
setSelectedCase(withKnownCaseFiles(detail));
|
||||
setDrafts((prev) => prev.filter((item) => item.id !== detail.id));
|
||||
setCases((prev) => {
|
||||
const existing = prev.find((item) => item.id === detail.id);
|
||||
@@ -961,9 +1037,7 @@ export function CasesPage() {
|
||||
canAddFiles={canEdit}
|
||||
onCaseUpdated={setSelectedCase}
|
||||
headerMetaLines={
|
||||
<p className="text-sm text-text-muted">
|
||||
{t('fromClinic', { name: selectedCase.clinic.name })}
|
||||
</p>
|
||||
<span>{t('fromClinic', { name: selectedCase.clinic.name })}</span>
|
||||
}
|
||||
commentsSection={
|
||||
selectedCaseId ? (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
|
||||
import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Eye, EyeOff, Send } from 'lucide-react';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
@@ -77,15 +78,15 @@ export function LabCaseCommentsPanel({
|
||||
const loadCommentsRef = useRef(loadComments);
|
||||
loadCommentsRef.current = loadComments;
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const refresh = useCallback(async (options?: { silent?: boolean }) => {
|
||||
if (!options?.silent) setLoading(true);
|
||||
try {
|
||||
const items = await loadCommentsRef.current();
|
||||
setComments(sortNewestFirst(items));
|
||||
} catch (error: unknown) {
|
||||
onError?.(getUserFacingError(error, tErrors, t('errorLoad')));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (!options?.silent) setLoading(false);
|
||||
}
|
||||
}, [onError, t, tErrors]);
|
||||
|
||||
@@ -93,6 +94,14 @@ export function LabCaseCommentsPanel({
|
||||
void refresh();
|
||||
}, [caseId, refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChanged = () => {
|
||||
void refresh({ silent: true });
|
||||
};
|
||||
window.addEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
return () => window.removeEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
}, [refresh]);
|
||||
|
||||
async function handlePost() {
|
||||
const trimmed = body.trim();
|
||||
if (!trimmed || !canPost || posting) return;
|
||||
|
||||
@@ -84,18 +84,28 @@ interface LabCaseShareQrThumbProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbProps) {
|
||||
export function LabCaseShareQrThumb({
|
||||
shareUrl,
|
||||
onClick,
|
||||
compact = false,
|
||||
}: LabCaseShareQrThumbProps & { compact?: boolean }) {
|
||||
const t = useTranslations('cases');
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="aspect-square w-24 sm:w-32 cursor-pointer rounded-[var(--radius-md)] border border-border/60 overflow-hidden bg-white p-2 transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary flex items-center justify-center"
|
||||
className={`aspect-square cursor-pointer overflow-hidden rounded-[var(--radius-md)] border border-border/60 bg-white transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary flex items-center justify-center ${
|
||||
compact ? 'w-14 p-1' : 'w-24 p-2 sm:w-32'
|
||||
}`}
|
||||
title={t('viewShareQr')}
|
||||
aria-label={t('viewShareQr')}
|
||||
>
|
||||
<LabCaseShareQrCode value={shareUrl} size={96} className="h-full w-full max-h-full max-w-full" />
|
||||
<LabCaseShareQrCode
|
||||
value={shareUrl}
|
||||
size={compact ? 48 : 96}
|
||||
className="h-full w-full max-h-full max-w-full"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -104,9 +114,11 @@ export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbPr
|
||||
export function LabCaseShareQr({
|
||||
shareUrl,
|
||||
className,
|
||||
compact = false,
|
||||
}: {
|
||||
shareUrl: string;
|
||||
className?: string;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const url = shareUrl.trim();
|
||||
@@ -115,7 +127,7 @@ export function LabCaseShareQr({
|
||||
return (
|
||||
<>
|
||||
<div className={className}>
|
||||
<LabCaseShareQrThumb shareUrl={url} onClick={() => setOpen(true)} />
|
||||
<LabCaseShareQrThumb shareUrl={url} compact={compact} onClick={() => setOpen(true)} />
|
||||
</div>
|
||||
<LabCaseShareQrDialog open={open} onClose={() => setOpen(false)} shareUrl={url} />
|
||||
</>
|
||||
|
||||
@@ -32,6 +32,10 @@ import { useToast } from '@/lib/hooks/useToast';
|
||||
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
|
||||
import { caseCommentsApi } from '@/lib/api/case-comments';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import {
|
||||
registerCaseFileStored,
|
||||
withKnownAttachments,
|
||||
} from '@/lib/uploads/caseUploadQueue';
|
||||
import { tasksApi } from '@/lib/api/tasks';
|
||||
import type { LabCaseAttachmentMeta } from '@/types/cases';
|
||||
import type {
|
||||
@@ -77,6 +81,18 @@ export function TasksPage() {
|
||||
const [caseFiles, setCaseFiles] = useState<LabCaseAttachmentMeta[]>([]);
|
||||
const [filesLoading, setFilesLoading] = useState(false);
|
||||
const filesRequestRef = useRef(0);
|
||||
const filesCaseIdRef = useRef(filesCaseId);
|
||||
filesCaseIdRef.current = filesCaseId;
|
||||
|
||||
useEffect(() => {
|
||||
return registerCaseFileStored((caseId, attachment) => {
|
||||
if (filesCaseIdRef.current !== caseId) return;
|
||||
setCaseFiles((current) => {
|
||||
if (current.some((file) => file.id === attachment.id)) return current;
|
||||
return [...current, attachment];
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const [search, setSearch] = useState(DEFAULT_TASKS_VIEW.search);
|
||||
const [clinicId, setClinicId] = useState(DEFAULT_TASKS_VIEW.clinicId);
|
||||
@@ -354,7 +370,7 @@ export function TasksPage() {
|
||||
try {
|
||||
const response = await casesApi.listAttachments(caseId);
|
||||
if (filesRequestRef.current !== requestId) return;
|
||||
setCaseFiles(response.data);
|
||||
setCaseFiles(withKnownAttachments(caseId, response.data));
|
||||
} catch (error: unknown) {
|
||||
if (filesRequestRef.current !== requestId) return;
|
||||
setFilesCaseId(null);
|
||||
@@ -681,9 +697,9 @@ export function TasksPage() {
|
||||
<p className="py-3 text-sm text-text-muted">{t('loading')}</p>
|
||||
) : (
|
||||
<CaseFilesPanel
|
||||
caseId={caseGroup.labCaseId}
|
||||
attachments={caseFiles}
|
||||
canAdd={false}
|
||||
onAdd={() => undefined}
|
||||
onDownload={(file) =>
|
||||
casesApi.getAttachmentFileBlob(caseGroup.labCaseId, file.id)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ export function MobileDetailBackButton({
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`${HIDE_FROM_CLASS[hideFrom]} inline-flex items-center gap-1 text-sm text-primary hover:opacity-90 mb-3`}
|
||||
className={`${HIDE_FROM_CLASS[hideFrom]} mb-1.5 inline-flex items-center gap-1 text-sm text-primary hover:opacity-90`}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4 icon-flat" />
|
||||
{t('back')}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { NavBadgePill } from '@/components/ui/shared/NavBadgePill';
|
||||
|
||||
export function UnderlineTabs<T extends string>({
|
||||
label,
|
||||
tabs,
|
||||
@@ -7,7 +9,7 @@ export function UnderlineTabs<T extends string>({
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
tabs: Array<{ id: T; label: string }>;
|
||||
tabs: Array<{ id: T; label: string; count?: number }>;
|
||||
value: T;
|
||||
onChange: (id: T) => void;
|
||||
}) {
|
||||
@@ -22,13 +24,16 @@ export function UnderlineTabs<T extends string>({
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
onClick={() => onChange(tab.id)}
|
||||
className={`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors ${
|
||||
className={`relative -mb-px border-b-2 px-3 py-2 text-base font-bold transition-colors ${
|
||||
active
|
||||
? 'border-primary text-primary'
|
||||
: 'border-transparent text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
<span className="pointer-events-none absolute -top-1.5 right-0 z-10 translate-x-1/2">
|
||||
<NavBadgePill count={tab.count ?? 0} ariaLabel={`${tab.label} ${tab.count ?? 0}`} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -32,6 +32,8 @@ interface TreatmentDetailsEditorProps {
|
||||
onActiveDetailChange: (id: string) => void;
|
||||
onDetailsChange: (details: TreatmentDetailDraft[]) => void;
|
||||
isDetailLocked: (detail: TreatmentDetailDraft) => boolean;
|
||||
/** Sent to a lab. Distinct from the edit lock, which waits for a completed step. */
|
||||
isDetailSent: (detail: TreatmentDetailDraft) => boolean;
|
||||
labDependentCodes: Set<string>;
|
||||
treatmentCatalog: TreatmentCatalogEntry[];
|
||||
disabled: boolean;
|
||||
@@ -82,6 +84,7 @@ export function TreatmentDetailsEditor({
|
||||
onActiveDetailChange,
|
||||
onDetailsChange,
|
||||
isDetailLocked,
|
||||
isDetailSent,
|
||||
labDependentCodes,
|
||||
treatmentCatalog,
|
||||
disabled,
|
||||
@@ -231,10 +234,10 @@ export function TreatmentDetailsEditor({
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{details.map((d, idx) => {
|
||||
const detailLocked = isDetailLocked(d);
|
||||
const detailSent = isDetailSent(d);
|
||||
const isActive = d.clientId === activeDetailId;
|
||||
const showRemoveAction = Boolean(onRemoveDetail);
|
||||
const removeDisabled = !canEdit || disabled || Boolean(d.sentAt) || detailLocked || uploadBusy;
|
||||
const removeDisabled = !canEdit || disabled || detailSent || uploadBusy;
|
||||
const chipLabel = formatDetailChipLabel(
|
||||
d,
|
||||
treatmentCatalog,
|
||||
@@ -268,12 +271,12 @@ export function TreatmentDetailsEditor({
|
||||
{showLabStatus ? (
|
||||
<span
|
||||
className={`shrink-0 ${
|
||||
detailLocked
|
||||
detailSent
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-amber-600 dark:text-amber-400'
|
||||
}`}
|
||||
>
|
||||
· {detailLocked ? t('detailSentBadge') : t('detailUnsentBadge')}
|
||||
· {detailSent ? t('detailSentBadge') : t('detailUnsentBadge')}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
|
||||
@@ -602,6 +602,13 @@ export function TreatmentWorkspace({
|
||||
[labCaseDrafts],
|
||||
);
|
||||
|
||||
const isDetailSent = useCallback(
|
||||
(detail: TreatmentDetailDraft) =>
|
||||
Boolean(detail.sentAt) ||
|
||||
labCaseDrafts.some((lc) => Boolean(lc.sentAt) && lc.detailClientId === detail.clientId),
|
||||
[labCaseDrafts],
|
||||
);
|
||||
|
||||
const activeSentLabCaseId = useMemo(() => {
|
||||
const match = labCaseDrafts.find(
|
||||
(lc) => lc.detailClientId === activeDetailId && lc.sentAt && lc.id,
|
||||
@@ -1351,7 +1358,53 @@ export function TreatmentWorkspace({
|
||||
useEffect(() => {
|
||||
const appointmentId = selectedAppointment?.id;
|
||||
const treatmentId = selectedStandalone?.id;
|
||||
if ((!appointmentId && !treatmentId) || workspaceMode !== 'live') return;
|
||||
if (workspaceMode !== 'live') return;
|
||||
|
||||
// A day with no visit must match a fresh open of the tab: one blank line,
|
||||
// no patient, no leftover plan from the day the arrows just left.
|
||||
if (!appointmentId && !treatmentId) {
|
||||
skipNextGetDraftRef.current = false;
|
||||
const current = detailsRef.current;
|
||||
const drafts = labCaseDraftsRef.current;
|
||||
const alreadyBlank =
|
||||
current.length === 1 &&
|
||||
!isDetailTypeSelected(current[0]) &&
|
||||
current[0].teeth.length === 0 &&
|
||||
current[0].toothSelectionGroups.length === 0 &&
|
||||
current[0].comment.trim() === '' &&
|
||||
current[0].attachmentMetas.length === 0 &&
|
||||
!current[0].sentAt &&
|
||||
drafts.length === 0;
|
||||
if (alreadyBlank) return;
|
||||
|
||||
const first = newDetail();
|
||||
const snap = serializeDetails([first]);
|
||||
const emptyLab = serializeLabCases([]);
|
||||
detailsRef.current = [first];
|
||||
savedSnapshotRef.current = snap;
|
||||
labCaseDraftsRef.current = [];
|
||||
savedLabCasesSnapshotRef.current = emptyLab;
|
||||
setDetails([first]);
|
||||
setActiveDetailId(first.clientId);
|
||||
setSavedSnapshot(snap);
|
||||
setLabCaseDrafts([]);
|
||||
setSavedLabCasesSnapshot(emptyLab);
|
||||
setActiveLabCaseId(null);
|
||||
setSaveStatus('idle');
|
||||
setPlanBilledManual(false);
|
||||
setPlanBilledAmount('');
|
||||
setLabWorkspaceView('chart');
|
||||
setShowWholeTreatmentPlan(false);
|
||||
setOrganizationSearch('');
|
||||
setVoiceResult(null);
|
||||
setSelectedPreviewId(null);
|
||||
setSelectedRailLabCaseId(null);
|
||||
if (autosaveTimerRef.current) {
|
||||
clearTimeout(autosaveTimerRef.current);
|
||||
autosaveTimerRef.current = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (skipNextGetDraftRef.current) {
|
||||
skipNextGetDraftRef.current = false;
|
||||
@@ -3050,6 +3103,7 @@ export function TreatmentWorkspace({
|
||||
onDetailsChange={setDetails}
|
||||
onTreatmentTypeChange={handleTreatmentTypeChange}
|
||||
isDetailLocked={isDetailLocked}
|
||||
isDetailSent={isDetailSent}
|
||||
labDependentCodes={labDependentCodes}
|
||||
treatmentCatalog={treatmentDropdownCatalog}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
|
||||
@@ -94,17 +94,56 @@ export const casesApi = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
removeAttachment: async (
|
||||
caseId: string,
|
||||
attachmentId: string,
|
||||
): Promise<{ success: boolean }> => {
|
||||
const response = await apiClient.delete(`/cases/${caseId}/attachments/${attachmentId}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
sectionCounts: async (
|
||||
caseId: string,
|
||||
): Promise<{ success: boolean; data: { files: number; messages: number } }> => {
|
||||
const response = await apiClient.get(`/cases/${caseId}/section-counts`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
markSectionRead: async (
|
||||
caseId: string,
|
||||
section: 'FILES' | 'MESSAGES',
|
||||
): Promise<{ success: boolean }> => {
|
||||
const response = await apiClient.post(`/cases/${caseId}/sections/${section}/read`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
uploadAttachments: async (
|
||||
caseId: string,
|
||||
files: File[],
|
||||
onUploadProgress?: (percent: number) => void,
|
||||
): Promise<{ success: boolean; data: LabCaseAttachmentMeta[] }> => {
|
||||
const form = new FormData();
|
||||
for (const file of files) {
|
||||
form.append('files', file);
|
||||
}
|
||||
const response = await apiClient.post(`/cases/${caseId}/attachments`, form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
timeout: 120_000,
|
||||
// No deadline and no body cap. A scan larger than ~40MB exceeds 120s on a
|
||||
// slow link, and a manual multipart header drops the boundary.
|
||||
timeout: 0,
|
||||
maxBodyLength: Infinity,
|
||||
maxContentLength: Infinity,
|
||||
transformRequest: (data, headers) => {
|
||||
if (typeof FormData !== 'undefined' && data instanceof FormData) {
|
||||
headers.delete('Content-Type');
|
||||
}
|
||||
return data;
|
||||
},
|
||||
onUploadProgress: onUploadProgress
|
||||
? (event) => {
|
||||
if (!event.total) return;
|
||||
onUploadProgress(Math.round((event.loaded / event.total) * 100));
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
@@ -166,7 +205,7 @@ export const casesApi = {
|
||||
getAttachmentFileBlob: async (caseId: string, attachmentId: string): Promise<Blob> => {
|
||||
const response = await apiClient.get(`/cases/${caseId}/attachments/${attachmentId}/file`, {
|
||||
responseType: 'blob',
|
||||
timeout: 120_000,
|
||||
timeout: 0,
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
@@ -115,8 +115,15 @@ export const treatmentsApi = {
|
||||
`/treatments/${treatmentId}/details/${encodeURIComponent(detailClientId)}/attachments`,
|
||||
form,
|
||||
{
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
timeout: 120_000,
|
||||
timeout: 0,
|
||||
maxBodyLength: Infinity,
|
||||
maxContentLength: Infinity,
|
||||
transformRequest: (data, headers) => {
|
||||
if (typeof FormData !== 'undefined' && data instanceof FormData) {
|
||||
headers.delete('Content-Type');
|
||||
}
|
||||
return data;
|
||||
},
|
||||
onUploadProgress: onUploadProgress
|
||||
? (event) => {
|
||||
if (!event.total) return;
|
||||
@@ -161,8 +168,15 @@ export const treatmentsApi = {
|
||||
`/treatments/appointments/${appointmentId}/details/${encodeURIComponent(detailClientId)}/attachments`,
|
||||
form,
|
||||
{
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
timeout: 120_000,
|
||||
timeout: 0,
|
||||
maxBodyLength: Infinity,
|
||||
maxContentLength: Infinity,
|
||||
transformRequest: (data, headers) => {
|
||||
if (typeof FormData !== 'undefined' && data instanceof FormData) {
|
||||
headers.delete('Content-Type');
|
||||
}
|
||||
return data;
|
||||
},
|
||||
onUploadProgress: onUploadProgress
|
||||
? (event) => {
|
||||
if (!event.total) return;
|
||||
@@ -218,7 +232,7 @@ export const treatmentsApi = {
|
||||
getAttachmentFileBlob: async (attachmentId: string): Promise<Blob> => {
|
||||
const response = await apiClient.get(`/treatments/attachments/${attachmentId}/file`, {
|
||||
responseType: 'blob',
|
||||
timeout: 120_000,
|
||||
timeout: 0,
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
49
frontend/src/lib/hooks/useCaseSectionCounts.ts
Normal file
49
frontend/src/lib/hooks/useCaseSectionCounts.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils';
|
||||
|
||||
export type CasePanelSection = 'details' | 'files' | 'messages';
|
||||
|
||||
const EMPTY = { files: 0, messages: 0 };
|
||||
|
||||
/**
|
||||
* Unread Files and Messages counts for one case.
|
||||
* Opening Details does not clear either cursor. The open Files or Messages tab is marked read.
|
||||
*/
|
||||
export function useCaseSectionCounts(caseId: string, section: CasePanelSection) {
|
||||
const [counts, setCounts] = useState(EMPTY);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const response = await casesApi.sectionCounts(caseId);
|
||||
if (cancelled) return;
|
||||
const next = { ...response.data };
|
||||
if ((section === 'files' || section === 'messages') && next[section] > 0) {
|
||||
await casesApi.markSectionRead(caseId, section === 'files' ? 'FILES' : 'MESSAGES');
|
||||
if (cancelled) return;
|
||||
next[section] = 0;
|
||||
}
|
||||
setCounts(next);
|
||||
} catch {
|
||||
if (!cancelled) setCounts(EMPTY);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
const onChanged = () => {
|
||||
void load();
|
||||
};
|
||||
window.addEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener(tabBadgesChangedEventName(), onChanged);
|
||||
};
|
||||
}, [caseId, section]);
|
||||
|
||||
return counts;
|
||||
}
|
||||
18
frontend/src/lib/hooks/useCaseUploadJobs.ts
Normal file
18
frontend/src/lib/hooks/useCaseUploadJobs.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
'use client';
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import {
|
||||
caseUploadSnapshot,
|
||||
subscribeCaseUploads,
|
||||
type CaseUploadJob,
|
||||
} from '@/lib/uploads/caseUploadQueue';
|
||||
|
||||
const EMPTY: CaseUploadJob[] = [];
|
||||
|
||||
export function useCaseUploadJobs(caseId: string): CaseUploadJob[] {
|
||||
return useSyncExternalStore(
|
||||
subscribeCaseUploads,
|
||||
() => caseUploadSnapshot(caseId),
|
||||
() => EMPTY,
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,8 @@ export function formatLabCaseActivityLine(
|
||||
return t('activityCaseCompleted', { actor, date });
|
||||
case 'CASE_AMENDED':
|
||||
return t('activityCaseAmended', { actor, date });
|
||||
case 'ATTACHMENT_ADDED':
|
||||
return t('activityAttachmentAdded', { actor, date });
|
||||
default:
|
||||
return t('activityGeneric', { date });
|
||||
}
|
||||
|
||||
@@ -101,6 +101,10 @@ export function RealtimeProvider({ children }: { children: ReactNode }) {
|
||||
setUnreadCount(payload.count);
|
||||
}
|
||||
});
|
||||
// File uploads have no inbox card. Refresh open case tabs the same way comments do.
|
||||
socket.on('case-section.changed', () => {
|
||||
notifyTabBadgesChanged();
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
|
||||
276
frontend/src/lib/uploads/caseUploadQueue.ts
Normal file
276
frontend/src/lib/uploads/caseUploadQueue.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
import type { LabCaseAttachmentMeta, LabCaseDetail } from '@/types/cases';
|
||||
|
||||
export type CaseUploadJob = {
|
||||
id: string;
|
||||
caseId: string;
|
||||
fileName: string;
|
||||
sizeBytes: number;
|
||||
percent: number;
|
||||
failed: boolean;
|
||||
};
|
||||
|
||||
type DraftBridge = {
|
||||
/** Flush the open draft before the first file in this batch is posted. */
|
||||
prepare: () => Promise<boolean>;
|
||||
/** Remember the new file id locally so a later autosave does not unlink it. */
|
||||
commit: (attachment: LabCaseAttachmentMeta) => void;
|
||||
/** Release the draft lock. One extra save only if the form changed during the upload. */
|
||||
settle: () => void;
|
||||
};
|
||||
|
||||
type StoredHandler = (caseId: string, attachment: LabCaseAttachmentMeta) => void;
|
||||
type FailureHandler = (error: unknown) => void;
|
||||
|
||||
const EMPTY: CaseUploadJob[] = [];
|
||||
const jobs: CaseUploadJob[] = [];
|
||||
const files = new Map<string, File>();
|
||||
const bridges = new Map<string, DraftBridge>();
|
||||
const prepared = new Set<string>();
|
||||
/** Files posted this session. A stale case fetch must not drop them, and must not refetch. */
|
||||
const known = new Map<string, LabCaseAttachmentMeta[]>();
|
||||
let byCase = new Map<string, CaseUploadJob[]>();
|
||||
const listeners = new Set<() => void>();
|
||||
let storedHandler: StoredHandler | null = null;
|
||||
let failureHandler: FailureHandler | null = null;
|
||||
let chain: Promise<void> = Promise.resolve();
|
||||
let emitTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function rebuild() {
|
||||
const next = new Map<string, CaseUploadJob[]>();
|
||||
for (const job of jobs) {
|
||||
const list = next.get(job.caseId);
|
||||
if (list) list.push(job);
|
||||
else next.set(job.caseId, [job]);
|
||||
}
|
||||
byCase = next;
|
||||
}
|
||||
|
||||
function emit() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function publish(immediate = false) {
|
||||
rebuild();
|
||||
if (listeners.size === 0) return;
|
||||
if (immediate) {
|
||||
if (emitTimer) clearTimeout(emitTimer);
|
||||
emitTimer = null;
|
||||
emit();
|
||||
return;
|
||||
}
|
||||
if (emitTimer) return;
|
||||
emitTimer = setTimeout(() => {
|
||||
emitTimer = null;
|
||||
if (listeners.size > 0) emit();
|
||||
}, 150);
|
||||
}
|
||||
|
||||
export function subscribeCaseUploads(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function caseUploadSnapshot(caseId: string): CaseUploadJob[] {
|
||||
return byCase.get(caseId) ?? EMPTY;
|
||||
}
|
||||
|
||||
export function registerDraftUploadBridge(caseId: string, bridge: DraftBridge) {
|
||||
bridges.set(caseId, bridge);
|
||||
const waiting = known.get(caseId);
|
||||
if (waiting?.length) {
|
||||
for (const attachment of waiting) bridge.commit(attachment);
|
||||
}
|
||||
return () => {
|
||||
if (bridges.get(caseId) === bridge) bridges.delete(caseId);
|
||||
};
|
||||
}
|
||||
|
||||
export function registerCaseFileStored(handler: StoredHandler) {
|
||||
storedHandler = handler;
|
||||
return () => {
|
||||
if (storedHandler === handler) storedHandler = null;
|
||||
};
|
||||
}
|
||||
|
||||
export function onCaseUploadFailure(handler: FailureHandler) {
|
||||
failureHandler = handler;
|
||||
return () => {
|
||||
if (failureHandler === handler) failureHandler = null;
|
||||
};
|
||||
}
|
||||
|
||||
export function forgetKnownCaseFile(caseId: string, attachmentId: string) {
|
||||
const list = known.get(caseId);
|
||||
if (!list) return;
|
||||
const next = list.filter((file) => file.id !== attachmentId);
|
||||
if (next.length === 0) known.delete(caseId);
|
||||
else known.set(caseId, next);
|
||||
}
|
||||
|
||||
const EMPTY_IDS: ReadonlySet<string> = new Set();
|
||||
|
||||
export function knownAttachmentIds(caseId: string): ReadonlySet<string> {
|
||||
const list = known.get(caseId);
|
||||
if (!list?.length) return EMPTY_IDS;
|
||||
return new Set(list.map((file) => file.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep files posted this session on top of a fetch.
|
||||
* A response that already includes them must not forget them: a slower fetch
|
||||
* from before the upload can still arrive and would drop the file.
|
||||
*/
|
||||
export function withKnownAttachments(
|
||||
caseId: string,
|
||||
files: LabCaseAttachmentMeta[],
|
||||
): LabCaseAttachmentMeta[] {
|
||||
const list = known.get(caseId);
|
||||
if (!list?.length) return files;
|
||||
const ids = new Set(files.map((file) => file.id));
|
||||
const missing = list.filter((file) => !ids.has(file.id));
|
||||
if (missing.length === 0) return files;
|
||||
return [...files, ...missing];
|
||||
}
|
||||
|
||||
export function withKnownCaseFiles(detail: LabCaseDetail): LabCaseDetail {
|
||||
const attachments = withKnownAttachments(detail.id, detail.attachments);
|
||||
if (attachments === detail.attachments) return detail;
|
||||
return { ...detail, attachments };
|
||||
}
|
||||
|
||||
export function caseHasActiveUpload(caseId: string): boolean {
|
||||
return prepared.has(caseId) || jobs.some((job) => job.caseId === caseId && !job.failed);
|
||||
}
|
||||
|
||||
function remember(caseId: string, attachment: LabCaseAttachmentMeta) {
|
||||
const list = known.get(caseId) ?? [];
|
||||
if (!list.some((file) => file.id === attachment.id)) {
|
||||
list.push(attachment);
|
||||
known.set(caseId, list);
|
||||
}
|
||||
}
|
||||
|
||||
function deliver(caseId: string, attachment: LabCaseAttachmentMeta) {
|
||||
remember(caseId, attachment);
|
||||
bridges.get(caseId)?.commit(attachment);
|
||||
storedHandler?.(caseId, attachment);
|
||||
}
|
||||
|
||||
function hasPending(caseId: string, exceptId?: string) {
|
||||
return jobs.some((job) => job.caseId === caseId && !job.failed && job.id !== exceptId);
|
||||
}
|
||||
|
||||
const idleWaiters = new Map<string, Set<() => void>>();
|
||||
|
||||
function notifyIdle(caseId: string) {
|
||||
if (caseHasActiveUpload(caseId)) return;
|
||||
const waiters = idleWaiters.get(caseId);
|
||||
if (!waiters?.size) return;
|
||||
idleWaiters.delete(caseId);
|
||||
for (const resolve of waiters) resolve();
|
||||
}
|
||||
|
||||
/** Resolves once this case has no upload still posting. */
|
||||
export function whenCaseUploadsIdle(caseId: string): Promise<void> {
|
||||
if (!caseHasActiveUpload(caseId)) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
const waiters = idleWaiters.get(caseId) ?? new Set();
|
||||
waiters.add(resolve);
|
||||
idleWaiters.set(caseId, waiters);
|
||||
});
|
||||
}
|
||||
|
||||
function settleIfIdle(caseId: string, exceptId?: string) {
|
||||
if (hasPending(caseId, exceptId)) return;
|
||||
prepared.delete(caseId);
|
||||
bridges.get(caseId)?.settle();
|
||||
notifyIdle(caseId);
|
||||
}
|
||||
|
||||
function failQueued(caseId: string) {
|
||||
for (const item of jobs) {
|
||||
if (item.caseId !== caseId || item.failed) continue;
|
||||
item.failed = true;
|
||||
item.percent = 0;
|
||||
files.delete(item.id);
|
||||
}
|
||||
}
|
||||
|
||||
async function runJob(job: CaseUploadJob) {
|
||||
if (job.failed) return;
|
||||
const bridge = bridges.get(job.caseId);
|
||||
if (bridge && !prepared.has(job.caseId)) {
|
||||
prepared.add(job.caseId);
|
||||
let ready = false;
|
||||
try {
|
||||
ready = await bridge.prepare();
|
||||
} catch {
|
||||
ready = false;
|
||||
}
|
||||
if (!ready) {
|
||||
prepared.delete(job.caseId);
|
||||
failQueued(job.caseId);
|
||||
publish(true);
|
||||
settleIfIdle(job.caseId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const file = files.get(job.id);
|
||||
if (!file) {
|
||||
job.failed = true;
|
||||
publish(true);
|
||||
settleIfIdle(job.caseId, job.id);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await casesApi.uploadAttachments(job.caseId, [file], (percent) => {
|
||||
job.percent = percent;
|
||||
publish(false);
|
||||
});
|
||||
const attachment = response.data[0];
|
||||
if (!attachment) throw new Error('empty upload');
|
||||
const index = jobs.findIndex((item) => item.id === job.id);
|
||||
if (index >= 0) jobs.splice(index, 1);
|
||||
files.delete(job.id);
|
||||
publish(true);
|
||||
deliver(job.caseId, attachment);
|
||||
settleIfIdle(job.caseId);
|
||||
} catch (error) {
|
||||
job.failed = true;
|
||||
job.percent = 0;
|
||||
files.delete(job.id);
|
||||
publish(true);
|
||||
failureHandler?.(error);
|
||||
settleIfIdle(job.caseId, job.id);
|
||||
}
|
||||
}
|
||||
|
||||
export function enqueueCaseFileUpload(caseId: string, file: File) {
|
||||
const job: CaseUploadJob = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
caseId,
|
||||
fileName: file.name,
|
||||
sizeBytes: file.size,
|
||||
percent: 0,
|
||||
failed: false,
|
||||
};
|
||||
jobs.unshift(job);
|
||||
files.set(job.id, file);
|
||||
publish(true);
|
||||
chain = chain.then(() => runJob(job)).catch(() => undefined);
|
||||
}
|
||||
|
||||
export function dismissCaseUploadJob(jobId: string) {
|
||||
const index = jobs.findIndex((job) => job.id === jobId);
|
||||
if (index < 0 || !jobs[index].failed) return;
|
||||
const caseId = jobs[index].caseId;
|
||||
jobs.splice(index, 1);
|
||||
files.delete(jobId);
|
||||
publish(true);
|
||||
settleIfIdle(caseId);
|
||||
}
|
||||
@@ -6,7 +6,8 @@ export type LabCaseActivityType =
|
||||
| 'CASE_AMENDED'
|
||||
| 'TASK_COMPLETED'
|
||||
| 'TASK_ASSIGNED'
|
||||
| 'CASE_COMPLETED';
|
||||
| 'CASE_COMPLETED'
|
||||
| 'ATTACHMENT_ADDED';
|
||||
|
||||
export interface LabCaseActivityItem {
|
||||
id: string;
|
||||
|
||||
@@ -401,6 +401,12 @@ docker compose -f docker-compose.prod.yml --env-file .env up -d
|
||||
|
||||
Backend runs `prisma migrate deploy` automatically on container start.
|
||||
|
||||
### Large attachment uploads
|
||||
|
||||
Case and treatment files have no size cap. Nginx `/api` (`nginx.ssl.conf.template`, rendered on deploy) sets `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. `location /` and `/admin` stay at 50MB. JSON bodies stay on the Express limit; only multipart uploads are unlimited.
|
||||
|
||||
A tag deploy that recreates nginx picks this up. Pulling only the backend image leaves the previous 50MB `/api` cap. Uploaded files are written to the backend container disk (`/app/uploads`, no volume). A very large upload can fill that disk, and recreating the backend container removes those files.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -257,6 +257,8 @@ curl.exe http://127.0.0.1/health
|
||||
|
||||
Replace any **default_server** / leftover `server { listen 80; }` in the host nginx that returns 404, or this file will never win.
|
||||
|
||||
Attachment uploads are unlimited only on `location /api` in this host file **and** in the Docker nginx behind it. Reloading Docker without pasting `windows-edge-http.conf` and running `nginx -s reload` leaves the Windows edge at 50MB, so a large scan still fails before it reaches the API.
|
||||
|
||||
From another machine (after **router forward TCP 80** → this PC):
|
||||
|
||||
```bash
|
||||
|
||||
@@ -39,7 +39,14 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
# Attachments have no size cap. Stream the body so a large scan is not
|
||||
# rejected or dropped when the client pauses.
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,14 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
# Attachments have no size cap. Stream the body so a large scan is not
|
||||
# rejected or dropped when the client pauses.
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,14 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
# Attachments have no size cap. Stream the body so a large scan is not
|
||||
# rejected or dropped when the client pauses.
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
|
||||
@@ -77,7 +77,14 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
# Attachments have no size cap. Stream the body so a large scan is not
|
||||
# rejected or dropped when the client pauses.
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ http {
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
# Unlimited at http{} so a gitea.wixur.ir vhost can inherit it (Docker layers
|
||||
# 413 with 50M). App server blocks below cap uploads at 50M.
|
||||
# 413 with 50M). The app HTML stays at 50M. /api is unlimited for attachments.
|
||||
client_max_body_size 0;
|
||||
|
||||
# Shared proxy to Docker staging
|
||||
@@ -43,6 +43,24 @@ http {
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
location /api {
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_pass http://127.0.0.1:18088;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:18088;
|
||||
proxy_http_version 1.1;
|
||||
@@ -68,6 +86,24 @@ http {
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
location /api {
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
proxy_request_buffering off;
|
||||
proxy_pass http://127.0.0.1:18088;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:18088;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
Reference in New Issue
Block a user