src/Repository/ProfileRepository.php line 96

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