532 lines
20 KiB
TypeScript
532 lines
20 KiB
TypeScript
'use client';
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
import { useTranslations } from 'next-intl';
|
|
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 { hasPermission } from '@/components/shared/permissions';
|
|
import { casesApi } from '@/lib/api/cases';
|
|
import { Button } from '@/components/ui/shared/Button';
|
|
import { SearchBar } from '@/components/ui/shared/SearchBar';
|
|
import type {
|
|
AssignableMember,
|
|
CasesFilterOptions,
|
|
LabCaseDetail,
|
|
LabCaseListItem,
|
|
LabTaskStatus,
|
|
PaginatedLabCases,
|
|
} from '@/types/cases';
|
|
|
|
const TREATMENT_TYPE_KEYS = {
|
|
consultation: 'typeConsultation',
|
|
filling: 'typeFilling',
|
|
endo: 'typeEndo',
|
|
visit: 'typeVisit',
|
|
hygiene: 'typeHygiene',
|
|
} as const;
|
|
|
|
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();
|
|
|
|
const [search, setSearch] = useState('');
|
|
const [clinicId, setClinicId] = useState('');
|
|
const [treatmentType, setTreatmentType] = useState('');
|
|
const [sentFrom, setSentFrom] = useState('');
|
|
const [sentTo, setSentTo] = useState('');
|
|
const [page, setPage] = useState(1);
|
|
|
|
const [cases, setCases] = useState<LabCaseListItem[]>([]);
|
|
const [pagination, setPagination] = useState<PaginatedLabCases['pagination']>({
|
|
page: 1,
|
|
limit: PAGE_SIZE,
|
|
total: 0,
|
|
totalPages: 1,
|
|
});
|
|
const [filterOptions, setFilterOptions] = useState<CasesFilterOptions>({
|
|
clinics: [],
|
|
treatmentTypes: [],
|
|
});
|
|
|
|
const [selectedCaseId, setSelectedCaseId] = useState<string | null>(null);
|
|
const [selectedCase, setSelectedCase] = useState<LabCaseDetail | null>(null);
|
|
const [members, setMembers] = useState<AssignableMember[]>([]);
|
|
const [loadingList, setLoadingList] = useState(false);
|
|
const [loadingDetail, setLoadingDetail] = useState(false);
|
|
const [updatingTaskId, setUpdatingTaskId] = useState<string | null>(null);
|
|
|
|
const canEdit = hasPermission(currentOrganization, 'TAB_CASES_EDIT');
|
|
const locale = user?.language ?? 'en';
|
|
|
|
const treatmentLabel = useCallback(
|
|
(type: string) => {
|
|
const key = TREATMENT_TYPE_KEYS[type as keyof typeof TREATMENT_TYPE_KEYS];
|
|
return key ? tTreatment(key) : type;
|
|
},
|
|
[tTreatment],
|
|
);
|
|
|
|
const statusOptions: { value: LabTaskStatus; label: string }[] = useMemo(
|
|
() => [
|
|
{ value: 'PENDING', label: t('statusPending') },
|
|
{ value: 'IN_PROGRESS', label: t('statusInProgress') },
|
|
{ value: 'COMPLETED', label: t('statusCompleted') },
|
|
],
|
|
[t],
|
|
);
|
|
|
|
const hasActiveFilters = Boolean(
|
|
search.trim() || clinicId || treatmentType || sentFrom || sentTo,
|
|
);
|
|
|
|
const loadCases = async (params: {
|
|
q: string;
|
|
clinicOrganizationId: string;
|
|
treatmentType: string;
|
|
sentFrom: string;
|
|
sentTo: string;
|
|
page: number;
|
|
}) => {
|
|
setLoadingList(true);
|
|
toast.setError('');
|
|
try {
|
|
const response = await casesApi.list({
|
|
q: params.q.trim() || undefined,
|
|
clinicOrganizationId: params.clinicOrganizationId || undefined,
|
|
treatmentType: params.treatmentType || undefined,
|
|
sentFrom: params.sentFrom || undefined,
|
|
sentTo: params.sentTo || undefined,
|
|
page: params.page,
|
|
limit: PAGE_SIZE,
|
|
});
|
|
setCases(response.data.items);
|
|
setPagination(response.data.pagination);
|
|
} catch (error: unknown) {
|
|
toast.showError(formatApiErrorMessage(error, t('errorLoadList')));
|
|
} finally {
|
|
setLoadingList(false);
|
|
}
|
|
};
|
|
|
|
const loadDetail = async (caseId: string) => {
|
|
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);
|
|
} finally {
|
|
setLoadingDetail(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
void casesApi.listFilterOptions().then((r) => setFilterOptions(r.data)).catch(() => {});
|
|
void casesApi.listAssignableMembers().then((r) => setMembers(r.data)).catch(() => {});
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only initial fetch
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
const timeout = setTimeout(() => {
|
|
void loadCases({
|
|
q: search,
|
|
clinicOrganizationId: clinicId,
|
|
treatmentType,
|
|
sentFrom,
|
|
sentTo,
|
|
page,
|
|
});
|
|
}, search ? 300 : 0);
|
|
return () => clearTimeout(timeout);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- debounced search + filter reload
|
|
}, [search, clinicId, treatmentType, sentFrom, sentTo, page]);
|
|
|
|
useEffect(() => {
|
|
if (selectedCaseId) {
|
|
void loadDetail(selectedCaseId);
|
|
} else {
|
|
setSelectedCase(null);
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload when selection changes
|
|
}, [selectedCaseId]);
|
|
|
|
function clearFilters() {
|
|
setSearch('');
|
|
setClinicId('');
|
|
setTreatmentType('');
|
|
setSentFrom('');
|
|
setSentTo('');
|
|
setPage(1);
|
|
}
|
|
|
|
async function handleTaskUpdate(
|
|
taskId: string,
|
|
payload: { assigneeUserId?: string | null; status?: LabTaskStatus },
|
|
) {
|
|
if (!selectedCaseId || !canEdit) return;
|
|
|
|
setUpdatingTaskId(taskId);
|
|
toast.setError('');
|
|
try {
|
|
await casesApi.updateTask(selectedCaseId, taskId, payload);
|
|
await loadDetail(selectedCaseId);
|
|
await loadCases({
|
|
q: search,
|
|
clinicOrganizationId: clinicId,
|
|
treatmentType,
|
|
sentFrom,
|
|
sentTo,
|
|
page,
|
|
});
|
|
} catch (error: unknown) {
|
|
toast.showError(formatApiErrorMessage(error, t('errorUpdateTask')));
|
|
} finally {
|
|
setUpdatingTaskId(null);
|
|
}
|
|
}
|
|
|
|
const filterSelectClass =
|
|
'w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary';
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div>
|
|
<h1 className="text-2xl font-semibold text-text-primary">{t('title')}</h1>
|
|
<p className="text-sm text-text-muted mt-1">{t('subtitle')}</p>
|
|
</div>
|
|
|
|
<div className="grid gap-4 lg:grid-cols-[minmax(300px,380px)_1fr]">
|
|
<section className="rounded-lg border border-border bg-surface p-4 space-y-3 flex flex-col min-h-0">
|
|
<SearchBar
|
|
embedded
|
|
value={search}
|
|
onChange={(value) => {
|
|
setSearch(value);
|
|
setPage(1);
|
|
}}
|
|
placeholder={t('searchPlaceholder')}
|
|
/>
|
|
|
|
<div className="grid gap-2 sm:grid-cols-2">
|
|
<label className="space-y-1">
|
|
<span className="text-xs font-medium text-text-muted">{t('filterClinic')}</span>
|
|
<select
|
|
value={clinicId}
|
|
onChange={(e) => {
|
|
setClinicId(e.target.value);
|
|
setPage(1);
|
|
}}
|
|
className={filterSelectClass}
|
|
>
|
|
<option value="">{t('filterClinicAll')}</option>
|
|
{filterOptions.clinics.map((clinic) => (
|
|
<option key={clinic.id} value={clinic.id}>
|
|
{clinic.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="space-y-1">
|
|
<span className="text-xs font-medium text-text-muted">{t('filterTreatmentType')}</span>
|
|
<select
|
|
value={treatmentType}
|
|
onChange={(e) => {
|
|
setTreatmentType(e.target.value);
|
|
setPage(1);
|
|
}}
|
|
className={filterSelectClass}
|
|
>
|
|
<option value="">{t('filterTreatmentTypeAll')}</option>
|
|
{filterOptions.treatmentTypes.map((type) => (
|
|
<option key={type.code} value={type.code}>
|
|
{treatmentLabel(type.code)}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="space-y-1">
|
|
<span className="text-xs font-medium text-text-muted">{t('filterSentFrom')}</span>
|
|
<input
|
|
type="date"
|
|
value={sentFrom}
|
|
onChange={(e) => {
|
|
setSentFrom(e.target.value);
|
|
setPage(1);
|
|
}}
|
|
className={filterSelectClass}
|
|
/>
|
|
</label>
|
|
|
|
<label className="space-y-1">
|
|
<span className="text-xs font-medium text-text-muted">{t('filterSentTo')}</span>
|
|
<input
|
|
type="date"
|
|
value={sentTo}
|
|
onChange={(e) => {
|
|
setSentTo(e.target.value);
|
|
setPage(1);
|
|
}}
|
|
className={filterSelectClass}
|
|
/>
|
|
</label>
|
|
</div>
|
|
|
|
{hasActiveFilters ? (
|
|
<Button variant="ghost" size="sm" onClick={clearFilters} className="self-start">
|
|
{t('clearFilters')}
|
|
</Button>
|
|
) : null}
|
|
|
|
<div className="flex-1 min-h-0">
|
|
{loadingList ? (
|
|
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
|
|
) : cases.length === 0 ? (
|
|
<p className="text-sm text-text-muted">{t('emptyList')}</p>
|
|
) : (
|
|
<ul className="space-y-2 max-h-[55vh] overflow-y-auto pr-1">
|
|
{cases.map((item) => {
|
|
const isActive = item.id === selectedCaseId;
|
|
|
|
return (
|
|
<li key={item.id}>
|
|
<button
|
|
type="button"
|
|
onClick={() => setSelectedCaseId(item.id)}
|
|
className={`w-full rounded-md border px-3 py-2.5 text-left transition-colors ${
|
|
isActive
|
|
? 'border-primary bg-primary/5'
|
|
: 'border-border hover:border-primary/40'
|
|
}`}
|
|
>
|
|
<div className="font-medium text-text-primary">
|
|
{formatPatientName(item.patient)}
|
|
</div>
|
|
<div className="text-xs text-text-muted mt-0.5">
|
|
{item.patient.mobile}
|
|
</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)}
|
|
</div>
|
|
<div className="text-xs text-text-muted mt-1 truncate">
|
|
{item.treatmentTypes.map(treatmentLabel).join(', ')}
|
|
</div>
|
|
<div className="mt-2">
|
|
<TaskProgressBar
|
|
completed={item.taskProgress.completed}
|
|
total={item.taskProgress.total}
|
|
/>
|
|
</div>
|
|
</button>
|
|
</li>
|
|
);
|
|
})}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
|
|
{pagination.totalPages > 1 ? (
|
|
<div className="flex items-center justify-between gap-2 pt-2 border-t border-border">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={page <= 1 || loadingList}
|
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
|
>
|
|
{t('prevPage')}
|
|
</Button>
|
|
<span className="text-xs text-text-muted text-center">
|
|
{t('pageSummary', {
|
|
page: pagination.page,
|
|
totalPages: pagination.totalPages,
|
|
total: pagination.total,
|
|
})}
|
|
</span>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={page >= pagination.totalPages || loadingList}
|
|
onClick={() => setPage((p) => p + 1)}
|
|
>
|
|
{t('nextPage')}
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
</section>
|
|
|
|
<section className="rounded-lg border border-border bg-surface p-4 min-h-[420px]">
|
|
{!selectedCaseId ? (
|
|
<p className="text-sm text-text-muted">{t('selectCaseHint')}</p>
|
|
) : 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">
|
|
<h2 className="text-lg font-semibold text-text-primary">
|
|
{formatPatientName(selectedCase.patient)}
|
|
</h2>
|
|
<p className="text-sm text-text-muted">
|
|
{t('patientMobile')}: {selectedCase.patient.mobile}
|
|
</p>
|
|
<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>
|
|
{selectedCase.labComment ? (
|
|
<p className="text-sm text-text-muted pt-1">
|
|
<span className="font-medium text-text-primary">{t('labComment')}:</span>{' '}
|
|
{selectedCase.labComment}
|
|
</p>
|
|
) : null}
|
|
</header>
|
|
|
|
{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) => (
|
|
<div
|
|
key={`${group.tooth}-${group.treatmentType}`}
|
|
className="rounded-md border border-border p-3 space-y-2"
|
|
>
|
|
<div className="text-sm font-medium text-text-primary">
|
|
{t('toothGroupTitle', {
|
|
tooth: group.tooth,
|
|
type: treatmentLabel(group.treatmentType),
|
|
})}
|
|
</div>
|
|
<ul className="space-y-2">
|
|
{group.tasks.map((task) => (
|
|
<li
|
|
key={task.id}
|
|
className="grid gap-2 sm:grid-cols-[1fr_160px_180px] items-center text-sm rounded bg-background p-2"
|
|
>
|
|
<span>
|
|
{task.stepOrder}. {task.stepLabel}
|
|
</span>
|
|
<select
|
|
value={task.status}
|
|
disabled={!canEdit || updatingTaskId === task.id}
|
|
onChange={(e) =>
|
|
void handleTaskUpdate(task.id, {
|
|
status: e.target.value as LabTaskStatus,
|
|
})
|
|
}
|
|
className="rounded border border-border bg-surface px-2 py-1 text-sm disabled:opacity-60"
|
|
>
|
|
{statusOptions.map((opt) => (
|
|
<option key={opt.value} value={opt.value}>
|
|
{opt.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<select
|
|
value={task.assigneeUserId ?? ''}
|
|
disabled={!canEdit || updatingTaskId === task.id}
|
|
onChange={(e) =>
|
|
void handleTaskUpdate(task.id, {
|
|
assigneeUserId: e.target.value || null,
|
|
})
|
|
}
|
|
className="rounded border border-border bg-surface px-2 py-1 text-sm disabled:opacity-60"
|
|
>
|
|
<option value="">{t('unassigned')}</option>
|
|
{members.map((member) => (
|
|
<option key={member.userId} value={member.userId}>
|
|
{member.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
))
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</section>
|
|
</div>
|
|
|
|
<ToastStack {...toast.messages} />
|
|
</div>
|
|
);
|
|
}
|