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:
@@ -0,0 +1,105 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { PlusIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import { formatNumber } from '../lib/utils';
|
||||
import type { PatientRecord } from '../types';
|
||||
|
||||
interface TenantTag { uuid: string; name: string; color: string; active: boolean }
|
||||
|
||||
/**
|
||||
* The برچسبها cell for a patient row: shows the record's tag dots and, on click,
|
||||
* opens a popover to assign/remove tenant tags inline. Assignment PATCHes the
|
||||
* record's full `tags` array (the backend replaces the set) and refreshes the list.
|
||||
*/
|
||||
export default function PatientTagsCell({ record }: { record: PatientRecord }) {
|
||||
const qc = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const current = record.tags ?? [];
|
||||
const currentUuids = current.map((t) => t.uuid);
|
||||
|
||||
const { data: tagsData, isLoading } = useQuery<ApiResponse<TenantTag[]>>({
|
||||
queryKey: ['tenant-tags'],
|
||||
queryFn: () => api.get('/api/v1/tenant-tags'),
|
||||
enabled: open,
|
||||
});
|
||||
const allTags = tagsData?.data ?? [];
|
||||
|
||||
const mutate = useMutation({
|
||||
mutationFn: (uuids: string[]) => api.patch(`/api/v1/patient/${record.uuid}`, { tags: uuids }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['patients'] }),
|
||||
onError: (e: any) => toast.error(e?.message || 'خطا در بهروزرسانی برچسبها'),
|
||||
});
|
||||
|
||||
const toggle = (uuid: string) => {
|
||||
const next = currentUuids.includes(uuid) ? currentUuids.filter((u) => u !== uuid) : [...currentUuids, uuid];
|
||||
mutate.mutate(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<span style={{ position: 'relative', display: 'inline-flex' }}>
|
||||
{current.length === 0 ? (
|
||||
<button type="button" onClick={() => setOpen((v) => !v)} className="btn sm ghost" style={{ color: 'var(--primary)', fontSize: 12.5, gap: 3 }}>
|
||||
<PlusIcon style={{ width: 14 }} /> اضافه کردن
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" onClick={() => setOpen((v) => !v)} style={{ display: 'inline-flex', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer', padding: 4 }} aria-label="ویرایش برچسبها">
|
||||
{current.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,
|
||||
}} />
|
||||
))}
|
||||
{current.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-3)', marginInlineStart: 4 }}>+{formatNumber(current.length - 3)}</span>}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{open && (
|
||||
<>
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 60 }} onClick={() => setOpen(false)} />
|
||||
<div style={{
|
||||
position: 'absolute', top: 'calc(100% + 6px)', insetInlineStart: 0, zIndex: 61,
|
||||
background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)',
|
||||
boxShadow: 'var(--shadow)', padding: 10, minWidth: 200, maxWidth: 300,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 600 }}>برچسبها</span>
|
||||
<button type="button" onClick={() => setOpen(false)} className="mini-btn" aria-label="بستن"><XMarkIcon style={{ width: 15 }} /></button>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '6px 0' }}>در حال بارگذاری…</div>
|
||||
) : allTags.length === 0 ? (
|
||||
<div style={{ fontSize: 12, color: 'var(--text-3)' }}>برچسبی تعریف نشده است.</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{allTags.map((tag) => {
|
||||
const assigned = currentUuids.includes(tag.uuid);
|
||||
return (
|
||||
<button
|
||||
key={tag.uuid}
|
||||
type="button"
|
||||
disabled={mutate.isPending}
|
||||
onClick={() => toggle(tag.uuid)}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
|
||||
fontSize: 12, height: 24, padding: '0 8px', borderRadius: 999,
|
||||
border: '1px solid var(--border)',
|
||||
background: assigned ? tag.color : 'var(--surface-2)',
|
||||
color: assigned ? '#fff' : 'var(--text-2)',
|
||||
}}
|
||||
>
|
||||
{assigned ? <XMarkIcon style={{ width: 12 }} /> : <PlusIcon style={{ width: 12 }} />}
|
||||
{tag.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import Modal from './ui/Modal';
|
||||
import PersianDateInput from './ui/PersianDateInput';
|
||||
|
||||
export interface PatientFilters {
|
||||
gender?: string; // male | female
|
||||
insurance_id?: string;
|
||||
admitted_from?: string; // gregorian Y-m-d
|
||||
admitted_to?: string;
|
||||
service_status?: string; // pending | completed
|
||||
has_debt?: boolean;
|
||||
tags?: string[]; // tenant-tag uuids
|
||||
}
|
||||
|
||||
interface TenantTag { uuid: string; name: string; color: string }
|
||||
interface PricingInsurance { insurance_id: number; insurance_name: string; type: string }
|
||||
|
||||
const EMPTY: PatientFilters = {};
|
||||
|
||||
function Segmented({ value, onChange, options }: { value: string | undefined; onChange: (v: string) => void; options: { label: string; value: string }[] }) {
|
||||
return (
|
||||
<div style={{ display: 'inline-flex', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', overflow: 'hidden' }}>
|
||||
{options.map((o) => {
|
||||
const active = (value ?? '') === o.value;
|
||||
return (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
onClick={() => onChange(o.value)}
|
||||
style={{
|
||||
padding: '7px 14px', border: 'none', cursor: 'pointer', fontSize: 13,
|
||||
background: active ? 'var(--primary-soft)' : 'var(--surface)',
|
||||
color: active ? 'var(--primary)' : 'var(--text-2)',
|
||||
}}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** فیلترها — advanced patient-list filter modal, ported from tauri FilesFilterModal. */
|
||||
export default function PatientsFilterModal({ open, onClose, value, onApply }: {
|
||||
open: boolean; onClose: () => void; value: PatientFilters; onApply: (f: PatientFilters) => void;
|
||||
}) {
|
||||
const [f, setF] = useState<PatientFilters>(value);
|
||||
useEffect(() => { if (open) setF(value); }, [open, value]);
|
||||
|
||||
const { data: tagsData } = useQuery<ApiResponse<TenantTag[]>>({
|
||||
queryKey: ['tenant-tags'], queryFn: () => api.get('/api/v1/tenant-tags'), enabled: open,
|
||||
});
|
||||
const tags = tagsData?.data ?? [];
|
||||
|
||||
const { data: pricingData } = useQuery<ApiResponse<{ insurances: PricingInsurance[] }>>({
|
||||
queryKey: ['insurance-pricing'], queryFn: () => api.get('/api/v1/insurance-pricing'), enabled: open,
|
||||
});
|
||||
const insurances = (pricingData?.data?.insurances ?? []).filter((i) => i.type === 'basic');
|
||||
|
||||
const set = <K extends keyof PatientFilters>(k: K, v: PatientFilters[K]) => setF((p) => ({ ...p, [k]: v }));
|
||||
const toggleTag = (uuid: string) => {
|
||||
const cur = f.tags ?? [];
|
||||
set('tags', cur.includes(uuid) ? cur.filter((u) => u !== uuid) : [...cur, uuid]);
|
||||
};
|
||||
|
||||
const label: React.CSSProperties = { fontSize: 13, fontWeight: 700, color: 'var(--text-2)', marginBottom: 8, display: 'block' };
|
||||
const selectedTags = f.tags ?? [];
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="فیلترها" size="md" footer={
|
||||
<>
|
||||
<button className="btn ghost sm" onClick={() => setF(EMPTY)} style={{ color: 'var(--accent)' }}>حذف همه</button>
|
||||
<button className="btn primary sm" onClick={() => onApply(f)}>اعمال تغییرات</button>
|
||||
</>
|
||||
}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
<div>
|
||||
<label style={label}>تاریخ پذیرش</label>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<div style={{ flex: 1 }}><PersianDateInput value={f.admitted_from ?? ''} onChange={(v) => set('admitted_from', v)} placeholder="از تاریخ" /></div>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>تا</span>
|
||||
<div style={{ flex: 1 }}><PersianDateInput value={f.admitted_to ?? ''} onChange={(v) => set('admitted_to', v)} placeholder="تا تاریخ" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={label}>نوع بیمه</label>
|
||||
<select className="input" value={f.insurance_id ?? ''} onChange={(e) => set('insurance_id', e.target.value || undefined)} aria-label="نوع بیمه">
|
||||
<option value="">همه بیمهها</option>
|
||||
{insurances.map((i) => <option key={i.insurance_id} value={String(i.insurance_id)}>{i.insurance_name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={label}>وضعیت سرویس</label>
|
||||
<Segmented
|
||||
value={f.service_status ?? ''}
|
||||
onChange={(v) => set('service_status', v || undefined)}
|
||||
options={[{ label: 'همه', value: '' }, { label: 'تکمیل نشده', value: 'pending' }, { label: 'تکمیل شده', value: 'completed' }]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={label}>وضعیت پرونده</label>
|
||||
<label className="switch" title="فقط پروندههای دارای بدهی" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
|
||||
<input type="checkbox" checked={!!f.has_debt} onChange={(e) => set('has_debt', e.target.checked)} aria-label="فقط پروندههای دارای بدهی" />
|
||||
<span className="switch-track"><span className="switch-thumb" /></span>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-2)' }}>فقط پروندههای دارای بدهی</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={label}>جنسیت بیمار</label>
|
||||
<Segmented
|
||||
value={f.gender ?? ''}
|
||||
onChange={(v) => set('gender', v || undefined)}
|
||||
options={[{ label: 'هر دو', value: '' }, { label: 'آقا', value: 'male' }, { label: 'خانم', value: 'female' }]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={label}>برچسب</label>
|
||||
{tags.length === 0 ? (
|
||||
<span style={{ fontSize: 12.5, color: 'var(--text-3)' }}>برچسبی تعریف نشده است.</span>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{tags.map((t) => {
|
||||
const on = selectedTags.includes(t.uuid);
|
||||
return (
|
||||
<button
|
||||
key={t.uuid} type="button" onClick={() => toggleTag(t.uuid)}
|
||||
style={{
|
||||
fontSize: 12, height: 26, padding: '0 10px', borderRadius: 999, cursor: 'pointer',
|
||||
border: '1px solid var(--border)',
|
||||
background: on ? t.color : 'var(--surface-2)', color: on ? '#fff' : 'var(--text-2)',
|
||||
}}
|
||||
>
|
||||
{t.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
+9
-1
@@ -25,7 +25,15 @@ Returns a paginated list of patient records belonging to the authenticated entit
|
||||
|-------|------|---------|-------------|
|
||||
| `page` | int | 1 | Page number |
|
||||
| `limit` | int | 20 | Items per page (10–50) |
|
||||
| `search` | string | — | Search by patient name or phone |
|
||||
| `search` | string | — | Search by patient name, phone or national code |
|
||||
| `tags` | string | — | Comma-separated tenant-tag uuids; matches records having any of them |
|
||||
| `gender` | string | — | Patient `UserProfile.gender` (e.g. `male`/`female`) |
|
||||
| `insurance_id` | int | — | Patient's basic insurance id (`UserProfile.basic_insurance_id`) |
|
||||
| `admitted_from` / `admitted_to` | int | — | Record creation (تاریخ پذیرش) unix-seconds range |
|
||||
| `service_status` | string | — | `pending` (has an unpaid session) or `completed` (has sessions, none unpaid) |
|
||||
| `has_debt` | bool | — | `1` → only records with an unpaid session (`payment_method='pending'`) |
|
||||
|
||||
> «بدهی» و «وضعیت سرویس» بر پایهی وجود مراجعهی پرداختنشده تعریف شدهاند (مدل بدهی مستقل ندارد). فیلترها روی هم AND میشوند و در count هم اعمال میگردند.
|
||||
|
||||
**Response 200:**
|
||||
|
||||
|
||||
@@ -528,8 +528,19 @@ class PatientController extends BaseController
|
||||
$limit = min(50, max(10, (int) $request->query->get('limit', 20)));
|
||||
$search = $request->query->get('search') ?: null;
|
||||
|
||||
$records = $this->recordRepo->findByEntity($entityType, $entityId, $page, $limit, $search);
|
||||
$total = $this->recordRepo->countByEntity($entityType, $entityId, $search);
|
||||
$tags = $request->query->get('tags');
|
||||
$filters = [
|
||||
'tags' => $tags ? array_filter(array_map('trim', explode(',', $tags))) : null,
|
||||
'gender' => $request->query->get('gender') ?: null,
|
||||
'insurance_id' => $request->query->get('insurance_id') ?: null,
|
||||
'admitted_from' => $request->query->get('admitted_from') ?: null,
|
||||
'admitted_to' => $request->query->get('admitted_to') ?: null,
|
||||
'service_status' => $request->query->get('service_status') ?: null,
|
||||
'has_debt' => $request->query->getBoolean('has_debt'),
|
||||
];
|
||||
|
||||
$records = $this->recordRepo->findByEntity($entityType, $entityId, $page, $limit, $search, $filters);
|
||||
$total = $this->recordRepo->countByEntity($entityType, $entityId, $search, $filters);
|
||||
|
||||
return $this->paginated(
|
||||
array_map(fn(PatientRecord $r) => $r->toArray(), $records),
|
||||
|
||||
@@ -28,42 +28,94 @@ class PatientRecordRepository extends ServiceEntityRepository
|
||||
]);
|
||||
}
|
||||
|
||||
public function findByEntity(string $entityType, int $entityId, int $page = 1, int $limit = 20, ?string $search = null): array
|
||||
/**
|
||||
* @param array<string, mixed> $filters tags(string[] tenant-tag uuids), gender,
|
||||
* insurance_id, admitted_from/admitted_to (unix), service_status
|
||||
* (pending|completed), has_debt(bool)
|
||||
* @return list<PatientRecord>
|
||||
*/
|
||||
public function findByEntity(string $entityType, int $entityId, int $page = 1, int $limit = 20, ?string $search = null, array $filters = []): array
|
||||
{
|
||||
$qb = $this->createQueryBuilder('r')
|
||||
->join('r.user', 'u')
|
||||
->where('r.entityType = :type')
|
||||
->andWhere('r.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->orderBy('r.id', 'DESC')
|
||||
$qb = $this->baseQuery($entityType, $entityId);
|
||||
$this->applyFilters($qb, $search, $filters);
|
||||
|
||||
return $qb->orderBy('r.id', 'DESC')
|
||||
->setFirstResult(($page - 1) * $limit)
|
||||
->setMaxResults($limit);
|
||||
|
||||
if ($search !== null && $search !== '') {
|
||||
$qb->andWhere('u.realName LIKE :search OR u.mobileNumber LIKE :search OR u.nationalCode LIKE :search')
|
||||
->setParameter('search', '%' . $search . '%');
|
||||
}
|
||||
|
||||
return $qb->getQuery()->getResult();
|
||||
->setMaxResults($limit)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function countByEntity(string $entityType, int $entityId, ?string $search = null): int
|
||||
/** @param array<string, mixed> $filters same shape as {@see findByEntity}. */
|
||||
public function countByEntity(string $entityType, int $entityId, ?string $search = null, array $filters = []): int
|
||||
{
|
||||
$qb = $this->createQueryBuilder('r')
|
||||
->select('COUNT(r.id)')
|
||||
$qb = $this->baseQuery($entityType, $entityId)->select('COUNT(r.id)');
|
||||
$this->applyFilters($qb, $search, $filters);
|
||||
|
||||
return (int) $qb->getQuery()->getSingleScalarResult();
|
||||
}
|
||||
|
||||
private function baseQuery(string $entityType, int $entityId): \Doctrine\ORM\QueryBuilder
|
||||
{
|
||||
return $this->createQueryBuilder('r')
|
||||
->join('r.user', 'u')
|
||||
->where('r.entityType = :type')
|
||||
->andWhere('r.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared search + advanced filters for the patient records list, applied to
|
||||
* both the page query and its count so totals stay consistent.
|
||||
* @param array<string, mixed> $filters
|
||||
*/
|
||||
private function applyFilters(\Doctrine\ORM\QueryBuilder $qb, ?string $search, array $filters): void
|
||||
{
|
||||
if ($search !== null && $search !== '') {
|
||||
$qb->andWhere('u.realName LIKE :search OR u.mobileNumber LIKE :search OR u.nationalCode LIKE :search')
|
||||
->setParameter('search', '%' . $search . '%');
|
||||
}
|
||||
|
||||
return (int) $qb->getQuery()->getSingleScalarResult();
|
||||
// برچسبها — رکوردهایی که حداقل یکی از تگهای انتخابشده را دارند.
|
||||
if (!empty($filters['tags'])) {
|
||||
$qb->andWhere('r.id IN (SELECT rt.id FROM App\Patient\Entity\PatientRecord rt JOIN rt.tags tg WHERE tg.uuid IN (:tagUuids))')
|
||||
->setParameter('tagUuids', (array) $filters['tags']);
|
||||
}
|
||||
|
||||
// جنسیت / نوع بیمه — از UserProfile بیمار (OneToOne با user).
|
||||
if (!empty($filters['gender']) || !empty($filters['insurance_id'])) {
|
||||
$qb->leftJoin(\App\UserProfile\Entity\UserProfile::class, 'pr', \Doctrine\ORM\Query\Expr\Join::WITH, 'pr.user = u');
|
||||
if (!empty($filters['gender'])) {
|
||||
$qb->andWhere('pr.gender = :gender')->setParameter('gender', $filters['gender']);
|
||||
}
|
||||
if (!empty($filters['insurance_id'])) {
|
||||
$qb->andWhere('pr.basicInsuranceId = :insId')->setParameter('insId', (int) $filters['insurance_id']);
|
||||
}
|
||||
}
|
||||
|
||||
// تاریخ پذیرش — تاریخ تشکیل پرونده (record.createdAt).
|
||||
if (!empty($filters['admitted_from'])) {
|
||||
$qb->andWhere('r.createdAt >= :aFrom')->setParameter('aFrom', (int) $filters['admitted_from']);
|
||||
}
|
||||
if (!empty($filters['admitted_to'])) {
|
||||
$qb->andWhere('r.createdAt <= :aTo')->setParameter('aTo', (int) $filters['admitted_to']);
|
||||
}
|
||||
|
||||
// وضعیت سرویس / بدهی — بر اساس وجود مراجعهی پرداختنشده (payment_method='pending').
|
||||
$pendingSub = 'SELECT sp.id FROM App\Patient\Entity\PatientSession sp WHERE sp.record = r AND sp.paymentMethod = :pendingPm';
|
||||
$anySub = 'SELECT sa.id FROM App\Patient\Entity\PatientSession sa WHERE sa.record = r';
|
||||
|
||||
if (!empty($filters['has_debt'])) {
|
||||
$qb->andWhere("EXISTS ($pendingSub)")->setParameter('pendingPm', 'pending');
|
||||
}
|
||||
if (($filters['service_status'] ?? null) === 'pending') {
|
||||
$qb->andWhere("EXISTS ($pendingSub)")->setParameter('pendingPm', 'pending');
|
||||
} elseif (($filters['service_status'] ?? null) === 'completed') {
|
||||
$qb->andWhere("NOT EXISTS ($pendingSub)")
|
||||
->andWhere("EXISTS ($anySub)")
|
||||
->setParameter('pendingPm', 'pending');
|
||||
}
|
||||
}
|
||||
|
||||
public function countUnique(string $entityType, int $entityId, int $from, int $to): int
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Patient;
|
||||
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Patient\Entity\PatientSession;
|
||||
use App\Tag\Entity\TenantTag;
|
||||
use App\Tests\ApiTestCase;
|
||||
use App\UserProfile\Entity\UserProfile;
|
||||
|
||||
/**
|
||||
* GET /api/v1/patients advanced filters: tags, gender, insurance, admission
|
||||
* date range, service status (pending/completed) and has-debt.
|
||||
*/
|
||||
class PatientListFilterTest extends ApiTestCase
|
||||
{
|
||||
private function doctor(): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر تست');
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $doctor];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{gender?:string,insurance?:int,tag?:TenantTag,pending?:bool,paid?:bool,createdAt?:int} $opts
|
||||
*/
|
||||
private function record(Doctor $doctor, array $opts = []): PatientRecord
|
||||
{
|
||||
$patient = $this->createUser(['ROLE_USER']);
|
||||
$record = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
|
||||
if (isset($opts['createdAt'])) {
|
||||
$ref = new \ReflectionProperty($record, 'createdAt');
|
||||
$ref->setAccessible(true);
|
||||
$ref->setValue($record, $opts['createdAt']);
|
||||
}
|
||||
$this->em->persist($record);
|
||||
|
||||
if (isset($opts['gender']) || isset($opts['insurance'])) {
|
||||
$profile = new UserProfile($patient);
|
||||
if (isset($opts['gender'])) $profile->setGender($opts['gender']);
|
||||
if (isset($opts['insurance'])) $profile->setBasicInsuranceId($opts['insurance']);
|
||||
$this->em->persist($profile);
|
||||
}
|
||||
if (isset($opts['tag'])) {
|
||||
$record->getTags()->add($opts['tag']);
|
||||
}
|
||||
if (!empty($opts['pending']) || !empty($opts['paid'])) {
|
||||
$session = new PatientSession($record);
|
||||
$session->setPaymentMethod(!empty($opts['pending']) ? 'pending' : 'cash');
|
||||
$this->em->persist($session);
|
||||
}
|
||||
$this->em->flush();
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
private function tag(Doctor $doctor, string $name): TenantTag
|
||||
{
|
||||
$tag = new TenantTag('doctor', $doctor->getId(), $name, '#5559CE');
|
||||
$this->em->persist($tag);
|
||||
$this->em->flush();
|
||||
return $tag;
|
||||
}
|
||||
|
||||
private function uuids(array $res): array
|
||||
{
|
||||
return array_map(static fn(array $r) => $r['uuid'], $res['data']);
|
||||
}
|
||||
|
||||
public function testFilterByTag(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$tag = $this->tag($doctor, 'خوشحساب');
|
||||
$tagged = $this->record($doctor, ['tag' => $tag]);
|
||||
$this->record($doctor); // untagged
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/patients?tags=' . $tag->getUuid(), $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertSame(1, $res['meta']['totalRecords']);
|
||||
self::assertSame($tagged->getUuid(), $res['data'][0]['uuid']);
|
||||
}
|
||||
|
||||
public function testFilterByGenderAndInsurance(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$male = $this->record($doctor, ['gender' => 'male', 'insurance' => 7]);
|
||||
$this->record($doctor, ['gender' => 'female', 'insurance' => 9]);
|
||||
|
||||
$byGender = $this->authJson('GET', '/api/v1/patients?gender=male', $owner);
|
||||
self::assertSame(1, $byGender['meta']['totalRecords']);
|
||||
self::assertSame($male->getUuid(), $byGender['data'][0]['uuid']);
|
||||
|
||||
$byIns = $this->authJson('GET', '/api/v1/patients?insurance_id=7', $owner);
|
||||
self::assertSame(1, $byIns['meta']['totalRecords']);
|
||||
self::assertSame($male->getUuid(), $byIns['data'][0]['uuid']);
|
||||
}
|
||||
|
||||
public function testFilterByAdmissionDateRange(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$old = $this->record($doctor, ['createdAt' => 1000]);
|
||||
$new = $this->record($doctor, ['createdAt' => 5000]);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/patients?admitted_from=4000&admitted_to=6000', $owner);
|
||||
self::assertSame(1, $res['meta']['totalRecords']);
|
||||
self::assertSame($new->getUuid(), $res['data'][0]['uuid']);
|
||||
self::assertNotContains($old->getUuid(), $this->uuids($res));
|
||||
}
|
||||
|
||||
public function testFilterByServiceStatusAndDebt(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$pending = $this->record($doctor, ['pending' => true]);
|
||||
$completed = $this->record($doctor, ['paid' => true]);
|
||||
|
||||
$onlyPending = $this->authJson('GET', '/api/v1/patients?service_status=pending', $owner);
|
||||
self::assertSame(1, $onlyPending['meta']['totalRecords']);
|
||||
self::assertSame($pending->getUuid(), $onlyPending['data'][0]['uuid']);
|
||||
|
||||
$onlyCompleted = $this->authJson('GET', '/api/v1/patients?service_status=completed', $owner);
|
||||
self::assertSame(1, $onlyCompleted['meta']['totalRecords']);
|
||||
self::assertSame($completed->getUuid(), $onlyCompleted['data'][0]['uuid']);
|
||||
|
||||
$withDebt = $this->authJson('GET', '/api/v1/patients?has_debt=1', $owner);
|
||||
self::assertSame(1, $withDebt['meta']['totalRecords']);
|
||||
self::assertSame($pending->getUuid(), $withDebt['data'][0]['uuid']);
|
||||
}
|
||||
|
||||
public function testNoFiltersReturnsAll(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$this->record($doctor);
|
||||
$this->record($doctor);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/patients', $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertSame(2, $res['meta']['totalRecords']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user