refactor(billing): rebuild payments list as flat invoice list (tauri parity)

Align /admin/my-payments with the tauri /payments source (per user): the list
is now a flat, newest-first list of the tenant's recorded invoices — one row
per invoice — instead of the per-patient aggregation built from Figma.

Backend:
- replace InvoiceRepository::patientPaymentSummary aggregation with
  tenantInvoices/countTenantInvoices (flat, joins patient name/national code).
- InvoiceService::patientPaymentList → tenantInvoiceList.
- BillingController: GET /api/v1/my/billing/patient-payments →
  GET /api/v1/my/billing/payments returning
  { invoice_uuid, patient_uuid, patient_name, national_code, issued_at,
    amount_rials, status } rows.
- node-2 patient invoices endpoint unchanged.

Frontend:
- useMyPayments: usePatientPayments → usePayments (flat PaymentRow).
- MyPaymentsPage columns match tauri DetailT: row #, avatar+name, national
  code, date-time, amount paid, مشاهده (no status column); 'اضافه کردن بیمار'
  links to /admin/patients/new. Filters (national code / status / Jalali date
  range) kept.

Tests + docs/api/billing.md updated. Intentionally omitted tauri extras:
mobile Cards view and the advanced ModalFilter.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-14 19:00:17 +03:30
co-authored by Claude Opus 4.8
parent 8d6278e125
commit 818506bf36
9 changed files with 166 additions and 192 deletions
+4 -4
View File
@@ -9,7 +9,7 @@ vi.mock('../lib/api', () => ({
}));
import { api } from '../lib/api';
import { usePatientPayments, usePatientInvoices } from './useMyPayments';
import { usePayments, usePatientInvoices } from './useMyPayments';
const get = api.get as ReturnType<typeof vi.fn>;
@@ -25,10 +25,10 @@ beforeEach(() => {
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 });
renderHook(() => usePayments({ 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('/api/v1/my/billing/payments?');
expect(url).toContain('page=2');
expect(url).toContain('national_code=1744');
expect(url).toContain('status=paid');
@@ -37,7 +37,7 @@ describe('useMyPayments', () => {
});
it('omits empty filters from the list URL', async () => {
renderHook(() => usePatientPayments({ page: 1 }), { wrapper });
renderHook(() => usePayments({ page: 1 }), { wrapper });
await waitFor(() => expect(get).toHaveBeenCalled());
const url = get.mock.calls[0][0] as string;
expect(url).not.toContain('national_code=');
+14 -13
View File
@@ -2,23 +2,24 @@ 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';
/** Two-state invoice status shown on both the list (node 1) and detail (node 2). */
export type PaymentRowStatus = 'paid' | 'unsettled';
export interface PatientPaymentRow {
/** One recorded invoice on the flat payments list (node 1). */
export interface PaymentRow {
invoice_uuid: string;
patient_uuid: string;
patient_name: string | null;
national_code: string | null;
invoice_count: number;
paid_rials: number;
remaining_rials: number;
issued_at: number;
amount_rials: number;
status: PaymentRowStatus;
}
export interface PatientPaymentFilters {
export interface PaymentFilters {
page: number;
national_code?: string;
status?: string; // paid | unsettled | unpaid
status?: string; // paid | unsettled
from?: number; // unix seconds
to?: number; // unix seconds
}
@@ -44,17 +45,17 @@ export interface PatientInvoicesPayload {
const LIMIT = 20;
/** Node 1 — paginated per-patient payment summary for the current tenant. */
export function usePatientPayments(filters: PatientPaymentFilters) {
/** Node 1 — flat, paginated list of the current tenant's recorded invoices. */
export function usePayments(filters: PaymentFilters) {
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()}`),
return useQuery<PaginatedResponse<PaymentRow>>({
queryKey: ['payments', filters],
queryFn: () => api.get(`/api/v1/my/billing/payments?${qs.toString()}`),
});
}
+6 -8
View File
@@ -15,10 +15,10 @@ 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' },
{ invoice_uuid: 'iv1', patient_uuid: 'p1', patient_name: 'دنیا خلیلی', national_code: '1744023654',
issued_at: 1717000000, amount_rials: 2350000, status: 'paid' },
{ invoice_uuid: 'iv2', patient_uuid: 'p2', patient_name: 'علی بدیعی', national_code: '2200112233',
issued_at: 1718000000, amount_rials: 6000000, status: 'unsettled' },
];
beforeEach(() => {
@@ -28,14 +28,12 @@ beforeEach(() => {
});
describe('MyPaymentsPage (لیست پرداخت‌ها)', () => {
it('renders patient payment rows with derived status labels', async () => {
it('renders a flat row per invoice with patient name and national code', 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();
expect(screen.getByText('2200112233')).toBeInTheDocument();
});
it('navigates to the patient detail on مشاهده', async () => {
+43 -34
View File
@@ -1,29 +1,22 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { MagnifyingGlassIcon, EyeIcon, BanknotesIcon } from '@heroicons/react/24/outline';
import { MagnifyingGlassIcon, EyeIcon, BanknotesIcon, UserPlusIcon } 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 { formatRial, formatDate, formatNumber, toDate } from '../lib/utils';
import {
usePatientPayments,
usePayments,
MY_PAYMENTS_LIMIT,
type PatientPaymentRow,
type PaymentRowStatus,
type PaymentRow,
} 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: PaymentRow[] = [];
const EMPTY: PatientPaymentRow[] = [];
/** 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));
}
/** 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 {
@@ -33,7 +26,19 @@ function dayBound(value: string, end: boolean): number | undefined {
return end ? secs + 86399 : secs;
}
/** لیست پرداخت‌ها — per-patient payment summary for the logged-in doctor/clinic. */
function Avatar({ name }: { name: string | null }) {
return (
<div style={{
width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
background: 'linear-gradient(145deg, var(--primary), var(--primary-700, var(--primary)))',
display: 'grid', placeItems: 'center', color: '#fff', fontSize: 13, fontWeight: 700,
}}>
{(name ?? '؟').charAt(0)}
</div>
);
}
/** لیست پرداخت‌ها — flat list of the tenant's recorded invoices (ported from tauri /payments). */
export default function MyPaymentsPage() {
const navigate = useNavigate();
const [page, setPage] = useState(1);
@@ -44,7 +49,7 @@ export default function MyPaymentsPage() {
const reset = () => setPage(1);
const { data, isLoading } = usePatientPayments({
const { data, isLoading } = usePayments({
page,
national_code: nationalCode.trim() || undefined,
status: status || undefined,
@@ -60,9 +65,17 @@ export default function MyPaymentsPage() {
return (
<>
<PageHeader title="لیست پرداخت‌ها" description="خلاصه‌ی پرداخت‌های بیماران شما" />
<PageHeader
title="لیست پرداخت‌ها"
description="پرداخت‌های ثبت‌شده‌ی بیماران شما"
action={
<button className="btn primary sm" onClick={() => navigate('/admin/patients/new')}>
<UserPlusIcon style={{ width: 16 }} /> اضافه کردن بیمار
</button>
}
/>
{/* فیلترها */}
{/* فیلترها — کد ملی + وضعیت + بازه‌ی تاریخ */}
<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,
@@ -89,7 +102,6 @@ export default function MyPaymentsPage() {
<option value="">همه وضعیتها</option>
<option value="paid">پرداخت شده</option>
<option value="unsettled">تسویه نشده</option>
<option value="unpaid">پرداخت نشده</option>
</select>
<div style={{ width: 150 }}>
@@ -117,27 +129,24 @@ export default function MyPaymentsPage() {
<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}>تاریخ</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)' }}>
<tr key={row.invoice_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>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Avatar name={row.patient_name} />
<span style={{ fontWeight: 600 }}>{row.patient_name ?? '—'}</span>
</div>
</td>
<td style={{ ...td, color: 'var(--text-2)' }} dir="ltr">{row.national_code ?? '—'}</td>
<td style={td} dir="ltr">{formatDate(row.issued_at)} - {formatTime(row.issued_at)}</td>
<td style={{ ...td, fontWeight: 600 }}>{formatRial(row.amount_rials)}</td>
<td style={{ ...td, textAlign: 'left' }}>
<button
className="cp-btn-secondary"
+7 -6
View File
@@ -185,15 +185,15 @@
```
`debt = claimed - paid` (حداقل صفر).
## GET /api/v1/my/billing/patient-payments
«لیست پرداخت‌ها» — یک ردیف به‌ازای هر بیمار با جمع صورتحساب‌های همان tenant. صورتحساب‌های `draft`/`void` نادیده گرفته می‌شوند.
## GET /api/v1/my/billing/payments
«لیست پرداخت‌ها» — فهرست مسطح صورتحساب‌های ثبت‌شده‌ی همان tenant (هر ردیف یک صورتحساب)، جدیدترین اول. فقط `finalized`/`paid`؛ `draft`/`void` نادیده گرفته می‌شوند.
**Query params:**
| param | توضیح |
|-------|-------|
| `national_code` | جست‌وجوی جزئی روی کد ملی بیمار (`LIKE`) |
| `status` | `paid` (باقیمانده=۰) · `unpaid` (پرداختی=۰ و باقیمانده>۰) · `unsettled` (هر دو>۰) — روی جمع‌ها اعمال می‌شود |
| `status` | `paid` (پرداخت‌شده) · `unsettled` (تسویه‌نشده = `finalized`) |
| `from` / `to` | بازه‌ی `issued_at` بر حسب ثانیه‌ی Unix |
| `page` / `limit` | صفحه‌بندی (پیش‌فرض ۱ / ۲۰، سقف ۱۰۰) |
@@ -202,13 +202,14 @@
{
"success": true,
"data": [
{ "patient_uuid": "…", "patient_name": "دنیا خلیلی", "national_code": "1744023654",
"invoice_count": 2, "paid_rials": 2350000, "remaining_rials": 500000, "status": "unsettled" }
{ "invoice_uuid": "…", "patient_uuid": "…", "patient_name": "دنیا خلیلی",
"national_code": "1744023654", "issued_at": 1717000000,
"amount_rials": 2350000, "status": "paid" }
],
"meta": { "totalRecords": 12, "totalPages": 1, "currentPage": 1 }
}
```
> `paid_rials` = جمع سهم بیمار روی صورتحساب‌های `paid`؛ `remaining_rials` = جمع سهم بیمار روی صورتحساب‌های `finalized`. `status` سمت سرور از همین دو مشتق می‌شود.
> `amount_rials` = سهم بیمار (`patient_rials`) همان صورتحساب. `status` دو حالته: `paid` یا `unsettled`.
**Errors:** `403` (`ERR_FORBIDDEN_001`) پروفایل tenant یافت نشد.
+7 -7
View File
@@ -157,13 +157,13 @@ class BillingController extends BaseController
}
/**
* لیست پرداخت‌ها — یک ردیف به‌ازای هر بیمار با جمع صورتحساب‌ها.
* فیلترها: national_code، status (paid|unsettled|unpaid)، from/to (unix ثانیه).
* پاسخ صفحه‌بندی: هر ردیف { patient_uuid, patient_name, national_code,
* invoice_count, paid_rials, remaining_rials, status }.
* لیست پرداخت‌ها — یک ردیف به‌ازای هر صورتحساب ثبت‌شده‌ی tenant (flat).
* فیلترها: national_code، status (paid|unsettled)، from/to (unix ثانیه).
* پاسخ صفحه‌بندی: هر ردیف { invoice_uuid, patient_uuid, patient_name,
* national_code, issued_at, amount_rials, status }.
*/
#[Route('/api/v1/my/billing/patient-payments', methods: ['GET'])]
public function listPatientPayments(Request $request, #[CurrentUser] User $user): JsonResponse
#[Route('/api/v1/my/billing/payments', methods: ['GET'])]
public function listPayments(Request $request, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
@@ -179,7 +179,7 @@ class BillingController extends BaseController
$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);
$result = $this->invoiceService->tenantInvoiceList($entityType, $entityId, $filters, $page, $limit);
return $this->paginated($result['items'], $result['total'], $page, $limit);
}
+54 -59
View File
@@ -27,36 +27,74 @@ class InvoiceRepository extends ServiceEntityRepository
}
/**
* 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.
* A flat, newest-first page of a tenant's recorded (finalized/paid) invoices,
* one row per invoice with the patient's name and national code joined in.
*
* @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}>
* status: paid | unsettled (maps to invoice paid / finalized).
* @return list<array{invoice_uuid:string,patient_uuid:string,patient_name:?string,national_code:?string,issued_at:int,amount_rials:int,status:string}>
*/
public function patientPaymentSummary(string $entityType, int $entityId, array $filters, int $page, int $limit): array
public function tenantInvoices(string $entityType, int $entityId, array $filters, int $page, int $limit): array
{
$rows = $this->summaryQuery($entityType, $entityId, $filters)
$rows = $this->tenantInvoicesQuery($entityType, $entityId, $filters)
->select(
'i.uuid AS invoice_uuid', 'r.uuid AS patient_uuid', 'u.realName AS patient_name',
'u.nationalCode AS national_code', 'i.issuedAt AS issued_at',
'i.patientRials AS amount_rials', 'i.status AS status',
)
->orderBy('i.issuedAt', 'DESC')
->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'],
'invoice_uuid' => $r['invoice_uuid'],
'patient_uuid' => $r['patient_uuid'],
'patient_name' => $r['patient_name'],
'national_code' => $r['national_code'],
'issued_at' => (int) $r['issued_at'],
'amount_rials' => (int) $r['amount_rials'],
'status' => $r['status'] === Invoice::STATUS_PAID ? 'paid' : 'unsettled',
], $rows);
}
/** Number of patients (groups) matching the same filters — for pagination. */
public function countPatientPaymentSummary(string $entityType, int $entityId, array $filters): int
public function countTenantInvoices(string $entityType, int $entityId, array $filters): int
{
return count($this->summaryQuery($entityType, $entityId, $filters)->getQuery()->getArrayResult());
return (int) $this->tenantInvoicesQuery($entityType, $entityId, $filters)
->select('COUNT(i.id)')
->getQuery()
->getSingleScalarResult();
}
private function tenantInvoicesQuery(string $entityType, int $entityId, array $filters): QueryBuilder
{
$qb = $this->createQueryBuilder('i')
->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]);
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']);
}
if (($filters['status'] ?? null) === 'paid') {
$qb->andWhere('i.status = :st')->setParameter('st', Invoice::STATUS_PAID);
} elseif (($filters['status'] ?? null) === 'unsettled') {
$qb->andWhere('i.status = :st')->setParameter('st', Invoice::STATUS_FINALIZED);
}
return $qb;
}
/**
@@ -94,49 +132,6 @@ class InvoiceRepository extends ServiceEntityRepository
->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);
+6 -13
View File
@@ -76,25 +76,18 @@ class InvoiceService
}
/**
* Paginated per-patient payment summary for a tenant. Each row gains a
* derived status: `paid` (nothing outstanding), `unpaid` (nothing paid
* yet), `unsettled` (partially paid).
* Paginated flat list of a tenant's recorded (finalized/paid) invoices for
* the payments list (node 1). Rows arrive ready-shaped from the repository;
* this only pairs them with the total for pagination.
*
* @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
public function tenantInvoiceList(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),
'items' => $this->invoiceRepo->tenantInvoices($entityType, $entityId, $filters, $page, $limit),
'total' => $this->invoiceRepo->countTenantInvoices($entityType, $entityId, $filters),
];
}
+25 -48
View File
@@ -11,8 +11,8 @@ 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.
* GET /api/v1/my/billing/payments — flat, tenant-scoped list of recorded
* invoices, and GET .../patients/{uuid}/invoices — one patient's invoices.
*/
class PatientPaymentsTest extends ApiTestCase
{
@@ -82,51 +82,30 @@ class PatientPaymentsTest extends ApiTestCase
$ref->setValue($obj, $value);
}
public function testAggregatesPerPatientWithDerivedStatus(): void
public function testListsFlatInvoicesNewestFirst(): 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
$this->invoice($doctor, $a, Invoice::STATUS_PAID, 100000, 2000);
$this->invoice($doctor, $a, Invoice::STATUS_FINALIZED, 50000, 1000);
$this->invoice($doctor, $a, Invoice::STATUS_DRAFT, 999999, 3000); // excluded
$this->invoice($doctor, $a, Invoice::STATUS_VOID, 999999, 3000); // excluded
$b = $this->patientRecord($doctor, 'علی بدیعی');
$this->invoice($doctor, $b, Invoice::STATUS_PAID, 200000);
$res = $this->authJson('GET', '/api/v1/my/billing/patient-payments', $owner);
$res = $this->authJson('GET', '/api/v1/my/billing/payments', $owner);
self::assertSame(200, $this->responseCode());
self::assertSame(2, $res['meta']['totalRecords']);
self::assertSame(2, $res['meta']['totalRecords']); // draft/void excluded
$byUuid = [];
foreach ($res['data'] as $row) {
$byUuid[$row['patient_uuid']] = $row;
}
// newest (issued_at DESC) first
self::assertSame('دنیا خلیلی', $res['data'][0]['patient_name']);
self::assertSame($this->nationalCodeOf($a), $res['data'][0]['national_code']);
self::assertSame(100000, $res['data'][0]['amount_rials']);
self::assertSame('paid', $res['data'][0]['status']);
self::assertArrayHasKey('invoice_uuid', $res['data'][0]);
self::assertSame($a->getUuid(), $res['data'][0]['patient_uuid']);
$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']);
self::assertSame(50000, $res['data'][1]['amount_rials']);
self::assertSame('unsettled', $res['data'][1]['status']);
}
public function testFiltersByNationalCodeAndStatus(): void
@@ -137,25 +116,23 @@ class PatientPaymentsTest extends ApiTestCase
$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);
$byCode = $this->authJson('GET', '/api/v1/my/billing/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);
$onlyPaid = $this->authJson('GET', '/api/v1/my/billing/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']);
$onlyUnsettled = $this->authJson('GET', '/api/v1/my/billing/payments?status=unsettled', $owner);
self::assertSame(1, $onlyUnsettled['meta']['totalRecords']);
self::assertSame($unpaid->getUuid(), $onlyUnsettled['data'][0]['patient_uuid']);
}
public function testEmptyWhenNoInvoices(): void
{
[$owner] = $this->doctor();
$res = $this->authJson('GET', '/api/v1/my/billing/patient-payments', $owner);
$res = $this->authJson('GET', '/api/v1/my/billing/payments', $owner);
self::assertSame(200, $this->responseCode());
self::assertSame(0, $res['meta']['totalRecords']);
self::assertCount(0, $res['data']);
@@ -164,7 +141,7 @@ class PatientPaymentsTest extends ApiTestCase
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);
$this->authJson('GET', '/api/v1/my/billing/payments', $orphan);
self::assertSame(403, $this->responseCode());
}