improvement: treatment preview and treatment history components overhauled. draft & completed status for treatment plan completely removed from the flow.

This commit is contained in:
2026-06-28 21:45:33 +03:30
parent 94b97aa0fa
commit feb0b26ad0
20 changed files with 571 additions and 608 deletions

View File

@@ -416,7 +416,6 @@
"loadingAppointments": "Loading appointments…",
"selectDayWithAppointment": "Select a day with at least one appointment.",
"confirmDiscard": "You have unsaved changes. Discard them and continue?",
"successDraftSaved": "Treatment draft saved.",
"errorChooseOrg": "Choose at least one active organization to send this case.",
"successCaseSent": "Case sent to selected organizations.",
"successFilesUploaded": "{count} file(s) uploaded successfully.",
@@ -428,7 +427,7 @@
"errorSaveDraft": "Failed to save treatment draft.",
"errorSendCase": "Failed to send case.",
"errorCaseMustSave": "Case must be saved before sending.",
"draftTitle": "Draft · {patientName}",
"treatmentPlanTitle": "Treatment · {patientName}",
"hiddenMessage": "Appointments are hidden.",
"showAppointments": "Show appointments",
"appointmentsTitle": "My appointments",
@@ -483,36 +482,30 @@
"successLabShipmentsSaved": "Lab shipments saved.",
"errorSaveLabShipments": "Failed to save lab shipments.",
"errorLabCaseNeedsDetails": "Select at least one treatment detail for this shipment.",
"saveDraft": "Save treatment draft",
"unsavedChanges": "Unsaved changes",
"draftSaved": "Draft saved",
"saveStatusSaving": "Saving…",
"saveStatusSaved": "All changes saved",
"saveStatusError": "Could not save — check your connection",
"sendSavesFirst": "Sending is per case and saves first automatically.",
"historyTitle": "Previous treatments",
"historySubtitle": "Completed treatments for this patient. Each case is listed separately.",
"historySubtitle": "Click a treatment to preview it. Use Open in the preview card to load it in the workspace.",
"loadingHistory": "Loading history…",
"historyEmpty": "No prior treatments for this patient.",
"statusLabel": "Status:",
"historyCaseLabel": "Case {n} · {type}",
"historyEmpty": "No other treatments recorded for this patient yet.",
"historyDetailLabel": "Detail {n} · {type}",
"previewTitle": "Treatment preview",
"openTreatment": "Open",
"selectAppointment": "Select an appointment to preview its treatment.",
"detailCount": "{n} detail(s)",
"detailSummary": "Detail {n}: {type}",
"detailAttachmentCount": "{n, plural, one {# file} other {# files}}",
"detailNotSentToLab": "Not sent to lab",
"detailPendingLabSend": "This lab detail has not been sent yet.",
"teethLabel": "Teeth:",
"teethNone": "None selected",
"reviewDetails": "Review details",
"previewTitle": "Treatment preview",
"previewDraft": "Preview current draft",
"selectAppointment": "Select an appointment to preview its draft.",
"caseCount": "{n} case(s)",
"attachmentCount": "{n} attachment(s)",
"caseSummary": "Case {n}: {type}",
"teethPrefix": "· Teeth",
"moreCases": "+ {n} more case(s)",
"previewDialogTitle": "Treatment preview",
"previewDialogSubtitle": "Review cases, attachments, and send destinations.",
"previewDialogSubtitlePhase4": "Review treatment details and attachments.",
"previewLabDispatchHint": "Use the lab dispatch panel in the workspace to send work to labs.",
"historicalReadonlyNotice": "You are viewing a past treatment (read-only).",
"errorNoAppointmentForTreatment": "This treatment has no linked appointment and cannot be opened.",
"noCases": "No cases in this treatment.",
"noDetails": "No treatment details in this draft.",
"noDetails": "No treatment details yet.",
"typeLabel": "Type:",
"commentsLabel": "Comments:",
"commentsEmpty": "Comments: —",

View File

@@ -416,7 +416,6 @@
"loadingAppointments": "در حال بارگذاری نوبت‌ها...",
"selectDayWithAppointment": "روزی را انتخاب کنید که حداقل یک نوبت داشته باشد.",
"confirmDiscard": "تغییرات ذخیره‌نشده دارید. آنها را کنار بگذارید و ادامه دهید؟",
"successDraftSaved": "پیش‌نویس درمان ذخیره شد.",
"errorChooseOrg": "حداقل یک سازمان فعال را برای ارسال این پرونده انتخاب کنید.",
"successCaseSent": "پرونده به سازمان‌های انتخاب شده ارسال شد.",
"successFilesUploaded": "{count} فایل با موفقیت بارگذاری شد.",
@@ -428,7 +427,7 @@
"errorSaveDraft": "ذخیره پیش‌نویس درمان ناموفق بود.",
"errorSendCase": "ارسال پرونده ناموفق بود.",
"errorCaseMustSave": "پرونده باید قبل از ارسال ذخیره شود.",
"draftTitle": "پیش‌نویس · {patientName}",
"treatmentPlanTitle": "درمان · {patientName}",
"hiddenMessage": "نوبت‌ها پنهان هستند.",
"showAppointments": "نمایش نوبت‌ها",
"appointmentsTitle": "نوبت‌های من",
@@ -483,35 +482,29 @@
"successLabShipmentsSaved": "محموله‌های لاب ذخیره شد.",
"errorSaveLabShipments": "ذخیره محموله‌های لاب ناموفق بود.",
"errorLabCaseNeedsDetails": "حداقل یک جزئیات درمان برای این محموله انتخاب کنید.",
"saveDraft": "ذخیره پیش‌نویس درمان",
"unsavedChanges": "تغییرات ذخیره‌نشده",
"draftSaved": "پیش‌نویس ذخیره شد",
"saveStatusSaving": "در حال ذخیره…",
"saveStatusSaved": "همه تغییرات ذخیره شد",
"saveStatusError": "ذخیره ناموفق بود — اتصال را بررسی کنید",
"sendSavesFirst": "ارسال برای هر پرونده به صورت جداگانه است و ابتدا به طور خودکار ذخیره می‌کند.",
"historyTitle": "درمان‌های قبلی",
"historySubtitle": "درمان‌های تکمیل شده برای این بیمار. هر پرونده به طور جداگانه فهرست شده است.",
"historySubtitle": "برای پیش‌نمایش روی یک درمان کلیک کنید. از دکمه باز کردن در کارت پیش‌نمایش برای بارگذاری در فضای کاری استفاده کنید.",
"loadingHistory": "در حال بارگذاری تاریخچه...",
"historyEmpty": "هیچ درمان قبلی برای این بیمار وجود ندارد.",
"statusLabel": "وضعیت:",
"historyCaseLabel": "پرونده {n} · {type}",
"historyEmpty": "هیچ درمان دیگری برای این بیمار ثبت نشده است.",
"historyDetailLabel": "جزئیات {n} · {type}",
"previewTitle": "پیش‌نمایش درمان",
"openTreatment": "باز کردن",
"selectAppointment": "یک نوبت را برای پیش‌نمایش درمان انتخاب کنید.",
"detailCount": "{n} جزئیات",
"detailSummary": "جزئیات {n}: {type}",
"detailAttachmentCount": "{n} فایل",
"detailNotSentToLab": "به لاب ارسال نشده",
"detailPendingLabSend": "این جزئیات لاب هنوز ارسال نشده است.",
"historicalReadonlyNotice": "در حال مشاهده یک درمان گذشته (فقط خواندنی) هستید.",
"errorNoAppointmentForTreatment": "این درمان نوبت مرتبطی ندارد و قابل باز کردن نیست.",
"teethLabel": "دندان‌ها:",
"teethNone": "هیچکدام انتخاب نشده",
"reviewDetails": "بررسی جزئیات",
"previewTitle": "پیش‌نمایش درمان",
"previewDraft": "پیش‌نمایش پیش‌نویس فعلی",
"selectAppointment": "یک نوبت را برای پیش‌نمایش پیش‌نویس آن انتخاب کنید.",
"caseCount": "{n} پرونده",
"attachmentCount": "{n} پیوست",
"caseSummary": "پرونده {n}: {type}",
"teethPrefix": "· دندان‌ها",
"moreCases": "+ {n} پرونده دیگر",
"previewDialogTitle": "پیش‌نمایش درمان",
"previewDialogSubtitle": "بررسی پرونده‌ها، پیوست‌ها و مقصدهای ارسال.",
"previewDialogSubtitlePhase4": "بررسی جزئیات درمان و پیوست‌ها.",
"previewLabDispatchHint": "برای ارسال کار به لابراتوار از بخش ارسال لاب در فضای کاری استفاده کنید.",
"noDetails": "جزئیات درمانی در این پیش‌نویس وجود ندارد.",
"noDetails": "هنوز جزئیات درمانی وجود ندارد.",
"noCases": "هیچ پرونده‌ای در این درمان وجود ندارد.",
"typeLabel": "نوع:",
"commentsLabel": "نظرات:",

