src/Controller/AgencyController.php line 585

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Subscription;
  4. use App\Repository\AgencyCrmIntegrationsRepository;
  5. use App\Repository\AuctionRequestRepository;
  6. use App\Repository\AuctionSourceRepository;
  7. use App\Repository\DebitRepository;
  8. use App\Repository\EventsRepository;
  9. use App\Repository\ManagerRepository;
  10. use App\Repository\SubscriptionRepository;
  11. use App\Service\GeoService;
  12. use DateTime;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Doctrine\ORM\Tools\Pagination\Paginator;
  15. use Knp\Component\Pager\Pagination\PaginationInterface;
  16. use Knp\Component\Pager\PaginatorInterface;
  17. use Psr\Log\LoggerInterface;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\Console\Helper\Helper as ConsoleHelper;
  20. use Symfony\Component\HttpClient\HttpClient;
  21. use Symfony\Component\HttpFoundation\JsonResponse;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  25. use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
  26. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  27. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  28. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. class AgencyController extends AbstractController
  31. {
  32.     private PaginatorInterface $paginator;
  33.     private ManagerRepository $managerRepository;
  34.     private AuctionRequestRepository $auctionRepository;
  35.     private DebitRepository $debitRepository;
  36.     private SubscriptionRepository $subscriptionRepository;
  37.     private GeoService $geoService;
  38.     private EntityManagerInterface $em;
  39.     private AuctionSourceRepository $auctionSource;
  40.     public function __construct(
  41.         EntityManagerInterface   $em,
  42.         AuctionRequestRepository $auctionRequestRepository,
  43.         ManagerRepository        $managerRepository,
  44.         DebitRepository          $debitRepository,
  45.         SubscriptionRepository   $subscriptionRepository,
  46.         GeoService               $geoService,
  47.         AuctionSourceRepository  $auctionSource,
  48.         PaginatorInterface       $paginator,
  49.         LoggerInterface          $logger
  50.     )
  51.     {
  52.         $this->em = $em;
  53.         $this->auctionRepository = $auctionRequestRepository;
  54.         $this->managerRepository = $managerRepository;
  55.         $this->debitRepository = $debitRepository;
  56.         $this->subscriptionRepository = $subscriptionRepository;
  57.         $this->geoService = $geoService;
  58.         $this->paginator = $paginator;
  59.         $this->auctionSource = $auctionSource;
  60.         $this->logger = $logger;
  61.     }
  62.     /**
  63.      * @Route("/auction", name="agency_auction")
  64.      */
  65.     public function agencyRequests(): Response
  66.     {
  67.         return $this->redirect('/birzha');
  68.     }
  69.     /**
  70.      * @Route("/birzha/login", name="agency_birzha_login")
  71.      * @param Request $request
  72.      *
  73.      * @return Response
  74.      * @throws ClientExceptionInterface
  75.      * @throws RedirectionExceptionInterface
  76.      * @throws ServerExceptionInterface
  77.      */
  78.     public function agencyBirzhaLogin(Request $request): Response
  79.     {
  80.         $host = $request->getHost();
  81.         $network = null;
  82.         $loginData = $this->checkLoginData();
  83.         $manager = $loginData['manager'];
  84.         if ($manager) {
  85.             return $this->redirect('/birzha');
  86.         }
  87.         if ($host == 'birzha.tat.ua') {
  88.             $network = 'tat';
  89.         }
  90.         return $this->render('login.html.twig', [
  91.             'manager' => $manager,
  92.             'network' => $network,
  93.         ]);
  94.     }
  95.     /**
  96.      * @Route("/birzha", name="agency_birzha")
  97.      * @param Request $request
  98.      *
  99.      * @return Response
  100.      * @throws ClientExceptionInterface
  101.      * @throws RedirectionExceptionInterface
  102.      * @throws ServerExceptionInterface
  103.      */
  104.     public function agencyBirzha(Request $request): Response
  105.     {
  106.         $host = $request->getHost();
  107.         if (!empty($request->query->all()) && isset($request->query->all()['r'])) {
  108.             setcookie(
  109.                 'referral',
  110.                 $request->query->all()['r'],
  111.                 ['expires' => strtotime("+30 day"), 'domain' => '.otpusk.com']
  112.             );
  113.             setcookie(
  114.                 'referral',
  115.                 $request->query->all()['r'],
  116.                 ['expires' => strtotime("+30 day"), 'domain' => '.tat.ua']
  117.             );
  118.         }
  119.         $network = null;
  120.         //      $data for manager test
  121.         if (($request->getHost() == '127.0.0.1')) {
  122.             $date = $request->get('data');
  123.             if (!$date) {
  124.                 $date = $request->query->all();
  125.             }
  126.             $id = null;
  127.             if (isset($date['manager']) && !isset($loginData['services'])) {
  128.                 $manager = $this->managerRepository->findOneBy(['id' => $date['manager']]);
  129.                 if ($manager) {
  130.                     $id = $manager->getId();
  131.                     $agency = $manager->getAgency();
  132.                     $this->get('session')->set(
  133.                         'loginData',
  134.                         [
  135.                             "id" => $id,
  136.                             "services" => ["agency" => ["id" => $agency->getId(), "name" => $agency->getName()]],
  137.                         ]
  138.                     );
  139.                 }
  140.             }
  141.         }
  142. //        end of test manager
  143.         $loginData = $this->checkLoginData();
  144.         $manager = $loginData['manager'];
  145.         $agency = $loginData['agency'];
  146.         $balance = $this->balance($agency);
  147.         $filterData = isset($_COOKIE['requests-filter']) ? (array)json_decode($_COOKIE['requests-filter']) : null;
  148.         $auctions = $this->auctionRepository->findByNotArchive($filterData);
  149.         $dataCountries = $this->auctionRepository->findByCountry();
  150.         $dataRegions = $this->auctionRepository->findByRegion();
  151.         $pagination = $this->pagination($auctions, $request);
  152.         $description = '';
  153.         if ($host == 'birzha.tat.ua') {
  154.             $network = 'tat';
  155.         }
  156.         $sources = $this->auctionSource->findBy(['active' => 0]);
  157.         return $this->render('agency.html.twig', [
  158.             'requests' => $pagination,
  159.             'manager' => $manager,
  160.             'balance' => $balance,
  161.             'description' => $description,
  162.             'network' => $network,
  163.             'host' => $host,
  164.             'filterData' => $filterData,
  165.             'sources' => $sources,
  166.             'dataCountries' => $dataCountries,
  167.             'dataRegions' => $dataRegions,
  168.         ]);
  169.     }
  170.     /**
  171.      * @Route("", name="land")
  172.      * @param Request $request
  173.      *
  174.      * @return Response
  175.      */
  176.     public function land(Request $request): Response
  177.     {
  178.         $host = $request->getHost();
  179.         $loginData = $this->checkLoginData();
  180.         $agency = $loginData['agency'];
  181.         if (!empty($request->query->all()) && isset($request->query->all()['r'])) {
  182.             setcookie(
  183.                 'referral',
  184.                 $request->query->all()['r'],
  185.                 ['expires' => strtotime("+30 day"), 'domain' => '.otpusk.com']
  186.             );
  187.             setcookie(
  188.                 'referral',
  189.                 $request->query->all()['r'],
  190.                 ['expires' => strtotime("+30 day"), 'domain' => '.tat.ua']
  191.             );
  192.         }
  193.         if ($host == 'birzha.tat.ua') {
  194.             return $this->render('/tat/landing.html.twig');
  195.         }
  196.         return $this->render('/landing.html.twig');
  197.     }
  198.     /**
  199.      * @Route("/birzha/my-own", name="birzha_my_own")
  200.      * @param Request $request
  201.      *
  202.      * @return Response
  203.      * @throws ClientExceptionInterface
  204.      * @throws RedirectionExceptionInterface
  205.      * @throws ServerExceptionInterface
  206.      */
  207.     public function agencyMyOwn(
  208.         Request $request
  209.     ): Response
  210.     {
  211.         $loginData = $this->checkLoginData();
  212.         $manager = $loginData['manager'];
  213.         $agency = $loginData['agency'];
  214.         $host = $request->getHost();
  215.         $pagination = $network = null;
  216.         $balance = $this->balance($agency);
  217.         $filterData = isset($_COOKIE['requests-filter']) ? (array)json_decode($_COOKIE['requests-filter']) : null;
  218.         if ($agency) {
  219.             $auctions = $this->debitRepository->findByAgency($agency->getId(), $filterData);
  220.             $pagination = $this->pagination($auctions, $request);
  221.         }
  222.         $dataCountries = $this->auctionRepository->findByCountry();
  223.         $dataRegions = $this->auctionRepository->findByRegion();
  224. //        $description   = 'Ви можете відмовитися від купленої заявки (і повернути кошти) якщо номер телефону клієнта вказано
  225. // некоректне або абонент не бере слухавку протягом доби.<br>
  226. // <strong>Для цього напишіть на vira@tat.ua номер заявки та прикріпіть скріншот, де видно дата та час дзвінка туристу.</strong>
  227. //  Після перевірки кошти будуть повернуті на баланс.';
  228.         $description = '';
  229.         if ($host == 'birzha.tat.ua') {
  230.             $network = 'tat';
  231.         }
  232.         $sources = $this->auctionSource->findBy(['active' => 0]);
  233.         if (!$manager) {
  234.             return $this->redirect('/birzha/login');
  235.         }
  236.         return $this->render('agency.html.twig', [
  237.             'requests' => $pagination,
  238.             'manager' => $manager,
  239.             'agency' => $agency,
  240.             'balance' => $balance,
  241.             'own' => true,
  242.             'description' => $description,
  243.             'network' => $network,
  244.             'filterData' => $filterData,
  245.             'sources' => $sources,
  246.             'dataCountries' => $dataCountries,
  247.             'dataRegions' => $dataRegions,
  248.         ]);
  249.     }
  250.     /**
  251.      * @Route("/auction/my-own", name="agency_my_own")
  252.      * @param Request $request
  253.      *
  254.      * @return Response
  255.      * @throws ClientExceptionInterface
  256.      * @throws RedirectionExceptionInterface
  257.      * @throws ServerExceptionInterface
  258.      */
  259.     public function agencyMyOwnOLD(
  260.         Request $request
  261.     ): Response
  262.     {
  263.         $loginData = $this->checkLoginData();
  264.         $manager = $loginData['manager'];
  265.         if ($manager) {
  266.             return $this->redirect('/birzha/my-own');
  267.         }
  268.         return $this->render('login.html.twig', [
  269.             'manager' => $manager,
  270.         ]);
  271.     }
  272.     /**
  273.      * @Route("/birzha/rules", name="agency_auction_rules")
  274.      * @param AuctionSourceRepository $sourceRepository
  275.      *
  276.      * @return Response
  277.      * @throws ClientExceptionInterface
  278.      * @throws DecodingExceptionInterface
  279.      * @throws RedirectionExceptionInterface
  280.      * @throws ServerExceptionInterface
  281.      * @throws TransportExceptionInterface
  282.      */
  283.     public function agencyRules(
  284.         Request                 $request,
  285.         AuctionSourceRepository $sourceRepository
  286.     ): Response
  287.     {
  288.         $loginData = $this->checkLoginData();
  289.         $manager = $loginData['manager'];
  290.         $agency = $loginData['agency'];
  291.         if (!$manager) {
  292.             return $this->redirect('/birzha/login');
  293.         }
  294.         $countries = $this->geoService->countries();
  295.         $regions = $this->geoService->regions();
  296.         $sources = $sourceRepository->findAll();
  297.         $balance = $this->balance($agency);
  298.         $description = 'На цій сторінці ви зможете налаштувати правила для автоматичної покупки заявок на аукціоні за прийнятною для Вас ціною, без особистої участі в аукціоні.';
  299.         $host = $request->getHost();
  300.         $network = null;
  301.         if ($host == 'birzha.tat.ua') {
  302.             $network = 'tat';
  303.         }
  304.         return $this->render('rules.html.twig', [
  305.             'countries' => $countries,
  306.             'regions' => $regions,
  307.             'manager' => $manager,
  308.             'agency' => $agency,
  309.             'balance' => $balance,
  310.             'sources' => $sources,
  311.             'description' => $description,
  312.             'network' => $network,
  313.         ]);
  314.     }
  315.     /**
  316.      * @Route("/birzha/subscription", name="agency_subscription")
  317.      * @return Response
  318.      * @throws ClientExceptionInterface
  319.      * @throws DecodingExceptionInterface
  320.      * @throws RedirectionExceptionInterface
  321.      * @throws ServerExceptionInterface
  322.      * @throws TransportExceptionInterface
  323.      */
  324.     public function agencySubscription(Request $request): Response
  325.     {
  326.         $loginData = $this->checkLoginData();
  327.         $manager = $loginData['manager'];
  328.         $agency = $loginData['agency'];
  329.         if (!$manager) {
  330.             return $this->redirect('/birzha/login');
  331.         }
  332.         $balance = $this->balance($agency);
  333.         $cities = $this->geoService->regions('ukr');
  334.         $host = $request->getHost();
  335.         $network = null;
  336.         if ($host == 'birzha.tat.ua') {
  337.             $network = 'tat';
  338.         }
  339.         return $this->render('subscription.html.twig', [
  340.             'cities' => $cities,
  341.             'manager' => $manager,
  342.             'agency' => $agency,
  343.             'balance' => $balance,
  344.             'network' => $network,
  345.         ]);
  346.     }
  347.     /**
  348.      * @Route("/stats", name="events-index")
  349.      * @param EventsRepository $eventsRepository
  350.      * @param Request $request
  351.      *
  352.      * @return Response
  353.      */
  354.     public function indexEvents(
  355.         EventsRepository $eventsRepository,
  356.         Request          $request
  357.     ): Response
  358.     {
  359.         $loginData = $this->checkLoginData();
  360.         $manager = $loginData['manager'];
  361.         $agency = $loginData['agency'];
  362.         if (!$manager) {
  363.             return $this->redirect('/birzha/login');
  364.         }
  365.         $balance = $this->balance($agency);
  366.         $events = $eventNames = null;
  367.         if ($agency) {
  368.             $date = $request->get('data');
  369.             $stat = $request->get('stats-id');
  370.             if (!$date) {
  371.                 $date = $request->query->all();
  372.             }
  373.             $events = $eventsRepository->findDataAgency($agency->getId(), $date, $stat);
  374.             $eventsDates = $eventsRepository->findDatesAndNamesAgency($agency->getId());
  375.             $eventNames = array_column($eventsDates, 'advertName', 'advertNum');
  376.         }
  377.         $meta = [];
  378.         $meta['title'] = 'Статистика';
  379.         return $this->render('events.html.twig', [
  380.             'manager' => $manager,
  381.             'agency' => $agency,
  382.             'balance' => $balance,
  383.             'events' => $events,
  384.             'eventNames' => $eventNames,
  385.             'meta' => $meta,
  386.         ]);
  387.     }
  388.     /**
  389.      * @Route("/finance", name="finance-index")
  390.      * @param Request $request
  391.      * @param DebitRepository $debitRepository
  392.      *
  393.      * @return Response
  394.      */
  395.     public function indexFinance(
  396.         Request         $request,
  397.         DebitRepository $debitRepository
  398.     ): Response
  399.     {
  400.         $loginData = $this->checkLoginData();
  401.         $manager = $loginData['manager'];
  402.         $agency = $loginData['agency'];
  403.         if (!$manager) {
  404.             return $this->redirect('/birzha/login');
  405.         }
  406.         $balance = $this->balance($agency);
  407.         $balanceFrom = $balanceTo = null;
  408.         if ($agency) {
  409.             $date = $request->get('data');
  410.             if (!$date) {
  411.                 $date = $request->query->all();
  412.             }
  413.             if (!$date) {
  414.                 $now = new DateTime('now');
  415.                 $dateFrom = new DateTime('now');
  416.                 $dateFrom->modify('first day of this month');
  417.                 $dateFrom = $dateFrom->format('Y-m-d');
  418.                 $dateTo = $now->format('Y-m-d');
  419.             } else {
  420.                 $dates = explode(" - ", $date['dates']);
  421.                 $dateFrom = new \DateTime($dates['0']);
  422.                 $dateTo = new \DateTime($dates['1']);
  423.                 $dateFrom = $dateFrom->format('Y-m-d');
  424.                 $dateTo = $dateTo->format('Y-m-d');
  425.             }
  426.             $balanceFrom = floatval($debitRepository->checkingPaid($agency->getId(), $dateFrom, '<')) - floatval(
  427.                     $debitRepository->checkingCost($agency->getId(), $dateFrom . ' 00:00:00', '<=')
  428.                 );
  429.             $balanceTo = floatval($debitRepository->checkingPaid($agency->getId(), $dateTo, '<=')) - floatval(
  430.                     $debitRepository->checkingCost($agency->getId(), $dateTo . ' 23:59:59', '<=')
  431.                 );
  432.             $debits = $debitRepository->findDebitsAgency($agency->getId(), $date);
  433.             $paid = $debitRepository->findPaidAgency($agency->getId(), $date);
  434.         }
  435.         $debits = array_merge($debits, $paid);
  436.         usort($debits, array($this, "sortFunction"));
  437.         $meta = [];
  438.         $meta['title'] = 'Финансы';
  439.         return $this->render('finances.html.twig', [
  440.             'manager' => $manager,
  441.             'agency' => $agency,
  442.             'balance' => $balance,
  443.             'debits' => $debits,
  444.             'meta' => $meta,
  445.             'balanceFrom' => $balanceFrom,
  446.             'balanceTo' => $balanceTo,
  447.         ]);
  448.     }
  449.     private function sortFunction($a, $b)
  450.     {
  451.         return strtotime($b["date"]) - strtotime($a["date"]);
  452.     }
  453.     private function balance($agency): float
  454.     {
  455.         if ($agency) {
  456.             $costArray = $this->debitRepository->findAllGreaterThanPrice($agency->getId());
  457.             $paidArray = $this->debitRepository->findPaid($agency->getId());
  458.             $cost = array_sum(array_column($costArray, 'cost'));
  459.             $paid = array_sum(array_column($paidArray, 'paid'));
  460.             return $paid - $cost;
  461.         } else {
  462.             return 0;
  463.         }
  464.     }
  465.     private function pagination($query, $request): PaginationInterface
  466.     {
  467.         $pg = new Paginator($query);
  468.         $pg->setUseOutputWalkers(false);
  469.         if ($pg->count() > 1200) {
  470.             $query->setHint('knp_paginator.count', 1200);
  471.         } else {
  472.             $query->setHint('knp_paginator.count', $pg->count());
  473.         }
  474.         if ($request->get('page', 1) > 100) {
  475.             $query->setDQL('SELECT r FROM App\Entity\AuctionRequest r WHERE 1 = 2');
  476.             return $this->paginator->paginate($query, $request->get('page', 1), 12);
  477.         }
  478.         return $this->paginator->paginate($query, $request->get('page', 1), 12);
  479.     }
  480.     function ruleSave($ruleEntity, $rule, $sourceRepository)
  481.     {
  482.         $ruleEntity->setActive(false);
  483.         if (isset($rule['active']) && $rule['active'] == 1) {
  484.             $ruleEntity->setActive(true);
  485.         }
  486.         if (isset($rule['price']) && $rule['price']) {
  487.             $ruleEntity->setPrice($rule['price']);
  488.         }
  489.         if (isset($rule['type']) && $rule['type']) {
  490.             $ruleEntity->setType(intval($rule['type']));
  491.         }
  492.         if (isset($rule['countries']) && $rule['countries']) {
  493.             $ruleEntity->setCountries($rule['countries']);
  494.         }
  495.         if (isset($rule['regions']) && $rule['regions']) {
  496.             $ruleEntity->setRegions($rule['regions']);
  497.         }
  498.         if (isset($rule['source']) && $rule['source']) {
  499.             $source = $sourceRepository->findOneBy(['id' => $rule['source']]);
  500.             $ruleEntity->setSource($source);
  501.         }
  502.         $manager = $this->managerRepository->findOneBy(['id' => $rule['manager']]);
  503.         $ruleEntity->setManager($manager);
  504.         $this->em->persist($ruleEntity);
  505.     }
  506.     function checkSubscription($manager)
  507.     {
  508.         if ($manager && !$manager->getSubscription()) {
  509.             $ifExist = $this->subscriptionRepository->findOneBy(['manager' => $manager]);
  510.             if (!$ifExist) {
  511.                 $subscription = new Subscription();
  512.                 $subscription->setManager($manager);
  513.                 $cities = $manager->getAgency()->getCities();
  514.                 if (is_array($cities)) {
  515.                     foreach ($cities as $item) {
  516.                         if ($item) {
  517.                             $array[] = $item;
  518.                         }
  519.                     }
  520.                     $subscription->setRegions($array);
  521.                 } else {
  522.                     $cities = str_replace("[", "", $cities);
  523.                     $cities = str_replace("]", "", $cities);
  524.                     $cities = str_replace(" ", "", $cities);
  525.                     $cities = explode("\"", $cities);
  526.                     $array = [];
  527.                     foreach ($cities as $item) {
  528.                         if ($item) {
  529.                             $array[] = $item;
  530.                         }
  531.                     }
  532.                     $subscription->setRegions($array);
  533.                 }
  534.                 $this->em->persist($subscription);
  535.                 $this->em->flush();
  536.             }
  537.         }
  538.     }
  539.     function checkLoginData()
  540.     {
  541.         $manager = $agency = null;
  542.         $loginData = $this->get('session')->get('loginData');
  543.         if (!$loginData && isset($_COOKIE['loginData'])) {
  544.             $loginData = json_decode($_COOKIE['loginData'], 1);
  545.         }
  546.         if ($loginData && isset($loginData['id']) && !isset($_COOKIE['admin_login'])) {
  547.             $manager = $this->managerRepository->findOneById($loginData['id']);
  548.             $this->checkSubscription($manager);
  549.         } else
  550.             if (isset($_COOKIE['authautologin']) or isset($_COOKIE['cookie_login'])) {
  551.                 $url = 'https://content.otpusk.com/me/auth/me/?_=' . rand(123456789, 987654321);
  552.                 $recoverRequest = curl_init();
  553.                 if (isset($_COOKIE['authautologin'])) {
  554.                     $login = 'Cookie: authautologin=' . $_COOKIE['authautologin'];
  555.                     $userAgent = $_SERVER['HTTP_USER_AGENT'];
  556.                 } else {
  557.                     $login = 'Cookie: ' . $_COOKIE['cookie_login'];
  558.                     $userAgent = 'www.otpusk.com';
  559.                 }
  560.                 curl_setopt_array($recoverRequest, array(
  561.                     CURLOPT_URL => $url,
  562.                     CURLOPT_USERAGENT => $userAgent,
  563.                     CURLOPT_HEADER => false,
  564.                     CURLOPT_HTTPHEADER => array(
  565.                         'Content-Type: application/json',
  566.                         $login,
  567.                     ),
  568.                     CURLOPT_REFERER => 'https://pro.otpusk.com',
  569.                     CURLOPT_RETURNTRANSFER => true,
  570.                     CURLOPT_SSL_VERIFYHOST => false,
  571.                     CURLOPT_SSL_VERIFYPEER => false,
  572.                     CURLOPT_TIMEOUT => 2,
  573.                 ));
  574.                 if (isset($_COOKIE['DM'])) {
  575.                     curl_setopt($recoverRequest, CURLOPT_VERBOSE, true);
  576.                     curl_setopt($recoverRequest, CURLOPT_STDERR, fopen('php://output', 'w'));
  577.                     curl_setopt($recoverRequest, CURLINFO_HEADER_OUT, true);
  578.                 }
  579.                 $data = curl_exec($recoverRequest);
  580.                 if (substr($data, 0, 3) == pack('H*', 'EFBBBF')) {
  581.                     $data = substr($data, 3);
  582.                 }
  583.                 $loginData = json_decode($data, 1);
  584.                 if (isset($loginData['error'])) {
  585.                     $this->logger->debug('checkLoginData :' . json_decode($loginData['error'])
  586.                     );
  587.                     return ['manager' => $manager, 'agency' => $agency];
  588.                 } else {
  589.                     $loginDataCookie = json_encode($data, 1);
  590.                     $this->get('session')->set('loginData', $loginData);
  591.                     $this->get('session')->set('user_login', $loginData['mail']);
  592.                     setcookie('user_login', $loginData['mail'], -86400, '/', '.otpusk.com');
  593.                     setcookie('user_login', $loginData['mail'], -86400, '/');
  594.                     setcookie('loginData', $loginDataCookie, -86400, '/', '.otpusk.com');
  595.                     setcookie('loginData', $loginDataCookie, -86400, '/');
  596.                     if ($loginData && isset($loginData['services']) && isset($loginData['services']['agency']) && isset($loginData['services']['agency']['id']) && isset($loginData['id'])) {
  597.                         $manager = $this->managerRepository->findOneById($loginData['id']);
  598.                         if ($manager->getName() != $loginData['name']) {
  599.                             $manager->setName($loginData['name']);
  600.                             $this->em->persist($manager);
  601.                             $this->em->flush();
  602.                         }
  603.                         $this->checkSubscription($manager);
  604.                     }
  605.                 }
  606.             }
  607.         if ($manager) {
  608.             $agency = $manager->getAgency();
  609.             if ($loginData && isset($loginData['services']) && isset($loginData['services']['agency'])) {
  610.                 if ($agency->getName() != $loginData['services']['agency']['name']) {
  611.                     $agency->setName($loginData['services']['agency']['name']);
  612.                     $this->em->persist($agency);
  613.                     $this->em->flush();
  614.                 }
  615.             }
  616.         }
  617.         return ['manager' => $manager, 'agency' => $agency];
  618.     }
  619.     /**
  620.      * @Route("/crm-settings", name="crm-index")
  621.      * @param \App\Repository\AgencyCrmIntegrationsRepository $agencyCrm
  622.      *
  623.      * @return Response
  624.      */
  625.     public function indexCrm(
  626.         Request                         $request,
  627.         AgencyCrmIntegrationsRepository $agencyCrm
  628.     ): Response
  629.     {
  630.         $loginData = $this->checkLoginData();
  631.         $manager = $loginData['manager'];
  632.         $agency = $loginData['agency'];
  633.         if (!$manager) {
  634.             return $this->redirect('/birzha/login');
  635.         }
  636.         $balance = $this->balance($agency);
  637.         $data = $tokens = [];
  638.         if ($agency) {
  639.             $tokens = $agencyCrm->findBy(['agency' => $agency->getId()]);
  640.         }
  641.         foreach ($tokens as $token) {
  642.             $data[$token->getCrmId()] = ['token' => $token->getToken(), 'userId' => $token->getUserId()];
  643.         }
  644.         $meta['title'] = 'Интеграция с CRM';
  645.         $host = $request->getHost();
  646.         $network = null;
  647.         if ($host == 'birzha.tat.ua') {
  648.             $network = 'tat';
  649.         }
  650.         return $this->render('crm.html.twig', [
  651.             'manager' => $manager,
  652.             'agency' => $agency,
  653.             'balance' => $balance,
  654.             'data' => $data,
  655.             'meta' => $meta,
  656.             'network' => $network,
  657.         ]);
  658.     }
  659.     /**
  660.      * @Route("/test", name="test-index")
  661.      */
  662.     public function test()
  663.     {
  664.         $httpClient = HttpClient::create();
  665.         $response = $httpClient->request(
  666.             'GET',
  667.             'https://api.otpusk.com/api/2.4/tours/cities?countryId=116&access_token=4b26a-e5237-9b0fa-bcc36-67732',
  668.             ['headers' => ['User-Agent' => 'pro.otpusk.com']]
  669.         );
  670.         $content = $response->toArray()['countries'];
  671.         $res = [];
  672.         foreach ($content as $item) {
  673.             $res[$item['id']] = ['name' => $item['name'], 'iso' => $item['iso']];
  674.         }
  675.         file_put_contents('/app/private/test.php', '<?php $arr = ' . var_export($res, true) . ';');
  676.         dd($res);
  677.     }
  678. }