improvement: some files replaced, lots of them i shall say. AGENT.MD file created. some rules and skills added for cursor agent.

This commit is contained in:
2026-07-12 21:08:29 +03:30
parent 1cdf853d32
commit 0d3fb0a51d
86 changed files with 4758 additions and 4260 deletions

View File

@@ -8,7 +8,7 @@ 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 { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
import { Button } from '@/components/ui/shared/Button';
import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton';
import { SearchBar } from '@/components/ui/shared/SearchBar';
@@ -18,7 +18,7 @@ import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
import {
formatCaseDateTime,
formatPatientName,
} from '@/components/ui/lab/caseDetailUtils';
} from '@/components/lab/caseDetailUtils';
import { treatmentsApi } from '@/lib/api/treatments';
import { casesApi } from '@/lib/api/cases';
import type { CounterpartItemDto } from '@/lib/api/organization';

View File

@@ -9,7 +9,8 @@ import {
} from '@/components/ui/shared/ResponsiveDialog';
import { ToastStack, type ToastMessages } from '@/components/ui/shared/Toast';
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge';
import { Badge } from '@/components/ui/shared/Badge';
import { organizationConnectionStatusVariant } from '@/components/organizations/connectionStatusVariant';
import { Table } from '@/components/ui/shared/Table';
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';

View File

@@ -5,7 +5,8 @@ import type {
CounterpartItemDto,
CounterpartSearchResultDto,
} from '@/lib/api/organization';
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge';
import { Badge } from '@/components/ui/shared/Badge';
import { organizationConnectionStatusVariant } from '@/components/organizations/connectionStatusVariant';
import { Button } from '@/components/ui/shared/Button';
import { Card } from '@/components/ui/shared/Card';
import { Input } from '@/components/ui/shared/Input';

View File

