src/Controller/TuneDatabaseController.php line 2141

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Config;
  4. use App\Entity\Tune\AdvertiserInfo;
  5. use App\Entity\Tune\AffiliateAccountManager;
  6. use App\Entity\Tune\AffiliateInfo;
  7. use App\Entity\Tune\AffiliateOfferApproval;
  8. use App\Entity\AffiliateOfferBlock;
  9. use App\Entity\AffiliateRating;
  10. use App\Entity\AffiliateTagRelationship;
  11. use App\Entity\Tune\AdvertiserAccountManager;
  12. use App\Entity\Tune\AdvertiserTagRelationship;
  13. use App\Entity\AffiliateTags;
  14. use App\Entity\HoAffiliateMmpPartnerMapping;
  15. use App\Entity\MafoId\MafoAdvertisersMapping;
  16. use App\Entity\MmpPartners;
  17. use App\Entity\ObjectMappingWithTuneWebAccount;
  18. use App\Entity\OfferScheduledChanges;
  19. use App\Entity\RecommendationsByObject;
  20. use App\Entity\ScheduledDisableLinks;
  21. use App\Entity\ApprovalControl;
  22. use App\Entity\PriceBulkEdit;
  23. use App\Entity\OfferCategoryRelationship;
  24. use App\Entity\OfferCreativeFile;
  25. use App\Entity\OfferGeoRelationship;
  26. use App\Entity\OfferGoalsInfo;
  27. use App\Entity\Tune\OfferInfo;
  28. use App\Entity\OfferTagRelationship;
  29. use App\Entity\OfferWhitelist;
  30. use App\Entity\PayoutBulkEdit;
  31. use App\Entity\PostbackControlLogs;
  32. use App\Entity\ScheduledAffiliateOfferApproval;
  33. use App\Entity\ScheduledAffiliateOfferBlock;
  34. use App\Entity\ScheduledAffiliateTagOfferApproval;
  35. use App\Entity\SourceTags;
  36. use App\Entity\AffiliateOfferBlockRepository;
  37. use App\Entity\Tag;
  38. use App\Entity\UserApiKey;
  39. use App\Services\AffiliateHasofferAPI;
  40. use App\Services\Alerts;
  41. use App\Services\Aws\ElasticCache;
  42. use App\Services\Aws\S3;
  43. use App\Services\BrandHasofferAPI;
  44. use App\Services\Common;
  45. use App\Services\FinancialToolsComponents;
  46. use App\Services\HyperApis;
  47. use App\Services\ImpressionsApis;
  48. use App\Services\MafoObjectsComponents;
  49. use App\Services\Metrics24APICalls;
  50. use App\Services\MmpComponents;
  51. use App\Services\MysqlQueries;
  52. use App\Services\UsersComponents;
  53. use Doctrine\Persistence\ManagerRegistry;
  54. use Mmoreram\GearmanBundle\Service\GearmanClientInterface;
  55. use PhpOffice\PhpSpreadsheet\IOFactory;
  56. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  57. use Symfony\Component\Routing\Annotation\Route;
  58. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  59. use Symfony\Component\HttpFoundation\JsonResponse;
  60. use Symfony\Component\HttpFoundation\Request;
  61. use Symfony\Component\HttpFoundation\Response;
  62. use function GuzzleHttp\Psr7\str;
  63. /**
  64.  *
  65.  * Database Navigation Tab related routes with endpoint /api/tune-database/{route}
  66.  *
  67.  * @Route("/api/tune-database", name="database_tune", host="%main_subdomain%")
  68.  */
  69. class TuneDatabaseController extends AbstractController
  70. {
  71.     private $commonCalls;
  72.     private $doctrine;
  73.     private $mysqlQueries;
  74.     private $brandHasofferApi;
  75.     private $elasticCache;
  76.     private $projectDir;
  77.     private $s3;
  78.     private $impressionsApis;
  79.     private $metrics24APICalls;
  80.     private $gearmanClientInterface;
  81.     public function __construct(Common $commonCallsManagerRegistry $doctrineMysqlQueries $mysqlQueriesBrandHasofferApi $brandHasofferApiElasticCache $elasticCacheImpressionsApis $impressionsApisstring $projectDir)
  82.     {
  83.         $this->commonCalls $commonCalls;
  84.         $this->doctrine $doctrine;
  85.         $this->mysqlQueries $mysqlQueries;
  86.         $this->brandHasofferApi $brandHasofferApi;
  87.         $this->elasticCache $elasticCache;
  88.         $this->impressionsApis $impressionsApis;
  89.         $this->projectDir $projectDir;
  90.     }
  91.     /**
  92.      * @Route("/bulk-cap", name="get_bulk_cap", methods={"GET"})
  93.      */
  94.     public function getBulCapAction(Request $request)
  95.     {
  96.         $bulkData $this->commonCalls->getBulkCapData();
  97.         $affiliateTagsForHO $this->brandHasofferApi->getAffiliateTags()['response']['data']['data'];
  98.         $affiliateTags = [];
  99.         foreach ($affiliateTagsForHO as $key => $value) {
  100.             $affiliateTags[] = [
  101.                 'value' => $key,
  102.                 'label' => $key " - " $value['Tag']['name']
  103.             ];
  104.         }
  105.         $affiliateOfferCapType = [];
  106.         foreach (Config::AFFILIATE_OFFER_CAP_TYPE as $value) {
  107.             $affiliateOfferCapType[] = [
  108.                 'value' => $value,
  109.                 'label' => str_replace("_"" "ucfirst($value))
  110.             ];
  111.         }
  112.         $response = [
  113.             'affiliateOfferCapType' => $affiliateOfferCapType,
  114.             'affiliateTags' => $affiliateTags,
  115.             'tableData' => $bulkData
  116.         ];
  117.         return new JsonResponse($response);
  118.     }
  119.     /**
  120.      * @Route("/bulk-cap", name="delete_bulk_cap", methods={"DELETE"})
  121.      */
  122.     public function deleteBulCapAction(Request $request)
  123.     {
  124.         $this->mysqlQueries->deleteFromBulkCapById($request->query->get('id'));
  125.         $response = [
  126.             'tableData' => $this->commonCalls->getBulkCapData()
  127.         ];
  128.         return new JsonResponse($response);
  129.     }
  130.     /**
  131.      * @Route("/bulk-cap", name="post_bulk_cap", methods={"POST"})
  132.      */
  133.     public function postBulCapAction(Request $request)
  134.     {
  135.         $payload json_decode($request->getContent(), true);
  136.         $affiliateTagList $payload['affiliateTagList'];
  137.         $affiliateOfferCapType $payload['affiliateOfferCapType'];
  138.         $capValue = (int)$payload['capValue'];
  139.         $offerList $payload['offerList'];
  140.         $affiliateTagArr = [];
  141.         foreach ($affiliateTagList as $key => $value) {
  142.             array_push($affiliateTagArr$value['value']);
  143.         }
  144.         $offerIdArr = [];
  145.         foreach ($offerList as $key => $value) {
  146.             array_push($offerIdArr$value['value']);
  147.         }
  148.         $affiliateOfferCapArr = [];
  149.         foreach ($affiliateOfferCapType as $key => $value) {
  150.             array_push($affiliateOfferCapArr$value['value']);
  151.         }
  152.         //        $offerInfoArr = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
  153.         $offerInfoArr $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
  154.         $affiliateTagArr $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagArr)['response']['data']['data'];
  155.         foreach ($offerInfoArr as $key => $value) {
  156.             foreach ($affiliateTagArr as $tagId => $v) {
  157.                 foreach ($affiliateOfferCapArr as $capType) {
  158.                     $combinationExist $this->mysqlQueries->getOfferIdAffiliateTagIdFromBulkCap($value['offerId'], $tagId$capType);
  159.                     if ($combinationExist) {
  160.                         $this->mysqlQueries->deleteFromBulkCapById($combinationExist->getId());
  161.                     }
  162.                     $this->mysqlQueries->insertToBulkCap($tagId$v['Tag']['name'], $capType$value['offerId'], $value['name'], $capValueucwords($this->getUser()->getName()));
  163.                 }
  164.             }
  165.         }
  166.         $response = [
  167.             'tableData' => $this->commonCalls->getBulkCapData()
  168.         ];
  169.         return new JsonResponse($response);
  170.     }
  171.     /**
  172.      * @Route("/bulk-cap-affiliate", name="get_bulk_cap_affiliate", methods={"GET"})
  173.      */
  174.     public function getBulCapByAffiliateAction(Request $request)
  175.     {
  176.         return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
  177.     }
  178.     /**
  179.      * @Route("/bulk-cap-affiliate", name="delete_bulk_cap_affiliate", methods={"DELETE"})
  180.      */
  181.     public function deleteBulCapAffiliateAction(Request $request)
  182.     {
  183.         $this->mysqlQueries->deleteBulkCapByAffiliateById($request->query->get('id'));
  184.         return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
  185.     }
  186.     /**
  187.      * @Route("/bulk-cap-affiliate", name="post_bulk_cap_affiliate", methods={"POST"})
  188.      */
  189.     public function postBulCapAffiliateAction(Request $request)
  190.     {
  191.         $payload json_decode($request->getContent(), true);
  192.         $affiliateList $payload['affiliateList'];
  193.         $affiliateOfferCapType $payload['affiliateOfferCapType'];
  194.         $capValue = (int)$payload['capValue'];
  195.         $offerList $payload['offerList'];
  196.         $offerIdArr = [];
  197.         foreach ($offerList as $key => $value) {
  198.             array_push($offerIdArr$value['value']);
  199.         }
  200.         $affiliateIdArr = [];
  201.         foreach ($affiliateList as $key => $value) {
  202.             array_push($affiliateIdArr$value['value']);
  203.         }
  204.         $affiliateOfferCapArr = [];
  205.         foreach ($affiliateOfferCapType as $key => $value) {
  206.             array_push($affiliateOfferCapArr$value['value']);
  207.         }
  208.         //        $offerInfoArr = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
  209.         $offerInfoArr $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
  210.         $affiliateInfoArr $this->brandHasofferApi->getAffiliateByAffiliateIdsArr($affiliateIdArr)['response']['data'];
  211.         foreach ($offerInfoArr as $key => $value) {
  212.             foreach ($affiliateInfoArr as $affiliateId => $v) {
  213.                 foreach ($affiliateOfferCapArr as $capType) {
  214.                     if ($capValue && in_array($capTypeConfig::AFFILIATE_OFFER_CAP_TYPE)) {
  215.                         $combinationExist $this->mysqlQueries->getBulkCapByAffiliate($value['offerId'], $affiliateId$capType);
  216.                         if ($combinationExist) {
  217.                             $this->mysqlQueries->deleteBulkCapByAffiliateById($combinationExist->getId());
  218.                         }
  219.                         $this->mysqlQueries->insertToBulkCapByAffiliate($affiliateId$v['Affiliate']['company'], $capType$value['offerId'], $value['name'], $capValueucwords($this->getUser()->getName()));
  220.                     }
  221.                 }
  222.             }
  223.         }
  224.         return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
  225.     }
  226.     /**
  227.      * @Route("/disable-links-added-from", name="get_disable_links_added_from", methods={"GET"})
  228.      */
  229.     public function getDisableLinkLogsAddedFrom(Request $request)
  230.     {
  231.         $addedFromArr = [];
  232.         foreach (Config::DISABLE_LINK_ADDED_FROM as $key => $value) {
  233.             $addedFromArr[] = [
  234.                 'value' => $value,
  235.                 'label' => $value
  236.             ];
  237.         }
  238.         return new JsonResponse($addedFromArr);
  239.     }
  240.     /**
  241.      * @Route("/disable-links-csv", name="get_disable_links_csv", methods={"GET"})
  242.      */
  243.     public function getDisableLinksCsvAction(Request $request)
  244.     {
  245.         $dateRange $request->query->get('dateRange') ?? null;
  246.         if ($dateRange == null) {
  247.             $dateStart null;
  248.             $dateEnd null;
  249.         } else {
  250.             $dateRangeArray explode(' - '$dateRange);
  251.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  252.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  253.         }
  254.         $queryParams $request->query->all();
  255.         $affiliateIdArray = !empty($queryParams['affiliates']) && is_string($queryParams['affiliates']) ? explode(","$queryParams['affiliates']) : [];
  256.         $offerIdArray = !empty($queryParams['offers']) && is_string($queryParams['offers']) ? explode(","$queryParams['offers']) : [];
  257.         $sourceIdArray = !empty($queryParams['sources']) && is_string($queryParams['sources']) ? explode(","$queryParams['sources']) : [];
  258.         $advertiserArray = !empty($queryParams['advertisers']) && is_string($queryParams['advertisers']) ? explode(","$queryParams['advertisers']) : [];
  259.         $addedFromArr = !empty($queryParams['addedFrom']) && is_string($queryParams['addedFrom']) ? explode(","$queryParams['addedFrom']) : [];
  260.         $disableLinkData $this->commonCalls->getDisableLinkLogs($affiliateIdArray$offerIdArray$sourceIdArray$advertiserArray$addedFromArr$dateStart$dateEnd);
  261.         $dataToExport = [];
  262.         if (!empty($disableLinkData)) {
  263.             //            $dataToExport[] = implode(",", array_keys($disableLinkData[0]));
  264.             $headers = [
  265.                 'Id',
  266.                 'Affiliate Id',
  267.                 'Affiliate Name',
  268.                 'Offer Id',
  269.                 'Offer Name',
  270.                 'Source',
  271.                 'Advertiser Id',
  272.                 'Advertiser Name',
  273.                 'Added From',
  274.                 'Date Inserted'
  275.             ];
  276.             $dataToExport[] = implode(","$headers);
  277.             foreach ($disableLinkData as $key => $value) {
  278.                 $data = [
  279.                     $value['id'],
  280.                     $value['affiliateId'],
  281.                     str_replace(","" "$value['affiliateName']),
  282.                     $value['offerId'],
  283.                     str_replace(","" "$value['offerName']),
  284.                     $value['source'],
  285.                     $value['advertiserId'],
  286.                     str_replace(","" "$value['advertiserName']),
  287.                     $value['addedFrom'],
  288.                     $value['date_inserted']
  289.                 ];
  290.                 array_push($dataToExportimplode(","$data));
  291.             }
  292.         }
  293.         $response = new Response(implode("\n"$dataToExport));
  294.         $response->headers->set('Content-Type''text/csv');
  295.         return $response;
  296.     }
  297.     /**
  298.      * @Route("/advertiser-info", name="get_advertiser_info", methods={"GET"})
  299.      */
  300.     public function getAdvertiserInfoAction(Request $request)
  301.     {
  302.         $dateRange $request->query->get('dateRange') ?? null;
  303.         if ($dateRange == null) {
  304.             $dateStart null;
  305.             $dateEnd null;
  306.         } else {
  307.             $dateRangeArray explode(' - '$dateRange);
  308.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  309.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  310.         }
  311.         $queryParams $request->query->all();
  312.         $advertiserIdArr = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(","$queryParams['advertiserIds']) : [];
  313.         $advertiserList $this->commonCalls->getAdvertisersListByStatusWithKeys();
  314.         if (empty($advertiserIdArr)) {
  315.             $advertiserIdArr array_keys($advertiserList);
  316.         }
  317.         $chooseBy $request->query->get('chooseBy');
  318.         $status 'active';
  319.         $data $this->mysqlQueries->getDataForAdvertiserOfferCountForChart($advertiserIdArr$dateStart$dateEnd$chooseBy$status);
  320.         $labels = [];
  321.         foreach ($data as $key => $value) {
  322.             $label null;
  323.             if (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_HOUR$value)) {
  324.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY] . ' ' $value[Config::ADVERTISER_INFO_CHOOSE_BY_HOUR] . ':00:00';
  325.             } elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_DAY$value)) {
  326.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY];
  327.             } elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_MONTH$value)) {
  328.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH];
  329.             }
  330.             $timestamp strtotime($label);
  331.             $data[$key]['timestamp'] = $timestamp;
  332.             if ($label && !in_array($label$labels)) {
  333.                 $labels[$timestamp] = $label;
  334.             }
  335.         }
  336.         ksort($labels);
  337.         $temp = [];
  338.         foreach ($data as $key => $value) {
  339.             $temp[$value['advertiserId']][$value['timestamp']] = round($value['average'], 2);
  340.         }
  341.         $dataForChartTemp = [];
  342.         foreach ($temp as $key => $value) {
  343.             foreach (array_keys($labels) as $label) {
  344.                 if (array_key_exists($label$value)) {
  345.                     $dataForChartTemp[$key][$label] = $value[$label];
  346.                 } else {
  347.                     $dataForChartTemp[$key][$label] = '0';
  348.                 }
  349.             }
  350.         }
  351.         //        echo json_encode($dataForChartTemp);die;
  352.         $dataForChart = [];
  353.         foreach ($dataForChartTemp as $key => $value) {
  354.             if (!array_key_exists($key$dataForChart)) {
  355.                 $dataForChart[$key] = [
  356.                     'label' => $key,
  357.                     'backgroundColor' => 'transparent',
  358.                     'pointHoverBackgroundColor' => '#fff',
  359.                     'borderWidth' => 2,
  360.                     'data' => [],
  361.                     'lineTension' => 0,
  362.                     'pointRadius' => 1,
  363.                     'borderColor' => '#' str_pad(dechex(mt_rand(00xFFFFFF)), 6'0'STR_PAD_LEFT)
  364.                 ];
  365.             }
  366.             $dataForChart[$key]['data'] = array_values($value);
  367.         }
  368.         $finalLabels = [];
  369.         foreach ($labels as $timestamp => $datetime) {
  370.             if ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_HOUR) {
  371.                 array_push($finalLabelsdate('H'strtotime($datetime)));
  372.             } elseif ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_DAY) {
  373.                 array_push($finalLabelsdate('d'strtotime($datetime)));
  374.             } elseif ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_MONTH) {
  375.                 array_push($finalLabelsdate('m'strtotime($datetime)));
  376.             } else {
  377.                 array_push($finalLabelsdate('H'strtotime($datetime)));
  378.             }
  379.         }
  380.         return new JsonResponse([
  381.             'labels' => array_values($finalLabels),
  382.             'datasets' => array_values($dataForChart)
  383.         ]);
  384.     }
  385.     /**
  386.      * @Route("/advertiser-info-csv", name="advertiser_info_csv", methods={"GET"})
  387.      */
  388.     public function getAdvertiserInfoCsvAction(Request $request)
  389.     {
  390.         $dateRange $request->query->get('dateRange') ?? null;
  391.         if ($dateRange == null) {
  392.             $dateStart null;
  393.             $dateEnd null;
  394.         } else {
  395.             $dateRangeArray explode(' - '$dateRange);
  396.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  397.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  398.         }
  399.         $queryParams $request->query->all();
  400.         $advertiserIdArr = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(","$queryParams['advertiserIds']) : [];
  401.         $advertiserList $this->commonCalls->getAdvertisersListByStatusWithKeys();
  402.         if (empty($advertiserIdArr)) {
  403.             $advertiserIdArr array_keys($advertiserList);
  404.         }
  405.         $chooseBy $request->query->get('chooseBy');
  406.         $status 'active';
  407.         $data $this->mysqlQueries->getDataForAdvertiserOfferCountForChart($advertiserIdArr$dateStart$dateEnd$chooseBy$status);
  408.         $labels = [];
  409.         $timestampsByAdvertiserId = [];
  410.         foreach ($data as $key => $value) {
  411.             $label null;
  412.             if (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_HOUR$value)) {
  413.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY] . ' ' $value[Config::ADVERTISER_INFO_CHOOSE_BY_HOUR] . ':00:00';
  414.             } elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_DAY$value)) {
  415.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY];
  416.             } elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_MONTH$value)) {
  417.                 $label $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH];
  418.             }
  419.             $timestamp strtotime($label);
  420.             $data[$key]['timestamp'] = $timestamp;
  421.             if ($label && !in_array($label$labels)) {
  422.                 $labels[$timestamp] = $label;
  423.                 $timestampsByAdvertiserId[$value['advertiserId']][] = $timestamp;
  424.             }
  425.         }
  426.         $temp = [];
  427.         foreach ($data as $key => $value) {
  428.             $temp[$value['advertiserId']][$value['timestamp']] = $value['average'];
  429.         }
  430.         ksort($labels);
  431.         $dataForCsv = [];
  432.         foreach ($temp as $key => $value) {
  433.             foreach (array_keys($labels) as $label) {
  434.                 if (array_key_exists($label$value)) {
  435.                     $dataForCsv[$key][$label] = $value[$label];
  436.                 } else {
  437.                     $dataForCsv[$key][$label] = '0';
  438.                 }
  439.             }
  440.         }
  441.         $labelsToDatetime array_values($labels);
  442.         $dataToExport = [];
  443.         if (!empty($dataForCsv)) {
  444.             $headers array_merge([""], $labelsToDatetime);
  445.             $dataToExport[] = implode(","$headers);
  446.             foreach ($dataForCsv as $key => $value) {
  447.                 $data = [array_key_exists($key$advertiserList) ? $key ' ' str_replace(","" "$advertiserList[$key]['name']) : $key];
  448.                 foreach ($value as $k => $v) {
  449.                     array_push($dataround($v2));
  450.                 }
  451.                 array_push($dataToExportimplode(","$data));
  452.             }
  453.         }
  454.         $response = new Response(implode("\n"$dataToExport));
  455.         $response->headers->set('Content-Type''text/csv');
  456.         return $response;
  457.     }
  458.     /**
  459.      * @Route("/payout-bulk-edit", name="get_payout_bulk_edit", methods={"GET"})
  460.      */
  461.     public function getPayoutBulkEditAction(Request $request)
  462.     {
  463.         return new JsonResponse($this->getPayoutBulkEditData());
  464.     }
  465.     /**
  466.      * @Route("/payout-bulk-edit", name="post_payout_bulk_edit", methods={"POST"})
  467.      */
  468.     public function postPayoutBulkEditAction(Request $request)
  469.     {
  470.         $payload json_decode($request->getContent(), true);
  471.         $affiliateTagIds $payload['affiliateTagIds'];
  472.         $affiliateIds $payload['affiliateIds'];
  473.         $offerIds $payload['offerIds'];
  474.         $payout $payload['price'];
  475.         if (!empty($offerIds)) {
  476.             //            $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
  477.             $offerInfo $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
  478.             if (!empty($affiliateTagIds)) {
  479.                 $affiliateTagIdsInfo $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagIds)['response']['data']['data'];
  480.                 foreach ($affiliateTagIdsInfo as $affiliateTagId => $affiliateTagData) {
  481.                     foreach ($offerInfo as $key => $value) {
  482.                         $combinationExist $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->checkPayoutBulkEditExist($affiliateTagIdnull$value['offerId']);
  483.                         if ($combinationExist) {
  484.                             if ($combinationExist->getPayout() != $payout) {
  485.                                 $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->updatePayoutBulkEdit($affiliateTagIdnull$value['offerId'], $payoutucwords($this->getUser()->getName()));
  486.                             }
  487.                         } else {
  488.                             $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->insertToPayoutBulkData($affiliateTagIdnull$payoutucwords($this->getUser()->getName()), $value['offerId']);
  489.                         }
  490.                     }
  491.                 }
  492.             }
  493.             if (!empty($affiliateIds)) {
  494.                 $affiliateIdsInfo $this->brandHasofferApi->getAffiliatesByAffiliateIdArr($affiliateIds)['response']['data'];
  495.                 foreach ($affiliateIdsInfo as $affiliateId => $affiliateData) {
  496.                     foreach ($offerInfo as $key => $value) {
  497.                         $combinationExist $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->checkPayoutBulkEditExist(null$affiliateId$value['offerId']);
  498.                         if ($combinationExist) {
  499.                             if ($combinationExist->getPayout() != $payout) {
  500.                                 $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->updatePayoutBulkEdit(null$affiliateId$value['offerId'], $payoutucwords($this->getUser()->getName()));
  501.                             }
  502.                         } else {
  503.                             $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->insertToPayoutBulkData(null$affiliateId$payoutucwords($this->getUser()->getName()), $value['offerId']);
  504.                         }
  505.                     }
  506.                 }
  507.             }
  508.         }
  509.         return new JsonResponse($this->getPayoutBulkEditData());
  510.     }
  511.     /**
  512.      * @Route("/payout-bulk-edit", name="delete_payout_bulk_edit", methods={"DELETE"})
  513.      */
  514.     public function deletePayoutBulkEditAction(Request $request)
  515.     {
  516.         $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->deletePayoutBulkEditData($request->query->get('id'));
  517.         return new JsonResponse($this->getPayoutBulkEditData());
  518.     }
  519.     private function getPayoutBulkEditData()
  520.     {
  521.         $data $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->getPayoutBulkEditData();
  522.         $payoutByAffiliateTag = [];
  523.         $payoutByAffiliate = [];
  524.         $distinctOfferIds = [];
  525.         foreach ($data as $key => $value) {
  526.             if (!in_array($value['offerId'], $distinctOfferIds)) {
  527.                 array_push($distinctOfferIds$value['offerId']);
  528.             }
  529.         }
  530.         $offerInfo = [];
  531.         if (!empty($distinctOfferIds)) {
  532.             //            $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($distinctOfferIds)['response']['data'];
  533.             $offerInfo $this->commonCalls->getOfferInfoByKey($distinctOfferIds);
  534.         }
  535.         foreach ($data as $key => $value) {
  536.             if ($value['dateUpdated']) {
  537.                 $value['dateInserted'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  538.             } else {
  539.                 $value['dateInserted'] = '';
  540.             }
  541.             $value['offerName'] = array_key_exists($value['offerId'], $offerInfo) ? $offerInfo[$value['offerId']]['name'] : '';
  542.             if ($value['affiliateTagId'] && !$value['affiliateId']) {
  543.                 $payoutByAffiliateTag[] = $value;
  544.             }
  545.             if (!$value['affiliateTagId'] && $value['affiliateId']) {
  546.                 $payoutByAffiliate[] = $value;
  547.             }
  548.         }
  549.         return [
  550.             'dataByAffiliateTag' => $payoutByAffiliateTag,
  551.             'dataByAffiliate' => $payoutByAffiliate
  552.         ];
  553.     }
  554.     /**
  555.      * @Route("/aff-off-approval", name="GET_AFFILIATE_OFFER_APPROVAL", methods={"GET"})
  556.      */
  557.     public function getAffiliateOfferApproval(Request $request)
  558.     {
  559.         $queryParams $request->query->all();
  560.         $affiliateIds = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(","$queryParams['affiliateIds']) : [];
  561.         $advertiserIds = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(","$queryParams['advertiserIds']) : [];
  562.         $offerIds = !empty($queryParams['offerIds']) && is_string($queryParams['offerIds']) ? explode(","$queryParams['offerIds']) : [];
  563.         $dateRange $request->query->get('dateRange') ?? null;
  564.         if ($dateRange == null) {
  565.             $dateStart null;
  566.             $dateEnd null;
  567.         } else {
  568.             $dateRangeArray explode(' - '$dateRange);
  569.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  570.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  571.         }
  572.         $data $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->getScheduledAffiliateOfferApprovalDataByFilters($affiliateIds$offerIds$advertiserIds$dateStart$dateEnd);
  573.         foreach ($data as $key => $value) {
  574.             $data[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  575.             $data[$key]['affiliateOfferCapType'] = ucwords(str_replace("_"" "$value['affiliateOfferCapType']));
  576.         }
  577.         return new JsonResponse($data);
  578.     }
  579.     /**
  580.      * @Route("/aff-off-approval", name="DELETE_AFFILIATE_OFFER_APPROVAL", methods={"DELETE"})
  581.      */
  582.     public function deleteAffiliateOfferApproval(Request $request)
  583.     {
  584.         $id $request->query->get('id');
  585.         $approvedData $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->getDataById($id);
  586.         $affiliateOfferApprovedCombinations $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkCombinationExistByOfferIdAffiliateId($approvedData->getOfferId(), $approvedData->getAffiliateId());
  587.         foreach ($affiliateOfferApprovedCombinations as $key => $value) {
  588.             if (!$value['isScheduled']) {
  589.                 $isOfferApproved $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($value['offerId'], $value['affiliateId']);
  590.                 if ($isOfferApproved) {
  591.                     $hoResponse $this->brandHasofferApi->setOfferApprovalForAffiliate($value['offerId'], $value['affiliateId'], Config::AFFILIATE_OFFER_APPROVAL_REJECTED_STATUS);
  592.                     if ($hoResponse['response']['status'] == 1) {
  593.                         $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($value['id']);
  594.                         $this->doctrine->getRepository(AffiliateOfferApproval::class)->deleteById($isOfferApproved->getId());
  595.                     }
  596.                 }
  597.             } else {
  598.                 $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($value['id']);
  599.             }
  600.         }
  601.         return new JsonResponse(true);
  602.     }
  603.     /**
  604.      * @Route("/aff-off-approval", name="POST_AFFILIATE_OFFER_APPROVAL", methods={"POST"})
  605.      */
  606.     public function postAffiliateOfferApproval(Request $request)
  607.     {
  608.         $payload json_decode($request->getContent(), true);
  609.         $affiliateIds $payload['affiliateIds'];
  610.         $capTypes $payload['capTypes'];
  611.         $capValue $payload['capValue'];
  612.         $offerIds $payload['offerIds'];
  613.         $affiliateInfo = [];
  614.         $offerInfo = [];
  615.         if (!empty($affiliateIds)) {
  616.             $affiliateInfo $this->brandHasofferApi->getAffiliatesByAffiliateIdArr($affiliateIds)['response']['data'];
  617.         }
  618.         if (!empty($offerIds)) {
  619.             //            $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
  620.             $offerInfo $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
  621.         }
  622.         foreach ($offerInfo as $key => $value) {
  623.             $advertiserInfo $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $value['advertiserId']]);
  624.             $advertiserCompany $advertiserInfo && $advertiserInfo->getCompany() ? $advertiserInfo->getCompany() : '';
  625.             foreach ($affiliateInfo as $k => $v) {
  626.                 if (!empty($capTypes)) {
  627.                     foreach ($capTypes as $capType) {
  628.                         if (in_array($capTypeConfig::AFFILIATE_OFFER_CAP_TYPE)) {
  629.                             $scheduledCombinationExist $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkIfOfferAffiliateCombinationExistByCapType($value['offerId'], $k$capType);
  630.                             if ($scheduledCombinationExist) {
  631.                                 $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
  632.                             }
  633.                             $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->insertToScheduledOfferApproval($k$v['Affiliate']['company'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany$capType$capValueucwords($this->getUser()->getName()));
  634.                         }
  635.                     }
  636.                 } else {
  637.                     $scheduledCombinationExist $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkIfOfferAffiliateCombinationExistByCapType($value['offerId'], $knull);
  638.                     if ($scheduledCombinationExist) {
  639.                         $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
  640.                     }
  641.                     $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->insertToScheduledOfferApproval($k$v['Affiliate']['company'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompanynullnullucwords($this->getUser()->getName()));
  642.                 }
  643.             }
  644.         }
  645.         return new JsonResponse(true);
  646.     }
  647.     /**
  648.      * @Route("/aff-tag-off-approval", name="POST_AFFILIATE_TAG_OFFER_APPROVAL", methods={"POST"})
  649.      */
  650.     public function postAffiliateTagOfferApproval(Request $request)
  651.     {
  652.         $payload json_decode($request->getContent(), true);
  653.         $affiliateTagIds $payload['affiliateTagIds'];
  654.         $capTypes $payload['capTypes'];
  655.         $capValue $payload['capValue'];
  656.         $offerIds $payload['offerIds'];
  657.         $affiliateTagInfo = [];
  658.         $offerInfo = [];
  659.         if (!empty($affiliateTagIds)) {
  660.             $affiliateTagInfo $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagIds)['response']['data']['data'];
  661.         }
  662.         if (!empty($offerIds)) {
  663.             //            $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
  664.             $offerInfo $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
  665.         }
  666.         foreach ($offerInfo as $key => $value) {
  667.             $advertiserInfo $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $value['advertiserId']]);
  668.             $advertiserCompany $advertiserInfo && $advertiserInfo->getCompany() ? $advertiserInfo->getCompany() : '';
  669.             foreach ($affiliateTagInfo as $k => $v) {
  670.                 if (!empty($capTypes)) {
  671.                     foreach ($capTypes as $capType) {
  672.                         if (in_array($capTypeConfig::AFFILIATE_OFFER_CAP_TYPE)) {
  673.                             $scheduledCombinationExist $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkIfOfferAffiliateTagCombinationExistByCapType($key$k$capType);
  674.                             if ($scheduledCombinationExist) {
  675.                                 $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
  676.                             }
  677.                             $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->insertToScheduledOfferApproval($k$v['Tag']['name'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany$capType$capValueucwords($this->getUser()->getName()));
  678.                         }
  679.                     }
  680.                 } else {
  681.                     $scheduledCombinationExist $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkIfOfferAffiliateTagCombinationExistByCapType($key$knull);
  682.                     if ($scheduledCombinationExist) {
  683.                         $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
  684.                     }
  685.                     $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->insertToScheduledOfferApproval($k$v['Tag']['name'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompanynullnullucwords($this->getUser()->getName()));
  686.                 }
  687.             }
  688.         }
  689.         return new JsonResponse(true);
  690.     }
  691.     /**
  692.      * @Route("/aff-tag-off-approval", name="GET_AFFILIATE_TAG_OFFER_APPROVAL", methods={"GET"})
  693.      */
  694.     public function getAffiliateTagOfferApproval(Request $request)
  695.     {
  696.         $queryParams $request->query->all();
  697.         $affiliateTagIds = !empty($queryParams['affiliateTagIds']) && is_string($queryParams['affiliateTagIds']) ? explode(","$queryParams['affiliateTagIds']) : [];
  698.         $advertiserIds = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(","$queryParams['advertiserIds']) : [];
  699.         $offerIds = !empty($queryParams['offerIds']) && is_string($queryParams['offerIds']) ? explode(","$queryParams['offerIds']) : [];
  700.         $dateRange $request->query->get('dateRange') ?? null;
  701.         if ($dateRange == null) {
  702.             $dateStart null;
  703.             $dateEnd null;
  704.         } else {
  705.             $dateRangeArray explode(' - '$dateRange);
  706.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  707.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  708.         }
  709.         $data $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->getScheduledAffiliateTagOfferApprovalDataByFilters($affiliateTagIds$offerIds$advertiserIds$dateStart$dateEnd);
  710.         foreach ($data as $key => $value) {
  711.             $data[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  712.             $data[$key]['affiliateTagOfferCapType'] = ucwords(str_replace("_"" "$value['affiliateTagOfferCapType']));
  713.         }
  714.         return new JsonResponse($data);
  715.     }
  716.     /**
  717.      * @Route("/aff-tag-off-approval", name="DELETE_AFFILIATE_TAG_OFFER_APPROVAL", methods={"DELETE"})
  718.      */
  719.     public function deleteAffiliateTagOfferApproval(Request $request)
  720.     {
  721.         $id $request->query->get('id');
  722.         $approvedData $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->getDataById($id);
  723.         $affiliateTagOfferApprovedCombinations $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkCombinationExistByOfferIdAffiliateTagId($approvedData->getOfferId(), $approvedData->getAffiliateTagId());
  724.         foreach ($affiliateTagOfferApprovedCombinations as $key => $value) {
  725.             if (!$value['isScheduled']) {
  726.                 $affiliatesByTagId $this->brandHasofferApi->getAffiliateTagRelation([$value['affiliateTagId']])['response']['data']['data'];
  727.                 foreach ($affiliatesByTagId as $k => $v) {
  728.                     $isOfferApproved $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($value['offerId'], $v['AffiliatesTags']['affiliate_id']);
  729.                     if ($isOfferApproved) {
  730.                         $hoResponse $this->brandHasofferApi->setOfferApprovalForAffiliate($value['offerId'], $v['AffiliatesTags']['affiliate_id'], Config::AFFILIATE_OFFER_APPROVAL_REJECTED_STATUS);
  731.                         if ($hoResponse['response']['status'] == 1) {
  732.                             $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
  733.                             $this->doctrine->getRepository(AffiliateOfferApproval::class)->deleteById($isOfferApproved->getId());
  734.                         }
  735.                     }
  736.                 }
  737.                 $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
  738.             } else {
  739.                 $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
  740.             }
  741.         }
  742.         return new JsonResponse(true);
  743.     }
  744.     /**
  745.      * @Route("/weekly-analyze", name="GET_WEEKLY_ANALYZE", methods={"GET"})
  746.      */
  747.     public function getWeeklyAnalyzeAction(Request $request)
  748.     {
  749.         $dateRangeI $request->query->get('dateRangeI') ?? null;
  750.         $dateRangeII $request->query->get('dateRangeII') ?? null;
  751.         $tuneAccounts $request->query->get('tuneAccount') ?? [];
  752.         // if ($tuneAccounts !== '') {
  753.         //     $tuneAccounts = explode(",", $tuneAccounts);
  754.         // }
  755.         if ($dateRangeI == null) {
  756.             $dateStartI null;
  757.             $dateEndI null;
  758.         } else {
  759.             $dateRangeIArray explode(' - '$dateRangeI);
  760.             $dateStartI date('Y-m-d'strtotime($dateRangeIArray[0]));
  761.             $dateEndI date('Y-m-d'strtotime('+1 day'strtotime($dateRangeIArray[1])));
  762.         }
  763.         if ($dateRangeII == null) {
  764.             $dateStartII null;
  765.             $dateEndII null;
  766.         } else {
  767.             $dateRangeIIArray explode(' - '$dateRangeII);
  768.             $dateStartII date('Y-m-d'strtotime($dateRangeIIArray[0]));
  769.             $dateEndII date('Y-m-d'strtotime('+1 day'strtotime($dateRangeIIArray[1])));
  770.         }
  771.         $advertiserIdsStr $request->query->get('advertiserIds');
  772.         $advertiserIdArr $advertiserIdsStr == "" ? [] : explode(","$advertiserIdsStr);
  773.         $advertiserIdsManagerStr $request->query->get('advertiserManagerIds');
  774.         $advertiserManagerIdArr $advertiserIdsManagerStr == "" ? [] : explode(","$advertiserIdsManagerStr);
  775.         $offerIdsStr $request->query->get('offerIds');
  776.         $offerIdArr $offerIdsStr == "" ? [] : explode(","$offerIdsStr);
  777.         $affiliateIdsStr $request->query->get('affiliateIds');
  778.         $affiliateIdArr $affiliateIdsStr == "" ? [] : explode(","$affiliateIdsStr);
  779.         $affiliateIdsManagerStr $request->query->get('affiliateManagerIds');
  780.         $affiliateManagerIdArr $affiliateIdsManagerStr == "" ? [] : explode(","$affiliateIdsManagerStr);
  781.         $byAdvertiser $request->query->get('byAdvertiser')  ? true false;
  782.         $byAffiliate $request->query->get('byAffiliate')  ? true false;
  783.         $byOffer $request->query->get('byOffer')  ? true false;
  784.         $data = ($this->getWeeklyAnalyzeData($advertiserIdArr$advertiserManagerIdArr$affiliateIdArr$affiliateManagerIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$dateStartII$dateEndII$tuneAccounts));
  785.         return new JsonResponse($data);
  786.     }
  787.     /**
  788.      * @Route("/weekly-analyze-csv", name="GET_WEEKLY_ANALYZE_CSV", methods={"GET"})
  789.      */
  790.     public function getWeeklyAnalyzeCSVAction(Request $request)
  791.     {
  792.         $dateRangeI $request->query->get('dateRangeI') ?? null;
  793.         $dateRangeII $request->query->get('dateRangeII') ?? null;
  794.         $tuneAccounts $request->query->get('tuneAccount') ?? [];
  795.         // if ($tuneAccounts !== '') {
  796.         // $tuneAccounts = explode(",", $tuneAccounts);
  797.         // }
  798.         if ($dateRangeI == null) {
  799.             $dateStartI null;
  800.             $dateEndI null;
  801.         } else {
  802.             $dateRangeIArray explode(' - '$dateRangeI);
  803.             $dateStartI date('Y-m-d'strtotime($dateRangeIArray[0]));
  804.             $dateEndI date('Y-m-d'strtotime('+1 day'strtotime($dateRangeIArray[1])));
  805.         }
  806.         if ($dateRangeII == null) {
  807.             $dateStartII null;
  808.             $dateEndII null;
  809.         } else {
  810.             $dateRangeIIArray explode(' - '$dateRangeII);
  811.             $dateStartII date('Y-m-d'strtotime($dateRangeIIArray[0]));
  812.             $dateEndII date('Y-m-d'strtotime('+1 day'strtotime($dateRangeIIArray[1])));
  813.         }
  814.         $advertiserIdsStr $request->query->get('advertiserIds');
  815.         $advertiserIdArr $advertiserIdsStr == "" ? [] : explode(","$advertiserIdsStr);
  816.         $advertiserIdsManagerStr $request->query->get('advertiserManagerIds');
  817.         $advertiserManagerIdArr $advertiserIdsManagerStr == "" ? [] : explode(","$advertiserIdsManagerStr);
  818.         $offerIdsStr $request->query->get('offerIds');
  819.         $offerIdArr $offerIdsStr == "" ? [] : explode(","$offerIdsStr);
  820.         $affiliateIdsStr $request->query->get('affiliateIds');
  821.         $affiliateIdArr $affiliateIdsStr == "" ? [] : explode(","$affiliateIdsStr);
  822.         $affiliateIdsManagerStr $request->query->get('affiliateManagerIds');
  823.         $affiliateManagerIdArr $affiliateIdsManagerStr == "" ? [] : explode(","$affiliateIdsManagerStr);
  824.         $byAdvertiser $request->query->get('byAdvertiser') == 'true' true false;
  825.         $byAffiliate $request->query->get('byAffiliate') == 'true' true false;
  826.         $byOffer $request->query->get('byOffer') == 'true' true false;
  827.         $stats $this->getWeeklyAnalyzeData($advertiserIdArr$advertiserManagerIdArr$affiliateIdArr$affiliateManagerIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$dateStartII$dateEndII$tuneAccounts);
  828.         $list = [];
  829.         if ($byAdvertiser) {
  830.             $list $this->commonCalls->getAdvertisersListByStatusWithKeys();
  831.         } elseif ($byAffiliate) {
  832.             $list $this->commonCalls->getAffiliateListByStatusWithKeys();
  833.         } elseif ($byOffer && !empty($offerIdArr)) {
  834.             //            $list = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
  835.             $list $this->commonCalls->getOfferInfoByKey($offerIdArr);
  836.         }
  837.         foreach ($stats as $key => $value) {
  838.             if (array_key_exists($value['id'], $list)) {
  839.                 if ($byAdvertiser) {
  840.                     $stats[$key]['name'] = $list[$value['id']]['name'];
  841.                 } elseif ($byAffiliate) {
  842.                     $stats[$key]['name'] = $list[$value['id']]['name'];
  843.                 } elseif ($byOffer && !empty($offerIdArr)) {
  844.                     $stats[$key]['name'] = array_key_exists($value['id'], $list) ? $list[$value['id']]['name'] : '';
  845.                 } else {
  846.                     $stats[$key]['name'] = '';
  847.                 }
  848.             } else {
  849.                 $stats[$key]['name'] = '';
  850.             }
  851.         }
  852.         $csvHeaders = [
  853.             'Id',
  854.             'Name',
  855.             'DR_I_Clicks',
  856.             'DR_I_Conversions',
  857.             'DR_I_Revenue',
  858.             'DR_I_Payout',
  859.             'DR_I_Profit',
  860.             'DR_II_Clicks',
  861.             'DR_II_Conversions',
  862.             'DR_II_Revenue',
  863.             'DR_II_Payout',
  864.             'DR_II_Profit',
  865.             'Revenue_Percent',
  866.             'Payout_Percent',
  867.             'Profit_Percent'
  868.         ];
  869.         $dataToExport = [];
  870.         array_push($dataToExportimplode(",", ['Date_Range_I'$dateStartI$dateEndI]));
  871.         array_push($dataToExportimplode(",", ['Date_Range_II'$dateStartII$dateEndII]));
  872.         array_push($dataToExportimplode(","$csvHeaders));
  873.         foreach ($stats as $key => $value) {
  874.             $temp = [
  875.                 $value['id'],
  876.                 $value['name'],
  877.                 $value['dateRangeIClicks'],
  878.                 $value['dateRangeIConversions'],
  879.                 $value['dateRangeIRevenue'],
  880.                 $value['dateRangeIPayout'],
  881.                 $value['dateRangeIProfit'],
  882.                 $value['dateRangeIIClicks'],
  883.                 $value['dateRangeIIConversions'],
  884.                 $value['dateRangeIIRevenue'],
  885.                 $value['dateRangeIIPayout'],
  886.                 $value['dateRangeIIProfit'],
  887.                 $value['payoutPercentChange'],
  888.                 $value['revenuePercentChange'],
  889.                 $value['profitPercentChange'],
  890.             ];
  891.             array_push($dataToExportimplode(","$temp));
  892.         }
  893.         $response = new Response(implode("\n"$dataToExport));
  894.         $response->headers->set('Content-Type''text/csv');
  895.         return $response;
  896.     }
  897.     private function getWeeklyAnalyzeData($advertiserIdArr$advertiserManagerIdArr$affiliateIdArr$affiliateManagerIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$dateStartII$dateEndII$tuneAccounts)
  898.     {
  899.         $stats = [];
  900.         foreach (Config::MAFO_SYSTEM_IDENTIFIER_TUNE_ACCOUNTS as $tuneAccount) {
  901.             if (!empty($tuneAccounts) && !in_array($tuneAccount$tuneAccounts)) {
  902.                 continue;
  903.             }
  904.             if ($byAdvertiser && empty($advertiserIdArr) && empty($advertiserManagerIdArr)) {
  905.                 $advertiserIdArr array_keys($this->commonCalls->getAdvertisersListByStatusWithKeys(['tuneAccount' => $tuneAccount]));
  906.             }
  907.             if ($byAffiliate && empty($affiliateIdArr) && empty($affiliateManagerIdArr)) {
  908.                 $affiliateIdArr array_keys($this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount));
  909.             }
  910.             if ($byOffer && empty($offerIdArr)) {
  911.                 $offerIdArr array_column($this->doctrine->getRepository(OfferInfo::class)->getOfferInfoByStatus(Config::ACTIVE_STATUS$tuneAccount), 'offerId');
  912.             }
  913.             $advertisersByEmployeeId = [];
  914.             if ($byAdvertiser && !empty($advertiserManagerIdArr)) {
  915.                 foreach ($advertiserManagerIdArr as $employeeId) {
  916.                     $advertisersByEmployeeIdResponse $this->brandHasofferApi->getAdvertiserIdsByEmployeeId($employeeId$tuneAccount);
  917.                     if (isset($advertisersByEmployeeIdResponse['response']['status']) && $advertisersByEmployeeIdResponse['response']['status']) {
  918.                         $advertisersByEmployeeId array_values(array_merge($advertisersByEmployeeId$advertisersByEmployeeIdResponse['response']['data']));
  919.                     }
  920.                 }
  921.             }
  922.             $affiliatesByEmployeeId = [];
  923.             if ($byAffiliate && !empty($affiliateManagerIdArr)) {
  924.                 foreach ($affiliateManagerIdArr as $employeeId) {
  925.                     $affiliatesByEmployeeIdResponse $this->brandHasofferApi->getAffiliateIdsByEmployeeId($employeeId$tuneAccount);
  926.                     if (isset($affiliatesByEmployeeIdResponse['response']['status']) && $affiliatesByEmployeeIdResponse['response']['status']) {
  927.                         $affiliatesByEmployeeId array_values(array_merge($affiliatesByEmployeeId$affiliatesByEmployeeIdResponse['response']['data']));
  928.                     }
  929.                 }
  930.             }
  931.             $advertiserIdArr array_values(array_unique(array_merge($advertiserIdArr$advertisersByEmployeeId)));
  932.             $affiliateIdArr array_values(array_unique(array_merge($affiliateIdArr$affiliatesByEmployeeId)));
  933.             if (empty($advertiserIdArr) && empty($affiliateIdArr) && empty($offerIdArr)) {
  934.                 continue;
  935.             }
  936.             if ($byAdvertiser && sizeof($advertiserIdArr) > 300) {
  937.                 $advertiserIdChunk array_chunk($advertiserIdArr300);
  938.                 $dataForWeekAnalyzeI = [];
  939.                 $dataForWeekAnalyzeII = [];
  940.                 foreach ($advertiserIdChunk as $advertiserIds) {
  941.                     $dataForWeekAnalyzeI array_merge($dataForWeekAnalyzeI$this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIds$affiliateIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$tuneAccount)['response']['data']['data']);
  942.                     $dataForWeekAnalyzeII array_merge($dataForWeekAnalyzeII$this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIds$affiliateIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartII$dateEndII$tuneAccount)['response']['data']['data']);
  943.                 }
  944.             } elseif ($byAffiliate && sizeof($affiliateIdArr) > 300) {
  945.                 $affiliateIdChunk array_chunk($affiliateIdArr300);
  946.                 $dataForWeekAnalyzeI = [];
  947.                 $dataForWeekAnalyzeII = [];
  948.                 foreach ($affiliateIdChunk as $affiliateIds) {
  949.                     $dataForWeekAnalyzeI array_merge($dataForWeekAnalyzeI$this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr$affiliateIds$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$tuneAccount)['response']['data']['data']);
  950.                     $dataForWeekAnalyzeII array_merge($dataForWeekAnalyzeII$this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr$affiliateIds$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartII$dateEndII$tuneAccount)['response']['data']['data']);
  951.                 }
  952.             } else {
  953.                 $dataForWeekAnalyzeI $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr$affiliateIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartI$dateEndI$tuneAccount)['response']['data']['data'];
  954.                 $dataForWeekAnalyzeII $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr$affiliateIdArr$offerIdArr$byAdvertiser$byAffiliate$byOffer$dateStartII$dateEndII$tuneAccount)['response']['data']['data'];
  955.             }
  956.             $uniqueIdsI = [];
  957.             $uniqueIdsII = [];
  958.             $statsByIdI = [];
  959.             $statsByIdII = [];
  960.             foreach ($dataForWeekAnalyzeI as $key => $value) {
  961.                 if (isset($value['Stat']['advertiser_id'])) {
  962.                     $value['Stat']['id'] = $value['Stat']['advertiser_id'];
  963.                 } elseif (isset($value['Stat']['affiliate_id'])) {
  964.                     $value['Stat']['id'] = $value['Stat']['affiliate_id'];
  965.                 } elseif (isset($value['Stat']['offer_id'])) {
  966.                     $value['Stat']['id'] = $value['Stat']['offer_id'];
  967.                 } else {
  968.                     continue;
  969.                 }
  970.                 if (!in_array($value['Stat']['id'], $uniqueIdsI)) {
  971.                     array_push($uniqueIdsI$value['Stat']['id']);
  972.                 }
  973.                 $statsByIdI[$value['Stat']['id']] = $value['Stat'];
  974.             }
  975.             foreach ($dataForWeekAnalyzeII as $key => $value) {
  976.                 if (isset($value['Stat']['advertiser_id'])) {
  977.                     $value['Stat']['id'] = $value['Stat']['advertiser_id'];
  978.                 } elseif (isset($value['Stat']['affiliate_id'])) {
  979.                     $value['Stat']['id'] = $value['Stat']['affiliate_id'];
  980.                 } elseif (isset($value['Stat']['offer_id'])) {
  981.                     $value['Stat']['id'] = $value['Stat']['offer_id'];
  982.                 } else {
  983.                     continue;
  984.                 }
  985.                 if (!in_array($value['Stat']['id'], $uniqueIdsII)) {
  986.                     array_push($uniqueIdsII$value['Stat']['id']);
  987.                 }
  988.                 $statsByIdII[$value['Stat']['id']] = $value['Stat'];
  989.             }
  990.             $uniqueIds array_values(array_unique(array_merge($uniqueIdsI$uniqueIdsII)));
  991.             $entitiesByIndex = [];
  992.             if ($byOffer) {
  993.                 $offerInfoArr $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($uniqueIds$tuneAccount);
  994.                 foreach ($offerInfoArr as $offerInfo) {
  995.                     $entitiesByIndex[$offerInfo['offerId'] . '_' $tuneAccount] = [
  996.                         'name' => $offerInfo['name'],
  997.                         'mafoId' => $offerInfo['mafoId']
  998.                     ];
  999.                 }
  1000.             } else if ($byAdvertiser) {
  1001.                 $advertiserInfoArr $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserInfoByAdvertiserIdArr($uniqueIds$tuneAccount);
  1002.                 foreach ($advertiserInfoArr as $advertiserInfo) {
  1003.                     $entitiesByIndex[$advertiserInfo['advertiserId'] . '_' $tuneAccount] = [
  1004.                         'name' => $advertiserInfo['company'],
  1005.                         'mafoId' => $advertiserInfo['mafoId']
  1006.                     ];
  1007.                 }
  1008.             } else if ($byAffiliate) {
  1009.                 $affiliateInfoArr $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByAffiliateIds($uniqueIds$tuneAccount);
  1010.                 foreach ($affiliateInfoArr as $affiliateInfo) {
  1011.                     $entitiesByIndex[$affiliateInfo['affiliateId'] . '_' $tuneAccount] = [
  1012.                         'name' => $affiliateInfo['company'],
  1013.                         'mafoId' => $affiliateInfo['mafoId']
  1014.                     ];
  1015.                 }
  1016.             }
  1017.             foreach ($uniqueIds as $id) {
  1018.                 $index $id '_' $tuneAccount;
  1019.                 $stats[$index]['id'] = $id;
  1020.                 $stats[$index]['name'] = $entitiesByIndex[$index]['name'] ?? '';
  1021.                 $stats[$index]['mafoId'] = $entitiesByIndex[$index]['mafoId'] ?? '';
  1022.                 $stats[$index]['tuneAccount'] = $tuneAccount;
  1023.                 if (array_key_exists($id$statsByIdI)) {
  1024.                     $stats[$index]['dateRangeIClicks'] = $statsByIdI[$id]['clicks'];
  1025.                     $stats[$index]['dateRangeIConversions'] = $statsByIdI[$id]['conversions'];
  1026.                     $stats[$index]['dateRangeIRevenue'] = round($statsByIdI[$id]['revenue'], 2);
  1027.                     $stats[$index]['dateRangeIPayout'] = round($statsByIdI[$id]['payout'], 2);
  1028.                     $stats[$index]['dateRangeIProfit'] = round($statsByIdI[$id]['profit'], 2);
  1029.                 } else {
  1030.                     $stats[$index]['dateRangeIClicks'] = 0;
  1031.                     $stats[$index]['dateRangeIConversions'] = 0;
  1032.                     $stats[$index]['dateRangeIRevenue'] = 0;
  1033.                     $stats[$index]['dateRangeIPayout'] = 0;
  1034.                     $stats[$index]['dateRangeIProfit'] = 0;
  1035.                 }
  1036.                 if (array_key_exists($id$statsByIdII)) {
  1037.                     $stats[$index]['dateRangeIIClicks'] = $statsByIdII[$id]['clicks'];
  1038.                     $stats[$index]['dateRangeIIConversions'] = $statsByIdII[$id]['conversions'];
  1039.                     $stats[$index]['dateRangeIIRevenue'] = round($statsByIdII[$id]['revenue'], 2);
  1040.                     $stats[$index]['dateRangeIIPayout'] = round($statsByIdII[$id]['payout'], 2);
  1041.                     $stats[$index]['dateRangeIIProfit'] = round($statsByIdII[$id]['profit'], 2);
  1042.                 } else {
  1043.                     $stats[$index]['dateRangeIIClicks'] = 0;
  1044.                     $stats[$index]['dateRangeIIConversions'] = 0;
  1045.                     $stats[$index]['dateRangeIIRevenue'] = 0;
  1046.                     $stats[$index]['dateRangeIIPayout'] = 0;
  1047.                     $stats[$index]['dateRangeIIProfit'] = 0;
  1048.                 }
  1049.             }
  1050.             foreach ($stats as $key => $value) {
  1051.                 if ($value['dateRangeIIPayout'] && $value['dateRangeIIPayout'] != 0) {
  1052.                     $stats[$key]['payoutPercentChange'] = round(((($value['dateRangeIIPayout'] - $value['dateRangeIPayout']) / $value['dateRangeIIPayout']) * 100), 2);
  1053.                 } else {
  1054.                     $stats[$key]['payoutPercentChange'] = 0;
  1055.                 }
  1056.                 if ($value['dateRangeIIRevenue'] && $value['dateRangeIIPayout'] != 0) {
  1057.                     $stats[$key]['revenuePercentChange'] = round(((($value['dateRangeIIRevenue'] - $value['dateRangeIRevenue']) / $value['dateRangeIIPayout']) * 100), 2);
  1058.                 } else {
  1059.                     $stats[$key]['revenuePercentChange'] = 0;
  1060.                 }
  1061.                 if ($value['dateRangeIIProfit'] && $value['dateRangeIIPayout'] != 0) {
  1062.                     $stats[$key]['profitPercentChange'] = round(((($value['dateRangeIIProfit'] - $value['dateRangeIProfit']) / $value['dateRangeIIPayout']) * 100), 2);
  1063.                 } else {
  1064.                     $stats[$key]['profitPercentChange'] = 0;
  1065.                 }
  1066.             }
  1067.         }
  1068.         return array_values($stats);
  1069.     }
  1070.     /**
  1071.      * @Route("/source-tags", name="GET_SOURCE_TAGS", methods={"GET"})
  1072.      */
  1073.     public function getSourceTagsAction(Request $request)
  1074.     {
  1075.         $sourcesTagsDbData $this->doctrine->getRepository('App\Entity\SourceTags')->getSourceTagsByIsDeleted(0);
  1076.         $sourcesTagsData = [];
  1077.         foreach ($sourcesTagsDbData as $key => $value) {
  1078.             $sourcesTagsData[$value['tagName']][$value['id']] = $value['source'];
  1079.         }
  1080.         return new JsonResponse($sourcesTagsData);
  1081.     }
  1082.     /**
  1083.      * @Route("/source-tags", name="POST_SOURCE_TAGS", methods={"POST"})
  1084.      */
  1085.     public function postSourceTagsAction(Request $request)
  1086.     {
  1087.         $payload json_decode($request->getContent(), true);
  1088.         $tagName $payload['tagName'];
  1089.         $sources $payload['sources'];
  1090.         foreach ($sources as $source) {
  1091.             $source trim($source);
  1092.             if ($source == '') {
  1093.                 continue;
  1094.             }
  1095.             $combinationExist $this->doctrine->getRepository(SourceTags::class)->checkIfSourceTagNameExist($source$tagName);
  1096.             if (!$combinationExist) {
  1097.                 $this->doctrine->getRepository(SourceTags::class)->insertToSourceTags($tagName$source0$this->getUser()->getName());
  1098.             } elseif ($combinationExist->getIsDeleted()) {
  1099.                 $this->doctrine->getRepository(SourceTags::class)->updateIsDeletedById($combinationExist->getId(), 0$this->getUser()->getName());
  1100.             }
  1101.         }
  1102.         return new JsonResponse(true);
  1103.     }
  1104.     /**
  1105.      * @Route("/source-tags/{id}", name="DELETE_SOURCE_TAGS", methods={"DELETE"})
  1106.      */
  1107.     public function deleteSourceTagsAction(Request $request$id)
  1108.     {
  1109.         $this->doctrine->getRepository(SourceTags::class)->updateIsDeletedById($id1$this->getUser()->getName());
  1110.         return new JsonResponse(true);
  1111.     }
  1112.     /**
  1113.      * @Route("/affiliate-tags", name="GET_AFFILIATE_TAGS", methods={"GET"})
  1114.      */
  1115.     public function getAffiliateTagsAction(Request $request)
  1116.     {
  1117.         $affiliateTagsDbData $this->doctrine->getRepository('App\Entity\AffiliateTags')->getAffiliateTagsByIsDeleted(0);
  1118.         $affiliateTagsData = [];
  1119.         foreach ($affiliateTagsDbData as $key => $value) {
  1120.             $affiliateTagsData[$value['tagName']][$value['id']] = $value['affiliateId'];
  1121.         }
  1122.         return new JsonResponse($affiliateTagsData);
  1123.     }
  1124.     /**
  1125.      * @Route("/affiliate-tags", name="POST_AFFILIATE_TAGS", methods={"POST"})
  1126.      */
  1127.     public function postAffiliateTagsAction(Request $request)
  1128.     {
  1129.         $payload json_decode($request->getContent(), true);
  1130.         $tagName $payload['tagName'];
  1131.         $affiliates $payload['affiliates'];
  1132.         foreach ($affiliates as $affiliate) {
  1133.             $affiliate trim($affiliate);
  1134.             if ($affiliate == '') {
  1135.                 continue;
  1136.             }
  1137.             $combinationExist $this->doctrine->getRepository(AffiliateTags::class)->checkIfAffiliateTagNameExist($affiliate$tagName);
  1138.             if (!$combinationExist) {
  1139.                 $this->doctrine->getRepository(AffiliateTags::class)->insertToAffiliateTags($tagName$affiliate0$this->getUser()->getName());
  1140.             } elseif ($combinationExist->getIsDeleted()) {
  1141.                 $this->doctrine->getRepository(AffiliateTags::class)->updateIsDeletedById($combinationExist->getId(), 0$this->getUser()->getName());
  1142.             }
  1143.         }
  1144.         return new JsonResponse(true);
  1145.     }
  1146.     /**
  1147.      * @Route("/affiliate-tags/{id}", name="DELETE_AFFILIATE_TAGS", methods={"DELETE"})
  1148.      */
  1149.     public function deleteAffiliateTagsAction(Request $request$id)
  1150.     {
  1151.         $this->doctrine->getRepository(AffiliateTags::class)->updateIsDeletedById($id1$this->getUser()->getName());
  1152.         return new JsonResponse(true);
  1153.     }
  1154.     /**
  1155.      * @Route("/affiliate-ho-mmp-mapping", name="get_affiliate_ho_mmp_mapping", methods={"GET"})
  1156.      */
  1157.     public function getAffiliateHoMmpMappingAction(Request $request)
  1158.     {
  1159.         $hoAffiliateId $request->query->get('hoAffiliateId');
  1160.         $tuneAccount $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1161.         $mappedData $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByTuneAffiliateId($hoAffiliateId$tuneAccount);
  1162.         $mafoUsers $this->commonCalls->getMafoUsersWithEmailIdAsKey();
  1163.         $data = [];
  1164.         foreach ($mappedData as $key => $value) {
  1165.             $data[] = [
  1166.                 'id' => $value['id'],
  1167.                 'hoAffiliateId' => $value['hoAffiliateId'],
  1168.                 'addedBy' => array_key_exists($value['addedByEmail'], $mafoUsers) ? $mafoUsers[$value['addedByEmail']]['name'] : $value['addedByEmail'],
  1169.                 'mmpPartnerId' => $value['mmpPartnerId'],
  1170.                 'mmpPartnerSource' => Config::MMP_TRACKING_SYSTEM_PRETTY[$value['mmpPartnerSource']]
  1171.             ];
  1172.         }
  1173.         return new JsonResponse($data);
  1174.     }
  1175.     /**
  1176.      * @Route("/affiliate-ho-mmp-mapping/{id}", name="patch_affiliate_ho_mmp_mapping", methods={"PATCH"})
  1177.      */
  1178.     public function patchAffiliateHoMmpMappingAction(Request $request$id)
  1179.     {
  1180.         $payload json_decode($request->getContent(), true);
  1181.         $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->updateHoAffiliateMmpPartnerMappingById(
  1182.             $id,
  1183.             $payload
  1184.         );
  1185.         return new JsonResponse(true);
  1186.     }
  1187.     /**
  1188.      * @Route("/affiliate-ho-mmp-mapping", name="post_affiliate_ho_mmp_mapping", methods={"POST"})
  1189.      */
  1190.     public function postAffiliateHoMmpMappingAction(Request $request)
  1191.     {
  1192.         $payload json_decode($request->getContent(), true);
  1193.         $hoAffiliateId $payload['hoAffiliateId'];
  1194.         $mmpPartners $payload['mmpPartners'];
  1195.         $mmpSource $payload['mmpSource'];
  1196.         $tuneAccount $payload['tuneAccount'];
  1197.         $data = [];
  1198.         foreach ($mmpPartners as $mmpPartner) {
  1199.             $data[] = [
  1200.                 'hoAffiliateId' => $hoAffiliateId,
  1201.                 'mmpPartnerId' => trim($mmpPartner['value']),
  1202.                 'mmpPartnerSource' => trim($mmpSource),
  1203.                 'tuneAccount' => $tuneAccount
  1204.             ];
  1205.         }
  1206.         $error = [];
  1207.         foreach ($data as $key => $value) {
  1208.             if (
  1209.                 $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['hoAffiliateId'], 'tuneAccount' => $value['tuneAccount']]) &&
  1210.                 array_key_exists($value['mmpPartnerSource'], Config::MMP_TRACKING_SYSTEM_PRETTY) &&
  1211.                 $value['mmpPartnerId']
  1212.             ) {
  1213.                 $combinationExists $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->findOneBy([
  1214.                     //                    'hoAffiliateId' => $value['hoAffiliateId'],
  1215.                     'mmpPartnerId' => $value['mmpPartnerId'],
  1216.                     'mmpPartnerSource' => $value['mmpPartnerSource'],
  1217.                     'tuneAccount' => $value['tuneAccount']
  1218.                 ]);
  1219.                 if (!$this->doctrine->getRepository(MmpPartners::class)->findOneBy([
  1220.                     'partner' => $value['mmpPartnerId'],
  1221.                     'mmpSource' => $value['mmpPartnerSource'],
  1222.                 ])) {
  1223.                     $this->doctrine->getRepository(MmpPartners::class)->insertToMmpPartners($value['mmpPartnerId'], $value['mmpPartnerSource'], $value['tuneAccount']);
  1224.                 }
  1225.                 if (!$combinationExists) {
  1226.                     $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->insertToHoAffiliateMmpPartnerMapping(
  1227.                         $value['hoAffiliateId'],
  1228.                         $value['mmpPartnerId'],
  1229.                         $this->getUser()->getEmail(),
  1230.                         Config::MMP_HO_AFFILIATE_ID_MMP_PARTNER_ID_MAPPING_ADDED_FROM_MMP_AFFILIATE_INFO,
  1231.                         1,
  1232.                         $value['mmpPartnerSource'],
  1233.                         $value['tuneAccount']
  1234.                     );
  1235.                 } elseif (!$combinationExists->getIsMappingEnabled()) {
  1236.                     $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->updateHoAffiliateMmpPartnerMappingById(
  1237.                         $combinationExists->getId(),
  1238.                         [
  1239.                             'hoAffiliateId' => $value['hoAffiliateId'],
  1240.                             'mmpPartnerId' => $value['mmpPartnerId'],
  1241.                             'mmpPartnerSource' => $value['mmpPartnerSource'],
  1242.                             'addedByEmail' => $this->getUser()->getEmail(),
  1243.                             'addedFrom' => Config::MMP_HO_AFFILIATE_ID_MMP_PARTNER_ID_MAPPING_ADDED_FROM_MMP_AFFILIATE_INFO,
  1244.                             'isMappingEnabled' => true
  1245.                         ]
  1246.                     );
  1247.                 } else {
  1248.                     $error[] = "Partner " $combinationExists->getMmpPartnerId() . " is already assigned to Tune Affiliate Id." $combinationExists->getHoAffiliateId();
  1249.                 }
  1250.             }
  1251.         }
  1252.         if ($error) {
  1253.             $error[] = 'Please Delete above partner mapping before assigning to new Tune Affiliate.';
  1254.             return new JsonResponse($errorConfig::HTTP_STATUS_CODE_BAD_REQUEST);
  1255.         }
  1256.         return new JsonResponse(true);
  1257.     }
  1258.     /**
  1259.      * @Route("/affiliate-info", name="get_affiliate_info", methods={"GET"})
  1260.      */
  1261.     public function getAffiliateInfoAction(Request $request)
  1262.     {
  1263.         $dateRange $request->query->get('dateRange') ?? null;
  1264.         if ($dateRange == null) {
  1265.             $dateStart null;
  1266.             $dateEnd null;
  1267.         } else {
  1268.             $dateRangeArray explode(' - '$dateRange);
  1269.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  1270.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  1271.         }
  1272.         $queryParams $request->query->all();
  1273.         $affiliateIdArr = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(","$queryParams['affiliateIds']) : [];
  1274.         $affiliateList $this->commonCalls->getAffiliateListByStatusWithKeys();
  1275.         if (empty($affiliateIdArr)) {
  1276.             $affiliateIdArr array_keys($affiliateList);
  1277.         }
  1278.         $chooseBy $request->query->get('chooseBy');
  1279.         $offerCountBy $request->query->get('offerCountBy');
  1280.         $status 'active';
  1281.         #$data = $this->get( 'mysql_queries' )->getDataForAdvertiserOfferCountForChart( $affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $status );
  1282.         $data $this->mysqlQueries->getDataForAffiliateOfferCountForChart($affiliateIdArr$dateStart$dateEnd$chooseBy$offerCountBy);
  1283.         $labels = [];
  1284.         foreach ($data as $key => $value) {
  1285.             $label null;
  1286.             if (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_HOUR$value)) {
  1287.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY] . ' ' $value[Config::AFFILIATE_INFO_CHOOSE_BY_HOUR] . ':00:00';
  1288.             } elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_DAY$value)) {
  1289.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY];
  1290.             } elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_MONTH$value)) {
  1291.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH];
  1292.             }
  1293.             $timestamp strtotime($label);
  1294.             $data[$key]['timestamp'] = $timestamp;
  1295.             if ($label && !in_array($label$labels)) {
  1296.                 $labels[$timestamp] = $label;
  1297.             }
  1298.         }
  1299.         ksort($labels);
  1300.         $temp = [];
  1301.         foreach ($data as $key => $value) {
  1302.             $temp[$value['affiliateId']][$value['timestamp']] = round($value['average'], 2);
  1303.         }
  1304.         $dataForChartTemp = [];
  1305.         foreach ($temp as $key => $value) {
  1306.             foreach (array_keys($labels) as $label) {
  1307.                 if (array_key_exists($label$value)) {
  1308.                     $dataForChartTemp[$key][$label] = $value[$label];
  1309.                 } else {
  1310.                     $dataForChartTemp[$key][$label] = '0';
  1311.                 }
  1312.             }
  1313.         }
  1314.         $dataForChart = [];
  1315.         foreach ($dataForChartTemp as $key => $value) {
  1316.             if (!array_key_exists($key$dataForChart)) {
  1317.                 $dataForChart[$key] = [
  1318.                     'label' => $key,
  1319.                     'backgroundColor' => 'transparent',
  1320.                     'pointHoverBackgroundColor' => '#fff',
  1321.                     'borderWidth' => 2,
  1322.                     'data' => [],
  1323.                     'lineTension' => 0,
  1324.                     'pointRadius' => 1,
  1325.                     'borderColor' => '#' str_pad(dechex(mt_rand(00xFFFFFF)), 6'0'STR_PAD_LEFT)
  1326.                 ];
  1327.             }
  1328.             $dataForChart[$key]['data'] = array_values($value);
  1329.         }
  1330.         $finalLabels = [];
  1331.         foreach ($labels as $timestamp => $datetime) {
  1332.             if ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_HOUR) {
  1333.                 array_push($finalLabelsdate('H'strtotime($datetime)));
  1334.             } elseif ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_DAY) {
  1335.                 array_push($finalLabelsdate('d'strtotime($datetime)));
  1336.             } elseif ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_MONTH) {
  1337.                 array_push($finalLabelsdate('m'strtotime($datetime)));
  1338.             } else {
  1339.                 array_push($finalLabelsdate('H'strtotime($datetime)));
  1340.             }
  1341.         }
  1342.         return new JsonResponse([
  1343.             'labels' => array_values($finalLabels),
  1344.             'datasets' => array_values($dataForChart)
  1345.         ]);
  1346.     }
  1347.     /**
  1348.      * @Route("/affiliate-info-csv", name="affiliate_info_csv", methods={"GET"})
  1349.      */
  1350.     public function getAffiliateInfoCsvAction(Request $request)
  1351.     {
  1352.         $dateRange $request->query->get('dateRange') ?? null;
  1353.         if ($dateRange == null) {
  1354.             $dateStart null;
  1355.             $dateEnd null;
  1356.         } else {
  1357.             $dateRangeArray explode(' - '$dateRange);
  1358.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  1359.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  1360.         }
  1361.         $queryParams $request->query->all();
  1362.         $affiliateIdArr = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(","$queryParams['affiliateIds']) : [];
  1363.         $affiliateList $this->commonCalls->getAffiliateListByStatusWithKeys();
  1364.         if (empty($affiliateIdArr)) {
  1365.             $affiliateIdArr array_keys($affiliateList);
  1366.         }
  1367.         $chooseBy $request->query->get('chooseBy');
  1368.         $offerCountBy $request->query->get('offerCountBy');
  1369.         $status 'active';
  1370.         #$data = $this->get( 'mysql_queries' )->getDataForAdvertiserOfferCountForChart( $affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $status );
  1371.         $data $this->mysqlQueries->getDataForAffiliateOfferCountForChart($affiliateIdArr$dateStart$dateEnd$chooseBy$offerCountBy);
  1372.         $labels = [];
  1373.         foreach ($data as $key => $value) {
  1374.             $label null;
  1375.             if (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_HOUR$value)) {
  1376.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY] . ' ' $value[Config::AFFILIATE_INFO_CHOOSE_BY_HOUR] . ':00:00';
  1377.             } elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_DAY$value)) {
  1378.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY];
  1379.             } elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_MONTH$value)) {
  1380.                 $label $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH];
  1381.             }
  1382.             $timestamp strtotime($label);
  1383.             $data[$key]['timestamp'] = $timestamp;
  1384.             if ($label && !in_array($label$labels)) {
  1385.                 $labels[$timestamp] = $label;
  1386.             }
  1387.         }
  1388.         ksort($labels);
  1389.         $temp = [];
  1390.         foreach ($data as $key => $value) {
  1391.             $temp[$value['affiliateId']][$value['timestamp']] = round($value['average'], 2);
  1392.         }
  1393.         $dataForCsv = [];
  1394.         foreach ($temp as $key => $value) {
  1395.             foreach (array_keys($labels) as $label) {
  1396.                 if (array_key_exists($label$value)) {
  1397.                     $dataForCsv[$key][$label] = $value[$label];
  1398.                 } else {
  1399.                     $dataForCsv[$key][$label] = '0';
  1400.                 }
  1401.             }
  1402.         }
  1403.         $labelsToDatetime array_values($labels);
  1404.         $dataToExport = [];
  1405.         if (!empty($dataForCsv)) {
  1406.             $headers array_merge([""], $labelsToDatetime);
  1407.             $dataToExport[] = implode(","$headers);
  1408.             foreach ($dataForCsv as $key => $value) {
  1409.                 $data = [array_key_exists($key$affiliateList) ? $key ' ' str_replace(","" "$affiliateList[$key]['name']) : $key];
  1410.                 foreach ($value as $k => $v) {
  1411.                     array_push($dataround($v2));
  1412.                 }
  1413.                 array_push($dataToExportimplode(","$data));
  1414.             }
  1415.         }
  1416.         $response = new Response(implode("\n"$dataToExport));
  1417.         $response->headers->set('Content-Type''text/csv');
  1418.         return $response;
  1419.     }
  1420.     /**
  1421.      * @Route("/fraud-flag-logs", name="post_fraud_flag_logs", methods={"POST"})
  1422.      */
  1423.     public function getFraudFlagLogs(Request $request)
  1424.     {
  1425.         $payload json_decode($request->getContent(), true);
  1426.         $dateRangeArray $payload['dateRange'] ?? null;
  1427.         if ($dateRangeArray == null) {
  1428.             $dateStart null;
  1429.             $dateEnd null;
  1430.         } else {
  1431.             $dateRangeArray explode(' - '$payload['dateRange']);
  1432.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  1433.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  1434.         }
  1435.         $affiliateIdArray $payload['affiliates'] ?? [];
  1436.         $offerIdArray $payload['offers'] ?? [];
  1437.         $advertiserArray $payload['advertisers'] ?? [];
  1438.         $fraudFlagData $this->commonCalls->getFraudFlagLogs($affiliateIdArray$offerIdArray$advertiserArray$dateStart$dateEnd);
  1439.         return new JsonResponse(array_values($fraudFlagData));
  1440.     }
  1441.     /**
  1442.      * @Route("/fraud-flag-logs", name="delete_fraud_flag_logs", methods={"DELETE"})
  1443.      */
  1444.     public function deleteFraudFlagLogsAction(Request $request)
  1445.     {
  1446.         $this->commonCalls->deleteFraudFlagLogs($request->query->get('id'));
  1447.         return new JsonResponse(true);
  1448.     }
  1449.     /**
  1450.      * @Route("/fraud-flag-logs-csv", name="get_fraud_flag_csv", methods={"GET"})
  1451.      */
  1452.     public function getFraudFlagLogsCsvAction(Request $request)
  1453.     {
  1454.         $dateRange $request->query->get('dateRange') ?? null;
  1455.         if ($dateRange == null) {
  1456.             $dateStart null;
  1457.             $dateEnd null;
  1458.         } else {
  1459.             $dateRangeArray explode(' - '$dateRange);
  1460.             $dateStart date('Y-m-d'strtotime($dateRangeArray[0]));
  1461.             $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($dateRangeArray[1])));
  1462.         }
  1463.         $queryParams $request->query->all();
  1464.         $affiliateIdArray = !empty($queryParams['affiliates']) && is_string($queryParams['affiliates']) ? explode(","$queryParams['affiliates']) : [];
  1465.         $offerIdArray = !empty($queryParams['offers']) && is_string($queryParams['offers']) ? explode(","$queryParams['offers']) : [];
  1466.         $advertiserArray = !empty($queryParams['advertisers']) && is_string($queryParams['advertisers']) ? explode(","$queryParams['advertisers']) : [];
  1467.         $fraudFlagData $this->commonCalls->getFraudFlagLogs($affiliateIdArray$offerIdArray$advertiserArray$dateStart$dateEnd);
  1468.         $dataToExport = [];
  1469.         if (!empty($fraudFlagData)) {
  1470.             $headers = [
  1471.                 'Transaction Id',
  1472.                 'Affiliate Id',
  1473.                 'Offer Id',
  1474.                 'Advertiser Id',
  1475.                 'Source',
  1476.                 'AdvSub1',
  1477.                 'Date Inserted'
  1478.             ];
  1479.             $dataToExport[] = implode(","$headers);
  1480.             foreach ($fraudFlagData as $key => $value) {
  1481.                 $data = [
  1482.                     $value['transactionId'],
  1483.                     $value['affiliateId'] . ' - ' str_replace(","" "$value['affiliateName']),
  1484.                     $value['offerId'] . ' - ' str_replace(","" "$value['offerName']),
  1485.                     $value['advertiserId'] . ' - ' str_replace(","" "$value['advertiserName']),
  1486.                     $value['source'],
  1487.                     $value['advSub1'],
  1488.                     $value['date_inserted']
  1489.                 ];
  1490.                 array_push($dataToExportimplode(","$data));
  1491.             }
  1492.         }
  1493.         $response = new Response(implode("\n"$dataToExport));
  1494.         $response->headers->set('Content-Type''text/csv');
  1495.         return $response;
  1496.     }
  1497.     /**
  1498.      * @Route("/offers/{offerId}", name="get_offer", methods={"GET"})
  1499.      */
  1500.     public function getOfferAction(Request $request$offerId)
  1501.     {
  1502.         //        $offerInfo = $this->commonCalls->populateOfferDetailsByOfferId($offerId);
  1503.         $this->commonCalls->populateDbByOfferId($offerId);
  1504.         die;
  1505.     }
  1506.     /**
  1507.      * @Route("/offers", name="get_offers", methods={"GET"})
  1508.      */
  1509.     public function getOffersAction(Request $request)
  1510.     {
  1511.         ini_set('memory_limit''512M');
  1512.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
  1513.         $page $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
  1514.         $sortBy $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
  1515.         $sortType $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
  1516.         $queryParams $request->query->all();
  1517.         $statusArr $queryParams['status'] ?? [];
  1518.         $categoriesIdArr $queryParams['categoryIds'] ?? [];
  1519.         $geoArr $queryParams['geos'] ?? [];
  1520.         $tagArr $queryParams['tags'] ?? [];
  1521.         $excludedTagArr $queryParams['excludedTags'] ?? [];
  1522.         $appIdsRequested $queryParams['appIds'] ?? [];
  1523.         $offerIds $queryParams['offerIds'] ?? [];
  1524.         $mafoOfferIds $queryParams['mafoOfferIds'] ?? [];
  1525.         $advertiserManagerIds $queryParams['advertiserManagerIds'] ?? [];
  1526.         $advertiserIds $queryParams['advertiserIds'] ?? [];
  1527.         $search $request->query->get('search') != '' $request->query->get('search') : null;
  1528.         $advancedFilters $queryParams['advancedFilters'] ?? null;
  1529.         $getGoals $request->query->get('getGoals') == 1;
  1530.         $getCreativeFiles $request->query->get('getCreativeFiles') == 1;
  1531.         $getOfferWhitelist $request->query->get('getOfferWhitelist') == 1;
  1532.         $pullOfferDataFromHo $request->query->get('pullOfferDataFromHo') == 1;
  1533.         $downloadDataAsCSV $request->query->get('csv') == 1;
  1534.         $tuneAccount $request->query->all('tuneAccount') ?? null;
  1535.         $offerType $queryParams['offerType'] ?? [];
  1536.         if ($pullOfferDataFromHo && is_array($advancedFilters) && $tuneAccount !== null) {
  1537.             $tuneAccount $tuneAccount[0];
  1538.             foreach ($advancedFilters as $key => $value) {
  1539.                 if (
  1540.                     is_array($value) && isset($value['field']) && isset($value['comparison']) && isset($value['value']) &&
  1541.                     $value['field'] == 'offerId' && $value['comparison'] == 'EQUAL_TO'
  1542.                 ) {
  1543.                     $this->commonCalls->populateDbByOfferId($value['value'], [
  1544.                         'calledFromCronJob' => false,
  1545.                         'tuneAccount' => $tuneAccount
  1546.                     ]);
  1547.                 }
  1548.             }
  1549.         }
  1550.         $offerIdsToSearch = [];
  1551.         $offersByCategory = [];
  1552.         if ($categoriesIdArr && is_array($categoriesIdArr) && sizeof($categoriesIdArr) > 0) {
  1553.             $offerCategoryData $this->doctrine->getRepository(OfferCategoryRelationship::class)->getOfferCategoryDataByCategoryIds($categoriesIdArr$tuneAccount);
  1554.             foreach ($offerCategoryData as $key => $value) {
  1555.                 if (!in_array($value['offerId'], $offersByCategory)) {
  1556.                     array_push($offersByCategory$value['offerId']);
  1557.                 }
  1558.             }
  1559.             $offerIdsToSearch = ($offersByCategory && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch$offersByCategory)) : $offersByCategory;
  1560.         }
  1561.         if ($advertiserManagerIds && is_array($advertiserManagerIds) && sizeof($advertiserManagerIds) > 0) {
  1562.             $advertiserAccountManagerData $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAccountManagerDataByIds($advertiserManagerIds$tuneAccount);
  1563.             $advertiserIdsByAccountManagerIds = [];
  1564.             foreach ($advertiserAccountManagerData as $key => $value) {
  1565.                 if (!in_array($value['advertiserId'], $advertiserIdsByAccountManagerIds)) {
  1566.                     $advertiserIdsByAccountManagerIds[] = "{$value['advertiserId']}";
  1567.                 }
  1568.             }
  1569.             $advertiserIds array_values(array_unique(array_merge($advertiserIdsByAccountManagerIds$advertiserIds)));
  1570.         }
  1571.         $offersByGeo = [];
  1572.         //        if ($geoArr && is_array($geoArr) && sizeof($geoArr) > 0) {
  1573.         //            $offerGeoData = $this->doctrine->getRepository(OfferGeoRelationship::class)->getOfferGeoDataByGeos($geoArr);
  1574.         //            foreach ($offerGeoData as $key => $value) {
  1575.         //                if (!in_array($value['offerId'], $offersByGeo)) {
  1576.         //                    array_push($offersByGeo, $value['offerId']);
  1577.         //                }
  1578.         //            }
  1579.         //            $offerIdsToSearch = ($offersByGeo && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch, $offersByGeo)) : $offersByGeo;
  1580.         //        }
  1581.         $offersByTag = [];
  1582.         if ($tagArr && is_array($tagArr) && sizeof($tagArr) > 0) {
  1583.             $offerTagData $this->doctrine->getRepository(OfferTagRelationship::class)->getOfferTagDataByTagIds($tagArr$tuneAccount);
  1584.             foreach ($offerTagData as $key => $value) {
  1585.                 if (!in_array($value['offerId'], $offersByTag)) {
  1586.                     array_push($offersByTag$value['offerId']);
  1587.                 }
  1588.             }
  1589.             $offerIdsToSearch = ($offersByTag && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch$offersByTag)) : $offersByTag;
  1590.         }
  1591.         $offersByExcludedTag = [];
  1592.         if ($excludedTagArr && is_array($excludedTagArr) && sizeof($excludedTagArr) > 0) {
  1593.             $offerTagData $this->doctrine->getRepository(OfferTagRelationship::class)->getOfferTagDataByExcludedTagIds($excludedTagArr$tuneAccount);
  1594.             foreach ($offerTagData as $key => $value) {
  1595.                 if (!in_array($value['offerId'], $offersByExcludedTag)) {
  1596.                     array_push($offersByExcludedTag$value['offerId']);
  1597.                 }
  1598.             }
  1599.             $offerIdsToSearch = ($offersByExcludedTag && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch$offersByExcludedTag)) : $offersByExcludedTag;
  1600.         }
  1601.         if ($offerIds && is_array($offerIds) && sizeof($offerIds) > 0) {
  1602.             $offerIdsToSearch array_values(array_unique(array_merge($offerIdsToSearch$offerIds)));
  1603.         }
  1604.         if (($offersByCategory || $offersByGeo || $offersByTag || $offersByExcludedTag) && !$offerIdsToSearch) {
  1605.             $offerIdsToSearch = [0];
  1606.         }
  1607.         $data $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->getOfferInfo($limit$page$sortBy$sortType$statusArr$search$advancedFilters$advertiserIds$appIdsRequested$offerIdsToSearch$geoArr$mafoOfferIds$tuneAccount$offerType);
  1608.         $finalArray $offerIds $advertiserIdsForManager $appIds $appIdsByOffer = [];
  1609.         foreach ($data as $key => $value) {
  1610.             $advertiserIdsForManager[] = $value['advertiserId'];
  1611.             $finalArray[$value['offerId']][] = $value;
  1612.             $appIdsByOffer[$value['offerId']] = ((string)$this->commonCalls->getScraper()->getAppId($value['previewUrl']));
  1613.             // Get the last added record index
  1614.             $lastIndex count($finalArray[$value['offerId']]) - 1;
  1615.             $finalArray[$value['offerId']][$lastIndex]['geoIdsJson'] = $value['geoIdsJson'] ? json_decode($value['geoIdsJson'], true) : [];
  1616.             $finalArray[$value['offerId']][$lastIndex]['categoryIdsJson'] = $value['categoryIdsJson'] ? json_decode($value['categoryIdsJson'], true) : [];
  1617.             $finalArray[$value['offerId']][$lastIndex]['tagIdsJson'] = $value['tagIdsJson'] ? json_decode($value['tagIdsJson'], true) : [];
  1618.             $finalArray[$value['offerId']][$lastIndex]['whitelistIpsJson'] = $value['whitelistIpsJson'] ? json_decode($value['whitelistIpsJson'], true) : [];
  1619.             $finalArray[$value['offerId']][$lastIndex]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  1620.             $finalArray[$value['offerId']][$lastIndex]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  1621.             $finalArray[$value['offerId']][$lastIndex]['defaultPayout'] = round($value['defaultPayout'], 2);
  1622.             $finalArray[$value['offerId']][$lastIndex]['maxPayout'] = round($value['maxPayout'], 2);
  1623.             $finalArray[$value['offerId']][$lastIndex]['isSkadNetworkApiEnabled'] = $value['isSkadNetworkApiEnabled'];
  1624.             $finalArray[$value['offerId']][$lastIndex]['skadNetworkAdjustTracker'] = $value['skadNetworkAdjustTracker'];
  1625.             $finalArray[$value['offerId']][$lastIndex]['skadNetworkBranchAffiliateIds'] = $value['skadNetworkBranchAffiliateIds'] ?? [];
  1626.             $finalArray[$value['offerId']][$lastIndex]['tuneAccount'] = $value['tuneAccount'];
  1627.             $finalArray[$value['offerId']][$lastIndex]['mafoOfferId'] = $value['mafoOfferId'];
  1628.             $finalArray[$value['offerId']][$lastIndex]['offerType'] = $value['offerType'] ? [
  1629.                 'value' => $value['offerType'],
  1630.                 'label' => array_search($value['offerType'], array_map('strtolower'Config::OFFER_TYPES)) !== false Config::OFFER_TYPES[array_search($value['offerType'], array_map('strtolower'Config::OFFER_TYPES))] : ucfirst($value['offerType'])
  1631.             ] : null;
  1632.             $finalArray[$value['offerId']][$lastIndex]['geoPretty'] = [];
  1633.             if ($finalArray[$value['offerId']][$lastIndex]['geoIdsJson']) {
  1634.                 $geosPretty = [];
  1635.                 foreach ($finalArray[$value['offerId']][$lastIndex]['geoIdsJson'] as $k => $v) {
  1636.                     $v $v === 'UK' 'GB' $v;
  1637.                     $geosPretty[] = array_key_exists($vConfig::COUNTRIES) ? Config::COUNTRIES[$v]['name'] : $v;
  1638.                 }
  1639.                 $finalArray[$value['offerId']][$lastIndex]['geoPretty'] = $geosPretty;
  1640.             }
  1641.             if ($getGoals) {
  1642.                 $finalArray[$value['offerId']][$lastIndex]['goals'] = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferId($value['offerId'], $tuneAccount);
  1643.             } else {
  1644.                 $finalArray[$value['offerId']][$lastIndex]['goals'] = [];
  1645.             }
  1646.             if ($getOfferWhitelist) {
  1647.                 $finalArray[$value['offerId']][$lastIndex]['offerWhitelist'] = $this->doctrine->getRepository(OfferWhitelist::class)->getOfferWhitelistByOfferId($value['offerId'], $tuneAccount);
  1648.             } else {
  1649.                 $finalArray[$value['offerId']][$lastIndex]['offerWhitelist'] = [];
  1650.             }
  1651.             if ($getCreativeFiles) {
  1652.                 $finalArray[$value['offerId']][$lastIndex]['creativeFiles'] = $this->doctrine->getRepository(OfferCreativeFile::class)->getCreativeFilesByOfferId($value['offerId'], $tuneAccount);
  1653.             } else {
  1654.                 $finalArray[$value['offerId']][$lastIndex]['creativeFiles'] = [];
  1655.             }
  1656.         }
  1657.         if ($downloadDataAsCSV == TRUE) {
  1658.             $appIds array_values($appIdsByOffer);
  1659.             $appInformationGroupedByAppId = array();
  1660.             $appInfoArr $this->doctrine->getRepository(\App\Entity\AppInfo::class)->getDataByAppIds($appIds);
  1661.             foreach ($appInfoArr as $key => $appInfo) {
  1662.                 $appInformationGroupedByAppId[$appInfo['appId']] = $appInfo;
  1663.             }
  1664.             $accountManagers $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAdvertiserManagerDataGroupByAdvertiserIds($advertiserIdsForManager);
  1665.             $advertiserListWithKeys $this->commonCalls->getAdvertisersListByStatusWithKeys();
  1666.             $exportableData array_values($finalArray);
  1667.             $header = ["Tune Account""Tune id""Mafo Offer Id""Offer name""Advertiser Id""Advertiser Name""Account Manager""Link to appstore""Description""Payout""Revenue""Geo""Total dailyCap""App name""Platform""Status"];
  1668.             $rows[] = $header;
  1669.             $i 0;
  1670.             foreach ($exportableData as $data) {
  1671.                 foreach ($data as $fields) {
  1672.                     $platform "";
  1673.                     $appName "";
  1674.                     $offerId $fields['offerId'];
  1675.                     if (isset($appIdsByOffer[$offerId])) {
  1676.                         $appId $appIdsByOffer[$offerId];
  1677.                         $appName = isset($appInformationGroupedByAppId[$appId]) ? $appInformationGroupedByAppId[$appId]['title'] : "";
  1678.                         $platform = isset($appInformationGroupedByAppId[$appId]) ? $appInformationGroupedByAppId[$appId]['platform'] : "";
  1679.                     }
  1680.                     $accountManager = isset($accountManagers[$fields["advertiserId"]]) ?
  1681.                         $accountManagers[$fields['advertiserId']]['firstName'] . " " $accountManagers[$fields['advertiserId']]['lastName'] . "<" $accountManagers[$fields['advertiserId']]['email'] . '>' "";
  1682.                     $advertiserName array_key_exists($fields["advertiserId"], $advertiserListWithKeys) ? $advertiserListWithKeys[$fields["advertiserId"]]['name'] : '';
  1683.                     $row = [$fields["tuneAccount"], $fields["offerId"], $fields["mafoOfferId"], $fields["name"], $fields["advertiserId"], $advertiserName$accountManager$fields["previewUrl"], $fields["description"], $fields["defaultPayout"], $fields["maxPayout"], implode(" "$fields["geoIdsJson"]), $fields["conversionCap"], $appName$platform$fields["status"]];
  1684.                     $rows[] = $row;
  1685.                     $i++;
  1686.                 }
  1687.             }
  1688.             $spreadsheet = new Spreadsheet();
  1689.             $spreadsheet->getProperties()->setCreator('MAFO')
  1690.                 ->setLastModifiedBy('MAFO')
  1691.                 ->setTitle('Offers')
  1692.                 ->setSubject('Offers')
  1693.                 ->setDescription('Searched Offers');
  1694.             $i 0;
  1695.             $spreadsheet->getActiveSheet()
  1696.                 ->fromArray(
  1697.                     $rows,
  1698.                     NULL,
  1699.                     'A1'
  1700.                 );
  1701.             header('Content-Type: application/vnd.ms-excel');
  1702.             header('Content-Disposition: attachment;filename="offers.xls"');
  1703.             header('Cache-Control: max-age=0');
  1704.             $writer IOFactory::createWriter($spreadsheet'Xls');
  1705.             $writer->save('php://output');
  1706.             exit;
  1707.         } else {
  1708.             $totalOffers 1;
  1709.             if (!$pullOfferDataFromHo) {
  1710.                 $totalOffers $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->getTotalData($statusArr$search$advancedFilters$advertiserIds$appIdsRequested$offerIdsToSearch$geoArr$mafoOfferIds$tuneAccount$offerType);
  1711.             }
  1712.             $noOfPages ceil($totalOffers $limit);
  1713.             $response["response"]["success"] = true;
  1714.             $response["response"]["httpStatus"] = 200;
  1715.             // Flatten the grouped offers array while preserving database sort order
  1716.             $flattenedData = [];
  1717.             foreach ($data as $originalRecord) {
  1718.                 $offerId $originalRecord['offerId'];
  1719.                 if (isset($finalArray[$offerId])) {
  1720.                     foreach ($finalArray[$offerId] as $offer) {
  1721.                         // Only add if this is the original record (to avoid duplicates)
  1722.                         if ($offer['id'] == $originalRecord['id']) {
  1723.                             $flattenedData[] = $offer;
  1724.                             break;
  1725.                         }
  1726.                     }
  1727.                 }
  1728.             }
  1729.             $response["response"]["data"] = [
  1730.                 "data" => $flattenedData,
  1731.                 "metaData" => [
  1732.                     "total" => $totalOffers,
  1733.                     "limit" => $limit,
  1734.                     "page" => $page,
  1735.                     "pages" => $noOfPages
  1736.                 ]
  1737.             ];
  1738.             return new JsonResponse($response);
  1739.         }
  1740.     }
  1741.     /**
  1742.      * @Route("/offers/{offerId}", name="patch_offers", methods={"PATCH"})
  1743.      */
  1744.     public function patchOffersAction(Request $request$offerId)
  1745.     {
  1746.         $payload json_decode($request->getContent(), true);
  1747.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1748.         $offerType $payload['offerType'] ?? null;
  1749.         if ($offerType && !in_array($offerTypearray_map('strtolower'Config::OFFER_TYPES))) {
  1750.             return new JsonResponse([
  1751.                 'response' => [
  1752.                     'success' => false,
  1753.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  1754.                     'data' => null,
  1755.                     'error' => ['Invalid Offer Type.']
  1756.                 ]
  1757.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  1758.         }
  1759.         foreach ($payload as $key => $value) {
  1760.             if ($value === null || $value === '') {
  1761.                 unset($payload[$key]);
  1762.             }
  1763.         }
  1764.         //        if (
  1765.         //            isset($payload['offerUrl'])
  1766.         //            && is_string($payload['offerUrl'])
  1767.         //            && !$payload['whitelistIps']
  1768.         //        ) {
  1769.         //            $payload['whitelistIps'] = $this->commonCalls->getWhitelistIPsAppsflyerOrAdjust($payload['offerUrl']);
  1770.         //        }
  1771.         $hoResponse $this->commonCalls->updateOffer($offerId$payload$payload['countries'], $payload['categories'], $payload['tags'], $payload['whitelistIps'] ?? [], $tuneAccount);
  1772.         if ($hoResponse['response']['status'] === 1) {
  1773.             return new JsonResponse([
  1774.                 'response' => [
  1775.                     'success' => true,
  1776.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  1777.                     'data' => $hoResponse['response']['data'],
  1778.                     'error' => null
  1779.                 ]
  1780.             ], Config::HTTP_STATUS_CODE_OK);
  1781.         } else {
  1782.             return new JsonResponse([
  1783.                 'response' => [
  1784.                     'success' => false,
  1785.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  1786.                     'data' => null,
  1787.                     'error' => $hoResponse['response']['errors']
  1788.                 ]
  1789.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  1790.         }
  1791.     }
  1792.     /**
  1793.      * @Route("/offers", name="post_offers", methods={"POST"})
  1794.      */
  1795.     public function postOffersAction(Request $request)
  1796.     {
  1797.         $payload json_decode($request->getContent(), true);
  1798.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1799.         $offerType $payload['offerType'] ?? null;
  1800.         if ($offerType && !in_array($offerTypearray_map('strtolower'Config::OFFER_TYPES))) {
  1801.             return new JsonResponse([
  1802.                 'response' => [
  1803.                     'success' => false,
  1804.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  1805.                     'data' => null,
  1806.                     'error' => ['Invalid Offer Type.']
  1807.                 ]
  1808.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  1809.         }
  1810.         foreach ($payload as $key => $value) {
  1811.             if ($value === null || $value === '') {
  1812.                 unset($payload[$key]);
  1813.             }
  1814.         }
  1815.         //        if (
  1816.         //            isset($payload['offerUrl'])
  1817.         //            && is_string($payload['offerUrl'])
  1818.         //            && !$payload['whitelistIps']
  1819.         //        ) {
  1820.         //            $payload['whitelistIps'] = $this->commonCalls->getWhitelistIPsAppsflyerOrAdjust($payload['offerUrl']);
  1821.         //        }
  1822.         $hoResponse $this->commonCalls->createNewOffer($payload$payload['countries'], $payload['categories'], $payload['tags'], $payload['whitelistIps'] ?? [], $tuneAccount);
  1823.         if ($hoResponse['response']['status'] === 1) {
  1824.             return new JsonResponse([
  1825.                 'response' => [
  1826.                     'success' => true,
  1827.                     'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
  1828.                     'data' => $hoResponse['response']['data'],
  1829.                     'error' => null
  1830.                 ]
  1831.             ], Config::HTTP_STATUS_CODE_CREATED);
  1832.         } else {
  1833.             return new JsonResponse([
  1834.                 'response' => [
  1835.                     'success' => false,
  1836.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  1837.                     'data' => null,
  1838.                     'error' => $hoResponse['response']['errors']
  1839.                 ]
  1840.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  1841.         }
  1842.     }
  1843.     /**
  1844.      * @Route("/offer-goals/{offerId}", name="get_offer_goals", methods={"GET"})
  1845.      */
  1846.     public function getOfferGoalsAction(Request $request$offerId)
  1847.     {
  1848.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1849.         $offerGoalData $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferId($offerId$tuneAccount);
  1850.         foreach ($offerGoalData as $key => $value) {
  1851.             $offerGoalData[$key]['defaultPayoutToDisplay'] = "{$value['defaultPayout']}' ' . (array_key_exists($value['payoutType'], Config::OFFER_GOAL_PAYOUT_TYPE_MAPPING_FOR_UI) ? Config::OFFER_GOAL_PAYOUT_TYPE_MAPPING_FOR_UI[$value['payoutType']] : '');
  1852.             $offerGoalData[$key]['maxPayoutToDisplay'] = "{$value['maxPayout']}' ' . (array_key_exists($value['revenueType'], Config::OFFER_GOAL_REVENUE_TYPE_MAPPING_FOR_UI) ? Config::OFFER_GOAL_REVENUE_TYPE_MAPPING_FOR_UI[$value['revenueType']] : '');
  1853.             $offerGoalData[$key]['protocolToDisplay'] = array_key_exists($value['protocol'], Config::CONVERSION_TRACKING_MAPPING_FOR_UI) ? Config::CONVERSION_TRACKING_MAPPING_FOR_UI[$value['protocol']] : '';
  1854.             $offerGoalData[$key]['value'] = $value['goalId'];
  1855.             $offerGoalData[$key]['label'] = $value['goalId'] . ' - ' $value['name'];
  1856.         }
  1857.         return new JsonResponse($offerGoalData);
  1858.     }
  1859.     /**
  1860.      * @Route("/offer-scheduled-changes", name="get_offer_scheduled_changes", methods={"GET"})
  1861.      */
  1862.     public function getOfferScheduledChangesAction(Request $request)
  1863.     {
  1864.         $offerId $request->query->get('offerId');
  1865.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1866.         $data $this->doctrine->getRepository(OfferScheduledChanges::class)->getOfferScheduledChangesByOfferId($offerIdConfig::DELETED_STATUS$tuneAccount);
  1867.         $users $this->commonCalls->getMafoUsersWithEmailIdAsKey();
  1868.         foreach ($data as $key => $value) {
  1869.             $data[$key]['addedByName'] = isset($users[$value['addedByEmail']]) ? $users[$value['addedByEmail']]['name'] : '';
  1870.             $data[$key]['ruleTimezonePretty'] = Config::TIMEZONES[$value['ruleTimezone']];
  1871.             $data[$key]['ruleTimezonePretty'] = Config::TIMEZONES[$value['ruleTimezone']];
  1872.             $temp = [];
  1873.             foreach ($value['daysRuleIsActive'] as $v) {
  1874.                 $temp[] = Config::DAYS_OF_WEEK[$v];
  1875.             }
  1876.             $data[$key]['daysRuleIsActivePretty'] = $temp;
  1877.         }
  1878.         return new JsonResponse($data);
  1879.     }
  1880.     /**
  1881.      * @Route("/offer-scheduled-changes/{id}", name="patch_offer_scheduled_changes", methods={"PATCH"})
  1882.      */
  1883.     public function patchOfferScheduledChangesAction(Request $request$id)
  1884.     {
  1885.         $payload json_decode($request->getContent(), true);
  1886.         $dataToUpdate = [];
  1887.         if (
  1888.             isset($payload['startTime']) &&
  1889.             isset($payload['endTime']) &&
  1890.             //            str_replace(":", "", $payload['startTime']) < str_replace(":", "", $payload['endTime']) &&
  1891.             preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/"$payload['startTime']) &&
  1892.             preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/"$payload['endTime'])
  1893.         ) {
  1894.             $dataToUpdate['startTime'] = $payload['startTime'];
  1895.             $dataToUpdate['endTime'] = $payload['endTime'];
  1896.         }
  1897.         if (isset($payload['ruleTimezone']) && array_key_exists($payload['ruleTimezone'], Config::TIMEZONES)) {
  1898.             $dataToUpdate['ruleTimezone'] = $payload['ruleTimezone'];
  1899.         }
  1900.         if (isset($payload['ruleStatueOnStart']) && in_array($payload['ruleStatueOnStart'], [Config::ACTIVE_STATUSConfig::PAUSED_STATUS])) {
  1901.             $dataToUpdate['ruleStatusOnStart'] = $payload['ruleStatusOnStart'];
  1902.         }
  1903.         if (isset($payload['ruleStatusOnEnd']) && in_array($payload['ruleStatusOnEnd'], [Config::ACTIVE_STATUSConfig::PAUSED_STATUS])) {
  1904.             $dataToUpdate['ruleStatusOnEnd'] = $payload['ruleStatusOnEnd'];
  1905.         }
  1906.         if (isset($payload['ruleStatus']) && in_array($payload['ruleStatus'], [Config::ACTIVE_STATUSConfig::PAUSED_STATUSConfig::DELETED_STATUS])) {
  1907.             $dataToUpdate['ruleStatus'] = $payload['ruleStatus'];
  1908.         }
  1909.         $dataToUpdate['addedByEmail'] = $this->getUser()->getEmail();
  1910.         $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->updateOfferScheduledChangesById(
  1911.             $id,
  1912.             $dataToUpdate
  1913.         );
  1914.         return new JsonResponse(true);
  1915.     }
  1916.     /**
  1917.      * @Route("/offer-scheduled-changes", name="post_offer_scheduled_changes", methods={"POST"})
  1918.      */
  1919.     public function postOfferScheduledChangesAction(Request $request)
  1920.     {
  1921.         $payload json_decode($request->getContent(), true);
  1922.         $ruleTimezone $payload['ruleTimezone'];
  1923.         $ruleStatusOnEnd $payload['ruleStatueOnEnd'];
  1924.         $ruleStatusOnStart $payload['ruleStatueOnStart'];
  1925.         $ruleProperty $payload['offerProperty'];
  1926.         $startTime $payload['startTime'];
  1927.         $endTime $payload['endTime'];
  1928.         $offerId $payload['offerId'];
  1929.         $daysRuleIsActive $payload['daysRuleIsActive'];
  1930.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1931.         $error null;
  1932.         //        if(str_replace(":", "", $startTime) > str_replace(":", "", $endTime)) {
  1933.         //            $error = 'Start Time cannot be greater than End Time.';
  1934.         //        }
  1935.         if (
  1936.             $this->getDoctrine()->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId]) &&
  1937.             sizeof(array_values(array_intersect(array_keys(Config::DAYS_OF_WEEK), $daysRuleIsActive))) === sizeof($daysRuleIsActive) &&
  1938.             preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/"$startTime) &&
  1939.             preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/"$endTime) &&
  1940.             //            str_replace(":", "", $startTime) < str_replace(":", "", $endTime) &&
  1941.             array_key_exists($ruleTimezoneConfig::TIMEZONES) &&
  1942.             in_array($rulePropertyConfig::OFFER_SCHEDULING_PROPERTIES) &&
  1943.             in_array($ruleStatusOnStart, [Config::ACTIVE_STATUSConfig::PAUSED_STATUS]) &&
  1944.             in_array($ruleStatusOnEnd, [Config::ACTIVE_STATUSConfig::PAUSED_STATUS]) &&
  1945.             !$error
  1946.         ) {
  1947.             $offerExists $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->getOfferScheduledChangesByOfferIdAndRuleProperty($offerId$rulePropertyConfig::DELETED_STATUS$tuneAccount);
  1948.             foreach ($offerExists as $key => $value) {
  1949.                 if (
  1950.                     sizeof(array_values(array_intersect($daysRuleIsActive$value['daysRuleIsActive'])))
  1951.                 ) {
  1952.                     $error 'Property you are saving already exist for given date/dates.';
  1953.                 }
  1954.             }
  1955.             if (!$offerExists || !$error) {
  1956.                 $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->insertToOfferScheduledChanges(
  1957.                     $offerId,
  1958.                     $startTime,
  1959.                     $endTime,
  1960.                     $ruleStatusOnStart,
  1961.                     $ruleStatusOnEnd,
  1962.                     $daysRuleIsActive,
  1963.                     $ruleProperty,
  1964.                     $ruleTimezone,
  1965.                     Config::ACTIVE_STATUS,
  1966.                     $this->getUser()->getEmail(),
  1967.                     $tuneAccount
  1968.                 );
  1969.             }
  1970.             // else {
  1971.             //
  1972.             //                $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->updateOfferScheduledChangesByOfferId(
  1973.             //                    $offerId, [
  1974.             //                        'startTime' => $startTime,
  1975.             //                        'endTime' => $endTime,
  1976.             //                        'ruleStatusOnStart' => $ruleStatusOnStart,
  1977.             //                        'ruleStatusOnEnd' => $ruleStatusOnEnd,
  1978.             ////                            'daysRuleIsActive' => $daysRuleIsActive,
  1979.             ////                            'ruleProperty' => $ruleProperty,
  1980.             //                        'ruleTimezone' => $ruleTimezone,
  1981.             //                        'ruleStatus' => Config::ACTIVE_STATUS,
  1982.             //                        'addedByEmail' => $this->getUser()->getEmail()
  1983.             //                    ]
  1984.             //                );
  1985.             //            }
  1986.         }
  1987.         if ($error) {
  1988.             return new JsonResponse($errorConfig::HTTP_STATUS_CODE_BAD_REQUEST);
  1989.         } else {
  1990.             return new JsonResponse(true);
  1991.         }
  1992.     }
  1993.     /**
  1994.      * @Route("/offer-goals", name="post_offer_goals", methods={"POST"})
  1995.      */
  1996.     public function postOfferGoalsAction(Request $request)
  1997.     {
  1998.         $payload json_decode($request->getContent(), true)['data'];
  1999.         foreach ($payload as $key => $value) {
  2000.             if ($value === null || $value === '') {
  2001.                 unset($payload[$key]);
  2002.             }
  2003.         }
  2004.         $dataToPushToHO = [];
  2005.         foreach ($payload as $key => $value) {
  2006.             $dataToPushToHO[$this->commonCalls->convertStringFromCamelCaseToSnakeCase($key)] = $value;
  2007.         }
  2008.         $hoResponse $this->commonCalls->createNewOfferGoal($dataToPushToHO);
  2009.         if ($hoResponse['response']['status'] === 1) {
  2010.             return new JsonResponse([
  2011.                 'response' => [
  2012.                     'success' => true,
  2013.                     'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
  2014.                     'data' => $hoResponse['response']['data'],
  2015.                     'error' => null
  2016.                 ]
  2017.             ], Config::HTTP_STATUS_CODE_CREATED);
  2018.         } else {
  2019.             return new JsonResponse([
  2020.                 'response' => [
  2021.                     'success' => false,
  2022.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  2023.                     'data' => null,
  2024.                     'error' => $hoResponse['response']['errors']
  2025.                 ]
  2026.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  2027.         }
  2028.     }
  2029.     /**
  2030.      * @Route("/goals/{goalId}", name="get_goal", methods={"GET"})
  2031.      */
  2032.     public function getGoalAction(Request $request$goalId)
  2033.     {
  2034.         $goalData $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalInfoByGoalId($goalId);
  2035.         $goalData['conversionTrackingMultiselectValue'] = [
  2036.             'label' => Config::CONVERSION_TRACKING_MAPPING_FOR_UI[$goalData['protocol']],
  2037.             'value' => $goalData['protocol']
  2038.         ];
  2039.         return new JsonResponse([$goalId => $goalData]);
  2040.     }
  2041.     /**
  2042.      * @Route("/goals/{goalId}", name="patch_goals", methods={"PATCH"})
  2043.      */
  2044.     public function patchGoalAction(Request $request$goalId)
  2045.     {
  2046.         $payload json_decode($request->getContent(), true)['payload'];
  2047.         foreach ($payload as $key => $value) {
  2048.             if ($value === null || $value === '') {
  2049.                 unset($payload[$key]);
  2050.             }
  2051.         }
  2052.         $dataToPushToHO = [];
  2053.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2054.         unset($payload['tuneAccount']);
  2055.         foreach ($payload as $key => $value) {
  2056.             $dataToPushToHO[$this->commonCalls->convertStringFromCamelCaseToSnakeCase($key)] = $value;
  2057.         }
  2058.         $hoResponse $this->commonCalls->updateOfferGoal($goalId$dataToPushToHO$tuneAccount);
  2059.         if ($hoResponse['response']['status'] === 1) {
  2060.             return new JsonResponse([
  2061.                 'response' => [
  2062.                     'success' => true,
  2063.                     'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
  2064.                     'data' => $hoResponse['response']['data'],
  2065.                     'error' => null
  2066.                 ]
  2067.             ], Config::HTTP_STATUS_CODE_CREATED);
  2068.         } else {
  2069.             return new JsonResponse([
  2070.                 'response' => [
  2071.                     'success' => false,
  2072.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  2073.                     'data' => null,
  2074.                     'error' => $hoResponse['response']['errors']
  2075.                 ]
  2076.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  2077.         }
  2078.     }
  2079.     /**
  2080.      * @Route("/offer-creatives", name="post_offer_creatives", methods={"POST"})
  2081.      */
  2082.     public function postOfferCreativesAction(Request $request)
  2083.     {
  2084.         $files = [];
  2085.         for ($fileCount 0$fileCount $request->request->get('fileCount'); $fileCount++) {
  2086.             $files[] = $request->files->get("file_$fileCount");
  2087.         }
  2088.         $offerId $request->request->get('offerId');
  2089.         $type $request->request->get('type');
  2090.         $isPrivate $request->request->get('isPrivate');
  2091.         foreach ($files as $file) {
  2092.             $response $this->commonCalls->uploadFile($offerId$file$type$isPrivate);
  2093.             if ($response['response']['status'] == 1) {
  2094.                 $response $response['response']['data']['OfferFile'];
  2095.                 $this->doctrine->getRepository(OfferCreativeFile::class)->insertToOfferCreativeFile($response['id'], $response['offer_id'], $response['display'], $response['filename'], $response['size'], $response['status'], $response['type'], $response['width'], $response['height'], $response['code'], $response['flash_vars'], $response['interface'], $response['account_id'], $response['is_private'], $response['url'], $response['preview_uri'], $response['thumbnail']);
  2096.             }
  2097.         }
  2098.         return new JsonResponse(true);
  2099.     }
  2100.     /**
  2101.      * @Route("/offer-creative-files/{offerId}", name="delete_offer_creative_files", methods={"DELETE"})
  2102.      */
  2103.     public function deleteOfferCreativesAction(Request $request$offerId)
  2104.     {
  2105.         $offerCreativeFileData $this->doctrine->getRepository(OfferCreativeFile::class)->getCreativeFilesByOfferId($offerId);
  2106.         foreach ($offerCreativeFileData as $key => $value) {
  2107.             $hoResponse $this->brandHasofferApi->setOfferCreativeFileStatusByFileId($value['fileId'], Config::DELETED_STATUS);
  2108.             if ($hoResponse['response']['status'] == 1) {
  2109.                 $this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($value['fileId'], Config::DELETED_STATUS);
  2110.             }
  2111.         }
  2112.         return new JsonResponse(true);
  2113.     }
  2114.     /**
  2115.      * @Route("/creative-files/{fileId}", name="delete_creative_files", methods={"DELETE"})
  2116.      */
  2117.     public function deleteCreativeFileAction(Request $request$fileId)
  2118.     {
  2119.         $hoResponse $this->brandHasofferApi->setOfferCreativeFileStatusByFileId($fileIdConfig::DELETED_STATUS);
  2120.         if ($hoResponse['response']['status'] == 1) {
  2121.             $this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($fileIdConfig::DELETED_STATUS);
  2122.         }
  2123.         return new JsonResponse(true);
  2124.     }
  2125.     /**
  2126.      * @Route("/offer-whitelist/{offerId}", name="get_offer_whitelist_by_offer_id", methods={"GET"})
  2127.      */
  2128.     public function getOfferWhitelistByOfferIdAction(Request $request$offerId)
  2129.     {
  2130.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2131.         $offerWhitelistData $this->doctrine->getRepository(OfferWhitelist::class)->getOfferWhitelistByOfferId($offerId$tuneAccount);
  2132.         return new JsonResponse($offerWhitelistData);
  2133.     }
  2134.     /**
  2135.      * @Route("/offer-whitelist", name="post_offer_whitelist_by_offer_id", methods={"POST"})
  2136.      */
  2137.     public function postOfferWhitelistAction(Request $request)
  2138.     {
  2139.         $payload json_decode($request->getContent(), true);
  2140.         $offerId $payload['offerId'];
  2141.         $tuneAccount $payload['tuneAccount'];
  2142.         $contentArr $payload['content'];
  2143.         $type $payload['type'];
  2144.         $contentType $payload['contentType'];
  2145.         foreach ($contentArr as $content) {
  2146.             $data $this->brandHasofferApi->addIpWhitelistToOffer($offerId$content$contentType$type$tuneAccount);
  2147.             echo json_encode($data);
  2148.         }
  2149.         return new JsonResponse(true);
  2150.     }
  2151.     /**
  2152.      * @Route("/offer-whitelist/{offerWhitelistId}", name="delete_offer_whitelist_by_offer_id", methods={"DELETE"})
  2153.      */
  2154.     public function deleteOffer(Request $request$offerWhitelistId)
  2155.     {
  2156.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2157.         $hoResponse $this->brandHasofferApi->deleteOfferWhitelistById($offerWhitelistId$tuneAccount);
  2158.         if ($hoResponse['response']['status'] == 1) {
  2159.             $this->doctrine->getRepository(OfferWhitelist::class)->deleteByWhitelistId($offerWhitelistId$tuneAccount);
  2160.         }
  2161.         return new JsonResponse(true);
  2162.     }
  2163.     /**
  2164.      * @Route("/postback-control-logs", name="get_postback_control_logs", methods={"GET"})
  2165.      */
  2166.     public function getPostbackControlLogsAction(Request $request)
  2167.     {
  2168.         $queryParams $request->query->all();
  2169.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  2170.         $advertiserIds $queryParams['advertiserIds'] ?? [];
  2171.         $offerIds $queryParams['offerIds'] ?? [];
  2172.         $downloadCSV $request->query->get('downloadCSV');
  2173.         $dateStart date('Y-m-d'strtotime($request->query->get('dateStart')));
  2174.         $dateEnd date('Y-m-d'strtotime("+1 day"strtotime($request->query->get('dateEnd'))));
  2175.         $postbackControlData $this->doctrine->getRepository(PostbackControlLogs::class)->getPostbackControlLogs($advertiserIds$affiliateIds$offerIds$dateStart$dateEnd);
  2176.         $columnKeys = [];
  2177.         foreach ($postbackControlData as $key => $value) {
  2178.             $postbackControlData[$key]['datetime'] = $value['datetime']->format('Y-m-d H:i:s');
  2179.             $postbackControlData[$key]['sessionDatetime'] = $value['sessionDatetime']->format('Y-m-d H:i:s');
  2180.             $postbackControlData[$key]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  2181.             $columnKeys array_keys($value);
  2182.         }
  2183.         if ($downloadCSV) {
  2184.             $headers = [];
  2185.             foreach ($columnKeys as $value) {
  2186.                 array_push($headersucwords(implode(" "preg_split('/(?=[A-Z])/'$value))));
  2187.             }
  2188.             $row[] = implode(","$headers);
  2189.             foreach ($postbackControlData as $key => $value) {
  2190.                 $row[] = implode(","array_values($value));
  2191.             }
  2192.             $content implode("\n"$row);
  2193.             return new Response(
  2194.                 $content,
  2195.                 200,
  2196.                 array(
  2197.                     'Content-Type' => 'text/csv; charset=UTF-8',
  2198.                     'Content-Disposition' => 'attachment; filename="postback-control-logs.csv"'
  2199.                 )
  2200.             );
  2201.         } else {
  2202.             return new JsonResponse($postbackControlData);
  2203.         }
  2204.     }
  2205.     /**
  2206.      * @Route("/blocked-offers", name="get_blocked_offers", methods={"GET"})
  2207.      */
  2208.     public function getBlockedOffersAction(Request $request)
  2209.     {
  2210.         $queryParams $request->query->all();
  2211.         $offerIds $queryParams['offerIds'] ?? [];
  2212.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  2213.         $blockedFrom $queryParams['blockedFrom'] ?? [];
  2214.         $blockedOffersData $this->doctrine->getRepository(AffiliateOfferBlock::class)->getBlockedOffersData($offerIds$affiliateIds$blockedFrom);
  2215.         foreach ($blockedOffersData as $key => $value) {
  2216.             $blockedOffersData[$key]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  2217.             $blockedOffersData[$key]['blockedFrom'] = Config::OFFER_AFFILIATE_BLOCK_FROM_LIST[$value['blockedFrom']];
  2218.             $blockedOffersData[$key]['tuneAccount'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['trackingAccount']] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2219.         }
  2220.         return new JsonResponse($blockedOffersData);
  2221.     }
  2222.     /**
  2223.      * @Route("/approval-control-database", name="get_approval_control_database", methods={"GET"})
  2224.      */
  2225.     public function approvalControlDatabaseGetAction(Request $request)
  2226.     {
  2227.         $byAdvertiser $request->query->get('byAdvertiser');
  2228.         $byOffer $request->query->get('byOffer');
  2229.         $queryParams $request->query->all();
  2230.         $advertiserIds $queryParams['advertiserIds'] ?? [];
  2231.         $offerIds $queryParams['offerIds'] ?? [];
  2232.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  2233.         $affiliateTagIds $queryParams['affiliateTagIds'] ?? [];
  2234.         $downloadCSV $request->query->get('downloadCSV') == true;
  2235.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  2236.         $page $request->query->get('page') ? $request->query->get('page') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  2237.         $approvalControlData $this->doctrine->getRepository(ApprovalControl::class)->getPaginatedApprovalControlData($byAdvertiser$byOffer$advertiserIds$offerIds$affiliateIds$affiliateTagIds$limit$pagetrue);
  2238.         $uniqueOfferIds array_map("trim"array_values(array_unique(array_filter(array_column($approvalControlData'offerId')))));
  2239.         // $offerInfo = [];
  2240.         // if ($uniqueOfferIds) {
  2241.         //     $offerInfo = $this->commonCalls->getOfferInfoByKey($uniqueOfferIds);
  2242.         // }
  2243.         $clickCapData $this->doctrine->getRepository('App\Entity\ClickCap')->getClickCapDataByIsDeleted(0);
  2244.         $clickCapDataRefactored = [];
  2245.         foreach ($clickCapData as $key => $value) {
  2246.             $index md5($value['offerId'] . '#' $value['advertiserId'] . '#' $value['affiliateId']);
  2247.             $clickCapDataRefactored[$index][] = $value;
  2248.         }
  2249.         $arr = [];
  2250.         foreach ($approvalControlData as $key => $value) {
  2251.             $index md5($value['affiliateId'] . '#' $value['affiliateTagId'] . '#' $value['advertiserId'] . '#' $value['offerId'] . '#' $value['offerId']);
  2252.             if (!isset($arr[$index])) {
  2253.                 $arr[$index]['ids'] = [];
  2254.                 $arr[$index]['affiliateId'] = $value['affiliateId'];
  2255.                 $arr[$index]['affiliateName'] = $value['affiliateName'];
  2256.                 $arr[$index]['advertiserId'] = $value['advertiserId'];
  2257.                 $arr[$index]['advertiserName'] = $value['advertiserName'];
  2258.                 $arr[$index]['offerId'] = $value['offerId'];
  2259.                 $arr[$index]['offerName'] = $value['offerName'];
  2260.                 $arr[$index]['isProcessed'] = $value['isProcessed'];
  2261.                 $arr[$index]['affiliateTagId'] = $value['affiliateTagId'];
  2262.                 $arr[$index]['affiliateTagId'] = $value['affiliateTagId'];
  2263.                 $arr[$index]['affiliateTagName'] = $value['affiliateTagName'];
  2264.                 $arr[$index]['tuneAccount'] = $value['tuneAccount'];
  2265.                 $arr[$index]['tuneAccountPretty'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['tuneAccount']] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2266.                 $arr[$index]['addedBy'] = $value['addedBy'];
  2267.                 $arr[$index]['approvalType'] = Config::APPROVAL_CONTROL_APPROVAL_TYPE[$value['approvalType']];
  2268.                 $arr[$index]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  2269.                 $arr[$index]['caps'] = [];
  2270.                 // $arr[$index]['offerName'] = isset($offerInfo[$arr[$index]['offerId']]) ? $offerInfo[$arr[$index]['offerId']]['name'] : '';
  2271.                 $indexes = [
  2272.                     md5($value['offerId'] . '#' null '#' $value['affiliateId']),
  2273.                     md5($value['offerId'] . '#' null '#' null),
  2274.                     md5(null '#' $value['advertiserId'] . '#' null)
  2275.                 ];
  2276.                 foreach ($indexes as $indexForClickCap) {
  2277.                     if (isset($clickCapDataRefactored[$indexForClickCap])) {
  2278.                         foreach ($clickCapDataRefactored[$indexForClickCap] as $k => $v) {
  2279.                             $str ucfirst($v['blockPeriod']) . ' Click Cap By ';
  2280.                             $str .= $v['byOffer'] ? 'Offer' '';
  2281.                             $str .= $v['byAffiliate'] ? 'Affiliate' '';
  2282.                             $str .= $v['byAdvertiser'] ? 'Advertiser' '';
  2283.                             $str .= $v['byOfferByAffiliate'] ? 'Affiliate And Offer' '';
  2284.                             $arr[$index]['caps'][] = [
  2285.                                 'capType' => $str,
  2286.                                 'capValue' => $v['clickCap'],
  2287.                             ];
  2288.                         }
  2289.                     }
  2290.                 }
  2291.             }
  2292.             $arr[$index]['ids'][] = $value['id'];
  2293.             if ($value['capType']) {
  2294.                 $arr[$index]['caps'][] = [
  2295.                     'capType' => ucwords(str_replace("_"" "$value['capType'])),
  2296.                     'capValue' => $value['capValue']
  2297.                 ];
  2298.             }
  2299.         }
  2300.         if ($downloadCSV) {
  2301.             $header = [
  2302.                 'Offer Id',
  2303.                 'Advertiser Id',
  2304.                 'Affiliate Id',
  2305.                 'Affiliate Tag Id',
  2306.                 'Caps',
  2307.                 'Is Processed',
  2308.                 'Added By',
  2309.                 'Created At',
  2310.             ];
  2311.             $rows = [$header];
  2312.             foreach ($arr as $key => $value) {
  2313.                 $caps "";
  2314.                 foreach ($value['caps'] as $k => $v) {
  2315.                     $caps .= "{$v['capType']}{$v['capValue']}\n";
  2316.                 }
  2317.                 $rows[] = [
  2318.                     $value['offerId'],
  2319.                     $value['advertiserId'],
  2320.                     $value['affiliateId'],
  2321.                     $value['affiliateTagId'],
  2322.                     $caps,
  2323.                     $value['isProcessed'] ? "YES" "NO",
  2324.                     $value['addedBy'],
  2325.                     $value['dateInserted'],
  2326.                 ];
  2327.             }
  2328.             $spreadsheet = new Spreadsheet();
  2329.             $spreadsheet->getProperties()->setCreator('MAFO')
  2330.                 ->setLastModifiedBy('MAFO')
  2331.                 ->setTitle('Approval Control')
  2332.                 ->setSubject('Approval Control')
  2333.                 ->setDescription('Approval Control');
  2334.             $spreadsheet->getActiveSheet()
  2335.                 ->fromArray(
  2336.                     $rows,
  2337.                     NULL,
  2338.                     'A1'
  2339.                 );
  2340.             header('Content-Type: application/vnd.ms-excel');
  2341.             header('Content-Disposition: attachment;filename="approval control.xls"');
  2342.             header('Cache-Control: max-age=0');
  2343.             $writer IOFactory::createWriter($spreadsheet'Xls');
  2344.             $writer->save('php://output');
  2345.             exit;
  2346.         } else {
  2347.             $totalRecordCount null;
  2348.             if (!$advertiserIds && !$offerIds && !$affiliateIds && !$affiliateTagIds) {
  2349.                 if ($byOffer) {
  2350.                     $totalRecordCount $this->elasticCache->redisGet(Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_OFFER);
  2351.                 } elseif ($byAdvertiser) {
  2352.                     $totalRecordCount $this->elasticCache->redisGet(Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_ADVERTISER);
  2353.                 }
  2354.             }
  2355.             if (!$totalRecordCount || (!$advertiserIds && !$offerIds && !$affiliateIds && !$affiliateTagIds)) {
  2356.                 $totalRecordCount $this->doctrine->getRepository(ApprovalControl::class)->getPaginatedApprovalControlData($byAdvertiser$byOffer$advertiserIds$offerIds$affiliateIds$affiliateTagIds$limit$pagefalse);
  2357.             }
  2358.             $noOfPages ceil($totalRecordCount $limit);
  2359.             $response["response"]["success"] = true;
  2360.             $response["response"]["httpStatus"] = 200;
  2361.             $response["response"]["data"] = [
  2362.                 "data" => array_values($arr),
  2363.                 "metaData" => [
  2364.                     "total" => (int)$totalRecordCount,
  2365.                     "limit" => (int)$limit,
  2366.                     "page" => (int)$page,
  2367.                     "pages" => $noOfPages
  2368.                 ]
  2369.             ];
  2370.         }
  2371.         return new JsonResponse($response);
  2372.     }
  2373.     /**
  2374.      * @Route("/approval-control", name="get_approval_control", methods={"GET"})
  2375.      */
  2376.     public function approvalControlGetAction(Request $request)
  2377.     {
  2378.         $byAdvertiser $request->query->get('byAdvertiser');
  2379.         $byAdvertiserTag $request->query->get('byAdvertiserTag');
  2380.         $byOffer $request->query->get('byOffer');
  2381.         $queryParams $request->query->all();
  2382.         $advertiserTagIds $queryParams['advertiserTagIds'] ?? [];
  2383.         $advertiserIds $queryParams['advertiserIds'] ?? [];
  2384.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  2385.         $affiliateTagIds $queryParams['affiliateTagIds'] ?? [];
  2386.         $offerIds $queryParams['offerIds'] ?? [];
  2387.         $fromOfferDetailPage $request->query->get('fromOfferDetailPage');
  2388.         $downloadCSV $request->query->get('downloadCSV') == true true false;
  2389.         $downloadCSVByApproved $request->query->get('downloadCSVByApproved') == true true false;
  2390.         $downloadCSVByUnapproved $request->query->get('downloadCSVByUnapproved') == true true false;
  2391.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2392.         $dateStart $request->query->get('dateStart');
  2393.         $dateEnd $request->query->get('dateEnd');
  2394.         $dateStart = isset($dateStart) ? date('Y-m-d'strtotime($request->query->get('dateStart'))) : null;
  2395.         $dateEnd = isset($dateEnd) ? date('Y-m-d'strtotime("+1 day"strtotime($request->query->get('dateEnd')))) : null;
  2396.         $finalFinalArr $finalArr = [
  2397.             'byAdvertiser' => [],
  2398.             'byAdvertiserTag' => [],
  2399.             'byOffer' => []
  2400.         ];
  2401.         $approvalControlData $this->doctrine->getRepository(ApprovalControl::class)->getApprovalControlData($byAdvertiser$byAdvertiserTag$byOffer$advertiserIds$advertiserTagIds$affiliateIds$affiliateTagIds$offerIds$dateStart$dateEnd$tuneAccount);
  2402.         $clickCaps = [
  2403.             'byOffer' => [],
  2404.             'byAdvertiser' => [],
  2405.             'byAffiliate' => [],
  2406.             'byOfferByAffiliate' => []
  2407.         ];
  2408.         $clickCapData $this->doctrine->getRepository('App\Entity\ClickCap')->getClickCapDataByIsDeleted(0);
  2409.         foreach ($clickCapData as $key => $value) {
  2410.             if ($value['byOffer']) {
  2411.                 $clickCaps['byOffer'][$value['offerId']][$value['blockPeriod']] = $value;
  2412.             } elseif ($value['byAdvertiser']) {
  2413.                 $clickCaps['byAdvertiser'][$value['advertiserId']][$value['blockPeriod']] = $value;
  2414.             } elseif ($value['byAffiliate']) {
  2415.                 $clickCaps['byAffiliate'][$value['affiliateId']][$value['blockPeriod']] = $value;
  2416.             } elseif ($value['byOfferByAffiliate']) {
  2417.                 $clickCaps['byOfferByAffiliate'][$value['offerId']][$value['affiliateId']][$value['blockPeriod']] = $value;
  2418.             }
  2419.         }
  2420.         $affiliateList $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
  2421.         $accountManagerInfo $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys(array_keys($affiliateList), $tuneAccount);
  2422.         $offerNameByOfferId = [];
  2423.         foreach ($approvalControlData as $key => $value) {
  2424.             $value['offerName'] = '';
  2425.             if (isset($value['offerId'])) {
  2426.                 if (!array_key_exists($value['offerId'], $offerNameByOfferId)) {
  2427.                     $offerData $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offerId'], 'tuneAccount' => $tuneAccount]);
  2428.                     if ($offerData) {
  2429.                         $offerNameByOfferId[$value['offerId']] = $offerData->getName();
  2430.                     } else {
  2431.                         $offerNameByOfferId[$value['offerId']] = $value['offerId'];
  2432.                     }
  2433.                 }
  2434.                 $value['offerName'] = $offerNameByOfferId[$value['offerId']];
  2435.             }
  2436.             $value['accountManagerName'] = array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['name'] : '';
  2437.             $value['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  2438.             $value['capType'] = ucwords(str_replace("_"" "$value['capType']));
  2439.             $value['offerId'] = (string)$value['offerId'];
  2440.             $value['approvalTypeRaw'] = $value['approvalType'];
  2441.             $value['approvalType'] = Config::APPROVAL_CONTROL_APPROVAL_TYPE[$value['approvalType']];
  2442.             $value['advertiserId'] || (!$value['advertiserId'] && !$value['advertiserTagId'] && !$value['offerId']) ? $finalArr['byAdvertiser'][] = $value false;
  2443.             $value['advertiserTagId'] ? $finalArr['byAdvertiserTag'][] = $value false;
  2444.             $value['offerId'] ? $finalArr['byOffer'][] = $value false;
  2445.         }
  2446.         if (isset($fromOfferDetailPage) && $fromOfferDetailPage && sizeof($offerIds) == 1) {
  2447.             $temp = [];
  2448.             foreach ($finalArr['byOffer'] as $key => $value) {
  2449.                 if ($value['affiliateId']) {
  2450.                     $temp[$value['affiliateId']] = $value;
  2451.                 }
  2452.             }
  2453.             $affiliateList $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
  2454.             $approvedAffiliatesByOfferId $this->brandHasofferApi->getApprovedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
  2455.             $unapprovedAffiliatesByOfferId $this->brandHasofferApi->getUnapprovedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
  2456.             $affiliatesForOfferId array_merge(!is_array($approvedAffiliatesByOfferId) ? [] : $approvedAffiliatesByOfferIdis_array($unapprovedAffiliatesByOfferId) ? $unapprovedAffiliatesByOfferId : []);
  2457.             foreach ($affiliatesForOfferId as $affiliateId) {
  2458.                 $approvalType Config::APPROVAL_CONTROL_APPROVAL_TYPE_DISAPPROVE_ONCE;
  2459.                 if (in_array($affiliateId$approvedAffiliatesByOfferId)) {
  2460.                     $approvalType Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE;
  2461.                 }
  2462.                 if (!array_key_exists($affiliateId$temp) && array_key_exists($affiliateId$affiliateList)) {
  2463.                     $temp[$affiliateId] = [
  2464.                         'id' => null,
  2465.                         'affiliateId' => (int)$affiliateId,
  2466.                         'accountManagerName' => array_key_exists($affiliateId$accountManagerInfo) ? $accountManagerInfo[$affiliateId]['firstName'] . ' ' $accountManagerInfo[$affiliateId]['lastName'] : '',
  2467.                         'affiliateTagId' => null,
  2468.                         'affiliateTagName' => null,
  2469.                         'advertiserId' => null,
  2470.                         'advertiserTagId' => null,
  2471.                         'offerId' => (string)$offerIds[0],
  2472.                         'approvalTypeRaw' => $approvalType,
  2473.                         'approvalType' => Config::APPROVAL_CONTROL_APPROVAL_TYPE[$approvalType],
  2474.                         'isProcessed' => true,
  2475.                         'addedBy' => null,
  2476.                         'dateUpdated' => null,
  2477.                         'capType' => null,
  2478.                         'capValue' => null,
  2479.                         'addedFrom' => null,
  2480.                         'dateInserted' => null,
  2481.                         'offerName' => isset($offerNameByOfferId[$offerIds[0]]) ? $offerNameByOfferId[$offerIds[0]] : ''
  2482.                     ];
  2483.                 }
  2484.             }
  2485.             ksort($temp);
  2486.             $finalArr['byOffer'] = array_values($temp);
  2487.             $finalArr['byAdvertiser'] = [];
  2488.             $finalArr['byAdvertiserTag'] = [];
  2489.         }
  2490.         foreach ($finalArr as $key => $value) {
  2491.             foreach ($value as $k => $v) {
  2492.                 $index md5($v['affiliateId'] . '#' $v['affiliateTagId'] . '#' $v['advertiserId'] . '#' $v['advertiserTagId'] . '#' $v['offerId'] . '#' $v['isProcessed'] . '#' $v['addedBy'] . '#' $v['addedFrom'] . '#' $v['approvalType']);
  2493.                 if (!array_key_exists($key$finalFinalArr)) {
  2494.                     $finalFinalArr[$key] = [];
  2495.                 }
  2496.                 if (!array_key_exists($index$finalFinalArr[$key])) {
  2497.                     $finalFinalArr[$key][$index] = [
  2498.                         'affiliateId' => $v['affiliateId'],
  2499.                         'affiliateTagId' => $v['affiliateTagId'],
  2500.                         'advertiserId' => $v['advertiserId'],
  2501.                         'advertiserTagId' => $v['advertiserTagId'],
  2502.                         'offerId' => $v['offerId'],
  2503.                         'isProcessed' => $v['isProcessed'],
  2504.                         'addedBy' => $v['addedBy'],
  2505.                         'addedFrom' => $v['addedFrom'],
  2506.                         'accountManagerName' => $v['accountManagerName'],
  2507.                         'offerName' => $v['offerName'],
  2508.                         'approvalTypeRaw' => $v['approvalTypeRaw'],
  2509.                         'dateUpdated' => $v['dateUpdated'],
  2510.                         'approvalType' => $v['approvalType'],
  2511.                         'caps' => [],
  2512.                         'ids' => []
  2513.                     ];
  2514.                 }
  2515.                 $finalFinalArr[$key][$index]['ids'][] = $v['id'];
  2516.                 if ($v['capType']) {
  2517.                     $finalFinalArr[$key][$index]['caps'][] = [
  2518.                         'capType' => $v['capType'],
  2519.                         'capValue' => $v['capValue']
  2520.                     ];
  2521.                 }
  2522.             }
  2523.         }
  2524.         foreach ($finalFinalArr as $key => $value) {
  2525.             foreach ($value as $k => $v) {
  2526.                 if (array_key_exists($v['affiliateId'], $clickCaps['byAffiliate'])) {
  2527.                     foreach ($clickCaps['byAffiliate'][$v['affiliateId']] as $blockPeriod => $capValue) {
  2528.                         $finalFinalArr[$key][$k]['caps'][] = [
  2529.                             'capType' => ucfirst($blockPeriod) . ' Click Cap By Affiliate',
  2530.                             'capValue' => $capValue['clickCap']
  2531.                         ];
  2532.                     }
  2533.                 }
  2534.                 if (array_key_exists($v['offerId'], $clickCaps['byOffer'])) {
  2535.                     foreach ($clickCaps['byOffer'][$v['offerId']] as $blockPeriod => $capValue) {
  2536.                         $finalFinalArr[$key][$k]['caps'][] = [
  2537.                             'capType' => ucfirst($blockPeriod) . ' Click Cap By Offer',
  2538.                             'capValue' => $capValue['clickCap']
  2539.                         ];
  2540.                     }
  2541.                 }
  2542.                 if (array_key_exists($v['advertiserId'], $clickCaps['byAdvertiser'])) {
  2543.                     foreach ($clickCaps['byAdvertiser'][$v['advertiserId']] as $blockPeriod => $capValue) {
  2544.                         $finalFinalArr[$key][$k]['caps'][] = [
  2545.                             'capType' => ucfirst($blockPeriod) . ' Click Cap By Advertiser',
  2546.                             'capValue' => $capValue['clickCap']
  2547.                         ];
  2548.                     }
  2549.                 }
  2550.                 if (array_key_exists($v['offerId'], $clickCaps['byOfferByAffiliate']) && array_key_exists($v['affiliateId'], $clickCaps['byOfferByAffiliate'][$v['offerId']])) {
  2551.                     foreach ($clickCaps['byOfferByAffiliate'][$v['offerId']][$v['affiliateId']] as $blockPeriod => $capValue) {
  2552.                         $finalFinalArr[$key][$k]['caps'][] = [
  2553.                             'capType' => ucfirst($blockPeriod) . ' Click Cap By Offer By Affiliate',
  2554.                             'capValue' => $capValue['clickCap']
  2555.                         ];
  2556.                     }
  2557.                 }
  2558.             }
  2559.             $value $finalFinalArr[$key];
  2560.             $finalFinalArr[$key] = array_values($value);
  2561.         }
  2562.         if ($downloadCSV) {
  2563.             $headers = ['Offer Id''Offer Name''Advertiser Id''Advertiser Name''Affiliate Id''Affiliate Name''Affiliate Tag Id''Affiliate Tag Name''Affiliate Account Manager''Added By''Approval Type''Cap Type''Cap Value''Added From''Date Inserted'];
  2564.             $advertiserList = [];
  2565.             if (sizeof($finalArr['byAdvertiser'])) {
  2566.                 $advertiserList $this->commonCalls->getAdvertisersListByStatusWithKeys([
  2567.                     'tuneAccount' => $tuneAccount
  2568.                 ]);
  2569.             }
  2570.             $affiliateTagList $this->commonCalls->getAffiliateTagListByStatusWithKeys($tuneAccount);
  2571.             $row[] = $headers;
  2572.             foreach ($finalFinalArr as $k => $v) {
  2573.                 foreach ($v as $key => $value) {
  2574.                     if (
  2575.                         (
  2576.                             $downloadCSVByApproved &&
  2577.                             (
  2578.                                 $value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE_ONCE ||
  2579.                                 $value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE
  2580.                             )
  2581.                         ) ||
  2582.                         (
  2583.                             $downloadCSVByUnapproved &&
  2584.                             (
  2585.                                 $value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_DISAPPROVE_ONCE
  2586.                             )
  2587.                         )
  2588.                     ) {
  2589.                         foreach ($value['caps'] as $capIndex => $capVal) {
  2590.                             $temp = [
  2591.                                 $value['offerId'],
  2592.                                 $value['offerName'],
  2593.                                 $value['advertiserId'],
  2594.                                 array_key_exists($value['advertiserId'], $advertiserList) ? $advertiserList[$value['advertiserId']]['name'] : '',
  2595.                                 $value['affiliateId'],
  2596.                                 array_key_exists($value['affiliateId'], $affiliateList) ? str_replace(","" "$affiliateList[$value['affiliateId']]['name']) : $value['affiliateId'],
  2597.                                 $value['affiliateTagId'],
  2598.                                 array_key_exists($value['affiliateTagId'], $affiliateTagList) ? str_replace(","" "$affiliateTagList[$value['affiliateTagId']]['name']) : '',
  2599.                                 $value['accountManagerName'],
  2600.                                 //                        array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['employeeId'] : null,
  2601.                                 $value['addedBy'],
  2602.                                 $value['approvalType'],
  2603.                                 $capVal['capType'],
  2604.                                 $capVal['capValue'],
  2605.                                 ucfirst(str_replace("_"" "$value['addedFrom'])),
  2606.                                 $value['dateUpdated'],
  2607.                             ];
  2608.                             $row[] = $temp;
  2609.                         }
  2610.                     }
  2611.                 }
  2612.             }
  2613.             $spreadsheet = new Spreadsheet();
  2614.             $spreadsheet->getProperties()->setCreator('MAFO')
  2615.                 ->setLastModifiedBy('MAFO')
  2616.                 ->setTitle('Approval Control')
  2617.                 ->setSubject('Approval Control')
  2618.                 ->setDescription('Approval Control');
  2619.             $spreadsheet->getActiveSheet()
  2620.                 ->fromArray(
  2621.                     $row,
  2622.                     NULL,
  2623.                     'A1'
  2624.                 );
  2625.             header('Content-Type: application/vnd.ms-excel');
  2626.             header('Content-Disposition: attachment;filename="approval control.xls"');
  2627.             header('Cache-Control: max-age=0');
  2628.             $writer IOFactory::createWriter($spreadsheet'Xls');
  2629.             $writer->save('php://output');
  2630.             exit;
  2631.         } else {
  2632.             return new JsonResponse($finalFinalArr);
  2633.         }
  2634.     }
  2635.     /**
  2636.      * @Route("/approval-control", name="post_approval_control", methods={"POST"})
  2637.      */
  2638.     public function approvalControlPostAction(Request $request)
  2639.     {
  2640.         $payload json_decode($request->getContent(), true);
  2641.         // $advertiserIds = $payload['advertiserIds'];
  2642.         $advertiserIdsWithTuneAccount $payload['advertiserIdsWithTuneAccount'] ?? [];
  2643.         $advertiserTagIds $payload['advertiserTagIds'] ?? [];
  2644.         $affiliateIds $payload['affiliateIds'];
  2645.         $affiliateTagIds $payload['affiliateTagIds'] ?? [];
  2646.         // $offerIdsPayload = $payload['offerIds'];
  2647.         $offerIdsWithTuneAccount $payload['offerIdsWithTuneAccount'] ?? [];
  2648.         $approvalType $payload['approvalType'];
  2649.         $capTypes $payload['approveCapType'];
  2650.         $capValue $payload['capValue'];
  2651.         // $tuneAccount = $payload['tuneAccount'] ? $payload['tuneAccount'] : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2652.         $addedFrom = isset($payload['addedFrom']) ? $payload['addedFrom'] : Config::APPROVAL_CONTROL_ADDED_FROM_APPROVAL_CONTROL;
  2653.         // $offerIds = [];
  2654.         // foreach ($offerIdsWithTuneAccount as $offerDetails) {
  2655.         //     $offerIds[] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $offerId));
  2656.         // }
  2657.         if (!array_key_exists($approvalTypeConfig::APPROVAL_CONTROL_APPROVAL_TYPE)) {
  2658.             return new JsonResponse(true);
  2659.         }
  2660.         foreach ($affiliateIds as $affiliateId) {
  2661.             if ($capTypes) {
  2662.                 foreach ($capTypes as $capType) {
  2663.                     if (in_array($capTypeConfig::AFFILIATE_OFFER_CAP_TYPE) && $capValue 0) {
  2664.                         foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
  2665.                             $advertiserId $advertiserDetails['value'];
  2666.                             $tuneAccount $advertiserDetails['tuneAccount'];
  2667.                             $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy([
  2668.                                 'affiliateId' => $affiliateId,
  2669.                                 'capType' => $capType,
  2670.                                 'advertiserId' => $advertiserId,
  2671.                                 'tuneAccount' => $tuneAccount
  2672.                             ]);
  2673.                             if (!$combinationExist) {
  2674.                                 $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnull$advertiserIdnullnull$approvalType$this->getUser()->getName(), $capType$capValue$addedFrom$tuneAccount);
  2675.                             } else {
  2676.                                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2677.                                     'approvalType' => $approvalType,
  2678.                                     'isProcessed' => 0,
  2679.                                     'isDeleted' => 0,
  2680.                                     'capValue' => $capValue,
  2681.                                     'addedFrom' => $addedFrom
  2682.                                 ]);
  2683.                             }
  2684.                         }
  2685.                         foreach ($advertiserTagIds as $advertiserTagId) {
  2686.                             $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => $capType'advertiserTagId' => $advertiserTagId'tuneAccount' => $tuneAccount]);
  2687.                             if (!$combinationExist) {
  2688.                                 $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnullnull$advertiserTagIdnull$approvalType$this->getUser()->getName(), $capType$capValue$addedFrom$tuneAccount);
  2689.                             } else {
  2690.                                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2691.                                     'approvalType' => $approvalType,
  2692.                                     'isProcessed' => 0,
  2693.                                     'isDeleted' => 0,
  2694.                                     'capValue' => $capValue,
  2695.                                     'addedFrom' => $addedFrom
  2696.                                 ]);
  2697.                             }
  2698.                         }
  2699.                         foreach ($offerIdsWithTuneAccount as $offerDetails) {
  2700.                             $offerId $offerDetails['value'];
  2701.                             $tuneAccount $offerDetails['tuneAccount'];
  2702.                             $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => $capType'offerId' => $offerId'tuneAccount' => $tuneAccount]);
  2703.                             if (!$combinationExist) {
  2704.                                 $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnullnullnull$offerId$approvalType$this->getUser()->getName(), $capType$capValue$addedFrom$tuneAccount);
  2705.                             } else {
  2706.                                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2707.                                     'approvalType' => $approvalType,
  2708.                                     'isProcessed' => 0,
  2709.                                     'isDeleted' => 0,
  2710.                                     'capValue' => $capValue,
  2711.                                     'addedFrom' => $addedFrom
  2712.                                 ]);
  2713.                             }
  2714.                         }
  2715.                     }
  2716.                 }
  2717.             } else {
  2718.                 foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
  2719.                     $advertiserId $advertiserDetails['value'];
  2720.                     $tuneAccount $advertiserDetails['tuneAccount'];
  2721.                     $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => null'advertiserId' => $advertiserId'tuneAccount' => $tuneAccount]);
  2722.                     if (!$combinationExist) {
  2723.                         $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnull$advertiserIdnullnull$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2724.                     } else {
  2725.                         $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2726.                             'approvalType' => $approvalType,
  2727.                             'isProcessed' => 0,
  2728.                             'isDeleted' => 0,
  2729.                             'addedFrom' => $addedFrom
  2730.                         ]);
  2731.                     }
  2732.                 }
  2733.                 foreach ($advertiserTagIds as $advertiserTagId) {
  2734.                     $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => null'advertiserTagId' => $advertiserTagId'tuneAccount' => $tuneAccount]);
  2735.                     if (!$combinationExist) {
  2736.                         $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnullnull$advertiserTagIdnull$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2737.                     } else {
  2738.                         $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2739.                             'approvalType' => $approvalType,
  2740.                             'isProcessed' => 0,
  2741.                             'isDeleted' => 0,
  2742.                             'addedFrom' => $addedFrom
  2743.                         ]);
  2744.                     }
  2745.                 }
  2746.                 foreach ($offerIdsWithTuneAccount as $offerDetails) {
  2747.                     $offerId $offerDetails['value'];
  2748.                     $tuneAccount $offerDetails['tuneAccount'];
  2749.                     $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => null'offerId' => $offerId'tuneAccount' => $tuneAccount]);
  2750.                     if (!$combinationExist) {
  2751.                         $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnullnullnull$offerId$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2752.                     } else {
  2753.                         $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2754.                             'approvalType' => $approvalType,
  2755.                             'isProcessed' => 0,
  2756.                             'isDeleted' => 0,
  2757.                             'addedFrom' => $addedFrom
  2758.                         ]);
  2759.                     }
  2760.                 }
  2761.             }
  2762.         }
  2763.         foreach ($affiliateTagIds as $affiliateTagId) {
  2764.             if ($capTypes) {
  2765.                 foreach ($capTypes as $capType) {
  2766.                     if (in_array($capTypeConfig::AFFILIATE_OFFER_CAP_TYPE) && $capValue 0) {
  2767.                         foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
  2768.                             $advertiserId $advertiserDetails['value'];
  2769.                             $tuneAccount $advertiserDetails['tuneAccount'];
  2770.                             $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId'capType' => $capType'advertiserId' => $advertiserId'tuneAccount' => $tuneAccount]);
  2771.                             if (!$combinationExist) {
  2772.                                 $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null$affiliateTagId$advertiserIdnullnull$approvalType$this->getUser()->getName(), $capType$capValue$addedFrom$tuneAccount);
  2773.                             } else {
  2774.                                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2775.                                     'approvalType' => $approvalType,
  2776.                                     'isProcessed' => 0,
  2777.                                     'isDeleted' => 0,
  2778.                                     'capValue' => $capValue,
  2779.                                     'addedFrom' => $addedFrom
  2780.                                 ]);
  2781.                             }
  2782.                         }
  2783.                         foreach ($offerIdsWithTuneAccount as $offerDetails) {
  2784.                             $offerId $offerDetails['value'];
  2785.                             $tuneAccount $offerDetails['tuneAccount'];
  2786.                             $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId'capType' => $capType'offerId' => $offerId'tuneAccount' => $tuneAccount]);
  2787.                             if (!$combinationExist) {
  2788.                                 $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null$affiliateTagIdnullnull$offerId$approvalType$this->getUser()->getName(), $capType$capValue$addedFrom$tuneAccount);
  2789.                             } else {
  2790.                                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2791.                                     'approvalType' => $approvalType,
  2792.                                     'isProcessed' => 0,
  2793.                                     'isDeleted' => 0,
  2794.                                     'capValue' => $capValue,
  2795.                                     'addedFrom' => $addedFrom
  2796.                                 ]);
  2797.                             }
  2798.                         }
  2799.                     }
  2800.                 }
  2801.             } else {
  2802.                 foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
  2803.                     $advertiserId $advertiserDetails['value'];
  2804.                     $tuneAccount $advertiserDetails['tuneAccount'];
  2805.                     $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId'capType' => null'advertiserId' => $advertiserId'tuneAccount' => $tuneAccount]);
  2806.                     if (!$combinationExist) {
  2807.                         $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null$affiliateTagId$advertiserIdnullnull$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2808.                     } else {
  2809.                         $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2810.                             'approvalType' => $approvalType,
  2811.                             'isProcessed' => 0,
  2812.                             'isDeleted' => 0,
  2813.                             'addedFrom' => $addedFrom
  2814.                         ]);
  2815.                     }
  2816.                 }
  2817.                 foreach ($offerIdsWithTuneAccount as $offerDetails) {
  2818.                     $offerId $offerDetails['value'];
  2819.                     $tuneAccount $offerDetails['tuneAccount'];
  2820.                     $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId'capType' => null'offerId' => $offerId'tuneAccount' => $tuneAccount]);
  2821.                     if (!$combinationExist) {
  2822.                         $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null$affiliateTagIdnullnull$offerId$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2823.                     } else {
  2824.                         $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2825.                             'approvalType' => $approvalType,
  2826.                             'isProcessed' => 0,
  2827.                             'isDeleted' => 0,
  2828.                             'addedFrom' => $addedFrom
  2829.                         ]);
  2830.                     }
  2831.                 }
  2832.             }
  2833.         }
  2834.         foreach ($affiliateIds as $affiliateId) {
  2835.             if (empty($advertiserIdsWithTuneAccount) && empty($advertiserTagIds) && empty($offerIdsWithTuneAccount)) {
  2836.                 $combinationExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId'capType' => null'offerId' => null'tuneAccount' => $tuneAccount]);
  2837.                 if (!$combinationExist) {
  2838.                     $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateIdnullnullnullnull$approvalType$this->getUser()->getName(), nullnull$addedFrom$tuneAccount);
  2839.                 } else {
  2840.                     $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
  2841.                         'approvalType' => $approvalType,
  2842.                         'isProcessed' => 0,
  2843.                         'isDeleted' => 0,
  2844.                         'addedFrom' => $addedFrom
  2845.                     ]);
  2846.                 }
  2847.             }
  2848.         }
  2849.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  2850.             $execCommand "php " $this->projectDir "/bin/console app:approvalControl true --env=prod > /dev/null &";
  2851.             exec($execCommand);
  2852.             $execCommand "php " $this->projectDir "/bin/console app:updateCache " Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_OFFER " --env=prod > /dev/null &";
  2853.             exec($execCommand);
  2854.             $execCommand "php " $this->projectDir "/bin/console app:updateCache " Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_ADVERTISER " --env=prod > /dev/null &";
  2855.             exec($execCommand);
  2856.         }
  2857.         return new JsonResponse(true);
  2858.     }
  2859.     /**
  2860.      * @Route("/approval-control/{id}", name="patch_approval_control", methods={"PATCH"})
  2861.      */
  2862.     public function patchApprovalControlAction(Request $request$id)
  2863.     {
  2864.         $payload json_decode($request->getContent(), true);
  2865.         $payload['isProcessed'] = 0;
  2866.         $payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2867.         $payload['addedBy'] = $this->getUser()->getName();
  2868.         $idExist $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['id' => $id]);
  2869.         if ($idExist) {
  2870.             $ids $id != '' explode(","$id) : [];
  2871.             foreach ($ids as $id) {
  2872.                 $this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($id$payload);
  2873.             }
  2874.         } elseif (isset($payload['affiliateId']) && isset($payload['offerId']) && isset($payload['approvalType'])) {
  2875.             $this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($payload['affiliateId'], nullnullnull$payload['offerId'], $payload['approvalType'], $this->getUser()->getName(), nullnullConfig::APPROVAL_CONTROL_ADDED_FROM_OFFER_INFO$payload['tuneAccount']);
  2876.         }
  2877.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  2878.             $execCommand "php " $this->projectDir "/bin/console app:approvalControl true --env=prod > /dev/null &";
  2879.             exec($execCommand);
  2880.         }
  2881.         return new JsonResponse(true);
  2882.     }
  2883.     /**
  2884.      * @Route("/block-control", name="get_block_control", methods={"GET"})
  2885.      */
  2886.     public function getBlockControlAction(Request $request)
  2887.     {
  2888.         $queryParams $request->query->all();
  2889.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  2890.         $affiliateTagIds $queryParams['affiliateTagIds'] ?? [];
  2891.         $offerIds $queryParams['offerIds'] ?? [];
  2892.         $fromOfferDetailPage $request->query->get('fromOfferDetailPage');
  2893.         $downloadCSV $request->query->get('downloadCSV') == true true false;
  2894.         $downloadCSVByBlocked $request->query->get('downloadCSVByBlocked') == true true false;
  2895.         $downloadCSVByUnblocked $request->query->get('downloadCSVByUnblocked') == true true false;
  2896.         $tuneAccount $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2897.         $dateStart $request->query->get('dateStart');
  2898.         $dateEnd $request->query->get('dateEnd');
  2899.         $dateStart = isset($dateStart) ? date('Y-m-d'strtotime($request->query->get('dateStart'))) : null;
  2900.         $dateEnd = isset($dateEnd) ? date('Y-m-d'strtotime("+1 day"strtotime($request->query->get('dateEnd')))) : null;
  2901.         $blockControlData $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->getScheduledOfferBlockData($affiliateIds$affiliateTagIds$offerIds$dateStart$dateEnd$tuneAccount);
  2902.         $affiliateList $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
  2903.         $accountManagerInfo $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys(array_keys($affiliateList), $tuneAccount);
  2904.         foreach ($blockControlData as $key => $value) {
  2905.             $blockControlData[$key]['accountManagerName'] = array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['firstName'] . ' ' $accountManagerInfo[$value['affiliateId']]['firstName'] : '';
  2906.             $blockControlData[$key]['blockTypeRaw'] = $value['blockType'];
  2907.             $blockControlData[$key]['offerId'] = (string)$value['offerId'];
  2908.             $blockControlData[$key]['blockType'] = ucfirst($value['blockType']) . 'ed';
  2909.         }
  2910.         if (isset($fromOfferDetailPage) && $fromOfferDetailPage && sizeof($offerIds) == 1) {
  2911.             $temp = [];
  2912.             foreach ($blockControlData as $key => $value) {
  2913.                 if ($value['affiliateId']) {
  2914.                     $temp[$value['affiliateId']] = $value;
  2915.                 }
  2916.             }
  2917.             $blockedAffiliateIds $this->brandHasofferApi->getBlockedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
  2918.             $unBlockedAffiliateIds $this->brandHasofferApi->getUnblockedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
  2919.             $affiliatesForOfferId array_merge($blockedAffiliateIds === "" ? [] : $blockedAffiliateIds$unBlockedAffiliateIds === "" ? [] : $unBlockedAffiliateIds);
  2920.             foreach ($affiliatesForOfferId as $affiliateId) {
  2921.                 $blockType Config::AFFILIATE_OFFER_UNBLOCK_MACRO;
  2922.                 if (in_array($affiliateId$blockedAffiliateIds)) {
  2923.                     $blockType Config::AFFILIATE_OFFER_BLOCK_MACRO;
  2924.                 }
  2925.                 if (!array_key_exists($affiliateId$temp) && array_key_exists($affiliateId$affiliateList)) {
  2926.                     $temp[$affiliateId] = [
  2927.                         'id' => null,
  2928.                         'affiliateId' => (int)$affiliateId,
  2929.                         'accountManagerName' => array_key_exists($affiliateId$accountManagerInfo) ? $accountManagerInfo[$affiliateId]['firstName'] . ' ' $accountManagerInfo[$affiliateId]['lastName'] : '',
  2930.                         'affiliateTagId' => null,
  2931.                         'offerId' => (string)$offerIds[0],
  2932.                         'isProcessed' => true,
  2933.                         'addedBy' => null,
  2934.                         'dateUpdated' => null,
  2935.                         'dateInserted' => null,
  2936.                         'blockTypeRaw' => $blockType,
  2937.                         'blockType' => ucfirst($blockType) . 'ed'
  2938.                     ];
  2939.                 }
  2940.             }
  2941.             ksort($temp);
  2942.             $blockControlData array_values($temp);
  2943.         }
  2944.         if ($downloadCSV) {
  2945.             $headers = ['Offer Id''Affiliate Id''Affiliate Name''Account Manager Id''Account Manager Name''Block Type'];
  2946.             $row[] = implode(","$headers);
  2947.             foreach ($blockControlData as $key => $value) {
  2948.                 if (
  2949.                     (
  2950.                         $downloadCSVByBlocked &&
  2951.                         (
  2952.                             $value['blockTypeRaw'] == Config::AFFILIATE_OFFER_BLOCK_MACRO
  2953.                         )
  2954.                     ) ||
  2955.                     (
  2956.                         $downloadCSVByUnblocked &&
  2957.                         (
  2958.                             $value['blockTypeRaw'] == Config::AFFILIATE_OFFER_UNBLOCK_MACRO
  2959.                         )
  2960.                     )
  2961.                 ) {
  2962.                     $temp = [
  2963.                         $value['offerId'],
  2964.                         $value['affiliateId'],
  2965.                         array_key_exists($value['affiliateId'], $affiliateList) ? str_replace(","" "$affiliateList[$value['affiliateId']]['name']) : $value['affiliateId'],
  2966.                         array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['employeeId'] : null,
  2967.                         $value['accountManagerName'],
  2968.                         ucfirst($value['blockType'])
  2969.                     ];
  2970.                     $row[] = implode(","array_values($temp));
  2971.                 }
  2972.             }
  2973.             $content implode("\n"$row);
  2974.             return new Response(
  2975.                 $content,
  2976.                 200,
  2977.                 array(
  2978.                     'Content-Type' => 'text/csv; charset=UTF-8',
  2979.                     'Content-Disposition' => 'attachment; filename="approval-control.csv"'
  2980.                 )
  2981.             );
  2982.         } else {
  2983.             return new JsonResponse($blockControlData);
  2984.         }
  2985.     }
  2986.     /**
  2987.      * @Route("/block-control", name="post_block_control", methods={"POST"})
  2988.      */
  2989.     public function postBlockControlAction(Request $request)
  2990.     {
  2991.         $payload json_decode($request->getContent(), true);
  2992.         $offerIds $payload['offerIds'];
  2993.         $affiliateIds $payload['affiliateIds'];
  2994.         $affiliateTagIds $payload['affiliateTagIds'];
  2995.         $blockType $payload['blockType'];
  2996.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  2997.         $blockedFrom = isset($payload['blockedFrom']) ? $payload['blockedFrom'] : Config::OFFER_AFFILIATE_BLOCK_FROM_OFFER_INFO;
  2998.         foreach ($offerIds as $offerId) {
  2999.             foreach ($affiliateIds as $affiliateId) {
  3000.                 $combinationExist $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['offerId' => $offerId'affiliateId' => $affiliateId'tuneAccount' => $tuneAccount]);
  3001.                 if ($combinationExist) {
  3002.                     $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($combinationExist->getId(), [
  3003.                         'isProcessed' => 0,
  3004.                         'addedBy' => $this->getUser()->getName(),
  3005.                         'blockType' => $blockType
  3006.                     ]);
  3007.                 } else {
  3008.                     $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($offerId$affiliateIdnull$blockedFrom$this->getUser()->getName(), $blockType$tuneAccount);
  3009.                 }
  3010.             }
  3011.             foreach ($affiliateTagIds as $affiliateTagId) {
  3012.                 $combinationExist $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['offerId' => $offerId'affiliateTagId' => $affiliateTagId'tuneAccount' => $tuneAccount]);
  3013.                 if ($combinationExist) {
  3014.                     $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($combinationExist->getId(), [
  3015.                         'isProcessed' => 0,
  3016.                         'addedBy' => $this->getUser()->getName(),
  3017.                         'blockType' => $blockType
  3018.                     ]);
  3019.                 } else {
  3020.                     $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($offerIdnull$affiliateTagId$blockedFrom$this->getUser()->getName(), $blockType$tuneAccount);
  3021.                 }
  3022.             }
  3023.         }
  3024.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  3025.             $execCommand "php " $this->projectDir "/bin/console app:processScheduledAffiliateOfferBlockCommand --env=prod > /dev/null &";
  3026.             exec($execCommand);
  3027.         }
  3028.         return new JsonResponse(true);
  3029.     }
  3030.     /**
  3031.      * @Route("/block-control/{id}", name="patch_block_control", methods={"PATCH"})
  3032.      */
  3033.     public function patchBlockControlAction(Request $request$id)
  3034.     {
  3035.         $payload json_decode($request->getContent(), true);
  3036.         $payload['addedBy'] = $this->getUser()->getName();
  3037.         $payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3038.         $payload['isProcessed'] = 0;
  3039.         $blockedFrom Config::OFFER_AFFILIATE_BLOCK_FROM_OFFER_INFO;
  3040.         $idExist $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['id' => $id]);
  3041.         if ($idExist) {
  3042.             $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($id$payload);
  3043.         } elseif (isset($payload['affiliateId']) && isset($payload['offerId']) && isset($payload['blockType'])) {
  3044.             $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($payload['offerId'], $payload['affiliateId'], null$blockedFrom$this->getUser()->getName(), $payload['blockType'], $payload['tuneAccount']);
  3045.         }
  3046.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  3047.             $execCommand "php " $this->projectDir "/bin/console app:processScheduledAffiliateOfferBlockCommand --env=prod > /dev/null &";
  3048.             exec($execCommand);
  3049.         }
  3050.         return new JsonResponse(true);
  3051.     }
  3052.     /**
  3053.      * @Route("/disable-link-by-link" ,name = "get_disable_link_by_link", methods={"GET"})
  3054.      */
  3055.     public function getDisableLinkByLinkAction(Request $request)
  3056.     {
  3057.         $payload $request->query->all();
  3058.         $decodedstat = isset($payload['token']) ? json_decode(base64_decode($payload['token']), true) : [];
  3059.         $offerId = isset($decodedstat['offerId']) ? $decodedstat['offerId'] : "";
  3060.         $advertiserId = isset($decodedstat['advertiserId']) ? $decodedstat['advertiserId'] : "";
  3061.         $affiliateId = isset($decodedstat['affiliateId']) ? $decodedstat['affiliateId'] : "";
  3062.         $source = isset($decodedstat['source']) ? $decodedstat['source'] : "";
  3063.         $this->commonCalls->disableLink($offerId$affiliateId$sourceConfig::DEFAULT_AFF_SUB2Config::DEFAULT_AFF_SUB3Config::DEFAULT_AFF_SUB5Config::DISABLE_LINK_FROM_APPNAME_CONTROL$advertiserId"[]");
  3064.         return new JsonResponse([
  3065.             'success' => true,
  3066.             'message' => 'Blocked Successfully'
  3067.         ]);
  3068.     }
  3069.     /**
  3070.      * @Route("/impressions", name="get_impressions", methods={"GET"})
  3071.      */
  3072.     public function getImpressionsAction(Request $request)
  3073.     {
  3074.         $impressionsData $this->impressionsApis->getImpressionsData();
  3075.         $offers = [];
  3076.         foreach ($impressionsData as $key => $value) {
  3077.             if (!array_key_exists($value['offer_id'], $offers)) {
  3078.                 $offerInfo $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offer_id']]);
  3079.                 $offers[$value['offer_id']] = $offerInfo $offerInfo->getName() : '';
  3080.             }
  3081.             $impressionsData[$key]['offer_name'] = $offers[$value['offer_id']];
  3082.         }
  3083.         return new JsonResponse(array_values($impressionsData));
  3084.     }
  3085.     /**
  3086.      * @Route("/impressions/{id}", name="delete_impressions", methods={"DELETE"})
  3087.      */
  3088.     public function deleteImpressionsAction(Request $request$id)
  3089.     {
  3090.         $this->impressionsApis->deleteImpressionsDataById($id);
  3091.         return new JsonResponse(true);
  3092.     }
  3093.     /**
  3094.      * @Route("/impressions/{id}", name="put_impressions", methods={"PUT"})
  3095.      */
  3096.     public function putImpressionsAction(Request $request$id)
  3097.     {
  3098.         $payload json_decode($request->getContent(), true);
  3099.         if ($payload['ctr'] >= 0) {
  3100.             $this->impressionsApis->putImpressionsDataById($id$payload);
  3101.         }
  3102.         return new JsonResponse(true);
  3103.     }
  3104.     /**
  3105.      * @Route("/impressions", name="post_impressions", methods={"POST"})
  3106.      */
  3107.     public function postImpressionsAction(Request $request)
  3108.     {
  3109.         $payload json_decode($request->getContent(), true);
  3110.         $offerIds $payload['offerIds'];
  3111.         $impressionLink trim($payload['impressionLink']);
  3112.         $ctr trim($payload['ctr']);
  3113.         foreach ($offerIds as $offerId) {
  3114.             if ($ctr >= 0) {
  3115.                 $this->impressionsApis->postImpressionsData([
  3116.                     'offer_id' => $offerId,
  3117.                     'ctr' => $ctr,
  3118.                     'impression_link' => $impressionLink,
  3119.                     'added_by' => $this->getUser()->getName(),
  3120.                     'added_by_id' => md5($this->getUser()->getName())
  3121.                 ]);
  3122.             }
  3123.         }
  3124.         return new JsonResponse(true);
  3125.     }
  3126.     /**
  3127.      * @Route("/affiliates", name="get_affiliates", methods={"GET"})
  3128.      */
  3129.     public function getAffiliatesAction(Request $request)
  3130.     {
  3131.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
  3132.         $page $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
  3133.         $sortBy $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
  3134.         $sortType $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
  3135.         $queryParams $request->query->all();
  3136.         $statusArr $queryParams['status'] ?? [];
  3137.         $accountManagerIds $queryParams['accountManagerIds'] ?? [];
  3138.         $affiliateTagIds $queryParams['affiliateTagIds'] ?? [];
  3139.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  3140.         $mmpPartnerIds $queryParams['mmpPartnerIds'] ?? [];
  3141.         $mafoAffiliateIds $queryParams['mafoAffiliateIds'] ?? [];
  3142.         $mmpSources $queryParams['mmpSources'] ?? [];
  3143.         $search $request->query->get('search') != '' $request->query->get('search') : null;
  3144.         $pullAffiliateDataFromHO $request->query->get('pullAffiliateDataFromHO') == true false;
  3145.         $withAffiliateIdKey $request->query->get('withKeys') == true false;
  3146.         $downloadDataAsCSV $request->query->get('downloadCSV') == true false;
  3147.         $tuneAccount $request->query->all('tuneAccount') != '' $request->query->all('tuneAccount') : [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE];
  3148.         if ($pullAffiliateDataFromHO && $search && $tuneAccount !== null) {
  3149.             $tuneAccount $tuneAccount[0];
  3150.             $this->commonCalls->updateAffiliateDBByIds([$search], [
  3151.                 'tuneAccount' => $tuneAccount
  3152.             ]);
  3153.         }
  3154.         if ($affiliateTagIds) {
  3155.             $tagIdsDataForAffiliate $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByTagIdArr($affiliateTagIds$tuneAccount);
  3156.             foreach ($tagIdsDataForAffiliate as $key => $value) {
  3157.                 !in_array($value['affiliateId'], $affiliateIds) ? array_push($affiliateIds$value['affiliateId']) : false;
  3158.             }
  3159.         }
  3160.         if ($mmpSources) {
  3161.             $mappedMmpSourcesAffiliates $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByMmpSources($mmpSources$tuneAccount);
  3162.             if ($affiliateIds) {
  3163.                 $affiliateIds array_values(array_intersect($affiliateIdsarray_values(array_unique(array_column($mappedMmpSourcesAffiliates'hoAffiliateId')))));
  3164.             } else {
  3165.                 $affiliateIds array_values(array_unique(array_column($mappedMmpSourcesAffiliates'hoAffiliateId')));
  3166.             }
  3167.         }
  3168.         if ($mmpPartnerIds) {
  3169.             $mappedMmpPartnerAffiliates $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByMmpPartnerIds($mmpPartnerIds$tuneAccount);
  3170.             if ($affiliateIds) {
  3171.                 $affiliateIds array_values(array_intersect($affiliateIdsarray_values(array_unique(array_column($mappedMmpPartnerAffiliates'hoAffiliateId')))));
  3172.             } else {
  3173.                 $affiliateIds array_values(array_unique(array_column($mappedMmpPartnerAffiliates'hoAffiliateId')));
  3174.             }
  3175.         }
  3176.         $data $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateInfo(nullnullnullnull$search$statusArr$accountManagerIds$affiliateIds$mafoAffiliateIds$tuneAccount);
  3177.         $distinctAccountManagerIds = [];
  3178.         $distinctAffiliateIds = [];
  3179.         $tagDataByAffiliateId = [];
  3180.         $accountManagerDataByKey = [];
  3181.         $tagDataByTagId = [];
  3182.         foreach ($data as $key => $value) {
  3183.             !in_array($value['accountManagerId'], $distinctAccountManagerIds) ? array_push($distinctAccountManagerIds$value['accountManagerId']) : false;
  3184.             !in_array($value['affiliateId'], $distinctAffiliateIds) ? array_push($distinctAffiliateIds$value['affiliateId']) : false;
  3185.         }
  3186.         if ($distinctAccountManagerIds) {
  3187.             $accountManagerData $this->doctrine->getRepository(AffiliateAccountManager::class)->getAccountManagerDataByIds($distinctAccountManagerIds$tuneAccount);
  3188.             foreach ($accountManagerData as $key => $value) {
  3189.                 $accountManagerDataByKey[$value['employeeId']] = $value;
  3190.             }
  3191.         }
  3192.         if ($distinctAffiliateIds) {
  3193.             $affiliateTagData $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByAffiliateIdArr($distinctAffiliateIds$tuneAccount);
  3194.             $distinctTagIds = [];
  3195.             foreach ($affiliateTagData as $key => $value) {
  3196.                 !in_array($value['tagId'], $distinctTagIds) ? array_push($distinctTagIds$value['tagId']) : false;
  3197.                 if (!array_key_exists($value['affiliateId'], $tagDataByAffiliateId)) {
  3198.                     $tagDataByAffiliateId[$value['affiliateId']] = [];
  3199.                 }
  3200.                 $tagDataByAffiliateId[$value['affiliateId']][] = $value['tagId'];
  3201.             }
  3202.             if ($distinctTagIds) {
  3203.                 $tagData $this->doctrine->getRepository(Tag::class)->getTagIdDataByTagIdArr($distinctTagIds$tuneAccount);
  3204.                 foreach ($tagData as $key => $value) {
  3205.                     $tagDataByTagId[$value['tagId']] = $value;
  3206.                 }
  3207.             }
  3208.         }
  3209.         $affiliateData = [];
  3210.         foreach ($data as $key => $value) {
  3211.             $value['accountManagerName'] = array_key_exists($value['accountManagerId'], $accountManagerDataByKey) ? $accountManagerDataByKey[$value['accountManagerId']]['firstName'] . ' ' $accountManagerDataByKey[$value['accountManagerId']]['lastName'] : '';
  3212.             if (array_key_exists($value['affiliateId'], $tagDataByAffiliateId)) {
  3213.                 $temp = [];
  3214.                 foreach ($tagDataByAffiliateId[$value['affiliateId']] as $k => $v) {
  3215.                     $temp[] = [
  3216.                         'tagId' => $v,
  3217.                         'tagName' => array_key_exists($v$tagDataByTagId) ? $tagDataByTagId[$v]['name'] : '',
  3218.                     ];
  3219.                 }
  3220.                 $value['tagData'] = $temp;
  3221.             } else {
  3222.                 $value['tagData'] = [];
  3223.             }
  3224.             $affiliateData[$value['affiliateId']] = $value;
  3225.         }
  3226.         if ($pullAffiliateDataFromHO && $affiliateData) {
  3227.             $affiliateInfoFromHO $this->brandHasofferApi->getAffiliateInfoByAffiliateIdsArr(array_keys($affiliateData), $tuneAccount)['response']['data'];
  3228.             foreach ($affiliateInfoFromHO as $key => $value) {
  3229.                 $value['Affiliate']['countryName'] = '';
  3230.                 if (isset($value['Affiliate']['country'])) {
  3231.                     $value['Affiliate']['countryName'] = array_key_exists($value['Affiliate']['country'], Config::COUNTRIES) ? Config::COUNTRIES[$value['Affiliate']['country']]['name'] : '';
  3232.                 }
  3233.                 $affiliateData[$value['Affiliate']['id']]['dataFromHO'] = $value;
  3234.             };
  3235.         }
  3236.         $mmpHoMappedDataByAffiliateId = [];
  3237.         if ($distinctAffiliateIds) {
  3238.             $mmpHoMappedData $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByTuneAffiliateIds($distinctAffiliateIds0$tuneAccount);
  3239.             foreach ($mmpHoMappedData as $key => $value) {
  3240.                 $mmpHoMappedDataByAffiliateId[$value['hoAffiliateId']][] = [
  3241.                     'mmpSource' => $value['mmpPartnerSource'],
  3242.                     'mmpPartnerId' => $value['mmpPartnerId']
  3243.                 ];
  3244.             }
  3245.         }
  3246.         foreach ($affiliateData as $key => $value) {
  3247.             $affiliateData[$key]['mmpMappedData'] = [];
  3248.             if (array_key_exists($value['affiliateId'], $mmpHoMappedDataByAffiliateId)) {
  3249.                 $affiliateData[$key]['mmpMappedData'] = $mmpHoMappedDataByAffiliateId[$value['affiliateId']];
  3250.             }
  3251.         }
  3252.         if ($downloadDataAsCSV) {
  3253.             $rows = [['Affiliate Id''MAFO Partner Id''Company''Status''Account Manager Id''Account Manager Name']];
  3254.             foreach ($affiliateData as $key => $value) {
  3255.                 $rows[] = [
  3256.                     $value['affiliateId'],
  3257.                     $value['mafoAffiliateId'],
  3258.                     $value['company'],
  3259.                     $value['status'],
  3260.                     $value['accountManagerId'],
  3261.                     $value['accountManagerName'],
  3262.                 ];
  3263.             }
  3264.             $spreadsheet = new Spreadsheet();
  3265.             $spreadsheet->getProperties()->setCreator('MAFO')
  3266.                 ->setLastModifiedBy('MAFO')
  3267.                 ->setTitle('Affiliates')
  3268.                 ->setSubject('Affiliates')
  3269.                 ->setDescription('Searched Affiliates');
  3270.             $i 0;
  3271.             $spreadsheet->getActiveSheet()
  3272.                 ->fromArray(
  3273.                     $rows,
  3274.                     NULL,
  3275.                     'A1'
  3276.                 );
  3277.             header('Content-Type: application/vnd.ms-excel');
  3278.             header('Content-Disposition: attachment;filename="affiliates.xls"');
  3279.             header('Cache-Control: max-age=0');
  3280.             $writer IOFactory::createWriter($spreadsheet'Xls');
  3281.             $writer->save('php://output');
  3282.             exit;
  3283.         } else {
  3284.             //            $totalAffiliates = $this->doctrine->getRepository('App\Entity\Tune\AffiliateInfo')->getTotalDataForForAffiliateInfo($statusArr, $search, $accountManagerIds, $affiliateIds);
  3285.             //            $noOfPages = ceil($totalAffiliates / $limit);
  3286.             $finalArr $affiliateData;
  3287.             $totalRecordCount $noOfPages 1;
  3288.             if (!$withAffiliateIdKey) {
  3289.                 $affiliateData array_values($affiliateData);
  3290.                 if (sizeof($affiliateData)) {
  3291.                     $entity $affiliateData[0];
  3292.                     if (array_key_exists($sortBy$entity)) {
  3293.                         $sortFlag 3;
  3294.                         if ($sortType == Config::SORT_TYPE_ASC) {
  3295.                             $sortFlag 4;
  3296.                         }
  3297.                         array_multisort(array_column($affiliateData$sortBy), $sortFlag$affiliateData);
  3298.                     }
  3299.                 }
  3300.                 $offset $limit * ($page 1);
  3301.                 $totalRecordCount sizeof($affiliateData);
  3302.                 $noOfPages ceil($totalRecordCount $limit);
  3303.                 $finalArr array_slice($affiliateData$offset$limit);
  3304.             }
  3305.             return new JsonResponse([
  3306.                 'response' => [
  3307.                     'success' => true,
  3308.                     'httpStatus' => 200,
  3309.                     'data' => [
  3310.                         'data' => $finalArr,
  3311.                         'metaData' => [
  3312.                             'total' => $totalRecordCount,
  3313.                             'limit' => $limit,
  3314.                             'page' => $page,
  3315.                             'pages' => $noOfPages
  3316.                         ]
  3317.                     ]
  3318.                 ]
  3319.             ]);
  3320.         }
  3321.     }
  3322.     /**
  3323.      * @Route("/affiliates/skadnetwork-api-token-refresh/{id}", name="get_affiliates_skadnetwork_api_token_refresh", methods={"GET"})
  3324.      */
  3325.     public function getSkadNetworkApiTokenRefreshAction(Request $request$id)
  3326.     {
  3327.         $key implode('-'str_split(substr(strtolower(md5(microtime() . rand(10009999))), 030), 6));
  3328.         return new JsonResponse($key);
  3329.     }
  3330.     /**
  3331.      * @Route("/affiliates/{id}/offer-access", name="get_affiliates_offer_access", methods={"GET"})
  3332.      */
  3333.     public function getAffiliateOfferAccessAction(Request $request$id)
  3334.     {
  3335.         $activeOfferIds $this->brandHasofferApi->getOfferIdsByStatus(Config::ACTIVE_STATUS)['response']['data'];
  3336.         $blockedOfferIds $this->brandHasofferApi->getBlockedOfferIdsByAffiliateId($id)['response']['data'];
  3337.         $approvedOfferIds $this->brandHasofferApi->getApprovedOfferIdsByAffiliateId($id)['response']['data'];
  3338.         $blockedActiveOfferIds array_values(array_intersect($activeOfferIds$blockedOfferIds));
  3339.         $unblockedActiveOfferIds array_values(array_diff($activeOfferIds$blockedActiveOfferIds));
  3340.         $approvedActiveOfferIds array_values(array_intersect($activeOfferIds$approvedOfferIds));
  3341.         $unapprovedActiveOfferIds array_values(array_diff($activeOfferIds$approvedActiveOfferIds));
  3342.         $approvedAndUnblockedOfferIds array_values(array_intersect($approvedActiveOfferIds$unblockedActiveOfferIds));
  3343.         $unapprovedAndUnblockedOfferIds array_values(array_intersect($unapprovedActiveOfferIds$unblockedActiveOfferIds));
  3344.         $approvedAndUnblockedOffers = [];
  3345.         $unapprovedAndUnblockedOffers = [];
  3346.         $blockedOffers = [];
  3347.         $distinctOfferIds array_values(array_unique(array_merge($approvedAndUnblockedOfferIds$unapprovedAndUnblockedOfferIds$blockedActiveOfferIds)));
  3348.         $offerInfo $this->commonCalls->getOfferInfoByKey($distinctOfferIds);
  3349.         foreach ($approvedAndUnblockedOfferIds as $offerId) {
  3350.             $offerName $advertiserId $advertiserName '';
  3351.             if (array_key_exists($offerId$offerInfo)) {
  3352.                 $offerName $offerInfo[$offerId]['name'];
  3353.                 $advertiserName $offerInfo[$offerId]['advertiserName'];
  3354.                 $advertiserId $offerInfo[$offerId]['advertiserId'];
  3355.             }
  3356.             $approvedAndUnblockedOffers[] = [
  3357.                 'value' => $offerId,
  3358.                 'label' => $offerId ' ' $offerName,
  3359.                 'offerId' => $offerId,
  3360.                 'offerName' => $offerName,
  3361.                 'advertiserId' => $advertiserId,
  3362.                 'advertiserName' => $advertiserName,
  3363.                 'addedBy' => ''
  3364.             ];
  3365.         }
  3366.         foreach ($unapprovedAndUnblockedOfferIds as $offerId) {
  3367.             $offerName $advertiserId $advertiserName '';
  3368.             if (array_key_exists($offerId$offerInfo)) {
  3369.                 $offerName $offerInfo[$offerId]['name'];
  3370.                 $advertiserName $offerInfo[$offerId]['advertiserName'];
  3371.                 $advertiserId $offerInfo[$offerId]['advertiserId'];
  3372.             }
  3373.             $unapprovedAndUnblockedOffers[] = [
  3374.                 'value' => $offerId,
  3375.                 'label' => $offerId ' ' $offerName,
  3376.                 'offerId' => $offerId,
  3377.                 'offerName' => $offerName,
  3378.                 'advertiserId' => $advertiserId,
  3379.                 'advertiserName' => $advertiserName,
  3380.                 'addedBy' => ''
  3381.             ];
  3382.         }
  3383.         foreach ($blockedActiveOfferIds as $offerId) {
  3384.             $offerName $advertiserId $advertiserName '';
  3385.             if (array_key_exists($offerId$offerInfo)) {
  3386.                 $offerName $offerInfo[$offerId]['name'];
  3387.                 $advertiserName $offerInfo[$offerId]['advertiserName'];
  3388.                 $advertiserId $offerInfo[$offerId]['advertiserId'];
  3389.             }
  3390.             $blockedOffers[] = [
  3391.                 'value' => $offerId,
  3392.                 'label' => $offerId ' ' $offerName,
  3393.                 'offerId' => $offerId,
  3394.                 'offerName' => $offerName,
  3395.                 'advertiserId' => $advertiserId,
  3396.                 'advertiserName' => $advertiserName,
  3397.                 'addedBy' => ''
  3398.             ];
  3399.         }
  3400.         return new JsonResponse([
  3401.             'blockedOffers' => $blockedOffers,
  3402.             'approvedAndUnblockedOffers' => $approvedAndUnblockedOffers,
  3403.             'unapprovedAndUnblockedOffers' => $unapprovedAndUnblockedOffers
  3404.         ]);
  3405.     }
  3406.     /**
  3407.      * @Route("/affiliates", name="post_affiliates", methods={"POST"})
  3408.      */
  3409.     public function postAffiliatesAction(Request $request)
  3410.     {
  3411.         $payload json_decode($request->getContent(), true);
  3412.         $tuneAccount $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3413.         $affiliateData $this->brandHasofferApi->createOrUpdateAffiliate(null, [
  3414.             'accountManagerId' => $payload['accountManagerId'],
  3415.             'address1' => $payload['address1'],
  3416.             'address2' => $payload['address2'],
  3417.             'city' => $payload['city'],
  3418.             'company' => $payload['company'],
  3419.             'country' => $payload['country'],
  3420.             'phone' => $payload['phone'],
  3421.             'region' => $payload['region'],
  3422.             'status' => $payload['status'] ?? Config::ACTIVE_STATUS,
  3423.             'zipcode' => $payload['zipcode']
  3424.         ], $tuneAccount);
  3425.         if ($affiliateData['response']['status'] == 1) {
  3426.             if (is_array($payload['tags']) && sizeof($payload['tags'])) {
  3427.                 $this->brandHasofferApi->setTagIdsForAffiliate($affiliateData['response']['data']['Affiliate']['id'], $payload['tags'], $tuneAccount);
  3428.             }
  3429.             $this->brandHasofferApi->createOrUpdateAffiliateUser(null, [
  3430.                 'title' => $payload['title'],
  3431.                 'status' => $payload['status'],
  3432.                 'phone' => $payload['phone'],
  3433.                 'password' => $payload['password'],
  3434.                 'passwordConfirmation' => $payload['confirmPassword'],
  3435.                 'lastName' => $payload['lastName'],
  3436.                 'firstName' => $payload['firstName'],
  3437.                 'email' => $payload['emailAddress'],
  3438.                 'cellPhone' => $payload['phone'],
  3439.                 'affiliateId' => $affiliateData['response']['data']['Affiliate']['id']
  3440.             ], $tuneAccount);
  3441.             $this->commonCalls->updateAffiliateDBByIds([$affiliateData['response']['data']['Affiliate']['id']], [
  3442.                 'tuneAccount' => $tuneAccount
  3443.             ]);
  3444.             return new JsonResponse([
  3445.                 'response' => [
  3446.                     'success' => true,
  3447.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  3448.                     'data' => $affiliateData['response']['data'],
  3449.                     'error' => null
  3450.                 ]
  3451.             ], Config::HTTP_STATUS_CODE_OK);
  3452.         } else {
  3453.             return new JsonResponse([
  3454.                 'response' => [
  3455.                     'success' => false,
  3456.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  3457.                     'data' => null,
  3458.                     'error' => $affiliateData['response']['errors']
  3459.                 ]
  3460.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  3461.         }
  3462.     }
  3463.     /**
  3464.      * @Route("/affiliates/{id}", name="patch_affiliates", methods={"PATCH"})
  3465.      */
  3466.     public function patchAffiliatesAction(Request $request$id)
  3467.     {
  3468.         $payload json_decode($request->getContent(), true);
  3469.         $tuneAccount $request->query->get('tuneAccount') != '' $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3470.         if (array_key_exists('updateHO'$payload)) {
  3471.             $affiliateData $this->brandHasofferApi->createOrUpdateAffiliate($id, [
  3472.                 'accountManagerId' => $payload['accountManagerId'] ?? null,
  3473.                 'address1' => $payload['address1'],
  3474.                 'address2' => $payload['address2'],
  3475.                 'city' => $payload['city'],
  3476.                 'company' => $payload['company'],
  3477.                 'country' => $payload['country'] ?? null,
  3478.                 'phone' => $payload['phone'],
  3479.                 'region' => $payload['region'],
  3480.                 'status' => $payload['status'],
  3481.                 'zipcode' => $payload['zipcode']
  3482.             ], $tuneAccount);
  3483.             if ($affiliateData['response']['status'] == 1) {
  3484.                 if (is_array($payload['tags']) && sizeof($payload['tags'])) {
  3485.                     $this->brandHasofferApi->setTagIdsForAffiliate($affiliateData['response']['data']['Affiliate']['id'], $payload['tags'], $tuneAccount);
  3486.                 }
  3487.                 $this->commonCalls->updateAffiliateDBByIds([$affiliateData['response']['data']['Affiliate']['id']], [
  3488.                     'tuneAccount' => $tuneAccount
  3489.                 ]);
  3490.                 return new JsonResponse([
  3491.                     'response' => [
  3492.                         'success' => true,
  3493.                         'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  3494.                         'data' => $affiliateData['response']['data'],
  3495.                         'error' => null
  3496.                     ]
  3497.                 ], Config::HTTP_STATUS_CODE_OK);
  3498.             } else {
  3499.                 return new JsonResponse([
  3500.                     'response' => [
  3501.                         'success' => false,
  3502.                         'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  3503.                         'data' => null,
  3504.                         'error' => $affiliateData['response']['errors']
  3505.                     ]
  3506.                 ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  3507.             }
  3508.         } else {
  3509.             $this->commonCalls->updateAffiliateDBByIds([$id], [
  3510.                 'createApiKeyIfNotExist' => true,
  3511.                 'tuneAccount' => $tuneAccount
  3512.             ]);
  3513.             $this->doctrine->getRepository(AffiliateInfo::class)->updateAffiliateInfoByAffiliateId($id$payload$tuneAccount);
  3514.             return new JsonResponse(true);
  3515.         }
  3516.     }
  3517.     /**
  3518.      * @Route("/advertisers", name="get_advertisers", methods={"GET"})
  3519.      */
  3520.     public function getAdvertisersAction(Request $request)
  3521.     {
  3522.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
  3523.         $page $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
  3524.         $sortBy $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
  3525.         $sortType $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
  3526.         $queryParams $request->query->all();
  3527.         $statusArr $queryParams['status'] ?? [];
  3528.         $accountManagerIds $queryParams['accountManagerIds'] ?? [];
  3529.         $tagIds $queryParams['tagIds'] ?? [];
  3530.         $mafoAdvertiserIds $queryParams['mafoAdvertiserIds'] ?? [];
  3531.         $advertiserIds $queryParams['advertiserIds'] ?? [];
  3532.         $search $request->query->get('search') != '' $request->query->get('search') : null;
  3533.         $pullAdvertiserDataFromHO $request->query->get('pullAdvertiserDataFromHO') == 1;
  3534.         $withAdvertiserIdKey $request->query->get('withKeys') == 1;
  3535.         $downloadDataAsCSV $request->query->get('downloadCSV') == true false;
  3536.         $tuneAccount $request->query->all('tuneAccount') != '' $request->query->all('tuneAccount') : [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE];
  3537.         if ($pullAdvertiserDataFromHO && $search) {
  3538.             $tuneAccount $tuneAccount[0];
  3539.             $this->commonCalls->updateAdvertiserDBByIds(advertiserIds: [$search], tuneAccount$tuneAccount);
  3540.         }
  3541.         if ($tagIds) {
  3542.             $tagIdsDataForAdvertiser $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByTagIdArr($tagIds);
  3543.             foreach ($tagIdsDataForAdvertiser as $key => $value) {
  3544.                 !in_array($value['advertiserId'], $advertiserIds) ? array_push($advertiserIds$value['advertiserId']) : false;
  3545.             }
  3546.         }
  3547.         if ($tagIds && !$advertiserIds) {
  3548.             $data = [];
  3549.         } else {
  3550.             $data $this->doctrine->getRepository('App\Entity\Tune\AdvertiserInfo')->getAdvertiserInfo($limit$page$sortBy$sortType$search$statusArr$accountManagerIds$advertiserIds$mafoAdvertiserIds$tuneAccount);
  3551.         }
  3552.         $distinctAccountManagerIds = [];
  3553.         $distinctAdvertiserIds = [];
  3554.         $tagDataByAdvertiserId = [];
  3555.         $accountManagerDataByKey = [];
  3556.         $tagDataByTagId = [];
  3557.         foreach ($data as $key => $value) {
  3558.             !in_array($value['accountManagerId'], $distinctAccountManagerIds) ? array_push($distinctAccountManagerIds$value['accountManagerId']) : false;
  3559.             !in_array($value['advertiserId'], $distinctAdvertiserIds) ? array_push($distinctAdvertiserIds$value['advertiserId']) : false;
  3560.         }
  3561.         if ($distinctAccountManagerIds) {
  3562.             $accountManagerData $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAccountManagerDataByIds($distinctAccountManagerIds$tuneAccount);
  3563.             foreach ($accountManagerData as $key => $value) {
  3564.                 $accountManagerDataByKey[$value['employeeId']] = $value;
  3565.             }
  3566.         }
  3567.         if ($distinctAdvertiserIds) {
  3568.             $advertiserTagData $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByAdvertiserIdArr($distinctAdvertiserIds, [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILEConfig::MAFO_SYSTEM_IDENTIFIER_TUNE_WEB]);
  3569.             $distinctTagIds = [];
  3570.             foreach ($advertiserTagData as $key => $value) {
  3571.                 !in_array($value['tagId'], $distinctTagIds) ? array_push($distinctTagIds$value['tagId']) : false;
  3572.                 if (!array_key_exists($value['advertiserId'], $tagDataByAdvertiserId)) {
  3573.                     $tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']] = [];
  3574.                 }
  3575.                 $tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']][] = $value['tagId'];
  3576.             }
  3577.             if ($distinctTagIds) {
  3578.                 $tagData $this->doctrine->getRepository(Tag::class)->getTagIdDataByTagIdArr($distinctTagIds, [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILEConfig::MAFO_SYSTEM_IDENTIFIER_TUNE_WEB]);
  3579.                 foreach ($tagData as $key => $value) {
  3580.                     $tagDataByTagId[$value['tagId']][$value['tuneAccount']] = $value;
  3581.                 }
  3582.             }
  3583.         }
  3584.         $advertiserData = [];
  3585.         foreach ($data as $key => $value) {
  3586.             $value['accountManagerName'] = array_key_exists($value['accountManagerId'], $accountManagerDataByKey) ? $accountManagerDataByKey[$value['accountManagerId']]['firstName'] . ' ' $accountManagerDataByKey[$value['accountManagerId']]['lastName'] : '';
  3587.             if (array_key_exists($value['advertiserId'], $tagDataByAdvertiserId)) {
  3588.                 $temp = [];
  3589.                 foreach ($tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']] as $k => $v) {
  3590.                     $temp[] = [
  3591.                         'tagId' => $v,
  3592.                         'tagName' => array_key_exists($v$tagDataByTagId) ? $tagDataByTagId[$v][$value['tuneAccount']]['name'] : '',
  3593.                     ];
  3594.                 }
  3595.                 $value['tagData'] = $temp;
  3596.             } else {
  3597.                 $value['tagData'] = [];
  3598.             }
  3599.             $value['discountType'] = !in_array($value['discountType'], Config::ADVERTISER_DISCOUNT_TYPES) ? Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT $value['discountType'];
  3600.             $value['discountTypePretty'] = ucwords(str_replace("_"" "$value['discountType']));
  3601.             $advertiserData[$value['advertiserId']] = $value;
  3602.         }
  3603.         if ($pullAdvertiserDataFromHO && $advertiserData) {
  3604.             $advertiserInfoFromHO $this->brandHasofferApi->getAdvertiserInfoByAdvertiserIdsArr(array_keys($advertiserData), $tuneAccount)['response']['data'];
  3605.             foreach ($advertiserInfoFromHO as $key => $value) {
  3606.                 $value['Advertiser']['countryName'] = '';
  3607.                 if (isset($value['Affiliate']['country'])) {
  3608.                     $value['Advertiser']['countryName'] = array_key_exists($value['Advertiser']['country'], Config::COUNTRIES) ? Config::COUNTRIES[$value['Advertiser']['country']]['name'] : '';
  3609.                 }
  3610.                 $advertiserData[$value['Advertiser']['id']]['dataFromHO'] = $value;
  3611.             };
  3612.         }
  3613.         if ($downloadDataAsCSV) {
  3614.             $rows = [['Advertiser Id''Company''Status''Account Manager Id''Account Manager Name']];
  3615.             foreach ($advertiserData as $key => $value) {
  3616.                 $rows[] = [
  3617.                     $value['advertiserId'],
  3618.                     $value['company'],
  3619.                     $value['status'],
  3620.                     $value['accountManagerId'],
  3621.                     $value['accountManagerName'],
  3622.                 ];
  3623.             }
  3624.             $spreadsheet = new Spreadsheet();
  3625.             $spreadsheet->getProperties()->setCreator('MAFO')
  3626.                 ->setLastModifiedBy('MAFO')
  3627.                 ->setTitle('Advertisers')
  3628.                 ->setSubject('Advertisers')
  3629.                 ->setDescription('Searched Advertisers');
  3630.             $i 0;
  3631.             $spreadsheet->getActiveSheet()
  3632.                 ->fromArray(
  3633.                     $rows,
  3634.                     NULL,
  3635.                     'A1'
  3636.                 );
  3637.             header('Content-Type: application/vnd.ms-excel');
  3638.             header('Content-Disposition: attachment;filename="advertisers.xls"');
  3639.             header('Cache-Control: max-age=0');
  3640.             $writer IOFactory::createWriter($spreadsheet'Xls');
  3641.             $writer->save('php://output');
  3642.             exit;
  3643.         } else {
  3644.             $totalAdvertisers $this->doctrine->getRepository('App\Entity\Tune\AdvertiserInfo')->getTotalDataForForAdvertiserInfo($statusArr$search$accountManagerIds$advertiserIds$tuneAccount);
  3645.             $noOfPages ceil($totalAdvertisers $limit);
  3646.             return new JsonResponse([
  3647.                 'response' => [
  3648.                     'success' => true,
  3649.                     'httpStatus' => 200,
  3650.                     'data' => [
  3651.                         'data' => $withAdvertiserIdKey $advertiserData array_values($advertiserData),
  3652.                         'metaData' => [
  3653.                             'total' => $totalAdvertisers,
  3654.                             'limit' => $limit,
  3655.                             'page' => $page,
  3656.                             'pages' => $noOfPages
  3657.                         ]
  3658.                     ]
  3659.                 ]
  3660.             ]);
  3661.         }
  3662.     }
  3663.     /**
  3664.      * @Route("/advertisers", name="post_advertisers", methods={"POST"})
  3665.      */
  3666.     public function postAdvertisersAction(Request $request)
  3667.     {
  3668.         $payload json_decode($request->getContent(), true);
  3669.         $payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3670.         if (strlen($payload['address1']) < 3) {
  3671.             $payload['address1'] = $payload['address1'] . ' ' $payload['company'];
  3672.         }
  3673.         $advertiserData $this->brandHasofferApi->createOrUpdateAdvertiser(null, [
  3674.             'accountManagerId' => $payload['accountManagerId'] ?? null,
  3675.             'address1' => $payload['address1'] ?? null,
  3676.             'address2' => $payload['address2'] ?? null,
  3677.             'city' => $payload['city'] ?? null,
  3678.             'company' => $payload['company'] ?? null,
  3679.             'country' => $payload['country'] ?? null,
  3680.             'phone' => $payload['phone'] ?? null,
  3681.             'region' => $payload['region'] ?? null,
  3682.             'status' => $payload['status'] ?? Config::ACTIVE_STATUS,
  3683.             'zipcode' => $payload['zipcode'] ?? null
  3684.         ], $payload['tuneAccount']);
  3685.         if ($advertiserData['response']['status'] == 1) {
  3686.             if (is_array($payload['tags']) && sizeof($payload['tags'])) {
  3687.                 $this->brandHasofferApi->setTagIdsForAdvertiser($advertiserData['response']['data']['Advertiser']['id'], $payload['tags'], $payload['tuneAccount']);
  3688.             }
  3689.             $this->brandHasofferApi->createOrUpdateAdvertiserUser(null, [
  3690.                 'title' => $payload['title'] ?? null,
  3691.                 'status' => $payload['status'] ?? null,
  3692.                 'phone' => $payload['phone'] ?? null,
  3693.                 'password' => $payload['password'] ?? null,
  3694.                 'passwordConfirmation' => $payload['confirmPassword'] ?? null,
  3695.                 'lastName' => $payload['lastName'] ?? null,
  3696.                 'firstName' => $payload['firstName'] ?? null,
  3697.                 'email' => $payload['emailAddress'] ?? null,
  3698.                 'cellPhone' => $payload['phone'] ?? null,
  3699.                 'advertiserId' => $advertiserData['response']['data']['Advertiser']['id'] ?? null
  3700.             ], $payload['tuneAccount']);
  3701.             $metaData = [
  3702.                 'advertiserDiscountType' => $payload['advertiserDiscountType'],
  3703.                 'advertiserDiscountValue' => $payload['advertiserDiscountValue'] ?? null,
  3704.             ];
  3705.             $this->commonCalls->updateAdvertiserDBById($advertiserData['response']['data']['Advertiser']['id'], $metaData$payload['tuneAccount']);
  3706.             return new JsonResponse([
  3707.                 'response' => [
  3708.                     'success' => true,
  3709.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  3710.                     'data' => $advertiserData['response']['data'],
  3711.                     'error' => null
  3712.                 ]
  3713.             ], Config::HTTP_STATUS_CODE_OK);
  3714.         } else {
  3715.             return new JsonResponse([
  3716.                 'response' => [
  3717.                     'success' => false,
  3718.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  3719.                     'data' => null,
  3720.                     'error' => $advertiserData['response']['errors']
  3721.                 ]
  3722.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  3723.         }
  3724.     }
  3725.     /**
  3726.      * @Route("/advertisers/{id}/skad-network", name="patch_advertisers_skad_network", methods={"PATCH"})
  3727.      */
  3728.     public function patchAdvertisersSKAdNetworkAction(Request $request$id)
  3729.     {
  3730.         $payload json_decode($request->getContent(), true);
  3731.         $skadNetworkFlag $payload['skadNetworkFlag'] ?? false;
  3732.         $skadNetworkId $payload['skadNetworkId'] ?? null;
  3733.         $skadNetworkPrivateKey $payload['skadNetworkPrivateKey'] ?? null;
  3734.         $this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserByAdvertiserId($id, [
  3735.             'skadNetworkFlag' => $skadNetworkFlag,
  3736.             'skadNetworkId' => $skadNetworkId,
  3737.             'skadNetworkPrivateKey' => $skadNetworkPrivateKey,
  3738.         ]);
  3739.         return new JsonResponse(true);
  3740.     }
  3741.     /**
  3742.      * @Route("/advertisers/{id}", name="patch_advertisers", methods={"PATCH"})
  3743.      */
  3744.     public function patchAdvertisersAction(Request $request$id)
  3745.     {
  3746.         $payload json_decode($request->getContent(), true);
  3747.         $payload['tuneAccount'] = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3748.         $advertiserData $this->brandHasofferApi->createOrUpdateAdvertiser($id, [
  3749.             'accountManagerId' => $payload['accountManagerId'] ?? null,
  3750.             'address1' => $payload['address1'],
  3751.             'address2' => $payload['address2'],
  3752.             'city' => $payload['city'],
  3753.             'company' => $payload['company'],
  3754.             'country' => $payload['country'] ?? null,
  3755.             'phone' => $payload['phone'],
  3756.             'region' => $payload['region'],
  3757.             'status' => $payload['status'],
  3758.             'zipcode' => $payload['zipcode']
  3759.         ], $payload['tuneAccount']);
  3760.         $metaData = [
  3761.             'advertiserDiscountType' => $payload['advertiserDiscountType'],
  3762.             'advertiserDiscountValue' => $payload['advertiserDiscountValue'],
  3763.         ];
  3764.         if ($advertiserData['response']['status'] == 1) {
  3765.             if (is_array($payload['tags']) && sizeof($payload['tags'])) {
  3766.                 $this->brandHasofferApi->setTagIdsForAdvertiser($advertiserData['response']['data']['Advertiser']['id'], $payload['tags'], $payload['tuneAccount']);
  3767.             }
  3768.             $this->commonCalls->updateAdvertiserDBById($advertiserData['response']['data']['Advertiser']['id'], $metaData$payload['tuneAccount']);
  3769.             return new JsonResponse([
  3770.                 'response' => [
  3771.                     'success' => true,
  3772.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  3773.                     'data' => $advertiserData['response']['data'],
  3774.                     'error' => null
  3775.                 ]
  3776.             ], Config::HTTP_STATUS_CODE_OK);
  3777.         } else {
  3778.             return new JsonResponse([
  3779.                 'response' => [
  3780.                     'success' => false,
  3781.                     'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
  3782.                     'data' => null,
  3783.                     'error' => $advertiserData['response']['errors']
  3784.                 ]
  3785.             ], Config::HTTP_STATUS_CODE_BAD_REQUEST);
  3786.         }
  3787.     }
  3788.     /**
  3789.      * @Route("/advertisers/affiliate-access/{id}", name="get_advertiser_affiliate_access", methods={"GET"})
  3790.      */
  3791.     public function getAdvertiserAffiliateAccessAction(Request $request$id)
  3792.     {
  3793.         $tuneAccount $request->query->get('tuneAccount') != '' $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  3794.         $blockedAffiliates $this->brandHasofferApi->getBlockedAffiliateIdsByAdvertiserId($id$tuneAccount);
  3795.         $unblockedAffiliateIds $this->brandHasofferApi->getUnblockedAffiliateIdsByAdvertiserId($id$tuneAccount);
  3796.         $blockedAffiliateIds $blockedAffiliates['response']['status'] == $blockedAffiliates['response']['data'] : [];
  3797.         $unblockedAffiliateIds $unblockedAffiliateIds['response']['status'] == $unblockedAffiliateIds['response']['data'] : [];
  3798.         $affiliateData $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
  3799.         $accountManagerData $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys($blockedAffiliateIds$tuneAccount);
  3800.         $blockAffiliatesData = [];
  3801.         $unblockedAffiliatesData = [];
  3802.         foreach ($blockedAffiliateIds as $affiliateId) {
  3803.             if (array_key_exists($affiliateId$affiliateData)) {
  3804.                 $blockAffiliatesData[$affiliateId] = [
  3805.                     'value' => $affiliateData[$affiliateId]['id'],
  3806.                     'label' => $affiliateData[$affiliateId]['id'] . ' - ' $affiliateData[$affiliateId]['name'],
  3807.                     'accountManagerName' => array_key_exists($affiliateId$accountManagerData) ? $accountManagerData[$affiliateId]['firstName'] . ' ' $accountManagerData[$affiliateId]['lastName'] : '',
  3808.                     'status' => $affiliateData[$affiliateId]['status']
  3809.                 ];
  3810.             } else {
  3811.                 $blockAffiliatesData[$affiliateId] = [
  3812.                     'value' => $affiliateId,
  3813.                     'label' => $affiliateId,
  3814.                     'accountManagerName' => '',
  3815.                     'status' => '',
  3816.                 ];
  3817.             }
  3818.         }
  3819.         foreach ($unblockedAffiliateIds as $affiliateId) {
  3820.             if (array_key_exists($affiliateId$affiliateData)) {
  3821.                 $unblockedAffiliatesData[$affiliateId] = [
  3822.                     'value' => $affiliateData[$affiliateId]['id'],
  3823.                     'label' => $affiliateData[$affiliateId]['id'] . ' - ' $affiliateData[$affiliateId]['name'],
  3824.                     'accountManagerName' => array_key_exists($affiliateId$accountManagerData) ? $accountManagerData[$affiliateId]['firstName'] . ' ' $accountManagerData[$affiliateId]['lastName'] : '',
  3825.                     'status' => $affiliateData[$affiliateId]['status']
  3826.                 ];
  3827.             } else {
  3828.                 $unblockedAffiliatesData[$affiliateId] = [
  3829.                     'value' => $affiliateId,
  3830.                     'label' => $affiliateId,
  3831.                     'accountManagerName' => '',
  3832.                     'status' => '',
  3833.                 ];
  3834.             }
  3835.         }
  3836.         return new JsonResponse([
  3837.             'blockedAffiliatesData' => array_values($blockAffiliatesData),
  3838.             'unblockedAffiliatesData' => array_values($unblockedAffiliatesData)
  3839.         ]);
  3840.     }
  3841.     /**
  3842.      * @Route("/advertisers/affiliate-access", name="post_advertiser_affiliate_access", methods={"POST"})
  3843.      */
  3844.     public function postAdvertiserAccessAction(Request $request)
  3845.     {
  3846.         $payload json_decode($request->getContent(), true);
  3847.         if (
  3848.             isset($payload['advertiserId']) &&
  3849.             isset($payload['tuneAccount']) &&
  3850.             isset($payload['affiliateId']) &&
  3851.             isset($payload['blockType']) &&
  3852.             $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $payload['affiliateId'], 'tuneAccount' => $payload['tuneAccount']]) &&
  3853.             $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $payload['advertiserId'], 'tuneAccount' => $payload['tuneAccount']]) &&
  3854.             in_array($payload['blockType'], [Config::AFFILIATE_OFFER_BLOCK_MACROConfig::AFFILIATE_OFFER_UNBLOCK_MACRO])
  3855.         ) {
  3856.             if ($payload['blockType'] == Config::AFFILIATE_OFFER_BLOCK_MACRO) {
  3857.                 $this->brandHasofferApi->blockAffiliateForAdvertiser($payload['affiliateId'], $payload['advertiserId'], $payload['tuneAccount']);
  3858.             } elseif ($payload['blockType'] == Config::AFFILIATE_OFFER_UNBLOCK_MACRO) {
  3859.                 $this->brandHasofferApi->unblockAffiliateForAdvertiser($payload['affiliateId'], $payload['advertiserId'], $payload['tuneAccount']);
  3860.             }
  3861.         }
  3862.         return new JsonResponse($payload);
  3863.     }
  3864.     /**
  3865.      * @Route("/disable-links" ,name = "post_disable_links", methods={"POST"})
  3866.      */
  3867.     public function postDisableLinksAction(Request $request)
  3868.     {
  3869.         $file $request->files->get('file');
  3870.         $payload = [];
  3871.         if ($file) {
  3872.             $file fopen($request->files->get('file')->getPathName(), 'r');
  3873.             $index 0;
  3874.             while (($line fgetcsv($file)) !== FALSE) {
  3875.                 if ($line && $index != 0) {
  3876.                     foreach ($line as $key => $value) {
  3877.                         if (preg_match("/\t/"$value)) {
  3878.                             $value explode("\t"$value)[0];
  3879.                         } else if ($this->commonCalls->checkForString($value';')) {
  3880.                             $value explode(";"$value)[0];
  3881.                         }
  3882.                         $line[$key] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/'''$value));
  3883.                     }
  3884.                     $subIdType $line[2];
  3885.                     if (
  3886.                         $subIdType == Config::DISABLE_LINK_SUB_TYPE_SOURCE ||
  3887.                         $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 ||
  3888.                         $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 ||
  3889.                         $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5
  3890.                     ) {
  3891.                         $payload[] = [
  3892.                             'affiliateId' => $line[0],
  3893.                             'offerId' => $line[1],
  3894.                             Config::DISABLE_LINK_SUB_TYPE_SOURCE => $subIdType == Config::DISABLE_LINK_SUB_TYPE_SOURCE $line[3] : Config::DEFAULT_SOURCE,
  3895.                             Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 $line[3] : Config::DEFAULT_AFF_SUB2,
  3896.                             Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 $line[3] : Config::DEFAULT_AFF_SUB3,
  3897.                             Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5 $line[3] : Config::DEFAULT_AFF_SUB5,
  3898.                         ];
  3899.                     }
  3900.                 }
  3901.                 $index += 1;
  3902.             }
  3903.             fclose($file);
  3904.         }
  3905.         foreach ($payload as $key => $value) {
  3906.             $this->doctrine->getRepository(ScheduledDisableLinks::class)->insertToScheduledDisableLinks($value['offerId'], $value['affiliateId'], $value[Config::DISABLE_LINK_SUB_TYPE_SOURCE], $value[Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2], $value[Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3], $value[Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5], Config::DISABLE_LINK_FROM_MAFO_CSV_UPLOAD$this->getUser()->getName());
  3907.         }
  3908.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  3909.             $execCommand "php " $this->projectDir "/bin/console app:processScheduledOfferDisableLinks --env=prod > /dev/null &";
  3910.             exec($execCommand);
  3911.         }
  3912.         return new JsonResponse(true);
  3913.     }
  3914.     /**
  3915.      * @Route("/price-bulk-edit", name="get_price_bulk_edit", methods={"GET"})
  3916.      */
  3917.     public function getPriceBulkEditAction(Request $request)
  3918.     {
  3919.         $queryParams $request->query->all();
  3920.         $offerIds $queryParams['offerIds'] ?? [];
  3921.         $affiliateIds $queryParams['affiliateIds'] ?? [];
  3922.         $affiliateTagIds $queryParams['affiliateTagIds'] ?? [];
  3923.         $byAffiliate $request->query->get('byAffiliate');
  3924.         $byAffiliateTag $request->query->get('byAffiliateTag');
  3925.         $dateStart date('Y-m-d'strtotime($request->query->get('dateStart')));
  3926.         $dateEnd date('Y-m-d'strtotime('+1 day'strtotime($request->query->get('dateEnd'))));
  3927.         $priceBulkData $this->doctrine->getRepository(PriceBulkEdit::class)->getPriceBulkEditByFilters($affiliateTagIds$affiliateIds$offerIds$dateStart$dateEnd$byAffiliate$byAffiliateTag0);
  3928.         // $affiliateTagsList = $this->commonCalls->getAffiliateTagListByStatusWithKeys();
  3929.         // $affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys();
  3930.         // $uniqueOfferIds = [];
  3931.         // $offerInfoWithKeys = [];
  3932.         // $uniqueOfferGoalIds = [];
  3933.         // $offerGoalInfoWithKeys = [];
  3934.         // foreach ($priceBulkData as $key => $value) {
  3935.         //     !in_array($value['goalId'], $uniqueOfferGoalIds) ? array_push($uniqueOfferGoalIds, $value['goalId']) : false;
  3936.         //     !in_array($value['offerId'], $uniqueOfferIds) ? array_push($uniqueOfferIds, $value['offerId']) : false;
  3937.         // }
  3938.         // if ($uniqueOfferIds) {
  3939.         //     $offerInfoWithKeys = $this->commonCalls->getOfferInfoByKey($uniqueOfferIds);
  3940.         // }
  3941.         // if ($uniqueOfferGoalIds) {
  3942.         //     $offerGoalInfoWithKeys = $this->commonCalls->getOfferGoalInfoByOfferGoalIdArrWithKeys($uniqueOfferGoalIds);
  3943.         // }
  3944.         foreach ($priceBulkData as $key => $value) {
  3945.             $priceBulkData[$key]['dateInserted'] = $value['dateUpdated']->format('Y-m-d H:i:s');
  3946.             // $priceBulkData[$key]['offerName'] = array_key_exists($value['offerId'], $offerInfoWithKeys) ? $offerInfoWithKeys[$value['offerId']]['name'] : '';
  3947.             // $priceBulkData[$key]['goalName'] = array_key_exists($value['goalId'], $offerGoalInfoWithKeys) ? $offerGoalInfoWithKeys[$value['goalId']]['name'] : '';
  3948.             // $priceBulkData[$key]['affiliateTagName'] = array_key_exists($value['affiliateTagId'], $affiliateTagsList) ? $affiliateTagsList[$value['affiliateTagId']]['name'] : '';
  3949.             // $priceBulkData[$key]['affiliateName'] = array_key_exists($value['affiliateId'], $affiliateList) ? $affiliateList[$value['affiliateId']]['name'] : '';
  3950.         }
  3951.         return new JsonResponse($priceBulkData);
  3952.     }
  3953.     /**
  3954.      * @Route("/price-bulk-edit", name="post_price_bulk_edit", methods={"POST"})
  3955.      */
  3956.     public function postPriceBulkEditAction(Request $request)
  3957.     {
  3958.         $file $request->files->get('file');
  3959.         $payload = [];
  3960.         if ($file) {
  3961.             $file fopen($request->files->get('file')->getPathName(), 'r');
  3962.             $index 0;
  3963.             while (($line fgetcsv($file)) !== FALSE) {
  3964.                 if ($line && $index != 0) {
  3965.                     foreach ($line as $key => $value) {
  3966.                         if (preg_match("/\t/"$value)) {
  3967.                             $value explode("\t"$value)[0];
  3968.                         } else if ($this->commonCalls->checkForString($value';')) {
  3969.                             $value explode(";"$value)[0];
  3970.                         }
  3971.                         $line[$key] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/'''$value));
  3972.                     }
  3973.                     $payload[] = [
  3974.                         'offerId' => $line[0],
  3975.                         'goalId' => $line[1] === '' null $line[1],
  3976.                         'affiliateId' => $line[2] === '' null $line[2],
  3977.                         'affiliateTag' => $line[3] === '' null $line[3],
  3978.                         'priceType' => $line[4],
  3979.                         'price' => $line[5],
  3980.                         'tuneAccount' => $line[6] === '' Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE $line[6]
  3981.                     ];
  3982.                 }
  3983.                 $index += 1;
  3984.             }
  3985.         } else {
  3986.             $request json_decode($request->getContent(), true);
  3987.             $offerIds $request['offerIds'];
  3988.             $affiliateIds $request['affiliateIds'];
  3989.             $affiliateTagIds $request['affiliateTagIds'];
  3990.             $offerGoalIds $request['offerGoalIds'];
  3991.             $priceType $request['priceType'];
  3992.             $price $request['price'];
  3993.             $tuneAccount $request['tuneAccount'];
  3994.             foreach ($offerIds as $offerId) {
  3995.                 foreach ($affiliateIds as $affiliateId) {
  3996.                     if ($offerGoalIds) {
  3997.                         foreach ($offerGoalIds as $offerGoalId) {
  3998.                             $payload[] = [
  3999.                                 'offerId' => $offerId,
  4000.                                 'goalId' => $offerGoalId,
  4001.                                 'affiliateId' => $affiliateId,
  4002.                                 'affiliateTag' => null,
  4003.                                 'priceType' => $priceType,
  4004.                                 'price' => $price,
  4005.                                 'tuneAccount' => $tuneAccount
  4006.                             ];
  4007.                         }
  4008.                     } else {
  4009.                         $payload[] = [
  4010.                             'offerId' => $offerId,
  4011.                             'goalId' => null,
  4012.                             'affiliateId' => $affiliateId,
  4013.                             'affiliateTag' => null,
  4014.                             'priceType' => $priceType,
  4015.                             'price' => $price,
  4016.                             'tuneAccount' => $tuneAccount
  4017.                         ];
  4018.                     }
  4019.                 }
  4020.                 foreach ($affiliateTagIds as $affiliateTagId) {
  4021.                     $tagInfo $this->doctrine->getRepository(Tag::class)->findOneBy(['tagId' => $affiliateTagId'tuneAccount' => $tuneAccount]);
  4022.                     if ($offerGoalIds) {
  4023.                         foreach ($offerGoalIds as $offerGoalId) {
  4024.                             $payload[] = [
  4025.                                 'offerId' => $offerId,
  4026.                                 'goalId' => $offerGoalId,
  4027.                                 'affiliateId' => null,
  4028.                                 'affiliateTag' => $tagInfo->getName(),
  4029.                                 'affiliateTagId' => $affiliateTagId,
  4030.                                 'priceType' => $priceType,
  4031.                                 'price' => $price,
  4032.                                 'tuneAccount' => $tuneAccount
  4033.                             ];
  4034.                         }
  4035.                     } else {
  4036.                         $payload[] = [
  4037.                             'offerId' => $offerId,
  4038.                             'goalId' => null,
  4039.                             'affiliateId' => null,
  4040.                             'affiliateTag' => $tagInfo->getName(),
  4041.                             'affiliateTagId' => $affiliateTagId,
  4042.                             'priceType' => $priceType,
  4043.                             'price' => $price,
  4044.                             'tuneAccount' => $tuneAccount
  4045.                         ];
  4046.                     }
  4047.                 }
  4048.             }
  4049.         }
  4050.         foreach ($payload as $key => $value) {
  4051.             if ($value['goalId']) {
  4052.                 $goalExist $this->doctrine->getRepository(OfferGoalsInfo::class)->findOneBy([
  4053.                     'offerId' => $value['offerId'],
  4054.                     'goalId' => $value['goalId'],
  4055.                     'tuneAccount' => $value['tuneAccount']
  4056.                 ]);
  4057.                 if (!$goalExist) {
  4058.                     continue;
  4059.                 }
  4060.             }
  4061.             $value['affiliateTagId'] = null;
  4062.             if ($value['affiliateTag']) {
  4063.                 $tagExist $this->doctrine->getRepository(Tag::class)->findOneBy(['name' => $value['affiliateTag'], 'tuneAccount' => $value['tuneAccount']]);
  4064.                 if ($tagExist) {
  4065.                     $value['affiliateTagId'] = $tagExist->getTagId();
  4066.                 } else {
  4067.                     continue;
  4068.                 }
  4069.             }
  4070.             if ($value['affiliateId']) {
  4071.                 $affiliateExist $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['affiliateId'], 'tuneAccount' => $value['tuneAccount']]);
  4072.                 if (!$affiliateExist) {
  4073.                     continue;
  4074.                 }
  4075.             }
  4076.             if ($value['affiliateTag'] && $value['affiliateId']) {
  4077.                 continue;
  4078.             }
  4079.             if (
  4080.                 in_array($value['priceType'], Config::PRICE_BULK_EDIT_PRICE_TYPES) &&
  4081.                 $value['price'] > &&
  4082.                 $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offerId']])
  4083.             ) {
  4084.                 $combinationExist $this->doctrine->getRepository(PriceBulkEdit::class)->findOneBy([
  4085.                     'affiliateId' => $value['affiliateId'],
  4086.                     'affiliateTagId' => $value['affiliateTagId'],
  4087.                     'offerId' => $value['offerId'],
  4088.                     'goalId' => $value['goalId'],
  4089.                     'priceType' => $value['priceType'],
  4090.                     'tuneAccount' => $value['tuneAccount']
  4091.                 ]);
  4092.                 if (!$combinationExist) {
  4093.                     $this->doctrine->getRepository(PriceBulkEdit::class)->insertToPayoutBulkData($value['affiliateId'], $value['affiliateTagId'], $value['offerId'], $value['goalId'], $value['priceType'], $value['price'], $this->getUser()->getName(), Config::PRICE_BULK_EDIT_DEFAULT_CURRENCY$value['tuneAccount']);
  4094.                 } else {
  4095.                     $this->doctrine->getRepository(PriceBulkEdit::class)->updatePriceBulkEditById($combinationExist->getId(), [
  4096.                         'price' => $value['price'],
  4097.                         'addedBy' => $this->getUser()->getName(),
  4098.                         'isDeleted' => 0,
  4099.                         'isScheduled' => 1
  4100.                     ]);
  4101.                 }
  4102.             }
  4103.         }
  4104.         if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
  4105.             $execCommand "php " $this->projectDir "/bin/console app:priceBulkEdit --env=prod > /dev/null &";
  4106.             exec($execCommand);
  4107.         }
  4108.         return new JsonResponse(true);
  4109.     }
  4110.     /**
  4111.      * @Route("/price-bulk-edit/{id}", name="patch_price_bulk_edit", methods={"PATCH"})
  4112.      */
  4113.     public function patchPriceBulkEditAction(Request $request$id)
  4114.     {
  4115.         $payload json_decode($request->getContent(), true);
  4116.         $payload['addedBy'] = $this->getUser()->getName();
  4117.         $this->doctrine->getRepository(PriceBulkEdit::class)->updatePriceBulkEditById($id$payload);
  4118.         return new JsonResponse(true);
  4119.     }
  4120.     /**
  4121.      * @Route("/link-hyper-client-with-tune-advertiser", name="post_link_hyper_tune", methods={"POST"})
  4122.      */
  4123.     public function postLinkHyperClientWithTuneAdvertiser(Request $requestMafoObjectsComponents $mafoObjectsComponentsHyperApis $hyperApis)
  4124.     {
  4125.         $payload json_decode($request->getContent(), true);
  4126.         $hyperClientId $payload['hyperClientId'];
  4127.         $tuneAdvertiserId $payload['tuneAdvertiserId'];
  4128.         $mafoAdvertisersMapping $this->doctrine->getRepository(MafoAdvertisersMapping::class)->findOneBy([
  4129.             'systemIdentifier' => Config::MAFO_SYSTEM_IDENTIFIER_TUNE,
  4130.             'systemIdentifierId' => $tuneAdvertiserId
  4131.         ]);
  4132.         if (!$mafoAdvertisersMapping) {
  4133.             $mafoObjectsComponents->createOrUpdateAdvertiser(Config::MAFO_SYSTEM_IDENTIFIER_TUNE$tuneAdvertiserId);
  4134.         }
  4135.         $mafoAdvertisersMapping $this->doctrine->getRepository(MafoAdvertisersMapping::class)->findOneBy([
  4136.             'systemIdentifier' => Config::MAFO_SYSTEM_IDENTIFIER_TUNE,
  4137.             'systemIdentifierId' => $tuneAdvertiserId
  4138.         ]);
  4139.         if ($mafoAdvertisersMapping) {
  4140.             $this->doctrine->getRepository(MafoAdvertisersMapping::class)->updateMafoAdvertisersMappingById($mafoAdvertisersMapping->getId(), [
  4141.                 'hyperClientId' => $hyperClientId
  4142.             ]);
  4143.         }
  4144.         $advertiserName null;
  4145.         $advertiserInfo $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy([
  4146.             'advertiserId' => $tuneAdvertiserId
  4147.         ]);
  4148.         if ($advertiserInfo) {
  4149.             $advertiserName $advertiserInfo->getCompany();
  4150.         }
  4151.         //                TODO: remove later when we shift web account completely to default account's hyper
  4152.         if ($this->doctrine->getRepository(ObjectMappingWithTuneWebAccount::class)->findOneBy([
  4153.             'defaultAccountId' => $tuneAdvertiserId,
  4154.             'objectType' => Config::TUNE_ACCOUNT_MAPPING_OBJECT_TYPE_ADVERTISER
  4155.         ])) {
  4156.             return new JsonResponse(true);
  4157.         }
  4158.         $hyperApis->mapTuneAdvertiserWithHyper($tuneAdvertiserId$advertiserName$hyperClientId);
  4159.         return new JsonResponse(true);
  4160.     }
  4161.     /**
  4162.      * @Route("/affiliate-rating", methods={"GET"})
  4163.      */
  4164.     public function affiliateRatingGetAction(Request $request)
  4165.     {
  4166.         $tuneAccount $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  4167.         $period date('Y-m-01'strtotime("-1 month"));
  4168.         $affiliateRatingData $this->doctrine->getRepository(AffiliateRating::class)->getAffiliateRatingDataByPeriod($request->query->get('affiliateId'), $period);
  4169.         return new JsonResponse($affiliateRatingData);
  4170.     }
  4171.     /**
  4172.      * @Route("/affiliate-rating", methods={"POST"})
  4173.      */
  4174.     public function affiliateRatingAction(Request $request)
  4175.     {
  4176.         $payload json_decode($request->getContent(), true);
  4177.         $tuneAccount $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  4178.         extract($payload);
  4179.         $period = new \Datetime(date('Y-m-01'strtotime("-1 month")));
  4180.         $checkAffiliateExistForPeriod $this->doctrine->getRepository(AffiliateRating::class)->findOneBy([
  4181.             'affiliateId' => $affiliateId,
  4182.             'period' => $period,
  4183.             'tuneAccount' => $tuneAccount
  4184.         ]);
  4185.         if ($checkAffiliateExistForPeriod) {
  4186.             $this->doctrine->getRepository(AffiliateRating::class)->updateAdjustAppDetailsById($checkAffiliateExistForPeriod->getId(), [
  4187.                 'qualityFeedback' => $qualityFeedback,
  4188.                 'responsivenessFeedback' => $responsivenessFeedback,
  4189.                 'clickControlFeedback' => $clickControlFeedback,
  4190.                 'impressionControlFeedback' => $impressionControlFeedback,
  4191.             ]);
  4192.         } else {
  4193.             $this->doctrine->getRepository(AffiliateRating::class)->insertToAffiliateRating($affiliateId$period$qualityFeedback$clickControlFeedback$impressionControlFeedback$responsivenessFeedback, [], $tuneAccount);
  4194.         }
  4195.         return new JsonResponse(true);
  4196.     }
  4197. }