improvment: code reviewd. docs and skills updated.

This commit is contained in:
2026-10-06 18:25:29 +03:30
parent 39e352a9f9
commit 69e99c7713
12 changed files with 137 additions and 37 deletions

View File

@@ -12,10 +12,10 @@ alwaysApply: false
- **Assignment** in detail only (`TAB_CASES_EDIT`). Completing a step stays on Tasks. Reopening a completed current-round step is Cases only (`PATCH /cases/:id/tasks/:taskId/reopen`); it removes that step’s commission. Tasks and the share link show a completed step as a badge.
- **Edit** (`POST /cases/:id/stop`, label `cases.stopCase`, `TAB_CASES_EDIT`): started lab-origin cases only. Completed steps and the prosthesis plan become a history round; in-progress steps are removed. `startedAt` clears so the case returns to the drafts rail and can be edited, then started again. The next Start drops any leftover current-round tasks before generating the new plan. History still says “Stopped {date}”. Open outsources with no finished step are cancelled. Refused once an outsourced step is done (`LAB_CASE_OUTSOURCE_OPEN`).
- **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.
- **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 and outsource children use the case id. `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). 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.
- **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}”.
- **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).

View File

@@ -13,7 +13,7 @@ alwaysApply: false
- **Task assignment:** assign in Cases (`TAB_CASES_EDIT`), but never assign a step while it is outsourced. Status edit on Tasks only for an in-progress task that is unassigned or assigned to you; a completed step is a badge. Reopening that step is Cases edit only. Others see “Assigned to {name}”.
- **Grouped comments:** when `sortBy=date`, one comments icon on **case header** (not per row); flat sort keeps per-row comments. Generated cases hide the eye control. Lab-to-lab cases use it for the other lab.
- **Grouped header:** two columns, two rows, shared `gap-y-1.5`, start column aligned to the start and end column to the end. Row 1: bold org · patient title, then due/important/origin badges after it, opposite comments + attachments side by side. Expanded files use `py-3` so Save to storage clears the header border. Row 2: received date when present, opposite `CaseTaskProgressBar` at the Cases width (`clamp(5.5rem, 42%, 20rem)`, same `max-w-xs` cap as case detail). File list: `GET /cases/:id/attachments` (cases or tasks read).
- **Share link page** (`/lab-case/[token]`): reuses `TaskRow` + assignee rules, lists only current non-outsourced tasks, and soft-refreshes on notification events; comments via token API — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Share link page** (`/lab-case/[token]`): reuses `TaskRow` + the grouped header without the attachments button, plus assignee rules. Lists only current non-outsourced tasks, and soft-refreshes on notification events; comments via token API — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Case due dates:** clinic sets in Treatment lab dispatch; lab sees on Cases/Tasks; `overdue` filter + `sortBy=dueDate` on Tasks.
- **Mobile UX:** `LAB_TASK_STATUS_SELECT_CLASS` (44px tap target on small screens); `TaskCaseGroupHeader` sticky while scrolling grouped tasks; filter selects use same touch sizing on Tasks. Date grouping separates each case with space and a rounded header so it does not sit on the last step above.
- **Show in case:** `GET /tasks/locate-page` finds page in full list; highlight + scroll.

View File

@@ -49,7 +49,7 @@ Task status updates use **`PATCH /tasks/:id`** (not token routes) — same assig
**Treatment lab dispatch:** after send, the same thumb + dialog (same `shareUrl` / token) so the dentist can scan to the focus page. Dest/jobs share a row with the QR; tracker + comments span the card **below** it (not beside it).
**Share focus page:** grouped tasks (reuse `TaskRow`, `TaskCaseGroupHeader`); comments via `LabCaseCommentsPanel` + token API (`viewerSide` from `session.accessMode`). Newest-first; sent/received use logical start/end. Access denied → inline message (`asApiError` for `LAB_CASE_ACCESS_DENIED`).
**Share focus page:** grouped tasks (reuse `TaskRow`, `TaskCaseGroupHeader` without the attachments button); comments via `LabCaseCommentsPanel` + token API (`viewerSide` from `session.accessMode`). Newest-first; sent/received use logical start/end. Access denied → inline message (`asApiError` for `LAB_CASE_ACCESS_DENIED`).
## Auth redirect (logged out → login → back)

View File

@@ -16,7 +16,7 @@ description: Lab Cases tab — list, filters, detail panel, assignment, share QR
- **Task group headers / list cards:** one mill-ticket line via [`ProsthesisJobLineLabel`](frontend/src/components/ui/lab/ProsthesisJobLineLabel.tsx) — `13 · Pontic - 14 · PFZ Crown`. The Case Sheet draws that same line as an SVG box (do not mount the React label in the capture). No picker category. Colored Pontic + leaf (`prosthesisTypeLabelStyleFromCatalog` on screen; Case Sheet uses `prosthesisTypePrintColorFromCatalog`, the heaviest family swatch). Inherit the parent font size. Indirect keeps subcategory + leaf (Inlay · Layered ceramic). FDI chart paints pontic color on those teeth.
- **Page size:** `PAGE_SIZE = 10` in `CasesPage.tsx`.
- **Auto-select:** On tab open / after filter reload, select first list item if none selected; keep selection when still in list; `?caseId=` URL wins.
- **Add case:** `TAB_CASES_EDIT` — `POST /cases` then replace the **right pane** with `CaseCreatePanel` (inline wizard, not a modal). One prosthesis plan per case (`sourceKey` = case id; no `LabCaseLine`). `ProsthesisAssignChart` (same picker/stacking as Treatment). Summary rows: `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same mill-ticket line as Treatment/Cases/Tasks). Underline tabs: Details, Files, Messages. Header: one origin combobox (linked clinic or lab, or a typed name), Dentist/Technician, patient name/mobile, due date (`AppDateInput`). **Start** (`POST /cases/:id/start`) generates one shared scan/model/pack set and, when a linked org is selected, notifies that org once (`PARTNER_CASE_CREATED`, share-link href). No `LabCaseSend`, no clinic `CASE_SENT`. Start also rejects illegal stacks (`PROSTHESIS_STACK_INVALID`) and un-bridged or mixed pontics (`PONTIC_BRIDGE_INVALID`). **Edit** (`POST /cases/:id/stop`, button `cases.stopCase`) is only a started lab-origin case: completed tasks and a copy of the prosthesis lines go on `LabCaseRound` (`roundId` set; in-progress tasks are deleted), `startedAt` clears, commissions and the stamped price stay. History still says “Stopped {date}”. Edit cancels open outsources that have no finished step, and is refused once an outsourced step is done (`LAB_CASE_OUTSOURCE_OPEN`). The case returns to the drafts rail and can be edited; the next **Start** first archives any leftover current-round tasks, then generates only the new round (`generateLabCaseTasks` ignores tasks that already have `roundId`). **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`) on a started or received case creates one `LAB_OUTSOURCE` child for one linked lab and the checked in-progress prosthesis steps. The child stores the sending lab as `referringClinicName` and clears the dentist and partner clinic, so the receiver never sees the original clinic. The sender’s chart stays the full prosthesis plan; the child’s chart is the selected jobs plus pontics on that bridge. Those parent steps leave Tasks until the child lab completes them, which is mirrored onto the parent with no actor. The sender sees that direct lab’s step status and comments (eye on only); a further lab, and the original clinic, are omitted. Recall (`POST /cases/:id/outsource/:childCaseId/recall`) only before any of those steps is completed or sent onward. Received child cases have Outsource, not Start, Delete, or Edit. Active lists, progress, and Today counts use `roundId` null. Case detail and the draft editor show past rounds under **Previous work** (plan, then completed steps only). **Delete** (`DELETE /cases/:id`) only for unstarted lab-origin drafts (`LAB_INTERNAL` && `!startedAt`); confirm in the create-panel header next to Start. Received clinic cases and started generated cases cannot be deleted.
- **Add case:** `TAB_CASES_EDIT` — `POST /cases` then replace the **right pane** with `CaseCreatePanel` (inline wizard, not a modal). One prosthesis plan per case (`sourceKey` = case id; no `LabCaseLine`). `ProsthesisAssignChart` (same picker/stacking as Treatment). Summary rows: `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same mill-ticket line as Treatment/Cases/Tasks). Underline tabs: Details, Files, Messages. Header: one origin combobox (linked clinic or lab, or a typed name), Dentist/Technician, patient name/mobile, due date (`AppDateInput`). **Start** (`POST /cases/:id/start`) generates one shared scan/model/pack set and, when a linked org is selected, notifies that org once (`PARTNER_CASE_CREATED`, share-link href). No `LabCaseSend`, no clinic `CASE_SENT`. Start also rejects illegal stacks (`PROSTHESIS_STACK_INVALID`) and un-bridged or mixed pontics (`PONTIC_BRIDGE_INVALID`). **Edit** (`POST /cases/:id/stop`, button `cases.stopCase`) is only a started lab-origin case: completed tasks and a copy of the prosthesis lines go on `LabCaseRound` (`roundId` set; in-progress tasks are deleted), `startedAt` clears, commissions and the stamped price stay. History still says “Stopped {date}”. Edit cancels open outsources that have no finished step, and is refused once an outsourced step is done (`LAB_CASE_OUTSOURCE_OPEN`). The case returns to the drafts rail and can be edited; the next **Start** first archives any leftover current-round tasks, then generates only the new round (`generateLabCaseTasks` ignores tasks that already have `roundId`). **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`) on a started or received case creates one `LAB_OUTSOURCE` child for one linked lab and the checked in-progress prosthesis steps. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` / `collidingOutsourceSourceKeys` use `childId:parentSourceKey` so the current-round unique index `(labCaseId, sourceKey, tooth, prosthesisTypeCode, workflowStepCode)` accepts both. `dedupeToothJobs` keys on `sourceKey|tooth|type`. The child stores the sending lab as `referringClinicName` and clears the dentist and partner clinic, so the receiver never sees the original clinic. The sender’s chart stays the full prosthesis plan; the child’s chart is the selected jobs plus pontics on that bridge. Those parent steps leave Tasks until the child lab completes them, which is mirrored onto the parent with no actor. The sender sees that direct lab’s step status and comments (eye on only); a further lab, and the original clinic, are omitted. Recall (`POST /cases/:id/outsource/:childCaseId/recall`) only before any of those steps is completed or sent onward. Received child cases have Outsource, not Start, Delete, or Edit. Active lists, progress, and Today counts use `roundId` null. Case detail and the draft editor show past rounds under **Previous work** (plan, then completed steps only). **Delete** (`DELETE /cases/:id`) only for unstarted lab-origin drafts (`LAB_INTERNAL` && `!startedAt`); confirm in the create-panel header next to Start. Received clinic cases and started generated cases cannot be deleted.
- **Right panel:** Draft lab-origin → wizard; started/received → `CaseDetailPanel`.
- **Left rail layout:** section is `flex flex-col` + `lg:min-h-[420px]` / `h-full` with `lg:items-stretch` on the grid; case list wrapper is `flex-1 min-h-0 overflow-y-auto` (do **not** use a fixed `max-h-[55vh]` — that leaves empty space above pagination).
@@ -53,7 +53,7 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
## 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.
**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.
**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)
@@ -64,7 +64,7 @@ Stock `html2canvas` **cannot** parse `lab()` / `oklch()` from app CSS. Do **not*
|----|--------|
| Hex/rgb **inline styles** only in print layout | Tailwind color utilities / CSS variables in capture |
| [`CaseSheetFdiChart`](frontend/src/components/ui/lab/CaseSheetFdiChart.tsx) (SVG, catalog hex colors) | Reuse interactive `FdiToothChart` for PDF |
| `onclone`: strip `style` + `link[rel=stylesheet]`; set pixel size only on the lockup SVGs | Resize every SVG (blanks the QR and squashes prosthesis/number rows) |
| `onclone`: strip `style` + `link[rel=stylesheet]`; size the lockup SVGs and the org-name line box. Do not overwrite `[data-case-sheet-org-text]` direction | Resize every SVG (blanks the QR and squashes prosthesis/number rows) |
| Prosthesis type names from **`prosthesisJobPathParts`** (subcategory · leaf, never the picker category) | Fallback `code.replace(/_/g,' ')` alone (breaks casing like `ti base…`) |
### Layout conventions
@@ -72,7 +72,7 @@ Stock `html2canvas` **cannot** parse `lab()` / `oklch()` from app CSS. Do **not*
- 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.
- 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 must not use `letter-spacing` (html2canvas draws each letter alone, so the script stops joining). Prosthesis SVG text is anchored on the inline start for the locale (`fa` starts at the right padding with `direction: rtl`).
- 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).

