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"