src/Controller/ClientSidePublisherController.php line 104

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Config;
  4. use App\Entity\AffiliateInfo;
  5. use App\Entity\Employees;
  6. use App\Entity\AgentControl;
  7. use App\Entity\OfferInfo;
  8. use App\Entity\NewsletterBuilder;
  9. use App\Entity\OfferGeoRelationship;
  10. use App\Services\AffiliateHasofferAPI;
  11. use App\Services\Alerts;
  12. use App\Services\Aws\ElasticCache;
  13. use App\Services\Aws\S3;
  14. use App\Services\BrandHasofferAPI;
  15. use App\Services\Common;
  16. use App\Services\FinancialToolsComponents;
  17. use App\Services\ImpressionsApis;
  18. use App\Services\Metrics24APICalls;
  19. use App\Services\MmpComponents;
  20. use App\Services\MysqlQueries;
  21. use App\Services\UsersComponents;
  22. use Doctrine\Persistence\ManagerRegistry;
  23. use Mmoreram\GearmanBundle\Service\GearmanClientInterface;
  24. use Symfony\Component\Routing\Annotation\Route;
  25. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use App\Repository\MafoPublisherMappingWithAffiliateRepository;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  31. use function GuzzleHttp\json_encode;
  32. /**
  33.  *
  34.  * Offer related routes with endpoint /api/offers/{route}
  35.  *
  36.  * @Route("/api/client/publisher", name="client_publisher_", host="%publishers_subdomain%")
  37.  */
  38. class ClientSidePublisherController extends AbstractController
  39. {
  40.     private $commonCalls;
  41.     private $doctrine;
  42.     private $mysqlQueries;
  43.     private $financialToolsComponents;
  44.     private $alerts;
  45.     private $brandHasofferApi;
  46.     private $mmpComponents;
  47.     private $affiliateHasofferAPI;
  48.     private $usersComponents;
  49.     private $elasticCache;
  50.     private $projectDir;
  51.     private $s3;
  52.     private $impressionsApis;
  53.     private $metrics24APICalls;
  54.     private $gearmanClientInterface;
  55.     private $mappingRepository;
  56.     public function __construct(Common $commonCallsManagerRegistry $doctrineMysqlQueries $mysqlQueriesMafoPublisherMappingWithAffiliateRepository $mappingRepository,
  57.                                 FinancialToolsComponents $financialToolsComponentsAlerts $alertsBrandHasofferApi $brandHasofferApiMmpComponents $mmpComponentsAffiliateHasofferAPI $affiliateHasofferAPIUsersComponents $usersComponentsElasticCache $elasticCacheS3 $s3ImpressionsApis $impressionsApisMetrics24APICalls $metrics24APICallsGearmanClientInterface $gearmanClientInterfacestring $projectDir)
  58.     {
  59.         $this->commonCalls $commonCalls;
  60.         $this->doctrine $doctrine;
  61.         $this->mysqlQueries $mysqlQueries;
  62.         $this->financialToolsComponents $financialToolsComponents;
  63.         $this->alerts $alerts;
  64.         $this->brandHasofferApi $brandHasofferApi;
  65.         $this->mmpComponents $mmpComponents;
  66.         $this->affiliateHasofferAPI $affiliateHasofferAPI;
  67.         $this->usersComponents $usersComponents;
  68.         $this->elasticCache $elasticCache;
  69.         $this->s3 $s3;
  70.         $this->impressionsApis $impressionsApis;
  71.         $this->metrics24APICalls $metrics24APICalls;
  72.         $this->gearmanClientInterface $gearmanClientInterface;
  73.         $this->projectDir $projectDir;
  74.         $this->mappingRepository $mappingRepository;
  75.     }
  76.     /**
  77.      * @Route("/validate", name="validate", methods={"GET"})
  78.      */
  79.     public function getValidateAction(Request $request)
  80.     {
  81.         return new JsonResponse(true);
  82.     }
  83.     /**
  84.      * @Route("/test", name="test", methods={"GET"})
  85.      */
  86.     public function getAgentControlAction(Request $request)
  87.     {
  88.         return new JsonResponse(true);
  89.     }
  90.     /**
  91.      * @Route("/login", name="login")
  92.      */
  93.     public function indexAction(AuthenticationUtils $authenticationUtils)
  94.     {
  95. //        $authenticationUtils = $authenticationUtils->get('security.authentication_utils');
  96.         // get the login error if there is one
  97.         $error $authenticationUtils->getLastAuthenticationError();
  98.         // last username entered by the user
  99.         $lastUsername $authenticationUtils->getLastUsername();
  100.         return $this->render('/publisher/login/index.html.twig', [
  101.             'last_username' => $lastUsername,
  102.             'error' => $error,
  103.         ]);
  104.     }
  105.     /**
  106.      * @Route("/details", name="get_publisher_details",  methods={"GET"})
  107.      */
  108.     public function getPublishersDetails(Request $request): Response
  109.     {
  110.         $publisherInfo $this->getUser();
  111.         $publisherId $publisherInfo->getId();
  112.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  113.         // Store mappedAffiliateIds in session
  114. //        $request->getSession()->set('mappedAffiliateIds', $mappedAffiliateIds);
  115.         $publisherData = [
  116.             'id' => $publisherInfo->getId(),
  117.             'email' => $publisherInfo->getEmail(),
  118.             'firstName' => $publisherInfo->getFirstName(),
  119.             'lastName' => $publisherInfo->getLastName(),
  120.             'status' => $publisherInfo->getStatus(),
  121.             'lastLoginAt' => $publisherInfo->getLastLoginAt(),
  122.             'dateUpdated' => $publisherInfo->getDateUpdated(),
  123.         ];
  124.         return $this->json($publisherData);
  125.     }
  126.     /**
  127.      * @Route("/report-columns/{report}", name="get_report_columns", methods={"GET"})
  128.      */
  129.     public function getReportColumnsAction(Request $request$report)
  130.     {
  131.         if ($report === Config::REPORT_ADVERTISER_MACRO) {
  132.             $savedCols Config::REPORT_ADVERTISER_COLUMNS;
  133.             $col = [];
  134.             foreach ($savedCols as $key => $value) {
  135.                 $value['accessor'] = str_replace("."Config::REPORT_ADVERTISER_ACCESSOR_SEPARATOR$value['accessor']);
  136.                 $col[] = $value;
  137.             }
  138.             return new JsonResponse($col);
  139.         } elseif (in_array($reportarray_keys(Config::TABLE_COLUMNS_WITH_JSON_FILE))) {
  140.             return new JsonResponse(array_values($this->commonCalls->getDataFromJsonFile(Config::TABLE_COLUMNS_WITH_JSON_FILE[$report])));
  141.         } else {
  142.             return new JsonResponse(array_values(Config::REPORT_COLUMN_MAPPING[$report]));
  143.         }
  144.     }
  145.     /**
  146.      * @Route("/hyper-statuses", name="get_hyper_statuses", methods={"GET"})
  147.      */
  148.     public function getHyperStatusesAction(Request $request)
  149.     {
  150.         $arr = [];
  151.         foreach (array_values(Config::HYPER_STATUS_MAFO_MACROS) as $key => $value) {
  152.             $arr[$value] = [
  153.                 'value' => $value,
  154.                 'label' => $value,
  155.             ];
  156.         }
  157.         return new JsonResponse(array_values($arr));
  158.     }
  159.     /**
  160.      * @Route("/affiliates", name="get_affiliates", methods={"GET"})
  161.      */
  162.     public function getAffiliatesAction(Request $request)
  163.     {
  164.         $publisherInfo $this->getUser();
  165.         $publisherId $publisherInfo->getId();
  166.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  167.         $keyword $request->query->get('keyword');
  168.         $dataByKeyword = [];
  169.         if($keyword) {
  170.             $dataByKeyword $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateByKeyword($keyword);
  171.         }
  172.         $statusArr $request->query->get('status') != '' $request->query->get('status') : [Config::ACTIVE_STATUS];
  173.         $affiliateData $this->commonCalls->getPublisherAffiliateListByStatusWithKeys($statusArr$mappedAffiliateIds);
  174.         $affiliateList = [];
  175.         foreach ($affiliateData as $key => $value) {
  176.             $affiliateList[$value['id']] = [
  177.                 'value' => $value['id'],
  178.                 'label' => $value['id'] . ' - ' $value['name'],
  179.                 'status' => $value['status']
  180.             ];
  181.         }
  182.         foreach($dataByKeyword as $key => $value) {
  183.             if(!array_key_exists($value['affiliateId'], $affiliateList)){
  184.                 $temp = [
  185.                     'value' => (int)$value['affiliateId'],
  186.                     'label' => $value['affiliateId'] . ' - ' $value['company'],
  187.                     'status' => $value['status']
  188.                 ];
  189.                 $affiliateList[$value['affiliateId']] = $temp;
  190.             }
  191.         }
  192.         ksort$affiliateList );
  193.         return new JsonResponse(array_values($affiliateList));
  194.     }
  195.     /**
  196.      * @Route("/mafo-users", name="get_mafo_users", methods={"GET"})
  197.      */
  198.     public function getAffiliateManagersAction(Request $request)
  199.     {
  200.         $publisherInfo $this->getUser();
  201.         $publisherId $publisherInfo->getId();
  202.         $affiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  203. //        $affiliateIds = $request->getSession()->get('mappedAffiliateIds', []);
  204.         $accountManagerIds $this->doctrine->getRepository(AffiliateInfo::class)->getUniqueAccountManagerIds($affiliateIds);
  205.         $employeesInfo $this->doctrine->getRepository(Employees::class)->getEmployeesByAccountManagerIds($accountManagerIds);
  206.         $responseArr = [];
  207.         foreach ($employeesInfo as $employeeId => $employee) {
  208.             $responseArr[] = [
  209.                 'value' => $employee['email'] ?? '',
  210.                 'label' => $employee['fullName'] ?? '',
  211.             ];
  212.         }
  213.         usort($responseArr, fn($a$b) => strcmp($a['label'], $b['label']));
  214.         return new JsonResponse($responseArr);
  215.     }
  216.     private function getAffiliateAndManagerData()
  217.     {
  218.         $publisherInfo $this->getUser();
  219.         $publisherId $publisherInfo->getId();
  220.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  221.         $accountManagerIds $this->doctrine->getRepository(AffiliateInfo::class)->getUniqueAccountManagerIds($mappedAffiliateIds);
  222.         // Get employees info by account manager IDs
  223.         $employeesInfo $this->doctrine->getRepository(Employees::class)->getEmployeesByAccountManagerIds($accountManagerIds);
  224.         // Convert each affiliate ID to a string for consistency
  225.         $mappedAffiliateIds array_map('strval'$mappedAffiliateIds);
  226.         // Extract emails from $employeesInfo for MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS
  227.         $affiliateManagerEmails array_map(function($employee) {
  228.             return $employee['email'];
  229.         }, $employeesInfo);
  230.         // Prepare and return both the formatted array and mappedAffiliateIds
  231.         return [
  232.             'formattedArray' => [
  233.                 'MULTISELECT_AFFILIATES' => $mappedAffiliateIds,
  234. //                'MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS' => $affiliateManagerEmails,
  235.             ],
  236.             'formattedTrafficReportArray' => [
  237.                 'MULTISELECT_MMP_TUNE_AFFILIATES' => $mappedAffiliateIds,
  238. //                'MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS' => $affiliateManagerEmails,
  239.             ],
  240.             'mappedAffiliateIds' => $mappedAffiliateIds,
  241.             'accountManagerEmails' => $affiliateManagerEmails,
  242.         ];
  243.     }
  244.     /**
  245.      * @Route("/financial-report", name="get_financial_report", methods={"GET"})
  246.      */
  247.     public function getfinancialReportAction(Request $request)
  248.     {
  249.         $affiliateData $this->getAffiliateAndManagerData();
  250.         $formattedArray $affiliateData['formattedArray'];
  251.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  252.         $mappedAccountManagerEmails $affiliateData['accountManagerEmails'];
  253.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  254.         $filters $request->query->get('filters');
  255.         $excludedFlagForFilters $request->query->get('excludedFlagForFilters') ?? [];
  256.         // Set $filters based on the specified condition
  257.         if (is_null($filters) && !empty(array_filter($excludedFlagForFilters))) {
  258.             $filters['MULTISELECT_AFFILIATES'] = [];
  259.         } else {
  260.             $filters $filters ?? $formattedArray;
  261.         }
  262.         // Check if MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS is present but MULTISELECT_AFFILIATES is missing
  263.         if (isset($filters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) && !isset($filters['MULTISELECT_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] !== 'true') {
  264.             $filters['MULTISELECT_AFFILIATES'] = $mappedAffiliateIds;
  265.         } else if (isset($filters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS']) && !isset($filters['MULTISELECT_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS'] !== 'true') {
  266.             $filters['MULTISELECT_AFFILIATES'] = $mappedAffiliateIds;
  267.         }
  268.         // Check if excludedFlagForFilters contains a true flag for MULTISELECT_AFFILIATES
  269.         if (!empty($excludedFlagForFilters['MULTISELECT_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_AFFILIATES'] === 'true') {
  270.             // Calculate the difference between mappedAffiliateIds and filters['MULTISELECT_AFFILIATES']
  271.             $filters['MULTISELECT_AFFILIATES'] = array_diff($mappedAffiliateIds$filters['MULTISELECT_AFFILIATES']);
  272.         }
  273.         if (
  274.             !empty($filters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  275.             !empty($excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  276.             $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] === 'true'
  277.         ) {
  278.             $filters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] = array_diff($mappedAccountManagerEmails$filters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']);
  279.         } else if (
  280.             empty($filters['MULTISELECT_AFFILIATES']) &&
  281.             !empty($excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  282.             $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] === 'true'
  283.         ) {
  284.             $filters['MULTISELECT_AFFILIATES'] = array_diff($mappedAffiliateIds$filters['MULTISELECT_AFFILIATES']);
  285.         }
  286.         if (
  287.             !empty($filters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS']) &&
  288.             !empty($excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS']) &&
  289.             $excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS'] === 'true'
  290.         ) {
  291.             $filters['MULTISELECT_AFFILIATES'] = $mappedAffiliateIds;
  292.         } else if (
  293.             empty($filters['MULTISELECT_AFFILIATES']) &&
  294.             !empty($excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS']) &&
  295.             $excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS'] === 'true'
  296.         ) {
  297.             $filters['MULTISELECT_AFFILIATES'] = array_diff($mappedAffiliateIds$filters['MULTISELECT_AFFILIATES']);
  298.         }
  299.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  300.         $page $request->query->get('page') ? $request->query->get('page') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  301.         $sortBy $request->query->get('sortBy') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_BY;
  302.         $sortType $request->query->get('sortType') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_TYPE;
  303.         $filtersToProcess = [];
  304.         if (isset($filters)) {
  305.             foreach ($filters as $key => $value) {
  306.                 $key === 'MULTISELECT_AFFILIATES' $filtersToProcess['affiliateIds'] = $value false;
  307.                 $key === 'MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS' $filtersToProcess['affiliateManagerEmailArr'] = $value false;
  308.                 $key === 'MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS' $filtersToProcess['hyperStatuses'] = $value false;
  309.             }
  310.         }
  311.         $excludedFlagsToProcess = [];
  312. //        if (isset($excludedFlagForFilters)) {
  313. //            foreach ($excludedFlagForFilters as $key => $value) {
  314. //                $key === 'MULTISELECT_AFFILIATES' ? $excludedFlagsToProcess['excludeAffiliateIds'] = $value : false;
  315. //                $key === 'MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS' ? $excludedFlagsToProcess['excludeAffiliateManagerEmailArr'] = $value : false;
  316. //                $key === 'MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS' ? $excludedFlagsToProcess['excludeHyperStatus'] = $value : false;
  317. //            }
  318. //        }
  319.         $dateStart date('Y-m-d'strtotime($request->query->get('startDate')));
  320.         $dateEnd date('Y-m-d'strtotime($request->query->get('endDate')));
  321.         if ($request->query->get('downloadCSV') == 'true') {
  322.             $limit Config::REPORTS_PAGINATION_DEFAULT_CSV_PAGE_SIZE;
  323.             $page Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  324.         }
  325.         $finalArr $this->financialToolsComponents->getPayoutTotalAggregatedData($dateStart$dateEnd$filtersToProcess$excludedFlagsToProcess$selectedColumns$this->getUser()->getEmail());
  326.         $allowedStatuses array_values(Config::HYPER_STATUS_AFFILIATE_MAFO_MACROS);
  327.         foreach ($finalArr as &$record) {
  328.             if (!in_array($record['hyperStatus'], $allowedStatuses)) {
  329.                 $record['hyperStatus'] = '';
  330.             }
  331.         }
  332.         $tableColumns $this->commonCalls->changeColumnVisibilityForTable(array_values($this->commonCalls->getDataFromJsonFile(Config::JSON_FILE_REPORTS_FINANCIAL_REPORT)), $selectedColumns, []);
  333.         if ($request->query->get('downloadCSV') == 'true') {
  334.             $this->commonCalls->downloadCSV($tableColumns$finalArr'Financial Report ' $dateStart '_' $dateEnd);
  335.         }
  336.         return new JsonResponse($this->commonCalls->getReportResponse($finalArr$tableColumns$limit$page$sortBy$sortType));
  337.     }
  338.     /**
  339.      * @Route("/traffic-report", methods={"GET"})
  340.      */
  341.     public function getTrafficReport(Request $request)
  342.     {
  343.         ini_set('memory_limit''512M');
  344.         $affiliateData $this->getAffiliateAndManagerData();
  345.         $formattedTrafficReportArray $affiliateData['formattedTrafficReportArray'];
  346.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  347.         $mappedAccountManagerEmails $affiliateData['accountManagerEmails'];
  348.         $filtersSelected $request->query->get('filters');
  349.         $excludedFlagForFilters $request->query->get('excludedFlagForFilters') ?? [];
  350.         $filters = [];
  351.         $excludedFiltersFlags = [];
  352.         // Set $filters based on the specified condition
  353.         if (is_null($filtersSelected) && !empty(array_filter($excludedFlagForFilters))) {
  354.             $filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES'] = [];
  355.         } else {
  356.             $filtersSelected $filtersSelected ?? $formattedTrafficReportArray;
  357.         }
  358.         // Check if excludedFlagForFilters contains a true flag for MULTISELECT_AFFILIATES
  359.         if (!empty($excludedFlagForFilters['MULTISELECT_MMP_TUNE_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_MMP_TUNE_AFFILIATES'] === 'true') {
  360.             // Calculate the difference between mappedAffiliateIds and filters['MULTISELECT_AFFILIATES']
  361.             $filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES'] = array_diff($mappedAffiliateIds$filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES']);
  362.         }
  363.         // Check if MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS is present but MULTISELECT_AFFILIATES is missing
  364.         if (isset($filtersSelected['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) && !isset($filters['MULTISELECT_MMP_TUNE_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] !== 'true') {
  365.             $filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES'] = $mappedAffiliateIds;
  366.         } else if (isset($filtersSelected['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS']) && !isset($filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES']) && $excludedFlagForFilters['MULTISELECT_FINANCIAL_TOOLS_HYPER_STATUS'] !== 'true') {
  367.             $filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES'] = $mappedAffiliateIds;
  368.         }
  369.         if (
  370.             !empty($filtersSelected['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  371.             !empty($excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  372.             $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] === 'true'
  373.         ) {
  374.             $filtersSelected['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] = array_diff($mappedAccountManagerEmails$filtersSelected['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']);
  375. //            $filtersSelected = $formattedTrafficReportArray;
  376.         } else if (
  377.             empty($filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES']) &&
  378.             !empty($excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS']) &&
  379.             $excludedFlagForFilters['MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS'] === 'true'
  380.         ) {
  381.             $filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES'] = array_diff($mappedAffiliateIds$filtersSelected['MULTISELECT_MMP_TUNE_AFFILIATES']);
  382.         }
  383.         if (isset($filtersSelected)) {
  384.             foreach ($filtersSelected as $key => $value) {
  385.                 $key === Config::MULTISELECT_MMP_STATISTICS_APP $filters['appIds'] = $value false;
  386.                 $key === Config::MULTISELECT_MMP_OFFERS $filters['offers'] = $value false;
  387.                 $key === Config::MULTISELECT_MMP_SOURCE_GLOBAL_NETWORK_REPORT $filters['mmpSource'] = $value false;
  388.                 $key === Config::MULTISELECT_MMP_PARTNERS $filters['affiliates'] = $value false;
  389.                 $key === Config::MULTISELECT_MMP_MAKER_OF_OFFER_RULE_IN_MMP_OFFERS $filters['users'] = $value false;
  390.                 $key === Config::MULTISELECT_GEO $filters['geos'] = $value false;
  391.                 $key === Config::MULTISELECT_MMP_TUNE_ADVERTISERS $filters['advertiserIds'] = $value false;
  392.                 $key === Config::MULTISELECT_MMP_TUNE_AFFILIATES $filters['hoAffiliateIds'] = $value false;
  393.                 $key === Config::MULTISELECT_MMP_EVENTS $filters['events'] = $value false;
  394.                 $key === Config::MULTISELECT_MMP_TUNE_OFFERS $filters['hoOfferIds'] = $value false;
  395.                 $key === Config::MULTISELECT_ADVERTISER_MANAGER_FROM_MAFO_USERS $filters['advertiserManagerEmailIds'] = $value false;
  396.                 $key === Config::MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS $filters['affiliateManagerEmailIds'] = $value false;
  397.                 $key === Config::MULTISELECT_ADVERTISER_MOBUPPS_TEAM $filters['advertiserMobuppsTeam'] = $value false;
  398.                 $key === Config::MULTISELECT_AFFILIATE_MOBUPPS_TEAM $filters['affiliateMobuppsTeam'] = $value false;
  399.                 $key === Config::MULTISELECT_AFFILIATE_CATEGORIES $filters['affiliateCategories'] = $value false;
  400.                 $key === Config::MULTISELECT_TUNE_PIDS $filters['tunePids'] = $value false;
  401.                 $key === Config::MULTISELECT_GLOBAL_REPORT_EXCLUDE_ZERO_VALUES $filters['excludeResultsWithZeroValues'] = $value false;
  402.                 $key === Config::MULTISELECT_MMP_IS_RETARGETED $filters['isRetargeted'] = $value false;
  403.             }
  404.         }
  405.         if (isset($excludedFlagForFilters)) {
  406. //            foreach ($excludedFlagForFilters as $key => $value) {
  407. //                $value = (int)$value;
  408. //                $key === Config::MULTISELECT_MMP_STATISTICS_APP ? $excludedFiltersFlags['appIds'] = $value : false;
  409. //                $key === Config::MULTISELECT_MMP_OFFERS ? $excludedFiltersFlags['offers'] = $value : false;
  410. //                $key === Config::MULTISELECT_MMP_SOURCE_GLOBAL_NETWORK_REPORT ? $excludedFiltersFlags['mmpSource'] = $value : false;
  411. //                $key === Config::MULTISELECT_MMP_PARTNERS ? $excludedFiltersFlags['affiliates'] = $value : false;
  412. //                $key === Config::MULTISELECT_MMP_MAKER_OF_OFFER_RULE_IN_MMP_OFFERS ? $excludedFiltersFlags['users'] = $value : false;
  413. //                $key === Config::MULTISELECT_GEO ? $excludedFiltersFlags['geos'] = $value : false;
  414. //                $key === Config::MULTISELECT_MMP_TUNE_ADVERTISERS ? $excludedFiltersFlags['advertiserIds'] = $value : false;
  415. //                $key === Config::MULTISELECT_MMP_TUNE_AFFILIATES ? $excludedFiltersFlags['hoAffiliateIds'] = $value : false;
  416. //                $key === Config::MULTISELECT_MMP_EVENTS ? $excludedFiltersFlags['events'] = $value : false;
  417. //                $key === Config::MULTISELECT_MMP_TUNE_OFFERS ? $excludedFiltersFlags['hoOfferIds'] = $value : false;
  418. //                $key === Config::MULTISELECT_ADVERTISER_MANAGER_FROM_MAFO_USERS ? $excludedFiltersFlags['advertiserManagerEmailIds'] = $value : false;
  419. //                $key === Config::MULTISELECT_AFFILIATE_MANAGER_FROM_MAFO_USERS ? $excludedFiltersFlags['affiliateManagerEmailIds'] = $value : false;
  420. //                $key === Config::MULTISELECT_ADVERTISER_MOBUPPS_TEAM ? $excludedFiltersFlags['advertiserMobuppsTeam'] = $value : false;
  421. //                $key === Config::MULTISELECT_AFFILIATE_MOBUPPS_TEAM ? $excludedFiltersFlags['affiliateMobuppsTeam'] = $value : false;
  422. //                $key === Config::MULTISELECT_AFFILIATE_CATEGORIES ? $excludedFiltersFlags['affiliateCategories'] = $value : false;
  423. //                $key === Config::MULTISELECT_TUNE_PIDS ? $excludedFiltersFlags['tunePids'] = $value : false;
  424. //                $key === Config::MULTISELECT_GLOBAL_REPORT_EXCLUDE_ZERO_VALUES ? $excludedFiltersFlags['excludeResultsWithZeroValues'] = $value : false;
  425. //            }
  426.         }
  427.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  428.         $groupedColumns $request->query->get('groups') != '' $request->query->get('groups') : [];
  429.         $dateStart date('Y-m-d'strtotime($request->query->get('startDate')));
  430.         $dateEnd date('Y-m-d'strtotime($request->query->get('endDate')));
  431.         $eventTimestampFrom strtotime($dateStart);
  432.         $eventTimeStampTo strtotime($dateEnd);
  433.         $sortBy $request->query->get('sortBy') ?? Config::REPORTS_PAGINATION_MMP_REPORT_DEFAULT_SORT_BY;
  434.         $sortType $request->query->get('sortType') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_TYPE;
  435.         $page $request->query->get('page') ?? Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  436.         $limit $request->query->get('limit') ?? Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  437.         $downloadDataAsCSV $request->query->get('downloadCSV') == 'true';
  438.         $ajaxRequestTimeout $request->query->get('ajaxRequestTimeout') == 1;
  439.         $tableColumns $this->commonCalls->changeColumnVisibilityForTable(
  440.             array_values($this->commonCalls->getDataFromJsonFile(Config::JSON_FILE_GLOBAL_NETWORK_REPORT)),
  441.             $selectedColumns, []
  442.         );
  443.         $finalReportData = [];
  444.         if ($ajaxRequestTimeout) {
  445.             $this->gearmanClientInterface->doBackgroundJob('AppWorkersMmpReportsWorker~generateGlobalReportAndSendMail'json_encode([
  446.                 'reportParams' => [
  447.                     $filters,
  448.                     $excludedFiltersFlags,
  449.                     $eventTimestampFrom,
  450.                     $eventTimeStampTo,
  451.                     $selectedColumns,
  452.                     $groupedColumns
  453.                 ],
  454.                 'tableColumns' => $tableColumns,
  455.                 'sendMailTo' => $this->getUser()->getEmail(),
  456.                 'dateStart' => $dateStart,
  457.                 'dateEnd' => $dateEnd,
  458.                 'requestedAt' => date('Y-m-d H:i:s'strtotime('now'))
  459.             ]));
  460.             return new JsonResponse([
  461.                 'response' => [
  462.                     'success' => true,
  463.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  464.                     'data' => [
  465.                         'tableColumns' => $tableColumns,
  466.                         'data' => [],
  467.                         'metaData' => [
  468.                             'total' => 0,
  469.                             'limit' => (int)$limit,
  470.                             'page' => (int)$page,
  471.                             'pages' => 1,
  472.                         ]
  473.                     ],
  474.                     'error' => null
  475.                 ]
  476.             ], Config::HTTP_STATUS_CODE_OK);
  477.         } elseif (
  478.             strtotime(date('m'strtotime($request->query->get('startDate'))))
  479.             >= strtotime(date(
  480.                 'm'strtotime("-" Config::MMP_REPORTS_TABLE_DATA_MONTH_LIMIT " months")
  481.             ))) {
  482.             ini_set('mysqlnd.net_read_timeout''1');
  483.             $finalReportData $this->mmpComponents->getMmpCumulativeData(
  484.                 $filters,
  485.                 $excludedFiltersFlags,
  486.                 $eventTimestampFrom,
  487.                 $eventTimeStampTo,
  488.                 $selectedColumns,
  489.                 $groupedColumns
  490.             );
  491.         }
  492.         $finalReportData $this->mmpComponents->normalizeMmpSource($finalReportData);
  493.         foreach ($tableColumns as $key => $value) {
  494.             if (isset($value['aggregate']) && $value['aggregate'] == 'sum') {
  495.                 $num round(array_sum(array_column($finalReportData$value['accessor'])), 2);
  496.                 if ($value['category'] == 'statistics') {
  497.                     $tableColumns[$key]['Footer'] = number_format($num);
  498.                 } else {
  499.                     $tableColumns[$key]['Footer'] = number_format($num2);
  500.                 }
  501.             }
  502.         }
  503.         if ($downloadDataAsCSV) {
  504.             $this->commonCalls->downloadCSV($tableColumns$finalReportData'Traffic Report ' $dateStart '_' $dateEnd);
  505.         } else {
  506.             $finalReportData array_values($finalReportData);
  507.             if (sizeof($finalReportData)) {
  508.                 $entity $finalReportData[0];
  509.                 if (array_key_exists($sortBy$entity)) {
  510.                     $sortFlag 3;
  511.                     if ($sortType == Config::SORT_TYPE_ASC) {
  512.                         $sortFlag 4;
  513.                     }
  514.                     array_multisort(array_column($finalReportData$sortBy), $sortFlag$finalReportData);
  515.                 }
  516.             }
  517.             $offset $limit * ($page 1);
  518.             $totalRecordCount sizeof($finalReportData);
  519.             $noOfPages ceil($totalRecordCount $limit);
  520.             return new JsonResponse([
  521.                 'response' => [
  522.                     'success' => true,
  523.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  524.                     'data' => [
  525.                         'tableColumns' => $tableColumns,
  526.                         'data' => array_slice($finalReportData$offset$limit),
  527.                         'metaData' => [
  528.                             'total' => $totalRecordCount,
  529.                             'limit' => (int)$limit,
  530.                             'page' => (int)$page,
  531.                             'pages' => (int)$noOfPages,
  532.                         ]
  533.                     ],
  534.                     'error' => null
  535.                 ]
  536.             ], Config::HTTP_STATUS_CODE_OK);
  537.         }
  538.     }
  539. }