Files
clinicpro/src/Billing/Service/InvoiceService.php
T
hamedandClaude Opus 4.8 4c29fa3274 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>
2026-07-14 18:24:33 +03:30

135 lines
5.8 KiB
PHP

<?php
namespace App\Billing\Service;
use App\Billing\Entity\Invoice;
use App\Billing\Entity\InvoiceItem;
use App\Billing\Repository\InvoiceRepository;
use App\Billing\ValueObject\Money;
use App\ClinicService\Service\TariffService;
use App\Insurance\Service\TenantInsuranceService;
use App\Patient\Entity\PatientSession;
class InvoiceService
{
public function __construct(
private readonly InvoiceRepository $invoiceRepo,
private readonly TariffService $tariffService,
private readonly TenantInsuranceService $tenantInsuranceService,
private readonly BillingCalculator $calculator,
) {}
/**
* ساخت Invoice از یک Encounter (PatientSession).
* تعرفه‌ی هر خدمت از Tariff سال جاری (با fallback)، پوشش از قرارداد بیمه‌ی tenant.
* ویزیت به‌عنوان یک آیتم جداگانه با همان قانون پوشش لحاظ می‌شود.
*/
public function createFromSession(PatientSession $session, string $entityType, int $entityId): Invoice
{
$existing = $session->getId() !== null ? $this->invoiceRepo->findBySession($session->getId()) : null;
if ($existing !== null) {
return $existing;
}
$invoice = new Invoice($entityType, $entityId);
$invoice->setPatientSessionId($session->getId())
->setPatientRecordId($session->getRecord()->getId())
->setBaseInsuranceId($session->getInsuranceBaseId())
->setSupplementaryInsuranceId($session->getInsuranceSupplementaryId());
$baseId = $session->getInsuranceBaseId();
$suppId = $session->getInsuranceSupplementaryId();
// ویزیت
$visitPrice = $session->getVisitPriceRials();
if ($visitPrice > 0) {
$baseRule = $this->tenantInsuranceService->coverageRule($entityType, $entityId, $baseId);
$suppRule = $this->tenantInsuranceService->coverageRule($entityType, $entityId, $suppId);
$breakdown = $this->calculator->calculateItem(new Money($visitPrice), $baseRule, $suppRule);
$invoice->addItem(new InvoiceItem($invoice, 'ویزیت', $visitPrice, 1, $breakdown, null));
}
// خدمات
foreach ($session->getServices() as $sessionService) {
$item = $sessionService->getServiceItem();
$qty = max(1, $sessionService->getQuantity());
$unitPrice = $this->tariffService->resolvePrice($item);
$total = new Money($unitPrice * $qty);
$baseRule = $this->tenantInsuranceService->coverageRuleForService($entityType, $entityId, $baseId, $item->getId());
$suppRule = $this->tenantInsuranceService->coverageRuleForService($entityType, $entityId, $suppId, $item->getId());
$breakdown = $this->calculator->calculateItem($total, $baseRule, $suppRule);
$invoice->addItem(new InvoiceItem($invoice, $item->getName(), $unitPrice, $qty, $breakdown, $item->getId()));
}
$invoice->recalculateTotals();
$this->invoiceRepo->save($invoice);
return $invoice;
}
public function finalize(Invoice $invoice): void
{
$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),
];
}
}