src/Repository/ProfileRepository.php line 98

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