feat(billing): patient payments list + patient invoices detail (doctor/clinic)

Port two nobat724 Figma screens into the admin SPA for the doctor/clinic
tenant panel:

- node 1 — لیست پرداخت‌ها (/admin/my-payments): per-patient payment summary
  (invoice count, paid, remaining, derived status paid/unsettled/unpaid),
  filters by national code / status / Jalali date range, pagination.
- node 2 — پرداخت‌های ثبت‌شده (/admin/my-payments/:patientUuid): a patient's
  recorded invoices with patient header, service title, total, status badge,
  and an expandable per-invoice item breakdown.

Backend (App\Billing):
- InvoiceRepository::patientPaymentSummary/countPatientPaymentSummary — DQL
  aggregation grouped by patient record (arbitrary join Invoice→PatientRecord
  →User), draft/void excluded, derived-status HAVING filters.
- InvoiceRepository::invoicesForPatient/count + InvoiceService methods that
  shape rows and derive status.
- BillingController: GET /api/v1/my/billing/patient-payments and
  GET /api/v1/my/billing/patients/{patientUuid}/invoices (thin, resolveEntity,
  tenant-scoped, 403/404). Invoice::getIssuedAt / InvoiceItem::getTitle added.
- docs/api/billing.md documents both endpoints.

Frontend: useMyPayments hooks, MyPaymentsPage, MyPaymentDetailPage, routes in
App.tsx (doctor/secretary/clinic, blockClinicScope) and a sidebar entry.
Persian strings hardcoded per existing admin convention (no i18n infra).

