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:
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user