Merge pull request 'feature: teeth color shades added. UI and UX updated in all flows accordingly. voice feature updated. pdf layouts matched and etc' (#132) from feature/teeth-color-shades into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 37m43s
Registry — build, push, deploy / deploy (push) Successful in 2m13s

Reviewed-on: #132
Reviewed-by: Babak <babak.safarnezhad@gmail.com>
This commit was merged in pull request #132.
This commit is contained in:
2026-11-21 17:34:40 +03:30
59 changed files with 979 additions and 36 deletions

View File

@@ -0,0 +1,18 @@
---
description: Case-level tooth shade (VITA codes) — storage, edit gates, surfaces, voice
globs: backend/src/modules/tooth-shade-catalog/**,backend/src/modules/cases/cases.service.ts,backend/src/modules/treatments/treatments.service.ts,backend/src/modules/voice/**,frontend/src/components/ui/shared/ToothShadeGuide.tsx,frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx,frontend/src/components/ui/treatment/TreatmentWorkspace.tsx,frontend/src/components/ui/lab/Case*.tsx,frontend/src/components/treatment/voice*.ts,frontend/src/components/lab/voiceLine.ts
alwaysApply: false
---
# Tooth shade
- **One optional shade per lab case**, not per tooth: `LabCase.toothShadeCode` → `ToothShade.code` (nullable FK). Codes: `0M1–0M3, A1–A4 (+A3.5), B1–B4, C1–C4, D2–D4`. Lab-dependent work only.
- **Null is normal.** Historical shades stay in comments/notes; never backfill. Every surface must tolerate `null`.
- **Validate** with `ToothShadeCatalogService.normalize` (canonicalizes `a 3,5` → `A3.5`, `OM1` → `0M1`; unknown → `TOOTH_SHADE_INVALID`). Inactive codes stay valid on existing cases; the picker lists active ones.
- **Edit gates** (`TOOTH_SHADE_LOCKED` on a real change only — autosave resends unchanged values, which must stay a no-op):
- Clinic (Treatment provider): unsent, or sent until any step in the outsource tree is completed.
- Lab: `LAB_INTERNAL` drafts via draft autosave; started via `PATCH /cases/:id/tooth-shade` until a current-round step in the tree is completed. Needs `TAB_CASES_EDIT`.
- Received `CLINIC_DISPATCH` and `LAB_OUTSOURCE` cases are read-only for the lab. Outsource copies the parent shade, and later parent edits update the children.
- **Full guide** (`ToothShadeGuide`, LTR tab order in every locale): Treatment editor under the type row for lab-dependent details, Cases create panel, and the case detail header (hidden there when read-only and empty). **Text only** elsewhere: Tasks grouped header (also the share page), Case Sheet PDF (`—` when empty).
- **Voice:** `toothShadeCode` field — never in `comment`. Lands only on a lab-dependent detail (or a lab case line).
- Exocad export does not map shade yet.

View File

@@ -76,6 +76,8 @@ frontend/src/
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps, plus model design and model create, to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper program or download) writes the open case into a DentalDB SQLite file on that computer. The browser remembers the file only after the DentalDB check and reopens it while it still exists; an invalid file is not remembered, so Browse stays available. Monolithic zirconia and PFZ are Coping, a pontic is a reduced pontic, and the opposite tooth is an antagonist, only when that pair already exists in the file. A titanium custom abutment on that Coping copies ImplantType CustomAbutment from a saved tooth of the same pair when the file already has it. The connect dialog says the feature is experimental, asks for a manual backup, says Nudentic is not responsible, and says the user uses it on their own. A one-word clinic name still fills Client, and an empty clinic name still writes the case. A patient name that cannot fill Name is not written, and the toast says so. Each new case gets the next tray for that client. After the write, the user can grant the CAD-Data folder so the empty project directory is created. A failed case rolls back. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Tooth shade (quick ref):** One optional VITA shade per lab case (`LabCase.toothShadeCode`, nullable; historical shades stay in notes). Full guide in Treatment (lab-dependent) and Cases create/detail; text only on Tasks, share page, and Case Sheet. Locks once any step in the outsource tree is completed; an unchanged resend is a no-op. See `.cursor/rules/tooth-shade.mdc`.
**Lab case share link (quick ref):**
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL.
- **Lab:** view with Cases or Tasks access; edit task status only with Tasks edit + assignee rules; comments if Cases or Tasks edit.

View File

@@ -17,6 +17,41 @@ export type TreatmentTypeSeed = {
availableInTreatment?: boolean;
};
export type ToothShadeSeed = {
code: string;
family: '0M' | 'A' | 'B' | 'C' | 'D';
sortOrder: number;
hex: string;
};
/**
* VITA Classical A1–D4 + Bleached 0M1–0M3 (exact codes).
* No universal official hex/RGB exists for these shades (VITA does not publish one;
* spectrophotometric Lab→sRGB conversions look muddy on screen). Swatches are
* approximate warm enamel tones for UI only — not clinical color matching.
*/
export const TOOTH_SHADES: readonly ToothShadeSeed[] = [
{ code: '0M1', family: '0M', sortOrder: 1, hex: '#F7F4EF' },
{ code: '0M2', family: '0M', sortOrder: 2, hex: '#F4EFE6' },
{ code: '0M3', family: '0M', sortOrder: 3, hex: '#F0E9DA' },
{ code: 'A1', family: 'A', sortOrder: 4, hex: '#F1E6D3' },
{ code: 'A2', family: 'A', sortOrder: 5, hex: '#E8D5B7' },
{ code: 'A3', family: 'A', sortOrder: 6, hex: '#DCC19A' },
{ code: 'A3.5', family: 'A', sortOrder: 7, hex: '#D0B08A' },
{ code: 'A4', family: 'A', sortOrder: 8, hex: '#C49A72' },
{ code: 'B1', family: 'B', sortOrder: 9, hex: '#F0E8D4' },
{ code: 'B2', family: 'B', sortOrder: 10, hex: '#E5D6B5' },
{ code: 'B3', family: 'B', sortOrder: 11, hex: '#D9C49A' },
{ code: 'B4', family: 'B', sortOrder: 12, hex: '#CDB07E' },
{ code: 'C1', family: 'C', sortOrder: 13, hex: '#E4DDD0' },
{ code: 'C2', family: 'C', sortOrder: 14, hex: '#D5CBBC' },
{ code: 'C3', family: 'C', sortOrder: 15, hex: '#C4B8A6' },
{ code: 'C4', family: 'C', sortOrder: 16, hex: '#B0A28F' },
{ code: 'D2', family: 'D', sortOrder: 17, hex: '#E2D6C4' },
{ code: 'D3', family: 'D', sortOrder: 18, hex: '#D4C4AD' },
{ code: 'D4', family: 'D', sortOrder: 19, hex: '#C5B094' },
] as const;
export const TREATMENT_TYPES: readonly TreatmentTypeSeed[] = [
{ code: 'restoration', labDependent: false, sortOrder: 1 },
{ code: 'specialized_restoration', labDependent: false, sortOrder: 2 },

View File

@@ -0,0 +1,38 @@
-- Tooth shade catalog + optional case-level shade on lab_cases
CREATE TABLE "tooth_shades" (
"code" TEXT NOT NULL,
"family" TEXT NOT NULL,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"hex" TEXT NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT true,
CONSTRAINT "tooth_shades_pkey" PRIMARY KEY ("code")
);
INSERT INTO "tooth_shades" ("code", "family", "sortOrder", "hex", "isActive") VALUES
('0M1', '0M', 1, '#F7F4EF', true),
('0M2', '0M', 2, '#F4EFE6', true),
('0M3', '0M', 3, '#F0E9DA', true),
('A1', 'A', 4, '#F1E6D3', true),
('A2', 'A', 5, '#E8D5B7', true),
('A3', 'A', 6, '#DCC19A', true),
('A3.5', 'A', 7, '#D0B08A', true),
('A4', 'A', 8, '#C49A72', true),
('B1', 'B', 9, '#F0E8D4', true),
('B2', 'B', 10, '#E5D6B5', true),
('B3', 'B', 11, '#D9C49A', true),
('B4', 'B', 12, '#CDB07E', true),
('C1', 'C', 13, '#E4DDD0', true),
('C2', 'C', 14, '#D5CBBC', true),
('C3', 'C', 15, '#C4B8A6', true),
('C4', 'C', 16, '#B0A28F', true),
('D2', 'D', 17, '#E2D6C4', true),
('D3', 'D', 18, '#D4C4AD', true),
('D4', 'D', 19, '#C5B094', true);
ALTER TABLE "lab_cases" ADD COLUMN "toothShadeCode" TEXT;
ALTER TABLE "lab_cases" ADD CONSTRAINT "lab_cases_toothShadeCode_fkey" FOREIGN KEY ("toothShadeCode") REFERENCES "tooth_shades"("code") ON DELETE SET NULL ON UPDATE CASCADE;
CREATE INDEX "lab_cases_toothShadeCode_idx" ON "lab_cases"("toothShadeCode");

View File

@@ -301,6 +301,8 @@ model LabCase {
origin LabCaseOrigin @default(CLINIC_DISPATCH)
/// Optional code from an external lab app (e.g. exocad) for print/matching.
externalCode String?
/// Optional VITA-style tooth shade code (ToothShade.code). Case-level, not per tooth.
toothShadeCode String?
accessToken String? @unique
referringClinicName String?
referringDentistName String?
@@ -309,6 +311,7 @@ model LabCase {
partnerClinicOrganizationId String?
treatment Treatment? @relation(fields: [treatmentId], references: [id], onDelete: Cascade)
toothShade ToothShade? @relation(fields: [toothShadeCode], references: [code], onDelete: SetNull)
partnerClinic Organization? @relation("LabCasePartnerClinic", fields: [partnerClinicOrganizationId], references: [id], onDelete: SetNull)
parentLabCase LabCase? @relation("LabCaseOutsourceParent", fields: [parentLabCaseId], references: [id], onDelete: SetNull)
childLabCases LabCase[] @relation("LabCaseOutsourceParent")
@@ -334,6 +337,7 @@ model LabCase {
@@index([partnerClinicOrganizationId])
@@index([parentLabCaseId])
@@index([listedAt])
@@index([toothShadeCode])
@@map("lab_cases")
}
@@ -412,6 +416,21 @@ model TreatmentType {
@@map("treatment_types")
}
/// Static VITA Classical + bleach shade guide. Labels are the codes themselves.
model ToothShade {
code String @id
/// Guide family: 0M | A | B | C | D
family String
sortOrder Int @default(0)
/// Approximate tab fill for the shade guide UI.
hex String
isActive Boolean @default(true)
labCases LabCase[]
@@map("tooth_shades")
}
enum CatalogEntityKind {
TREATMENT_TYPE
PROSTHESIS_TYPE

View File

@@ -8,6 +8,7 @@ import {
LEGACY_TREATMENT_TYPES,
LAB_WORKFLOW_STEPS,
PROSTHESIS_TYPES,
TOOTH_SHADES,
CATALOG_TRANSLATIONS,
buildProsthesisStepCodes,
} from './catalog-seed-data';
@@ -159,6 +160,26 @@ async function main() {
}
console.log('✅ Seeded treatment type catalog');
for (const shade of TOOTH_SHADES) {
await prisma.toothShade.upsert({
where: { code: shade.code },
update: {
family: shade.family,
sortOrder: shade.sortOrder,
hex: shade.hex,
isActive: true,
},
create: {
code: shade.code,
family: shade.family,
sortOrder: shade.sortOrder,
hex: shade.hex,
isActive: true,
},
});
}
console.log('✅ Seeded tooth shade catalog');
for (const step of LAB_WORKFLOW_STEPS) {
await prisma.labWorkflowStep.upsert({
where: { code: step.code },

View File

@@ -232,6 +232,12 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
navigation: { name: 'Catalog', icon: 'Catalog' },
actions: catalogActions,
}),
resource(prisma, 'ToothShade', {
navigation: { name: 'Catalog', icon: 'Catalog' },
// Codes are stored on lab cases; edit hex/order/active only.
properties: { code: { isDisabled: true } },
actions: catalogActions,
}),
resource(prisma, 'BillingSheet', {
navigation: { name: 'Billing', icon: 'CreditCard' },

View File

@@ -19,6 +19,7 @@ import { TasksModule } from './modules/tasks/tasks.module';
import { TreatmentCatalogModule } from './modules/treatment-catalog/treatment-catalog.module';
import { CatalogModule } from './modules/catalog/catalog.module';
import { ProsthesisCatalogModule } from './modules/prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from './modules/tooth-shade-catalog/tooth-shade-catalog.module';
import { LabCaseCommentsModule } from './modules/lab-case-comments/lab-case-comments.module';
import { TodayModule } from './modules/today/today.module';
import { NotificationsModule } from './modules/notifications/notifications.module';
@@ -55,6 +56,7 @@ import { SubscriptionWriteInterceptor } from './modules/subscription/subscriptio
CatalogModule,
TreatmentCatalogModule,
ProsthesisCatalogModule,
ToothShadeCatalogModule,
AuthModule,
PatientsModule,
AppointmentsModule,

View File

@@ -159,6 +159,8 @@ export const ErrorCode = {
TREATMENT_CASE_ALREADY_SENT: 'TREATMENT_CASE_ALREADY_SENT',
TREATMENT_DUE_DATE_LOCKED: 'TREATMENT_DUE_DATE_LOCKED',
TREATMENT_INVALID_DUE_DATE: 'TREATMENT_INVALID_DUE_DATE',
TOOTH_SHADE_INVALID: 'TOOTH_SHADE_INVALID',
TOOTH_SHADE_LOCKED: 'TOOTH_SHADE_LOCKED',
TREATMENT_DETAIL_KEY_REQUIRED: 'TREATMENT_DETAIL_KEY_REQUIRED',
TREATMENT_FILE_REQUIRED: 'TREATMENT_FILE_REQUIRED',
TREATMENT_ATTACHMENT_NOT_FOUND: 'TREATMENT_ATTACHMENT_NOT_FOUND',

View File

@@ -25,6 +25,7 @@ import {
ListLabCasesDto,
UpdateLabCaseImportantDto,
UpdateLabCaseExternalCodeDto,
UpdateLabCaseToothShadeDto,
AssignLabCaseTaskDto,
CreateLabInternalCaseDto,
UpdateLabInternalCaseDto,
@@ -252,6 +253,17 @@ export class CasesController {
return this.casesService.setCaseExternalCode(id, dto, organizationId, req.user.id, req.user.language);
}
@Patch(':id/tooth-shade')
@ApiOperation({ summary: 'Set or clear the optional tooth shade for a lab-origin case' })
setCaseToothShade(
@Param('id') id: string,
@Body() dto: UpdateLabCaseToothShadeDto,
@Req() req,
) {
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
return this.casesService.setCaseToothShade(id, dto, organizationId, req.user.id, req.user.language);
}
@Patch(':caseId/tasks/:taskId/assign')
@ApiOperation({ summary: 'Assign or unassign a task to lab staff' })
assignTask(

View File

@@ -3,6 +3,7 @@ import { PrismaService } from '../../../prisma/prisma.service';
import { LabOrgGuard } from '../../common/guards/lab-org.guard';
import { NotificationsModule } from '../notifications/notifications.module';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { TasksModule } from '../tasks/tasks.module';
import { CatalogModule } from '../catalog/catalog.module';
import { LabCaseCommentsModule } from '../lab-case-comments/lab-case-comments.module';
@@ -14,7 +15,16 @@ import { LabCaseAccessController } from './lab-case-access.controller';
import { LabCaseAccessService } from './lab-case-access.service';
@Module({
imports: [ProsthesisCatalogModule, NotificationsModule, TasksModule, CatalogModule, LabCaseCommentsModule, BillingModule, SubscriptionModule],
imports: [
ProsthesisCatalogModule,
ToothShadeCatalogModule,
NotificationsModule,
TasksModule,
CatalogModule,
LabCaseCommentsModule,
BillingModule,
SubscriptionModule,
],
controllers: [LabCaseAccessController, CasesController],
providers: [CasesService, LabCaseAccessService, PrismaService, LabOrgGuard],
exports: [CasesService, LabCaseAccessService],

View File

@@ -19,8 +19,18 @@ import {
normalizeCatalogLocale,
} from '../catalog/catalog-label.service';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { normalizeTeeth } from '../treatments/treatment.utils';
import { ListLabCasesDto, UpdateLabCaseImportantDto, UpdateLabCaseExternalCodeDto, AssignLabCaseTaskDto, CreateLabInternalCaseDto, UpdateLabInternalCaseDto, OutsourceLabCaseDto } from './dto/cases.dto';
import {
ListLabCasesDto,
UpdateLabCaseImportantDto,
UpdateLabCaseExternalCodeDto,
UpdateLabCaseToothShadeDto,
AssignLabCaseTaskDto,
CreateLabInternalCaseDto,
UpdateLabInternalCaseDto,
OutsourceLabCaseDto,
} from './dto/cases.dto';
import { generateLabCaseTasks } from './lab-case-task.generator';
import {
isLabCaseOverdue,
@@ -65,6 +75,7 @@ import {
import {
deleteOutsourceDescendants,
listOutsourceDescendantIds,
outsourceTreeHasCompletedTask,
} from './lab-case-outsource.tree';
function dedupeToothJobs<
@@ -159,6 +170,7 @@ export class CasesService {
constructor(
private readonly prisma: PrismaService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
private readonly catalogLabels: CatalogLabelService,
private readonly labCaseActivity: LabCaseActivityService,
private readonly userNotifications: UserNotificationService,
@@ -469,6 +481,8 @@ export class CasesService {
await this.assertCanEditCases(actorUserId, labOrganizationId);
await this.assertPartnerClinic(dto.partnerClinicOrganizationId, labOrganizationId);
const toothShadeCode = await this.toothShadeCatalog.normalize(dto.toothShadeCode);
const created = await this.prisma.labCase.create({
data: {
origin: LabCaseOrigin.LAB_INTERNAL,
@@ -479,6 +493,7 @@ export class CasesService {
patientDisplayMobile: dto.patientDisplayMobile?.trim() || null,
partnerClinicOrganizationId: dto.partnerClinicOrganizationId || null,
dueDate: dto.dueDate ? new Date(dto.dueDate) : null,
toothShadeCode,
sortOrder: 0,
},
include: labCaseListInclude,
@@ -512,6 +527,8 @@ export class CasesService {
await this.assertPartnerClinic(dto.partnerClinicOrganizationId, labOrganizationId);
const toothShadeCode = await this.toothShadeCatalog.normalizeOptional(dto.toothShadeCode);
const removedFiles: string[] = [];
const saved = await this.prisma.$transaction(async (tx) => {
await tx.labCase.update({
@@ -524,6 +541,7 @@ export class CasesService {
partnerClinicOrganizationId: dto.partnerClinicOrganizationId || null,
dueDate:
dto.dueDate === undefined ? undefined : dto.dueDate ? new Date(dto.dueDate) : null,
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
});
@@ -835,6 +853,7 @@ export class CasesService {
sentAt: new Date(),
accessToken: generateLabCaseAccessToken(),
dueDate: existing.dueDate,
toothShadeCode: existing.toothShadeCode,
referringClinicName: sender?.name.trim() || null,
referringDentistName: null,
patientDisplayName:
@@ -1442,6 +1461,56 @@ export class CasesService {
return { success: true, data: await this.mapLabCaseDetail(labCase, localeInput, labOrganizationId) };
}
/**
* Lab-origin shade edit: draft always, or started with no completed current-round step
* anywhere in its outsource tree. Outsource children take the new shade too.
* Clinic-dispatch and outsource receivers cannot change shade here.
*/
async setCaseToothShade(
labCaseId: string,
dto: UpdateLabCaseToothShadeDto,
labOrganizationId: string,
actorUserId: string,
localeInput?: string | null,
) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
const existing = await this.prisma.labCase.findFirst({
where: {
id: labCaseId,
origin: LabCaseOrigin.LAB_INTERNAL,
destinationOrganizationId: labOrganizationId,
},
select: { id: true, startedAt: true, toothShadeCode: true },
});
if (!existing) {
throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const toothShadeCode = await this.toothShadeCatalog.normalize(dto.toothShadeCode);
if (toothShadeCode !== existing.toothShadeCode) {
await this.prisma.$transaction(async (tx) => {
if (existing.startedAt && (await outsourceTreeHasCompletedTask(tx, labCaseId))) {
throw new AppException(ErrorCode.TOOTH_SHADE_LOCKED, HttpStatus.CONFLICT);
}
const ids = [labCaseId, ...(await listOutsourceDescendantIds(tx, labCaseId))];
await tx.labCase.updateMany({
where: { id: { in: ids } },
data: { toothShadeCode },
});
});
}
const labCase = await this.prisma.labCase.findFirstOrThrow({
where: { id: labCaseId },
include: labCaseListInclude,
});
return { success: true, data: await this.mapLabCaseDetail(labCase, localeInput, labOrganizationId) };
}
async listAssignableStaff(labOrganizationId: string, actorUserId: string) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
@@ -1779,6 +1848,7 @@ export class CasesService {
isOverdue: isLabCaseOverdue(lc.dueDate, currentTasks),
isImportant: lc.isImportant,
externalCode: lc.externalCode ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
origin: lc.origin,
startedAt: lc.startedAt?.toISOString() ?? null,
referringClinicName: lc.referringClinicName,

View File

@@ -27,6 +27,13 @@ export class UpdateLabCaseExternalCodeDto {
externalCode?: string | null;
}
export class UpdateLabCaseToothShadeDto {
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class OutsourceLabCaseDto {
@IsUUID()
destinationOrganizationId!: string;
@@ -126,6 +133,11 @@ export class CreateLabInternalCaseDto {
@IsOptional()
@IsDateString()
dueDate?: string | null;
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class UpdateLabInternalCaseDto extends CreateLabInternalCaseDto {

View File

@@ -964,6 +964,7 @@ export class TasksService {
isImportant: task.labCase.isImportant,
caseDueDate: task.labCase.dueDate?.toISOString() ?? null,
isCaseOverdue: isLabCaseOverdue(task.labCase.dueDate, task.labCase.tasks),
toothShadeCode: task.labCase.toothShadeCode ?? null,
assignee: task.assignee
? { id: task.assignee.id, name: task.assignee.name }
: null,

View File

@@ -0,0 +1,21 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ToothShadeCatalogService } from './tooth-shade-catalog.service';
@ApiTags('tooth-shade-catalog')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@Controller('tooth-shade-catalog')
export class ToothShadeCatalogController {
constructor(private readonly toothShadeCatalog: ToothShadeCatalogService) {}
@Get()
@ApiOperation({ summary: 'List tooth shade guide codes (VITA Classical + bleach)' })
list() {
return this.toothShadeCatalog.list().then((data) => ({
success: true,
data,
}));
}
}

View File

@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ToothShadeCatalogController } from './tooth-shade-catalog.controller';
import { ToothShadeCatalogService } from './tooth-shade-catalog.service';
@Module({
controllers: [ToothShadeCatalogController],
providers: [ToothShadeCatalogService, PrismaService],
exports: [ToothShadeCatalogService],
})
export class ToothShadeCatalogModule {}

View File

@@ -0,0 +1,61 @@
import { HttpStatus, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import { PrismaService } from '../../../prisma/prisma.service';
import { canonicalToothShadeCode } from './tooth-shade-code';
export type ToothShadeCatalogEntry = {
code: string;
family: string;
sortOrder: number;
hex: string;
};
@Injectable()
export class ToothShadeCatalogService implements OnModuleInit {
private readonly logger = new Logger(ToothShadeCatalogService.name);
/** Every stored code, active or not — a deactivated shade stays valid on existing cases. */
private knownCodes: Set<string> | null = null;
constructor(private readonly prisma: PrismaService) {}
async onModuleInit() {
try {
await this.loadKnownCodes();
} catch (error) {
this.logger.warn(`Tooth shade catalog not loaded at boot: ${String(error)}`);
}
}
private async loadKnownCodes(): Promise<Set<string>> {
const rows = await this.prisma.toothShade.findMany({ select: { code: true } });
this.knownCodes = new Set(rows.map((row) => row.code));
return this.knownCodes;
}
/** Active shades for the picker and voice prompt, read fresh so AdminJS edits show at once. */
async list(): Promise<ToothShadeCatalogEntry[]> {
return this.prisma.toothShade.findMany({
where: { isActive: true },
orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
select: { code: true, family: true, sortOrder: true, hex: true },
});
}
/** Null/empty clears. Unknown codes throw TOOTH_SHADE_INVALID. */
async normalize(input: string | null | undefined): Promise<string | null> {
const code = canonicalToothShadeCode(input);
if (code === null) return null;
const known =
this.knownCodes?.has(code) ? this.knownCodes : await this.loadKnownCodes();
if (!known.has(code)) {
throw new AppException(ErrorCode.TOOTH_SHADE_INVALID, HttpStatus.BAD_REQUEST);
}
return code;
}
/** `undefined` means "leave unchanged" (field omitted from the request). */
async normalizeOptional(input: string | null | undefined): Promise<string | null | undefined> {
if (input === undefined) return undefined;
return this.normalize(input);
}
}

View File

@@ -0,0 +1,29 @@
import { canonicalToothShadeCode } from './tooth-shade-code';
describe('canonicalToothShadeCode', () => {
it('keeps exact catalog codes', () => {
for (const code of ['0M1', 'A1', 'A3.5', 'B4', 'C1', 'D2']) {
expect(canonicalToothShadeCode(code)).toBe(code);
}
});
it('fixes case, spacing, decimal separators and digits', () => {
expect(canonicalToothShadeCode(' a2 ')).toBe('A2');
expect(canonicalToothShadeCode('A 3,5')).toBe('A3.5');
expect(canonicalToothShadeCode('a3/5')).toBe('A3.5');
expect(canonicalToothShadeCode('A۳٫۵')).toBe('A3.5');
expect(canonicalToothShadeCode('B٢')).toBe('B2');
});
it('reads a letter O as the bleach zero', () => {
expect(canonicalToothShadeCode('OM1')).toBe('0M1');
expect(canonicalToothShadeCode('om 3')).toBe('0M3');
});
it('returns null for empty or non-string input', () => {
expect(canonicalToothShadeCode('')).toBeNull();
expect(canonicalToothShadeCode(' ')).toBeNull();
expect(canonicalToothShadeCode(null)).toBeNull();
expect(canonicalToothShadeCode(2)).toBeNull();
});
});

View File

@@ -0,0 +1,20 @@
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹';
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
/**
* Canonical spelling of a typed or dictated shade ("a 3,5" → "A3.5", "OM1" → "0M1").
* Returns null for empty input. It does not check the catalog.
*/
export function canonicalToothShadeCode(input: unknown): string | null {
if (typeof input !== 'string') return null;
let value = input.normalize('NFKC').trim();
if (!value) return null;
value = value.replace(/[۰-۹]/g, (d) => String(PERSIAN_DIGITS.indexOf(d)));
value = value.replace(/[٠-٩]/g, (d) => String(ARABIC_DIGITS.indexOf(d)));
value = value
.replace(/[\s\-_]+/g, '')
.replace(/[,/٫]/g, '.')
.toUpperCase();
if (/^OM\d/.test(value)) value = `0M${value.slice(2)}`;
return value || null;
}

View File

@@ -121,6 +121,11 @@ export class SaveLabCaseDto {
@IsOptional()
@IsDateString()
dueDate?: string | null;
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class UpdateLabCaseDueDateDto {

View File

@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { LabCaseCommentsModule } from '../lab-case-comments/lab-case-comments.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { TreatmentsController } from './treatments.controller';
@@ -10,7 +11,14 @@ import { BillingModule } from '../billing/billing.module';
import { SubscriptionModule } from '../subscription/subscription.module';
@Module({
imports: [ProsthesisCatalogModule, LabCaseCommentsModule, NotificationsModule, BillingModule, SubscriptionModule],
imports: [
ProsthesisCatalogModule,
ToothShadeCatalogModule,
LabCaseCommentsModule,
NotificationsModule,
BillingModule,
SubscriptionModule,
],
controllers: [TreatmentsController],
providers: [TreatmentsService, PrismaService, ClinicOrgGuard],
})

View File

@@ -18,6 +18,7 @@ import {
outsourceTreeHasCompletedTask,
} from '../cases/lab-case-outsource.tree';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service';
import {
SaveTreatmentDraftDto,
@@ -145,6 +146,7 @@ export class TreatmentsService {
private readonly prisma: PrismaService,
private readonly treatmentCatalog: TreatmentCatalogService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
private readonly labCaseActivity: LabCaseActivityService,
private readonly userNotifications: UserNotificationService,
private readonly billing: BillingService,
@@ -999,6 +1001,15 @@ export class TreatmentsService {
lc.dueDate,
);
}
if (lc.toothShadeCode !== undefined) {
await this.updateLabCaseToothShadeInTx(
tx,
lc.id,
organizationId,
actorUserId,
lc.toothShadeCode,
);
}
continue;
}
@@ -1010,6 +1021,7 @@ export class TreatmentsService {
throw new AppException(ErrorCode.TREATMENT_INVALID_DUE_DATE, HttpStatus.BAD_REQUEST);
}
}
const toothShadeCode = await this.toothShadeCatalog.normalizeOptional(lc.toothShadeCode);
const row = lc.id
? await tx.labCase.update({
@@ -1019,6 +1031,7 @@ export class TreatmentsService {
sortOrder: index,
destinationOrganizationId: lc.destinationOrganizationId ?? null,
...(dueDate !== undefined ? { dueDate } : {}),
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
})
: await tx.labCase.create({
@@ -1029,6 +1042,7 @@ export class TreatmentsService {
sortOrder: index,
destinationOrganizationId: lc.destinationOrganizationId ?? null,
...(dueDate !== undefined ? { dueDate } : {}),
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
});
@@ -1342,6 +1356,47 @@ export class TreatmentsService {
});
}
/**
* Sent case: autosave resends every lab case, so an unchanged shade is a no-op even after
* the plan locks. A real change is refused once any step in the outsource tree is done,
* and otherwise also lands on the outsource children.
*/
private async updateLabCaseToothShadeInTx(
tx: Prisma.TransactionClient,
labCaseId: string,
organizationId: string,
actorUserId: string,
toothShadeInput: string | null,
) {
const labCase = await tx.labCase.findFirst({
where: {
id: labCaseId,
treatment: {
organizationId,
...treatmentProviderScopeWhere(actorUserId),
},
},
select: { id: true, toothShadeCode: true },
});
if (!labCase) {
throw new AppException(ErrorCode.LAB_CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const toothShadeCode = await this.toothShadeCatalog.normalize(toothShadeInput);
if (toothShadeCode === labCase.toothShadeCode) return;
if (await outsourceTreeHasCompletedTask(tx, labCaseId)) {
throw new AppException(ErrorCode.TOOTH_SHADE_LOCKED, HttpStatus.CONFLICT);
}
const ids = [labCaseId, ...(await listOutsourceDescendantIds(tx, labCaseId))];
await tx.labCase.updateMany({
where: { id: { in: ids } },
data: { toothShadeCode },
});
}
async uploadDetailAttachments(
appointmentId: string,
detailClientKey: string,
@@ -1717,6 +1772,7 @@ export class TreatmentsService {
destinationOrganizationId?: string | null;
sentAt?: Date | null;
dueDate?: Date | null;
toothShadeCode?: string | null;
accessToken?: string | null;
details?: Array<{
treatmentDetailId: string;
@@ -1763,6 +1819,7 @@ export class TreatmentsService {
destinationOrganizationId: lc.destinationOrganizationId ?? null,
sentAt: lc.sentAt?.toISOString() ?? null,
dueDate: lc.dueDate?.toISOString() ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
taskProgress,
treatmentDetailId: lc.details?.[0]?.treatmentDetailId ?? null,
detail: lc.details?.[0]

View File

@@ -106,8 +106,8 @@ export function buildExtractionPrompt(
'You are a parser, not an assistant: report only what was said.',
'',
'HARD RULES',
'1. Never invent a code. treatmentType and prosthesis[].types[] must be codes from the',
' lists below. labId must be an id from the lab list. If what you heard is not in a',
'1. Never invent a code. treatmentType, prosthesis[].types[] and toothShadeCode must be',
' codes from the lists below. labId must be an id from the lab list. If what you heard is not in a',
' list, use null (or omit it from prosthesis[].types[]).',
'2. "side" is always the PATIENT\'s side. The patient\'s upper right is quadrant 1. Never',
" flip to the viewer's point of view.",
@@ -121,7 +121,7 @@ export function buildExtractionPrompt(
' as a prosthesis[].targets entry with "arch" set and "position" null.',
'7. "comment" holds the meaningful speech that fits no other field — observations,',
' patient context, anything worth keeping that is not a treatmentType, tooth,',
' prosthesis, lab or deadline. Filler and small talk (greetings, thanks, "ok") are',
' prosthesis, lab, deadline or tooth shade. Filler and small talk (greetings, thanks, "ok") are',
' dropped entirely, never noted. When the clinician asked for a note, keep the asking',
' words out of its text.',
'8. pontic is a per-tooth role, never a material and never a jaw. Never stack pontic with',
@@ -189,11 +189,20 @@ export function buildExtractionPrompt(
' for a note, the asking words stay out of its text: for "بنویس که بیمار حساسیت به',
' سرما دارد", comment is "بیمار حساسیت به سرما دارد".',
' WHERE THE NOTE ENDS: a clause you also reported in another field — a lab, a tooth,',
' a prosthesis, a deadline — is that instruction, so it never belongs in "comment" as',
' well. Nothing may appear in two fields. Example: "توی توضیحات بنویس رنگ دندون A2',
' هست و بفرست برای لابراتوآر سانشاین" -> comment "رنگ دندون A2 هست", and the lab',
' goes to labId. "و بفرست برای لابراتوآر سانشاین" is an instruction, not the note.',
' a prosthesis, a deadline, a tooth shade — is that instruction, so it never belongs',
' in "comment" as well. Nothing may appear in two fields. Example: "توی توضیحات بنویس',
' بیمار حساسیت به سرما دارد و رنگ دندون A2 هست و بفرست برای لابراتوآر سانشاین" ->',
' comment "بیمار حساسیت به سرما دارد", toothShadeCode "A2", and the lab goes to labId.',
'- toothShadeCode: a CODE from the TOOTH SHADES list when a shade (رنگ / shade / kleur)',
' was spoken, e.g. "آ دو" or "A two" -> "A2", "آ سه و نیم" -> "A3.5", "او ام یک" or',
' "bleach one" -> "0M1". One shade for the whole case. Null when none. Never invent a',
' code. Never also put that shade in comment. The digit in a shade is never a tooth.',
'- labMatchExact: true only when the spoken name matched a lab name exactly.',
'',
'TOOTH SHADES (codes only — use exactly):',
catalog.toothShades.length > 0
? catalog.toothShades.map((s) => `- ${s.code}`).join('\n')
: '(none)',
].join('\n');
return [

View File

@@ -101,6 +101,7 @@ const CTX: ResolveContext = {
]),
prosthesisSubcategoryCodes: new Set(['night_guard']),
linkedLabIds: new Set(['lab-sina', 'lab-mehr']),
toothShadeCodes: new Set(['0M1', 'A1', 'A2', 'A3.5', 'B1']),
};
describe('resolveConnectedSpans', () => {
@@ -530,6 +531,7 @@ describe('resolveVoiceIntent', () => {
labId: null,
labMatchExact: false,
due: null,
toothShadeCode: null,
};
it('composes a plain restoration', () => {
@@ -553,6 +555,21 @@ describe('resolveVoiceIntent', () => {
});
});
it('keeps a catalog tooth shade, canonicalizing the spelling', () => {
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'A2' }, CTX).toothShadeCode).toBe('A2');
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'a 3,5' }, CTX).toothShadeCode).toBe(
'A3.5',
);
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'OM1' }, CTX).toothShadeCode).toBe('0M1');
expect(resolveVoiceIntent(base, CTX).toothShadeCode).toBeNull();
});
it('drops a tooth shade outside the catalog and reports it', () => {
const result = resolveVoiceIntent({ ...base, toothShadeCode: 'Z9' }, CTX);
expect(result.toothShadeCode).toBeNull();
expect(result.unresolved).toContainEqual({ spoken: 'Z9', reason: 'unknown_catalog_code' });
});
it('drops a lab id the clinic is not linked to', () => {
// Shipping to a lab the clinic never named is worse than shipping nowhere.
const result = resolveVoiceIntent(

View File

@@ -10,6 +10,7 @@ import {
type Arch,
type PatientSide,
} from '../../common/fdi';
import { canonicalToothShadeCode } from '../tooth-shade-catalog/tooth-shade-code';
import { resolveDueDate } from './due-date.resolver';
import {
resolveToothIntent,
@@ -51,6 +52,7 @@ export type ResolvedExtraction = {
labId: string | null;
labMatchExact: boolean;
dueDate: string | null;
toothShadeCode: string | null;
unresolved: UnresolvedItem[];
};
@@ -71,6 +73,7 @@ export type ResolveContext = {
prosthesisCategoryCodes: ReadonlySet<string>;
prosthesisSubcategoryCodes: ReadonlySet<string>;
linkedLabIds: ReadonlySet<string>;
toothShadeCodes: ReadonlySet<string>;
};
function spokenOf(intent: unknown): string {
@@ -562,6 +565,17 @@ export function resolveVoiceIntent(
unresolved.push({ spoken: '', reason: 'unknown_catalog_code' });
}
const toothShadeCode = resolveCatalogCode(
canonicalToothShadeCode(intent?.toothShadeCode),
ctx.toothShadeCodes,
);
if (intent?.toothShadeCode != null && !toothShadeCode) {
unresolved.push({
spoken: String(intent.toothShadeCode),
reason: 'unknown_catalog_code',
});
}
return {
treatmentType: hasResolvedAssignment ? 'prosthesis' : treatmentType,
teeth: spanResult.teeth,
@@ -571,6 +585,7 @@ export function resolveVoiceIntent(
labId,
labMatchExact: labId ? intent?.labMatchExact === true : false,
dueDate: due.dueDate,
toothShadeCode,
unresolved,
};
}

View File

@@ -27,6 +27,7 @@ const wire = (overrides: Partial<WireVoiceIntent> = {}): WireVoiceIntent => ({
labId: null,
labMatchExact: false,
due: emptyDue,
toothShadeCode: null,
...overrides,
});

View File

@@ -54,6 +54,7 @@ export type WireVoiceIntent = {
labId: string | null;
labMatchExact: boolean;
due: WireDue;
toothShadeCode: string | null;
};
const TOOTH_SCHEMA = {
@@ -129,6 +130,7 @@ export const VOICE_INTENT_JSON_SCHEMA = {
'labId',
'labMatchExact',
'due',
'toothShadeCode',
],
properties: {
treatmentType: {
@@ -177,6 +179,12 @@ export const VOICE_INTENT_JSON_SCHEMA = {
type: 'boolean',
description: 'True only when the spoken name matched a lab name exactly.',
},
toothShadeCode: {
type: ['string', 'null'],
description:
'A tooth shade CODE from the supplied shade list (e.g. "A2", "0M1", "A3.5"), or null. ' +
'Never invent a code. Never put a shade into comment when it belongs here.',
},
due: {
type: 'object',
additionalProperties: false,
@@ -308,5 +316,9 @@ export function toVoiceIntent(wire: WireVoiceIntent): VoiceIntent {
labId: wire?.labId ?? null,
labMatchExact: wire?.labMatchExact === true,
due: toDueIntent(wire?.due),
toothShadeCode:
typeof wire?.toothShadeCode === 'string' && wire.toothShadeCode.trim()
? wire.toothShadeCode.trim()
: null,
};
}

View File

@@ -30,6 +30,7 @@ const catalog = (): ExtractionCatalog => ({
],
prosthesisSubcategories: [{ code: 'veneer', label: 'Veneer' }],
labs: [{ id: 'org-lab-1', name: 'Some Lab' }],
toothShades: [{ code: 'A2' }, { code: '0M1' }],
});
describe('narrowCatalogForOrgType', () => {

View File

@@ -25,6 +25,7 @@ const CATALOG = {
prosthesisCategories: [{ code: 'crown', label: 'روکش‌ها' }],
prosthesisSubcategories: [],
labs: [{ id: 'lab-1', name: 'لابراتوار سینا' }],
toothShades: [{ code: 'A2' }, { code: '0M1' }],
};
type ChatBody = {

View File

@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { VoiceController } from './voice.controller';
import { VoiceService } from './voice.service';
@Module({
imports: [ProsthesisCatalogModule],
imports: [ProsthesisCatalogModule, ToothShadeCatalogModule],
controllers: [VoiceController],
providers: [VoiceService, PrismaService],
})

View File

@@ -52,6 +52,8 @@ export type ExtractionCatalog = {
prosthesisSubcategories: { code: string; label: string }[];
/** The clinic's linked labs — a closed choice list. */
labs: { id: string; name: string }[];
/** VITA Classical + bleach shade codes (labels are the codes). */
toothShades: { code: string }[];
};
export type ExtractionResult = {

View File

@@ -31,6 +31,7 @@ const EMPTY_INTENT = {
labId: null,
labMatchExact: false,
due: null,
toothShadeCode: null,
};
const DTO: ExtractVoiceDto = {
@@ -114,11 +115,18 @@ function buildService(opts: {
.mockResolvedValue([{ code: 'veneer', label: 'Veneer' }]),
};
const toothShadeCatalog = {
list: jest.fn().mockResolvedValue([
{ code: 'A2', family: 'A', sortOrder: 5, hex: '#E8D5B7' },
]),
};
return new VoiceService(
prisma as never,
config as never,
treatmentCatalog as never,
prosthesisCatalog as never,
toothShadeCatalog as never,
);
}

View File

@@ -17,6 +17,7 @@ import {
import { narrowCatalogForOrgType } from './narrowCatalogForOrgType';
import { normalizeCatalogLocale } from '../catalog/catalog-label.service';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service';
import { weekStartForLocale } from './due-date.resolver';
import {
@@ -57,6 +58,7 @@ export class VoiceService {
private readonly config: ConfigService,
private readonly treatmentCatalog: TreatmentCatalogService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
) {}
private get voiceConfig(): VoiceConfig {
@@ -165,6 +167,7 @@ export class VoiceService {
catalog.prosthesisSubcategories.map((c) => c.code),
),
linkedLabIds: new Set(catalog.labs.map((l) => l.id)),
toothShadeCodes: new Set(catalog.toothShades.map((s) => s.code)),
});
} catch (error) {
throw this.toAppException(error, 'extraction');
@@ -291,12 +294,14 @@ export class VoiceService {
prosthesisCategories,
prosthesisSubcategories,
labs,
toothShades,
] = await Promise.all([
this.treatmentCatalog.list(locale, null),
this.prosthesisCatalog.list(locale),
this.prosthesisCatalog.listCategories(locale),
this.prosthesisCatalog.listSubcategories(locale),
this.listLinkedLabs(organizationId),
this.toothShadeCatalog.list(),
]);
return {
@@ -309,6 +314,7 @@ export class VoiceService {
prosthesisCategories,
prosthesisSubcategories,
labs,
toothShades: toothShades.map((s) => ({ code: s.code })),
};
}
@@ -381,6 +387,7 @@ export class VoiceService {
prosthesisAssignments: resolved.prosthesisAssignments.length,
lab: resolved.labId != null,
dueDate: resolved.dueDate != null,
toothShade: resolved.toothShadeCode != null,
},
unresolvedCount: resolved.unresolved.length,
}),

View File

@@ -77,6 +77,8 @@ export type VoiceIntent = {
/** False when the spoken name only approximately matched — the UI then requires an explicit tick. */
labMatchExact: boolean;
due: DueIntent | null;
/** Optional VITA-style tooth shade code from the shade guide, or null. */
toothShadeCode: string | null;
};
/** Why a spoken item could not be turned into a domain value. Shown to the user. */

View File

@@ -615,7 +615,9 @@
"errorDeleteCase": "Could not delete the case.",
"draftsTitle": "Drafts",
"draftsSubtitle": "Unstarted cases you created. Start a draft to add it to the case list.",
"draftsEmpty": "No drafts."
"draftsEmpty": "No drafts.",
"caseSheetToothShade": "Shade",
"errorUpdateToothShade": "Could not save the tooth shade."
},
"labCaseAccess": {
"pageTitle": "Case tasks",
@@ -1058,7 +1060,8 @@
"unknown_catalog_code": "not in this clinic’s list",
"invalid_date": "not a usable date"
},
"voiceFailed": "Voice entry failed. Please try again."
"voiceFailed": "Voice entry failed. Please try again.",
"toothShadeLabel": "Tooth shade"
},
"organizations": {
"loadingOrganization": "Loading organization...",
@@ -1680,6 +1683,11 @@
"BILLING_STAFF_INVALID": "Choose a staff member for this payment.",
"BILLING_PARTY_INVALID": "Choose a valid party for this filter.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "The selected lab does not provide one or more prosthesis types in this case.",
"BILLING_OBLIGATION_NOT_EDITABLE": "Only the destination lab can set this case fee."
"BILLING_OBLIGATION_NOT_EDITABLE": "Only the destination lab can set this case fee.",
"TOOTH_SHADE_INVALID": "That tooth shade is not valid.",
"TOOTH_SHADE_LOCKED": "The tooth shade cannot be changed after a lab step is completed."
},
"toothShade": {
"label": "Tooth shade"
}
}

View File

@@ -616,7 +616,9 @@
"errorDeleteCase": "حذف پرونده ممکن نشد.",
"draftsTitle": "پیش‌نویس‌ها",
"draftsSubtitle": "پرونده‌های شروع‌نشده‌ای که ساخته‌اید. با شروع پیش‌نویس، به فهرست پرونده‌ها اضافه می‌شود.",
"draftsEmpty": "پیش‌نویسی نیست."
"draftsEmpty": "پیش‌نویسی نیست.",
"caseSheetToothShade": "رنگ",
"errorUpdateToothShade": "ذخیره رنگ دندان ممکن نشد."
},
"labCaseAccess": {
"pageTitle": "وظایف پرونده",
@@ -1059,7 +1061,8 @@
"unknown_catalog_code": "در فهرست این مطب نیست",
"invalid_date": "تاریخ قابل استفاده نیست"
},
"voiceFailed": "ثبت گفتاری انجام نشد. لطفاً دوباره تلاش کنید."
"voiceFailed": "ثبت گفتاری انجام نشد. لطفاً دوباره تلاش کنید.",
"toothShadeLabel": "رنگ دندان"
},
"organizations": {
"loadingOrganization": "در حال بارگذاری سازمان...",
@@ -1681,6 +1684,11 @@
"BILLING_STAFF_INVALID": "یک عضو کارکنان برای این پرداخت انتخاب کنید.",
"BILLING_PARTY_INVALID": "طرف معتبری برای این فیلتر انتخاب کنید.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "لابراتوار انتخاب‌شده یک یا چند نوع پروتز این پرونده را ارائه نمی‌دهد.",
"BILLING_OBLIGATION_NOT_EDITABLE": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند."
"BILLING_OBLIGATION_NOT_EDITABLE": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند.",
"TOOTH_SHADE_INVALID": "این رنگ دندان معتبر نیست.",
"TOOTH_SHADE_LOCKED": "پس از تکمیل یک مرحله لابراتوار نمی‌توان رنگ دندان را تغییر داد."
},
"toothShade": {
"label": "رنگ دندان"
}
}

View File

@@ -616,7 +616,9 @@
"errorDeleteCase": "Case kon niet worden verwijderd.",
"draftsTitle": "Concepten",
"draftsSubtitle": "Niet-gestarte cases die u hebt gemaakt. Start een concept om het in de caselijst te zetten.",
"draftsEmpty": "Geen concepten."
"draftsEmpty": "Geen concepten.",
"caseSheetToothShade": "Kleur",
"errorUpdateToothShade": "De tandkleur kon niet worden opgeslagen."
},
"labCaseAccess": {
"pageTitle": "Dossiertaken",
@@ -1058,7 +1060,8 @@
"unknown_catalog_code": "staat niet in de lijst van deze praktijk",
"invalid_date": "geen bruikbare datum"
},
"voiceFailed": "Spraakinvoer is mislukt. Probeer het opnieuw."
"voiceFailed": "Spraakinvoer is mislukt. Probeer het opnieuw.",
"toothShadeLabel": "Tandkleur"
},
"organizations": {
"loadingOrganization": "Organisatie laden...",
@@ -1680,6 +1683,11 @@
"BILLING_STAFF_INVALID": "Kies een medewerker voor deze betaling.",
"BILLING_PARTY_INVALID": "Kies een geldige partij voor dit filter.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "Het geselecteerde lab levert een of meer prothesetypen in deze case niet.",
"BILLING_OBLIGATION_NOT_EDITABLE": "Alleen het bestemmingslab kan dit casetarief instellen."
"BILLING_OBLIGATION_NOT_EDITABLE": "Alleen het bestemmingslab kan dit casetarief instellen.",
"TOOTH_SHADE_INVALID": "Die tandkleur is ongeldig.",
"TOOTH_SHADE_LOCKED": "De tandkleur kan niet worden gewijzigd nadat een labstap is voltooid."
},
"toothShade": {
"label": "Tandkleur"
}
}

View File

@@ -56,6 +56,7 @@ export type CaseTaskGroup = {
caseDueDate: string | null;
isCaseOverdue: boolean;
isImportant: boolean;
toothShadeCode?: string | null;
taskProgress: LabTaskListItem['taskProgress'];
origin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL' | 'LAB_OUTSOURCE';
partnerOrganizationType?: 'CLINIC' | 'LAB' | string | null;
@@ -96,6 +97,7 @@ export function groupTasksForDisplay(
caseDueDate: task.caseDueDate ?? null,
isCaseOverdue: task.isCaseOverdue,
isImportant: task.isImportant,
toothShadeCode: task.toothShadeCode ?? null,
taskProgress: task.taskProgress,
origin: task.origin,
partnerOrganizationType: task.partnerOrganizationType,

View File

@@ -46,6 +46,7 @@ const result = (overrides: Partial<VoiceExtractionResult> = {}): VoiceExtraction
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
});
@@ -57,6 +58,7 @@ const allTicked: VoiceApplySelection = {
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const tick = (overrides: Partial<VoiceApplySelection> = {}): VoiceApplySelection => ({
...allTicked,

View File

@@ -26,7 +26,7 @@ export function buildLabLineFromVoice(
result: VoiceExtractionResult,
selection: VoiceApplySelection,
ctx: VoiceLineContext,
): { line: LineDraft | null; dueDate: string | null } {
): { line: LineDraft | null; dueDate: string | null; toothShadeCode: string | null } {
const line = newLine();
if (selection.comment && result.comment) {
@@ -70,5 +70,7 @@ export function buildLabLineFromVoice(
return {
line: isBlankLine(line) ? null : line,
dueDate: selection.dueDate && result.dueDate ? result.dueDate : null,
toothShadeCode:
selection.toothShade && result.toothShadeCode ? result.toothShadeCode : null,
};
}

View File

@@ -77,6 +77,7 @@ const result = (overrides: Partial<VoiceExtractionResult> = {}): VoiceExtraction
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
});
@@ -88,6 +89,7 @@ const allTicked: VoiceApplySelection = {
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const tick = (overrides: Partial<VoiceApplySelection> = {}): VoiceApplySelection => ({
...allTicked,
@@ -385,6 +387,33 @@ describe('buildVoiceApplyPlan — the comment', () => {
});
});
describe('buildVoiceApplyPlan — the tooth shade', () => {
it('lands on the lab draft of a lab-dependent detail, even with nothing else', () => {
const plan = buildVoiceApplyPlan(result({ toothShadeCode: 'A2' }), tick(), ctx());
expect(plan.labCaseDraft?.toothShadeCode).toBe('A2');
expect(plan.detail.comment).toBe('');
});
it('is skipped when its row is unticked', () => {
const plan = buildVoiceApplyPlan(
result({ toothShadeCode: 'A2' }),
tick({ toothShade: false }),
ctx(),
);
expect(plan.labCaseDraft).toBeNull();
});
it('never creates a lab draft on a detail that is not lab-dependent', () => {
const plan = buildVoiceApplyPlan(
result({ treatmentType: 'restoration', toothShadeCode: 'A2' }),
tick(),
ctx({ defaultTreatmentType: 'restoration' }),
);
expect(plan.detail.treatmentType).toBe('restoration');
expect(plan.labCaseDraft).toBeNull();
});
});
describe('buildVoiceApplyPlan — it does not mutate what it was given', () => {
it('copies the dictated teeth rather than aliasing them', () => {
const dictated = result({ treatmentType: 'restoration', teeth: ['21'] });

View File

@@ -81,10 +81,12 @@ export function buildVoiceApplyPlan(
detail.toothSelectionGroups = landed.groups;
}
const landsShade = labDependent && selection.toothShade && Boolean(result.toothShadeCode);
const wantsLabDraft =
lines.some((line) => line.applied.length > 0) ||
Boolean(selection.lab && result.labId) ||
Boolean(selection.dueDate && result.dueDate);
Boolean(selection.dueDate && result.dueDate) ||
landsShade;
if (!wantsLabDraft) return { detail, labCaseDraft: null };
@@ -97,6 +99,9 @@ export function buildVoiceApplyPlan(
if (selection.dueDate && result.dueDate) {
labCaseDraft.dueDate = result.dueDate;
}
if (landsShade) {
labCaseDraft.toothShadeCode = result.toothShadeCode;
}
labCaseDraft.toothProsthesis = lines.flatMap((line) => {
// A jaw appliance belongs to no selection group; a tooth takes the group it landed in.
const selectionGroupId = line.isJaw

View File

@@ -95,6 +95,7 @@ function baseResult(overrides: Partial<VoiceExtractionResult> = {}): VoiceExtrac
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
};
@@ -112,6 +113,21 @@ describe('isLabDependentResult', () => {
});
describe('voiceRowAvailability', () => {
it('shows a tooth shade row only for lab-dependent work', () => {
expect(
voiceRowAvailability(
baseResult({ treatmentType: 'prosthesis', toothShadeCode: 'A2' }),
LAB_DEPENDENT,
).toothShade,
).toBe(true);
expect(
voiceRowAvailability(baseResult({ toothShadeCode: 'A2' }), LAB_DEPENDENT).toothShade,
).toBe(false);
expect(
voiceRowAvailability(baseResult({ toothShadeCode: 'A2' }), LAB_DEPENDENT, 'lab').toothShade,
).toBe(true);
});
it('shows a plain teeth row for a non-lab-dependent type', () => {
const result = baseResult({ teeth: ['14'] });
const available = voiceRowAvailability(result, LAB_DEPENDENT);
@@ -158,8 +174,24 @@ describe('initialVoiceSelection', () => {
describe('countSelected', () => {
it('intersects the selection with availability rather than counting raw ticks', () => {
const selection = { treatmentType: true, teeth: true, comment: true, prosthesis: true, lab: true, dueDate: true };
const available = { treatmentType: true, teeth: false, comment: true, prosthesis: false, lab: true, dueDate: false };
const selection = {
treatmentType: true,
teeth: true,
comment: true,
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const available = {
treatmentType: true,
teeth: false,
comment: true,
prosthesis: false,
lab: true,
dueDate: false,
toothShade: false,
};
expect(countSelected(selection, available)).toBe(3);
});
});

View File

@@ -67,6 +67,8 @@ export function voiceRowAvailability(
comment: Boolean(result.comment?.trim()),
lab: !isLab && result.labId != null,
dueDate: result.dueDate != null,
// A shade belongs to the lab case, so only lab-dependent work carries one.
toothShade: labDependent && result.toothShadeCode != null,
};
}
@@ -88,6 +90,7 @@ export function initialVoiceSelection(
prosthesis: available.prosthesis,
lab: available.lab && result.labMatchExact,
dueDate: available.dueDate,
toothShade: available.toothShade,
};
}

View File

@@ -50,8 +50,9 @@ import type { LabCaseDetail } from '@/types/cases';
import type { FdiToothId } from '@/types/treatment';
import type { LinkedOrganizationOption } from '@/types/treatment';
import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { ProsthesisCatalogEntry, ToothShadeCatalogEntry } from '@/types/treatment-catalog';
import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
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';
@@ -139,6 +140,7 @@ interface CaseCreatePanelProps {
labCase: LabCaseDetail;
canEdit: boolean;
prosthesisCatalog?: ProsthesisCatalogEntry[];
toothShadeCatalog?: ToothShadeCatalogEntry[];
/** Dictation owned by the Add case control. Applied onto this case's single plan. */
voiceResult?: VoiceExtractionResult | null;
onVoiceResultHandled?: () => void;
@@ -152,6 +154,7 @@ export function CaseCreatePanel({
labCase,
canEdit,
prosthesisCatalog,
toothShadeCatalog = [],
voiceResult = null,
onVoiceResultHandled,
onSaved,
@@ -182,6 +185,9 @@ export function CaseCreatePanel({
labCase.partnerClinicOrganizationId ?? '',
);
const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate));
const [toothShadeCode, setToothShadeCode] = useState<string | null>(
labCase.toothShadeCode ?? null,
);
const [plan, setPlan] = useState<LineDraft>(() => planFromDetail(labCase));
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
const sectionCounts = useCaseSectionCounts(labCase.id, section);
@@ -222,6 +228,7 @@ export function CaseCreatePanel({
setPatientDisplayMobile(labCase.patientDisplayMobile ?? '');
setPartnerClinicOrganizationId(labCase.partnerClinicOrganizationId ?? '');
setDueDate(toDateInputValue(labCase.dueDate));
setToothShadeCode(labCase.toothShadeCode ?? null);
setPlan(planFromDetail(labCase));
setSection('details');
// Hydrate only when switching drafts — never re-apply the same id after autosave.
@@ -293,6 +300,7 @@ export function CaseCreatePanel({
patientDisplayMobile: patientDisplayMobile.trim() || null,
partnerClinicOrganizationId: partnerClinicOrganizationId || null,
dueDate: dueDate || null,
toothShadeCode,
toothProsthesis: plan.toothProsthesis.map((tp) => ({
tooth: tp.tooth,
prosthesisTypeCode: tp.prosthesisTypeCode,
@@ -307,6 +315,7 @@ export function CaseCreatePanel({
patientDisplayMobile,
partnerClinicOrganizationId,
dueDate,
toothShadeCode,
plan,
],
);
@@ -475,15 +484,20 @@ export function CaseCreatePanel({
* already has jobs is merged. A dictated due date and comment still land.
*/
function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) {
const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, {
const {
line,
dueDate: dictatedDueDate,
toothShadeCode: dictatedShade,
} = buildLabLineFromVoice(applied, selection, {
prosthesisCatalog: prosthesisOptions,
});
onVoiceResultHandled?.();
if (dictatedDueDate) setDueDate(dictatedDueDate);
if (dictatedShade) setToothShadeCode(dictatedShade);
// 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'));
if (!dictatedDueDate && !dictatedShade) onError(tTreatment('voiceNothingExtracted'));
return;
}
@@ -662,6 +676,17 @@ export function CaseCreatePanel({
defaultToToday={false}
/>
</label>
{toothShadeCatalog.length > 0 ? (
<div className="sm:col-span-2">
<ToothShadeGuide
shades={toothShadeCatalog}
value={toothShadeCode}
onChange={setToothShadeCode}
disabled={disabled}
readOnly={disabled}
/>
</div>
) : null}
</div>
<UnderlineTabs

View File

@@ -60,7 +60,9 @@ import type {
LabCaseTaskGroup,
LabTaskStatus,
} from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { ProsthesisCatalogEntry, ToothShadeCatalogEntry } from '@/types/treatment-catalog';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
import { isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
function caseSheetLineNotes(labCase: LabCaseDetail): string[] {
const raw = [labCase.detail?.comment];
@@ -233,6 +235,9 @@ export interface CaseDetailPanelProps {
onImportantChange?: (checked: boolean) => void;
updatingExternalCode?: boolean;
onExternalCodeChange?: (externalCode: string | null) => void;
toothShadeCatalog?: ToothShadeCatalogEntry[];
updatingToothShade?: boolean;
onToothShadeChange?: (toothShadeCode: string | null) => void;
commentsSection?: ReactNode;
assignableStaff?: AssignableTaskStaff[];
canAssignTasks?: boolean;
@@ -274,6 +279,9 @@ export function CaseDetailPanel({
onImportantChange,
updatingExternalCode = false,
onExternalCodeChange,
toothShadeCatalog = [],
updatingToothShade = false,
onToothShadeChange,
commentsSection,
assignableStaff = [],
canAssignTasks = false,
@@ -436,6 +444,7 @@ export function CaseDetailPanel({
orderNumber: t('caseSheetOrderNumber'),
orderDate: t('caseSheetOrderDate'),
dateDue: t('caseSheetDateDue'),
toothShade: t('caseSheetToothShade'),
sender: t('caseSheetSender'),
recipient: t('caseSheetRecipient'),
patient: t('caseSheetPatient'),
@@ -543,6 +552,15 @@ export function CaseDetailPanel({
),
);
const canEditToothShade =
canEditImportant &&
isLabGeneratedCase(labCase.origin) &&
(!labCase.startedAt || (labCase.taskProgress?.completed ?? 0) === 0) &&
Boolean(onToothShadeChange);
// Read-only cases without a shade (all historical ones) skip the empty guide.
const showToothShadeGuide =
toothShadeCatalog.length > 0 && (canEditToothShade || Boolean(labCase.toothShadeCode));
return (
<div className="@container space-y-4 min-w-0">
<header className="grid grid-cols-1 items-start gap-3 border-b border-border pb-3 @2xl:grid-cols-[minmax(0,1fr)_auto] @2xl:gap-4">
@@ -577,6 +595,16 @@ export function CaseDetailPanel({
</>
) : null}
</div>
{showToothShadeGuide ? (
<ToothShadeGuide
className="mt-2"
shades={toothShadeCatalog}
value={labCase.toothShadeCode ?? null}
onChange={canEditToothShade ? onToothShadeChange : undefined}
disabled={updatingToothShade}
readOnly={!canEditToothShade}
/>
) : null}
</div>
{labCase.shareUrl ? (
<div className="shrink-0 @2xl:hidden">

View File

@@ -31,6 +31,7 @@ export type CaseSheetLabels = {
orderNumber: string;
orderDate: string;
dateDue: string;
toothShade: string;
sender: string;
recipient: string;
patient: string;
@@ -291,7 +292,7 @@ export function CaseSheetPrintLayout({
<section
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gridTemplateColumns: '1fr 1fr 1fr 1fr',
alignItems: 'start',
gap: 12,
marginTop: RULE_GAP,
@@ -300,6 +301,11 @@ export function CaseSheetPrintLayout({
<MetaBlock label={labels.orderNumber} value={orderNumber} rtl={rtl} />
<MetaBlock label={labels.orderDate} value={formatCaseDateTime(orderDate, locale)} rtl={rtl} />
<MetaBlock label={labels.dateDue} value={formatCaseDateTime(labCase.dueDate, locale)} rtl={rtl} />
<MetaBlock
label={labels.toothShade}
value={labCase.toothShadeCode?.trim() || '—'}
rtl={rtl}
/>
</section>
<section

View File

@@ -30,6 +30,7 @@ import {
} from '@/lib/uploads/caseUploadQueue';
import { caseCommentsApi } from '@/lib/api/case-comments';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { toothShadeCatalogApi } from '@/lib/api/tooth-shade-catalog';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
@@ -44,7 +45,11 @@ import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackB
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { AppDateInput } from '@/components/ui/shared/AppDateInput';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import type {
AssignableTaskStaff,
CasesFilterOptions,
@@ -104,7 +109,9 @@ export function CasesPage() {
prosthesisTypes: [],
});
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [toothShadeCatalog, setToothShadeCatalog] = useState<ToothShadeCatalogEntry[]>([]);
const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);
const [updatingToothShade, setUpdatingToothShade] = useState(false);
const [selectedCaseId, setSelectedCaseId] = useState<string | null>(null);
const [mobileDetailOpen, setMobileDetailOpen] = useState(false);
@@ -301,6 +308,7 @@ export function CasesPage() {
useEffect(() => {
void casesApi.listFilterOptions().then((r) => setFilterOptions(r.data)).catch(() => {});
void prosthesisCatalogApi.list().then((r) => setProsthesisCatalog(r.data)).catch(() => {});
void toothShadeCatalogApi.list().then((r) => setToothShadeCatalog(r.data)).catch(() => {});
void treatmentCatalogApi.list().then((r) => setTreatmentCatalog(r.data)).catch(() => {});
if (canEdit) {
void casesApi.listAssignableStaff().then((r) => setAssignableStaff(r.data)).catch(() => {});
@@ -658,6 +666,28 @@ export function CasesPage() {
}
}
async function handleCaseToothShadeChange(toothShadeCode: string | null) {
if (!selectedCaseId || !canEdit || !selectedCase) return;
const caseId = selectedCaseId;
const previousCase = selectedCase;
setSelectedCase({ ...selectedCase, toothShadeCode });
setUpdatingToothShade(true);
toast.setError('');
try {
const response = await casesApi.setCaseToothShade(caseId, toothShadeCode);
if (selectedCaseIdRef.current === caseId) {
setSelectedCase(withKnownCaseFiles(response.data));
}
} catch (error: unknown) {
if (selectedCaseIdRef.current === caseId) setSelectedCase(previousCase);
toast.showError(getUserFacingError(error, tErrors, t('errorUpdateToothShade')));
} finally {
setUpdatingToothShade(false);
}
}
const filterSelectClass = `${FORM_SELECT_CLASS} w-full min-w-0 rounded-md py-1.5 text-xs sm:py-2 sm:text-sm`;
function renderCaseCard(item: LabCaseListItem) {
@@ -910,6 +940,7 @@ export function CasesPage() {
labCase={selectedCase}
canEdit={canEdit}
prosthesisCatalog={prosthesisCatalog}
toothShadeCatalog={toothShadeCatalog}
voiceResult={
voiceResult && voiceCaseIdRef.current === selectedCase.id ? voiceResult : null
}
@@ -1008,6 +1039,9 @@ export function CasesPage() {
onImportantChange={(checked) => void handleCaseImportantToggle(checked)}
updatingExternalCode={updatingExternalCode}
onExternalCodeChange={(code) => void handleCaseExternalCodeChange(code)}
toothShadeCatalog={toothShadeCatalog}
updatingToothShade={updatingToothShade}
onToothShadeChange={(code) => void handleCaseToothShadeChange(code)}
assignableStaff={assignableStaff}
canAssignTasks={canEdit}
assigningTaskId={assigningTaskId}

View File

@@ -8,6 +8,7 @@ import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import { CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
import type { CaseTaskGroup } from '@/components/lab/taskListGrouping';
import { formatPatientName } from '@/components/lab/caseDetailUtils';
import { ToothShadeReadonlyText } from '@/components/ui/shared/ToothShadeGuide';
import { formatAppDate, APP_DATE } from '@/lib/i18n/format';
interface TaskCaseGroupHeaderProps {
@@ -57,6 +58,12 @@ export function TaskCaseGroupHeader({
</Badge>
) : null}
<LabCaseOriginBadge origin={caseGroup.origin} className="text-[10px]" />
{caseGroup.toothShadeCode ? (
<ToothShadeReadonlyText
code={caseGroup.toothShadeCode}
className="text-[10px] text-text-secondary"
/>
) : null}
</>
);

View File

@@ -0,0 +1,111 @@
'use client';
import { useTranslations } from 'next-intl';
import type { ToothShadeCatalogEntry } from '@/types/treatment-catalog';
type ToothShadeGuideProps = {
shades: readonly ToothShadeCatalogEntry[];
value: string | null;
onChange?: (code: string | null) => void;
disabled?: boolean;
/** When true, tabs are not interactive (still shows selected lift). */
readOnly?: boolean;
className?: string;
};
/**
* Physical shade-guide look: tooth tab + stem + label.
* Selected tab lifts via margin (not transform) so `overflow-x-auto` cannot clip the top.
*/
export function ToothShadeGuide({
shades,
value,
onChange,
disabled = false,
readOnly = false,
className = '',
}: ToothShadeGuideProps) {
const t = useTranslations('toothShade');
const interactive = !disabled && !readOnly && Boolean(onChange);
return (
<div className={`w-full min-w-0 border-y border-border/70 py-2 ${className}`}>
<p className="mb-1.5 text-center text-xs font-medium text-text-muted">{t('label')}</p>
{/* LTR in every locale so the tabs keep the physical guide order (0M → D). */}
<div className="flex w-full justify-center">
<div
dir="ltr"
className="inline-flex max-w-full gap-0.5 overflow-x-auto px-0.5 pb-0.5 [-ms-overflow-style:none] [scrollbar-width:none] sm:gap-1 [&::-webkit-scrollbar]:hidden"
role="radiogroup"
aria-label={t('label')}
aria-disabled={disabled || readOnly || undefined}
>
{shades.map((shade) => {
const selected = value === shade.code;
return (
<button
key={shade.code}
type="button"
role="radio"
aria-checked={selected}
disabled={!interactive}
title={shade.code}
onClick={() => {
if (!interactive || !onChange) return;
onChange(selected ? null : shade.code);
}}
className={`group relative flex shrink-0 flex-col items-center transition-[margin] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-1 ${
selected ? 'mt-0 z-[1]' : 'mt-1'
} ${interactive ? 'cursor-pointer' : 'cursor-default'}`}
>
<span
className={`relative flex h-9 w-5 items-end justify-center overflow-hidden rounded-t-[0.65rem] border sm:h-10 sm:w-6 ${
selected
? 'border-primary border-[1.5px] shadow-[0_5px_8px_-3px_rgba(15,23,42,0.4)]'
: 'border-border/70 shadow-sm'
}`}
style={{ backgroundColor: shade.hex }}
aria-hidden
>
<span
className="mb-0.5 h-2 w-2.5 rounded-t-full bg-black/5 sm:h-2.5 sm:w-3"
style={{ boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.35)' }}
/>
</span>
<span
className={`h-2.5 w-[2px] sm:h-3 ${selected ? 'bg-primary/70' : 'bg-slate-400/80'}`}
aria-hidden
/>
<span
className={`mt-0.5 max-w-[2.1rem] truncate text-[9px] font-semibold leading-none sm:max-w-[2.4rem] sm:text-[10px] ${
selected ? 'text-primary' : 'text-text-secondary'
}`}
>
{shade.code}
</span>
</button>
);
})}
</div>
</div>
</div>
);
}
/** Compact labeled value for Tasks / PDF / share headers. */
export function ToothShadeReadonlyText({
code,
className = '',
}: {
code: string | null | undefined;
className?: string;
}) {
const t = useTranslations('toothShade');
if (!code) return null;
return (
<span className={className}>
<span className="text-text-muted">{t('label')}: </span>
<span className="font-medium text-text-primary tabular-nums">{code}</span>
</span>
);
}

View File

@@ -12,7 +12,11 @@ import { TreatmentDetailAttachmentsStrip } from '@/components/ui/treatment/Treat
import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar';
import type { VoiceCaptureState } from '@/lib/voice/useVoiceCapture';
import type { LabCaseToothProsthesisDraft, TreatmentDetailDraft } from '@/types/treatment';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import { treatmentTypeColor, treatmentTypeOptionStyle } from '@/components/shared/treatmentTypeDisplay';
import {
isDetailTypeSelected,
@@ -28,6 +32,7 @@ import {
WORKSPACE_ACTION_BTN_HEIGHT,
WorkspaceActionLabel,
} from '@/components/ui/shared/WorkspaceActionLabel';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
interface TreatmentDetailsEditorProps {
details: TreatmentDetailDraft[];
@@ -79,6 +84,9 @@ interface TreatmentDetailsEditorProps {
prosthesisCatalog?: ProsthesisCatalogEntry[];
/** Jobs live on the lab-case draft, not on TreatmentDetailDraft. */
toothProsthesis?: LabCaseToothProsthesisDraft[];
toothShadeCatalog?: ToothShadeCatalogEntry[];
toothShadeCode?: string | null;
onToothShadeChange?: (code: string | null) => void;
}
export function TreatmentDetailsEditor({
@@ -117,6 +125,9 @@ export function TreatmentDetailsEditor({
liveDetailCalculated,
prosthesisCatalog = [],
toothProsthesis = [],
toothShadeCatalog = [],
toothShadeCode = null,
onToothShadeChange,
}: TreatmentDetailsEditorProps) {
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
@@ -388,6 +399,18 @@ export function TreatmentDetailsEditor({
) : null}
</div>
{activeDetail &&
labDependentCodes.has(activeDetail.treatmentType) &&
toothShadeCatalog.length > 0 ? (
<ToothShadeGuide
shades={toothShadeCatalog}
value={toothShadeCode}
onChange={onToothShadeChange}
disabled={readOnly}
readOnly={readOnly || !onToothShadeChange}
/>
) : null}
{chart ? (
<div className="relative min-w-0 w-full">
{chartLocked ? (

View File

@@ -31,6 +31,7 @@ import {
import { appointmentsApi } from '@/lib/api/appointments';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { toothShadeCatalogApi } from '@/lib/api/tooth-shade-catalog';
import { voiceApi } from '@/lib/api/voice';
import { useVoiceCapture } from '@/lib/voice/useVoiceCapture';
import { isMediaRecorderSupported } from '@/lib/voice/audioFormat';
@@ -94,7 +95,11 @@ import {
import type { Organization } from '@/types/organization';
import type { Patient } from '@/types/patient';
import type { AppointmentRecord } from '@/types/appointment';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import type {
FdiToothId,
LabCaseDraft,
@@ -282,6 +287,7 @@ function mapLabCaseDraftFromApi(lc: PastLabCase): LabCaseDraft {
sentAt: lc.sentAt ?? null,
sends: lc.sends ?? [],
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
taskProgress: lc.taskProgress ?? null,
shareUrl: lc.shareUrl ?? null,
calculatedAmount: lc.calculatedAmount ?? null,
@@ -351,6 +357,7 @@ function serializeLabCases(drafts: LabCaseDraft[]): string {
destinationOrganizationId: lc.destinationOrganizationId ?? null,
detailClientId: lc.detailClientId,
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
attachmentIds: [...lc.attachmentIds].sort(),
toothProsthesis: [...lc.toothProsthesis]
.map((tp) => ({
@@ -375,6 +382,7 @@ function isLabCasesDirty(drafts: LabCaseDraft[], savedSnapshot: string | null):
lc.toothProsthesis.length > 0 ||
Boolean(lc.destinationOrganizationId) ||
Boolean(lc.dueDate) ||
Boolean(lc.toothShadeCode) ||
lc.attachmentIds.length > 0,
);
}
@@ -525,6 +533,7 @@ export function TreatmentWorkspace({
const [labDependentCodes, setLabDependentCodes] = useState<Set<string>>(new Set());
const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [toothShadeCatalog, setToothShadeCatalog] = useState<ToothShadeCatalogEntry[]>([]);
const treatmentDropdownCatalog = useMemo(
() => treatmentCatalog.filter((entry) => entry.availableInTreatment),
[treatmentCatalog],
@@ -1208,11 +1217,12 @@ export function TreatmentWorkspace({
let cancelled = false;
void (async () => {
try {
const [orgsResponse, catalogResponse, prosthesisResponse, voiceResponse] =
const [orgsResponse, catalogResponse, prosthesisResponse, shadeResponse, voiceResponse] =
await Promise.all([
treatmentsApi.listLinkedOrganizations(),
treatmentCatalogApi.list(),
prosthesisCatalogApi.list(),
toothShadeCatalogApi.list(),
// Voice availability comes from the API, not a NEXT_PUBLIC_* var: those are
// baked in at build time, so enabling a locale would need a frontend rebuild.
// A failure here must not take the whole treatment tab down with it.
@@ -1223,6 +1233,7 @@ export function TreatmentWorkspace({
setOrgs(orgsResponse.data);
setTreatmentCatalog(catalogResponse.data);
setProsthesisCatalog(prosthesisResponse.data);
setToothShadeCatalog(shadeResponse.data);
setLabDependentCodes(
new Set(catalogResponse.data.filter((entry) => entry.labDependent).map((entry) => entry.code)),
);
@@ -1674,6 +1685,7 @@ export function TreatmentWorkspace({
),
attachmentIds: lc.attachmentIds,
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
};
})
.filter((row): row is NonNullable<typeof row> => row !== null);
@@ -2680,9 +2692,8 @@ export function TreatmentWorkspace({
tErrors,
]);
// Auto-create an unsent draft when the active detail is prosthesis (no wizard step).
// Auto-create an unsent draft when the active detail is prosthesis (shade + dispatch need a case).
useEffect(() => {
if (!showLabDispatch) return;
if (!canEditTreatmentForDay || !hasLiveContext) return;
const activeDetail = details.find((d) => d.clientId === activeDetailId);
if (!activeDetail || !labDependentCodes.has(activeDetail.treatmentType)) return;
@@ -2701,7 +2712,6 @@ export function TreatmentWorkspace({
isDetailLocked,
labCaseDrafts,
labDependentCodes,
showLabDispatch,
]);
const handleSendLabCase = useCallback(
@@ -3194,6 +3204,24 @@ export function TreatmentWorkspace({
toothProsthesis={
labCaseDraftForDetail(labCaseDrafts, activeDetailId)?.toothProsthesis ?? []
}
toothShadeCatalog={toothShadeCatalog}
toothShadeCode={
labCaseDraftForDetail(labCaseDrafts, activeDetailId)?.toothShadeCode ?? null
}
onToothShadeChange={(code) => {
const prev = labCaseDraftsRef.current;
const target = labCaseDraftForDetail(prev, activeDetailId);
const next = target
? prev.map((lc) =>
lc.clientId === target.clientId ? { ...lc, toothShadeCode: code } : lc,
)
: [
...prev,
{ ...newLabCaseDraft(), detailClientId: activeDetailId, toothShadeCode: code },
];
labCaseDraftsRef.current = next;
setLabCaseDrafts(next);
}}
chart={
<div ref={labPanelRef} className="min-w-0 w-full">
{showLabDispatch && labWorkspaceView === 'dispatch' ? (

View File

@@ -389,6 +389,18 @@ export function VoiceReviewSheet({
</span>
</Row>
) : null}
{available.toothShade && effective.toothShadeCode ? (
<Row
label={t('toothShadeLabel')}
checked={selection.toothShade}
onChange={toggle('toothShade')}
>
<span className="text-sm font-medium tabular-nums text-text-primary">
{effective.toothShadeCode}
</span>
</Row>
) : null}
</div>
)}

View File

@@ -16,6 +16,7 @@ export interface LabInternalCasePayload {
patientDisplayMobile?: string | null;
partnerClinicOrganizationId?: string | null;
dueDate?: string | null;
toothShadeCode?: string | null;
toothProsthesis?: Array<{
tooth: string;
prosthesisTypeCode: string;
@@ -195,6 +196,14 @@ export const casesApi = {
return response.data;
},
setCaseToothShade: async (
caseId: string,
toothShadeCode: string | null,
): Promise<{ success: boolean; data: LabCaseDetail }> => {
const response = await apiClient.patch(`/cases/${caseId}/tooth-shade`, { toothShadeCode });
return response.data;
},
listAttachments: async (
caseId: string,
): Promise<{ success: boolean; data: LabCaseAttachmentMeta[] }> => {

View File

@@ -0,0 +1,9 @@
import { apiClient } from './client';
import type { ToothShadeCatalogEntry } from '@/types/treatment-catalog';
export const toothShadeCatalogApi = {
list: async (): Promise<{ success: boolean; data: ToothShadeCatalogEntry[] }> => {
const response = await apiClient.get('/tooth-shade-catalog');
return response.data;
},
};

View File

@@ -154,6 +154,8 @@ export interface LabCaseDetail {
isImportant: boolean;
/** Optional external lab-app code (e.g. exocad); used as PDF order number when set. */
externalCode?: string | null;
/** Optional VITA-style tooth shade for the whole case. */
toothShadeCode?: string | null;
referringClinicName?: string | null;
referringDentistName?: string | null;
patientDisplayName?: string | null;
@@ -309,6 +311,7 @@ export interface LabTaskListItem {
isImportant: boolean;
caseDueDate: string | null;
isCaseOverdue: boolean;
toothShadeCode?: string | null;
assignee: LabTaskUser | null;
assignedAt: string | null;
lastStatusChangedAt: string | null;

View File

@@ -17,3 +17,10 @@ export interface ProsthesisCatalogEntry {
chartRegion: 'crown' | 'root' | 'arch' | string;
stackGroup: 'restoration' | 'implant' | 'post_core' | 'arch' | string;
}
export interface ToothShadeCatalogEntry {
code: string;
family: string;
sortOrder: number;
hex: string;
}

View File

@@ -127,6 +127,7 @@ export interface PastLabCase {
}>;
sends?: LabCaseSendInfo[];
dueDate?: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
attachments?: TreatmentAttachmentMeta[];
/** Present on sent cases — same share URL the lab Cases QR encodes. */
@@ -197,6 +198,7 @@ export interface LabCaseDraft {
sentAt?: string | null;
sends?: LabCaseSendInfo[];
dueDate?: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
shareUrl?: string | null;
calculatedAmount?: string | null;
@@ -230,6 +232,7 @@ export interface SaveLabCasePayload {
}>;
attachmentIds?: string[];
dueDate?: string | null;
toothShadeCode?: string | null;
}
export interface SaveTreatmentPayload {
@@ -253,6 +256,7 @@ export interface LabCaseResponse {
} | null;
sends: LabCaseSendInfo[];
dueDate: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
toothProsthesis?: LabCaseToothProsthesisDraft[];
attachments?: TreatmentAttachmentMeta[];

View File

@@ -59,6 +59,7 @@ export interface VoiceExtractionResult {
/** When false, the lab row must not tick itself — the name only approximately matched. */
labMatchExact: boolean;
dueDate: string | null;
toothShadeCode: string | null;
unresolved: VoiceUnresolvedItem[];
}
@@ -77,6 +78,7 @@ export interface VoiceApplySelection {
prosthesis: boolean;
lab: boolean;
dueDate: boolean;
toothShade: boolean;
}
export type VoicePhase = 'idle' | 'recording' | 'processing';