From 57eff31ec00323d109a1341015a18af7a2b58a08 Mon Sep 17 00:00:00 2001 From: rameen Date: Wed, 14 Oct 2026 14:50:13 +0330 Subject: [PATCH 1/3] in the middle of exocat db connection. --- frontend/.gitignore | 5 +- frontend/messages/en.json | 39 ++ frontend/messages/fa.json | 39 ++ frontend/messages/nl.json | 39 ++ frontend/next.config.ts | 1 + frontend/package-lock.json | 117 ++++-- frontend/package.json | 3 + frontend/scripts/copy-sql-wasm.mjs | 8 + .../[locale]/(dashboard)/local-db/page.tsx | 7 + .../src/components/local-db/agentClient.ts | 132 +++++++ .../src/components/local-db/browserFile.ts | 74 ++++ .../src/components/local-db/downloadBytes.ts | 11 + .../src/components/local-db/sqliteSession.ts | 76 ++++ .../src/components/local-db/sqliteSql.spec.ts | 150 +++++++ frontend/src/components/local-db/sqliteSql.ts | 164 ++++++++ frontend/src/components/shared/permissions.ts | 5 + .../components/ui/local-db/LocalDbPage.tsx | 372 ++++++++++++++++++ frontend/src/components/ui/shared/Sidebar.tsx | 7 + frontend/src/proxy.ts | 3 +- frontend/src/types/sqljs.d.ts | 28 ++ local-agent/package.json | 9 + local-agent/src/dialog.js | 56 +++ local-agent/src/guard.js | 46 +++ local-agent/src/guard.test.js | 55 +++ local-agent/src/server.js | 200 ++++++++++ 25 files changed, 1603 insertions(+), 43 deletions(-) create mode 100644 frontend/scripts/copy-sql-wasm.mjs create mode 100644 frontend/src/app/[locale]/(dashboard)/local-db/page.tsx create mode 100644 frontend/src/components/local-db/agentClient.ts create mode 100644 frontend/src/components/local-db/browserFile.ts create mode 100644 frontend/src/components/local-db/downloadBytes.ts create mode 100644 frontend/src/components/local-db/sqliteSession.ts create mode 100644 frontend/src/components/local-db/sqliteSql.spec.ts create mode 100644 frontend/src/components/local-db/sqliteSql.ts create mode 100644 frontend/src/components/ui/local-db/LocalDbPage.tsx create mode 100644 frontend/src/types/sqljs.d.ts create mode 100644 local-agent/package.json create mode 100644 local-agent/src/dialog.js create mode 100644 local-agent/src/guard.js create mode 100644 local-agent/src/guard.test.js create mode 100644 local-agent/src/server.js diff --git a/frontend/.gitignore b/frontend/.gitignore index 2bd9440..6c019a0 100644 --- a/frontend/.gitignore +++ b/frontend/.gitignore @@ -44,4 +44,7 @@ next-env.d.ts # Prisma prisma/*.db -prisma/*.db-journal \ No newline at end of file +prisma/*.db-journal + +# Copied from sql.js before dev/build (see scripts/copy-sql-wasm.mjs) +/public/sql-wasm-browser.wasm \ No newline at end of file diff --git a/frontend/messages/en.json b/frontend/messages/en.json index f03362b..550899c 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -60,6 +60,7 @@ "treatment": "Treatment", "cases": "Cases", "tasks": "Tasks", + "localDb": "Local database", "billing": "Billing", "reports": "Reports", "clinics": "Clinics", @@ -1331,6 +1332,44 @@ "cancel": "Cancel", "walkInPatient": "Walk-in" }, + "localDb": { + "title": "Local database", + "intro": "Choose a SQLite file on this computer. Rows you add stay in this tab until you apply them.", + "safariHelp": "Safari saves back through the local program. Start it, paste the pairing code, then browse. If the program is not running, you can still open a copy and download the updated file.", + "browse": "Browse", + "apply": "Apply", + "downloadCopy": "Download updated file", + "unsaved": "Unsaved changes", + "saved": "Saved to the file", + "noFile": "No file open. Browse for a .db, .sqlite, or .sqlite3 file.", + "tableLabel": "Table", + "noTables": "This file has no tables.", + "emptyTable": "This table has no rows.", + "truncated": "Showing the first {count} rows.", + "addRecord": "Add record", + "add": "Add", + "nullValue": "—", + "blobValue": "(binary)", + "agentOffline": "The local program is not running, so Apply cannot replace the original file. You can still open a copy and download the updated file.", + "pairingLabel": "Pairing code", + "pairingHint": "Printed when the local program starts. It is stored in this browser.", + "pairingRequired": "Enter the pairing code from the local program.", + "pairingRejected": "That pairing code was rejected. Check the code printed by the local program.", + "fileChanged": "The file changed on disk. Browse it again before applying.", + "notSqlite": "Choose a .db, .sqlite, or .sqlite3 file.", + "openFailed": "Could not open that file.", + "loadFailed": "Could not read that database.", + "applyFailed": "Could not write the file.", + "applyDownloaded": "Downloaded an updated copy. That download does not replace the original file.", + "cancelled": "File selection was cancelled.", + "emptyRequired": "Fill in {column}.", + "invalidNumber": "{column} must be a number.", + "conflict": "That record conflicts with a row already in the table.", + "addFailed": "Could not add that record.", + "saveModeBrowser": "Apply writes this file directly.", + "saveModeAgent": "Apply writes this file through the local program.", + "saveModeDownload": "Apply downloads a new copy." + }, "errors": { "GENERIC": "Something went wrong. Please try again.", "NETWORK_ERROR": "Could not reach the server. Check your connection and try again.", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 629d05a..61bd671 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -60,6 +60,7 @@ "treatment": "درمان", "cases": "پرونده‌ها", "tasks": "وظایف", + "localDb": "پایگاه داده محلی", "billing": "صورتحساب", "reports": "گزارش‌ها", "clinics": "کلینیک‌ها", @@ -1332,6 +1333,44 @@ "cancel": "انصراف", "walkInPatient": "بدون نوبت" }, + "localDb": { + "title": "پایگاه داده محلی", + "intro": "یک فایل SQLite روی همین رایانه انتخاب کنید. ردیف‌هایی که اضافه می‌کنید تا زدن اعمال، فقط در همین برگه می‌مانند.", + "safariHelp": "سافاری از راه برنامه محلی فایل را ذخیره می‌کند. آن را اجرا کنید، کد جفت‌سازی را بچسبانید، سپس مرور کنید. اگر برنامه در حال اجرا نیست، باز هم می‌توانید یک نسخه باز کنید و فایل به‌روز را دانلود کنید.", + "browse": "مرور", + "apply": "اعمال", + "downloadCopy": "دانلود فایل به‌روز", + "unsaved": "تغییرهای ذخیره‌نشده", + "saved": "در فایل ذخیره شد", + "noFile": "فایلی باز نیست. یک فایل ‎.db یا ‎.sqlite یا ‎.sqlite3 را مرور کنید.", + "tableLabel": "جدول", + "noTables": "این فایل جدولی ندارد.", + "emptyTable": "این جدول ردیفی ندارد.", + "truncated": "‏{count} ردیف اول نشان داده می‌شود.", + "addRecord": "افزودن رکورد", + "add": "افزودن", + "nullValue": "—", + "blobValue": "(داده دودویی)", + "agentOffline": "برنامه محلی در حال اجرا نیست، پس اعمال نمی‌تواند فایل اصلی را جایگزین کند. هنوز می‌توانید یک نسخه باز کنید و فایل به‌روز را دانلود کنید.", + "pairingLabel": "کد جفت‌سازی", + "pairingHint": "هنگام شروع برنامه محلی چاپ می‌شود و در همین مرورگر ذخیره می‌گردد.", + "pairingRequired": "کد جفت‌سازی را از برنامه محلی وارد کنید.", + "pairingRejected": "این کد جفت‌سازی پذیرفته نشد. کدی را که برنامه محلی چاپ کرده بررسی کنید.", + "fileChanged": "فایل روی دیسک عوض شده است. پیش از اعمال، دوباره آن را مرور کنید.", + "notSqlite": "یک فایل ‎.db یا ‎.sqlite یا ‎.sqlite3 انتخاب کنید.", + "openFailed": "این فایل باز نشد.", + "loadFailed": "این پایگاه داده خوانده نشد.", + "applyFailed": "نوشتن فایل انجام نشد.", + "applyDownloaded": "یک نسخه به‌روز دانلود شد. این دانلود جایگزین فایل اصلی نمی‌شود.", + "cancelled": "انتخاب فایل لغو شد.", + "emptyRequired": "‏{column} را پر کنید.", + "invalidNumber": "‏{column} باید عدد باشد.", + "conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.", + "addFailed": "این رکورد اضافه نشد.", + "saveModeBrowser": "اعمال این فایل را مستقیم می‌نویسد.", + "saveModeAgent": "اعمال این فایل را از راه برنامه محلی می‌نویسد.", + "saveModeDownload": "اعمال یک نسخه تازه دانلود می‌کند." + }, "errors": { "GENERIC": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.", "NETWORK_ERROR": "اتصال به سرور برقرار نشد. اتصال اینترنت را بررسی کنید.", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 58b009a..3c6a86f 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -60,6 +60,7 @@ "treatment": "Behandeling", "cases": "Dossiers", "tasks": "Taken", + "localDb": "Lokale database", "billing": "Facturatie", "reports": "Rapporten", "clinics": "Klinieken", @@ -1331,6 +1332,44 @@ "cancel": "Annuleren", "walkInPatient": "Walk-in" }, + "localDb": { + "title": "Lokale database", + "intro": "Kies een SQLite-bestand op deze computer. Rijen die u toevoegt blijven in dit tabblad tot u ze toepast.", + "safariHelp": "Safari schrijft terug via het lokale programma. Start het, plak de koppelcode en blader. Als het programma niet draait, kunt u nog steeds een kopie openen en het bijgewerkte bestand downloaden.", + "browse": "Bladeren", + "apply": "Toepassen", + "downloadCopy": "Bijgewerkt bestand downloaden", + "unsaved": "Niet-opgeslagen wijzigingen", + "saved": "Opgeslagen in het bestand", + "noFile": "Geen bestand open. Blader naar een .db-, .sqlite- of .sqlite3-bestand.", + "tableLabel": "Tabel", + "noTables": "Dit bestand heeft geen tabellen.", + "emptyTable": "Deze tabel heeft geen rijen.", + "truncated": "De eerste {count} rijen worden getoond.", + "addRecord": "Record toevoegen", + "add": "Toevoegen", + "nullValue": "—", + "blobValue": "(binair)", + "agentOffline": "Het lokale programma draait niet, dus Toepassen kan het oorspronkelijke bestand niet vervangen. U kunt nog steeds een kopie openen en het bijgewerkte bestand downloaden.", + "pairingLabel": "Koppelcode", + "pairingHint": "Wordt afgedrukt wanneer het lokale programma start. De code blijft in deze browser bewaard.", + "pairingRequired": "Vul de koppelcode van het lokale programma in.", + "pairingRejected": "Die koppelcode is geweigerd. Controleer de code die het lokale programma afdrukt.", + "fileChanged": "Het bestand op schijf is gewijzigd. Blader er opnieuw naartoe voordat u toepast.", + "notSqlite": "Kies een .db-, .sqlite- of .sqlite3-bestand.", + "openFailed": "Dat bestand kon niet worden geopend.", + "loadFailed": "Die database kon niet worden gelezen.", + "applyFailed": "Het bestand kon niet worden geschreven.", + "applyDownloaded": "Een bijgewerkte kopie is gedownload. Die download vervangt het oorspronkelijke bestand niet.", + "cancelled": "Bestandskeuze is geannuleerd.", + "emptyRequired": "Vul {column} in.", + "invalidNumber": "{column} moet een getal zijn.", + "conflict": "Dat record botst met een rij die al in de tabel staat.", + "addFailed": "Dat record kon niet worden toegevoegd.", + "saveModeBrowser": "Toepassen schrijft dit bestand direct.", + "saveModeAgent": "Toepassen schrijft dit bestand via het lokale programma.", + "saveModeDownload": "Toepassen downloadt een nieuwe kopie." + }, "errors": { "GENERIC": "Er is iets misgegaan. Probeer het opnieuw.", "NETWORK_ERROR": "Kan de server niet bereiken. Controleer uw verbinding.", diff --git a/frontend/next.config.ts b/frontend/next.config.ts index c4ebdf5..9989af8 100644 --- a/frontend/next.config.ts +++ b/frontend/next.config.ts @@ -41,6 +41,7 @@ const nextConfig: NextConfig = { }, output: 'standalone', compress: true, + serverExternalPackages: ['sql.js'], }; export default withSentryConfig(withNextIntl(nextConfig), { diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1c03b7a..00c8382 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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" } diff --git a/frontend/package.json b/frontend/package.json index 9930109..4d5926e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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": { diff --git a/frontend/scripts/copy-sql-wasm.mjs b/frontend/scripts/copy-sql-wasm.mjs new file mode 100644 index 0000000..1ee77a6 --- /dev/null +++ b/frontend/scripts/copy-sql-wasm.mjs @@ -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); diff --git a/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx b/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx new file mode 100644 index 0000000..3f995ae --- /dev/null +++ b/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx @@ -0,0 +1,7 @@ +'use client'; + +import { LocalDbPage } from '@/components/ui/local-db/LocalDbPage'; + +export default function Page() { + return ; +} diff --git a/frontend/src/components/local-db/agentClient.ts b/frontend/src/components/local-db/agentClient.ts new file mode 100644 index 0000000..ea9e216 --- /dev/null +++ b/frontend/src/components/local-db/agentClient.ts @@ -0,0 +1,132 @@ +import type { DatabaseSink } from '@/components/local-db/browserFile'; + +export const AGENT_ORIGIN = 'http://127.0.0.1:17654'; +export const AGENT_TOKEN_STORAGE_KEY = 'dyolink.localSqliteAgentToken'; + +export class AgentError extends Error { + constructor( + readonly code: + | 'UNREACHABLE' + | 'UNAUTHORIZED' + | 'FILE_CHANGED' + | 'CANCELLED' + | 'NOT_OPEN' + | 'BAD_EXTENSION' + | 'NOT_SQLITE' + | 'TOO_LARGE' + | 'BUSY' + | 'FAILED', + ) { + super(code); + this.name = 'AgentError'; + } +} + +type AgentFailure = { + error?: string; +}; + +function bytesToBase64(bytes: Uint8Array): string { + let binary = ''; + const chunk = 0x8000; + for (let index = 0; index < bytes.length; index += chunk) { + const slice = bytes.subarray(index, index + chunk); + binary += String.fromCharCode(...slice); + } + return btoa(binary); +} + +function base64ToBytes(value: string): Uint8Array { + const binary = atob(value); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index += 1) { + bytes[index] = binary.charCodeAt(index); + } + return bytes; +} + +async function agentFetch(path: string, token: string | null, init?: RequestInit): Promise { + try { + return await fetch(`${AGENT_ORIGIN}${path}`, { + ...init, + headers: { + ...(init?.headers ?? {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + }); + } catch { + throw new AgentError('UNREACHABLE'); + } +} + +function failureCode(status: number, body: AgentFailure): AgentError['code'] { + if (status === 401) return 'UNAUTHORIZED'; + if (status === 413) return 'TOO_LARGE'; + if (body.error === 'PATH_MISMATCH') return 'FILE_CHANGED'; + switch (body.error) { + case 'FILE_CHANGED': + case 'CANCELLED': + case 'NOT_OPEN': + case 'BAD_EXTENSION': + case 'NOT_SQLITE': + case 'BUSY': + return body.error; + default: + return 'FAILED'; + } +} + +export async function agentIsRunning(): Promise { + try { + const response = await fetch(`${AGENT_ORIGIN}/health`, { + signal: AbortSignal.timeout(1500), + }); + return response.ok; + } catch { + return false; + } +} + +export function readStoredAgentToken(): string { + if (typeof localStorage === 'undefined') return ''; + return localStorage.getItem(AGENT_TOKEN_STORAGE_KEY) ?? ''; +} + +export function storeAgentToken(token: string): void { + const trimmed = token.trim(); + if (!trimmed) { + localStorage.removeItem(AGENT_TOKEN_STORAGE_KEY); + return; + } + localStorage.setItem(AGENT_TOKEN_STORAGE_KEY, trimmed); +} + +/** Ask the local program to show the system file dialog and read that file. */ +export async function openWithAgent(token: string): Promise { + const response = await agentFetch('/open', token, { method: 'POST' }); + const body = (await response.json().catch(() => ({}))) as AgentFailure & { + name?: string; + bytesBase64?: string; + }; + if (!response.ok || !body.name || !body.bytesBase64) { + throw new AgentError(failureCode(response.status, body)); + } + const name = body.name; + const bytes = base64ToBytes(body.bytesBase64); + return { + name, + kind: 'agent', + bytes, + write: async (next) => { + const writeResponse = await agentFetch('/write', token, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ bytesBase64: bytesToBase64(next) }), + }); + if (!writeResponse.ok) { + const writeBody = (await writeResponse.json().catch(() => ({}))) as AgentFailure; + throw new AgentError(failureCode(writeResponse.status, writeBody)); + } + }, + }; +} diff --git a/frontend/src/components/local-db/browserFile.ts b/frontend/src/components/local-db/browserFile.ts new file mode 100644 index 0000000..96688b8 --- /dev/null +++ b/frontend/src/components/local-db/browserFile.ts @@ -0,0 +1,74 @@ +export type DatabaseKind = 'browser' | 'agent' | 'download'; + +export type DatabaseSink = { + name: string; + kind: DatabaseKind; + bytes: Uint8Array; + write: (bytes: Uint8Array) => Promise; +}; + +type FilePickerHandle = { + getFile: () => Promise; + createWritable: () => Promise<{ + write: (data: BufferSource) => Promise; + close: () => Promise; + }>; +}; + +type OpenFilePicker = (options?: { + multiple?: boolean; + excludeAcceptAllOption?: boolean; + types?: Array<{ description?: string; accept: Record }>; +}) => Promise; + +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' + ); +} + +export async function openWithBrowserPicker(): Promise { + const picker = filePicker(); + if (!picker) { + throw new Error('FILE_PICKER_UNAVAILABLE'); + } + const [handle] = await picker({ + multiple: false, + excludeAcceptAllOption: false, + types: [ + { + description: 'SQLite database', + accept: { + 'application/vnd.sqlite3': ['.db', '.sqlite', '.sqlite3'], + 'application/x-sqlite3': ['.db', '.sqlite', '.sqlite3'], + }, + }, + ], + }); + const file = await handle.getFile(); + const bytes = new Uint8Array(await file.arrayBuffer()); + return { + name: file.name, + kind: 'browser', + bytes, + write: async (next) => { + const writable = await handle.createWritable(); + await writable.write(Uint8Array.from(next)); + await writable.close(); + }, + }; +} diff --git a/frontend/src/components/local-db/downloadBytes.ts b/frontend/src/components/local-db/downloadBytes.ts new file mode 100644 index 0000000..fdb9bd4 --- /dev/null +++ b/frontend/src/components/local-db/downloadBytes.ts @@ -0,0 +1,11 @@ +/** Save a copy. This does not replace the file the user originally opened. */ +export function downloadBytes(filename: string, bytes: Uint8Array): void { + const copy = bytes.slice(); + const blob = new Blob([copy.buffer as ArrayBuffer]); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + link.click(); + URL.revokeObjectURL(url); +} diff --git a/frontend/src/components/local-db/sqliteSession.ts b/frontend/src/components/local-db/sqliteSession.ts new file mode 100644 index 0000000..c56c010 --- /dev/null +++ b/frontend/src/components/local-db/sqliteSession.ts @@ -0,0 +1,76 @@ +import { + insertRow, + listUserTables, + readTable, + type SqliteCell, + type SqliteColumn, +} 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 | 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) { + return { + all(sql: string, params: Array = []): 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 = []) { + 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 { + const SQL = await loadSqlJs(); + return new LocalSqlite(new SQL.Database(bytes)); + } + + listTables(): string[] { + return listUserTables(asQuery(this.db)); + } + + readTable(name: string): { + columns: SqliteColumn[]; + rows: SqliteCell[][]; + truncated: boolean; + } { + return readTable(asQuery(this.db), name); + } + + insertRow(table: string, raw: Record): void { + insertRow(asQuery(this.db), table, raw); + } + + exportBytes(): Uint8Array { + const exported = this.db.export(); + return new Uint8Array(exported); + } + + close(): void { + this.db.close(); + } +} diff --git a/frontend/src/components/local-db/sqliteSql.spec.ts b/frontend/src/components/local-db/sqliteSql.spec.ts new file mode 100644 index 0000000..d2767e6 --- /dev/null +++ b/frontend/src/components/local-db/sqliteSql.spec.ts @@ -0,0 +1,150 @@ +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { + SqliteEditError, + TABLE_ROW_LIMIT, + buildInsert, + insertRow, + listUserTables, + quoteIdent, + readTable, + sqliteFailureCode, + type SqliteCell, + type SqliteColumn, + type SqliteQuery, +} from './sqliteSql'; + +const require = createRequire(import.meta.url); + +type SqlStatement = { + bind(values?: Array): void; + step(): boolean; + get(): SqliteCell[]; + free(): void; +}; + +type SqlDatabase = { + run(sql: string, params?: Array): void; + prepare(sql: string): SqlStatement; + export(): Uint8Array; + close(): void; +}; + +async function openSql(bytes?: Uint8Array): Promise { + const initSqlJs = require('sql.js') as (config?: { + wasmBinary?: Uint8Array; + }) => Promise<{ Database: new (data?: Uint8Array) => SqlDatabase }>; + const wasm = readFileSync(require.resolve('sql.js/dist/sql-wasm.wasm')); + const SQL = await initSqlJs({ wasmBinary: wasm }); + return new SQL.Database(bytes); +} + +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); + }, + }; +} + +const peopleColumns: SqliteColumn[] = [ + { name: 'id', type: 'INTEGER', notNull: false, defaultValue: null, pk: 1 }, + { name: 'name', type: 'TEXT', notNull: true, defaultValue: null, pk: 0 }, +]; + +describe('quoteIdent', () => { + it('quotes a name that contains a double quote', () => { + expect(quoteIdent('a"b')).toBe('"a""b"'); + }); +}); + +describe('buildInsert', () => { + it('omits a blank integer primary key and binds the other values', () => { + const plan = buildInsert('people', peopleColumns, { id: '', name: 'Ada' }); + expect(plan.sql).toBe('INSERT INTO "people" ("name") VALUES (?)'); + expect(plan.params).toEqual(['Ada']); + }); + + it('keeps a hostile table name inside one identifier', () => { + const plan = buildInsert('t"; drop table t; --', peopleColumns, { + id: '4', + name: 'Ada', + }); + expect(plan.sql).toBe( + 'INSERT INTO "t""; drop table t; --" ("id", "name") VALUES (?, ?)', + ); + expect(plan.params).toEqual([4, 'Ada']); + }); + + it('rejects an empty required column', () => { + expect(() => buildInsert('people', peopleColumns, { id: '', name: ' ' })).toThrow( + SqliteEditError, + ); + }); + + it('rejects a non-numeric integer', () => { + try { + buildInsert('people', peopleColumns, { id: 'nope', name: 'Ada' }); + expect.fail('expected INVALID_NUMBER'); + } catch (error) { + expect(error).toBeInstanceOf(SqliteEditError); + expect((error as SqliteEditError).code).toBe('INVALID_NUMBER'); + expect((error as SqliteEditError).column).toBe('id'); + } + }); +}); + +describe('sqlite tables', () => { + it('lists user tables, inserts a row, and reloads the exported file', async () => { + const db = await openSql(); + const query = asQuery(db); + db.run( + 'CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)', + ); + db.run('CREATE TABLE visits (id INTEGER PRIMARY KEY)'); + + expect(listUserTables(query)).toEqual(['people', 'visits']); + + insertRow(query, 'people', { id: '', name: 'Ada' }); + const table = readTable(query, 'people'); + expect(table.columns.map((column) => column.name)).toEqual(['id', 'name']); + expect(table.rows).toEqual([[1, 'Ada']]); + expect(table.truncated).toBe(false); + + const reloaded = await openSql(db.export()); + expect(listUserTables(asQuery(reloaded))).toEqual(['people', 'visits']); + expect(readTable(asQuery(reloaded), 'people').rows).toEqual([[1, 'Ada']]); + db.close(); + reloaded.close(); + }); + + it('marks the read as truncated past the row limit', async () => { + const db = await openSql(); + const query = asQuery(db); + db.run('CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)'); + const extra = TABLE_ROW_LIMIT + 1; + for (let i = 0; i < extra; i += 1) { + db.run('INSERT INTO notes (body) VALUES (?)', [`n${i}`]); + } + const table = readTable(query, 'notes'); + expect(table.rows).toHaveLength(TABLE_ROW_LIMIT); + expect(table.truncated).toBe(true); + db.close(); + }); +}); + +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'); + }); +}); diff --git a/frontend/src/components/local-db/sqliteSql.ts b/frontend/src/components/local-db/sqliteSql.ts new file mode 100644 index 0000000..c6b4c25 --- /dev/null +++ b/frontend/src/components/local-db/sqliteSql.ts @@ -0,0 +1,164 @@ +export const TABLE_ROW_LIMIT = 200; + +export type SqliteCell = string | number | null | Uint8Array; + +export type SqliteColumn = { + name: string; + type: string; + notNull: boolean; + defaultValue: string | null; + pk: number; +}; + +export type SqliteQuery = { + all(sql: string, params?: Array): SqliteCell[][]; + run(sql: string, params?: Array): void; +}; + +export class SqliteEditError extends Error { + constructor( + readonly code: 'EMPTY_REQUIRED' | 'INVALID_NUMBER' | 'UNKNOWN_TABLE', + readonly column = '', + ) { + super(code); + this.name = 'SqliteEditError'; + } +} + +export type InsertPlan = { + sql: string; + params: Array; +}; + +/** Double-quote a SQLite identifier, including embedded quotes. */ +export function quoteIdent(name: string): string { + return `"${name.replaceAll('"', '""')}"`; +} + +export function listUserTables(db: SqliteQuery): string[] { + const rows = db.all( + `SELECT name FROM sqlite_master + WHERE type = 'table' AND name NOT LIKE 'sqlite_%' + ORDER BY name`, + ); + return rows.map((row) => String(row[0])); +} + +export function tableColumns(db: SqliteQuery, table: string): SqliteColumn[] { + const rows = db.all(`PRAGMA table_info(${quoteIdent(table)})`); + return rows.map((row) => ({ + name: String(row[1] ?? ''), + type: row[2] == null ? '' : String(row[2]), + notNull: Number(row[3]) === 1, + defaultValue: row[4] == null ? null : String(row[4]), + pk: Number(row[5] ?? 0), + })); +} + +export function readTable( + db: SqliteQuery, + table: string, + limit = TABLE_ROW_LIMIT, +): { columns: SqliteColumn[]; rows: SqliteCell[][]; truncated: boolean } { + const columns = tableColumns(db, table); + const fetched = db.all( + `SELECT * FROM ${quoteIdent(table)} LIMIT ${limit + 1}`, + ); + const truncated = fetched.length > limit; + return { + columns, + rows: truncated ? fetched.slice(0, limit) : fetched, + truncated, + }; +} + +export function columnIsRequired(column: SqliteColumn): boolean { + if (column.pk > 0 && isIntegerType(column.type)) return false; + return column.notNull && column.defaultValue == null; +} + +function isIntegerType(declared: string): boolean { + const type = declared.toUpperCase(); + return type.includes('INT') || type.includes('BOOL'); +} + +function isRealType(declared: string): boolean { + const type = declared.toUpperCase(); + return ( + type.includes('REAL') || + type.includes('FLOA') || + type.includes('DOUB') || + type.includes('NUMERIC') || + type.includes('DECIMAL') + ); +} + +function coerceCell( + column: SqliteColumn, + raw: string, +): { omit: true } | { omit: false; value: string | number | null } { + const trimmed = raw.trim(); + if (trimmed === '') { + if (column.pk > 0 && isIntegerType(column.type)) return { omit: true }; + if (column.notNull && column.defaultValue == null) { + throw new SqliteEditError('EMPTY_REQUIRED', column.name); + } + if (column.notNull && column.defaultValue != null) return { omit: true }; + return { omit: false, value: null }; + } + if (isIntegerType(column.type)) { + if (!/^-?\d+$/.test(trimmed)) { + throw new SqliteEditError('INVALID_NUMBER', column.name); + } + return { omit: false, value: Number(trimmed) }; + } + if (isRealType(column.type)) { + if (!/^-?(?:\d+\.?\d*|\.\d+)$/.test(trimmed)) { + throw new SqliteEditError('INVALID_NUMBER', column.name); + } + return { omit: false, value: Number(trimmed) }; + } + return { omit: false, value: raw }; +} + +/** INSERT for one row. Blank integer primary keys are left for SQLite to assign. */ +export function buildInsert( + table: string, + columns: SqliteColumn[], + raw: Record, +): InsertPlan { + const names: string[] = []; + const params: Array = []; + for (const column of columns) { + const coerced = coerceCell(column, raw[column.name] ?? ''); + if (coerced.omit) continue; + names.push(quoteIdent(column.name)); + params.push(coerced.value); + } + if (names.length === 0) { + return { sql: `INSERT INTO ${quoteIdent(table)} DEFAULT VALUES`, params: [] }; + } + const placeholders = names.map(() => '?').join(', '); + return { + sql: `INSERT INTO ${quoteIdent(table)} (${names.join(', ')}) VALUES (${placeholders})`, + params, + }; +} + +export function insertRow( + db: SqliteQuery, + table: string, + raw: Record, +): void { + if (!listUserTables(db).includes(table)) { + throw new SqliteEditError('UNKNOWN_TABLE'); + } + const plan = buildInsert(table, tableColumns(db, table), raw); + db.run(plan.sql, plan.params); +} + +/** 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'; +} diff --git a/frontend/src/components/shared/permissions.ts b/frontend/src/components/shared/permissions.ts index c71f636..57f7bb5 100644 --- a/frontend/src/components/shared/permissions.ts +++ b/frontend/src/components/shared/permissions.ts @@ -62,6 +62,11 @@ export function getRequiredReadPermissionForPath(pathname: string): string | nul export function canAccessDashboardRoute(org: Organization | null, pathname: string): boolean { if (!org) return false; + // Temporary. Lab-only, and not in DASHBOARD_ROUTES so it is never the landing page. + if (pathname === '/local-db' || pathname.startsWith('/local-db/')) { + return org.type === 'LAB'; + } + const route = getRouteConfigForPath(pathname); if (!route) return true; diff --git a/frontend/src/components/ui/local-db/LocalDbPage.tsx b/frontend/src/components/ui/local-db/LocalDbPage.tsx new file mode 100644 index 0000000..5c71334 --- /dev/null +++ b/frontend/src/components/ui/local-db/LocalDbPage.tsx @@ -0,0 +1,372 @@ +'use client'; + +import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'; +import { useTranslations } from 'next-intl'; +import { Button } from '@/components/ui/shared/Button'; +import { Input } from '@/components/ui/shared/Input'; +import { Table, TABLE_HEADER_CELL_CLASS } from '@/components/ui/shared/Table'; +import { useToast } from '@/components/ui/shared/ToastProvider'; +import { + AgentError, + agentIsRunning, + openWithAgent, + readStoredAgentToken, + storeAgentToken, +} from '@/components/local-db/agentClient'; +import { + browserCanWriteLocalFile, + isPickerCancel, + openWithBrowserPicker, + type DatabaseKind, + type DatabaseSink, +} from '@/components/local-db/browserFile'; +import { downloadBytes } from '@/components/local-db/downloadBytes'; +import { LocalSqlite } from '@/components/local-db/sqliteSession'; +import { + SqliteEditError, + TABLE_ROW_LIMIT, + columnIsRequired, + sqliteFailureCode, + type SqliteCell, + type SqliteColumn, +} from '@/components/local-db/sqliteSql'; +import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles'; + +function cellText(value: SqliteCell, nullLabel: string, blobLabel: string): string { + if (value == null) return nullLabel; + if (value instanceof Uint8Array) return blobLabel; + return String(value); +} + +function describeError( + error: unknown, + t: (key: string, values?: Record) => string, + fallback: 'openFailed' | 'applyFailed' | 'addFailed', +): string { + if (error instanceof SqliteEditError) { + if (error.code === 'EMPTY_REQUIRED') return t('emptyRequired', { column: error.column }); + if (error.code === 'INVALID_NUMBER') return t('invalidNumber', { column: error.column }); + return t('loadFailed'); + } + if (error instanceof AgentError) { + if (error.code === 'UNAUTHORIZED') return t('pairingRejected'); + if (error.code === 'FILE_CHANGED') return t('fileChanged'); + if (error.code === 'CANCELLED') return t('cancelled'); + if (error.code === 'BAD_EXTENSION' || error.code === 'NOT_SQLITE') return t('notSqlite'); + if (error.code === 'UNREACHABLE') return t('agentOffline'); + return t(fallback); + } + const message = error instanceof Error ? error.message : ''; + if (message && sqliteFailureCode(message) === 'conflict') return t('conflict'); + if (message) return t(fallback); + return t(fallback); +} + +export function LocalDbPage() { + const t = useTranslations('localDb'); + const { showSuccess, showInfo } = useToast(); + const sessionRef = useRef(null); + const sinkRef = useRef(null); + const fileInputRef = useRef(null); + + const [canWriteDirect, setCanWriteDirect] = useState(false); + const [checkedBrowser, setCheckedBrowser] = useState(false); + const [agentOnline, setAgentOnline] = useState(null); + const [pairing, setPairing] = useState(''); + const [fileName, setFileName] = useState(''); + const [kind, setKind] = useState(null); + const [dirty, setDirty] = useState(false); + const [tables, setTables] = useState([]); + const [selectedTable, setSelectedTable] = useState(''); + const [columns, setColumns] = useState([]); + const [rows, setRows] = useState([]); + const [truncated, setTruncated] = useState(false); + const [draft, setDraft] = useState>({}); + const [revision, setRevision] = useState(0); + const [error, setError] = useState(''); + + useEffect(() => { + const direct = browserCanWriteLocalFile(); + setCanWriteDirect(direct); + setCheckedBrowser(true); + setPairing(readStoredAgentToken()); + if (!direct) { + void agentIsRunning().then(setAgentOnline); + } + }, []); + + useEffect(() => { + const session = sessionRef.current; + if (!session || !selectedTable) { + setColumns([]); + setRows([]); + setTruncated(false); + return; + } + try { + const data = session.readTable(selectedTable); + setColumns(data.columns); + setRows(data.rows); + setTruncated(data.truncated); + setDraft({}); + } catch { + setError(t('loadFailed')); + } + }, [selectedTable, revision, t]); + + async function loadSink(sink: DatabaseSink) { + let session: LocalSqlite; + try { + session = await LocalSqlite.open(sink.bytes); + } catch { + setError(t('loadFailed')); + return; + } + sessionRef.current?.close(); + sessionRef.current = session; + sinkRef.current = sink; + const names = session.listTables(); + setFileName(sink.name); + setKind(sink.kind); + setDirty(false); + setTables(names); + setSelectedTable(names[0] ?? ''); + setRevision((value) => value + 1); + setError(''); + } + + async function onBrowse() { + setError(''); + if (browserCanWriteLocalFile()) { + try { + await loadSink(await openWithBrowserPicker()); + } catch (caught) { + if (isPickerCancel(caught)) return; + setError(t('openFailed')); + } + return; + } + + const token = pairing.trim(); + if (!token) { + setError(t('pairingRequired')); + return; + } + storeAgentToken(token); + if (agentOnline === false) { + fileInputRef.current?.click(); + return; + } + try { + await loadSink(await openWithAgent(token)); + setAgentOnline(true); + } catch (caught) { + if (caught instanceof AgentError && caught.code === 'UNREACHABLE') { + setAgentOnline(false); + setError(t('agentOffline')); + return; + } + if (caught instanceof AgentError && caught.code === 'CANCELLED') { + setError(t('cancelled')); + return; + } + setError(describeError(caught, t, 'openFailed')); + } + } + + async function onFileInput(event: ChangeEvent) { + const file = event.target.files?.[0]; + event.target.value = ''; + if (!file) return; + const lower = file.name.toLowerCase(); + if (!lower.endsWith('.db') && !lower.endsWith('.sqlite') && !lower.endsWith('.sqlite3')) { + setError(t('notSqlite')); + return; + } + const bytes = new Uint8Array(await file.arrayBuffer()); + await loadSink({ + name: file.name, + kind: 'download', + bytes, + write: async (next) => { + downloadBytes(file.name, next); + }, + }); + } + + function onAdd(event: FormEvent) { + event.preventDefault(); + const session = sessionRef.current; + if (!session || !selectedTable) return; + try { + session.insertRow(selectedTable, draft); + setDirty(true); + setError(''); + setRevision((value) => value + 1); + } catch (caught) { + setError(describeError(caught, t, 'addFailed')); + } + } + + async function onApply() { + const session = sessionRef.current; + const sink = sinkRef.current; + if (!session || !sink) return; + try { + await sink.write(session.exportBytes()); + setDirty(false); + setError(''); + if (sink.kind === 'download') showInfo(t('applyDownloaded')); + else showSuccess(t('saved')); + } catch (caught) { + setError(describeError(caught, t, 'applyFailed')); + } + } + + const saveMode = + kind === 'browser' ? t('saveModeBrowser') : kind === 'agent' ? t('saveModeAgent') : kind === 'download' ? t('saveModeDownload') : ''; + + return ( +
+
+

