- Updated CoverageRule and related entities to include franchise_percent instead of franchise_rials. - Modified Appointment entity to carry supplementary insurance ID alongside base insurance. - Implemented SessionBillingService to ensure finalized invoices for insured patient sessions. - Created InvoiceFinalized event to trigger claims creation upon invoice finalization. - Added BackfillMissingClaimsCommand to generate claims for finalized invoices without existing claims. - Developed tests to validate the new functionality for supplementary insurance handling in appointments and claims.
191 lines
7.2 KiB
PHP
191 lines
7.2 KiB
PHP
<?php
|
|
|
|
namespace App\Billing\Service;
|
|
|
|
use App\Billing\Contract\ClaimSubmitterInterface;
|
|
use App\Billing\Entity\Claim;
|
|
use App\Billing\Entity\ClaimItem;
|
|
use App\Billing\Entity\Invoice;
|
|
use App\Billing\Entity\ClaimStatusLog;
|
|
use App\Billing\Repository\ClaimRepository;
|
|
use App\Billing\Repository\ClaimStatusLogRepository;
|
|
use App\Auth\Entity\User;
|
|
use App\Shared\Constant\ErrorCodes;
|
|
use App\Shared\Exception\AppException;
|
|
|
|
class ClaimService
|
|
{
|
|
public function __construct(
|
|
private readonly ClaimRepository $claimRepo,
|
|
private readonly ClaimSubmitterInterface $submitter,
|
|
private readonly ClaimStatusLogRepository $statusLogRepo,
|
|
) {}
|
|
|
|
/**
|
|
* ساخت مطالبات از یک صورتحساب نهاییشده.
|
|
* یک Claim برای بیمهی پایه و یک Claim برای بیمهی مکمل (در صورت وجود سهم).
|
|
* @return Claim[]
|
|
*/
|
|
public function createFromInvoice(Invoice $invoice): array
|
|
{
|
|
if ($invoice->getStatus() !== Invoice::STATUS_FINALIZED) {
|
|
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'فقط از صورتحساب نهاییشده میتوان مطالبه ساخت', 422);
|
|
}
|
|
|
|
if ($invoice->getId() !== null && $this->claimRepo->existsForInvoice($invoice->getId())) {
|
|
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'برای این صورتحساب قبلاً مطالبه ثبت شده است', 422);
|
|
}
|
|
|
|
$claims = [];
|
|
|
|
$baseId = $invoice->getBaseInsuranceId();
|
|
if ($baseId !== null) {
|
|
$claim = $this->buildClaim($invoice, $baseId, Claim::KIND_BASE);
|
|
if ($claim !== null) {
|
|
$claims[] = $claim;
|
|
}
|
|
}
|
|
|
|
$suppId = $invoice->getSupplementaryInsuranceId();
|
|
if ($suppId !== null) {
|
|
$claim = $this->buildClaim($invoice, $suppId, Claim::KIND_SUPPLEMENTARY);
|
|
if ($claim !== null) {
|
|
$claims[] = $claim;
|
|
}
|
|
}
|
|
|
|
if ($claims === []) {
|
|
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'سهم بیمهای برای این صورتحساب وجود ندارد', 422);
|
|
}
|
|
|
|
foreach ($claims as $claim) {
|
|
$this->claimRepo->save($claim, false);
|
|
}
|
|
$this->claimRepo->getEntityManager()->flush();
|
|
|
|
// بعد از flush تا id مطالبه موجود باشد.
|
|
foreach ($claims as $claim) {
|
|
$this->logTransition($claim, null, $claim->getStatus(), 'ایجاد مطالبه', null);
|
|
}
|
|
$this->claimRepo->getEntityManager()->flush();
|
|
|
|
return $claims;
|
|
}
|
|
|
|
/**
|
|
* مطالبات جاافتادهی یک صورتحساب نهاییشده را میسازد و مطالبات موجود را دست نمیزند.
|
|
* برخلاف createFromInvoice که یک عملِ کاربر است و با خطا جواب میدهد، این متد
|
|
* روی رویدادِ نهاییشدن صدا زده میشود و «کاری برای انجام نبود» حالت عادیاش است.
|
|
*
|
|
* @return Claim[] مطالبات تازهساختهشده
|
|
*/
|
|
public function syncFromInvoice(Invoice $invoice): array
|
|
{
|
|
if ($invoice->getStatus() !== Invoice::STATUS_FINALIZED || $invoice->getId() === null) {
|
|
return [];
|
|
}
|
|
|
|
$existingKinds = $this->claimRepo->kindsForInvoice($invoice->getId());
|
|
|
|
$claims = [];
|
|
foreach ([
|
|
Claim::KIND_BASE => $invoice->getBaseInsuranceId(),
|
|
Claim::KIND_SUPPLEMENTARY => $invoice->getSupplementaryInsuranceId(),
|
|
] as $kind => $insuranceId) {
|
|
if ($insuranceId === null || in_array($kind, $existingKinds, true)) {
|
|
continue;
|
|
}
|
|
|
|
$claim = $this->buildClaim($invoice, $insuranceId, $kind);
|
|
if ($claim !== null) {
|
|
$claims[] = $claim;
|
|
}
|
|
}
|
|
|
|
if ($claims === []) {
|
|
return [];
|
|
}
|
|
|
|
foreach ($claims as $claim) {
|
|
$this->claimRepo->save($claim, false);
|
|
}
|
|
$this->claimRepo->getEntityManager()->flush();
|
|
|
|
foreach ($claims as $claim) {
|
|
$this->logTransition($claim, null, $claim->getStatus(), 'ایجاد مطالبه', null);
|
|
}
|
|
$this->claimRepo->getEntityManager()->flush();
|
|
|
|
return $claims;
|
|
}
|
|
|
|
private function buildClaim(Invoice $invoice, int $insuranceId, string $kind): ?Claim
|
|
{
|
|
$claim = new Claim($invoice->getEntityType(), $invoice->getEntityId(), $insuranceId, $kind);
|
|
|
|
$hasShare = false;
|
|
foreach ($invoice->getItems() as $item) {
|
|
$share = $kind === Claim::KIND_BASE
|
|
? $item->getBaseInsuranceRials()
|
|
: $item->getSupplementaryRials();
|
|
|
|
if ($share > 0) {
|
|
$claim->addItem(new ClaimItem($claim, $item->getId(), $share));
|
|
$hasShare = true;
|
|
}
|
|
}
|
|
|
|
return $hasShare ? $claim : null;
|
|
}
|
|
|
|
public function transition(Claim $claim, string $target, array $opts = [], ?User $actor = null): void
|
|
{
|
|
if (!$claim->canTransitionTo($target)) {
|
|
throw new AppException(
|
|
ErrorCodes::ERR_VALIDATION_001,
|
|
sprintf('انتقال از «%s» به «%s» مجاز نیست', $claim->getStatus(), $target),
|
|
422
|
|
);
|
|
}
|
|
|
|
if ($target === Claim::STATUS_REJECTED && trim((string) ($opts['reason'] ?? '')) === '') {
|
|
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422, 'reason');
|
|
}
|
|
|
|
$from = $claim->getStatus();
|
|
|
|
match ($target) {
|
|
Claim::STATUS_SUBMITTED => $this->doSubmit($claim, $opts['tracking_number'] ?? null),
|
|
Claim::STATUS_APPROVED => $claim->approve($opts['approved_rials'] ?? null),
|
|
Claim::STATUS_REJECTED => $claim->reject($opts['reason'] ?? ''),
|
|
Claim::STATUS_PAID => $claim->pay($opts['paid_rials'] ?? null),
|
|
default => throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'وضعیت نامعتبر', 422),
|
|
};
|
|
|
|
$this->claimRepo->save($claim, false);
|
|
$this->logTransition($claim, $from, $target, $opts['note'] ?? $opts['reason'] ?? null, $actor);
|
|
$this->claimRepo->getEntityManager()->flush();
|
|
}
|
|
|
|
private function logTransition(Claim $claim, ?string $from, string $to, ?string $note, ?User $actor): void
|
|
{
|
|
$log = (new ClaimStatusLog((int) $claim->getId(), $from, $to))
|
|
->setNote($note)
|
|
->setActor($actor?->getId(), $actor?->getRealName() ?? $actor?->getMobileNumber());
|
|
|
|
$this->statusLogRepo->save($log, false);
|
|
}
|
|
|
|
private function doSubmit(Claim $claim, ?string $trackingNumber): void
|
|
{
|
|
$result = $this->submitter->submit($claim);
|
|
if (!$result->success) {
|
|
throw new AppException(ErrorCodes::ERR_VALIDATION_001, $result->errorMessage ?? 'ارسال مطالبه ناموفق بود', 422);
|
|
}
|
|
$claim->submit();
|
|
if ($trackingNumber !== null) {
|
|
$claim->setTrackingNumber((string) $trackingNumber);
|
|
}
|
|
}
|
|
}
|