Tests: tests/Billing/PatientPaymentsTest.php (8), useMyPayments + both page
tests (11). Note: pre-existing LoginPage.test failures are unrelated (proven
by stashing this change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-14 18:24:33 +03:30
co-authored by Claude Opus 4.8
parent bfeffbc7b3
commit 4c29fa3274
15 changed files with 1101 additions and 0 deletions
+5
View File
@@ -38,6 +38,8 @@ import RepresentationFinancePage from './pages/RepresentationFinancePage';
import RepresentationProfilePage from './pages/RepresentationProfilePage';
import DoctorProfilePage from './pages/DoctorProfilePage';
import MyPatientsPage from './pages/MyPatientsPage';
import MyPaymentsPage from './pages/MyPaymentsPage';
import MyPaymentDetailPage from './pages/MyPaymentDetailPage';
import NewSessionPage from './pages/NewSessionPage';
import InsurancePricingPage from './pages/InsurancePricingPage';
import ClaimsPage from './pages/ClaimsPage';
@@ -197,6 +199,9 @@ export default function App() {
{/* دکتر / منشی / کلینیک */}
<Route path="my-patients" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><MyPatientsPage /></RoleRoute>} />
<Route path="my-payments" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><MyPaymentsPage /></RoleRoute>} />
<Route path="my-payments/:patientUuid" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><MyPaymentDetailPage /></RoleRoute>} />
<Route path="patients" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientsListPage /></RoleRoute>} />
<Route path="patients/new" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientRecordFormPage /></RoleRoute>} />
<Route path="patients/:uuid/edit" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientRecordFormPage /></RoleRoute>} />
@@ -213,6 +213,11 @@ function buildSections(
label: "پرونده بیماران",
feature: "patient_records",
},
{
to: "/admin/my-payments",
icon: CreditCardIcon,
label: "پرداخت‌ها",
},
{
to: "/admin/claims",
icon: DocumentTextIcon,
@@ -278,6 +283,11 @@ function buildSections(
label: "پرونده بیماران",
feature: "patient_records",
},
{
to: "/admin/my-payments",
icon: CreditCardIcon,
label: "پرداخت‌ها",
},
{
to: "/admin/claims",
icon: DocumentTextIcon,
@@ -338,6 +348,11 @@ function buildSections(
label: "پرونده بیماران",
feature: "patient_records",
},
{
to: "/admin/my-payments",
icon: CreditCardIcon,
label: "پرداخت‌ها",
},
{
to: "/admin/insurance-pricing",
icon: ShieldCheckIcon,
+57
View File
@@ -0,0 +1,57 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
vi.mock('../lib/api', () => ({
api: { get: vi.fn() },
ApiError: class extends Error {},
}));
import { api } from '../lib/api';
import { usePatientPayments, usePatientInvoices } from './useMyPayments';
const get = api.get as ReturnType<typeof vi.fn>;
function wrapper({ children }: { children: React.ReactNode }) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}
beforeEach(() => {
get.mockReset();
get.mockResolvedValue({ success: true, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } });
});
describe('useMyPayments', () => {
it('builds the list URL with all active filters', async () => {
renderHook(() => usePatientPayments({ page: 2, national_code: '1744', status: 'paid', from: 100, to: 200 }), { wrapper });
await waitFor(() => expect(get).toHaveBeenCalled());
const url = get.mock.calls[0][0] as string;
expect(url).toContain('/api/v1/my/billing/patient-payments?');
expect(url).toContain('page=2');
expect(url).toContain('national_code=1744');
expect(url).toContain('status=paid');
expect(url).toContain('from=100');
expect(url).toContain('to=200');
});
it('omits empty filters from the list URL', async () => {
renderHook(() => usePatientPayments({ page: 1 }), { wrapper });
await waitFor(() => expect(get).toHaveBeenCalled());
const url = get.mock.calls[0][0] as string;
expect(url).not.toContain('national_code=');
expect(url).not.toContain('status=');
});
it('does not fetch invoices until a patient uuid is provided', async () => {
const { rerender } = renderHook(({ uuid }: { uuid?: string }) => usePatientInvoices(uuid, 1), {
wrapper, initialProps: { uuid: undefined as string | undefined },
});
expect(get).not.toHaveBeenCalled();
rerender({ uuid: 'abc' });
await waitFor(() => expect(get).toHaveBeenCalled());
expect(get.mock.calls[0][0]).toContain('/api/v1/my/billing/patients/abc/invoices');
});
});
+70
View File
@@ -0,0 +1,70 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
/** A derived per-patient payment status shown on the list (node 1). */
export type PaymentRowStatus = 'paid' | 'unpaid' | 'unsettled';
export interface PatientPaymentRow {
patient_uuid: string;
patient_name: string | null;
national_code: string | null;
invoice_count: number;
paid_rials: number;
remaining_rials: number;
status: PaymentRowStatus;
}
export interface PatientPaymentFilters {
page: number;
national_code?: string;
status?: string; // paid | unsettled | unpaid
from?: number; // unix seconds
to?: number; // unix seconds
}
/** A single invoice status on the detail table (node 2) — two-state. */
export type InvoiceRowStatus = 'paid' | 'unsettled';
export interface PatientInvoiceRow {
uuid: string;
number: number;
issued_at: number;
total_rials: number;
status: InvoiceRowStatus;
service_title: string | null;
items: Array<{ uuid: string; title: string; quantity: number; total_rials: number; patient_rials: number }>;
}
export interface PatientInvoicesPayload {
patient: { uuid: string; name: string | null; national_code: string | null };
data: PatientInvoiceRow[];
meta: { totalRecords: number; totalPages: number; currentPage: number };
}
const LIMIT = 20;
/** Node 1 — paginated per-patient payment summary for the current tenant. */
export function usePatientPayments(filters: PatientPaymentFilters) {
const qs = new URLSearchParams({ page: String(filters.page), limit: String(LIMIT) });
if (filters.national_code) qs.set('national_code', filters.national_code);
if (filters.status) qs.set('status', filters.status);
if (filters.from) qs.set('from', String(filters.from));
if (filters.to) qs.set('to', String(filters.to));
return useQuery<PaginatedResponse<PatientPaymentRow>>({
queryKey: ['patient-payments', filters],
queryFn: () => api.get(`/api/v1/my/billing/patient-payments?${qs.toString()}`),
});
}
/** Node 2 — a single patient's recorded invoices (header + paginated list). */
export function usePatientInvoices(patientUuid: string | undefined, page: number) {
return useQuery<ApiResponse<PatientInvoicesPayload>>({
queryKey: ['patient-invoices', patientUuid, page],
queryFn: () => api.get(`/api/v1/my/billing/patients/${patientUuid}/invoices?page=${page}&limit=${LIMIT}`),
enabled: !!patientUuid,
});
}
export const MY_PAYMENTS_LIMIT = LIMIT;
@@ -0,0 +1,70 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { Route, Routes } from 'react-router-dom';
import { renderWithProviders } from '../test/utils';
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({ api: { get: vi.fn() }, ApiError: class extends Error {} }));
import { api } from '../lib/api';
import MyPaymentDetailPage from './MyPaymentDetailPage';
const get = api.get as ReturnType<typeof vi.fn>;
const PAYLOAD = {
patient: { uuid: 'abc', name: 'دنیا خلیلی', national_code: '1744023654' },
data: [
{ uuid: 'i1', number: 12345, issued_at: 1717000000, total_rials: 2350000, status: 'paid',
service_title: 'روکش دندان',
items: [{ uuid: 'it1', title: 'روکش دندان', quantity: 1, total_rials: 2350000, patient_rials: 2350000 }] },
{ uuid: 'i2', number: 52614, issued_at: 1718000000, total_rials: 6000000, status: 'unsettled',
service_title: 'طرح لبخند', items: [] },
],
meta: { totalRecords: 2, totalPages: 1, currentPage: 1 },
};
function renderPage() {
return renderWithProviders(
<Routes>
<Route path="/admin/my-payments/:patientUuid" element={<MyPaymentDetailPage />} />
</Routes>,
{ route: '/admin/my-payments/abc' },
);
}
beforeEach(() => {
get.mockReset();
get.mockResolvedValue({ success: true, data: PAYLOAD });
});
describe('MyPaymentDetailPage (پرداخت‌های ثبت‌شده)', () => {
it('renders the patient header and invoice rows', async () => {
renderPage();
expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getByText(/1744023654/)).toBeInTheDocument();
expect(screen.getByText('روکش دندان')).toBeInTheDocument();
expect(screen.getByText('طرح لبخند')).toBeInTheDocument();
expect(screen.getByText('پرداخت شده')).toBeInTheDocument();
expect(screen.getByText('تسویه نشده')).toBeInTheDocument();
});
it('fetches invoices for the patient uuid from the route', async () => {
renderPage();
await screen.findByText('دنیا خلیلی');
expect(get.mock.calls[0][0]).toContain('/api/v1/my/billing/patients/abc/invoices');
});
it('expands a row to show its line items on بیشتر', async () => {
renderPage();
await screen.findByText('روکش دندان');
fireEvent.click(screen.getAllByRole('button', { name: /بیشتر/ })[0]);
// the item breakdown appears (title repeated inside the expanded sub-row)
expect(await screen.findAllByText('روکش دندان')).toHaveLength(2);
});
it('shows an empty state when the patient has no invoices', async () => {
get.mockResolvedValue({ success: true, data: { patient: PAYLOAD.patient, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } } });
renderPage();
expect(await screen.findByText('صورتحسابی ثبت نشده است')).toBeInTheDocument();
});
});
+150
View File
@@ -0,0 +1,150 @@
import { Fragment, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ChevronRightIcon, ChevronDownIcon, PlusIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import PageHeader from '../components/ui/PageHeader';
import Pagination from '../components/ui/Pagination';
import { formatRial, formatDate, formatNumber } from '../lib/utils';
import {
usePatientInvoices,
MY_PAYMENTS_LIMIT,
type PatientInvoiceRow,
type InvoiceRowStatus,
} from '../hooks/useMyPayments';
const STATUS_LABEL: Record<InvoiceRowStatus, string> = { paid: 'پرداخت شده', unsettled: 'تسویه نشده' };
const STATUS_BADGE: Record<InvoiceRowStatus, string> = { paid: 'green', unsettled: 'amber' };
const EMPTY: PatientInvoiceRow[] = [];
/** HH:MM (Persian digits) from a unix timestamp. */
function formatTime(unix: number): string {
return new Intl.DateTimeFormat('fa-IR', { hour: '2-digit', minute: '2-digit' }).format(new Date(unix * 1000));
}
/** پرداخت‌های ثبت‌شده — a single patient's recorded invoices (node 2). */
export default function MyPaymentDetailPage() {
const { patientUuid } = useParams<{ patientUuid: string }>();
const navigate = useNavigate();
const [page, setPage] = useState(1);
const [expanded, setExpanded] = useState<string | null>(null);
const { data, isLoading } = usePatientInvoices(patientUuid, page);
const payload = data?.data;
const patient = payload?.patient;
const rows = payload?.data ?? EMPTY;
const total = payload?.meta?.totalRecords ?? 0;
const th: React.CSSProperties = { textAlign: 'right', padding: '12px 16px', fontWeight: 600 };
const td: React.CSSProperties = { padding: '12px 16px' };
return (
<>
<PageHeader
title="پرداخت‌های ثبت‌شده"
action={
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn sm" onClick={() => navigate('/admin/my-payments')}>
<ChevronRightIcon style={{ width: 15 }} /> بازگشت
</button>
<button className="btn primary sm" onClick={() => toast.info('ثبت پرداخت جدید به‌زودی اضافه می‌شود')}>
<PlusIcon style={{ width: 15 }} /> پرداخت جدید
</button>
</div>
}
/>
{/* سربرگ بیمار */}
<div style={{
display: 'flex', gap: 24, flexWrap: 'wrap', alignItems: 'center',
marginBottom: 16, padding: '14px 16px',
background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)',
}}>
<span style={{ fontSize: 14 }}>
نام بیمار: <b style={{ fontWeight: 700 }}>{patient?.name ?? '—'}</b>
</span>
<span style={{ fontSize: 14, color: 'var(--text-2)' }} dir="ltr">
کدملی: {patient?.national_code ?? '—'}
</span>
</div>
{isLoading ? (
<div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری</div>
) : rows.length === 0 ? (
<div className="card" style={{ padding: '60px 24px', textAlign: 'center', color: 'var(--text-3)' }}>
<div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6, color: 'var(--text-2)' }}>صورتحسابی ثبت نشده است</div>
<div style={{ fontSize: 13 }}>برای این بیمار هنوز پرداخت ثبتشدهای وجود ندارد.</div>
</div>
) : (
<>
<div className="card" style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--border)', color: 'var(--text-3)', fontSize: 12 }}>
<th style={th}>شماره صورتحساب</th>
<th style={th}>تاریخ</th>
<th style={th}>ساعت</th>
<th style={th}>نوع خدمت</th>
<th style={th}>مبلغ کل (تومان)</th>
<th style={th}>وضعیت</th>
<th style={{ ...th, textAlign: 'left' }}>جزئیات</th>
</tr>
</thead>
<tbody>
{rows.map((row) => {
const open = expanded === row.uuid;
return (
<Fragment key={row.uuid}>
<tr style={{ borderBottom: open ? 'none' : '1px solid var(--border)' }}>
<td style={{ ...td, fontWeight: 600 }} dir="ltr">#{formatNumber(row.number)}</td>
<td style={td}>{formatDate(row.issued_at)}</td>
<td style={td} dir="ltr">{formatTime(row.issued_at)}</td>
<td style={{ ...td, color: 'var(--text-2)' }}>{row.service_title ?? '—'}</td>
<td style={{ ...td, fontWeight: 600 }}>{formatRial(row.total_rials)}</td>
<td style={td}>
<span className={`badge ${STATUS_BADGE[row.status]}`}><span className="bdot" />{STATUS_LABEL[row.status]}</span>
</td>
<td style={{ ...td, textAlign: 'left' }}>
<button
className="btn sm ghost"
style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--primary)' }}
onClick={() => setExpanded(open ? null : row.uuid)}
>
بیشتر <ChevronDownIcon style={{ width: 15, transform: open ? 'rotate(180deg)' : undefined, transition: 'transform .15s' }} />
</button>
</td>
</tr>
{open && (
<tr style={{ borderBottom: '1px solid var(--border)', background: 'var(--surface-2)' }}>
<td colSpan={7} style={{ padding: '10px 16px 14px' }}>
{row.items.length === 0 ? (
<span style={{ fontSize: 12.5, color: 'var(--text-3)' }}>آیتمی ثبت نشده است.</span>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{row.items.map((it) => (
<div key={it.uuid} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13 }}>
<span style={{ color: 'var(--text-2)' }}>
{it.title}{it.quantity > 1 ? ` × ${formatNumber(it.quantity)}` : ''}
</span>
<span style={{ fontWeight: 600 }}>{formatRial(it.total_rials)}</span>
</div>
))}
</div>
)}
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
</div>
<div style={{ marginTop: 16 }}>
<Pagination page={page} total={total} limit={MY_PAYMENTS_LIMIT} onPageChange={setPage} />
</div>
</>
)}
</>
);
}
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
const navigate = vi.fn();
vi.mock('react-router-dom', async (orig) => ({
...(await orig<typeof import('react-router-dom')>()),
useNavigate: () => navigate,
}));
vi.mock('../lib/api', () => ({ api: { get: vi.fn() }, ApiError: class extends Error {} }));
import { api } from '../lib/api';
import MyPaymentsPage from './MyPaymentsPage';
const get = api.get as ReturnType<typeof vi.fn>;
const ROWS = [
{ patient_uuid: 'p1', patient_name: 'دنیا خلیلی', national_code: '1744023654',
invoice_count: 2, paid_rials: 2350000, remaining_rials: 500000, status: 'unsettled' },
{ patient_uuid: 'p2', patient_name: 'علی بدیعی', national_code: '2200112233',
invoice_count: 1, paid_rials: 2000000, remaining_rials: 0, status: 'paid' },
];
beforeEach(() => {
navigate.mockReset();
get.mockReset();
get.mockResolvedValue({ success: true, data: ROWS, meta: { totalRecords: 2, totalPages: 1, currentPage: 1 } });
});
describe('MyPaymentsPage (لیست پرداخت‌ها)', () => {
it('renders patient payment rows with derived status labels', async () => {
renderWithProviders(<MyPaymentsPage />, { route: '/admin/my-payments' });
expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getByText('علی بدیعی')).toBeInTheDocument();
// status labels appear both as a filter <option> and as a row badge
expect(screen.getAllByText('تسویه نشده').length).toBeGreaterThan(1);
expect(screen.getAllByText('پرداخت شده').length).toBeGreaterThan(1);
expect(screen.getByText('1744023654')).toBeInTheDocument();
});
it('navigates to the patient detail on مشاهده', async () => {
renderWithProviders(<MyPaymentsPage />, { route: '/admin/my-payments' });
await screen.findByText('دنیا خلیلی');
fireEvent.click(screen.getAllByRole('button', { name: /مشاهده/ })[0]);
expect(navigate).toHaveBeenCalledWith('/admin/my-payments/p1');
});
it('shows an empty state when there are no payments', async () => {
get.mockResolvedValue({ success: true, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } });
renderWithProviders(<MyPaymentsPage />, { route: '/admin/my-payments' });
expect(await screen.findByText('پرداختی یافت نشد')).toBeInTheDocument();
});
it('sends the national_code filter to the API', async () => {
renderWithProviders(<MyPaymentsPage />, { route: '/admin/my-payments' });
await screen.findByText('دنیا خلیلی');
fireEvent.change(screen.getByPlaceholderText('کد ملی بیمار را وارد کنید...'), { target: { value: '1744' } });
await waitFor(() => expect(get.mock.calls.some(([u]) => String(u).includes('national_code=1744'))).toBe(true));
});
});
+162
View File
@@ -0,0 +1,162 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { MagnifyingGlassIcon, EyeIcon, BanknotesIcon } from '@heroicons/react/24/outline';
import PageHeader from '../components/ui/PageHeader';
import Pagination from '../components/ui/Pagination';
import PersianDateInput from '../components/ui/PersianDateInput';
import { formatRial, formatNumber, toDate } from '../lib/utils';
import {
usePatientPayments,
MY_PAYMENTS_LIMIT,
type PatientPaymentRow,
type PaymentRowStatus,
} from '../hooks/useMyPayments';
const STATUS_LABEL: Record<PaymentRowStatus, string> = {
paid: 'پرداخت شده',
unsettled: 'تسویه نشده',
unpaid: 'پرداخت نشده',
};
const STATUS_BADGE: Record<PaymentRowStatus, string> = {
paid: 'green',
unsettled: 'amber',
unpaid: 'red',
};
const EMPTY: PatientPaymentRow[] = [];
/** unix start-of-day for `from`, end-of-day for `to`, from a gregorian Y-m-d. */
function dayBound(value: string, end: boolean): number | 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;
}
/** لیست پرداخت‌ها — per-patient payment summary for the logged-in doctor/clinic. */
export default function MyPaymentsPage() {
const navigate = useNavigate();
const [page, setPage] = useState(1);
const [nationalCode, setNationalCode] = useState('');
const [status, setStatus] = useState('');
const [from, setFrom] = useState('');
const [to, setTo] = useState('');
const reset = () => setPage(1);
const { data, isLoading } = usePatientPayments({
page,
national_code: nationalCode.trim() || undefined,
status: status || undefined,
from: from ? dayBound(from, false) : undefined,
to: to ? dayBound(to, true) : undefined,
});
const rows = data?.data ?? EMPTY;
const total = data?.meta?.totalRecords ?? 0;
const th: React.CSSProperties = { textAlign: 'right', padding: '12px 16px', fontWeight: 600 };
const td: React.CSSProperties = { padding: '12px 16px' };
return (
<>
<PageHeader title="لیست پرداخت‌ها" description="خلاصه‌ی پرداخت‌های بیماران شما" />
{/* فیلترها */}
<div style={{ display: 'flex', gap: 10, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' }}>
<div style={{
flex: '1 1 240px', minWidth: 200, display: 'flex', alignItems: 'center', gap: 8,
background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: '9px 12px',
}}>
<MagnifyingGlassIcon style={{ width: 18, color: 'var(--text-3)', flexShrink: 0 }} />
<input
style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1, fontSize: 14 }}
value={nationalCode}
onChange={(e) => { setNationalCode(e.target.value.replace(/\D/g, '')); reset(); }}
placeholder="کد ملی بیمار را وارد کنید..."
dir="ltr"
inputMode="numeric"
/>
</div>
<select
className="input"
style={{ flex: '0 0 auto', width: 160 }}
value={status}
onChange={(e) => { setStatus(e.target.value); reset(); }}
aria-label="وضعیت"
>
<option value="">همه وضعیتها</option>
<option value="paid">پرداخت شده</option>
<option value="unsettled">تسویه نشده</option>
<option value="unpaid">پرداخت نشده</option>
</select>
<div style={{ width: 150 }}>
<PersianDateInput value={from} onChange={(v) => { setFrom(v); reset(); }} placeholder="از تاریخ" />
</div>
<div style={{ width: 150 }}>
<PersianDateInput value={to} onChange={(v) => { setTo(v); reset(); }} placeholder="تا تاریخ" />
</div>
</div>
{isLoading ? (
<div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری</div>
) : rows.length === 0 ? (
<div className="card" style={{ padding: '60px 24px', textAlign: 'center', color: 'var(--text-3)' }}>
<BanknotesIcon style={{ width: 48, margin: '0 auto 16px', display: 'block', opacity: 0.4 }} />
<div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6, color: 'var(--text-2)' }}>پرداختی یافت نشد</div>
<div style={{ fontSize: 13 }}>با ثبت صورتحساب برای بیماران، این فهرست پر میشود.</div>
</div>
) : (
<>
<div className="card" style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--border)', color: 'var(--text-3)', fontSize: 12 }}>
<th style={th}>ردیف</th>
<th style={th}>نام بیمار</th>
<th style={th}>کد ملی</th>
<th style={th}>تعداد صورتحساب</th>
<th style={th}>مبلغ پرداختی</th>
<th style={th}>مبلغ باقیمانده</th>
<th style={th}>وضعیت</th>
<th style={{ ...th, textAlign: 'left' }}>عملیات</th>
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr key={row.patient_uuid} style={{ borderBottom: '1px solid var(--border)' }}>
<td style={td}>{formatNumber((page - 1) * MY_PAYMENTS_LIMIT + i + 1)}</td>
<td style={{ ...td, fontWeight: 600 }}>{row.patient_name ?? '—'}</td>
<td style={{ ...td, color: 'var(--text-2)' }} dir="ltr">{row.national_code ?? '—'}</td>
<td style={td}>{formatNumber(row.invoice_count)}</td>
<td style={{ ...td, fontWeight: 600 }}>{formatRial(row.paid_rials)}</td>
<td style={{ ...td, color: row.remaining_rials > 0 ? 'var(--danger)' : 'var(--text-2)' }}>
{formatRial(row.remaining_rials)}
</td>
<td style={td}>
<span className={`badge ${STATUS_BADGE[row.status]}`}><span className="bdot" />{STATUS_LABEL[row.status]}</span>
</td>
<td style={{ ...td, textAlign: 'left' }}>
<button
className="cp-btn-secondary"
style={{ height: 32, padding: '0 12px', display: 'inline-flex', alignItems: 'center', gap: 5 }}
onClick={() => navigate(`/admin/my-payments/${row.patient_uuid}`)}
>
<EyeIcon style={{ width: 15 }} /> مشاهده
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div style={{ marginTop: 16 }}>
<Pagination page={page} total={total} limit={MY_PAYMENTS_LIMIT} onPageChange={setPage} />
</div>
</>
)}
</>
);
}