feature: Phase3 - Task templates + generation on send

This commit is contained in:
2026-06-28 16:46:42 +03:30
parent 8b4ef6195d
commit 21f545ebdb
25 changed files with 1448 additions and 31 deletions

View File

@@ -317,7 +317,26 @@
},
"cases": {
"title": "Cases",
"stubDescription": "Received lab cases from linked clinics will appear here. Full inbox and task workflow coming in a later phase."
"subtitle": "Lab cases sent from linked clinics. Assign tasks and track progress by tooth.",
"searchPlaceholder": "Search by patient name or mobile…",
"emptyList": "No cases received yet.",
"selectCaseHint": "Select a case from the list to view tasks.",
"fromClinic": "From {name}",
"sentAt": "Sent {date}",
"taskProgressLabel": "Tasks: {completed} of {total} completed",
"taskProgressShort": "{progress} tasks",
"treatmentDetails": "Treatment details",
"teethLabel": "Teeth",
"tasksByTooth": "Tasks by tooth",
"toothGroupTitle": "Tooth {tooth} · {type}",
"noTasks": "No tasks were generated for this case.",
"unassigned": "Unassigned",
"statusPending": "Pending",
"statusInProgress": "In progress",
"statusCompleted": "Completed",
"errorLoadList": "Failed to load cases.",
"errorLoadDetail": "Failed to load case details.",
"errorUpdateTask": "Failed to update task."
},
"appointments": {
"title": "Appointments",

View File

@@ -317,7 +317,26 @@
},
"cases": {
"title": "پرونده‌ها",
"stubDescription": "پرونده‌های دریافتی از کلینیک‌های متصل به زودی اینجا نمایش داده می‌شوند. صندوق ورودی کامل و گردش کار وظایف در فاز بعدی اضافه می‌شود."
"subtitle": "پرونده‌های ارسالی از کلینیک‌های متصل. وظایف را تخصیص دهید و پیشرفت هر دندان را پیگیری کنید.",
"searchPlaceholder": "جستجو با نام یا موبایل بیمار…",
"emptyList": "هنوز پرونده‌ای دریافت نشده است.",
"selectCaseHint": "برای مشاهده وظایف، یک پرونده از فهرست انتخاب کنید.",
"fromClinic": "از {name}",
"sentAt": "ارسال {date}",
"taskProgressLabel": "وظایف: {completed} از {total} انجام شده",
"taskProgressShort": "{progress} وظیفه",
"treatmentDetails": "جزئیات درمان",
"teethLabel": "دندان‌ها",
"tasksByTooth": "وظایف به تفکیک دندان",
"toothGroupTitle": "دندان {tooth} · {type}",
"noTasks": "برای این پرونده وظیفه‌ای ایجاد نشده است.",
"unassigned": "بدون مسئول",
"statusPending": "در انتظار",
"statusInProgress": "در حال انجام",
"statusCompleted": "انجام شده",
"errorLoadList": "بارگذاری پرونده‌ها ناموفق بود.",
"errorLoadDetail": "بارگذاری جزئیات پرونده ناموفق بود.",
"errorUpdateTask": "به‌روزرسانی وظیفه ناموفق بود."
},
"appointments": {
"title": "نوبت‌ها",

View File

@@ -317,7 +317,26 @@
},
"cases": {
"title": "Dossiers",
"stubDescription": "Ontvangen labdossiers van gekoppelde klinieken verschijnen hier. Volledige inbox en takenworkflow volgen in een latere fase."
"subtitle": "Labdossiers van gekoppelde klinieken. Wijs taken toe en volg de voortgang per tand.",
"searchPlaceholder": "Zoeken op patiëntnaam of mobiel…",
"emptyList": "Nog geen dossiers ontvangen.",
"selectCaseHint": "Selecteer een dossier uit de lijst om taken te bekijken.",
"fromClinic": "Van {name}",
"sentAt": "Verzonden {date}",
"taskProgressLabel": "Taken: {completed} van {total} voltooid",
"taskProgressShort": "{progress} taken",
"treatmentDetails": "Behandeldetails",
"teethLabel": "Tanden",
"tasksByTooth": "Taken per tand",
"toothGroupTitle": "Tand {tooth} · {type}",
"noTasks": "Er zijn geen taken gegenereerd voor dit dossier.",
"unassigned": "Niet toegewezen",
"statusPending": "In afwachting",
"statusInProgress": "Bezig",
"statusCompleted": "Voltooid",
"errorLoadList": "Dossiers laden mislukt.",
"errorLoadDetail": "Dossierdetails laden mislukt.",
"errorUpdateTask": "Taak bijwerken mislukt."
},
"appointments": {
"title": "Afspraken",

View File

@@ -1,14 +1,315 @@
'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 type { AssignableMember, LabCaseDetail, LabCaseListItem, LabTaskStatus } from '@/types/cases';
const TREATMENT_TYPE_KEYS = {
consultation: 'typeConsultation',
filling: 'typeFilling',
endo: 'typeEndo',
visit: 'typeVisit',
hygiene: 'typeHygiene',
} as const;
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));
}
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 [cases, setCases] = useState<LabCaseListItem[]>([]);
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 loadCases = async (q: string) => {
setLoadingList(true);
toast.setError('');
try {
const response = await casesApi.list({ q: q.trim() || undefined, page: 1, limit: 50 });
setCases(response.data.items);
} 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 loadCases('');
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(search);
}, 300);
return () => clearTimeout(timeout);
// eslint-disable-next-line react-hooks/exhaustive-deps -- debounced search only
}, [search]);
useEffect(() => {
if (selectedCaseId) {
void loadDetail(selectedCaseId);
} else {
setSelectedCase(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload when selection changes
}, [selectedCaseId]);
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(search);
} catch (error: unknown) {
toast.showError(formatApiErrorMessage(error, t('errorUpdateTask')));
} finally {
setUpdatingTaskId(null);
}
}
return (
<div className="space-y-4">
<h1 className="text-2xl font-semibold text-text-primary">{t('title')}</h1>
<p className="text-sm text-text-muted max-w-xl">{t('stubDescription')}</p>
<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(280px,360px)_1fr]">
<section className="rounded-lg border border-border bg-surface p-4 space-y-3">
<input
type="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('searchPlaceholder')}
className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
/>
{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-[70vh] overflow-y-auto">
{cases.map((item) => {
const isActive = item.id === selectedCaseId;
const progress =
item.taskProgress.total > 0
? `${item.taskProgress.completed}/${item.taskProgress.total}`
: '0/0';
return (
<li key={item.id}>
<button
type="button"
onClick={() => setSelectedCaseId(item.id)}
className={`w-full rounded-md border px-3 py-2 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.clinic.name}</div>
<div className="flex items-center justify-between text-xs text-text-muted mt-1">
<span>{formatDateTime(item.sentAt, locale)}</span>
<span>{t('taskProgressShort', { progress })}</span>
</div>
<div className="text-xs text-text-muted mt-1 truncate">
{item.treatmentTypes.map(treatmentLabel).join(', ')}
</div>
</button>
</li>
);
})}
</ul>
)}
</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('fromClinic', { name: selectedCase.clinic.name })}
</p>
<p className="text-sm text-text-muted">
{t('sentAt', { date: formatDateTime(selectedCase.sentAt, locale) })}
</p>
<p className="text-sm text-text-muted">
{t('taskProgressLabel', {
completed: selectedCase.taskProgress.completed,
total: selectedCase.taskProgress.total,
})}
</p>
</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>
);
}

View File

@@ -0,0 +1,36 @@
import { apiClient } from './client';
import type {
AssignableMember,
LabCaseDetail,
LabCaseTask,
ListLabCasesParams,
PaginatedLabCases,
} from '@/types/cases';
export const casesApi = {
list: async (
params: ListLabCasesParams = {},
): Promise<{ success: boolean; data: PaginatedLabCases }> => {
const response = await apiClient.get('/cases', { params });
return response.data;
},
getOne: async (id: string): Promise<{ success: boolean; data: LabCaseDetail }> => {
const response = await apiClient.get(`/cases/${id}`);
return response.data;
},
listAssignableMembers: async (): Promise<{ success: boolean; data: AssignableMember[] }> => {
const response = await apiClient.get('/cases/assignable-members');
return response.data;
},
updateTask: async (
caseId: string,
taskId: string,
payload: { assigneeUserId?: string | null; status?: LabCaseTask['status'] },
): Promise<{ success: boolean; data: LabCaseTask }> => {
const response = await apiClient.patch(`/cases/${caseId}/tasks/${taskId}`, payload);
return response.data;
},
};

View File

@@ -0,0 +1,86 @@
export type LabTaskStatus = 'PENDING' | 'IN_PROGRESS' | 'COMPLETED';
export interface LabCaseListItem {
id: string;
sentAt: string | null;
clinic: { id: string; name: string };
patient: {
id: string;
firstName: string;
lastName: string;
mobile: string;
};
treatmentTypes: string[];
taskProgress: { completed: number; total: number };
}
export interface LabCaseTask {
id: string;
tooth: string;
treatmentType: string;
stepOrder: number;
stepLabel: string;
status: LabTaskStatus;
assigneeUserId: string | null;
assignee: { id: string; name: string; email: string } | null;
}
export interface LabCaseTasksByTooth {
tooth: string;
treatmentType: string;
tasks: LabCaseTask[];
}
export interface LabCaseDetail {
id: string;
sentAt: string | null;
labComment: string | null;
clinic: { id: string; name: string };
patient: {
id: string;
firstName: string;
lastName: string;
mobile: string;
};
appointmentStartAt: string | null;
treatmentTypes: string[];
details: Array<{
id: string;
treatmentType: string;
teeth: string[];
comment: string | null;
}>;
sends: Array<{
organizationId: string;
organizationName: string;
sentAt: string;
}>;
tasks: LabCaseTask[];
tasksByTooth: LabCaseTasksByTooth[];
taskProgress: { completed: number; total: number };
}
export interface AssignableMember {
userId: string;
name: string;
email: string;
isOwner: boolean;
}
export interface ListLabCasesParams {
q?: string;
page?: number;
limit?: number;
clinicOrganizationId?: string;
treatmentType?: string;
}
export interface PaginatedLabCases {
items: LabCaseListItem[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}