Files
dyolink/docs/specs/voice-lab-case-entry.md
Amin Mousavi af45868236 docs(voice): flatten voice-treatment-entry spec and record decision 55
Restructure docs/specs to match voice-lab-case-entry.md: spec.md moves to
voice-treatment-entry.md (git mv), progress.md is removed. Status header,
repos block, decision 16 in the lab spec, and the $1 comment row now
record the leftover-speech revision on feat/voice/leftover-comment.
2026-11-10 21:19:28 +03:30

19 KiB

type, status, created, repos, aliases
type status created repos aliases
task active 2026-09-16
repo path branch base role spec_slug merge_after
dyolink ~/PersonalProjects/dyolink feat/cases/add-voice-input-for-lab-case-line origin/master lab-mode extraction catalog + lab line apply + shared review sheet voice-lab-case-entry
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 · Revised: 2026-11-10 (decision 16 — the note rule changed underneath this spec) Depends on: voice-treatment-entry, 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:

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:

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.

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). One exception, added 2026-11-10: since the note became leftover speech (decision 55 in voice-treatment-entry), a dictated phrase that mentions a person can reach line.comment. The review sheet shows the note before apply, so the clinician can untick it.


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)
16 The line comment inherits the leftover-speech note rule (voice-treatment-entry decision 55) The prompt and resolver are shared, so line.comment now holds meaningful phrases that fit no field; a dictated phrase naming a person can reach it, and the sheet previews the note before apply (§8)