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:
hamed
2026-06-23 15:05:24 +03:30
co-authored by Claude Opus 4.8
parent 5b1dfe9b40
commit 89191eee57
54 changed files with 4233 additions and 10 deletions
@@ -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,
];
}
}
+109
View File
@@ -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);
}
}