forked from admin/dyolink
improvements: browsing exocad's db ui flow bug fixed so that user can choose another file if the first file is invalid. exocad's material data insertion updated based on real data
This commit is contained in:
@@ -14,7 +14,7 @@ alwaysApply: false
|
||||
- **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
|
||||
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps plus `model_design` / `model_create`, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step (the whole plan for a historical `__case__` model step). Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Scan, packing, and shipping stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
|
||||
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
- **Send to Exocad:** local DentalDB SQLite write from the case header, every origin, at every screen size, only in Chrome and Edge (`showOpenFilePicker`). Other browsers do not show the button. There is no local helper and no download fallback. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id when the file is written. The browser remembers the file handle. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
|
||||
- **Send to Exocad:** local DentalDB SQLite write from the case header, every origin, at every screen size, only in Chrome and Edge (`showOpenFilePicker`). Other browsers do not show the button. There is no local helper and no download fallback. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id when the file is written. The browser remembers the file handle only after the DentalDB check. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a DentalDB database is not remembered, and Browse stays available. An empty `workParamsSHA` is filled from the newest saved `WorkParamsDB.xml` case. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
|
||||
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Files and Messages show unread counts (`LabCaseSectionReadState`); opening Details does not clear them. `ATTACHMENT_ADDED` is not a sidebar badge. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
|
||||
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 56px line box so html2canvas does not clip the 28px glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print root top padding is 16px portrait / 24px landscape so the QR is not clipped; `html2canvas` `scrollY` is 0. The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). Section rules keep a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename.
|
||||
- **Detail chrome:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
|
||||
|
||||
@@ -60,8 +60,8 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
|
||||
Writes the open case into a DentalDB SQLite file on this computer. Nothing is uploaded to the Dyolink server. Close Exocad before writing, then open it again.
|
||||
|
||||
- Button `cases.sendToExocad` on the case header at every screen size, every origin, for anyone who can open the case, only when the browser can overwrite the picked file (`showOpenFilePicker`: Chrome and Edge). It is separate from Outsource. Safari and other browsers do not show it. There is no local helper program and no download fallback.
|
||||
- `LocalDbSessionProvider` holds the open file. The browser overwrites the picked file and remembers that file handle (IndexedDB). The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse again.
|
||||
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. Match or create the client from `referringClinicName`, otherwise the case clinic name. Never use practice id `2147483647`. Match or create the patient by first and last name. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows.
|
||||
- `LocalDbSessionProvider` holds the open file. The browser overwrites the picked file and remembers that file handle (IndexedDB) only after the file passes the DentalDB check. The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a DentalDB database is not remembered, and the connect dialog stays open so Browse can be used again.
|
||||
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. Match or create the client from `referringClinicName`, otherwise the case clinic name. Never use practice id `2147483647`. Match or create the patient by first and last name. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. When `workParamsSHA` is empty, the treatment copies that hash and a new `WorkParamsInfo` / `WorkParamsInfoLocal` row from the newest saved case whose file is `WorkParamsDB.xml`. That is the material configuration Exocad needs to open the tooth chart. The CAD-Data project folder is still created by Exocad's own Save.
|
||||
- FDI restorations become `ToothWork` (`WorkTypeSN` / `MaterialSN`). A pontic uses the connected crown’s material. Implant, post and core, denture, and `UA`/`LA` are skipped and listed after the send.
|
||||
- When the file is written and `externalCode` is empty, save the Exocad `treatment_id` through `PATCH /cases/:id/external-code` (`TAB_CASES_EDIT`).
|
||||
- There is no Local database tab. Send to Exocad keeps `LocalDbSessionProvider`, `LocalDbConnectDialog`, and the file open/write path.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Reference rows that signup connects by name. Seed also upserts them.
|
||||
-- A migrated database that never ran seed must still be able to register.
|
||||
|
||||
INSERT INTO "organization_types" ("id", "name")
|
||||
SELECT gen_random_uuid()::text, 'CLINIC'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "organization_types" WHERE "name" = 'CLINIC');
|
||||
|
||||
INSERT INTO "organization_types" ("id", "name")
|
||||
SELECT gen_random_uuid()::text, 'LAB'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "organization_types" WHERE "name" = 'LAB');
|
||||
|
||||
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
|
||||
SELECT gen_random_uuid()::text, 'trial', 5, 0, '{}'::jsonb
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'trial');
|
||||
|
||||
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
|
||||
SELECT gen_random_uuid()::text, 'Small', 5, 150, '{}'::jsonb
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Small');
|
||||
|
||||
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
|
||||
SELECT gen_random_uuid()::text, 'Medium', 10, 250, '{}'::jsonb
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Medium');
|
||||
|
||||
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
|
||||
SELECT gen_random_uuid()::text, 'Large', 15, 400, '{}'::jsonb
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Large');
|
||||
|
||||
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
|
||||
SELECT gen_random_uuid()::text, 'Enterprise', 999999, 1000, '{}'::jsonb
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Enterprise');
|
||||
29
backend/src/common/reference-catalog.ts
Normal file
29
backend/src/common/reference-catalog.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
type CatalogDb = Prisma.TransactionClient;
|
||||
|
||||
const TRIAL_PLAN = {
|
||||
name: 'trial',
|
||||
maxUsers: 5,
|
||||
price: 0,
|
||||
features: {},
|
||||
} as const;
|
||||
|
||||
/** Signup connects this row by name. Create it when a database was migrated without seed. */
|
||||
export async function ensureTrialPlan(db: CatalogDb): Promise<void> {
|
||||
await db.plan.upsert({
|
||||
where: { name: TRIAL_PLAN.name },
|
||||
update: {},
|
||||
create: { ...TRIAL_PLAN },
|
||||
});
|
||||
}
|
||||
|
||||
/** CLINIC and LAB are required before an organization can connect its type. */
|
||||
export async function ensureOrganizationType(db: CatalogDb, name: string): Promise<void> {
|
||||
if (name !== 'CLINIC' && name !== 'LAB') return;
|
||||
await db.organizationType.upsert({
|
||||
where: { name },
|
||||
update: {},
|
||||
create: { name },
|
||||
});
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import { JwtPayload } from './interfaces/jwt-payload.interface';
|
||||
import { ownerPermissionsForOrgType, type OrganizationTypeName } from '../../common/organization-type';
|
||||
import { getEffectivePermissionNames, getOrgTypeFromMembership, hasActivePlan, participatesInTasks, participatesInTreatments, participationPermissionsForOrgType } from '../../common/membership-permissions';
|
||||
import { assertClinicOrganization, assertLabOrganization } from '../../common/organization-type';
|
||||
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
|
||||
import { StaffWorkingHoursService } from '../staff/staff-working-hours.service';
|
||||
import { UpsertWorkingHoursDto } from '../staff/dto/upsert-working-hours.dto';
|
||||
import { UpdateParticipationDto } from './dto/update-participation.dto';
|
||||
@@ -340,6 +341,8 @@ export class AuthService {
|
||||
}
|
||||
|
||||
await this.assertRegistrationAvailable(tx, email, payload.mobile);
|
||||
await ensureOrganizationType(tx, payload.organizationType);
|
||||
await ensureTrialPlan(tx);
|
||||
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
@@ -463,6 +466,7 @@ export class AuthService {
|
||||
try {
|
||||
const organization = await this.prisma.$transaction(async (tx) => {
|
||||
await assertOwnerOrganizationNameAvailable(tx, userId, organizationName);
|
||||
await ensureOrganizationType(tx, dto.organizationType);
|
||||
|
||||
const createdOrganization = await tx.organization.create({
|
||||
data: {
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
EmailVerificationService,
|
||||
} from '../email-verification/email-verification.service';
|
||||
import { canConnectOrganizationTypes } from '../../common/linked-organizations';
|
||||
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
|
||||
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
|
||||
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
|
||||
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
||||
@@ -627,6 +628,7 @@ export class OrganizationService {
|
||||
await assertOwnerOrganizationNameAvailable(tx, owner.id, organizationName, {
|
||||
conflictCode: ErrorCode.ORG_INVITE_NAME_TAKEN,
|
||||
});
|
||||
await ensureOrganizationType(tx, invitedType);
|
||||
|
||||
// Placeholder org until acceptInvite; plan stays null until acceptance.
|
||||
invitedOrg = await tx.organization.create({
|
||||
@@ -813,6 +815,8 @@ export class OrganizationService {
|
||||
});
|
||||
|
||||
let targetOrganizationId = invitation.invitedOrganizationId;
|
||||
await ensureOrganizationType(tx, dto.organizationType);
|
||||
await ensureTrialPlan(tx);
|
||||
if (targetOrganizationId) {
|
||||
await tx.organization.update({
|
||||
where: { id: targetOrganizationId },
|
||||
|
||||
1153
docs/exocad error.txt
Normal file
1153
docs/exocad error.txt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -110,6 +110,11 @@ async function saveBrowserHandle(handle: FilePickerHandle): Promise<void> {
|
||||
db.close();
|
||||
}
|
||||
|
||||
/** Drop the remembered file so the next send asks for a database again. */
|
||||
export async function forgetBrowserDatabase(): Promise<void> {
|
||||
await clearBrowserHandle();
|
||||
}
|
||||
|
||||
async function clearBrowserHandle(): Promise<void> {
|
||||
cachedHandle = null;
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
@@ -185,19 +190,33 @@ export async function openWithBrowserPicker(): Promise<DatabaseSink> {
|
||||
if (!picker) {
|
||||
throw new Error('FILE_PICKER_UNAVAILABLE');
|
||||
}
|
||||
const [handle] = await picker({
|
||||
multiple: false,
|
||||
excludeAcceptAllOption: false,
|
||||
id: 'dyolink-exocad-database',
|
||||
types: [
|
||||
{
|
||||
description: 'SQLite database',
|
||||
accept: {
|
||||
'application/vnd.sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
'application/x-sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'C',location:'browserFile.ts:openWithBrowserPicker',message:'picker invoked',data:{phase:'start'},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
try {
|
||||
const [handle] = await picker({
|
||||
multiple: false,
|
||||
excludeAcceptAllOption: false,
|
||||
id: 'dyolink-exocad-database',
|
||||
types: [
|
||||
{
|
||||
description: 'SQLite database',
|
||||
accept: {
|
||||
'application/vnd.sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
'application/x-sqlite3': ['.db', '.sqlite', '.sqlite3'],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return sinkFromBrowserHandle(handle);
|
||||
],
|
||||
});
|
||||
const sink = await sinkFromBrowserHandle(handle);
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'C',location:'browserFile.ts:openWithBrowserPicker',message:'picker returned',data:{phase:'returned',fileName:sink.name},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
return sink;
|
||||
} catch (error) {
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'C',location:'browserFile.ts:openWithBrowserPicker',message:'picker failed',data:{phase:'threw',errorName:error instanceof Error ? error.name : 'unknown'},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,4 +253,61 @@ describe('transferCaseToExocad', () => {
|
||||
expect(() => transferCaseToExocad(query, sampleCase(), options)).toThrow(ExocadTransferError);
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('copies the lab default material configuration onto a new treatment', async () => {
|
||||
const db = await openSql();
|
||||
const query = seed(db);
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN workParamsSHA TEXT');
|
||||
db.run('ALTER TABLE Treatment ADD COLUMN workParamInfoId INT');
|
||||
db.run('CREATE TABLE WorkParamsData (hash TEXT primary key, content BLOB)');
|
||||
db.run(
|
||||
`CREATE TABLE WorkParamsInfo (
|
||||
id integer primary key autoincrement,
|
||||
workParamsDataHash TEXT,
|
||||
lastModificationDate DATETIME,
|
||||
foreign key (workParamsDataHash) references WorkParamsData(hash)
|
||||
)`,
|
||||
);
|
||||
db.run('CREATE TABLE WorkParamsInfoLocal (id INT primary key, fileName TEXT)');
|
||||
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('content-hash', x'00')`);
|
||||
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('endo-hash', x'01')`);
|
||||
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (5, 'content-hash', '2024-09-27')`);
|
||||
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (6, 'endo-hash', '2024-09-27')`);
|
||||
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (5, 'D:\\config\\WorkParamsDB.xml')`);
|
||||
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (6, 'D:\\config\\WorkParamsDB-EndoCrown.xml')`);
|
||||
db.run(
|
||||
`INSERT INTO Treatment (
|
||||
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
|
||||
) VALUES (50, 0, 1, 1, 1, 1, '2026-01-01', 16, 'donor', 'donor-case', 'file-sha', 5)`,
|
||||
);
|
||||
db.run(
|
||||
`INSERT INTO Treatment (
|
||||
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
|
||||
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
|
||||
) VALUES (60, 0, 1, 1, 1, 1, '2026-02-01', 16, 'endo', 'endo-case', 'endo-sha', 6)`,
|
||||
);
|
||||
|
||||
transferCaseToExocad(query, sampleCase(), options);
|
||||
const header = query.all(
|
||||
'SELECT workParamsSHA, workParamInfoId FROM Treatment WHERE importedOrderId = ?',
|
||||
['case-1'],
|
||||
);
|
||||
const infoId = header[0]?.[1];
|
||||
expect(header[0]?.[0]).toBe('file-sha');
|
||||
expect(infoId).not.toBe(5);
|
||||
expect(query.all('SELECT workParamsDataHash FROM WorkParamsInfo WHERE id = ?', [infoId as number])).toEqual([
|
||||
['content-hash'],
|
||||
]);
|
||||
expect(query.all('SELECT fileName FROM WorkParamsInfoLocal WHERE id = ?', [infoId as number])).toEqual([
|
||||
['D:\\config\\WorkParamsDB.xml'],
|
||||
]);
|
||||
|
||||
transferCaseToExocad(query, sampleCase({ teeth: [{ tooth: '16', prosthesisTypeCode: 'pfm_crown' }] }), options);
|
||||
expect(query.all('SELECT COUNT(*) FROM WorkParamsInfo')).toEqual([[3]]);
|
||||
expect(
|
||||
query.all('SELECT workParamInfoId FROM Treatment WHERE importedOrderId = ?', ['case-1']),
|
||||
).toEqual([[infoId]]);
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -198,6 +198,11 @@ function assertExocad(db: SqliteQuery): void {
|
||||
if (lab.length === 0) throw new ExocadTransferError('NOT_EXOCAD');
|
||||
}
|
||||
|
||||
/** Reject a SQLite file that is not a DentalDB database. Call this before remembering the file. */
|
||||
export function assertExocadDatabase(db: SqliteQuery): void {
|
||||
assertExocad(db);
|
||||
}
|
||||
|
||||
function clientRows(db: SqliteQuery): Array<{ practiceId: number; name: string }> {
|
||||
return db
|
||||
.all(
|
||||
@@ -320,6 +325,66 @@ function insertTeeth(db: SqliteQuery, treatmentId: number, writes: ToothWrite[])
|
||||
}
|
||||
}
|
||||
|
||||
function treatmentHasColumn(db: SqliteQuery, column: string): boolean {
|
||||
const rows = db.all('PRAGMA table_info(Treatment)');
|
||||
return rows.some((row) => String(row[1] ?? '').toLowerCase() === column.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the treatment at the lab's current default material configuration.
|
||||
* Exocad loads WorkParamsInfo by workParamInfoId. A null id is the read-only
|
||||
* project warning and the tooth-click crash. Each saved case has its own info row.
|
||||
*/
|
||||
function embedMaterialConfiguration(db: SqliteQuery, treatmentId: number): void {
|
||||
if (!treatmentHasColumn(db, 'workParamsSHA') || !treatmentHasColumn(db, 'workParamInfoId')) return;
|
||||
const tables = db.all(`SELECT name FROM sqlite_master WHERE type = 'table'`);
|
||||
const names = new Set(tables.map((row) => String(row[0] ?? '').toLowerCase()));
|
||||
if (!names.has('workparamsinfo') || !names.has('workparamsinfolocal')) return;
|
||||
|
||||
const current = db.all(
|
||||
'SELECT workParamsSHA, workParamInfoId FROM Treatment WHERE treatment_id = ?',
|
||||
[treatmentId],
|
||||
);
|
||||
const currentSha = String(current[0]?.[0] ?? '').trim();
|
||||
const currentInfo = numberValue(current[0]?.[1]);
|
||||
if (currentSha && currentInfo > 0) return;
|
||||
|
||||
const donor = db.all(
|
||||
`SELECT t.workParamsSHA, i.workParamsDataHash, i.lastModificationDate, l.fileName, t.workParamInfoId
|
||||
FROM Treatment t
|
||||
JOIN WorkParamsInfo i ON i.id = t.workParamInfoId
|
||||
JOIN WorkParamsInfoLocal l ON l.id = i.id
|
||||
WHERE t.treatment_id != ?
|
||||
AND t.workParamsSHA IS NOT NULL
|
||||
AND trim(t.workParamsSHA) != ''
|
||||
AND l.fileName LIKE '%WorkParamsDB.xml'
|
||||
ORDER BY t.treatment_id DESC
|
||||
LIMIT 1`,
|
||||
[treatmentId],
|
||||
);
|
||||
const source = donor[0];
|
||||
if (!source || source[3] == null) {
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'E',location:'exocadTransfer.ts:embedMaterialConfiguration',message:'no material donor',data:{treatmentId},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
return;
|
||||
}
|
||||
|
||||
db.run(
|
||||
`INSERT INTO WorkParamsInfo (workParamsDataHash, lastModificationDate) VALUES (?, ?)`,
|
||||
[source[1] == null ? null : String(source[1]), source[2] == null ? null : String(source[2])],
|
||||
);
|
||||
const newId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
db.run('INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (?, ?)', [newId, String(source[3])]);
|
||||
db.run(
|
||||
'UPDATE Treatment SET workParamsSHA = ?, workParamInfoId = ? WHERE treatment_id = ?',
|
||||
[String(source[0]), newId, treatmentId],
|
||||
);
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'E',location:'exocadTransfer.ts:embedMaterialConfiguration',message:'embedded material configuration',data:{treatmentId,donorInfoId:numberValue(source[4]),newInfoId:newId,shaCopied:true},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
}
|
||||
|
||||
function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTransferOptions): ExocadTransferResult {
|
||||
const practiceId = ensureClient(db, input.clinicName);
|
||||
const patientId = ensurePatient(db, practiceId, input.patientFirstName, input.patientLastName);
|
||||
@@ -356,6 +421,7 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
|
||||
);
|
||||
deleteToothWork(db, treatmentId);
|
||||
insertTeeth(db, treatmentId, writes);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: false, skipped };
|
||||
}
|
||||
|
||||
@@ -370,6 +436,7 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
|
||||
);
|
||||
const treatmentId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
|
||||
insertTeeth(db, treatmentId, writes);
|
||||
embedMaterialConfiguration(db, treatmentId);
|
||||
return { treatmentId, created: true, skipped };
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ type LocalDbTranslator = (key: string) => string;
|
||||
export function localDbErrorText(
|
||||
error: unknown,
|
||||
t: LocalDbTranslator,
|
||||
fallback: 'openFailed' | 'applyFailed',
|
||||
fallback: 'openFailed' | 'applyFailed' | 'loadFailed',
|
||||
): string {
|
||||
if (error instanceof ExocadTransferError) return t('notExocad');
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
} from '@/components/lab/caseDetailUtils';
|
||||
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
|
||||
import { browserCanWriteLocalFile } from '@/components/local-db/browserFile';
|
||||
import type { ExocadCaseInput } from '@/components/local-db/exocadTransfer';
|
||||
import { ExocadTransferError, 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';
|
||||
@@ -434,6 +434,10 @@ export function CaseDetailPanel({
|
||||
try {
|
||||
result = localDb.transferCase(toExocadCase(labCase));
|
||||
} catch (caught) {
|
||||
if (caught instanceof ExocadTransferError) await localDb.abandon();
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'A',location:'CaseDetailPanel.tsx:onSendToExocad',message:'transfer failed',data:{errorName:caught instanceof Error ? caught.name : 'unknown',code:caught instanceof ExocadTransferError ? caught.code : null},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
openWithBrowserPicker,
|
||||
type DatabaseSink,
|
||||
} from '@/components/local-db/browserFile';
|
||||
import { localDbErrorText } from '@/components/local-db/localDbErrors';
|
||||
|
||||
type LocalDbOpenControlsProps = {
|
||||
onOpened: (sink: DatabaseSink) => Promise<void>;
|
||||
@@ -30,8 +31,8 @@ export function LocalDbOpenControls({ onOpened }: LocalDbOpenControlsProps) {
|
||||
}
|
||||
try {
|
||||
await onOpened(sink);
|
||||
} catch {
|
||||
setError(t('loadFailed'));
|
||||
} catch (caught) {
|
||||
setError(localDbErrorText(caught, t, 'loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,10 +10,17 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { transferCaseToExocad, type ExocadCaseInput, type ExocadTransferResult } from '@/components/local-db/exocadTransfer';
|
||||
import {
|
||||
assertExocadDatabase,
|
||||
ExocadTransferError,
|
||||
transferCaseToExocad,
|
||||
type ExocadCaseInput,
|
||||
type ExocadTransferResult,
|
||||
} from '@/components/local-db/exocadTransfer';
|
||||
import {
|
||||
browserCanWriteLocalFile,
|
||||
browserDatabaseStillExists,
|
||||
forgetBrowserDatabase,
|
||||
preloadBrowserHandle,
|
||||
reopenStoredBrowserFile,
|
||||
type DatabaseSink,
|
||||
@@ -29,6 +36,8 @@ import { LocalDbConnectDialog } from '@/components/ui/local-db/LocalDbConnectDia
|
||||
|
||||
export type LocalDbSessionValue = {
|
||||
apply: () => Promise<void>;
|
||||
/** Forget the open file after it is rejected, so the next send can browse again. */
|
||||
abandon: () => Promise<void>;
|
||||
requestConnection: () => Promise<boolean>;
|
||||
transferCase: (input: ExocadCaseInput) => ExocadTransferResult;
|
||||
};
|
||||
@@ -66,6 +75,15 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const replaceWithSink = useCallback(async (sink: DatabaseSink) => {
|
||||
const next = await LocalSqlite.open(sink.bytes);
|
||||
try {
|
||||
next.execute((query) => assertExocadDatabase(query));
|
||||
} catch (error) {
|
||||
next.close();
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'D',location:'LocalDbSessionProvider.tsx:replaceWithSink',message:'rejected database',data:{fileName:sink.name,valid:false,errorName:error instanceof Error ? error.name : 'unknown'},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
await sink.remember?.();
|
||||
} catch {
|
||||
@@ -74,8 +92,19 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
|
||||
sessionRef.current?.close();
|
||||
sessionRef.current = next;
|
||||
sinkRef.current = sink;
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'D',location:'LocalDbSessionProvider.tsx:replaceWithSink',message:'accepted database',data:{fileName:sink.name,valid:true},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
}, []);
|
||||
|
||||
const abandon = useCallback(async () => {
|
||||
dropSession();
|
||||
await forgetBrowserDatabase();
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'A',location:'LocalDbSessionProvider.tsx:abandon',message:'forgot rejected database',data:{forgot:true},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
}, [dropSession]);
|
||||
|
||||
const apply = useCallback(async () => {
|
||||
const session = sessionRef.current;
|
||||
const sink = sinkRef.current;
|
||||
@@ -101,17 +130,27 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
|
||||
const sink = sinkRef.current;
|
||||
if (sessionRef.current && sink) {
|
||||
const alive = await browserDatabaseStillExists();
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'A',location:'LocalDbSessionProvider.tsx:requestConnection',message:'existing session',data:{alive,fileName:sink.name},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
if (alive) return true;
|
||||
dropSession();
|
||||
}
|
||||
try {
|
||||
const restored = browserCanWriteLocalFile() ? await reopenStoredBrowserFile() : null;
|
||||
if (restored) {
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'B',location:'LocalDbSessionProvider.tsx:requestConnection',message:'restoring remembered file',data:{fileName:restored.name},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
await replaceWithSink(restored);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// The file dialog is the fallback when the saved file cannot be read.
|
||||
} catch (error) {
|
||||
dropSession();
|
||||
if (error instanceof ExocadTransferError) await forgetBrowserDatabase();
|
||||
// #region agent log
|
||||
fetch('http://127.0.0.1:7814/ingest/421f4a54-ac71-4eaa-bb62-6b661023387a',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'9546d2'},body:JSON.stringify({sessionId:'9546d2',runId:'post-fix',hypothesisId:'B',location:'LocalDbSessionProvider.tsx:requestConnection',message:'remembered file rejected',data:{errorName:error instanceof Error ? error.name : 'unknown'},timestamp:Date.now()})}).catch(()=>{});
|
||||
// #endregion
|
||||
}
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
connectResolveRef.current = resolve;
|
||||
@@ -125,8 +164,8 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
|
||||
}, [dropSession, replaceWithSink]);
|
||||
|
||||
const value = useMemo<LocalDbSessionValue>(
|
||||
() => ({ apply, requestConnection, transferCase }),
|
||||
[apply, requestConnection, transferCase],
|
||||
() => ({ apply, abandon, requestConnection, transferCase }),
|
||||
[abandon, apply, requestConnection, transferCase],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user