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

@@ -3,17 +3,17 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { MessageSquare } from 'lucide-react';
import { ToastStack } from '@/components/ui/shared/Toast';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { canEditCases, canEditTasks } from '@/components/shared/permissions';
import { Badge } from '@/components/ui/shared/Badge';
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 {
formatCaseDateTime,
formatPatientName,
} from '@/components/ui/lab/caseDetailUtils';
import { casesApi } from '@/lib/api/cases';
import { tasksApi } from '@/lib/api/tasks';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
@@ -29,47 +29,11 @@ import type {
LabTaskStatus,
PaginatedLabCases,
} from '@/types/cases';
import {
formatToothList,
prosthesisTypeBadgeStyle,
} from '@/components/ui/treatment/prosthesisTypeDisplay';
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>
);
}
export default function CasesPage() {
const t = useTranslations('cases');
const tTreatment = useTranslations('treatment');
const tCommon = useTranslations('common');
const { currentOrganization, user } = useAuth();
const toast = useToast();
@@ -99,7 +63,7 @@ export default function CasesPage() {
const [selectedCase, setSelectedCase] = useState<LabCaseDetail | null>(null);
const [loadingList, setLoadingList] = useState(false);
const [loadingDetail, setLoadingDetail] = useState(false);
const [updatingTaskId, setUpdatingTaskId] = useState<string | null>(null);
const [updatingImportant, setUpdatingImportant] = useState(false);
const [commentCount, setCommentCount] = useState(0);
const canEdit = canEditCases(currentOrganization);
@@ -152,17 +116,23 @@ export default function CasesPage() {
}
};
const loadDetail = async (caseId: string) => {
setLoadingDetail(true);
const loadDetail = async (caseId: string, options?: { silent?: boolean }) => {
if (!options?.silent) {
setLoadingDetail(true);
}
toast.setError('');
try {
const response = await casesApi.getOne(caseId);
setSelectedCase(response.data);
} catch (error: unknown) {
toast.showError(formatApiErrorMessage(error, t('errorLoadDetail')));
setSelectedCase(null);
if (!options?.silent) {
setSelectedCase(null);
}
} finally {
setLoadingDetail(false);
if (!options?.silent) {
setLoadingDetail(false);
}
}
};
@@ -217,34 +187,6 @@ export default function CasesPage() {
[],
);
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]);
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,
}));
}
return selectedCase.tasksByTooth.map((g) => ({
prosthesisTypeCode: g.prosthesisTypeCode,
teeth: g.teeth,
}));
}, [selectedCase]);
function clearFilters() {
setSearch('');
setClinicId('');
@@ -254,18 +196,22 @@ export default function CasesPage() {
setPage(1);
}
async function handleImportantToggle(taskId: string, isImportant: boolean) {
if (!selectedCaseId || !canEdit) return;
async function handleCaseImportantToggle(isImportant: boolean) {
if (!selectedCaseId || !canEdit || !selectedCase) return;
setUpdatingTaskId(taskId);
const previousCase = selectedCase;
setSelectedCase({ ...selectedCase, isImportant });
setUpdatingImportant(true);
toast.setError('');
try {
await casesApi.setTaskImportant(selectedCaseId, taskId, isImportant);
await loadDetail(selectedCaseId);
const response = await casesApi.setCaseImportant(selectedCaseId, isImportant);
setSelectedCase(response.data);
} catch (error: unknown) {
setSelectedCase(previousCase);
toast.showError(formatApiErrorMessage(error, t('errorUpdateTask')));
} finally {
setUpdatingTaskId(null);
setUpdatingImportant(false);
}
}
@@ -391,13 +337,13 @@ export default function CasesPage() {
</div>
<div className="text-xs text-text-muted mt-0.5">{item.clinic.name}</div>
<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}
/>
@@ -445,181 +391,53 @@ export default function CasesPage() {
) : 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>
<Button type="button" variant="outline" size="sm" onClick={scrollToComments}>
<MessageSquare className="h-4 w-4 me-1.5" />
{commentCount > 0
? t('commentsCount', { count: commentCount })
: t('showComments')}
</Button>
</div>
<p className="text-sm text-text-muted">
{t('patientMobile')}: {selectedCase.patient.mobile}
</p>
<CaseDetailPanel
labCase={selectedCase}
locale={locale}
treatmentLabel={treatmentLabel}
statusOptions={statusOptions}
loadAttachmentBlob={loadCaseAttachmentBlob}
showCommentsButton
commentCount={commentCount}
onCommentsClick={scrollToComments}
canEditImportant={canEdit}
updatingImportant={updatingImportant}
onImportantChange={(checked) => void handleCaseImportantToggle(checked)}
headerMetaLines={
<p className="text-sm text-text-muted">
{t('fromClinic', { name: selectedCase.clinic.name })}
</p>
<p className="text-sm text-text-muted">
{t('sentAt', { date: formatDateTime(selectedCase.sentAt, locale) })}
</p>
<div className="pt-1 max-w-xs">
<p className="text-sm text-text-muted mb-1">
{t('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">{t('latestAttachment')}</p>
<LabCaseAttachmentPreview
}
commentsSection={
selectedCaseId ? (
<section id="case-comments" className="scroll-mt-4 border-t border-border pt-4">
<LabCaseCommentsPanel
caseId={selectedCaseId}
attachment={latestCaseAttachment}
loadBlob={loadCaseAttachmentBlob}
canPost={canEditComments}
canToggleVisibility={canEditComments}
loadComments={async () => {
const r = await tasksApi.listComments(selectedCaseId);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await tasksApi.addComment(selectedCaseId, {
body,
visibleToClinic,
});
setCommentCount((n) => n + 1);
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await tasksApi.setCommentVisibility(commentId, visible);
return r.data;
}}
onError={toast.showError}
/>
</div>
) : null}
</div>
{selectedCase.details.length > 0 && (
<div className="space-y-2">
<h3 className="text-sm font-medium text-text-primary">{t('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">
{t('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">{t('tasksByTooth')}</h3>
{selectedCase.tasksByTooth.length === 0 ? (
<p className="text-sm text-text-muted">{t('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">
{t('toothGroupTitle', {
teeth: formatToothList(group.teeth),
prosthesis: group.prosthesisTypeLabel,
})}
</span>
</div>
<ul className="space-y-2">
{group.tasks.map((task) => (
<li
key={task.id}
className="rounded bg-background p-2 text-sm space-y-1"
>
<div className="flex flex-wrap items-center gap-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>
{canEdit ? (
<label className="flex items-center gap-1.5 text-xs cursor-pointer shrink-0">
<input
type="checkbox"
checked={task.isImportant}
disabled={updatingTaskId === task.id}
onChange={(e) =>
void handleImportantToggle(task.id, e.target.checked)
}
/>
{t('importantLabel')}
</label>
) : task.isImportant ? (
<Badge variant="warning" fixedWidth={false}>
{t('importantLabel')}
</Badge>
) : null}
</div>
<p className="text-[11px] text-text-muted">
{task.lastStatusChangedBy
? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
: t('lastUpdatedUnknown')}
{task.lastStatusChangedAt
? ` · ${formatDateTime(task.lastStatusChangedAt, locale)}`
: ''}
</p>
</li>
))}
</ul>
</div>
))
)}
</div>
{selectedCaseId ? (
<section id="case-comments" className="scroll-mt-4 border-t border-border pt-4">
<LabCaseCommentsPanel
caseId={selectedCaseId}
canPost={canEditComments}
canToggleVisibility={canEditComments}
loadComments={async () => {
const r = await tasksApi.listComments(selectedCaseId);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await tasksApi.addComment(selectedCaseId, {
body,
visibleToClinic,
});
setCommentCount((n) => n + 1);
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await tasksApi.setCommentVisibility(commentId, visible);
return r.data;
}}
onError={toast.showError}
/>
</section>
) : null}
</div>
</section>
) : null
}
/>
)}
</section>
</div>

View File

@@ -51,13 +51,11 @@ export default function TasksPage() {
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [updatingTaskId, setUpdatingTaskId] = useState<string | null>(null);
const [expandedCommentsCaseId, setExpandedCommentsCaseId] = useState<string | null>(null);
const [expandedCommentsTaskId, setExpandedCommentsTaskId] = useState<string | null>(null);
const [search, setSearch] = useState('');
const [clinicId, setClinicId] = useState('');
const [statusFilter, setStatusFilter] = useState<'' | LabTaskStatus>('');
const [showCompleted, setShowCompleted] = useState(false);
const [importantOnly, setImportantOnly] = useState(false);
const [statusFilter, setStatusFilter] = useState<'' | LabTaskStatus>('IN_PROGRESS');
const [sentFrom, setSentFrom] = useState('');
const [sentTo, setSentTo] = useState('');
const [sortBy, setSortBy] = useState<TaskSortField>('date');
@@ -87,18 +85,11 @@ export default function TasksPage() {
};
if (search.trim()) params.q = search.trim();
if (clinicId) params.clinicOrganizationId = clinicId;
if (statusFilter) {
params.status = statusFilter;
} else if (showCompleted) {
params.completed = undefined;
} else {
params.completed = false;
}
if (importantOnly) params.important = true;
if (statusFilter) params.status = statusFilter;
if (sentFrom) params.sentFrom = sentFrom;
if (sentTo) params.sentTo = sentTo;
return params;
}, [page, search, clinicId, statusFilter, showCompleted, importantOnly, sentFrom, sentTo, sortBy, sortDir]);
}, [page, search, clinicId, statusFilter, sentFrom, sentTo, sortBy, sortDir]);
const clinicOptions = useMemo(() => {
const map = new Map<string, string>();
@@ -228,10 +219,10 @@ export default function TasksPage() {
className={`${filterSelectClass} min-w-0 flex-1`}
>
<option value="date">{t('sortDate')}</option>
<option value="status">{t('sortStatus')}</option>
<option value="clinic">{t('sortClinic')}</option>
<option value="patient">{t('sortPatient')}</option>
<option value="important">{t('sortImportant')}</option>
<option value="prosthesis">{t('sortProsthesis')}</option>
<option value="taskType">{t('sortTaskType')}</option>
</select>
<select
value={sortDir}
@@ -245,30 +236,6 @@ export default function TasksPage() {
</div>
</label>
</div>
<div className="flex flex-wrap items-center gap-4 text-sm">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={showCompleted}
onChange={(e) => {
setShowCompleted(e.target.checked);
setPage(1);
}}
/>
{t('showCompleted')}
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={importantOnly}
onChange={(e) => {
setImportantOnly(e.target.checked);
setPage(1);
}}
/>
{t('importantOnly')}
</label>
</div>
</section>
<section className="surface-card min-h-[280px]">
@@ -279,7 +246,7 @@ export default function TasksPage() {
) : (
<ul className="divide-y divide-border">
{tasks.map((task, index) => {
const commentsOpen = expandedCommentsCaseId === task.labCaseId;
const commentsOpen = expandedCommentsTaskId === task.id;
return (
<li key={task.id}>
@@ -343,7 +310,7 @@ export default function TasksPage() {
<button
type="button"
onClick={() =>
setExpandedCommentsCaseId(commentsOpen ? null : task.labCaseId)
setExpandedCommentsTaskId(commentsOpen ? null : task.id)
}
className={`p-1.5 rounded border ${
commentsOpen