Merge pull request 'Send case into the local Exocad database' (#113) from feature/exocat-db-connection into master
Reviewed-on: #113 Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
This commit was merged in pull request #113.
This commit is contained in:
@@ -14,9 +14,10 @@ alwaysApply: false
|
||||
- **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
|
||||
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge. Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Case-level steps stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
|
||||
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
- **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. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. 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:** **Mark as important** is centered in the header on `lg`. Below that, the header is one compact stack: name and the same QR thumb as desktop (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, the progress bar without a separate “tasks completed” sentence, important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`responsiveFill`). External code sits under the progress bar in the start column, same width as the bar; billed price is under important on `lg`. Get PDF and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource from `lg` up. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
|
||||
- **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}”.
|
||||
- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. The upload queue sits with the toast, so leaving Files or Cases does not cancel it and does not refetch the case; the open case patches from the response. A draft flushes once, then keeps the new file id so autosave does not unlink it. Nginx `/api` uses `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. JSON bodies stay on the Express limit; only multipart is unlimited. Production must recreate nginx from the SSL template. Staging also needs the Windows host nginx reloaded. Do not set `Content-Type: multipart/form-data` by hand.
|
||||
- **Drafts rail:** unstarted lab-origin cases sit in a collapsed `TreatmentRailSection`; expands on click or **Add case**. Main list is received + started cases (`drafts=exclude` / `drafts=only`), newest first by `listedAt` (`LAB_CASE_LIST_ORDER_BY`; trigger `lab_cases_listed_at_sync` = `COALESCE(startedAt, sentAt)`). Never `orderBy startedAt, sentAt` and never a `GENERATED ALWAYS` `listedAt`.
|
||||
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. The rail button is full width. Its mic uses the existing lab voice apply on that case’s one plan (blank plan replaced, existing jobs merged). No draft yet → create the draft, then record. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`). Comments on Cases accept `TAB_CASES_*` (owners are not blocked by Tasks opt-in).
|
||||
|
||||
@@ -47,12 +47,23 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
|
||||
- Comments: shared `LabCaseCommentsPanel` + `tasksApi` comment routes (`viewerSide="LAB"`). Newest-first; sent/received use logical start/end alignment (RTL-safe). Compact `h-9` composer with primary send + visibility controls. Lab-origin cases (`LAB_INTERNAL`, including after Start) are visible to lab comments/mark-read — do not require `sentAt` / `LabCaseSend`. Generated cases hide the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. Received cases use it for the clinic. Lab-to-lab cases use the same eye button for the sending lab: off keeps the comment on this lab, on shows it in that lab's handoff and notifies them. Comments that already existed on a lab-to-lab case stay shared.
|
||||
- Mark read: `POST /notifications/mark-case-read` on select (Cases tab badge)
|
||||
- FDI chart (`CaseToothChartPanel`): prosthesis colors + **connected bridge dots** from `selectionGroupId` (`buildCaseConnectedTeeth` / `buildCaseProsthesisRows` in `caseDetailUtils.ts`).
|
||||
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header on `lg`. Below `lg` the header is one compact stack: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width from `lg` up). **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end. Each file being uploaded is its own card with a progress bar (one request per file). The job lives above the page, so leaving Files or Cases does not cancel it; coming back shows the same card. Finishing patches the open case from the upload response. It does not fetch the case again. A draft flushes once before the batch, then keeps the new file id locally so a later autosave does not unlink it. Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only.
|
||||
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** and the billed price sit under the external code field. The header layout follows the detail panel width (Tailwind container query `@container`, not the viewport). From `@2xl` (42rem) it is two columns (info start, actions end). Narrower, including the split list/detail view on a small laptop and phones, it is one stack with the buttons under the info: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, then the progress bar (no separate “tasks completed” sentence), external code, important, and billed, stacked. The action buttons (Edit, Outsource, Send to Exocad, Get PDF) are one equal-width grid (`CaseLifecycleButton` `responsiveFill`, truncating caption): 2 columns when the panel is narrow, one equal column per button from `@xl`, 2 columns again in the `@2xl` end column (`@2xl:w-72`), with the QR below. A lone last button spans both columns. Send to Exocad shows at every screen size, but only when the browser can overwrite the picked file (Chrome and Edge). External code is the same width as the progress bar (no title; placeholder only). Save code on blur → `PATCH /cases/:id/external-code`. Add files uses that button at the treatment action width. **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end. Each file being uploaded is its own card with a progress bar (one request per file). The job lives above the page, so leaving Files or Cases does not cancel it; coming back shows the same card. Finishing patches the open case from the upload response. It does not fetch the case again. A draft flushes once before the batch, then keeps the new file id locally so a later autosave does not unlink it. Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only.
|
||||
- **Section badges:** Files counts `ATTACHMENT_ADDED` and Messages counts `LAB_COMMENT` / `CLINIC_COMMENT`, after `LabCaseSectionReadState`, excluding the actor. `GET /cases/:id/section-counts`. `POST /cases/:id/sections/:section/read` only when that tab is open and its count is greater than 0. Opening Details does not clear them. Uploads emit `case-section.changed` to other lab members who can read Cases or Tasks (no inbox card). The existing socket turns that into `tab-badges-changed`. `ATTACHMENT_ADDED` is not a sidebar Cases/Tasks/Treatment count. `LabCaseSectionReadState` has a composite id and stays off the AdminJS allowlist.
|
||||
- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `send_timeout 3600s`, `proxy_request_buffering off`, proxy read/send 3600s). The server-level `send_timeout 10` would cut a paused download, so `/api` overrides it. JSON and urlencoded bodies stay on the Express limits; only multipart is unlimited. Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). The attachment row and the case link are one transaction; the disk file is removed only after that transaction commits on delete, and only for a lab-owned upload. A failed activity row does not fail the upload. Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. Releasing this needs `prisma migrate deploy` (the backend container runs it on start; Postgres 15) and a nginx recreate from `nginx.ssl.conf.template`. Staging’s Windows host nginx is a separate paste-and-reload of `windows-edge-http.conf`; Docker alone leaves the 50MB edge. Uploaded bytes live on the backend container disk (`/app/uploads`, no volume) and can fill that disk.
|
||||
- **Case Sheet PDF** — see below.
|
||||
- **Share link (sent cases):** `shareUrl` on detail; attachment preview left + QR thumb right; `LabCaseShareQrDialog` (`react-qr-code`). Full flow: `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
## 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.
|
||||
|
||||
- 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). The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse 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.
|
||||
- FDI restorations become `ToothWork` (`WorkTypeSN` / `MaterialSN`). A pontic uses the connected crown’s material. Implant, post and core, denture, and `UA`/`LA` are skipped and listed after the send.
|
||||
- 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.
|
||||
|
||||
## Case Sheet PDF
|
||||
|
||||
**Entry:** Get PDF on `CaseDetailPanel` (primary, same width as Outsource, no icon) — menu chooses portrait or landscape. Organization name uses a 56px line box so the 28px glyphs are not clipped. The print root has top padding (16px portrait, 24px landscape) so the header QR is not clipped at the page edge. `html2canvas` uses `scrollY: 0` (the host is `position: fixed`). The page stays LTR in every locale. On the Persian sheet that name is a shrink-wrapped `inline-block` (`data-case-sheet-org-text`, `direction: ltr` unless the name itself contains Arabic script, `letter-spacing` and `word-spacing` `0px`) so html2canvas does not stretch the words across the header column. Party and meta values use `printRtlValueStyle`: Arabic script stays RTL; Latin stays LTR, isolated, and right-aligned under the Persian label. Section rules use a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) is the only extra margin, for Persian descenders.
|
||||
|
||||
@@ -72,7 +72,7 @@ frontend/src/
|
||||
|
||||
**Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable and non-outsourceable; historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/SKILL.md`.
|
||||
|
||||
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **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. There is no Local database tab. Send to Exocad keeps `LocalDbSessionProvider` and reopens the last database file while that file still exists. 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.
|
||||
@@ -110,7 +110,7 @@ Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpe
|
||||
| `.cursor/skills/add-feature/` | New tab, API module, or end-to-end feature |
|
||||
| `.cursor/skills/treatment-workspace/` | Treatment tab: preview vs form, history, load flow, drafts, type-first entry, connected teeth |
|
||||
| `.cursor/skills/lab-tasks/` | Lab Tasks tab: `listedAt` sort (same as Cases), case grouping, step-completed filter, prosthesis colors |
|
||||
| `.cursor/skills/lab-cases/` | Lab Cases tab: `listedAt` newest-first, prosthesis filter, auto-select, Case Sheet PDF, external code |
|
||||
| `.cursor/skills/lab-cases/` | Lab Cases tab: `listedAt` newest-first, prosthesis filter, auto-select, Case Sheet PDF, external code, Send to Exocad |
|
||||
| `.cursor/skills/lab-case-share-link/` | Case QR share link: access token, focus page, auth redirect, access rules |
|
||||
| `.cursor/skills/tab-badges/` | Sidebar tab badges: Cases/Tasks/Treatment, LabCaseActivity, tab-counts API, read cursors |
|
||||
| `.cursor/skills/notifications-inbox/` | Header bell inbox: UserNotification fan-out, Socket.IO realtime |
|
||||
|
||||
5
frontend/.gitignore
vendored
5
frontend/.gitignore
vendored
@@ -44,4 +44,7 @@ next-env.d.ts
|
||||
|
||||
# Prisma
|
||||
prisma/*.db
|
||||
prisma/*.db-journal
|
||||
prisma/*.db-journal
|
||||
|
||||
# Copied from sql.js before dev/build (see scripts/copy-sql-wasm.mjs)
|
||||
/public/sql-wasm-browser.wasm
|
||||
@@ -546,6 +546,12 @@
|
||||
"fromLabBadge": "From lab",
|
||||
"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}.",
|
||||
"sendToExocadConnectTitle": "Connect Exocad database",
|
||||
"sendToExocadCloseHint": "Close Exocad before sending. Open it again afterwards to see the case.",
|
||||
"sendCaseTitle": "Outsource steps",
|
||||
"sendCaseSelectAll": "Select all",
|
||||
"sendCaseLab": "Lab",
|
||||
@@ -1331,6 +1337,14 @@
|
||||
"cancel": "Cancel",
|
||||
"walkInPatient": "Walk-in"
|
||||
},
|
||||
"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."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "Something went wrong. Please try again.",
|
||||
"NETWORK_ERROR": "Could not reach the server. Check your connection and try again.",
|
||||
|
||||
@@ -546,6 +546,12 @@
|
||||
"receivedBadge": "از کلینیک",
|
||||
"fromLabBadge": "از لابراتوار",
|
||||
"sendCase": "برون سپاری",
|
||||
"sendToExocad": "ارسال به Exocad",
|
||||
"sendToExocadSaved": "به Exocad به عنوان پرونده {id} فرستاده شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadUpdated": "پرونده {id} در Exocad بهروز شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendToExocadSkipped": "فرستاده نشد: {lines}.",
|
||||
"sendToExocadConnectTitle": "اتصال پایگاه داده Exocad",
|
||||
"sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.",
|
||||
"sendCaseTitle": "مراحل برون سپاری",
|
||||
"sendCaseSelectAll": "انتخاب همه",
|
||||
"sendCaseLab": "لابراتوار",
|
||||
@@ -1332,6 +1338,14 @@
|
||||
"cancel": "انصراف",
|
||||
"walkInPatient": "بدون نوبت"
|
||||
},
|
||||
"localDb": {
|
||||
"browse": "مرور",
|
||||
"openFailed": "این فایل باز نشد.",
|
||||
"loadFailed": "این پایگاه داده خوانده نشد.",
|
||||
"applyFailed": "نوشتن فایل انجام نشد.",
|
||||
"conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.",
|
||||
"notExocad": "این فایل پایگاه داده Exocad نیست."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
|
||||
"NETWORK_ERROR": "اتصال به سرور برقرار نشد. اتصال اینترنت را بررسی کنید.",
|
||||
|
||||
@@ -546,6 +546,12 @@
|
||||
"receivedBadge": "Van kliniek",
|
||||
"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}.",
|
||||
"sendToExocadConnectTitle": "Exocad-database koppelen",
|
||||
"sendToExocadCloseHint": "Sluit Exocad voordat u verstuurt. Open het daarna opnieuw om de casus te zien.",
|
||||
"sendCaseTitle": "Stappen uitbesteden",
|
||||
"sendCaseSelectAll": "Alles selecteren",
|
||||
"sendCaseLab": "Lab",
|
||||
@@ -1331,6 +1337,14 @@
|
||||
"cancel": "Annuleren",
|
||||
"walkInPatient": "Walk-in"
|
||||
},
|
||||
"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."
|
||||
},
|
||||
"errors": {
|
||||
"GENERIC": "Er is iets misgegaan. Probeer het opnieuw.",
|
||||
"NETWORK_ERROR": "Kan de server niet bereiken. Controleer uw verbinding.",
|
||||
|
||||
@@ -41,6 +41,7 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
output: 'standalone',
|
||||
compress: true,
|
||||
serverExternalPackages: ['sql.js'],
|
||||
};
|
||||
|
||||
export default withSentryConfig(withNextIntl(nextConfig), {
|
||||
|
||||
117
frontend/package-lock.json
generated
117
frontend/package-lock.json
generated
@@ -23,6 +23,7 @@
|
||||
"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": {
|
||||
@@ -80,7 +81,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
|
||||
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.29.0",
|
||||
"@babel/generator": "^7.29.0",
|
||||
@@ -1499,6 +1499,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
|
||||
"integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/gen-mapping": "^0.3.5",
|
||||
"@jridgewell/trace-mapping": "^0.3.25"
|
||||
@@ -1746,7 +1747,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
|
||||
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
@@ -1768,7 +1768,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.10.0.tgz",
|
||||
"integrity": "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@opentelemetry/semantic-conventions": "^1.29.0"
|
||||
},
|
||||
@@ -1784,7 +1783,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.220.0.tgz",
|
||||
"integrity": "sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@opentelemetry/api-logs": "0.220.0",
|
||||
"import-in-the-middle": "^3.0.0",
|
||||
@@ -1835,7 +1833,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.10.0.tgz",
|
||||
"integrity": "sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "2.10.0",
|
||||
"@opentelemetry/resources": "2.10.0",
|
||||
@@ -2239,7 +2236,6 @@
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -3782,7 +3778,6 @@
|
||||
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
@@ -3855,7 +3850,6 @@
|
||||
"integrity": "sha512-XZzOmihLIr8AD1b9hL9ccNMzEMWt/dE2u7NyTY9jJG6YNiNthaD5XtUHVF2uCXZ15ng+z2hT3MVuxnUYhq6k1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.57.0",
|
||||
"@typescript-eslint/types": "8.57.0",
|
||||
@@ -4505,6 +4499,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz",
|
||||
"integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/helper-numbers": "1.13.2",
|
||||
"@webassemblyjs/helper-wasm-bytecode": "1.13.2"
|
||||
@@ -4514,25 +4509,29 @@
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz",
|
||||
"integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@webassemblyjs/helper-api-error": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz",
|
||||
"integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@webassemblyjs/helper-buffer": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz",
|
||||
"integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@webassemblyjs/helper-numbers": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz",
|
||||
"integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/floating-point-hex-parser": "1.13.2",
|
||||
"@webassemblyjs/helper-api-error": "1.13.2",
|
||||
@@ -4543,13 +4542,15 @@
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz",
|
||||
"integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@webassemblyjs/helper-wasm-section": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz",
|
||||
"integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@webassemblyjs/helper-buffer": "1.14.1",
|
||||
@@ -4562,6 +4563,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz",
|
||||
"integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@xtuc/ieee754": "^1.2.0"
|
||||
}
|
||||
@@ -4571,6 +4573,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz",
|
||||
"integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@xtuc/long": "4.2.2"
|
||||
}
|
||||
@@ -4579,13 +4582,15 @@
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz",
|
||||
"integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@webassemblyjs/wasm-edit": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz",
|
||||
"integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@webassemblyjs/helper-buffer": "1.14.1",
|
||||
@@ -4602,6 +4607,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz",
|
||||
"integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@webassemblyjs/helper-wasm-bytecode": "1.13.2",
|
||||
@@ -4615,6 +4621,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz",
|
||||
"integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@webassemblyjs/helper-buffer": "1.14.1",
|
||||
@@ -4627,6 +4634,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz",
|
||||
"integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@webassemblyjs/helper-api-error": "1.13.2",
|
||||
@@ -4641,6 +4649,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz",
|
||||
"integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@webassemblyjs/ast": "1.14.1",
|
||||
"@xtuc/long": "4.2.2"
|
||||
@@ -4650,20 +4659,21 @@
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
|
||||
"integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",
|
||||
"license": "BSD-3-Clause"
|
||||
"license": "BSD-3-Clause",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@xtuc/long": {
|
||||
"version": "4.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",
|
||||
"integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",
|
||||
"license": "Apache-2.0"
|
||||
"license": "Apache-2.0",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.16.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
|
||||
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -4715,6 +4725,7 @@
|
||||
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
|
||||
"integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ajv": "^8.0.0"
|
||||
},
|
||||
@@ -4732,6 +4743,7 @@
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -4747,7 +4759,8 @@
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
@@ -5028,7 +5041,6 @@
|
||||
"integrity": "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.26.0"
|
||||
}
|
||||
@@ -5105,7 +5117,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -5124,7 +5135,8 @@
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/cac": {
|
||||
"version": "6.7.14",
|
||||
@@ -5284,6 +5296,7 @@
|
||||
"resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz",
|
||||
"integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
}
|
||||
@@ -5345,7 +5358,8 @@
|
||||
"version": "2.20.3",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
|
||||
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/commondir": {
|
||||
"version": "1.0.1",
|
||||
@@ -6043,7 +6057,6 @@
|
||||
"integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -6229,7 +6242,6 @@
|
||||
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@rtsao/scc": "^1.1.0",
|
||||
"array-includes": "^3.1.9",
|
||||
@@ -6486,6 +6498,7 @@
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.8.x"
|
||||
}
|
||||
@@ -6575,7 +6588,8 @@
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
"license": "BSD-3-Clause",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/fastq": {
|
||||
"version": "1.20.1",
|
||||
@@ -7671,6 +7685,7 @@
|
||||
"resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
|
||||
"integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/node": "*",
|
||||
"merge-stream": "^2.0.0",
|
||||
@@ -7685,6 +7700,7 @@
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
|
||||
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
@@ -8197,7 +8213,8 @@
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
|
||||
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/merge2": {
|
||||
"version": "1.4.1",
|
||||
@@ -8272,6 +8289,7 @@
|
||||
"resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.8.0.tgz",
|
||||
"integrity": "sha512-2cT9+goJfBhtMz+gJqejSf09ClgmYhPhccRb/fb0ztVbixt0BkO8mRuI26FoPPuUNkRk6iEDryWAIouc5W8eJA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "^0.3.31",
|
||||
"jest-worker": "^27.4.5",
|
||||
@@ -8402,14 +8420,14 @@
|
||||
"version": "2.6.2",
|
||||
"resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
|
||||
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz",
|
||||
"integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@next/env": "16.1.6",
|
||||
"@swc/helpers": "0.5.15",
|
||||
@@ -8535,6 +8553,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/next-intl/node_modules/@swc/helpers": {
|
||||
"version": "0.5.23",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
|
||||
"integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/next/node_modules/postcss": {
|
||||
"version": "8.4.31",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
|
||||
@@ -9058,7 +9087,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
||||
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -9068,7 +9096,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@@ -9081,7 +9108,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.2.tgz",
|
||||
"integrity": "sha512-1CHvcDYzuRUNOflt4MOq3ZM46AronNJtQ1S7tnX6YN4y72qhgiUItpacZUAQ0TyWYci3yz1X+rXaSxiuEm86PA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -9097,8 +9123,7 @@
|
||||
"version": "16.13.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-qr-code": {
|
||||
"version": "2.2.0",
|
||||
@@ -9118,7 +9143,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
|
||||
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/use-sync-external-store": "^0.0.6",
|
||||
"use-sync-external-store": "^1.4.0"
|
||||
@@ -9171,8 +9195,7 @@
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/redux-thunk": {
|
||||
"version": "3.1.0",
|
||||
@@ -9239,6 +9262,7 @@
|
||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -9329,7 +9353,6 @@
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
|
||||
"integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.9"
|
||||
},
|
||||
@@ -9460,6 +9483,7 @@
|
||||
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz",
|
||||
"integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/json-schema": "^7.0.9",
|
||||
"ajv": "^8.9.0",
|
||||
@@ -9496,6 +9520,7 @@
|
||||
"resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",
|
||||
"integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3"
|
||||
},
|
||||
@@ -9507,7 +9532,8 @@
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
@@ -9764,6 +9790,7 @@
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -9782,11 +9809,18 @@
|
||||
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
|
||||
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"buffer-from": "^1.0.0",
|
||||
"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",
|
||||
@@ -10084,6 +10118,7 @@
|
||||
"resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",
|
||||
"integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",
|
||||
"license": "BSD-2-Clause",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/source-map": "^0.3.3",
|
||||
"acorn": "^8.15.0",
|
||||
@@ -10168,7 +10203,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -10376,7 +10410,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -10700,7 +10733,6 @@
|
||||
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -10799,6 +10831,7 @@
|
||||
"resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz",
|
||||
"integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.1.2"
|
||||
},
|
||||
@@ -10817,6 +10850,7 @@
|
||||
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.110.2.tgz",
|
||||
"integrity": "sha512-TciLrfM7zgEjqGdY851HkirDsSPQgTFsWQpl9oHqMAMYsHhEC0bKjscvjpnz+pzx10hLC8qISApGrsnrCP4UtQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.8",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
@@ -10859,6 +10893,7 @@
|
||||
"resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz",
|
||||
"integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
@@ -10868,6 +10903,7 @@
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
|
||||
"integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
@@ -11065,7 +11101,6 @@
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
"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",
|
||||
@@ -25,6 +27,7 @@
|
||||
"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": {
|
||||
|
||||
8
frontend/scripts/copy-sql-wasm.mjs
Normal file
8
frontend/scripts/copy-sql-wasm.mjs
Normal file
@@ -0,0 +1,8 @@
|
||||
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,6 +10,7 @@ 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';
|
||||
@@ -94,6 +95,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
<CaseUploadFailureReporter />
|
||||
<ConfirmProvider>
|
||||
<RealtimeProvider>
|
||||
<LocalDbSessionProvider>
|
||||
<div className="app-dashboard-shell flex h-[100dvh] app-web-bg text-text-primary">
|
||||
{sidebarOpen ? (
|
||||
<button
|
||||
@@ -119,6 +121,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</LocalDbSessionProvider>
|
||||
</RealtimeProvider>
|
||||
</ConfirmProvider>
|
||||
</ToastProvider>
|
||||
|
||||
203
frontend/src/components/local-db/browserFile.ts
Normal file
203
frontend/src/components/local-db/browserFile.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
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();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
256
frontend/src/components/local-db/exocadTransfer.spec.ts
Normal file
256
frontend/src/components/local-db/exocadTransfer.spec.ts
Normal file
@@ -0,0 +1,256 @@
|
||||
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,
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
const result = transferCaseToExocad(query, sampleCase(), options);
|
||||
|
||||
expect(result).toMatchObject({ treatmentId: 1, created: true, skipped: [] });
|
||||
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 fname = ?', ['Ada']),
|
||||
).toEqual([[0, 2, 1, 'Ada', 'Lovelace', null]]);
|
||||
expect(
|
||||
query.all(
|
||||
'SELECT practice_pr_id, patient_patient_id, t_Notes, t_duedate, projectGUID, importedOrderId, flags FROM Treatment',
|
||||
),
|
||||
).toEqual([[2, 1, 'Dr Smith\nShade A2', '2026-10-20', 'guid-1', 'case-1', 0]]);
|
||||
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([
|
||||
['14', 'AnatomicCrown', 'ZI'],
|
||||
]);
|
||||
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);
|
||||
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({ treatmentId: 1, 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')).toEqual([['guid-1', 'case-1']]);
|
||||
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([['16', 'Coping', 'NP']]);
|
||||
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);
|
||||
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' },
|
||||
],
|
||||
}),
|
||||
options,
|
||||
);
|
||||
|
||||
expect(result.skipped).toEqual([
|
||||
{ tooth: '14', prosthesisTypeCode: 'prefabricated_abutment', reason: 'unmapped' },
|
||||
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture', reason: 'arch' },
|
||||
{ tooth: '21', prosthesisTypeCode: 'pontic', reason: 'pontic' },
|
||||
]);
|
||||
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork ORDER BY ToothId')).toEqual([
|
||||
['13', 'AnatomicPontic', 'LS2'],
|
||||
['14', 'AnatomicCrown', 'LS2'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('maps an older zirconia veneer', 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([]);
|
||||
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([
|
||||
['11', 'Veneer', 'ZI'],
|
||||
]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('uses the Default client when the case has no clinic name', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options);
|
||||
expect(query.all('SELECT practice_pr_id FROM Treatment')).toEqual([[1]]);
|
||||
expect(query.all('SELECT COUNT(*) FROM clients')).toEqual([[2]]);
|
||||
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();
|
||||
});
|
||||
});
|
||||
396
frontend/src/components/local-db/exocadTransfer.ts
Normal file
396
frontend/src/components/local-db/exocadTransfer.ts
Normal file
@@ -0,0 +1,396 @@
|
||||
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;
|
||||
|
||||
const RESTORATION: Record<string, { workType: string; material: string }> = {
|
||||
monolithic_zirconia: { workType: 'AnatomicCrown', material: 'ZI' },
|
||||
pfz_crown: { workType: 'AnatomicCrown', material: 'ZI' },
|
||||
pfm_crown: { workType: 'Coping', material: 'NP' },
|
||||
full_metal_crown: { workType: 'AnatomicCrown', material: 'NP' },
|
||||
glass_ceramic_crown: { workType: 'AnatomicCrown', material: 'LS2' },
|
||||
press_ceramic: { workType: 'AnatomicCrown', material: 'LS2' },
|
||||
pmma: { workType: 'AnatomicCrown', material: 'PMMA' },
|
||||
temporary_resin_crown: { workType: 'AnatomicCrown', material: 'PMMA' },
|
||||
peek_crown: { workType: 'AnatomicCrown', material: 'PEEK' },
|
||||
veneer_full_contour: { workType: 'Veneer', material: 'LS2' },
|
||||
veneer_layered: { workType: 'Veneer', material: 'LS2' },
|
||||
inlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
inlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
onlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
onlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
overlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
overlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
|
||||
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: 'AnatomicInlay', material: 'LS2' },
|
||||
};
|
||||
|
||||
export class ExocadTransferError extends Error {
|
||||
constructor(readonly code: 'NOT_EXOCAD') {
|
||||
super(code);
|
||||
this.name = 'ExocadTransferError';
|
||||
}
|
||||
}
|
||||
|
||||
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[];
|
||||
};
|
||||
|
||||
export type ExocadTransferOptions = {
|
||||
now?: string;
|
||||
projectGuid?: string;
|
||||
};
|
||||
|
||||
type ToothWrite = {
|
||||
toothId: string;
|
||||
workType: string;
|
||||
material: string;
|
||||
};
|
||||
|
||||
function sameText(left: string, right: string): boolean {
|
||||
return left.trim().toLowerCase() === right.trim().toLowerCase();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function buildNotes(dentistName: string, comment: string): string | null {
|
||||
const parts = [dentistName.trim(), comment.trim()].filter((part) => part.length > 0);
|
||||
return parts.length > 0 ? parts.join('\n') : null;
|
||||
}
|
||||
|
||||
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 planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: ExocadSkippedLine[] } {
|
||||
const groupMaterial = new Map<string, string>();
|
||||
for (const job of jobs) {
|
||||
const group = job.selectionGroupId?.trim() ?? '';
|
||||
const mapped = RESTORATION[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) => RESTORATION[job.prosthesisTypeCode]);
|
||||
if (restoration) {
|
||||
const mapped = RESTORATION[restoration.prosthesisTypeCode];
|
||||
writes.push({ toothId: tooth, workType: mapped.workType, material: mapped.material });
|
||||
for (const job of group) {
|
||||
if (job === restoration) continue;
|
||||
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) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: pontic.prosthesisTypeCode, reason: 'pontic' });
|
||||
} else {
|
||||
writes.push({ toothId: tooth, workType: 'AnatomicPontic', material });
|
||||
}
|
||||
for (const job of group) {
|
||||
if (job === pontic) continue;
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const job of group) {
|
||||
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
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 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);
|
||||
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'],
|
||||
);
|
||||
return practiceId;
|
||||
}
|
||||
|
||||
function ensurePatient(
|
||||
db: SqliteQuery,
|
||||
practiceId: number,
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
): number {
|
||||
const first = firstName.trim();
|
||||
const last = lastName.trim();
|
||||
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),
|
||||
);
|
||||
if (existing) return numberValue(existing[0]);
|
||||
|
||||
const max = rows.reduce((highest, row) => Math.max(highest, numberValue(row[0])), 0);
|
||||
const patientId = max + 1;
|
||||
db.run(
|
||||
`INSERT INTO patients (lab_id, practice_id, patient_id, fname, lname, dateOfBirth)
|
||||
VALUES (?, ?, ?, ?, ?, NULL)`,
|
||||
[EXOCAD_LAB_ID, practiceId, patientId, first, last],
|
||||
);
|
||||
return patientId;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function insertTeeth(db: SqliteQuery, treatmentId: number, writes: ToothWrite[]): 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],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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 notes = buildNotes(input.dentistName, input.comment);
|
||||
const due = exocadDueDate(input.dueDate);
|
||||
const now = options.now ?? new Date().toISOString();
|
||||
const { writes, skipped } = planTeeth(input.teeth);
|
||||
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]);
|
||||
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],
|
||||
);
|
||||
deleteToothWork(db, treatmentId);
|
||||
insertTeeth(db, treatmentId, writes);
|
||||
return { treatmentId, created: false, skipped };
|
||||
}
|
||||
|
||||
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]);
|
||||
insertTeeth(db, treatmentId, writes);
|
||||
return { treatmentId, created: true, skipped };
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
16
frontend/src/components/local-db/localDbErrors.ts
Normal file
16
frontend/src/components/local-db/localDbErrors.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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',
|
||||
): string {
|
||||
if (error instanceof ExocadTransferError) return t('notExocad');
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
if (message && sqliteFailureCode(message) === 'conflict') return t('conflict');
|
||||
return t(fallback);
|
||||
}
|
||||
58
frontend/src/components/local-db/sqliteSession.ts
Normal file
58
frontend/src/components/local-db/sqliteSession.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
9
frontend/src/components/local-db/sqliteSql.spec.ts
Normal file
9
frontend/src/components/local-db/sqliteSql.spec.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
12
frontend/src/components/local-db/sqliteSql.ts
Normal file
12
frontend/src/components/local-db/sqliteSql.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
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,6 +26,10 @@ import {
|
||||
formatPatientName,
|
||||
} from '@/components/lab/caseDetailUtils';
|
||||
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
|
||||
import { browserCanWriteLocalFile } from '@/components/local-db/browserFile';
|
||||
import type { ExocadCaseInput } from '@/components/local-db/exocadTransfer';
|
||||
import { localDbErrorText } from '@/components/local-db/localDbErrors';
|
||||
import { useLocalDbSession } from '@/components/ui/local-db/LocalDbSessionProvider';
|
||||
import type { CaseSheetOrientation } from '@/components/ui/lab/CaseSheetPrintLayout';
|
||||
import { caseCommentsApi } from '@/lib/api/case-comments';
|
||||
import { casesApi } from '@/lib/api/cases';
|
||||
@@ -63,6 +67,23 @@ function caseSheetLineNotes(labCase: LabCaseDetail): string[] {
|
||||
return notes;
|
||||
}
|
||||
|
||||
function toExocadCase(labCase: LabCaseDetail): ExocadCaseInput {
|
||||
return {
|
||||
caseId: labCase.id,
|
||||
clinicName: labCase.referringClinicName?.trim() || labCase.clinic.name,
|
||||
patientFirstName: labCase.patient.firstName,
|
||||
patientLastName: labCase.patient.lastName,
|
||||
dentistName: labCase.referringDentistName?.trim() ?? '',
|
||||
comment: labCase.detail?.comment?.trim() ?? '',
|
||||
dueDate: labCase.dueDate,
|
||||
teeth: labCase.toothProsthesis.map((row) => ({
|
||||
tooth: row.tooth,
|
||||
prosthesisTypeCode: row.prosthesisTypeCode,
|
||||
selectionGroupId: row.selectionGroupId,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function CurrentRoundTaskStatus({
|
||||
task,
|
||||
statusOptions,
|
||||
@@ -225,6 +246,14 @@ export interface CaseDetailPanelProps {
|
||||
onCaseUpdated?: (detail: LabCaseDetail) => void;
|
||||
}
|
||||
|
||||
/** One equal-width column per header action once the panel is `@xl` wide (full class names for Tailwind). */
|
||||
const HEADER_ACTION_COLUMNS: Record<number, string> = {
|
||||
1: '@xl:grid-cols-1',
|
||||
2: '@xl:grid-cols-2',
|
||||
3: '@xl:grid-cols-3',
|
||||
4: '@xl:grid-cols-4',
|
||||
};
|
||||
|
||||
export function CaseDetailPanel({
|
||||
labCase,
|
||||
locale,
|
||||
@@ -258,6 +287,7 @@ export function CaseDetailPanel({
|
||||
onCaseUpdated,
|
||||
}: CaseDetailPanelProps) {
|
||||
const t = useTranslations('cases');
|
||||
const tLocal = useTranslations('localDb');
|
||||
const tTreatment = useTranslations('treatment');
|
||||
const tComments = useTranslations('caseComments');
|
||||
const tErrors = useTranslations('errors');
|
||||
@@ -265,6 +295,7 @@ export function CaseDetailPanel({
|
||||
const intlLocale = useLocale();
|
||||
const messages = useMessages();
|
||||
const toast = useToast();
|
||||
const localDb = useLocalDbSession();
|
||||
const confirm = useConfirm();
|
||||
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
|
||||
const sectionCounts = useCaseSectionCounts(labCase.id, section);
|
||||
@@ -273,6 +304,7 @@ 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 ?? '');
|
||||
|
||||
@@ -280,6 +312,10 @@ export function CaseDetailPanel({
|
||||
setExternalCodeDraft(labCase.externalCode ?? '');
|
||||
}, [labCase.id, labCase.externalCode]);
|
||||
|
||||
useEffect(() => {
|
||||
setCanWriteLocalFile(browserCanWriteLocalFile());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sheetMenuOpen) return;
|
||||
function onPointerDown(event: MouseEvent) {
|
||||
@@ -394,6 +430,38 @@ export function CaseDetailPanel({
|
||||
}
|
||||
}
|
||||
|
||||
async function onSendToExocad() {
|
||||
const connected = await localDb.requestConnection();
|
||||
if (!connected) return;
|
||||
let result;
|
||||
try {
|
||||
result = localDb.transferCase(toExocadCase(labCase));
|
||||
} catch (caught) {
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await localDb.apply();
|
||||
const id = String(result.treatmentId);
|
||||
if (!labCase.externalCode?.trim() && canEditImportant) {
|
||||
onExternalCodeChange?.(id);
|
||||
}
|
||||
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);
|
||||
if (skipped) toast.showInfo(skipped);
|
||||
} catch (caught) {
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
const pdfLabel = t('downloadCaseSheet');
|
||||
const legacySharedTasks = labCase.tasksByTooth.find(
|
||||
(group) => group.prosthesisTypeCode === CASE_TASK_SCOPE,
|
||||
@@ -423,9 +491,18 @@ export function CaseDetailPanel({
|
||||
...line,
|
||||
}));
|
||||
|
||||
const headerActionCount = Math.min(
|
||||
4,
|
||||
Math.max(
|
||||
1,
|
||||
[Boolean(canStop && onStop), Boolean(canSend && onSend), canWriteLocalFile, true].filter(Boolean)
|
||||
.length,
|
||||
),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 min-w-0">
|
||||
<header className="grid grid-cols-1 items-start gap-2 border-b border-border pb-3 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] lg:items-stretch lg:gap-4">
|
||||
<div className="@container space-y-4 min-w-0">
|
||||
<header className="grid grid-cols-1 items-start gap-3 border-b border-border pb-3 @2xl:grid-cols-[minmax(0,1fr)_auto] @2xl:gap-4">
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -459,7 +536,7 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
</div>
|
||||
{labCase.shareUrl ? (
|
||||
<div className="shrink-0 lg:hidden">
|
||||
<div className="shrink-0 @2xl:hidden">
|
||||
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />
|
||||
</div>
|
||||
) : null}
|
||||
@@ -487,39 +564,36 @@ export function CaseDetailPanel({
|
||||
) : labCase.externalCode?.trim() ? (
|
||||
<p className="text-sm text-text-muted">{labCase.externalCode.trim()}</p>
|
||||
) : null}
|
||||
{canEditImportant ? (
|
||||
<Checkbox
|
||||
checked={labCase.isImportant ?? false}
|
||||
disabled={updatingImportant}
|
||||
label={t('markCaseImportant')}
|
||||
onChange={(checked) => onImportantChange?.(checked)}
|
||||
/>
|
||||
) : labCase.isImportant ? (
|
||||
<Badge variant="warning" fixedWidth={false}>
|
||||
{t('importantLabel')}
|
||||
</Badge>
|
||||
) : null}
|
||||
{labCase.billedAmount != null || labCase.calculatedAmount != null ? (
|
||||
<p className="text-xs text-text-secondary sm:text-sm">
|
||||
<span className="font-bold text-text-primary">{t('billedLead')}</span>
|
||||
{' '}
|
||||
{t('billedCurrencyNote')}
|
||||
{' : '}
|
||||
{formatAppMoney(labCase.billedAmount ?? labCase.calculatedAmount, intlLocale)}
|
||||
{' '}
|
||||
{t('billedCurrencySuffix')}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row flex-wrap items-center justify-between gap-x-3 gap-y-1 lg:h-full lg:flex-col lg:items-center lg:justify-start">
|
||||
{canEditImportant ? (
|
||||
<Checkbox
|
||||
checked={labCase.isImportant ?? false}
|
||||
disabled={updatingImportant}
|
||||
label={t('markCaseImportant')}
|
||||
onChange={(checked) => onImportantChange?.(checked)}
|
||||
/>
|
||||
) : labCase.isImportant ? (
|
||||
<Badge variant="warning" fixedWidth={false}>
|
||||
{t('importantLabel')}
|
||||
</Badge>
|
||||
) : null}
|
||||
{labCase.billedAmount != null || labCase.calculatedAmount != null ? (
|
||||
<p className="text-xs text-text-secondary sm:text-sm lg:mt-auto lg:text-center">
|
||||
<span className="font-bold text-text-primary">{t('billedLead')}</span>
|
||||
{' '}
|
||||
{t('billedCurrencyNote')}
|
||||
{' : '}
|
||||
{formatAppMoney(labCase.billedAmount ?? labCase.calculatedAmount, intlLocale)}
|
||||
{' '}
|
||||
{t('billedCurrencySuffix')}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full shrink-0 flex-col items-stretch gap-2 lg:items-end">
|
||||
<div className="flex w-full flex-wrap items-center gap-2 lg:w-auto lg:justify-end">
|
||||
<div className="flex w-full shrink-0 flex-col items-stretch gap-2 @2xl:w-auto @2xl:items-end">
|
||||
<div className={`grid w-full grid-cols-2 gap-2 @2xl:w-72 @2xl:grid-cols-2 @max-xl:[&>*:last-child:nth-child(odd)]:col-span-2 @2xl:[&>*:last-child:nth-child(odd)]:col-span-2 ${HEADER_ACTION_COLUMNS[headerActionCount]}`}>
|
||||
{canStop && onStop ? (
|
||||
<div className="min-w-0 flex-1 lg:flex-none">
|
||||
<div className="min-w-0">
|
||||
<CaseLifecycleButton
|
||||
variant="danger"
|
||||
label={t('stopCase')}
|
||||
@@ -530,7 +604,7 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
) : null}
|
||||
{canSend && onSend ? (
|
||||
<div className="min-w-0 flex-1 lg:flex-none">
|
||||
<div className="min-w-0">
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={t('sendCase')}
|
||||
@@ -539,7 +613,17 @@ export function CaseDetailPanel({
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div ref={sheetMenuRef} className="relative min-w-0 flex-1 lg:flex-none">
|
||||
{canWriteLocalFile ? (
|
||||
<div className="min-w-0">
|
||||
<CaseLifecycleButton
|
||||
variant="outline"
|
||||
label={t('sendToExocad')}
|
||||
responsiveFill
|
||||
onClick={() => onSendToExocad()}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div ref={sheetMenuRef} className="relative min-w-0">
|
||||
<CaseLifecycleButton
|
||||
variant="primary"
|
||||
label={pdfLabel}
|
||||
@@ -570,7 +654,7 @@ export function CaseDetailPanel({
|
||||
</div>
|
||||
</div>
|
||||
{labCase.shareUrl ? (
|
||||
<div className="hidden shrink-0 lg:block">
|
||||
<div className="hidden shrink-0 @2xl:block">
|
||||
<LabCaseShareQr key={labCase.shareUrl} shareUrl={labCase.shareUrl} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -9,22 +9,19 @@ type CaseLifecycleButtonProps = {
|
||||
label: string;
|
||||
variant: 'primary' | 'danger' | 'outline';
|
||||
icon?: ReactNode;
|
||||
/** Extra labels that widen this button so a longer caption still fits. */
|
||||
matchLabels?: readonly string[];
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
ariaExpanded?: boolean;
|
||||
ariaHaspopup?: 'menu';
|
||||
/** Fill the row below the lg breakpoint. Desktop keeps the shared label width. */
|
||||
/** Fill the parent grid cell at every width (no shared label width). The caption truncates. */
|
||||
responsiveFill?: boolean;
|
||||
onClick: () => void;
|
||||
onClick: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
export function CaseLifecycleButton({
|
||||
label,
|
||||
variant,
|
||||
icon,
|
||||
matchLabels = [],
|
||||
disabled,
|
||||
isLoading,
|
||||
ariaExpanded,
|
||||
@@ -43,7 +40,6 @@ export function CaseLifecycleButton({
|
||||
t('stopCase'),
|
||||
t('sendCase'),
|
||||
tCommon('delete'),
|
||||
...matchLabels,
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -51,30 +47,38 @@ export function CaseLifecycleButton({
|
||||
type="button"
|
||||
variant={variant}
|
||||
size="sm"
|
||||
className={`${WORKSPACE_ACTION_BTN_CLASS}${responsiveFill ? ' w-full min-w-0 lg:w-auto' : ''}`}
|
||||
className={`${WORKSPACE_ACTION_BTN_CLASS}${responsiveFill ? ' w-full min-w-0' : ''}`}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
aria-expanded={ariaExpanded}
|
||||
aria-haspopup={ariaHaspopup}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span className="inline-flex items-center justify-center gap-1.5">
|
||||
<span className="inline-flex max-w-full min-w-0 items-center justify-center gap-1.5">
|
||||
{icon ? <span className="shrink-0">{icon}</span> : null}
|
||||
<span className="inline-grid justify-items-center">
|
||||
{widthLabels.map((text, index) => (
|
||||
<span
|
||||
key={`${index}-${text}`}
|
||||
className={`invisible col-start-1 row-start-1 whitespace-nowrap${responsiveFill ? ' hidden lg:block' : ''}`}
|
||||
aria-hidden
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
))}
|
||||
<span
|
||||
className={`col-start-1 row-start-1 whitespace-nowrap${responsiveFill ? ' max-lg:truncate' : ''}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
className={
|
||||
responsiveFill
|
||||
? 'min-w-0 truncate whitespace-nowrap'
|
||||
: 'inline-grid justify-items-center'
|
||||
}
|
||||
>
|
||||
{responsiveFill
|
||||
? label
|
||||
: (
|
||||
<>
|
||||
{widthLabels.map((text, index) => (
|
||||
<span
|
||||
key={`${index}-${text}`}
|
||||
className="invisible col-start-1 row-start-1 whitespace-nowrap"
|
||||
aria-hidden
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
))}
|
||||
<span className="col-start-1 row-start-1 whitespace-nowrap">{label}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
41
frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx
Normal file
41
frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'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>
|
||||
<div className="mt-4">
|
||||
<LocalDbOpenControls onOpened={onOpened} />
|
||||
</div>
|
||||
</ResponsiveDialogPanel>
|
||||
</ResponsiveDialogOverlay>
|
||||
);
|
||||
}
|
||||
53
frontend/src/components/ui/local-db/LocalDbOpenControls.tsx
Normal file
53
frontend/src/components/ui/local-db/LocalDbOpenControls.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
'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';
|
||||
|
||||
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 {
|
||||
setError(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>
|
||||
);
|
||||
}
|
||||
146
frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx
Normal file
146
frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { transferCaseToExocad, type ExocadCaseInput, type ExocadTransferResult } from '@/components/local-db/exocadTransfer';
|
||||
import {
|
||||
browserCanWriteLocalFile,
|
||||
browserDatabaseStillExists,
|
||||
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.
|
||||
* The next send reopens that file when it still exists. A missing file shows Browse again.
|
||||
*/
|
||||
|
||||
export type LocalDbSessionValue = {
|
||||
apply: () => Promise<void>;
|
||||
requestConnection: () => Promise<boolean>;
|
||||
transferCase: (input: ExocadCaseInput) => ExocadTransferResult;
|
||||
};
|
||||
|
||||
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 {
|
||||
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 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 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 {
|
||||
// The file dialog is the fallback when the saved file cannot be read.
|
||||
}
|
||||
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, requestConnection, transferCase }),
|
||||
[apply, requestConnection, transferCase],
|
||||
);
|
||||
|
||||
return (
|
||||
<LocalDbSessionContext.Provider value={value}>
|
||||
{children}
|
||||
{connectOpen ? (
|
||||
<LocalDbConnectDialog
|
||||
onCancel={() => finishConnect(false)}
|
||||
onOpened={async (sink) => {
|
||||
await replaceWithSink(sink);
|
||||
finishConnect(true);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</LocalDbSessionContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -62,6 +62,7 @@ export function proxy(request: NextRequest) {
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
|
||||
// `.wasm` stays a public file so the in-browser SQLite engine can load.
|
||||
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|wasm)$).*)',
|
||||
],
|
||||
};
|
||||
|
||||
28
frontend/src/types/sqljs.d.ts
vendored
Normal file
28
frontend/src/types/sqljs.d.ts
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
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>;
|
||||
}
|
||||
Reference in New Issue
Block a user