View File

@@ -416,7 +416,6 @@
"loadingAppointments": "Afspraken laden...",
"selectDayWithAppointment": "Selecteer een dag met ten minste één afspraak.",
"confirmDiscard": "U heeft niet-opgeslagen wijzigingen. Wilt u deze negeren en doorgaan?",
"successDraftSaved": "Behandelconcept opgeslagen.",
"errorChooseOrg": "Kies ten minste één actieve organisatie om deze case te verzenden.",
"successCaseSent": "Case verzonden naar geselecteerde organisaties.",
"successFilesUploaded": "{count} bestand(en) succesvol geüpload.",
@@ -428,7 +427,7 @@
"errorSaveDraft": "Behandelconcept opslaan mislukt.",
"errorSendCase": "Case verzenden mislukt.",
"errorCaseMustSave": "Case moet worden opgeslagen voor verzending.",
"draftTitle": "Concept · {patientName}",
"treatmentPlanTitle": "Behandeling · {patientName}",
"hiddenMessage": "Afspraken zijn verborgen.",
"showAppointments": "Afspraken tonen",
"appointmentsTitle": "Mijn afspraken",
@@ -483,36 +482,30 @@
"successLabShipmentsSaved": "Labzendingen opgeslagen.",
"errorSaveLabShipments": "Labzendingen opslaan mislukt.",
"errorLabCaseNeedsDetails": "Selecteer minimaal één behandeldetail voor deze zending.",
"saveDraft": "Behandelconcept opslaan",
"unsavedChanges": "Niet-opgeslagen wijzigingen",
"draftSaved": "Concept opgeslagen",
"saveStatusSaving": "Opslaan…",
"saveStatusSaved": "Alle wijzigingen opgeslagen",
"saveStatusError": "Opslaan mislukt — controleer uw verbinding",
"sendSavesFirst": "Verzenden is per case en slaat eerst automatisch op.",
"historyTitle": "Eerdere behandelingen",
"historySubtitle": "Voltooide behandelingen voor deze patiënt. Elke case wordt afzonderlijk weergegeven.",
"historySubtitle": "Klik op een behandeling om te bekijken. Gebruik Open in de voorbeeldkkaart om deze in de werkruimte te laden.",
"loadingHistory": "Geschiedenis laden...",
"historyEmpty": "Geen eerdere behandelingen voor deze patiënt.",
"statusLabel": "Status:",
"historyCaseLabel": "Case {n} · {type}",
"historyEmpty": "Geen andere behandelingen voor deze patiënt geregistreerd.",
"historyDetailLabel": "Detail {n} · {type}",
"previewTitle": "Behandelvoorbeeld",
"openTreatment": "Openen",
"selectAppointment": "Selecteer een afspraak om de behandeling te bekijken.",
"detailCount": "{n} detail(s)",
"detailSummary": "Detail {n}: {type}",
"detailAttachmentCount": "{n, plural, one {# bestand} other {# bestanden}}",
"detailNotSentToLab": "Niet naar lab verzonden",
"detailPendingLabSend": "Dit labdetail is nog niet verzonden.",
"historicalReadonlyNotice": "U bekijkt een eerdere behandeling (alleen-lezen).",
"errorNoAppointmentForTreatment": "Deze behandeling heeft geen gekoppelde afspraak en kan niet worden geopend.",
"teethLabel": "Tanden:",
"teethNone": "Geen geselecteerd",
"reviewDetails": "Details bekijken",
"previewTitle": "Behandelvoorbeeld",
"previewDraft": "Bekijk huidig concept",
"selectAppointment": "Selecteer een afspraak om het concept te bekijken.",
"caseCount": "{n} case(s)",
"attachmentCount": "{n} bijlage(n)",
"caseSummary": "Case {n}: {type}",
"teethPrefix": "· Tanden",
"moreCases": "+ {n} meer case(s)",
"previewDialogTitle": "Behandelvoorbeeld",
"previewDialogSubtitle": "Bekijk casussen, bijlagen en verzendbestemmingen.",
"previewDialogSubtitlePhase4": "Bekijk behandeldetails en bijlagen.",
"previewLabDispatchHint": "Gebruik het lab-dispatchpaneel in de werkruimte om werk naar labs te sturen.",
"noCases": "Geen casussen in deze behandeling.",
"noDetails": "Geen behandeldetails in dit concept.",
"noDetails": "Nog geen behandeldetails.",
"typeLabel": "Type:",
"commentsLabel": "Opmerkingen:",
"commentsEmpty": "Opmerkingen: —",

View File

@@ -0,0 +1,43 @@
'use client';
import { useTranslations } from 'next-intl';
import { CaseSentLabel } from '@/components/ui/treatment/CaseSentLabel';
import { labNotSentBadgeClass, labSentBadgeClass } from '@/components/ui/treatment/treatmentStatusStyles';
import type { LinkedOrganizationOption, PastTreatmentDetail } from '@/types/treatment';
interface DetailLabSendBadgeProps {
detail: Pick<
PastTreatmentDetail,
'treatmentType' | 'sentAt' | 'sends' | 'destinationOrganizationId'
>;
labDependentCodes: Set<string>;
orgs?: LinkedOrganizationOption[];
className?: string;
}
export function DetailLabSendBadge({
detail,
labDependentCodes,
orgs,
className = '',
}: DetailLabSendBadgeProps) {
const t = useTranslations('treatment');
if (!labDependentCodes.has(detail.treatmentType)) {
return null;
}
if (detail.sentAt) {
return (
<CaseSentLabel
treatmentCase={detail}
orgs={orgs}
className={`${labSentBadgeClass} ${className}`.trim()}
/>
);
}
return (
<span className={`${labNotSentBadgeClass} ${className}`.trim()}>{t('detailNotSentToLab')}</span>
);
}

View File

