feature/cases #55

Merged
rameen merged 18 commits from feature/cases into master 2026-07-10 18:26:56 +03:30
11 changed files with 739 additions and 15 deletions
Showing only changes of commit 3e81c110a3 - Show all commits

View File

@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service'; import { PrismaService } from '../../../prisma/prisma.service';
import { LabOrgGuard } from '../../common/guards/lab-org.guard'; import { LabOrgGuard } from '../../common/guards/lab-org.guard';
import { TreatmentCatalogModule } from '../treatment-catalog/treatment-catalog.module';
import { CasesController } from './cases.controller'; import { CasesController } from './cases.controller';
import { CasesService } from './cases.service'; import { CasesService } from './cases.service';
@Module({ @Module({
imports: [TreatmentCatalogModule],
controllers: [CasesController], controllers: [CasesController],
providers: [CasesService, PrismaService, LabOrgGuard], providers: [CasesService, PrismaService, LabOrgGuard],
exports: [CasesService],
}) })
export class CasesModule {} export class CasesModule {}

View File

@@ -156,6 +156,86 @@ export class CasesService {
}; };
} }
/** Cases exchanged between one clinic and one lab (Organizations connection history). */
async listBetweenOrganizations(
clinicOrganizationId: string,
labOrganizationId: string,
query: ListLabCasesDto,
) {
if (query.treatmentType) {
this.treatmentCatalog.assertKnownTreatmentType(query.treatmentType);
}
const page = query.page ?? 1;
const limit = Math.min(Math.max(query.limit ?? 20, 1), 100);
const skip = (page - 1) * limit;
const where: Prisma.LabCaseWhereInput = {
...this.buildListWhere(labOrganizationId, query),
treatment: { organizationId: clinicOrganizationId },
sends: { some: { organizationId: labOrganizationId } },
};
const [items, total] = await Promise.all([
this.prisma.labCase.findMany({
where,
include: {
treatment: {
include: {
organization: { select: { id: true, name: true } },
patient: { select: { id: true, firstName: true, lastName: true, mobile: true } },
},
},
details: {
include: {
detail: { select: { treatmentType: true } },
},
},
tasks: { select: { id: true, status: true } },
},
orderBy: [{ sentAt: 'desc' }],
skip,
take: limit,
}),
this.prisma.labCase.count({ where }),
]);
return {
success: true,
data: {
items: items.map((lc) => this.mapLabCaseListItem(lc)),
pagination: {
page,
limit,
total,
totalPages: Math.max(1, Math.ceil(total / limit)),
},
},
};
}
async getOneBetweenOrganizations(
labCaseId: string,
clinicOrganizationId: string,
labOrganizationId: string,
) {
const labCase = await this.prisma.labCase.findFirst({
where: {
id: labCaseId,
sentAt: { not: null },
treatment: { organizationId: clinicOrganizationId },
sends: { some: { organizationId: labOrganizationId } },
},
include: labCaseListInclude,
});
if (!labCase) {
throw new NotFoundException('Case not found');
}
return { success: true, data: this.mapLabCaseDetail(labCase) };
}
async getOne(labCaseId: string, labOrganizationId: string, actorUserId: string) { async getOne(labCaseId: string, labOrganizationId: string, actorUserId: string) {
await this.assertCanReadCases(actorUserId, labOrganizationId); await this.assertCanReadCases(actorUserId, labOrganizationId);

View File

@@ -18,6 +18,7 @@ import { InviteOrganizationDto } from './dto/invite-organization.dto';
import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto'; import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto';
import { RespondConnectionRequestDto } from './dto/respond-connection-request.dto'; import { RespondConnectionRequestDto } from './dto/respond-connection-request.dto';
import { OrganizationService } from './organization.service'; import { OrganizationService } from './organization.service';
import { ListLabCasesDto } from '../cases/dto/cases.dto';
/** /**
* Counterpart orgs (clinic↔lab). * Counterpart orgs (clinic↔lab).
@@ -121,6 +122,40 @@ export class OrganizationController {
return this.organizationService.deleteConnection(req.user.id, organizationId, connectionId); return this.organizationService.deleteConnection(req.user.id, organizationId, connectionId);
} }
@Get('connections/:connectionId/cases')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'List cases exchanged with a connected organization' })
listConnectionCases(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('connectionId') connectionId: string,
@Query() query: ListLabCasesDto,
) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.listConnectionCases(
req.user.id,
organizationId,
connectionId,
query,
);
}
@Get('connections/:connectionId/cases/:caseId')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Get one case exchanged with a connected organization' })
getConnectionCase(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('connectionId') connectionId: string,
@Param('caseId') caseId: string,
) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.getConnectionCase(
req.user.id,
organizationId,
connectionId,
caseId,
);
}
@Post('invitations/:invitationId/link') @Post('invitations/:invitationId/link')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Get a shareable invite link for a pending invitation' }) @ApiOperation({ summary: 'Get a shareable invite link for a pending invitation' })

View File

@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service'; import { PrismaService } from '../../../prisma/prisma.service';
import { CasesModule } from '../cases/cases.module';
import { OrganizationController } from './organization.controller'; import { OrganizationController } from './organization.controller';
import { OrganizationService } from './organization.service'; import { OrganizationService } from './organization.service';
@Module({ @Module({
imports: [CasesModule],
controllers: [OrganizationController], controllers: [OrganizationController],
providers: [OrganizationService, PrismaService], providers: [OrganizationService, PrismaService],
}) })

View File

@@ -9,6 +9,8 @@ import { LinkStatus } from '@prisma/client';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { createHash, randomBytes } from 'crypto'; import { createHash, randomBytes } from 'crypto';
import { PrismaService } from '../../../prisma/prisma.service'; import { PrismaService } from '../../../prisma/prisma.service';
import { ListLabCasesDto } from '../cases/dto/cases.dto';
import { CasesService } from '../cases/cases.service';
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto'; import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto'; import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
import { InviteOrganizationDto } from './dto/invite-organization.dto'; import { InviteOrganizationDto } from './dto/invite-organization.dto';
@@ -28,7 +30,10 @@ import { RespondConnectionRequestDto } from './dto/respond-connection-request.dt
*/ */
@Injectable() @Injectable()
export class OrganizationService { export class OrganizationService {
constructor(private readonly prisma: PrismaService) {} constructor(
private readonly prisma: PrismaService,
private readonly casesService: CasesService,
) {}
getOrganizationIdFromUser(user: { organizationId?: string }) { getOrganizationIdFromUser(user: { organizationId?: string }) {
if (!user?.organizationId) { if (!user?.organizationId) {
@@ -340,6 +345,64 @@ export class OrganizationService {
}; };
} }
async listConnectionCases(
userId: string,
organizationId: string,
connectionId: string,
query: ListLabCasesDto,
) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditOrganizations(actor)) {
throw new ForbiddenException('You do not have permission to manage organizations');
}
const { clinicOrganizationId, labOrganizationId, counterpart } =
await this.resolveActiveConnectionParties(connectionId, organizationId, actor);
const result = await this.casesService.listBetweenOrganizations(
clinicOrganizationId,
labOrganizationId,
query,
);
return {
...result,
data: {
...result.data,
counterpart,
},
};
}
async getConnectionCase(
userId: string,
organizationId: string,
connectionId: string,
caseId: string,
) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditOrganizations(actor)) {
throw new ForbiddenException('You do not have permission to manage organizations');
}
const { clinicOrganizationId, labOrganizationId, counterpart } =
await this.resolveActiveConnectionParties(connectionId, organizationId, actor);
const result = await this.casesService.getOneBetweenOrganizations(
caseId,
clinicOrganizationId,
labOrganizationId,
);
return {
...result,
data: {
...result.data,
counterpart,
},
};
}
/** Re-issue a shareable URL for a pending invitation (rotates token; previous URL stops working). */ /** Re-issue a shareable URL for a pending invitation (rotates token; previous URL stops working). */
async getInvitationLink(userId: string, organizationId: string, invitationId: string) { async getInvitationLink(userId: string, organizationId: string, invitationId: string) {
const actor = await this.getActorMembership(userId, organizationId); const actor = await this.getActorMembership(userId, organizationId);
@@ -640,6 +703,58 @@ export class OrganizationService {
}; };
} }
private async resolveActiveConnectionParties(
connectionId: string,
organizationId: string,
actor: {
organization: { type: { name: string } };
},
) {
const link = await this.prisma.organizationLink.findFirst({
where: {
id: connectionId,
status: LinkStatus.ACTIVE,
OR: [{ organizationAId: organizationId }, { organizationBId: organizationId }],
},
include: {
organizationA: { select: { id: true, name: true, type: true } },
organizationB: { select: { id: true, name: true, type: true } },
},
});
if (!link) {
throw new NotFoundException('Connected organization not found');
}
const counterpart =
link.organizationAId === organizationId ? link.organizationB : link.organizationA;
const orgType = actor.organization.type.name;
if (orgType === 'CLINIC') {
if (counterpart.type.name !== 'LAB') {
throw new BadRequestException('Counterpart organization is not a lab');
}
return {
clinicOrganizationId: organizationId,
labOrganizationId: counterpart.id,
counterpart: { id: counterpart.id, name: counterpart.name },
};
}
if (orgType === 'LAB') {
if (counterpart.type.name !== 'CLINIC') {
throw new BadRequestException('Counterpart organization is not a clinic');
}
return {
clinicOrganizationId: counterpart.id,
labOrganizationId: organizationId,
counterpart: { id: counterpart.id, name: counterpart.name },
};
}
throw new BadRequestException('Unknown organization type');
}
private async getActorMembership(userId: string, organizationId: string) { private async getActorMembership(userId: string, organizationId: string) {
return this.prisma.membership.findFirst({ return this.prisma.membership.findFirst({
where: { userId, organizationId }, where: { userId, organizationId },

View File

@@ -606,7 +606,16 @@
"continueArrow": "Continue →", "continueArrow": "Continue →",
"planLabel": "Plan: {name} • {maxUsers} users", "planLabel": "Plan: {name} • {maxUsers} users",
"counterpartClinic": "Clinic", "counterpartClinic": "Clinic",
"counterpartLab": "Lab" "counterpartLab": "Lab",
"viewCaseHistory": "View case history",
"caseHistoryBackToConnections": "← Back to connections",
"caseHistoryTitle": "Case history with {name}",
"caseHistorySubtitleClinic": "Cases you sent to this lab, including lab workflow status for each step.",
"caseHistorySubtitleLab": "Cases received from this clinic, including task status for each step.",
"caseHistoryEmpty": "No cases exchanged with this organization yet.",
"caseHistorySentToLab": "Sent to {name}",
"caseHistoryErrorLoadList": "Failed to load case history.",
"caseHistoryErrorLoadDetail": "Failed to load case details."
}, },
"settings": { "settings": {
"accountTitle": "Account", "accountTitle": "Account",

View File

@@ -606,7 +606,16 @@
"continueArrow": "ادامه →", "continueArrow": "ادامه →",
"planLabel": "طرح: {name} • {maxUsers} کاربر", "planLabel": "طرح: {name} • {maxUsers} کاربر",
"counterpartClinic": "کلینیک", "counterpartClinic": "کلینیک",
"counterpartLab": "لابراتوار" "counterpartLab": "لابراتوار",
"viewCaseHistory": "مشاهده تاریخچه پرونده‌ها",
"caseHistoryBackToConnections": "← بازگشت به اتصالات",
"caseHistoryTitle": "تاریخچه پرونده با {name}",
"caseHistorySubtitleClinic": "پرونده‌هایی که به این لابراتوار ارسال کرده‌اید، شامل وضعیت گردش کار لابراتوار برای هر مرحله.",
"caseHistorySubtitleLab": "پرونده‌های دریافتی از این کلینیک، شامل وضعیت وظایف برای هر مرحله.",
"caseHistoryEmpty": "هنوز پرونده‌ای با این سازمان رد و بدل نشده است.",
"caseHistorySentToLab": "ارسال شده به {name}",
"caseHistoryErrorLoadList": "بارگذاری تاریخچه پرونده ناموفق بود.",
"caseHistoryErrorLoadDetail": "بارگذاری جزئیات پرونده ناموفق بود."
}, },
"settings": { "settings": {
"accountTitle": "حساب کاربری", "accountTitle": "حساب کاربری",

View File

@@ -606,7 +606,16 @@
"continueArrow": "Doorgaan →", "continueArrow": "Doorgaan →",
"planLabel": "Plan: {name} • {maxUsers} gebruikers", "planLabel": "Plan: {name} • {maxUsers} gebruikers",
"counterpartClinic": "Kliniek", "counterpartClinic": "Kliniek",
"counterpartLab": "Laboratorium" "counterpartLab": "Laboratorium",
"viewCaseHistory": "Casusgeschiedenis bekijken",
"caseHistoryBackToConnections": "← Terug naar verbindingen",
"caseHistoryTitle": "Casusgeschiedenis met {name}",
"caseHistorySubtitleClinic": "Cases die u naar dit lab hebt gestuurd, inclusief lab-workflowstatus per stap.",
"caseHistorySubtitleLab": "Cases ontvangen van deze kliniek, inclusief taakstatus per stap.",
"caseHistoryEmpty": "Nog geen cases uitgewisseld met deze organisatie.",
"caseHistorySentToLab": "Verzonden naar {name}",
"caseHistoryErrorLoadList": "Casusgeschiedenis laden mislukt.",
"caseHistoryErrorLoadDetail": "Casusdetails laden mislukt."
}, },
"settings": { "settings": {
"accountTitle": "Account", "accountTitle": "Account",

View File

@@ -3,7 +3,7 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { useToast } from '@/lib/hooks/useToast'; import { useToast } from '@/lib/hooks/useToast';
import { Check, Trash2, UserPlus, X } from 'lucide-react'; import { Check, History, Trash2, UserPlus, X } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { notifyPendingConnectionsChanged } from '@/lib/hooks/usePendingConnectionsCount'; import { notifyPendingConnectionsChanged } from '@/lib/hooks/usePendingConnectionsCount';
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy'; import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
@@ -16,6 +16,7 @@ import {
import { invitationTargetFromConnectionRow } from '@/components/invitations/organizationInviteLinks'; import { invitationTargetFromConnectionRow } from '@/components/invitations/organizationInviteLinks';
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton'; import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog'; import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
import { ConnectionCaseHistoryContent } from '@/components/ui/organizations/ConnectionCaseHistoryContent';
import { Button } from '@/components/ui/shared/Button'; import { Button } from '@/components/ui/shared/Button';
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge'; import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge';
import { Input } from '@/components/ui/shared/Input'; import { Input } from '@/components/ui/shared/Input';
@@ -90,6 +91,9 @@ export default function OrganizationsPage() {
const [historyOpen, setHistoryOpen] = useState(false); const [historyOpen, setHistoryOpen] = useState(false);
const [historyLoading, setHistoryLoading] = useState(false); const [historyLoading, setHistoryLoading] = useState(false);
const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]); const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]);
const [caseHistoryConnection, setCaseHistoryConnection] = useState<CounterpartItemDto | null>(
null,
);
const { const {
copiedId, copiedId,
@@ -289,6 +293,15 @@ export default function OrganizationsPage() {
return <p className="text-sm text-text-secondary">{t('loadingOrganization')}</p>; return <p className="text-sm text-text-secondary">{t('loadingOrganization')}</p>;
} }
if (caseHistoryConnection) {
return (
<ConnectionCaseHistoryContent
connection={caseHistoryConnection}
onBack={() => setCaseHistoryConnection(null)}
/>
);
}
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between"> <div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
@@ -426,16 +439,27 @@ export default function OrganizationsPage() {
</> </>
)} )}
{row.status === 'ACTIVE' && ( {row.status === 'ACTIVE' && (
<button <>
type="button" <button
className="p-2 rounded-md text-text-secondary hover:bg-red-500/15 hover:text-red-600 disabled:text-text-muted disabled:opacity-50" type="button"
disabled={deleteConnectionRowId !== null && deleteConnectionRowId !== row.id} className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
onClick={() => void deleteConnection(row.id)} onClick={() => setCaseHistoryConnection(row)}
aria-label={t('removeConnection')} aria-label={t('viewCaseHistory')}
title={t('removeConnection')} title={t('viewCaseHistory')}
> >
<Trash2 className="w-4 h-4" /> <History className="w-4 h-4" />
</button> </button>
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-red-500/15 hover:text-red-600 disabled:text-text-muted disabled:opacity-50"
disabled={deleteConnectionRowId !== null && deleteConnectionRowId !== row.id}
onClick={() => void deleteConnection(row.id)}
aria-label={t('removeConnection')}
title={t('removeConnection')}
>
<Trash2 className="w-4 h-4" />
</button>
</>
)} )}
</div> </div>
</td> </td>

View File

@@ -0,0 +1,407 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { organizationApi } from '@/lib/api/organization';
import { Badge, type BadgeVariant } 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 type { CounterpartItemDto } from '@/lib/api/organization';
import type { LabCaseDetail, LabCaseListItem, LabTaskStatus } from '@/types/cases';
const TREATMENT_TYPE_KEYS = {
consultation: 'typeConsultation',
filling: 'typeFilling',
endo: 'typeEndo',
visit: 'typeVisit',
hygiene: 'typeHygiene',
} as const;
const PAGE_SIZE = 20;
function taskStatusVariant(status: LabTaskStatus): BadgeVariant {
switch (status) {
case 'COMPLETED':
return 'success';
case 'IN_PROGRESS':
return 'default';
default:
return 'warning';
}
}
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;
}
export function ConnectionCaseHistoryContent({
connection,
onBack,
}: ConnectionCaseHistoryContentProps) {
const t = useTranslations('organizations');
const tCases = useTranslations('cases');
const tTreatment = useTranslations('treatment');
const tCommon = useTranslations('common');
const { currentOrganization, user } = useAuth();
const { showError, setError, messages: toastMessages } = useToast();
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [cases, setCases] = useState<LabCaseListItem[]>([]);
const [pagination, setPagination] = useState({
page: 1,
limit: PAGE_SIZE,
total: 0,
totalPages: 1,
});
const [selectedCaseId, setSelectedCaseId] = useState<string | null>(null);
const [selectedCase, setSelectedCase] = useState<LabCaseDetail | null>(null);
const [loadingList, setLoadingList] = useState(false);
const [loadingDetail, setLoadingDetail] = useState(false);
const locale = user?.language ?? 'en';
const isClinic = currentOrganization?.type === 'CLINIC';
const tRef = useRef(t);
tRef.current = t;
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: tCases('statusPending') },
{ value: 'IN_PROGRESS', label: tCases('statusInProgress') },
{ value: 'COMPLETED', label: tCases('statusCompleted') },
],
[tCases],
);
useEffect(() => {
let cancelled = false;
const timeout = setTimeout(() => {
void (async () => {
setLoadingList(true);
setError('');
try {
const response = await organizationApi.listConnectionCases(connection.id, {
q: search.trim() || undefined,
page,
limit: PAGE_SIZE,
});
if (cancelled) return;
setCases(response.data.items);
setPagination(response.data.pagination);
} catch (error: unknown) {
if (cancelled) return;
showError(formatApiErrorMessage(error, tRef.current('caseHistoryErrorLoadList')));
} finally {
if (!cancelled) setLoadingList(false);
}
})();
}, search ? 300 : 0);
return () => {
cancelled = true;
clearTimeout(timeout);
};
}, [search, page, connection.id, showError, setError]);
useEffect(() => {
if (!selectedCaseId) {
setSelectedCase(null);
return;
}
let cancelled = false;
void (async () => {
setLoadingDetail(true);
setError('');
try {
const response = await organizationApi.getConnectionCase(connection.id, selectedCaseId);
if (cancelled) return;
setSelectedCase(response.data);
} catch (error: unknown) {
if (cancelled) return;
showError(formatApiErrorMessage(error, tRef.current('caseHistoryErrorLoadDetail')));
setSelectedCase(null);
} finally {
if (!cancelled) setLoadingDetail(false);
}
})();
return () => {
cancelled = true;
};
}, [selectedCaseId, connection.id, showError, setError]);
return (
<div className="space-y-6">
<div>
<button
type="button"
onClick={onBack}
className="text-sm text-primary hover:opacity-90"
>
{t('caseHistoryBackToConnections')}
</button>
</div>
<div>
<h1 className="text-2xl font-semibold text-text-primary">
{t('caseHistoryTitle', { name: connection.organizationName })}
</h1>
<p className="text-sm text-text-secondary mt-1">
{isClinic ? t('caseHistorySubtitleClinic') : t('caseHistorySubtitleLab')}
</p>
</div>
<ToastStack {...toastMessages} />
<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={tCases('searchPlaceholder')}
/>
<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('caseHistoryEmpty')}</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>
{!isClinic ? (
<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)}
</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))}
>
{tCases('prevPage')}
</Button>
<span className="text-xs text-text-muted text-center">
{tCases('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)}
>
{tCases('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">{tCases('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">
{tCases('patientMobile')}: {selectedCase.patient.mobile}
</p>
{!isClinic ? (
<p className="text-sm text-text-muted">
{tCases('fromClinic', { name: selectedCase.clinic.name })}
</p>
) : (
<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>
{selectedCase.labComment ? (
<p className="text-sm text-text-muted pt-1">
<span className="font-medium text-text-primary">{tCases('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">
{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) => (
<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">
{tCases('toothGroupTitle', {
tooth: group.tooth,
type: treatmentLabel(group.treatmentType),
})}
</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={taskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
</li>
))}
</ul>
</div>
))
)}
</div>
</div>
)}
</section>
</div>
</div>
);
}

View File

@@ -1,4 +1,9 @@
import { apiClient } from './client'; import { apiClient } from './client';
import type {
LabCaseDetail,
ListLabCasesParams,
PaginatedLabCases,
} from '@/types/cases';
export interface CounterpartSearchResultDto { export interface CounterpartSearchResultDto {
id: string; id: string;
@@ -130,4 +135,30 @@ export const organizationApi = {
const response = await apiClient.post('/organizations/invitations/accept', body); const response = await apiClient.post('/organizations/invitations/accept', body);
return response.data; return response.data;
}, },
listConnectionCases: async (
connectionId: string,
params: ListLabCasesParams = {},
): Promise<{
success: boolean;
data: PaginatedLabCases & { counterpart: { id: string; name: string } };
}> => {
const response = await apiClient.get(`/organizations/connections/${connectionId}/cases`, {
params,
});
return response.data;
},
getConnectionCase: async (
connectionId: string,
caseId: string,
): Promise<{
success: boolean;
data: LabCaseDetail & { counterpart: { id: string; name: string } };
}> => {
const response = await apiClient.get(
`/organizations/connections/${connectionId}/cases/${caseId}`,
);
return response.data;
},
}; };