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:
@@ -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,
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -185,6 +185,55 @@
|
||||
```
|
||||
`debt = claimed - paid` (حداقل صفر).
|
||||
|
||||
## GET /api/v1/my/billing/patient-payments
|
||||
«لیست پرداختها» — یک ردیف بهازای هر بیمار با جمع صورتحسابهای همان tenant. صورتحسابهای `draft`/`void` نادیده گرفته میشوند.
|
||||
|
||||
**Query params:**
|
||||
|
||||
| param | توضیح |
|
||||
|-------|-------|
|
||||
| `national_code` | جستوجوی جزئی روی کد ملی بیمار (`LIKE`) |
|
||||
| `status` | `paid` (باقیمانده=۰) · `unpaid` (پرداختی=۰ و باقیمانده>۰) · `unsettled` (هر دو>۰) — روی جمعها اعمال میشود |
|
||||
| `from` / `to` | بازهی `issued_at` بر حسب ثانیهی Unix |
|
||||
| `page` / `limit` | صفحهبندی (پیشفرض ۱ / ۲۰، سقف ۱۰۰) |
|
||||
|
||||
**Response 200** (صفحهبندیشدهی مسطح):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "patient_uuid": "…", "patient_name": "دنیا خلیلی", "national_code": "1744023654",
|
||||
"invoice_count": 2, "paid_rials": 2350000, "remaining_rials": 500000, "status": "unsettled" }
|
||||
],
|
||||
"meta": { "totalRecords": 12, "totalPages": 1, "currentPage": 1 }
|
||||
}
|
||||
```
|
||||
> `paid_rials` = جمع سهم بیمار روی صورتحسابهای `paid`؛ `remaining_rials` = جمع سهم بیمار روی صورتحسابهای `finalized`. `status` سمت سرور از همین دو مشتق میشود.
|
||||
|
||||
**Errors:** `403` (`ERR_FORBIDDEN_001`) پروفایل tenant یافت نشد.
|
||||
|
||||
## GET /api/v1/my/billing/patients/{patientUuid}/invoices
|
||||
«پرداختهای ثبتشده» — سربرگ بیمار + فهرست صفحهبندیشدهی صورتحسابهای `finalized`/`paid` او (جدیدترین اول). فقط مالک رکورد (همان tenant) دسترسی دارد.
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"patient": { "uuid": "…", "name": "دنیا خلیلی", "national_code": "1744023654" },
|
||||
"data": [
|
||||
{ "uuid": "…", "number": 12345, "issued_at": 1717000000, "total_rials": 2350000,
|
||||
"status": "paid", "service_title": "روکش دندان",
|
||||
"items": [ { "uuid": "…", "title": "روکش دندان", "quantity": 1, "total_rials": 2350000, "patient_rials": 2350000 } ] }
|
||||
],
|
||||
"meta": { "totalRecords": 3, "totalPages": 1, "currentPage": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
> `status` دو حالته: `paid` (پرداختشده) یا `unsettled` (تسویهنشده = `finalized`). `service_title` عنوان اولین آیتم است (+ «و موارد دیگر» اگر بیش از یک آیتم باشد).
|
||||
|
||||
**Errors:** `403` پروفایل tenant یافت نشد · `404` (`ERR_NOT_FOUND_001`) بیمار متعلق به این tenant نیست/یافت نشد.
|
||||
|
||||
---
|
||||
|
||||
## ارسال مطالبه (ClaimSubmitter)
|
||||
|
||||
@@ -12,6 +12,7 @@ use App\Billing\Service\InvoiceService;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Insurance\Repository\InsuranceRepository;
|
||||
use App\Patient\Repository\PatientRecordRepository;
|
||||
use App\Patient\Repository\PatientSessionRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
@@ -33,6 +34,7 @@ class BillingController extends BaseController
|
||||
private readonly ClaimService $claimService,
|
||||
private readonly ClaimRepository $claimRepo,
|
||||
private readonly PatientSessionRepository $sessionRepo,
|
||||
private readonly PatientRecordRepository $recordRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly InsuranceRepository $insuranceRepo,
|
||||
@@ -154,6 +156,73 @@ class BillingController extends BaseController
|
||||
return $this->success(['data' => $invoice->toArray()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* لیست پرداختها — یک ردیف بهازای هر بیمار با جمع صورتحسابها.
|
||||
* فیلترها: national_code، status (paid|unsettled|unpaid)، from/to (unix ثانیه).
|
||||
* پاسخ صفحهبندی: هر ردیف { patient_uuid, patient_name, national_code,
|
||||
* invoice_count, paid_rials, remaining_rials, status }.
|
||||
*/
|
||||
#[Route('/api/v1/my/billing/patient-payments', methods: ['GET'])]
|
||||
public function listPatientPayments(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$filters = [
|
||||
'national_code' => $request->query->get('national_code') ?: null,
|
||||
'status' => $request->query->get('status') ?: null,
|
||||
'from' => $request->query->get('from') ?: null,
|
||||
'to' => $request->query->get('to') ?: null,
|
||||
];
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(100, max(1, (int) $request->query->get('limit', 20)));
|
||||
|
||||
$result = $this->invoiceService->patientPaymentList($entityType, $entityId, $filters, $page, $limit);
|
||||
|
||||
return $this->paginated($result['items'], $result['total'], $page, $limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* پرداختهای ثبتشدهی یک بیمار — سربرگ بیمار + فهرست صفحهبندیشدهی صورتحسابها.
|
||||
* فقط مالک رکورد (همان tenant) اجازه دارد؛ در غیر این صورت ۴۰۴.
|
||||
* پاسخ: { patient:{uuid,name,national_code}, data:[صورتحسابها], meta:{...} }.
|
||||
*/
|
||||
#[Route('/api/v1/my/billing/patients/{patientUuid}/invoices', methods: ['GET'])]
|
||||
public function listPatientInvoices(string $patientUuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$record = $this->recordRepo->findByUuid($patientUuid);
|
||||
if ($record === null || $record->getEntityType() !== $entityType || $record->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'بیمار یافت نشد', 404);
|
||||
}
|
||||
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(100, max(1, (int) $request->query->get('limit', 20)));
|
||||
|
||||
$result = $this->invoiceService->patientInvoiceList($entityType, $entityId, $record->getId(), $page, $limit);
|
||||
$patient = $record->getUser();
|
||||
|
||||
return $this->success([
|
||||
'patient' => [
|
||||
'uuid' => $record->getUuid(),
|
||||
'name' => $patient->getRealName(),
|
||||
'national_code' => $patient->getNationalCode(),
|
||||
],
|
||||
'data' => $result['items'],
|
||||
'meta' => [
|
||||
'totalRecords' => $result['total'],
|
||||
'totalPages' => (int) ceil($result['total'] / $limit),
|
||||
'currentPage' => $page,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
// ── Claims (مطالبات بیمه) ──────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/billing/claims', methods: ['POST'])]
|
||||
|
||||
@@ -92,6 +92,7 @@ class Invoice
|
||||
public function getSupplementaryInsuranceId(): ?int { return $this->supplementaryInsuranceId; }
|
||||
public function getTotalRials(): int { return $this->totalRials; }
|
||||
public function getPatientRials(): int { return $this->patientRials; }
|
||||
public function getIssuedAt(): int { return $this->issuedAt; }
|
||||
/** @return Collection<int, InvoiceItem> */
|
||||
public function getItems(): Collection { return $this->items; }
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ class InvoiceItem
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getServiceItemId(): ?int { return $this->serviceItemId; }
|
||||
public function getTitle(): string { return $this->title; }
|
||||
public function getTotalRials(): int { return $this->totalRials; }
|
||||
public function getBaseInsuranceRials(): int { return $this->baseInsuranceRials; }
|
||||
public function getSupplementaryRials(): int { return $this->supplementaryRials; }
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\Invoice;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\ORM\Query\Expr\Join;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class InvoiceRepository extends ServiceEntityRepository
|
||||
@@ -23,6 +26,117 @@ class InvoiceRepository extends ServiceEntityRepository
|
||||
return $this->findOneBy(['patientSessionId' => $patientSessionId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* One row per patient (record) with their invoice totals for a tenant.
|
||||
* paid = patient share on paid invoices; remaining = patient share on
|
||||
* finalized-but-unpaid invoices. draft/void invoices are ignored.
|
||||
*
|
||||
* @param array{national_code?:?string,status?:?string,from?:?int,to?:?int} $filters
|
||||
* status: paid|unsettled|unpaid — derived from paid/remaining via HAVING.
|
||||
* @return list<array{patient_uuid:string,patient_name:?string,national_code:?string,invoice_count:int,paid_rials:int,remaining_rials:int}>
|
||||
*/
|
||||
public function patientPaymentSummary(string $entityType, int $entityId, array $filters, int $page, int $limit): array
|
||||
{
|
||||
$rows = $this->summaryQuery($entityType, $entityId, $filters)
|
||||
->setFirstResult(($page - 1) * $limit)
|
||||
->setMaxResults($limit)
|
||||
->getQuery()
|
||||
->getArrayResult();
|
||||
|
||||
return array_map(static fn(array $r): array => [
|
||||
'patient_uuid' => $r['patient_uuid'],
|
||||
'patient_name' => $r['patient_name'],
|
||||
'national_code' => $r['national_code'],
|
||||
'invoice_count' => (int) $r['invoice_count'],
|
||||
'paid_rials' => (int) $r['paid_rials'],
|
||||
'remaining_rials' => (int) $r['remaining_rials'],
|
||||
], $rows);
|
||||
}
|
||||
|
||||
/** Number of patients (groups) matching the same filters — for pagination. */
|
||||
public function countPatientPaymentSummary(string $entityType, int $entityId, array $filters): int
|
||||
{
|
||||
return count($this->summaryQuery($entityType, $entityId, $filters)->getQuery()->getArrayResult());
|
||||
}
|
||||
|
||||
/**
|
||||
* A patient's recorded (finalized/paid) invoices for a tenant, newest first.
|
||||
* @return list<Invoice>
|
||||
*/
|
||||
public function invoicesForPatient(string $entityType, int $entityId, int $recordId, int $page, int $limit): array
|
||||
{
|
||||
return $this->patientInvoicesQuery($entityType, $entityId, $recordId)
|
||||
->orderBy('i.issuedAt', 'DESC')
|
||||
->setFirstResult(($page - 1) * $limit)
|
||||
->setMaxResults($limit)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function countInvoicesForPatient(string $entityType, int $entityId, int $recordId): int
|
||||
{
|
||||
return (int) $this->patientInvoicesQuery($entityType, $entityId, $recordId)
|
||||
->select('COUNT(i.id)')
|
||||
->getQuery()
|
||||
->getSingleScalarResult();
|
||||
}
|
||||
|
||||
private function patientInvoicesQuery(string $entityType, int $entityId, int $recordId): QueryBuilder
|
||||
{
|
||||
return $this->createQueryBuilder('i')
|
||||
->where('i.entityType = :type')
|
||||
->andWhere('i.entityId = :id')
|
||||
->andWhere('i.patientRecordId = :record')
|
||||
->andWhere('i.status IN (:active)')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('record', $recordId)
|
||||
->setParameter('active', [Invoice::STATUS_FINALIZED, Invoice::STATUS_PAID]);
|
||||
}
|
||||
|
||||
private function summaryQuery(string $entityType, int $entityId, array $filters): QueryBuilder
|
||||
{
|
||||
$paidSum = 'SUM(CASE WHEN i.status = :paid THEN i.patientRials ELSE 0 END)';
|
||||
$remSum = 'SUM(CASE WHEN i.status = :finalized THEN i.patientRials ELSE 0 END)';
|
||||
|
||||
$qb = $this->createQueryBuilder('i')
|
||||
->select('r.uuid AS patient_uuid', 'u.realName AS patient_name', 'u.nationalCode AS national_code')
|
||||
->addSelect('COUNT(i.id) AS invoice_count')
|
||||
->addSelect("$paidSum AS paid_rials")
|
||||
->addSelect("$remSum AS remaining_rials")
|
||||
->innerJoin(PatientRecord::class, 'r', Join::WITH, 'r.id = i.patientRecordId')
|
||||
->innerJoin('r.user', 'u')
|
||||
->where('i.entityType = :type')
|
||||
->andWhere('i.entityId = :id')
|
||||
->andWhere('i.status IN (:active)')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('active', [Invoice::STATUS_FINALIZED, Invoice::STATUS_PAID])
|
||||
->setParameter('paid', Invoice::STATUS_PAID)
|
||||
->setParameter('finalized', Invoice::STATUS_FINALIZED)
|
||||
->groupBy('r.id')->addGroupBy('r.uuid')->addGroupBy('u.realName')->addGroupBy('u.nationalCode')
|
||||
->orderBy('MAX(i.issuedAt)', 'DESC');
|
||||
|
||||
if (!empty($filters['national_code'])) {
|
||||
$qb->andWhere('u.nationalCode LIKE :nc')->setParameter('nc', '%' . $filters['national_code'] . '%');
|
||||
}
|
||||
if (!empty($filters['from'])) {
|
||||
$qb->andWhere('i.issuedAt >= :from')->setParameter('from', (int) $filters['from']);
|
||||
}
|
||||
if (!empty($filters['to'])) {
|
||||
$qb->andWhere('i.issuedAt <= :to')->setParameter('to', (int) $filters['to']);
|
||||
}
|
||||
|
||||
// Derived-status filters applied on the aggregates.
|
||||
switch ($filters['status'] ?? null) {
|
||||
case 'paid': $qb->having("$remSum = 0"); break;
|
||||
case 'unpaid': $qb->having("$paidSum = 0")->andHaving("$remSum > 0"); break;
|
||||
case 'unsettled': $qb->having("$paidSum > 0")->andHaving("$remSum > 0"); break;
|
||||
}
|
||||
|
||||
return $qb;
|
||||
}
|
||||
|
||||
public function save(Invoice $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
|
||||
@@ -74,4 +74,61 @@ class InvoiceService
|
||||
$invoice->finalize();
|
||||
$this->invoiceRepo->save($invoice);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paginated per-patient payment summary for a tenant. Each row gains a
|
||||
* derived status: `paid` (nothing outstanding), `unpaid` (nothing paid
|
||||
* yet), `unsettled` (partially paid).
|
||||
*
|
||||
* @param array{national_code?:?string,status?:?string,from?:?int,to?:?int} $filters
|
||||
* @return array{items: list<array<string, mixed>>, total: int}
|
||||
*/
|
||||
public function patientPaymentList(string $entityType, int $entityId, array $filters, int $page, int $limit): array
|
||||
{
|
||||
$items = array_map(static function (array $row): array {
|
||||
$row['status'] = $row['remaining_rials'] === 0
|
||||
? 'paid'
|
||||
: ($row['paid_rials'] === 0 ? 'unpaid' : 'unsettled');
|
||||
return $row;
|
||||
}, $this->invoiceRepo->patientPaymentSummary($entityType, $entityId, $filters, $page, $limit));
|
||||
|
||||
return [
|
||||
'items' => $items,
|
||||
'total' => $this->invoiceRepo->countPatientPaymentSummary($entityType, $entityId, $filters),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A patient's recorded invoices, shaped for the detail table: number, issue
|
||||
* time, a single service title (first item, "+ more" when several), total,
|
||||
* a two-state status (paid|unsettled), and the full item breakdown.
|
||||
*
|
||||
* @return array{items: list<array<string, mixed>>, total: int}
|
||||
*/
|
||||
public function patientInvoiceList(string $entityType, int $entityId, int $recordId, int $page, int $limit): array
|
||||
{
|
||||
$items = array_map(function (Invoice $invoice): array {
|
||||
$lineItems = array_map(static fn(InvoiceItem $i) => $i->toArray(), $invoice->getItems()->toArray());
|
||||
$title = match (count($lineItems)) {
|
||||
0 => null,
|
||||
1 => $lineItems[0]['title'],
|
||||
default => $lineItems[0]['title'] . ' و موارد دیگر',
|
||||
};
|
||||
|
||||
return [
|
||||
'uuid' => $invoice->getUuid(),
|
||||
'number' => $invoice->getId(),
|
||||
'issued_at' => $invoice->getIssuedAt(),
|
||||
'total_rials' => $invoice->getTotalRials(),
|
||||
'status' => $invoice->getStatus() === Invoice::STATUS_PAID ? 'paid' : 'unsettled',
|
||||
'service_title' => $title,
|
||||
'items' => $lineItems,
|
||||
];
|
||||
}, $this->invoiceRepo->invoicesForPatient($entityType, $entityId, $recordId, $page, $limit));
|
||||
|
||||
return [
|
||||
'items' => $items,
|
||||
'total' => $this->invoiceRepo->countInvoicesForPatient($entityType, $entityId, $recordId),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Billing;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Billing\Entity\Invoice;
|
||||
use App\Billing\Entity\InvoiceItem;
|
||||
use App\Billing\ValueObject\ShareBreakdown;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* GET /api/v1/my/billing/patient-payments — per-patient payment summary for the
|
||||
* caller's tenant, with paid/remaining aggregates and a derived row status.
|
||||
*/
|
||||
class PatientPaymentsTest extends ApiTestCase
|
||||
{
|
||||
/** @return array{0: User, 1: Doctor} owner user + their doctor profile */
|
||||
private function doctor(): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر تست');
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $doctor];
|
||||
}
|
||||
|
||||
// national_code is UNIQUE and db_test is never reset, so randomise it per
|
||||
// patient (like mobile) to avoid cross-run collisions; read it back from the
|
||||
// record's user when a test needs to filter by it.
|
||||
private function patientRecord(Doctor $doctor, string $realName): PatientRecord
|
||||
{
|
||||
$patient = $this->createUser(['ROLE_USER']);
|
||||
$this->setField($patient, 'realName', $realName);
|
||||
$this->setField($patient, 'nationalCode', str_pad((string) random_int(0, 9_999_999_999), 10, '0', STR_PAD_LEFT));
|
||||
|
||||
$record = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
|
||||
$this->em->persist($record);
|
||||
$this->em->flush();
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
private function nationalCodeOf(PatientRecord $record): string
|
||||
{
|
||||
return $record->getUser()->getNationalCode();
|
||||
}
|
||||
|
||||
private function invoice(
|
||||
Doctor $doctor,
|
||||
PatientRecord $record,
|
||||
string $status,
|
||||
int $patientRials,
|
||||
?int $issuedAt = null,
|
||||
?string $itemTitle = null,
|
||||
int $totalRials = 0,
|
||||
): Invoice {
|
||||
$invoice = new Invoice('doctor', $doctor->getId());
|
||||
$invoice->setPatientRecordId($record->getId());
|
||||
if ($itemTitle !== null) {
|
||||
// Item added only for its title (service_title); totals set below by hand.
|
||||
$invoice->addItem(new InvoiceItem($invoice, $itemTitle, $totalRials, 1, new ShareBreakdown($totalRials, 0, 0, $patientRials), null));
|
||||
}
|
||||
$this->setField($invoice, 'status', $status);
|
||||
$this->setField($invoice, 'patientRials', $patientRials);
|
||||
$this->setField($invoice, 'totalRials', $totalRials);
|
||||
if ($issuedAt !== null) {
|
||||
$this->setField($invoice, 'issuedAt', $issuedAt);
|
||||
}
|
||||
$this->em->persist($invoice);
|
||||
$this->em->flush();
|
||||
|
||||
return $invoice;
|
||||
}
|
||||
|
||||
private function setField(object $obj, string $prop, mixed $value): void
|
||||
{
|
||||
$ref = new \ReflectionProperty($obj, $prop);
|
||||
$ref->setAccessible(true);
|
||||
$ref->setValue($obj, $value);
|
||||
}
|
||||
|
||||
public function testAggregatesPerPatientWithDerivedStatus(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
|
||||
$a = $this->patientRecord($doctor, 'دنیا خلیلی');
|
||||
$this->invoice($doctor, $a, Invoice::STATUS_PAID, 100000);
|
||||
$this->invoice($doctor, $a, Invoice::STATUS_FINALIZED, 50000);
|
||||
$this->invoice($doctor, $a, Invoice::STATUS_DRAFT, 999999); // ignored
|
||||
$this->invoice($doctor, $a, Invoice::STATUS_VOID, 999999); // ignored
|
||||
|
||||
$b = $this->patientRecord($doctor, 'علی بدیعی');
|
||||
$this->invoice($doctor, $b, Invoice::STATUS_PAID, 200000);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/my/billing/patient-payments', $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertSame(2, $res['meta']['totalRecords']);
|
||||
|
||||
$byUuid = [];
|
||||
foreach ($res['data'] as $row) {
|
||||
$byUuid[$row['patient_uuid']] = $row;
|
||||
}
|
||||
|
||||
$rowA = $byUuid[$a->getUuid()];
|
||||
self::assertSame('دنیا خلیلی', $rowA['patient_name']);
|
||||
self::assertSame(2, $rowA['invoice_count']); // draft/void excluded
|
||||
self::assertSame(100000, $rowA['paid_rials']);
|
||||
self::assertSame(50000, $rowA['remaining_rials']);
|
||||
self::assertSame('unsettled', $rowA['status']);
|
||||
|
||||
$rowB = $byUuid[$b->getUuid()];
|
||||
self::assertSame(200000, $rowB['paid_rials']);
|
||||
self::assertSame(0, $rowB['remaining_rials']);
|
||||
self::assertSame('paid', $rowB['status']);
|
||||
}
|
||||
|
||||
public function testUnpaidStatusWhenNothingPaid(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$c = $this->patientRecord($doctor, 'مازیار عزیزی');
|
||||
$this->invoice($doctor, $c, Invoice::STATUS_FINALIZED, 300000);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/my/billing/patient-payments', $owner);
|
||||
self::assertSame('unpaid', $res['data'][0]['status']);
|
||||
self::assertSame(0, $res['data'][0]['paid_rials']);
|
||||
self::assertSame(300000, $res['data'][0]['remaining_rials']);
|
||||
}
|
||||
|
||||
public function testFiltersByNationalCodeAndStatus(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$paid = $this->patientRecord($doctor, 'بیمار پرداخت');
|
||||
$unpaid = $this->patientRecord($doctor, 'بیمار بدهکار');
|
||||
$this->invoice($doctor, $paid, Invoice::STATUS_PAID, 100000);
|
||||
$this->invoice($doctor, $unpaid, Invoice::STATUS_FINALIZED, 100000);
|
||||
|
||||
// national_code (partial match)
|
||||
$byCode = $this->authJson('GET', '/api/v1/my/billing/patient-payments?national_code=' . $this->nationalCodeOf($paid), $owner);
|
||||
self::assertSame(1, $byCode['meta']['totalRecords']);
|
||||
self::assertSame($paid->getUuid(), $byCode['data'][0]['patient_uuid']);
|
||||
|
||||
// derived status
|
||||
$onlyPaid = $this->authJson('GET', '/api/v1/my/billing/patient-payments?status=paid', $owner);
|
||||
self::assertSame(1, $onlyPaid['meta']['totalRecords']);
|
||||
self::assertSame('paid', $onlyPaid['data'][0]['status']);
|
||||
|
||||
$onlyUnpaid = $this->authJson('GET', '/api/v1/my/billing/patient-payments?status=unpaid', $owner);
|
||||
self::assertSame(1, $onlyUnpaid['meta']['totalRecords']);
|
||||
self::assertSame($unpaid->getUuid(), $onlyUnpaid['data'][0]['patient_uuid']);
|
||||
}
|
||||
|
||||
public function testEmptyWhenNoInvoices(): void
|
||||
{
|
||||
[$owner] = $this->doctor();
|
||||
$res = $this->authJson('GET', '/api/v1/my/billing/patient-payments', $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertSame(0, $res['meta']['totalRecords']);
|
||||
self::assertCount(0, $res['data']);
|
||||
}
|
||||
|
||||
public function testForbiddenWithoutProfile(): void
|
||||
{
|
||||
$orphan = $this->createUser(['ROLE_DOCTOR']); // ROLE_DOCTOR but no Doctor row
|
||||
$this->authJson('GET', '/api/v1/my/billing/patient-payments', $orphan);
|
||||
self::assertSame(403, $this->responseCode());
|
||||
}
|
||||
|
||||
// ── Node 2: a patient's recorded invoices ────────────────────────────────
|
||||
|
||||
public function testListsPatientInvoicesWithHeaderAndDerivedStatus(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$record = $this->patientRecord($doctor, 'دنیا خلیلی');
|
||||
|
||||
$this->invoice($doctor, $record, Invoice::STATUS_PAID, 235000, 1000, 'روکش دندان', 235000);
|
||||
$this->invoice($doctor, $record, Invoice::STATUS_FINALIZED, 600000, 2000, 'طرح لبخند', 600000);
|
||||
$this->invoice($doctor, $record, Invoice::STATUS_DRAFT, 111, 3000, 'پیشنویس', 111); // excluded
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/my/billing/patients/' . $record->getUuid() . '/invoices', $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
|
||||
// header
|
||||
self::assertSame('دنیا خلیلی', $res['data']['patient']['name']);
|
||||
self::assertSame($this->nationalCodeOf($record), $res['data']['patient']['national_code']);
|
||||
|
||||
// invoices — draft excluded, newest (issued_at DESC) first
|
||||
self::assertSame(2, $res['data']['meta']['totalRecords']);
|
||||
$rows = $res['data']['data'];
|
||||
self::assertCount(2, $rows);
|
||||
self::assertSame('طرح لبخند', $rows[0]['service_title']);
|
||||
self::assertSame('unsettled', $rows[0]['status']);
|
||||
self::assertSame(600000, $rows[0]['total_rials']);
|
||||
self::assertSame('روکش دندان', $rows[1]['service_title']);
|
||||
self::assertSame('paid', $rows[1]['status']);
|
||||
}
|
||||
|
||||
public function testPatientInvoicesNotFoundForOtherTenant(): void
|
||||
{
|
||||
[, $doctor] = $this->doctor();
|
||||
$record = $this->patientRecord($doctor, 'بیمار');
|
||||
|
||||
[$other] = $this->doctor();
|
||||
$this->authJson('GET', '/api/v1/my/billing/patients/' . $record->getUuid() . '/invoices', $other);
|
||||
self::assertSame(404, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testPatientInvoicesEmpty(): void
|
||||
{
|
||||
[$owner, $doctor] = $this->doctor();
|
||||
$record = $this->patientRecord($doctor, 'بدون فاکتور');
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/my/billing/patients/' . $record->getUuid() . '/invoices', $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertSame(0, $res['data']['meta']['totalRecords']);
|
||||
self::assertCount(0, $res['data']['data']);
|
||||
self::assertSame('بدون فاکتور', $res['data']['patient']['name']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user