feature: branch reviewed

This commit is contained in:
2026-11-30 12:44:11 +03:30
parent 1017cc14ac
commit 565b014235
15 changed files with 436 additions and 113 deletions

View File

@@ -14,7 +14,7 @@ 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 plus `model_design` / `model_create`, 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, or that line’s teeth for a model step (the whole plan for a historical `__case__` model step). Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Scan, packing, and shipping 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`.
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts`. Folder session: `ExocadExportFolderProvider`. Prosthesis pairs stay the same (`Coping`/`ZI` for monolithic/PFZ, pontic `ReducedPontic`, etc.); IPS Overlay uses `AnatomicInlay`/`LS2` (no OverlayCrown in the official table). Case shade → `ToothShade` `VCL:<code>`. Bridge `MesialConnector` from `selectionGroupId`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/SKILL.md`.
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts`. Folder session: `ExocadExportFolderProvider` (changeable Auto-Import folder). Active indirect leaves and implant stacks are mapped; empty plans refuse export; Coping pontics use `ReducedPontic`, full-contour use `AnatomicPontic`; shade is `VCL` or bleach `V3DM`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/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. 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:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. The destination lab with `TAB_BILLING_EDIT` edits that fee (`PUT /billing/cases/:id/amount`) and the open case updates immediately; anyone else sees the stored fee, or the calculated quote when no fee is stored. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **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}”.

View File

@@ -15,4 +15,4 @@ alwaysApply: false
- Received `CLINIC_DISPATCH` and `LAB_OUTSOURCE` cases are read-only for the lab. Outsource copies the parent shade, and later parent edits update the children.
- **Full guide** (`ToothShadeGuide`, LTR tab order in every locale): Treatment editor under the type row for lab-dependent details, Cases create panel, and the case detail header (hidden there when read-only and empty). **Text only** elsewhere: Tasks grouped header (also the share page), Case Sheet PDF (`—` when empty).
- **Voice:** `toothShadeCode` field — never in `comment`. Lands only on a lab-dependent detail (or a lab case line).
- Exocad `.dentalProject` export maps the case shade to per-tooth `ToothShade` as `VCL:<code>` (no incisal/gingival zones).
- Exocad `.dentalProject` export maps the case shade to per-tooth `ToothShade`: classical codes as `VCL:<code>`, bleach `0M1`–`0M3` as `V3DM:<code>` (no incisal/gingival zones).

View File

@@ -64,7 +64,8 @@ Writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import fo
- `ExocadExportFolderProvider` remembers the Auto-Import directory handle (IndexedDB). The next export reopens that folder when permission remains and skips Browse. A missing or denied folder shows the folder picker again.
- The connect dialog asks for the DentalDB Project Auto-Import folder and notes that this release exports case data only (scan companion files are still placed by the user when needed).
- Builder: `frontend/src/components/lab/exocad/exocadDentalProject.ts`. Root is `<Treatment UseRecipientMaterialConfiguration="True">`. `ProjectGUID` is the Dyolink case id. `PracticeName` is the clinic name (no `PracticeId`). Patient family/given names are mandatory (`PatientName` / `PatientFirstName`); a one-word name is refused. `Notes` are the case comment bodies, or the detail comment when the thread is empty. File name is `{date}-{shortCaseId}.dentalProject`.
- Tooth mapping (same pairs as before, expressed as XML `ReconstructionType` / `Material`): Monolithic Zirconia and PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Veneer Zirconia = `Veneer`/`ZI`; IPS veneers = `Veneer`/`LS2`; Zirconia Overlay and IPS Overlay = `AnatomicInlay` (`ZI` / `LS2` — OverlayCrown is outside the official 3rd-party table). Pontic = `ReducedPontic` with the connected crown material. `customized_abutment` on a Coping sets `ImplantType` `CustomAbutment` and `MaterialAbutment` `TI`; a plain Coping sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Antagonists and scan files are not exported in this phase. Case `toothShadeCode` becomes per-tooth `ToothShade` as `VCL:<code>`.
- Tooth mapping (XML `ReconstructionType` / `Material`): Monolithic Zirconia and PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Temporary Resin = `ProvisionalCrown`/`TEMP`. Active indirect: `veneer_*` → `Veneer`/`LS2`; `*_full_contour` inlay/onlay/overlay → `AnatomicInlay`/`LS2`; `*_layered` inlay/onlay/overlay → `OffsetInlay`/`LS2`. Legacy veneer/overlay leaves keep their old pairs; overlays never use OverlayCrown. Pontic follows the abutment family: `Coping` → `ReducedPontic`, full-contour → `AnatomicPontic`, with the abutment material. `customized_abutment` → `CustomAbutment`/`TI`; `zirconia_abutment` → `CustomAbutment`/`ZI`; `screw_retained` → `WithoutAbutment`. Unmapped stacks (`ti_base_abutment`, prefab/multi-unit, post & core) are skipped and never force `ImplantType None`. A plain Coping with no implant stack sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Empty exports are refused (`NOTHING_TO_EXPORT`). Antagonists and scan files are not exported in this phase. Case shade → `ToothShade` as `VCL:<code>` or bleach `V3DM:0M*`.
- Auto-Import folder can be changed from the case header; success toast names the folder when known.
- `externalCode` stays manual-only — export does not auto-fill it.
- There is no Local database tab.

View File