@@ -0,0 +1,603 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useToast } from '@/lib/hooks/useToast';
import { Check, History, Trash2, UserPlus, X } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { notifyPendingConnectionsChanged } from '@/lib/hooks/usePendingConnectionsCount';
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
import {
organizationApi,
type CounterpartItemDto,
type CounterpartSearchResultDto,
type OrganizationInvitationHistoryItemDto,
} from '@/lib/api/organization';
import { invitationTargetFromConnectionRow } from '@/components/invitations/organizationInviteLinks';
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';
import { OrganizationConnectionsMobileList } from '@/components/ui/organizations/OrganizationConnectionsMobileList';
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
import { ConnectionCaseHistoryContent } from '@/components/ui/organizations/ConnectionCaseHistoryContent';
import { Button } from '@/components/ui/shared/Button';
import { Badge } from '@/components/ui/shared/Badge';
import { organizationConnectionStatusVariant } from '@/components/organizations/connectionStatusVariant';
import { Input } from '@/components/ui/shared/Input';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { Table } from '@/components/ui/shared/Table';
import { ToastStack } from '@/components/ui/shared/Toast';
import { getUserFacingError } from '@/components/shared/formatApiError';
function formatOrganizationStatusLabel(status: string): string {
if (!status) return status;
const lower = status.toLowerCase();
return lower.charAt(0).toUpperCase() + lower.slice(1);
}
function formatTableDate(value: string): string {
const d = new Date(value);
if (Number.isNaN(d.getTime())) return '\u2014';
return d.toLocaleDateString();
}
type TableMode = 'existing' | 'search';
export function OrganizationsPage() {
const t = useTranslations('organizations');
const tErrors = useTranslations('errors');
const tNav = useTranslations('nav');
const tCommon = useTranslations('common');
const { currentOrganization } = useAuth();
const [loading, setLoading] = useState(true);
const toast = useToast();
const { showError, setError: setToastError } = toast;
const formatApiMessage = useCallback(
(err: unknown): string => getUserFacingError(err, tErrors, tCommon('errorGeneric')),
[tCommon, tErrors],
);
const formatConnectionStatusLabel = useCallback(
(row: CounterpartItemDto, currentOrganizationId: string): string => {
if (row.status === 'PENDING') {
if (
row.pendingInvitationId &&
row.requestedByOrganizationId === currentOrganizationId
) {
return t('statusInvitationPending');
}
return t('statusConnectionPending');
}
if (row.status === 'ACTIVE') return t('statusConnected');
if (row.status === 'REJECTED') return t('statusDeclined');
return formatOrganizationStatusLabel(row.status);
},
[t],
);
const [query, setQuery] = useState('');
const [mode, setMode] = useState<TableMode>('existing');
const [searching, setSearching] = useState(false);
const [searchResults, setSearchResults] = useState<CounterpartSearchResultDto[]>([]);
const [pendingConnectionRowId, setPendingConnectionRowId] = useState<string | null>(null);
const [deleteConnectionRowId, setDeleteConnectionRowId] = useState<string | null>(null);
const [items, setItems] = useState<CounterpartItemDto[]>([]);
const [manualOrganizationName, setManualOrganizationName] = useState('');
const [manualOwnerEmail, setManualOwnerEmail] = useState('');
const [inviteLoading, setInviteLoading] = useState(false);
const [showInviteForm, setShowInviteForm] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]);
const [caseHistoryConnection, setCaseHistoryConnection] = useState<CounterpartItemDto | null>(
null,
);
const {
copiedId,
copyingInvitationId,
storeInviteLink,
copyInvitationLink,
pruneAcceptedLinks,
} = useOrganizationInviteLinkCopy(currentOrganization?.id);
const counterpart =
currentOrganization?.type === 'LAB' ? t('counterpartClinic') : t('counterpartLab');
const tabLabel = currentOrganization?.type === 'LAB' ? tNav('clinics') : tNav('labs');
const existingRows = items;
async function loadList() {
setLoading(true);
toast.setError('');
try {
const res = await organizationApi.list();
setItems(res.data.items);
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setLoading(false);
}
}
useEffect(() => {
void loadList();
}, []);
useEffect(() => {
let cancelled = false;
const q = query.trim();
if (!q) {
setMode('existing');
setSearchResults([]);
setShowInviteForm(false);
setSearching(false);
return;
}
setMode('search');
setShowInviteForm(false);
setSearching(true);
const timeout = setTimeout(() => {
void (async () => {
setToastError('');
try {
const res = await organizationApi.search(q);
if (cancelled) return;
setSearchResults(res.data);
} catch (e) {
if (cancelled) return;
showError(formatApiMessage(e));
setSearchResults([]);
} finally {
if (!cancelled) setSearching(false);
}
})();
}, 300);
return () => {
cancelled = true;
clearTimeout(timeout);
};
}, [query, formatApiMessage, showError, setToastError]);
async function submitConnectionRequest(targetOrganizationId: string) {
setPendingConnectionRowId(targetOrganizationId);
toast.setError('');
try {
await organizationApi.createConnectionRequest(targetOrganizationId);
toast.showSuccess(t('successConnectionSent', { counterpart }));
setSearchResults([]);
setQuery('');
setMode('existing');
await loadList();
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setPendingConnectionRowId(null);
}
}
async function sendInvite() {
setInviteLoading(true);
toast.setError('');
try {
const res = await organizationApi.invite({
organizationName: manualOrganizationName.trim(),
ownerEmail: manualOwnerEmail.trim(),
});
storeInviteLink(res.data.invitationId, manualOwnerEmail, res.data.invitationUrl);
toast.showSuccess(t('successInviteCreated', { email: manualOwnerEmail.trim() }));
setManualOrganizationName('');
setManualOwnerEmail('');
setShowInviteForm(false);
setMode('existing');
setQuery('');
setSearchResults([]);
await loadList();
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setInviteLoading(false);
}
}
async function loadInvitationHistory() {
const res = await organizationApi.listInvitations();
setHistoryItems(res.data.items);
pruneAcceptedLinks(res.data.items);
return res.data.items;
}
async function openInvitationHistory() {
setHistoryOpen(true);
setHistoryLoading(true);
toast.clear();
try {
await loadInvitationHistory();
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setHistoryLoading(false);
}
}
async function handleHistoryCopy(invitation: OrganizationInvitationHistoryItemDto) {
toast.setError('');
try {
await copyInvitationLink(invitation, {
onRegenerated: async () => {
await loadInvitationHistory();
},
});
toast.showSuccess(t('successLinkCopied'));
} catch (e) {
toast.showError(formatApiMessage(e));
}
}
async function handleCopyInvitationFromRow(row: CounterpartItemDto) {
const target = invitationTargetFromConnectionRow(row, currentOrganization!.id);
if (!target) return;
toast.setError('');
try {
await copyInvitationLink(
{
id: target.id,
organizationName: row.organizationName,
ownerEmail: target.ownerEmail,
status: target.status,
createdAt: row.createdAt,
acceptedAt: target.acceptedAt,
},
{
onRegenerated: async () => {
await loadList();
},
},
);
toast.showSuccess(t('successLinkCopied'));
} catch (e) {
toast.showError(formatApiMessage(e));
}
}
async function respondToPendingConnection(connectionId: string, action: 'ACCEPT' | 'REJECT') {
setPendingConnectionRowId(connectionId);
toast.setError('');
try {
await organizationApi.respondToConnectionRequest(connectionId, action);
toast.showSuccess(
action === 'ACCEPT' ? t('successAccepted') : t('successDeclined'),
);
notifyPendingConnectionsChanged();
await loadList();
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setPendingConnectionRowId(null);
}
}
async function deleteConnection(connectionId: string) {
setDeleteConnectionRowId(connectionId);
toast.setError('');
try {
await organizationApi.deleteConnection(connectionId);
toast.showSuccess(t('successRemoved'));
await loadList();
} catch (e) {
toast.showError(formatApiMessage(e));
} finally {
setDeleteConnectionRowId(null);
}
}
function clearSearchView() {
setMode('existing');
setQuery('');
setSearchResults([]);
setShowInviteForm(false);
}
if (!currentOrganization) {
return <p className="text-sm text-text-secondary">{t('loadingOrganization')}</p>;
}
if (caseHistoryConnection) {
return (
<ConnectionCaseHistoryContent
connection={caseHistoryConnection}
onBack={() => setCaseHistoryConnection(null)}
/>
);
}
return (
<div className="space-y-6">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
<div>
<h1 className="text-xl sm:text-2xl font-semibold text-text-primary">{tabLabel}</h1>
<p className="text-sm text-text-secondary mt-1">{t('subtitle')}</p>
</div>
<Button type="button" size="sm" className="w-full sm:w-auto shrink-0" onClick={() => void openInvitationHistory()}>
{t('invitationHistory')}
</Button>
</div>
{!historyOpen && <ToastStack {...toast.messages} />}
<SearchBar
value={query}
onChange={setQuery}
placeholder={t('searchPlaceholder', { counterpart: counterpart.toLowerCase() })}
actions={
query.trim() ? (
<button
type="button"
onClick={clearSearchView}
className="px-4 py-2 rounded-[var(--radius-sm)] text-sm font-medium border text-text-secondary border-border/40 hover:bg-background-card/70 hover:border-border"
>
{t('backToList')}
</button>
) : undefined
}
/>
<OrganizationConnectionsMobileList
loading={loading || searching}
mode={mode}
existingRows={existingRows}
searchResults={searchResults}
currentOrganizationId={currentOrganization.id}
counterpart={counterpart}
pendingConnectionRowId={pendingConnectionRowId}
deleteConnectionRowId={deleteConnectionRowId}
copiedId={copiedId}
copyingInvitationId={copyingInvitationId}
showInviteForm={showInviteForm}
manualOrganizationName={manualOrganizationName}
manualOwnerEmail={manualOwnerEmail}
inviteLoading={inviteLoading}
formatConnectionStatusLabel={formatConnectionStatusLabel}
formatTableDate={formatTableDate}
getInvitationTarget={(row) => invitationTargetFromConnectionRow(row, currentOrganization.id)}
onCopyInvitation={(row) => void handleCopyInvitationFromRow(row)}
onRespond={(rowId, action) => void respondToPendingConnection(rowId, action)}
onViewCaseHistory={setCaseHistoryConnection}
onDeleteConnection={(rowId) => void deleteConnection(rowId)}
onSendConnectionRequest={(orgId) => void submitConnectionRequest(orgId)}
onToggleInviteForm={() => setShowInviteForm((v) => !v)}
onManualOrganizationNameChange={setManualOrganizationName}
onManualOwnerEmailChange={setManualOwnerEmail}
onSendInvite={() => void sendInvite()}
labels={{
loading: tCommon('loadingEllipsis'),
emptyConnections: t('emptyConnections'),
noDirectoryResults: t('noDirectoryResults'),
hideInvitationFields: t('hideInvitationFields'),
sendInvitationLink: t('sendInvitationLink'),
counterpartNameLabel: t('counterpartNameLabel', { counterpart }),
ownerEmailLabel: t('ownerEmailLabel'),
sendInvitation: t('sendInvitation'),
sendRequest: t('sendRequest'),
acceptRequest: t('acceptRequest'),
declineRequest: t('declineRequest'),
viewCaseHistory: t('viewCaseHistory'),
removeConnection: t('removeConnection'),
statusToday: t('statusToday'),
statusFound: t('statusFound'),
}}
/>
<div className="hidden lg:block">
<Table
headers={
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableOrganization')}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableOwnerEmail')}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableDate')}
</th>
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableStatus')}
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableAction')}
</th>
</tr>
}
body={
<>
{loading || (mode === 'search' && searching) ? (
<tr>
<td colSpan={5} className="px-6 py-8 text-sm text-text-secondary">
{tCommon('loadingEllipsis')}
</td>
</tr>
) : mode === 'existing' ? (
existingRows.length === 0 ? (
<tr>
<td colSpan={5} className="px-6 py-8 text-sm text-text-secondary">
{t('emptyConnections')}
</td>
</tr>
) : (
existingRows.map((row) => {
const canRespond =
row.status === 'PENDING' &&
row.requestedByOrganizationId !== null &&
row.requestedByOrganizationId !== currentOrganization.id;
const invitationTarget = invitationTargetFromConnectionRow(
row,
currentOrganization.id,
);
return (
<tr key={row.id} className="hover:bg-background-secondary/45">
<td className="px-6 py-1.5 text-sm font-medium text-text-primary">
{row.organizationName}
</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">{row.ownerEmail}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">
{formatTableDate(row.createdAt)}
</td>
<td className="px-6 py-1.5 text-center align-middle">
<Badge variant={organizationConnectionStatusVariant(row.status)} fixedWidth={false}>
{formatConnectionStatusLabel(row, currentOrganization.id)}
</Badge>
</td>
<td className="px-6 py-1.5 text-right">
<div className="inline-flex items-center gap-2">
{invitationTarget && (
<CopyInvitationLinkButton
invitation={invitationTarget}
copied={copiedId === invitationTarget.id}
copying={copyingInvitationId === invitationTarget.id}
onCopy={() => void handleCopyInvitationFromRow(row)}
/>
)}
{canRespond && (
<>
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:text-text-muted disabled:opacity-50"
disabled={pendingConnectionRowId !== null && pendingConnectionRowId !== row.id}
onClick={() => void respondToPendingConnection(row.id, 'ACCEPT')}
aria-label={t('acceptRequest')}
title={t('acceptRequest')}
>
<Check className="w-4 h-4" />
</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={pendingConnectionRowId !== null && pendingConnectionRowId !== row.id}
onClick={() => void respondToPendingConnection(row.id, 'REJECT')}
aria-label={t('declineRequest')}
title={t('declineRequest')}
>
<X className="w-4 h-4" />
</button>
</>
)}
{row.status === 'ACTIVE' && (
<>
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
onClick={() => setCaseHistoryConnection(row)}
aria-label={t('viewCaseHistory')}
title={t('viewCaseHistory')}
>
<History className="w-4 h-4" />
</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>
</td>
</tr>
);
})
)
) : searchResults.length > 0 ? (
searchResults.map((r) => (
<tr key={r.id} className="hover:bg-background-secondary/45">
<td className="px-6 py-1.5 text-sm font-medium text-text-primary">{r.name}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">{r.owner.email}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">{t('statusToday')}</td>
<td className="px-6 py-1.5 text-center align-middle">
<Badge variant="default" fixedWidth={false}>{t('statusFound')}</Badge>
</td>
<td className="px-6 py-1.5 text-right">
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:text-text-muted disabled:opacity-50"
disabled={
pendingConnectionRowId !== null && pendingConnectionRowId !== r.id
}
onClick={() => void submitConnectionRequest(r.id)}
aria-label={t('sendRequest')}
title={t('sendRequest')}
>
<UserPlus className="w-4 h-4" />
</button>
</td>
</tr>
))
) : (
<tr>
<td colSpan={5} className="px-6 py-6">
<div className="flex flex-col gap-3">
<p className="text-sm text-text-secondary">
{t('noDirectoryResults')}
</p>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" onClick={() => setShowInviteForm((v) => !v)}>
{showInviteForm ? t('hideInvitationFields') : t('sendInvitationLink')}
</Button>
</div>
{showInviteForm && (
<div className="grid gap-3 sm:grid-cols-3 mt-1">
<Input
label={t('counterpartNameLabel', { counterpart })}
value={manualOrganizationName}
onChange={(e) => setManualOrganizationName(e.target.value)}
/>
<Input
label={t('ownerEmailLabel')}
type="email"
value={manualOwnerEmail}
onChange={(e) => setManualOwnerEmail(e.target.value)}
/>
<div className="flex items-end">
<Button
type="button"
isLoading={inviteLoading}
disabled={!manualOrganizationName.trim() || !manualOwnerEmail.trim()}
onClick={() => void sendInvite()}
className="w-full"
>
{t('sendInvitation')}
</Button>
</div>
</div>
)}
</div>
</td>
</tr>
)}
</>
}
/>
</div>
<InvitationHistoryDialog
open={historyOpen}
onClose={() => setHistoryOpen(false)}
loading={historyLoading}
items={historyItems}
copiedId={copiedId}
copyingInvitationId={copyingInvitationId}
onCopy={(invitation) => void handleHistoryCopy(invitation)}
toastMessages={toast.messages}
/>
</div>
);
}