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
+105
View File
@@ -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>
);
}