View File

@@ -31,7 +31,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
**Grouped comments:** one comments button on the case header; panel expands below it (`expandedCommentsCaseId`). Per-task comments button only in **flat** sort (`showCommentsButton={flatMode}`). Shared `LabCaseCommentsPanel` with `viewerSide="LAB"` (newest-first, logical start/end chat align). Generated cases (`LAB_INTERNAL`) hide the eye control. Lab-to-lab cases use that same button so the comment can be shown to the other lab.
**Grouped attachments:** paperclip beside the comments button, on the end of row 1. Lists files with `GET /cases/:id/attachments` (cases or tasks read; download uses the same audience) and renders `CaseFilesPanel` view/download only.
**Grouped attachments:** paperclip beside the comments button, on the end of row 1. Lists files with `GET /cases/:id/attachments` (cases or tasks read; download uses the same audience) and renders `CaseFilesPanel` view/download only. The share focus page reuses this header without the attachments button.
## Prosthesis colors

View File

@@ -43,7 +43,7 @@ Full tab-badge map: `.cursor/skills/tab-badges/SKILL.md`.
## Emit sites (parallel to LabCaseActivity)
CASE_SENT, CLINIC_COMMENT, LAB_COMMENT (+ LAB_COMMENT_CLINIC), CASE_IMPORTANT, CASE_COMPLETED (all tasks in the case done — not each step), TASK_ASSIGNED (assignee only), CONNECTION_REQUEST, STAFF_INVITE — see service call sites.
CASE_SENT, CLINIC_COMMENT, LAB_COMMENT (+ LAB_COMMENT_CLINIC), CASE_IMPORTANT, CASE_COMPLETED (all tasks in the case done — not each step), PARTNER_CASE_CREATED (lab-origin Start, once, to the linked clinic `TAB_TREATMENT_EDIT` or lab `TAB_CASES_READ`, share-link href), TASK_ASSIGNED (assignee only), CONNECTION_REQUEST, STAFF_INVITE — see service call sites. When that generated case is fully done, the same partner also gets `CASE_COMPLETED` on the share link.
**Inbox card context** is denormalized inside `UserNotificationService.notify()` (`enrichInboxPayload`) from ids already on the payload (`labCaseId`, `taskId`, `fromOrganizationId`). Emit sites stay thin (`{ labCaseId }`, etc.). Inbox list/read does **not** join related tables. Older rows may lack these fields until new events are emitted.