@@ -1,39 +1,29 @@
'use client';
import { useTranslations } from 'next-intl';
import { FileText } from 'lucide-react';
import { TreatmentHistoryDetailLine } from '@/components/ui/treatment/TreatmentHistoryDetailLine';
import type { PastTreatment } from '@/types/treatment';
import { CaseSentLabel } from '@/components/ui/treatment/CaseSentLabel';
const TREATMENT_TYPE_KEYS = {
consultation: 'typeConsultation',
filling: 'typeFilling',
endo: 'typeEndo',
visit: 'typeVisit',
hygiene: 'typeHygiene',
} as const;
interface PastTreatmentsPanelProps {
items: PastTreatment[];
loading?: boolean;
onReviewTreatment?: (treatment: PastTreatment) => void;
selectedPreviewId?: string | null;
onSelectTreatment?: (treatment: PastTreatment) => void;
}
export function PastTreatmentsPanel({
items,
loading,
onReviewTreatment,
selectedPreviewId,
onSelectTreatment,
}: PastTreatmentsPanelProps) {
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
return (
<div className="surface-card p-4 space-y-3">
<div>
<h3 className="text-sm font-semibold text-text-primary">{t('historyTitle')}</h3>
<p className="text-[11px] text-text-muted mt-0.5">
{t('historySubtitle')}
</p>
<p className="text-[11px] text-text-muted mt-0.5">{t('historySubtitle')}</p>
</div>
{loading && <p className="text-sm text-text-muted">{t('loadingHistory')}</p>}
@@ -42,95 +32,60 @@ export function PastTreatmentsPanel({
<p className="text-sm text-text-muted">{t('historyEmpty')}</p>
)}
<div className="space-y-3 max-h-[min(420px,50vh)] overflow-y-auto pr-1">
{items.map((treatment) => (
<article
key={treatment.id}
className="border border-border/70 rounded-[var(--radius-md)] p-2.5 bg-background-secondary/40 space-y-2"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-sm font-medium text-text-primary truncate">{treatment.title}</p>
<p className="text-[11px] text-text-secondary capitalize mt-0.5">
{t('statusLabel')} {treatment.status}
</p>
</div>
<div className="space-y-1.5 max-h-[min(420px,50vh)] overflow-y-auto pr-1">
{items.map((treatment) => {
const isSelected = selectedPreviewId === treatment.id;
return (
<article
key={treatment.id}
role="button"
tabIndex={0}
onClick={() => onSelectTreatment?.(treatment)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onSelectTreatment?.(treatment);
}
}}
className={`
border rounded-[var(--radius-sm)] px-2 py-1.5 cursor-pointer transition-colors
focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/45
${
isSelected
? 'border-primary bg-primary/5'
: 'border-border/60 bg-background-secondary/30 hover:border-border hover:bg-background-secondary/50'
}
`}
>
<time
className="text-[11px] text-text-muted tabular-nums shrink-0"
className="text-xs font-medium text-text-primary tabular-nums block"
dateTime={treatment.treatmentAt}
>
{new Date(treatment.treatmentAt).toLocaleDateString()}
{new Date(treatment.treatmentAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</time>
</div>
<div className="space-y-1.5">
{treatment.details.map((c, idx) => {
const attachments = c.attachmentMetas ?? [];
const typeKey = TREATMENT_TYPE_KEYS[c.treatmentType as keyof typeof TREATMENT_TYPE_KEYS];
const typeLabel = typeKey ? t(typeKey) : c.treatmentType;
return (
<div
key={c.id}
className="border border-border/60 rounded-[var(--radius-sm)] px-2.5 py-2 bg-background-secondary/30 space-y-1"
>
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-medium text-text-primary capitalize">
{t('historyCaseLabel', { n: idx + 1, type: typeLabel })}
</p>
{c.sentAt && (
<CaseSentLabel
treatmentCase={c}
className="text-[10px] text-text-muted shrink-0 text-right"
/>
)}
{treatment.details.length === 0 ? (
<p className="text-[10px] text-text-muted mt-1">{t('noDetails')}</p>
) : (
<div className="mt-1.5 divide-y divide-border/50 border-t border-border/40 pointer-events-none">
{treatment.details.map((detail, idx) => (
<div key={detail.clientId ?? detail.id} className="py-1.5">
<TreatmentHistoryDetailLine
detail={detail}
detailNumber={idx + 1}
/>
</div>
<p className="text-[11px] text-text-secondary">
{t('teethLabel')} {c.teeth.length ? [...c.teeth].sort().join(', ') : t('teethNone')}
</p>
{c.notes?.trim() && (
<p className="text-[11px] text-text-muted line-clamp-2">{c.notes}</p>
)}
<div>
<p className="text-[10px] uppercase tracking-wide text-text-muted mb-1">
{t('attachments')}
</p>
{attachments.length === 0 ? (
<p className="text-[11px] text-text-muted">{tCommon('none')}</p>
) : (
<ul className="space-y-0.5">
{attachments.map((doc) => (
<li
key={doc.id}
className="flex items-center gap-1.5 text-[11px] text-text-secondary"
>
<FileText className="w-3 h-3 shrink-0 icon-flat" aria-hidden />
<span className="truncate">{doc.fileName}</span>
<span className="text-text-muted tabular-nums shrink-0">
{(doc.sizeBytes / 1024).toFixed(1)} KB
</span>
</li>
))}
</ul>
)}
</div>
</div>
);
})}
</div>
{onReviewTreatment && (
<div className="pt-1 flex justify-end">
<button
type="button"
onClick={() => onReviewTreatment(treatment)}
className="text-xs text-primary hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 rounded-[var(--radius-sm)] px-1"
>
{t('reviewDetails')}
</button>
</div>
)}
</article>
))}
))}
</div>
)}
</article>
);
})}
</div>
</div>
);

View File

@@ -0,0 +1,57 @@
'use client';
import { useTranslations } from 'next-intl';
import { DetailLabSendBadge } from '@/components/ui/treatment/DetailLabSendBadge';
import { TreatmentTypeBadge } from '@/components/ui/treatment/TreatmentTypeBadge';
import type { LinkedOrganizationOption, PastTreatmentDetail } from '@/types/treatment';
interface TreatmentDetailSummaryRowProps {
detail: PastTreatmentDetail;
detailNumber: number;
labDependentCodes: Set<string>;
orgs?: LinkedOrganizationOption[];
compact?: boolean;
}
export function TreatmentDetailSummaryRow({
detail,
detailNumber,
labDependentCodes,
orgs,
compact = false,
}: TreatmentDetailSummaryRowProps) {
const t = useTranslations('treatment');
const teeth = detail.teeth.length ? [...detail.teeth].sort().join(', ') : t('teethNone');
const attachmentCount = detail.attachmentMetas?.length ?? 0;
return (
<div
className={`rounded-[var(--radius-sm)] border border-border/60 bg-background-secondary/30 ${
compact ? 'px-2.5 py-2' : 'px-3 py-2'
} space-y-1`}
>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-1.5 min-w-0">
<span className={`text-text-muted tabular-nums ${compact ? 'text-[11px]' : 'text-xs'}`}>
{t('detailLabel', { n: detailNumber })}
</span>
<TreatmentTypeBadge type={detail.treatmentType} />
</div>
<DetailLabSendBadge detail={detail} labDependentCodes={labDependentCodes} orgs={orgs} />
</div>
<p className={`text-text-secondary ${compact ? 'text-[11px]' : 'text-xs'}`}>
{t('teethLabel')} {teeth}
</p>
{attachmentCount > 0 && (
<p className={`text-text-muted ${compact ? 'text-[11px]' : 'text-xs'}`}>
{t('detailAttachmentCount', { n: attachmentCount })}
</p>
)}
{detail.notes?.trim() && (
<p className={`text-text-muted line-clamp-2 ${compact ? 'text-[11px]' : 'text-xs'}`}>
{detail.notes}
</p>
)}
</div>
);
}

View File

@@ -4,6 +4,11 @@ import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { Dropdown } from '@/components/ui/shared/Dropdown';
import {
autosaveStatusClass,
labPendingBannerClass,
labSentBannerClass,
} from '@/components/ui/treatment/treatmentStatusStyles';
import type { TreatmentDetailDraft } from '@/types/treatment';
import { TREATMENT_TYPE_COLORS, treatmentTypeLabelKey } from '@/components/ui/treatment/treatmentTypeDisplay';
@@ -13,12 +18,12 @@ interface TreatmentDetailsEditorProps {
onActiveDetailChange: (id: string) => void;
onDetailsChange: (details: TreatmentDetailDraft[]) => void;
isDetailLocked: (detail: TreatmentDetailDraft) => boolean;
labDependentCodes: Set<string>;
disabled: boolean;
canEdit: boolean;
saveStatus: 'idle' | 'dirty' | 'saving' | 'saved' | 'error';
uploadBusy: boolean;
onAddDetail: () => void;
onPreview: () => void;
onUploadFiles: (files: FileList | null) => void;
}
@@ -28,16 +33,15 @@ export function TreatmentDetailsEditor({
onActiveDetailChange,
onDetailsChange,
isDetailLocked,
labDependentCodes,
disabled,
canEdit,
saveStatus,
uploadBusy,
onAddDetail,
onPreview,
onUploadFiles,
}: TreatmentDetailsEditorProps) {
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
const attachmentInputRef = useRef<HTMLInputElement>(null);
const activeDetail = details.find((d) => d.clientId === activeDetailId) ?? details[0];
@@ -46,6 +50,8 @@ export function TreatmentDetailsEditor({
const locked = isDetailLocked(activeDetail);
const readOnly = disabled || locked;
const treatmentTypeTextColor = TREATMENT_TYPE_COLORS[activeDetail.treatmentType];
const isLabDependent = labDependentCodes.has(activeDetail.treatmentType);
const showPendingLabHint = isLabDependent && !locked && !readOnly;
return (
<div className="surface-card p-4 space-y-4">
@@ -54,14 +60,9 @@ export function TreatmentDetailsEditor({
<h3 className="text-sm font-semibold text-text-primary">{t('detailsTitle')}</h3>
<p className="text-xs text-text-muted mt-0.5">{t('detailsSubtitle')}</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" variant="secondary" disabled={!canEdit || disabled} onClick={onPreview}>
{tCommon('preview')}
</Button>
<Button type="button" variant="primary" disabled={!canEdit || disabled} onClick={onAddDetail}>
{t('addDetail')}
</Button>
</div>
<Button type="button" variant="primary" disabled={!canEdit || disabled} onClick={onAddDetail}>
{t('addDetail')}
</Button>
</div>
<div className="flex flex-wrap gap-2">
@@ -88,9 +89,10 @@ export function TreatmentDetailsEditor({
<div className="space-y-4 border border-border/60 rounded-[var(--radius-md)] p-4 bg-background-secondary/30">
{locked && (
<p className="text-xs text-text-muted rounded-[var(--radius-sm)] border border-border/50 bg-background-secondary/50 px-2 py-1.5">
{t('detailLockedInShipment')}
</p>
<p className={labSentBannerClass}>{t('detailLockedInShipment')}</p>
)}
{showPendingLabHint && (
<p className={labPendingBannerClass}>{t('detailPendingLabSend')}</p>
)}
<label className="block text-xs font-medium text-text-secondary">
@@ -173,9 +175,7 @@ export function TreatmentDetailsEditor({
{canEdit && saveStatus !== 'idle' && (
<p
className={`text-xs pt-2 border-t border-border/60 ${
saveStatus === 'error' ? 'text-red-500' : 'text-text-muted'
}`}
className={`text-xs pt-2 border-t border-border/60 ${autosaveStatusClass(saveStatus)}`}
role="status"
aria-live="polite"
>

View File

@@ -0,0 +1,32 @@
'use client';
import { useTranslations } from 'next-intl';
import { TreatmentTypeBadge } from '@/components/ui/treatment/TreatmentTypeBadge';
import type { PastTreatmentDetail } from '@/types/treatment';
interface TreatmentHistoryDetailLineProps {
detail: PastTreatmentDetail;
detailNumber: number;
}
export function TreatmentHistoryDetailLine({
detail,
detailNumber,
}: TreatmentHistoryDetailLineProps) {
const t = useTranslations('treatment');
const teeth = detail.teeth.length ? [...detail.teeth].sort().join(', ') : t('teethNone');
const attachmentCount = detail.attachmentMetas?.length ?? 0;
return (
<div className="flex items-center gap-2 min-w-0 text-[11px] leading-tight">
<span className="text-text-muted tabular-nums shrink-0">{detailNumber}.</span>
<TreatmentTypeBadge type={detail.treatmentType} />
<span className="text-text-secondary truncate min-w-0">{teeth}</span>
{attachmentCount > 0 && (
<span className="text-text-muted shrink-0 tabular-nums">
{t('detailAttachmentCount', { n: attachmentCount })}
</span>
)}
</div>
);
}

View File

@@ -1,106 +0,0 @@
'use client';
import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { FileText } from 'lucide-react';
import { treatmentsApi } from '@/lib/api/treatments';
import type { TreatmentAttachmentMeta } from '@/types/treatment';
interface TreatmentLatestAttachmentPreviewProps {
attachment?: TreatmentAttachmentMeta | null;
className?: string;
}
function isImageMime(mimeType: string): boolean {
return mimeType.startsWith('image/');
}
function isPdfMime(mimeType: string): boolean {
return mimeType === 'application/pdf';
}
export function TreatmentLatestAttachmentPreview({
attachment,
className = '',
}: TreatmentLatestAttachmentPreviewProps) {
const tCommon = useTranslations('common');
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [loadFailed, setLoadFailed] = useState(false);
const [loading, setLoading] = useState(false);
const canRenderPreview = attachment
? isImageMime(attachment.mimeType) || isPdfMime(attachment.mimeType)
: false;
useEffect(() => {
if (!attachment || !canRenderPreview) {
setPreviewUrl(null);
setLoadFailed(false);
setLoading(false);
return;
}
let cancelled = false;
let objectUrl: string | null = null;
setLoading(true);
setLoadFailed(false);
setPreviewUrl(null);
void treatmentsApi
.getAttachmentFileBlob(attachment.id)
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
setPreviewUrl(objectUrl);
})
.catch(() => {
if (!cancelled) setLoadFailed(true);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [attachment, canRenderPreview]);
return (
<div
className={`aspect-square w-[6rem] shrink-0 overflow-hidden rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/50 ${className}`}
title={attachment?.fileName}
>
{!attachment ? (
<div className="flex h-full w-full items-center justify-center text-[10px] text-text-muted">
{tCommon('none')}
</div>
) : loading ? (
<div className="flex h-full w-full items-center justify-center text-[10px] text-text-muted">
{tCommon('loadingEllipsis')}
</div>
) : loadFailed || !canRenderPreview || !previewUrl ? (
<div className="flex h-full w-full flex-col items-center justify-center gap-1 p-1.5 text-center">
<FileText className="h-4 w-4 shrink-0 icon-flat text-text-muted" aria-hidden />
<span className="line-clamp-2 text-[9px] leading-tight text-text-secondary">
{attachment.fileName}
</span>
</div>
) : isImageMime(attachment.mimeType) ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={previewUrl}
alt={attachment.fileName}
className="h-full w-full object-fill"
/>
) : (
<iframe
src={previewUrl}
title={attachment.fileName}
className="h-full w-full border-0"
/>
)}
</div>
);
}

View File

@@ -2,71 +2,61 @@
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import type { PastTreatment } from '@/types/treatment';
const TREATMENT_TYPE_KEYS = {
consultation: 'typeConsultation',
filling: 'typeFilling',
endo: 'typeEndo',
visit: 'typeVisit',
hygiene: 'typeHygiene',
} as const;
import { TreatmentDetailSummaryRow } from '@/components/ui/treatment/TreatmentDetailSummaryRow';
import type { LinkedOrganizationOption, PastTreatment } from '@/types/treatment';
interface TreatmentPreviewCardProps {
draft: PastTreatment | null;
disabled?: boolean;
onPreview: () => void;
treatment: PastTreatment | null;
labDependentCodes: Set<string>;
orgs?: LinkedOrganizationOption[];
openDisabled?: boolean;
onOpen: () => void;
}
export function TreatmentPreviewCard({ draft, disabled, onPreview }: TreatmentPreviewCardProps) {
export function TreatmentPreviewCard({
treatment,
labDependentCodes,
orgs,
openDisabled = false,
onOpen,
}: TreatmentPreviewCardProps) {
const t = useTranslations('treatment');
const attachmentCount = draft
? draft.details.reduce((n, c) => n + (c.attachmentMetas?.length ?? 0), 0)
: 0;
return (
<div className="surface-card p-4 space-y-3">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-text-primary">{t('previewTitle')}</h3>
<Button type="button" variant="primary" disabled={disabled || !draft} onClick={onPreview}>
{t('previewDraft')}
<Button type="button" variant="primary" disabled={openDisabled || !treatment} onClick={onOpen}>
{t('openTreatment')}
</Button>
</div>
{!draft ? (
{!treatment ? (
<p className="text-sm text-text-muted">{t('selectAppointment')}</p>
) : (
<div className="border border-border/70 rounded-[var(--radius-md)] p-3 bg-background-secondary/40 space-y-2">
<div className="flex items-start justify-between gap-2">
<p className="text-sm font-medium text-text-primary">{draft.title}</p>
<span className="text-xs text-text-muted tabular-nums shrink-0 capitalize">{draft.status}</span>
<p className="text-sm font-medium text-text-primary">{treatment.title}</p>
<time
className="text-xs text-text-muted tabular-nums shrink-0"
dateTime={treatment.treatmentAt}
>
{new Date(treatment.treatmentAt).toLocaleDateString()}
</time>
</div>
<p className="text-xs text-text-secondary">
{t('caseCount', { n: draft.details.length })} ·{' '}
{t('attachmentCount', { n: attachmentCount })}
</p>
<div className="space-y-2">
{draft.details.slice(0, 2).map((c, idx) => {
const typeKey = TREATMENT_TYPE_KEYS[c.treatmentType as keyof typeof TREATMENT_TYPE_KEYS];
const typeLabel = typeKey ? t(typeKey) : c.treatmentType;
return (
<div
key={c.id}
className="rounded-[var(--radius-sm)] border border-border/60 px-2.5 py-2 text-xs text-text-secondary"
>
<span className="text-text-primary font-medium capitalize">
{t('caseSummary', { n: idx + 1, type: typeLabel })}
</span>
{c.teeth.length > 0 && (
<span className="ml-1 tabular-nums">
{t('teethPrefix')} {[...c.teeth].sort().join(', ')}
</span>
)}
</div>
);
})}
{draft.details.length > 2 && (
<p className="text-xs text-text-muted">{t('moreCases', { n: draft.details.length - 2 })}</p>
<div className="space-y-2 max-h-[min(280px,40vh)] overflow-y-auto pr-1">
{treatment.details.length === 0 ? (
<p className="text-xs text-text-muted">{t('noDetails')}</p>
) : (
treatment.details.map((detail, idx) => (
<TreatmentDetailSummaryRow
key={detail.clientId ?? detail.id}
detail={detail}
detailNumber={idx + 1}
labDependentCodes={labDependentCodes}
orgs={orgs}
compact
/>
))
)}
</div>
</div>

View File

@@ -1,180 +0,0 @@
'use client';
import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Loader2, Paperclip } from 'lucide-react';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import type { LinkedOrganizationOption, PastTreatment, PastTreatmentCase } from '@/types/treatment';
import { CaseSentLabel } from '@/components/ui/treatment/CaseSentLabel';
import { TreatmentLatestAttachmentPreview } from '@/components/ui/treatment/TreatmentLatestAttachmentPreview';
import { treatmentTypeLabelKey } from '@/components/ui/treatment/treatmentTypeDisplay';
export type TreatmentPreviewMode = 'readonly' | 'editable';
interface TreatmentPreviewDialogProps {
open: boolean;
onClose: () => void;
treatment: PastTreatment | null;
mode: TreatmentPreviewMode;
orgs?: LinkedOrganizationOption[];
uploadBusyCaseId?: string | null;
onAttach?: (caseKey: string, files: FileList) => void | Promise<void>;
}
function caseKey(c: PastTreatmentCase): string {
return c.clientId ?? c.id;
}
const caseActionIconClass =
'inline-flex items-center justify-center rounded-[var(--radius-sm)] p-1.5 text-text-secondary transition-colors hover:bg-background-card/80 hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40';
export function TreatmentPreviewDialog({
open,
onClose,
treatment,
mode,
orgs = [],
uploadBusyCaseId,
onAttach,
}: TreatmentPreviewDialogProps) {
const t = useTranslations('treatment');
const fileInputsRef = useRef<Record<string, HTMLInputElement | null>>({});
if (!open || !treatment) return null;
const editable = mode === 'editable';
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div
className="w-full max-w-[min(56rem,calc(100vw-15rem))] max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
role="dialog"
aria-modal="true"
aria-labelledby="treatment-preview-title"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h2 id="treatment-preview-title" className="text-lg font-semibold text-text-primary pr-2">
{t('previewDialogTitle')}
</h2>
<p className="text-xs text-text-muted mt-0.5">{t('previewDialogSubtitlePhase4')}</p>
</div>
<DialogCloseButton onClick={onClose} />
</div>
<div className="border border-border/70 rounded-[var(--radius-md)] p-4 bg-background-secondary/40 space-y-3">
<div className="flex items-start justify-between gap-2">
<p className="text-sm font-medium text-text-primary">{treatment.title}</p>
<span className="text-xs text-text-muted tabular-nums shrink-0">
{new Date(treatment.treatmentAt).toLocaleDateString()}
</span>
</div>
<p className="text-xs text-text-secondary capitalize">
{t('statusLabel')} {treatment.status}
</p>
{editable && (
<p className="text-xs text-text-muted">{t('previewLabDispatchHint')}</p>
)}
{treatment.details.length === 0 ? (
<p className="text-sm text-text-muted">{t('noDetails')}</p>
) : (
<div className="space-y-2">
{treatment.details.map((c, idx) => {
const key = caseKey(c);
const attachments = c.attachmentMetas ?? [];
const latestAttachment =
attachments.length > 0 ? attachments[attachments.length - 1] : null;
const sent = Boolean(c.sentAt);
const actionsEnabled = editable && !sent;
const comment = c.notes?.trim() ?? '';
const attachBusy = uploadBusyCaseId === key;
const typeKey = treatmentTypeLabelKey(c.treatmentType);
const typeLabel = t(typeKey as 'typeConsultation');
return (
<div
key={key}
className="rounded-[var(--radius-md)] border border-border/60 px-3 py-2 bg-background-secondary/30"
>
<div className="grid grid-cols-[minmax(0,1fr)_auto] gap-x-4 gap-y-1">
<div className="min-w-0 space-y-0.5">
<div className="flex items-center gap-2">
<p className="text-xs font-medium text-text-primary">
{t('detailLabel', { n: idx + 1 })}
</p>
{actionsEnabled && onAttach && (
<div className="flex items-center gap-0.5">
<input
ref={(el) => {
fileInputsRef.current[key] = el;
}}
type="file"
multiple
className="sr-only"
aria-hidden
onChange={(e) => {
if (e.target.files?.length) {
void onAttach(key, e.target.files);
}
e.target.value = '';
}}
/>
<button
type="button"
className={caseActionIconClass}
disabled={attachBusy}
aria-label={t('attachFilesShort')}
title={t('attachFilesShort')}
onClick={() => fileInputsRef.current[key]?.click()}
>
{attachBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
) : (
<Paperclip className="h-3.5 w-3.5" aria-hidden />
)}
</button>
</div>
)}
</div>
<p className="text-[11px] text-text-secondary capitalize">
{t('typeLabel')} {typeLabel}
</p>
<p className="text-[11px] text-text-secondary">
{t('teethLabel')}{' '}
{c.teeth.length ? [...c.teeth].sort().join(', ') : t('teethNone')}
</p>
{comment ? (
<p className="text-[11px] text-text-muted line-clamp-2" title={comment}>
{t('commentsLabel')} {comment}
</p>
) : (
<p className="text-text-muted text-[11px]">{t('commentsEmpty')}</p>
)}
</div>
<div className="flex min-w-[6rem] flex-col items-end gap-1">
{sent && (
<CaseSentLabel
treatmentCase={c}
orgs={orgs}
className="text-[10px] text-text-muted text-right"
/>
)}
<p className="text-[10px] uppercase tracking-wide text-text-muted">
{t('attachments')}
</p>
<TreatmentLatestAttachmentPreview attachment={latestAttachment} />
</div>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
'use client';
import { useTranslations } from 'next-intl';
import { purposeStyle } from '@/components/ui/appointments/appointmentPurposeStyles';
import { TREATMENT_TYPE_KEYS, treatmentTypeLabelKey } from '@/components/ui/treatment/treatmentTypeDisplay';
interface TreatmentTypeBadgeProps {
type: string;
className?: string;
}
export function TreatmentTypeBadge({ type, className = '' }: TreatmentTypeBadgeProps) {
const t = useTranslations('treatment');
const typeKey = treatmentTypeLabelKey(type);
const label =
type in TREATMENT_TYPE_KEYS ? t(typeKey as 'typeEndo') : type;
return (
<span
className={`inline-flex items-center justify-center box-border rounded-md border min-h-[1.75rem] px-2.5 py-1 text-xs font-medium capitalize leading-none shrink-0 ${purposeStyle(type)} ${className}`.trim()}
>
{label}
</span>
);
}

View File

@@ -8,10 +8,6 @@ import { LabCasesDispatchPanel } from '@/components/ui/treatment/LabCasesDispatc
import { PastTreatmentsPanel } from '@/components/ui/treatment/PastTreatmentsPanel';
import { TreatmentDetailsEditor } from '@/components/ui/treatment/TreatmentDetailsEditor';
import { TreatmentPreviewCard } from '@/components/ui/treatment/TreatmentPreviewCard';
import {
TreatmentPreviewDialog,
type TreatmentPreviewMode,
} from '@/components/ui/treatment/TreatmentPreviewDialog';
import { ToastStack } from '@/components/ui/shared/Toast';
import { treatmentTypeLabelKey } from '@/components/ui/treatment/treatmentTypeDisplay';
import {
@@ -40,6 +36,57 @@ import type {
TreatmentDetailDraft,
} from '@/types/treatment';
type WorkspaceMode = 'live' | 'historical';
function isTreatmentDayHistorical(treatmentAt: string, todayStart: Date): boolean {
return compareLocalDayStart(new Date(treatmentAt), todayStart) < 0;
}
function labCaseDraftsToPast(
labCaseDrafts: LabCaseDraft[],
details: TreatmentDetailDraft[],
): PastLabCase[] {
return labCaseDrafts.map((lc) => ({
id: lc.id ?? lc.clientId,
clientId: lc.clientId,
destinationOrganizationId: lc.destinationOrganizationId,
labComment: lc.labComment || null,
sentAt: lc.sentAt ?? null,
treatmentDetailIds: lc.detailClientIds
.map((cid) => details.find((d) => d.clientId === cid)?.id)
.filter((id): id is string => Boolean(id)),
details: lc.detailClientIds.map((cid) => {
const d = details.find((x) => x.clientId === cid);
return {
id: d?.id ?? cid,
clientId: cid,
treatmentType: d?.treatmentType ?? 'consultation',
teeth: d?.teeth ?? [],
};
}),
sends: lc.sends ?? [],
}));
}
function buildWorkspaceSnapshot(
appointment: TreatmentAppointment,
details: TreatmentDetailDraft[],
labCaseDrafts: LabCaseDraft[],
title: string,
id?: string,
): PastTreatment {
return {
...detailsToPreviewTreatment(details, {
id: id ?? `preview-${appointment.id}`,
title,
patientId: appointment.patientId,
treatmentAt: appointment.startAt,
}),
appointmentId: appointment.id,
labCases: labCaseDraftsToPast(labCaseDrafts, details),
};
}
function newDetail(): TreatmentDetailDraft {
return {
clientId:
@@ -134,14 +181,13 @@ function isDetailsDirty(
function detailsToPreviewTreatment(
details: TreatmentDetailDraft[],
meta: { title: string; patientId: string; treatmentAt: string; status: string; id?: string },
meta: { title: string; patientId: string; treatmentAt: string; id?: string },
): PastTreatment {
return {
id: meta.id ?? 'current-draft',
patientId: meta.patientId,
title: meta.title,
treatmentAt: meta.treatmentAt,
status: meta.status,
details: details.map((d, idx) => ({
id: d.id ?? d.clientId ?? `draft-${idx + 1}`,
clientId: d.clientId,
@@ -181,6 +227,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
const [history, setHistory] = useState<PastTreatment[]>([]);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyPatientId, setHistoryPatientId] = useState<string | null>(null);
const [orgs, setOrgs] = useState<LinkedOrganizationOption[]>([]);
const [labDependentCodes, setLabDependentCodes] = useState<Set<string>>(new Set());
@@ -191,6 +238,8 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
const [activeLabCaseId, setActiveLabCaseId] = useState<string | null>(null);
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
const [saveStatus, setSaveStatus] = useState<'idle' | 'dirty' | 'saving' | 'saved' | 'error'>('idle');
const [selectedPreviewId, setSelectedPreviewId] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>('live');
const selectionLockedRef = useRef(selectionLocked);
selectionLockedRef.current = selectionLocked;
@@ -203,16 +252,17 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
const saveInFlightRef = useRef(false);
const saveQueuedRef = useRef(false);
const draftHydratingRef = useRef(false);
const workspaceModeRef = useRef(workspaceMode);
workspaceModeRef.current = workspaceMode;
const labCaseDraftsRef = useRef(labCaseDrafts);
labCaseDraftsRef.current = labCaseDrafts;
const skipNextGetDraftRef = useRef(false);
const [sendBusyId, setSendBusyId] = useState<string | null>(null);
const [uploadBusyDetailId, setUploadBusyDetailId] = useState<string | null>(null);
const [organizationSearch, setOrganizationSearch] = useState('');
const [recentOrganizationIds, setRecentOrganizationIds] = useState<string[]>([]);
const [previewOpen, setPreviewOpen] = useState(false);
const [previewTreatment, setPreviewTreatment] = useState<PastTreatment | null>(null);
const [previewMode, setPreviewMode] = useState<TreatmentPreviewMode>('readonly');
const isDetailLocked = useCallback(
(detail: TreatmentDetailDraft) =>
labCaseDrafts.some((lc) => lc.sentAt && lc.detailClientIds.includes(detail.clientId)),
@@ -236,7 +286,66 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
[selectedDay, todayStart],
);
const canEditTreatmentForDay = canEdit && Boolean(selectedAppointment) && !isViewingPastDay;
const canEditTreatmentForDay =
canEdit &&
Boolean(selectedAppointment) &&
!isViewingPastDay &&
workspaceMode === 'live';
const historyPanelItems = useMemo(() => {
return history.filter((item) => {
if (
workspaceMode === 'live' &&
selectedAppointmentId &&
item.appointmentId === selectedAppointmentId
) {
return false;
}
return true;
});
}, [history, selectedAppointmentId, workspaceMode]);
const currentDraftPreview = useMemo<PastTreatment | null>(() => {
if (!selectedAppointment) return null;
return buildWorkspaceSnapshot(
selectedAppointment,
details,
labCaseDrafts,
t('treatmentPlanTitle', {
patientName: `${selectedAppointment.patientFirstName} ${selectedAppointment.patientLastName}`,
}),
'current-draft',
);
}, [details, labCaseDrafts, selectedAppointment, t]);
const previewTreatment = useMemo(() => {
if (!selectedPreviewId) return currentDraftPreview;
return historyPanelItems.find((item) => item.id === selectedPreviewId) ?? currentDraftPreview;
}, [selectedPreviewId, historyPanelItems, currentDraftPreview]);
const isPreviewAlreadyOpen = useMemo(() => {
if (!previewTreatment?.appointmentId || !selectedAppointmentId) return false;
if (selectedAppointmentId !== previewTreatment.appointmentId) return false;
if (workspaceMode === 'historical') return true;
if (workspaceMode === 'live' && selectedPreviewId === null) return true;
if (workspaceMode === 'live' && selectedPreviewId === previewTreatment.id) return true;
return false;
}, [previewTreatment, selectedAppointmentId, workspaceMode, selectedPreviewId]);
const hydrateFromTreatment = useCallback((treatment: PastTreatment) => {
const mapped = treatment.details.map(mapDetailFromApi);
setDetails(mapped);
setActiveDetailId((prev) => {
const stillExists = mapped.some((d) => d.clientId === prev);
return stillExists ? prev : mapped[0]?.clientId ?? prev;
});
setSavedSnapshot(serializeDetails(mapped));
const mappedLabCases = (treatment.labCases ?? []).map(mapLabCaseDraftFromApi);
setLabCaseDrafts(mappedLabCases);
setActiveLabCaseId(mappedLabCases[0]?.clientId ?? null);
setOrganizationSearch('');
setSaveStatus('idle');
}, []);
const activeDetail = useMemo(
() => details.find((d) => d.clientId === activeDetailId) ?? details[0],
@@ -245,18 +354,6 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
const selectedTeethSet = useMemo(() => new Set(activeDetail?.teeth ?? []), [activeDetail?.teeth]);
const currentDraftPreview = useMemo<PastTreatment | null>(() => {
if (!selectedAppointment) return null;
return detailsToPreviewTreatment(details, {
title: t('draftTitle', {
patientName: `${selectedAppointment.patientFirstName} ${selectedAppointment.patientLastName}`,
}),
patientId: selectedAppointment.patientId,
treatmentAt: new Date().toISOString(),
status: 'draft',
});
}, [details, selectedAppointment, t]);
useEffect(() => {
setSelectionLocked(false);
}, [selectedDay]);
@@ -332,15 +429,18 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
}, [showError, t]);
useEffect(() => {
if (!selectedAppointment) {
setHistory([]);
return;
if (selectedAppointment?.patientId) {
setHistoryPatientId(selectedAppointment.patientId);
}
}, [selectedAppointment?.patientId]);
useEffect(() => {
if (!historyPatientId) return;
let cancelled = false;
setHistoryLoading(true);
void (async () => {
try {
const response = await treatmentsApi.listPatientHistory(selectedAppointment.patientId);
const response = await treatmentsApi.listPatientHistory(historyPatientId);
if (!cancelled) setHistory(response.data);
} catch (error: unknown) {
if (!cancelled) {
@@ -353,11 +453,16 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
return () => {
cancelled = true;
};
}, [selectedAppointment?.patientId, showError, t]);
}, [historyPatientId, showError, t]);
useEffect(() => {
const appointmentId = selectedAppointment?.id;
if (!appointmentId) return;
if (!appointmentId || workspaceMode !== 'live') return;
if (skipNextGetDraftRef.current) {
skipNextGetDraftRef.current = false;
return;
}
let cancelled = false;
draftHydratingRef.current = true;
@@ -405,7 +510,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
cancelled = true;
draftHydratingRef.current = false;
};
}, [selectedAppointment?.id, showError, t]);
}, [selectedAppointment?.id, workspaceMode, showError, t]);
const persistDraft = useCallback(
async (options?: { force?: boolean }) => {
@@ -416,12 +521,11 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
if (!options?.force && !dirty) {
return detailsToPreviewTreatment(currentDetails, {
title: t('draftTitle', {
title: t('treatmentPlanTitle', {
patientName: `${selectedAppointment.patientFirstName} ${selectedAppointment.patientLastName}`,
}),
patientId: selectedAppointment.patientId,
treatmentAt: selectedAppointment.startAt,
status: 'draft',
});
}
@@ -479,13 +583,24 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
}
}, [selectedAppointment, persistDraft, showError, t]);
const refreshHistory = useCallback(async (patientId: string) => {
try {
const response = await treatmentsApi.listPatientHistory(patientId);
setHistory(response.data);
} catch (error: unknown) {
showError(formatApiErrorMessage(error, t('errorLoadHistory')));
}
}, [showError, t]);
const flushDraftSave = useCallback(async (): Promise<boolean> => {
if (autosaveTimerRef.current) {
clearTimeout(autosaveTimerRef.current);
autosaveTimerRef.current = null;
}
if (!selectedAppointment || !canEditTreatmentForDay) return true;
if (workspaceModeRef.current !== 'live' || !selectedAppointment || !canEditTreatmentForDay) {
return true;
}
while (saveInFlightRef.current) {
await new Promise((resolve) => setTimeout(resolve, 50));
@@ -497,11 +612,14 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
try {
await runDraftSave();
if (historyPatientId) {
await refreshHistory(historyPatientId);
}
return true;
} catch {
return window.confirm(t('confirmDiscard'));
}
}, [selectedAppointment, canEditTreatmentForDay, runDraftSave, t]);
}, [selectedAppointment, canEditTreatmentForDay, runDraftSave, historyPatientId, refreshHistory, t]);
useEffect(() => {
if (draftHydratingRef.current || !canEditTreatmentForDay || !selectedAppointment?.id) {
@@ -528,16 +646,22 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
};
}, [details, isDirty, canEditTreatmentForDay, selectedAppointment?.id, runDraftSave]);
const resetToLiveContext = useCallback(() => {
setWorkspaceMode('live');
setSelectedPreviewId(null);
}, []);
const onPickAppointment = useCallback(
(id: string) => {
void (async () => {
const ok = await flushDraftSave();
if (!ok) return;
resetToLiveContext();
setSelectionLocked(true);
setSelectedAppointmentId(id);
})();
},
[flushDraftSave],
[flushDraftSave, resetToLiveContext],
);
const onSelectDay = useCallback(
@@ -545,12 +669,56 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
void (async () => {
const ok = await flushDraftSave();
if (!ok) return;
const patientIdToRefresh = historyPatientId;
resetToLiveContext();
setSelectedDay(day);
if (patientIdToRefresh) {
await refreshHistory(patientIdToRefresh);
}
})();
},
[flushDraftSave],
[flushDraftSave, resetToLiveContext, historyPatientId, refreshHistory],
);
const handleSelectPreviewTreatment = useCallback((treatment: PastTreatment) => {
setSelectedPreviewId(treatment.id);
}, []);
const handleOpenTreatment = useCallback(() => {
void (async () => {
const treatment = previewTreatment;
if (!treatment?.appointmentId) {
showError(t('errorNoAppointmentForTreatment'));
return;
}
if (isPreviewAlreadyOpen) return;
const ok = workspaceModeRef.current === 'live' ? await flushDraftSave() : true;
if (!ok) return;
const isHistorical = isTreatmentDayHistorical(treatment.treatmentAt, todayStart);
setWorkspaceMode(isHistorical ? 'historical' : 'live');
setSelectedPreviewId(treatment.id);
setSelectedDay(startOfLocalDay(new Date(treatment.treatmentAt)));
setSelectionLocked(true);
setSelectedAppointmentId(treatment.appointmentId);
skipNextGetDraftRef.current = true;
draftHydratingRef.current = true;
hydrateFromTreatment(treatment);
draftHydratingRef.current = false;
})();
}, [
previewTreatment,
isPreviewAlreadyOpen,
flushDraftSave,
hydrateFromTreatment,
showError,
t,
todayStart,
]);
const uploadForDetail = useCallback(
async (detailClientId: string, files: FileList | File[]) => {
if (!canEditTreatmentForDay || !selectedAppointment) return;
@@ -685,17 +853,6 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
],
);
const openPreview = useCallback((treatment: PastTreatment, mode: TreatmentPreviewMode) => {
setPreviewTreatment(treatment);
setPreviewMode(mode);
setPreviewOpen(true);
}, []);
const openCurrentDraftPreview = useCallback(() => {
if (!currentDraftPreview) return;
openPreview(currentDraftPreview, canEditTreatmentForDay ? 'editable' : 'readonly');
}, [currentDraftPreview, canEditTreatmentForDay, openPreview]);
if (!canView) {
return (
<div className="surface-card p-6 max-w-xl">
@@ -727,7 +884,13 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
loading={apptsLoading}
/>
{isViewingPastDay && (
{workspaceMode === 'historical' && (
<p className="text-sm text-emerald-700 dark:text-emerald-400 rounded-[var(--radius-md)] border border-emerald-500/40 bg-emerald-500/10 px-3 py-2">
{t('historicalReadonlyNotice')}
</p>
)}
{isViewingPastDay && workspaceMode === 'live' && (
<p className="text-sm text-text-secondary rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/50 px-3 py-2">
{t('pastDayNotice')}
</p>
@@ -757,15 +920,18 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
)}
<TreatmentPreviewCard
draft={currentDraftPreview}
disabled={!selectedAppointment}
onPreview={openCurrentDraftPreview}
treatment={previewTreatment}
labDependentCodes={labDependentCodes}
orgs={orgs}
openDisabled={isPreviewAlreadyOpen}
onOpen={handleOpenTreatment}
/>
<PastTreatmentsPanel
items={history}
items={historyPanelItems}
loading={historyLoading}
onReviewTreatment={(item) => openPreview(item, 'readonly')}
selectedPreviewId={selectedPreviewId}
onSelectTreatment={handleSelectPreviewTreatment}
/>
</div>
@@ -793,6 +959,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
onActiveDetailChange={setActiveDetailId}
onDetailsChange={setDetails}
isDetailLocked={isDetailLocked}
labDependentCodes={labDependentCodes}
disabled={!canEditTreatmentForDay}
canEdit={canEdit}
saveStatus={saveStatus}
@@ -802,7 +969,6 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
setDetails((prev) => [...prev, next]);
setActiveDetailId(next.clientId);
}}
onPreview={openCurrentDraftPreview}
onUploadFiles={(files) => void uploadForDetail(activeDetailId, files ?? [])}
/>
@@ -839,18 +1005,6 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
/>
</div>
</div>
<TreatmentPreviewDialog
open={previewOpen}
onClose={() => setPreviewOpen(false)}
treatment={
previewMode === 'editable' && currentDraftPreview ? currentDraftPreview : previewTreatment
}
mode={previewMode}
orgs={orgs}
uploadBusyCaseId={uploadBusyDetailId}
onAttach={(caseKey, files) => uploadForDetail(caseKey, files)}
/>
</div>
);
}

View File

@@ -0,0 +1,26 @@
export const labSentBadgeClass =
'inline-flex items-center rounded-[var(--radius-sm)] border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[11px] font-medium text-emerald-600 dark:text-emerald-400';
export const labNotSentBadgeClass =
'inline-flex items-center rounded-[var(--radius-sm)] border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 dark:text-amber-400';
export const labSentBannerClass =
'text-xs rounded-[var(--radius-sm)] border border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 px-2 py-1.5';
export const labPendingBannerClass =
'text-xs rounded-[var(--radius-sm)] border border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400 px-2 py-1.5';
export function autosaveStatusClass(status: 'dirty' | 'saving' | 'saved' | 'error'): string {
switch (status) {
case 'dirty':
return 'text-amber-600 dark:text-amber-400';
case 'saving':
return 'text-text-muted animate-pulse';
case 'saved':
return 'text-emerald-600 dark:text-emerald-400';
case 'error':
return 'text-red-500';
default:
return 'text-text-muted';
}
}

View File

@@ -108,7 +108,6 @@ export interface PastTreatment {
appointmentId?: string | null;
title: string;
treatmentAt: string;
status: string;
details: PastTreatmentDetail[];
labCases: PastLabCase[];
documents: TreatmentAttachmentMeta[];