diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 82aed6d..9445af4 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -41,6 +41,7 @@ export const ErrorCode = { PERMISSION_ACCESS_TASKS: 'PERMISSION_ACCESS_TASKS', PERMISSION_EDIT_TASKS: 'PERMISSION_EDIT_TASKS', PERMISSION_ACCESS_CASES: 'PERMISSION_ACCESS_CASES', + PERMISSION_EDIT_CASES: 'PERMISSION_EDIT_CASES', PERMISSION_ACCESS_BILLING: 'PERMISSION_ACCESS_BILLING', PERMISSION_EDIT_BILLING: 'PERMISSION_EDIT_BILLING', PERMISSION_ACCESS_STAFF: 'PERMISSION_ACCESS_STAFF', diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index b08976d..c146a0f 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -1474,7 +1474,7 @@ export class CasesService { if (names.includes('TAB_CASES_EDIT')) { return; } - throw new AppException(ErrorCode.PERMISSION_ACCESS_CASES, HttpStatus.FORBIDDEN); + throw new AppException(ErrorCode.PERMISSION_EDIT_CASES, HttpStatus.FORBIDDEN); } private async getMembership(userId: string, organizationId: string) { diff --git a/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts b/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts new file mode 100644 index 0000000..e5a7f74 --- /dev/null +++ b/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts @@ -0,0 +1,64 @@ +import { narrowCatalogForOrgType } from './narrowCatalogForOrgType'; +import type { ExtractionCatalog } from './voice.providers'; + +const catalog = (): ExtractionCatalog => ({ + treatmentTypes: [ + { code: 'prosthesis', label: 'Prosthesis' }, + { code: 'restoration', label: 'Restoration' }, + ], + prosthesisTypes: [ + { + code: 'pfm_crown', + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + { + code: 'complete_denture', + label: 'Complete Denture', + category: 'denture', + subcategory: '', + chartRegion: 'arch', + stackGroup: 'arch', + }, + ], + prosthesisCategories: [ + { code: 'crown', label: 'Crown' }, + { code: 'denture', label: 'Denture' }, + ], + prosthesisSubcategories: [{ code: 'veneer', label: 'Veneer' }], + labs: [{ id: 'org-lab-1', name: 'Some Lab' }], +}); + +describe('narrowCatalogForOrgType', () => { + it('drops the treatment types and the linked labs for a LAB org', () => { + const narrowed = narrowCatalogForOrgType(catalog(), 'LAB'); + expect(narrowed.treatmentTypes).toEqual([]); + expect(narrowed.labs).toEqual([]); + }); + + it('keeps the prosthesis tree, its categories and its subcategories intact for a LAB org', () => { + const full = catalog(); + const narrowed = narrowCatalogForOrgType(full, 'LAB'); + expect(narrowed.prosthesisTypes).toEqual(full.prosthesisTypes); + expect(narrowed.prosthesisCategories).toEqual(full.prosthesisCategories); + expect(narrowed.prosthesisSubcategories).toEqual( + full.prosthesisSubcategories, + ); + }); + + it('returns the catalog unchanged for a CLINIC org', () => { + const full = catalog(); + expect(narrowCatalogForOrgType(full, 'CLINIC')).toEqual(catalog()); + expect(narrowCatalogForOrgType(full, 'CLINIC').labs).toHaveLength(1); + }); + + it('does not mutate the catalog it was given', () => { + const full = catalog(); + narrowCatalogForOrgType(full, 'LAB'); + expect(full.treatmentTypes).toHaveLength(2); + expect(full.labs).toHaveLength(1); + }); +}); diff --git a/backend/src/modules/voice/narrowCatalogForOrgType.ts b/backend/src/modules/voice/narrowCatalogForOrgType.ts new file mode 100644 index 0000000..6bd477e --- /dev/null +++ b/backend/src/modules/voice/narrowCatalogForOrgType.ts @@ -0,0 +1,20 @@ +import type { OrganizationTypeName } from '../../common/organization-type'; +import type { ExtractionCatalog } from './voice.providers'; + +/** + * A LAB org dictates into a case line: the treatment type is always `prosthesis` (written + * server-side) and the lab is the destination itself. Emptying both lists is the whole of lab + * mode — the prompt already renders an empty list as "(none available)", so the model has no + * code left to emit for either field. + * + * It also closes a hole: `listLinkedLabs` does not filter by organisation type, so for a LAB + * org it returns the linked *clinics*, and a lab owner naming their referring clinic would get + * that clinic's id back as `labId`. + */ +export function narrowCatalogForOrgType( + catalog: ExtractionCatalog, + orgType: OrganizationTypeName, +): ExtractionCatalog { + if (orgType !== 'LAB') return catalog; + return { ...catalog, treatmentTypes: [], labs: [] }; +} diff --git a/backend/src/modules/voice/voice.controller.ts b/backend/src/modules/voice/voice.controller.ts index 0b93657..1ad2794 100644 --- a/backend/src/modules/voice/voice.controller.ts +++ b/backend/src/modules/voice/voice.controller.ts @@ -9,7 +9,6 @@ import { } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import type { Request, Response } from 'express'; -import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { ExtractVoiceDto } from './dto/voice.dto'; import { VoiceThrottlerGuard } from './voice-throttler.guard'; @@ -19,7 +18,9 @@ type VoiceRequestUser = { id: string; organizationId?: string }; @ApiTags('voice') @ApiBearerAuth('JWT-auth') -@UseGuards(JwtAuthGuard, ClinicOrgGuard) +// No org-type guard: both org types dictate, and the service branches on the selected org's +// type for the permission it asserts and for the catalog it hands the model. +@UseGuards(JwtAuthGuard) @Controller('voice') export class VoiceController { constructor(private readonly voiceService: VoiceService) {} @@ -41,7 +42,7 @@ export class VoiceController { @UseGuards(VoiceThrottlerGuard) @ApiOperation({ summary: - 'Transcribe a recording and extract treatment detail intents (TAB_TREATMENT_EDIT)', + 'Transcribe a recording and extract entry intents (CLINIC: TAB_TREATMENT_EDIT, LAB: TAB_CASES_EDIT)', }) async extract( @Req() req: Request & { user: VoiceRequestUser }, diff --git a/backend/src/modules/voice/voice.service.spec.ts b/backend/src/modules/voice/voice.service.spec.ts new file mode 100644 index 0000000..fdb8a77 --- /dev/null +++ b/backend/src/modules/voice/voice.service.spec.ts @@ -0,0 +1,218 @@ +import { AppException, ErrorCode } from '../../common/errors'; +import { VoiceService } from './voice.service'; +import type { ExtractionCatalog, ExtractionResult } from './voice.providers'; +import type { ExtractVoiceDto } from './dto/voice.dto'; + +const mockExtract = jest.fn< + Promise, + [string, ExtractionCatalog, string] +>(); + +jest.mock('./openrouter.provider', () => ({ + OpenRouterAsrProvider: jest.fn().mockImplementation(() => ({ + transcribe: () => + Promise.resolve({ + text: 'tooth twelve, pfm crown', + usage: { costUsd: 0.001, seconds: 3 }, + }), + })), + OpenRouterExtractionProvider: jest.fn().mockImplementation(() => ({ + extract: (transcript: string, catalog: ExtractionCatalog, locale: string) => + mockExtract(transcript, catalog, locale), + })), +})); + +const EMPTY_INTENT = { + treatmentType: null, + teeth: [], + connectedSpans: [], + comment: null, + commentTrigger: null, + prosthesis: [], + labId: null, + labMatchExact: false, + due: null, +}; + +const DTO: ExtractVoiceDto = { + audio: 'AAAA', + format: 'webm', + timeZone: 'UTC', + durationMs: 3_000, + locale: 'en', +}; + +function buildService(opts: { + orgType: 'CLINIC' | 'LAB'; + permissions: string[]; +}): VoiceService { + const prisma = { + organization: { + findUnique: jest.fn().mockResolvedValue({ type: { name: opts.orgType } }), + }, + membership: { + findFirst: jest.fn().mockResolvedValue({ + isOwner: false, + organization: { type: { name: opts.orgType }, plan: { name: 'pro' } }, + permissions: opts.permissions.map((name) => ({ + permission: { name }, + })), + }), + }, + // The counterpart link a lab org has: `listLinkedLabs` does not filter by org type, so + // for a LAB org this row is a linked *clinic*. + organizationLink: { + findMany: jest + .fn() + .mockResolvedValueOnce([ + { organizationB: { id: 'org-counterpart', name: 'Counterpart' } }, + ]) + .mockResolvedValue([]), + }, + }; + + const config = { + get: () => ({ + openRouter: { apiKey: 'test-key', baseUrl: 'https://example.invalid' }, + profiles: { + en: { + asr: { provider: 'openrouter', model: 'asr-model' }, + llm: { provider: 'openrouter', model: 'llm-model' }, + }, + }, + maxRecordingMs: 120_000, + throttle: { ttl: 60, limit: 10 }, + }), + }; + + const treatmentCatalog = { + list: jest.fn().mockResolvedValue([ + { code: 'prosthesis', label: 'Prosthesis', availableInTreatment: true }, + { code: 'restoration', label: 'Restoration', availableInTreatment: true }, + ]), + }; + + const prosthesisCatalog = { + list: jest.fn().mockResolvedValue([ + { + code: 'pfm_crown', + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + ]), + listCategories: jest + .fn() + .mockResolvedValue([{ code: 'crown', label: 'Crown' }]), + listSubcategories: jest + .fn() + .mockResolvedValue([{ code: 'veneer', label: 'Veneer' }]), + }; + + return new VoiceService( + prisma as never, + config as never, + treatmentCatalog as never, + prosthesisCatalog as never, + ); +} + +async function codeOfThrown(promise: Promise): Promise { + try { + await promise; + return 'NO_THROW'; + } catch (error) { + return error instanceof AppException + ? (error.getResponse() as { code: string }).code + : `UNEXPECTED:${String(error)}`; + } +} + +describe('VoiceService.extract — the org type decides the permission and the catalog', () => { + beforeEach(() => { + mockExtract.mockReset(); + mockExtract.mockResolvedValue({ intent: EMPTY_INTENT, costUsd: 0.002 }); + }); + + const user = { id: 'user-1', organizationId: 'org-1' }; + + it('C01 CLINIC granted: TAB_TREATMENT_EDIT passes, and the model gets the full catalog', async () => { + const service = buildService({ + orgType: 'CLINIC', + permissions: ['TAB_TREATMENT_EDIT'], + }); + + await service.extract(user, DTO, 'en'); + + const catalog = mockExtract.mock.calls[0][1]; + expect(catalog.treatmentTypes.map((t) => t.code)).toEqual([ + 'prosthesis', + 'restoration', + ]); + expect(catalog.labs).toHaveLength(1); + }); + + it('C02 CLINIC denied: no TAB_TREATMENT_EDIT is 403 and never reaches the model', async () => { + const service = buildService({ + orgType: 'CLINIC', + permissions: ['TAB_TREATMENT_READ'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_EDIT_TREATMENTS, + ); + expect(mockExtract).not.toHaveBeenCalled(); + }); + + it('C03 LAB granted: TAB_CASES_EDIT passes, and the model gets no treatment types and no labs', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_EDIT'], + }); + + await service.extract(user, DTO, 'en'); + + const catalog = mockExtract.mock.calls[0][1]; + expect(catalog.treatmentTypes).toEqual([]); + expect(catalog.labs).toEqual([]); + expect(catalog.prosthesisTypes.map((p) => p.code)).toEqual(['pfm_crown']); + }); + + it('C04 LAB denied: no TAB_CASES_EDIT is 403 and never reaches the model', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_READ'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_EDIT_CASES, + ); + expect(mockExtract).not.toHaveBeenCalled(); + }); + + it('denies a LAB member holding the clinic-side edit permission', async () => { + // TAB_TREATMENT_EDIT is clinic-only, so it must not open the lab route. + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_TREATMENT_EDIT'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_EDIT_CASES, + ); + }); + + it('rejects a request with no selected organisation before any vendor call', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_EDIT'], + }); + + expect( + await codeOfThrown(service.extract({ id: 'user-1' }, DTO, 'en')), + ).toBe(ErrorCode.AUTH_ORG_NOT_SELECTED); + expect(mockExtract).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/modules/voice/voice.service.ts b/backend/src/modules/voice/voice.service.ts index 7c554cf..17d5f22 100644 --- a/backend/src/modules/voice/voice.service.ts +++ b/backend/src/modules/voice/voice.service.ts @@ -9,6 +9,11 @@ import { } from '../../common/zoned-civil-time'; import type { VoiceConfig, VoiceProfile } from '../../configs/configurations'; import { hasEffectivePermission } from '../../common/membership-permissions'; +import { + getOrganizationTypeName, + type OrganizationTypeName, +} from '../../common/organization-type'; +import { narrowCatalogForOrgType } from './narrowCatalogForOrgType'; import { normalizeCatalogLocale } from '../catalog/catalog-label.service'; import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service'; import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service'; @@ -80,7 +85,7 @@ export class VoiceService { ): Promise { const startedAt = Date.now(); const organizationId = this.assertOrganization(user); - await this.assertCanEditTreatment(user.id, organizationId); + const orgType = await this.assertCanDictate(user.id, organizationId); const catalogLocale = normalizeCatalogLocale(locale); const profile = this.resolveProfile(catalogLocale); @@ -136,7 +141,10 @@ export class VoiceService { try { // Inside the try: a catalog/DB failure here must surface as VOICE_EXTRACT_FAILED, which // the clinician can act on, rather than a generic 500. - const catalog = await this.buildCatalog(organizationId, catalogLocale); + const catalog = narrowCatalogForOrgType( + await this.buildCatalog(organizationId, catalogLocale), + orgType, + ); const result = await extraction.extract( transcript, catalog, @@ -183,7 +191,27 @@ export class VoiceService { return user.organizationId; } - private async assertCanEditTreatment(userId: string, organizationId: string) { + /** + * The one gate on dictation, and the source of the extraction mode: the selected org's type + * decides both the permission asserted and — through the returned type — the catalog the + * model is handed. It is never taken from the request body. + * + * `TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it on + * the lab side would deny every lab member including the owner. + */ + private async assertCanDictate( + userId: string, + organizationId: string, + ): Promise { + const orgType = await getOrganizationTypeName(this.prisma, organizationId); + const [permission, deniedCode] = + orgType === 'LAB' + ? (['TAB_CASES_EDIT', ErrorCode.PERMISSION_EDIT_CASES] as const) + : ([ + 'TAB_TREATMENT_EDIT', + ErrorCode.PERMISSION_EDIT_TREATMENTS, + ] as const); + const membership = await this.prisma.membership.findFirst({ where: { userId, @@ -201,12 +229,10 @@ export class VoiceService { HttpStatus.FORBIDDEN, ); } - if (!hasEffectivePermission(membership, 'TAB_TREATMENT_EDIT')) { - throw new AppException( - ErrorCode.PERMISSION_EDIT_TREATMENTS, - HttpStatus.FORBIDDEN, - ); + if (!hasEffectivePermission(membership, permission)) { + throw new AppException(deniedCode, HttpStatus.FORBIDDEN); } + return orgType; } private resolveProfile(locale: string): VoiceProfile { diff --git a/docs/specs/voice-lab-case-entry.md b/docs/specs/voice-lab-case-entry.md new file mode 100644 index 0000000..93d845e --- /dev/null +++ b/docs/specs/voice-lab-case-entry.md @@ -0,0 +1,378 @@ +--- +type: task +status: active +created: 2026-09-16 +repos: + - repo: dyolink + path: ~/PersonalProjects/dyolink + branch: feat/cases/add-voice-input-for-lab-case-line + base: origin/master + role: lab-mode extraction catalog + lab line apply + shared review sheet + spec_slug: voice-lab-case-entry + merge_after: [] +aliases: [voice lab case, lab dictation, case line voice, lab mic] +--- + +# Voice entry for a lab case line + +**Area:** Cases tab (LAB orgs) — `CaseCreatePanel` +**Created:** 2026-09-16 +**Depends on:** [`voice-treatment-entry`](voice-treatment-entry/spec.md), already merged +to `master`. Every resolver, the prompt, the review sheet and the stack rules come from +there unchanged. This spec records only what differs. + +A lab owner entering their own work fills a case draft by hand: Add Line, tap the FDI +chart, open the prosthesis popover, pick a leaf, repeat. The clinic side already replaced +that with a microphone. The same dictation describes the same thing on the lab side — the +teeth and the job — so the same contract should fill it. + +--- + +## 1. Scope + +**In:** one dictation fills **one case line** — its teeth, its prosthesis stack, its +comment — plus the case's due date. + +**Out:** the case header's identity fields. Patient name, patient mobile, referring +dentist, referring clinic and the partner-clinic dropdown stay typed by hand (§9). + +The header is where a case carries a person's name. Keeping the mic away from it is what +lets this ship without reopening the transcript decision in `voice-treatment-entry` §10. + +--- + +## 2. What a lab line is + +`LineDraft` (`CaseCreatePanel.tsx:35`) is already the shape the extraction produces: + +```ts +type LineDraft = { + clientId: string; + id?: string; + teeth: FdiToothId[]; + toothSelectionGroups: ToothSelectionGroup[]; + comment: string; + toothProsthesis: Array<{ tooth; prosthesisTypeCode; selectionGroupId?; detailClientId }>; + attachments: LabCaseAttachmentMeta[]; +}; +``` + +Against a clinic `TreatmentDetailDraft` it has no `treatmentType` — on the lab side that is +always `prosthesis`, written server-side at `cases.service.ts:488` — and it folds the +clinic's separate `LabCaseDraft` rows into `toothProsthesis` on the line itself. + +Attachments are out of scope: dictation cannot produce one. + +### The save model is simpler than the clinic's, and that matters + +`CaseCreatePanel` autosaves through **one** `PUT /cases/:id` carrying the header, the lines +and their `toothProsthesis` together. `buildPayload` (`:177`) reads React **state**; the +debounced effect (`:239`) fires 500 ms after any state change; `persist` (`:210`) sends it. + +Two consequences, both load-bearing: + +1. **No ref dance.** The clinic side reads `detailsRef.current` and `labCaseDraftsRef.current` + because a save runs before the re-render. Here nothing saves inside the handler, so + `setLines` is the whole apply. Three of the five defects found in clinic live use were in + that ref coupling; they cannot occur here. +2. **No cross-request validation.** The clinic's lab rows go in a second request that + re-reads the saved detail and rejects a tooth the detail does not carry + (`TREATMENT_TOOTH_NOT_ON_DETAIL`, `treatments.service.ts:806`). The lab write validates + only the prosthesis code (`cases.service.ts:481`) because the line and its jobs arrive in + one transaction from one payload and cannot disagree. + +Point 2 cuts both ways: nothing *rejects* a mismatch either. A line whose `teeth` and +`toothProsthesis` disagree would be written silently, and the case chart would then show +something the generated tasks do not. §6 keeps the clinic's invariant for that reason. + +--- + +## 3. User flow + +``` +Cases tab → Add Case → draft opens in the right pane (CaseCreatePanel) + +┌──────────────────────────────────┐ +│ Patient [ typed ] │ +│ Dentist [ typed ] │ +│ Clinic [ dropdown / typed ] │ +│ Due [ AppDateInput ] │ ← the mic may write this +├──────────────────────────────────┤ +│ Lines [+ Add Line][🎤]│ ← the mic lives here +│ · Line 1 12,13 · PFM crown │ +└──────────────────────────────────┘ +``` + +1. Tap the mic. `VoiceRecordingBar` shows elapsed time and the level meter, exactly as on + the clinic side. +2. Tap stop. The clip goes to `POST /voice/extract`. +3. `VoiceReviewSheet` opens in lab mode with at most three rows (§5). +4. Confirm. The line lands, the autosave effect picks it up 500 ms later. + +The mic sits beside **Add Line** (`CaseCreatePanel.tsx:412-426`), built the same way +`AddDetailWithVoice` builds the clinic's split button, and shares its `disabled` state. + +**No new i18n keys.** Every voice string is under `treatment.*`, and `CaseCreatePanel` +already holds `tTreatment = useTranslations('treatment')` at `:110`. + +--- + +## 4. Lab mode is an empty catalog, not a second prompt + +`buildExtractionPrompt` renders whatever catalog it is handed. It already prints +`(none available)` for an empty code list and `(none linked — labId must be null)` for an +empty lab list. So lab mode needs **no prompt text change at all**: + +| Catalog field | CLINIC | LAB | Why | +|---|---|---|---| +| `treatmentTypes` | full list | `[]` | the type is always `prosthesis`, written server-side | +| `labs` | linked labs | `[]` | the lab *is* the destination | +| `prosthesisTypes` / categories / subcategories | full tree | full tree | unchanged | + +The model cannot emit a `treatmentType` or a `labId` because neither list has anything in +it. The resolver needs no change; the two fields simply come back null. + +### The bug this avoids + +`listLinkedLabs` (`voice.service.ts:272`) does **not** filter by organisation type. For a +LAB org it returns the linked **clinics**, and the prompt would present them under the +heading `LABS THIS CLINIC CAN SEND TO`. A lab owner naming their referring clinic would get +that clinic's id back as `labId`. Emptying the list is what stops it. + +### The narrowing is a pure function + +`buildCatalog` (`:257`) stays untested I/O. The decision comes out: + +```ts +export function narrowCatalogForOrgType( + catalog: ExtractionCatalog, + orgType: OrganizationTypeName, +): ExtractionCatalog; +``` + +`LAB` returns the catalog with `treatmentTypes: []` and `labs: []`. `CLINIC` returns it +untouched. It has its own spec (§10) because it is the one place a future change to +`listLinkedLabs` could silently reach lab callers again. + +--- + +## 5. Gating and permissions + +`voice.controller.ts:22` carries `@UseGuards(JwtAuthGuard, ClinicOrgGuard)`, so a LAB org +gets 403 on both voice routes today. That guard comes off the controller. + +Mode is **derived from the organisation, never sent by the client.** The selected org is +already in the JWT and is already the authority for every other service in this repo. + +``` +extract(user, dto, locale) + │ + ├─ getOrganizationTypeName(orgId) organization-type.ts:76 + │ + ├─ CLINIC → assert TAB_TREATMENT_EDIT (voice.service.ts:186, unchanged) + │ catalog: full + │ + └─ LAB → assert TAB_CASES_EDIT + catalog: narrowed +``` + +A `mode` field on the DTO was rejected: it can only ever hold one correct value per org, and +a body field deciding authorisation is a hole to guard rather than a fact to read. + +`assertCanEditTreatment` (`:186`) is renamed and generalised to take the permission code; +the clinic call site keeps `TAB_TREATMENT_EDIT`. + +`TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it for the +lab side would 403 every lab member including the owner. `TAB_CASES_EDIT` is the permission +that already gates Add Case. + +The denial code is **`PERMISSION_EDIT_CASES`**, added by this task. Cases was the one feature +with no edit-specific code, so `cases.service.ts` throws `PERMISSION_ACCESS_CASES` for both a +failed read check (`:1375`) and a failed edit check (`:1391`). Reusing it here would tell a lab +member who holds `TAB_CASES_READ` that they have no access to cases, which is false — they can +read every case, they just cannot edit one. All three layers of the error contract carry the new +code (§11 decision 15). + +**Availability** (`GET /voice/availability`) is one config for both sides. A separate lab +toggle is speculative — if voice is on, it is on. + +--- + +## 6. Review sheet: one component, one `mode` prop + +`voiceRowAvailability` takes a third argument. Three rows disappear on their own once the +catalog is empty; one has to be forced. + +| Row | CLINIC | LAB | +|---|---|---| +| Treatment type | when heard | never | +| Teeth (plain) | when not lab-dependent | never | +| Teeth and prosthesis | when lab-dependent | **always** | +| Note | when heard | when heard | +| Lab | when heard | never | +| Due date | when heard | when heard | + +The one that breaks without a change: `voiceRowAvailability` derives `labDependent` from the +treatment type. In lab mode the type is null, so `labDependent` would be **false** — showing +the plain teeth row and hiding the prosthesis row, exactly backwards. In lab mode it is +forced true. + +Everything else is identical, because a lab line and a prosthesis detail hold the same data: +the mini FDI chart, the target list, the stack preview through `applyLeafToJobs`, the struck +-through refused codes, the jobless targets, the candidate chips. + +That shared surface is the point. Five defects were fixed in this component over the last +week. A forked lab sheet would have needed all five fixed twice. + +--- + +## 7. Apply + +`buildLabLineFromVoice` in `frontend/src/components/lab/voiceLine.ts`, pure, its own spec. + +```ts +export function buildLabLineFromVoice( + result: VoiceExtractionResult, + selection: VoiceApplySelection, + ctx: { prosthesisCatalog: readonly ProsthesisCatalogEntry[] }, +): { line: LineDraft; dueDate: string | null }; +``` + +A sibling of `buildVoiceApplyPlan`, not a mode on it: the return shapes have nothing in +common, and a union return would recreate the thing that made the original callback hard to +test. Both call the same `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the stack +rules and the bridge splitting stay in one place. + +### Rules it keeps from the clinic side + +- **Decision 40 — a tooth is on the line only by carrying a job.** The plain `teeth` list is + never copied across. Nothing on the lab side enforces this (§2), which is exactly why the + apply must; otherwise the case chart and the generated tasks disagree and neither is wrong + enough to throw. +- **Decision 39 — teeth and prosthesis apply together**, as one row. +- A code the stack rules refuse is not applied, and the sheet already said so. +- Non-adjacent teeth never share a `selectionGroupId` (`splitDisconnectedRuns`). On this side + a shared group id tells the lab's own task generator to build a bridge, so the consequence + is more direct than on the clinic side. + +### Where the line goes + +Fill the active line when it is **blank** — no teeth, no jobs, no comment, no attachments, +the exact state `newLine()` produces (`:50`) — otherwise append and make the new line active. + +A fresh draft opens with one blank line (`linesFromDetail` returns `[newLine()]`), so +always-append would leave a blank line above the dictated one on every first use. Nothing +rejects it: `start` only requires that *some* line has jobs (`cases.service.ts:551`), so the +blank line would ship to the floor. + +### One dictation is one line + +Whatever the dictation held goes into one line, even when it names several different jobs. +A line's `id` becomes the `sourceKey` (`cases.service.ts:487`) that `generateLabCaseTasks` +groups by, so this is a real choice, not a display one — but "one utterance, one line" is the +rule a lab owner can predict without knowing how tasks are grouped. Two lines means dictating +twice. + +### The due date + +The row stays, and ticking it calls the panel's `setDueDate` — the same state the +`AppDateInput` writes (`:129`). This is the single field outside the line that the mic +touches. A date is a resolved value with no identity in it, the resolver already handles +Jalali and per-locale week starts, and a lab owner will say "تا پنجشنبه" whether or not the +design planned for it. The sheet shows it before it lands and it can be unticked. + +--- + +## 8. Data handling + +Nothing changes. The transcript never leaves the server and is logged there at info level +(`voice-treatment-entry` §10). `logTelemetry` stays patient-free. + +The lab side does not weaken that: no extracted field carries a name, because the header is +out of scope (§1) and the catalog is narrowed (§4). + +--- + +## 9. Known gaps + +Recorded so the first manual pass does not read them as bugs. + +1. **A dictated referring clinic is dropped, with no mention.** "از مطب دکتر احمدی" produces + nothing and the sheet says nothing about it. Matching it would mean handing the model the + linked organisations again — the list §4 deliberately empties — and the result is a name. + Revisit only if it proves annoying in use. +2. **Patient name and mobile are typed.** Same reason, more sharply: these are the fields the + transcript decision exists to protect. +3. **Attachments are not dictatable.** Nothing to extract. +4. **`VoiceThrottlerGuard` limits are tuned for a dentist**, who dictates a few times per + visit. A lab owner entering a morning's cases will dictate far more often. Watch it in the + manual pass; do not retune it blind. + +--- + +## 10. Verification + +### Automated + +- `cd backend && npm test -- narrowCatalogForOrgType` — **new**: + - LAB drops `treatmentTypes` and `labs`; + - LAB keeps the prosthesis tree, its categories and its subcategories intact; + - CLINIC is returned unchanged. +- `cd backend && npm test` — the existing 220 must stay green. The resolver is untouched. +- `cd backend && npm run build`. +- `cd frontend && npx vitest run` — **new** `voiceLine.spec.ts`: + - a tooth reaches `line.teeth` only by carrying a job; + - every `toothProsthesis` row naming a real tooth is in `line.teeth` (the invariant + nothing enforces server-side); + - a jaw sentinel is in `toothProsthesis` with an empty `selectionGroupId` and is not a + tooth on the line; + - two non-adjacent teeth never share a `selectionGroupId`; + - an unticked note row leaves `comment` empty; + - the due date comes back separately and is null when its row is unticked. + - Plus `voiceReviewRows.spec.ts`: lab mode forces the prosthesis row on and the type, plain + teeth and lab rows off. + - Each new test must be shown to fail with its rule reverted, not merely to pass. +- `cd frontend && npx tsc --noEmit` — the cross-cutting gate. +- `cd frontend && npm run build`. +- ESLint on every touched file, no new warnings. + +### Manual — `fa`, LAB org, a linked clinic present + +1. Cases → Add Case. The mic is enabled beside Add Line. +2. «برای دندون ۱۲ و ۱۳ روکش پی‌اف‌ام میخوام» → the sheet shows one row, both teeth, the + crown on each. No treatment-type row. No lab row. +3. Confirm → line 1 is filled, **not** line 2. Wait 1 s, reload the case: it persisted. +4. Dictate again, «۲۶ زیرکونیا» → line 2 appears and becomes active. +5. «یه کامپلیت دنچر برای فک بالا» → the jaw is selected, no tooth is invented, and the chart + shows the arch highlight. +6. «توی یادداشت‌ها بنویس رنگ A2» → the note row appears with `رنگ A2` and nothing else. +7. «تا پنجشنبه» → the due date row appears; ticking it fills the header field. +8. «از مطب دکتر احمدی، ۱۲ روکش» → the crown lands, the clinic field stays empty, nothing is + said about it (§9 item 1). +9. Start the case → tasks generate, and the task groups match the lines. +10. As a lab member **without** `TAB_CASES_EDIT`: the mic is disabled, and a forced request + returns 403. +11. As a clinic user: the treatment workspace mic still behaves exactly as before. +12. Safari and iPad, since that is where the original recording defects appeared. + +--- + +## 11. Decision log + +| # | Decision | Why | +|---|---|---| +| 1 | One dictation fills one line; the header is typed | Keeps names out of every extracted field, so `voice-treatment-entry` §10 does not reopen (§1) | +| 2 | Lab mode is an empty `treatmentTypes` + `labs` catalog | The prompt already renders both as empty; zero prompt text changes, and the model cannot emit a field it has no list for (§4) | +| 3 | Mode is derived from the org type, never sent | The JWT's org is already the authority; a body field deciding authorisation is a hole to guard (§5) | +| 4 | `ClinicOrgGuard` off the controller; `TAB_CASES_EDIT` for LAB | `TAB_TREATMENT_EDIT` is clinic-only, so reusing it would 403 every lab member (§5) | +| 5 | Reuse `VoiceReviewSheet` with a `mode` prop | Five fixes landed in it this week; a fork would need all five twice (§6) | +| 6 | Force `labDependent` true in lab mode | A null treatment type would otherwise show the plain teeth row and hide the prosthesis row (§6) | +| 7 | `buildLabLineFromVoice` is a sibling, not a mode | The return shapes share nothing; a union return recreates the untestable callback (§7) | +| 8 | Keep decision 40 even though nothing enforces it | The lab write validates only the prosthesis code, so a mismatch is written silently rather than rejected (§2, §7) | +| 9 | Fill a blank active line, otherwise append | A fresh draft already holds one blank line, and `start` would ship it (§7) | +| 10 | One dictation is one line | `sourceKey` groups tasks by line, so splitting is a real choice — but predictability wins (§7) | +| 11 | The due date row stays and writes the header | The one non-line field; a date carries no identity, and it will be dictated anyway (§7) | +| 12 | The referring clinic is dropped silently | Matching it needs the org list §4 empties, and the result is a name (§9) | +| 13 | `narrowCatalogForOrgType` is extracted and unit tested | `voice.service` has never been unit tested; this is the one decision in it worth pinning (§4, §10) | +| 14 | No new i18n keys | Every voice string is under `treatment.*`, and `CaseCreatePanel` already holds that namespace (§3) | +| 15 | `PERMISSION_EDIT_CASES` is added rather than reusing `PERMISSION_ACCESS_CASES` | The check is on an edit permission; "no access to cases" is false for a `TAB_CASES_READ` holder and points them at the wrong setting (§5) | diff --git a/frontend/messages/en.json b/frontend/messages/en.json index b144db1..a681a4b 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -1299,6 +1299,7 @@ "PERMISSION_ACCESS_TASKS": "You do not have access to tasks.", "PERMISSION_EDIT_TASKS": "You cannot edit tasks.", "PERMISSION_ACCESS_CASES": "You do not have access to cases.", + "PERMISSION_EDIT_CASES": "You cannot edit cases.", "PERMISSION_ACCESS_BILLING": "You do not have access to billing.", "PERMISSION_EDIT_BILLING": "You cannot edit billing for this organization.", "LAB_CASE_ACCESS_DENIED": "You do not have permission to view this shared case.", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 6771170..03dc2b1 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -1300,6 +1300,7 @@ "PERMISSION_ACCESS_TASKS": "به وظایف دسترسی ندارید.", "PERMISSION_EDIT_TASKS": "نمی‌توانید وظایف را ویرایش کنید.", "PERMISSION_ACCESS_CASES": "به پرونده‌ها دسترسی ندارید.", + "PERMISSION_EDIT_CASES": "نمی‌توانید پرونده‌ها را ویرایش کنید.", "PERMISSION_ACCESS_BILLING": "به صورتحساب دسترسی ندارید.", "PERMISSION_EDIT_BILLING": "نمی‌توانید صورتحساب این سازمان را ویرایش کنید.", "LAB_CASE_ACCESS_DENIED": "اجازه مشاهده این پرونده اشتراک‌گذاری‌شده را ندارید.", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index b180d9f..dea4a9c 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -1299,6 +1299,7 @@ "PERMISSION_ACCESS_TASKS": "U hebt geen toegang tot taken.", "PERMISSION_EDIT_TASKS": "U kunt taken niet bewerken.", "PERMISSION_ACCESS_CASES": "U hebt geen toegang tot dossiers.", + "PERMISSION_EDIT_CASES": "U kunt dossiers niet bewerken.", "PERMISSION_ACCESS_BILLING": "U hebt geen toegang tot facturatie.", "PERMISSION_EDIT_BILLING": "U kunt facturatie voor deze organisatie niet bewerken.", "LAB_CASE_ACCESS_DENIED": "U hebt geen toestemming om dit gedeelde dossier te bekijken.", diff --git a/frontend/src/components/lab/caseLineDraft.ts b/frontend/src/components/lab/caseLineDraft.ts new file mode 100644 index 0000000..8ae904a --- /dev/null +++ b/frontend/src/components/lab/caseLineDraft.ts @@ -0,0 +1,48 @@ +import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups'; +import type { LabCaseAttachmentMeta } from '@/types/cases'; +import type { FdiToothId } from '@/types/treatment'; + +/** + * One editable case line. Against a clinic `TreatmentDetailDraft` it carries no treatment type + * — the lab side is always `prosthesis`, written server-side — and folds the clinic's separate + * lab-case rows into `toothProsthesis` on the line itself. + */ +export type LineDraft = { + clientId: string; + id?: string; + teeth: FdiToothId[]; + toothSelectionGroups: ToothSelectionGroup[]; + comment: string; + toothProsthesis: Array<{ + tooth: string; + prosthesisTypeCode: string; + selectionGroupId?: string; + detailClientId: string; + }>; + attachments: LabCaseAttachmentMeta[]; +}; + +export function newLine(): LineDraft { + const clientId = + typeof crypto !== 'undefined' && 'randomUUID' in crypto + ? crypto.randomUUID() + : `line-${Date.now()}`; + return { + clientId, + teeth: [], + toothSelectionGroups: [], + comment: '', + toothProsthesis: [], + attachments: [], + }; +} + +/** Exactly the state `newLine` produces — what a dictation may overwrite instead of appending. */ +export function isBlankLine(line: LineDraft): boolean { + return ( + line.teeth.length === 0 && + line.toothProsthesis.length === 0 && + line.comment.trim() === '' && + line.attachments.length === 0 + ); +} diff --git a/frontend/src/components/lab/voiceLine.spec.ts b/frontend/src/components/lab/voiceLine.spec.ts new file mode 100644 index 0000000..e446ee0 --- /dev/null +++ b/frontend/src/components/lab/voiceLine.spec.ts @@ -0,0 +1,300 @@ +import { describe, expect, it } from 'vitest'; +import { ARCH_TOOTH_UPPER, isArchSentinel } from '@/components/treatment/prosthesisTree'; +import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; +import { isBlankLine, newLine } from './caseLineDraft'; +import { buildLabLineFromVoice } from './voiceLine'; + +const CATALOG: ProsthesisCatalogEntry[] = [ + { + code: 'pfm_crown', + sortOrder: 1, + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + { + code: 'cast_post_core', + sortOrder: 2, + label: 'Cast Post & Core', + category: 'post_core', + subcategory: '', + chartRegion: 'root', + stackGroup: 'post_core', + }, + { + code: 'complete_denture', + sortOrder: 3, + label: 'Complete Denture', + category: 'denture', + subcategory: '', + chartRegion: 'arch', + stackGroup: 'arch', + }, +]; + +const ctx = { prosthesisCatalog: CATALOG }; + +const result = (overrides: Partial = {}): VoiceExtractionResult => ({ + treatmentType: null, + teeth: [], + toothSelectionGroups: [], + comment: null, + prosthesisAssignments: [], + labId: null, + labMatchExact: false, + dueDate: null, + unresolved: [], + ...overrides, +}); + +const allTicked: VoiceApplySelection = { + treatmentType: true, + teeth: true, + comment: true, + prosthesis: true, + lab: true, + dueDate: true, +}; +const tick = (overrides: Partial = {}): VoiceApplySelection => ({ + ...allTicked, + ...overrides, +}); + +/** Narrows the nullable line and fails loudly when the dictation produced nothing. */ +function built(out: ReturnType) { + if (!out.line) throw new Error('expected a line, got null'); + return out.line; +} + +describe('buildLabLineFromVoice — which teeth reach the line', () => { + it('puts a tooth on the line only when it carries a job', () => { + const line = built(buildLabLineFromVoice( + result({ + teeth: ['12', '14', '16'], + prosthesisAssignments: [{ targets: ['12', '14'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + )); + expect(line.teeth).toEqual(['12', '14']); + }); + + it('never copies the plain teeth list across, so bare teeth build no line', () => { + const out = buildLabLineFromVoice(result({ teeth: ['21', '22'] }), tick(), ctx); + expect(out.line).toBeNull(); + }); + + it('leaves a target off the line when every code it named was refused', () => { + const out = buildLabLineFromVoice( + result({ + teeth: ['12'], + // Not in the catalog, so the stack rules refuse it and nothing lands. + prosthesisAssignments: [{ targets: ['12'], types: ['not_in_catalog'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(out.line).toBeNull(); + }); + + it('keeps the invariant nothing enforces server-side: every job names a tooth on the line', () => { + const line = built(buildLabLineFromVoice( + result({ + teeth: ['16'], + prosthesisAssignments: [ + { targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }, + { targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' }, + ], + }), + tick(), + ctx, + )); + const onTeeth = line.toothProsthesis + .filter((row) => !isArchSentinel(row.tooth)) + .map((row) => row.tooth); + expect(onTeeth.length).toBeGreaterThan(0); + for (const tooth of onTeeth) { + expect(line.teeth).toContain(tooth); + } + }); +}); + +describe('buildLabLineFromVoice — prosthesis rows', () => { + it('applies a stack in landing order and drops a code the stack rules refuse', () => { + const line = built(buildLabLineFromVoice( + result({ + prosthesisAssignments: [ + // A post & core cannot go under a crown that is already there. + { targets: ['12'], types: ['pfm_crown', 'cast_post_core'], spoken: '' }, + ], + }), + tick(), + ctx, + )); + expect(line.toothProsthesis.map((row) => row.prosthesisTypeCode)).toEqual(['pfm_crown']); + }); + + it('carries a jaw appliance with an empty selection group and adds no tooth', () => { + const line = built(buildLabLineFromVoice( + result({ + prosthesisAssignments: [ + { targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' }, + ], + }), + tick(), + ctx, + )); + expect(line.toothProsthesis).toEqual([ + { + detailClientId: line.clientId, + tooth: ARCH_TOOTH_UPPER, + prosthesisTypeCode: 'complete_denture', + selectionGroupId: '', + }, + ]); + expect(line.teeth).toEqual([]); + }); + + it('never gives two non-adjacent teeth the same selection group', () => { + const line = built(buildLabLineFromVoice( + result({ + // Dictated as one connected span, but 12 and 16 are not neighbours: a shared group id + // would tell the task generator to build a bridge across the gap. + toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '16'] }], + prosthesisAssignments: [{ targets: ['12', '16'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + )); + const groupOf = (tooth: string) => + line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; + expect(groupOf('12')).toBeTruthy(); + expect(groupOf('16')).toBeTruthy(); + expect(groupOf('12')).not.toBe(groupOf('16')); + }); + + it('keeps adjacent teeth dictated as a bridge in one selection group', () => { + const line = built(buildLabLineFromVoice( + result({ + toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '13'] }], + prosthesisAssignments: [{ targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + )); + const groupOf = (tooth: string) => + line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; + expect(groupOf('12')).toBe(groupOf('13')); + }); + + it('builds no line at all when the prosthesis row is unticked', () => { + const out = buildLabLineFromVoice( + result({ + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), + tick({ prosthesis: false }), + ctx, + ); + expect(out.line).toBeNull(); + }); +}); + +describe('buildLabLineFromVoice — the note and the due date', () => { + it('takes the note when its row is ticked', () => { + const line = built(buildLabLineFromVoice(result({ comment: 'shade A2' }), tick(), ctx)); + expect(line.comment).toBe('shade A2'); + }); + + it('builds no line when the note row is unticked and nothing else was dictated', () => { + const out = buildLabLineFromVoice( + result({ comment: 'shade A2' }), + tick({ comment: false }), + ctx, + ); + expect(out.line).toBeNull(); + }); + + it('returns a due-date-only dictation as a date and NO line', () => { + // The bug the correctness critic found: this used to return a blank line, which the + // panel appended and autosaved. `start` only requires that *some* line carries jobs, + // so the empty line shipped to the floor (decision 9). + const out = buildLabLineFromVoice(result({ dueDate: '2026-09-24' }), tick(), ctx); + expect(out.dueDate).toBe('2026-09-24'); + expect(out.line).toBeNull(); + }); + + it('still returns the line when a due date rides along with real work', () => { + const out = buildLabLineFromVoice( + result({ + dueDate: '2026-09-24', + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(out.dueDate).toBe('2026-09-24'); + expect(out.line?.teeth).toEqual(['12']); + }); + + it('returns a null due date when its row is unticked', () => { + const out = buildLabLineFromVoice( + result({ dueDate: '2026-09-24' }), + tick({ dueDate: false }), + ctx, + ); + expect(out.dueDate).toBeNull(); + }); + + it('writes no lab destination anywhere, even with a labId and its row ticked', () => { + const out = buildLabLineFromVoice( + result({ + labId: 'org-clinic-1', + labMatchExact: true, + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(JSON.stringify(out)).not.toContain('org-clinic-1'); + }); +}); + +describe('isBlankLine — whether a dictation fills the active line or appends', () => { + it('is true for the exact state newLine produces', () => { + expect(isBlankLine(newLine())).toBe(true); + }); + + it('is false once the line carries teeth, a job, a comment or an attachment', () => { + expect(isBlankLine({ ...newLine(), teeth: ['12'] })).toBe(false); + expect( + isBlankLine({ + ...newLine(), + toothProsthesis: [ + { tooth: '12', prosthesisTypeCode: 'pfm_crown', detailClientId: 'x' }, + ], + }), + ).toBe(false); + expect(isBlankLine({ ...newLine(), comment: 'shade A2' })).toBe(false); + expect( + isBlankLine({ + ...newLine(), + attachments: [ + { + id: 'a1', + fileName: 'x.png', + mimeType: 'image/png', + sizeBytes: 1, + createdAt: '2026-09-16', + } as never, + ], + }), + ).toBe(false); + }); + + it('is true for a line whose only content is whitespace', () => { + expect(isBlankLine({ ...newLine(), comment: ' ' })).toBe(true); + }); +}); diff --git a/frontend/src/components/lab/voiceLine.ts b/frontend/src/components/lab/voiceLine.ts new file mode 100644 index 0000000..71da2b0 --- /dev/null +++ b/frontend/src/components/lab/voiceLine.ts @@ -0,0 +1,74 @@ +import { groupsFromFlatTeeth } from '@/components/treatment/toothSelectionGroups'; +import { prosthesisTargetLines } from '@/components/treatment/voiceReviewRows'; +import type { FdiToothId } from '@/types/treatment'; +import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; +import { isBlankLine, newLine, type LineDraft } from './caseLineDraft'; + +export interface VoiceLineContext { + prosthesisCatalog: readonly ProsthesisCatalogEntry[]; +} + +/** + * Turns a confirmed review sheet into one case line, plus the case's due date. + * + * A sibling of `buildVoiceApplyPlan` rather than a mode on it — the return shapes share + * nothing — but both go through `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the + * stack rules and the bridge splitting stay in one place. + * + * The due date comes back separately because it belongs to the case header, not to the line. + * + * `line` is null when the dictation produced no line content. A due-date-only dictation, or one + * whose codes were all refused, must not append an empty line: `start` only requires that *some* + * line carries jobs, so an empty one ships to the floor (decision 9). + */ +export function buildLabLineFromVoice( + result: VoiceExtractionResult, + selection: VoiceApplySelection, + ctx: VoiceLineContext, +): { line: LineDraft | null; dueDate: string | null } { + const line = newLine(); + + if (selection.comment && result.comment) { + line.comment = result.comment; + } + + // The stack that will actually land, built through the same `applyLeafToJobs` the manual + // chart writes through — a code the stack rules refuse is not applied. + const targetLines = selection.prosthesis + ? prosthesisTargetLines(result.prosthesisAssignments, ctx.prosthesisCatalog) + : []; + + // A tooth is on the line only by carrying a job (decision 40). The plain `teeth` list is + // never copied across: the lab write validates only the prosthesis code, so a line whose + // teeth and jobs disagree would be saved silently and the generated tasks would not match + // the chart. + const teeth = targetLines + .filter((target) => !target.isJaw && target.applied.length > 0) + .map((target) => target.target as FdiToothId); + + line.teeth = teeth; + // Seeded from the dictated groups, so `splitDisconnectedRuns` runs: on this side a shared + // group id tells the task generator to build a bridge across the gap. + line.toothSelectionGroups = groupsFromFlatTeeth(teeth, result.toothSelectionGroups); + + line.toothProsthesis = targetLines.flatMap((target) => { + // A jaw appliance belongs to no selection group; a tooth takes the group it landed in. + const selectionGroupId = target.isJaw + ? '' + : (line.toothSelectionGroups.find((group) => + (group.teeth as readonly string[]).includes(target.target), + )?.groupId ?? ''); + return target.applied.map((prosthesisTypeCode) => ({ + detailClientId: line.clientId, + tooth: target.target, + prosthesisTypeCode, + selectionGroupId, + })); + }); + + return { + line: isBlankLine(line) ? null : line, + dueDate: selection.dueDate && result.dueDate ? result.dueDate : null, + }; +} diff --git a/frontend/src/components/treatment/voiceReviewRows.spec.ts b/frontend/src/components/treatment/voiceReviewRows.spec.ts index 7b997ca..05f8635 100644 --- a/frontend/src/components/treatment/voiceReviewRows.spec.ts +++ b/frontend/src/components/treatment/voiceReviewRows.spec.ts @@ -425,3 +425,59 @@ describe('hasAnythingToApply', () => { expect(hasAnythingToApply(baseResult({ teeth: ['14'] }), LAB_DEPENDENT)).toBe(true); }); }); + +describe('voiceRowAvailability in lab mode', () => { + // A lab line has no treatment type at all, so the derived labDependent flag would be false + // and the rows would come out exactly backwards. + const labResult = baseResult({ + treatmentType: null, + teeth: ['12'], + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }); + + it('shows the merged teeth-and-prosthesis row even with no treatment type', () => { + const available = voiceRowAvailability(labResult, LAB_DEPENDENT, 'lab'); + expect(available.prosthesis).toBe(true); + expect(available.teeth).toBe(false); + }); + + it('never shows the treatment type row, even when one was resolved', () => { + const forced = baseResult({ treatmentType: 'prosthesis' }); + expect(voiceRowAvailability(forced, LAB_DEPENDENT, 'lab').treatmentType).toBe(false); + expect(voiceRowAvailability(forced, LAB_DEPENDENT).treatmentType).toBe(true); + }); + + it('never shows the lab row, even when a labId came back', () => { + const withLab = baseResult({ labId: 'org-1' }); + expect(voiceRowAvailability(withLab, LAB_DEPENDENT, 'lab').lab).toBe(false); + expect(voiceRowAvailability(withLab, LAB_DEPENDENT).lab).toBe(true); + }); + + it('keeps the note and due date rows on the same when-heard rule', () => { + const heard = baseResult({ comment: 'shade A2', dueDate: '2026-09-24' }); + const available = voiceRowAvailability(heard, LAB_DEPENDENT, 'lab'); + expect(available.comment).toBe(true); + expect(available.dueDate).toBe(true); + const silent = voiceRowAvailability(baseResult(), LAB_DEPENDENT, 'lab'); + expect(silent.comment).toBe(false); + expect(silent.dueDate).toBe(false); + }); + + it('ticks the prosthesis row and nothing clinic-only by default', () => { + const selection = initialVoiceSelection(labResult, LAB_DEPENDENT, 'lab'); + expect(selection.prosthesis).toBe(true); + expect(selection.treatmentType).toBe(false); + expect(selection.teeth).toBe(false); + expect(selection.lab).toBe(false); + }); + + it('still reports a recording that produced nothing usable', () => { + expect(hasAnythingToApply(baseResult(), LAB_DEPENDENT, 'lab')).toBe(false); + }); + + it('defaults to clinic mode when no mode is given', () => { + expect(voiceRowAvailability(labResult, LAB_DEPENDENT)).toEqual( + voiceRowAvailability(labResult, LAB_DEPENDENT, 'clinic'), + ); + }); +}); diff --git a/frontend/src/components/treatment/voiceReviewRows.ts b/frontend/src/components/treatment/voiceReviewRows.ts index b40ae56..3119dbc 100644 --- a/frontend/src/components/treatment/voiceReviewRows.ts +++ b/frontend/src/components/treatment/voiceReviewRows.ts @@ -25,6 +25,7 @@ import type { FdiToothId } from '@/types/treatment'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { VoiceApplySelection, + VoiceEntryMode, VoiceExtractionResult, VoiceProsthesisAssignment, VoiceUnresolvedItem, @@ -52,14 +53,19 @@ function hasProsthesisWork(result: VoiceExtractionResult): boolean { export function voiceRowAvailability( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ) { - const labDependent = isLabDependentResult(result, labDependentCodes); + const isLab = mode === 'lab'; + // A lab line is always prosthesis work, and the catalog it was extracted against carries no + // treatment types at all — so the derived flag would be false and the rows exactly backwards: + // the plain teeth row shown, the merged prosthesis row hidden (decision 6). + const labDependent = isLab || isLabDependentResult(result, labDependentCodes); return { - treatmentType: result.treatmentType != null, + treatmentType: !isLab && result.treatmentType != null, teeth: !labDependent && result.teeth.length > 0, prosthesis: labDependent && (result.teeth.length > 0 || hasProsthesisWork(result)), comment: Boolean(result.comment?.trim()), - lab: result.labId != null, + lab: !isLab && result.labId != null, dueDate: result.dueDate != null, }; } @@ -72,8 +78,9 @@ export function voiceRowAvailability( export function initialVoiceSelection( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ): VoiceApplySelection { - const available = voiceRowAvailability(result, labDependentCodes); + const available = voiceRowAvailability(result, labDependentCodes, mode); return { treatmentType: available.treatmentType, teeth: available.teeth, @@ -399,8 +406,9 @@ export function unresolvedForAssignment( export function hasAnythingToApply( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ): boolean { - return Object.values(voiceRowAvailability(result, labDependentCodes)).some(Boolean); + return Object.values(voiceRowAvailability(result, labDependentCodes, mode)).some(Boolean); } export { archSentinels, allAssignmentTargets }; diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 8fecaf4..a5d93cd 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -1,8 +1,8 @@ 'use client'; import { useCallback, useEffect, useRef, useState } from 'react'; -import { useTranslations } from 'next-intl'; -import { Trash2 } from 'lucide-react'; +import { useLocale, useTranslations } from 'next-intl'; +import { Mic, Square, Trash2 } from 'lucide-react'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles'; import { @@ -20,52 +20,33 @@ import { pruneToothProsthesisForGroups, toothEdgeKey, unlinkAdjacentTeeth, - type ToothSelectionGroup, } from '@/components/treatment/toothSelectionGroups'; import { AppDateInput } from '@/components/ui/shared/AppDateInput'; import { Button } from '@/components/ui/shared/Button'; import { ProsthesisAssignChart } from '@/components/ui/treatment/ProsthesisAssignChart'; +import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar'; +import { VoiceReviewSheet } from '@/components/ui/treatment/VoiceReviewSheet'; +import { isBlankLine, newLine, type LineDraft } from '@/components/lab/caseLineDraft'; import { toDateInputValue } from '@/components/lab/labCaseDueDateDisplay'; +import { buildLabLineFromVoice } from '@/components/lab/voiceLine'; import { casesApi } from '@/lib/api/cases'; import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog'; -import type { LabCaseAttachmentMeta, LabCaseDetail } from '@/types/cases'; +import { voiceApi } from '@/lib/api/voice'; +import { isMediaRecorderSupported } from '@/lib/voice/audioFormat'; +import { useVoiceCapture, type VoiceCaptureState } from '@/lib/voice/useVoiceCapture'; +import type { LabCaseDetail } from '@/types/cases'; import type { FdiToothId } from '@/types/treatment'; import type { LinkedOrganizationOption } from '@/types/treatment'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { + VoiceApplySelection, + VoiceAvailability, + VoiceExtractionResult, +} from '@/types/voice'; const INPUT_CLASS = 'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35'; -type LineDraft = { - clientId: string; - id?: string; - teeth: FdiToothId[]; - toothSelectionGroups: ToothSelectionGroup[]; - comment: string; - toothProsthesis: Array<{ - tooth: string; - prosthesisTypeCode: string; - selectionGroupId?: string; - detailClientId: string; - }>; - attachments: LabCaseAttachmentMeta[]; -}; - -function newLine(): LineDraft { - const clientId = - typeof crypto !== 'undefined' && 'randomUUID' in crypto - ? crypto.randomUUID() - : `line-${Date.now()}`; - return { - clientId, - teeth: [], - toothSelectionGroups: [], - comment: '', - toothProsthesis: [], - attachments: [], - }; -} - function linesFromDetail(labCase: LabCaseDetail): LineDraft[] { const source = labCase.lines ?? []; if (source.length === 0) return [newLine()]; @@ -116,6 +97,7 @@ export function CaseCreatePanel({ const tTreatment = useTranslations('treatment'); const tErrors = useTranslations('errors'); const tCommon = useTranslations('common'); + const locale = useLocale(); const [referringClinicName, setReferringClinicName] = useState( labCase.referringClinicName ?? '', @@ -139,6 +121,8 @@ export function CaseCreatePanel({ const [prosthesisOptions, setProsthesisOptions] = useState( prosthesisCatalog ?? [], ); + const [voiceAvailability, setVoiceAvailability] = useState(null); + const [voiceResult, setVoiceResult] = useState(null); const [saving, setSaving] = useState(false); const [starting, setStarting] = useState(false); const [deleting, setDeleting] = useState(false); @@ -170,6 +154,7 @@ export function CaseCreatePanel({ useEffect(() => { void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined); + void voiceApi.availability().then((r) => setVoiceAvailability(r.data)).catch(() => undefined); }, []); useEffect(() => { @@ -180,6 +165,24 @@ export function CaseCreatePanel({ void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined); }, [prosthesisCatalog]); + const voice = useVoiceCapture({ + // The locale the lab owner is reading and speaking in, so the ASR hint, the catalog labels + // and the week start all match what the microphone was offered for. + locale, + maxMs: voiceAvailability?.maxRecordingMs ?? null, + onExtracted: setVoiceResult, + onError: (error) => + onError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))), + }); + + // Absence renders the Add Line button unsplit. Gated on the browser's own recording support + // as well as the server config: without it the control appears on a browser that cannot + // record and fails on tap. + const voiceEnabled = + Boolean(voiceAvailability?.enabled) && + (voiceAvailability?.locales.includes(locale) ?? false) && + isMediaRecorderSupported(); + const activeLine = lines.find((l) => l.clientId === activeLineId) ?? lines[0]; const groups = activeLine?.toothSelectionGroups.length @@ -293,12 +296,60 @@ export function CaseCreatePanel({ return () => clearTimeout(timeout); }, [buildPayload, canEdit]); + function addLine() { + const line = newLine(); + setLines((prev) => [...prev, line]); + setActiveLineId(line.clientId); + } + function updateActiveLine(patch: (line: LineDraft) => LineDraft) { setLines((prev) => prev.map((line) => (line.clientId === activeLine?.clientId ? patch(line) : line)), ); } + /** + * One dictation is one line. It fills the active line while that line is still blank — a + * fresh draft opens with one, and always appending would leave it above the dictated line + * and ship it to the floor, since `start` only requires that *some* line carries jobs. + */ + function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) { + const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, { + prosthesisCatalog: prosthesisOptions, + }); + setVoiceResult(null); + if (dictatedDueDate) setDueDate(dictatedDueDate); + // Null when the dictation carried no line content — a due date on its own still lands. + // Without the notice, Apply on a row that lands no job closes the sheet and changes nothing. + if (!line) { + if (!dictatedDueDate) onError(tTreatment('voiceNothingExtracted')); + return; + } + + const target = activeLine; + if (target && isBlankLine(target)) { + setLines((prev) => + prev.map((l) => + l.clientId === target.clientId + ? { + ...line, + // Keep the line's identity: it may already have been saved once. + clientId: target.clientId, + id: target.id, + toothProsthesis: line.toothProsthesis.map((tp) => ({ + ...tp, + detailClientId: target.clientId, + })), + } + : l, + ), + ); + return; + } + setLines((prev) => [...prev, line]); + setActiveLineId(line.clientId); + } + async function handleDelete() { if (!canEdit) return; if (!window.confirm(t('confirmDeleteDraftCase'))) return; @@ -463,20 +514,25 @@ export function CaseCreatePanel({ -
-

{t('caseLinesTitle')}

- +
+
+

{t('caseLinesTitle')}

+ {voiceEnabled ? ( + + ) : ( + + )} +
+ {voiceEnabled ? : null}
@@ -623,6 +679,74 @@ export function CaseCreatePanel({
) : null} + + {voiceResult ? ( + applyVoice(selection, applied)} + onDiscard={() => setVoiceResult(null)} + /> + ) : null} +
+ ); +} + +/** + * "Add line", split into two segments with the microphone at the logical end — built like the + * clinic's `AddDetailWithVoice`, out of two raw buttons rather than two shared `Button`s, which + * hardcode their own rounding and would fight a segmented control. + */ +function AddLineWithVoice({ + addLabel, + startLabel, + stopLabel, + disabled, + onAddLine, + voice, +}: { + addLabel: string; + startLabel: string; + stopLabel: string; + disabled: boolean; + onAddLine: () => void; + voice: VoiceCaptureState; +}) { + const isRecording = voice.phase === 'recording'; + const isBusy = voice.phase !== 'idle'; + const micLabel = isRecording ? stopLabel : startLabel; + + return ( +
+ +
); } diff --git a/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx b/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx index 0b369df..f823a87 100644 --- a/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx +++ b/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx @@ -34,17 +34,21 @@ import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { FdiToothId, LinkedOrganizationOption } from '@/types/treatment'; import type { VoiceApplySelection, + VoiceEntryMode, VoiceExtractionResult, VoiceUnresolvedItem, } from '@/types/voice'; interface VoiceReviewSheetProps { result: VoiceExtractionResult; - treatmentCatalog: TreatmentCatalogEntry[]; + /** `lab` hides the treatment type, plain teeth and lab rows — see `voiceRowAvailability`. */ + mode?: VoiceEntryMode; + /** Unused in lab mode: the type row never renders, so no catalog is needed to label it. */ + treatmentCatalog?: TreatmentCatalogEntry[]; prosthesisCatalog: ProsthesisCatalogEntry[]; /** `prosthesis` today, but kept generic — the same set the workspace already tracks. */ - labDependentCodes: ReadonlySet; - labs: LinkedOrganizationOption[]; + labDependentCodes?: ReadonlySet; + labs?: LinkedOrganizationOption[]; /** The result is handed back because the sheet may have added teeth or jobs the model missed. */ onApply: (selection: VoiceApplySelection, result: VoiceExtractionResult) => void; onDiscard: () => void; @@ -52,6 +56,9 @@ interface VoiceReviewSheetProps { type ArchPick = 'upper' | 'lower'; +/** Module-level so the default prop is referentially stable across renders. */ +const NO_LAB_DEPENDENT_CODES: ReadonlySet = new Set(); + /** * Confirmation step between the model's output and the form. * @@ -60,10 +67,11 @@ type ArchPick = 'upper' | 'lower'; */ export function VoiceReviewSheet({ result, - treatmentCatalog, + mode = 'clinic', + treatmentCatalog = [], prosthesisCatalog, - labDependentCodes, - labs, + labDependentCodes = NO_LAB_DEPENDENT_CODES, + labs = [], onApply, onDiscard, }: VoiceReviewSheetProps) { @@ -71,7 +79,7 @@ export function VoiceReviewSheet({ const tProsthesis = useTranslations('prosthesis'); const { formatDate } = useAppFormatters(); const [selection, setSelection] = useState(() => - initialVoiceSelection(result, labDependentCodes), + initialVoiceSelection(result, labDependentCodes, mode), ); // Every kind of candidate chip the sheet can offer, tracked separately because each folds @@ -101,8 +109,8 @@ export function VoiceReviewSheet({ }, [result, chosenTeeth, chosenAssignmentTeeth, chosenArches, chosenLeaves]); const available = useMemo( - () => voiceRowAvailability(effective, labDependentCodes), - [effective, labDependentCodes], + () => voiceRowAvailability(effective, labDependentCodes, mode), + [effective, labDependentCodes, mode], ); const connectedTeeth = useMemo(() => connectedTeethFromResult(effective), [effective]); const selectedTeeth = useMemo(() => new Set(effective.teeth), [effective.teeth]); @@ -142,7 +150,7 @@ export function VoiceReviewSheet({ ? { ...selection, treatmentType: true } : selection; - const nothingToApply = !hasAnythingToApply(effective, labDependentCodes); + const nothingToApply = !hasAnythingToApply(effective, labDependentCodes, mode); const selectedCount = countSelected(effectiveSelection, available); const targetLabel = (target: string): string => { diff --git a/frontend/src/types/voice.ts b/frontend/src/types/voice.ts index 8aa6ae6..be01cc8 100644 --- a/frontend/src/types/voice.ts +++ b/frontend/src/types/voice.ts @@ -80,3 +80,9 @@ export interface VoiceApplySelection { } export type VoicePhase = 'idle' | 'recording' | 'processing'; + +/** + * Which side dictated. Derived from the organisation on the server; on the client it only + * picks which review rows exist, since a lab line has no treatment type and no destination. + */ +export type VoiceEntryMode = 'clinic' | 'lab';