View File

@@ -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. Lab-origin Start has no clinic send; 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. 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 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 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.

View File

@@ -50,6 +50,8 @@ import {
buildDirectOutsourceHandoffs,
outsourceBlocksStop,
outsourceRecallAllowed,
collidingOutsourceSourceKeys,
outsourceChildSourceKey,
outsourceTaskProblem,
toothRowsForOutsource,
type OutsourceTaskRow,
@@ -59,10 +61,12 @@ import {
listOutsourceDescendantIds,
} from './lab-case-outsource.tree';
function dedupeToothJobs<T extends { tooth: string; prosthesisTypeCode: string }>(rows: T[]): T[] {
function dedupeToothJobs<
T extends { tooth: string; prosthesisTypeCode: string; sourceKey?: string },
>(rows: T[]): T[] {
const byKey = new Map<string, T>();
for (const row of rows) {
byKey.set(`${row.tooth}|${row.prosthesisTypeCode}`, row);
byKey.set(`${row.sourceKey ?? ''}|${row.tooth}|${row.prosthesisTypeCode}`, row);
}
return [...byKey.values()];
}
@@ -846,12 +850,18 @@ export class CasesService {
})),
selectedRows,
);
const uniqueToothRows = dedupeToothJobs(toothRows);
const collidingSources = collidingOutsourceSourceKeys(selected);
const uniqueToothRows = dedupeToothJobs(
toothRows.map((row) => ({
...row,
sourceKey: outsourceChildSourceKey(child.id, row.sourceKey, collidingSources),
})),
);
if (uniqueToothRows.length > 0) {
await tx.labCaseToothProsthesis.createMany({
data: uniqueToothRows.map((row) => ({
labCaseId: child.id,
sourceKey: child.id,
sourceKey: row.sourceKey,
tooth: row.tooth,
prosthesisTypeCode: row.prosthesisTypeCode,
selectionGroupId: row.selectionGroupId,
@@ -864,7 +874,7 @@ export class CasesService {
await tx.labCaseTask.create({
data: {
labCaseId: child.id,
sourceKey: child.id,
sourceKey: outsourceChildSourceKey(child.id, task.sourceKey, collidingSources),
tooth: task.tooth,
teeth: task.teeth as Prisma.InputJsonValue,
treatmentType: task.treatmentType,

View File

@@ -3,6 +3,8 @@ import {
buildDirectOutsourceHandoffs,
outsourceBlocksStop,
outsourceRecallAllowed,
collidingOutsourceSourceKeys,
outsourceChildSourceKey,
outsourceTaskProblem,
toothRowsForOutsource,
type OutsourceTaskRow,
@@ -28,6 +30,24 @@ describe('lab case outsourcing rules', () => {
});
});
it('keeps one child source key unless two parent steps would collide', () => {
const tasks = [
{ sourceKey: 'detail-a', tooth: '14', prosthesisTypeCode: 'pfz_crown', workflowStepCode: 'design' },
{ sourceKey: 'detail-b', tooth: '21', prosthesisTypeCode: 'pfz_crown', workflowStepCode: 'design' },
];
expect(collidingOutsourceSourceKeys(tasks).size).toBe(0);
expect(outsourceChildSourceKey('child', 'detail-a', new Set())).toBe('child');
const sameTooth = [
tasks[0],
{ ...tasks[0], sourceKey: 'detail-b' },
];
const colliding = collidingOutsourceSourceKeys(sameTooth);
expect([...colliding].sort()).toEqual(['detail-a', 'detail-b']);
expect(outsourceChildSourceKey('child', 'detail-a', colliding)).toBe('child:detail-a');
expect(outsourceChildSourceKey('child', 'detail-b', colliding)).toBe('child:detail-b');
});
it('refuses case-level, finished, and already sent steps', () => {
expect(outsourceTaskProblem([step], ['task-1'])).toBeNull();
expect(

View File

@@ -80,6 +80,43 @@ export type ToothRow = {
selectionGroupId: string;
};
/**
* Child rows use the child case id as sourceKey. Two parent steps that share
* tooth, type, and workflow still need different keys, or the child unique
* index rejects the second insert.
*/
export function outsourceChildSourceKey(
childCaseId: string,
parentSourceKey: string,
collidingParentSourceKeys: ReadonlySet<string>,
): string {
if (collidingParentSourceKeys.has(parentSourceKey)) {
return `${childCaseId}:${parentSourceKey}`;
}
return childCaseId;
}
export function collidingOutsourceSourceKeys(
tasks: readonly {
sourceKey: string;
tooth: string;
prosthesisTypeCode: string;
workflowStepCode: string;
}[],
): Set<string> {
const counts = new Map<string, number>();
for (const task of tasks) {
const key = `${task.tooth}\0${task.prosthesisTypeCode}\0${task.workflowStepCode}`;
counts.set(key, (counts.get(key) ?? 0) + 1);
}
const sources = new Set<string>();
for (const task of tasks) {
const key = `${task.tooth}\0${task.prosthesisTypeCode}\0${task.workflowStepCode}`;
if ((counts.get(key) ?? 0) > 1) sources.add(task.sourceKey);
}
return sources;
}
/** Tooth rows the child chart needs: selected job teeth, plus pontics on that bridge. */
export function toothRowsForOutsource<T extends ToothRow>(
rows: readonly T[],

View File

@@ -116,18 +116,25 @@ export async function downloadCaseSheetPdf({
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.justifyContent = 'flex-start';
node.style.height = '48px';
node.style.lineHeight = '48px';
node.style.overflow = 'hidden';
const text = node.firstElementChild;
node.style.direction = 'ltr';
node.style.letterSpacing = '0px';
node.style.wordSpacing = '0px';
const text = node.querySelector('[data-case-sheet-org-text]');
if (!(text instanceof HTMLElement)) return;
text.style.display = 'block';
text.style.minWidth = '0';
text.style.display = 'inline-block';
text.style.maxWidth = '100%';
text.style.overflow = 'visible';
text.style.lineHeight = '48px';
text.style.paddingTop = '0';
text.style.paddingBottom = '0';
text.style.letterSpacing = '0px';
text.style.wordSpacing = '0px';
text.style.whiteSpace = 'nowrap';
text.style.unicodeBidi = 'isolate';
});
clonedDoc.querySelectorAll('[data-case-sheet-lockup]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;

View File

@@ -82,7 +82,9 @@ function printLabelStyle(rtl: boolean) {
...(rtl
? {
direction: 'rtl' as const,
letterSpacing: 'normal' as const,
textAlign: 'right' as const,
letterSpacing: '0px' as const,
wordSpacing: '0px' as const,
textTransform: 'none' as const,
}
: { letterSpacing: '0.04em' as const, textTransform: 'uppercase' as const }),
@@ -98,7 +100,9 @@ function printHeadingStyle(rtl: boolean) {
...(rtl
? {
direction: 'rtl' as const,
letterSpacing: 'normal' as const,
textAlign: 'right' as const,
letterSpacing: '0px' as const,
wordSpacing: '0px' as const,
textTransform: 'none' as const,
}
: {}),
@@ -109,6 +113,24 @@ const body = { color: '#0f172a', fontSize: 13, lineHeight: '16px' };
/** Extra drop so Farsi descenders clear the rule. Latin layouts stay put. */
const FA_RULE_DROP = 6;
const ARABIC_SCRIPT = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]/;
/**
* html2canvas spreads RTL text across a full-width box and opens gaps
* between Latin words. Persian copy stays RTL; Latin values stay LTR and
* only the alignment follows the Persian column.
*/
function printRtlValueStyle(value: string) {
const arabic = ARABIC_SCRIPT.test(value);
return {
direction: arabic ? ('rtl' as const) : ('ltr' as const),
unicodeBidi: 'isolate' as const,
textAlign: 'right' as const,
letterSpacing: '0px' as const,
wordSpacing: '0px' as const,
};
}
function printRule(rtl: boolean) {
return {
borderTop: '1px solid #cbd5e1',
@@ -165,7 +187,7 @@ export function CaseSheetPrintLayout({
fontSize: '13px',
lineHeight: '16px',
direction: 'ltr',
...(rtl ? { letterSpacing: 'normal' as const } : {}),
...(rtl ? { letterSpacing: '0px' as const, wordSpacing: '0px' as const } : {}),
}}
>
<header
@@ -186,6 +208,7 @@ export function CaseSheetPrintLayout({
alignSelf: 'center',
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,
@@ -193,24 +216,27 @@ export function CaseSheetPrintLayout({
fontSize: 22,
fontWeight: 600,
lineHeight: '48px',
whiteSpace: 'nowrap',
...(rtl
? {
direction: 'rtl' as const,
letterSpacing: 'normal' as const,
textAlign: 'left' as const,
textTransform: 'none' as const,
}
: {}),
direction: 'ltr',
letterSpacing: '0px',
wordSpacing: '0px',
}}
>
<span
data-case-sheet-org-text
style={{
display: 'block',
minWidth: 0,
display: 'inline-block',
maxWidth: '100%',
overflow: 'visible',
lineHeight: '48px',
whiteSpace: 'nowrap',
verticalAlign: 'middle',
letterSpacing: '0px',
wordSpacing: '0px',
unicodeBidi: 'isolate',
// Keep Latin names LTR so the words stay together. A Persian
// name still reads RTL, but only inside its own width.
direction: ARABIC_SCRIPT.test(organizationName) ? 'rtl' : 'ltr',
textAlign: ARABIC_SCRIPT.test(organizationName) ? 'right' : 'left',
}}
>
{organizationName || labels.title}
@@ -521,7 +547,7 @@ function MetaBlock({ label, value, rtl }: { label: string; value: string; rtl: b
...body,
margin: '2px 0 0',
fontWeight: 500,
...(rtl ? { direction: 'rtl' as const, letterSpacing: 'normal' as const } : {}),
...(rtl ? printRtlValueStyle(value) : {}),
}}
>
{value}
@@ -549,7 +575,7 @@ function PartyBlock({
margin: '4px 0 0',
fontSize: 15,
fontWeight: 600,
...(rtl ? { direction: 'rtl' as const, letterSpacing: 'normal' as const } : {}),
...(rtl ? printRtlValueStyle(title) : {}),
}}
>
{title}
@@ -560,7 +586,7 @@ function PartyBlock({
margin: '2px 0 0',
fontSize: 12,
color: '#475569',
...(rtl ? { direction: 'rtl' as const, letterSpacing: 'normal' as const } : {}),
...(rtl ? printRtlValueStyle(subtitle) : {}),
}}
>
{subtitle}