feat: insurance & medical billing system (6 phases)
Multi-tenant insurance contracts, service coverage, versioned tariffs, invoice calculation, and insurance claims with debt reporting. - TenantInsurance: per-tenant insurance contracts (coverage/franchise/ceiling, versioning, soft-deactivate) + active guard - ServiceItem.insuranceCovered + TenantServiceCoverage per-service overrides - Tariff: versioned yearly tariffs with fallback to ServiceItem price - Billing domain: Money/ShareBreakdown VOs, BillingCalculator (unit-tested), Invoice/InvoiceItem aggregate, InvoiceService.createFromSession - Claim/ClaimItem with state machine (pending->submitted->approved/rejected->paid), ClaimService, insurance-debt report - ClaimSubmitterInterface + ManualClaimSubmitter (future insurance API ready) - Admin UI: insurance-pricing page, claims page, service tariff modal, service insurance toggle; routes + sidebar entries - Architecture doc + billing/insurance/clinic-services API docs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Contract;
|
||||
|
||||
final readonly class ClaimSubmissionResult
|
||||
{
|
||||
public function __construct(
|
||||
public bool $success,
|
||||
public ?string $referenceCode = null,
|
||||
public ?string $errorMessage = null,
|
||||
) {}
|
||||
|
||||
public static function ok(?string $referenceCode = null): self
|
||||
{
|
||||
return new self(true, $referenceCode, null);
|
||||
}
|
||||
|
||||
public static function fail(string $errorMessage): self
|
||||
{
|
||||
return new self(false, null, $errorMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Contract;
|
||||
|
||||
use App\Billing\Entity\Claim;
|
||||
|
||||
/**
|
||||
* انتزاع ارسال مطالبه به بیمه. پیادهسازی فعلی manual است؛
|
||||
* در آینده میتوان پیادهسازی متصل به API شرکتهای بیمهی ایران را بدون تغییر دامنه جایگزین کرد.
|
||||
*/
|
||||
interface ClaimSubmitterInterface
|
||||
{
|
||||
public function submit(Claim $claim): ClaimSubmissionResult;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Controller;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use App\Billing\Repository\InvoiceRepository;
|
||||
use App\Billing\Service\ClaimService;
|
||||
use App\Billing\Service\InvoiceService;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Patient\Repository\PatientSessionRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\CurrentUser;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
#[OA\Tag(name: 'Billing')]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
class BillingController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly InvoiceService $invoiceService,
|
||||
private readonly InvoiceRepository $invoiceRepo,
|
||||
private readonly ClaimService $claimService,
|
||||
private readonly ClaimRepository $claimRepo,
|
||||
private readonly PatientSessionRepository $sessionRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
) {}
|
||||
|
||||
#[Route('/api/v1/billing/invoices', methods: ['POST'])]
|
||||
public function create(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$sessionUuid = trim($data['session_uuid'] ?? '');
|
||||
if ($sessionUuid === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'session_uuid الزامی است', 422);
|
||||
}
|
||||
|
||||
$session = $this->sessionRepo->findByUuid($sessionUuid);
|
||||
if ($session === null || !$this->ownsSession($session, $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'مراجعه یافت نشد', 404);
|
||||
}
|
||||
|
||||
$invoice = $this->invoiceService->createFromSession($session, $entityType, $entityId);
|
||||
|
||||
return $this->success(['data' => $invoice->toArray()], 201);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/invoices/{uuid}', methods: ['GET'])]
|
||||
public function show(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$invoice = $this->invoiceRepo->findByUuid($uuid);
|
||||
if ($invoice === null || $invoice->getEntityType() !== $entityType || $invoice->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'صورتحساب یافت نشد', 404);
|
||||
}
|
||||
|
||||
return $this->success(['data' => $invoice->toArray()]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/invoices/{uuid}/finalize', methods: ['POST'])]
|
||||
public function finalize(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$invoice = $this->invoiceRepo->findByUuid($uuid);
|
||||
if ($invoice === null || $invoice->getEntityType() !== $entityType || $invoice->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'صورتحساب یافت نشد', 404);
|
||||
}
|
||||
|
||||
$this->invoiceService->finalize($invoice);
|
||||
|
||||
return $this->success(['data' => $invoice->toArray()]);
|
||||
}
|
||||
|
||||
// ── Claims (مطالبات بیمه) ──────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/billing/claims', methods: ['POST'])]
|
||||
public function createClaim(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$invoiceUuid = trim($data['invoice_uuid'] ?? '');
|
||||
if ($invoiceUuid === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'invoice_uuid الزامی است', 422);
|
||||
}
|
||||
|
||||
$invoice = $this->invoiceRepo->findByUuid($invoiceUuid);
|
||||
if ($invoice === null || $invoice->getEntityType() !== $entityType || $invoice->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'صورتحساب یافت نشد', 404);
|
||||
}
|
||||
|
||||
$claims = $this->claimService->createFromInvoice($invoice);
|
||||
|
||||
return $this->success(['data' => array_map(fn(Claim $c) => $c->toArray(), $claims)], 201);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/claims', methods: ['GET'])]
|
||||
public function listClaims(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$status = $request->query->get('status') ?: null;
|
||||
$claims = $this->claimRepo->findByTenant($entityType, $entityId, $status);
|
||||
|
||||
return $this->success(['data' => array_map(fn(Claim $c) => $c->toArray(), $claims)]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/claims/{uuid}/{action}', methods: ['POST'], requirements: ['action' => 'submit|approve|reject|pay'])]
|
||||
public function transitionClaim(string $uuid, string $action, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$claim = $this->claimRepo->findByUuid($uuid);
|
||||
if ($claim === null || $claim->getEntityType() !== $entityType || $claim->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'مطالبه یافت نشد', 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$target = match ($action) {
|
||||
'submit' => Claim::STATUS_SUBMITTED,
|
||||
'approve' => Claim::STATUS_APPROVED,
|
||||
'reject' => Claim::STATUS_REJECTED,
|
||||
'pay' => Claim::STATUS_PAID,
|
||||
};
|
||||
|
||||
if ($action === 'reject' && trim($data['reason'] ?? '') === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422);
|
||||
}
|
||||
|
||||
$this->claimService->transition($claim, $target, [
|
||||
'approved_rials' => isset($data['approved_rials']) ? (int) $data['approved_rials'] : null,
|
||||
'paid_rials' => isset($data['paid_rials']) ? (int) $data['paid_rials'] : null,
|
||||
'reason' => trim($data['reason'] ?? ''),
|
||||
]);
|
||||
|
||||
return $this->success(['data' => $claim->toArray()]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/reports/insurance-debt', methods: ['GET'])]
|
||||
public function insuranceDebt(#[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
return $this->success(['data' => $this->claimRepo->debtReport($entityType, $entityId)]);
|
||||
}
|
||||
|
||||
private function ownsSession($session, string $entityType, int $entityId): bool
|
||||
{
|
||||
$record = $session->getRecord();
|
||||
return $record->getEntityType() === $entityType && $record->getEntityId() === $entityId;
|
||||
}
|
||||
|
||||
private function resolveEntity(User $user): array
|
||||
{
|
||||
if ($user->hasRole('ROLE_DOCTOR')) {
|
||||
$doctor = $this->doctorRepo->findByUser($user);
|
||||
return $doctor !== null ? ['doctor', $doctor->getId()] : ['doctor', null];
|
||||
}
|
||||
if ($user->hasRole('ROLE_CLINIC')) {
|
||||
$clinic = $this->clinicRepo->findByUser($user);
|
||||
return $clinic !== null ? ['clinic', $clinic->getId()] : ['clinic', null];
|
||||
}
|
||||
return ['unknown', null];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: ClaimRepository::class)]
|
||||
#[ORM\Table(name: 'claims')]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_claim_tenant')]
|
||||
#[ORM\Index(columns: ['insurance_id', 'status'], name: 'idx_claim_insurance_status')]
|
||||
class Claim
|
||||
{
|
||||
public const STATUS_PENDING = 'pending';
|
||||
public const STATUS_SUBMITTED = 'submitted';
|
||||
public const STATUS_APPROVED = 'approved';
|
||||
public const STATUS_REJECTED = 'rejected';
|
||||
public const STATUS_PAID = 'paid';
|
||||
|
||||
public const KIND_BASE = 'base';
|
||||
public const KIND_SUPPLEMENTARY = 'supplementary';
|
||||
|
||||
private const TRANSITIONS = [
|
||||
self::STATUS_PENDING => [self::STATUS_SUBMITTED],
|
||||
self::STATUS_SUBMITTED => [self::STATUS_APPROVED, self::STATUS_REJECTED],
|
||||
self::STATUS_APPROVED => [self::STATUS_PAID],
|
||||
self::STATUS_REJECTED => [],
|
||||
self::STATUS_PAID => [],
|
||||
];
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
|
||||
private string $entityType;
|
||||
|
||||
#[ORM\Column(name: 'entity_id', type: 'integer')]
|
||||
private int $entityId;
|
||||
|
||||
#[ORM\Column(name: 'insurance_id', type: 'integer')]
|
||||
private int $insuranceId;
|
||||
|
||||
#[ORM\Column(name: 'insurance_kind', type: 'string', length: 15)]
|
||||
private string $insuranceKind;
|
||||
|
||||
#[ORM\Column(name: 'total_claimed_rials', type: 'integer')]
|
||||
private int $totalClaimedRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'total_approved_rials', type: 'integer', nullable: true)]
|
||||
private ?int $totalApprovedRials = null;
|
||||
|
||||
#[ORM\Column(name: 'total_paid_rials', type: 'integer', nullable: true)]
|
||||
private ?int $totalPaidRials = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 15)]
|
||||
private string $status = self::STATUS_PENDING;
|
||||
|
||||
#[ORM\Column(name: 'reject_reason', type: 'text', nullable: true)]
|
||||
private ?string $rejectReason = null;
|
||||
|
||||
#[ORM\Column(name: 'submitted_at', type: 'integer', nullable: true)]
|
||||
private ?int $submittedAt = null;
|
||||
|
||||
#[ORM\Column(name: 'settled_at', type: 'integer', nullable: true)]
|
||||
private ?int $settledAt = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
#[ORM\OneToMany(targetEntity: ClaimItem::class, mappedBy: 'claim', cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $items;
|
||||
|
||||
public function __construct(string $entityType, int $entityId, int $insuranceId, string $insuranceKind)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->entityType = $entityType;
|
||||
$this->entityId = $entityId;
|
||||
$this->insuranceId = $insuranceId;
|
||||
$this->insuranceKind = $insuranceKind;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
$this->items = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getEntityType(): string { return $this->entityType; }
|
||||
public function getEntityId(): int { return $this->entityId; }
|
||||
public function getInsuranceId(): int { return $this->insuranceId; }
|
||||
public function getInsuranceKind(): string { return $this->insuranceKind; }
|
||||
public function getStatus(): string { return $this->status; }
|
||||
public function getTotalClaimedRials(): int { return $this->totalClaimedRials; }
|
||||
public function getTotalApprovedRials(): ?int { return $this->totalApprovedRials; }
|
||||
public function getTotalPaidRials(): ?int { return $this->totalPaidRials; }
|
||||
/** @return Collection<int, ClaimItem> */
|
||||
public function getItems(): Collection { return $this->items; }
|
||||
|
||||
public function addItem(ClaimItem $item): self
|
||||
{
|
||||
$this->items->add($item);
|
||||
$this->totalClaimedRials += $item->getClaimedRials();
|
||||
$this->updatedAt = time();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function canTransitionTo(string $status): bool
|
||||
{
|
||||
return in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
|
||||
}
|
||||
|
||||
public function submit(): void
|
||||
{
|
||||
$this->status = self::STATUS_SUBMITTED;
|
||||
$this->submittedAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function approve(?int $approvedRials = null): void
|
||||
{
|
||||
$this->status = self::STATUS_APPROVED;
|
||||
$this->totalApprovedRials = $approvedRials ?? $this->totalClaimedRials;
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function reject(string $reason): void
|
||||
{
|
||||
$this->status = self::STATUS_REJECTED;
|
||||
$this->rejectReason = $reason;
|
||||
$this->settledAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function pay(?int $paidRials = null): void
|
||||
{
|
||||
$this->status = self::STATUS_PAID;
|
||||
$this->totalPaidRials = $paidRials ?? $this->totalApprovedRials ?? $this->totalClaimedRials;
|
||||
$this->settledAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'entity_type' => $this->entityType,
|
||||
'entity_id' => $this->entityId,
|
||||
'insurance_id' => $this->insuranceId,
|
||||
'insurance_kind' => $this->insuranceKind,
|
||||
'total_claimed_rials' => $this->totalClaimedRials,
|
||||
'total_approved_rials' => $this->totalApprovedRials,
|
||||
'total_paid_rials' => $this->totalPaidRials,
|
||||
'status' => $this->status,
|
||||
'reject_reason' => $this->rejectReason,
|
||||
'submitted_at' => $this->submittedAt,
|
||||
'settled_at' => $this->settledAt,
|
||||
'created_at' => $this->createdAt,
|
||||
'items' => array_map(fn(ClaimItem $i) => $i->toArray(), $this->items->toArray()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\ClaimItemRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
#[ORM\Entity(repositoryClass: ClaimItemRepository::class)]
|
||||
#[ORM\Table(name: 'claim_items')]
|
||||
#[ORM\Index(columns: ['invoice_item_id'], name: 'idx_claim_item_invoice_item')]
|
||||
class ClaimItem
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Claim::class, inversedBy: 'items')]
|
||||
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
|
||||
private Claim $claim;
|
||||
|
||||
#[ORM\Column(name: 'invoice_item_id', type: 'integer')]
|
||||
private int $invoiceItemId;
|
||||
|
||||
#[ORM\Column(name: 'claimed_rials', type: 'integer')]
|
||||
private int $claimedRials;
|
||||
|
||||
#[ORM\Column(name: 'approved_rials', type: 'integer', nullable: true)]
|
||||
private ?int $approvedRials = null;
|
||||
|
||||
public function __construct(Claim $claim, int $invoiceItemId, int $claimedRials)
|
||||
{
|
||||
$this->claim = $claim;
|
||||
$this->invoiceItemId = $invoiceItemId;
|
||||
$this->claimedRials = $claimedRials;
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getInvoiceItemId(): int { return $this->invoiceItemId; }
|
||||
public function getClaimedRials(): int { return $this->claimedRials; }
|
||||
public function getApprovedRials(): ?int { return $this->approvedRials; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'invoice_item_id' => $this->invoiceItemId,
|
||||
'claimed_rials' => $this->claimedRials,
|
||||
'approved_rials' => $this->approvedRials,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\InvoiceRepository;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: InvoiceRepository::class)]
|
||||
#[ORM\Table(name: 'invoices')]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_invoice_tenant')]
|
||||
#[ORM\Index(columns: ['patient_session_id'], name: 'idx_invoice_session')]
|
||||
class Invoice
|
||||
{
|
||||
public const STATUS_DRAFT = 'draft';
|
||||
public const STATUS_FINALIZED = 'finalized';
|
||||
public const STATUS_PAID = 'paid';
|
||||
public const STATUS_VOID = 'void';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
|
||||
private string $entityType;
|
||||
|
||||
#[ORM\Column(name: 'entity_id', type: 'integer')]
|
||||
private int $entityId;
|
||||
|
||||
#[ORM\Column(name: 'patient_session_id', type: 'integer', nullable: true)]
|
||||
private ?int $patientSessionId = null;
|
||||
|
||||
#[ORM\Column(name: 'patient_record_id', type: 'integer', nullable: true)]
|
||||
private ?int $patientRecordId = null;
|
||||
|
||||
#[ORM\Column(name: 'base_insurance_id', type: 'integer', nullable: true)]
|
||||
private ?int $baseInsuranceId = null;
|
||||
|
||||
#[ORM\Column(name: 'supplementary_insurance_id', type: 'integer', nullable: true)]
|
||||
private ?int $supplementaryInsuranceId = null;
|
||||
|
||||
#[ORM\Column(name: 'total_rials', type: 'integer')]
|
||||
private int $totalRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'base_insurance_rials', type: 'integer')]
|
||||
private int $baseInsuranceRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'supplementary_rials', type: 'integer')]
|
||||
private int $supplementaryRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'patient_rials', type: 'integer')]
|
||||
private int $patientRials = 0;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 15)]
|
||||
private string $status = self::STATUS_DRAFT;
|
||||
|
||||
#[ORM\Column(name: 'issued_at', type: 'integer')]
|
||||
private int $issuedAt;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
#[ORM\OneToMany(targetEntity: InvoiceItem::class, mappedBy: 'invoice', cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $items;
|
||||
|
||||
public function __construct(string $entityType, int $entityId)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->entityType = $entityType;
|
||||
$this->entityId = $entityId;
|
||||
$this->issuedAt = time();
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
$this->items = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getEntityType(): string { return $this->entityType; }
|
||||
public function getEntityId(): int { return $this->entityId; }
|
||||
public function getStatus(): string { return $this->status; }
|
||||
public function getBaseInsuranceId(): ?int { return $this->baseInsuranceId; }
|
||||
public function getSupplementaryInsuranceId(): ?int { return $this->supplementaryInsuranceId; }
|
||||
public function getTotalRials(): int { return $this->totalRials; }
|
||||
public function getPatientRials(): int { return $this->patientRials; }
|
||||
/** @return Collection<int, InvoiceItem> */
|
||||
public function getItems(): Collection { return $this->items; }
|
||||
|
||||
public function setPatientSessionId(?int $v): self { $this->patientSessionId = $v; return $this; }
|
||||
public function setPatientRecordId(?int $v): self { $this->patientRecordId = $v; return $this; }
|
||||
public function setBaseInsuranceId(?int $v): self { $this->baseInsuranceId = $v; return $this; }
|
||||
public function setSupplementaryInsuranceId(?int $v): self { $this->supplementaryInsuranceId = $v; return $this; }
|
||||
|
||||
public function addItem(InvoiceItem $item): self
|
||||
{
|
||||
$this->items->add($item);
|
||||
$item->attachTo($this);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function recalculateTotals(): void
|
||||
{
|
||||
$total = $base = $supp = $patient = 0;
|
||||
foreach ($this->items as $item) {
|
||||
$total += $item->getTotalRials();
|
||||
$base += $item->getBaseInsuranceRials();
|
||||
$supp += $item->getSupplementaryRials();
|
||||
$patient += $item->getPatientRials();
|
||||
}
|
||||
$this->totalRials = $total;
|
||||
$this->baseInsuranceRials = $base;
|
||||
$this->supplementaryRials = $supp;
|
||||
$this->patientRials = $patient;
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function finalize(): void
|
||||
{
|
||||
if ($this->status === self::STATUS_DRAFT) {
|
||||
$this->status = self::STATUS_FINALIZED;
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'entity_type' => $this->entityType,
|
||||
'entity_id' => $this->entityId,
|
||||
'patient_session_id' => $this->patientSessionId,
|
||||
'patient_record_id' => $this->patientRecordId,
|
||||
'base_insurance_id' => $this->baseInsuranceId,
|
||||
'supplementary_insurance_id' => $this->supplementaryInsuranceId,
|
||||
'total_rials' => $this->totalRials,
|
||||
'base_insurance_rials' => $this->baseInsuranceRials,
|
||||
'supplementary_rials' => $this->supplementaryRials,
|
||||
'patient_rials' => $this->patientRials,
|
||||
'status' => $this->status,
|
||||
'issued_at' => $this->issuedAt,
|
||||
'items' => array_map(fn(InvoiceItem $i) => $i->toArray(), $this->items->toArray()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\InvoiceItemRepository;
|
||||
use App\Billing\ValueObject\ShareBreakdown;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: InvoiceItemRepository::class)]
|
||||
#[ORM\Table(name: 'invoice_items')]
|
||||
class InvoiceItem
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Invoice::class, inversedBy: 'items')]
|
||||
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
|
||||
private Invoice $invoice;
|
||||
|
||||
#[ORM\Column(name: 'service_item_id', type: 'integer', nullable: true)]
|
||||
private ?int $serviceItemId = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 200)]
|
||||
private string $title;
|
||||
|
||||
#[ORM\Column(name: 'tariff_rials', type: 'integer')]
|
||||
private int $tariffRials;
|
||||
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private int $quantity;
|
||||
|
||||
#[ORM\Column(name: 'total_rials', type: 'integer')]
|
||||
private int $totalRials;
|
||||
|
||||
#[ORM\Column(name: 'base_insurance_rials', type: 'integer')]
|
||||
private int $baseInsuranceRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'supplementary_rials', type: 'integer')]
|
||||
private int $supplementaryRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'patient_rials', type: 'integer')]
|
||||
private int $patientRials = 0;
|
||||
|
||||
public function __construct(
|
||||
Invoice $invoice,
|
||||
string $title,
|
||||
int $tariffRials,
|
||||
int $quantity,
|
||||
ShareBreakdown $breakdown,
|
||||
?int $serviceItemId = null,
|
||||
) {
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->invoice = $invoice;
|
||||
$this->title = $title;
|
||||
$this->tariffRials = $tariffRials;
|
||||
$this->quantity = $quantity;
|
||||
$this->serviceItemId = $serviceItemId;
|
||||
$this->totalRials = $breakdown->totalRials;
|
||||
$this->baseInsuranceRials = $breakdown->baseInsuranceRials;
|
||||
$this->supplementaryRials = $breakdown->supplementaryRials;
|
||||
$this->patientRials = $breakdown->patientRials;
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getServiceItemId(): ?int { return $this->serviceItemId; }
|
||||
public function getTotalRials(): int { return $this->totalRials; }
|
||||
public function getBaseInsuranceRials(): int { return $this->baseInsuranceRials; }
|
||||
public function getSupplementaryRials(): int { return $this->supplementaryRials; }
|
||||
public function getPatientRials(): int { return $this->patientRials; }
|
||||
|
||||
public function attachTo(Invoice $invoice): void
|
||||
{
|
||||
$this->invoice = $invoice;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'service_item_id' => $this->serviceItemId,
|
||||
'title' => $this->title,
|
||||
'tariff_rials' => $this->tariffRials,
|
||||
'quantity' => $this->quantity,
|
||||
'total_rials' => $this->totalRials,
|
||||
'base_insurance_rials' => $this->baseInsuranceRials,
|
||||
'supplementary_rials' => $this->supplementaryRials,
|
||||
'patient_rials' => $this->patientRials,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\ClaimItem;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class ClaimItemRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ClaimItem::class);
|
||||
}
|
||||
|
||||
public function existsForInvoiceItem(int $invoiceItemId, int $insuranceKindClaimInsuranceId): bool
|
||||
{
|
||||
return $this->createQueryBuilder('ci')
|
||||
->select('COUNT(ci.id)')
|
||||
->join('ci.claim', 'c')
|
||||
->where('ci.invoiceItemId = :iid')
|
||||
->andWhere('c.insuranceId = :ins')
|
||||
->setParameter('iid', $invoiceItemId)
|
||||
->setParameter('ins', $insuranceKindClaimInsuranceId)
|
||||
->getQuery()
|
||||
->getSingleScalarResult() > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\Claim;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class ClaimRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Claim::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?Claim
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
/** @return Claim[] */
|
||||
public function findByTenant(string $entityType, int $entityId, ?string $status = null): array
|
||||
{
|
||||
$qb = $this->createQueryBuilder('c')
|
||||
->where('c.entityType = :type')
|
||||
->andWhere('c.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->orderBy('c.id', 'DESC');
|
||||
|
||||
if ($status !== null) {
|
||||
$qb->andWhere('c.status = :status')->setParameter('status', $status);
|
||||
}
|
||||
|
||||
return $qb->getQuery()->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* گزارش بدهی بیمه: جمع claimed/approved/paid بر اساس بیمه برای tenant.
|
||||
* @return array<int, array{insurance_id:int, claimed:int, approved:int, paid:int, debt:int}>
|
||||
*/
|
||||
public function debtReport(string $entityType, int $entityId): array
|
||||
{
|
||||
$rows = $this->createQueryBuilder('c')
|
||||
->select('c.insuranceId AS insurance_id')
|
||||
->addSelect('SUM(c.totalClaimedRials) AS claimed')
|
||||
->addSelect('SUM(COALESCE(c.totalApprovedRials, 0)) AS approved')
|
||||
->addSelect('SUM(COALESCE(c.totalPaidRials, 0)) AS paid')
|
||||
->where('c.entityType = :type')
|
||||
->andWhere('c.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->groupBy('c.insuranceId')
|
||||
->getQuery()
|
||||
->getArrayResult();
|
||||
|
||||
return array_map(function (array $r) {
|
||||
$claimed = (int) $r['claimed'];
|
||||
$paid = (int) $r['paid'];
|
||||
return [
|
||||
'insurance_id' => (int) $r['insurance_id'],
|
||||
'claimed' => $claimed,
|
||||
'approved' => (int) $r['approved'],
|
||||
'paid' => $paid,
|
||||
'debt' => max(0, $claimed - $paid),
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
public function save(Claim $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\InvoiceItem;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class InvoiceItemRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, InvoiceItem::class);
|
||||
}
|
||||
|
||||
public function save(InvoiceItem $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\Invoice;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class InvoiceRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Invoice::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?Invoice
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function findBySession(int $patientSessionId): ?Invoice
|
||||
{
|
||||
return $this->findOneBy(['patientSessionId' => $patientSessionId]);
|
||||
}
|
||||
|
||||
public function save(Invoice $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Service;
|
||||
|
||||
use App\Billing\ValueObject\Money;
|
||||
use App\Billing\ValueObject\ShareBreakdown;
|
||||
use App\Insurance\ValueObject\CoverageRule;
|
||||
|
||||
class BillingCalculator
|
||||
{
|
||||
/**
|
||||
* محاسبهی سهم برای یک آیتم.
|
||||
* ترتیب: کل → پوشش پایه (با سقف) → باقیمانده → پوشش مکمل روی باقیمانده (با سقف) → فرانشیز سهم بیمار.
|
||||
*/
|
||||
public function calculateItem(
|
||||
Money $total,
|
||||
?CoverageRule $base,
|
||||
?CoverageRule $supplementary,
|
||||
): ShareBreakdown {
|
||||
$baseShare = Money::zero();
|
||||
$remaining = $total;
|
||||
|
||||
if ($base !== null && $base->covered) {
|
||||
$baseShare = $total->percent($base->coveragePercent);
|
||||
if ($base->ceilingRials !== null) {
|
||||
$baseShare = $baseShare->min(new Money($base->ceilingRials));
|
||||
}
|
||||
$remaining = $total->sub($baseShare);
|
||||
}
|
||||
|
||||
$suppShare = Money::zero();
|
||||
if ($supplementary !== null && $supplementary->covered) {
|
||||
$suppShare = $remaining->percent($supplementary->coveragePercent);
|
||||
if ($supplementary->ceilingRials !== null) {
|
||||
$suppShare = $suppShare->min(new Money($supplementary->ceilingRials));
|
||||
}
|
||||
$remaining = $remaining->sub($suppShare);
|
||||
}
|
||||
|
||||
// فرانشیز سهم بیمار است؛ از سهم بیمه کم نمیکند ولی سهم بیمار از کل بیشتر نمیشود.
|
||||
$franchise = new Money(
|
||||
($base?->franchiseRials ?? 0) + ($supplementary?->franchiseRials ?? 0)
|
||||
);
|
||||
$patient = $remaining->add($franchise)->min($total);
|
||||
|
||||
return new ShareBreakdown(
|
||||
totalRials: $total->rials,
|
||||
baseInsuranceRials: $baseShare->rials,
|
||||
supplementaryRials: $suppShare->rials,
|
||||
patientRials: $patient->rials,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?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\Repository\ClaimRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
class ClaimService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClaimRepository $claimRepo,
|
||||
private readonly ClaimSubmitterInterface $submitter,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* ساخت مطالبات از یک صورتحساب نهاییشده.
|
||||
* یک Claim برای بیمهی پایه و یک Claim برای بیمهی مکمل (در صورت وجود سهم).
|
||||
* @return Claim[]
|
||||
*/
|
||||
public function createFromInvoice(Invoice $invoice): array
|
||||
{
|
||||
if ($invoice->getStatus() !== Invoice::STATUS_FINALIZED) {
|
||||
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();
|
||||
|
||||
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 = []): void
|
||||
{
|
||||
if (!$claim->canTransitionTo($target)) {
|
||||
throw new AppException(
|
||||
ErrorCodes::ERR_VALIDATION_001,
|
||||
sprintf('انتقال از «%s» به «%s» مجاز نیست', $claim->getStatus(), $target),
|
||||
422
|
||||
);
|
||||
}
|
||||
|
||||
match ($target) {
|
||||
Claim::STATUS_SUBMITTED => $this->doSubmit($claim),
|
||||
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);
|
||||
}
|
||||
|
||||
private function doSubmit(Claim $claim): void
|
||||
{
|
||||
$result = $this->submitter->submit($claim);
|
||||
if (!$result->success) {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, $result->errorMessage ?? 'ارسال مطالبه ناموفق بود', 422);
|
||||
}
|
||||
$claim->submit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?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();
|
||||
$unitPrice = $this->tariffService->resolvePrice($item);
|
||||
$total = new Money($unitPrice);
|
||||
|
||||
$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, 1, $breakdown, $item->getId()));
|
||||
}
|
||||
|
||||
$invoice->recalculateTotals();
|
||||
$this->invoiceRepo->save($invoice);
|
||||
|
||||
return $invoice;
|
||||
}
|
||||
|
||||
public function finalize(Invoice $invoice): void
|
||||
{
|
||||
$invoice->finalize();
|
||||
$this->invoiceRepo->save($invoice);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Service;
|
||||
|
||||
use App\Billing\Contract\ClaimSubmissionResult;
|
||||
use App\Billing\Contract\ClaimSubmitterInterface;
|
||||
use App\Billing\Entity\Claim;
|
||||
|
||||
/**
|
||||
* پیادهسازی پیشفرض: ارسال دستی (آفلاین). مطالبه صرفاً به وضعیت submitted میرود
|
||||
* و ارسال واقعی به بیمه بهصورت دستی توسط کاربر انجام میشود.
|
||||
* در آینده با یک پیادهسازی متصل به API بیمه جایگزین میشود (بدون تغییر در ClaimService).
|
||||
*/
|
||||
final class ManualClaimSubmitter implements ClaimSubmitterInterface
|
||||
{
|
||||
public function submit(Claim $claim): ClaimSubmissionResult
|
||||
{
|
||||
return ClaimSubmissionResult::ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\ValueObject;
|
||||
|
||||
final readonly class Money
|
||||
{
|
||||
public function __construct(public int $rials)
|
||||
{
|
||||
if ($rials < 0) {
|
||||
throw new \InvalidArgumentException('Money cannot be negative');
|
||||
}
|
||||
}
|
||||
|
||||
public static function zero(): self
|
||||
{
|
||||
return new self(0);
|
||||
}
|
||||
|
||||
public function add(Money $o): self
|
||||
{
|
||||
return new self($this->rials + $o->rials);
|
||||
}
|
||||
|
||||
public function sub(Money $o): self
|
||||
{
|
||||
return new self(max(0, $this->rials - $o->rials));
|
||||
}
|
||||
|
||||
public function percent(float $p): self
|
||||
{
|
||||
return new self((int) round($this->rials * $p / 100));
|
||||
}
|
||||
|
||||
public function min(Money $o): self
|
||||
{
|
||||
return new self(min($this->rials, $o->rials));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\ValueObject;
|
||||
|
||||
final readonly class ShareBreakdown
|
||||
{
|
||||
public function __construct(
|
||||
public int $totalRials,
|
||||
public int $baseInsuranceRials,
|
||||
public int $supplementaryRials,
|
||||
public int $patientRials,
|
||||
) {}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'total_rials' => $this->totalRials,
|
||||
'base_insurance_rials' => $this->baseInsuranceRials,
|
||||
'supplementary_rials' => $this->supplementaryRials,
|
||||
'patient_rials' => $this->patientRials,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user