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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\ServiceSection;
|
||||
use App\ClinicService\Repository\ServiceItemRepository;
|
||||
use App\ClinicService\Repository\ServiceSectionRepository;
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
use App\ClinicService\Service\TariffService;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
@@ -32,6 +34,8 @@ class ClinicServiceController extends BaseController
|
||||
private readonly SubscriptionService $subscriptionService,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly TariffRepository $tariffRepo,
|
||||
private readonly TariffService $tariffService,
|
||||
) {}
|
||||
|
||||
// ── Service Sections ─────────────────────────────────────────────────────
|
||||
@@ -157,6 +161,13 @@ class ClinicServiceController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($data['insurance_covered'])) {
|
||||
$item->setInsuranceCovered((bool) $data['insurance_covered']);
|
||||
}
|
||||
if (array_key_exists('insurance_price_rials', $data)) {
|
||||
$item->setInsurancePriceRials($data['insurance_price_rials'] !== null ? (int) $data['insurance_price_rials'] : null);
|
||||
}
|
||||
|
||||
$this->itemRepo->save($item);
|
||||
|
||||
return $this->success($item->toArray(), 201);
|
||||
@@ -181,6 +192,12 @@ class ClinicServiceController extends BaseController
|
||||
$staff = $data['staff_uuid'] ? $this->staffRepo->findByUuid($data['staff_uuid']) : null;
|
||||
$item->setStaff($staff);
|
||||
}
|
||||
if (isset($data['insurance_covered'])) {
|
||||
$item->setInsuranceCovered((bool) $data['insurance_covered']);
|
||||
}
|
||||
if (array_key_exists('insurance_price_rials', $data)) {
|
||||
$item->setInsurancePriceRials($data['insurance_price_rials'] !== null ? (int) $data['insurance_price_rials'] : null);
|
||||
}
|
||||
|
||||
$this->itemRepo->save($item);
|
||||
|
||||
@@ -206,6 +223,51 @@ class ClinicServiceController extends BaseController
|
||||
return $this->success(['message' => 'سرویس حذف شد']);
|
||||
}
|
||||
|
||||
// ── Tariffs (تعرفهی نسخهدار سالانه) ──────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/service-items/{uuid}/tariffs', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function listTariffs(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
|
||||
$item = $this->itemRepo->findByUuid($uuid);
|
||||
if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
$tariffs = $this->tariffRepo->findByService($item->getId());
|
||||
|
||||
return $this->success([
|
||||
'current_year' => $this->tariffService->currentJalaliYear(),
|
||||
'default_price_rials' => $item->getPriceRials(),
|
||||
'data' => array_map(fn($t) => $t->toArray(), $tariffs),
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/service-items/{uuid}/tariffs/{year}', methods: ['PUT'], requirements: ['year' => '\d+'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function setTariff(string $uuid, int $year, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
|
||||
$item = $this->itemRepo->findByUuid($uuid);
|
||||
if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
if ($year < 1390 || $year > 1500) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'سال نامعتبر است', 422);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$price = (int) ($data['price_rials'] ?? 0);
|
||||
|
||||
$tariff = $this->tariffService->upsert($item->getId(), $year, $price);
|
||||
|
||||
return $this->success(['data' => $tariff->toArray()]);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private function resolveEntity(User $user): array
|
||||
|
||||
@@ -36,6 +36,12 @@ class ServiceItem
|
||||
#[ORM\Column(type: 'boolean')]
|
||||
private bool $active = true;
|
||||
|
||||
#[ORM\Column(name: 'insurance_covered', type: 'boolean')]
|
||||
private bool $insuranceCovered = false;
|
||||
|
||||
#[ORM\Column(name: 'insurance_price_rials', type: 'integer', nullable: true)]
|
||||
private ?int $insurancePriceRials = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
@@ -59,6 +65,8 @@ class ServiceItem
|
||||
public function getName(): string { return $this->name; }
|
||||
public function getPriceRials(): int { return $this->priceRials; }
|
||||
public function isActive(): bool { return $this->active; }
|
||||
public function isInsuranceCovered(): bool { return $this->insuranceCovered; }
|
||||
public function getInsurancePriceRials(): ?int { return $this->insurancePriceRials; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
public function getUpdatedAt(): int { return $this->updatedAt; }
|
||||
|
||||
@@ -66,6 +74,8 @@ class ServiceItem
|
||||
public function setName(string $name): self { $this->name = $name; $this->updatedAt = time(); return $this; }
|
||||
public function setPriceRials(int $price): self { $this->priceRials = $price; $this->updatedAt = time(); return $this; }
|
||||
public function setActive(bool $active): self { $this->active = $active; $this->updatedAt = time(); return $this; }
|
||||
public function setInsuranceCovered(bool $v): self { $this->insuranceCovered = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setInsurancePriceRials(?int $v): self { $this->insurancePriceRials = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
@@ -77,6 +87,8 @@ class ServiceItem
|
||||
'name' => $this->name,
|
||||
'price_rials' => $this->priceRials,
|
||||
'active' => $this->active,
|
||||
'insurance_covered' => $this->insuranceCovered,
|
||||
'insurance_price_rials' => $this->insurancePriceRials,
|
||||
'created_at' => $this->createdAt,
|
||||
'updated_at' => $this->updatedAt,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Entity;
|
||||
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: TariffRepository::class)]
|
||||
#[ORM\Table(name: 'service_tariffs')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_service_tariff_year', columns: ['service_item_id', 'year'])]
|
||||
#[ORM\Index(columns: ['service_item_id', 'is_active'], name: 'idx_tariff_service_active')]
|
||||
class Tariff
|
||||
{
|
||||
#[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: 'service_item_id', type: 'integer')]
|
||||
private int $serviceItemId;
|
||||
|
||||
#[ORM\Column(type: 'smallint')]
|
||||
private int $year;
|
||||
|
||||
#[ORM\Column(name: 'price_rials', type: 'integer')]
|
||||
private int $priceRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'is_active', type: 'boolean')]
|
||||
private bool $isActive = true;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(int $serviceItemId, int $year, int $priceRials = 0)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->serviceItemId = $serviceItemId;
|
||||
$this->year = $year;
|
||||
$this->priceRials = $priceRials;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getServiceItemId(): int { return $this->serviceItemId; }
|
||||
public function getYear(): int { return $this->year; }
|
||||
public function getPriceRials(): int { return $this->priceRials; }
|
||||
public function isActive(): bool { return $this->isActive; }
|
||||
|
||||
public function setPriceRials(int $v): self { $this->priceRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setActive(bool $v): self { $this->isActive = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'service_item_id' => $this->serviceItemId,
|
||||
'year' => $this->year,
|
||||
'price_rials' => $this->priceRials,
|
||||
'is_active' => $this->isActive,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Repository;
|
||||
|
||||
use App\ClinicService\Entity\Tariff;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class TariffRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Tariff::class);
|
||||
}
|
||||
|
||||
public function findForServiceYear(int $serviceItemId, int $year): ?Tariff
|
||||
{
|
||||
return $this->findOneBy([
|
||||
'serviceItemId' => $serviceItemId,
|
||||
'year' => $year,
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Tariff[] */
|
||||
public function findByService(int $serviceItemId): array
|
||||
{
|
||||
return $this->createQueryBuilder('t')
|
||||
->where('t.serviceItemId = :sid')
|
||||
->setParameter('sid', $serviceItemId)
|
||||
->orderBy('t.year', 'DESC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?Tariff
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function save(Tariff $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Service;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\Tariff;
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
|
||||
class TariffService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TariffRepository $tariffRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* تعرفهی یک خدمت برای یک سال شمسی.
|
||||
* اگر تعرفهی آن سال ثبت نشده باشد، به priceRials خود خدمت fallback میشود.
|
||||
*/
|
||||
public function resolvePrice(ServiceItem $service, ?int $year = null): int
|
||||
{
|
||||
$year ??= $this->currentJalaliYear();
|
||||
|
||||
$tariff = $service->getId() !== null
|
||||
? $this->tariffRepo->findForServiceYear($service->getId(), $year)
|
||||
: null;
|
||||
|
||||
return $tariff?->getPriceRials() ?? $service->getPriceRials();
|
||||
}
|
||||
|
||||
public function upsert(int $serviceItemId, int $year, int $priceRials): Tariff
|
||||
{
|
||||
$tariff = $this->tariffRepo->findForServiceYear($serviceItemId, $year);
|
||||
if ($tariff === null) {
|
||||
$tariff = new Tariff($serviceItemId, $year, $priceRials);
|
||||
} else {
|
||||
$tariff->setPriceRials($priceRials)->setActive(true);
|
||||
}
|
||||
$this->tariffRepo->save($tariff);
|
||||
return $tariff;
|
||||
}
|
||||
|
||||
public function currentJalaliYear(): int
|
||||
{
|
||||
$fmt = new \IntlDateFormatter(
|
||||
'en_US@calendar=persian',
|
||||
\IntlDateFormatter::FULL,
|
||||
\IntlDateFormatter::NONE,
|
||||
'Asia/Tehran',
|
||||
\IntlDateFormatter::TRADITIONAL,
|
||||
'yyyy'
|
||||
);
|
||||
return (int) $fmt->format(time());
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,19 @@
|
||||
namespace App\Insurance\Controller;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Insurance\Entity\DoctorInsurance;
|
||||
use App\Insurance\Entity\EntityInsurancePricing;
|
||||
use App\Insurance\Entity\Insurance;
|
||||
use App\Insurance\Enum\InsuranceType;
|
||||
use App\Insurance\Entity\TenantInsurance;
|
||||
use App\Insurance\Repository\DoctorInsuranceRepository;
|
||||
use App\Insurance\Repository\EntityInsurancePricingRepository;
|
||||
use App\Insurance\Repository\InsuranceRepository;
|
||||
use App\Insurance\Repository\TenantInsuranceRepository;
|
||||
use App\Insurance\Repository\TenantServiceCoverageRepository;
|
||||
use App\Insurance\Service\TenantInsuranceService;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use App\Shared\Service\FileValidatorService;
|
||||
@@ -27,10 +34,28 @@ class InsuranceController extends BaseController
|
||||
private readonly InsuranceRepository $insuranceRepo,
|
||||
private readonly DoctorInsuranceRepository $doctorInsuranceRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly EntityInsurancePricingRepository $pricingRepo,
|
||||
private readonly TenantInsuranceRepository $tenantInsuranceRepo,
|
||||
private readonly TenantServiceCoverageRepository $serviceCoverageRepo,
|
||||
private readonly TenantInsuranceService $tenantInsuranceService,
|
||||
private readonly FileValidatorService $fileValidator,
|
||||
private readonly string $projectDir,
|
||||
) {}
|
||||
|
||||
private function resolveEntity(User $user): array
|
||||
{
|
||||
if ($user->hasRole('ROLE_DOCTOR')) {
|
||||
$doctor = $this->doctorRepo->findByUser($user);
|
||||
return $doctor !== null ? [EntityInsurancePricing::TYPE_DOCTOR, $doctor->getId()] : [EntityInsurancePricing::TYPE_DOCTOR, null];
|
||||
}
|
||||
if ($user->hasRole('ROLE_CLINIC')) {
|
||||
$clinic = $this->clinicRepo->findByUser($user);
|
||||
return $clinic !== null ? [EntityInsurancePricing::TYPE_CLINIC, $clinic->getId()] : [EntityInsurancePricing::TYPE_CLINIC, null];
|
||||
}
|
||||
return ['unknown', null];
|
||||
}
|
||||
|
||||
// ── Public list ───────────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/insurances', methods: ['GET'])]
|
||||
@@ -183,6 +208,232 @@ class InsuranceController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
// ── Entity insurance pricing (visit price by insurance) ───────────────────
|
||||
|
||||
#[Route('/api/v1/insurance-pricing', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function getInsurancePricing(#[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$rows = $this->pricingRepo->findByEntity($entityType, $entityId);
|
||||
|
||||
$freeVisitPriceRials = 0;
|
||||
$perInsurance = [];
|
||||
foreach ($rows as $row) {
|
||||
if ($row->isFreeVisit()) {
|
||||
$freeVisitPriceRials = $row->getPatientShareRials();
|
||||
} else {
|
||||
$perInsurance[$row->getInsuranceId()] = $row->getPatientShareRials();
|
||||
}
|
||||
}
|
||||
|
||||
$insurances = array_map(function (Insurance $i) use ($perInsurance) {
|
||||
return [
|
||||
'insurance_id' => $i->getId(),
|
||||
'insurance_name' => $i->getName(),
|
||||
'type' => $i->getType()->value,
|
||||
'patient_share_rials' => $perInsurance[$i->getId()] ?? null,
|
||||
];
|
||||
}, $this->insuranceRepo->findActive(null));
|
||||
|
||||
return $this->success([
|
||||
'entity_type' => $entityType,
|
||||
'entity_id' => $entityId,
|
||||
'free_visit_price_rials' => $freeVisitPriceRials,
|
||||
'insurances' => $insurances,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/insurance-pricing', methods: ['PUT'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function saveInsurancePricing(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) ?? [];
|
||||
|
||||
if (array_key_exists('free_visit_price_rials', $data)) {
|
||||
$this->upsertPricing($entityType, $entityId, null, (int) $data['free_visit_price_rials']);
|
||||
}
|
||||
|
||||
foreach (($data['insurances'] ?? []) as $row) {
|
||||
$insuranceId = isset($row['insurance_id']) ? (int) $row['insurance_id'] : null;
|
||||
if ($insuranceId === null) {
|
||||
continue;
|
||||
}
|
||||
if (!array_key_exists('patient_share_rials', $row) || $row['patient_share_rials'] === null) {
|
||||
$existing = $this->pricingRepo->findOneForInsurance($entityType, $entityId, $insuranceId);
|
||||
if ($existing !== null) {
|
||||
$this->pricingRepo->remove($existing, false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$this->upsertPricing($entityType, $entityId, $insuranceId, (int) $row['patient_share_rials']);
|
||||
}
|
||||
|
||||
$this->pricingRepo->getEntityManager()->flush();
|
||||
|
||||
return $this->getInsurancePricing($user);
|
||||
}
|
||||
|
||||
private function upsertPricing(string $entityType, int $entityId, ?int $insuranceId, int $shareRials): void
|
||||
{
|
||||
$row = $this->pricingRepo->findOneForInsurance($entityType, $entityId, $insuranceId);
|
||||
if ($row === null) {
|
||||
$row = new EntityInsurancePricing($entityType, $entityId, $insuranceId, $shareRials);
|
||||
} else {
|
||||
$row->setPatientShareRials($shareRials);
|
||||
}
|
||||
$this->pricingRepo->save($row, false);
|
||||
}
|
||||
|
||||
// ── TenantInsurance — قراردادهای بیمهی tenant ─────────────────────────────
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function listTenantInsurances(#[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$contracts = $this->tenantInsuranceRepo->findActiveByTenant($entityType, $entityId);
|
||||
|
||||
$byId = [];
|
||||
foreach ($this->insuranceRepo->findActive(null) as $ins) {
|
||||
$byId[$ins->getId()] = ['name' => $ins->getName(), 'type' => $ins->getType()->value];
|
||||
}
|
||||
|
||||
$data = array_map(function (TenantInsurance $c) use ($byId) {
|
||||
$row = $c->toArray();
|
||||
$row['insurance_name'] = $byId[$c->getInsuranceId()]['name'] ?? null;
|
||||
$row['insurance_kind'] = $byId[$c->getInsuranceId()]['type'] ?? null;
|
||||
return $row;
|
||||
}, $contracts);
|
||||
|
||||
return $this->success(['data' => $data]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances', methods: ['POST'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function activateTenantInsurance(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) ?? [];
|
||||
$insuranceId = isset($data['insurance_id']) ? (int) $data['insurance_id'] : 0;
|
||||
if ($insuranceId <= 0) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'insurance_id الزامی است', 422);
|
||||
}
|
||||
|
||||
$contract = $this->tenantInsuranceService->activate(
|
||||
$entityType,
|
||||
$entityId,
|
||||
$insuranceId,
|
||||
(float) ($data['coverage_percent'] ?? 0),
|
||||
(int) ($data['franchise_rials'] ?? 0),
|
||||
isset($data['annual_ceiling_rials']) && $data['annual_ceiling_rials'] !== null
|
||||
? (int) $data['annual_ceiling_rials'] : null,
|
||||
);
|
||||
|
||||
return $this->success(['data' => $contract->toArray()], 201);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances/{uuid}', methods: ['PATCH'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function updateTenantInsurance(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$contract = $this->tenantInsuranceRepo->findByUuid($uuid);
|
||||
if ($contract === null || $contract->getEntityType() !== $entityType || $contract->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'قرارداد یافت نشد', 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
if (array_key_exists('coverage_percent', $data)) {
|
||||
$contract->setCoveragePercent((float) $data['coverage_percent']);
|
||||
}
|
||||
if (array_key_exists('franchise_rials', $data)) {
|
||||
$contract->setFranchiseRials((int) $data['franchise_rials']);
|
||||
}
|
||||
if (array_key_exists('annual_ceiling_rials', $data)) {
|
||||
$contract->setAnnualCeilingRials($data['annual_ceiling_rials'] !== null ? (int) $data['annual_ceiling_rials'] : null);
|
||||
}
|
||||
|
||||
$this->tenantInsuranceRepo->save($contract);
|
||||
|
||||
return $this->success(['data' => $contract->toArray()]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances/{uuid}', methods: ['DELETE'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function deactivateTenantInsurance(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$contract = $this->tenantInsuranceRepo->findByUuid($uuid);
|
||||
if ($contract === null || $contract->getEntityType() !== $entityType || $contract->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'قرارداد یافت نشد', 404);
|
||||
}
|
||||
|
||||
$this->tenantInsuranceService->deactivate($contract);
|
||||
|
||||
return $this->success(['message' => 'قرارداد بیمه غیرفعال شد']);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances/{uuid}/service-coverage', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function listServiceCoverage(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$contract = $this->tenantInsuranceRepo->findByUuid($uuid);
|
||||
if ($contract === null || $contract->getEntityType() !== $entityType || $contract->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'قرارداد یافت نشد', 404);
|
||||
}
|
||||
|
||||
$rows = $this->serviceCoverageRepo->findByContract($contract->getId());
|
||||
|
||||
return $this->success(['data' => array_map(fn($r) => $r->toArray(), $rows)]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/tenant-insurances/{uuid}/service-coverage', methods: ['PUT'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function setServiceCoverage(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$contract = $this->tenantInsuranceRepo->findByUuid($uuid);
|
||||
if ($contract === null || $contract->getEntityType() !== $entityType || $contract->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'قرارداد یافت نشد', 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$serviceItemId = isset($data['service_item_id']) ? (int) $data['service_item_id'] : 0;
|
||||
if ($serviceItemId <= 0) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'service_item_id الزامی است', 422);
|
||||
}
|
||||
|
||||
$this->tenantInsuranceService->setServiceCoverage(
|
||||
$contract,
|
||||
$serviceItemId,
|
||||
(bool) ($data['covered'] ?? true),
|
||||
isset($data['coverage_percent']) && $data['coverage_percent'] !== null ? (float) $data['coverage_percent'] : null,
|
||||
isset($data['franchise_rials']) && $data['franchise_rials'] !== null ? (int) $data['franchise_rials'] : null,
|
||||
isset($data['ceiling_rials']) && $data['ceiling_rials'] !== null ? (int) $data['ceiling_rials'] : null,
|
||||
);
|
||||
|
||||
return $this->success(['message' => 'پوشش خدمت ذخیره شد']);
|
||||
}
|
||||
|
||||
// ── DoctorInsurance CRUD ──────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/insurance/', methods: ['POST'])]
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Entity;
|
||||
|
||||
use App\Insurance\Repository\EntityInsurancePricingRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
#[ORM\Entity(repositoryClass: EntityInsurancePricingRepository::class)]
|
||||
#[ORM\Table(name: 'entity_insurance_pricing')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_entity_insurance', columns: ['entity_type', 'entity_id', 'insurance_id'])]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_entity_pricing_owner')]
|
||||
class EntityInsurancePricing
|
||||
{
|
||||
public const TYPE_DOCTOR = 'doctor';
|
||||
public const TYPE_CLINIC = 'clinic';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[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', nullable: true)]
|
||||
private ?int $insuranceId = null;
|
||||
|
||||
#[ORM\Column(name: 'patient_share_rials', type: 'integer')]
|
||||
private int $patientShareRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(string $entityType, int $entityId, ?int $insuranceId, int $patientShareRials = 0)
|
||||
{
|
||||
$this->entityType = $entityType;
|
||||
$this->entityId = $entityId;
|
||||
$this->insuranceId = $insuranceId;
|
||||
$this->patientShareRials = $patientShareRials;
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getEntityType(): string { return $this->entityType; }
|
||||
public function getEntityId(): int { return $this->entityId; }
|
||||
public function getInsuranceId(): ?int { return $this->insuranceId; }
|
||||
public function getPatientShareRials(): int { return $this->patientShareRials; }
|
||||
|
||||
public function isFreeVisit(): bool { return $this->insuranceId === null; }
|
||||
|
||||
public function setPatientShareRials(int $v): self { $this->patientShareRials = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'entity_type' => $this->entityType,
|
||||
'entity_id' => $this->entityId,
|
||||
'insurance_id' => $this->insuranceId,
|
||||
'patient_share_rials' => $this->patientShareRials,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Entity;
|
||||
|
||||
use App\Insurance\Repository\TenantInsuranceRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: TenantInsuranceRepository::class)]
|
||||
#[ORM\Table(name: 'tenant_insurances')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_tenant_insurance_version', columns: ['entity_type', 'entity_id', 'insurance_id', 'version'])]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id', 'is_active'], name: 'idx_tenant_insurance_active')]
|
||||
class TenantInsurance
|
||||
{
|
||||
public const TYPE_DOCTOR = 'doctor';
|
||||
public const TYPE_CLINIC = 'clinic';
|
||||
|
||||
#[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(type: 'integer')]
|
||||
private int $version = 1;
|
||||
|
||||
#[ORM\Column(name: 'is_active', type: 'boolean')]
|
||||
private bool $isActive = true;
|
||||
|
||||
#[ORM\Column(name: 'coverage_percent', type: 'decimal', precision: 5, scale: 2)]
|
||||
private string $coveragePercent = '0.00';
|
||||
|
||||
#[ORM\Column(name: 'franchise_rials', type: 'integer')]
|
||||
private int $franchiseRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'annual_ceiling_rials', type: 'integer', nullable: true)]
|
||||
private ?int $annualCeilingRials = null;
|
||||
|
||||
#[ORM\Column(name: 'effective_from', type: 'integer')]
|
||||
private int $effectiveFrom;
|
||||
|
||||
#[ORM\Column(name: 'effective_to', type: 'integer', nullable: true)]
|
||||
private ?int $effectiveTo = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(string $entityType, int $entityId, int $insuranceId, int $version = 1)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->entityType = $entityType;
|
||||
$this->entityId = $entityId;
|
||||
$this->insuranceId = $insuranceId;
|
||||
$this->version = $version;
|
||||
$this->effectiveFrom = time();
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
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 getVersion(): int { return $this->version; }
|
||||
public function isActive(): bool { return $this->isActive; }
|
||||
public function getCoveragePercent(): float { return (float) $this->coveragePercent; }
|
||||
public function getFranchiseRials(): int { return $this->franchiseRials; }
|
||||
public function getAnnualCeilingRials(): ?int { return $this->annualCeilingRials; }
|
||||
public function getEffectiveFrom(): int { return $this->effectiveFrom; }
|
||||
public function getEffectiveTo(): ?int { return $this->effectiveTo; }
|
||||
|
||||
public function setActive(bool $v): self { $this->isActive = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setCoveragePercent(float $v): self { $this->coveragePercent = (string) $v; $this->updatedAt = time(); return $this; }
|
||||
public function setFranchiseRials(int $v): self { $this->franchiseRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setAnnualCeilingRials(?int $v): self { $this->annualCeilingRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setEffectiveTo(?int $v): self { $this->effectiveTo = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'entity_type' => $this->entityType,
|
||||
'entity_id' => $this->entityId,
|
||||
'insurance_id' => $this->insuranceId,
|
||||
'version' => $this->version,
|
||||
'is_active' => $this->isActive,
|
||||
'coverage_percent' => (float) $this->coveragePercent,
|
||||
'franchise_rials' => $this->franchiseRials,
|
||||
'annual_ceiling_rials' => $this->annualCeilingRials,
|
||||
'effective_from' => $this->effectiveFrom,
|
||||
'effective_to' => $this->effectiveTo,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Entity;
|
||||
|
||||
use App\Insurance\Repository\TenantServiceCoverageRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: TenantServiceCoverageRepository::class)]
|
||||
#[ORM\Table(name: 'tenant_service_coverage')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_tenant_service_coverage', columns: ['tenant_insurance_id', 'service_item_id'])]
|
||||
#[ORM\Index(columns: ['service_item_id'], name: 'idx_tsc_service')]
|
||||
class TenantServiceCoverage
|
||||
{
|
||||
#[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: 'tenant_insurance_id', type: 'integer')]
|
||||
private int $tenantInsuranceId;
|
||||
|
||||
#[ORM\Column(name: 'service_item_id', type: 'integer')]
|
||||
private int $serviceItemId;
|
||||
|
||||
#[ORM\Column(type: 'boolean')]
|
||||
private bool $covered = true;
|
||||
|
||||
#[ORM\Column(name: 'coverage_percent', type: 'decimal', precision: 5, scale: 2, nullable: true)]
|
||||
private ?string $coveragePercent = null;
|
||||
|
||||
#[ORM\Column(name: 'franchise_rials', type: 'integer', nullable: true)]
|
||||
private ?int $franchiseRials = null;
|
||||
|
||||
#[ORM\Column(name: 'ceiling_rials', type: 'integer', nullable: true)]
|
||||
private ?int $ceilingRials = null;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(int $tenantInsuranceId, int $serviceItemId)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->tenantInsuranceId = $tenantInsuranceId;
|
||||
$this->serviceItemId = $serviceItemId;
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getTenantInsuranceId(): int { return $this->tenantInsuranceId; }
|
||||
public function getServiceItemId(): int { return $this->serviceItemId; }
|
||||
public function isCovered(): bool { return $this->covered; }
|
||||
public function getCoveragePercent(): ?float { return $this->coveragePercent !== null ? (float) $this->coveragePercent : null; }
|
||||
public function getFranchiseRials(): ?int { return $this->franchiseRials; }
|
||||
public function getCeilingRials(): ?int { return $this->ceilingRials; }
|
||||
|
||||
public function setCovered(bool $v): self { $this->covered = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setCoveragePercent(?float $v): self { $this->coveragePercent = $v !== null ? (string) $v : null; $this->updatedAt = time(); return $this; }
|
||||
public function setFranchiseRials(?int $v): self { $this->franchiseRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setCeilingRials(?int $v): self { $this->ceilingRials = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'tenant_insurance_id' => $this->tenantInsuranceId,
|
||||
'service_item_id' => $this->serviceItemId,
|
||||
'covered' => $this->covered,
|
||||
'coverage_percent' => $this->getCoveragePercent(),
|
||||
'franchise_rials' => $this->franchiseRials,
|
||||
'ceiling_rials' => $this->ceilingRials,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Repository;
|
||||
|
||||
use App\Insurance\Entity\EntityInsurancePricing;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class EntityInsurancePricingRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, EntityInsurancePricing::class);
|
||||
}
|
||||
|
||||
/** @return EntityInsurancePricing[] */
|
||||
public function findByEntity(string $entityType, int $entityId): array
|
||||
{
|
||||
return $this->findBy(['entityType' => $entityType, 'entityId' => $entityId]);
|
||||
}
|
||||
|
||||
public function findOneForInsurance(string $entityType, int $entityId, ?int $insuranceId): ?EntityInsurancePricing
|
||||
{
|
||||
return $this->findOneBy([
|
||||
'entityType' => $entityType,
|
||||
'entityId' => $entityId,
|
||||
'insuranceId' => $insuranceId,
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(EntityInsurancePricing $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
|
||||
public function remove(EntityInsurancePricing $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->remove($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Repository;
|
||||
|
||||
use App\Insurance\Entity\TenantInsurance;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class TenantInsuranceRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, TenantInsurance::class);
|
||||
}
|
||||
|
||||
/** @return TenantInsurance[] */
|
||||
public function findActiveByTenant(string $entityType, int $entityId): array
|
||||
{
|
||||
return $this->createQueryBuilder('t')
|
||||
->where('t.entityType = :type')
|
||||
->andWhere('t.entityId = :id')
|
||||
->andWhere('t.isActive = true')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->orderBy('t.insuranceId', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?TenantInsurance
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function findActiveContract(string $entityType, int $entityId, int $insuranceId): ?TenantInsurance
|
||||
{
|
||||
return $this->createQueryBuilder('t')
|
||||
->where('t.entityType = :type')
|
||||
->andWhere('t.entityId = :id')
|
||||
->andWhere('t.insuranceId = :ins')
|
||||
->andWhere('t.isActive = true')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('ins', $insuranceId)
|
||||
->orderBy('t.version', 'DESC')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
}
|
||||
|
||||
public function latestVersion(string $entityType, int $entityId, int $insuranceId): int
|
||||
{
|
||||
$max = $this->createQueryBuilder('t')
|
||||
->select('MAX(t.version)')
|
||||
->where('t.entityType = :type')
|
||||
->andWhere('t.entityId = :id')
|
||||
->andWhere('t.insuranceId = :ins')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('ins', $insuranceId)
|
||||
->getQuery()
|
||||
->getSingleScalarResult();
|
||||
|
||||
return (int) ($max ?? 0);
|
||||
}
|
||||
|
||||
public function save(TenantInsurance $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Repository;
|
||||
|
||||
use App\Insurance\Entity\TenantServiceCoverage;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class TenantServiceCoverageRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, TenantServiceCoverage::class);
|
||||
}
|
||||
|
||||
public function findOneFor(int $tenantInsuranceId, int $serviceItemId): ?TenantServiceCoverage
|
||||
{
|
||||
return $this->findOneBy([
|
||||
'tenantInsuranceId' => $tenantInsuranceId,
|
||||
'serviceItemId' => $serviceItemId,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return TenantServiceCoverage[] */
|
||||
public function findByContract(int $tenantInsuranceId): array
|
||||
{
|
||||
return $this->findBy(['tenantInsuranceId' => $tenantInsuranceId]);
|
||||
}
|
||||
|
||||
public function save(TenantServiceCoverage $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
|
||||
public function remove(TenantServiceCoverage $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->remove($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\Service;
|
||||
|
||||
use App\Insurance\Entity\TenantInsurance;
|
||||
use App\Insurance\Repository\InsuranceRepository;
|
||||
use App\Insurance\Repository\TenantInsuranceRepository;
|
||||
use App\Insurance\Repository\TenantServiceCoverageRepository;
|
||||
use App\Insurance\ValueObject\CoverageRule;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
class TenantInsuranceService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TenantInsuranceRepository $repo,
|
||||
private readonly InsuranceRepository $insuranceRepo,
|
||||
private readonly TenantServiceCoverageRepository $coverageRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* فعالسازی یا بهروزرسانی قرارداد بیمه برای یک tenant.
|
||||
* اگر قرارداد فعالی موجود باشد، همان ویرایش میشود؛ در غیر این صورت نسخهی جدید ساخته میشود.
|
||||
*/
|
||||
public function activate(
|
||||
string $entityType,
|
||||
int $entityId,
|
||||
int $insuranceId,
|
||||
float $coveragePercent,
|
||||
int $franchiseRials = 0,
|
||||
?int $annualCeilingRials = null,
|
||||
): TenantInsurance {
|
||||
if ($this->insuranceRepo->find($insuranceId) === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'بیمه یافت نشد', 404);
|
||||
}
|
||||
|
||||
$contract = $this->repo->findActiveContract($entityType, $entityId, $insuranceId);
|
||||
if ($contract === null) {
|
||||
$version = $this->repo->latestVersion($entityType, $entityId, $insuranceId) + 1;
|
||||
$contract = new TenantInsurance($entityType, $entityId, $insuranceId, $version);
|
||||
}
|
||||
|
||||
$contract->setCoveragePercent($coveragePercent)
|
||||
->setFranchiseRials($franchiseRials)
|
||||
->setAnnualCeilingRials($annualCeilingRials)
|
||||
->setActive(true);
|
||||
|
||||
$this->repo->save($contract);
|
||||
|
||||
return $contract;
|
||||
}
|
||||
|
||||
public function deactivate(TenantInsurance $contract): void
|
||||
{
|
||||
$contract->setActive(false)->setEffectiveTo(time());
|
||||
$this->repo->save($contract);
|
||||
}
|
||||
|
||||
/**
|
||||
* بررسی فعالبودن یک بیمه برای tenant. در پذیرش/صورتحساب استفاده میشود.
|
||||
*/
|
||||
public function assertActive(string $entityType, int $entityId, int $insuranceId): TenantInsurance
|
||||
{
|
||||
$contract = $this->repo->findActiveContract($entityType, $entityId, $insuranceId);
|
||||
if ($contract === null) {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'این بیمه برای این کلینیک/پزشک فعال نیست', 422);
|
||||
}
|
||||
return $contract;
|
||||
}
|
||||
|
||||
/**
|
||||
* قانون پوشش یک بیمه برای tenant جاری (برای BillingCalculator).
|
||||
* اگر قرارداد فعالی نباشد، notCovered برمیگردد.
|
||||
*/
|
||||
public function coverageRule(string $entityType, int $entityId, ?int $insuranceId): CoverageRule
|
||||
{
|
||||
if ($insuranceId === null) {
|
||||
return CoverageRule::notCovered();
|
||||
}
|
||||
|
||||
$contract = $this->repo->findActiveContract($entityType, $entityId, $insuranceId);
|
||||
if ($contract === null) {
|
||||
return CoverageRule::notCovered();
|
||||
}
|
||||
|
||||
return new CoverageRule(
|
||||
coveragePercent: $contract->getCoveragePercent(),
|
||||
franchiseRials: $contract->getFranchiseRials(),
|
||||
ceilingRials: $contract->getAnnualCeilingRials(),
|
||||
covered: true,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* قانون پوشش یک خدمت خاص تحت بیمهی tenant.
|
||||
* اگر override خدمت موجود باشد اعمال میشود؛ فیلدهای null از قرارداد ارث میبرند.
|
||||
*/
|
||||
public function coverageRuleForService(string $entityType, int $entityId, ?int $insuranceId, int $serviceItemId): CoverageRule
|
||||
{
|
||||
if ($insuranceId === null) {
|
||||
return CoverageRule::notCovered();
|
||||
}
|
||||
|
||||
$contract = $this->repo->findActiveContract($entityType, $entityId, $insuranceId);
|
||||
if ($contract === null) {
|
||||
return CoverageRule::notCovered();
|
||||
}
|
||||
|
||||
$override = $this->coverageRepo->findOneFor($contract->getId(), $serviceItemId);
|
||||
if ($override !== null && !$override->isCovered()) {
|
||||
return CoverageRule::notCovered();
|
||||
}
|
||||
|
||||
return new CoverageRule(
|
||||
coveragePercent: $override?->getCoveragePercent() ?? $contract->getCoveragePercent(),
|
||||
franchiseRials: $override?->getFranchiseRials() ?? $contract->getFranchiseRials(),
|
||||
ceilingRials: $override?->getCeilingRials() ?? $contract->getAnnualCeilingRials(),
|
||||
covered: true,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{covered: bool, percent: float|null, franchise: int|null, ceiling: int|null}|null */
|
||||
public function getServiceCoverage(int $tenantInsuranceId, int $serviceItemId): ?array
|
||||
{
|
||||
$override = $this->coverageRepo->findOneFor($tenantInsuranceId, $serviceItemId);
|
||||
return $override?->toArray();
|
||||
}
|
||||
|
||||
public function setServiceCoverage(
|
||||
TenantInsurance $contract,
|
||||
int $serviceItemId,
|
||||
bool $covered,
|
||||
?float $coveragePercent,
|
||||
?int $franchiseRials,
|
||||
?int $ceilingRials,
|
||||
): void {
|
||||
$override = $this->coverageRepo->findOneFor($contract->getId(), $serviceItemId)
|
||||
?? new \App\Insurance\Entity\TenantServiceCoverage($contract->getId(), $serviceItemId);
|
||||
|
||||
$override->setCovered($covered)
|
||||
->setCoveragePercent($coveragePercent)
|
||||
->setFranchiseRials($franchiseRials)
|
||||
->setCeilingRials($ceilingRials);
|
||||
|
||||
$this->coverageRepo->save($override);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Insurance\ValueObject;
|
||||
|
||||
final readonly class CoverageRule
|
||||
{
|
||||
public function __construct(
|
||||
public float $coveragePercent,
|
||||
public int $franchiseRials,
|
||||
public ?int $ceilingRials,
|
||||
public bool $covered = true,
|
||||
) {}
|
||||
|
||||
public static function notCovered(): self
|
||||
{
|
||||
return new self(0.0, 0, null, false);
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,9 @@ class PatientSession
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getRecord(): PatientRecord { return $this->record; }
|
||||
public function getAppointment(): ?Appointment { return $this->appointment; }
|
||||
public function getInsuranceBaseId(): ?int { return $this->insuranceBaseId; }
|
||||
public function getInsuranceSupplementaryId(): ?int { return $this->insuranceSupplementaryId; }
|
||||
public function getServices(): Collection { return $this->services; }
|
||||
public function getVisitPriceRials(): int { return $this->visitPriceRials; }
|
||||
public function getBaseInsuranceDiscountPercent(): float { return (float) $this->baseInsuranceDiscountPercent; }
|
||||
public function getSupplementaryDiscountPercent(): float { return (float) $this->supplementaryDiscountPercent; }
|
||||
|
||||
Reference in New Issue
Block a user