Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| add2b5a7be | |||
| ea0b2ad547 | |||
| 599371846c | |||
| 565b014235 | |||
| 1017cc14ac | |||
| d476edf4ec |
@@ -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:** local DentalDB SQLite write from the case header, every origin, at every screen size, only in Chrome and Edge (`showOpenFilePicker`). Other browsers do not show the button. There is no local helper and no download fallback. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id when the file is written. The browser remembers the file handle only after the DentalDB check. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a DentalDB database is not remembered, and Browse stays available. An empty `workParamsSHA` is copied from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`) onto a new `WorkParamsInfo` and `WorkParamsInfoLocal`. Do not set treatment `flags` to 16. The connect dialog says the feature is experimental and asks for a manual backup; Nudentic is not responsible. A tooth is written only when that work type and material already exist. Monolithic zirconia and PFZ are `Coping`, a pontic is `ReducedPontic`, and the FDI opposite is `Antagonist`/`Healthy` when that pair exists. Parameters come from the fullest saved tooth of the same pair, without shade. A Coping donor is the fullest tooth whose `ImplantType` already matches. `customized_abutment` on that Coping copies `CustomAbutment` only when a saved tooth of the same pair already has it; otherwise that value is not invented. A plain Coping copies `None` when a saved coping has it. Other abutment codes are not mapped. More than one technician is left unset. Client is an exact name, one unique token match, or a new client with the given name, including one word. An empty clinic name still writes the case. A patient name that cannot be split is not written and the toast says why. A new case gets the next `t_schaleId` for that client. After the write, the user can grant the CAD-Data folder so the empty `{date}_{practice}-{tray}` directory is created; cancelling that grant leaves the case in the database. Notes are the comment body. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
|
||||
- **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}”.
|
||||
|
||||
@@ -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 export does not map shade yet.
|
||||
- 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).
|
||||
|
||||
@@ -58,15 +58,16 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
|
||||
|
||||
## Send to Exocad
|
||||
|
||||
Writes the open case into a DentalDB SQLite file on this computer. Nothing is uploaded to the Dyolink server. Close Exocad before writing, then open it again.
|
||||
Writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder on this computer. Nothing is uploaded to the Dyolink server and DentalDB’s SQLite file is never opened or mutated.
|
||||
|
||||
- Button `cases.sendToExocad` on the case header at every screen size, every origin, for anyone who can open the case, only when the browser can overwrite the picked file (`showOpenFilePicker`: Chrome and Edge). It is separate from Outsource. Safari and other browsers do not show it. There is no local helper program and no download fallback.
|
||||
- `LocalDbSessionProvider` holds the open file. The browser overwrites the picked file and remembers that file handle (IndexedDB) only after the file passes the DentalDB check. The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a usable DentalDB database is not remembered, and the connect dialog stays open so Browse can be used again.
|
||||
- The connect dialog warns that Send to Exocad is experimental, that the user must make a manual backup of the DentalDB file first, that Nudentic is not responsible for any issues, and that the user uses the feature on their own.
|
||||
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. The client is the case clinic name (the sheet sender). Reuse a client when the trimmed name matches one client, ignoring case, or when exactly one client name contains every token. Otherwise create a client with the name as given, including one word. Several partial matches do not pick a client. An empty clinic name still writes the case on one empty-named client. Never use practice id `2147483647`. Match a patient of that client by the same tokens, ignoring order. DentalDB stores the family name in `fname` and the given name in `lname`. A new patient is created only when both parts exist. Otherwise nothing is written and the toast says Name could not be filled. `t_Notes` is the case comment bodies, or the detail comment when the thread is empty. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. A new case sets `t_schaleId` to one more than that client's highest tray, or 1. An update keeps a tray that is already set. The project directory is `{date}_{practice}-{tray}` from the stored treatment date. After the database write, the user grants the `CAD-Data` folder once; that handle is remembered and only the empty project directory is created. If that grant is cancelled, the case stays in the database and the toast says Save can still fail. One case is one transaction: a failed insert rolls the case back and the database is unchanged. When `workParamsSHA` is empty, copy that hash onto a new `WorkParamsInfo` and `WorkParamsInfoLocal` from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`), then set `workParamsSHA` and `workParamInfoId`. Do not set treatment `flags` to 16.
|
||||
- A tooth is written only when the catalog name has an obvious Exocad material and that exact `WorkTypeSN` + `MaterialSN` already exists on a saved tooth. Copy numeric and textual parameters and their dependents from the fullest saved tooth of that same pair. For a Coping, that donor is the fullest tooth whose `ImplantType` already matches. Do not copy shade. Do not copy a donor with no parameters, and do not copy one material's numbers onto another. Obvious pairs: Monolithic Zirconia and PFZ Crown = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic Crown = `AnatomicCrown`/`GCER`; pontic = `ReducedPontic` plus the connected crown material when that pontic pair exists; IPS Overlay = `OverlayCrown`/`LS2`. Pressed Ceramic / IPS e.max (`AnatomicCrown`/`LS2`), PEEK (`AnatomicCrown`/`PEEK`), Veneer Zirconia (`Veneer`/`ZI`), IPS veneers (`Veneer`/`LS2`), and Zirconia Overlay (`AnatomicInlay`/`ZI`) are the same rule: written only when the opened file already has that pair. Each written tooth also gets its FDI opposite as `Antagonist`/`Healthy` when that pair exists and the opposite is not itself a restoration. When the file already stores them, the case scan mode is `AntagonistType` `RegisteredJaws` and the tooth shade is `---`. A file with exactly one technician assigns that technician. More than one technician is left unset. Temporary resin, veneer/inlay/onlay/overlay full-contour or layered with no material in the name, cast post, fiber post, and an abutment with no crown get no tooth row. The case header is still created. `customized_abutment` (Custom Abutment (Titanium)) on a Coping copies `ImplantType` `CustomAbutment` from a saved tooth of that same pair when the file already has it. If it does not, that value is not invented and the crown is copied from a `None` coping when one exists. A plain Coping copies `ImplantType` `None` when a saved coping has it, and does not take `CustomAbutment` from another tooth. Other abutment codes are not mapped. An abutment on a tooth that was written is not listed again. The skipped toast still lists teeth that were not written.
|
||||
- When the file is written and `externalCode` is empty, save the Exocad `treatment_id` through `PATCH /cases/:id/external-code` (`TAB_CASES_EDIT`).
|
||||
- There is no Local database tab. Send to Exocad keeps `LocalDbSessionProvider`, `LocalDbConnectDialog`, and the file open/write path.
|
||||
- Button `cases.sendToExocad` on the case header at every screen size, every origin, for anyone who can open the case, only when the browser can write a picked folder (`showDirectoryPicker`: Chrome and Edge). It is separate from Outsource. Safari and other browsers do not show it. There is no local helper and no download fallback.
|
||||
- `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 (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.
|
||||
|
||||
## Case Sheet PDF
|
||||
|
||||
|
||||
@@ -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 program or download) writes the open case into a DentalDB SQLite file on that computer. The browser remembers the file only after the DentalDB check and reopens it while it still exists; an invalid file is not remembered, so Browse stays available. Monolithic zirconia and PFZ are Coping, a pontic is a reduced pontic, and the opposite tooth is an antagonist, only when that pair already exists in the file. A titanium custom abutment on that Coping copies ImplantType CustomAbutment from a saved tooth of the same pair when the file already has it. The connect dialog says the feature is experimental, asks for a manual backup, says Nudentic is not responsible, and says the user uses it on their own. A one-word clinic name still fills Client, and an empty clinic name still writes the case. A patient name that cannot fill Name is not written, and the toast says so. Each new case gets the next tray for that client. After the write, the user can grant the CAD-Data folder so the empty project directory is created. A failed case rolls back. 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`.
|
||||
|
||||
|
||||
Binary file not shown.
3
frontend/.gitignore
vendored
3
frontend/.gitignore
vendored
@@ -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
|
||||
@@ -558,13 +558,22 @@
|
||||
"generatedBadge": "Generated",
|
||||
"sendCase": "Outsource",
|
||||
"sendToExocad": "Send to Exocad",
|
||||
"sendToExocadSaved": "Sent to Exocad as case {id}. Open Exocad again to see the case.",
|
||||
"sendToExocadUpdated": "Updated Exocad case {id}. Open Exocad again to see the case.",
|
||||
"sendToExocadSkipped": "Not sent: {lines}.",
|
||||
"sendToExocadFolderMissing": "The case was written. The Exocad project folder was not created, so Save in Exocad can still fail until you choose the CAD-Data folder.",
|
||||
"sendToExocadConnectTitle": "Connect Exocad database",
|
||||
"sendToExocadCloseHint": "Close Exocad before sending. Open it again afterwards to see the case.",
|
||||
"sendToExocadExperimentalWarning": "This is an experimental feature. Make a manual backup of the Exocad database before using it. Nudentic is not responsible for any issues. You use this feature on your own.",
|
||||
"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.",
|
||||
@@ -1473,16 +1482,6 @@
|
||||
"incomeEmptyCommission": "No commission records in this month.",
|
||||
"errorLoadIncome": "Could not load the income details."
|
||||
},
|
||||
"localDb": {
|
||||
"browse": "Browse",
|
||||
"openFailed": "Could not open that file.",
|
||||
"loadFailed": "Could not read that database.",
|
||||
"applyFailed": "Could not write the file.",
|
||||
"conflict": "That record conflicts with a row already in the table.",
|
||||
"notExocad": "That file is not an Exocad database.",
|
||||
"patientNameIncomplete": "Not sent. The patient name needs a last name so Exocad can fill Name. Edit the patient and try again. The Exocad database was not changed.",
|
||||
"sendRolledBack": "Not sent. The Exocad database was not changed."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "Something went wrong. Please try again.",
|
||||
"NETWORK_ERROR": "Could not reach the server. Check your connection and try again.",
|
||||
|
||||
@@ -558,13 +558,22 @@
|
||||
"fromLabBadge": "از لابراتوار",
|
||||
"sendCase": "برون سپاری",
|
||||
"sendToExocad": "ارسال به Exocad",
|
||||
"sendToExocadSaved": "به Exocad به عنوان پرونده {id} فرستاده شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadUpdated": "پرونده {id} در Exocad بهروز شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadSkipped": "فرستاده نشد: {lines}.",
|
||||
"sendToExocadFolderMissing": "پرونده نوشته شد. پوشه پروژه Exocad ساخته نشد، بنابراین ذخیره در Exocad تا وقتی پوشه CAD-Data را انتخاب نکنید میتواند ناموفق بماند.",
|
||||
"sendToExocadConnectTitle": "اتصال پایگاه داده Exocad",
|
||||
"sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadExperimentalWarning": "این قابلیت آزمایشی است. پیش از استفاده، یک نسخه پشتیبان دستی از پایگاه داده 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": "این برونسپاری شامل کار بدون تعرفه است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.",
|
||||
@@ -1474,16 +1483,6 @@
|
||||
"incomeEmptyCommission": "در این ماه رکورد کمیسیونی نیست.",
|
||||
"errorLoadIncome": "بارگذاری جزئیات درآمد ناموفق بود."
|
||||
},
|
||||
"localDb": {
|
||||
"browse": "مرور",
|
||||
"openFailed": "این فایل باز نشد.",
|
||||
"loadFailed": "این پایگاه داده خوانده نشد.",
|
||||
"applyFailed": "نوشتن فایل انجام نشد.",
|
||||
"conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.",
|
||||
"notExocad": "این فایل پایگاه داده Exocad نیست.",
|
||||
"patientNameIncomplete": "ارسال نشد. نام بیمار نام خانوادگی ندارد، بنابراین Name در Exocad پر نمیشود. نام بیمار را اصلاح کنید و دوباره بفرستید. پایگاه داده Exocad تغییر نکرد.",
|
||||
"sendRolledBack": "ارسال نشد. پایگاه داده Exocad تغییر نکرد."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
|
||||
"NETWORK_ERROR": "اتصال به سرور برقرار نشد. اتصال اینترنت را بررسی کنید.",
|
||||
|
||||
@@ -558,13 +558,22 @@
|
||||
"fromLabBadge": "Van lab",
|
||||
"sendCase": "Uitbesteden",
|
||||
"sendToExocad": "Naar Exocad sturen",
|
||||
"sendToExocadSaved": "Naar Exocad gestuurd als casus {id}. Open Exocad opnieuw om de casus te zien.",
|
||||
"sendToExocadUpdated": "Exocad-casus {id} bijgewerkt. Open Exocad opnieuw om de casus te zien.",
|
||||
"sendToExocadSkipped": "Niet gestuurd: {lines}.",
|
||||
"sendToExocadFolderMissing": "De casus is opgeslagen. De Exocad-projectmap is niet aangemaakt, dus Opslaan in Exocad kan nog mislukken totdat u de map CAD-Data kiest.",
|
||||
"sendToExocadConnectTitle": "Exocad-database koppelen",
|
||||
"sendToExocadCloseHint": "Sluit Exocad voordat u verstuurt. Open het daarna opnieuw om de casus te zien.",
|
||||
"sendToExocadExperimentalWarning": "Dit is een experimentele functie. Maak een handmatige back-up van de Exocad-database voordat u deze gebruikt. Nudentic is niet aansprakelijk voor eventuele problemen. U gebruikt deze functie op eigen verantwoordelijkheid.",
|
||||
"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.",
|
||||
@@ -1473,16 +1482,6 @@
|
||||
"incomeEmptyCommission": "Geen commissieregels in deze maand.",
|
||||
"errorLoadIncome": "De inkomstendetails konden niet worden geladen."
|
||||
},
|
||||
"localDb": {
|
||||
"browse": "Bladeren",
|
||||
"openFailed": "Dat bestand kon niet worden geopend.",
|
||||
"loadFailed": "Die database kon niet worden gelezen.",
|
||||
"applyFailed": "Het bestand kon niet worden geschreven.",
|
||||
"conflict": "Dat record botst met een rij die al in de tabel staat.",
|
||||
"notExocad": "Dat bestand is geen Exocad-database.",
|
||||
"patientNameIncomplete": "Niet verzonden. De patiëntnaam heeft geen achternaam, dus Exocad kan Name niet invullen. Pas de patiënt aan en probeer het opnieuw. De Exocad-database is niet gewijzigd.",
|
||||
"sendRolledBack": "Niet verzonden. De Exocad-database is niet gewijzigd."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "Er is iets misgegaan. Probeer het opnieuw.",
|
||||
"NETWORK_ERROR": "Kan de server niet bereiken. Controleer uw verbinding.",
|
||||
|
||||
@@ -41,7 +41,6 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
output: 'standalone',
|
||||
compress: true,
|
||||
serverExternalPackages: ['sql.js'],
|
||||
};
|
||||
|
||||
export default withSentryConfig(withNextIntl(nextConfig), {
|
||||
|
||||
7
frontend/package-lock.json
generated
7
frontend/package-lock.json
generated
@@ -24,7 +24,6 @@
|
||||
"react-qr-code": "^2.0.15",
|
||||
"recharts": "^3.9.2",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"sql.js": "^1.14.2",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -9799,12 +9798,6 @@
|
||||
"source-map": "^0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sql.js": {
|
||||
"version": "1.14.2",
|
||||
"resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.14.2.tgz",
|
||||
"integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/stable-hash": {
|
||||
"version": "0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz",
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"predev": "node scripts/copy-sql-wasm.mjs",
|
||||
"prebuild": "node scripts/copy-sql-wasm.mjs",
|
||||
"dev": "next dev -p 3001",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3001",
|
||||
@@ -28,7 +26,6 @@
|
||||
"react-qr-code": "^2.0.15",
|
||||
"recharts": "^3.9.2",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"sql.js": "^1.14.2",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
Binary file not shown.
@@ -1,8 +0,0 @@
|
||||
import { copyFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const source = require.resolve('sql.js/dist/sql-wasm-browser.wasm');
|
||||
const destination = path.join(process.cwd(), 'public', 'sql-wasm-browser.wasm');
|
||||
copyFileSync(source, destination);
|
||||
@@ -10,10 +10,10 @@ import Sidebar from '@/components/ui/shared/Sidebar';
|
||||
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
|
||||
import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
|
||||
import { NotificationBell } from '@/components/ui/notifications/NotificationBell';
|
||||
import { LocalDbSessionProvider } from '@/components/ui/local-db/LocalDbSessionProvider';
|
||||
import { ConfirmProvider } from '@/components/ui/shared/ConfirmProvider';
|
||||
import { ToastProvider } from '@/components/ui/shared/ToastProvider';
|
||||
import { CaseUploadFailureReporter } from '@/components/ui/lab/CaseUploadFailureReporter';
|
||||
import { ExocadExportFolderProvider } from '@/components/ui/lab/ExocadExportFolderProvider';
|
||||
import { RealtimeProvider } from '@/lib/realtime/RealtimeProvider';
|
||||
import {
|
||||
canAccessDashboardRoute,
|
||||
@@ -95,7 +95,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
<CaseUploadFailureReporter />
|
||||
<ConfirmProvider>
|
||||
<RealtimeProvider>
|
||||
<LocalDbSessionProvider>
|
||||
<ExocadExportFolderProvider>
|
||||
<div className="app-dashboard-shell flex h-[100dvh] app-web-bg text-text-primary">
|
||||
{sidebarOpen ? (
|
||||
<button
|
||||
@@ -128,7 +128,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</LocalDbSessionProvider>
|
||||
</ExocadExportFolderProvider>
|
||||
</RealtimeProvider>
|
||||
</ConfirmProvider>
|
||||
</ToastProvider>
|
||||
|
||||
323
frontend/src/components/lab/exocad/exocadDentalProject.spec.ts
Normal file
323
frontend/src/components/lab/exocad/exocadDentalProject.spec.ts
Normal file
@@ -0,0 +1,323 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ExocadExportError,
|
||||
buildExocadDentalProject,
|
||||
exocadExportFileName,
|
||||
exocadToothShade,
|
||||
mesialNeighbor,
|
||||
personParts,
|
||||
type ExocadCaseInput,
|
||||
} from './exocadDentalProject';
|
||||
|
||||
const CASE_ID = '12345678-90ab-cdef-1234-567890abcdef';
|
||||
|
||||
function baseInput(overrides: Partial<ExocadCaseInput> = {}): ExocadCaseInput {
|
||||
return {
|
||||
caseId: CASE_ID,
|
||||
clinicName: 'Sunrise Clinic',
|
||||
patientFirstName: 'John',
|
||||
patientLastName: 'Doe',
|
||||
comment: '',
|
||||
dueDate: '2026-11-29',
|
||||
toothShadeCode: null,
|
||||
teeth: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('personParts', () => {
|
||||
it('keeps explicit first and last names', () => {
|
||||
expect(personParts('John', 'Doe')).toEqual({ given: 'John', family: 'Doe' });
|
||||
});
|
||||
|
||||
it('splits a single combined field into given and family', () => {
|
||||
expect(personParts('John Doe', '')).toEqual({ given: 'John', family: 'Doe' });
|
||||
});
|
||||
|
||||
it('rejects a one-word name', () => {
|
||||
expect(personParts('Madonna', '')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('mesialNeighbor', () => {
|
||||
it('moves toward the midline within a quadrant', () => {
|
||||
expect(mesialNeighbor('16')).toBe('15');
|
||||
expect(mesialNeighbor('26')).toBe('25');
|
||||
expect(mesialNeighbor('36')).toBe('35');
|
||||
expect(mesialNeighbor('46')).toBe('45');
|
||||
});
|
||||
|
||||
it('crosses the midline for central incisors', () => {
|
||||
expect(mesialNeighbor('11')).toBe('21');
|
||||
expect(mesialNeighbor('21')).toBe('11');
|
||||
expect(mesialNeighbor('31')).toBe('41');
|
||||
expect(mesialNeighbor('41')).toBe('31');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exocadToothShade', () => {
|
||||
it('formats VITA classical codes as VCL', () => {
|
||||
expect(exocadToothShade('A2')).toBe('VCL:A2');
|
||||
});
|
||||
|
||||
it('formats bleach 0M shades as V3DM', () => {
|
||||
expect(exocadToothShade('0M1')).toBe('V3DM:0M1');
|
||||
expect(exocadToothShade('0m2')).toBe('V3DM:0M2');
|
||||
});
|
||||
|
||||
it('omits empty shades', () => {
|
||||
expect(exocadToothShade(null)).toBeNull();
|
||||
expect(exocadToothShade(' ')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildExocadDentalProject', () => {
|
||||
it('writes required tags, practice name, and mapped crown materials', () => {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
comment: 'Please check occlusion',
|
||||
toothShadeCode: 'A2',
|
||||
teeth: [
|
||||
{ tooth: '16', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
{ tooth: '26', prosthesisTypeCode: 'pfm_crown' },
|
||||
{ tooth: '36', prosthesisTypeCode: 'press_ceramic' },
|
||||
],
|
||||
}),
|
||||
{ exportDate: '2026-11-29' },
|
||||
);
|
||||
|
||||
expect(project.fileName).toBe(exocadExportFileName(CASE_ID, '2026-11-29'));
|
||||
expect(project.projectGuid).toBe(CASE_ID);
|
||||
expect(project.skipped).toEqual([]);
|
||||
expect(project.xml).toContain('<Treatment UseRecipientMaterialConfiguration="True">');
|
||||
expect(project.xml).toContain('<PracticeName>Sunrise Clinic</PracticeName>');
|
||||
expect(project.xml).toContain(`<ProjectGUID>${CASE_ID}</ProjectGUID>`);
|
||||
expect(project.xml).toContain('<PatientName>Doe</PatientName>');
|
||||
expect(project.xml).toContain('<PatientFirstName>John</PatientFirstName>');
|
||||
expect(project.xml).toContain('<Notes>Please check occlusion</Notes>');
|
||||
expect(project.xml).toContain('<Number>16</Number>');
|
||||
expect(project.xml).toContain('<ReconstructionType>Coping</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>ZI</Material>');
|
||||
expect(project.xml).toContain('<Material>NP</Material>');
|
||||
expect(project.xml).toContain('<ReconstructionType>AnatomicCrown</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>LS2</Material>');
|
||||
expect(project.xml).toContain('<ToothShade>VCL:A2</ToothShade>');
|
||||
expect(project.xml).toContain('<ImplantType>None</ImplantType>');
|
||||
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({
|
||||
clinicName: 'A & B <Clinic>',
|
||||
patientFirstName: 'Ann "Marie"',
|
||||
patientLastName: "O'Neil",
|
||||
comment: 'Use <temp> & "shade"',
|
||||
teeth: [{ tooth: '11', prosthesisTypeCode: 'full_metal_crown' }],
|
||||
}),
|
||||
);
|
||||
expect(project.xml).toContain('<PracticeName>A & B <Clinic></PracticeName>');
|
||||
expect(project.xml).toContain('<PatientName>O'Neil</PatientName>');
|
||||
expect(project.xml).toContain('<PatientFirstName>Ann "Marie"</PatientFirstName>');
|
||||
expect(project.xml).toContain('<Notes>Use <temp> & "shade"</Notes>');
|
||||
});
|
||||
|
||||
it('marks mesial connectors on a cutback bridge and maps the pontic as ReducedPontic', () => {
|
||||
const group = 'bridge-1';
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '14', prosthesisTypeCode: 'pfz_crown', selectionGroupId: group },
|
||||
{ tooth: '15', prosthesisTypeCode: 'pontic', selectionGroupId: group },
|
||||
{ tooth: '16', prosthesisTypeCode: 'pfz_crown', selectionGroupId: group },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(project.skipped).toEqual([]);
|
||||
expect(project.xml).toContain('<Number>15</Number>');
|
||||
expect(project.xml).toContain('<ReconstructionType>ReducedPontic</ReconstructionType>');
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>16<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>\s*<MesialConnector>true<\/MesialConnector>/,
|
||||
);
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>15<\/Number>\s*<ReconstructionType>ReducedPontic<\/ReconstructionType>\s*<MesialConnector>true<\/MesialConnector>/,
|
||||
);
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>14<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>\s*<MesialConnector>false<\/MesialConnector>/,
|
||||
);
|
||||
});
|
||||
|
||||
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({
|
||||
teeth: [
|
||||
{ tooth: '36', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
{ tooth: '36', prosthesisTypeCode: 'customized_abutment' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(project.xml).toContain('<ImplantType>CustomAbutment</ImplantType>');
|
||||
expect(project.xml).toContain('<MaterialAbutment>TI</MaterialAbutment>');
|
||||
});
|
||||
|
||||
it('maps zirconia abutments and screw-retained implants', () => {
|
||||
const zirconia = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '16', prosthesisTypeCode: 'pfz_crown' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'zirconia_abutment' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
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: '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(
|
||||
baseInput({
|
||||
patientFirstName: 'Madonna',
|
||||
patientLastName: '',
|
||||
teeth: [{ tooth: '11', prosthesisTypeCode: 'full_metal_crown' }],
|
||||
}),
|
||||
),
|
||||
).toThrow(ExocadExportError);
|
||||
});
|
||||
|
||||
it('maps IPS overlay to AnatomicInlay because OverlayCrown is outside the official table', () => {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [{ tooth: '24', prosthesisTypeCode: 'ips_overlay' }],
|
||||
}),
|
||||
);
|
||||
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>/,
|
||||
);
|
||||
});
|
||||
});
|
||||
513
frontend/src/components/lab/exocad/exocadDentalProject.ts
Normal file
513
frontend/src/components/lab/exocad/exocadDentalProject.ts
Normal file
@@ -0,0 +1,513 @@
|
||||
/**
|
||||
* Build an official Exocad `.dentalProject` XML file (3rd-party auto-import).
|
||||
* Prosthesis → ReconstructionType / Material pairs follow the prior DentalDB mapping
|
||||
* where those values appear in the official specification tables.
|
||||
*/
|
||||
|
||||
export type ExocadExportFailure = 'PATIENT_NAME_INCOMPLETE' | 'NOTHING_TO_EXPORT';
|
||||
|
||||
export class ExocadExportError extends Error {
|
||||
constructor(readonly code: ExocadExportFailure) {
|
||||
super(code);
|
||||
this.name = 'ExocadExportError';
|
||||
}
|
||||
}
|
||||
|
||||
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 overlays
|
||||
* use AnatomicInlay. Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
|
||||
*/
|
||||
const MATERIAL_MATCH: Record<string, MaterialMatch> = {
|
||||
monolithic_zirconia: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
pfz_crown: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
pfm_crown: { reconstructionType: 'Coping', material: 'NP' },
|
||||
full_metal_crown: { reconstructionType: 'AnatomicCrown', material: 'NP' },
|
||||
glass_ceramic_crown: { reconstructionType: 'AnatomicCrown', material: 'GCER' },
|
||||
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' },
|
||||
zirconia_overlay: { reconstructionType: 'AnatomicInlay', material: 'ZI' },
|
||||
ips_overlay: { reconstructionType: 'AnatomicInlay', material: 'LS2' },
|
||||
};
|
||||
|
||||
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([
|
||||
'AnatomicCrown',
|
||||
'AnatomicWaxup',
|
||||
'BarPillar',
|
||||
'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;
|
||||
selectionGroupId?: string;
|
||||
};
|
||||
|
||||
export type ExocadCaseInput = {
|
||||
caseId: string;
|
||||
clinicName: string;
|
||||
patientFirstName: string;
|
||||
patientLastName: string;
|
||||
comment: string;
|
||||
dueDate: string | null;
|
||||
toothShadeCode?: string | null;
|
||||
teeth: ExocadToothJob[];
|
||||
};
|
||||
|
||||
export type ExocadSkippedLine = {
|
||||
tooth: string;
|
||||
prosthesisTypeCode: string;
|
||||
reason: 'arch' | 'unmapped' | 'pontic';
|
||||
};
|
||||
|
||||
export type ExocadImplantType = 'None' | 'CustomAbutment' | 'WithoutAbutment';
|
||||
|
||||
export type ExocadToothXml = {
|
||||
number: string;
|
||||
reconstructionType: string;
|
||||
material: string;
|
||||
mesialConnector: boolean;
|
||||
implantType?: ExocadImplantType;
|
||||
materialAbutment?: string;
|
||||
toothShade?: string;
|
||||
};
|
||||
|
||||
export type ExocadDentalProject = {
|
||||
projectGuid: string;
|
||||
fileName: string;
|
||||
xml: string;
|
||||
skipped: ExocadSkippedLine[];
|
||||
};
|
||||
|
||||
export type ExocadDentalProjectOptions = {
|
||||
/** Override ProjectGUID (tests). Defaults to the Dyolink case id. */
|
||||
projectGuid?: string;
|
||||
/** Calendar day used in the export file name. Defaults to today (UTC). */
|
||||
exportDate?: string;
|
||||
};
|
||||
|
||||
function isArchTooth(tooth: string): boolean {
|
||||
const normalized = tooth.trim().toUpperCase();
|
||||
return normalized === 'UA' || normalized === 'LA';
|
||||
}
|
||||
|
||||
function isFdiTooth(tooth: string): boolean {
|
||||
return /^\d{1,2}$/.test(tooth.trim());
|
||||
}
|
||||
|
||||
/** Keep a leading calendar date. */
|
||||
export function exocadDueDate(value: string | null | undefined): string | null {
|
||||
const match = /^(\d{4}-\d{2}-\d{2})/.exec(value?.trim() ?? '');
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* DentalDB / Exocad store family name as PatientName and given name as PatientFirstName.
|
||||
* Require both parts (split a single field when needed).
|
||||
*/
|
||||
export function personParts(
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
): { given: string; family: string } | null {
|
||||
const given = firstName.trim();
|
||||
const family = lastName.trim();
|
||||
if (given && family) return { given, family };
|
||||
const parts = `${given} ${family}`
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.filter((part) => part.length > 0);
|
||||
if (parts.length < 2) return null;
|
||||
return { given: parts.slice(0, -1).join(' '), family: parts[parts.length - 1] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mesial neighbor in FDI permanent dentition.
|
||||
* Centrals connect across the midline (11↔21, 31↔41).
|
||||
*/
|
||||
export function mesialNeighbor(tooth: string): string | null {
|
||||
const number = Number(tooth);
|
||||
if (!Number.isInteger(number)) return null;
|
||||
const quadrant = Math.floor(number / 10);
|
||||
const position = number % 10;
|
||||
if (position < 1 || position > 8) return null;
|
||||
if (position > 1) return String(quadrant * 10 + (position - 1));
|
||||
if (quadrant === 1) return '21';
|
||||
if (quadrant === 2) return '11';
|
||||
if (quadrant === 3) return '41';
|
||||
if (quadrant === 4) return '31';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 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}`;
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function buildNotes(comment: string): string | null {
|
||||
const text = comment.trim();
|
||||
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: 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 groupAbutment = new Map<string, GroupAbutment>();
|
||||
for (const job of jobs) {
|
||||
const group = job.selectionGroupId?.trim() ?? '';
|
||||
const mapped = MATERIAL_MATCH[job.prosthesisTypeCode];
|
||||
if (!group || !mapped || groupAbutment.has(group)) continue;
|
||||
groupAbutment.set(group, {
|
||||
material: mapped.material,
|
||||
ponticType: ponticTypeForAbutment(mapped.reconstructionType),
|
||||
});
|
||||
}
|
||||
|
||||
const writes: ToothWrite[] = [];
|
||||
const skipped: ExocadSkippedLine[] = [];
|
||||
const byTooth = new Map<string, ExocadToothJob[]>();
|
||||
const toothOrder: string[] = [];
|
||||
for (const job of jobs) {
|
||||
const tooth = job.tooth.trim();
|
||||
const group = byTooth.get(tooth);
|
||||
if (group) group.push(job);
|
||||
else {
|
||||
byTooth.set(tooth, [job]);
|
||||
toothOrder.push(tooth);
|
||||
}
|
||||
}
|
||||
|
||||
for (const tooth of toothOrder) {
|
||||
const group = byTooth.get(tooth) ?? [];
|
||||
if (isArchTooth(tooth) || !isFdiTooth(tooth)) {
|
||||
const reason = isArchTooth(tooth) ? 'arch' : 'unmapped';
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const restoration = group.find((job) => MATERIAL_MATCH[job.prosthesisTypeCode]);
|
||||
if (restoration) {
|
||||
const mapped = MATERIAL_MATCH[restoration.prosthesisTypeCode];
|
||||
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,
|
||||
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 abutment = groupAbutment.get(pontic.selectionGroupId?.trim() ?? '');
|
||||
if (abutment) {
|
||||
writes.push({
|
||||
toothId: tooth,
|
||||
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';
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
}
|
||||
|
||||
writes.sort(
|
||||
(left, right) =>
|
||||
Number(left.toothId) - Number(right.toothId) ||
|
||||
left.reconstructionType.localeCompare(right.reconstructionType),
|
||||
);
|
||||
return { writes, skipped };
|
||||
}
|
||||
|
||||
function connectedToothIds(writes: ToothWrite[]): Set<string> {
|
||||
const byGroup = new Map<string, string[]>();
|
||||
for (const write of writes) {
|
||||
if (!write.selectionGroupId) continue;
|
||||
const list = byGroup.get(write.selectionGroupId) ?? [];
|
||||
list.push(write.toothId);
|
||||
byGroup.set(write.selectionGroupId, list);
|
||||
}
|
||||
const connected = new Set<string>();
|
||||
for (const teeth of byGroup.values()) {
|
||||
if (teeth.length < 2) continue;
|
||||
for (const tooth of teeth) connected.add(tooth);
|
||||
}
|
||||
return connected;
|
||||
}
|
||||
|
||||
function toXmlTeeth(writes: ToothWrite[], shade: string | null): ExocadToothXml[] {
|
||||
const bridgeTeeth = connectedToothIds(writes);
|
||||
const inBridge = new Set(writes.map((row) => row.toothId));
|
||||
|
||||
return writes.map((write) => {
|
||||
const mesial = mesialNeighbor(write.toothId);
|
||||
const mesialConnector = Boolean(
|
||||
write.selectionGroupId &&
|
||||
bridgeTeeth.has(write.toothId) &&
|
||||
mesial &&
|
||||
inBridge.has(mesial) &&
|
||||
writes.some(
|
||||
(other) => other.toothId === mesial && other.selectionGroupId === write.selectionGroupId,
|
||||
),
|
||||
);
|
||||
|
||||
const implantType =
|
||||
write.implantType && IMPLANT_ALLOWED.has(write.reconstructionType) ? write.implantType : undefined;
|
||||
|
||||
const row: ExocadToothXml = {
|
||||
number: write.toothId,
|
||||
reconstructionType: write.reconstructionType,
|
||||
material: write.material,
|
||||
mesialConnector,
|
||||
implantType,
|
||||
materialAbutment:
|
||||
implantType === 'CustomAbutment' ? write.materialAbutment ?? undefined : undefined,
|
||||
toothShade: shade ?? undefined,
|
||||
};
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
function toothXml(tooth: ExocadToothXml): string {
|
||||
const lines = [
|
||||
' <Tooth>',
|
||||
` <Number>${escapeXml(tooth.number)}</Number>`,
|
||||
` <ReconstructionType>${escapeXml(tooth.reconstructionType)}</ReconstructionType>`,
|
||||
` <MesialConnector>${tooth.mesialConnector ? 'true' : 'false'}</MesialConnector>`,
|
||||
` <Material>${escapeXml(tooth.material)}</Material>`,
|
||||
];
|
||||
if (tooth.implantType) {
|
||||
lines.push(` <ImplantType>${escapeXml(tooth.implantType)}</ImplantType>`);
|
||||
}
|
||||
if (tooth.materialAbutment) {
|
||||
lines.push(` <MaterialAbutment>${escapeXml(tooth.materialAbutment)}</MaterialAbutment>`);
|
||||
}
|
||||
if (tooth.toothShade) {
|
||||
lines.push(` <ToothShade>${escapeXml(tooth.toothShade)}</ToothShade>`);
|
||||
}
|
||||
lines.push(' </Tooth>');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function shortCaseToken(caseId: string): string {
|
||||
return caseId.replace(/-/g, '').slice(0, 8).toUpperCase() || 'CASE';
|
||||
}
|
||||
|
||||
/** 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`;
|
||||
}
|
||||
|
||||
/** Build the official `.dentalProject` XML for one Dyolink case. */
|
||||
export function buildExocadDentalProject(
|
||||
input: ExocadCaseInput,
|
||||
options: ExocadDentalProjectOptions = {},
|
||||
): ExocadDentalProject {
|
||||
const parts = personParts(input.patientFirstName, input.patientLastName);
|
||||
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) ?? new Date().toISOString().slice(0, 10);
|
||||
const fileName = exocadExportFileName(input.caseId, exportDate);
|
||||
const notes = buildNotes(input.comment);
|
||||
const practiceName = input.clinicName.trim();
|
||||
|
||||
const body: string[] = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<Treatment UseRecipientMaterialConfiguration="True">',
|
||||
];
|
||||
if (practiceName) {
|
||||
body.push(' <Practice>');
|
||||
body.push(` <PracticeName>${escapeXml(practiceName)}</PracticeName>`);
|
||||
body.push(' </Practice>');
|
||||
}
|
||||
body.push(` <ProjectGUID>${escapeXml(projectGuid)}</ProjectGUID>`);
|
||||
if (notes) body.push(` <Notes>${escapeXml(notes)}</Notes>`);
|
||||
body.push(' <Patient>');
|
||||
body.push(` <PatientName>${escapeXml(parts.family)}</PatientName>`);
|
||||
body.push(` <PatientFirstName>${escapeXml(parts.given)}</PatientFirstName>`);
|
||||
body.push(' </Patient>');
|
||||
body.push(' <Teeth>');
|
||||
for (const tooth of teeth) body.push(toothXml(tooth));
|
||||
body.push(' </Teeth>');
|
||||
body.push('</Treatment>');
|
||||
body.push('');
|
||||
|
||||
return {
|
||||
projectGuid,
|
||||
fileName,
|
||||
xml: body.join('\n'),
|
||||
skipped,
|
||||
};
|
||||
}
|
||||
16
frontend/src/components/lab/exocad/exocadExportErrors.ts
Normal file
16
frontend/src/components/lab/exocad/exocadExportErrors.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { ExocadExportError } from '@/components/lab/exocad/exocadDentalProject';
|
||||
|
||||
type ExocadExportTranslator = (key: string) => string;
|
||||
|
||||
/** Map an Exocad export failure to a `cases` message. */
|
||||
export function exocadExportErrorText(
|
||||
error: unknown,
|
||||
t: ExocadExportTranslator,
|
||||
fallback: 'exportFailed' | 'folderWriteFailed',
|
||||
): 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);
|
||||
}
|
||||
187
frontend/src/components/lab/exocad/exocadExportFolder.ts
Normal file
187
frontend/src/components/lab/exocad/exocadExportFolder.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Browser File System Access helpers for Exocad's Project Auto-Import folder.
|
||||
* Chrome and Edge remember the directory handle so the next export can skip Browse.
|
||||
*/
|
||||
|
||||
type FilePermission = 'granted' | 'denied' | 'prompt';
|
||||
|
||||
export type ExocadDirectoryHandle = {
|
||||
name?: string;
|
||||
queryPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
requestPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
getFileHandle: (
|
||||
name: string,
|
||||
options?: { create?: boolean },
|
||||
) => Promise<{
|
||||
createWritable: () => Promise<{
|
||||
write: (data: BufferSource | Blob | string) => Promise<void>;
|
||||
close: () => Promise<void>;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
|
||||
type OpenDirectoryPicker = (options?: {
|
||||
mode?: 'readwrite';
|
||||
id?: string;
|
||||
}) => Promise<ExocadDirectoryHandle>;
|
||||
|
||||
const HANDLE_DB = 'dyolink-exocad';
|
||||
const HANDLE_STORE = 'files';
|
||||
const AUTO_IMPORT_KEY = 'auto-import';
|
||||
|
||||
let cachedDirectory: ExocadDirectoryHandle | null = null;
|
||||
|
||||
function directoryPicker(): OpenDirectoryPicker | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const picker = (window as Window & { showDirectoryPicker?: OpenDirectoryPicker }).showDirectoryPicker;
|
||||
return picker ?? null;
|
||||
}
|
||||
|
||||
/** Chrome and Edge can write into a user-picked Auto-Import folder. */
|
||||
export function browserCanWriteExocadExport(): boolean {
|
||||
return directoryPicker() != null;
|
||||
}
|
||||
|
||||
export function isPickerCancel(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error != null &&
|
||||
'name' in error &&
|
||||
(error as { name?: string }).name === 'AbortError'
|
||||
);
|
||||
}
|
||||
|
||||
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 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> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(HANDLE_DB, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
if (!request.result.objectStoreNames.contains(HANDLE_STORE)) {
|
||||
request.result.createObjectStore(HANDLE_STORE);
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
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<ExocadDirectoryHandle | null>((resolve, reject) => {
|
||||
const request = db.transaction(HANDLE_STORE, 'readonly').objectStore(HANDLE_STORE).get(AUTO_IMPORT_KEY);
|
||||
request.onsuccess = () => resolve((request.result as ExocadDirectoryHandle | undefined) ?? null);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
db.close();
|
||||
cachedDirectory = handle;
|
||||
return handle;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDirectoryHandle(handle: ExocadDirectoryHandle): Promise<void> {
|
||||
cachedDirectory = handle;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).put(handle, AUTO_IMPORT_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
}
|
||||
|
||||
async function clearDirectoryHandle(): Promise<void> {
|
||||
cachedDirectory = null;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
try {
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).delete(AUTO_IMPORT_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
} catch {
|
||||
cachedDirectory = null;
|
||||
}
|
||||
}
|
||||
|
||||
const READ_WRITE = { mode: 'readwrite' as const };
|
||||
|
||||
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;
|
||||
return (await handle.requestPermission(READ_WRITE)) === 'granted' ? handle : null;
|
||||
}
|
||||
|
||||
export function preloadExocadExportFolder(): void {
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
void loadDirectoryHandle();
|
||||
}
|
||||
|
||||
/** Drop the remembered Auto-Import folder so the next export asks again. */
|
||||
export async function forgetExocadExportFolder(): Promise<void> {
|
||||
await clearDirectoryHandle();
|
||||
}
|
||||
|
||||
/** Reopen the remembered folder when permission is still granted. */
|
||||
export async function reopenStoredExocadExportFolder(): Promise<ExocadDirectoryHandle | null> {
|
||||
const handle = await loadDirectoryHandle();
|
||||
if (!handle) return null;
|
||||
try {
|
||||
return await grantedDirectory(handle);
|
||||
} catch (error) {
|
||||
if (isMissingFileError(error)) await clearDirectoryHandle();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ask the user to pick the DentalDB Project Auto-Import folder. */
|
||||
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' });
|
||||
await saveDirectoryHandle(handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
/** Write one `.dentalProject` file into the Auto-Import folder. */
|
||||
export async function writeExocadDentalProjectFile(
|
||||
handle: ExocadDirectoryHandle,
|
||||
fileName: string,
|
||||
xml: string,
|
||||
): Promise<void> {
|
||||
const safe = fileName.trim();
|
||||
if (!safe || /[\\/]/.test(safe) || !safe.endsWith('.dentalProject')) {
|
||||
throw new Error('INVALID_EXPORT_FILE_NAME');
|
||||
}
|
||||
const file = await handle.getFileHandle(safe, { create: true });
|
||||
const writable = await file.createWritable();
|
||||
await writable.write(xml);
|
||||
await writable.close();
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
export type DatabaseSink = {
|
||||
name: string;
|
||||
bytes: Uint8Array;
|
||||
write: (bytes: Uint8Array) => Promise<void>;
|
||||
/** Called after the file parses, so a bad database is not remembered. */
|
||||
remember?: () => Promise<void>;
|
||||
};
|
||||
|
||||
type FilePermission = 'granted' | 'denied' | 'prompt';
|
||||
|
||||
type FilePickerHandle = {
|
||||
getFile: () => Promise<File>;
|
||||
queryPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
requestPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
createWritable: () => Promise<{
|
||||
write: (data: BufferSource) => Promise<void>;
|
||||
close: () => Promise<void>;
|
||||
}>;
|
||||
};
|
||||
|
||||
type OpenFilePicker = (options?: {
|
||||
multiple?: boolean;
|
||||
excludeAcceptAllOption?: boolean;
|
||||
id?: string;
|
||||
types?: Array<{ description?: string; accept: Record<string, string[]> }>;
|
||||
}) => Promise<FilePickerHandle[]>;
|
||||
|
||||
const HANDLE_DB = 'dyolink-exocad';
|
||||
const HANDLE_STORE = 'files';
|
||||
const HANDLE_KEY = 'database';
|
||||
|
||||
let cachedHandle: FilePickerHandle | null = null;
|
||||
|
||||
function filePicker(): OpenFilePicker | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const picker = (window as Window & { showOpenFilePicker?: OpenFilePicker }).showOpenFilePicker;
|
||||
return picker ?? null;
|
||||
}
|
||||
|
||||
/** Chrome and Edge can overwrite the file the user just picked. */
|
||||
export function browserCanWriteLocalFile(): boolean {
|
||||
return filePicker() != null;
|
||||
}
|
||||
|
||||
export function isPickerCancel(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error != null &&
|
||||
'name' in error &&
|
||||
(error as { name?: string }).name === 'AbortError'
|
||||
);
|
||||
}
|
||||
|
||||
function isMissingFileError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error != null &&
|
||||
'name' in error &&
|
||||
(error as { name?: string }).name === 'NotFoundError'
|
||||
);
|
||||
}
|
||||
|
||||
function handleDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(HANDLE_DB, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
if (!request.result.objectStoreNames.contains(HANDLE_STORE)) {
|
||||
request.result.createObjectStore(HANDLE_STORE);
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
/** Chrome keeps permission for a handle stored here, so the next send can skip Browse. */
|
||||
async function loadBrowserHandle(): Promise<FilePickerHandle | null> {
|
||||
if (cachedHandle) return cachedHandle;
|
||||
if (typeof indexedDB === 'undefined') return null;
|
||||
try {
|
||||
const db = await handleDb();
|
||||
const handle = await new Promise<FilePickerHandle | null>((resolve, reject) => {
|
||||
const request = db.transaction(HANDLE_STORE, 'readonly').objectStore(HANDLE_STORE).get(HANDLE_KEY);
|
||||
request.onsuccess = () => resolve((request.result as FilePickerHandle | undefined) ?? null);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
db.close();
|
||||
cachedHandle = handle;
|
||||
return handle;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function preloadBrowserHandle(): void {
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
void loadBrowserHandle();
|
||||
}
|
||||
|
||||
async function saveBrowserHandle(handle: FilePickerHandle): Promise<void> {
|
||||
cachedHandle = handle;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).put(handle, HANDLE_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
}
|
||||
|
||||
/** Drop the remembered file so the next send asks for a database again. */
|
||||
export async function forgetBrowserDatabase(): Promise<void> {
|
||||
await clearBrowserHandle();
|
||||
}
|
||||
|
||||
async function clearBrowserHandle(): Promise<void> {
|
||||
cachedHandle = null;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
try {
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).delete(HANDLE_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
} catch {
|
||||
cachedHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function sinkFromBrowserHandle(handle: FilePickerHandle): Promise<DatabaseSink> {
|
||||
const file = await handle.getFile();
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
return {
|
||||
name: file.name,
|
||||
bytes,
|
||||
write: async (next) => {
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(Uint8Array.from(next));
|
||||
await writable.close();
|
||||
},
|
||||
remember: () => saveBrowserHandle(handle),
|
||||
};
|
||||
}
|
||||
|
||||
const READ_WRITE = { mode: 'readwrite' as const };
|
||||
|
||||
async function permissionFor(handle: FilePickerHandle): Promise<FilePermission> {
|
||||
const current = handle.queryPermission ? await handle.queryPermission(READ_WRITE) : 'prompt';
|
||||
if (current === 'granted' || !handle.requestPermission) return current;
|
||||
return handle.requestPermission(READ_WRITE);
|
||||
}
|
||||
|
||||
/** Read the remembered file. Null means Browse should open. A deleted file is forgotten. */
|
||||
export async function reopenStoredBrowserFile(): Promise<DatabaseSink | null> {
|
||||
const handle = await loadBrowserHandle();
|
||||
if (!handle) return null;
|
||||
try {
|
||||
const permission = await permissionFor(handle);
|
||||
if (permission !== 'granted') return null;
|
||||
return await sinkFromBrowserHandle(handle);
|
||||
} catch (error) {
|
||||
if (isMissingFileError(error)) await clearBrowserHandle();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** True while the remembered file is still on disk. Other failures keep the open session. */
|
||||
export async function browserDatabaseStillExists(): Promise<boolean> {
|
||||
const handle = cachedHandle ?? (await loadBrowserHandle());
|
||||
if (!handle) return false;
|
||||
try {
|
||||
await handle.getFile();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (isMissingFileError(error)) {
|
||||
await clearBrowserHandle();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function openWithBrowserPicker(): Promise<DatabaseSink> {
|
||||
const picker = filePicker();
|
||||
if (!picker) {
|
||||
throw new Error('FILE_PICKER_UNAVAILABLE');
|
||||
}
|
||||
const [handle] = await picker({
|
||||
multiple: false,
|
||||
excludeAcceptAllOption: false,
|
||||
id: 'dyolink-exocad-database',
|
||||
types: [
|
||||
{
|
||||
description: 'SQLite database',
|
||||
accept: {
|
||||
'application/vnd.sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
'application/x-sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return sinkFromBrowserHandle(handle);
|
||||
}
|
||||
|
||||
type DirectoryHandle = {
|
||||
queryPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
requestPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
|
||||
getDirectoryHandle: (name: string, options?: { create?: boolean }) => Promise<unknown>;
|
||||
};
|
||||
|
||||
type OpenDirectoryPicker = (options?: {
|
||||
mode?: 'readwrite';
|
||||
id?: string;
|
||||
}) => Promise<DirectoryHandle>;
|
||||
|
||||
const CAD_DATA_KEY = 'cad-data';
|
||||
|
||||
let cachedDirectory: DirectoryHandle | null = null;
|
||||
|
||||
function directoryPicker(): OpenDirectoryPicker | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const picker = (window as Window & { showDirectoryPicker?: OpenDirectoryPicker }).showDirectoryPicker;
|
||||
return picker ?? null;
|
||||
}
|
||||
|
||||
async function loadDirectoryHandle(): Promise<DirectoryHandle | 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 tx = db.transaction(HANDLE_STORE, 'readonly');
|
||||
const request = tx.objectStore(HANDLE_STORE).get(CAD_DATA_KEY);
|
||||
request.onsuccess = () => resolve((request.result as DirectoryHandle | undefined) ?? null);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
db.close();
|
||||
cachedDirectory = handle;
|
||||
return handle;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDirectoryHandle(handle: DirectoryHandle): Promise<void> {
|
||||
cachedDirectory = handle;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).put(handle, CAD_DATA_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
}
|
||||
|
||||
async function clearDirectoryHandle(): Promise<void> {
|
||||
cachedDirectory = null;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
try {
|
||||
const db = await handleDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(HANDLE_STORE, 'readwrite');
|
||||
tx.objectStore(HANDLE_STORE).delete(CAD_DATA_KEY);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
} catch {
|
||||
cachedDirectory = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function grantedDirectory(handle: DirectoryHandle): Promise<DirectoryHandle | null> {
|
||||
const permission = handle.queryPermission ? await handle.queryPermission(READ_WRITE) : 'prompt';
|
||||
if (permission === 'granted') return handle;
|
||||
if (!handle.requestPermission) return null;
|
||||
return (await handle.requestPermission(READ_WRITE)) === 'granted' ? handle : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create one empty project directory inside the CAD-Data folder the user grants.
|
||||
* The database file permission cannot create that folder. Cancel leaves the case in the database.
|
||||
*/
|
||||
export async function ensureExocadProjectDirectory(folderName: string): Promise<boolean> {
|
||||
const safe = folderName.trim();
|
||||
if (!safe || /[\\/]/.test(safe)) return false;
|
||||
try {
|
||||
const remembered = await loadDirectoryHandle();
|
||||
const ready = remembered ? await grantedDirectory(remembered) : null;
|
||||
if (ready) {
|
||||
await ready.getDirectoryHandle(safe, { create: true });
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
if (isMissingFileError(error)) await clearDirectoryHandle();
|
||||
else return false;
|
||||
}
|
||||
const picker = directoryPicker();
|
||||
if (!picker) return false;
|
||||
try {
|
||||
const handle = await picker({ mode: 'readwrite', id: 'dyolink-exocad-cad-data' });
|
||||
await saveDirectoryHandle(handle);
|
||||
await handle.getDirectoryHandle(safe, { create: true });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,951 +0,0 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
EXOCAD_MULTIDIE_PRACTICE_ID,
|
||||
ExocadTransferError,
|
||||
transferCaseToExocad,
|
||||
type ExocadCaseInput,
|
||||
} from './exocadTransfer';
|
||||
import type { SqliteCell, SqliteQuery } from './sqliteSql';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
type SqlStatement = {
|
||||
bind(values?: Array<string | number | null>): void;
|
||||
step(): boolean;
|
||||
get(): SqliteCell[];
|
||||
free(): void;
|
||||
};
|
||||
|
||||
type SqlDatabase = {
|
||||
run(sql: string, params?: Array<string | number | null>): void;
|
||||
prepare(sql: string): SqlStatement;
|
||||
close(): void;
|
||||
};
|
||||
|
||||
const SCHEMA = [
|
||||
`CREATE TABLE laboratories (
|
||||
id INT not null, name TEXT, language TEXT, country TEXT not null,
|
||||
city TEXT not null, zip TEXT not null, street TEXT not null, primary key (id)
|
||||
)`,
|
||||
`CREATE TABLE clients (
|
||||
lab_id INT not null, practice_id INT not null, name TEXT, language TEXT,
|
||||
country TEXT not null, city TEXT not null, zip TEXT not null, street TEXT not null,
|
||||
email TEXT, flags BIGINT, primary key (lab_id, practice_id),
|
||||
foreign key (lab_id) references laboratories(id)
|
||||
)`,
|
||||
`CREATE TABLE patients (
|
||||
lab_id INT not null, practice_id INT not null, patient_id INT not null,
|
||||
fname TEXT, lname TEXT, dateOfBirth DATETIME,
|
||||
primary key (lab_id, practice_id, patient_id),
|
||||
foreign key (lab_id, practice_id) references clients(lab_id, practice_id)
|
||||
)`,
|
||||
`CREATE TABLE Treatment (
|
||||
treatment_id integer primary key autoincrement,
|
||||
practice_lab_id INT, practice_pr_id INT,
|
||||
patient_lab_id INT, patient_practice_id INT, patient_patient_id INT,
|
||||
t_date DATETIME, t_Notes TEXT, flags BIGINT, projectGUID TEXT,
|
||||
importedOrderId TEXT, t_duedate TEXT, t_schaleId INT,
|
||||
foreign key (practice_lab_id, practice_pr_id) references clients(lab_id, practice_id),
|
||||
foreign key (patient_lab_id, patient_practice_id, patient_patient_id)
|
||||
references patients(lab_id, practice_id, patient_id)
|
||||
)`,
|
||||
`CREATE TABLE ToothWork (
|
||||
id integer primary key autoincrement, WorkParams TEXT, WorkParamsFile TEXT,
|
||||
ToothId TEXT, flags BIGINT, WorkTypeSN TEXT, MaterialSN TEXT, treatment_id BIGINT,
|
||||
foreign key (treatment_id) references Treatment(treatment_id)
|
||||
)`,
|
||||
`CREATE TABLE ToothWorkParameters (
|
||||
id integer primary key autoincrement, custom_wd_id INT, toothWork_id INT,
|
||||
foreign key (toothWork_id) references ToothWork(id)
|
||||
)`,
|
||||
`CREATE TABLE TextualToothWorkParameter (
|
||||
id INT not null, ParameterSN TEXT, ValueSN TEXT, primary key (id),
|
||||
foreign key (id) references ToothWorkParameters(id)
|
||||
)`,
|
||||
`CREATE TABLE NumericToothWorkParameter (
|
||||
id INT not null, ParameterSN TEXT, value DOUBLE, primary key (id),
|
||||
foreign key (id) references ToothWorkParameters(id)
|
||||
)`,
|
||||
`CREATE TABLE DependentToothWorkParameters (
|
||||
id integer primary key autoincrement, parent_param_id INT,
|
||||
dep_param_string TEXT, dep_param_value_string TEXT, dep_param_kind INTEGER,
|
||||
foreign key (parent_param_id) references TextualToothWorkParameter(id)
|
||||
)`,
|
||||
`CREATE TABLE DependentOnNumericToothWorkParameters (
|
||||
id integer primary key autoincrement, parent_param_id INTEGER,
|
||||
dep_param_string TEXT, dep_param_value_string TEXT, dep_param_kind INTEGER,
|
||||
foreign key (parent_param_id) references NumericToothWorkParameter(id)
|
||||
)`,
|
||||
`CREATE TABLE ValuedMaterialParameters (
|
||||
id integer primary key autoincrement, PARAM_TYPE TEXT not null, ValueSN TEXT,
|
||||
MaterialSN TEXT, MaterialPropertySN TEXT, toothwork_id INT,
|
||||
foreign key (toothwork_id) references ToothWork(id)
|
||||
)`,
|
||||
];
|
||||
|
||||
async function openSql(): Promise<SqlDatabase> {
|
||||
const initSqlJs = require('sql.js') as (config?: {
|
||||
wasmBinary?: Uint8Array;
|
||||
}) => Promise<{ Database: new () => SqlDatabase }>;
|
||||
const wasm = readFileSync(require.resolve('sql.js/dist/sql-wasm.wasm'));
|
||||
const SQL = await initSqlJs({ wasmBinary: wasm });
|
||||
return new SQL.Database();
|
||||
}
|
||||
|
||||
function asQuery(db: SqlDatabase): SqliteQuery {
|
||||
return {
|
||||
all(sql, params = []) {
|
||||
const stmt = db.prepare(sql);
|
||||
if (params.length > 0) stmt.bind(params);
|
||||
const rows: SqliteCell[][] = [];
|
||||
while (stmt.step()) rows.push(stmt.get());
|
||||
stmt.free();
|
||||
return rows;
|
||||
},
|
||||
run(sql, params = []) {
|
||||
db.run(sql, params);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function seed(db: SqlDatabase): SqliteQuery {
|
||||
for (const statement of SCHEMA) db.run(statement);
|
||||
db.run(`INSERT INTO laboratories (id, name, language, country, city, zip, street) VALUES (0, 'Default', 'de', 'de', '', '', '')`);
|
||||
db.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (0, 2147483647, 'MultiDiePractice', 'de', '', '', '', '', '', 0)`,
|
||||
);
|
||||
db.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (0, 1, 'Default', '', '', '', '', '', NULL, 0)`,
|
||||
);
|
||||
db.run(`INSERT INTO patients (lab_id, practice_id, patient_id, fname, lname, dateOfBirth) VALUES (1, 1, 1, '1', '1', 1)`);
|
||||
db.run(`INSERT INTO patients (lab_id, practice_id, patient_id, fname, lname, dateOfBirth) VALUES (2, 2, 2, '2', '2', 2)`);
|
||||
db.run('PRAGMA foreign_keys = ON');
|
||||
return asQuery(db);
|
||||
}
|
||||
|
||||
function seedSavedPair(
|
||||
query: SqliteQuery,
|
||||
workType: string,
|
||||
material: string,
|
||||
options: {
|
||||
toothId?: string;
|
||||
textual?: Array<{ name: string; value: string; dependent?: { name: string; value: string; kind: number } }>;
|
||||
numeric?: Array<{ name: string; value: number; dependent?: { name: string; value: string; kind: number } }>;
|
||||
color?: string;
|
||||
} = {},
|
||||
): void {
|
||||
if (query.all('SELECT treatment_id FROM Treatment WHERE treatment_id = 900').length === 0) {
|
||||
query.run(
|
||||
`INSERT INTO Treatment (
|
||||
treatment_id, practice_lab_id, practice_pr_id,
|
||||
patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, flags, projectGUID, importedOrderId
|
||||
) VALUES (900, 0, 1, 1, 1, 1, '2020-01-01', 16, 'donor-guid', 'donor-case')`,
|
||||
);
|
||||
}
|
||||
query.run(
|
||||
`INSERT INTO ToothWork (ToothId, flags, WorkTypeSN, MaterialSN, treatment_id) VALUES (?, 0, ?, ?, 900)`,
|
||||
[options.toothId ?? '99', workType, material],
|
||||
);
|
||||
const toothWorkId = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
for (const row of options.textual ?? []) {
|
||||
query.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (NULL, ?)', [toothWorkId]);
|
||||
const id = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
query.run('INSERT INTO TextualToothWorkParameter (id, ParameterSN, ValueSN) VALUES (?, ?, ?)', [id, row.name, row.value]);
|
||||
if (row.dependent) {
|
||||
query.run(
|
||||
`INSERT INTO DependentToothWorkParameters
|
||||
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[id, row.dependent.name, row.dependent.value, row.dependent.kind],
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const row of options.numeric ?? []) {
|
||||
query.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (NULL, ?)', [toothWorkId]);
|
||||
const id = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
query.run('INSERT INTO NumericToothWorkParameter (id, ParameterSN, value) VALUES (?, ?, ?)', [id, row.name, row.value]);
|
||||
if (row.dependent) {
|
||||
query.run(
|
||||
`INSERT INTO DependentOnNumericToothWorkParameters
|
||||
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[id, row.dependent.name, row.dependent.value, row.dependent.kind],
|
||||
);
|
||||
}
|
||||
}
|
||||
if (options.color) {
|
||||
query.run(
|
||||
`INSERT INTO ValuedMaterialParameters
|
||||
(PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN, toothwork_id)
|
||||
VALUES ('TEXTUAL', ?, ?, 'Color', ?)`,
|
||||
[options.color, material, toothWorkId],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const options = { now: '2026-10-16T09:00:00.000Z', projectGuid: 'guid-1' };
|
||||
|
||||
function sampleCase(overrides: Partial<ExocadCaseInput> = {}): ExocadCaseInput {
|
||||
return {
|
||||
caseId: 'case-1',
|
||||
clinicName: 'North Clinic',
|
||||
patientFirstName: 'Ada',
|
||||
patientLastName: 'Lovelace',
|
||||
dentistName: 'Dr Smith',
|
||||
comment: 'Shade A2',
|
||||
dueDate: '2026-10-20T00:00:00.000Z',
|
||||
teeth: [{ tooth: '14', prosthesisTypeCode: 'monolithic_zirconia', selectionGroupId: 'bridge' }],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('transferCaseToExocad', () => {
|
||||
it('creates the clinic, patient, header, and tooth work', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '90' });
|
||||
const result = transferCaseToExocad(query, sampleCase(), options);
|
||||
|
||||
expect(result).toMatchObject({ created: true, skipped: [] });
|
||||
expect(result.treatmentId).not.toBe(900);
|
||||
expect(query.all('SELECT practice_id, name FROM clients WHERE name = ?', ['North Clinic'])).toEqual([
|
||||
[2, 'North Clinic'],
|
||||
]);
|
||||
expect(
|
||||
query.all('SELECT lab_id, practice_id, patient_id, fname, lname, dateOfBirth FROM patients WHERE lname = ?', ['Ada']),
|
||||
).toEqual([[0, 2, 1, 'Lovelace', 'Ada', null]]);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT practice_pr_id, patient_patient_id, t_Notes, t_duedate, projectGUID, importedOrderId, flags FROM Treatment WHERE treatment_id = ?',
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[2, 1, 'Shade A2', '2026-10-20', 'guid-1', 'case-1', 0]]);
|
||||
expect(
|
||||
query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId', [result.treatmentId]),
|
||||
).toEqual([
|
||||
['14', 'Coping', 'ZI'],
|
||||
['44', 'Antagonist', 'Healthy'],
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT COUNT(*) FROM ToothWorkParameters params
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[0]]);
|
||||
expect(query.all('SELECT name FROM clients WHERE practice_id = ?', [EXOCAD_MULTIDIE_PRACTICE_ID])).toEqual([
|
||||
['MultiDiePractice'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('updates the same treatment and reuses the clinic and patient', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
seedSavedPair(query, 'Coping', 'NP', { toothId: '98' });
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '90' });
|
||||
transferCaseToExocad(query, sampleCase(), options);
|
||||
const second = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
clinicName: ' north clinic ',
|
||||
patientFirstName: 'ada',
|
||||
patientLastName: 'lovelace',
|
||||
teeth: [{ tooth: '16', prosthesisTypeCode: 'pfm_crown' }],
|
||||
}),
|
||||
{ now: '2026-10-17T09:00:00.000Z', projectGuid: 'guid-2' },
|
||||
);
|
||||
|
||||
expect(second).toMatchObject({ created: false, skipped: [] });
|
||||
expect(query.all('SELECT COUNT(*) FROM clients WHERE practice_id != ?', [EXOCAD_MULTIDIE_PRACTICE_ID])).toEqual([[2]]);
|
||||
expect(query.all('SELECT COUNT(*) FROM patients WHERE lab_id = 0')).toEqual([[1]]);
|
||||
expect(
|
||||
query.all('SELECT projectGUID, importedOrderId FROM Treatment WHERE treatment_id = ?', [second.treatmentId]),
|
||||
).toEqual([['guid-1', 'case-1']]);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId',
|
||||
[second.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['16', 'Coping', 'NP'],
|
||||
['46', 'Antagonist', 'Healthy'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('maps a pontic from the connected crown and skips the lines Exocad cannot take yet', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'GCER', {
|
||||
toothId: '81',
|
||||
numeric: [{ name: 'MinThickness', value: 0.2 }],
|
||||
});
|
||||
seedSavedPair(query, 'AnatomicCrown', 'GCER', {
|
||||
toothId: '82',
|
||||
textual: [{ name: 'PreparationType', value: 'Crown', dependent: { name: 'ScanAbutmentScan', value: 'false', kind: 0 } }],
|
||||
numeric: [{ name: 'MinThickness', value: 0.5, dependent: { name: 'MinThicknessSpecial', value: '0', kind: 1 } }],
|
||||
color: 'A1',
|
||||
});
|
||||
seedSavedPair(query, 'ReducedPontic', 'GCER', { toothId: '83' });
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
teeth: [
|
||||
{ tooth: '14', prosthesisTypeCode: 'glass_ceramic_crown', selectionGroupId: 'bridge' },
|
||||
{ tooth: '13', prosthesisTypeCode: 'pontic', selectionGroupId: 'bridge' },
|
||||
{ tooth: '14', prosthesisTypeCode: 'prefabricated_abutment' },
|
||||
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture' },
|
||||
{ tooth: '21', prosthesisTypeCode: 'pontic' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'press_ceramic' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
|
||||
expect(result.skipped).toEqual([
|
||||
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture', reason: 'arch' },
|
||||
{ tooth: '21', prosthesisTypeCode: 'pontic', reason: 'pontic' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'press_ceramic', reason: 'unmapped' },
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId',
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['13', 'ReducedPontic', 'GCER'],
|
||||
['14', 'AnatomicCrown', 'GCER'],
|
||||
]);
|
||||
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
['Shade A2'],
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT textual.ParameterSN, textual.ValueSN
|
||||
FROM TextualToothWorkParameter textual
|
||||
JOIN ToothWorkParameters params ON params.id = textual.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['PreparationType', 'Crown']]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.ParameterSN, numeric.value
|
||||
FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['MinThickness', 0.5]]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT dep.dep_param_string, dep.dep_param_value_string, dep.dep_param_kind
|
||||
FROM DependentToothWorkParameters dep
|
||||
JOIN TextualToothWorkParameter textual ON textual.id = dep.parent_param_id
|
||||
JOIN ToothWorkParameters params ON params.id = textual.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['ScanAbutmentScan', 'false', 0]]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT dep.dep_param_string, dep.dep_param_value_string, dep.dep_param_kind
|
||||
FROM DependentOnNumericToothWorkParameters dep
|
||||
JOIN NumericToothWorkParameter numeric ON numeric.id = dep.parent_param_id
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['MinThicknessSpecial', '0', 1]]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT valued.ValueSN, valued.MaterialSN, valued.MaterialPropertySN
|
||||
FROM ValuedMaterialParameters valued
|
||||
JOIN ToothWork work ON work.id = valued.toothwork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT COUNT(*) FROM ToothWorkParameters params
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '13'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[0]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('leaves a material with no saved pair out of the tooth table', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ teeth: [{ tooth: '11', prosthesisTypeCode: 'veneer_zirconia' }] }),
|
||||
options,
|
||||
);
|
||||
|
||||
expect(result.skipped).toEqual([{ tooth: '11', prosthesisTypeCode: 'veneer_zirconia', reason: 'unmapped' }]);
|
||||
expect(query.all('SELECT ToothId FROM ToothWork WHERE treatment_id = ?', [result.treatmentId])).toEqual([]);
|
||||
expect(query.all('SELECT t_Notes, projectGUID, importedOrderId FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
['Shade A2', 'guid-1', 'case-1'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('writes a saved veneer pair and keeps a PMMA color off a zirconia tooth', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Veneer', 'ZI', {
|
||||
toothId: '71',
|
||||
numeric: [{ name: 'MinThickness', value: 0.4 }],
|
||||
color: 'A2',
|
||||
});
|
||||
seedSavedPair(query, 'AnatomicCrown', 'ZI', { toothId: '72', color: 'A1', numeric: [{ name: 'MinThickness', value: 0.5 }] });
|
||||
seedSavedPair(query, 'AnatomicCrown', 'PMMA', { toothId: '73', color: 'A', numeric: [{ name: 'MinThickness', value: 0.3 }] });
|
||||
const veneer = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ caseId: 'veneer-case', teeth: [{ tooth: '11', prosthesisTypeCode: 'veneer_zirconia' }] }),
|
||||
options,
|
||||
);
|
||||
expect(
|
||||
query.all('SELECT WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ?', [veneer.treatmentId]),
|
||||
).toEqual([['Veneer', 'ZI']]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT ValueSN FROM ValuedMaterialParameters valued
|
||||
JOIN ToothWork work ON work.id = valued.toothwork_id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[veneer.treatmentId],
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.value
|
||||
FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[veneer.treatmentId],
|
||||
),
|
||||
).toEqual([[0.4]]);
|
||||
|
||||
const pmma = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ caseId: 'pmma-case', teeth: [{ tooth: '12', prosthesisTypeCode: 'pmma' }] }),
|
||||
{ ...options, projectGuid: 'guid-pmma' },
|
||||
);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.value
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN NumericToothWorkParameter numeric ON numeric.id = params.id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[pmma.treatmentId],
|
||||
),
|
||||
).toEqual([[0.3]]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT COUNT(*) FROM ValuedMaterialParameters valued
|
||||
JOIN ToothWork work ON work.id = valued.toothwork_id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[pmma.treatmentId],
|
||||
),
|
||||
).toEqual([[0]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('does not invent a material for a name that does not name one', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'PMMA');
|
||||
seedSavedPair(query, 'AnatomicCrown', 'LS2', { toothId: '97' });
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
teeth: [
|
||||
{ tooth: '11', prosthesisTypeCode: 'temporary_resin_crown' },
|
||||
{ tooth: '12', prosthesisTypeCode: 'veneer_layered' },
|
||||
{ tooth: '13', prosthesisTypeCode: 'fiber_post_core' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
|
||||
expect(query.all('SELECT ToothId FROM ToothWork WHERE treatment_id = ?', [result.treatmentId])).toEqual([]);
|
||||
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
['Shade A2'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('writes the case when the clinic name is one word or empty', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
const blank = transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options);
|
||||
const again = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ caseId: 'case-blank-2', clinicName: ' ' }),
|
||||
{ ...options, projectGuid: 'guid-blank' },
|
||||
);
|
||||
expect(query.all('SELECT name, practice_id FROM clients WHERE TRIM(name) = ?', [''])).toEqual([['', 2]]);
|
||||
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [blank.treatmentId])).toEqual([[2]]);
|
||||
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [again.treatmentId])).toEqual([[2]]);
|
||||
|
||||
const named = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ caseId: 'case-yavari', clinicName: 'yavari' }),
|
||||
{ ...options, projectGuid: 'guid-yavari' },
|
||||
);
|
||||
expect(query.all('SELECT name FROM clients WHERE practice_id = (SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?)', [named.treatmentId])).toEqual([
|
||||
['yavari'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('reuses one existing client and a patient stored family-name first', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
query.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (0, 120, 'Yavari Hoseinali', '', '', '', '', '', '', 0)`,
|
||||
);
|
||||
query.run(
|
||||
`INSERT INTO patients (lab_id, practice_id, patient_id, fname, lname, dateOfBirth)
|
||||
VALUES (0, 120, 7, 'Khorasani', 'Zahra', NULL)`,
|
||||
);
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ clinicName: 'yavari', patientFirstName: 'Zahra', patientLastName: 'khorasani' }),
|
||||
options,
|
||||
);
|
||||
expect(query.all('SELECT practice_pr_id, patient_patient_id FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
[120, 7],
|
||||
]);
|
||||
expect(query.all('SELECT COUNT(*) FROM patients WHERE practice_id = 120')).toEqual([[1]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('reuses an exact client name before a partial match', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
for (const [id, name] of [
|
||||
[120, 'Yavari Hoseinali'],
|
||||
[178, 'Yavari,Tehran'],
|
||||
[189, 'yavari'],
|
||||
] as const) {
|
||||
query.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (0, ?, ?, '', '', '', '', '', '', 0)`,
|
||||
[id, name],
|
||||
);
|
||||
}
|
||||
const exact = transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
|
||||
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [exact.treatmentId])).toEqual([[189]]);
|
||||
expect(query.all('SELECT COUNT(*) FROM clients WHERE name = ?', ['yavari'])).toEqual([[1]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('creates a client instead of choosing among several partial matches', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
for (const [id, name] of [
|
||||
[120, 'Yavari Hoseinali'],
|
||||
[178, 'Yavari,Tehran'],
|
||||
] as const) {
|
||||
query.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (0, ?, ?, '', '', '', '', '', '', 0)`,
|
||||
[id, name],
|
||||
);
|
||||
}
|
||||
const created = transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
|
||||
const row = query.all(
|
||||
'SELECT clients.name, clients.practice_id FROM clients JOIN Treatment ON Treatment.practice_pr_id = clients.practice_id WHERE Treatment.treatment_id = ?',
|
||||
[created.treatmentId],
|
||||
);
|
||||
expect(row).toEqual([['yavari', 179]]);
|
||||
expect(row[0][1]).not.toBe(120);
|
||||
expect(row[0][1]).not.toBe(178);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('does not write when the patient name has no last name', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
try {
|
||||
transferCaseToExocad(query, sampleCase({ patientFirstName: 'Ada', patientLastName: ' ' }), options);
|
||||
expect.unreachable();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ExocadTransferError);
|
||||
expect((error as ExocadTransferError).code).toBe('PATIENT_NAME_INCOMPLETE');
|
||||
}
|
||||
expect(query.all('SELECT COUNT(*) FROM clients')).toEqual([[2]]);
|
||||
expect(query.all("SELECT treatment_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('assigns the next tray and keeps it when the same case is sent again', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
const first = transferCaseToExocad(query, sampleCase(), options);
|
||||
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [first.treatmentId])).toEqual([[1]]);
|
||||
expect(first.projectFolder).toBe('2026-10-16_00002-001');
|
||||
|
||||
const second = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ caseId: 'case-2' }),
|
||||
{ ...options, projectGuid: 'guid-2', now: '2026-10-17T09:00:00.000Z' },
|
||||
);
|
||||
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [second.treatmentId])).toEqual([[2]]);
|
||||
expect(second.projectFolder).toBe('2026-10-17_00002-002');
|
||||
|
||||
const updated = transferCaseToExocad(query, sampleCase(), { ...options, now: '2026-11-01T09:00:00.000Z' });
|
||||
expect(updated.treatmentId).toBe(first.treatmentId);
|
||||
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [updated.treatmentId])).toEqual([[1]]);
|
||||
expect(updated.projectFolder).toBe('2026-11-01_00002-001');
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('writes coping, reduced pontic, and the opposite antagonist without a shade', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'ZI', { toothId: '70', color: 'A1' });
|
||||
seedSavedPair(query, 'Coping', 'ZI', { toothId: '71', numeric: [{ name: 'MinThickness', value: 0.6 }], color: 'A2' });
|
||||
seedSavedPair(query, 'ReducedPontic', 'ZI', { toothId: '72' });
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '73' });
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
comment: 'Full ZR(A2)+1PC',
|
||||
dentistName: 'Niki',
|
||||
teeth: [
|
||||
{ tooth: '13', prosthesisTypeCode: 'monolithic_zirconia', selectionGroupId: 'bridge' },
|
||||
{ tooth: '13', prosthesisTypeCode: 'customized_abutment_titanium' },
|
||||
{ tooth: '14', prosthesisTypeCode: 'pontic', selectionGroupId: 'bridge' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'pfz_crown', selectionGroupId: 'bridge' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
expect(result.skipped).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId',
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['13', 'Coping', 'ZI'],
|
||||
['14', 'ReducedPontic', 'ZI'],
|
||||
['15', 'Coping', 'ZI'],
|
||||
['43', 'Antagonist', 'Healthy'],
|
||||
['44', 'Antagonist', 'Healthy'],
|
||||
['45', 'Antagonist', 'Healthy'],
|
||||
]);
|
||||
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
['Full ZR(A2)+1PC'],
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.value
|
||||
FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '13'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[0.6]]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT COUNT(*) FROM ValuedMaterialParameters valued
|
||||
JOIN ToothWork work ON work.id = valued.toothwork_id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[0]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('does not mark a restored opposite tooth as an antagonist', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '90' });
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
teeth: [
|
||||
{ tooth: '14', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
{ tooth: '44', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
expect(
|
||||
query.all('SELECT ToothId, WorkTypeSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId', [result.treatmentId]),
|
||||
).toEqual([
|
||||
['14', 'Coping'],
|
||||
['44', 'Coping'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('copies the shared scan mode and blank shade, and the only technician', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN tech_lab_id INT');
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN tech_tech_id INT');
|
||||
db.run(
|
||||
`CREATE TABLE TreatmentValuedParameters (
|
||||
id integer primary key autoincrement, PARAM_TYPE TEXT, ParamSN TEXT, ValueSN TEXT, treatment_id INT
|
||||
)`,
|
||||
);
|
||||
db.run('CREATE TABLE technicians (lab_id INT, tech_id INT, fname TEXT, lname TEXT)');
|
||||
db.run(`INSERT INTO TreatmentValuedParameters (PARAM_TYPE, ParamSN, ValueSN, treatment_id) VALUES ('TEXTUAL', 'AntagonistType', 'RegisteredJaws', 900)`);
|
||||
db.run(`INSERT INTO TreatmentValuedParameters (PARAM_TYPE, ParamSN, ValueSN, treatment_id) VALUES ('TEXTUAL', 'AntagonistType', 'MushBite', 900)`);
|
||||
db.run(`INSERT INTO TreatmentValuedParameters (PARAM_TYPE, ParamSN, ValueSN, treatment_id) VALUES ('TEXTUAL', 'ToothColor', '---', 900)`);
|
||||
db.run(`INSERT INTO TreatmentValuedParameters (PARAM_TYPE, ParamSN, ValueSN, treatment_id) VALUES ('TEXTUAL', 'ToothColor', 'A2', 900)`);
|
||||
db.run(`INSERT INTO technicians (lab_id, tech_id, fname, lname) VALUES (0, 12, 'Niki', NULL)`);
|
||||
const result = transferCaseToExocad(query, sampleCase(), options);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT ParamSN, ValueSN FROM TreatmentValuedParameters WHERE treatment_id = ? ORDER BY ParamSN',
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['AntagonistType', 'RegisteredJaws'],
|
||||
['ToothColor', '---'],
|
||||
]);
|
||||
expect(query.all('SELECT tech_lab_id, tech_tech_id FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
[0, 12],
|
||||
]);
|
||||
db.run(`INSERT INTO technicians (lab_id, tech_id, fname, lname) VALUES (0, 2, 'Parsa', NULL)`);
|
||||
const second = transferCaseToExocad(query, sampleCase(), { ...options, now: '2026-10-17T09:00:00.000Z' });
|
||||
expect(query.all('SELECT tech_lab_id, tech_tech_id FROM Treatment WHERE treatment_id = ?', [second.treatmentId])).toEqual([
|
||||
[0, 12],
|
||||
]);
|
||||
const third = transferCaseToExocad(query, sampleCase({ caseId: 'case-2' }), { ...options, projectGuid: 'guid-2' });
|
||||
expect(query.all('SELECT tech_lab_id, tech_tech_id FROM Treatment WHERE treatment_id = ?', [third.treatmentId])).toEqual([
|
||||
[null, null],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('refuses a file that is not a DentalDB database', async () => {
|
||||
const db = await openSql();
|
||||
const query = asQuery(db);
|
||||
expect(() => transferCaseToExocad(query, sampleCase(), options)).toThrow(ExocadTransferError);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('copies the lab default material configuration onto a new treatment', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN workParamsSHA TEXT');
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN workParamInfoId INT');
|
||||
db.run('CREATE TABLE WorkParamsData (hash TEXT primary key, content BLOB)');
|
||||
db.run(
|
||||
`CREATE TABLE WorkParamsInfo (
|
||||
id integer primary key autoincrement,
|
||||
workParamsDataHash TEXT,
|
||||
lastModificationDate DATETIME,
|
||||
foreign key (workParamsDataHash) references WorkParamsData(hash)
|
||||
)`,
|
||||
);
|
||||
db.run('CREATE TABLE WorkParamsInfoLocal (id INT primary key, fileName TEXT)');
|
||||
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('content-hash', x'00')`);
|
||||
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('endo-hash', x'01')`);
|
||||
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (5, 'content-hash', '2024-09-27')`);
|
||||
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (6, 'endo-hash', '2024-09-27')`);
|
||||
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (5, 'D:\\config\\WorkParamsDB.xml')`);
|
||||
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (6, 'D:\\config\\WorkParamsDB-EndoCrown.xml')`);
|
||||
db.run(
|
||||
`INSERT INTO Treatment (
|
||||
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
|
||||
) VALUES (50, 0, 1, 1, 1, 1, '2026-01-01', 16, 'donor', 'donor-case', 'file-sha', 5)`,
|
||||
);
|
||||
db.run(
|
||||
`INSERT INTO Treatment (
|
||||
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
|
||||
) VALUES (60, 0, 1, 1, 1, 1, '2026-02-01', 16, 'endo', 'endo-case', 'endo-sha', 6)`,
|
||||
);
|
||||
|
||||
transferCaseToExocad(query, sampleCase(), options);
|
||||
const header = query.all(
|
||||
'SELECT workParamsSHA, workParamInfoId, flags FROM Treatment WHERE importedOrderId = ?',
|
||||
['case-1'],
|
||||
);
|
||||
const infoId = header[0]?.[1];
|
||||
expect(header[0]?.[0]).toBe('file-sha');
|
||||
expect(header[0]?.[2]).toBe(0);
|
||||
expect(infoId).not.toBe(5);
|
||||
expect(query.all('SELECT workParamsDataHash FROM WorkParamsInfo WHERE id = ?', [infoId as number])).toEqual([
|
||||
['content-hash'],
|
||||
]);
|
||||
expect(query.all('SELECT fileName FROM WorkParamsInfoLocal WHERE id = ?', [infoId as number])).toEqual([
|
||||
['D:\\config\\WorkParamsDB.xml'],
|
||||
]);
|
||||
|
||||
transferCaseToExocad(query, sampleCase({ teeth: [{ tooth: '16', prosthesisTypeCode: 'pfm_crown' }] }), options);
|
||||
expect(query.all('SELECT COUNT(*) FROM WorkParamsInfo')).toEqual([[3]]);
|
||||
expect(
|
||||
query.all('SELECT workParamInfoId FROM Treatment WHERE importedOrderId = ?', ['case-1']),
|
||||
).toEqual([[infoId]]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('copies CustomAbutment only from a coping that already has it', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI', {
|
||||
toothId: '81',
|
||||
textual: [
|
||||
{ name: 'ImplantType', value: 'None' },
|
||||
{ name: 'PreparationType', value: 'Crown' },
|
||||
],
|
||||
numeric: [{ name: 'MinThickness', value: 0.5 }],
|
||||
});
|
||||
seedSavedPair(query, 'Coping', 'ZI', {
|
||||
toothId: '82',
|
||||
textual: [
|
||||
{ name: 'ImplantType', value: 'CustomAbutment' },
|
||||
{ name: 'PreparationType', value: 'Crown' },
|
||||
],
|
||||
numeric: [{ name: 'MinThickness', value: 0.55 }],
|
||||
});
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
teeth: [
|
||||
{ tooth: '13', prosthesisTypeCode: 'customized_abutment' },
|
||||
{ tooth: '14', prosthesisTypeCode: 'monolithic_zirconia', selectionGroupId: 'bridge' },
|
||||
{ tooth: '14', prosthesisTypeCode: 'customized_abutment' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'zirconia_abutment' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
expect(result.skipped).toEqual([{ tooth: '13', prosthesisTypeCode: 'customized_abutment', reason: 'unmapped' }]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT work.ToothId, textual.ValueSN
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN TextualToothWorkParameter textual ON textual.id = params.id
|
||||
WHERE work.treatment_id = ? AND textual.ParameterSN = 'ImplantType'
|
||||
ORDER BY work.ToothId`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['14', 'CustomAbutment'],
|
||||
['15', 'None'],
|
||||
['16', 'None'],
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT work.ToothId, numeric.value
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN NumericToothWorkParameter numeric ON numeric.id = params.id
|
||||
WHERE work.treatment_id = ? AND numeric.ParameterSN = 'MinThickness'
|
||||
ORDER BY work.ToothId`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['14', 0.55],
|
||||
['15', 0.5],
|
||||
['16', 0.5],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('does not invent CustomAbutment when the file only has plain copings', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI', {
|
||||
toothId: '81',
|
||||
textual: [{ name: 'ImplantType', value: 'None' }],
|
||||
numeric: [{ name: 'MinThickness', value: 0.5 }],
|
||||
});
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
teeth: [
|
||||
{ tooth: '21', prosthesisTypeCode: 'monolithic_zirconia' },
|
||||
{ tooth: '21', prosthesisTypeCode: 'customized_abutment' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
expect(result.skipped).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT textual.ValueSN
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN TextualToothWorkParameter textual ON textual.id = params.id
|
||||
WHERE work.treatment_id = ? AND work.WorkTypeSN = 'Coping' AND textual.ParameterSN = 'ImplantType'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['None']]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('does not copy CustomAbutment onto a plain crown', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'Coping', 'ZI', {
|
||||
toothId: '81',
|
||||
textual: [{ name: 'ImplantType', value: 'CustomAbutment' }],
|
||||
numeric: [{ name: 'MinThickness', value: 0.6 }],
|
||||
});
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({ teeth: [{ tooth: '36', prosthesisTypeCode: 'monolithic_zirconia' }] }),
|
||||
options,
|
||||
);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT textual.ValueSN
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN TextualToothWorkParameter textual ON textual.id = params.id
|
||||
WHERE work.treatment_id = ? AND textual.ParameterSN = 'ImplantType'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.value
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN NumericToothWorkParameter numeric ON numeric.id = params.id
|
||||
WHERE work.treatment_id = ? AND work.WorkTypeSN = 'Coping' AND numeric.ParameterSN = 'MinThickness'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([[0.6]]);
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
@@ -1,830 +0,0 @@
|
||||
import type { SqliteQuery } from '@/components/local-db/sqliteSql';
|
||||
|
||||
/** DentalDB's own lab row in a default database. */
|
||||
const EXOCAD_LAB_ID = 0;
|
||||
|
||||
/** Reserved by DentalDB for multi-die work. Never create a clinic here. */
|
||||
export const EXOCAD_MULTIDIE_PRACTICE_ID = 2147483647;
|
||||
|
||||
const REQUIRED_TABLES = [
|
||||
'laboratories',
|
||||
'clients',
|
||||
'patients',
|
||||
'Treatment',
|
||||
'ToothWork',
|
||||
'ToothWorkParameters',
|
||||
'TextualToothWorkParameter',
|
||||
'NumericToothWorkParameter',
|
||||
'DependentToothWorkParameters',
|
||||
'DependentOnNumericToothWorkParameters',
|
||||
'ValuedMaterialParameters',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Catalog codes with one obvious Exocad work type and material.
|
||||
* A tooth is written only when the opened database already has that pair.
|
||||
*/
|
||||
const MATERIAL_MATCH: Record<string, { workType: string; material: string }> = {
|
||||
monolithic_zirconia: { workType: 'Coping', material: 'ZI' },
|
||||
pfz_crown: { workType: 'Coping', material: 'ZI' },
|
||||
pfm_crown: { workType: 'Coping', material: 'NP' },
|
||||
full_metal_crown: { workType: 'AnatomicCrown', material: 'NP' },
|
||||
glass_ceramic_crown: { workType: 'AnatomicCrown', material: 'GCER' },
|
||||
pmma: { workType: 'AnatomicCrown', material: 'PMMA' },
|
||||
press_ceramic: { workType: 'AnatomicCrown', material: 'LS2' },
|
||||
peek_crown: { workType: 'AnatomicCrown', material: 'PEEK' },
|
||||
veneer_zirconia: { workType: 'Veneer', material: 'ZI' },
|
||||
veneer_ips_press: { workType: 'Veneer', material: 'LS2' },
|
||||
veneer_ips_cad: { workType: 'Veneer', material: 'LS2' },
|
||||
zirconia_overlay: { workType: 'AnatomicInlay', material: 'ZI' },
|
||||
ips_overlay: { workType: 'OverlayCrown', material: 'LS2' },
|
||||
};
|
||||
|
||||
export type ExocadTransferFailure = 'NOT_EXOCAD' | 'PATIENT_NAME_INCOMPLETE';
|
||||
|
||||
export class ExocadTransferError extends Error {
|
||||
constructor(readonly code: ExocadTransferFailure) {
|
||||
super(code);
|
||||
this.name = 'ExocadTransferError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Case-level values shared by every photographed November 2026 case.
|
||||
* Written only when the opened file already stores that exact value.
|
||||
*/
|
||||
const CONFIRMED_CASE_PARAMS: Record<string, string> = {
|
||||
AntagonistType: 'RegisteredJaws',
|
||||
ToothColor: '---',
|
||||
};
|
||||
|
||||
export type ExocadToothJob = {
|
||||
tooth: string;
|
||||
prosthesisTypeCode: string;
|
||||
selectionGroupId?: string;
|
||||
};
|
||||
|
||||
export type ExocadCaseInput = {
|
||||
caseId: string;
|
||||
clinicName: string;
|
||||
patientFirstName: string;
|
||||
patientLastName: string;
|
||||
dentistName: string;
|
||||
comment: string;
|
||||
dueDate: string | null;
|
||||
teeth: ExocadToothJob[];
|
||||
};
|
||||
|
||||
export type ExocadSkippedLine = {
|
||||
tooth: string;
|
||||
prosthesisTypeCode: string;
|
||||
reason: 'arch' | 'unmapped' | 'pontic';
|
||||
};
|
||||
|
||||
export type ExocadTransferResult = {
|
||||
treatmentId: number;
|
||||
created: boolean;
|
||||
skipped: ExocadSkippedLine[];
|
||||
/** `{date}_{practice}-{tray}` under the Exocad CAD-Data directory. */
|
||||
projectFolder: string;
|
||||
};
|
||||
|
||||
export type ExocadTransferOptions = {
|
||||
now?: string;
|
||||
projectGuid?: string;
|
||||
};
|
||||
|
||||
type ToothWrite = {
|
||||
toothId: string;
|
||||
workType: string;
|
||||
material: string;
|
||||
/**
|
||||
* Coping teeth only. A titanium custom abutment is still a Coping; the opened
|
||||
* file stores that as ImplantType CustomAbutment. Pontics and antagonists have
|
||||
* no ImplantType. Null means do not filter the donor by that parameter.
|
||||
*/
|
||||
implantType: 'CustomAbutment' | 'None' | null;
|
||||
};
|
||||
|
||||
/** Catalog code whose sheet label is "Custom Abutment (Titanium)". */
|
||||
const CUSTOM_ABUTMENT_CODE = 'customized_abutment';
|
||||
|
||||
function numberValue(value: unknown): number {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
/** Keep a leading calendar date. Anything else is left empty. */
|
||||
export function exocadDueDate(value: string | null | undefined): string | null {
|
||||
const match = /^(\d{4}-\d{2}-\d{2})/.exec(value?.trim() ?? '');
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/** Directory Exocad Save lists: `2026-11-12_00120-006`. */
|
||||
export function exocadProjectFolder(dateValue: string, practiceId: number, schaleId: number): string {
|
||||
const date = exocadDueDate(dateValue) ?? '0000-00-00';
|
||||
const practice = String(practiceId).padStart(5, '0');
|
||||
const tray = String(schaleId).padStart(3, '0');
|
||||
return `${date}_${practice}-${tray}`;
|
||||
}
|
||||
|
||||
function buildNotes(comment: string): string | null {
|
||||
const text = comment.trim();
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
/** Letters and numbers only, so "Yavari,Tehran" and "Ms.Maleki" share a token with the plain name. */
|
||||
function nameTokens(value: string): string[] {
|
||||
return value.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
||||
}
|
||||
|
||||
function coversTokens(candidate: string, tokens: string[]): boolean {
|
||||
if (tokens.length === 0) return false;
|
||||
const have = new Set(nameTokens(candidate));
|
||||
return tokens.every((token) => have.has(token));
|
||||
}
|
||||
|
||||
/**
|
||||
* DentalDB shows Name as the given name then the family name, and stores the
|
||||
* family name in `fname` and the given name in `lname`.
|
||||
*/
|
||||
function personParts(firstName: string, lastName: string): { given: string; family: string } | null {
|
||||
const given = firstName.trim();
|
||||
const family = lastName.trim();
|
||||
if (given && family) return { given, family };
|
||||
const parts = `${given} ${family}`
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.filter((part) => part.length > 0);
|
||||
if (parts.length < 2) return null;
|
||||
return { given: parts.slice(0, -1).join(' '), family: parts[parts.length - 1] };
|
||||
}
|
||||
|
||||
/** FDI opposite arch: 11↔41, 21↔31, and the same position in the other arch. */
|
||||
function oppositeFdi(tooth: string): string | null {
|
||||
const number = Number(tooth);
|
||||
if (!Number.isInteger(number)) return null;
|
||||
const quadrant = Math.floor(number / 10);
|
||||
const position = number % 10;
|
||||
if (position < 1 || position > 8) return null;
|
||||
const oppositeQuadrant: Record<number, number> = { 1: 4, 2: 3, 3: 2, 4: 1 };
|
||||
const target = oppositeQuadrant[quadrant];
|
||||
if (!target) return null;
|
||||
return String(target * 10 + position);
|
||||
}
|
||||
|
||||
function isArchTooth(tooth: string): boolean {
|
||||
const normalized = tooth.trim().toUpperCase();
|
||||
return normalized === 'UA' || normalized === 'LA';
|
||||
}
|
||||
|
||||
function isFdiTooth(tooth: string): boolean {
|
||||
return /^\d{1,2}$/.test(tooth.trim());
|
||||
}
|
||||
|
||||
function pairExists(db: SqliteQuery, workType: string, material: string): boolean {
|
||||
return db.all('SELECT id FROM ToothWork WHERE WorkTypeSN = ? AND MaterialSN = ? LIMIT 1', [workType, material]).length > 0;
|
||||
}
|
||||
|
||||
function planTeeth(db: SqliteQuery, jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: ExocadSkippedLine[] } {
|
||||
const groupMaterial = new Map<string, string>();
|
||||
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);
|
||||
}
|
||||
|
||||
const writes: ToothWrite[] = [];
|
||||
const skipped: ExocadSkippedLine[] = [];
|
||||
const byTooth = new Map<string, ExocadToothJob[]>();
|
||||
const toothOrder: string[] = [];
|
||||
for (const job of jobs) {
|
||||
const tooth = job.tooth.trim();
|
||||
const group = byTooth.get(tooth);
|
||||
if (group) group.push(job);
|
||||
else {
|
||||
byTooth.set(tooth, [job]);
|
||||
toothOrder.push(tooth);
|
||||
}
|
||||
}
|
||||
|
||||
for (const tooth of toothOrder) {
|
||||
const group = byTooth.get(tooth) ?? [];
|
||||
if (isArchTooth(tooth) || !isFdiTooth(tooth)) {
|
||||
const reason = isArchTooth(tooth) ? 'arch' : 'unmapped';
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const restoration = group.find((job) => MATERIAL_MATCH[job.prosthesisTypeCode]);
|
||||
if (restoration) {
|
||||
const mapped = MATERIAL_MATCH[restoration.prosthesisTypeCode];
|
||||
if (pairExists(db, mapped.workType, mapped.material)) {
|
||||
const abutment = group.some((job) => job.prosthesisTypeCode === CUSTOM_ABUTMENT_CODE);
|
||||
writes.push({
|
||||
toothId: tooth,
|
||||
workType: mapped.workType,
|
||||
material: mapped.material,
|
||||
implantType: mapped.workType === 'Coping' ? (abutment ? 'CustomAbutment' : 'None') : null,
|
||||
});
|
||||
} else {
|
||||
for (const job of group) {
|
||||
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 && pairExists(db, 'ReducedPontic', material)) {
|
||||
writes.push({ toothId: tooth, workType: 'ReducedPontic', material, implantType: null });
|
||||
} else {
|
||||
for (const job of group) {
|
||||
const reason = job === pontic ? (material ? 'unmapped' : 'pontic') : 'unmapped';
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
}
|
||||
|
||||
if (pairExists(db, 'Antagonist', 'Healthy')) {
|
||||
const occupied = new Set(writes.map((row) => row.toothId));
|
||||
const antagonists: ToothWrite[] = [];
|
||||
for (const row of writes) {
|
||||
const opposite = oppositeFdi(row.toothId);
|
||||
if (!opposite || occupied.has(opposite)) continue;
|
||||
antagonists.push({ toothId: opposite, workType: 'Antagonist', material: 'Healthy', implantType: null });
|
||||
occupied.add(opposite);
|
||||
}
|
||||
writes.push(...antagonists);
|
||||
}
|
||||
|
||||
writes.sort((left, right) => numberValue(left.toothId) - numberValue(right.toothId) || left.workType.localeCompare(right.workType));
|
||||
return { writes, skipped };
|
||||
}
|
||||
|
||||
function assertExocad(db: SqliteQuery): void {
|
||||
const rows = db.all(`SELECT name FROM sqlite_master WHERE type = 'table'`);
|
||||
const names = new Set(rows.map((row) => String(row[0] ?? '').toLowerCase()));
|
||||
const ready = REQUIRED_TABLES.every((name) => names.has(name.toLowerCase()));
|
||||
if (!ready) throw new ExocadTransferError('NOT_EXOCAD');
|
||||
const lab = db.all('SELECT id FROM laboratories WHERE id = ?', [EXOCAD_LAB_ID]);
|
||||
if (lab.length === 0) throw new ExocadTransferError('NOT_EXOCAD');
|
||||
}
|
||||
|
||||
/** Reject a SQLite file that is not a DentalDB database. Call this before remembering the file. */
|
||||
export function assertExocadDatabase(db: SqliteQuery): void {
|
||||
assertExocad(db);
|
||||
}
|
||||
|
||||
function clientRows(db: SqliteQuery): Array<{ practiceId: number; name: string }> {
|
||||
return db
|
||||
.all(
|
||||
'SELECT practice_id, name FROM clients WHERE lab_id = ? AND practice_id != ?',
|
||||
[EXOCAD_LAB_ID, EXOCAD_MULTIDIE_PRACTICE_ID],
|
||||
)
|
||||
.map((row) => ({ practiceId: numberValue(row[0]), name: row[1] == null ? '' : String(row[1]) }));
|
||||
}
|
||||
|
||||
function nextPracticeId(rows: Array<{ practiceId: number }>): number {
|
||||
const max = rows.reduce((highest, row) => Math.max(highest, row.practiceId), 0);
|
||||
const next = max + 1;
|
||||
return next === EXOCAD_MULTIDIE_PRACTICE_ID ? next + 1 : next;
|
||||
}
|
||||
|
||||
function insertClient(db: SqliteQuery, name: string): number {
|
||||
const practiceId = nextPracticeId(clientRows(db));
|
||||
db.run(
|
||||
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
|
||||
VALUES (?, ?, ?, '', '', '', '', '', '', 0)`,
|
||||
[EXOCAD_LAB_ID, practiceId, name],
|
||||
);
|
||||
return practiceId;
|
||||
}
|
||||
|
||||
type ClientChoice = { practiceId: number } | { createName: string };
|
||||
|
||||
function decideClient(rows: Array<{ practiceId: number; name: string }>, clinicName: string): ClientChoice {
|
||||
const wanted = clinicName.trim();
|
||||
if (!wanted) {
|
||||
const blank = rows.find((row) => row.name.trim() === '');
|
||||
if (blank) return { practiceId: blank.practiceId };
|
||||
return { createName: '' };
|
||||
}
|
||||
const exact = rows.filter((row) => row.name.trim().toLocaleLowerCase() === wanted.toLocaleLowerCase());
|
||||
if (exact.length === 1) return { practiceId: exact[0].practiceId };
|
||||
const tokens = nameTokens(wanted);
|
||||
const matches = rows.filter((row) => coversTokens(row.name, tokens));
|
||||
if (matches.length === 1) return { practiceId: matches[0].practiceId };
|
||||
return { createName: wanted };
|
||||
}
|
||||
|
||||
function matchingPatientId(
|
||||
db: SqliteQuery,
|
||||
practiceId: number,
|
||||
tokens: string[],
|
||||
): number | null {
|
||||
const rows = db.all(
|
||||
'SELECT patient_id, fname, lname FROM patients WHERE lab_id = ? AND practice_id = ?',
|
||||
[EXOCAD_LAB_ID, practiceId],
|
||||
);
|
||||
const matches = rows.filter((row) =>
|
||||
coversTokens(`${row[1] == null ? '' : String(row[1])} ${row[2] == null ? '' : String(row[2])}`, tokens),
|
||||
);
|
||||
if (matches.length !== 1) return null;
|
||||
return numberValue(matches[0][0]);
|
||||
}
|
||||
|
||||
function insertPatient(
|
||||
db: SqliteQuery,
|
||||
practiceId: number,
|
||||
parts: { given: string; family: string },
|
||||
): number {
|
||||
const rows = db.all(
|
||||
'SELECT patient_id FROM patients WHERE lab_id = ? AND practice_id = ?',
|
||||
[EXOCAD_LAB_ID, practiceId],
|
||||
);
|
||||
const patientId = rows.reduce((highest, row) => Math.max(highest, numberValue(row[0])), 0) + 1;
|
||||
db.run(
|
||||
`INSERT INTO patients (lab_id, practice_id, patient_id, fname, lname, dateOfBirth)
|
||||
VALUES (?, ?, ?, ?, ?, NULL)`,
|
||||
[EXOCAD_LAB_ID, practiceId, patientId, parts.family, parts.given],
|
||||
);
|
||||
return patientId;
|
||||
}
|
||||
|
||||
/** Match or create a client, including a one-word or empty clinic name. The patient still needs two name parts. */
|
||||
function resolveParties(
|
||||
db: SqliteQuery,
|
||||
input: ExocadCaseInput,
|
||||
): { practiceId: number; patientId: number } {
|
||||
const decision = decideClient(clientRows(db), input.clinicName);
|
||||
const parts = personParts(input.patientFirstName, input.patientLastName);
|
||||
const tokens = nameTokens(`${input.patientFirstName} ${input.patientLastName}`);
|
||||
|
||||
if ('createName' in decision) {
|
||||
if (!parts) throw new ExocadTransferError('PATIENT_NAME_INCOMPLETE');
|
||||
const practiceId = insertClient(db, decision.createName);
|
||||
return { practiceId, patientId: insertPatient(db, practiceId, parts) };
|
||||
}
|
||||
|
||||
const matched = matchingPatientId(db, decision.practiceId, tokens);
|
||||
if (matched != null) return { practiceId: decision.practiceId, patientId: matched };
|
||||
if (!parts) throw new ExocadTransferError('PATIENT_NAME_INCOMPLETE');
|
||||
return { practiceId: decision.practiceId, patientId: insertPatient(db, decision.practiceId, parts) };
|
||||
}
|
||||
|
||||
function deleteToothWork(db: SqliteQuery, treatmentId: number): void {
|
||||
const treatment = [treatmentId];
|
||||
db.run(
|
||||
`DELETE FROM DependentToothWorkParameters
|
||||
WHERE parent_param_id IN (
|
||||
SELECT textual.id FROM TextualToothWorkParameter textual
|
||||
JOIN ToothWorkParameters params ON params.id = textual.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?
|
||||
)`,
|
||||
treatment,
|
||||
);
|
||||
db.run(
|
||||
`DELETE FROM DependentOnNumericToothWorkParameters
|
||||
WHERE parent_param_id IN (
|
||||
SELECT numeric.id FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?
|
||||
)`,
|
||||
treatment,
|
||||
);
|
||||
db.run(
|
||||
`DELETE FROM TextualToothWorkParameter
|
||||
WHERE id IN (
|
||||
SELECT params.id FROM ToothWorkParameters params
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?
|
||||
)`,
|
||||
treatment,
|
||||
);
|
||||
db.run(
|
||||
`DELETE FROM NumericToothWorkParameter
|
||||
WHERE id IN (
|
||||
SELECT params.id FROM ToothWorkParameters params
|
||||
JOIN ToothWork work ON work.id = params.toothWork_id
|
||||
WHERE work.treatment_id = ?
|
||||
)`,
|
||||
treatment,
|
||||
);
|
||||
db.run(
|
||||
`DELETE FROM ToothWorkParameters
|
||||
WHERE toothWork_id IN (SELECT id FROM ToothWork WHERE treatment_id = ?)`,
|
||||
treatment,
|
||||
);
|
||||
db.run(
|
||||
`DELETE FROM ValuedMaterialParameters
|
||||
WHERE toothwork_id IN (SELECT id FROM ToothWork WHERE treatment_id = ?)`,
|
||||
treatment,
|
||||
);
|
||||
db.run('DELETE FROM ToothWork WHERE treatment_id = ?', treatment);
|
||||
}
|
||||
|
||||
type DependentCopy = {
|
||||
name: string | null;
|
||||
value: string | null;
|
||||
kind: number;
|
||||
};
|
||||
|
||||
type ParameterCopy = {
|
||||
customWdId: number | null;
|
||||
name: string | null;
|
||||
valueText: string | null;
|
||||
valueNumber: number | null;
|
||||
dependents: DependentCopy[];
|
||||
};
|
||||
|
||||
type MaterialSnapshot = {
|
||||
textual: ParameterCopy[];
|
||||
numeric: ParameterCopy[];
|
||||
};
|
||||
|
||||
function cellText(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function cellNumber(value: unknown): number | null {
|
||||
if (value == null || value === '') return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function pairKey(workType: string, material: string, implantType: string | null): string {
|
||||
return `${workType}\0${material}\0${implantType ?? ''}`;
|
||||
}
|
||||
|
||||
/** Fullest saved tooth of this pair. When implantValue is set, it must already use that ImplantType. */
|
||||
function findDonorId(db: SqliteQuery, workType: string, material: string, implantValue: string | null): number {
|
||||
const implantFilter = implantValue
|
||||
? `AND EXISTS (
|
||||
SELECT 1 FROM ToothWorkParameters implantParams
|
||||
JOIN TextualToothWorkParameter implantText ON implantText.id = implantParams.id
|
||||
WHERE implantParams.toothWork_id = work.id
|
||||
AND implantText.ParameterSN = 'ImplantType'
|
||||
AND implantText.ValueSN = ?
|
||||
)`
|
||||
: '';
|
||||
const donors = db.all(
|
||||
`SELECT work.id
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
WHERE work.WorkTypeSN = ? AND work.MaterialSN = ?
|
||||
${implantFilter}
|
||||
GROUP BY work.id
|
||||
ORDER BY COUNT(params.id) DESC, work.id DESC
|
||||
LIMIT 1`,
|
||||
implantValue ? [workType, material, implantValue] : [workType, material],
|
||||
);
|
||||
return numberValue(donors[0]?.[0]);
|
||||
}
|
||||
|
||||
function readDependents(db: SqliteQuery, table: string, parentId: number): DependentCopy[] {
|
||||
return db
|
||||
.all(
|
||||
`SELECT dep_param_string, dep_param_value_string, dep_param_kind FROM ${table} WHERE parent_param_id = ?`,
|
||||
[parentId],
|
||||
)
|
||||
.map((row) => ({
|
||||
name: cellText(row[0]),
|
||||
value: cellText(row[1]),
|
||||
kind: cellNumber(row[2]) ?? 0,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter rows copied from a saved tooth of this work type and material.
|
||||
* A Coping donor is chosen by ImplantType when the file already has that value.
|
||||
* CustomAbutment is never written unless a saved tooth already uses it.
|
||||
* Shade stays off this copy; the case shade is the separate blank ToothColor.
|
||||
*/
|
||||
function readMaterialSnapshot(
|
||||
db: SqliteQuery,
|
||||
workType: string,
|
||||
material: string,
|
||||
implantType: 'CustomAbutment' | 'None' | null,
|
||||
): MaterialSnapshot | null {
|
||||
const exact = implantType ? findDonorId(db, workType, material, implantType) : 0;
|
||||
const plainFallback = !exact && implantType === 'CustomAbutment' ? findDonorId(db, workType, material, 'None') : 0;
|
||||
const chosenId = exact || plainFallback || findDonorId(db, workType, material, null);
|
||||
if (!chosenId) return null;
|
||||
|
||||
const textual = db
|
||||
.all(
|
||||
`SELECT params.custom_wd_id, textual.ParameterSN, textual.ValueSN, textual.id
|
||||
FROM TextualToothWorkParameter textual
|
||||
JOIN ToothWorkParameters params ON params.id = textual.id
|
||||
WHERE params.toothWork_id = ?`,
|
||||
[chosenId],
|
||||
)
|
||||
.map((row) => ({
|
||||
customWdId: cellNumber(row[0]),
|
||||
name: cellText(row[1]),
|
||||
valueText: cellText(row[2]),
|
||||
valueNumber: null,
|
||||
dependents: readDependents(db, 'DependentToothWorkParameters', numberValue(row[3])),
|
||||
}));
|
||||
const numeric = db
|
||||
.all(
|
||||
`SELECT params.custom_wd_id, numeric.ParameterSN, numeric.value, numeric.id
|
||||
FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
WHERE params.toothWork_id = ?`,
|
||||
[chosenId],
|
||||
)
|
||||
.map((row) => ({
|
||||
customWdId: cellNumber(row[0]),
|
||||
name: cellText(row[1]),
|
||||
valueText: null,
|
||||
valueNumber: cellNumber(row[2]),
|
||||
dependents: readDependents(db, 'DependentOnNumericToothWorkParameters', numberValue(row[3])),
|
||||
}));
|
||||
if (!exact && implantType) {
|
||||
const copied = textual.find((row) => row.name === 'ImplantType')?.valueText;
|
||||
const keepPlain = implantType === 'CustomAbutment' && copied === 'None';
|
||||
if (!keepPlain) {
|
||||
return { textual: textual.filter((row) => row.name !== 'ImplantType'), numeric };
|
||||
}
|
||||
}
|
||||
return { textual, numeric };
|
||||
}
|
||||
|
||||
function materialSnapshots(db: SqliteQuery, writes: ToothWrite[]): Map<string, MaterialSnapshot | null> {
|
||||
const snapshots = new Map<string, MaterialSnapshot | null>();
|
||||
for (const write of writes) {
|
||||
const key = pairKey(write.workType, write.material, write.implantType);
|
||||
if (snapshots.has(key)) continue;
|
||||
snapshots.set(key, readMaterialSnapshot(db, write.workType, write.material, write.implantType));
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
function insertParameter(db: SqliteQuery, toothWorkId: number, row: ParameterCopy, kind: 'textual' | 'numeric'): void {
|
||||
db.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (?, ?)', [row.customWdId, toothWorkId]);
|
||||
const id = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
if (kind === 'textual') {
|
||||
db.run('INSERT INTO TextualToothWorkParameter (id, ParameterSN, ValueSN) VALUES (?, ?, ?)', [
|
||||
id,
|
||||
row.name,
|
||||
row.valueText,
|
||||
]);
|
||||
for (const dependent of row.dependents) {
|
||||
db.run(
|
||||
`INSERT INTO DependentToothWorkParameters
|
||||
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[id, dependent.name, dependent.value, dependent.kind],
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
db.run('INSERT INTO NumericToothWorkParameter (id, ParameterSN, value) VALUES (?, ?, ?)', [
|
||||
id,
|
||||
row.name,
|
||||
row.valueNumber,
|
||||
]);
|
||||
for (const dependent of row.dependents) {
|
||||
db.run(
|
||||
`INSERT INTO DependentOnNumericToothWorkParameters
|
||||
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[id, dependent.name, dependent.value, dependent.kind],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function applyMaterialSnapshot(db: SqliteQuery, toothWorkId: number, snapshot: MaterialSnapshot): void {
|
||||
for (const row of snapshot.textual) insertParameter(db, toothWorkId, row, 'textual');
|
||||
for (const row of snapshot.numeric) insertParameter(db, toothWorkId, row, 'numeric');
|
||||
}
|
||||
|
||||
function insertTeeth(
|
||||
db: SqliteQuery,
|
||||
treatmentId: number,
|
||||
writes: ToothWrite[],
|
||||
snapshots: Map<string, MaterialSnapshot | null>,
|
||||
): void {
|
||||
for (const row of writes) {
|
||||
db.run(
|
||||
`INSERT INTO ToothWork (ToothId, flags, WorkTypeSN, MaterialSN, treatment_id)
|
||||
VALUES (?, 0, ?, ?, ?)`,
|
||||
[row.toothId, row.workType, row.material, treatmentId],
|
||||
);
|
||||
const toothWorkId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
const snapshot = snapshots.get(pairKey(row.workType, row.material, row.implantType));
|
||||
if (snapshot) applyMaterialSnapshot(db, toothWorkId, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
function tableExists(db: SqliteQuery, name: string): boolean {
|
||||
return (
|
||||
db.all(`SELECT name FROM sqlite_master WHERE type = 'table' AND lower(name) = lower(?)`, [name]).length > 0
|
||||
);
|
||||
}
|
||||
|
||||
/** Copy the blank shade and the two-model scan mode when this file already uses those values. */
|
||||
function copyConfirmedCaseParameters(db: SqliteQuery, treatmentId: number): void {
|
||||
if (!tableExists(db, 'TreatmentValuedParameters')) return;
|
||||
for (const [paramSn, value] of Object.entries(CONFIRMED_CASE_PARAMS)) {
|
||||
const found = db.all(
|
||||
`SELECT PARAM_TYPE FROM TreatmentValuedParameters WHERE ParamSN = ? AND ValueSN = ? LIMIT 1`,
|
||||
[paramSn, value],
|
||||
);
|
||||
if (found.length === 0) continue;
|
||||
db.run('DELETE FROM TreatmentValuedParameters WHERE treatment_id = ? AND ParamSN = ?', [treatmentId, paramSn]);
|
||||
db.run(
|
||||
`INSERT INTO TreatmentValuedParameters (PARAM_TYPE, ParamSN, ValueSN, treatment_id) VALUES (?, ?, ?, ?)`,
|
||||
[cellText(found[0][0]) ?? 'TEXTUAL', paramSn, value, treatmentId],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Assign a technician only when the file has exactly one, so a multi-technician lab is not guessed. */
|
||||
function assignSoleTechnician(db: SqliteQuery, treatmentId: number): void {
|
||||
if (!treatmentHasColumn(db, 'tech_lab_id') || !treatmentHasColumn(db, 'tech_tech_id')) return;
|
||||
if (!tableExists(db, 'technicians')) return;
|
||||
const rows = db.all('SELECT lab_id, tech_id FROM technicians');
|
||||
if (rows.length !== 1) return;
|
||||
db.run('UPDATE Treatment SET tech_lab_id = ?, tech_tech_id = ? WHERE treatment_id = ?', [
|
||||
numberValue(rows[0][0]),
|
||||
numberValue(rows[0][1]),
|
||||
treatmentId,
|
||||
]);
|
||||
}
|
||||
|
||||
function treatmentHasColumn(db: SqliteQuery, column: string): boolean {
|
||||
const rows = db.all('PRAGMA table_info(Treatment)');
|
||||
return rows.some((row) => String(row[1] ?? '').toLowerCase() === column.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill an empty workParamsSHA from the newest saved case whose file name ends
|
||||
* with WorkParamsDB.xml, not WorkParamsDB-EndoCrown.xml. Exocad loads
|
||||
* WorkParamsInfo by workParamInfoId. A null id is the read-only project warning
|
||||
* and the tooth-click crash. Each saved case has its own info row.
|
||||
*/
|
||||
function embedMaterialConfiguration(db: SqliteQuery, treatmentId: number): void {
|
||||
if (!treatmentHasColumn(db, 'workParamsSHA') || !treatmentHasColumn(db, 'workParamInfoId')) return;
|
||||
const tables = db.all(`SELECT name FROM sqlite_master WHERE type = 'table'`);
|
||||
const names = new Set(tables.map((row) => String(row[0] ?? '').toLowerCase()));
|
||||
if (!names.has('workparamsinfo') || !names.has('workparamsinfolocal')) return;
|
||||
|
||||
const current = db.all(
|
||||
'SELECT workParamsSHA, workParamInfoId FROM Treatment WHERE treatment_id = ?',
|
||||
[treatmentId],
|
||||
);
|
||||
const currentSha = String(current[0]?.[0] ?? '').trim();
|
||||
const currentInfo = numberValue(current[0]?.[1]);
|
||||
if (currentSha && currentInfo > 0) return;
|
||||
|
||||
const donor = db.all(
|
||||
`SELECT t.workParamsSHA, i.workParamsDataHash, i.lastModificationDate, l.fileName, t.workParamInfoId
|
||||
FROM Treatment t
|
||||
JOIN WorkParamsInfo i ON i.id = t.workParamInfoId
|
||||
JOIN WorkParamsInfoLocal l ON l.id = i.id
|
||||
WHERE t.treatment_id != ?
|
||||
AND t.workParamsSHA IS NOT NULL
|
||||
AND trim(t.workParamsSHA) != ''
|
||||
AND l.fileName LIKE '%WorkParamsDB.xml'
|
||||
ORDER BY t.treatment_id DESC
|
||||
LIMIT 1`,
|
||||
[treatmentId],
|
||||
);
|
||||
const source = donor[0];
|
||||
if (!source || source[3] == null) return;
|
||||
|
||||
db.run(
|
||||
`INSERT INTO WorkParamsInfo (workParamsDataHash, lastModificationDate) VALUES (?, ?)`,
|
||||
[source[1] == null ? null : String(source[1]), source[2] == null ? null : String(source[2])],
|
||||
);
|
||||
const newId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
db.run('INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (?, ?)', [newId, String(source[3])]);
|
||||
db.run(
|
||||
'UPDATE Treatment SET workParamsSHA = ?, workParamInfoId = ? WHERE treatment_id = ?',
|
||||
[String(source[0]), newId, treatmentId],
|
||||
);
|
||||
}
|
||||
|
||||
function nextSchaleId(db: SqliteQuery, practiceId: number): number {
|
||||
if (!treatmentHasColumn(db, 't_schaleId')) return 1;
|
||||
const rows = db.all(
|
||||
'SELECT MAX(t_schaleId) FROM Treatment WHERE practice_lab_id = ? AND practice_pr_id = ?',
|
||||
[EXOCAD_LAB_ID, practiceId],
|
||||
);
|
||||
return numberValue(rows[0]?.[0]) + 1;
|
||||
}
|
||||
|
||||
function storedSchaleId(db: SqliteQuery, treatmentId: number): number | null {
|
||||
if (!treatmentHasColumn(db, 't_schaleId')) return null;
|
||||
const rows = db.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [treatmentId]);
|
||||
const value = numberValue(rows[0]?.[0]);
|
||||
return value > 0 ? value : null;
|
||||
}
|
||||
|
||||
function writeSchaleId(db: SqliteQuery, treatmentId: number, schaleId: number): void {
|
||||
if (!treatmentHasColumn(db, 't_schaleId')) return;
|
||||
db.run('UPDATE Treatment SET t_schaleId = ? WHERE treatment_id = ?', [schaleId, treatmentId]);
|
||||
}
|
||||
|
||||
function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTransferOptions): ExocadTransferResult {
|
||||
const { practiceId, patientId } = resolveParties(db, input);
|
||||
const due = exocadDueDate(input.dueDate);
|
||||
const now = options.now ?? new Date().toISOString();
|
||||
const { writes, skipped } = planTeeth(db, input.teeth);
|
||||
const notes = buildNotes(input.comment);
|
||||
const snapshots = materialSnapshots(db, writes);
|
||||
const header = [
|
||||
EXOCAD_LAB_ID,
|
||||
practiceId,
|
||||
EXOCAD_LAB_ID,
|
||||
practiceId,
|
||||
patientId,
|
||||
now,
|
||||
notes,
|
||||
due,
|
||||
];
|
||||
|
||||
const existing = db.all('SELECT treatment_id FROM Treatment WHERE importedOrderId = ?', [input.caseId]);
|
||||
if (existing.length > 0) {
|
||||
const treatmentId = numberValue(existing[0][0]);
|
||||
const keptSchale = storedSchaleId(db, treatmentId);
|
||||
const schaleId = keptSchale ?? nextSchaleId(db, practiceId);
|
||||
db.run(
|
||||
`UPDATE Treatment SET
|
||||
practice_lab_id = ?,
|
||||
practice_pr_id = ?,
|
||||
patient_lab_id = ?,
|
||||
patient_practice_id = ?,
|
||||
patient_patient_id = ?,
|
||||
t_date = ?,
|
||||
t_Notes = ?,
|
||||
t_duedate = ?
|
||||
WHERE treatment_id = ?`,
|
||||
[...header, treatmentId],
|
||||
);
|
||||
if (keptSchale == null) writeSchaleId(db, treatmentId, schaleId);
|
||||
deleteToothWork(db, treatmentId);
|
||||
insertTeeth(db, treatmentId, writes, snapshots);
|
||||
copyConfirmedCaseParameters(db, treatmentId);
|
||||
assignSoleTechnician(db, treatmentId);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: false, skipped, projectFolder: exocadProjectFolder(now, practiceId, schaleId) };
|
||||
}
|
||||
|
||||
const schaleId = nextSchaleId(db, practiceId);
|
||||
const projectGuid = options.projectGuid ?? crypto.randomUUID();
|
||||
db.run(
|
||||
`INSERT INTO Treatment (
|
||||
practice_lab_id, practice_pr_id,
|
||||
patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, t_Notes, t_duedate, flags, projectGUID, importedOrderId
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
|
||||
[...header, projectGuid, input.caseId],
|
||||
);
|
||||
const treatmentId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
writeSchaleId(db, treatmentId, schaleId);
|
||||
insertTeeth(db, treatmentId, writes, snapshots);
|
||||
copyConfirmedCaseParameters(db, treatmentId);
|
||||
assignSoleTechnician(db, treatmentId);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: true, skipped, projectFolder: exocadProjectFolder(now, practiceId, schaleId) };
|
||||
}
|
||||
|
||||
/** Insert or update one DentalDB case. Disk stays unchanged until the caller exports the database. */
|
||||
export function transferCaseToExocad(
|
||||
db: SqliteQuery,
|
||||
input: ExocadCaseInput,
|
||||
options: ExocadTransferOptions = {},
|
||||
): ExocadTransferResult {
|
||||
assertExocad(db);
|
||||
db.run('BEGIN');
|
||||
try {
|
||||
const result = writeCase(db, input, options);
|
||||
db.run('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
db.run('ROLLBACK');
|
||||
} catch {
|
||||
// The transaction is already closed.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { ExocadTransferError } from '@/components/local-db/exocadTransfer';
|
||||
import { sqliteFailureCode } from '@/components/local-db/sqliteSql';
|
||||
|
||||
type LocalDbTranslator = (key: string) => string;
|
||||
|
||||
/** Map a local-database failure to a `localDb` message. The raw engine text stays off the screen. */
|
||||
export function localDbErrorText(
|
||||
error: unknown,
|
||||
t: LocalDbTranslator,
|
||||
fallback: 'openFailed' | 'applyFailed' | 'loadFailed' | 'sendRolledBack',
|
||||
): string {
|
||||
if (error instanceof ExocadTransferError) {
|
||||
if (error.code === 'PATIENT_NAME_INCOMPLETE') return t('patientNameIncomplete');
|
||||
return t('notExocad');
|
||||
}
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
if (message && sqliteFailureCode(message) === 'conflict') return t('conflict');
|
||||
return t(fallback);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { SqliteCell, SqliteQuery } from '@/components/local-db/sqliteSql';
|
||||
import type { Database, SqlValue, Statement } from 'sql.js';
|
||||
|
||||
const WASM_URL = '/sql-wasm-browser.wasm';
|
||||
|
||||
let sqlPromise: Promise<{ Database: new (data?: ArrayLike<number> | null) => Database }> | null =
|
||||
null;
|
||||
|
||||
async function loadSqlJs() {
|
||||
if (!sqlPromise) {
|
||||
sqlPromise = (async () => {
|
||||
const imported = await import('sql.js');
|
||||
return imported.default({
|
||||
locateFile: () => WASM_URL,
|
||||
});
|
||||
})();
|
||||
}
|
||||
return sqlPromise;
|
||||
}
|
||||
|
||||
function asQuery(db: Database): SqliteQuery {
|
||||
return {
|
||||
all(sql: string, params: Array<string | number | null> = []): SqliteCell[][] {
|
||||
const stmt: Statement = db.prepare(sql);
|
||||
if (params.length > 0) stmt.bind(params as SqlValue[]);
|
||||
const rows: SqliteCell[][] = [];
|
||||
while (stmt.step()) rows.push(stmt.get());
|
||||
stmt.free();
|
||||
return rows;
|
||||
},
|
||||
run(sql: string, params: Array<string | number | null> = []) {
|
||||
db.run(sql, params as SqlValue[]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** In-memory SQLite database. Disk is unchanged until the caller writes `exportBytes()`. */
|
||||
export class LocalSqlite {
|
||||
private constructor(private readonly db: Database) {}
|
||||
|
||||
static async open(bytes: Uint8Array): Promise<LocalSqlite> {
|
||||
const SQL = await loadSqlJs();
|
||||
return new LocalSqlite(new SQL.Database(bytes));
|
||||
}
|
||||
|
||||
execute<T>(fn: (query: SqliteQuery) => T): T {
|
||||
return fn(asQuery(this.db));
|
||||
}
|
||||
|
||||
exportBytes(): Uint8Array {
|
||||
const exported = this.db.export();
|
||||
return new Uint8Array(exported);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sqliteFailureCode } from './sqliteSql';
|
||||
|
||||
describe('sqliteFailureCode', () => {
|
||||
it('maps a unique violation and leaves other failures generic', () => {
|
||||
expect(sqliteFailureCode('UNIQUE constraint failed: people.name')).toBe('conflict');
|
||||
expect(sqliteFailureCode('no such table: missing')).toBe('failed');
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
export type SqliteCell = string | number | null | Uint8Array;
|
||||
|
||||
export type SqliteQuery = {
|
||||
all(sql: string, params?: Array<string | number | null>): SqliteCell[][];
|
||||
run(sql: string, params?: Array<string | number | null>): void;
|
||||
};
|
||||
|
||||
/** Map a SQLite engine message to a stable code. The raw text stays off the screen. */
|
||||
export function sqliteFailureCode(message: string): 'conflict' | 'failed' {
|
||||
if (/unique constraint failed/i.test(message)) return 'conflict';
|
||||
return 'failed';
|
||||
}
|
||||
@@ -26,10 +26,13 @@ import {
|
||||
formatPatientName,
|
||||
} from '@/components/lab/caseDetailUtils';
|
||||
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
|
||||
import { browserCanWriteLocalFile } from '@/components/local-db/browserFile';
|
||||
import { ExocadTransferError, type ExocadCaseInput } from '@/components/local-db/exocadTransfer';
|
||||
import { localDbErrorText } from '@/components/local-db/localDbErrors';
|
||||
import { useLocalDbSession } from '@/components/ui/local-db/LocalDbSessionProvider';
|
||||
import {
|
||||
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';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
@@ -77,15 +80,15 @@ function caseSheetLineNotes(labCase: LabCaseDetail): string[] {
|
||||
return notes;
|
||||
}
|
||||
|
||||
function toExocadCase(labCase: LabCaseDetail): ExocadCaseInput {
|
||||
function toExocadCase(labCase: LabCaseDetail, comment: string): ExocadCaseInput {
|
||||
return {
|
||||
caseId: labCase.id,
|
||||
clinicName: labCase.clinic.name,
|
||||
patientFirstName: labCase.patient.firstName,
|
||||
patientLastName: labCase.patient.lastName,
|
||||
dentistName: labCase.referringDentistName?.trim() ?? '',
|
||||
comment: labCase.detail?.comment?.trim() ?? '',
|
||||
comment,
|
||||
dueDate: labCase.dueDate,
|
||||
toothShadeCode: labCase.toothShadeCode ?? null,
|
||||
teeth: labCase.toothProsthesis.map((row) => ({
|
||||
tooth: row.tooth,
|
||||
prosthesisTypeCode: row.prosthesisTypeCode,
|
||||
@@ -304,7 +307,6 @@ export function CaseDetailPanel({
|
||||
}: CaseDetailPanelProps) {
|
||||
const t = useTranslations('cases');
|
||||
const tBilling = useTranslations('billing');
|
||||
const tLocal = useTranslations('localDb');
|
||||
const tTreatment = useTranslations('treatment');
|
||||
const tComments = useTranslations('caseComments');
|
||||
const tErrors = useTranslations('errors');
|
||||
@@ -331,7 +333,7 @@ export function CaseDetailPanel({
|
||||
);
|
||||
const messages = useMessages();
|
||||
const toast = useToast();
|
||||
const localDb = useLocalDbSession();
|
||||
const exocadExport = useExocadExportFolder();
|
||||
const confirm = useConfirm();
|
||||
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
|
||||
const sectionCounts = useCaseSectionCounts(labCase.id, section);
|
||||
@@ -340,7 +342,6 @@ export function CaseDetailPanel({
|
||||
);
|
||||
const [downloadingPdf, setDownloadingPdf] = useState(false);
|
||||
const [sheetMenuOpen, setSheetMenuOpen] = useState(false);
|
||||
const [canWriteLocalFile, setCanWriteLocalFile] = useState(false);
|
||||
const sheetMenuRef = useRef<HTMLDivElement>(null);
|
||||
const [externalCodeDraft, setExternalCodeDraft] = useState(labCase.externalCode ?? '');
|
||||
|
||||
@@ -348,10 +349,6 @@ export function CaseDetailPanel({
|
||||
setExternalCodeDraft(labCase.externalCode ?? '');
|
||||
}, [labCase.id, labCase.externalCode]);
|
||||
|
||||
useEffect(() => {
|
||||
setCanWriteLocalFile(browserCanWriteLocalFile());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sheetMenuOpen) return;
|
||||
function onPointerDown(event: MouseEvent) {
|
||||
@@ -465,8 +462,6 @@ export function CaseDetailPanel({
|
||||
}
|
||||
|
||||
async function onSendToExocad() {
|
||||
const connected = await localDb.requestConnection();
|
||||
if (!connected) return;
|
||||
let comment = labCase.detail?.comment?.trim() ?? '';
|
||||
try {
|
||||
const listed = await caseCommentsApi.list(labCase.id);
|
||||
@@ -478,39 +473,35 @@ export function CaseDetailPanel({
|
||||
} catch {
|
||||
comment = labCase.detail?.comment?.trim() ?? '';
|
||||
}
|
||||
let result;
|
||||
let project;
|
||||
try {
|
||||
result = localDb.transferCase({ ...toExocadCase(labCase), comment });
|
||||
project = buildExocadDentalProject(toExocadCase(labCase, comment));
|
||||
} catch (caught) {
|
||||
if (caught instanceof ExocadTransferError && caught.code === 'NOT_EXOCAD') await localDb.abandon();
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'sendRolledBack'));
|
||||
toast.showError(exocadExportErrorText(caught, t, 'exportFailed'));
|
||||
return;
|
||||
}
|
||||
const ready = await exocadExport.requestFolder();
|
||||
if (!ready) return;
|
||||
try {
|
||||
await localDb.apply();
|
||||
const id = String(result.treatmentId);
|
||||
if (!labCase.externalCode?.trim() && canEditImportant) {
|
||||
onExternalCodeChange?.(id);
|
||||
await exocadExport.writeProjectFile(project.fileName, project.xml);
|
||||
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', {
|
||||
lines: project.skipped
|
||||
.map((line) => `${line.tooth} ${line.prosthesisTypeCode}`)
|
||||
.join(', '),
|
||||
}),
|
||||
);
|
||||
}
|
||||
const saved = result.created
|
||||
? t('sendToExocadSaved', { id })
|
||||
: t('sendToExocadUpdated', { id });
|
||||
const skipped =
|
||||
result.skipped.length > 0
|
||||
? t('sendToExocadSkipped', {
|
||||
lines: result.skipped.map((line) => `${line.tooth} ${line.prosthesisTypeCode}`).join(', '),
|
||||
})
|
||||
: '';
|
||||
toast.showSuccess(saved);
|
||||
try {
|
||||
const folderReady = await localDb.ensureProjectFolder(result.projectFolder);
|
||||
if (!folderReady) toast.showInfo(t('sendToExocadFolderMissing'));
|
||||
} catch {
|
||||
toast.showInfo(t('sendToExocadFolderMissing'));
|
||||
}
|
||||
if (skipped) toast.showInfo(skipped);
|
||||
} catch (caught) {
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
|
||||
if (isExocadFolderGoneError(caught)) await exocadExport.abandon();
|
||||
toast.showError(exocadExportErrorText(caught, t, 'folderWriteFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,8 +538,9 @@ export function CaseDetailPanel({
|
||||
4,
|
||||
Math.max(
|
||||
1,
|
||||
[Boolean(canStop && onStop), Boolean(canSend && onSend), canWriteLocalFile, true].filter(Boolean)
|
||||
.length,
|
||||
[Boolean(canStop && onStop), Boolean(canSend && onSend), exocadExport.canExport, true].filter(
|
||||
Boolean,
|
||||
).length,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -733,7 +725,7 @@ export function CaseDetailPanel({
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{canWriteLocalFile ? (
|
||||
{exocadExport.canExport ? (
|
||||
<div className="min-w-0">
|
||||
<CaseLifecycleButton
|
||||
variant="outline"
|
||||
@@ -773,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} />
|
||||
|
||||
80
frontend/src/components/ui/lab/ExocadExportFolderDialog.tsx
Normal file
80
frontend/src/components/ui/lab/ExocadExportFolderDialog.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import {
|
||||
ResponsiveDialogOverlay,
|
||||
ResponsiveDialogPanel,
|
||||
} from '@/components/ui/shared/ResponsiveDialog';
|
||||
import {
|
||||
isPickerCancel,
|
||||
pickExocadExportFolder,
|
||||
type ExocadDirectoryHandle,
|
||||
} from '@/components/lab/exocad/exocadExportFolder';
|
||||
|
||||
type ExocadExportFolderDialogProps = {
|
||||
currentFolderName?: string | null;
|
||||
onCancel: () => void;
|
||||
onOpened: (handle: ExocadDirectoryHandle) => Promise<void>;
|
||||
};
|
||||
|
||||
export function ExocadExportFolderDialog({
|
||||
currentFolderName,
|
||||
onCancel,
|
||||
onOpened,
|
||||
}: ExocadExportFolderDialogProps) {
|
||||
const t = useTranslations('cases');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function onBrowse() {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
const handle = await pickExocadExportFolder();
|
||||
await onOpened(handle);
|
||||
} catch (caught) {
|
||||
if (isPickerCancel(caught)) return;
|
||||
setError(t('sendToExocadFolderOpenFailed'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ResponsiveDialogOverlay onBackdropClick={onCancel}>
|
||||
<ResponsiveDialogPanel
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="exocad-export-folder-title"
|
||||
maxWidthClass="sm:max-w-lg"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 id="exocad-export-folder-title" className="text-lg font-semibold text-text-primary">
|
||||
{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()}>
|
||||
{currentFolderName ? t('sendToExocadChangeFolder') : t('sendToExocadBrowseFolder')}
|
||||
</Button>
|
||||
{error ? (
|
||||
<p className="text-sm text-red-600" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</ResponsiveDialogPanel>
|
||||
</ResponsiveDialogOverlay>
|
||||
);
|
||||
}
|
||||
165
frontend/src/components/ui/lab/ExocadExportFolderProvider.tsx
Normal file
165
frontend/src/components/ui/lab/ExocadExportFolderProvider.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import {
|
||||
browserCanWriteExocadExport,
|
||||
forgetExocadExportFolder,
|
||||
preloadExocadExportFolder,
|
||||
reopenStoredExocadExportFolder,
|
||||
writeExocadDentalProjectFile,
|
||||
type ExocadDirectoryHandle,
|
||||
} from '@/components/lab/exocad/exocadExportFolder';
|
||||
import { ExocadExportFolderDialog } from '@/components/ui/lab/ExocadExportFolderDialog';
|
||||
|
||||
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 it is gone or permission is revoked. */
|
||||
abandon: () => Promise<void>;
|
||||
};
|
||||
|
||||
const ExocadExportFolderContext = createContext<ExocadExportFolderValue | null>(null);
|
||||
|
||||
export function useExocadExportFolder(): ExocadExportFolderValue {
|
||||
const value = useContext(ExocadExportFolderContext);
|
||||
if (!value) {
|
||||
throw new Error('ExocadExportFolderProvider is missing');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function ExocadExportFolderProvider({ children }: { children: ReactNode }) {
|
||||
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();
|
||||
}, []);
|
||||
|
||||
const writeProjectFile = useCallback(async (fileName: string, xml: string) => {
|
||||
const folder = folderRef.current;
|
||||
if (!folder) throw new Error('FOLDER_NOT_OPEN');
|
||||
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 () => {
|
||||
if (folderRef.current) return true;
|
||||
try {
|
||||
const restored = browserCanWriteExocadExport() ? await reopenStoredExocadExportFolder() : null;
|
||||
if (restored) {
|
||||
adoptFolder(restored);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
folderRef.current = null;
|
||||
setFolderName(null);
|
||||
await forgetExocadExportFolder();
|
||||
}
|
||||
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,
|
||||
folderName,
|
||||
resolveFolderName,
|
||||
requestFolder,
|
||||
changeFolder,
|
||||
writeProjectFile,
|
||||
abandon,
|
||||
}),
|
||||
[
|
||||
abandon,
|
||||
canExport,
|
||||
changeFolder,
|
||||
folderName,
|
||||
requestFolder,
|
||||
resolveFolderName,
|
||||
writeProjectFile,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<ExocadExportFolderContext.Provider value={value}>
|
||||
{children}
|
||||
{connectOpen ? (
|
||||
<ExocadExportFolderDialog
|
||||
currentFolderName={folderName}
|
||||
onCancel={() => finishConnect(false)}
|
||||
onOpened={async (handle) => {
|
||||
adoptFolder(handle);
|
||||
finishConnect(true);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</ExocadExportFolderContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import {
|
||||
ResponsiveDialogOverlay,
|
||||
ResponsiveDialogPanel,
|
||||
} from '@/components/ui/shared/ResponsiveDialog';
|
||||
import type { DatabaseSink } from '@/components/local-db/browserFile';
|
||||
import { LocalDbOpenControls } from '@/components/ui/local-db/LocalDbOpenControls';
|
||||
|
||||
type LocalDbConnectDialogProps = {
|
||||
onCancel: () => void;
|
||||
onOpened: (sink: DatabaseSink) => Promise<void>;
|
||||
};
|
||||
|
||||
export function LocalDbConnectDialog({ onCancel, onOpened }: LocalDbConnectDialogProps) {
|
||||
const t = useTranslations('cases');
|
||||
|
||||
return (
|
||||
<ResponsiveDialogOverlay onBackdropClick={onCancel}>
|
||||
<ResponsiveDialogPanel
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="exocad-connect-title"
|
||||
maxWidthClass="sm:max-w-lg"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 id="exocad-connect-title" className="text-lg font-semibold text-text-primary">
|
||||
{t('sendToExocadConnectTitle')}
|
||||
</h2>
|
||||
<DialogCloseButton onClick={onCancel} />
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-text-secondary">{t('sendToExocadCloseHint')}</p>
|
||||
<p className="mt-2 text-sm text-text-secondary">{t('sendToExocadExperimentalWarning')}</p>
|
||||
<div className="mt-4">
|
||||
<LocalDbOpenControls onOpened={onOpened} />
|
||||
</div>
|
||||
</ResponsiveDialogPanel>
|
||||
</ResponsiveDialogOverlay>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import {
|
||||
isPickerCancel,
|
||||
openWithBrowserPicker,
|
||||
type DatabaseSink,
|
||||
} from '@/components/local-db/browserFile';
|
||||
import { localDbErrorText } from '@/components/local-db/localDbErrors';
|
||||
|
||||
type LocalDbOpenControlsProps = {
|
||||
onOpened: (sink: DatabaseSink) => Promise<void>;
|
||||
};
|
||||
|
||||
/** Chrome and Edge only: the picked file is overwritten in place. */
|
||||
export function LocalDbOpenControls({ onOpened }: LocalDbOpenControlsProps) {
|
||||
const t = useTranslations('localDb');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function onBrowse() {
|
||||
setError('');
|
||||
let sink;
|
||||
try {
|
||||
sink = await openWithBrowserPicker();
|
||||
} catch (caught) {
|
||||
if (isPickerCancel(caught)) return;
|
||||
setError(t('openFailed'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await onOpened(sink);
|
||||
} catch (caught) {
|
||||
setError(localDbErrorText(caught, t, 'loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" onClick={() => onBrowse()}>
|
||||
{t('browse')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-red-600" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import {
|
||||
assertExocadDatabase,
|
||||
transferCaseToExocad,
|
||||
type ExocadCaseInput,
|
||||
type ExocadTransferResult,
|
||||
} from '@/components/local-db/exocadTransfer';
|
||||
import {
|
||||
browserCanWriteLocalFile,
|
||||
browserDatabaseStillExists,
|
||||
ensureExocadProjectDirectory,
|
||||
forgetBrowserDatabase,
|
||||
preloadBrowserHandle,
|
||||
reopenStoredBrowserFile,
|
||||
type DatabaseSink,
|
||||
} from '@/components/local-db/browserFile';
|
||||
import { LocalSqlite } from '@/components/local-db/sqliteSession';
|
||||
import { LocalDbConnectDialog } from '@/components/ui/local-db/LocalDbConnectDialog';
|
||||
|
||||
/**
|
||||
* Open Exocad database for Send to Exocad.
|
||||
* Chrome and Edge only. The browser remembers the file handle after the DentalDB check.
|
||||
* The next send reopens that file when it still exists. A missing or rejected file shows Browse again.
|
||||
*/
|
||||
|
||||
export type LocalDbSessionValue = {
|
||||
apply: () => Promise<void>;
|
||||
/** Forget the open file after it is rejected, so the next send can browse again. */
|
||||
abandon: () => Promise<void>;
|
||||
requestConnection: () => Promise<boolean>;
|
||||
transferCase: (input: ExocadCaseInput) => ExocadTransferResult;
|
||||
/** Create the empty CAD-Data project directory. False when the folder was not granted. */
|
||||
ensureProjectFolder: (folderName: string) => Promise<boolean>;
|
||||
};
|
||||
|
||||
const LocalDbSessionContext = createContext<LocalDbSessionValue | null>(null);
|
||||
|
||||
export function useLocalDbSession(): LocalDbSessionValue {
|
||||
const value = useContext(LocalDbSessionContext);
|
||||
if (!value) {
|
||||
throw new Error('LocalDbSessionProvider is missing');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
|
||||
const sessionRef = useRef<LocalSqlite | null>(null);
|
||||
const sinkRef = useRef<DatabaseSink | null>(null);
|
||||
const connectResolveRef = useRef<((connected: boolean) => void) | null>(null);
|
||||
const pendingConnectRef = useRef<Promise<boolean> | null>(null);
|
||||
const [connectOpen, setConnectOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
preloadBrowserHandle();
|
||||
return () => {
|
||||
sessionRef.current?.close();
|
||||
sessionRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const dropSession = useCallback(() => {
|
||||
sessionRef.current?.close();
|
||||
sessionRef.current = null;
|
||||
sinkRef.current = null;
|
||||
}, []);
|
||||
|
||||
const replaceWithSink = useCallback(async (sink: DatabaseSink) => {
|
||||
const next = await LocalSqlite.open(sink.bytes);
|
||||
try {
|
||||
next.execute((query) => assertExocadDatabase(query));
|
||||
} catch (error) {
|
||||
next.close();
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
await sink.remember?.();
|
||||
} catch {
|
||||
// This visit can still write. The next visit asks for the file again.
|
||||
}
|
||||
sessionRef.current?.close();
|
||||
sessionRef.current = next;
|
||||
sinkRef.current = sink;
|
||||
}, []);
|
||||
|
||||
const abandon = useCallback(async () => {
|
||||
dropSession();
|
||||
await forgetBrowserDatabase();
|
||||
}, [dropSession]);
|
||||
|
||||
const apply = useCallback(async () => {
|
||||
const session = sessionRef.current;
|
||||
const sink = sinkRef.current;
|
||||
if (!session || !sink) throw new Error('NOT_OPEN');
|
||||
await sink.write(session.exportBytes());
|
||||
}, []);
|
||||
|
||||
const transferCase = useCallback((input: ExocadCaseInput) => {
|
||||
const session = sessionRef.current;
|
||||
if (!session) throw new Error('NOT_OPEN');
|
||||
return session.execute((query) => transferCaseToExocad(query, input));
|
||||
}, []);
|
||||
|
||||
const ensureProjectFolder = useCallback(
|
||||
(folderName: string) => ensureExocadProjectDirectory(folderName),
|
||||
[],
|
||||
);
|
||||
|
||||
const finishConnect = useCallback((connected: boolean) => {
|
||||
setConnectOpen(false);
|
||||
connectResolveRef.current?.(connected);
|
||||
connectResolveRef.current = null;
|
||||
}, []);
|
||||
|
||||
const requestConnection = useCallback(() => {
|
||||
if (pendingConnectRef.current) return pendingConnectRef.current;
|
||||
const pending = (async () => {
|
||||
const sink = sinkRef.current;
|
||||
if (sessionRef.current && sink) {
|
||||
const alive = await browserDatabaseStillExists();
|
||||
if (alive) return true;
|
||||
dropSession();
|
||||
}
|
||||
try {
|
||||
const restored = browserCanWriteLocalFile() ? await reopenStoredBrowserFile() : null;
|
||||
if (restored) {
|
||||
await replaceWithSink(restored);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
dropSession();
|
||||
await forgetBrowserDatabase();
|
||||
}
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
connectResolveRef.current = resolve;
|
||||
setConnectOpen(true);
|
||||
});
|
||||
})().finally(() => {
|
||||
pendingConnectRef.current = null;
|
||||
});
|
||||
pendingConnectRef.current = pending;
|
||||
return pending;
|
||||
}, [dropSession, replaceWithSink]);
|
||||
|
||||
const value = useMemo<LocalDbSessionValue>(
|
||||
() => ({ apply, abandon, requestConnection, transferCase, ensureProjectFolder }),
|
||||
[abandon, apply, ensureProjectFolder, requestConnection, transferCase],
|
||||
);
|
||||
|
||||
return (
|
||||
<LocalDbSessionContext.Provider value={value}>
|
||||
{children}
|
||||
{connectOpen ? (
|
||||
<LocalDbConnectDialog
|
||||
onCancel={() => finishConnect(false)}
|
||||
onOpened={async (sink) => {
|
||||
await replaceWithSink(sink);
|
||||
finishConnect(true);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</LocalDbSessionContext.Provider>
|
||||
);
|
||||
}
|
||||
28
frontend/src/types/sqljs.d.ts
vendored
28
frontend/src/types/sqljs.d.ts
vendored
@@ -1,28 +0,0 @@
|
||||
declare module 'sql.js' {
|
||||
export type SqlValue = string | number | null | Uint8Array;
|
||||
|
||||
export interface Statement {
|
||||
bind(values?: SqlValue[]): boolean;
|
||||
step(): boolean;
|
||||
get(): SqlValue[];
|
||||
free(): boolean;
|
||||
}
|
||||
|
||||
export interface Database {
|
||||
run(sql: string, params?: SqlValue[]): Database;
|
||||
prepare(sql: string): Statement;
|
||||
export(): Uint8Array;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export interface SqlJsStatic {
|
||||
Database: new (data?: ArrayLike<number> | null) => Database;
|
||||
}
|
||||
|
||||
export interface InitSqlJsConfig {
|
||||
locateFile?: (file: string) => string;
|
||||
wasmBinary?: ArrayBuffer | Uint8Array;
|
||||
}
|
||||
|
||||
export default function initSqlJs(config?: InitSqlJsConfig): Promise<SqlJsStatic>;
|
||||
}
|
||||
@@ -267,6 +267,21 @@ curl http://wixur.ir/health
|
||||
|
||||
**Mobinnet:** public **80** is the modem. Use **443** instead: router forward **TCP 443 → 192.168.1.100**, then `https://wixur.ir`. Let's Encrypt after mobile-data `/health` works (self-signed is enough for that test).
|
||||
|
||||
### HTTPS certificates
|
||||
|
||||
Public port 80 is the modem, so Let's Encrypt cannot renew `wixur.ir` over HTTP. Renewal writes a TXT record in the Arvan zone `wixur.ir` and never uses port 80. That is the same check production uses for `nudentic.ir`. Do not run `install-arvan-renew.sh` on this PC. That script is only for the Linux certbot container.
|
||||
|
||||
One certificate covers `wixur.ir`, `www.wixur.ir`, `gitea.wixur.ir`, and `errors.wixur.ir`. Windows nginx keeps the PEM filenames already in `C:\tools\nginx-1.29.5\conf\nginx.conf`. [`scripts/renew-wixur-cert.ps1`](scripts/renew-wixur-cert.ps1) copies the new chain and key onto each of those paths and reloads nginx.
|
||||
|
||||
Put the Arvan API key on one line in `C:\dyolink\secrets\arvan-api-key`. Do not commit it. Docker Desktop must be running. On this PC:
|
||||
|
||||
```powershell
|
||||
cd C:\path\to\dyolink\infrastructure\scripts
|
||||
.\renew-wixur-cert.ps1 -Register
|
||||
```
|
||||
|
||||
`-Register` schedules that script daily at 03:15 under the signed-in account, then issues or renews immediately. A later run with no switch only renews and reloads.
|
||||
|
||||
---
|
||||
|
||||
## Test the pipeline
|
||||
@@ -375,6 +390,7 @@ On the Windows host, from repo `infrastructure/`:
|
||||
| Git clone fails in workflow | Set `CLONE_HOST=127.0.0.1:3000` |
|
||||
| Port 80 bind forbidden / access permissions | Portproxy already owns 80. Bind Docker to `18088` and point portproxy **80 → 127.0.0.1:18088**. Free IIS if it holds 80. |
|
||||
| `http://wixur.ir` unreachable / empty reply | Docker Desktop: run **portproxy** (§7). `127.0.0.1:18088/health` must work on Windows first. Router must forward **80**. |
|
||||
| Browser says the certificate date is invalid for `wixur.ir`, `gitea.wixur.ir`, or `errors.wixur.ir` | The Let's Encrypt files on the Windows nginx expired. HTTP renewal cannot succeed while public port 80 is the modem. On the PC run `infrastructure\scripts\renew-wixur-cert.ps1`. |
|
||||
| Port 8088 bind forbidden / access permissions | Portproxy already owns 8088. Bind Docker to `18088` and point portproxy **8088 → 127.0.0.1:18088**. |
|
||||
| Port 8088 unreachable from Mac / empty reply | Legacy URL. Prefer `http://wixur.ir`. Same 18088 backend; add portproxy 8088 only as fallback. |
|
||||
| Backend restart loop | JWT secrets still placeholder; fix `backend.staging.env` |
|
||||
@@ -410,6 +426,8 @@ docker logs dyolink_frontend_staging --tail 50
|
||||
| `infrastructure/nginx/http-only.conf` | HTTP reverse proxy **inside Docker** staging |
|
||||
| `infrastructure/nginx/windows-edge-http.conf` | Windows **host** nginx on port 80/443 → 18088 |
|
||||
| `infrastructure/nginx/windows-gitea.wixur.snippet.conf` | Windows nginx vhost for `https://gitea.wixur.ir` (unlimited body — Docker push) |
|
||||
| `infrastructure/scripts/renew-wixur-cert.ps1` | Renew `wixur.ir` / `gitea` / `errors` by Arvan DNS and reload Windows nginx |
|
||||
| `infrastructure/scripts/arvan-dns-auth.py` | Certbot hook: create the Arvan TXT record (`arvan_dns.py`, cleanup hook beside it) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,72 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal.
|
||||
|
||||
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The Arvan key is one line
|
||||
in /etc/letsencrypt/arvan-api-key (never printed).
|
||||
"""
|
||||
import json
|
||||
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
method=method,
|
||||
headers={
|
||||
"Authorization": auth_header(),
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def txt_visible(name, value):
|
||||
url = "https://dns.google/resolve?name={}&type=TXT".format(name)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=15) as resp:
|
||||
payload = json.loads(resp.read().decode())
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||
return False
|
||||
for answer in payload.get("Answer") or []:
|
||||
data = answer.get("data", "").strip('"')
|
||||
if value in data:
|
||||
return True
|
||||
return False
|
||||
from arvan_dns import txt_visible, upsert_txt, zone_and_record
|
||||
|
||||
|
||||
def main():
|
||||
domain = os.environ["CERTBOT_DOMAIN"]
|
||||
value = os.environ["CERTBOT_VALIDATION"]
|
||||
status, body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, domain),
|
||||
{"type": "txt", "name": "_acme-challenge", "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if status == 422 and "duplicate" in body.lower():
|
||||
status = 200
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
fqdn = "_acme-challenge.{}".format(domain)
|
||||
zone, name, fqdn = zone_and_record(domain)
|
||||
upsert_txt(zone, name, value)
|
||||
for _ in range(18):
|
||||
if txt_visible(fqdn, value):
|
||||
print("TXT record is visible")
|
||||
|
||||
@@ -1,69 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Remove the _acme-challenge TXT record created for one Certbot attempt."""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url):
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
method=method,
|
||||
headers={"Authorization": auth_header(), "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
yield from walk(item)
|
||||
elif isinstance(node, dict):
|
||||
if "id" in node and "type" in node:
|
||||
yield node
|
||||
for value in node.values():
|
||||
yield from walk(value)
|
||||
from arvan_dns import delete_record, list_txt, record_names_match, txt_text, zone_and_record
|
||||
|
||||
|
||||
def main():
|
||||
domain = os.environ["CERTBOT_DOMAIN"]
|
||||
value = os.environ.get("CERTBOT_VALIDATION", "")
|
||||
status, body = request("GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, domain))
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
||||
payload = json.loads(body)
|
||||
for record in walk(payload):
|
||||
zone, name, fqdn = zone_and_record(domain)
|
||||
for record in list_txt(zone):
|
||||
if str(record.get("type", "")).lower() != "txt":
|
||||
continue
|
||||
if record.get("name") not in ("_acme-challenge", "_acme-challenge." + domain):
|
||||
if not record_names_match(record.get("name"), name, fqdn):
|
||||
continue
|
||||
text = ""
|
||||
raw_value = record.get("value")
|
||||
if isinstance(raw_value, dict):
|
||||
text = str(raw_value.get("text", ""))
|
||||
if value and value not in text:
|
||||
if value and value not in txt_text(record):
|
||||
continue
|
||||
del_status, _ = request(
|
||||
"DELETE",
|
||||
"{}/{}/dns-records/{}".format(API, domain, record["id"]),
|
||||
)
|
||||
if del_status not in (200, 204, 404):
|
||||
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(del_status))
|
||||
delete_record(zone, record["id"])
|
||||
print("TXT record removed")
|
||||
|
||||
|
||||
|
||||
148
infrastructure/scripts/arvan_dns.py
Normal file
148
infrastructure/scripts/arvan_dns.py
Normal file
@@ -0,0 +1,148 @@
|
||||
"""Arvan DNS helpers for a Certbot DNS-01 check.
|
||||
|
||||
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The API key is one line
|
||||
in /etc/letsencrypt/arvan-api-key and is never printed.
|
||||
|
||||
nudentic.ir is its own zone, so the TXT name is _acme-challenge.
|
||||
A name under wixur.ir uses that zone: gitea.wixur.ir becomes
|
||||
_acme-challenge.gitea in zone wixur.ir.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
headers = {"Authorization": auth_header(), "Accept": "application/json"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def zone_and_record(domain):
|
||||
domain = domain.strip().rstrip(".")
|
||||
override = os.environ.get("ARVAN_ZONE", "").strip().rstrip(".")
|
||||
labels = domain.split(".")
|
||||
if override:
|
||||
zone = override
|
||||
elif len(labels) > 2:
|
||||
zone = ".".join(labels[-2:])
|
||||
else:
|
||||
zone = domain
|
||||
if domain == zone:
|
||||
name = "_acme-challenge"
|
||||
elif domain.endswith("." + zone):
|
||||
prefix = domain[: -(len(zone) + 1)]
|
||||
name = "_acme-challenge." + prefix
|
||||
else:
|
||||
raise SystemExit("CERTBOT_DOMAIN is not in the Arvan zone")
|
||||
fqdn = name + "." + zone
|
||||
return zone, name, fqdn
|
||||
|
||||
|
||||
def record_names_match(got, name, fqdn):
|
||||
if not isinstance(got, str):
|
||||
return False
|
||||
got = got.strip().rstrip(".").lower()
|
||||
return got in (name.lower(), fqdn.lower())
|
||||
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
yield from walk(item)
|
||||
elif isinstance(node, dict):
|
||||
if "id" in node and "type" in node:
|
||||
yield node
|
||||
for value in node.values():
|
||||
yield from walk(value)
|
||||
|
||||
|
||||
def txt_text(record):
|
||||
raw_value = record.get("value")
|
||||
if isinstance(raw_value, dict):
|
||||
return str(raw_value.get("text", ""))
|
||||
if isinstance(raw_value, str):
|
||||
return raw_value
|
||||
return ""
|
||||
|
||||
|
||||
def list_txt(zone):
|
||||
status, body = request(
|
||||
"GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, zone)
|
||||
)
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
||||
return list(walk(json.loads(body)))
|
||||
|
||||
|
||||
def delete_record(zone, record_id):
|
||||
status, _body = request(
|
||||
"DELETE", "{}/{}/dns-records/{}".format(API, zone, record_id)
|
||||
)
|
||||
if status not in (200, 204, 404):
|
||||
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(status))
|
||||
|
||||
|
||||
def upsert_txt(zone, name, value):
|
||||
status, body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, zone),
|
||||
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if 200 <= status < 300:
|
||||
return
|
||||
if status == 422 and "duplicate" in body.lower():
|
||||
for record in list_txt(zone):
|
||||
if str(record.get("type", "")).lower() != "txt":
|
||||
continue
|
||||
if not record_names_match(record.get("name"), name, name + "." + zone):
|
||||
continue
|
||||
if value and value in txt_text(record):
|
||||
return
|
||||
delete_record(zone, record["id"])
|
||||
status, _body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, zone),
|
||||
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if 200 <= status < 300 or (status == 422 and "duplicate" in _body.lower()):
|
||||
return
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
|
||||
|
||||
def txt_visible(fqdn, value):
|
||||
urls = (
|
||||
"https://dns.google/resolve?name={}&type=TXT".format(fqdn),
|
||||
"https://cloudflare-dns.com/dns-query?name={}&type=TXT".format(fqdn),
|
||||
)
|
||||
for url in urls:
|
||||
req = urllib.request.Request(url, headers={"Accept": "application/dns-json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
payload = json.loads(resp.read().decode())
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||
continue
|
||||
for answer in payload.get("Answer") or []:
|
||||
data = answer.get("data", "").strip('"')
|
||||
if value in data:
|
||||
return True
|
||||
return False
|
||||
@@ -14,10 +14,11 @@ if [ ! -s "$KEY" ]; then
|
||||
fi
|
||||
|
||||
docker cp "$KEY" dyolink_certbot_prod:/etc/letsencrypt/arvan-api-key
|
||||
docker cp "$SCRIPT_DIR/arvan_dns.py" dyolink_certbot_prod:/etc/letsencrypt/arvan_dns.py
|
||||
docker cp "$SCRIPT_DIR/arvan-dns-auth.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-auth.py
|
||||
docker cp "$SCRIPT_DIR/arvan-dns-cleanup.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-cleanup.py
|
||||
docker exec dyolink_certbot_prod chmod 600 /etc/letsencrypt/arvan-api-key
|
||||
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
||||
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan_dns.py /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
||||
|
||||
docker exec -i dyolink_certbot_prod python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
|
||||
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
@@ -0,0 +1,204 @@
|
||||
# Issue or renew the wixur.ir certificate with an Arvan DNS check, copy it onto
|
||||
# the PEM files Windows nginx already uses, and reload nginx.
|
||||
# Requires Docker Desktop. The Arvan API key is one line in
|
||||
# C:\dyolink\secrets\arvan-api-key and is not printed.
|
||||
# -Register also schedules this script daily at 03:15.
|
||||
|
||||
param(
|
||||
[switch]$Register
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$KeyFile = 'C:\dyolink\secrets\arvan-api-key'
|
||||
$LeDir = 'C:\dyolink\letsencrypt'
|
||||
$NginxHome = 'C:\tools\nginx-1.29.5'
|
||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$TaskName = 'Dyolink renew wixur certificate'
|
||||
$Names = @('wixur.ir', 'www.wixur.ir', 'gitea.wixur.ir', 'errors.wixur.ir')
|
||||
|
||||
function Convert-DockerPath {
|
||||
param([string]$Path)
|
||||
$full = [IO.Path]::GetFullPath($Path)
|
||||
if ($full -match '^([A-Za-z]):\\(.*)$') {
|
||||
return '/' + $Matches[1].ToLower() + '/' + ($Matches[2] -replace '\\', '/')
|
||||
}
|
||||
return ($full -replace '\\', '/')
|
||||
}
|
||||
|
||||
function Register-RenewTask {
|
||||
param([string]$ScriptPath)
|
||||
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`""
|
||||
$trigger = New-ScheduledTaskTrigger -Daily -At '03:15'
|
||||
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
|
||||
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
|
||||
Write-Host "Scheduled $TaskName daily at 03:15."
|
||||
}
|
||||
|
||||
function Get-NginxText {
|
||||
param([string]$Path, [int]$Depth = 0)
|
||||
if ($Depth -gt 5 -or -not (Test-Path -LiteralPath $Path)) { return '' }
|
||||
$dir = Split-Path -Parent $Path
|
||||
$raw = Get-Content -LiteralPath $Path -Raw
|
||||
$included = [regex]::Replace($raw, '(?m)^\s*include\s+([^;]+);', {
|
||||
param($match)
|
||||
$spec = $match.Groups[1].Value.Trim().Trim('"').Trim("'")
|
||||
$full = $spec
|
||||
if ($spec -notmatch '^[A-Za-z]:\\' -and -not $spec.StartsWith('\\')) {
|
||||
$full = Join-Path $dir ($spec -replace '/', '\')
|
||||
}
|
||||
$chunks = @()
|
||||
foreach ($file in @(Get-Item -Path $full -ErrorAction SilentlyContinue)) {
|
||||
$chunks += Get-NginxText -Path $file.FullName -Depth ($Depth + 1)
|
||||
}
|
||||
$chunks -join "`n"
|
||||
})
|
||||
return $included
|
||||
}
|
||||
|
||||
function Split-ServerBlocks {
|
||||
param([string]$Text)
|
||||
$blocks = @()
|
||||
$idx = 0
|
||||
while ($true) {
|
||||
$start = $Text.IndexOf('server', $idx)
|
||||
if ($start -lt 0) { break }
|
||||
$brace = $Text.IndexOf('{', $start)
|
||||
if ($brace -lt 0) { break }
|
||||
$depth = 0
|
||||
$end = -1
|
||||
for ($i = $brace; $i -lt $Text.Length; $i++) {
|
||||
$ch = $Text[$i]
|
||||
if ($ch -eq '{') { $depth++ }
|
||||
elseif ($ch -eq '}') {
|
||||
$depth--
|
||||
if ($depth -eq 0) { $end = $i; break }
|
||||
}
|
||||
}
|
||||
if ($end -lt 0) { break }
|
||||
$blocks += $Text.Substring($start, $end - $start + 1)
|
||||
$idx = $end + 1
|
||||
}
|
||||
return $blocks
|
||||
}
|
||||
|
||||
function Resolve-NginxPath {
|
||||
param([string]$Relative)
|
||||
$clean = $Relative.Trim().Trim('"').Trim("'")
|
||||
if ($clean -match '^[A-Za-z]:\\' -or $clean.StartsWith('\\')) { return $clean }
|
||||
$rel = $clean -replace '/', '\'
|
||||
$candidates = @(
|
||||
(Join-Path $NginxHome $rel),
|
||||
(Join-Path $NginxHome (Join-Path 'conf' $rel))
|
||||
)
|
||||
foreach ($candidate in $candidates) {
|
||||
if (Test-Path -LiteralPath $candidate) { return $candidate }
|
||||
}
|
||||
return $candidates[1]
|
||||
}
|
||||
|
||||
function Get-CertTargets {
|
||||
$conf = Join-Path $NginxHome 'conf\nginx.conf'
|
||||
$text = Get-NginxText -Path $conf
|
||||
$targets = @()
|
||||
foreach ($block in (Split-ServerBlocks -Text $text)) {
|
||||
$serverNames = @()
|
||||
foreach ($match in [regex]::Matches($block, '(?m)^\s*server_name\s+([^;]+);')) {
|
||||
$serverNames += ($match.Groups[1].Value -split '\s+')
|
||||
}
|
||||
$hit = $false
|
||||
foreach ($name in $serverNames) {
|
||||
if ($Names -contains $name.Trim()) { $hit = $true }
|
||||
}
|
||||
if (-not $hit) { continue }
|
||||
$chain = [regex]::Match($block, '(?m)^\s*ssl_certificate\s+(\S+)\s*;')
|
||||
$key = [regex]::Match($block, '(?m)^\s*ssl_certificate_key\s+(\S+)\s*;')
|
||||
if (-not $chain.Success -or -not $key.Success) { continue }
|
||||
$targets += [pscustomobject]@{
|
||||
Chain = Resolve-NginxPath $chain.Groups[1].Value
|
||||
Key = Resolve-NginxPath $key.Groups[1].Value
|
||||
}
|
||||
}
|
||||
if ($targets.Count -eq 0) {
|
||||
$ssl = Join-Path $NginxHome 'conf\ssl'
|
||||
$targets = @(
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'wixur-chain.pem'; Key = Join-Path $ssl 'wixur-key.pem' },
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'gitea-chain.pem'; Key = Join-Path $ssl 'gitea-key.pem' },
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'errors-chain.pem'; Key = Join-Path $ssl 'errors-key.pem' }
|
||||
)
|
||||
}
|
||||
return $targets
|
||||
}
|
||||
|
||||
if ($Register) {
|
||||
Register-RenewTask -ScriptPath $PSCommandPath
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $KeyFile)) {
|
||||
throw "Missing $KeyFile"
|
||||
}
|
||||
foreach ($hook in @('arvan_dns.py', 'arvan-dns-auth.py', 'arvan-dns-cleanup.py')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ScriptDir $hook))) {
|
||||
throw "Missing $hook next to this script"
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $LeDir | Out-Null
|
||||
$hookDir = Join-Path $LeDir 'hooks'
|
||||
New-Item -ItemType Directory -Force -Path $hookDir | Out-Null
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan_dns.py') -Destination (Join-Path $hookDir 'arvan_dns.py')
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-auth.py') -Destination (Join-Path $hookDir 'arvan-dns-auth.py')
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-cleanup.py') -Destination (Join-Path $hookDir 'arvan-dns-cleanup.py')
|
||||
Copy-Item -Force -Path $KeyFile -Destination (Join-Path $LeDir 'arvan-api-key')
|
||||
|
||||
$renewal = Join-Path $LeDir 'renewal\wixur.ir.conf'
|
||||
$emailArgs = '--register-unsafely-without-email'
|
||||
if ($env:LETSENCRYPT_EMAIL) {
|
||||
$emailArgs = "--email $env:LETSENCRYPT_EMAIL --no-eff-email"
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $renewal) {
|
||||
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot renew --cert-name wixur.ir --non-interactive"
|
||||
} else {
|
||||
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot certonly --manual --preferred-challenges dns --manual-auth-hook /etc/letsencrypt/hooks/arvan-dns-auth.py --manual-cleanup-hook /etc/letsencrypt/hooks/arvan-dns-cleanup.py --cert-name wixur.ir -d wixur.ir -d www.wixur.ir -d gitea.wixur.ir -d errors.wixur.ir --agree-tos --non-interactive $emailArgs"
|
||||
}
|
||||
|
||||
$leMount = Convert-DockerPath $LeDir
|
||||
Write-Host 'Requesting the certificate.'
|
||||
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $certbotCmd
|
||||
if ($LASTEXITCODE -ne 0) { throw "certbot failed ($LASTEXITCODE)" }
|
||||
|
||||
$exportCmd = 'cp -L /etc/letsencrypt/live/wixur.ir/fullchain.pem /etc/letsencrypt/export-fullchain.pem && cp -L /etc/letsencrypt/live/wixur.ir/privkey.pem /etc/letsencrypt/export-privkey.pem'
|
||||
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $exportCmd
|
||||
if ($LASTEXITCODE -ne 0) { throw "could not read the new certificate ($LASTEXITCODE)" }
|
||||
|
||||
$chainSrc = Join-Path $LeDir 'export-fullchain.pem'
|
||||
$keySrc = Join-Path $LeDir 'export-privkey.pem'
|
||||
$seen = @{}
|
||||
foreach ($target in (Get-CertTargets)) {
|
||||
$dir = Split-Path -Parent $target.Chain
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
if (-not $seen.ContainsKey($target.Chain)) {
|
||||
Copy-Item -Force -Path $chainSrc -Destination $target.Chain
|
||||
Write-Host "Updated $($target.Chain)"
|
||||
$seen[$target.Chain] = $true
|
||||
}
|
||||
if (-not $seen.ContainsKey($target.Key)) {
|
||||
Copy-Item -Force -Path $keySrc -Destination $target.Key
|
||||
Write-Host "Updated $($target.Key)"
|
||||
$seen[$target.Key] = $true
|
||||
}
|
||||
}
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue $chainSrc, $keySrc
|
||||
|
||||
Push-Location $NginxHome
|
||||
try {
|
||||
& .\nginx.exe -t
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nginx -t failed' }
|
||||
& .\nginx.exe -s reload
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nginx reload failed' }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Write-Host 'Nginx reloaded.'
|
||||
Reference in New Issue
Block a user