improvements: export to exocad rules updated based on the actual data.
This commit is contained in:
@@ -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. A tooth is written only when that work type and material already exist; parameters, dependents, and color come from the fullest saved tooth of the same pair. Unmatched lines go to `t_Notes` as `tooth code`. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
|
||||
- **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 and Name reuse one existing match, or a complete first and last name; otherwise the case is not written and the toast says why. Notes are the comment body. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
|
||||
- **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. 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}”.
|
||||
|
||||
@@ -61,8 +61,9 @@ Writes the open case into a DentalDB SQLite file on this computer. Nothing is up
|
||||
|
||||
- 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.
|
||||
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. Match or create the client from `referringClinicName`, otherwise the case clinic name. Never use practice id `2147483647`. Match or create the patient by first and last name. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. 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. The CAD-Data project folder is still created by Exocad's own Save.
|
||||
- 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 parameters, dependent rows, and `ValuedMaterialParameters` color from the fullest saved tooth of that same pair. 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 = `AnatomicCrown`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic Crown = `AnatomicCrown`/`GCER`; pontic = `AnatomicPontic` 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. Temporary resin, veneer/inlay/onlay/overlay full-contour or layered with no material in the name, abutments, cast post, and fiber post get no tooth row. The case header is still created. Unmatched lines are appended to `t_Notes` as `tooth code`, and the skipped toast still lists them.
|
||||
- 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 an existing client only when exactly one client name contains every token. A new client is created only when that name has a first and last name; a single token that is not unique is not written, and the toast says Client could not be filled. 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. 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. The CAD-Data project folder is still created by Exocad's own Save.
|
||||
- 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.
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -83,6 +83,9 @@ infrastructure/scripts/copy-prod-backup-askpass.exe
|
||||
*.db
|
||||
*.sqlite3
|
||||
|
||||
# Local Exocad comparison photos and DentalDB copy. Never commit.
|
||||
docs/exocad info/
|
||||
|
||||
# === Gitea specific (keep Actions workflows; ignore other local .gitea noise) ===
|
||||
.gitea/*
|
||||
!.gitea/workflows
|
||||
|
||||
@@ -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. A tooth is written only when that work type and material already exist in the file. 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 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 clinic or patient name that cannot fill Client or Name is not written, and the toast says which name failed. 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 case share link (quick ref):**
|
||||
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -556,6 +556,7 @@
|
||||
"sendToExocadSkipped": "Not sent: {lines}.",
|
||||
"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.",
|
||||
"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.",
|
||||
@@ -1434,7 +1435,10 @@
|
||||
"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."
|
||||
"notExocad": "That file is not an Exocad database.",
|
||||
"clientNameIncomplete": "Not sent. The clinic name needs a last name so Exocad can fill Client. Edit the clinic name and try again. The Exocad database was not changed.",
|
||||
"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.",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"sendToExocadSkipped": "فرستاده نشد: {lines}.",
|
||||
"sendToExocadConnectTitle": "اتصال پایگاه داده Exocad",
|
||||
"sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadExperimentalWarning": "این قابلیت آزمایشی است. پیش از استفاده، یک نسخه پشتیبان دستی از پایگاه داده Exocad بگیرید. نودنتیک مسئول هیچ مشکلی نیست. استفاده از این قابلیت بر عهده خود شماست.",
|
||||
"sendCaseTitle": "مراحل برون سپاری",
|
||||
"outsourcePrice": "قیمت برونسپاری",
|
||||
"outsourcePricePending": "این برونسپاری شامل کار بدون تعرفه است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.",
|
||||
@@ -1435,7 +1436,10 @@
|
||||
"loadFailed": "این پایگاه داده خوانده نشد.",
|
||||
"applyFailed": "نوشتن فایل انجام نشد.",
|
||||
"conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.",
|
||||
"notExocad": "این فایل پایگاه داده Exocad نیست."
|
||||
"notExocad": "این فایل پایگاه داده Exocad نیست.",
|
||||
"clientNameIncomplete": "ارسال نشد. نام کلینیک نام خانوادگی ندارد، بنابراین Client در Exocad پر نمیشود. نام کلینیک را اصلاح کنید و دوباره بفرستید. پایگاه داده Exocad تغییر نکرد.",
|
||||
"patientNameIncomplete": "ارسال نشد. نام بیمار نام خانوادگی ندارد، بنابراین Name در Exocad پر نمیشود. نام بیمار را اصلاح کنید و دوباره بفرستید. پایگاه داده Exocad تغییر نکرد.",
|
||||
"sendRolledBack": "ارسال نشد. پایگاه داده Exocad تغییر نکرد."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"sendToExocadSkipped": "Niet gestuurd: {lines}.",
|
||||
"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.",
|
||||
"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.",
|
||||
@@ -1434,7 +1435,10 @@
|
||||
"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."
|
||||
"notExocad": "Dat bestand is geen Exocad-database.",
|
||||
"clientNameIncomplete": "Niet verzonden. De klinieknaam heeft geen achternaam, dus Exocad kan Client niet invullen. Pas de klinieknaam aan en probeer het opnieuw. De Exocad-database is niet gewijzigd.",
|
||||
"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.",
|
||||
|
||||
@@ -208,7 +208,8 @@ describe('transferCaseToExocad', () => {
|
||||
it('creates the clinic, patient, header, and tooth work', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'ZI');
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '90' });
|
||||
const result = transferCaseToExocad(query, sampleCase(), options);
|
||||
|
||||
expect(result).toMatchObject({ created: true, skipped: [] });
|
||||
@@ -217,17 +218,20 @@ describe('transferCaseToExocad', () => {
|
||||
[2, 'North Clinic'],
|
||||
]);
|
||||
expect(
|
||||
query.all('SELECT lab_id, practice_id, patient_id, fname, lname, dateOfBirth FROM patients WHERE fname = ?', ['Ada']),
|
||||
).toEqual([[0, 2, 1, 'Ada', 'Lovelace', null]]);
|
||||
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, 'Dr Smith\nShade A2', '2026-10-20', 'guid-1', 'case-1', 0]]);
|
||||
).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 = ?', [result.treatmentId]),
|
||||
).toEqual([['14', 'AnatomicCrown', 'ZI']]);
|
||||
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
|
||||
@@ -245,8 +249,9 @@ describe('transferCaseToExocad', () => {
|
||||
it('updates the same treatment and reuses the clinic and patient', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'ZI');
|
||||
seedSavedPair(query, 'Coping', 'ZI');
|
||||
seedSavedPair(query, 'Coping', 'NP', { toothId: '98' });
|
||||
seedSavedPair(query, 'Antagonist', 'Healthy', { toothId: '90' });
|
||||
transferCaseToExocad(query, sampleCase(), options);
|
||||
const second = transferCaseToExocad(
|
||||
query,
|
||||
@@ -266,8 +271,14 @@ describe('transferCaseToExocad', () => {
|
||||
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 = ?', [second.treatmentId]),
|
||||
).toEqual([['16', 'Coping', 'NP']]);
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -284,7 +295,7 @@ describe('transferCaseToExocad', () => {
|
||||
numeric: [{ name: 'MinThickness', value: 0.5, dependent: { name: 'MinThicknessSpecial', value: '0', kind: 1 } }],
|
||||
color: 'A1',
|
||||
});
|
||||
seedSavedPair(query, 'AnatomicPontic', 'GCER', { toothId: '83' });
|
||||
seedSavedPair(query, 'ReducedPontic', 'GCER', { toothId: '83' });
|
||||
const result = transferCaseToExocad(
|
||||
query,
|
||||
sampleCase({
|
||||
@@ -301,7 +312,6 @@ describe('transferCaseToExocad', () => {
|
||||
);
|
||||
|
||||
expect(result.skipped).toEqual([
|
||||
{ tooth: '14', prosthesisTypeCode: 'prefabricated_abutment', reason: 'unmapped' },
|
||||
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture', reason: 'arch' },
|
||||
{ tooth: '21', prosthesisTypeCode: 'pontic', reason: 'pontic' },
|
||||
{ tooth: '15', prosthesisTypeCode: 'press_ceramic', reason: 'unmapped' },
|
||||
@@ -312,11 +322,11 @@ describe('transferCaseToExocad', () => {
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([
|
||||
['13', 'AnatomicPontic', 'GCER'],
|
||||
['13', 'ReducedPontic', 'GCER'],
|
||||
['14', 'AnatomicCrown', 'GCER'],
|
||||
]);
|
||||
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
|
||||
['Dr Smith\nShade A2\n14 prefabricated_abutment\nUA complete_denture\n21 pontic\n15 press_ceramic'],
|
||||
['Shade A2'],
|
||||
]);
|
||||
expect(
|
||||
query.all(
|
||||
@@ -368,7 +378,7 @@ describe('transferCaseToExocad', () => {
|
||||
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
|
||||
[result.treatmentId],
|
||||
),
|
||||
).toEqual([['A1', 'GCER', 'Color']]);
|
||||
).toEqual([]);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT COUNT(*) FROM ToothWorkParameters params
|
||||
@@ -392,7 +402,7 @@ describe('transferCaseToExocad', () => {
|
||||
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([
|
||||
['Dr Smith\nShade A2\n11 veneer_zirconia', 'guid-1', 'case-1'],
|
||||
['Shade A2', 'guid-1', 'case-1'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
@@ -422,7 +432,17 @@ describe('transferCaseToExocad', () => {
|
||||
WHERE work.treatment_id = ?`,
|
||||
[veneer.treatmentId],
|
||||
),
|
||||
).toEqual([['A2']]);
|
||||
).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,
|
||||
@@ -431,15 +451,22 @@ describe('transferCaseToExocad', () => {
|
||||
);
|
||||
expect(
|
||||
query.all(
|
||||
`SELECT numeric.value, valued.ValueSN
|
||||
`SELECT numeric.value
|
||||
FROM ToothWork work
|
||||
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
|
||||
JOIN NumericToothWorkParameter numeric ON numeric.id = params.id
|
||||
JOIN ValuedMaterialParameters valued ON valued.toothwork_id = work.id
|
||||
WHERE work.treatment_id = ?`,
|
||||
[pmma.treatmentId],
|
||||
),
|
||||
).toEqual([[0.3, 'A']]);
|
||||
).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();
|
||||
});
|
||||
|
||||
@@ -462,21 +489,210 @@ describe('transferCaseToExocad', () => {
|
||||
|
||||
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([
|
||||
['Dr Smith\nShade A2\n11 temporary_resin_crown\n12 veneer_layered\n13 fiber_post_core'],
|
||||
['Shade A2'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('uses the Default client when the case has no clinic name', async () => {
|
||||
it('does not write when the clinic name has no last name', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
seedSavedPair(query, 'AnatomicCrown', 'ZI');
|
||||
transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options);
|
||||
expect(query.all("SELECT practice_pr_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([[1]]);
|
||||
expect(() => transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options)).toThrow(ExocadTransferError);
|
||||
try {
|
||||
transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ExocadTransferError);
|
||||
expect((error as ExocadTransferError).code).toBe('CLIENT_NAME_INCOMPLETE');
|
||||
}
|
||||
expect(query.all("SELECT treatment_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([]);
|
||||
expect(query.all('SELECT COUNT(*) FROM clients')).toEqual([[2]]);
|
||||
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('does not guess between clients that share one name token', 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],
|
||||
);
|
||||
}
|
||||
expect(() => transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options)).toThrow(ExocadTransferError);
|
||||
expect(query.all("SELECT treatment_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([]);
|
||||
expect(query.all('SELECT COUNT(*) FROM clients WHERE name = ?', ['yavari'])).toEqual([[1]]);
|
||||
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('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);
|
||||
@@ -541,4 +757,139 @@ describe('transferCaseToExocad', () => {
|
||||
).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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,8 +25,8 @@ const REQUIRED_TABLES = [
|
||||
* 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: 'AnatomicCrown', material: 'ZI' },
|
||||
pfz_crown: { workType: 'AnatomicCrown', material: 'ZI' },
|
||||
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' },
|
||||
@@ -40,13 +40,27 @@ const MATERIAL_MATCH: Record<string, { workType: string; material: string }> = {
|
||||
ips_overlay: { workType: 'OverlayCrown', material: 'LS2' },
|
||||
};
|
||||
|
||||
export type ExocadTransferFailure =
|
||||
| 'NOT_EXOCAD'
|
||||
| 'CLIENT_NAME_INCOMPLETE'
|
||||
| 'PATIENT_NAME_INCOMPLETE';
|
||||
|
||||
export class ExocadTransferError extends Error {
|
||||
constructor(readonly code: 'NOT_EXOCAD') {
|
||||
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;
|
||||
@@ -85,11 +99,16 @@ 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;
|
||||
};
|
||||
|
||||
function sameText(left: string, right: string): boolean {
|
||||
return left.trim().toLowerCase() === right.trim().toLowerCase();
|
||||
}
|
||||
/** Catalog code whose sheet label is "Custom Abutment (Titanium)". */
|
||||
const CUSTOM_ABUTMENT_CODE = 'customized_abutment';
|
||||
|
||||
function numberValue(value: unknown): number {
|
||||
const parsed = Number(value);
|
||||
@@ -102,10 +121,49 @@ export function exocadDueDate(value: string | null | undefined): string | null {
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
function buildNotes(dentistName: string, comment: string, skipped: ExocadSkippedLine[]): string | null {
|
||||
const parts = [dentistName.trim(), comment.trim()].filter((part) => part.length > 0);
|
||||
for (const line of skipped) parts.push(`${line.tooth} ${line.prosthesisTypeCode}`);
|
||||
return parts.length > 0 ? parts.join('\n') : null;
|
||||
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 {
|
||||
@@ -158,13 +216,17 @@ function planTeeth(db: SqliteQuery, jobs: ExocadToothJob[]): { writes: ToothWrit
|
||||
if (restoration) {
|
||||
const mapped = MATERIAL_MATCH[restoration.prosthesisTypeCode];
|
||||
if (pairExists(db, mapped.workType, mapped.material)) {
|
||||
writes.push({ toothId: tooth, workType: mapped.workType, material: 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 {
|
||||
skipped.push({ tooth, prosthesisTypeCode: restoration.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
for (const job of group) {
|
||||
if (job === restoration) continue;
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -172,14 +234,13 @@ function planTeeth(db: SqliteQuery, jobs: ExocadToothJob[]): { writes: ToothWrit
|
||||
const pontic = group.find((job) => job.prosthesisTypeCode === 'pontic');
|
||||
if (pontic) {
|
||||
const material = groupMaterial.get(pontic.selectionGroupId?.trim() ?? '') ?? '';
|
||||
if (material && pairExists(db, 'AnatomicPontic', material)) {
|
||||
writes.push({ toothId: tooth, workType: 'AnatomicPontic', material });
|
||||
if (material && pairExists(db, 'ReducedPontic', material)) {
|
||||
writes.push({ toothId: tooth, workType: 'ReducedPontic', material, implantType: null });
|
||||
} else {
|
||||
skipped.push({ tooth, prosthesisTypeCode: pontic.prosthesisTypeCode, reason: material ? 'unmapped' : 'pontic' });
|
||||
}
|
||||
for (const job of group) {
|
||||
if (job === pontic) continue;
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
for (const job of group) {
|
||||
const reason = job === pontic ? (material ? 'unmapped' : 'pontic') : 'unmapped';
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -189,6 +250,18 @@ function planTeeth(db: SqliteQuery, jobs: ExocadToothJob[]): { writes: ToothWrit
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -222,50 +295,87 @@ function nextPracticeId(rows: Array<{ practiceId: number }>): number {
|
||||
return next === EXOCAD_MULTIDIE_PRACTICE_ID ? next + 1 : next;
|
||||
}
|
||||
|
||||
function ensureClient(db: SqliteQuery, clinicName: string): number {
|
||||
const rows = clientRows(db);
|
||||
const wanted = clinicName.trim();
|
||||
const match = wanted
|
||||
? rows.find((row) => sameText(row.name, wanted))
|
||||
: rows.find((row) => row.practiceId === 1) ?? rows.find((row) => sameText(row.name, 'Default'));
|
||||
if (match) return match.practiceId;
|
||||
|
||||
const practiceId = nextPracticeId(rows);
|
||||
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, wanted || 'Default'],
|
||||
[EXOCAD_LAB_ID, practiceId, name],
|
||||
);
|
||||
return practiceId;
|
||||
}
|
||||
|
||||
function ensurePatient(
|
||||
type ClientChoice =
|
||||
| { practiceId: number }
|
||||
| { createName: string }
|
||||
| { failure: 'CLIENT_NAME_INCOMPLETE' };
|
||||
|
||||
function decideClient(rows: Array<{ practiceId: number; name: string }>, clinicName: string): ClientChoice {
|
||||
const wanted = clinicName.trim();
|
||||
const tokens = nameTokens(wanted);
|
||||
if (tokens.length === 0) return { failure: 'CLIENT_NAME_INCOMPLETE' };
|
||||
const matches = rows.filter((row) => coversTokens(row.name, tokens));
|
||||
if (matches.length === 1) return { practiceId: matches[0].practiceId };
|
||||
if (tokens.length >= 2) return { createName: wanted };
|
||||
return { failure: 'CLIENT_NAME_INCOMPLETE' };
|
||||
}
|
||||
|
||||
function matchingPatientId(
|
||||
db: SqliteQuery,
|
||||
practiceId: number,
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
): number {
|
||||
const first = firstName.trim();
|
||||
const last = lastName.trim();
|
||||
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 existing = rows.find(
|
||||
(row) => sameText(row[1] == null ? '' : String(row[1]), first) && sameText(row[2] == null ? '' : String(row[2]), last),
|
||||
const matches = rows.filter((row) =>
|
||||
coversTokens(`${row[1] == null ? '' : String(row[1])} ${row[2] == null ? '' : String(row[2])}`, tokens),
|
||||
);
|
||||
if (existing) return numberValue(existing[0]);
|
||||
if (matches.length !== 1) return null;
|
||||
return numberValue(matches[0][0]);
|
||||
}
|
||||
|
||||
const max = rows.reduce((highest, row) => Math.max(highest, numberValue(row[0])), 0);
|
||||
const patientId = max + 1;
|
||||
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, first, last],
|
||||
[EXOCAD_LAB_ID, practiceId, patientId, parts.family, parts.given],
|
||||
);
|
||||
return patientId;
|
||||
}
|
||||
|
||||
/** Match an existing client and patient, or create both only when each name has two parts. */
|
||||
function resolveParties(
|
||||
db: SqliteQuery,
|
||||
input: ExocadCaseInput,
|
||||
): { practiceId: number; patientId: number } {
|
||||
const decision = decideClient(clientRows(db), input.clinicName);
|
||||
if ('failure' in decision) throw new ExocadTransferError(decision.failure);
|
||||
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(
|
||||
@@ -333,17 +443,9 @@ type ParameterCopy = {
|
||||
dependents: DependentCopy[];
|
||||
};
|
||||
|
||||
type ColorCopy = {
|
||||
paramType: string | null;
|
||||
value: string | null;
|
||||
material: string | null;
|
||||
property: string | null;
|
||||
};
|
||||
|
||||
type MaterialSnapshot = {
|
||||
textual: ParameterCopy[];
|
||||
numeric: ParameterCopy[];
|
||||
colors: ColorCopy[];
|
||||
};
|
||||
|
||||
function cellText(value: unknown): string | null {
|
||||
@@ -357,8 +459,33 @@ function cellNumber(value: unknown): number | null {
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function pairKey(workType: string, material: string): string {
|
||||
return `${workType}\0${material}`;
|
||||
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[] {
|
||||
@@ -374,20 +501,22 @@ function readDependents(db: SqliteQuery, table: string, parentId: number): Depen
|
||||
}));
|
||||
}
|
||||
|
||||
/** Parameter and color rows from the fullest saved tooth of this work type and material. */
|
||||
function readMaterialSnapshot(db: SqliteQuery, workType: string, material: string): MaterialSnapshot | null {
|
||||
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 = ?
|
||||
GROUP BY work.id
|
||||
ORDER BY COUNT(params.id) DESC, work.id DESC
|
||||
LIMIT 1`,
|
||||
[workType, material],
|
||||
);
|
||||
const donorId = numberValue(donors[0]?.[0]);
|
||||
if (!donorId) return null;
|
||||
/**
|
||||
* 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(
|
||||
@@ -395,7 +524,7 @@ function readMaterialSnapshot(db: SqliteQuery, workType: string, material: strin
|
||||
FROM TextualToothWorkParameter textual
|
||||
JOIN ToothWorkParameters params ON params.id = textual.id
|
||||
WHERE params.toothWork_id = ?`,
|
||||
[donorId],
|
||||
[chosenId],
|
||||
)
|
||||
.map((row) => ({
|
||||
customWdId: cellNumber(row[0]),
|
||||
@@ -410,7 +539,7 @@ function readMaterialSnapshot(db: SqliteQuery, workType: string, material: strin
|
||||
FROM NumericToothWorkParameter numeric
|
||||
JOIN ToothWorkParameters params ON params.id = numeric.id
|
||||
WHERE params.toothWork_id = ?`,
|
||||
[donorId],
|
||||
[chosenId],
|
||||
)
|
||||
.map((row) => ({
|
||||
customWdId: cellNumber(row[0]),
|
||||
@@ -419,27 +548,22 @@ function readMaterialSnapshot(db: SqliteQuery, workType: string, material: strin
|
||||
valueNumber: cellNumber(row[2]),
|
||||
dependents: readDependents(db, 'DependentOnNumericToothWorkParameters', numberValue(row[3])),
|
||||
}));
|
||||
const colors = db
|
||||
.all(
|
||||
`SELECT PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN
|
||||
FROM ValuedMaterialParameters WHERE toothwork_id = ?`,
|
||||
[donorId],
|
||||
)
|
||||
.map((row) => ({
|
||||
paramType: cellText(row[0]),
|
||||
value: cellText(row[1]),
|
||||
material: cellText(row[2]),
|
||||
property: cellText(row[3]),
|
||||
}));
|
||||
return { textual, numeric, colors };
|
||||
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);
|
||||
const key = pairKey(write.workType, write.material, write.implantType);
|
||||
if (snapshots.has(key)) continue;
|
||||
snapshots.set(key, readMaterialSnapshot(db, write.workType, write.material));
|
||||
snapshots.set(key, readMaterialSnapshot(db, write.workType, write.material, write.implantType));
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
@@ -481,14 +605,6 @@ function insertParameter(db: SqliteQuery, toothWorkId: number, row: ParameterCop
|
||||
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');
|
||||
for (const color of snapshot.colors) {
|
||||
db.run(
|
||||
`INSERT INTO ValuedMaterialParameters
|
||||
(PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN, toothwork_id)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[color.paramType, color.value, color.material, color.property, toothWorkId],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function insertTeeth(
|
||||
@@ -504,11 +620,47 @@ function insertTeeth(
|
||||
[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));
|
||||
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());
|
||||
@@ -563,12 +715,11 @@ function embedMaterialConfiguration(db: SqliteQuery, treatmentId: number): void
|
||||
}
|
||||
|
||||
function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTransferOptions): ExocadTransferResult {
|
||||
const practiceId = ensureClient(db, input.clinicName);
|
||||
const patientId = ensurePatient(db, practiceId, input.patientFirstName, input.patientLastName);
|
||||
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.dentistName, input.comment, skipped);
|
||||
const notes = buildNotes(input.comment);
|
||||
const snapshots = materialSnapshots(db, writes);
|
||||
const header = [
|
||||
EXOCAD_LAB_ID,
|
||||
@@ -599,6 +750,8 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
|
||||
);
|
||||
deleteToothWork(db, treatmentId);
|
||||
insertTeeth(db, treatmentId, writes, snapshots);
|
||||
copyConfirmedCaseParameters(db, treatmentId);
|
||||
assignSoleTechnician(db, treatmentId);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: false, skipped };
|
||||
}
|
||||
@@ -614,6 +767,8 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
|
||||
);
|
||||
const treatmentId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
insertTeeth(db, treatmentId, writes, snapshots);
|
||||
copyConfirmedCaseParameters(db, treatmentId);
|
||||
assignSoleTechnician(db, treatmentId);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: true, skipped };
|
||||
}
|
||||
|
||||
@@ -7,9 +7,13 @@ type LocalDbTranslator = (key: string) => string;
|
||||
export function localDbErrorText(
|
||||
error: unknown,
|
||||
t: LocalDbTranslator,
|
||||
fallback: 'openFailed' | 'applyFailed' | 'loadFailed',
|
||||
fallback: 'openFailed' | 'applyFailed' | 'loadFailed' | 'sendRolledBack',
|
||||
): string {
|
||||
if (error instanceof ExocadTransferError) return t('notExocad');
|
||||
if (error instanceof ExocadTransferError) {
|
||||
if (error.code === 'CLIENT_NAME_INCOMPLETE') return t('clientNameIncomplete');
|
||||
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);
|
||||
|
||||
@@ -73,7 +73,7 @@ function caseSheetLineNotes(labCase: LabCaseDetail): string[] {
|
||||
function toExocadCase(labCase: LabCaseDetail): ExocadCaseInput {
|
||||
return {
|
||||
caseId: labCase.id,
|
||||
clinicName: labCase.referringClinicName?.trim() || labCase.clinic.name,
|
||||
clinicName: labCase.clinic.name,
|
||||
patientFirstName: labCase.patient.firstName,
|
||||
patientLastName: labCase.patient.lastName,
|
||||
dentistName: labCase.referringDentistName?.trim() ?? '',
|
||||
@@ -439,12 +439,23 @@ 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);
|
||||
const bodies = [...listed.data]
|
||||
.sort((left, right) => new Date(left.createdAt).getTime() - new Date(right.createdAt).getTime())
|
||||
.map((entry) => entry.body.trim())
|
||||
.filter((body) => body.length > 0);
|
||||
if (bodies.length > 0) comment = bodies.join('\n');
|
||||
} catch {
|
||||
comment = labCase.detail?.comment?.trim() ?? '';
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = localDb.transferCase(toExocadCase(labCase));
|
||||
result = localDb.transferCase({ ...toExocadCase(labCase), comment });
|
||||
} catch (caught) {
|
||||
if (caught instanceof ExocadTransferError) await localDb.abandon();
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
|
||||
if (caught instanceof ExocadTransferError && caught.code === 'NOT_EXOCAD') await localDb.abandon();
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'sendRolledBack'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -32,6 +32,7 @@ export function LocalDbConnectDialog({ onCancel, onOpened }: LocalDbConnectDialo
|
||||
<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>
|
||||
|
||||
Reference in New Issue
Block a user