improvement: all demo bugs fixed. give me more baby.

This commit is contained in:
2026-07-08 02:53:47 +03:30
parent 86b1e3afff
commit 8d334833ff
23 changed files with 876 additions and 626 deletions

View File

@@ -2,65 +2,30 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { MessageSquare } from 'lucide-react';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { canEditCases } from '@/components/shared/permissions';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { organizationApi } from '@/lib/api/organization';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { treatmentTypeLabelFromCatalog } from '@/components/ui/treatment/treatmentTypeDisplay';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { ToastStack } from '@/components/ui/shared/Toast';
import { CaseDetailPanel, CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
import { CaseToothChartPanel } from '@/components/ui/lab/CaseToothChartPanel';
import { LabCaseAttachmentPreview } from '@/components/ui/lab/LabCaseAttachmentPreview';
import { labTaskStatusVariant } from '@/components/ui/lab/labTaskStatusDisplay';
import {
formatToothList,
prosthesisTypeBadgeStyle,
} from '@/components/ui/treatment/prosthesisTypeDisplay';
formatCaseDateTime,
formatPatientName,
} from '@/components/ui/lab/caseDetailUtils';
import { treatmentsApi } from '@/lib/api/treatments';
import { casesApi } from '@/lib/api/cases';
import type { CounterpartItemDto } from '@/lib/api/organization';
import type { LabCaseDetail, LabCaseListItem, LabTaskStatus } from '@/types/cases';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';
const PAGE_SIZE = 20;
function formatPatientName(patient: { firstName: string; lastName: string }) {
return `${patient.firstName} ${patient.lastName}`.trim();
}
function formatDateTime(value: string | null, locale: string) {
if (!value) return '—';
return new Intl.DateTimeFormat(locale, {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(value));
}
function TaskProgressBar({ completed, total }: { completed: number; total: number }) {
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
return (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-text-muted">
<span>
{completed}/{total}
</span>
<span>{pct}%</span>
</div>
<div className="h-1.5 rounded-full bg-border overflow-hidden">
<div
className="h-full rounded-full bg-primary transition-all duration-300"
style={{ width: `${pct}%` }}
/>
</div>
</div>
);
}
interface ConnectionCaseHistoryContentProps {
connection: CounterpartItemDto;
onBack: () => void;
@@ -90,10 +55,12 @@ export function ConnectionCaseHistoryContent({
const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);
const [loadingList, setLoadingList] = useState(false);
const [loadingDetail, setLoadingDetail] = useState(false);
const [updatingImportant, setUpdatingImportant] = useState(false);
const [commentCount, setCommentCount] = useState(0);
const locale = user?.language ?? 'en';
const isClinic = currentOrganization?.type === 'CLINIC';
const canEditImportant = !isClinic && canEditCases(currentOrganization);
const tRef = useRef(t);
tRef.current = t;
@@ -194,33 +161,24 @@ export function ConnectionCaseHistoryContent({
[],
);
const latestCaseAttachment = useMemo(() => {
if (!selectedCase?.attachments.length) return null;
return [...selectedCase.attachments].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
)[0];
}, [selectedCase?.attachments]);
async function handleCaseImportantToggle(isImportant: boolean) {
if (!selectedCaseId || !canEditImportant || !selectedCase) return;
const caseProsthesisRows = useMemo(() => {
if (!selectedCase) return [];
if (selectedCase.toothProsthesis.length > 0) {
const byCode = new Map<string, string[]>();
for (const row of selectedCase.toothProsthesis) {
const key = row.prosthesisTypeCode;
const teeth = byCode.get(key) ?? [];
if (!teeth.includes(row.tooth)) teeth.push(row.tooth);
byCode.set(key, teeth);
}
return [...byCode.entries()].map(([prosthesisTypeCode, teeth]) => ({
prosthesisTypeCode,
teeth,
}));
const previousCase = selectedCase;
setSelectedCase({ ...selectedCase, isImportant });
setUpdatingImportant(true);
setError('');
try {
const response = await casesApi.setCaseImportant(selectedCaseId, isImportant);
setSelectedCase(response.data);
} catch (error: unknown) {
setSelectedCase(previousCase);
showError(formatApiErrorMessage(error, tCases('errorUpdateTask')));
} finally {
setUpdatingImportant(false);
}
return selectedCase.tasksByTooth.map((g) => ({
prosthesisTypeCode: g.prosthesisTypeCode,
teeth: g.teeth,
}));
}, [selectedCase]);
}
return (
<div className="space-y-6">
@@ -286,13 +244,13 @@ export function ConnectionCaseHistoryContent({
<div className="text-xs text-text-muted mt-0.5">{item.clinic.name}</div>
) : null}
<div className="text-xs text-text-muted mt-1">
{formatDateTime(item.sentAt, locale)}
{formatCaseDateTime(item.sentAt, locale)}
</div>
<div className="text-xs text-text-muted mt-1 truncate">
{item.treatmentTypes.map(treatmentLabel).join(', ')}
</div>
<div className="mt-2">
<TaskProgressBar
<CaseTaskProgressBar
completed={item.taskProgress.completed}
total={item.taskProgress.total}
/>
@@ -340,25 +298,20 @@ export function ConnectionCaseHistoryContent({
) : loadingDetail || !selectedCase ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : (
<div className="space-y-4">
<header className="space-y-1 border-b border-border pb-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<h2 className="text-lg font-semibold text-text-primary">
{formatPatientName(selectedCase.patient)}
</h2>
{isClinic ? (
<Button type="button" variant="outline" size="sm" onClick={scrollToComments}>
<MessageSquare className="h-4 w-4 me-1.5" />
{commentCount > 0
? tCases('commentsCount', { count: commentCount })
: tCases('showComments')}
</Button>
) : null}
</div>
<p className="text-sm text-text-muted">
{tCases('patientMobile')}: {selectedCase.patient.mobile}
</p>
{!isClinic ? (
<CaseDetailPanel
labCase={selectedCase}
locale={locale}
treatmentLabel={treatmentLabel}
statusOptions={statusOptions}
loadAttachmentBlob={loadClinicAttachmentBlob}
showCommentsButton={isClinic}
commentCount={commentCount}
onCommentsClick={scrollToComments}
canEditImportant={canEditImportant}
updatingImportant={updatingImportant}
onImportantChange={(checked) => void handleCaseImportantToggle(checked)}
headerMetaLines={
!isClinic ? (
<p className="text-sm text-text-muted">
{tCases('fromClinic', { name: selectedCase.clinic.name })}
</p>
@@ -366,148 +319,38 @@ export function ConnectionCaseHistoryContent({
<p className="text-sm text-text-muted">
{t('caseHistorySentToLab', { name: connection.organizationName })}
</p>
)}
<p className="text-sm text-text-muted">
{tCases('sentAt', { date: formatDateTime(selectedCase.sentAt, locale) })}
</p>
<div className="pt-1 max-w-xs">
<p className="text-sm text-text-muted mb-1">
{tCases('taskProgressLabel', {
completed: selectedCase.taskProgress.completed,
total: selectedCase.taskProgress.total,
})}
</p>
<TaskProgressBar
completed={selectedCase.taskProgress.completed}
total={selectedCase.taskProgress.total}
/>
</div>
</header>
<div className="flex flex-wrap items-start gap-4">
<CaseToothChartPanel
details={selectedCase.details}
prosthesisRows={caseProsthesisRows}
scale={0.5}
className="min-w-0 flex-1"
/>
{latestCaseAttachment && selectedCaseId ? (
<div className="shrink-0 space-y-1">
<p className="text-xs font-medium text-text-secondary">
{tCases('latestAttachment')}
</p>
<LabCaseAttachmentPreview
)
}
commentsSection={
isClinic && selectedCaseId ? (
<section id="case-comments" className="scroll-mt-4 border-t border-border pt-4">
<LabCaseCommentsPanel
caseId={selectedCaseId}
attachment={latestCaseAttachment}
loadBlob={loadClinicAttachmentBlob}
canPost
canToggleVisibility={false}
loadComments={async () => {
const r = await organizationApi.listConnectionCaseComments(
connection.id,
selectedCaseId,
);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body) => {
const r = await organizationApi.addConnectionCaseComment(
connection.id,
selectedCaseId,
body,
);
setCommentCount((n) => n + 1);
return r.data;
}}
onError={showError}
/>
</div>
) : null}
</div>
{selectedCase.details.length > 0 && (
<div className="space-y-2">
<h3 className="text-sm font-medium text-text-primary">
{tCases('treatmentDetails')}
</h3>
<ul className="space-y-2 text-sm">
{selectedCase.details.map((detail) => (
<li
key={detail.id}
className="rounded-md bg-background border border-border p-2"
>
<div className="font-medium">{treatmentLabel(detail.treatmentType)}</div>
<div className="text-text-muted">
{tCases('teethLabel')}: {detail.teeth.join(', ') || '—'}
</div>
{detail.comment ? (
<div className="text-text-muted mt-1">{detail.comment}</div>
) : null}
</li>
))}
</ul>
</div>
)}
<div className="space-y-3">
<h3 className="text-sm font-medium text-text-primary">{tCases('tasksByTooth')}</h3>
{selectedCase.tasksByTooth.length === 0 ? (
<p className="text-sm text-text-muted">{tCases('noTasks')}</p>
) : (
selectedCase.tasksByTooth.map((group, groupIndex) => (
<div
key={`${group.treatmentDetailId}-${group.prosthesisTypeCode}`}
className="rounded-md border border-border p-3 space-y-2"
>
<div className="flex flex-wrap items-center gap-2">
<Badge
truncate
title={group.prosthesisTypeLabel}
style={prosthesisTypeBadgeStyle(group.prosthesisTypeCode, groupIndex)}
>
{group.prosthesisTypeLabel}
</Badge>
<span className="text-sm font-medium text-text-primary">
{tCases('toothGroupTitle', {
teeth: formatToothList(group.teeth),
prosthesis: group.prosthesisTypeLabel,
})}
</span>
</div>
<ul className="space-y-2">
{group.tasks.map((task) => (
<li
key={task.id}
className="flex flex-wrap items-center gap-2 text-sm rounded bg-background p-2"
>
<span className="min-w-0 flex-1">
{task.stepOrder}. {task.stepLabel}
</span>
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
{task.lastStatusChangedBy ? (
<span className="text-[11px] text-text-muted">
{tCases('lastUpdatedBy', { name: task.lastStatusChangedBy.name })}
</span>
) : null}
</li>
))}
</ul>
</div>
))
)}
</div>
{isClinic && selectedCaseId ? (
<section id="case-comments" className="scroll-mt-4 border-t border-border pt-4">
<LabCaseCommentsPanel
caseId={selectedCaseId}
canPost
canToggleVisibility={false}
loadComments={async () => {
const r = await organizationApi.listConnectionCaseComments(
connection.id,
selectedCaseId,
);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body) => {
const r = await organizationApi.addConnectionCaseComment(
connection.id,
selectedCaseId,
body,
);
setCommentCount((n) => n + 1);
return r.data;
}}
onError={showError}
/>
</section>
) : null}
</div>
</section>
) : null
}
/>
)}
</section>
</div>