{t('title')}

+

{t('intro')}

+ {checkedBrowser && !canWriteDirect ? ( +

{t('safariHelp')}

+ ) : null} +
+ + {checkedBrowser && !canWriteDirect && agentOnline === false ? ( +

+ {t('agentOffline')} +

+ ) : null} + + {checkedBrowser && !canWriteDirect ? ( +
+ { + setPairing(event.target.value); + storeAgentToken(event.target.value); + }} + /> +

{t('pairingHint')}

+
+ ) : null} + +
+ + + void onFileInput(event)} + /> +
+ + {error ? ( +

+ {error} +

+ ) : null} + + {fileName ? ( +
+

+ {fileName} + {dirty ? {t('unsaved')} : null} +

+ {saveMode ?

{saveMode}

: null} +
+ ) : ( +

{t('noFile')}

+ )} + + {fileName && tables.length === 0 ?

{t('noTables')}

: null} + + {tables.length > 0 ? ( + + ) : null} + + {selectedTable && columns.length > 0 ? ( + rows.length > 0 ? ( + + {columns.map((column) => ( + + ))} + + } + body={rows.map((row, rowIndex) => ( + + {row.map((value, columnIndex) => { + const text = cellText(value, t('nullValue'), t('blobValue')); + return ( + + ); + })} + + ))} + /> + ) : ( +

{t('emptyTable')}

+ ) + ) : null} + + {truncated ? ( +

{t('truncated', { count: TABLE_ROW_LIMIT })}

+ ) : null} + + {selectedTable && columns.length > 0 ? ( + +

{t('addRecord')}

+
+ {columns.map((column) => ( + + setDraft((current) => ({ ...current, [column.name]: event.target.value })) + } + /> + ))} +
+ + + ) : null} + + ); +} diff --git a/frontend/src/components/ui/shared/Sidebar.tsx b/frontend/src/components/ui/shared/Sidebar.tsx index 99c536c..e8065f9 100644 --- a/frontend/src/components/ui/shared/Sidebar.tsx +++ b/frontend/src/components/ui/shared/Sidebar.tsx @@ -14,6 +14,7 @@ import { Package, ListTodo, Building2, + Database, X, } from 'lucide-react'; import type { OrgTypeName } from '@/components/shared/permissions'; @@ -70,6 +71,8 @@ function Sidebar({ mobileOpen = false, onClose }: SidebarProps) { { name: t('patients'), path: '/patients', icon: Users, read: 'TAB_PATIENTS_READ', orgTypes: ['CLINIC'] }, { name: t('cases'), path: '/cases', icon: Package, read: 'TAB_CASES_READ', orgTypes: ['LAB'] }, { name: t('tasks'), path: '/tasks', icon: ListTodo, read: 'TAB_TASKS_READ', orgTypes: ['LAB'] }, + // Temporary. Remove this item when the local database page goes away. + { name: t('localDb'), path: '/local-db', icon: Database, read: '', orgTypes: ['LAB'] }, { name: t('appointment'), path: '/appointments', icon: Calendar, read: 'TAB_APPOINTMENTS_READ', orgTypes: ['CLINIC'] }, { name: t('treatment'), path: '/treatment', icon: FlaskConical, read: 'TAB_TREATMENT_READ', orgTypes: ['CLINIC'] }, { name: t('billing'), path: '/billing', icon: CreditCard, read: 'TAB_BILLING_READ', orgTypes: ['CLINIC', 'LAB'] }, @@ -96,6 +99,10 @@ function Sidebar({ mobileOpen = false, onClose }: SidebarProps) { if (item.path === '/tasks') { return canViewTasks(currentOrganization); } + // Temporary local database tab: every lab org, no permission. + if (item.path === '/local-db') { + return true; + } return canViewTab(currentOrganization, item.read); }), [currentOrganization, menu, orgType], diff --git a/frontend/src/proxy.ts b/frontend/src/proxy.ts index 26d1888..0be87c3 100644 --- a/frontend/src/proxy.ts +++ b/frontend/src/proxy.ts @@ -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)$).*)', ], }; diff --git a/frontend/src/types/sqljs.d.ts b/frontend/src/types/sqljs.d.ts new file mode 100644 index 0000000..e291794 --- /dev/null +++ b/frontend/src/types/sqljs.d.ts @@ -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 | null) => Database; + } + + export interface InitSqlJsConfig { + locateFile?: (file: string) => string; + wasmBinary?: ArrayBuffer | Uint8Array; + } + + export default function initSqlJs(config?: InitSqlJsConfig): Promise; +} diff --git a/local-agent/package.json b/local-agent/package.json new file mode 100644 index 0000000..12145f1 --- /dev/null +++ b/local-agent/package.json @@ -0,0 +1,9 @@ +{ + "name": "dyolink-local-agent", + "private": true, + "type": "module", + "scripts": { + "start": "node src/server.js", + "test": "node --test src/guard.test.js" + } +} diff --git a/local-agent/src/dialog.js b/local-agent/src/dialog.js new file mode 100644 index 0000000..9d89c25 --- /dev/null +++ b/local-agent/src/dialog.js @@ -0,0 +1,56 @@ +import { execFile } from 'node:child_process'; +import path from 'node:path'; +import { promisify } from 'node:util'; +import { isSqlitePath } from './guard.js'; + +const execFileAsync = promisify(execFile); + +async function showOpenDialog() { + if (process.platform === 'darwin') { + const { stdout } = await execFileAsync('osascript', [ + '-e', + 'POSIX path of (choose file with prompt "Select a SQLite database")', + ]); + return stdout.trim(); + } + + if (process.platform === 'win32') { + const script = [ + 'Add-Type -AssemblyName System.Windows.Forms', + '$dialog = New-Object System.Windows.Forms.OpenFileDialog', + "$dialog.Filter = 'SQLite (*.db;*.sqlite;*.sqlite3)|*.db;*.sqlite;*.sqlite3'", + "$dialog.Title = 'Select a SQLite database'", + "if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.FileName }", + ].join('; '); + const { stdout } = await execFileAsync( + 'powershell.exe', + ['-NoProfile', '-STA', '-Command', script], + { windowsHide: false }, + ); + return stdout.trim(); + } + + const { stdout } = await execFileAsync('zenity', [ + '--file-selection', + '--title=Select a SQLite database', + ]); + return stdout.trim(); +} + +function isCancel(error) { + const message = `${error?.stderr ?? ''}\n${error?.message ?? ''}`; + return /user cancel/i.test(message) || message.includes('-128') || error?.code === 1 && /cancel/i.test(message); +} + +/** Show the system file dialog and return a sqlite path, or an error code. */ +export async function pickSqliteFile() { + try { + const picked = await showOpenDialog(); + if (!picked) return { error: 'CANCELLED' }; + if (!isSqlitePath(picked)) return { error: 'BAD_EXTENSION', name: path.basename(picked) }; + return { path: picked }; + } catch (error) { + if (isCancel(error)) return { error: 'CANCELLED' }; + return { error: 'FAILED' }; + } +} diff --git a/local-agent/src/guard.js b/local-agent/src/guard.js new file mode 100644 index 0000000..39762b6 --- /dev/null +++ b/local-agent/src/guard.js @@ -0,0 +1,46 @@ +import { Buffer } from 'node:buffer'; + +const SQLITE_MAGIC = Buffer.from('SQLite format 3\0'); + +export function isSqlitePath(filePath) { + const lower = filePath.toLowerCase(); + return lower.endsWith('.db') || lower.endsWith('.sqlite') || lower.endsWith('.sqlite3'); +} + +export function isSqliteBytes(bytes) { + return bytes.length >= SQLITE_MAGIC.length && bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC); +} + +/** + * Write is allowed only for the file that was opened, and only while that + * file's size and modified time still match the copy that was read. + * @returns {string | null} + */ +export function writeGuard(opened, current) { + if (!opened) return 'NOT_OPEN'; + if (current.path !== opened.path) return 'PATH_MISMATCH'; + if (current.size !== opened.size || current.mtimeMs !== opened.mtimeMs) return 'FILE_CHANGED'; + return null; +} + +/** The request body cannot choose a path. Only the database bytes are kept. */ +export function parseWriteBody(body) { + if (typeof body?.bytesBase64 !== 'string' || body.bytesBase64.length === 0) { + return { error: 'BAD_BODY' }; + } + return { bytesBase64: body.bytesBase64 }; +} + +/** + * Decide whether the opened file may be replaced. + * `body.path` is ignored so a caller cannot aim the write at another file. + */ +export function commitWrite({ opened, current, body }) { + const parsed = parseWriteBody(body); + if (parsed.error) return parsed; + const bytes = Buffer.from(parsed.bytesBase64, 'base64'); + if (!isSqliteBytes(bytes)) return { error: 'NOT_SQLITE' }; + const guard = writeGuard(opened, current); + if (guard) return { error: guard }; + return { ok: true, path: opened.path, bytes }; +} diff --git a/local-agent/src/guard.test.js b/local-agent/src/guard.test.js new file mode 100644 index 0000000..161946d --- /dev/null +++ b/local-agent/src/guard.test.js @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { Buffer } from 'node:buffer'; +import { commitWrite, isSqlitePath, writeGuard } from './guard.js'; + +const opened = { path: '/Users/clinic/data.db', size: 100, mtimeMs: 50 }; + +function sqliteBody(extra = {}) { + const bytes = Buffer.concat([Buffer.from('SQLite format 3\0'), Buffer.from('rest')]); + return { ...extra, bytesBase64: bytes.toString('base64') }; +} + +test('writeGuard allows the opened snapshot only', () => { + assert.equal(writeGuard(opened, { ...opened }), null); + assert.equal(writeGuard(null, opened), 'NOT_OPEN'); + assert.equal( + writeGuard(opened, { ...opened, path: '/tmp/other.db' }), + 'PATH_MISMATCH', + ); + assert.equal(writeGuard(opened, { ...opened, size: 101 }), 'FILE_CHANGED'); + assert.equal(writeGuard(opened, { ...opened, mtimeMs: 51 }), 'FILE_CHANGED'); +}); + +test('commitWrite writes the opened path and ignores a path in the body', () => { + const result = commitWrite({ + opened, + current: { ...opened }, + body: sqliteBody({ path: '/etc/passwd' }), + }); + assert.equal(result.ok, true); + assert.equal(result.path, opened.path); + assert.equal(result.bytes.subarray(0, 16).toString(), 'SQLite format 3\0'); +}); + +test('commitWrite refuses a changed file and a non-sqlite payload', () => { + const changed = commitWrite({ + opened, + current: { ...opened, size: 0 }, + body: sqliteBody(), + }); + assert.equal(changed.error, 'FILE_CHANGED'); + assert.equal(changed.path, undefined); + + const junk = commitWrite({ + opened, + current: { ...opened }, + body: { bytesBase64: Buffer.from('hello').toString('base64') }, + }); + assert.equal(junk.error, 'NOT_SQLITE'); +}); + +test('isSqlitePath accepts database extensions only', () => { + assert.equal(isSqlitePath('/tmp/Clinic.SQLITE'), true); + assert.equal(isSqlitePath('/tmp/notes.txt'), false); +}); diff --git a/local-agent/src/server.js b/local-agent/src/server.js new file mode 100644 index 0000000..9c2229a --- /dev/null +++ b/local-agent/src/server.js @@ -0,0 +1,200 @@ +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { homedir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { pickSqliteFile } from './dialog.js'; +import { commitWrite } from './guard.js'; + +const HOST = '127.0.0.1'; +const PORT = 17654; +const BODY_LIMIT = 96 * 1024 * 1024; + +const ALLOWED_ORIGINS = new Set([ + 'http://localhost:3001', + 'http://127.0.0.1:3001', + 'https://wixur.ir', + 'https://nudentic.ir', +]); + +const tokenFile = path.join(homedir(), '.dyolink', 'local-agent-token'); + +/** @type {{ path: string, size: number, mtimeMs: number } | null} */ +let opened = null; +let picking = false; + +function loadToken() { + if (existsSync(tokenFile)) { + const existing = readFileSync(tokenFile, 'utf8').trim(); + if (existing) return existing; + } + mkdirSync(path.dirname(tokenFile), { recursive: true }); + const created = randomBytes(16).toString('hex'); + writeFileSync(tokenFile, `${created}\n`, { mode: 0o600 }); + return created; +} + +function tokensMatch(expected, provided) { + const left = createHash('sha256').update(expected).digest(); + const right = createHash('sha256').update(provided).digest(); + return timingSafeEqual(left, right); +} + +function bearer(req) { + const header = req.headers.authorization ?? ''; + const match = /^Bearer\s+(.+)$/i.exec(header); + return match ? match[1].trim() : ''; +} + +function snapshot(filePath) { + const stat = statSync(filePath); + return { path: filePath, size: stat.size, mtimeMs: Math.round(stat.mtimeMs) }; +} + +function readBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + req.on('data', (chunk) => { + size += chunk.length; + if (size > BODY_LIMIT) { + reject(Object.assign(new Error('TOO_LARGE'), { code: 'TOO_LARGE' })); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} + +function send(res, status, body) { + const payload = JSON.stringify(body); + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(payload), + 'Cache-Control': 'no-store', + }); + res.end(payload); +} + +function applyCors(req, res) { + const origin = req.headers.origin; + if (origin && ALLOWED_ORIGINS.has(origin)) { + res.setHeader('Access-Control-Allow-Origin', origin); + res.setHeader('Vary', 'Origin'); + res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + } + if (req.headers['access-control-request-private-network'] === 'true') { + res.setHeader('Access-Control-Allow-Private-Network', 'true'); + } +} + +async function handleOpen() { + if (picking) return { status: 409, body: { error: 'BUSY' } }; + picking = true; + try { + const picked = await pickSqliteFile(); + if (picked.error) return { status: 400, body: { error: picked.error } }; + const current = snapshot(picked.path); + const bytes = readFileSync(picked.path); + opened = current; + return { + status: 200, + body: { + name: path.basename(picked.path), + bytesBase64: bytes.toString('base64'), + size: current.size, + mtimeMs: current.mtimeMs, + }, + }; + } finally { + picking = false; + } +} + +async function handleWrite(req) { + let raw; + try { + raw = await readBody(req); + } catch (error) { + if (error?.code === 'TOO_LARGE') return { status: 413, body: { error: 'TOO_LARGE' } }; + return { status: 400, body: { error: 'BAD_BODY' } }; + } + let body; + try { + body = JSON.parse(raw.toString('utf8')); + } catch { + return { status: 400, body: { error: 'BAD_BODY' } }; + } + if (!opened) return { status: 400, body: { error: 'NOT_OPEN' } }; + + let current; + try { + current = snapshot(opened.path); + } catch { + return { status: 409, body: { error: 'FILE_CHANGED' } }; + } + const result = commitWrite({ opened, current, body }); + if (!result.ok) { + const status = result.error === 'FILE_CHANGED' || result.error === 'PATH_MISMATCH' ? 409 : 400; + return { status, body: { error: result.error } }; + } + writeFileSync(result.path, result.bytes); + opened = snapshot(result.path); + return { status: 200, body: { ok: true } }; +} + +export function startAgent() { + const token = loadToken(); + const server = createServer(async (req, res) => { + applyCors(req, res); + if (req.method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + const url = new URL(req.url ?? '/', `http://${HOST}`); + try { + if (req.method === 'GET' && url.pathname === '/health') { + send(res, 200, { ok: true }); + return; + } + if (!tokensMatch(token, bearer(req))) { + send(res, 401, { error: 'UNAUTHORIZED' }); + return; + } + if (req.method === 'POST' && url.pathname === '/open') { + const result = await handleOpen(); + send(res, result.status, result.body); + return; + } + if (req.method === 'POST' && url.pathname === '/write') { + const result = await handleWrite(req); + send(res, result.status, result.body); + return; + } + send(res, 404, { error: 'NOT_FOUND' }); + } catch { + if (!res.headersSent) send(res, 500, { error: 'FAILED' }); + } + }); + + server.requestTimeout = 0; + server.headersTimeout = 0; + server.listen(PORT, HOST, () => { + process.stdout.write(`Dyolink local database helper listening on http://${HOST}:${PORT}\n`); + process.stdout.write(`Pairing code: ${token}\n`); + }); + return server; +} + +const isMain = + process.argv[1] && + fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); + +if (isMain) startAgent(); -- 2.53.0.windows.1 From c80f268668abef52a83af87a0a56f83fd32cdec6 Mon Sep 17 00:00:00 2001 From: rameen Date: Fri, 16 Oct 2026 15:54:50 +0330 Subject: [PATCH 2/3] Send a lab case into the local Exocad database. Write the clinic, patient, and mapped teeth into DentalDB from the case, and keep the Local database tab as a temporary viewer. --- .cursor/rules/lab-cases.mdc | 1 + .cursor/skills/lab-cases/SKILL.md | 11 + AGENTS.md | 4 +- frontend/messages/en.json | 7 + frontend/messages/fa.json | 7 + frontend/messages/nl.json | 7 + .../src/app/[locale]/(dashboard)/layout.tsx | 3 + .../[locale]/(dashboard)/local-db/page.tsx | 1 + .../local-db/exocadTransfer.spec.ts | 256 +++++++++++ .../src/components/local-db/exocadTransfer.ts | 396 ++++++++++++++++++ .../src/components/local-db/localDbErrors.ts | 30 ++ .../src/components/local-db/sqliteSession.ts | 5 + frontend/src/components/shared/permissions.ts | 4 +- .../src/components/ui/lab/CaseDetailPanel.tsx | 67 +++ .../components/ui/lab/CaseLifecycleButton.tsx | 2 +- .../ui/local-db/LocalDbConnectDialog.tsx | 41 ++ .../ui/local-db/LocalDbOpenControls.tsx | 174 ++++++++ .../components/ui/local-db/LocalDbPage.tsx | 250 +++-------- .../ui/local-db/LocalDbSessionProvider.tsx | 180 ++++++++ frontend/src/components/ui/shared/Sidebar.tsx | 7 +- 20 files changed, 1245 insertions(+), 208 deletions(-) create mode 100644 frontend/src/components/local-db/exocadTransfer.spec.ts create mode 100644 frontend/src/components/local-db/exocadTransfer.ts create mode 100644 frontend/src/components/local-db/localDbErrors.ts create mode 100644 frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx create mode 100644 frontend/src/components/ui/local-db/LocalDbOpenControls.tsx create mode 100644 frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx diff --git a/.cursor/rules/lab-cases.mdc b/.cursor/rules/lab-cases.mdc index 28a5b7c..4b3c8ef 100644 --- a/.cursor/rules/lab-cases.mdc +++ b/.cursor/rules/lab-cases.mdc @@ -14,6 +14,7 @@ alwaysApply: false - **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on. - **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps, 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. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id only when the original file is written. The Local database tab is a temporary viewer; keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path when that tab is removed. - **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, 48px line box so html2canvas does not clip the glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the order number. - **Detail chrome:** **Mark as important** is centered in the header 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}”. diff --git a/.cursor/skills/lab-cases/SKILL.md b/.cursor/skills/lab-cases/SKILL.md index dd11b49..00dc2a0 100644 --- a/.cursor/skills/lab-cases/SKILL.md +++ b/.cursor/skills/lab-cases/SKILL.md @@ -53,6 +53,17 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth? - **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, every origin, for anyone who can open the case. It is separate from Outsource. +- `LocalDbSessionProvider` holds the open file for the dashboard session. Chrome and Edge overwrite the picked file. Other browsers use `local-agent` (`127.0.0.1:17654`) or download a copy. A refresh asks the user to connect 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 original file is written (`browser` or `agent`) and `externalCode` is empty, save the Exocad `treatment_id` through `PATCH /cases/:id/external-code` (`TAB_CASES_EDIT`). A download does not set that number and does not replace the original file. +- The `/local-db` tab is a temporary viewer. Deleting that route later must keep `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 48px line box so the glyphs are not clipped. The page stays LTR in every locale. On the Persian sheet that name is a shrink-wrapped `inline-block` (`data-case-sheet-org-text`, `direction: ltr` unless the name itself contains Arabic script, `letter-spacing` and `word-spacing` `0px`) so html2canvas does not stretch the words across the header column. Party and meta values use `printRtlValueStyle`: Arabic script stays RTL; Latin stays LTR, isolated, and right-aligned under the Persian label. `FA_RULE_DROP` (6px) is the only extra rule margin, so Persian descenders clear the line. diff --git a/AGENTS.md b/AGENTS.md index 242f432..c615f9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +72,7 @@ frontend/src/ **Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable and non-outsourceable; historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/SKILL.md`. -**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces order number. 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 order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). 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** writes the open case into a DentalDB SQLite file on that computer. The Local database sidebar tab is a temporary viewer; removing it must keep `LocalDbSessionProvider`. 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 | diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 550899c..b884458 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -547,6 +547,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", @@ -1366,6 +1372,7 @@ "invalidNumber": "{column} must be a number.", "conflict": "That record conflicts with a row already in the table.", "addFailed": "Could not add that record.", + "notExocad": "That file is not an Exocad database.", "saveModeBrowser": "Apply writes this file directly.", "saveModeAgent": "Apply writes this file through the local program.", "saveModeDownload": "Apply downloads a new copy." diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 61bd671..137ab11 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -547,6 +547,12 @@ "receivedBadge": "از کلینیک", "fromLabBadge": "از لابراتوار", "sendCase": "برون سپاری", + "sendToExocad": "ارسال به Exocad", + "sendToExocadSaved": "به Exocad به عنوان پرونده {id} فرستاده شد. Exocad را دوباره باز کنید تا پرونده را ببینید.", + "sendToExocadUpdated": "پرونده {id} در Exocad به‌روز شد. Exocad را دوباره باز کنید تا پرونده را ببینید.", + "sendToExocadSkipped": "فرستاده نشد: {lines}.", + "sendToExocadConnectTitle": "اتصال پایگاه داده Exocad", + "sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.", "sendCaseTitle": "مراحل برون سپاری", "sendCaseSelectAll": "انتخاب همه", "sendCaseLab": "لابراتوار", @@ -1367,6 +1373,7 @@ "invalidNumber": "‏{column} باید عدد باشد.", "conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.", "addFailed": "این رکورد اضافه نشد.", + "notExocad": "این فایل پایگاه داده Exocad نیست.", "saveModeBrowser": "اعمال این فایل را مستقیم می‌نویسد.", "saveModeAgent": "اعمال این فایل را از راه برنامه محلی می‌نویسد.", "saveModeDownload": "اعمال یک نسخه تازه دانلود می‌کند." diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 3c6a86f..35f8e2b 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -547,6 +547,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", @@ -1366,6 +1372,7 @@ "invalidNumber": "{column} moet een getal zijn.", "conflict": "Dat record botst met een rij die al in de tabel staat.", "addFailed": "Dat record kon niet worden toegevoegd.", + "notExocad": "Dat bestand is geen Exocad-database.", "saveModeBrowser": "Toepassen schrijft dit bestand direct.", "saveModeAgent": "Toepassen schrijft dit bestand via het lokale programma.", "saveModeDownload": "Toepassen downloadt een nieuwe kopie." diff --git a/frontend/src/app/[locale]/(dashboard)/layout.tsx b/frontend/src/app/[locale]/(dashboard)/layout.tsx index 0948928..9091d72 100644 --- a/frontend/src/app/[locale]/(dashboard)/layout.tsx +++ b/frontend/src/app/[locale]/(dashboard)/layout.tsx @@ -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 +
{sidebarOpen ? (
+
diff --git a/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx b/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx index 3f995ae..fe6493b 100644 --- a/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx +++ b/frontend/src/app/[locale]/(dashboard)/local-db/page.tsx @@ -2,6 +2,7 @@ import { LocalDbPage } from '@/components/ui/local-db/LocalDbPage'; +/** Temporary route. Delete this page later. Keep LocalDbSessionProvider for Send to Exocad. */ export default function Page() { return ; } diff --git a/frontend/src/components/local-db/exocadTransfer.spec.ts b/frontend/src/components/local-db/exocadTransfer.spec.ts new file mode 100644 index 0000000..247f3ba --- /dev/null +++ b/frontend/src/components/local-db/exocadTransfer.spec.ts @@ -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): void; + step(): boolean; + get(): SqliteCell[]; + free(): void; +}; + +type SqlDatabase = { + run(sql: string, params?: Array): 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 { + 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 { + 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(); + }); +}); diff --git a/frontend/src/components/local-db/exocadTransfer.ts b/frontend/src/components/local-db/exocadTransfer.ts new file mode 100644 index 0000000..4e1127d --- /dev/null +++ b/frontend/src/components/local-db/exocadTransfer.ts @@ -0,0 +1,396 @@ +import type { SqliteQuery } from '@/components/local-db/sqliteSql'; + +/** DentalDB's own lab row in a default database. */ +export 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 = { + 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(); + 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(); + 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; + } +} diff --git a/frontend/src/components/local-db/localDbErrors.ts b/frontend/src/components/local-db/localDbErrors.ts new file mode 100644 index 0000000..1c3b474 --- /dev/null +++ b/frontend/src/components/local-db/localDbErrors.ts @@ -0,0 +1,30 @@ +import { AgentError } from '@/components/local-db/agentClient'; +import { ExocadTransferError } from '@/components/local-db/exocadTransfer'; +import { SqliteEditError, sqliteFailureCode } from '@/components/local-db/sqliteSql'; + +type LocalDbTranslator = (key: string, values?: Record) => 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' | 'addFailed', +): string { + if (error instanceof SqliteEditError) { + if (error.code === 'EMPTY_REQUIRED') return t('emptyRequired', { column: error.column }); + if (error.code === 'INVALID_NUMBER') return t('invalidNumber', { column: error.column }); + return t('loadFailed'); + } + if (error instanceof ExocadTransferError) return t('notExocad'); + if (error instanceof AgentError) { + if (error.code === 'UNAUTHORIZED') return t('pairingRejected'); + if (error.code === 'FILE_CHANGED') return t('fileChanged'); + if (error.code === 'CANCELLED') return t('cancelled'); + if (error.code === 'BAD_EXTENSION' || error.code === 'NOT_SQLITE') return t('notSqlite'); + if (error.code === 'UNREACHABLE') return t('agentOffline'); + return t(fallback); + } + const message = error instanceof Error ? error.message : ''; + if (message && sqliteFailureCode(message) === 'conflict') return t('conflict'); + return t(fallback); +} diff --git a/frontend/src/components/local-db/sqliteSession.ts b/frontend/src/components/local-db/sqliteSession.ts index c56c010..8b71863 100644 --- a/frontend/src/components/local-db/sqliteSession.ts +++ b/frontend/src/components/local-db/sqliteSession.ts @@ -4,6 +4,7 @@ import { readTable, type SqliteCell, type SqliteColumn, + type SqliteQuery, } from '@/components/local-db/sqliteSql'; import type { Database, SqlValue, Statement } from 'sql.js'; @@ -65,6 +66,10 @@ export class LocalSqlite { insertRow(asQuery(this.db), table, raw); } + execute(fn: (query: SqliteQuery) => T): T { + return fn(asQuery(this.db)); + } + exportBytes(): Uint8Array { const exported = this.db.export(); return new Uint8Array(exported); diff --git a/frontend/src/components/shared/permissions.ts b/frontend/src/components/shared/permissions.ts index 57f7bb5..e11a5fe 100644 --- a/frontend/src/components/shared/permissions.ts +++ b/frontend/src/components/shared/permissions.ts @@ -62,7 +62,9 @@ export function getRequiredReadPermissionForPath(pathname: string): string | nul export function canAccessDashboardRoute(org: Organization | null, pathname: string): boolean { if (!org) return false; - // Temporary. Lab-only, and not in DASHBOARD_ROUTES so it is never the landing page. + // Temporary viewer. Lab-only, and not in DASHBOARD_ROUTES so it is never the landing page. + // Removing this route later must keep LocalDbSessionProvider, the connect dialog, + // and the file open/write path. Send to Exocad uses those. if (pathname === '/local-db' || pathname.startsWith('/local-db/')) { return org.type === 'LAB'; } diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index c46385f..cb5e0d8 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -26,6 +26,9 @@ import { formatPatientName, } from '@/components/lab/caseDetailUtils'; import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf'; +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 +66,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, @@ -258,6 +278,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 +286,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); @@ -394,6 +416,42 @@ 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 { + const kind = await localDb.apply(); + const id = String(result.treatmentId); + if (!labCase.externalCode?.trim() && canEditImportant && kind !== 'download') { + 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(', '), + }) + : ''; + if (kind === 'download') { + toast.showInfo([tLocal('applyDownloaded'), skipped].filter((line) => line.length > 0).join(' ')); + } else { + 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, @@ -539,6 +597,15 @@ export function CaseDetailPanel({ /> ) : null} +
+ onSendToExocad()} + /> +
void; + onClick: () => void | Promise; }; export function CaseLifecycleButton({ diff --git a/frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx b/frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx new file mode 100644 index 0000000..6279c93 --- /dev/null +++ b/frontend/src/components/ui/local-db/LocalDbConnectDialog.tsx @@ -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; +}; + +export function LocalDbConnectDialog({ onCancel, onOpened }: LocalDbConnectDialogProps) { + const t = useTranslations('cases'); + + return ( + + +
+

+ {t('sendToExocadConnectTitle')} +

+ +
+

{t('sendToExocadCloseHint')}

+
+ +
+
+
+ ); +} diff --git a/frontend/src/components/ui/local-db/LocalDbOpenControls.tsx b/frontend/src/components/ui/local-db/LocalDbOpenControls.tsx new file mode 100644 index 0000000..711a6c2 --- /dev/null +++ b/frontend/src/components/ui/local-db/LocalDbOpenControls.tsx @@ -0,0 +1,174 @@ +'use client'; + +import { useEffect, useRef, useState, type ChangeEvent, type ReactNode } from 'react'; +import { useTranslations } from 'next-intl'; +import { Button } from '@/components/ui/shared/Button'; +import { Input } from '@/components/ui/shared/Input'; +import { + AgentError, + agentIsRunning, + openWithAgent, + readStoredAgentToken, + storeAgentToken, +} from '@/components/local-db/agentClient'; +import { + browserCanWriteLocalFile, + isPickerCancel, + openWithBrowserPicker, + type DatabaseSink, +} from '@/components/local-db/browserFile'; +import { downloadBytes } from '@/components/local-db/downloadBytes'; +import { localDbErrorText } from '@/components/local-db/localDbErrors'; + +type LocalDbOpenControlsProps = { + onOpened: (sink: DatabaseSink) => Promise; + extra?: ReactNode; +}; + +export function LocalDbOpenControls({ onOpened, extra }: LocalDbOpenControlsProps) { + const t = useTranslations('localDb'); + const fileInputRef = useRef(null); + const [canWriteDirect, setCanWriteDirect] = useState(false); + const [checkedBrowser, setCheckedBrowser] = useState(false); + const [agentOnline, setAgentOnline] = useState(null); + const [pairing, setPairing] = useState(''); + const [error, setError] = useState(''); + + useEffect(() => { + const direct = browserCanWriteLocalFile(); + setCanWriteDirect(direct); + setCheckedBrowser(true); + setPairing(readStoredAgentToken()); + if (!direct) { + void agentIsRunning().then(setAgentOnline); + } + }, []); + + async function onBrowse() { + setError(''); + if (browserCanWriteLocalFile()) { + 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; + } + + const token = pairing.trim(); + if (!token) { + setError(t('pairingRequired')); + return; + } + storeAgentToken(token); + if (agentOnline === false) { + fileInputRef.current?.click(); + return; + } + let sink; + try { + sink = await openWithAgent(token); + setAgentOnline(true); + } catch (caught) { + if (caught instanceof AgentError && caught.code === 'UNREACHABLE') { + setAgentOnline(false); + setError(t('agentOffline')); + return; + } + if (caught instanceof AgentError && caught.code === 'CANCELLED') { + setError(t('cancelled')); + return; + } + setError(localDbErrorText(caught, t, 'openFailed')); + return; + } + try { + await onOpened(sink); + } catch { + setError(t('loadFailed')); + } + } + + async function onFileInput(event: ChangeEvent) { + const file = event.target.files?.[0]; + event.target.value = ''; + if (!file) return; + const lower = file.name.toLowerCase(); + if (!lower.endsWith('.db') && !lower.endsWith('.sqlite') && !lower.endsWith('.sqlite3')) { + setError(t('notSqlite')); + return; + } + const bytes = new Uint8Array(await file.arrayBuffer()); + try { + await onOpened({ + name: file.name, + kind: 'download', + bytes, + write: async (next) => { + downloadBytes(file.name, next); + }, + }); + } catch { + setError(t('loadFailed')); + } + } + + return ( +
+ {checkedBrowser && !canWriteDirect ? ( +

{t('safariHelp')}

+ ) : null} + + {checkedBrowser && !canWriteDirect && agentOnline === false ? ( +

+ {t('agentOffline')} +

+ ) : null} + + {checkedBrowser && !canWriteDirect ? ( +
+ { + setPairing(event.target.value); + storeAgentToken(event.target.value); + }} + /> +

{t('pairingHint')}

+
+ ) : null} + +
+ + {extra} + void onFileInput(event)} + /> +
+ + {error ? ( +

+ {error} +

+ ) : null} +
+ ); +} diff --git a/frontend/src/components/ui/local-db/LocalDbPage.tsx b/frontend/src/components/ui/local-db/LocalDbPage.tsx index 5c71334..42d3ac8 100644 --- a/frontend/src/components/ui/local-db/LocalDbPage.tsx +++ b/frontend/src/components/ui/local-db/LocalDbPage.tsx @@ -1,103 +1,61 @@ 'use client'; -import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'; +import { useEffect, useState, type FormEvent } from 'react'; import { useTranslations } from 'next-intl'; import { Button } from '@/components/ui/shared/Button'; import { Input } from '@/components/ui/shared/Input'; import { Table, TABLE_HEADER_CELL_CLASS } from '@/components/ui/shared/Table'; import { useToast } from '@/components/ui/shared/ToastProvider'; +import { LocalDbOpenControls } from '@/components/ui/local-db/LocalDbOpenControls'; +import { useLocalDbSession } from '@/components/ui/local-db/LocalDbSessionProvider'; +import { localDbErrorText } from '@/components/local-db/localDbErrors'; import { - AgentError, - agentIsRunning, - openWithAgent, - readStoredAgentToken, - storeAgentToken, -} from '@/components/local-db/agentClient'; -import { - browserCanWriteLocalFile, - isPickerCancel, - openWithBrowserPicker, - type DatabaseKind, - type DatabaseSink, -} from '@/components/local-db/browserFile'; -import { downloadBytes } from '@/components/local-db/downloadBytes'; -import { LocalSqlite } from '@/components/local-db/sqliteSession'; -import { - SqliteEditError, TABLE_ROW_LIMIT, columnIsRequired, - sqliteFailureCode, type SqliteCell, type SqliteColumn, } from '@/components/local-db/sqliteSql'; import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles'; +/** Temporary viewer of a local SQLite file. Send to Exocad does not use this page. */ + function cellText(value: SqliteCell, nullLabel: string, blobLabel: string): string { if (value == null) return nullLabel; if (value instanceof Uint8Array) return blobLabel; return String(value); } -function describeError( - error: unknown, - t: (key: string, values?: Record) => string, - fallback: 'openFailed' | 'applyFailed' | 'addFailed', -): string { - if (error instanceof SqliteEditError) { - if (error.code === 'EMPTY_REQUIRED') return t('emptyRequired', { column: error.column }); - if (error.code === 'INVALID_NUMBER') return t('invalidNumber', { column: error.column }); - return t('loadFailed'); - } - if (error instanceof AgentError) { - if (error.code === 'UNAUTHORIZED') return t('pairingRejected'); - if (error.code === 'FILE_CHANGED') return t('fileChanged'); - if (error.code === 'CANCELLED') return t('cancelled'); - if (error.code === 'BAD_EXTENSION' || error.code === 'NOT_SQLITE') return t('notSqlite'); - if (error.code === 'UNREACHABLE') return t('agentOffline'); - return t(fallback); - } - const message = error instanceof Error ? error.message : ''; - if (message && sqliteFailureCode(message) === 'conflict') return t('conflict'); - if (message) return t(fallback); - return t(fallback); -} - export function LocalDbPage() { const t = useTranslations('localDb'); const { showSuccess, showInfo } = useToast(); - const sessionRef = useRef(null); - const sinkRef = useRef(null); - const fileInputRef = useRef(null); + const session = useLocalDbSession(); - const [canWriteDirect, setCanWriteDirect] = useState(false); - const [checkedBrowser, setCheckedBrowser] = useState(false); - const [agentOnline, setAgentOnline] = useState(null); - const [pairing, setPairing] = useState(''); - const [fileName, setFileName] = useState(''); - const [kind, setKind] = useState(null); - const [dirty, setDirty] = useState(false); const [tables, setTables] = useState([]); const [selectedTable, setSelectedTable] = useState(''); const [columns, setColumns] = useState([]); const [rows, setRows] = useState([]); const [truncated, setTruncated] = useState(false); const [draft, setDraft] = useState>({}); - const [revision, setRevision] = useState(0); const [error, setError] = useState(''); useEffect(() => { - const direct = browserCanWriteLocalFile(); - setCanWriteDirect(direct); - setCheckedBrowser(true); - setPairing(readStoredAgentToken()); - if (!direct) { - void agentIsRunning().then(setAgentOnline); + if (!session.connected) { + setTables([]); + setSelectedTable(''); + return; } - }, []); + try { + const names = session.listTables(); + setTables(names); + setSelectedTable((current) => (names.includes(current) ? current : (names[0] ?? ''))); + setError(''); + } catch { + setError(t('loadFailed')); + } + }, [session.connected, session.fileName, session.listTables, session.revision, t]); useEffect(() => { - const session = sessionRef.current; - if (!session || !selectedTable) { + if (!session.connected || !selectedTable) { setColumns([]); setRows([]); setTruncated(false); @@ -112,168 +70,56 @@ export function LocalDbPage() { } catch { setError(t('loadFailed')); } - }, [selectedTable, revision, t]); - - async function loadSink(sink: DatabaseSink) { - let session: LocalSqlite; - try { - session = await LocalSqlite.open(sink.bytes); - } catch { - setError(t('loadFailed')); - return; - } - sessionRef.current?.close(); - sessionRef.current = session; - sinkRef.current = sink; - const names = session.listTables(); - setFileName(sink.name); - setKind(sink.kind); - setDirty(false); - setTables(names); - setSelectedTable(names[0] ?? ''); - setRevision((value) => value + 1); - setError(''); - } - - async function onBrowse() { - setError(''); - if (browserCanWriteLocalFile()) { - try { - await loadSink(await openWithBrowserPicker()); - } catch (caught) { - if (isPickerCancel(caught)) return; - setError(t('openFailed')); - } - return; - } - - const token = pairing.trim(); - if (!token) { - setError(t('pairingRequired')); - return; - } - storeAgentToken(token); - if (agentOnline === false) { - fileInputRef.current?.click(); - return; - } - try { - await loadSink(await openWithAgent(token)); - setAgentOnline(true); - } catch (caught) { - if (caught instanceof AgentError && caught.code === 'UNREACHABLE') { - setAgentOnline(false); - setError(t('agentOffline')); - return; - } - if (caught instanceof AgentError && caught.code === 'CANCELLED') { - setError(t('cancelled')); - return; - } - setError(describeError(caught, t, 'openFailed')); - } - } - - async function onFileInput(event: ChangeEvent) { - const file = event.target.files?.[0]; - event.target.value = ''; - if (!file) return; - const lower = file.name.toLowerCase(); - if (!lower.endsWith('.db') && !lower.endsWith('.sqlite') && !lower.endsWith('.sqlite3')) { - setError(t('notSqlite')); - return; - } - const bytes = new Uint8Array(await file.arrayBuffer()); - await loadSink({ - name: file.name, - kind: 'download', - bytes, - write: async (next) => { - downloadBytes(file.name, next); - }, - }); - } + }, [selectedTable, session.connected, session.readTable, session.revision, t]); function onAdd(event: FormEvent) { event.preventDefault(); - const session = sessionRef.current; - if (!session || !selectedTable) return; + if (!selectedTable) return; try { session.insertRow(selectedTable, draft); - setDirty(true); setError(''); - setRevision((value) => value + 1); } catch (caught) { - setError(describeError(caught, t, 'addFailed')); + setError(localDbErrorText(caught, t, 'addFailed')); } } async function onApply() { - const session = sessionRef.current; - const sink = sinkRef.current; - if (!session || !sink) return; try { - await sink.write(session.exportBytes()); - setDirty(false); + const kind = await session.apply(); setError(''); - if (sink.kind === 'download') showInfo(t('applyDownloaded')); + if (kind === 'download') showInfo(t('applyDownloaded')); else showSuccess(t('saved')); } catch (caught) { - setError(describeError(caught, t, 'applyFailed')); + setError(localDbErrorText(caught, t, 'applyFailed')); } } const saveMode = - kind === 'browser' ? t('saveModeBrowser') : kind === 'agent' ? t('saveModeAgent') : kind === 'download' ? t('saveModeDownload') : ''; + session.kind === 'browser' + ? t('saveModeBrowser') + : session.kind === 'agent' + ? t('saveModeAgent') + : session.kind === 'download' + ? t('saveModeDownload') + : ''; return (

{t('title')}

{t('intro')}

- {checkedBrowser && !canWriteDirect ? ( -

{t('safariHelp')}

- ) : null}
- {checkedBrowser && !canWriteDirect && agentOnline === false ? ( -

- {t('agentOffline')} -

- ) : null} - - {checkedBrowser && !canWriteDirect ? ( -
- { - setPairing(event.target.value); - storeAgentToken(event.target.value); - }} - /> -

{t('pairingHint')}

-
- ) : null} - -
- - - void onFileInput(event)} - /> -
+ { + await session.replaceWithSink(sink); + }} + extra={ + + } + /> {error ? (

@@ -281,11 +127,11 @@ export function LocalDbPage() {

) : null} - {fileName ? ( + {session.fileName ? (

- {fileName} - {dirty ? {t('unsaved')} : null} + {session.fileName} + {session.dirty ? {t('unsaved')} : null}

{saveMode ?

{saveMode}

: null}
@@ -293,7 +139,7 @@ export function LocalDbPage() {

{t('noFile')}

)} - {fileName && tables.length === 0 ?

{t('noTables')}

: null} + {session.fileName && tables.length === 0 ?

{t('noTables')}

: null} {tables.length > 0 ? (
+ {column.name} +
+ {text} +
- {columns.map((column) => ( - - ))} - - } - body={rows.map((row, rowIndex) => ( - - {row.map((value, columnIndex) => { - const text = cellText(value, t('nullValue'), t('blobValue')); - return ( - - ); - })} - - ))} - /> - ) : ( -

{t('emptyTable')}

- ) - ) : null} - - {truncated ? ( -

{t('truncated', { count: TABLE_ROW_LIMIT })}

- ) : null} - - {selectedTable && columns.length > 0 ? ( - -

{t('addRecord')}

-
- {columns.map((column) => ( - - setDraft((current) => ({ ...current, [column.name]: event.target.value })) - } - /> - ))} -
- - - ) : null} - - ); -} diff --git a/frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx b/frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx index e6c1ea4..f57242b 100644 --- a/frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx +++ b/frontend/src/components/ui/local-db/LocalDbSessionProvider.tsx @@ -11,28 +11,24 @@ import { type ReactNode, } from 'react'; import { transferCaseToExocad, type ExocadCaseInput, type ExocadTransferResult } from '@/components/local-db/exocadTransfer'; -import type { DatabaseKind, DatabaseSink } from '@/components/local-db/browserFile'; +import { + browserCanWriteLocalFile, + browserDatabaseStillExists, + preloadBrowserHandle, + reopenStoredBrowserFile, + type DatabaseSink, +} from '@/components/local-db/browserFile'; import { LocalSqlite } from '@/components/local-db/sqliteSession'; -import type { SqliteCell, SqliteColumn } from '@/components/local-db/sqliteSql'; import { LocalDbConnectDialog } from '@/components/ui/local-db/LocalDbConnectDialog'; /** - * Open Exocad file for this browser session. - * The Local database tab is a temporary viewer. Removing that tab later must keep - * this provider, the connect dialog, and the file open/write path. Send to Exocad uses them. + * 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 = { - fileName: string; - kind: DatabaseKind | null; - dirty: boolean; - connected: boolean; - revision: number; - listTables: () => string[]; - readTable: (name: string) => { columns: SqliteColumn[]; rows: SqliteCell[][]; truncated: boolean }; - insertRow: (table: string, raw: Record) => void; - replaceWithSink: (sink: DatabaseSink) => Promise; - apply: () => Promise; + apply: () => Promise; requestConnection: () => Promise; transferCase: (input: ExocadCaseInput) => ExocadTransferResult; }; @@ -52,67 +48,46 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) { const sinkRef = useRef(null); const connectResolveRef = useRef<((connected: boolean) => void) | null>(null); const pendingConnectRef = useRef | null>(null); - const [fileName, setFileName] = useState(''); - const [kind, setKind] = useState(null); - const [dirty, setDirty] = useState(false); - const [revision, setRevision] = useState(0); const [connectOpen, setConnectOpen] = useState(false); useEffect(() => { + preloadBrowserHandle(); return () => { sessionRef.current?.close(); sessionRef.current = null; }; }, []); - const bump = useCallback(() => { - setRevision((value) => value + 1); + 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; - setFileName(sink.name); - setKind(sink.kind); - setDirty(false); - bump(); - }, [bump]); + }, []); 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()); - setDirty(false); - return sink.kind; }, []); - const listTables = useCallback(() => sessionRef.current?.listTables() ?? [], []); - - const readTable = useCallback((name: string) => { - const session = sessionRef.current; - if (!session) return { columns: [], rows: [], truncated: false }; - return session.readTable(name); - }, []); - - const insertRow = useCallback((table: string, raw: Record) => { - const session = sessionRef.current; - if (!session) throw new Error('NOT_OPEN'); - session.insertRow(table, raw); - setDirty(true); - bump(); - }, [bump]); - const transferCase = useCallback((input: ExocadCaseInput) => { const session = sessionRef.current; if (!session) throw new Error('NOT_OPEN'); - const result = session.execute((query) => transferCaseToExocad(query, input)); - setDirty(true); - bump(); - return result; - }, [bump]); + return session.execute((query) => transferCaseToExocad(query, input)); + }, []); const finishConnect = useCallback((connected: boolean) => { setConnectOpen(false); @@ -121,46 +96,37 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) { }, []); const requestConnection = useCallback(() => { - if (sessionRef.current && sinkRef.current) return Promise.resolve(true); if (pendingConnectRef.current) return pendingConnectRef.current; - const pending = new Promise((resolve) => { - connectResolveRef.current = resolve; - setConnectOpen(true); - }).finally(() => { + 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((resolve) => { + connectResolveRef.current = resolve; + setConnectOpen(true); + }); + })().finally(() => { pendingConnectRef.current = null; }); pendingConnectRef.current = pending; return pending; - }, []); + }, [dropSession, replaceWithSink]); const value = useMemo( - () => ({ - fileName, - kind, - dirty, - connected: fileName.length > 0, - revision, - listTables, - readTable, - insertRow, - replaceWithSink, - apply, - requestConnection, - transferCase, - }), - [ - fileName, - kind, - dirty, - revision, - listTables, - readTable, - insertRow, - replaceWithSink, - apply, - requestConnection, - transferCase, - ], + () => ({ apply, requestConnection, transferCase }), + [apply, requestConnection, transferCase], ); return ( diff --git a/frontend/src/components/ui/shared/Sidebar.tsx b/frontend/src/components/ui/shared/Sidebar.tsx index 5128ef9..99c536c 100644 --- a/frontend/src/components/ui/shared/Sidebar.tsx +++ b/frontend/src/components/ui/shared/Sidebar.tsx @@ -14,7 +14,6 @@ import { Package, ListTodo, Building2, - Database, X, } from 'lucide-react'; import type { OrgTypeName } from '@/components/shared/permissions'; @@ -71,10 +70,6 @@ function Sidebar({ mobileOpen = false, onClose }: SidebarProps) { { name: t('patients'), path: '/patients', icon: Users, read: 'TAB_PATIENTS_READ', orgTypes: ['CLINIC'] }, { name: t('cases'), path: '/cases', icon: Package, read: 'TAB_CASES_READ', orgTypes: ['LAB'] }, { name: t('tasks'), path: '/tasks', icon: ListTodo, read: 'TAB_TASKS_READ', orgTypes: ['LAB'] }, - // Temporary viewer. Remove this item when the local database page goes away. - // Keep LocalDbSessionProvider, the connect dialog, and the file open/write path: - // Send to Exocad uses them. - { name: t('localDb'), path: '/local-db', icon: Database, read: '', orgTypes: ['LAB'] }, { name: t('appointment'), path: '/appointments', icon: Calendar, read: 'TAB_APPOINTMENTS_READ', orgTypes: ['CLINIC'] }, { name: t('treatment'), path: '/treatment', icon: FlaskConical, read: 'TAB_TREATMENT_READ', orgTypes: ['CLINIC'] }, { name: t('billing'), path: '/billing', icon: CreditCard, read: 'TAB_BILLING_READ', orgTypes: ['CLINIC', 'LAB'] }, @@ -101,11 +96,6 @@ function Sidebar({ mobileOpen = false, onClose }: SidebarProps) { if (item.path === '/tasks') { return canViewTasks(currentOrganization); } - // Temporary viewer. Keep it until the page is removed. - // Send to Exocad does not use this route. Keep LocalDbSessionProvider when this item goes. - if (item.path === '/local-db') { - return true; - } return canViewTab(currentOrganization, item.read); }), [currentOrganization, menu, orgType], diff --git a/local-agent/package.json b/local-agent/package.json deleted file mode 100644 index 12145f1..0000000 --- a/local-agent/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "dyolink-local-agent", - "private": true, - "type": "module", - "scripts": { - "start": "node src/server.js", - "test": "node --test src/guard.test.js" - } -} diff --git a/local-agent/src/dialog.js b/local-agent/src/dialog.js deleted file mode 100644 index 9d89c25..0000000 --- a/local-agent/src/dialog.js +++ /dev/null @@ -1,56 +0,0 @@ -import { execFile } from 'node:child_process'; -import path from 'node:path'; -import { promisify } from 'node:util'; -import { isSqlitePath } from './guard.js'; - -const execFileAsync = promisify(execFile); - -async function showOpenDialog() { - if (process.platform === 'darwin') { - const { stdout } = await execFileAsync('osascript', [ - '-e', - 'POSIX path of (choose file with prompt "Select a SQLite database")', - ]); - return stdout.trim(); - } - - if (process.platform === 'win32') { - const script = [ - 'Add-Type -AssemblyName System.Windows.Forms', - '$dialog = New-Object System.Windows.Forms.OpenFileDialog', - "$dialog.Filter = 'SQLite (*.db;*.sqlite;*.sqlite3)|*.db;*.sqlite;*.sqlite3'", - "$dialog.Title = 'Select a SQLite database'", - "if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.FileName }", - ].join('; '); - const { stdout } = await execFileAsync( - 'powershell.exe', - ['-NoProfile', '-STA', '-Command', script], - { windowsHide: false }, - ); - return stdout.trim(); - } - - const { stdout } = await execFileAsync('zenity', [ - '--file-selection', - '--title=Select a SQLite database', - ]); - return stdout.trim(); -} - -function isCancel(error) { - const message = `${error?.stderr ?? ''}\n${error?.message ?? ''}`; - return /user cancel/i.test(message) || message.includes('-128') || error?.code === 1 && /cancel/i.test(message); -} - -/** Show the system file dialog and return a sqlite path, or an error code. */ -export async function pickSqliteFile() { - try { - const picked = await showOpenDialog(); - if (!picked) return { error: 'CANCELLED' }; - if (!isSqlitePath(picked)) return { error: 'BAD_EXTENSION', name: path.basename(picked) }; - return { path: picked }; - } catch (error) { - if (isCancel(error)) return { error: 'CANCELLED' }; - return { error: 'FAILED' }; - } -} diff --git a/local-agent/src/guard.js b/local-agent/src/guard.js deleted file mode 100644 index 39762b6..0000000 --- a/local-agent/src/guard.js +++ /dev/null @@ -1,46 +0,0 @@ -import { Buffer } from 'node:buffer'; - -const SQLITE_MAGIC = Buffer.from('SQLite format 3\0'); - -export function isSqlitePath(filePath) { - const lower = filePath.toLowerCase(); - return lower.endsWith('.db') || lower.endsWith('.sqlite') || lower.endsWith('.sqlite3'); -} - -export function isSqliteBytes(bytes) { - return bytes.length >= SQLITE_MAGIC.length && bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC); -} - -/** - * Write is allowed only for the file that was opened, and only while that - * file's size and modified time still match the copy that was read. - * @returns {string | null} - */ -export function writeGuard(opened, current) { - if (!opened) return 'NOT_OPEN'; - if (current.path !== opened.path) return 'PATH_MISMATCH'; - if (current.size !== opened.size || current.mtimeMs !== opened.mtimeMs) return 'FILE_CHANGED'; - return null; -} - -/** The request body cannot choose a path. Only the database bytes are kept. */ -export function parseWriteBody(body) { - if (typeof body?.bytesBase64 !== 'string' || body.bytesBase64.length === 0) { - return { error: 'BAD_BODY' }; - } - return { bytesBase64: body.bytesBase64 }; -} - -/** - * Decide whether the opened file may be replaced. - * `body.path` is ignored so a caller cannot aim the write at another file. - */ -export function commitWrite({ opened, current, body }) { - const parsed = parseWriteBody(body); - if (parsed.error) return parsed; - const bytes = Buffer.from(parsed.bytesBase64, 'base64'); - if (!isSqliteBytes(bytes)) return { error: 'NOT_SQLITE' }; - const guard = writeGuard(opened, current); - if (guard) return { error: guard }; - return { ok: true, path: opened.path, bytes }; -} diff --git a/local-agent/src/guard.test.js b/local-agent/src/guard.test.js deleted file mode 100644 index 161946d..0000000 --- a/local-agent/src/guard.test.js +++ /dev/null @@ -1,55 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { Buffer } from 'node:buffer'; -import { commitWrite, isSqlitePath, writeGuard } from './guard.js'; - -const opened = { path: '/Users/clinic/data.db', size: 100, mtimeMs: 50 }; - -function sqliteBody(extra = {}) { - const bytes = Buffer.concat([Buffer.from('SQLite format 3\0'), Buffer.from('rest')]); - return { ...extra, bytesBase64: bytes.toString('base64') }; -} - -test('writeGuard allows the opened snapshot only', () => { - assert.equal(writeGuard(opened, { ...opened }), null); - assert.equal(writeGuard(null, opened), 'NOT_OPEN'); - assert.equal( - writeGuard(opened, { ...opened, path: '/tmp/other.db' }), - 'PATH_MISMATCH', - ); - assert.equal(writeGuard(opened, { ...opened, size: 101 }), 'FILE_CHANGED'); - assert.equal(writeGuard(opened, { ...opened, mtimeMs: 51 }), 'FILE_CHANGED'); -}); - -test('commitWrite writes the opened path and ignores a path in the body', () => { - const result = commitWrite({ - opened, - current: { ...opened }, - body: sqliteBody({ path: '/etc/passwd' }), - }); - assert.equal(result.ok, true); - assert.equal(result.path, opened.path); - assert.equal(result.bytes.subarray(0, 16).toString(), 'SQLite format 3\0'); -}); - -test('commitWrite refuses a changed file and a non-sqlite payload', () => { - const changed = commitWrite({ - opened, - current: { ...opened, size: 0 }, - body: sqliteBody(), - }); - assert.equal(changed.error, 'FILE_CHANGED'); - assert.equal(changed.path, undefined); - - const junk = commitWrite({ - opened, - current: { ...opened }, - body: { bytesBase64: Buffer.from('hello').toString('base64') }, - }); - assert.equal(junk.error, 'NOT_SQLITE'); -}); - -test('isSqlitePath accepts database extensions only', () => { - assert.equal(isSqlitePath('/tmp/Clinic.SQLITE'), true); - assert.equal(isSqlitePath('/tmp/notes.txt'), false); -}); diff --git a/local-agent/src/server.js b/local-agent/src/server.js deleted file mode 100644 index 9c2229a..0000000 --- a/local-agent/src/server.js +++ /dev/null @@ -1,200 +0,0 @@ -import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; -import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:http'; -import { homedir } from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { pickSqliteFile } from './dialog.js'; -import { commitWrite } from './guard.js'; - -const HOST = '127.0.0.1'; -const PORT = 17654; -const BODY_LIMIT = 96 * 1024 * 1024; - -const ALLOWED_ORIGINS = new Set([ - 'http://localhost:3001', - 'http://127.0.0.1:3001', - 'https://wixur.ir', - 'https://nudentic.ir', -]); - -const tokenFile = path.join(homedir(), '.dyolink', 'local-agent-token'); - -/** @type {{ path: string, size: number, mtimeMs: number } | null} */ -let opened = null; -let picking = false; - -function loadToken() { - if (existsSync(tokenFile)) { - const existing = readFileSync(tokenFile, 'utf8').trim(); - if (existing) return existing; - } - mkdirSync(path.dirname(tokenFile), { recursive: true }); - const created = randomBytes(16).toString('hex'); - writeFileSync(tokenFile, `${created}\n`, { mode: 0o600 }); - return created; -} - -function tokensMatch(expected, provided) { - const left = createHash('sha256').update(expected).digest(); - const right = createHash('sha256').update(provided).digest(); - return timingSafeEqual(left, right); -} - -function bearer(req) { - const header = req.headers.authorization ?? ''; - const match = /^Bearer\s+(.+)$/i.exec(header); - return match ? match[1].trim() : ''; -} - -function snapshot(filePath) { - const stat = statSync(filePath); - return { path: filePath, size: stat.size, mtimeMs: Math.round(stat.mtimeMs) }; -} - -function readBody(req) { - return new Promise((resolve, reject) => { - const chunks = []; - let size = 0; - req.on('data', (chunk) => { - size += chunk.length; - if (size > BODY_LIMIT) { - reject(Object.assign(new Error('TOO_LARGE'), { code: 'TOO_LARGE' })); - req.destroy(); - return; - } - chunks.push(chunk); - }); - req.on('end', () => resolve(Buffer.concat(chunks))); - req.on('error', reject); - }); -} - -function send(res, status, body) { - const payload = JSON.stringify(body); - res.writeHead(status, { - 'Content-Type': 'application/json; charset=utf-8', - 'Content-Length': Buffer.byteLength(payload), - 'Cache-Control': 'no-store', - }); - res.end(payload); -} - -function applyCors(req, res) { - const origin = req.headers.origin; - if (origin && ALLOWED_ORIGINS.has(origin)) { - res.setHeader('Access-Control-Allow-Origin', origin); - res.setHeader('Vary', 'Origin'); - res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - } - if (req.headers['access-control-request-private-network'] === 'true') { - res.setHeader('Access-Control-Allow-Private-Network', 'true'); - } -} - -async function handleOpen() { - if (picking) return { status: 409, body: { error: 'BUSY' } }; - picking = true; - try { - const picked = await pickSqliteFile(); - if (picked.error) return { status: 400, body: { error: picked.error } }; - const current = snapshot(picked.path); - const bytes = readFileSync(picked.path); - opened = current; - return { - status: 200, - body: { - name: path.basename(picked.path), - bytesBase64: bytes.toString('base64'), - size: current.size, - mtimeMs: current.mtimeMs, - }, - }; - } finally { - picking = false; - } -} - -async function handleWrite(req) { - let raw; - try { - raw = await readBody(req); - } catch (error) { - if (error?.code === 'TOO_LARGE') return { status: 413, body: { error: 'TOO_LARGE' } }; - return { status: 400, body: { error: 'BAD_BODY' } }; - } - let body; - try { - body = JSON.parse(raw.toString('utf8')); - } catch { - return { status: 400, body: { error: 'BAD_BODY' } }; - } - if (!opened) return { status: 400, body: { error: 'NOT_OPEN' } }; - - let current; - try { - current = snapshot(opened.path); - } catch { - return { status: 409, body: { error: 'FILE_CHANGED' } }; - } - const result = commitWrite({ opened, current, body }); - if (!result.ok) { - const status = result.error === 'FILE_CHANGED' || result.error === 'PATH_MISMATCH' ? 409 : 400; - return { status, body: { error: result.error } }; - } - writeFileSync(result.path, result.bytes); - opened = snapshot(result.path); - return { status: 200, body: { ok: true } }; -} - -export function startAgent() { - const token = loadToken(); - const server = createServer(async (req, res) => { - applyCors(req, res); - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url ?? '/', `http://${HOST}`); - try { - if (req.method === 'GET' && url.pathname === '/health') { - send(res, 200, { ok: true }); - return; - } - if (!tokensMatch(token, bearer(req))) { - send(res, 401, { error: 'UNAUTHORIZED' }); - return; - } - if (req.method === 'POST' && url.pathname === '/open') { - const result = await handleOpen(); - send(res, result.status, result.body); - return; - } - if (req.method === 'POST' && url.pathname === '/write') { - const result = await handleWrite(req); - send(res, result.status, result.body); - return; - } - send(res, 404, { error: 'NOT_FOUND' }); - } catch { - if (!res.headersSent) send(res, 500, { error: 'FAILED' }); - } - }); - - server.requestTimeout = 0; - server.headersTimeout = 0; - server.listen(PORT, HOST, () => { - process.stdout.write(`Dyolink local database helper listening on http://${HOST}:${PORT}\n`); - process.stdout.write(`Pairing code: ${token}\n`); - }); - return server; -} - -const isMain = - process.argv[1] && - fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); - -if (isMain) startAgent(); -- 2.53.0.windows.1
- {column.name} -
- {text} -