feature: Phase4 - Clinic two-step treatment UI
This commit is contained in:
@@ -4,14 +4,16 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { AppointmentsStrip } from '@/components/ui/treatment/AppointmentsStrip';
|
||||
import { FdiToothChart } from '@/components/ui/treatment/FdiToothChart';
|
||||
import { LabCasesDispatchPanel } from '@/components/ui/treatment/LabCasesDispatchPanel';
|
||||
import { PastTreatmentsPanel } from '@/components/ui/treatment/PastTreatmentsPanel';
|
||||
import { TreatmentCasesEditor } from '@/components/ui/treatment/TreatmentCasesEditor';
|
||||
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 {
|
||||
addCalendarDays,
|
||||
compareLocalDayStart,
|
||||
@@ -19,6 +21,7 @@ import {
|
||||
startOfLocalDay,
|
||||
} from '@/components/appointments/appointmentTime';
|
||||
import { appointmentsApi } from '@/lib/api/appointments';
|
||||
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
|
||||
import { treatmentsApi } from '@/lib/api/treatments';
|
||||
import { pickAutoAppointment } from '@/components/shared/treatmentSelection';
|
||||
import { canEditTreatment, canViewTreatment } from '@/components/shared/permissions';
|
||||
@@ -28,27 +31,21 @@ import type { Organization } from '@/types/organization';
|
||||
import type { AppointmentRecord } from '@/types/appointment';
|
||||
import type {
|
||||
FdiToothId,
|
||||
LabCaseDraft,
|
||||
LinkedOrganizationOption,
|
||||
PastLabCase,
|
||||
PastTreatment,
|
||||
PastTreatmentCase,
|
||||
TreatmentAppointment,
|
||||
TreatmentCaseDraft,
|
||||
TreatmentDetailDraft,
|
||||
} from '@/types/treatment';
|
||||
|
||||
const TREATMENT_TYPE_KEYS = {
|
||||
consultation: 'typeConsultation',
|
||||
filling: 'typeFilling',
|
||||
endo: 'typeEndo',
|
||||
visit: 'typeVisit',
|
||||
hygiene: 'typeHygiene',
|
||||
} as const;
|
||||
|
||||
function newCase(): TreatmentCaseDraft {
|
||||
function newDetail(): TreatmentDetailDraft {
|
||||
return {
|
||||
clientId:
|
||||
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID()
|
||||
: `case-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
: `detail-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
treatmentType: 'consultation',
|
||||
teeth: [],
|
||||
comment: '',
|
||||
@@ -58,6 +55,20 @@ function newCase(): TreatmentCaseDraft {
|
||||
};
|
||||
}
|
||||
|
||||
function newLabCaseDraft(): LabCaseDraft {
|
||||
return {
|
||||
clientId:
|
||||
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID()
|
||||
: `lab-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
destinationOrganizationId: null,
|
||||
labComment: '',
|
||||
detailClientIds: [],
|
||||
sentAt: null,
|
||||
sends: [],
|
||||
};
|
||||
}
|
||||
|
||||
function mapAppointment(record: AppointmentRecord): TreatmentAppointment {
|
||||
return {
|
||||
id: record.id,
|
||||
@@ -71,7 +82,7 @@ function mapAppointment(record: AppointmentRecord): TreatmentAppointment {
|
||||
};
|
||||
}
|
||||
|
||||
function mapDetailFromApi(d: PastTreatmentCase): TreatmentCaseDraft {
|
||||
function mapDetailFromApi(d: PastTreatmentCase): TreatmentDetailDraft {
|
||||
return {
|
||||
clientId: d.clientId,
|
||||
id: d.id,
|
||||
@@ -86,23 +97,33 @@ function mapDetailFromApi(d: PastTreatmentCase): TreatmentCaseDraft {
|
||||
};
|
||||
}
|
||||
|
||||
function serializeCases(cases: TreatmentCaseDraft[]) {
|
||||
function mapLabCaseDraftFromApi(lc: PastLabCase): LabCaseDraft {
|
||||
return {
|
||||
clientId: lc.clientId,
|
||||
id: lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId,
|
||||
labComment: lc.labComment ?? '',
|
||||
detailClientIds: lc.details.map((d) => d.clientId),
|
||||
sentAt: lc.sentAt ?? null,
|
||||
sends: lc.sends ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function serializeDetails(details: TreatmentDetailDraft[]) {
|
||||
return JSON.stringify(
|
||||
cases.map((c) => ({
|
||||
clientId: c.clientId,
|
||||
id: c.id,
|
||||
treatmentType: c.treatmentType,
|
||||
teeth: c.teeth,
|
||||
comment: c.comment,
|
||||
attachmentMetas: c.attachmentMetas,
|
||||
sendToOrganizationIds: c.sendToOrganizationIds,
|
||||
sentAt: c.sentAt,
|
||||
details.map((d) => ({
|
||||
clientId: d.clientId,
|
||||
id: d.id,
|
||||
treatmentType: d.treatmentType,
|
||||
teeth: d.teeth,
|
||||
comment: d.comment,
|
||||
attachmentMetas: d.attachmentMetas,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function casesToPreviewTreatment(
|
||||
cases: TreatmentCaseDraft[],
|
||||
function detailsToPreviewTreatment(
|
||||
details: TreatmentDetailDraft[],
|
||||
meta: { title: string; patientId: string; treatmentAt: string; status: string; id?: string },
|
||||
): PastTreatment {
|
||||
return {
|
||||
@@ -111,17 +132,17 @@ function casesToPreviewTreatment(
|
||||
title: meta.title,
|
||||
treatmentAt: meta.treatmentAt,
|
||||
status: meta.status,
|
||||
details: cases.map((c, idx) => ({
|
||||
id: c.id ?? c.clientId ?? `draft-${idx + 1}`,
|
||||
clientId: c.clientId,
|
||||
treatmentType: c.treatmentType,
|
||||
teeth: c.teeth,
|
||||
notes: c.comment || null,
|
||||
attachmentMetas: c.attachmentMetas,
|
||||
labCaseId: c.labCaseId ?? null,
|
||||
destinationOrganizationId: c.sendToOrganizationIds[0] ?? null,
|
||||
sends: c.sends ?? [],
|
||||
sentAt: c.sentAt ?? null,
|
||||
details: details.map((d, idx) => ({
|
||||
id: d.id ?? d.clientId ?? `draft-${idx + 1}`,
|
||||
clientId: d.clientId,
|
||||
treatmentType: d.treatmentType,
|
||||
teeth: d.teeth,
|
||||
notes: d.comment || null,
|
||||
attachmentMetas: d.attachmentMetas,
|
||||
labCaseId: d.labCaseId ?? null,
|
||||
destinationOrganizationId: d.sendToOrganizationIds[0] ?? null,
|
||||
sends: d.sends ?? [],
|
||||
sentAt: d.sentAt ?? null,
|
||||
})),
|
||||
labCases: [],
|
||||
documents: [],
|
||||
@@ -152,17 +173,21 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
|
||||
const [orgs, setOrgs] = useState<LinkedOrganizationOption[]>([]);
|
||||
const [labDependentCodes, setLabDependentCodes] = useState<Set<string>>(new Set());
|
||||
|
||||
const [cases, setCases] = useState<TreatmentCaseDraft[]>(() => [newCase()]);
|
||||
const [activeCaseId, setActiveCaseId] = useState<string>(() => cases[0].clientId);
|
||||
const [details, setDetails] = useState<TreatmentDetailDraft[]>(() => [newDetail()]);
|
||||
const [labCaseDrafts, setLabCaseDrafts] = useState<LabCaseDraft[]>([]);
|
||||
const [activeDetailId, setActiveDetailId] = useState<string>(() => details[0].clientId);
|
||||
const [activeLabCaseId, setActiveLabCaseId] = useState<string | null>(null);
|
||||
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
|
||||
|
||||
const selectionLockedRef = useRef(selectionLocked);
|
||||
selectionLockedRef.current = selectionLocked;
|
||||
|
||||
const [saveBusy, setSaveBusy] = useState(false);
|
||||
const [saveLabBusy, setSaveLabBusy] = useState(false);
|
||||
const [sendBusyId, setSendBusyId] = useState<string | null>(null);
|
||||
const [uploadBusyCaseId, setUploadBusyCaseId] = useState<string | null>(null);
|
||||
const [uploadBusyDetailId, setUploadBusyDetailId] = useState<string | null>(null);
|
||||
const [organizationSearch, setOrganizationSearch] = useState('');
|
||||
const [recentOrganizationIds, setRecentOrganizationIds] = useState<string[]>([]);
|
||||
|
||||
@@ -170,12 +195,18 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
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)),
|
||||
[labCaseDrafts],
|
||||
);
|
||||
|
||||
const isDirty = useMemo(() => {
|
||||
if (savedSnapshot === null) {
|
||||
return cases.length !== 1 || cases[0].comment !== '' || cases[0].teeth.length > 0;
|
||||
return details.length !== 1 || details[0].comment !== '' || details[0].teeth.length > 0;
|
||||
}
|
||||
return serializeCases(cases) !== savedSnapshot;
|
||||
}, [cases, savedSnapshot]);
|
||||
return serializeDetails(details) !== savedSnapshot;
|
||||
}, [details, savedSnapshot]);
|
||||
|
||||
const selectedAppointment = useMemo(
|
||||
() => appointments.find((a) => a.id === selectedAppointmentId) ?? null,
|
||||
@@ -189,16 +220,16 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
const canEditTreatmentForDay = canEdit && Boolean(selectedAppointment) && !isViewingPastDay;
|
||||
|
||||
const activeCase = useMemo(
|
||||
() => cases.find((c) => c.clientId === activeCaseId) ?? cases[0],
|
||||
[cases, activeCaseId],
|
||||
const activeDetail = useMemo(
|
||||
() => details.find((d) => d.clientId === activeDetailId) ?? details[0],
|
||||
[details, activeDetailId],
|
||||
);
|
||||
|
||||
const selectedTeethSet = useMemo(() => new Set(activeCase?.teeth ?? []), [activeCase?.teeth]);
|
||||
const selectedTeethSet = useMemo(() => new Set(activeDetail?.teeth ?? []), [activeDetail?.teeth]);
|
||||
|
||||
const currentDraftPreview = useMemo<PastTreatment | null>(() => {
|
||||
if (!selectedAppointment) return null;
|
||||
return casesToPreviewTreatment(cases, {
|
||||
return detailsToPreviewTreatment(details, {
|
||||
title: t('draftTitle', {
|
||||
patientName: `${selectedAppointment.patientFirstName} ${selectedAppointment.patientLastName}`,
|
||||
}),
|
||||
@@ -206,7 +237,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
treatmentAt: new Date().toISOString(),
|
||||
status: 'draft',
|
||||
});
|
||||
}, [cases, selectedAppointment, t]);
|
||||
}, [details, selectedAppointment, t]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectionLocked(false);
|
||||
@@ -262,8 +293,15 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const list = await treatmentsApi.listLinkedOrganizations();
|
||||
if (!cancelled) setOrgs(list.data);
|
||||
const [orgsResponse, catalogResponse] = await Promise.all([
|
||||
treatmentsApi.listLinkedOrganizations(),
|
||||
treatmentCatalogApi.list(),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
setOrgs(orgsResponse.data);
|
||||
setLabDependentCodes(
|
||||
new Set(catalogResponse.data.filter((entry) => entry.labDependent).map((entry) => entry.code)),
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (!cancelled) {
|
||||
showError(formatApiErrorMessage(error, t('errorLoadOrgs')));
|
||||
@@ -311,18 +349,22 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
if (response.data?.details?.length) {
|
||||
const mapped = response.data.details.map(mapDetailFromApi);
|
||||
setCases(mapped);
|
||||
setActiveCaseId((prev) => {
|
||||
const stillExists = mapped.some((c) => c.clientId === prev);
|
||||
setDetails(mapped);
|
||||
setActiveDetailId((prev) => {
|
||||
const stillExists = mapped.some((d) => d.clientId === prev);
|
||||
return stillExists ? prev : mapped[0].clientId;
|
||||
});
|
||||
setSavedSnapshot(serializeCases(mapped));
|
||||
setSavedSnapshot(serializeDetails(mapped));
|
||||
} else {
|
||||
const first = newCase();
|
||||
setCases([first]);
|
||||
setActiveCaseId(first.clientId);
|
||||
setSavedSnapshot(serializeCases([first]));
|
||||
const first = newDetail();
|
||||
setDetails([first]);
|
||||
setActiveDetailId(first.clientId);
|
||||
setSavedSnapshot(serializeDetails([first]));
|
||||
}
|
||||
|
||||
const mappedLabCases = (response.data?.labCases ?? []).map(mapLabCaseDraftFromApi);
|
||||
setLabCaseDrafts(mappedLabCases);
|
||||
setActiveLabCaseId(mappedLabCases[0]?.clientId ?? null);
|
||||
setOrganizationSearch('');
|
||||
} catch (error: unknown) {
|
||||
if (!cancelled) {
|
||||
@@ -357,31 +399,31 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
[confirmDiscardIfDirty],
|
||||
);
|
||||
|
||||
const uploadForCase = useCallback(
|
||||
async (caseClientId: string, files: FileList | File[]) => {
|
||||
const uploadForDetail = useCallback(
|
||||
async (detailClientId: string, files: FileList | File[]) => {
|
||||
if (!canEditTreatmentForDay || !selectedAppointment) return;
|
||||
const list = files instanceof FileList ? Array.from(files) : files;
|
||||
if (!list.length) return;
|
||||
|
||||
setUploadBusyCaseId(caseClientId);
|
||||
setUploadBusyDetailId(detailClientId);
|
||||
try {
|
||||
const uploaded = await treatmentsApi.uploadCaseAttachments(
|
||||
selectedAppointment.id,
|
||||
caseClientId,
|
||||
detailClientId,
|
||||
list,
|
||||
);
|
||||
setCases((prev) =>
|
||||
prev.map((c) =>
|
||||
c.clientId === caseClientId
|
||||
? { ...c, attachmentMetas: [...c.attachmentMetas, ...uploaded.data] }
|
||||
: c,
|
||||
setDetails((prev) =>
|
||||
prev.map((d) =>
|
||||
d.clientId === detailClientId
|
||||
? { ...d, attachmentMetas: [...d.attachmentMetas, ...uploaded.data] }
|
||||
: d,
|
||||
),
|
||||
);
|
||||
showSuccess(t('successFilesUploaded', { count: uploaded.data.length }));
|
||||
} catch (error: unknown) {
|
||||
showError(formatApiErrorMessage(error, t('errorUpload')));
|
||||
} finally {
|
||||
setUploadBusyCaseId(null);
|
||||
setUploadBusyDetailId(null);
|
||||
}
|
||||
},
|
||||
[canEditTreatmentForDay, selectedAppointment, showSuccess, showError, t],
|
||||
@@ -391,7 +433,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
if (!selectedAppointment) throw new Error('No appointment selected');
|
||||
|
||||
const response = await treatmentsApi.saveDraft(selectedAppointment.id, {
|
||||
details: cases.map(({ clientId, id, treatmentType, teeth, comment, attachmentMetas }) => ({
|
||||
details: details.map(({ clientId, id, treatmentType, teeth, comment, attachmentMetas }) => ({
|
||||
clientId,
|
||||
id,
|
||||
treatmentType,
|
||||
@@ -401,14 +443,50 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
})),
|
||||
});
|
||||
const mapped = response.data.details.map(mapDetailFromApi);
|
||||
setCases(mapped);
|
||||
setActiveCaseId((prev) => {
|
||||
const stillExists = mapped.some((c) => c.clientId === prev);
|
||||
setDetails(mapped);
|
||||
setActiveDetailId((prev) => {
|
||||
const stillExists = mapped.some((d) => d.clientId === prev);
|
||||
return stillExists ? prev : mapped[0]?.clientId ?? prev;
|
||||
});
|
||||
setSavedSnapshot(serializeCases(mapped));
|
||||
setSavedSnapshot(serializeDetails(mapped));
|
||||
return response.data;
|
||||
}, [cases, selectedAppointment]);
|
||||
}, [details, selectedAppointment]);
|
||||
|
||||
const persistLabCases = useCallback(
|
||||
async (savedTreatment: PastTreatment) => {
|
||||
if (!selectedAppointment) throw new Error('No appointment selected');
|
||||
|
||||
const detailIdByClientId = new Map(
|
||||
savedTreatment.details.map((d) => [d.clientId, d.id]),
|
||||
);
|
||||
|
||||
const payload = labCaseDrafts.map((lc) => ({
|
||||
clientId: lc.clientId,
|
||||
id: lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId ?? undefined,
|
||||
labComment: lc.labComment.trim() || undefined,
|
||||
treatmentDetailIds: lc.detailClientIds
|
||||
.map((clientId) => detailIdByClientId.get(clientId))
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
}));
|
||||
|
||||
if (payload.length === 0) {
|
||||
return savedTreatment;
|
||||
}
|
||||
|
||||
const response = await treatmentsApi.saveLabCases(selectedAppointment.id, {
|
||||
labCases: payload,
|
||||
});
|
||||
const mapped = response.data.labCases.map(mapLabCaseDraftFromApi);
|
||||
setLabCaseDrafts(mapped);
|
||||
setActiveLabCaseId((prev) => {
|
||||
if (prev && mapped.some((lc) => lc.clientId === prev)) return prev;
|
||||
return mapped[0]?.clientId ?? null;
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
[labCaseDrafts, selectedAppointment],
|
||||
);
|
||||
|
||||
const handleSaveAll = useCallback(async () => {
|
||||
if (!canEditTreatmentForDay || !selectedAppointment) return;
|
||||
@@ -423,70 +501,69 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
}
|
||||
}, [canEditTreatmentForDay, selectedAppointment, persistDraft, showSuccess, showError, t]);
|
||||
|
||||
const handleSendCase = useCallback(
|
||||
async (treatmentCase: TreatmentCaseDraft) => {
|
||||
const handleSaveLabCases = useCallback(async () => {
|
||||
if (!canEditTreatmentForDay || !selectedAppointment) return;
|
||||
setSaveLabBusy(true);
|
||||
try {
|
||||
const saved = await persistDraft();
|
||||
await persistLabCases(saved);
|
||||
showSuccess(t('successLabShipmentsSaved'));
|
||||
} catch (error: unknown) {
|
||||
showError(formatApiErrorMessage(error, t('errorSaveLabShipments')));
|
||||
} finally {
|
||||
setSaveLabBusy(false);
|
||||
}
|
||||
}, [
|
||||
canEditTreatmentForDay,
|
||||
selectedAppointment,
|
||||
persistDraft,
|
||||
persistLabCases,
|
||||
showSuccess,
|
||||
showError,
|
||||
t,
|
||||
]);
|
||||
|
||||
const handleSendLabCase = useCallback(
|
||||
async (labCase: LabCaseDraft) => {
|
||||
if (!canEditTreatmentForDay || !selectedAppointment) return;
|
||||
const destinationOrgId = treatmentCase.sendToOrganizationIds.find((id) =>
|
||||
orgs.some((o) => o.id === id && o.active),
|
||||
);
|
||||
if (!destinationOrgId) {
|
||||
if (!labCase.destinationOrganizationId) {
|
||||
showError(t('errorChooseOrg'));
|
||||
return;
|
||||
}
|
||||
setSendBusyId(treatmentCase.clientId);
|
||||
if (labCase.detailClientIds.length === 0) {
|
||||
showError(t('errorLabCaseNeedsDetails'));
|
||||
return;
|
||||
}
|
||||
|
||||
setSendBusyId(labCase.clientId);
|
||||
try {
|
||||
const saved = await persistDraft();
|
||||
const serverDetail = saved.details.find((c) => c.clientId === treatmentCase.clientId);
|
||||
if (!serverDetail?.id) throw new Error(t('errorCaseMustSave'));
|
||||
const afterLabCases = await persistLabCases(saved);
|
||||
|
||||
const labCaseClientId = treatmentCase.labCaseId
|
||||
? saved.labCases.find((lc) => lc.id === treatmentCase.labCaseId)?.clientId
|
||||
: `lab-${treatmentCase.clientId}`;
|
||||
|
||||
const existingLabCase = saved.labCases.find(
|
||||
(lc) =>
|
||||
lc.treatmentDetailIds.includes(serverDetail.id) &&
|
||||
!lc.sentAt,
|
||||
const refreshedLabCase = afterLabCases.labCases.find(
|
||||
(lc) => lc.clientId === labCase.clientId || lc.id === labCase.id,
|
||||
);
|
||||
if (!refreshedLabCase?.id) throw new Error(t('errorSendCase'));
|
||||
|
||||
const withLabCases = await treatmentsApi.saveLabCases(selectedAppointment.id, {
|
||||
labCases: [
|
||||
{
|
||||
clientId: existingLabCase?.clientId ?? labCaseClientId ?? `lab-${treatmentCase.clientId}`,
|
||||
id: existingLabCase?.id ?? treatmentCase.labCaseId ?? undefined,
|
||||
destinationOrganizationId: destinationOrgId,
|
||||
treatmentDetailIds: [serverDetail.id],
|
||||
},
|
||||
],
|
||||
});
|
||||
const response = await treatmentsApi.sendLabCase(refreshedLabCase.id);
|
||||
|
||||
const labCase = withLabCases.data.labCases.find((lc) =>
|
||||
lc.treatmentDetailIds.includes(serverDetail.id),
|
||||
);
|
||||
if (!labCase?.id) throw new Error(t('errorSendCase'));
|
||||
|
||||
const response = await treatmentsApi.sendLabCase(labCase.id);
|
||||
|
||||
setCases((prev) => {
|
||||
const next = prev.map((c) =>
|
||||
c.clientId === treatmentCase.clientId
|
||||
setLabCaseDrafts((prev) =>
|
||||
prev.map((lc) =>
|
||||
lc.clientId === labCase.clientId
|
||||
? {
|
||||
...c,
|
||||
labCaseId: response.data.id,
|
||||
...lc,
|
||||
id: response.data.id,
|
||||
sentAt: response.data.sentAt,
|
||||
sendToOrganizationIds: response.data.destinationOrganizationId
|
||||
? [response.data.destinationOrganizationId]
|
||||
: [],
|
||||
destinationOrganizationId: response.data.destinationOrganizationId,
|
||||
sends: response.data.sends,
|
||||
}
|
||||
: c,
|
||||
);
|
||||
setSavedSnapshot(serializeCases(next));
|
||||
return next;
|
||||
});
|
||||
: lc,
|
||||
),
|
||||
);
|
||||
|
||||
setRecentOrganizationIds((prev) => {
|
||||
const next = [destinationOrgId, ...prev.filter((id) => id !== destinationOrgId)];
|
||||
return next.slice(0, 10);
|
||||
const orgId = labCase.destinationOrganizationId!;
|
||||
return [orgId, ...prev.filter((id) => id !== orgId)].slice(0, 10);
|
||||
});
|
||||
showSuccess(t('successCaseSent'));
|
||||
} catch (error: unknown) {
|
||||
@@ -495,47 +572,33 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
setSendBusyId(null);
|
||||
}
|
||||
},
|
||||
[canEditTreatmentForDay, selectedAppointment, orgs, persistDraft, showSuccess, showError, t],
|
||||
[
|
||||
canEditTreatmentForDay,
|
||||
selectedAppointment,
|
||||
persistDraft,
|
||||
persistLabCases,
|
||||
showSuccess,
|
||||
showError,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const openPreview = useCallback(
|
||||
(treatment: PastTreatment, mode: TreatmentPreviewMode) => {
|
||||
setPreviewTreatment(treatment);
|
||||
setPreviewMode(mode);
|
||||
setPreviewOpen(true);
|
||||
},
|
||||
[],
|
||||
);
|
||||
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]);
|
||||
|
||||
const getCaseOrgIds = useCallback(
|
||||
(caseKey: string) => cases.find((c) => c.clientId === caseKey)?.sendToOrganizationIds ?? [],
|
||||
[cases],
|
||||
);
|
||||
|
||||
const toggleCaseOrg = useCallback((caseKey: string, orgId: string, checked: boolean) => {
|
||||
setCases((prev) =>
|
||||
prev.map((c) => {
|
||||
if (c.clientId !== caseKey || c.sentAt) return c;
|
||||
const next = new Set(c.sendToOrganizationIds);
|
||||
if (checked) next.add(orgId);
|
||||
else next.delete(orgId);
|
||||
return { ...c, sendToOrganizationIds: [...next] };
|
||||
}),
|
||||
);
|
||||
}, []);
|
||||
|
||||
if (!canView) {
|
||||
return (
|
||||
<div className="surface-card p-6 max-w-xl">
|
||||
<h2 className="text-lg font-semibold text-text-primary">{t('noPermissionTitle')}</h2>
|
||||
<p className="text-sm text-text-secondary mt-2">
|
||||
{t('noPermissionBody')}
|
||||
</p>
|
||||
<p className="text-sm text-text-secondary mt-2">{t('noPermissionBody')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -545,7 +608,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<header className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">{t('title')}</h1>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{canEdit ? t('subtitleEdit') : t('subtitleReadOnly')}
|
||||
{canEdit ? t('subtitleEditPhase4') : t('subtitleReadOnly')}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -579,7 +642,9 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<p className="text-[11px] text-text-secondary">
|
||||
{t('purposeLabel')}{' '}
|
||||
<span className="capitalize text-text-primary">
|
||||
{t(TREATMENT_TYPE_KEYS[selectedAppointment.purpose as keyof typeof TREATMENT_TYPE_KEYS] ?? selectedAppointment.purpose)}
|
||||
{t(
|
||||
treatmentTypeLabelKey(selectedAppointment.purpose) as 'typeConsultation',
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -598,7 +663,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<PastTreatmentsPanel
|
||||
items={history}
|
||||
loading={historyLoading}
|
||||
onReviewTreatment={(t) => openPreview(t, 'readonly')}
|
||||
onReviewTreatment={(item) => openPreview(item, 'readonly')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -606,53 +671,73 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<FdiToothChart
|
||||
selected={selectedTeethSet}
|
||||
onToggle={(fdi) => {
|
||||
if (!canEditTreatmentForDay) return;
|
||||
setCases((prev) =>
|
||||
prev.map((c) => {
|
||||
if (c.clientId !== activeCaseId) return c;
|
||||
const set = new Set(c.teeth);
|
||||
if (!canEditTreatmentForDay || isDetailLocked(activeDetail)) return;
|
||||
setDetails((prev) =>
|
||||
prev.map((d) => {
|
||||
if (d.clientId !== activeDetailId) return d;
|
||||
const set = new Set(d.teeth);
|
||||
if (set.has(fdi)) set.delete(fdi);
|
||||
else set.add(fdi);
|
||||
return { ...c, teeth: [...set].sort() as FdiToothId[] };
|
||||
return { ...d, teeth: [...set].sort() as FdiToothId[] };
|
||||
}),
|
||||
);
|
||||
}}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
disabled={!canEditTreatmentForDay || isDetailLocked(activeDetail)}
|
||||
/>
|
||||
|
||||
<TreatmentCasesEditor
|
||||
cases={cases}
|
||||
activeCaseId={activeCaseId}
|
||||
onActiveCaseChange={setActiveCaseId}
|
||||
onCasesChange={setCases}
|
||||
<TreatmentDetailsEditor
|
||||
details={details}
|
||||
activeDetailId={activeDetailId}
|
||||
onActiveDetailChange={setActiveDetailId}
|
||||
onDetailsChange={setDetails}
|
||||
isDetailLocked={isDetailLocked}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
canEdit={canEdit}
|
||||
isDirty={isDirty}
|
||||
saveBusy={saveBusy}
|
||||
sendBusyId={sendBusyId}
|
||||
uploadBusy={uploadBusyCaseId === activeCaseId}
|
||||
uploadBusy={uploadBusyDetailId === activeDetailId}
|
||||
onAddDetail={() => {
|
||||
const next = newDetail();
|
||||
setDetails((prev) => [...prev, next]);
|
||||
setActiveDetailId(next.clientId);
|
||||
}}
|
||||
onPreview={openCurrentDraftPreview}
|
||||
onSave={() => void handleSaveAll()}
|
||||
onUploadFiles={(files) => void uploadForDetail(activeDetailId, files ?? [])}
|
||||
/>
|
||||
|
||||
<LabCasesDispatchPanel
|
||||
details={details}
|
||||
labCases={labCaseDrafts}
|
||||
labDependentCodes={labDependentCodes}
|
||||
activeLabCaseId={activeLabCaseId}
|
||||
onActiveLabCaseChange={setActiveLabCaseId}
|
||||
onLabCasesChange={setLabCaseDrafts}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
canEdit={canEdit}
|
||||
orgs={orgs}
|
||||
organizationSearch={organizationSearch}
|
||||
onOrganizationSearchChange={setOrganizationSearch}
|
||||
recentOrganizationIds={recentOrganizationIds}
|
||||
onRecentOrganizationPick={(orgId) => {
|
||||
setCases((prev) =>
|
||||
prev.map((c) => {
|
||||
if (c.clientId !== activeCaseId || c.sentAt) return c;
|
||||
if (c.sendToOrganizationIds.includes(orgId)) return c;
|
||||
return { ...c, sendToOrganizationIds: [...c.sendToOrganizationIds, orgId] };
|
||||
}),
|
||||
if (!activeLabCaseId) return;
|
||||
setLabCaseDrafts((prev) =>
|
||||
prev.map((lc) =>
|
||||
lc.clientId === activeLabCaseId && !lc.sentAt
|
||||
? { ...lc, destinationOrganizationId: orgId }
|
||||
: lc,
|
||||
),
|
||||
);
|
||||
}}
|
||||
onAddCase={() => {
|
||||
const nextCase = newCase();
|
||||
setCases((prev) => [...prev, nextCase]);
|
||||
setActiveCaseId(nextCase.clientId);
|
||||
sendBusyId={sendBusyId}
|
||||
saveLabBusy={saveLabBusy}
|
||||
onAddLabCase={() => {
|
||||
const next = newLabCaseDraft();
|
||||
setLabCaseDrafts((prev) => [...prev, next]);
|
||||
setActiveLabCaseId(next.clientId);
|
||||
}}
|
||||
onPreview={openCurrentDraftPreview}
|
||||
onSave={() => void handleSaveAll()}
|
||||
onSendCase={(c) => void handleSendCase(c)}
|
||||
onUploadFiles={(files) => void uploadForCase(activeCaseId, files ?? [])}
|
||||
onSaveLabCases={() => void handleSaveLabCases()}
|
||||
onSendLabCase={(lc) => void handleSendLabCase(lc)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -665,16 +750,8 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
}
|
||||
mode={previewMode}
|
||||
orgs={orgs}
|
||||
sendBusyCaseId={sendBusyId}
|
||||
uploadBusyCaseId={uploadBusyCaseId}
|
||||
onAttach={(caseKey, files) => uploadForCase(caseKey, files)}
|
||||
onSend={(caseKey, organizationIds) => {
|
||||
const c = cases.find((item) => item.clientId === caseKey);
|
||||
if (!c) return;
|
||||
void handleSendCase({ ...c, sendToOrganizationIds: organizationIds });
|
||||
}}
|
||||
getCaseOrgIds={getCaseOrgIds}
|
||||
onToggleCaseOrg={toggleCaseOrg}
|
||||
uploadBusyCaseId={uploadBusyDetailId}
|
||||
onAttach={(caseKey, files) => uploadForDetail(caseKey, files)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user