<?php
namespace App\Controller;
use App\Entity\Subscription;
use App\Repository\AgencyCrmIntegrationsRepository;
use App\Repository\AuctionRequestRepository;
use App\Repository\AuctionSourceRepository;
use App\Repository\DebitRepository;
use App\Repository\EventsRepository;
use App\Repository\ManagerRepository;
use App\Repository\SubscriptionRepository;
use App\Service\GeoService;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Knp\Component\Pager\Pagination\PaginationInterface;
use Knp\Component\Pager\PaginatorInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Helper\Helper as ConsoleHelper;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Component\Routing\Annotation\Route;
class AgencyController extends AbstractController
{
private PaginatorInterface $paginator;
private ManagerRepository $managerRepository;
private AuctionRequestRepository $auctionRepository;
private DebitRepository $debitRepository;
private SubscriptionRepository $subscriptionRepository;
private GeoService $geoService;
private EntityManagerInterface $em;
private AuctionSourceRepository $auctionSource;
public function __construct(
EntityManagerInterface $em,
AuctionRequestRepository $auctionRequestRepository,
ManagerRepository $managerRepository,
DebitRepository $debitRepository,
SubscriptionRepository $subscriptionRepository,
GeoService $geoService,
AuctionSourceRepository $auctionSource,
PaginatorInterface $paginator,
LoggerInterface $logger
) {
$this->em = $em;
$this->auctionRepository = $auctionRequestRepository;
$this->managerRepository = $managerRepository;
$this->debitRepository = $debitRepository;
$this->subscriptionRepository = $subscriptionRepository;
$this->geoService = $geoService;
$this->paginator = $paginator;
$this->auctionSource = $auctionSource;
$this->logger = $logger;
}
/**
* @Route("/auction", name="agency_auction")
*/
public function agencyRequests(): Response
{
return $this->redirect('/birzha');
}
/**
* @Route("/birzha/login", name="agency_birzha_login")
* @param Request $request
*
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function agencyBirzhaLogin(Request $request): Response
{
$host = $request->getHost();
$network = null;
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
if ($manager) {
return $this->redirect('/birzha');
}
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
return $this->render('login.html.twig', [
'manager' => $manager,
'network' => $network,
]);
}
/**
* @Route("/birzha", name="agency_birzha")
* @param Request $request
*
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function agencyBirzha(Request $request): Response
{
$host = $request->getHost();
if ( ! empty($request->query->all()) && isset($request->query->all()['r'])) {
setcookie(
'referral',
$request->query->all()['r'],
['expires' => strtotime("+30 day"), 'domain' => '.otpusk.com']
);
setcookie(
'referral',
$request->query->all()['r'],
['expires' => strtotime("+30 day"), 'domain' => '.tat.ua']
);
}
$network = null;
// $data for manager test
if (($request->getHost() == '127.0.0.1')) {
$date = $request->get('data');
if ( ! $date) {
$date = $request->query->all();
}
$id = null;
if (isset($date['manager']) && ! isset($loginData['services'])) {
$manager = $this->managerRepository->findOneBy(['id' => $date['manager']]);
if ($manager) {
$id = $manager->getId();
$agency = $manager->getAgency();
$this->get('session')->set(
'loginData',
[
"id" => $id,
"services" => ["agency" => ["id" => $agency->getId(), "name" => $agency->getName()]],
]
);
}
}
}
// end of test manager
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
$balance = $this->balance($agency);
$filterData = isset($_COOKIE['requests-filter']) ? (array)json_decode($_COOKIE['requests-filter']) : null;
$auctions = $this->auctionRepository->findByNotArchive($filterData);
$dataCountries = $this->auctionRepository->findByCountry();
$dataRegions = $this->auctionRepository->findByRegion();
$pagination = $this->pagination($auctions, $request);
$description = '';
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
$sources = $this->auctionSource->findBy(['active' => 0]);
return $this->render('agency.html.twig', [
'requests' => $pagination,
'manager' => $manager,
'balance' => $balance,
'description' => $description,
'network' => $network,
'host' => $host,
'filterData' => $filterData,
'sources' => $sources,
'dataCountries' => $dataCountries,
'dataRegions' => $dataRegions,
]);
}
/**
* @Route("", name="land")
* @param Request $request
*
* @return Response
*/
public function land(Request $request): Response
{
$host = $request->getHost();
$loginData = $this->checkLoginData();
$agency = $loginData['agency'];
if ( ! empty($request->query->all()) && isset($request->query->all()['r'])) {
setcookie(
'referral',
$request->query->all()['r'],
['expires' => strtotime("+30 day"), 'domain' => '.otpusk.com']
);
setcookie(
'referral',
$request->query->all()['r'],
['expires' => strtotime("+30 day"), 'domain' => '.tat.ua']
);
}
if ($host == 'birzha.tat.ua') {
return $this->render('/tat/landing.html.twig');
}
return $this->render('/landing.html.twig');
}
/**
* @Route("/birzha/my-own", name="birzha_my_own")
* @param Request $request
*
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function agencyMyOwn(
Request $request
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
$host = $request->getHost();
$pagination = $network = null;
$balance = $this->balance($agency);
$filterData = isset($_COOKIE['requests-filter']) ? (array)json_decode($_COOKIE['requests-filter']) : null;
if ($agency) {
$auctions = $this->debitRepository->findByAgency($agency->getId(), $filterData);
$pagination = $this->pagination($auctions, $request);
}
$dataCountries = $this->auctionRepository->findByCountry();
$dataRegions = $this->auctionRepository->findByRegion();
// $description = 'Ви можете відмовитися від купленої заявки (і повернути кошти) якщо номер телефону клієнта вказано
// некоректне або абонент не бере слухавку протягом доби.<br>
// <strong>Для цього напишіть на vera@otpusk.com номер заявки та прикріпіть скріншот, де видно дата та час дзвінка туристу.</strong>
// Після перевірки кошти будуть повернуті на баланс.';
$description = '';
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
$sources = $this->auctionSource->findBy(['active' => 0]);
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
return $this->render('agency.html.twig', [
'requests' => $pagination,
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'own' => true,
'description' => $description,
'network' => $network,
'filterData' => $filterData,
'sources' => $sources,
'dataCountries' => $dataCountries,
'dataRegions' => $dataRegions,
]);
}
/**
* @Route("/auction/my-own", name="agency_my_own")
* @param Request $request
*
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function agencyMyOwnOLD(
Request $request
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
if ($manager) {
return $this->redirect('/birzha/my-own');
}
return $this->render('login.html.twig', [
'manager' => $manager,
]);
}
/**
* @Route("/birzha/rules", name="agency_auction_rules")
* @param AuctionSourceRepository $sourceRepository
*
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function agencyRules(
Request $request,
AuctionSourceRepository $sourceRepository
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
$countries = $this->geoService->countries();
$regions = $this->geoService->regions();
$sources = $sourceRepository->findAll();
$balance = $this->balance($agency);
$description = 'На цій сторінці ви зможете налаштувати правила для автоматичної покупки заявок на аукціоні за прийнятною для Вас ціною, без особистої участі в аукціоні.';
$host = $request->getHost();
$network = null;
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
return $this->render('rules.html.twig', [
'countries' => $countries,
'regions' => $regions,
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'sources' => $sources,
'description' => $description,
'network' => $network,
]);
}
/**
* @Route("/birzha/subscription", name="agency_subscription")
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function agencySubscription(Request $request): Response
{
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
$balance = $this->balance($agency);
$cities = $this->geoService->regions('ukr');
$host = $request->getHost();
$network = null;
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
return $this->render('subscription.html.twig', [
'cities' => $cities,
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'network' => $network,
]);
}
/**
* @Route("/stats", name="events-index")
* @param EventsRepository $eventsRepository
* @param Request $request
*
* @return Response
*/
public function indexEvents(
EventsRepository $eventsRepository,
Request $request
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
$balance = $this->balance($agency);
$events = $eventNames = null;
if ($agency) {
$date = $request->get('data');
$stat = $request->get('stats-id');
if ( ! $date) {
$date = $request->query->all();
}
$events = $eventsRepository->findDataAgency($agency->getId(), $date, $stat);
$eventsDates = $eventsRepository->findDatesAndNamesAgency($agency->getId());
$eventNames = array_column($eventsDates, 'advertName', 'advertNum');
}
$meta = [];
$meta['title'] = 'Статистика';
return $this->render('events.html.twig', [
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'events' => $events,
'eventNames' => $eventNames,
'meta' => $meta,
]);
}
/**
* @Route("/finance", name="finance-index")
* @param Request $request
* @param DebitRepository $debitRepository
*
* @return Response
*/
public function indexFinance(
Request $request,
DebitRepository $debitRepository
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
$balance = $this->balance($agency);
$balanceFrom = $balanceTo = null;
if ($agency) {
$date = $request->get('data');
if ( ! $date) {
$date = $request->query->all();
}
if ( ! $date) {
$now = new DateTime('now');
$dateFrom = new DateTime('now');
$dateFrom->modify('first day of this month');
$dateFrom = $dateFrom->format('Y-m-d');
$dateTo = $now->format('Y-m-d');
} else {
$dates = explode(" - ", $date['dates']);
$dateFrom = new \DateTime($dates['0']);
$dateTo = new \DateTime($dates['1']);
$dateFrom = $dateFrom->format('Y-m-d');
$dateTo = $dateTo->format('Y-m-d');
}
$balanceFrom = floatval($debitRepository->checkingPaid($agency->getId(), $dateFrom, '<')) - floatval(
$debitRepository->checkingCost($agency->getId(), $dateFrom.' 00:00:00', '<=')
);
$balanceTo = floatval($debitRepository->checkingPaid($agency->getId(), $dateTo, '<=')) - floatval(
$debitRepository->checkingCost($agency->getId(), $dateTo.' 23:59:59', '<=')
);
$debits = $debitRepository->findDebitsAgency($agency->getId(), $date);
$paid = $debitRepository->findPaidAgency($agency->getId(), $date);
}
$debits = array_merge($debits, $paid);
usort($debits, array($this, "sortFunction"));
$meta = [];
$meta['title'] = 'Финансы';
return $this->render('finances.html.twig', [
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'debits' => $debits,
'meta' => $meta,
'balanceFrom' => $balanceFrom,
'balanceTo' => $balanceTo,
]);
}
private function sortFunction($a, $b)
{
return strtotime($b["date"]) - strtotime($a["date"]);
}
private function balance($agency): float
{
if ($agency) {
$costArray = $this->debitRepository->findAllGreaterThanPrice($agency->getId());
$paidArray = $this->debitRepository->findPaid($agency->getId());
$cost = array_sum(array_column($costArray, 'cost'));
$paid = array_sum(array_column($paidArray, 'paid'));
return $paid - $cost;
} else {
return 0;
}
}
private function pagination($query, $request): PaginationInterface
{
$pg = new Paginator($query);
$pg->setUseOutputWalkers(false);
if ($pg->count() > 1200) {
$query->setHint('knp_paginator.count', 1200);
} else {
$query->setHint('knp_paginator.count', $pg->count());
}
if ($request->get('page', 1) > 100) {
$query->setDQL('SELECT r FROM App\Entity\AuctionRequest r WHERE 1 = 2');
return $this->paginator->paginate($query, $request->get('page', 1), 12);
}
return $this->paginator->paginate($query, $request->get('page', 1), 12);
}
function ruleSave($ruleEntity, $rule, $sourceRepository)
{
$ruleEntity->setActive(false);
if (isset($rule['active']) && $rule['active'] == 1) {
$ruleEntity->setActive(true);
}
if (isset($rule['price']) && $rule['price']) {
$ruleEntity->setPrice($rule['price']);
}
if (isset($rule['type']) && $rule['type']) {
$ruleEntity->setType(intval($rule['type']));
}
if (isset($rule['countries']) && $rule['countries']) {
$ruleEntity->setCountries($rule['countries']);
}
if (isset($rule['regions']) && $rule['regions']) {
$ruleEntity->setRegions($rule['regions']);
}
if (isset($rule['source']) && $rule['source']) {
$source = $sourceRepository->findOneBy(['id' => $rule['source']]);
$ruleEntity->setSource($source);
}
$manager = $this->managerRepository->findOneBy(['id' => $rule['manager']]);
$ruleEntity->setManager($manager);
$this->em->persist($ruleEntity);
}
function checkSubscription($manager)
{
if ($manager && ! $manager->getSubscription()) {
$ifExist = $this->subscriptionRepository->findOneBy(['manager' => $manager]);
if ( ! $ifExist) {
$subscription = new Subscription();
$subscription->setManager($manager);
$cities = $manager->getAgency()->getCities();
if (is_array($cities)){
foreach ($cities as $item) {
if ($item) {
$array[] = $item;
}
}
$subscription->setRegions($array);
}else {
$cities = str_replace("[", "", $cities);
$cities = str_replace("]", "", $cities);
$cities = str_replace(" ", "", $cities);
$cities = explode("\"", $cities);
$array = [];
foreach ($cities as $item) {
if ($item) {
$array[] = $item;
}
}
$subscription->setRegions($array);
}
$this->em->persist($subscription);
$this->em->flush();
}
}
}
function checkLoginData()
{
$manager = $agency = null;
$loginData = $this->get('session')->get('loginData');
if ( ! $loginData && isset($_COOKIE['loginData'])) {
$loginData = json_decode($_COOKIE['loginData'], 1);
}
if ($loginData && isset($loginData['id']) && !isset($_COOKIE['admin_login'])) {
$manager = $this->managerRepository->findOneById($loginData['id']);
$this->checkSubscription($manager);
} else
if (isset($_COOKIE['authautologin']) or isset($_COOKIE['cookie_login'])) {
$url = 'https://www.otpusk.com/me/auth/me/?_='.rand(123456789, 987654321);
$recoverRequest = curl_init();
if (isset($_COOKIE['authautologin'])) {
$login = 'Cookie: authautologin='.$_COOKIE['authautologin'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
} else {
$login = 'Cookie: '.$_COOKIE['cookie_login'];
$userAgent = 'www.otpusk.com';
}
curl_setopt_array($recoverRequest, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $userAgent,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
$login,
),
CURLOPT_REFERER => 'https://pro.otpusk.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 2,
));
$data = curl_exec($recoverRequest);
if (substr($data, 0, 3) == pack('H*', 'EFBBBF')) {
$data = substr($data, 3);
}
$loginData = json_decode($data, 1);
if (isset($loginData['error'])) {
$this->logger->debug('checkLoginData :' . json_decode($loginData['error'])
);
return ['manager' => $manager, 'agency' => $agency];
} else {
$loginDataCookie = json_encode($data, 1);
$this->get('session')->set('loginData', $loginData);
$this->get('session')->set('user_login', $loginData['mail']);
setcookie('user_login', $loginData['mail'], -86400, '/', '.otpusk.com');
setcookie('user_login', $loginData['mail'], -86400, '/');
setcookie('loginData', $loginDataCookie, -86400, '/', '.otpusk.com');
setcookie('loginData', $loginDataCookie, -86400, '/');
if ($loginData && isset($loginData['services']) && isset($loginData['services']['agency']) && isset($loginData['services']['agency']['id']) && isset($loginData['id'])) {
$manager = $this->managerRepository->findOneById($loginData['id']);
if ($manager->getName() != $loginData['name']) {
$manager->setName($loginData['name']);
$this->em->persist($manager);
$this->em->flush();
}
$this->checkSubscription($manager);
}
}
}
if ($manager) {
$agency = $manager->getAgency();
if ($loginData && isset($loginData['services']) && isset($loginData['services']['agency'])) {
if ($agency->getName() != $loginData['services']['agency']['name']) {
$agency->setName($loginData['services']['agency']['name']);
$this->em->persist($agency);
$this->em->flush();
}
}
}
return ['manager' => $manager, 'agency' => $agency];
}
/**
* @Route("/crm-settings", name="crm-index")
* @param \App\Repository\AgencyCrmIntegrationsRepository $agencyCrm
*
* @return Response
*/
public function indexCrm(
Request $request,
AgencyCrmIntegrationsRepository $agencyCrm
): Response {
$loginData = $this->checkLoginData();
$manager = $loginData['manager'];
$agency = $loginData['agency'];
if ( ! $manager) {
return $this->redirect('/birzha/login');
}
$balance = $this->balance($agency);
$data = $tokens = [];
if ($agency) {
$tokens = $agencyCrm->findBy(['agency' => $agency->getId()]);
}
foreach ($tokens as $token) {
$data[$token->getCrmId()] = ['token' => $token->getToken(), 'userId' => $token->getUserId()];
}
$meta['title'] = 'Интеграция с CRM';
$host = $request->getHost();
$network = null;
if ($host == 'birzha.tat.ua') {
$network = 'tat';
}
return $this->render('crm.html.twig', [
'manager' => $manager,
'agency' => $agency,
'balance' => $balance,
'data' => $data,
'meta' => $meta,
'network' => $network,
]);
}
/**
* @Route("/test", name="test-index")
*/
public function test()
{
$httpClient = HttpClient::create();
$response = $httpClient->request(
'GET',
'https://api.otpusk.com/api/2.4/tours/cities?countryId=116&access_token=4b26a-e5237-9b0fa-bcc36-67732',
['headers' => ['User-Agent' => 'pro.otpusk.com']]
);
$content = $response->toArray()['countries'];
$res = [];
foreach ($content as $item) {
$res[$item['id']] = ['name' => $item['name'], 'iso' => $item['iso']];
}
file_put_contents('/app/private/test.php', '<?php $arr = '.var_export($res, true).';');
dd($res);
}
}