src/Service/EventsService.php line 361

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Adverts;
  4. use App\Entity\Debit;
  5. use App\EntityOtpusk\Events;
  6. use App\Exception\EventsException;
  7. use App\Repository\AgencyRepository;
  8. use App\Repository\BlackListRepository;
  9. use App\Repository\DebitRepository;
  10. use App\Repository\EventsRepository;
  11. use App\Repository\TourRepository;
  12. use App\Repository\AdvertsRepository;
  13. use App\Repository\ManagerLogsRepository;
  14. use App\Service\Ipv6Service;
  15. use ClickHouseDB\Exception\ClickHouseException;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Psr\Log\LoggerInterface;
  18. use Symfony\Component\Cache\Adapter\MemcachedAdapter;
  19. use Symfony\Component\HttpClient\HttpClient;
  20. use Symfony\Component\HttpKernel\KernelInterface;
  21. use Symfony\Contracts\HttpClient\HttpClientInterface;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. /**
  24.  * Class EventsService
  25.  * @package App\Service
  26.  */
  27. class EventsService
  28. {
  29.     /**
  30.      * @var EntityManagerInterface
  31.      */
  32.     private $em;
  33.     /**
  34.      * @var TourRepository
  35.      */
  36.     private $tourRepository;
  37.     /**
  38.      * @var EventsRepository
  39.      */
  40.     private $eventsRepository;
  41.     /**
  42.      * @var KernelInterface
  43.      */
  44.     private $kernelInterface;
  45.     /**
  46.      * @var DebitRepository
  47.      */
  48.     private $debitRepository;
  49.     /**
  50.      * @var AgencyRepository
  51.      */
  52.     private $agencyRepository;
  53.     /**
  54.      * @var NotificationService
  55.      */
  56.     private $notificationService;
  57.     /**
  58.      * @var ManagerLogsRepository
  59.      */
  60.     private $managerLogsRepository;
  61.     /**
  62.      * @var AdvertsRepository
  63.      */
  64.     private $advertsRepository;
  65.     /**
  66.      * @var HttpClientInterface
  67.      */
  68.     private $client;
  69.     /**
  70.      * @var LoggerInterface
  71.      */
  72.     private $logger;
  73.     /**
  74.      * @var \App\Repository\BlackListRepository
  75.      */
  76.     private BlackListRepository $blackListRepository;
  77.     /**
  78.      * @var RequestStack
  79.      */
  80.     private $requestStack;
  81.     /**
  82.      * EventsService constructor.
  83.      *
  84.      * @param EntityManagerInterface $em
  85.      * @param TourRepository $tourRepository
  86.      * @param EventsRepository $eventsRepository
  87.      * @param BlackListRepository $blackListRepository
  88.      * @param DebitRepository $debitRepository
  89.      * @param AgencyRepository $agencyRepository
  90.      * @param NotificationService $notificationService
  91.      * @param ManagerLogsRepository $managerLogsRepository
  92.      * @param AdvertsRepository $advertsRepository
  93.      * @param KernelInterface $kernelInterface
  94.      * @param LoggerInterface $logger
  95.      * @param HttpClientInterface $client
  96.      * @param Request $request
  97.      */
  98.     public function __construct(
  99.         EntityManagerInterface $em,
  100.         TourRepository $tourRepository,
  101.         EventsRepository $eventsRepository,
  102.         BlackListRepository $blackListRepository,
  103.         DebitRepository $debitRepository,
  104.         AgencyRepository $agencyRepository,
  105.         NotificationService $notificationService,
  106.         ManagerLogsRepository $managerLogsRepository,
  107.         AdvertsRepository $advertsRepository,
  108.         KernelInterface $kernelInterface,
  109.         HttpClientInterface $client,
  110.         LoggerInterface $logger,
  111.         RequestStack $requestStack
  112.     ) {
  113.         $this->em                    $em;
  114.         $this->tourRepository        $tourRepository;
  115.         $this->eventsRepository      $eventsRepository;
  116.         $this->blackListRepository   $blackListRepository;
  117.         $this->kernelInterface       $kernelInterface;
  118.         $this->debitRepository       $debitRepository;
  119.         $this->agencyRepository      $agencyRepository;
  120.         $this->managerLogsRepository $managerLogsRepository;
  121.         $this->advertsRepository     $advertsRepository;
  122.         $this->notificationService   $notificationService;
  123.         $this->client                $client;
  124.         $this->logger                $logger;
  125.         $this->requestStack          $requestStack;
  126.     }
  127.     public function getEvents(Events $event)
  128.     {
  129.         $this->eventsRepository->_connect();
  130.     }
  131.     public function saveEvent(Events $event$getEvent=false)
  132.     {
  133.         $tourInfo $this->tourRepository->getTourInfo(
  134.             $event->getOfferId(),
  135.             $event->getOperatorId(),
  136.             $event->getCruiseId()
  137.         );
  138.         if ($tourInfo && $tourInfo->getOfferId()) {
  139.             $event->setOperatorId($tourInfo->getOperatorId());
  140.             $event->setCountryId($tourInfo->getCountryId());
  141.             $event->setHotelId($tourInfo->getHotelId());
  142.             $event->setFromCityId($tourInfo->getFromCityId());
  143.             $event->setCheckIn($tourInfo->getCheckIn());
  144.             $event->setNights($tourInfo->getNights());
  145.             if (empty($tourInfo->getChild())) {
  146.                 $event->setPeople($tourInfo->getAdult());
  147.             } else {
  148.                 if (empty($event->getPeople())) {
  149.                     $child $tourInfo->getChild();
  150.                     if ($child == 1) {
  151.                         $child '06';
  152.                     } elseif ($child == 2) {
  153.                         $child '0608';
  154.                     } elseif ($child == 3) {
  155.                         $child '060810';
  156.                     } elseif ($child == 4) {
  157.                         $child '05070911';
  158.                     }
  159.                     $event->setPeople($tourInfo->getAdult().$child);
  160.                 }
  161.             }
  162.             $event->setFood($tourInfo->getFood());
  163.             $event->setTransport($tourInfo->getTransport());
  164.             $event->setRoomId($tourInfo->getRoomId());
  165.             if ($tourInfo->getCurrency() == 'uah') {
  166.                 $priceUah $tourInfo->getPrice();
  167.             } else {
  168.                 $priceUah $tourInfo->getPriceUah();
  169.                 if (empty($priceUah)) {
  170.                     $priceUah $tourInfo->getPrice() * $tourInfo->getCurrencyRate();
  171.                 }
  172.             }
  173.             $event->setPrice($priceUah);
  174.             $event->setCurrency($tourInfo->getCurrency());
  175.         }
  176.         if(!$event->getHotelId()) {
  177.             $httpClient HttpClient::create();
  178.             $offreId    $event->getOfferId();
  179.             $response   $httpClient->request(
  180.                 'GET',
  181.                 'https://api.otpusk.com/api/2.5/tours/offer?offerId='.$offreId.'&access_token=4b26a-e5237-9b0fa-bcc36-67732',
  182.                 ['headers' => ['User-Agent' => 'pro.otpusk.com']]
  183.             );
  184.             if (200 == $response->getStatusCode()) {
  185.                 $content $response->toArray()['offer'];
  186.             if(!$event->getCountryId() && isset($content['countryId']))
  187.                     $event->setCountryId($content['countryId']);
  188.             if(!$event->getHotelId() && isset($content['hotelId']))
  189.                     $event->setHotelId($content['hotelId']);
  190.             if(!$event->getFromCityId() && isset($content['fromCity']))
  191.                     $event->setFromCityId($content['fromCity']);
  192.             if(!$event->getRoomId() && isset($content['roomId']))
  193.                     $event->setRoomId($content['roomId']);
  194.             if(!$event->getPrice() && isset($content['priceUah']))
  195.                     $event->setPrice($content['priceUah']);
  196.             }
  197.         }
  198.         $event->setEventPrice(0);
  199.         // Ищем объявление
  200.         $advertsRepository $this->em->getRepository(Adverts::class);
  201.         /** @var $advertInfo Adverts */
  202.         $advertInfo $advertsRepository->find($event->getAdvertId());
  203.         $event->setEventPrice(0);
  204.         if ($advertInfo && $advertInfo->getAgency() &&
  205.             $advertInfo->getAgency()->getActive() > &&
  206.             $advertInfo->getAgency()->getStatus() == 'premium')
  207.         {
  208.             $event->setAgencyId($advertInfo->getAgency()->getId());
  209.             $event->setEventPrice($advertInfo->getPrice() ?? 50);
  210.         } else {
  211.             $event->setEventPosition(22);
  212.         }
  213.         /*
  214.         if ($event->getEventPrice() > 0) {
  215.             if (!$tourInfo || !$tourInfo->getOfferId()) {
  216.                 // если не найден offer
  217.                 $event->setEventPrice(0);
  218.                 $event->setEventPosition(24);
  219.             }
  220.         }
  221.         */
  222.         // fixme: нужно как-то проверять относится ли officeId и advertId к одному агентству
  223.         if ($event->getEventPrice() > 0) {
  224.             try {
  225.                 $ip $this->blackListRepository->getByIp(intval($event->getIp()));
  226.                 if ($ip) {
  227.                     // Ip в черном списке
  228.                     $event->setEventPrice(0);
  229.                     $event->setEventPosition(31);
  230.                 }
  231.             } catch (ClickHouseException $e) {
  232.                 $events 'error: '.$e->getMessage();
  233.             }
  234.             if (isset($_COOKIE['DM'])) {
  235.                 header('X-31-blacklist: '.$ip);
  236.             }
  237.         }
  238.         if ($event->getEventPrice() > 0) {
  239.             // проверяем был ли уже такое событие сегодня у этого объявления
  240.             $option    = array(
  241.                 \Memcached::OPT_PREFIX_KEY => (getenv('MEMCACHED_PREFIX') ? getenv(
  242.                     'MEMCACHED_PREFIX'
  243.                 ) : ($_ENV['MEMCACHED_PREFIX'] ?? '')),
  244.             );
  245.             $client    MemcachedAdapter::createConnection(
  246.                 getenv('MEMCACHED_SERV') ? getenv('MEMCACHED_SERV') : $_ENV['MEMCACHED_SERV'],
  247.                 $option
  248.             );
  249.             $cache_key 'event_'.$event->getEventDate()->format('Ymd').'_'.$event->getAdvertId().'_'.$event->getIp();
  250.             if (isset($_COOKIE['DM'])) {
  251.                 $MEMCACHED_PREFIX = (getenv('MEMCACHED_PREFIX') ? getenv(
  252.                     'MEMCACHED_PREFIX'
  253.                 ) : ($_ENV['MEMCACHED_PREFIX'] ?? ''));
  254.                 $MEMCACHED_SERV   = (getenv('MEMCACHED_SERV') ? getenv('MEMCACHED_SERV') : $_ENV['MEMCACHED_SERV']);
  255.                 $client->set('test_'.$cache_keytime(), 24 60 60);
  256.                 header(
  257.                     'X-26-memTest: '.$MEMCACHED_SERV.'@'.$MEMCACHED_PREFIX.'&'.$cache_key.'='.$client->get(
  258.                         'test_'.$cache_key
  259.                     )
  260.                 );
  261.             }
  262.             if ($event_time $client->get($cache_key)) {
  263.                 // уникальное событие, если сегодня уже было
  264.                 $event->setEventPrice(0);
  265.                 $event->setEventPosition(26);
  266.             } else {
  267.                 $client->set($cache_keytime(), time() + (24 60 60));
  268.             }
  269.         }
  270.         if ($event->getEventPrice() > 0) {
  271.             try {
  272.                 $log $this->managerLogsRepository->findOneBy(['ip' => $event->getIp()]);
  273.                 if ($log && $log->getIp2Long() == $event->getIp()) {
  274.                     // игнорируем если это IP менеджера любого из агентства
  275.                     $event->setEventPrice(0);
  276.                     $event->setEventPosition(27);
  277.                 }
  278.             } catch (Exception $e) {
  279.             }
  280.             if (isset($_COOKIE['DM'])) {
  281.                 header('X-27-isManager: '.$event->getIp().'='.($log $log->getIp2Long() : -1));
  282.             }
  283.         }
  284.         if ($event->getEventPrice() > 0) {
  285.             if ($advertInfo->getDaybudget() > 0) {
  286.                 try {
  287.                     $dayCost $this->debitRepository->findCostsForCurrentDay($advertInfo->getAgency()->getId());
  288.                     if ($dayCost && $dayCost >= $advertInfo->getDaybudget()) {
  289.                         // если превысили дневной бюджет
  290.                         $event->setEventPrice(0);
  291.                         $event->setEventPosition(28);
  292.                     }
  293.                 } catch (Exception $e) {
  294.                     $dayCost 'error: '.$e->getMessage();
  295.                 }
  296.                 if (isset($_COOKIE['DM'])) {
  297.                     header('X-28-dayLimit: '.$dayCost.'>='.$advertInfo->getDaybudget());
  298.                 }
  299.             }
  300.         }
  301.         if ($event->getEventPrice() > 0) {
  302.             try {
  303.                 $events $this->eventsRepository->getTotalEventsToDayByIp(intval($event->getIp()));
  304.                 if ($events >= 3) {
  305.                     // Не более 3-х платных взаимодействий в сутки с одного IP в не зависимости от объявлений
  306.                     $event->setEventPrice(0);
  307.                     $event->setEventPosition(29);
  308.                 }
  309.             } catch (ClickHouseException $e) {
  310.                 $events 'error: '.$e->getMessage();
  311.             }
  312.             if (isset($_COOKIE['DM'])) {
  313.                 header('X-29-events: '.$events.'>='3);
  314.             }
  315.         }
  316.         // TODO return if didnt help
  317.         /*
  318.         if ($event->getEventPrice() > 0) {
  319.             if (isset($_COOKIE['DM'])) header('X-30-IP: ' . $event->getIp() .' = '. Ipv6Service::long2ip($event->getIp()));
  320.             try {
  321.                 $countryIso = $this->eventsRepository->checkCountryIp($event->getIp());
  322.                 if ($countryIso && $countryIso != 'UA') {
  323.                     //Если ip не из Украины
  324.                     $event->setEventPrice(0);
  325.                     $event->setEventPosition(30);
  326.                 }
  327.             } catch (ClickHouseException $e) {
  328.                 $countryIso = 'error: '.$e->getMessage();
  329.             }
  330.             if (isset($_COOKIE['DM'])) header('X-30-CountryCode: ' . $countryIso);
  331.         }
  332.         */
  333.         try {
  334.             $this->eventsRepository->save($event);
  335.         } catch (ClickHouseException $e) {
  336.             if (isset($_COOKIE['DM'])) {
  337.                 header('X-88-error: '.$e->getMessage());
  338.             }
  339.         }
  340.         if (false !== stripos($getEvent??$event->getEventTypeName(), 'showFormAd')) {
  341.             // для собитий show ціни немає
  342.             $event->setEventPrice(0);
  343.             $event->setEventPosition(32);
  344.         }
  345.         return $event->getEventPrice();
  346.     }
  347.     public function sendGA($clientId=false$sessionId=falseEvents $event$getEvent=false)
  348.     {
  349.         $APP_ENV = (getenv('APP_ENV') ? getenv('APP_ENV') : $_ENV['APP_ENV']);
  350.         if ($APP_ENV != 'prod') {
  351.             $this->logger->info('Error Send GA env: '.$APP_ENV);
  352.             return false;
  353.         }
  354.         $account_id = (getenv('GA_ACCOUNT') ? getenv('GA_ACCOUNT') : ($_ENV['GA_ACCOUNT'] ?? ''));
  355.         if (isset($_COOKIE['DM'])) {
  356.             header('X-ACCOUNT-ID: '.$account_id);
  357.             header('X-Event-Price: '.$event->getEventPrice());
  358.             header('X-client: '.$clientId);
  359.         }
  360.         if ($event->getEventPrice() <= 0) {
  361.             $this->logger->info('Error Send GA price: '.$event->getEventPrice());
  362.             return false;
  363.         }
  364.         if (empty($account_id)) {
  365.             $this->logger->info('Error Send GA account: '.$account_id);
  366.             return null;
  367.         }
  368.         $trans_id date('d0m').'0'
  369.                     .sprintf("%u"$event->getIp()).'_'
  370.                     .$event->getAdvertId().'_'
  371.                     .($event->getCruiseId() > '' $event->getCountryId().'_')
  372.                     .$event->getRegionId().'_'
  373.                     .($event->getCruiseId() > 'excursion' 'package');
  374.         if (isset($_COOKIE['DM'])) {
  375.             header('X-TRANS-ID: '.$trans_id);
  376.         }
  377.         if (!empty($clientId)) {
  378.             /*
  379.             // send GA #33394
  380.             $response = $this->client->request(
  381.                 'POST',
  382.                 'http://www.google-analytics.com/collect',
  383.                 [
  384.                     'body' => [
  385.                         'v' => '1', //версия протокола, походу второй нет, только первая
  386.                         'tid' => $account_id, //ид гугл аналитики.
  387.                         'cid' => $clientId, //Client ID – будет отдавать фронт
  388.                         't' => 'transaction', //тип хита в этом случае
  389.                         'ti' => $trans_id, //ид транзакции
  390.                         'tr' => $event->getEventPrice() // сумма транзакции
  391.                     ],
  392.                     'timeout' => 5,
  393.                     'max_duration' => 5,
  394.                     'buffer' => false,
  395.                     'verify_peer' => false,
  396.                     'verify_host' => false,
  397.                     'headers' => [
  398.                         'User-Agent' => 'www.otpusk.com',
  399.                     ],
  400.                 ]
  401.             );
  402.             $this->logger->info('Send GA1 ' . $response->getInfo('url') . ' status: ' . $response->getStatusCode());
  403.             if (isset($_COOKIE['DM'])) {
  404.                 header('X-SEND-GA1: ' . $response->getStatusCode());
  405.             }
  406.             $response = $this->client->request(
  407.                 'POST',
  408.                 'http://www.google-analytics.com/collect',
  409.                 [
  410.                     'body' => [
  411.                         'v' => '1', //версия протокола, походу второй нет, только первая
  412.                         'tid' => $account_id, //ид гугл аналитики.
  413.                         'cid' => $clientId, //Client ID – будет отдавать фронт
  414.                         't' => 'item', //тип хита в этом случае
  415.                         'ti' => $trans_id, //ид транзакции
  416.                         'in' => $event->getAgencyId(), // Название турфирмы
  417.                         'ip' => $event->getPrice(), // стоимость товара
  418.                         'iv' => ($event->getCruiseId() > 0 ? 'Excursion' : 'Package'),
  419.                     ],
  420.                     'timeout' => 5,
  421.                     'max_duration' => 5,
  422.                     'buffer' => false,
  423.                     'verify_peer' => false,
  424.                     'verify_host' => false,
  425.                     'headers' => [
  426.                         'User-Agent' => 'www.otpusk.com',
  427.                     ],
  428.                 ]
  429.             );
  430.             $this->logger->info('Send GA2 ' . $response->getInfo('url') . ' status: ' . $response->getStatusCode());
  431.             if (isset($_COOKIE['DM'])) {
  432.                 header('X-SEND-GA2: ' . $response->getStatusCode());
  433.             }
  434.             */
  435.             $post = [
  436.                 'client_id' => $clientId,
  437.                 'non_personalized_ads' => false,
  438.                 'events' => [
  439.                     [
  440.                         //'name' => 'purchase',
  441.                         'name' => 'api'.ucfirst($getEvent??$event->getEventTypeName()), // 'purchase',
  442.                         //'timestamp_micros' => microtime(true) * 1000000,
  443.                         'params' => [
  444.                             'eventCategory' => 'offerPageAds',
  445.                             'type' => ($event->getCruiseId() > 'Excursion' 'Package'),
  446.                             'value' => (float)$event->getEventPrice(),
  447.                             'lang' => 'UK',
  448.                             'currency' => 'UAH',
  449.                             'client_id' => $clientId,
  450.                             'session_id' => $sessionId,
  451.                             'debug_mode' => true,
  452.                             /*
  453.                             'transaction_id' => $trans_id,
  454.                             //'agency_id' => $event->getAgencyId(),
  455.                             'items' => [
  456.                                 [
  457.                                     'item_id' => (string)($event->getAdvertId() . $event->getRegionId()),
  458.                                     'item_name' => 'id: ' . ((string)$event->getAdvertId() . $event->getRegionId()),
  459.                                     //'item_name' => $event->getEventType(),
  460.                                     'item_category' => ($event->getCruiseId() > 0 ? 'Excursion' : 'Package'),
  461.                                     //'item_brand' => $event->getAgencyId(),
  462.                                     'price' => (float)$event->getEventPrice(),
  463.                                     'currency' => 'UAH',
  464.                                     'quantity' => 1,
  465.                                 ]
  466.                             ],
  467.                             */
  468.                         ]
  469.                     ]
  470.                 ],
  471.                 //'validationBehavior' => 'ENFORCE_RECOMMENDATIONS'
  472.             ];
  473.             $userAgent 'www.otpusk.com';
  474.             $currentRequest $this->requestStack->getCurrentRequest();
  475.             if ($currentRequest) {
  476.                 $userAgent $currentRequest->headers->get('User-Agent''www.otpusk.com');
  477.             }
  478.             $headers = [
  479.                 'User-Agent' => $userAgent,
  480.                 'Content-Type' => 'application/json',
  481.                 //'Accept' => 'application/json',
  482.             ];
  483.             $response $this->client->request(
  484.                 'POST',
  485.                 //'https://www.google-analytics.com/debug/mp/collect?api_secret=' . urlencode('X7iB6sPfTWqTIvOwjwqV7Q') . '&measurement_id=' . urlencode('G-V52QLQJ1C6'),
  486.                 'https://www.google-analytics.com/mp/collect?api_secret=' urlencode('X7iB6sPfTWqTIvOwjwqV7Q') . '&measurement_id=' urlencode('G-V52QLQJ1C6'),
  487.                 [
  488.                     'body' => json_encode($post),
  489.                     'timeout' => 5,
  490.                     'max_duration' => 5,
  491.                     'buffer' => false,
  492.                     'verify_peer' => false,
  493.                     'verify_host' => false,
  494.                     'headers' => $headers,
  495.                 ]
  496.             );
  497.             $this->logger->info('Send GA4 ' $response->getInfo('url') . ' status: ' $response->getStatusCode());
  498.             if (isset($_COOKIE['DM'])) {
  499.                 header('X-SEND-GA4: ' $response->getInfo('url') . ' ' $response->getStatusCode() . ' ' json_encode($post) . ' ' json_encode($headers));
  500.             }
  501.         }
  502.         return true;
  503.     }
  504.     public function gelLast($limit 20)
  505.     {
  506.         return $this->eventsRepository->findAll(10);
  507.     }
  508.     public function updateDebitsByEvents()
  509.     {
  510.         $now    = new \DateTime('now');
  511.         $now    $now->format('Y-m-d');
  512.         $events $this->eventsRepository->findToDayEvents($now);
  513.         foreach ($events as $event) {
  514.             $data false;
  515.             if ($event['agencyId']) {
  516.                 $agency $this->agencyRepository->findOneBy(['id' => $event['agencyId'], 'status' => 'premium']);
  517.                 if ($agency) {
  518.                     $debit $this->debitRepository->findByAgencyAndEvent($agency$now);
  519.                     if ( ! $debit) {
  520.                         $debit = new Debit();
  521.                         $debit->setAgency($agency);
  522.                         $debit->setDateType(3);
  523.                         $debit->setType('event');
  524.                         $debit->setStatus('paid');
  525.                         $debit->setDate(new \DateTime($now));
  526.                         $debit->setCreatedAt(new \DateTime($now.' 12:00:00'));
  527.                     }
  528.                     $debit->setSum($event['eventPrices']);
  529.                     $this->em->persist($debit);
  530.                     $this->em->flush();
  531.                     $data $this->debitRepository->checkingNegativeBalance($event['agencyId']);
  532.                 }
  533.             }
  534.             if ($data) {
  535.                 if ($agency && $agency->getStatus() == 'premium') {
  536.                     $handle curl_init();
  537.                     $url    'https://control.otpusk.com/api/setagencynopaid?agencyId='.$event['agencyId'].'&access_token=4b26a-e5237-9b0fa-bcc36-67732';
  538.                     curl_setopt($handleCURLOPT_USERAGENT'pro.otpusk.com');
  539.                     curl_setopt($handleCURLOPT_SSL_VERIFYHOSTfalse);
  540.                     curl_setopt($handleCURLOPT_SSL_VERIFYPEERfalse);
  541.                     curl_setopt($handleCURLOPT_URL$url);
  542.                     curl_setopt($handleCURLOPT_RETURNTRANSFERtrue);
  543.                     curl_setopt($handleCURLOPT_FAILONERRORtrue);
  544.                     var_dump(curl_exec($handle));
  545.                     echo 'http code: '.var_export(curl_getinfo($handleCURLINFO_HTTP_CODE), 1).PHP_EOL;
  546.                     echo 'agencyId: '.var_export($event['agencyId'], 1).PHP_EOL;
  547.                     echo 'curl error: '.var_export(curl_error($handle), 1).PHP_EOL;
  548.                     curl_close($handle);
  549.                     if ($data['email']) {
  550.                         $this->notificationService->negativeBalance($data);
  551.                     }
  552.                 }
  553.             }
  554.         }
  555.     }
  556.     public function updateDebitsByEventsAgencies()
  557.     {
  558.         $now      = new \DateTime('now');
  559.         $now      $now->format('Y-m-d');
  560.         $agencies $this->eventsRepository->findAgenciesByEvents();
  561.         $agencies array_column($agencies'agencyId');
  562.         if ( ! empty($agencies)) {
  563.             $events $this->eventsRepository->findToDayEvents($now$agencies);
  564.             foreach ($events as $event) {
  565.                 $data false;
  566.                 if ($event['agencyId']) {
  567.                     $agency $this->agencyRepository->findOneBy(['id' => $event['agencyId'], 'status' => 'premium']);
  568.                     if ($agency) {
  569.                         $debit $this->debitRepository->findByAgencyAndEvent($agency$now);
  570.                         if ( ! $debit) {
  571.                             $debit = new Debit();
  572.                             $debit->setAgency($agency);
  573.                             $debit->setDateType(3);
  574.                             $debit->setType('event');
  575.                             $debit->setStatus('paid');
  576.                             $debit->setDate(new \DateTime($now));
  577.                             $debit->setCreatedAt(new \DateTime($now.' 12:00:00'));
  578.                         }
  579.                         $debit->setSum($event['eventPrices']);
  580.                         $this->em->persist($debit);
  581.                         $this->em->flush();
  582.                         $data $this->debitRepository->checkingNegativeBalance($event['agencyId']);
  583.                     }
  584.                 }
  585.                 if ($data) {
  586.                     if ($agency && $agency->getStatus() == 'premium') {
  587.                         $handle curl_init();
  588.                         $url    'https://control.otpusk.com/api/setagencynopaid?agencyId='.$event['agencyId'].'&access_token=4b26a-e5237-9b0fa-bcc36-67732';
  589.                         curl_setopt($handleCURLOPT_USERAGENT'pro.otpusk.com');
  590.                         curl_setopt($handleCURLOPT_SSL_VERIFYHOSTfalse);
  591.                         curl_setopt($handleCURLOPT_SSL_VERIFYPEERfalse);
  592.                         curl_setopt($handleCURLOPT_URL$url);
  593.                         curl_setopt($handleCURLOPT_RETURNTRANSFERtrue);
  594.                         curl_setopt($handleCURLOPT_FAILONERRORtrue);
  595.                         var_dump(curl_exec($handle));
  596.                         echo 'http code: '.var_export(curl_getinfo($handleCURLINFO_HTTP_CODE), 1).PHP_EOL;
  597.                         echo 'agencyId: '.var_export($event['agencyId'], 1).PHP_EOL;
  598.                         echo 'curl error: '.var_export(curl_error($handle), 1).PHP_EOL;
  599.                         curl_close($handle);
  600.                         if ($data['email']) {
  601.                             $this->notificationService->negativeBalance($data);
  602.                         }
  603.                     }
  604.                 }
  605.             }
  606.         }
  607.     }
  608.     public function fixDebitsByEvents()
  609.     {
  610.         $datesArray = [
  611.             '2021-04-12',
  612.             '2021-04-11',
  613.             '2021-04-10',
  614.             '2021-04-09',
  615.             '2021-04-08',
  616.             '2021-04-07',
  617.             '2021-04-06',
  618.             '2021-04-05',
  619.             '2021-04-04',
  620.             '2021-04-03',
  621.             '2021-04-02',
  622.         ];
  623.         foreach ($datesArray as $now) {
  624.             $events $this->eventsRepository->findToDayEvents($now);
  625.             foreach ($events as $event) {
  626.                 if ($event['agencyId']) {
  627.                     $agency $this->agencyRepository->findOneBy(['id' => $event['agencyId']]);
  628.                     if ($agency) {
  629.                         $debit $this->debitRepository->findByAgencyAndEvent($agency$now);
  630.                         if ( ! $debit) {
  631.                             $debit = new Debit();
  632.                             $debit->setAgency($agency);
  633.                             $debit->setDateType(3);
  634.                             $debit->setType('event');
  635.                             $debit->setStatus('paid');
  636.                             $debit->setDate(new \DateTime($now));
  637.                         }
  638.                         $debit->setSum($event['eventPrices']);
  639.                         $this->em->persist($debit);
  640.                         $this->em->flush();
  641.                     }
  642.                 }
  643.             }
  644.         }
  645.     }
  646.     public function updateEmptyEvents()
  647.     {
  648.         $events $this->eventsRepository->findEventsUntillNow('2021-10-19');
  649.         foreach ($events as $event) {
  650.             $httpClient HttpClient::create();
  651.             $offreId    $event['offerId'];
  652.             $response   $httpClient->request(
  653.                 'GET',
  654.                 'https://api.otpusk.com/api/2.5/tours/offer?offerId='.$offreId.'&access_token=4b26a-e5237-9b0fa-bcc36-67732',
  655.                 ['headers' => ['User-Agent' => 'pro.otpusk.com']]
  656.             );
  657.             if (200 == $response->getStatusCode()) {
  658.                 $content $response->toArray()['offer'];
  659.                 if ($content) {
  660.                     var_dump($event['offerId']);
  661.                     $this->eventsRepository->updateEvent($event$content);
  662.                     sleep(1);
  663.                 }
  664.             }
  665.         }
  666.     }
  667. }