src/Controller/ClientSidePublisherController.php line 126

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Config;
  4. use App\Entity\MafoId\MafoAffiliates;
  5. use App\Entity\MafoId\MafoOffers;
  6. use App\Entity\Tune\AffiliateInfo;
  7. use App\Entity\Employees;
  8. use App\Entity\AgentControl;
  9. use App\Entity\MmpMobileApps;
  10. use App\Entity\MmpOffers;
  11. use App\Entity\Tune\OfferInfo;
  12. use App\Entity\NewsletterBuilder;
  13. use App\Entity\OfferGeoRelationship;
  14. use App\Services\AffiliateHasofferAPI;
  15. use App\Services\Alerts;
  16. use App\Services\Aws\ElasticCache;
  17. use App\Services\Aws\S3;
  18. use App\Services\BrandHasofferAPI;
  19. use App\Services\Common;
  20. use App\Services\MafoFinancialToolsComponents;
  21. use App\Services\ImpressionsApis;
  22. use App\Services\Metrics24APICalls;
  23. use App\Services\MmpComponents;
  24. use App\Services\MysqlQueries;
  25. use App\Services\UsersComponents;
  26. use Doctrine\Persistence\ManagerRegistry;
  27. use Mmoreram\GearmanBundle\Service\GearmanClientInterface;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use App\Repository\MafoPublisherCabinetManagerMappingWithAffiliateRepository;
  33. use Symfony\Component\HttpFoundation\Response;
  34. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  35. use function GuzzleHttp\json_encode;
  36. use App\Traits\TrafficReportTrait;
  37. /**
  38.  *
  39.  * Offer related routes with endpoint /api/offers/{route}
  40.  *
  41.  * @Route("/api/client/publisher", name="client_publisher_", host="%publishers_subdomain%")
  42.  */
  43. class ClientSidePublisherController extends AbstractController
  44. {
  45.     use TrafficReportTrait;
  46.     private $commonCalls;
  47.     private $doctrine;
  48.     private $mysqlQueries;
  49.     private $mafoFinancialToolsComponents;
  50.     private $alerts;
  51.     private $brandHasofferApi;
  52.     private $mmpComponents;
  53.     private $affiliateHasofferAPI;
  54.     private $usersComponents;
  55.     private $elasticCache;
  56.     private $projectDir;
  57.     private $s3;
  58.     private $impressionsApis;
  59.     private $metrics24APICalls;
  60.     private $gearmanClientInterface;
  61.     private $mappingRepository;
  62.     public function __construct(
  63.         Common                                                    $commonCalls,
  64.         ManagerRegistry                                           $doctrine,
  65.         MysqlQueries                                              $mysqlQueries,
  66.         MafoPublisherCabinetManagerMappingWithAffiliateRepository $mappingRepository,
  67.         MafoFinancialToolsComponents                              $mafoFinancialToolsComponents,
  68.         Alerts                                                    $alerts,
  69.         BrandHasofferApi                                          $brandHasofferApi,
  70.         MmpComponents                                             $mmpComponents,
  71.         AffiliateHasofferAPI                                      $affiliateHasofferAPI,
  72.         UsersComponents                                           $usersComponents,
  73.         ElasticCache                                              $elasticCache,
  74.         S3                                                        $s3,
  75.         ImpressionsApis                                           $impressionsApis,
  76.         Metrics24APICalls                                         $metrics24APICalls,
  77.         GearmanClientInterface                                    $gearmanClientInterface,
  78.         string                                                    $projectDir
  79.     )
  80.     {
  81.         $this->commonCalls $commonCalls;
  82.         $this->doctrine $doctrine;
  83.         $this->mysqlQueries $mysqlQueries;
  84.         $this->mafoFinancialToolsComponents $mafoFinancialToolsComponents;
  85.         $this->alerts $alerts;
  86.         $this->brandHasofferApi $brandHasofferApi;
  87.         $this->mmpComponents $mmpComponents;
  88.         $this->affiliateHasofferAPI $affiliateHasofferAPI;
  89.         $this->usersComponents $usersComponents;
  90.         $this->elasticCache $elasticCache;
  91.         $this->s3 $s3;
  92.         $this->impressionsApis $impressionsApis;
  93.         $this->metrics24APICalls $metrics24APICalls;
  94.         $this->gearmanClientInterface $gearmanClientInterface;
  95.         $this->projectDir $projectDir;
  96.         $this->mappingRepository $mappingRepository;
  97.     }
  98.     /**
  99.      * @Route("/validate", name="validate", methods={"GET"})
  100.      */
  101.     public function getValidateAction(Request $request)
  102.     {
  103.         return new JsonResponse(true);
  104.     }
  105.     /**
  106.      * @Route("/test", name="test", methods={"GET"})
  107.      */
  108.     public function getAgentControlAction(Request $request)
  109.     {
  110.         return new JsonResponse(true);
  111.     }
  112.     /**
  113.      * @Route("/login", name="login")
  114.      */
  115.     public function indexAction(AuthenticationUtils $authenticationUtils)
  116.     {
  117.         //        $authenticationUtils = $authenticationUtils->get('security.authentication_utils');
  118.         // get the login error if there is one
  119.         $error $authenticationUtils->getLastAuthenticationError();
  120.         // last username entered by the user
  121.         $lastUsername $authenticationUtils->getLastUsername();
  122.         return $this->render('/publisher/login/index.html.twig', [
  123.             'last_username' => $lastUsername,
  124.             'error' => $error,
  125.         ]);
  126.     }
  127.     /**
  128.      * @Route("/details", name="get_publisher_details",  methods={"GET"})
  129.      */
  130.     public function getPublishersDetails(Request $request): Response
  131.     {
  132.         $publisherInfo $this->getUser();
  133.         $publisherId $publisherInfo->getId();
  134.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  135.         $publisherData = [
  136.             'id' => $publisherInfo->getId(),
  137.             'email' => $publisherInfo->getEmail(),
  138.             'firstName' => $publisherInfo->getFirstName(),
  139.             'lastName' => $publisherInfo->getLastName(),
  140.             'status' => $publisherInfo->getStatus(),
  141.             'lastLoginAt' => $publisherInfo->getLastLoginAt(),
  142.             'dateUpdated' => $publisherInfo->getDateUpdated(),
  143.         ];
  144.         return $this->json($publisherData);
  145.     }
  146.     /**
  147.      * @Route("/report-columns/{report}", name="get_report_columns", methods={"GET"})
  148.      */
  149.     public function getReportColumnsAction(Request $request$report)
  150.     {
  151.         if (in_array($reportarray_keys(Config::TABLE_COLUMNS_WITH_JSON_FILE))) {
  152.             return new JsonResponse(array_values($this->commonCalls->getDataFromJsonFile(Config::TABLE_COLUMNS_WITH_JSON_FILE[$report])));
  153.         }
  154.     }
  155.     /**
  156.      * @Route("/hyper-statuses", name="get_hyper_statuses", methods={"GET"})
  157.      */
  158.     public function getHyperStatusesAction(Request $request)
  159.     {
  160.         $arr = [];
  161.         foreach (array_values(Config::HYPER_STATUS_MAFO_MACROS) as $key => $value) {
  162.             $arr[$value] = [
  163.                 'value' => $value,
  164.                 'label' => $value,
  165.             ];
  166.         }
  167.         return new JsonResponse(array_values($arr));
  168.     }
  169.     /**
  170.      * @Route("/affiliates", name="get_affiliates", methods={"GET"})
  171.      */
  172.     public function getAffiliatesAction(Request $request)
  173.     {
  174.         $publisherInfo $this->getUser();
  175.         $publisherId $publisherInfo->getId();
  176.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  177.         $keyword $request->query->get('keyword');
  178.         $dataByKeyword = [];
  179.         if ($keyword) {
  180.             $dataByKeyword $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateByKeyword($keyword);
  181.         }
  182.         $statusArr $request->query->get('status') != '' $request->query->get('status') : [Config::ACTIVE_STATUS];
  183.         $affiliateData $this->commonCalls->getPublisherAffiliateListByStatusWithKeys($statusArr$mappedAffiliateIds);
  184.         $affiliateList = [];
  185.         foreach ($affiliateData as $key => $value) {
  186.             $affiliateList[$value['id']] = [
  187.                 'value' => $value['id'],
  188.                 'label' => $value['id'] . ' - ' $value['name'],
  189.                 'status' => $value['status']
  190.             ];
  191.         }
  192.         foreach ($dataByKeyword as $key => $value) {
  193.             if (!array_key_exists($value['affiliateId'], $affiliateList)) {
  194.                 $temp = [
  195.                     'value' => (int)$value['affiliateId'],
  196.                     'label' => $value['affiliateId'] . ' - ' $value['company'],
  197.                     'status' => $value['status']
  198.                 ];
  199.                 $affiliateList[$value['affiliateId']] = $temp;
  200.             }
  201.         }
  202.         ksort($affiliateList);
  203.         return new JsonResponse(array_values($affiliateList));
  204.     }
  205.     /**
  206.      * @Route("/mafo-users", name="get_mafo_users", methods={"GET"})
  207.      */
  208.     public function getAffiliateManagersAction(Request $request)
  209.     {
  210.         $affiliateData $this->getAffiliateAndManagerData();
  211.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  212.         if (empty($mappedAffiliateIds)) {
  213.             return new JsonResponse([]);
  214.         }
  215.         $accountManagerEmails $this->doctrine->getRepository(MafoAffiliates::class)
  216.             ->getAccountManagerEmailsByAffiliateIds($mappedAffiliateIds);
  217.         if (empty($accountManagerEmails)) {
  218.             return new JsonResponse([]);
  219.         }
  220.         $employeesInfo $this->doctrine->getRepository(Employees::class)
  221.             ->getEmployeesByEmails($accountManagerEmails);
  222.         $responseArr = [];
  223.         foreach ($employeesInfo as $email => $employee) {
  224.             $responseArr[] = [
  225.                 'value' => $employee['email'] ?? '',
  226.                 'label' => $employee['fullName'] . "[{$employee['email']}]"
  227.             ];
  228.         }
  229.         usort($responseArr, fn($a$b) => strcmp($a['label'], $b['label']));
  230.         return new JsonResponse($responseArr);
  231.     }
  232.     private function getAffiliateAndManagerData()
  233.     {
  234.         $publisherInfo $this->getUser();
  235.         $publisherId $publisherInfo->getId();
  236.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  237.         $accountManagerEmails $this->doctrine->getRepository(MafoAffiliates::class)
  238.             ->getAccountManagerEmailsByAffiliateIds($mappedAffiliateIds);
  239.         $mappedAffiliateIds array_map('strval'$mappedAffiliateIds);
  240.         return [
  241.             'formattedArray' => [
  242.                 'MULTISELECT_MAFO_AFFILIATES' => $mappedAffiliateIds,
  243.             ],
  244.             'formattedTrafficReportArray' => [
  245.                 'MULTISELECT_MAFO_AFFILIATES' => $mappedAffiliateIds,
  246.             ],
  247.             'mappedAffiliateIds' => $mappedAffiliateIds,
  248.             'accountManagerEmails' => $accountManagerEmails,
  249.         ];
  250.     }
  251.     /**
  252.      * @Route("/financial-report", name="get_financial_report", methods={"GET"})
  253.      */
  254.     public function getfinancialReportAction(Request $request)
  255.     {
  256.         $affiliateData $this->getAffiliateAndManagerData();
  257.         $formattedArray $affiliateData['formattedArray'];
  258.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  259.         $mappedAccountManagerEmails $affiliateData['accountManagerEmails'];
  260.         if (empty($mappedAffiliateIds)) {
  261.             return new JsonResponse([
  262.                 'response' => [
  263.                     'success' => true,
  264.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  265.                     'data' => [],
  266.                     'message' => 'No data available.',
  267.                     'error' => null
  268.                 ]
  269.             ], Config::HTTP_STATUS_CODE_OK);
  270.         }
  271.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  272.         $validationError $this->validatePublisherFinancialReportFields($selectedColumns);
  273.         if ($validationError !== null) {
  274.             return new JsonResponse($validationErrorConfig::HTTP_STATUS_CODE_BAD_REQUEST);
  275.         }
  276.         $filtersSelected $request->query->get('filters') ?? [];
  277.         $excludedFlagForFilters $request->query->get('excludedFlagForFilters') ?? [];
  278.         $processedFilters $this->processPublisherFinancialReportFilters(
  279.             $filtersSelected,
  280.             $excludedFlagForFilters,
  281.             $mappedAffiliateIds
  282.         );
  283.         $filters $processedFilters['filters'];
  284.         $excludedFiltersFlags $processedFilters['excludedFiltersFlags'];
  285.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  286.         $page $request->query->get('page') ? $request->query->get('page') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  287.         $sortBy $request->query->get('sortBy') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_BY;
  288.         $sortType $request->query->get('sortType') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_TYPE;
  289.         $dateStart date('Y-m-1'strtotime('-0 month'strtotime($request->query->get('startDate'))));
  290.         $dateEnd date('Y-m-1'strtotime('+0 month 'strtotime($request->query->get('endDate'))));
  291.         if ($request->query->get('downloadCSV') == 'true') {
  292.             $limit Config::REPORTS_PAGINATION_DEFAULT_CSV_PAGE_SIZE;
  293.             $page Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  294.         }
  295.         $finalArr $this->mafoFinancialToolsComponents->getPayoutTotalAggregatedData($dateStart$dateEnd$filters$excludedFiltersFlags$selectedColumnsnull);
  296.         $allowedStatuses array_values(Config::HYPER_STATUS_AFFILIATE_MAFO_MACROS);
  297.         foreach ($finalArr as &$record) {
  298.             if (!in_array($record['hyperStatus'], $allowedStatuses)) {
  299.                 $record['hyperStatus'] = '';
  300.             }
  301.         }
  302.         $tableColumns $this->commonCalls->changeColumnVisibilityForTable(array_values($this->commonCalls->getDataFromJsonFile(Config::JSON_FILE_CLIENT_SIDE_PUBLIHSER_FINANCIAL_REPORT)), $selectedColumns, []);
  303.         if ($request->query->get('downloadCSV') == 'true') {
  304.             $this->commonCalls->downloadCSV($tableColumns$finalArr'Financial Report ' $dateStart '_' $dateEnd);
  305.         }
  306.         return new JsonResponse($this->commonCalls->getReportResponse($finalArr$tableColumns$limit$page$sortBy$sortType));
  307.     }
  308.     /**
  309.      * @Route("/traffic-report", methods={"GET"})
  310.      */
  311.     public function getTrafficReport(Request $request)
  312.     {
  313.         $affiliateData $this->getAffiliateAndManagerData();
  314.         $formattedTrafficReportArray $affiliateData['formattedTrafficReportArray'];
  315.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  316.         if (empty($mappedAffiliateIds)) {
  317.             return new JsonResponse([
  318.                 'response' => [
  319.                     'success' => true,
  320.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  321.                     'data' => [],
  322.                     'message' => 'No data available.',
  323.                     'error' => null]
  324.             ], Config::HTTP_STATUS_CODE_OK);
  325.         }
  326.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  327.         $validationError $this->validatePublisherTrafficReportFields($selectedColumns);
  328.         if ($validationError !== null) {
  329.             return new JsonResponse($validationErrorConfig::HTTP_STATUS_CODE_BAD_REQUEST);
  330.         }
  331.         $filtersSelected $request->query->get('filters') ?? [];
  332.         $excludedFlagForFilters $request->query->get('excludedFlagForFilters') ?? [];
  333.         $processedFilters $this->processPublisherTrafficReportFilters(
  334.             $filtersSelected,
  335.             $excludedFlagForFilters,
  336.             $mappedAffiliateIds
  337.         );
  338.         $filters $processedFilters['filters'];
  339.         $excludedFiltersFlags $processedFilters['excludedFiltersFlags'];
  340.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  341.         $groupedColumns $request->query->get('groups') != '' $request->query->get('groups') : [];
  342.         $dateStart date('Y-m-d'strtotime($request->query->get('startDate')));
  343.         $dateEnd date('Y-m-d'strtotime($request->query->get('endDate')));
  344.         $eventTimestampFrom strtotime($dateStart);
  345.         $eventTimeStampTo strtotime($dateEnd);
  346.         $sortBy $request->query->get('sortBy') ?? Config::REPORTS_PAGINATION_MMP_REPORT_DEFAULT_SORT_BY;
  347.         $sortType $request->query->get('sortType') ?? Config::REPORTS_PAGINATION_DEFAULT_SORT_TYPE;
  348.         $page $request->query->get('page') ?? Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  349.         $limit $request->query->get('limit') ?? Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  350.         $downloadDataAsCSV $request->query->get('downloadCSV') == 'true';
  351.         $tableColumns $this->commonCalls->changeColumnVisibilityForTable(
  352.             array_values($this->commonCalls->getDataFromJsonFile(Config::JSON_FILE_GLOBAL_NETWORK_REPORT)),
  353.             $selectedColumns,
  354.             []
  355.         );
  356.             $finalReportData $this->mmpComponents->getMmpCumulativeData(
  357.                 $filters,
  358.                 $excludedFiltersFlags,
  359.                 $eventTimestampFrom,
  360.                 $eventTimeStampTo,
  361.                 $selectedColumns,
  362.                 $groupedColumns
  363.             );
  364.         $finalReportData $this->mmpComponents->normalizeMmpSource($finalReportData);
  365.         foreach ($tableColumns as $key => $value) {
  366.             if (isset($value['aggregate']) && $value['aggregate'] == 'sum') {
  367.                 $num round(array_sum(array_column($finalReportData$value['accessor'])), 2);
  368.                 if ($value['category'] == 'statistics') {
  369.                     $tableColumns[$key]['Footer'] = number_format($num);
  370.                 } else {
  371.                     $tableColumns[$key]['Footer'] = number_format($num2);
  372.                 }
  373.             }
  374.         }
  375.         if ($downloadDataAsCSV) {
  376.             $this->commonCalls->downloadCSV($tableColumns$finalReportData'Traffic Report ' $dateStart '_' $dateEnd);
  377.         } else {
  378.             $finalReportData array_values($finalReportData);
  379.             if (sizeof($finalReportData)) {
  380.                 $entity $finalReportData[0];
  381.                 if (array_key_exists($sortBy$entity)) {
  382.                     $sortFlag 3;
  383.                     if ($sortType == Config::SORT_TYPE_ASC) {
  384.                         $sortFlag 4;
  385.                     }
  386.                     array_multisort(array_column($finalReportData$sortBy), $sortFlag$finalReportData);
  387.                 }
  388.             }
  389.             $offset $limit * ($page 1);
  390.             $totalRecordCount sizeof($finalReportData);
  391.             $noOfPages ceil($totalRecordCount $limit);
  392.             return new JsonResponse([
  393.                 'response' => [
  394.                     'success' => true,
  395.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  396.                     'data' => [
  397.                         'tableColumns' => $tableColumns,
  398.                         'data' => array_slice($finalReportData$offset$limit),
  399.                         'metaData' => [
  400.                             'total' => $totalRecordCount,
  401.                             'limit' => (int)$limit,
  402.                             'page' => (int)$page,
  403.                             'pages' => (int)$noOfPages,
  404.                         ]
  405.                     ],
  406.                     'error' => null
  407.                 ]
  408.             ], Config::HTTP_STATUS_CODE_OK);
  409.         }
  410.     }
  411.     /**
  412.      * @Route("/table-columns/{table}", name="get_table_columns", methods={"GET"})
  413.      */
  414.     public function getTableColumnsAction(Request $request$table)
  415.     {
  416.         return new JsonResponse(array_values($this->commonCalls->getDataFromJsonFile(Config::TABLE_COLUMNS_WITH_JSON_FILE[$table])));
  417.     }
  418.     /**
  419.      * @Route("/mobile-apps-list", name="get_mobile_apps_list", methods={"GET"})
  420.      */
  421.     public function getMobileAppsListAction(Request $request)
  422.     {
  423.         $mobileAppsData $this->doctrine->getRepository(MmpMobileApps::class)->getMmpMobileAppByIsDeleted(0);
  424.         $appIds array_values(array_unique(array_merge(array_column($mobileAppsData'bundleId'), [])));
  425.         $appData $this->commonCalls->getAppInfoWithKeys();
  426.         $data = [];
  427.         foreach ($appIds as $key => $value) {
  428.             if (preg_match("/\t/"$value)) {
  429.                 continue;
  430.             }
  431.             $appName array_key_exists($value$appData) ? " - " $appData[$value]['title'] : '';
  432.             $data[$value] = [
  433.                 'value' => $value,
  434.                 'label' => $value $appName
  435.             ];
  436.         }
  437.         return new JsonResponse(array_values($data));
  438.     }
  439.     /**
  440.      * @Route("/countries", name="get_countries", methods={"GET"})
  441.      */
  442.     public function getCountriesAction()
  443.     {
  444.         $countryList = [];
  445.         foreach (Config::COUNTRIES as $key => $value) {
  446.             $countryList[$key] = [
  447.                 'value' => $key,
  448.                 'label' => $key ' - ' $value['name']
  449.             ];
  450.         }
  451.         ksort($countryList);
  452.         return new JsonResponse(array_values($countryList));
  453.     }
  454.     /**
  455.      * @Route("/mafo-affiliates", methods={"GET"})
  456.      */
  457.     public
  458.     function getMafoAffiliatesAction(Request $request)
  459.     {
  460.         $affiliateData $this->getAffiliateAndManagerData();
  461.         $mappedAffiliateIds $affiliateData['mappedAffiliateIds'];
  462.         if (empty($mappedAffiliateIds)) {
  463.             return new JsonResponse([]);
  464.         }
  465.         $affiliates $this->doctrine->getRepository(MafoAffiliates::class)->getAffiliates([], [], Config::REPORTS_PAGINATION_DEFAULT_CSV_PAGE_SIZEConfig::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBERConfig::REPORTS_PAGINATION_DEFAULT_SORT_BYConfig::REPORTS_PAGINATION_DEFAULT_SORT_TYPE);
  466.         $arr = [];
  467.         foreach ($affiliates as $key => $value) {
  468.             if (in_array((string)$value['id'], $mappedAffiliateIds)) {
  469.                 $arr[] = [
  470.                     'value' => $value['id'],
  471.                     'label' => $value['id'] . ' - ' $value['name']
  472.                 ];
  473.             }
  474.         }
  475.         return new JsonResponse($arr);
  476.     }
  477.     /**
  478.      * @Route("/offers", name="get_offers", methods={"GET"})
  479.      */
  480.     public function getPublisherOffersAction(Request $request)
  481.     {
  482.         $filters $request->query->get('filters') ?? [];
  483.         $excludedFlagForFilters $request->query->get('excludedFlagForFilters') ?? [];
  484.         $publisherInfo $this->getUser();
  485.         $publisherId $publisherInfo->getId();
  486.         $limit $request->query->get('limit') ? $request->query->get('limit') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
  487.         $page $request->query->get('page') ? $request->query->get('page') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
  488.         $mmpOfferIds $appIds $mafoAdvertiserIds $geos = [];
  489.         if (isset($filters)) {
  490.             foreach ($filters as $key => $value) {
  491.                 $key === 'MULTISELECT_MMP_OFFERS' $mmpOfferIds $value false;
  492.                 $key === 'MULTISELECT_MMP_STATISTICS_APP' $appIds $value false;
  493.                 $key === 'MULTISELECT_MAFO_ADVERTISERS' $mafoAdvertiserIds $value false;
  494.                 $key === 'MULTISELECT_GEO' $geos $value false;
  495.             }
  496.         }
  497.         $mmpOfferIdsExcluded $appIdsExcluded $mafoAdvertiserIdsExcluded $excludeGeos = [];
  498.         if (isset($excludedFlagForFilters)) {
  499.             foreach ($excludedFlagForFilters as $key => $value) {
  500.                 $key === 'MULTISELECT_MMP_OFFERS' $mmpOfferIdsExcluded $value false;
  501.                 $key === 'MULTISELECT_MMP_STATISTICS_APP' $appIdsExcluded $value false;
  502.                 $key === 'MULTISELECT_MAFO_ADVERTISERS' $mafoAdvertiserIdsExcluded $value false;
  503.                 $key === 'MULTISELECT_GEO' $excludeGeos $value false;
  504.             }
  505.         }
  506.         $selectedColumns $request->query->get('data') != '' $request->query->get('data') : [];
  507.         $publisherOfferIds $this->mmpComponents->getVisibleOfferIdsForPublisherManager($publisherId);
  508.         $mappedAffiliateIds $this->mappingRepository->findMappedAffiliateIdsByPublisherId($publisherId);
  509.         // If no offers found for this publisher, return empty result
  510.         if (empty($publisherOfferIds)) {
  511.             return new JsonResponse([
  512.                 'response' => [
  513.                     'success' => true,
  514.                     'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  515.                     'data' => [
  516.                         'tableColumns' => [],
  517.                         'data' => [],
  518.                         'metaData' => [
  519.                             'total' => 0,
  520.                             'limit' => (int)$limit,
  521.                             'page' => (int)$page,
  522.                             'pages' => 0,
  523.                         ]
  524.                     ],
  525.                     'error' => null
  526.                 ]
  527.             ], Config::HTTP_STATUS_CODE_OK);
  528.         }
  529.         // Merge with existing mmpOfferIds filter
  530.         if (!empty($mmpOfferIds)) {
  531.             $mmpOfferIds array_intersect($mmpOfferIds$publisherOfferIds);
  532.         } else {
  533.             $mmpOfferIds $publisherOfferIds;
  534.         }
  535.         // Use the common service to get and process offers data
  536.         $filters = [
  537.             'MULTISELECT_MMP_OFFERS' => $mmpOfferIds,
  538.             'MULTISELECT_MMP_STATISTICS_APP' => $appIds,
  539.             'MULTISELECT_MAFO_ADVERTISERS' => $mafoAdvertiserIds,
  540.             'MULTISELECT_GEO' => $geos,
  541.         ];
  542.         $excludedFlagForFilters = [
  543.             'MULTISELECT_MMP_OFFERS' => $mmpOfferIdsExcluded,
  544.             'MULTISELECT_MMP_STATISTICS_APP' => $appIdsExcluded,
  545.             'MULTISELECT_MAFO_ADVERTISERS' => $mafoAdvertiserIdsExcluded,
  546.             'MULTISELECT_GEO' => $excludeGeos,
  547.         ];
  548.         $offersData $this->mmpComponents->getMmpOffersData($filters$excludedFlagForFilters);
  549.         $hoAffiliateListList $this->commonCalls->getAffiliateListByStatusWithKeys();
  550.         $processedData $this->mmpComponents->processOffersData($offersData$hoAffiliateListList);
  551.         $offersData $processedData['offersData'];
  552.         $publisherPermissionsByOfferId $processedData['publisherPermissionsByOfferId'];
  553.         $tableColumns $this->commonCalls->changeColumnVisibilityForTable(array_values($this->commonCalls->getDataFromJsonFile(Config::JSON_FILE_MMP_STATISTICS_MMP_OFFERS)), $selectedColumns, []);
  554.         // Pass publisher manager ID to filter allowed/blocked lists to show only managed affiliates
  555.         $finalArr $this->mmpComponents->formatOffersForResponse($offersData$publisherPermissionsByOfferId$publisherId);
  556.         $finalArr $this->mmpComponents->normalizeMmpSource($finalArr);
  557.         $finalArr $this->replacePayoutFromPartnerRules($finalArr$selectedColumns$mappedAffiliateIds);
  558.         $downloadCSV $request->query->get('downloadCSV');
  559.         if ($downloadCSV == || $downloadCSV === 'true' || $downloadCSV === true) {
  560.             $this->commonCalls->downloadCSV($tableColumns$finalArr'MMP Offers');
  561.         }
  562.         $offset $limit * ($page 1);
  563.         $totalRecordCount sizeof($finalArr);
  564.         $noOfPages ceil($totalRecordCount $limit);
  565.         return new JsonResponse([
  566.             'response' => [
  567.                 'success' => true,
  568.                 'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  569.                 'data' => [
  570.                     'tableColumns' => $tableColumns,
  571.                     'data' => array_slice($finalArr$offset$limit),
  572.                     'metaData' => [
  573.                         'total' => $totalRecordCount,
  574.                         'limit' => (int)$limit,
  575.                         'page' => (int)$page,
  576.                         'pages' => (int)$noOfPages,
  577.                     ]
  578.                 ],
  579.                 'error' => null
  580.             ]
  581.         ], Config::HTTP_STATUS_CODE_OK);
  582.     }
  583.     /**
  584.      * Get visible offers for a Publisher Manager based on new affiliate mapping logic
  585.      * @param int $publisherManagerId The Publisher Manager (PAM) ID
  586.      * @return array Array of visible offer IDs
  587.      */
  588.     /**
  589.      * @Route("/mmp-tracking-system", name="get_mmp-tracking-system", methods={"GET"})
  590.      */
  591.     public function getMmpTrackingSystem(Request $request)
  592.     {
  593.         $mmpTrackingSystem = [];
  594.         foreach (Config::MMP_TRACKING_SYSTEM_ADVERTISER_CABINET_SIMPLIFIED as $key => $value) {
  595.             $mmpTrackingSystem[] = [
  596.                 'value' => $key,
  597.                 'label' => $value
  598.             ];
  599.         }
  600.         return new JsonResponse($mmpTrackingSystem);
  601.     }
  602.     /**
  603.      * @Route("/mafo-offers", methods={"GET"})
  604.      */
  605.     public
  606.     function getMafoOffersAction(Request $request)
  607.     {
  608.         $offers $this->doctrine->getRepository(MafoOffers::class)->getOffersList();
  609.         $arr = [];
  610.         foreach ($offers as $key => $value) {
  611.             $arr[] = [
  612.                 'value' => $value['id'],
  613.                 'label' => $value['id'] . ' - ' $value['name']
  614.             ];
  615.         }
  616.         return new JsonResponse($arr);
  617.     }
  618.     /**
  619.      * @Route("/advertiser-manager", name="get_advertiser_managers", methods={"GET"})
  620.      */
  621.     public function getMafoUsersAction(Request $request)
  622.     {
  623.         // Forward to UtilitiesController logic
  624.         return $this->forward('App\Controller\UtilitiesController::getMafoUsersAction', [
  625.             'request' => $request,
  626.         ]);
  627.     }
  628.     /**
  629.      * Replace payout and payoutModelPretty values from mmp_partner_rules table
  630.      *
  631.      * @param array $finalArr - The formatted offers array
  632.      * @param array $selectedColumns - The columns selected by the user
  633.      * @param array $mappedAffiliateIds - The affiliate IDs mapped to the publisher
  634.      * @return array - The modified offers array with replaced payout values
  635.      */
  636.     private function replacePayoutFromPartnerRules(array $finalArr, array $selectedColumns, array $mappedAffiliateIds): array
  637.     {
  638.         if (empty($finalArr)) {
  639.             return $finalArr;
  640.         }
  641.         $mmpOfferIds array_unique(array_column($finalArr'mmpOfferId'));
  642.         if (empty($mmpOfferIds)) {
  643.             return $finalArr;
  644.         }
  645.         $mmpPartnerRulesRepo $this->doctrine->getRepository(\App\Entity\MmpPartnerRules::class);
  646.         $partnerRules $mmpPartnerRulesRepo->getPayoutRulesByMmpOfferIds($mmpOfferIds);
  647.         if (empty($partnerRules)) {
  648.             return $finalArr;
  649.         }
  650.         $payoutMap = [];
  651.         foreach ($partnerRules as $rule) {
  652.             $mmpOfferId $rule['mmpOfferId'];
  653.             if (!isset($payoutMap[$mmpOfferId])) {
  654.                 $payoutMap[$mmpOfferId] = [
  655.                     'payout' => $rule['payout'],
  656.                     'payoutModel' => $rule['payoutModel']
  657.                 ];
  658.             }
  659.         }
  660.         foreach ($finalArr as &$offer) {
  661.             $mmpOfferId $offer['mmpOfferId'];
  662.             if (isset($payoutMap[$mmpOfferId])) {
  663.                 $partnerPayout $payoutMap[$mmpOfferId];
  664.                 if ($partnerPayout['payout'] !== null) {
  665.                     $offer['payout'] = $partnerPayout['payout'];
  666.                 }
  667.                 if ($partnerPayout['payoutModel'] !== null) {
  668.                     $offer['payoutModelPretty'] = strtoupper($partnerPayout['payoutModel']);
  669.                 }
  670.             }
  671.         }
  672.         return $finalArr;
  673.     }
  674. }