src/Repository/ProfileRepository.php line 100

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by simpson <simpsonwork@gmail.com>
  4.  * Date: 2019-03-19
  5.  * Time: 22:23
  6.  */
  7. namespace App\Repository;
  8. use App\Entity\Account\Advertiser;
  9. use App\Entity\Location\City;
  10. use App\Entity\Location\MapCoordinate;
  11. use App\Entity\Profile\Genders;
  12. use App\Entity\Profile\Photo;
  13. use App\Entity\Profile\Profile;
  14. use App\Entity\Sales\Profile\AdBoardPlacement;
  15. use App\Entity\Sales\Profile\AdBoardPlacementType;
  16. use App\Entity\Sales\Profile\PlacementHiding;
  17. use App\Entity\Saloon\Saloon;
  18. use App\Entity\User;
  19. use App\Repository\ReadModel\CityReadModel;
  20. use App\Repository\ReadModel\ProfileApartmentPricingReadModel;
  21. use App\Repository\ReadModel\ProfileListingReadModel;
  22. use App\Repository\ReadModel\ProfileMapReadModel;
  23. use App\Repository\ReadModel\ProfilePersonParametersReadModel;
  24. use App\Repository\ReadModel\ProfilePlacementHidingDetailReadModel;
  25. use App\Repository\ReadModel\ProfilePlacementPriceDetailReadModel;
  26. use App\Repository\ReadModel\ProfileTakeOutPricingReadModel;
  27. use App\Repository\ReadModel\ProvidedServiceReadModel;
  28. use App\Repository\ReadModel\StationLineReadModel;
  29. use App\Repository\ReadModel\StationReadModel;
  30. use App\Service\Features;
  31. use App\Specification\Profile\ProfileIdINOrderedByINValues;
  32. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  33. use Doctrine\ORM\AbstractQuery;
  34. use Doctrine\Persistence\ManagerRegistry;
  35. use Doctrine\DBAL\Statement;
  36. use Doctrine\ORM\QueryBuilder;
  37. use Happyr\DoctrineSpecification\Filter\Filter;
  38. use Happyr\DoctrineSpecification\Query\QueryModifier;
  39. use Porpaginas\Doctrine\ORM\ORMQueryResult;
  40. class ProfileRepository extends ServiceEntityRepository
  41. {
  42.     use SpecificationTrait;
  43.     use EntityIteratorTrait;
  44.     private Features $features;
  45.     private DistrictRepository $districts;
  46.     public function __construct(ManagerRegistry $registry, Features $features, DistrictRepository $districts)
  47.     {
  48.         parent::__construct($registry, Profile::class);
  49.         $this->features = $features;
  50.         $this->districts = $districts;
  51.     }
  52.     /**
  53.      * Возвращает итератор по данным, необходимым для генерации файлов sitemap, в виде массивов с
  54.      * следующими ключами:
  55.      *  - id
  56.      *  - uri
  57.      *  - updatedAt
  58.      *  - city_uri
  59.      *
  60.      * @return iterable<array{id: int, uri: string, updatedAt: \DateTimeImmutable, city_uri: string}>
  61.      */
  62.     public function sitemapItemsIterator(): iterable
  63.     {
  64.         $qb = $this->createQueryBuilder('profile')
  65.             ->select('profile.id, profile.uriIdentity AS uri, profile.updatedAt, city.uriIdentity AS city_uri')
  66.             ->join('profile.city', 'city')
  67.             ->andWhere('profile.deletedAt IS NULL');
  68.         $this->addModerationFilterToQb($qb, 'profile');
  69.         return $qb->getQuery()->toIterable([], AbstractQuery::HYDRATE_ARRAY);
  70.     }
  71.     protected function addModerationFilterToQb(QueryBuilder $qb, string $dqlAlias): void
  72.     {
  73.         if ($this->features->hard_moderation()) {
  74.             $qb->leftJoin(sprintf('%s.owner', $dqlAlias), 'owner');
  75.             $qb->andWhere(
  76.                 $qb->expr()->orX(
  77.                     sprintf('%s.moderationStatus = :status_passed', $dqlAlias),
  78.                     $qb->expr()->andX(
  79.                         sprintf('%s.moderationStatus = :status_waiting', $dqlAlias),
  80.                         'owner.trusted = true'
  81.                     )
  82.                 )
  83.             );
  84.             $qb->setParameter('status_passed', Profile::MODERATION_STATUS_APPROVED);
  85.             $qb->setParameter('status_waiting', Profile::MODERATION_STATUS_WAITING);
  86.         } else {
  87.             $qb->andWhere(sprintf('%s.moderationStatus IN (:statuses)', $dqlAlias));
  88.             $qb->setParameter('statuses', [Profile::MODERATION_STATUS_NOT_PASSED, Profile::MODERATION_STATUS_WAITING, Profile::MODERATION_STATUS_APPROVED]);
  89.         }
  90.     }
  91.     public function ofUriIdentityWithinCity(string $uriIdentity, City $city): ?Profile
  92.     {
  93.         return $this->findOneBy([
  94.             'uriIdentity' => $uriIdentity,
  95.             'city' => $city,
  96.         ]);
  97.     }
  98.     /**
  99.      * Метод проверки уникальности анкет по URI не должен использовать никаких фильтров, кроме URI и города,
  100.      * поэтому QueryBuilder не используется
  101.      * @see https://redminez.net/issues/27310
  102.      */
  103.     public function isUniqueUriIdentityExistWithinCity(string $uriIdentity, City $city): bool
  104.     {
  105.         $connection = $this->_em->getConnection();
  106.         $stmt = $connection->executeQuery('SELECT COUNT(id) FROM profiles WHERE uri_identity = ? AND city_id = ?', [$uriIdentity, $city->getId()]);
  107.         $count = $stmt->fetchOne();
  108.         return $count > 0;
  109.     }
  110.     public function countByCity(): array
  111.     {
  112.         $qb = $this->createQueryBuilder('profile')
  113.             ->select('IDENTITY(profile.city), COUNT(profile.id)')
  114.             ->groupBy('profile.city');
  115.         $this->addFemaleGenderFilterToQb($qb, 'profile');
  116.         $this->addModerationFilterToQb($qb, 'profile');
  117.         //$this->excludeHavingPlacementHiding($qb, 'profile');
  118.         $this->havingAdBoardPlacement($qb, 'profile');
  119.         $query = $qb->getQuery()
  120.             ->useResultCache(true)
  121.             ->setResultCacheLifetime(120);
  122.         $rawResult = $query->getScalarResult();
  123.         $indexedResult = [];
  124.         foreach ($rawResult as $row) {
  125.             $indexedResult[$row[1]] = $row[2];
  126.         }
  127.         return $indexedResult;
  128.     }
  129.     protected function addFemaleGenderFilterToQb(QueryBuilder $qb, string $alias): void
  130.     {
  131.         $this->addGenderFilterToQb($qb, $alias, [Genders::FEMALE]);
  132.     }
  133.     protected function addGenderFilterToQb(QueryBuilder $qb, string $alias, array $genders = [Genders::FEMALE]): void
  134.     {
  135.         $qb->andWhere(sprintf('%s.personParameters.gender IN (:genders)', $alias));
  136.         $qb->setParameter('genders', $genders);
  137.     }
  138.     private function havingAdBoardPlacement(QueryBuilder $qb, string $alias): void
  139.     {
  140.         $qb->join(sprintf('%s.adBoardPlacement', $alias), 'adboard_placement');
  141.     }
  142.     public function countByStations(): array
  143.     {
  144.         $qb = $this->createQueryBuilder('profiles')
  145.             ->select('stations.id, COUNT(profiles.id) as cnt')
  146.             ->join('profiles.stations', 'stations')
  147.             //это условие сильно затормжаживает запрос, но оно и не нужно при условии, что чужих(от других городов) станций у анкеты нет
  148.             //->where('profiles.city = stations.city')
  149.             ->groupBy('stations.id');
  150.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  151.         $this->addModerationFilterToQb($qb, 'profiles');
  152.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  153.         $this->havingAdBoardPlacement($qb, 'profiles');
  154.         $query = $qb->getQuery()
  155.             ->useResultCache(true)
  156.             ->setResultCacheLifetime(120);
  157.         $rawResult = $query->getScalarResult();
  158.         $indexedResult = [];
  159.         foreach ($rawResult as $row) {
  160.             $indexedResult[$row['id']] = $row['cnt'];
  161.         }
  162.         return $indexedResult;
  163.     }
  164.     public function countByDistricts(): array
  165.     {
  166.         $qb = $this->createQueryBuilder('profiles')
  167.             ->select('districts.id, COUNT(profiles.id) as cnt')
  168.             ->join('profiles.stations', 'stations')
  169.             ->join('stations.district', 'districts')
  170.             ->groupBy('districts.id');
  171.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  172.         $this->addModerationFilterToQb($qb, 'profiles');
  173.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  174.         $this->havingAdBoardPlacement($qb, 'profiles');
  175.         $query = $qb->getQuery()
  176.             ->useResultCache(true)
  177.             ->setResultCacheLifetime(120);
  178.         $rawResult = $query->getScalarResult();
  179.         $indexedResult = [];
  180.         foreach ($rawResult as $row) {
  181.             $indexedResult[$row['id']] = $row['cnt'];
  182.         }
  183.         return $indexedResult;
  184.     }
  185.     public function countByCounties(): array
  186.     {
  187.         $qb = $this->createQueryBuilder('profiles')
  188.             ->select('counties.id, COUNT(profiles.id) as cnt')
  189.             ->join('profiles.stations', 'stations')
  190.             ->join('stations.district', 'districts')
  191.             ->join('districts.county', 'counties')
  192.             ->groupBy('counties.id');
  193.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  194.         $this->addModerationFilterToQb($qb, 'profiles');
  195.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  196.         $this->havingAdBoardPlacement($qb, 'profiles');
  197.         $query = $qb->getQuery()
  198.             ->useResultCache(true)
  199.             ->setResultCacheLifetime(120);
  200.         $rawResult = $query->getScalarResult();
  201.         $indexedResult = [];
  202.         foreach ($rawResult as $row) {
  203.             $indexedResult[$row['id']] = $row['cnt'];
  204.         }
  205.         return $indexedResult;
  206.     }
  207.     /**
  208.      * @param array|int[] $ids
  209.      * @return Profile[]
  210.      */
  211.     public function findByIds(array $ids): array
  212.     {
  213.         return $this->createQueryBuilder('profile')
  214.             ->andWhere('profile.id IN (:ids)')
  215.             ->setParameter('ids', $ids)
  216.             ->orderBy('FIELD(profile.id,:ids2)')
  217.             ->setParameter('ids2', $ids)
  218.             ->getQuery()
  219.             ->getResult();
  220.     }
  221.     public function findByIdsIterate(array $ids): iterable
  222.     {
  223.         $qb = $this->createQueryBuilder('profile')
  224.             ->andWhere('profile.id IN (:ids)')
  225.             ->setParameter('ids', $ids)
  226.             ->orderBy('FIELD(profile.id,:ids2)')
  227.             ->setParameter('ids2', $ids);
  228.         return $this->iterateQueryBuilder($qb);
  229.     }
  230.     /**
  231.      * Список анкет указанного типа (массажистки или нет), привязанных к аккаунту
  232.      */
  233.     public function ofOwnerAndTypePaged(User $owner, bool $masseurs): ORMQueryResult
  234.     {
  235.         $qb = $this->createQueryBuilder('profile')
  236.             ->andWhere('profile.owner = :owner')
  237.             ->setParameter('owner', $owner)
  238.             ->andWhere('profile.masseur = :is_masseur')
  239.             ->setParameter('is_masseur', $masseurs);
  240.         return new ORMQueryResult($qb);
  241.     }
  242.     /**
  243.      * Список активных анкет, привязанных к аккаунту
  244.      */
  245.     public function activeAndOwnedBy(User $owner): ORMQueryResult
  246.     {
  247.         $qb = $this->createQueryBuilder('profile')
  248.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  249.             ->andWhere('profile.owner = :owner')
  250.             ->setParameter('owner', $owner);
  251.         return new ORMQueryResult($qb);
  252.     }
  253.     /**
  254.      * Список активных или скрытых анкет, привязанных к аккаунту
  255.      *
  256.      * @return Profile[]|ORMQueryResult
  257.      */
  258.     public function activeOrHiddenAndOwnedBy(User $owner): ORMQueryResult
  259.     {
  260.         $qb = $this->createQueryBuilder('profile')
  261.             ->leftJoin('profile.adBoardPlacement', 'profile_adboard_placement')
  262.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  263.             ->andWhere('profile_adboard_placement IS NOT NULL OR placement_hiding IS NOT NULL')
  264.             ->andWhere('profile.owner = :owner')
  265.             ->setParameter('owner', $owner);
  266.         return new ORMQueryResult($qb);
  267.     }
  268.     public function activePaidAdBoardPlacementAndOwnedBy(User $owner): ORMQueryResult
  269.     {
  270.         $qb = $this->createQueryBuilder('profile')
  271.             ->addSelect('profile_adboard_placement', 'placement_price', 'city', 'owner')
  272.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  273.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  274.             ->join('profile.city', 'city')
  275.             ->join('profile.owner', 'owner')
  276.             ->andWhere('profile_adboard_placement.type <> :free_placement_type')
  277.             ->andWhere('profile.owner = :owner')
  278.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  279.             ->setParameter('owner', $owner);
  280.         return new ORMQueryResult($qb);
  281.     }
  282.     public function paidAdBoardPlacementChargeRowsOfOwner(User $owner): array
  283.     {
  284.         $qb = $this->createQueryBuilder('profile')
  285.             ->select([
  286.                 'profile.id AS profile_id',
  287.                 'profile.approved AS approved',
  288.                 'profile.masseur AS is_masseur',
  289.                 'profile.personParameters.gender AS gender',
  290.                 'profile_adboard_placement.type AS placement_type',
  291.                 'profile_adboard_placement.planManaged AS plan_managed',
  292.                 'placement_price.id AS placement_price_id',
  293.                 'placement_price.priceAmount AS price_amount',
  294.                 'placement_price.duration AS duration',
  295.                 'placement_price.currency AS currency',
  296.                 'placement_price.dynamicPriceMatrix AS dynamic_price_matrix',
  297.                 'city.id AS city_id',
  298.                 'city.cityPriceCategory AS city_price_category',
  299.                 'city.timezone AS timezone',
  300.                 'owner.currencyCode AS owner_currency',
  301.             ])
  302.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  303.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  304.             ->join('profile.city', 'city')
  305.             ->join('profile.owner', 'owner')
  306.             ->andWhere('profile_adboard_placement.type <> :free_placement_type')
  307.             ->andWhere('profile.owner = :owner')
  308.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  309.             ->setParameter('owner', $owner);
  310.         return $qb->getQuery()->getArrayResult();
  311.     }
  312.     public function currentChargeableAndOwnedBy(User $owner): ORMQueryResult
  313.     {
  314.         $qb = $this->createQueryBuilder('profile')
  315.             ->addSelect('profile_adboard_placement', 'placement_price', 'placement_hiding', 'city', 'owner')
  316.             ->leftJoin('profile.adBoardPlacement', 'profile_adboard_placement')
  317.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  318.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  319.             ->join('profile.city', 'city')
  320.             ->join('profile.owner', 'owner')
  321.             ->andWhere('(profile_adboard_placement IS NOT NULL AND profile_adboard_placement.type <> :free_placement_type) OR placement_hiding IS NOT NULL')
  322.             ->andWhere('profile.owner = :owner')
  323.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  324.             ->setParameter('owner', $owner);
  325.         return new ORMQueryResult($qb);
  326.     }
  327.     public function countFreeUnapprovedLimited(): int
  328.     {
  329.         $qb = $this->createQueryBuilder('profile')
  330.             ->select('count(profile)')
  331.             ->join('profile.adBoardPlacement', 'placement')
  332.             ->andWhere('placement.type = :placement_type')
  333.             ->setParameter('placement_type', AdBoardPlacementType::FREE)
  334.             ->leftJoin('profile.placementHiding', 'hiding')
  335.             ->andWhere('hiding IS NULL')
  336.             ->andWhere('profile.approved = false');
  337.         return (int)$qb->getQuery()->getSingleScalarResult();
  338.     }
  339.     public function iterateFreeUnapprovedLimited(int $limit): iterable
  340.     {
  341.         $qb = $this->createQueryBuilder('profile')
  342.             ->join('profile.adBoardPlacement', 'placement')
  343.             ->andWhere('placement.type = :placement_type')
  344.             ->setParameter('placement_type', AdBoardPlacementType::FREE)
  345.             ->leftJoin('profile.placementHiding', 'hiding')
  346.             ->andWhere('hiding IS NULL')
  347.             ->andWhere('profile.approved = false')
  348.             ->setMaxResults($limit);
  349.         return $this->iterateQueryBuilder($qb);
  350.     }
  351.     /**
  352.      * Число активных анкет, привязанных к аккаунту
  353.      */
  354.     public function countActiveOfOwner(User $owner, ?bool $isMasseur = false): int
  355.     {
  356.         $qb = $this->createQueryBuilder('profile')
  357.             ->select('COUNT(profile.id)')
  358.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  359.             ->andWhere('profile.owner = :owner')
  360.             ->setParameter('owner', $owner);
  361.         if ($this->features->hard_moderation()) {
  362.             $qb->leftJoin('profile.owner', 'owner');
  363.             $qb->andWhere(
  364.                 $qb->expr()->orX(
  365.                     'profile.moderationStatus = :status_passed',
  366.                     $qb->expr()->andX(
  367.                         'profile.moderationStatus = :status_waiting',
  368.                         'owner.trusted = true'
  369.                     )
  370.                 )
  371.             );
  372.             $qb->setParameter('status_passed', Profile::MODERATION_STATUS_APPROVED);
  373.             $qb->setParameter('status_waiting', Profile::MODERATION_STATUS_WAITING);
  374.         } else {
  375.             $qb->andWhere('profile.moderationStatus IN (:statuses)')
  376.                 ->setParameter('statuses', [Profile::MODERATION_STATUS_NOT_PASSED, Profile::MODERATION_STATUS_WAITING, Profile::MODERATION_STATUS_APPROVED]);
  377.         }
  378.         if (null !== $isMasseur) {
  379.             $qb->andWhere('profile.masseur = :is_masseur')
  380.                 ->setParameter('is_masseur', $isMasseur);
  381.         }
  382.         return (int)$qb->getQuery()->getSingleScalarResult();
  383.     }
  384.     /**
  385.      * Число всех анкет, привязанных к аккаунту
  386.      */
  387.     public function countAllOfOwnerNotDeleted(User $owner, ?bool $isMasseur = false): int
  388.     {
  389.         $qb = $this->createQueryBuilder('profile')
  390.             ->select('COUNT(profile.id)')
  391.             ->andWhere('profile.owner = :owner')
  392.             ->setParameter('owner', $owner)
  393.             //потому что используется в т.ч. на тех страницах, где отключен фильтр вывода "только неудаленных"
  394.             ->andWhere('profile.deletedAt IS NULL');
  395.         if (null !== $isMasseur) {
  396.             $qb->andWhere('profile.masseur = :is_masseur')
  397.                 ->setParameter('is_masseur', $isMasseur);
  398.         }
  399.         return (int)$qb->getQuery()->getSingleScalarResult();
  400.     }
  401.     public function findPreviewByOwner(Advertiser $owner, int $limit): array
  402.     {
  403.         return $this->createQueryBuilder('profile')
  404.             ->addSelect('city')
  405.             ->join('profile.city', 'city')
  406.             ->andWhere('profile.owner = :owner')
  407.             ->andWhere('profile.deletedAt IS NULL')
  408.             ->setParameter('owner', $owner)
  409.             ->orderBy('profile.id', 'DESC')
  410.             ->setMaxResults($limit)
  411.             ->getQuery()
  412.             ->getResult();
  413.     }
  414.     public function getTimezonesListByUser(User $owner): array
  415.     {
  416.         $q = $this->_em->createQuery(sprintf("
  417.                 SELECT c
  418.                 FROM %s c
  419.                 WHERE c.id IN (
  420.                     SELECT DISTINCT(c2.id) 
  421.                     FROM %s p
  422.                     JOIN p.city c2
  423.                     WHERE p.owner = :user
  424.                 )
  425.             ", $this->_em->getClassMetadata(City::class)->name, $this->_em->getClassMetadata(Profile::class)->name))
  426.             ->setParameter('user', $owner);
  427.         return $q->getResult();
  428.     }
  429.     /**
  430.      * Список анкет, привязанных к аккаунту
  431.      *
  432.      * @return Profile[]
  433.      */
  434.     public function ofOwner(User $owner): array
  435.     {
  436.         $qb = $this->createQueryBuilder('profile')
  437.             ->andWhere('profile.owner = :owner')
  438.             ->setParameter('owner', $owner);
  439.         return $qb->getQuery()->getResult();
  440.     }
  441.     public function ofOwnerPaged(User $owner, array $genders = [Genders::FEMALE]): ORMQueryResult
  442.     {
  443.         $qb = $this->createQueryBuilder('profile')
  444.             ->andWhere('profile.owner = :owner')
  445.             ->setParameter('owner', $owner)
  446.             ->andWhere('profile.personParameters.gender IN (:genders)')
  447.             ->setParameter('genders', $genders);
  448.         return new ORMQueryResult($qb);
  449.     }
  450.     public function searchLinkableToSaloonByOwner(User $owner, ?string $query, int $limit = 20): array
  451.     {
  452.         $qb = $this->createQueryBuilder('profile')
  453.             ->andWhere('profile.owner = :owner')
  454.             ->setParameter('owner', $owner)
  455.             ->orderBy('profile.id', 'DESC')
  456.             ->setMaxResults($limit)
  457.         ;
  458.         if ($query) {
  459.             $qb
  460.                 ->andWhere('LOWER(JSON_UNQUOTE(JSON_EXTRACT(profile.name, :json_path))) LIKE :query')
  461.                 ->setParameter('json_path', '$.ru')
  462.                 ->setParameter('query', '%' . addcslashes(mb_strtolower(trim($query)), '%_') . '%')
  463.             ;
  464.         }
  465.         return $qb->getQuery()->getResult();
  466.     }
  467.     public function findLinkableToSaloonByOwnerAndIds(User $owner, array $ids): array
  468.     {
  469.         $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
  470.         if (empty($ids)) {
  471.             return [];
  472.         }
  473.         return $this->createQueryBuilder('profile')
  474.             ->andWhere('profile.owner = :owner')
  475.             ->andWhere('profile.id IN (:ids)')
  476.             ->setParameter('owner', $owner)
  477.             ->setParameter('ids', $ids)
  478.             ->getQuery()
  479.             ->getResult()
  480.         ;
  481.     }
  482.     public function findPublicProfilesBySaloon(Saloon $saloon, int $limit = 6, int $offset = 0): array
  483.     {
  484.         $profiles = $this->createPublicProfilesBySaloonQueryBuilder($saloon)
  485.             ->addSelect('placement')
  486.             ->orderBy('profile.id', 'DESC')
  487.             ->setMaxResults($limit)
  488.             ->setFirstResult($offset)
  489.             ->getQuery()
  490.             ->getResult()
  491.         ;
  492.         $this->loadPublicProfilePreviewRelations($profiles);
  493.         return $profiles;
  494.     }
  495.     public function countPublicProfilesBySaloon(Saloon $saloon): int
  496.     {
  497.         return (int)$this->createPublicProfilesBySaloonQueryBuilder($saloon)
  498.             ->select('COUNT(DISTINCT profile.id)')
  499.             ->getQuery()
  500.             ->getSingleScalarResult()
  501.         ;
  502.     }
  503.     public function findPublicProfilesBySaloonCircular(Saloon $saloon, int $limit, int $offset, int $total): array
  504.     {
  505.         if ($total <= 0 || $limit <= 0) {
  506.             return [];
  507.         }
  508.         $offset %= $total;
  509.         $firstChunkLimit = min($limit, $total - $offset);
  510.         $profiles = $this->findPublicProfilesBySaloon($saloon, $firstChunkLimit, $offset);
  511.         if (count($profiles) < $limit && $offset > 0) {
  512.             $profiles = array_merge(
  513.                 $profiles,
  514.                 $this->findPublicProfilesBySaloon($saloon, $limit - count($profiles), 0)
  515.             );
  516.         }
  517.         return $profiles;
  518.     }
  519.     public function findPublicProfilesBySaloonRotatedByPlacementStatus(Saloon $saloon, int $limit, int $offset, int $rotationSeed): array
  520.     {
  521.         if ($limit <= 0) {
  522.             return [];
  523.         }
  524.         $profiles = $this->createPublicProfilesBySaloonQueryBuilder($saloon)
  525.             ->addSelect('placement')
  526.             ->orderBy('placement.type', 'DESC')
  527.             ->addOrderBy('placement.placedAt', 'DESC')
  528.             ->addOrderBy('profile.id', 'DESC')
  529.             ->getQuery()
  530.             ->getResult()
  531.         ;
  532.         $profiles = array_slice($this->rotateProfilesWithinPlacementTypes($profiles, $rotationSeed), $offset, $limit);
  533.         $this->loadPublicProfilePreviewRelations($profiles);
  534.         return $profiles;
  535.     }
  536.     private function rotateProfilesWithinPlacementTypes(array $profiles, int $rotationSeed): array
  537.     {
  538.         $profilesByPlacementType = [];
  539.         foreach ($profiles as $profile) {
  540.             $profilesByPlacementType[$this->getProfilePlacementPriority($profile)][] = $profile;
  541.         }
  542.         krsort($profilesByPlacementType, SORT_NUMERIC);
  543.         $rotatedProfiles = [];
  544.         foreach ($profilesByPlacementType as $profilesGroup) {
  545.             $profilesGroupCount = count($profilesGroup);
  546.             $groupOffset = $profilesGroupCount > 0 ? $rotationSeed % $profilesGroupCount : 0;
  547.             if (0 === $groupOffset) {
  548.                 $rotatedProfiles = array_merge($rotatedProfiles, $profilesGroup);
  549.                 continue;
  550.             }
  551.             $rotatedProfiles = array_merge(
  552.                 $rotatedProfiles,
  553.                 array_slice($profilesGroup, $groupOffset),
  554.                 array_slice($profilesGroup, 0, $groupOffset)
  555.             );
  556.         }
  557.         return $rotatedProfiles;
  558.     }
  559.     private function getProfilePlacementPriority(Profile $profile): int
  560.     {
  561.         $placement = $profile->getAdBoardPlacement();
  562.         return $placement instanceof AdBoardPlacement ? $placement->getType()->getValue() : 0;
  563.     }
  564.     private function createPublicProfilesBySaloonQueryBuilder(Saloon $saloon): QueryBuilder
  565.     {
  566.         return $this->createQueryBuilder('profile')
  567.             ->leftJoin('profile.adBoardPlacement', 'placement')
  568.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  569.             ->andWhere('profile.saloon = :saloon')
  570.             ->andWhere('profile.moderationStatus = :moderation_status')
  571.             ->andWhere('placement_hiding IS NULL')
  572.             ->setParameter('saloon', $saloon)
  573.             ->setParameter('moderation_status', Profile::MODERATION_STATUS_APPROVED)
  574.         ;
  575.     }
  576.     private function loadPublicProfilePreviewRelations(array $profiles): void
  577.     {
  578.         if (empty($profiles)) {
  579.             return;
  580.         }
  581.         $this->createQueryBuilder('profile')
  582.             ->leftJoin('profile.city', 'city')
  583.             ->leftJoin('profile.stations', 'station')
  584.             ->leftJoin('profile.avatar', 'avatar')
  585.             ->leftJoin('profile.photos', 'photo')
  586.             ->addSelect('city')
  587.             ->addSelect('station')
  588.             ->addSelect('avatar')
  589.             ->addSelect('photo')
  590.             ->andWhere('profile IN (:profiles)')
  591.             ->setParameter('profiles', $profiles)
  592.             ->getQuery()
  593.             ->getResult()
  594.         ;
  595.     }
  596.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterIterateAll(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): \Generator
  597.     {
  598.         $query = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur)->getQuery();
  599.         foreach ($query->iterate() as $row) {
  600.             yield $row[0];
  601.         }
  602.     }
  603.     private function queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): QueryBuilder
  604.     {
  605.         $qb = $this->createQueryBuilder('profile')
  606.             ->andWhere('profile.owner = :owner')
  607.             ->setParameter('owner', $owner);
  608.         switch ($placementTypeFilter) {
  609.             case 'paid':
  610.                 $qb->join('profile.adBoardPlacement', 'placement')
  611.                     ->andWhere('placement.type != :placement_type')
  612.                     ->setParameter('placement_type', AdBoardPlacementType::FREE);
  613.                 break;
  614.             case 'free':
  615.                 $qb->join('profile.adBoardPlacement', 'placement')
  616.                     ->andWhere('placement.type = :placement_type')
  617.                     ->setParameter('placement_type', AdBoardPlacementType::FREE);
  618.                 break;
  619.             case 'ultra-vip':
  620.                 $qb->join('profile.adBoardPlacement', 'placement')
  621.                     ->andWhere('placement.type = :placement_type')
  622.                     ->setParameter('placement_type', AdBoardPlacementType::ULTRA_VIP);
  623.                 break;
  624.             case 'vip':
  625.                 $qb->join('profile.adBoardPlacement', 'placement')
  626.                     ->andWhere('placement.type = :placement_type')
  627.                     ->setParameter('placement_type', AdBoardPlacementType::VIP);
  628.                 break;
  629.             case 'standard':
  630.                 $qb->join('profile.adBoardPlacement', 'placement')
  631.                     ->andWhere('placement.type = :placement_type')
  632.                     ->setParameter('placement_type', AdBoardPlacementType::STANDARD);
  633.                 break;
  634.             case 'hidden':
  635.                 $qb->join('profile.placementHiding', 'placement_hiding');
  636.                 break;
  637.             case 'all':
  638.             default:
  639.                 break;
  640.         }
  641.         if ($nameFilter) {
  642.             $nameExpr = $qb->expr()->orX(
  643.                 'LOWER(JSON_UNQUOTE(JSON_EXTRACT(profile.name, :jsonPath))) LIKE :name_filter',
  644.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '-| ', '') LIKE :name_filter"),
  645.                 'LOWER(profile.phoneNumber) LIKE :name_filter',
  646.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '\+7', '8') LIKE :name_filter"),
  647.             );
  648.             $qb->setParameter('jsonPath', '$.ru');
  649.             $qb->setParameter('name_filter', '%' . addcslashes(mb_strtolower(str_replace(['(', ')', ' ', '-'], '', $nameFilter)), '%_') . '%');
  650.             $qb->andWhere($nameExpr);
  651.         }
  652.         if (null !== $isMasseur) {
  653.             $qb->andWhere('profile.masseur = :is_masseur')
  654.                 ->setParameter('is_masseur', $isMasseur);
  655.         }
  656.         return $qb;
  657.     }
  658.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterPaged(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): ORMQueryResult
  659.     {
  660.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  661.         //сортируем анкеты по статусу UltraVip->Vip->Standard->Free->Hidden
  662.         $aliases = $qb->getAllAliases();
  663.         if (false == in_array('placement', $aliases))
  664.             $qb->leftJoin('profile.adBoardPlacement', 'placement');
  665.         if (false == in_array('placement_hiding', $aliases))
  666.             $qb->leftJoin('profile.placementHiding', 'placement_hiding');
  667.         $qb->addSelect('IF(placement_hiding.id IS NULL, 0, 1) as HIDDEN is_hidden');
  668.         $qb->addOrderBy('placement.type', 'DESC');
  669.         $qb->addOrderBy('placement.placedAt', 'DESC');
  670.         $qb->addOrderBy('is_hidden', 'ASC');
  671.         return new ORMQueryResult($qb);
  672.     }
  673.     public function idsOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): array
  674.     {
  675.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  676.         $qb->select('profile.id');
  677.         return $qb->getQuery()->getResult('column_hydrator');
  678.     }
  679.     public function countOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): int
  680.     {
  681.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  682.         $qb->select('count(profile.id)')
  683.             ->setMaxResults(1);
  684.         return (int)$qb->getQuery()->getSingleScalarResult();
  685.     }
  686.     /**
  687.      * @deprecated
  688.      */
  689.     public function hydrateProfileRow(array $row): ProfileListingReadModel
  690.     {
  691.         $profile = new ProfileListingReadModel();
  692.         $profile->id = $row['id'];
  693.         $profile->city = $row['city'];
  694.         $profile->uriIdentity = $row['uriIdentity'];
  695.         $profile->name = $row['name'];
  696.         $profile->description = $row['description'];
  697.         $profile->phoneNumber = $row['phoneNumber'];
  698.         $profile->isMasseur = $row['masseur'];
  699.         $profile->approved = $row['approved'];
  700.         $now = new \DateTimeImmutable('now');
  701.         $hasRunningTopPlacement = false;
  702.         foreach ($row['topPlacements'] as $topPlacement) {
  703.             if ($topPlacement['placedAt'] <= $now && $now <= $topPlacement['expiresAt'])
  704.                 $hasRunningTopPlacement = true;
  705.         }
  706.         $profile->active = null !== $row['adBoardPlacement'] || $hasRunningTopPlacement;
  707.         $profile->hidden = null != $row['placementHiding'];
  708.         $profile->personParameters = new ProfilePersonParametersReadModel();
  709.         $profile->personParameters->age = $row['personParameters.age'];
  710.         $profile->personParameters->height = $row['personParameters.height'];
  711.         $profile->personParameters->weight = $row['personParameters.weight'];
  712.         $profile->personParameters->breastSize = $row['personParameters.breastSize'];
  713.         $profile->personParameters->bodyType = $row['personParameters.bodyType'];
  714.         $profile->personParameters->hairColor = $row['personParameters.hairColor'];
  715.         $profile->personParameters->privateHaircut = $row['personParameters.privateHaircut'];
  716.         $profile->personParameters->nationality = $row['personParameters.nationality'];
  717.         $profile->personParameters->hasTattoo = $row['personParameters.hasTattoo'];
  718.         $profile->personParameters->hasPiercing = $row['personParameters.hasPiercing'];
  719.         $profile->stations = $row['stations'];
  720.         $profile->avatar = $row['avatar'];
  721.         foreach ($row['photos'] as $photo)
  722.             if ($photo['main'])
  723.                 $profile->mainPhoto = $photo;
  724.         $profile->mainPhoto = null;
  725.         $profile->photos = [];
  726.         $profile->selfies = [];
  727.         foreach ($row['photos'] as $photo) {
  728.             if ($photo['main'])
  729.                 $profile->mainPhoto = $photo;
  730.             if ($photo['type'] == Photo::TYPE_PHOTO)
  731.                 $profile->photos[] = $photo;
  732.             if ($photo['type'] == Photo::TYPE_SELFIE)
  733.                 $profile->selfies[] = $photo;
  734.         }
  735.         $profile->videos = $row['videos'];
  736.         $profile->comments = $row['comments'];
  737.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  738.         $profile->apartmentsPricing->oneHourPrice = $row['apartmentsPricing.oneHourPrice'];
  739.         $profile->apartmentsPricing->twoHoursPrice = $row['apartmentsPricing.twoHoursPrice'];
  740.         $profile->apartmentsPricing->nightPrice = $row['apartmentsPricing.nightPrice'];
  741.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  742.         $profile->takeOutPricing->oneHourPrice = $row['takeOutPricing.oneHourPrice'];
  743.         $profile->takeOutPricing->twoHoursPrice = $row['takeOutPricing.twoHoursPrice'];
  744.         $profile->takeOutPricing->nightPrice = $row['takeOutPricing.nightPrice'];
  745.         return $profile;
  746.     }
  747.     public function deletedByPeriod(\DateTimeInterface $start, \DateTimeInterface $end): array
  748.     {
  749.         $qb = $this->createQueryBuilder('profile')
  750.             ->join('profile.city', 'city')
  751.             ->select('profile.uriIdentity _profile')
  752.             ->addSelect('city.uriIdentity _city')
  753.             ->andWhere('profile.deletedAt >= :start')
  754.             ->andWhere('profile.deletedAt <= :end')
  755.             ->setParameter('start', $start)
  756.             ->setParameter('end', $end);
  757.         return $qb->getQuery()->getResult();
  758.     }
  759.     public function listForMapMatchingSpec(Filter|QueryModifier $specification, int $coordinatesRoundPrecision = 3): array
  760.     {
  761.         $this->getEntityManager()->getConnection()->executeQuery("
  762.             SET SESSION group_concat_max_len = 100000;
  763.         ");
  764.         /** @var QueryBuilder $qb */
  765.         $qb = $this->createQueryBuilder($dqlAlias = 'p');
  766.         $qb->select(sprintf('GROUP_CONCAT(p.id), CONCAT(ROUND(MIN(p.mapCoordinate.latitude),5),\',\',ROUND(MIN(p.mapCoordinate.longitude),5)), count(p.id), CONCAT(ROUND(p.mapCoordinate.latitude,%1$s),\',\',ROUND(p.mapCoordinate.longitude,%1$s)) as coords, GROUP_CONCAT(p.masseur)', $coordinatesRoundPrecision));
  767.         $qb->groupBy('coords');
  768.         $specification->modify($qb, $dqlAlias);
  769.         $qb->andWhere($specification->getFilter($qb, $dqlAlias));
  770.         return $qb->getQuery()->getResult();
  771.     }
  772.     public function fetchListingByIds(ProfileIdINOrderedByINValues $specification): array
  773.     {
  774.         $ids = implode(',', $specification->getIds());
  775.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  776.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  777.         $sql = "
  778.             SELECT 
  779.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  780.                     as `name`, 
  781.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  782.                     as `description`,
  783.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  784.                     as `avatar_path`,
  785.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  786.                     as `adboard_placement_type`,
  787.                 (SELECT position FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  788.                     as `adboard_placement_position`,
  789.                 c.id 
  790.                     as `city_id`, 
  791.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  792.                     as `city_name`, 
  793.                 c.uri_identity 
  794.                     as `city_uri_identity`,
  795.                 c.country_code 
  796.                     as `city_country_code`,
  797.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  798.                     as `has_top_placement`,
  799.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  800.                     as `has_placement_hiding`,
  801.                 (SELECT COUNT(*) FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  802.                     as `comments_count`,
  803.                 (SELECT COUNT(*) FROM profile_media_files pmf_photo WHERE p.id = pmf_photo.profile_id AND pmf_photo.type = 'photo') 
  804.                     as `photos_count`,
  805.                 (SELECT COUNT(*) FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  806.                     as `videos_count`,
  807.                 (SELECT COUNT(*) FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  808.                     as `selfies_count`,
  809.                 p.primary_station_id 
  810.             FROM profiles `p`
  811.             JOIN cities `c` ON c.id = p.city_id 
  812.             WHERE p.id IN ($ids)
  813.             ORDER BY FIELD(p.id,$ids)";
  814.         $connection = $this->getEntityManager()->getConnection();
  815.         $result = $connection->executeQuery($sql);
  816.         $profiles = $result->fetchAllAssociative();
  817.         $sql = "SELECT 
  818.                     cs.id 
  819.                         as `id`,
  820.                     JSON_UNQUOTE(JSON_EXTRACT(cs.name, '$.ru')) 
  821.                         as `name`, 
  822.                     cs.uri_identity 
  823.                         as `uriIdentity`, 
  824.                     ps.profile_id
  825.                         as `profile_id`,
  826.                     csl.name
  827.                         as `line_name`,
  828.                     csl.color
  829.                         as `line_color`,
  830.                     cs.county_id, cs.district_id
  831.                 FROM profile_stations ps
  832.                 JOIN city_stations cs ON ps.station_id = cs.id 
  833.                 LEFT JOIN city_subway_station_lines cssl ON cssl.station_id = cs.id
  834.                 LEFT JOIN city_subway_lines csl ON csl.id = cssl.line_id
  835.                 WHERE ps.profile_id IN ($ids)";
  836.         $result = $connection->executeQuery($sql);
  837.         $stations = $result->fetchAllAssociative();
  838.         $districtIds = array_unique(array_column($stations, 'district_id'));
  839.         $districts = $this->districts->ofIds($districtIds);
  840.         $sql = "SELECT 
  841.                     s.id 
  842.                         as `id`,
  843.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  844.                         as `name`, 
  845.                     s.group 
  846.                         as `group`, 
  847.                     s.uri_identity 
  848.                         as `uriIdentity`,
  849.                     pps.profile_id
  850.                         as `profile_id`,
  851.                     pps.service_condition
  852.                         as `condition`,
  853.                     pps.extra_charge
  854.                         as `extra_charge`,
  855.                     pps.comment
  856.                         as `comment`
  857.                 FROM profile_provided_services pps
  858.                 JOIN services s ON pps.service_id = s.id 
  859.                 WHERE pps.profile_id IN ($ids)
  860.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  861.         $result = $connection->executeQuery($sql);
  862.         $providedServices = $result->fetchAllAssociative();
  863.         $result = array_map(function ($profile) use ($stations, $districts, $providedServices): ProfileListingReadModel {
  864.             return $this->hydrateProfileRow2($profile, $stations, $districts, $providedServices);
  865.         }, $profiles);
  866.         return $result;
  867.     }
  868.     public function hydrateProfileRow2(array $row, array $stations, array $districts, array $services): ProfileListingReadModel
  869.     {
  870.         $profile = new ProfileListingReadModel();
  871.         $profile->id = $row['id'];
  872.         $profile->moderationStatus = $row['moderation_status'];
  873.         $profile->city = new CityReadModel();
  874.         $profile->city->id = $row['city_id'];
  875.         $profile->city->name = $row['city_name'];
  876.         $profile->city->uriIdentity = $row['city_uri_identity'];
  877.         $profile->city->countryCode = $row['city_country_code'];
  878.         $profile->uriIdentity = $row['uri_identity'];
  879.         $profile->name = $row['name'];
  880.         $profile->description = $row['description'];
  881.         $profile->phoneNumber = $row['phone_number'];
  882.         $profile->isMasseur = (bool)$row['is_masseur'];
  883.         $profile->approved = (bool)$row['is_approved'];
  884.         $profile->isUltraVip = $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_ULTRA_VIP;
  885.         $profile->isVip = $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_VIP;
  886.         $profile->isStandard = false !== array_search(
  887.                 $row['adboard_placement_type'],
  888.                 [
  889.                     AdBoardPlacement::POSITION_GROUP_STANDARD_APPROVED, AdBoardPlacement::POSITION_GROUP_STANDARD,
  890.                     AdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER_APPROVED, AdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER
  891.                 ]
  892.             );
  893.         $profile->position = $row['adboard_placement_position'];
  894.         $profile->active = null !== $row['adboard_placement_type'] || $row['has_top_placement'];
  895.         $profile->hidden = $row['has_placement_hiding'] == true;
  896.         $profile->personParameters = new ProfilePersonParametersReadModel();
  897.         $profile->personParameters->age = $row['person_age'];
  898.         $profile->personParameters->height = $row['person_height'];
  899.         $profile->personParameters->weight = $row['person_weight'];
  900.         $profile->personParameters->breastSize = $row['person_breast_size'];
  901.         $profile->personParameters->bodyType = $row['person_body_type'];
  902.         $profile->personParameters->hairColor = $row['person_hair_color'];
  903.         $profile->personParameters->privateHaircut = $row['person_private_haircut'];
  904.         $profile->personParameters->nationality = $row['person_nationality'];
  905.         $profile->personParameters->hasTattoo = $row['person_has_tattoo'];
  906.         $profile->personParameters->hasPiercing = $row['person_has_piercing'];
  907.         $profile->stations = [];
  908.         $profile->districts = [];
  909.         $profile->counties = [];
  910.         foreach ($stations as $station) {
  911.             if ($profile->id !== $station['profile_id'])
  912.                 continue;
  913.             $profileStation = $profile->stations[$station['id']] ?? new StationReadModel($station['id'], $station['uriIdentity'], $station['name'], []);
  914.             if (null !== $station['line_name']) {
  915.                 $profileStation->lines[] = new StationLineReadModel($station['line_name'], $station['line_color']);
  916.             }
  917.             $profile->stations[$station['id']] = $profileStation;
  918.             if (array_key_exists($station['district_id'] ?? 0, $districts) && !array_key_exists($station['district_id'], $profile->districts)) {
  919.                 $profile->districts[$station['district_id']] = $districts[$station['district_id']];
  920.             }
  921.         }
  922.         $primaryId = (int)$row['primary_station_id'];
  923.         if (!empty($profile->stations)) {
  924.             uasort($profile->stations, function (StationReadModel $a, StationReadModel $b) use ($primaryId) {
  925.                 $aPrimary = $a->id === $primaryId;
  926.                 $bPrimary = $b->id === $primaryId;
  927.                 if ($aPrimary !== $bPrimary) {
  928.                     return $aPrimary ? -1 : 1;
  929.                 }
  930.                 return strnatcasecmp($a->name, $b->name);
  931.             });
  932.         }
  933.         if ($primaryId) {
  934.             $profile->primaryStation = $profile->stations[$primaryId] ?? null;
  935.         }
  936.         $profile->providedServices = [];
  937.         foreach ($services as $service) {
  938.             if ($profile->id !== $service['profile_id'])
  939.                 continue;
  940.             $providedService = $profile->providedServices[$service['id']] ?? new ProvidedServiceReadModel(
  941.                 $service['id'], $service['name'], $service['group'], $service['uriIdentity'],
  942.                 $service['condition'], $service['extra_charge'], $service['comment']
  943.             );
  944.             $profile->providedServices[$service['id']] = $providedService;
  945.         }
  946.         $profile->selfies = $row['selfies_count'] ?? 0;
  947.         $profile->videos = $row['videos_count'] ?? 0;
  948.         $profile->photos = $row['photos_count'] ?? 0;
  949.         $avatar = [
  950.             'path' => $row['avatar_path'] ?? '',
  951.             'type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO
  952.         ];
  953.         if ($this->features->crop_avatar()) {
  954.             $profile->avatar = $avatar;
  955.         } else {
  956.             $profile->mainPhoto = $avatar;
  957.         }
  958.         $profile->comments = $row['comments_count'] ?? 0;
  959.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  960.         $profile->apartmentsPricing->oneHourPrice = $row['apartments_one_hour_price'];
  961.         $profile->apartmentsPricing->twoHoursPrice = $row['apartments_two_hours_price'];
  962.         $profile->apartmentsPricing->nightPrice = $row['apartments_night_price'];
  963.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  964.         $profile->takeOutPricing->oneHourPrice = $row['take_out_one_hour_price'];
  965.         $profile->takeOutPricing->twoHoursPrice = $row['take_out_two_hours_price'];
  966.         $profile->takeOutPricing->nightPrice = $row['take_out_night_price'];
  967.         $profile->takeOutPricing->locations = $row['take_out_locations'] ? array_map('intval', explode(',', $row['take_out_locations'])) : [];
  968.         $profile->seo = $row['seo'] ? json_decode($row['seo'], true) : null;
  969.         return $profile;
  970.     }
  971.     public function fetchMapProfilesByIds(ProfileIdINOrderedByINValues $specification): array
  972.     {
  973.         $ids = implode(',', $specification->getIds());
  974.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  975.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  976.         $sql = "
  977.             SELECT 
  978.                 p.id, p.uri_identity, p.map_latitude, p.map_longitude, p.phone_number, p.is_masseur, p.is_approved,
  979.                 p.person_age, p.person_breast_size, p.person_height, p.person_weight, pap.type as placement_type, p.primary_station_id,
  980.                 JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  981.                     as `name`,
  982.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  983.                     as `avatar_path`,
  984.                 p.apartments_one_hour_price, p.apartments_two_hours_price, p.apartments_night_price, p.take_out_one_hour_price, p.take_out_two_hours_price, p.take_out_night_price,
  985.                 GROUP_CONCAT(ps.station_id) as `stations`,
  986.                 GROUP_CONCAT(pps.service_id) as `services`,
  987.                 EXISTS(SELECT * FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  988.                     as `has_comments`,
  989.                 EXISTS(SELECT * FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  990.                     as `has_videos`,
  991.                 EXISTS(SELECT * FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  992.                     as `has_selfies`,
  993.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  994.                     as `has_top_placement`
  995.             FROM profiles `p`
  996.             LEFT JOIN profile_stations ps ON ps.profile_id = p.id
  997.             LEFT JOIN profile_provided_services pps ON pps.profile_id = p.id
  998.             LEFT JOIN profile_adboard_placements pap ON pap.profile_id = p.id
  999.             WHERE p.id IN ($ids)
  1000.             GROUP BY p.id
  1001.             "; // AND p.map_latitude IS NOT NULL AND p.map_longitude IS NOT NULL; ORDER BY FIELD(p.id,$ids)
  1002.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1003.         $profiles = $result->fetchAllAssociative();
  1004.         $result = array_map(function ($profile): ProfileMapReadModel {
  1005.             return $this->hydrateMapProfileRow($profile);
  1006.         }, $profiles);
  1007.         return $result;
  1008.     }
  1009.     public function hydrateMapProfileRow(array $row): ProfileMapReadModel
  1010.     {
  1011.         $profile = new ProfileMapReadModel();
  1012.         $profile->id = $row['id'];
  1013.         $profile->uriIdentity = $row['uri_identity'];
  1014.         $profile->name = $row['name'];
  1015.         $profile->phoneNumber = $row['phone_number'];
  1016.         $profile->avatar = ['path' => $row['avatar_path'] ?? '', 'type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO];
  1017.         $profile->mapLatitude = $row['map_latitude'];
  1018.         $profile->mapLongitude = $row['map_longitude'];
  1019.         $profile->age = $row['person_age'];
  1020.         $profile->breastSize = $row['person_breast_size'];
  1021.         $profile->height = $row['person_height'];
  1022.         $profile->weight = $row['person_weight'];
  1023.         $profile->isMasseur = $row['is_masseur'];
  1024.         $profile->isApproved = $row['is_approved'];
  1025.         $profile->hasComments = $row['has_comments'];
  1026.         $profile->hasSelfies = $row['has_selfies'];
  1027.         $profile->hasVideos = $row['has_videos'];
  1028.         $profile->apartmentOneHourPrice = $row['apartments_one_hour_price'];
  1029.         $profile->apartmentTwoHoursPrice = $row['apartments_two_hours_price'];
  1030.         $profile->apartmentNightPrice = $row['apartments_night_price'];
  1031.         $profile->takeOutOneHourPrice = $row['take_out_one_hour_price'];
  1032.         $profile->takeOutTwoHoursPrice = $row['take_out_two_hours_price'];
  1033.         $profile->takeOutNightPrice = $row['take_out_night_price'];
  1034.         $profile->station = $row['primary_station_id'] ?? ($row['stations'] ? explode(',', $row['stations'])[0] : null);
  1035.         $profile->services = $row['services'] ? array_unique(explode(',', $row['services'])) : [];
  1036.         $profile->isPaid = $row['placement_type'] >= AdBoardPlacement::POSITION_GROUP_STANDARD || $row['has_top_placement'] !== null;
  1037. //        $prices = [ $row['apartments_one_hour_price'], $row['apartments_two_hours_price'], $row['apartments_night_price'],
  1038. //            $row['take_out_one_hour_price'], $row['take_out_two_hours_price'], $row['take_out_night_price'] ];
  1039. //        $prices = array_filter($prices, function($item) {
  1040. //            return $item != null;
  1041. //        });
  1042. //        $profile->price = count($prices) ? min($prices) : null;
  1043.         return $profile;
  1044.     }
  1045.     public function fetchAccountProfileListByIds(ProfileIdINOrderedByINValues $specification): array
  1046.     {
  1047.         $ids = implode(',', $specification->getIds());
  1048.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  1049.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  1050.         $sql = "
  1051.             SELECT 
  1052.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  1053.                     as `name`, 
  1054.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  1055.                     as `description`,
  1056.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  1057.                     as `avatar_path`,
  1058.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  1059.                     as `adboard_placement_type`,
  1060.                 c.id 
  1061.                     as `city_id`, 
  1062.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  1063.                     as `city_name`, 
  1064.                 c.uri_identity 
  1065.                     as `city_uri_identity`,
  1066.                 c.country_code 
  1067.                     as `city_country_code`,
  1068.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  1069.                     as `has_top_placement`,
  1070.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  1071.                     as `has_placement_hiding`,
  1072.                 (SELECT COUNT(*) FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  1073.                     as `comments_count`,
  1074.                 (SELECT COUNT(*) FROM profile_media_files pmf_photo WHERE p.id = pmf_photo.profile_id AND pmf_photo.type = 'photo') 
  1075.                     as `photos_count`,
  1076.                 (SELECT COUNT(*) FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  1077.                     as `videos_count`,
  1078.                 (SELECT COUNT(*) FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  1079.                     as `selfies_count`,
  1080.                 p.primary_station_id 
  1081.             FROM profiles `p`
  1082.             JOIN cities `c` ON c.id = p.city_id 
  1083.             WHERE p.id IN ($ids)
  1084.             ORDER BY FIELD(p.id,$ids)";
  1085.         $connection = $this->getEntityManager()->getConnection();
  1086.         $result = $connection->executeQuery($sql);
  1087.         $profiles = $result->fetchAllAssociative();
  1088.         $sql = "SELECT 
  1089.                     JSON_UNQUOTE(JSON_EXTRACT(cs.name, '$.ru')) 
  1090.                         as `name`, 
  1091.                     cs.uri_identity 
  1092.                         as `uriIdentity`, 
  1093.                     ps.profile_id
  1094.                         as `profile_id`,
  1095.                     cs.district_id, cs.county_id
  1096.                 FROM profile_stations ps
  1097.                 JOIN city_stations cs ON ps.station_id = cs.id                 
  1098.                 WHERE ps.profile_id IN ($ids)";
  1099.         $result = $connection->executeQuery($sql);
  1100.         $stations = $result->fetchAllAssociative();
  1101.         $districtIds = array_unique(array_column($stations, 'district_id'));
  1102.         $districts = $this->districts->ofIds($districtIds);
  1103.         $sql = "SELECT 
  1104.                     s.id 
  1105.                         as `id`,
  1106.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  1107.                         as `name`, 
  1108.                     s.group 
  1109.                         as `group`, 
  1110.                     s.uri_identity 
  1111.                         as `uriIdentity`,
  1112.                     pps.profile_id
  1113.                         as `profile_id`,
  1114.                     pps.service_condition
  1115.                         as `condition`,
  1116.                     pps.extra_charge
  1117.                         as `extra_charge`,
  1118.                     pps.comment
  1119.                         as `comment`
  1120.                 FROM profile_provided_services pps
  1121.                 JOIN services s ON pps.service_id = s.id 
  1122.                 WHERE pps.profile_id IN ($ids)
  1123.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  1124.         $result = $connection->executeQuery($sql);
  1125.         $providedServices = $result->fetchAllAssociative();
  1126.         $result = array_map(function ($profile) use ($stations, $districts, $providedServices): ProfileListingReadModel {
  1127.             return $this->hydrateProfileRow2($profile, $stations, $districts, $providedServices);
  1128.         }, $profiles);
  1129.         return $result;
  1130.     }
  1131.     public function getCommentedProfilesPaged(User $owner): ORMQueryResult
  1132.     {
  1133.         $qb = $this->createQueryBuilder('profile')
  1134.             ->join('profile.comments', 'comment')
  1135.             ->andWhere('profile.owner = :owner')
  1136.             ->setParameter('owner', $owner)
  1137.             ->orderBy('comment.createdAt', 'DESC');
  1138.         return new ORMQueryResult($qb);
  1139.     }
  1140.     /**
  1141.      * @return ProfilePlacementPriceDetailReadModel[]
  1142.      */
  1143.     public function fetchOfOwnerPlacedPriceDetails(User $owner): array
  1144.     {
  1145.         $sql = "
  1146.             SELECT 
  1147.                 p.id, p.is_approved, psp.price_amount
  1148.             FROM profiles `p`
  1149.             JOIN profile_adboard_placements pap ON pap.profile_id = p.id AND pap.placement_price_id IS NOT NULL
  1150.             JOIN paid_service_prices psp ON pap.placement_price_id = psp.id
  1151.             WHERE p.user_id = {$owner->getId()}
  1152.         ";
  1153.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1154.         $profiles = $result->fetchAllAssociative();
  1155.         return array_map(function (array $row): ProfilePlacementPriceDetailReadModel {
  1156.             return new ProfilePlacementPriceDetailReadModel(
  1157.                 $row['id'], $row['is_approved'], $row['price_amount'] / 24
  1158.             );
  1159.         }, $profiles);
  1160.     }
  1161.     /**
  1162.      * @return ProfilePlacementHidingDetailReadModel[]
  1163.      */
  1164.     public function fetchOfOwnerHiddenDetails(User $owner): array
  1165.     {
  1166.         $sql = "
  1167.             SELECT 
  1168.                 p.id, p.is_approved
  1169.             FROM profiles `p`
  1170.             JOIN placement_hidings ph ON ph.profile_id = p.id
  1171.             WHERE p.user_id = {$owner->getId()}
  1172.         ";
  1173.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1174.         $profiles = $result->fetchAllAssociative();
  1175.         return array_map(function (array $row): ProfilePlacementHidingDetailReadModel {
  1176.             return new ProfilePlacementHidingDetailReadModel(
  1177.                 $row['id'], $row['is_approved'], true
  1178.             );
  1179.         }, $profiles);
  1180.     }
  1181.     protected function modifyListingQueryBuilder(QueryBuilder $qb, string $alias): void
  1182.     {
  1183.         $qb
  1184.             ->addSelect('city')
  1185.             ->addSelect('station')
  1186.             ->addSelect('photo')
  1187.             ->addSelect('video')
  1188.             ->addSelect('comment')
  1189.             ->addSelect('avatar')
  1190.             ->join(sprintf('%s.city', $alias), 'city');
  1191.         if (!in_array('station', $qb->getAllAliases()))
  1192.             $qb->leftJoin(sprintf('%s.stations', $alias), 'station');
  1193.         if (!in_array('photo', $qb->getAllAliases()))
  1194.             $qb->leftJoin(sprintf('%s.photos', $alias), 'photo');
  1195.         if (!in_array('video', $qb->getAllAliases()))
  1196.             $qb->leftJoin(sprintf('%s.videos', $alias), 'video');
  1197.         if (!in_array('avatar', $qb->getAllAliases()))
  1198.             $qb->leftJoin(sprintf('%s.avatar', $alias), 'avatar');
  1199.         if (!in_array('comment', $qb->getAllAliases()))
  1200.             $qb->leftJoin(sprintf('%s.comments', $alias), 'comment');
  1201.         $this->addFemaleGenderFilterToQb($qb, $alias);
  1202.         //TODO убрать, если все ок
  1203.         //$this->excludeHavingPlacementHiding($qb, $alias);
  1204.         if (!in_array('profile_adboard_placement', $qb->getAllAliases())) {
  1205.             $qb
  1206.                 ->leftJoin(sprintf('%s.adBoardPlacement', $alias), 'profile_adboard_placement');
  1207.         }
  1208.         $qb->addSelect('profile_adboard_placement');
  1209.         if (!in_array('profile_top_placement', $qb->getAllAliases())) {
  1210.             $qb
  1211.                 ->leftJoin(sprintf('%s.topPlacements', $alias), 'profile_top_placement');
  1212.         }
  1213.         $qb->addSelect('profile_top_placement');
  1214.         //if($this->features->free_profiles()) {
  1215.         if (!in_array('placement_hiding', $qb->getAllAliases())) {
  1216.             $qb
  1217.                 ->leftJoin(sprintf('%s.placementHiding', $alias), 'placement_hiding');
  1218.         }
  1219.         $qb->addSelect('placement_hiding');
  1220.         //}
  1221.     }
  1222.     protected function addActiveFilterToQb(QueryBuilder $qb, string $dqlAlias)
  1223.     {
  1224.         if (!in_array('profile_adboard_placement', $qb->getAllAliases())) {
  1225.             $qb
  1226.                 ->join(sprintf('%s.adBoardPlacement', $dqlAlias), 'profile_adboard_placement');
  1227.         }
  1228.     }
  1229.     private function excludeHavingPlacementHiding(QueryBuilder $qb, $alias): void
  1230.     {
  1231.         if ($this->features->free_profiles()) {
  1232. //            if (!in_array('placement_hiding', $qb->getAllAliases())) {
  1233. //                $qb
  1234. //                    ->leftJoin(sprintf('%s.placementHiding', $alias), 'placement_hiding')
  1235. //                    ->andWhere(sprintf('placement_hiding IS NULL'))
  1236. //                ;
  1237. //        }
  1238.             $sub = new QueryBuilder($qb->getEntityManager());
  1239.             $sub->select("exclude_hidden_placement_hiding");
  1240.             $sub->from($qb->getEntityManager()->getClassMetadata(PlacementHiding::class)->name, "exclude_hidden_placement_hiding");
  1241.             $sub->andWhere(sprintf('exclude_hidden_placement_hiding.profile = %s', $alias));
  1242.             $qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
  1243.         }
  1244.     }
  1245. }