feat(patients): inline tag popover + advanced filters on the records list

Port the remaining pieces of tauri /files list into /admin/patients:

- inline tag assignment: the برچسب‌ها cell (table + card) opens a popover to
  assign/remove tenant tags without leaving the list. Uses existing endpoints
  (GET /api/v1/tenant-tags + PATCH /api/v1/patient/{uuid} { tags:[uuid] }).
  New component assets/admin/components/PatientTagsCell.tsx.
- advanced filter modal (PatientsFilterModal): admission date range, insurance,
  service status (pending/completed), has-debt, gender, tags — wired to the
  list query with an active-filter badge on the button.

Backend: GET /api/v1/patients gains tags/gender/insurance_id/admitted_from/
admitted_to/service_status/has_debt filters via a shared applyFilters() on
PatientRecordRepository (findByEntity + countByEntity stay consistent). Debt
and service status derive from unpaid sessions (payment_method='pending'),
documented in docs/api/patient.md.

Tests: tests/Patient/PatientListFilterTest.php (5) + PatientsListPage tag-popover
and filter-apply tests. Pre-existing LoginPage.test failures are unrelated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-14 19:40:54 +03:30
co-authored by Claude Opus 4.8
parent 4edeffe325
commit fd91840ba2
8 changed files with 578 additions and 52 deletions
+37 -10
View File
@@ -1,7 +1,8 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
@@ -11,16 +12,21 @@ import { api } from '../lib/api';
import PatientsListPage from './PatientsListPage';
const get = api.get as ReturnType<typeof vi.fn>;
const patch = api.patch as ReturnType<typeof vi.fn>;
const PATIENTS = [
{ uuid: 'r1', user_name: 'دنیا خلیلی', user_mobile: '09165401233', user_national_code: '1744023654', record_number: '123456789', tags: [{ uuid: 't1', name: 'فوری', color: '#F00' }] },
{ uuid: 'r2', user_name: 'علی بدیعی زاده', user_mobile: '09165401233', user_national_code: null, record_number: '123456789', tags: [] },
];
beforeEach(() => {
get.mockReset();
get.mockResolvedValue({
success: true,
data: [
{ uuid: 'r1', user_name: 'دنیا خلیلی', user_mobile: '09165401233', user_national_code: '1744023654', record_number: '123456789', tags: [{ uuid: 't1', name: 'فوری', color: '#F00' }] },
{ uuid: 'r2', user_name: 'علی بدیعی زاده', user_mobile: '09165401233', user_national_code: null, record_number: '123456789', tags: [] },
],
meta: { totalRecords: 2 },
patch.mockReset();
patch.mockResolvedValue({ success: true, data: {} });
get.mockImplementation((url: string) => {
if (url.includes('/tenant-tags')) return Promise.resolve({ success: true, data: [{ uuid: 'tag1', name: 'خوش‌حساب', color: '#0a0', active: true }] });
if (url.includes('/insurance-pricing')) return Promise.resolve({ success: true, data: { insurances: [{ insurance_id: 1, insurance_name: 'تأمین اجتماعی', type: 'basic' }] } });
return Promise.resolve({ success: true, data: PATIENTS, meta: { totalRecords: 2 } });
});
});
@@ -30,8 +36,8 @@ describe('PatientsListPage (پرونده‌ها)', () => {
expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getByText('علی بدیعی زاده')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /تشکیل پرونده/ })).toBeInTheDocument();
// record with no tags shows the "add" link
expect(screen.getByText('+ اضافه کردن')).toBeInTheDocument();
// record with no tags shows the inline "add" trigger
expect(screen.getByText('اضافه کردن')).toBeInTheDocument();
});
it('switches to the card view', async () => {
@@ -41,4 +47,25 @@ describe('PatientsListPage (پرونده‌ها)', () => {
expect(screen.getByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getAllByText('مشاهده').length).toBeGreaterThan(0);
});
it('assigns a tag inline through the برچسب‌ها popover', async () => {
renderWithProviders(<PatientsListPage />, { route: '/admin/patients' });
await screen.findByText('علی بدیعی زاده');
fireEvent.click(screen.getByText('اضافه کردن')); // open popover for the untagged record (r2)
fireEvent.click(await screen.findByText('خوش‌حساب')); // toggle the tenant tag
await waitFor(() => expect(patch).toHaveBeenCalledWith('/api/v1/patient/r2', { tags: ['tag1'] }));
});
it('applies an advanced filter and re-queries with the param', async () => {
renderWithProviders(<PatientsListPage />, { route: '/admin/patients' });
await screen.findByText('دنیا خلیلی');
fireEvent.click(screen.getByLabelText('فیلترها'));
fireEvent.click(await screen.findByLabelText('فقط پرونده‌های دارای بدهی'));
fireEvent.click(screen.getByRole('button', { name: 'اعمال تغییرات' }));
await waitFor(() => expect(get.mock.calls.some(([u]) => String(u).includes('has_debt=1'))).toBe(true));
});
});
+47 -19
View File
@@ -8,25 +8,27 @@ import {
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { formatNumber } from '../lib/utils';
import { formatNumber, toDate } from '../lib/utils';
import Pagination from '../components/ui/Pagination';
import PatientTagsCell from '../components/PatientTagsCell';
import PatientsFilterModal, { type PatientFilters } from '../components/PatientsFilterModal';
const LIMIT = 20;
const EMPTY: PatientRecord[] = [];
function TagDots({ tags }: { tags?: PatientRecord['tags'] }) {
if (!tags || tags.length === 0) return null;
return (
<span style={{ display: 'inline-flex', alignItems: 'center' }}>
{tags.slice(0, 3).map((t, i) => (
<span key={t.uuid} title={t.name} style={{
width: 16, height: 16, borderRadius: '50%', background: t.color,
border: '2px solid var(--surface)', marginInlineStart: i === 0 ? 0 : -6,
}} />
))}
{tags.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-3)', marginInlineStart: 4 }}>+{formatNumber(tags.length - 3)}</span>}
</span>
);
/** unix start-of-day for `from`, end-of-day for `to`, from a gregorian Y-m-d. */
function dayBound(value: string | undefined, end: boolean): number | undefined {
if (!value) return undefined;
const d = toDate(value);
if (!d) return undefined;
const secs = Math.floor(d.setHours(0, 0, 0, 0) / 1000);
return end ? secs + 86399 : secs;
}
/** Number of filters currently applied (for the button badge). */
function countFilters(f: PatientFilters): number {
return [f.gender, f.insurance_id, f.admitted_from, f.admitted_to, f.service_status, f.has_debt || undefined, f.tags?.length ? '1' : undefined]
.filter(Boolean).length;
}
/** پرونده‌ها — patient records list (table + card views) matching the Figma design. */
@@ -35,12 +37,28 @@ export default function PatientsListPage() {
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [view, setView] = useState<'table' | 'card'>('table');
const [filterOpen, setFilterOpen] = useState(false);
const [filters, setFilters] = useState<PatientFilters>({});
const qs = new URLSearchParams({ page: String(page), limit: String(LIMIT) });
if (search) qs.set('search', search);
if (filters.gender) qs.set('gender', filters.gender);
if (filters.insurance_id) qs.set('insurance_id', filters.insurance_id);
if (filters.service_status) qs.set('service_status', filters.service_status);
if (filters.has_debt) qs.set('has_debt', '1');
if (filters.tags?.length) qs.set('tags', filters.tags.join(','));
const af = dayBound(filters.admitted_from, false);
const at = dayBound(filters.admitted_to, true);
if (af) qs.set('admitted_from', String(af));
if (at) qs.set('admitted_to', String(at));
const { data, isLoading } = useQuery<ApiResponse<PatientRecord[]> & { meta?: { totalRecords: number } }>({
queryKey: ['patients', page, search],
queryFn: () => api.get(`/api/v1/patients?page=${page}&limit=${LIMIT}&search=${encodeURIComponent(search)}`),
queryKey: ['patients', qs.toString()],
queryFn: () => api.get(`/api/v1/patients?${qs.toString()}`),
});
const activeFilters = countFilters(filters);
const records = data?.data ?? EMPTY;
const total = data?.meta?.totalRecords ?? 0;
@@ -70,8 +88,11 @@ export default function PatientsListPage() {
<TableCellsIcon style={{ width: 18 }} />
</button>
</div>
<button className="btn" aria-label="فیلترها" style={{ height: 40, width: 44, padding: 0, display: 'grid', placeItems: 'center' }}>
<button className="btn" aria-label="فیلترها" onClick={() => setFilterOpen(true)} style={{ height: 40, position: 'relative', width: 44, padding: 0, display: 'grid', placeItems: 'center', color: activeFilters ? 'var(--primary)' : undefined }}>
<AdjustmentsHorizontalIcon style={{ width: 18 }} />
{activeFilters > 0 && (
<span style={{ position: 'absolute', top: -6, insetInlineEnd: -6, minWidth: 16, height: 16, padding: '0 4px', borderRadius: 999, background: 'var(--primary)', color: '#fff', fontSize: 10, display: 'grid', placeItems: 'center' }}>{formatNumber(activeFilters)}</span>
)}
</button>
<button className="btn primary" style={{ height: 40 }} onClick={() => navigate('/admin/patients/new')}>
<PlusIcon style={{ width: 16 }} /> تشکیل پرونده
@@ -107,7 +128,7 @@ export default function PatientsListPage() {
</span>
</td>
<td style={{ padding: '12px 14px' }}>
{r.tags && r.tags.length > 0 ? <TagDots tags={r.tags} /> : <Link to={editHref(r)} style={{ color: 'var(--primary)', fontSize: 12.5, textDecoration: 'none' }}>+ اضافه کردن</Link>}
<PatientTagsCell record={r} />
</td>
<td style={{ padding: '12px 14px' }}>{r.record_number || '—'}</td>
<td style={{ padding: '12px 14px', direction: 'ltr' }}>{r.user_mobile || '—'}</td>
@@ -129,7 +150,7 @@ export default function PatientsListPage() {
<div key={r.uuid} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
<span style={{ fontWeight: 700, fontSize: 15 }}>{r.user_name || '—'}</span>
<TagDots tags={r.tags} />
<PatientTagsCell record={r} />
</div>
<div style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
<span>شماره پرونده: {r.record_number || '—'}</span>
@@ -148,6 +169,13 @@ export default function PatientsListPage() {
<div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}>
<Pagination page={page} total={total} limit={LIMIT} onPageChange={setPage} />
</div>
<PatientsFilterModal
open={filterOpen}
value={filters}
onClose={() => setFilterOpen(false)}
onApply={(f) => { setFilters(f); setPage(1); setFilterOpen(false); }}
/>
</div>
);
}