@@ -74,7 +74,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. A type with both dry milling and sintering generates `milling_dry_sinter`; both wet milling and sintering generate `milling_wet_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Model design and model create can be outsourced with that line’s teeth, or the whole plan for a historical `__case__` model step; scan, packing, and shipping cannot. 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 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, plus model design and model create, 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. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Prosthesis pairs stay the same (`Coping`/`ZI` for monolithic/PFZ, pontic `ReducedPontic`, custom abutment on Coping, etc.); IPS Overlay uses `AnatomicInlay`/`LS2`. Case shade maps to `ToothShade` as `VCL:<code>`. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. 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, plus model design and model create, 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. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Prosthesis pairs stay the same (`Coping`/`ZI` for monolithic/PFZ, custom abutment on Coping, etc.); IPS Overlay uses `AnatomicInlay`/`LS2`; active indirect leaves and implant stacks are mapped; Coping bridges use `ReducedPontic`, full-contour use `AnatomicPontic`. Case shade maps to `VCL:<code>` or bleach `V3DM:0M*`. Empty plans refuse export. The Auto-Import folder can be changed. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Tooth shade (quick ref):** One optional VITA shade per lab case (`LabCase.toothShadeCode`, nullable; historical shades stay in notes). Full guide in Treatment (lab-dependent) and Cases create/detail; text only on Tasks, share page, and Case Sheet. Locks once any step in the outsource tree is completed; an unchanged resend is a no-op. See `.cursor/rules/tooth-shade.mdc`.

3
frontend/.gitignore vendored
View File

@@ -45,6 +45,3 @@ next-env.d.ts
# Prisma
prisma/*.db
prisma/*.db-journal
# Copied from sql.js before dev/build (see scripts/copy-sql-wasm.mjs)
/public/sql-wasm-browser.wasm

View File

@@ -559,15 +559,21 @@
"sendCase": "Outsource",
"sendToExocad": "Send to Exocad",
"sendToExocadSaved": "Exported {fileName}. DentalDB will import it from the Auto-Import folder.",
"sendToExocadSavedWithFolder": "Exported {fileName} to {folder}. DentalDB will import it from that Auto-Import folder.",
"sendToExocadSkipped": "Not exported: {lines}.",
"sendToExocadConnectTitle": "Choose Exocad Auto-Import folder",
"sendToExocadChangeFolderTitle": "Change Exocad Auto-Import folder",
"sendToExocadFolderHint": "Select the Project Auto-Import folder configured in DentalDB. The next export reuses that folder when it is still available.",
"sendToExocadCurrentFolder": "Current folder: {name}",
"sendToExocadScanNote": "This export writes case data only. Place any scan files into the same folder yourself if DentalDB needs them.",
"sendToExocadBrowseFolder": "Choose folder",
"sendToExocadChangeFolder": "Change Auto-Import folder",
"sendToExocadChangeFolderNamed": "Change folder ({name})",
"sendToExocadFolderOpenFailed": "Could not open that folder.",
"exportFailed": "Could not build the Exocad project file.",
"folderWriteFailed": "Could not write the Exocad project file. Choose the Auto-Import folder again.",
"patientNameIncomplete": "Not exported. The patient name needs a first and last name so Exocad can fill Patient. Edit the patient and try again.",
"nothingToExport": "Not exported. None of the prosthesis jobs on this case map to Exocad teeth. Adjust the plan and try again.",
"sendCaseTitle": "Outsource steps",
"outsourcePrice": "Outsource price",
"outsourcePricePending": "This outsource includes work without a fee. You can send it, but the destination lab must set the final amount in Billing.",

View File

@@ -559,15 +559,21 @@
"sendCase": "برون سپاری",
"sendToExocad": "ارسال به Exocad",
"sendToExocadSaved": "پرونده {fileName} صادر شد. DentalDB آن را از پوشه Auto-Import وارد می‌کند.",
"sendToExocadSavedWithFolder": "پرونده {fileName} در {folder} صادر شد. DentalDB آن را از همان پوشه Auto-Import وارد می‌کند.",
"sendToExocadSkipped": "صادر نشد: {lines}.",
"sendToExocadConnectTitle": "انتخاب پوشه Auto-Import اکزوکد",
"sendToExocadChangeFolderTitle": "تغییر پوشه Auto-Import اکزوکد",
"sendToExocadFolderHint": "پوشه Project Auto-Import تنظیم‌شده در DentalDB را انتخاب کنید. ارسال بعدی در صورت در دسترس بودن همان پوشه را دوباره استفاده می‌کند.",
"sendToExocadCurrentFolder": "پوشه فعلی: {name}",
"sendToExocadScanNote": "این خروجی فقط داده‌های پرونده را می‌نویسد. در صورت نیاز، فایل‌های اسکن را خودتان در همان پوشه قرار دهید.",
"sendToExocadBrowseFolder": "انتخاب پوشه",
"sendToExocadChangeFolder": "تغییر پوشه Auto-Import",
"sendToExocadChangeFolderNamed": "تغییر پوشه ({name})",
"sendToExocadFolderOpenFailed": "باز کردن آن پوشه ممکن نشد.",
"exportFailed": "ساخت پرونده پروژه اکزوکد ممکن نشد.",
"folderWriteFailed": "نوشتن پرونده پروژه اکزوکد ممکن نشد. پوشه Auto-Import را دوباره انتخاب کنید.",
"patientNameIncomplete": "صادر نشد. نام بیمار باید نام و نام خانوادگی داشته باشد تا Patient در اکزوکد پر شود. بیمار را اصلاح کنید و دوباره تلاش کنید.",
"nothingToExport": "صادر نشد. هیچ‌کدام از کارهای پروتزی این پرونده به دندان‌های اکزوکد نگاشت نمی‌شوند. طرح را اصلاح کنید و دوباره تلاش کنید.",
"sendCaseTitle": "مراحل برون سپاری",
"outsourcePrice": "قیمت برون‌سپاری",
"outsourcePricePending": "این برون‌سپاری شامل کار بدون تعرفه است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.",

View File

@@ -559,15 +559,21 @@
"sendCase": "Uitbesteden",
"sendToExocad": "Naar Exocad sturen",
"sendToExocadSaved": "{fileName} geëxporteerd. DentalDB importeert dit vanuit de Auto-Import-map.",
"sendToExocadSavedWithFolder": "{fileName} geëxporteerd naar {folder}. DentalDB importeert dit vanuit die Auto-Import-map.",
"sendToExocadSkipped": "Niet geëxporteerd: {lines}.",
"sendToExocadConnectTitle": "Exocad Auto-Import-map kiezen",
"sendToExocadChangeFolderTitle": "Exocad Auto-Import-map wijzigen",
"sendToExocadFolderHint": "Selecteer de Project Auto-Import-map die in DentalDB is geconfigureerd. De volgende export hergebruikt die map wanneer die nog beschikbaar is.",
"sendToExocadCurrentFolder": "Huidige map: {name}",
"sendToExocadScanNote": "Deze export schrijft alleen casusgegevens. Plaats eventuele scanbestanden zelf in dezelfde map als DentalDB die nodig heeft.",
"sendToExocadBrowseFolder": "Map kiezen",
"sendToExocadChangeFolder": "Auto-Import-map wijzigen",
"sendToExocadChangeFolderNamed": "Map wijzigen ({name})",
"sendToExocadFolderOpenFailed": "Die map kon niet worden geopend.",
"exportFailed": "Het Exocad-projectbestand kon niet worden opgebouwd.",
"folderWriteFailed": "Het Exocad-projectbestand kon niet worden geschreven. Kies de Auto-Import-map opnieuw.",
"patientNameIncomplete": "Niet geëxporteerd. De patiëntnaam heeft een voor- en achternaam nodig zodat Exocad Patient kan invullen. Pas de patiënt aan en probeer het opnieuw.",
"nothingToExport": "Niet geëxporteerd. Geen van de prothesewerkzaamheden op deze casus kan naar Exocad-tanden worden gemapt. Pas het plan aan en probeer het opnieuw.",
"sendCaseTitle": "Stappen uitbesteden",
"outsourcePrice": "Uitbestedingsprijs",
"outsourcePricePending": "Deze uitbesteding bevat werk zonder tarief. Verzenden is toegestaan, maar het bestemmingslab moet het definitieve bedrag in Facturatie instellen.",

View File

@@ -58,7 +58,11 @@ describe('mesialNeighbor', () => {
describe('exocadToothShade', () => {
it('formats VITA classical codes as VCL', () => {
expect(exocadToothShade('A2')).toBe('VCL:A2');
expect(exocadToothShade('0M1')).toBe('VCL:0M1');
});
it('formats bleach 0M shades as V3DM', () => {
expect(exocadToothShade('0M1')).toBe('V3DM:0M1');
expect(exocadToothShade('0m2')).toBe('V3DM:0M2');
});
it('omits empty shades', () => {
@@ -102,6 +106,17 @@ describe('buildExocadDentalProject', () => {
expect(project.xml).not.toContain('Antagonist');
});
it('uses the export date for the file name, not the due date', () => {
const project = buildExocadDentalProject(
baseInput({
dueDate: '2026-01-01',
teeth: [{ tooth: '11', prosthesisTypeCode: 'full_metal_crown' }],
}),
{ exportDate: '2026-11-30' },
);
expect(project.fileName).toBe(exocadExportFileName(CASE_ID, '2026-11-30'));
});
it('escapes XML special characters in notes and names', () => {
const project = buildExocadDentalProject(
baseInput({
@@ -118,7 +133,7 @@ describe('buildExocadDentalProject', () => {
expect(project.xml).toContain('<Notes>Use &lt;temp&gt; &amp; &quot;shade&quot;</Notes>');
});
it('marks mesial connectors on a connected bridge and maps the pontic', () => {
it('marks mesial connectors on a cutback bridge and maps the pontic as ReducedPontic', () => {
const group = 'bridge-1';
const project = buildExocadDentalProject(
baseInput({
@@ -144,6 +159,21 @@ describe('buildExocadDentalProject', () => {
);
});
it('uses AnatomicPontic for a full-contour abutment bridge', () => {
const group = 'bridge-2';
const project = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '36', prosthesisTypeCode: 'press_ceramic', selectionGroupId: group },
{ tooth: '37', prosthesisTypeCode: 'pontic', selectionGroupId: group },
],
}),
);
expect(project.xml).toContain('<ReconstructionType>AnatomicCrown</ReconstructionType>');
expect(project.xml).toContain('<ReconstructionType>AnatomicPontic</ReconstructionType>');
expect(project.xml).not.toContain('ReducedPontic');
});
it('copies CustomAbutment and titanium abutment material on a coping', () => {
const project = buildExocadDentalProject(
baseInput({
@@ -157,26 +187,100 @@ describe('buildExocadDentalProject', () => {
expect(project.xml).toContain('<MaterialAbutment>TI</MaterialAbutment>');
});
it('skips arch jobs and unmapped prosthesis codes', () => {
const project = buildExocadDentalProject(
it('maps zirconia abutments and screw-retained implants', () => {
const zirconia = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture' },
{ tooth: '21', prosthesisTypeCode: 'temporary_crown' },
{ tooth: '22', prosthesisTypeCode: 'pontic' },
{ tooth: '16', prosthesisTypeCode: 'pfz_crown' },
{ tooth: '16', prosthesisTypeCode: 'zirconia_abutment' },
],
}),
);
expect(project.xml).toContain('<Teeth>');
expect(project.xml).toContain('</Teeth>');
expect(project.xml).not.toContain('<Number>');
expect(zirconia.xml).toContain('<ImplantType>CustomAbutment</ImplantType>');
expect(zirconia.xml).toContain('<MaterialAbutment>ZI</MaterialAbutment>');
const screw = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '26', prosthesisTypeCode: 'monolithic_zirconia' },
{ tooth: '26', prosthesisTypeCode: 'screw_retained' },
],
}),
);
expect(screw.xml).toContain('<ImplantType>WithoutAbutment</ImplantType>');
expect(screw.xml).not.toContain('MaterialAbutment');
});
it('omits ImplantType None when an unmapped implant stack is present and lists it as skipped', () => {
const project = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '16', prosthesisTypeCode: 'pfz_crown' },
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment' },
],
}),
);
expect(project.xml).not.toContain('<ImplantType>');
expect(project.skipped).toEqual([
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture', reason: 'arch' },
{ tooth: '21', prosthesisTypeCode: 'temporary_crown', reason: 'unmapped' },
{ tooth: '22', prosthesisTypeCode: 'pontic', reason: 'pontic' },
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment', reason: 'unmapped' },
]);
});
it('maps ImplantType on AnatomicCrown when a custom abutment is stacked', () => {
const project = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '46', prosthesisTypeCode: 'full_metal_crown' },
{ tooth: '46', prosthesisTypeCode: 'customized_abutment' },
],
}),
);
expect(project.xml).toContain('<ReconstructionType>AnatomicCrown</ReconstructionType>');
expect(project.xml).toContain('<ImplantType>CustomAbutment</ImplantType>');
});
it('maps active indirect catalog leaves', () => {
const project = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '11', prosthesisTypeCode: 'veneer_full_contour' },
{ tooth: '14', prosthesisTypeCode: 'inlay_layered' },
{ tooth: '24', prosthesisTypeCode: 'overlay_full_contour' },
],
}),
);
expect(project.xml).toContain('<ReconstructionType>Veneer</ReconstructionType>');
expect(project.xml).toContain('<ReconstructionType>OffsetInlay</ReconstructionType>');
expect(project.xml).toContain('<ReconstructionType>AnatomicInlay</ReconstructionType>');
});
it('refuses to export when no teeth can be written', () => {
expect(() =>
buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture' },
{ tooth: '22', prosthesisTypeCode: 'pontic' },
],
}),
),
).toThrowError(ExocadExportError);
try {
buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture' },
{ tooth: '22', prosthesisTypeCode: 'pontic' },
],
}),
);
} catch (error) {
expect(error).toBeInstanceOf(ExocadExportError);
expect((error as ExocadExportError).code).toBe('NOTHING_TO_EXPORT');
}
});
it('rejects incomplete patient names without writing XML', () => {
expect(() =>
buildExocadDentalProject(
@@ -198,4 +302,22 @@ describe('buildExocadDentalProject', () => {
expect(project.xml).toContain('<ReconstructionType>AnatomicInlay</ReconstructionType>');
expect(project.xml).toContain('<Material>LS2</Material>');
});
it('marks mesial connectors across the midline on a connected pair', () => {
const group = 'midline';
const project = buildExocadDentalProject(
baseInput({
teeth: [
{ tooth: '11', prosthesisTypeCode: 'pfz_crown', selectionGroupId: group },
{ tooth: '21', prosthesisTypeCode: 'pfz_crown', selectionGroupId: group },
],
}),
);
expect(project.xml).toMatch(
/<Number>11<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>\s*<MesialConnector>true<\/MesialConnector>/,
);
expect(project.xml).toMatch(
/<Number>21<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>\s*<MesialConnector>true<\/MesialConnector>/,
);
});
});

View File

@@ -1,10 +1,10 @@
/**
* Build an official Exocad `.dentalProject` XML file (3rd-party auto-import).
* Prosthesis → ReconstructionType / Material pairs match the prior DentalDB mapping
* where those values appear in the official specification.
* Prosthesis → ReconstructionType / Material pairs follow the prior DentalDB mapping
* where those values appear in the official specification tables.
*/
export type ExocadExportFailure = 'PATIENT_NAME_INCOMPLETE';
export type ExocadExportFailure = 'PATIENT_NAME_INCOMPLETE' | 'NOTHING_TO_EXPORT';
export class ExocadExportError extends Error {
constructor(readonly code: ExocadExportFailure) {
@@ -13,12 +13,17 @@ export class ExocadExportError extends Error {
}
}
type MaterialMatch = {
reconstructionType: string;
material: string;
};
/**
* Catalog codes with one obvious Exocad work type and material.
* OverlayCrown is not in the official 3rd-party ReconstructionType table, so IPS Overlay
* uses AnatomicInlay (same family as zirconia overlay).
* OverlayCrown is not in the official 3rd-party ReconstructionType table, so overlays
* use AnatomicInlay. Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
*/
const MATERIAL_MATCH: Record<string, { reconstructionType: string; material: string }> = {
const MATERIAL_MATCH: Record<string, MaterialMatch> = {
monolithic_zirconia: { reconstructionType: 'Coping', material: 'ZI' },
pfz_crown: { reconstructionType: 'Coping', material: 'ZI' },
pfm_crown: { reconstructionType: 'Coping', material: 'NP' },
@@ -27,6 +32,17 @@ const MATERIAL_MATCH: Record<string, { reconstructionType: string; material: str
pmma: { reconstructionType: 'AnatomicCrown', material: 'PMMA' },
press_ceramic: { reconstructionType: 'AnatomicCrown', material: 'LS2' },
peek_crown: { reconstructionType: 'AnatomicCrown', material: 'PEEK' },
temporary_resin_crown: { reconstructionType: 'ProvisionalCrown', material: 'TEMP' },
// Active indirect catalog leaves
veneer_full_contour: { reconstructionType: 'Veneer', material: 'LS2' },
veneer_layered: { reconstructionType: 'Veneer', material: 'LS2' },
inlay_full_contour: { reconstructionType: 'AnatomicInlay', material: 'LS2' },
inlay_layered: { reconstructionType: 'OffsetInlay', material: 'LS2' },
onlay_full_contour: { reconstructionType: 'AnatomicInlay', material: 'LS2' },
onlay_layered: { reconstructionType: 'OffsetInlay', material: 'LS2' },
overlay_full_contour: { reconstructionType: 'AnatomicInlay', material: 'LS2' },
overlay_layered: { reconstructionType: 'OffsetInlay', material: 'LS2' },
// Legacy inactive leaves (still present on historical cases)
veneer_zirconia: { reconstructionType: 'Veneer', material: 'ZI' },
veneer_ips_press: { reconstructionType: 'Veneer', material: 'LS2' },
veneer_ips_cad: { reconstructionType: 'Veneer', material: 'LS2' },
@@ -34,8 +50,30 @@ const MATERIAL_MATCH: Record<string, { reconstructionType: string; material: str
ips_overlay: { reconstructionType: 'AnatomicInlay', material: 'LS2' },
};
/** Catalog code whose sheet label is "Custom Abutment (Titanium)". */
const CUSTOM_ABUTMENT_CODE = 'customized_abutment';
type ImplantMatch = {
implantType: 'CustomAbutment' | 'WithoutAbutment';
materialAbutment?: string;
};
/** Implant stacks we can express with official ImplantType / MaterialAbutment values. */
const IMPLANT_MATCH: Record<string, ImplantMatch> = {
customized_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
zirconia_abutment: { implantType: 'CustomAbutment', materialAbutment: 'ZI' },
screw_retained: { implantType: 'WithoutAbutment' },
};
/**
* Implant / post stacks that are not representable in the official ImplantType table.
* When present with a restoration, they are listed as skipped and ImplantType is omitted
* (never written as None — that would claim a natural prep).
*/
const UNMAPPED_STACK_CODES = new Set([
'ti_base_abutment',
'prefabricated_abutment',
'multi_unit_abutment',
'cast_post_core',
'fiber_post_core',
]);
/** Reconstruction types that may carry ImplantType in the official table. */
const IMPLANT_ALLOWED = new Set([
@@ -45,9 +83,13 @@ const IMPLANT_ALLOWED = new Set([
'Coping',
'OverpressCrown',
'PrimaryTelescope',
'ProvisionalCrown',
'ReducedWaxup',
]);
/** VITA 3D-Master bleach shades in Dyolink's tooth-shade catalog. */
const V3DM_SHADE_CODES = new Set(['0M1', '0M2', '0M3']);
export type ExocadToothJob = {
tooth: string;
prosthesisTypeCode: string;
@@ -71,12 +113,14 @@ export type ExocadSkippedLine = {
reason: 'arch' | 'unmapped' | 'pontic';
};
export type ExocadImplantType = 'None' | 'CustomAbutment' | 'WithoutAbutment';
export type ExocadToothXml = {
number: string;
reconstructionType: string;
material: string;
mesialConnector: boolean;
implantType?: 'None' | 'CustomAbutment';
implantType?: ExocadImplantType;
materialAbutment?: string;
toothShade?: string;
};
@@ -147,10 +191,12 @@ export function mesialNeighbor(tooth: string): string | null {
return null;
}
/** Map a Dyolink VITA classical-style code to Exocad `ToothShade` (`VCL:A1`). */
/** Map a Dyolink shade code to Exocad `ToothShade` (`VCL:A1` or `V3DM:0M1`). */
export function exocadToothShade(code: string | null | undefined): string | null {
const trimmed = code?.trim();
if (!trimmed) return null;
const canonical = trimmed.toUpperCase();
if (V3DM_SHADE_CODES.has(canonical)) return `V3DM:${canonical}`;
return `VCL:${trimmed}`;
}
@@ -168,21 +214,67 @@ function buildNotes(comment: string): string | null {
return text.length > 0 ? text : null;
}
/** Cutback abutments get ReducedPontic; full-contour abutments get AnatomicPontic. */
function ponticTypeForAbutment(reconstructionType: string): 'ReducedPontic' | 'AnatomicPontic' {
return reconstructionType === 'Coping' ? 'ReducedPontic' : 'AnatomicPontic';
}
type ToothWrite = {
toothId: string;
reconstructionType: string;
material: string;
implantType: 'CustomAbutment' | 'None' | null;
implantType: ExocadImplantType | null;
materialAbutment?: string;
selectionGroupId: string;
};
type GroupAbutment = {
material: string;
ponticType: 'ReducedPontic' | 'AnatomicPontic';
};
function resolveImplant(group: ExocadToothJob[]): {
implantType: ExocadImplantType | null;
materialAbutment?: string;
consumedCodes: Set<string>;
skippedStacks: ExocadToothJob[];
} {
const consumedCodes = new Set<string>();
const skippedStacks: ExocadToothJob[] = [];
for (const [code, mapped] of Object.entries(IMPLANT_MATCH)) {
const hit = group.find((job) => job.prosthesisTypeCode === code);
if (!hit) continue;
consumedCodes.add(code);
return {
implantType: mapped.implantType,
materialAbutment: mapped.materialAbutment,
consumedCodes,
skippedStacks,
};
}
for (const job of group) {
if (!UNMAPPED_STACK_CODES.has(job.prosthesisTypeCode)) continue;
skippedStacks.push(job);
}
if (skippedStacks.length > 0) {
return { implantType: null, consumedCodes, skippedStacks };
}
return { implantType: 'None', consumedCodes, skippedStacks };
}
function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: ExocadSkippedLine[] } {
const groupMaterial = new Map<string, string>();
const groupAbutment = new Map<string, GroupAbutment>();
for (const job of jobs) {
const group = job.selectionGroupId?.trim() ?? '';
const mapped = MATERIAL_MATCH[job.prosthesisTypeCode];
if (!group || !mapped || groupMaterial.has(group)) continue;
groupMaterial.set(group, mapped.material);
if (!group || !mapped || groupAbutment.has(group)) continue;
groupAbutment.set(group, {
material: mapped.material,
ponticType: ponticTypeForAbutment(mapped.reconstructionType),
});
}
const writes: ToothWrite[] = [];
@@ -212,28 +304,64 @@ function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: Exo
const restoration = group.find((job) => MATERIAL_MATCH[job.prosthesisTypeCode]);
if (restoration) {
const mapped = MATERIAL_MATCH[restoration.prosthesisTypeCode];
const abutment = group.some((job) => job.prosthesisTypeCode === CUSTOM_ABUTMENT_CODE);
const implant = resolveImplant(group);
const allowImplant = IMPLANT_ALLOWED.has(mapped.reconstructionType);
let implantType: ExocadImplantType | null = null;
let materialAbutment: string | undefined;
if (allowImplant) {
if (implant.implantType === 'None') {
// Natural prep: only Coping historically always carried an explicit None.
implantType = mapped.reconstructionType === 'Coping' ? 'None' : null;
} else if (implant.implantType) {
implantType = implant.implantType;
materialAbutment = implant.materialAbutment;
}
}
writes.push({
toothId: tooth,
reconstructionType: mapped.reconstructionType,
material: mapped.material,
implantType: mapped.reconstructionType === 'Coping' ? (abutment ? 'CustomAbutment' : 'None') : null,
implantType,
materialAbutment,
selectionGroupId: restoration.selectionGroupId?.trim() ?? '',
});
for (const job of implant.skippedStacks) {
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
}
for (const job of group) {
if (job === restoration) continue;
if (implant.consumedCodes.has(job.prosthesisTypeCode)) continue;
if (implant.skippedStacks.includes(job)) continue;
if (MATERIAL_MATCH[job.prosthesisTypeCode] && job !== restoration) {
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
} else if (
!IMPLANT_MATCH[job.prosthesisTypeCode] &&
!UNMAPPED_STACK_CODES.has(job.prosthesisTypeCode) &&
job.prosthesisTypeCode !== 'pontic'
) {
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
}
}
continue;
}
const pontic = group.find((job) => job.prosthesisTypeCode === 'pontic');
if (pontic) {
const material = groupMaterial.get(pontic.selectionGroupId?.trim() ?? '') ?? '';
if (material) {
const abutment = groupAbutment.get(pontic.selectionGroupId?.trim() ?? '');
if (abutment) {
writes.push({
toothId: tooth,
reconstructionType: 'ReducedPontic',
material,
reconstructionType: abutment.ponticType,
material: abutment.material,
implantType: null,
selectionGroupId: pontic.selectionGroupId?.trim() ?? '',
});
for (const job of group) {
if (job === pontic) continue;
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
}
} else {
for (const job of group) {
const reason = job === pontic ? 'pontic' : 'unmapped';
@@ -297,7 +425,8 @@ function toXmlTeeth(writes: ToothWrite[], shade: string | null): ExocadToothXml[
material: write.material,
mesialConnector,
implantType,
materialAbutment: implantType === 'CustomAbutment' ? 'TI' : undefined,
materialAbutment:
implantType === 'CustomAbutment' ? write.materialAbutment ?? undefined : undefined,
toothShade: shade ?? undefined,
};
return row;
@@ -329,7 +458,7 @@ function shortCaseToken(caseId: string): string {
return caseId.replace(/-/g, '').slice(0, 8).toUpperCase() || 'CASE';
}
/** Safe `.dentalProject` basename: `{date}-{caseToken}.dentalProject`. */
/** Safe `.dentalProject` basename: `{exportDate}-{caseToken}.dentalProject`. */
export function exocadExportFileName(caseId: string, exportDate: string): string {
const date = exocadDueDate(exportDate) ?? '0000-00-00';
return `${date}-${shortCaseToken(caseId)}.dentalProject`;
@@ -344,13 +473,12 @@ export function buildExocadDentalProject(
if (!parts) throw new ExocadExportError('PATIENT_NAME_INCOMPLETE');
const { writes, skipped } = planTeeth(input.teeth);
if (writes.length === 0) throw new ExocadExportError('NOTHING_TO_EXPORT');
const shade = exocadToothShade(input.toothShadeCode);
const teeth = toXmlTeeth(writes, shade);
const projectGuid = options.projectGuid?.trim() || input.caseId;
const exportDate =
exocadDueDate(options.exportDate) ??
exocadDueDate(input.dueDate) ??
new Date().toISOString().slice(0, 10);
const exportDate = exocadDueDate(options.exportDate) ?? new Date().toISOString().slice(0, 10);
const fileName = exocadExportFileName(input.caseId, exportDate);
const notes = buildNotes(input.comment);
const practiceName = input.clinicName.trim();

View File

@@ -2,7 +2,7 @@ import { ExocadExportError } from '@/components/lab/exocad/exocadDentalProject';
type ExocadExportTranslator = (key: string) => string;
/** Map an Exocad export failure to a `cases` / `exocadExport` message. */
/** Map an Exocad export failure to a `cases` message. */
export function exocadExportErrorText(
error: unknown,
t: ExocadExportTranslator,
@@ -10,6 +10,7 @@ export function exocadExportErrorText(
): string {
if (error instanceof ExocadExportError) {
if (error.code === 'PATIENT_NAME_INCOMPLETE') return t('patientNameIncomplete');
if (error.code === 'NOTHING_TO_EXPORT') return t('nothingToExport');
}
return t(fallback);
}

View File

@@ -5,7 +5,7 @@
type FilePermission = 'granted' | 'denied' | 'prompt';
type DirectoryHandle = {
export type ExocadDirectoryHandle = {
name?: string;
queryPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
requestPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
@@ -23,13 +23,13 @@ type DirectoryHandle = {
type OpenDirectoryPicker = (options?: {
mode?: 'readwrite';
id?: string;
}) => Promise<DirectoryHandle>;
}) => Promise<ExocadDirectoryHandle>;
const HANDLE_DB = 'dyolink-exocad';
const HANDLE_STORE = 'files';
const AUTO_IMPORT_KEY = 'auto-import';
let cachedDirectory: DirectoryHandle | null = null;
let cachedDirectory: ExocadDirectoryHandle | null = null;
function directoryPicker(): OpenDirectoryPicker | null {
if (typeof window === 'undefined') return null;
@@ -51,13 +51,22 @@ export function isPickerCancel(error: unknown): boolean {
);
}
function errorName(error: unknown): string | null {
if (typeof error !== 'object' || error == null || !('name' in error)) return null;
return (error as { name?: string }).name ?? null;
}
function isMissingFileError(error: unknown): boolean {
return (
typeof error === 'object' &&
error != null &&
'name' in error &&
(error as { name?: string }).name === 'NotFoundError'
);
return errorName(error) === 'NotFoundError';
}
function isNotAllowedError(error: unknown): boolean {
return errorName(error) === 'NotAllowedError';
}
/** True when the remembered Auto-Import folder is gone or the permission was revoked. */
export function isExocadFolderGoneError(error: unknown): boolean {
return isMissingFileError(error) || isNotAllowedError(error);
}
function handleDb(): Promise<IDBDatabase> {
@@ -73,14 +82,14 @@ function handleDb(): Promise<IDBDatabase> {
});
}
async function loadDirectoryHandle(): Promise<DirectoryHandle | null> {
async function loadDirectoryHandle(): Promise<ExocadDirectoryHandle | null> {
if (cachedDirectory) return cachedDirectory;
if (typeof indexedDB === 'undefined') return null;
try {
const db = await handleDb();
const handle = await new Promise<DirectoryHandle | null>((resolve, reject) => {
const handle = await new Promise<ExocadDirectoryHandle | null>((resolve, reject) => {
const request = db.transaction(HANDLE_STORE, 'readonly').objectStore(HANDLE_STORE).get(AUTO_IMPORT_KEY);
request.onsuccess = () => resolve((request.result as DirectoryHandle | undefined) ?? null);
request.onsuccess = () => resolve((request.result as ExocadDirectoryHandle | undefined) ?? null);
request.onerror = () => reject(request.error);
});
db.close();
@@ -91,7 +100,7 @@ async function loadDirectoryHandle(): Promise<DirectoryHandle | null> {
}
}
async function saveDirectoryHandle(handle: DirectoryHandle): Promise<void> {
async function saveDirectoryHandle(handle: ExocadDirectoryHandle): Promise<void> {
cachedDirectory = handle;
if (typeof indexedDB === 'undefined') return;
const db = await handleDb();
@@ -123,7 +132,7 @@ async function clearDirectoryHandle(): Promise<void> {
const READ_WRITE = { mode: 'readwrite' as const };
async function grantedDirectory(handle: DirectoryHandle): Promise<DirectoryHandle | null> {
async function grantedDirectory(handle: ExocadDirectoryHandle): Promise<ExocadDirectoryHandle | null> {
const current = handle.queryPermission ? await handle.queryPermission(READ_WRITE) : 'prompt';
if (current === 'granted') return handle;
if (!handle.requestPermission) return null;
@@ -141,7 +150,7 @@ export async function forgetExocadExportFolder(): Promise<void> {
}
/** Reopen the remembered folder when permission is still granted. */
export async function reopenStoredExocadExportFolder(): Promise<DirectoryHandle | null> {
export async function reopenStoredExocadExportFolder(): Promise<ExocadDirectoryHandle | null> {
const handle = await loadDirectoryHandle();
if (!handle) return null;
try {
@@ -153,7 +162,7 @@ export async function reopenStoredExocadExportFolder(): Promise<DirectoryHandle
}
/** Ask the user to pick the DentalDB Project Auto-Import folder. */
export async function pickExocadExportFolder(): Promise<DirectoryHandle> {
export async function pickExocadExportFolder(): Promise<ExocadDirectoryHandle> {
const picker = directoryPicker();
if (!picker) throw new Error('DIRECTORY_PICKER_UNAVAILABLE');
const handle = await picker({ mode: 'readwrite', id: 'dyolink-exocad-auto-import' });
@@ -163,7 +172,7 @@ export async function pickExocadExportFolder(): Promise<DirectoryHandle> {
/** Write one `.dentalProject` file into the Auto-Import folder. */
export async function writeExocadDentalProjectFile(
handle: DirectoryHandle,
handle: ExocadDirectoryHandle,
fileName: string,
xml: string,
): Promise<void> {

View File

@@ -27,11 +27,11 @@ import {
} from '@/components/lab/caseDetailUtils';
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
import {
ExocadExportError,
buildExocadDentalProject,
type ExocadCaseInput,
} from '@/components/lab/exocad/exocadDentalProject';
import { exocadExportErrorText } from '@/components/lab/exocad/exocadExportErrors';
import { isExocadFolderGoneError } from '@/components/lab/exocad/exocadExportFolder';
import { useExocadExportFolder } from '@/components/ui/lab/ExocadExportFolderProvider';
import type { CaseSheetOrientation } from '@/components/ui/lab/CaseSheetPrintLayout';
import { caseCommentsApi } from '@/lib/api/case-comments';
@@ -462,8 +462,6 @@ export function CaseDetailPanel({
}
async function onSendToExocad() {
const ready = await exocadExport.requestFolder();
if (!ready) return;
let comment = labCase.detail?.comment?.trim() ?? '';
try {
const listed = await caseCommentsApi.list(labCase.id);
@@ -482,9 +480,16 @@ export function CaseDetailPanel({
toast.showError(exocadExportErrorText(caught, t, 'exportFailed'));
return;
}
const ready = await exocadExport.requestFolder();
if (!ready) return;
try {
await exocadExport.writeProjectFile(project.fileName, project.xml);
toast.showSuccess(t('sendToExocadSaved', { fileName: project.fileName }));
const folder = exocadExport.resolveFolderName();
toast.showSuccess(
folder
? t('sendToExocadSavedWithFolder', { fileName: project.fileName, folder })
: t('sendToExocadSaved', { fileName: project.fileName }),
);
if (project.skipped.length > 0) {
toast.showInfo(
t('sendToExocadSkipped', {
@@ -495,11 +500,7 @@ export function CaseDetailPanel({
);
}
} catch (caught) {
if (caught instanceof ExocadExportError) {
toast.showError(exocadExportErrorText(caught, t, 'exportFailed'));
return;
}
await exocadExport.abandon();
if (isExocadFolderGoneError(caught)) await exocadExport.abandon();
toast.showError(exocadExportErrorText(caught, t, 'folderWriteFailed'));
}
}
@@ -764,6 +765,17 @@ export function CaseDetailPanel({
) : null}
</div>
</div>
{exocadExport.canExport ? (
<button
type="button"
className="text-start text-xs text-text-muted underline-offset-2 hover:text-text-secondary hover:underline @2xl:text-end"
onClick={() => void exocadExport.changeFolder()}
>
{exocadExport.folderName
? t('sendToExocadChangeFolderNamed', { name: exocadExport.folderName })
: t('sendToExocadChangeFolder')}
</button>
) : null}
{labCase.shareUrl ? (
<div className="hidden shrink-0 @2xl:block">
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />

View File

@@ -11,26 +11,20 @@ import {
import {
isPickerCancel,
pickExocadExportFolder,
type ExocadDirectoryHandle,
} from '@/components/lab/exocad/exocadExportFolder';
type FolderHandle = {
getFileHandle: (
name: string,
options?: { create?: boolean },
) => Promise<{
createWritable: () => Promise<{
write: (data: BufferSource | Blob | string) => Promise<void>;
close: () => Promise<void>;
}>;
}>;
};
type ExocadExportFolderDialogProps = {
currentFolderName?: string | null;
onCancel: () => void;
onOpened: (handle: FolderHandle) => Promise<void>;
onOpened: (handle: ExocadDirectoryHandle) => Promise<void>;
};
export function ExocadExportFolderDialog({ onCancel, onOpened }: ExocadExportFolderDialogProps) {
export function ExocadExportFolderDialog({
currentFolderName,
onCancel,
onOpened,
}: ExocadExportFolderDialogProps) {
const t = useTranslations('cases');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
@@ -59,15 +53,20 @@ export function ExocadExportFolderDialog({ onCancel, onOpened }: ExocadExportFol
>
<div className="flex items-start justify-between gap-3">
<h2 id="exocad-export-folder-title" className="text-lg font-semibold text-text-primary">
{t('sendToExocadConnectTitle')}
{currentFolderName ? t('sendToExocadChangeFolderTitle') : t('sendToExocadConnectTitle')}
</h2>
<DialogCloseButton onClick={onCancel} />
</div>
<p className="mt-2 text-sm text-text-secondary">{t('sendToExocadFolderHint')}</p>
{currentFolderName ? (
<p className="mt-2 text-sm text-text-secondary">
{t('sendToExocadCurrentFolder', { name: currentFolderName })}
</p>
) : null}
<p className="mt-2 text-sm text-text-secondary">{t('sendToExocadScanNote')}</p>
<div className="mt-4 space-y-3">
<Button type="button" isLoading={busy} onClick={() => void onBrowse()}>
{t('sendToExocadBrowseFolder')}
{currentFolderName ? t('sendToExocadChangeFolder') : t('sendToExocadBrowseFolder')}
</Button>
{error ? (
<p className="text-sm text-red-600" role="alert">

View File

@@ -13,33 +13,27 @@ import {
import {
browserCanWriteExocadExport,
forgetExocadExportFolder,
pickExocadExportFolder,
preloadExocadExportFolder,
reopenStoredExocadExportFolder,
writeExocadDentalProjectFile,
type ExocadDirectoryHandle,
} from '@/components/lab/exocad/exocadExportFolder';
import { ExocadExportFolderDialog } from '@/components/ui/lab/ExocadExportFolderDialog';
type FolderHandle = {
getFileHandle: (
name: string,
options?: { create?: boolean },
) => Promise<{
createWritable: () => Promise<{
write: (data: BufferSource | Blob | string) => Promise<void>;
close: () => Promise<void>;
}>;
}>;
};
export type ExocadExportFolderValue = {
/** True in Chrome / Edge when `showDirectoryPicker` exists. */
canExport: boolean;
/** Display name of the remembered Auto-Import folder, when known. */
folderName: string | null;
/** Current folder name from the live handle (avoids a stale React state race). */
resolveFolderName: () => string | null;
/** Ensure a remembered or newly picked Auto-Import folder is ready. */
requestFolder: () => Promise<boolean>;
/** Always open the folder picker so the user can switch Auto-Import folders. */
changeFolder: () => Promise<boolean>;
/** Write one `.dentalProject` into the open Auto-Import folder. */
writeProjectFile: (fileName: string, xml: string) => Promise<void>;
/** Forget the folder after a hard failure so Browse is shown again. */
/** Forget the folder after it is gone or permission is revoked. */
abandon: () => Promise<void>;
};
@@ -54,19 +48,26 @@ export function useExocadExportFolder(): ExocadExportFolderValue {
}
export function ExocadExportFolderProvider({ children }: { children: ReactNode }) {
const folderRef = useRef<FolderHandle | null>(null);
const folderRef = useRef<ExocadDirectoryHandle | null>(null);
const connectResolveRef = useRef<((connected: boolean) => void) | null>(null);
const pendingConnectRef = useRef<Promise<boolean> | null>(null);
const [connectOpen, setConnectOpen] = useState(false);
const [canExport, setCanExport] = useState(false);
const [folderName, setFolderName] = useState<string | null>(null);
useEffect(() => {
setCanExport(browserCanWriteExocadExport());
preloadExocadExportFolder();
}, []);
const adoptFolder = useCallback((handle: ExocadDirectoryHandle) => {
folderRef.current = handle;
setFolderName(handle.name?.trim() || null);
}, []);
const abandon = useCallback(async () => {
folderRef.current = null;
setFolderName(null);
await forgetExocadExportFolder();
}, []);
@@ -76,12 +77,23 @@ export function ExocadExportFolderProvider({ children }: { children: ReactNode }
await writeExocadDentalProjectFile(folder, fileName, xml);
}, []);
const resolveFolderName = useCallback(() => {
return folderRef.current?.name?.trim() || null;
}, []);
const finishConnect = useCallback((connected: boolean) => {
setConnectOpen(false);
connectResolveRef.current?.(connected);
connectResolveRef.current = null;
}, []);
const openPickerDialog = useCallback(() => {
return new Promise<boolean>((resolve) => {
connectResolveRef.current = resolve;
setConnectOpen(true);
});
}, []);
const requestFolder = useCallback(() => {
if (pendingConnectRef.current) return pendingConnectRef.current;
const pending = (async () => {
@@ -89,27 +101,50 @@ export function ExocadExportFolderProvider({ children }: { children: ReactNode }
try {
const restored = browserCanWriteExocadExport() ? await reopenStoredExocadExportFolder() : null;
if (restored) {
folderRef.current = restored;
adoptFolder(restored);
return true;
}
} catch {
folderRef.current = null;
setFolderName(null);
await forgetExocadExportFolder();
}
return await new Promise<boolean>((resolve) => {
connectResolveRef.current = resolve;
setConnectOpen(true);
});
return await openPickerDialog();
})().finally(() => {
pendingConnectRef.current = null;
});
pendingConnectRef.current = pending;
return pending;
}, []);
}, [adoptFolder, openPickerDialog]);
const changeFolder = useCallback(() => {
if (pendingConnectRef.current) return pendingConnectRef.current;
const pending = openPickerDialog().finally(() => {
pendingConnectRef.current = null;
});
pendingConnectRef.current = pending;
return pending;
}, [openPickerDialog]);
const value = useMemo<ExocadExportFolderValue>(
() => ({ canExport, requestFolder, writeProjectFile, abandon }),
[abandon, canExport, requestFolder, writeProjectFile],
() => ({
canExport,
folderName,
resolveFolderName,
requestFolder,
changeFolder,
writeProjectFile,
abandon,
}),
[
abandon,
canExport,
changeFolder,
folderName,
requestFolder,
resolveFolderName,
writeProjectFile,
],
);
return (
@@ -117,9 +152,10 @@ export function ExocadExportFolderProvider({ children }: { children: ReactNode }
{children}
{connectOpen ? (
<ExocadExportFolderDialog
currentFolderName={folderName}
onCancel={() => finishConnect(false)}
onOpened={async (handle) => {
folderRef.current = handle;
adoptFolder(handle);
finishConnect(true);
}}
/>