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(); } /** * Latest version of every insurance the tenant has a contract with, active or not. * The management UI shows one row per insurance with a فعال/غیرفعال toggle, so both * states must be returned; older versions are collapsed to the newest. * * @return TenantInsurance[] */ public function findLatestByTenant(string $entityType, int $entityId): array { $rows = $this->createQueryBuilder('t') ->where('t.entityType = :type') ->andWhere('t.entityId = :id') ->setParameter('type', $entityType) ->setParameter('id', $entityId) ->orderBy('t.insuranceId', 'ASC') ->addOrderBy('t.version', 'DESC') ->getQuery() ->getResult(); $latest = []; foreach ($rows as $row) { $latest[$row->getInsuranceId()] ??= $row; } return array_values($latest); } 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(); } } }