<?php
namespace App\Controller;
use App\Config;
use App\Entity\Tune\AdvertiserInfo;
use App\Entity\Tune\AffiliateAccountManager;
use App\Entity\Tune\AffiliateInfo;
use App\Entity\Tune\AffiliateOfferApproval;
use App\Entity\AffiliateOfferBlock;
use App\Entity\AffiliateRating;
use App\Entity\AffiliateTagRelationship;
use App\Entity\Tune\AdvertiserAccountManager;
use App\Entity\Tune\AdvertiserTagRelationship;
use App\Entity\AffiliateTags;
use App\Entity\HoAffiliateMmpPartnerMapping;
use App\Entity\MafoId\MafoAdvertisersMapping;
use App\Entity\MmpPartners;
use App\Entity\ObjectMappingWithTuneWebAccount;
use App\Entity\OfferScheduledChanges;
use App\Entity\RecommendationsByObject;
use App\Entity\ScheduledDisableLinks;
use App\Entity\ApprovalControl;
use App\Entity\PriceBulkEdit;
use App\Entity\OfferCategoryRelationship;
use App\Entity\OfferCreativeFile;
use App\Entity\OfferGeoRelationship;
use App\Entity\OfferGoalsInfo;
use App\Entity\Tune\OfferInfo;
use App\Entity\OfferTagRelationship;
use App\Entity\OfferWhitelist;
use App\Entity\PayoutBulkEdit;
use App\Entity\PostbackControlLogs;
use App\Entity\ScheduledAffiliateOfferApproval;
use App\Entity\ScheduledAffiliateOfferBlock;
use App\Entity\ScheduledAffiliateTagOfferApproval;
use App\Entity\SourceTags;
use App\Entity\AffiliateOfferBlockRepository;
use App\Entity\Tag;
use App\Entity\UserApiKey;
use App\Services\AffiliateHasofferAPI;
use App\Services\Alerts;
use App\Services\Aws\ElasticCache;
use App\Services\Aws\S3;
use App\Services\BrandHasofferAPI;
use App\Services\Common;
use App\Services\FinancialToolsComponents;
use App\Services\HyperApis;
use App\Services\ImpressionsApis;
use App\Services\MafoObjectsComponents;
use App\Services\Metrics24APICalls;
use App\Services\MmpComponents;
use App\Services\MysqlQueries;
use App\Services\UsersComponents;
use Doctrine\Persistence\ManagerRegistry;
use Mmoreram\GearmanBundle\Service\GearmanClientInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use function GuzzleHttp\Psr7\str;
/**
*
* Database Navigation Tab related routes with endpoint /api/tune-database/{route}
*
* @Route("/api/tune-database", name="database_tune", host="%main_subdomain%")
*/
class TuneDatabaseController extends AbstractController
{
private $commonCalls;
private $doctrine;
private $mysqlQueries;
private $brandHasofferApi;
private $elasticCache;
private $projectDir;
private $s3;
private $impressionsApis;
private $metrics24APICalls;
private $gearmanClientInterface;
public function __construct(Common $commonCalls, ManagerRegistry $doctrine, MysqlQueries $mysqlQueries, BrandHasofferApi $brandHasofferApi, ElasticCache $elasticCache, ImpressionsApis $impressionsApis, string $projectDir)
{
$this->commonCalls = $commonCalls;
$this->doctrine = $doctrine;
$this->mysqlQueries = $mysqlQueries;
$this->brandHasofferApi = $brandHasofferApi;
$this->elasticCache = $elasticCache;
$this->impressionsApis = $impressionsApis;
$this->projectDir = $projectDir;
}
/**
* @Route("/bulk-cap", name="get_bulk_cap", methods={"GET"})
*/
public function getBulCapAction(Request $request)
{
$bulkData = $this->commonCalls->getBulkCapData();
$affiliateTagsForHO = $this->brandHasofferApi->getAffiliateTags()['response']['data']['data'];
$affiliateTags = [];
foreach ($affiliateTagsForHO as $key => $value) {
$affiliateTags[] = [
'value' => $key,
'label' => $key . " - " . $value['Tag']['name']
];
}
$affiliateOfferCapType = [];
foreach (Config::AFFILIATE_OFFER_CAP_TYPE as $value) {
$affiliateOfferCapType[] = [
'value' => $value,
'label' => str_replace("_", " ", ucfirst($value))
];
}
$response = [
'affiliateOfferCapType' => $affiliateOfferCapType,
'affiliateTags' => $affiliateTags,
'tableData' => $bulkData
];
return new JsonResponse($response);
}
/**
* @Route("/bulk-cap", name="delete_bulk_cap", methods={"DELETE"})
*/
public function deleteBulCapAction(Request $request)
{
$this->mysqlQueries->deleteFromBulkCapById($request->query->get('id'));
$response = [
'tableData' => $this->commonCalls->getBulkCapData()
];
return new JsonResponse($response);
}
/**
* @Route("/bulk-cap", name="post_bulk_cap", methods={"POST"})
*/
public function postBulCapAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$affiliateTagList = $payload['affiliateTagList'];
$affiliateOfferCapType = $payload['affiliateOfferCapType'];
$capValue = (int)$payload['capValue'];
$offerList = $payload['offerList'];
$affiliateTagArr = [];
foreach ($affiliateTagList as $key => $value) {
array_push($affiliateTagArr, $value['value']);
}
$offerIdArr = [];
foreach ($offerList as $key => $value) {
array_push($offerIdArr, $value['value']);
}
$affiliateOfferCapArr = [];
foreach ($affiliateOfferCapType as $key => $value) {
array_push($affiliateOfferCapArr, $value['value']);
}
// $offerInfoArr = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
$offerInfoArr = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
$affiliateTagArr = $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagArr)['response']['data']['data'];
foreach ($offerInfoArr as $key => $value) {
foreach ($affiliateTagArr as $tagId => $v) {
foreach ($affiliateOfferCapArr as $capType) {
$combinationExist = $this->mysqlQueries->getOfferIdAffiliateTagIdFromBulkCap($value['offerId'], $tagId, $capType);
if ($combinationExist) {
$this->mysqlQueries->deleteFromBulkCapById($combinationExist->getId());
}
$this->mysqlQueries->insertToBulkCap($tagId, $v['Tag']['name'], $capType, $value['offerId'], $value['name'], $capValue, ucwords($this->getUser()->getName()));
}
}
}
$response = [
'tableData' => $this->commonCalls->getBulkCapData()
];
return new JsonResponse($response);
}
/**
* @Route("/bulk-cap-affiliate", name="get_bulk_cap_affiliate", methods={"GET"})
*/
public function getBulCapByAffiliateAction(Request $request)
{
return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
}
/**
* @Route("/bulk-cap-affiliate", name="delete_bulk_cap_affiliate", methods={"DELETE"})
*/
public function deleteBulCapAffiliateAction(Request $request)
{
$this->mysqlQueries->deleteBulkCapByAffiliateById($request->query->get('id'));
return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
}
/**
* @Route("/bulk-cap-affiliate", name="post_bulk_cap_affiliate", methods={"POST"})
*/
public function postBulCapAffiliateAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$affiliateList = $payload['affiliateList'];
$affiliateOfferCapType = $payload['affiliateOfferCapType'];
$capValue = (int)$payload['capValue'];
$offerList = $payload['offerList'];
$offerIdArr = [];
foreach ($offerList as $key => $value) {
array_push($offerIdArr, $value['value']);
}
$affiliateIdArr = [];
foreach ($affiliateList as $key => $value) {
array_push($affiliateIdArr, $value['value']);
}
$affiliateOfferCapArr = [];
foreach ($affiliateOfferCapType as $key => $value) {
array_push($affiliateOfferCapArr, $value['value']);
}
// $offerInfoArr = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
$offerInfoArr = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
$affiliateInfoArr = $this->brandHasofferApi->getAffiliateByAffiliateIdsArr($affiliateIdArr)['response']['data'];
foreach ($offerInfoArr as $key => $value) {
foreach ($affiliateInfoArr as $affiliateId => $v) {
foreach ($affiliateOfferCapArr as $capType) {
if ($capValue > 0 && in_array($capType, Config::AFFILIATE_OFFER_CAP_TYPE)) {
$combinationExist = $this->mysqlQueries->getBulkCapByAffiliate($value['offerId'], $affiliateId, $capType);
if ($combinationExist) {
$this->mysqlQueries->deleteBulkCapByAffiliateById($combinationExist->getId());
}
$this->mysqlQueries->insertToBulkCapByAffiliate($affiliateId, $v['Affiliate']['company'], $capType, $value['offerId'], $value['name'], $capValue, ucwords($this->getUser()->getName()));
}
}
}
}
return new JsonResponse($this->commonCalls->getBulkCapByAffiliateData());
}
/**
* @Route("/disable-links-added-from", name="get_disable_links_added_from", methods={"GET"})
*/
public function getDisableLinkLogsAddedFrom(Request $request)
{
$addedFromArr = [];
foreach (Config::DISABLE_LINK_ADDED_FROM as $key => $value) {
$addedFromArr[] = [
'value' => $value,
'label' => $value
];
}
return new JsonResponse($addedFromArr);
}
/**
* @Route("/disable-links-csv", name="get_disable_links_csv", methods={"GET"})
*/
public function getDisableLinksCsvAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$affiliateIdArray = !empty($queryParams['affiliates']) && is_string($queryParams['affiliates']) ? explode(",", $queryParams['affiliates']) : [];
$offerIdArray = !empty($queryParams['offers']) && is_string($queryParams['offers']) ? explode(",", $queryParams['offers']) : [];
$sourceIdArray = !empty($queryParams['sources']) && is_string($queryParams['sources']) ? explode(",", $queryParams['sources']) : [];
$advertiserArray = !empty($queryParams['advertisers']) && is_string($queryParams['advertisers']) ? explode(",", $queryParams['advertisers']) : [];
$addedFromArr = !empty($queryParams['addedFrom']) && is_string($queryParams['addedFrom']) ? explode(",", $queryParams['addedFrom']) : [];
$disableLinkData = $this->commonCalls->getDisableLinkLogs($affiliateIdArray, $offerIdArray, $sourceIdArray, $advertiserArray, $addedFromArr, $dateStart, $dateEnd);
$dataToExport = [];
if (!empty($disableLinkData)) {
// $dataToExport[] = implode(",", array_keys($disableLinkData[0]));
$headers = [
'Id',
'Affiliate Id',
'Affiliate Name',
'Offer Id',
'Offer Name',
'Source',
'Advertiser Id',
'Advertiser Name',
'Added From',
'Date Inserted'
];
$dataToExport[] = implode(",", $headers);
foreach ($disableLinkData as $key => $value) {
$data = [
$value['id'],
$value['affiliateId'],
str_replace(",", " ", $value['affiliateName']),
$value['offerId'],
str_replace(",", " ", $value['offerName']),
$value['source'],
$value['advertiserId'],
str_replace(",", " ", $value['advertiserName']),
$value['addedFrom'],
$value['date_inserted']
];
array_push($dataToExport, implode(",", $data));
}
}
$response = new Response(implode("\n", $dataToExport));
$response->headers->set('Content-Type', 'text/csv');
return $response;
}
/**
* @Route("/advertiser-info", name="get_advertiser_info", methods={"GET"})
*/
public function getAdvertiserInfoAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$advertiserIdArr = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(",", $queryParams['advertiserIds']) : [];
$advertiserList = $this->commonCalls->getAdvertisersListByStatusWithKeys();
if (empty($advertiserIdArr)) {
$advertiserIdArr = array_keys($advertiserList);
}
$chooseBy = $request->query->get('chooseBy');
$status = 'active';
$data = $this->mysqlQueries->getDataForAdvertiserOfferCountForChart($advertiserIdArr, $dateStart, $dateEnd, $chooseBy, $status);
$labels = [];
foreach ($data as $key => $value) {
$label = null;
if (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_HOUR, $value)) {
$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';
} elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_DAY, $value)) {
$label = $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY];
} elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_MONTH, $value)) {
$label = $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH];
}
$timestamp = strtotime($label);
$data[$key]['timestamp'] = $timestamp;
if ($label && !in_array($label, $labels)) {
$labels[$timestamp] = $label;
}
}
ksort($labels);
$temp = [];
foreach ($data as $key => $value) {
$temp[$value['advertiserId']][$value['timestamp']] = round($value['average'], 2);
}
$dataForChartTemp = [];
foreach ($temp as $key => $value) {
foreach (array_keys($labels) as $label) {
if (array_key_exists($label, $value)) {
$dataForChartTemp[$key][$label] = $value[$label];
} else {
$dataForChartTemp[$key][$label] = '0';
}
}
}
// echo json_encode($dataForChartTemp);die;
$dataForChart = [];
foreach ($dataForChartTemp as $key => $value) {
if (!array_key_exists($key, $dataForChart)) {
$dataForChart[$key] = [
'label' => $key,
'backgroundColor' => 'transparent',
'pointHoverBackgroundColor' => '#fff',
'borderWidth' => 2,
'data' => [],
'lineTension' => 0,
'pointRadius' => 1,
'borderColor' => '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT)
];
}
$dataForChart[$key]['data'] = array_values($value);
}
$finalLabels = [];
foreach ($labels as $timestamp => $datetime) {
if ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_HOUR) {
array_push($finalLabels, date('H', strtotime($datetime)));
} elseif ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_DAY) {
array_push($finalLabels, date('d', strtotime($datetime)));
} elseif ($chooseBy == Config::ADVERTISER_INFO_CHOOSE_BY_MONTH) {
array_push($finalLabels, date('m', strtotime($datetime)));
} else {
array_push($finalLabels, date('H', strtotime($datetime)));
}
}
return new JsonResponse([
'labels' => array_values($finalLabels),
'datasets' => array_values($dataForChart)
]);
}
/**
* @Route("/advertiser-info-csv", name="advertiser_info_csv", methods={"GET"})
*/
public function getAdvertiserInfoCsvAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$advertiserIdArr = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(",", $queryParams['advertiserIds']) : [];
$advertiserList = $this->commonCalls->getAdvertisersListByStatusWithKeys();
if (empty($advertiserIdArr)) {
$advertiserIdArr = array_keys($advertiserList);
}
$chooseBy = $request->query->get('chooseBy');
$status = 'active';
$data = $this->mysqlQueries->getDataForAdvertiserOfferCountForChart($advertiserIdArr, $dateStart, $dateEnd, $chooseBy, $status);
$labels = [];
$timestampsByAdvertiserId = [];
foreach ($data as $key => $value) {
$label = null;
if (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_HOUR, $value)) {
$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';
} elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_DAY, $value)) {
$label = $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_DAY];
} elseif (array_key_exists(Config::ADVERTISER_INFO_CHOOSE_BY_MONTH, $value)) {
$label = $value[Config::ADVERTISER_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::ADVERTISER_INFO_CHOOSE_BY_MONTH];
}
$timestamp = strtotime($label);
$data[$key]['timestamp'] = $timestamp;
if ($label && !in_array($label, $labels)) {
$labels[$timestamp] = $label;
$timestampsByAdvertiserId[$value['advertiserId']][] = $timestamp;
}
}
$temp = [];
foreach ($data as $key => $value) {
$temp[$value['advertiserId']][$value['timestamp']] = $value['average'];
}
ksort($labels);
$dataForCsv = [];
foreach ($temp as $key => $value) {
foreach (array_keys($labels) as $label) {
if (array_key_exists($label, $value)) {
$dataForCsv[$key][$label] = $value[$label];
} else {
$dataForCsv[$key][$label] = '0';
}
}
}
$labelsToDatetime = array_values($labels);
$dataToExport = [];
if (!empty($dataForCsv)) {
$headers = array_merge([""], $labelsToDatetime);
$dataToExport[] = implode(",", $headers);
foreach ($dataForCsv as $key => $value) {
$data = [array_key_exists($key, $advertiserList) ? $key . ' ' . str_replace(",", " ", $advertiserList[$key]['name']) : $key];
foreach ($value as $k => $v) {
array_push($data, round($v, 2));
}
array_push($dataToExport, implode(",", $data));
}
}
$response = new Response(implode("\n", $dataToExport));
$response->headers->set('Content-Type', 'text/csv');
return $response;
}
/**
* @Route("/payout-bulk-edit", name="get_payout_bulk_edit", methods={"GET"})
*/
public function getPayoutBulkEditAction(Request $request)
{
return new JsonResponse($this->getPayoutBulkEditData());
}
/**
* @Route("/payout-bulk-edit", name="post_payout_bulk_edit", methods={"POST"})
*/
public function postPayoutBulkEditAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$affiliateTagIds = $payload['affiliateTagIds'];
$affiliateIds = $payload['affiliateIds'];
$offerIds = $payload['offerIds'];
$payout = $payload['price'];
if (!empty($offerIds)) {
// $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
if (!empty($affiliateTagIds)) {
$affiliateTagIdsInfo = $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagIds)['response']['data']['data'];
foreach ($affiliateTagIdsInfo as $affiliateTagId => $affiliateTagData) {
foreach ($offerInfo as $key => $value) {
$combinationExist = $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->checkPayoutBulkEditExist($affiliateTagId, null, $value['offerId']);
if ($combinationExist) {
if ($combinationExist->getPayout() != $payout) {
$this->getDoctrine()->getRepository(PayoutBulkEdit::class)->updatePayoutBulkEdit($affiliateTagId, null, $value['offerId'], $payout, ucwords($this->getUser()->getName()));
}
} else {
$this->getDoctrine()->getRepository(PayoutBulkEdit::class)->insertToPayoutBulkData($affiliateTagId, null, $payout, ucwords($this->getUser()->getName()), $value['offerId']);
}
}
}
}
if (!empty($affiliateIds)) {
$affiliateIdsInfo = $this->brandHasofferApi->getAffiliatesByAffiliateIdArr($affiliateIds)['response']['data'];
foreach ($affiliateIdsInfo as $affiliateId => $affiliateData) {
foreach ($offerInfo as $key => $value) {
$combinationExist = $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->checkPayoutBulkEditExist(null, $affiliateId, $value['offerId']);
if ($combinationExist) {
if ($combinationExist->getPayout() != $payout) {
$this->getDoctrine()->getRepository(PayoutBulkEdit::class)->updatePayoutBulkEdit(null, $affiliateId, $value['offerId'], $payout, ucwords($this->getUser()->getName()));
}
} else {
$this->getDoctrine()->getRepository(PayoutBulkEdit::class)->insertToPayoutBulkData(null, $affiliateId, $payout, ucwords($this->getUser()->getName()), $value['offerId']);
}
}
}
}
}
return new JsonResponse($this->getPayoutBulkEditData());
}
/**
* @Route("/payout-bulk-edit", name="delete_payout_bulk_edit", methods={"DELETE"})
*/
public function deletePayoutBulkEditAction(Request $request)
{
$this->getDoctrine()->getRepository(PayoutBulkEdit::class)->deletePayoutBulkEditData($request->query->get('id'));
return new JsonResponse($this->getPayoutBulkEditData());
}
private function getPayoutBulkEditData()
{
$data = $this->getDoctrine()->getRepository(PayoutBulkEdit::class)->getPayoutBulkEditData();
$payoutByAffiliateTag = [];
$payoutByAffiliate = [];
$distinctOfferIds = [];
foreach ($data as $key => $value) {
if (!in_array($value['offerId'], $distinctOfferIds)) {
array_push($distinctOfferIds, $value['offerId']);
}
}
$offerInfo = [];
if (!empty($distinctOfferIds)) {
// $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($distinctOfferIds)['response']['data'];
$offerInfo = $this->commonCalls->getOfferInfoByKey($distinctOfferIds);
}
foreach ($data as $key => $value) {
if ($value['dateUpdated']) {
$value['dateInserted'] = $value['dateUpdated']->format('Y-m-d H:i:s');
} else {
$value['dateInserted'] = '';
}
$value['offerName'] = array_key_exists($value['offerId'], $offerInfo) ? $offerInfo[$value['offerId']]['name'] : '';
if ($value['affiliateTagId'] && !$value['affiliateId']) {
$payoutByAffiliateTag[] = $value;
}
if (!$value['affiliateTagId'] && $value['affiliateId']) {
$payoutByAffiliate[] = $value;
}
}
return [
'dataByAffiliateTag' => $payoutByAffiliateTag,
'dataByAffiliate' => $payoutByAffiliate
];
}
/**
* @Route("/aff-off-approval", name="GET_AFFILIATE_OFFER_APPROVAL", methods={"GET"})
*/
public function getAffiliateOfferApproval(Request $request)
{
$queryParams = $request->query->all();
$affiliateIds = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(",", $queryParams['affiliateIds']) : [];
$advertiserIds = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(",", $queryParams['advertiserIds']) : [];
$offerIds = !empty($queryParams['offerIds']) && is_string($queryParams['offerIds']) ? explode(",", $queryParams['offerIds']) : [];
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$data = $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->getScheduledAffiliateOfferApprovalDataByFilters($affiliateIds, $offerIds, $advertiserIds, $dateStart, $dateEnd);
foreach ($data as $key => $value) {
$data[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
$data[$key]['affiliateOfferCapType'] = ucwords(str_replace("_", " ", $value['affiliateOfferCapType']));
}
return new JsonResponse($data);
}
/**
* @Route("/aff-off-approval", name="DELETE_AFFILIATE_OFFER_APPROVAL", methods={"DELETE"})
*/
public function deleteAffiliateOfferApproval(Request $request)
{
$id = $request->query->get('id');
$approvedData = $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->getDataById($id);
$affiliateOfferApprovedCombinations = $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkCombinationExistByOfferIdAffiliateId($approvedData->getOfferId(), $approvedData->getAffiliateId());
foreach ($affiliateOfferApprovedCombinations as $key => $value) {
if (!$value['isScheduled']) {
$isOfferApproved = $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($value['offerId'], $value['affiliateId']);
if ($isOfferApproved) {
$hoResponse = $this->brandHasofferApi->setOfferApprovalForAffiliate($value['offerId'], $value['affiliateId'], Config::AFFILIATE_OFFER_APPROVAL_REJECTED_STATUS);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($value['id']);
$this->doctrine->getRepository(AffiliateOfferApproval::class)->deleteById($isOfferApproved->getId());
}
}
} else {
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($value['id']);
}
}
return new JsonResponse(true);
}
/**
* @Route("/aff-off-approval", name="POST_AFFILIATE_OFFER_APPROVAL", methods={"POST"})
*/
public function postAffiliateOfferApproval(Request $request)
{
$payload = json_decode($request->getContent(), true);
$affiliateIds = $payload['affiliateIds'];
$capTypes = $payload['capTypes'];
$capValue = $payload['capValue'];
$offerIds = $payload['offerIds'];
$affiliateInfo = [];
$offerInfo = [];
if (!empty($affiliateIds)) {
$affiliateInfo = $this->brandHasofferApi->getAffiliatesByAffiliateIdArr($affiliateIds)['response']['data'];
}
if (!empty($offerIds)) {
// $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
}
foreach ($offerInfo as $key => $value) {
$advertiserInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $value['advertiserId']]);
$advertiserCompany = $advertiserInfo && $advertiserInfo->getCompany() ? $advertiserInfo->getCompany() : '';
foreach ($affiliateInfo as $k => $v) {
if (!empty($capTypes)) {
foreach ($capTypes as $capType) {
if (in_array($capType, Config::AFFILIATE_OFFER_CAP_TYPE)) {
$scheduledCombinationExist = $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkIfOfferAffiliateCombinationExistByCapType($value['offerId'], $k, $capType);
if ($scheduledCombinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
}
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->insertToScheduledOfferApproval($k, $v['Affiliate']['company'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany, $capType, $capValue, ucwords($this->getUser()->getName()));
}
}
} else {
$scheduledCombinationExist = $this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->checkIfOfferAffiliateCombinationExistByCapType($value['offerId'], $k, null);
if ($scheduledCombinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
}
$this->doctrine->getRepository(ScheduledAffiliateOfferApproval::class)->insertToScheduledOfferApproval($k, $v['Affiliate']['company'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany, null, null, ucwords($this->getUser()->getName()));
}
}
}
return new JsonResponse(true);
}
/**
* @Route("/aff-tag-off-approval", name="POST_AFFILIATE_TAG_OFFER_APPROVAL", methods={"POST"})
*/
public function postAffiliateTagOfferApproval(Request $request)
{
$payload = json_decode($request->getContent(), true);
$affiliateTagIds = $payload['affiliateTagIds'];
$capTypes = $payload['capTypes'];
$capValue = $payload['capValue'];
$offerIds = $payload['offerIds'];
$affiliateTagInfo = [];
$offerInfo = [];
if (!empty($affiliateTagIds)) {
$affiliateTagInfo = $this->brandHasofferApi->getAffiliateTagsByTagIdArr($affiliateTagIds)['response']['data']['data'];
}
if (!empty($offerIds)) {
// $offerInfo = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIds)['response']['data'];
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
}
foreach ($offerInfo as $key => $value) {
$advertiserInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $value['advertiserId']]);
$advertiserCompany = $advertiserInfo && $advertiserInfo->getCompany() ? $advertiserInfo->getCompany() : '';
foreach ($affiliateTagInfo as $k => $v) {
if (!empty($capTypes)) {
foreach ($capTypes as $capType) {
if (in_array($capType, Config::AFFILIATE_OFFER_CAP_TYPE)) {
$scheduledCombinationExist = $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkIfOfferAffiliateTagCombinationExistByCapType($key, $k, $capType);
if ($scheduledCombinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
}
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->insertToScheduledOfferApproval($k, $v['Tag']['name'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany, $capType, $capValue, ucwords($this->getUser()->getName()));
}
}
} else {
$scheduledCombinationExist = $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkIfOfferAffiliateTagCombinationExistByCapType($key, $k, null);
if ($scheduledCombinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($scheduledCombinationExist->getId());
}
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->insertToScheduledOfferApproval($k, $v['Tag']['name'], $value['offerId'], $value['name'], $value['advertiserId'], $advertiserCompany, null, null, ucwords($this->getUser()->getName()));
}
}
}
return new JsonResponse(true);
}
/**
* @Route("/aff-tag-off-approval", name="GET_AFFILIATE_TAG_OFFER_APPROVAL", methods={"GET"})
*/
public function getAffiliateTagOfferApproval(Request $request)
{
$queryParams = $request->query->all();
$affiliateTagIds = !empty($queryParams['affiliateTagIds']) && is_string($queryParams['affiliateTagIds']) ? explode(",", $queryParams['affiliateTagIds']) : [];
$advertiserIds = !empty($queryParams['advertiserIds']) && is_string($queryParams['advertiserIds']) ? explode(",", $queryParams['advertiserIds']) : [];
$offerIds = !empty($queryParams['offerIds']) && is_string($queryParams['offerIds']) ? explode(",", $queryParams['offerIds']) : [];
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$data = $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->getScheduledAffiliateTagOfferApprovalDataByFilters($affiliateTagIds, $offerIds, $advertiserIds, $dateStart, $dateEnd);
foreach ($data as $key => $value) {
$data[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
$data[$key]['affiliateTagOfferCapType'] = ucwords(str_replace("_", " ", $value['affiliateTagOfferCapType']));
}
return new JsonResponse($data);
}
/**
* @Route("/aff-tag-off-approval", name="DELETE_AFFILIATE_TAG_OFFER_APPROVAL", methods={"DELETE"})
*/
public function deleteAffiliateTagOfferApproval(Request $request)
{
$id = $request->query->get('id');
$approvedData = $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->getDataById($id);
$affiliateTagOfferApprovedCombinations = $this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->checkCombinationExistByOfferIdAffiliateTagId($approvedData->getOfferId(), $approvedData->getAffiliateTagId());
foreach ($affiliateTagOfferApprovedCombinations as $key => $value) {
if (!$value['isScheduled']) {
$affiliatesByTagId = $this->brandHasofferApi->getAffiliateTagRelation([$value['affiliateTagId']])['response']['data']['data'];
foreach ($affiliatesByTagId as $k => $v) {
$isOfferApproved = $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($value['offerId'], $v['AffiliatesTags']['affiliate_id']);
if ($isOfferApproved) {
$hoResponse = $this->brandHasofferApi->setOfferApprovalForAffiliate($value['offerId'], $v['AffiliatesTags']['affiliate_id'], Config::AFFILIATE_OFFER_APPROVAL_REJECTED_STATUS);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
$this->doctrine->getRepository(AffiliateOfferApproval::class)->deleteById($isOfferApproved->getId());
}
}
}
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
} else {
$this->doctrine->getRepository(ScheduledAffiliateTagOfferApproval::class)->deleteById($value['id']);
}
}
return new JsonResponse(true);
}
/**
* @Route("/weekly-analyze", name="GET_WEEKLY_ANALYZE", methods={"GET"})
*/
public function getWeeklyAnalyzeAction(Request $request)
{
$dateRangeI = $request->query->get('dateRangeI') ?? null;
$dateRangeII = $request->query->get('dateRangeII') ?? null;
$tuneAccounts = $request->query->get('tuneAccount') ?? [];
// if ($tuneAccounts !== '') {
// $tuneAccounts = explode(",", $tuneAccounts);
// }
if ($dateRangeI == null) {
$dateStartI = null;
$dateEndI = null;
} else {
$dateRangeIArray = explode(' - ', $dateRangeI);
$dateStartI = date('Y-m-d', strtotime($dateRangeIArray[0]));
$dateEndI = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeIArray[1])));
}
if ($dateRangeII == null) {
$dateStartII = null;
$dateEndII = null;
} else {
$dateRangeIIArray = explode(' - ', $dateRangeII);
$dateStartII = date('Y-m-d', strtotime($dateRangeIIArray[0]));
$dateEndII = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeIIArray[1])));
}
$advertiserIdsStr = $request->query->get('advertiserIds');
$advertiserIdArr = $advertiserIdsStr == "" ? [] : explode(",", $advertiserIdsStr);
$advertiserIdsManagerStr = $request->query->get('advertiserManagerIds');
$advertiserManagerIdArr = $advertiserIdsManagerStr == "" ? [] : explode(",", $advertiserIdsManagerStr);
$offerIdsStr = $request->query->get('offerIds');
$offerIdArr = $offerIdsStr == "" ? [] : explode(",", $offerIdsStr);
$affiliateIdsStr = $request->query->get('affiliateIds');
$affiliateIdArr = $affiliateIdsStr == "" ? [] : explode(",", $affiliateIdsStr);
$affiliateIdsManagerStr = $request->query->get('affiliateManagerIds');
$affiliateManagerIdArr = $affiliateIdsManagerStr == "" ? [] : explode(",", $affiliateIdsManagerStr);
$byAdvertiser = $request->query->get('byAdvertiser') ? true : false;
$byAffiliate = $request->query->get('byAffiliate') ? true : false;
$byOffer = $request->query->get('byOffer') ? true : false;
$data = ($this->getWeeklyAnalyzeData($advertiserIdArr, $advertiserManagerIdArr, $affiliateIdArr, $affiliateManagerIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $dateStartII, $dateEndII, $tuneAccounts));
return new JsonResponse($data);
}
/**
* @Route("/weekly-analyze-csv", name="GET_WEEKLY_ANALYZE_CSV", methods={"GET"})
*/
public function getWeeklyAnalyzeCSVAction(Request $request)
{
$dateRangeI = $request->query->get('dateRangeI') ?? null;
$dateRangeII = $request->query->get('dateRangeII') ?? null;
$tuneAccounts = $request->query->get('tuneAccount') ?? [];
// if ($tuneAccounts !== '') {
// $tuneAccounts = explode(",", $tuneAccounts);
// }
if ($dateRangeI == null) {
$dateStartI = null;
$dateEndI = null;
} else {
$dateRangeIArray = explode(' - ', $dateRangeI);
$dateStartI = date('Y-m-d', strtotime($dateRangeIArray[0]));
$dateEndI = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeIArray[1])));
}
if ($dateRangeII == null) {
$dateStartII = null;
$dateEndII = null;
} else {
$dateRangeIIArray = explode(' - ', $dateRangeII);
$dateStartII = date('Y-m-d', strtotime($dateRangeIIArray[0]));
$dateEndII = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeIIArray[1])));
}
$advertiserIdsStr = $request->query->get('advertiserIds');
$advertiserIdArr = $advertiserIdsStr == "" ? [] : explode(",", $advertiserIdsStr);
$advertiserIdsManagerStr = $request->query->get('advertiserManagerIds');
$advertiserManagerIdArr = $advertiserIdsManagerStr == "" ? [] : explode(",", $advertiserIdsManagerStr);
$offerIdsStr = $request->query->get('offerIds');
$offerIdArr = $offerIdsStr == "" ? [] : explode(",", $offerIdsStr);
$affiliateIdsStr = $request->query->get('affiliateIds');
$affiliateIdArr = $affiliateIdsStr == "" ? [] : explode(",", $affiliateIdsStr);
$affiliateIdsManagerStr = $request->query->get('affiliateManagerIds');
$affiliateManagerIdArr = $affiliateIdsManagerStr == "" ? [] : explode(",", $affiliateIdsManagerStr);
$byAdvertiser = $request->query->get('byAdvertiser') == 'true' ? true : false;
$byAffiliate = $request->query->get('byAffiliate') == 'true' ? true : false;
$byOffer = $request->query->get('byOffer') == 'true' ? true : false;
$stats = $this->getWeeklyAnalyzeData($advertiserIdArr, $advertiserManagerIdArr, $affiliateIdArr, $affiliateManagerIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $dateStartII, $dateEndII, $tuneAccounts);
$list = [];
if ($byAdvertiser) {
$list = $this->commonCalls->getAdvertisersListByStatusWithKeys();
} elseif ($byAffiliate) {
$list = $this->commonCalls->getAffiliateListByStatusWithKeys();
} elseif ($byOffer && !empty($offerIdArr)) {
// $list = $this->brandHasofferApi->getOffersByOfferIdsArr($offerIdArr)['response']['data'];
$list = $this->commonCalls->getOfferInfoByKey($offerIdArr);
}
foreach ($stats as $key => $value) {
if (array_key_exists($value['id'], $list)) {
if ($byAdvertiser) {
$stats[$key]['name'] = $list[$value['id']]['name'];
} elseif ($byAffiliate) {
$stats[$key]['name'] = $list[$value['id']]['name'];
} elseif ($byOffer && !empty($offerIdArr)) {
$stats[$key]['name'] = array_key_exists($value['id'], $list) ? $list[$value['id']]['name'] : '';
} else {
$stats[$key]['name'] = '';
}
} else {
$stats[$key]['name'] = '';
}
}
$csvHeaders = [
'Id',
'Name',
'DR_I_Clicks',
'DR_I_Conversions',
'DR_I_Revenue',
'DR_I_Payout',
'DR_I_Profit',
'DR_II_Clicks',
'DR_II_Conversions',
'DR_II_Revenue',
'DR_II_Payout',
'DR_II_Profit',
'Revenue_Percent',
'Payout_Percent',
'Profit_Percent'
];
$dataToExport = [];
array_push($dataToExport, implode(",", ['Date_Range_I', $dateStartI, $dateEndI]));
array_push($dataToExport, implode(",", ['Date_Range_II', $dateStartII, $dateEndII]));
array_push($dataToExport, implode(",", $csvHeaders));
foreach ($stats as $key => $value) {
$temp = [
$value['id'],
$value['name'],
$value['dateRangeIClicks'],
$value['dateRangeIConversions'],
$value['dateRangeIRevenue'],
$value['dateRangeIPayout'],
$value['dateRangeIProfit'],
$value['dateRangeIIClicks'],
$value['dateRangeIIConversions'],
$value['dateRangeIIRevenue'],
$value['dateRangeIIPayout'],
$value['dateRangeIIProfit'],
$value['payoutPercentChange'],
$value['revenuePercentChange'],
$value['profitPercentChange'],
];
array_push($dataToExport, implode(",", $temp));
}
$response = new Response(implode("\n", $dataToExport));
$response->headers->set('Content-Type', 'text/csv');
return $response;
}
private function getWeeklyAnalyzeData($advertiserIdArr, $advertiserManagerIdArr, $affiliateIdArr, $affiliateManagerIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $dateStartII, $dateEndII, $tuneAccounts)
{
$stats = [];
foreach (Config::MAFO_SYSTEM_IDENTIFIER_TUNE_ACCOUNTS as $tuneAccount) {
if (!empty($tuneAccounts) && !in_array($tuneAccount, $tuneAccounts)) {
continue;
}
if ($byAdvertiser && empty($advertiserIdArr) && empty($advertiserManagerIdArr)) {
$advertiserIdArr = array_keys($this->commonCalls->getAdvertisersListByStatusWithKeys(['tuneAccount' => $tuneAccount]));
}
if ($byAffiliate && empty($affiliateIdArr) && empty($affiliateManagerIdArr)) {
$affiliateIdArr = array_keys($this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount));
}
if ($byOffer && empty($offerIdArr)) {
$offerIdArr = array_column($this->doctrine->getRepository(OfferInfo::class)->getOfferInfoByStatus(Config::ACTIVE_STATUS, $tuneAccount), 'offerId');
}
$advertisersByEmployeeId = [];
if ($byAdvertiser && !empty($advertiserManagerIdArr)) {
foreach ($advertiserManagerIdArr as $employeeId) {
$advertisersByEmployeeIdResponse = $this->brandHasofferApi->getAdvertiserIdsByEmployeeId($employeeId, $tuneAccount);
if (isset($advertisersByEmployeeIdResponse['response']['status']) && $advertisersByEmployeeIdResponse['response']['status']) {
$advertisersByEmployeeId = array_values(array_merge($advertisersByEmployeeId, $advertisersByEmployeeIdResponse['response']['data']));
}
}
}
$affiliatesByEmployeeId = [];
if ($byAffiliate && !empty($affiliateManagerIdArr)) {
foreach ($affiliateManagerIdArr as $employeeId) {
$affiliatesByEmployeeIdResponse = $this->brandHasofferApi->getAffiliateIdsByEmployeeId($employeeId, $tuneAccount);
if (isset($affiliatesByEmployeeIdResponse['response']['status']) && $affiliatesByEmployeeIdResponse['response']['status']) {
$affiliatesByEmployeeId = array_values(array_merge($affiliatesByEmployeeId, $affiliatesByEmployeeIdResponse['response']['data']));
}
}
}
$advertiserIdArr = array_values(array_unique(array_merge($advertiserIdArr, $advertisersByEmployeeId)));
$affiliateIdArr = array_values(array_unique(array_merge($affiliateIdArr, $affiliatesByEmployeeId)));
if (empty($advertiserIdArr) && empty($affiliateIdArr) && empty($offerIdArr)) {
continue;
}
if ($byAdvertiser && sizeof($advertiserIdArr) > 300) {
$advertiserIdChunk = array_chunk($advertiserIdArr, 300);
$dataForWeekAnalyzeI = [];
$dataForWeekAnalyzeII = [];
foreach ($advertiserIdChunk as $advertiserIds) {
$dataForWeekAnalyzeI = array_merge($dataForWeekAnalyzeI, $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIds, $affiliateIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $tuneAccount)['response']['data']['data']);
$dataForWeekAnalyzeII = array_merge($dataForWeekAnalyzeII, $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIds, $affiliateIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartII, $dateEndII, $tuneAccount)['response']['data']['data']);
}
} elseif ($byAffiliate && sizeof($affiliateIdArr) > 300) {
$affiliateIdChunk = array_chunk($affiliateIdArr, 300);
$dataForWeekAnalyzeI = [];
$dataForWeekAnalyzeII = [];
foreach ($affiliateIdChunk as $affiliateIds) {
$dataForWeekAnalyzeI = array_merge($dataForWeekAnalyzeI, $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr, $affiliateIds, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $tuneAccount)['response']['data']['data']);
$dataForWeekAnalyzeII = array_merge($dataForWeekAnalyzeII, $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr, $affiliateIds, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartII, $dateEndII, $tuneAccount)['response']['data']['data']);
}
} else {
$dataForWeekAnalyzeI = $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr, $affiliateIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartI, $dateEndI, $tuneAccount)['response']['data']['data'];
$dataForWeekAnalyzeII = $this->brandHasofferApi->getStatsForWeeklyAnalyze($advertiserIdArr, $affiliateIdArr, $offerIdArr, $byAdvertiser, $byAffiliate, $byOffer, $dateStartII, $dateEndII, $tuneAccount)['response']['data']['data'];
}
$uniqueIdsI = [];
$uniqueIdsII = [];
$statsByIdI = [];
$statsByIdII = [];
foreach ($dataForWeekAnalyzeI as $key => $value) {
if (isset($value['Stat']['advertiser_id'])) {
$value['Stat']['id'] = $value['Stat']['advertiser_id'];
} elseif (isset($value['Stat']['affiliate_id'])) {
$value['Stat']['id'] = $value['Stat']['affiliate_id'];
} elseif (isset($value['Stat']['offer_id'])) {
$value['Stat']['id'] = $value['Stat']['offer_id'];
} else {
continue;
}
if (!in_array($value['Stat']['id'], $uniqueIdsI)) {
array_push($uniqueIdsI, $value['Stat']['id']);
}
$statsByIdI[$value['Stat']['id']] = $value['Stat'];
}
foreach ($dataForWeekAnalyzeII as $key => $value) {
if (isset($value['Stat']['advertiser_id'])) {
$value['Stat']['id'] = $value['Stat']['advertiser_id'];
} elseif (isset($value['Stat']['affiliate_id'])) {
$value['Stat']['id'] = $value['Stat']['affiliate_id'];
} elseif (isset($value['Stat']['offer_id'])) {
$value['Stat']['id'] = $value['Stat']['offer_id'];
} else {
continue;
}
if (!in_array($value['Stat']['id'], $uniqueIdsII)) {
array_push($uniqueIdsII, $value['Stat']['id']);
}
$statsByIdII[$value['Stat']['id']] = $value['Stat'];
}
$uniqueIds = array_values(array_unique(array_merge($uniqueIdsI, $uniqueIdsII)));
$entitiesByIndex = [];
if ($byOffer) {
$offerInfoArr = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($uniqueIds, $tuneAccount);
foreach ($offerInfoArr as $offerInfo) {
$entitiesByIndex[$offerInfo['offerId'] . '_' . $tuneAccount] = [
'name' => $offerInfo['name'],
'mafoId' => $offerInfo['mafoId']
];
}
} else if ($byAdvertiser) {
$advertiserInfoArr = $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserInfoByAdvertiserIdArr($uniqueIds, $tuneAccount);
foreach ($advertiserInfoArr as $advertiserInfo) {
$entitiesByIndex[$advertiserInfo['advertiserId'] . '_' . $tuneAccount] = [
'name' => $advertiserInfo['company'],
'mafoId' => $advertiserInfo['mafoId']
];
}
} else if ($byAffiliate) {
$affiliateInfoArr = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByAffiliateIds($uniqueIds, $tuneAccount);
foreach ($affiliateInfoArr as $affiliateInfo) {
$entitiesByIndex[$affiliateInfo['affiliateId'] . '_' . $tuneAccount] = [
'name' => $affiliateInfo['company'],
'mafoId' => $affiliateInfo['mafoId']
];
}
}
foreach ($uniqueIds as $id) {
$index = $id . '_' . $tuneAccount;
$stats[$index]['id'] = $id;
$stats[$index]['name'] = $entitiesByIndex[$index]['name'] ?? '';
$stats[$index]['mafoId'] = $entitiesByIndex[$index]['mafoId'] ?? '';
$stats[$index]['tuneAccount'] = $tuneAccount;
if (array_key_exists($id, $statsByIdI)) {
$stats[$index]['dateRangeIClicks'] = $statsByIdI[$id]['clicks'];
$stats[$index]['dateRangeIConversions'] = $statsByIdI[$id]['conversions'];
$stats[$index]['dateRangeIRevenue'] = round($statsByIdI[$id]['revenue'], 2);
$stats[$index]['dateRangeIPayout'] = round($statsByIdI[$id]['payout'], 2);
$stats[$index]['dateRangeIProfit'] = round($statsByIdI[$id]['profit'], 2);
} else {
$stats[$index]['dateRangeIClicks'] = 0;
$stats[$index]['dateRangeIConversions'] = 0;
$stats[$index]['dateRangeIRevenue'] = 0;
$stats[$index]['dateRangeIPayout'] = 0;
$stats[$index]['dateRangeIProfit'] = 0;
}
if (array_key_exists($id, $statsByIdII)) {
$stats[$index]['dateRangeIIClicks'] = $statsByIdII[$id]['clicks'];
$stats[$index]['dateRangeIIConversions'] = $statsByIdII[$id]['conversions'];
$stats[$index]['dateRangeIIRevenue'] = round($statsByIdII[$id]['revenue'], 2);
$stats[$index]['dateRangeIIPayout'] = round($statsByIdII[$id]['payout'], 2);
$stats[$index]['dateRangeIIProfit'] = round($statsByIdII[$id]['profit'], 2);
} else {
$stats[$index]['dateRangeIIClicks'] = 0;
$stats[$index]['dateRangeIIConversions'] = 0;
$stats[$index]['dateRangeIIRevenue'] = 0;
$stats[$index]['dateRangeIIPayout'] = 0;
$stats[$index]['dateRangeIIProfit'] = 0;
}
}
foreach ($stats as $key => $value) {
if ($value['dateRangeIIPayout'] && $value['dateRangeIIPayout'] != 0) {
$stats[$key]['payoutPercentChange'] = round(((($value['dateRangeIIPayout'] - $value['dateRangeIPayout']) / $value['dateRangeIIPayout']) * 100), 2);
} else {
$stats[$key]['payoutPercentChange'] = 0;
}
if ($value['dateRangeIIRevenue'] && $value['dateRangeIIPayout'] != 0) {
$stats[$key]['revenuePercentChange'] = round(((($value['dateRangeIIRevenue'] - $value['dateRangeIRevenue']) / $value['dateRangeIIPayout']) * 100), 2);
} else {
$stats[$key]['revenuePercentChange'] = 0;
}
if ($value['dateRangeIIProfit'] && $value['dateRangeIIPayout'] != 0) {
$stats[$key]['profitPercentChange'] = round(((($value['dateRangeIIProfit'] - $value['dateRangeIProfit']) / $value['dateRangeIIPayout']) * 100), 2);
} else {
$stats[$key]['profitPercentChange'] = 0;
}
}
}
return array_values($stats);
}
/**
* @Route("/source-tags", name="GET_SOURCE_TAGS", methods={"GET"})
*/
public function getSourceTagsAction(Request $request)
{
$sourcesTagsDbData = $this->doctrine->getRepository('App\Entity\SourceTags')->getSourceTagsByIsDeleted(0);
$sourcesTagsData = [];
foreach ($sourcesTagsDbData as $key => $value) {
$sourcesTagsData[$value['tagName']][$value['id']] = $value['source'];
}
return new JsonResponse($sourcesTagsData);
}
/**
* @Route("/source-tags", name="POST_SOURCE_TAGS", methods={"POST"})
*/
public function postSourceTagsAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$tagName = $payload['tagName'];
$sources = $payload['sources'];
foreach ($sources as $source) {
$source = trim($source);
if ($source == '') {
continue;
}
$combinationExist = $this->doctrine->getRepository(SourceTags::class)->checkIfSourceTagNameExist($source, $tagName);
if (!$combinationExist) {
$this->doctrine->getRepository(SourceTags::class)->insertToSourceTags($tagName, $source, 0, $this->getUser()->getName());
} elseif ($combinationExist->getIsDeleted()) {
$this->doctrine->getRepository(SourceTags::class)->updateIsDeletedById($combinationExist->getId(), 0, $this->getUser()->getName());
}
}
return new JsonResponse(true);
}
/**
* @Route("/source-tags/{id}", name="DELETE_SOURCE_TAGS", methods={"DELETE"})
*/
public function deleteSourceTagsAction(Request $request, $id)
{
$this->doctrine->getRepository(SourceTags::class)->updateIsDeletedById($id, 1, $this->getUser()->getName());
return new JsonResponse(true);
}
/**
* @Route("/affiliate-tags", name="GET_AFFILIATE_TAGS", methods={"GET"})
*/
public function getAffiliateTagsAction(Request $request)
{
$affiliateTagsDbData = $this->doctrine->getRepository('App\Entity\AffiliateTags')->getAffiliateTagsByIsDeleted(0);
$affiliateTagsData = [];
foreach ($affiliateTagsDbData as $key => $value) {
$affiliateTagsData[$value['tagName']][$value['id']] = $value['affiliateId'];
}
return new JsonResponse($affiliateTagsData);
}
/**
* @Route("/affiliate-tags", name="POST_AFFILIATE_TAGS", methods={"POST"})
*/
public function postAffiliateTagsAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$tagName = $payload['tagName'];
$affiliates = $payload['affiliates'];
foreach ($affiliates as $affiliate) {
$affiliate = trim($affiliate);
if ($affiliate == '') {
continue;
}
$combinationExist = $this->doctrine->getRepository(AffiliateTags::class)->checkIfAffiliateTagNameExist($affiliate, $tagName);
if (!$combinationExist) {
$this->doctrine->getRepository(AffiliateTags::class)->insertToAffiliateTags($tagName, $affiliate, 0, $this->getUser()->getName());
} elseif ($combinationExist->getIsDeleted()) {
$this->doctrine->getRepository(AffiliateTags::class)->updateIsDeletedById($combinationExist->getId(), 0, $this->getUser()->getName());
}
}
return new JsonResponse(true);
}
/**
* @Route("/affiliate-tags/{id}", name="DELETE_AFFILIATE_TAGS", methods={"DELETE"})
*/
public function deleteAffiliateTagsAction(Request $request, $id)
{
$this->doctrine->getRepository(AffiliateTags::class)->updateIsDeletedById($id, 1, $this->getUser()->getName());
return new JsonResponse(true);
}
/**
* @Route("/affiliate-ho-mmp-mapping", name="get_affiliate_ho_mmp_mapping", methods={"GET"})
*/
public function getAffiliateHoMmpMappingAction(Request $request)
{
$hoAffiliateId = $request->query->get('hoAffiliateId');
$tuneAccount = $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$mappedData = $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByTuneAffiliateId($hoAffiliateId, $tuneAccount);
$mafoUsers = $this->commonCalls->getMafoUsersWithEmailIdAsKey();
$data = [];
foreach ($mappedData as $key => $value) {
$data[] = [
'id' => $value['id'],
'hoAffiliateId' => $value['hoAffiliateId'],
'addedBy' => array_key_exists($value['addedByEmail'], $mafoUsers) ? $mafoUsers[$value['addedByEmail']]['name'] : $value['addedByEmail'],
'mmpPartnerId' => $value['mmpPartnerId'],
'mmpPartnerSource' => Config::MMP_TRACKING_SYSTEM_PRETTY[$value['mmpPartnerSource']]
];
}
return new JsonResponse($data);
}
/**
* @Route("/affiliate-ho-mmp-mapping/{id}", name="patch_affiliate_ho_mmp_mapping", methods={"PATCH"})
*/
public function patchAffiliateHoMmpMappingAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->updateHoAffiliateMmpPartnerMappingById(
$id,
$payload
);
return new JsonResponse(true);
}
/**
* @Route("/affiliate-ho-mmp-mapping", name="post_affiliate_ho_mmp_mapping", methods={"POST"})
*/
public function postAffiliateHoMmpMappingAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$hoAffiliateId = $payload['hoAffiliateId'];
$mmpPartners = $payload['mmpPartners'];
$mmpSource = $payload['mmpSource'];
$tuneAccount = $payload['tuneAccount'];
$data = [];
foreach ($mmpPartners as $mmpPartner) {
$data[] = [
'hoAffiliateId' => $hoAffiliateId,
'mmpPartnerId' => trim($mmpPartner['value']),
'mmpPartnerSource' => trim($mmpSource),
'tuneAccount' => $tuneAccount
];
}
$error = [];
foreach ($data as $key => $value) {
if (
$this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['hoAffiliateId'], 'tuneAccount' => $value['tuneAccount']]) &&
array_key_exists($value['mmpPartnerSource'], Config::MMP_TRACKING_SYSTEM_PRETTY) &&
$value['mmpPartnerId']
) {
$combinationExists = $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->findOneBy([
// 'hoAffiliateId' => $value['hoAffiliateId'],
'mmpPartnerId' => $value['mmpPartnerId'],
'mmpPartnerSource' => $value['mmpPartnerSource'],
'tuneAccount' => $value['tuneAccount']
]);
if (!$this->doctrine->getRepository(MmpPartners::class)->findOneBy([
'partner' => $value['mmpPartnerId'],
'mmpSource' => $value['mmpPartnerSource'],
])) {
$this->doctrine->getRepository(MmpPartners::class)->insertToMmpPartners($value['mmpPartnerId'], $value['mmpPartnerSource'], $value['tuneAccount']);
}
if (!$combinationExists) {
$this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->insertToHoAffiliateMmpPartnerMapping(
$value['hoAffiliateId'],
$value['mmpPartnerId'],
$this->getUser()->getEmail(),
Config::MMP_HO_AFFILIATE_ID_MMP_PARTNER_ID_MAPPING_ADDED_FROM_MMP_AFFILIATE_INFO,
1,
$value['mmpPartnerSource'],
$value['tuneAccount']
);
} elseif (!$combinationExists->getIsMappingEnabled()) {
$this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->updateHoAffiliateMmpPartnerMappingById(
$combinationExists->getId(),
[
'hoAffiliateId' => $value['hoAffiliateId'],
'mmpPartnerId' => $value['mmpPartnerId'],
'mmpPartnerSource' => $value['mmpPartnerSource'],
'addedByEmail' => $this->getUser()->getEmail(),
'addedFrom' => Config::MMP_HO_AFFILIATE_ID_MMP_PARTNER_ID_MAPPING_ADDED_FROM_MMP_AFFILIATE_INFO,
'isMappingEnabled' => true
]
);
} else {
$error[] = "Partner " . $combinationExists->getMmpPartnerId() . " is already assigned to Tune Affiliate Id." . $combinationExists->getHoAffiliateId();
}
}
}
if ($error) {
$error[] = 'Please Delete above partner mapping before assigning to new Tune Affiliate.';
return new JsonResponse($error, Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
return new JsonResponse(true);
}
/**
* @Route("/affiliate-info", name="get_affiliate_info", methods={"GET"})
*/
public function getAffiliateInfoAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$affiliateIdArr = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(",", $queryParams['affiliateIds']) : [];
$affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys();
if (empty($affiliateIdArr)) {
$affiliateIdArr = array_keys($affiliateList);
}
$chooseBy = $request->query->get('chooseBy');
$offerCountBy = $request->query->get('offerCountBy');
$status = 'active';
#$data = $this->get( 'mysql_queries' )->getDataForAdvertiserOfferCountForChart( $affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $status );
$data = $this->mysqlQueries->getDataForAffiliateOfferCountForChart($affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $offerCountBy);
$labels = [];
foreach ($data as $key => $value) {
$label = null;
if (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_HOUR, $value)) {
$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';
} elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_DAY, $value)) {
$label = $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY];
} elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_MONTH, $value)) {
$label = $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH];
}
$timestamp = strtotime($label);
$data[$key]['timestamp'] = $timestamp;
if ($label && !in_array($label, $labels)) {
$labels[$timestamp] = $label;
}
}
ksort($labels);
$temp = [];
foreach ($data as $key => $value) {
$temp[$value['affiliateId']][$value['timestamp']] = round($value['average'], 2);
}
$dataForChartTemp = [];
foreach ($temp as $key => $value) {
foreach (array_keys($labels) as $label) {
if (array_key_exists($label, $value)) {
$dataForChartTemp[$key][$label] = $value[$label];
} else {
$dataForChartTemp[$key][$label] = '0';
}
}
}
$dataForChart = [];
foreach ($dataForChartTemp as $key => $value) {
if (!array_key_exists($key, $dataForChart)) {
$dataForChart[$key] = [
'label' => $key,
'backgroundColor' => 'transparent',
'pointHoverBackgroundColor' => '#fff',
'borderWidth' => 2,
'data' => [],
'lineTension' => 0,
'pointRadius' => 1,
'borderColor' => '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT)
];
}
$dataForChart[$key]['data'] = array_values($value);
}
$finalLabels = [];
foreach ($labels as $timestamp => $datetime) {
if ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_HOUR) {
array_push($finalLabels, date('H', strtotime($datetime)));
} elseif ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_DAY) {
array_push($finalLabels, date('d', strtotime($datetime)));
} elseif ($chooseBy == Config::AFFILIATE_INFO_CHOOSE_BY_MONTH) {
array_push($finalLabels, date('m', strtotime($datetime)));
} else {
array_push($finalLabels, date('H', strtotime($datetime)));
}
}
return new JsonResponse([
'labels' => array_values($finalLabels),
'datasets' => array_values($dataForChart)
]);
}
/**
* @Route("/affiliate-info-csv", name="affiliate_info_csv", methods={"GET"})
*/
public function getAffiliateInfoCsvAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$affiliateIdArr = !empty($queryParams['affiliateIds']) && is_string($queryParams['affiliateIds']) ? explode(",", $queryParams['affiliateIds']) : [];
$affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys();
if (empty($affiliateIdArr)) {
$affiliateIdArr = array_keys($affiliateList);
}
$chooseBy = $request->query->get('chooseBy');
$offerCountBy = $request->query->get('offerCountBy');
$status = 'active';
#$data = $this->get( 'mysql_queries' )->getDataForAdvertiserOfferCountForChart( $affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $status );
$data = $this->mysqlQueries->getDataForAffiliateOfferCountForChart($affiliateIdArr, $dateStart, $dateEnd, $chooseBy, $offerCountBy);
$labels = [];
foreach ($data as $key => $value) {
$label = null;
if (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_HOUR, $value)) {
$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';
} elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_DAY, $value)) {
$label = $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_DAY];
} elseif (array_key_exists(Config::AFFILIATE_INFO_CHOOSE_BY_MONTH, $value)) {
$label = $value[Config::AFFILIATE_INFO_CHOOSE_BY_YEAR] . '-' . $value[Config::AFFILIATE_INFO_CHOOSE_BY_MONTH];
}
$timestamp = strtotime($label);
$data[$key]['timestamp'] = $timestamp;
if ($label && !in_array($label, $labels)) {
$labels[$timestamp] = $label;
}
}
ksort($labels);
$temp = [];
foreach ($data as $key => $value) {
$temp[$value['affiliateId']][$value['timestamp']] = round($value['average'], 2);
}
$dataForCsv = [];
foreach ($temp as $key => $value) {
foreach (array_keys($labels) as $label) {
if (array_key_exists($label, $value)) {
$dataForCsv[$key][$label] = $value[$label];
} else {
$dataForCsv[$key][$label] = '0';
}
}
}
$labelsToDatetime = array_values($labels);
$dataToExport = [];
if (!empty($dataForCsv)) {
$headers = array_merge([""], $labelsToDatetime);
$dataToExport[] = implode(",", $headers);
foreach ($dataForCsv as $key => $value) {
$data = [array_key_exists($key, $affiliateList) ? $key . ' ' . str_replace(",", " ", $affiliateList[$key]['name']) : $key];
foreach ($value as $k => $v) {
array_push($data, round($v, 2));
}
array_push($dataToExport, implode(",", $data));
}
}
$response = new Response(implode("\n", $dataToExport));
$response->headers->set('Content-Type', 'text/csv');
return $response;
}
/**
* @Route("/fraud-flag-logs", name="post_fraud_flag_logs", methods={"POST"})
*/
public function getFraudFlagLogs(Request $request)
{
$payload = json_decode($request->getContent(), true);
$dateRangeArray = $payload['dateRange'] ?? null;
if ($dateRangeArray == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $payload['dateRange']);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$affiliateIdArray = $payload['affiliates'] ?? [];
$offerIdArray = $payload['offers'] ?? [];
$advertiserArray = $payload['advertisers'] ?? [];
$fraudFlagData = $this->commonCalls->getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd);
return new JsonResponse(array_values($fraudFlagData));
}
/**
* @Route("/fraud-flag-logs", name="delete_fraud_flag_logs", methods={"DELETE"})
*/
public function deleteFraudFlagLogsAction(Request $request)
{
$this->commonCalls->deleteFraudFlagLogs($request->query->get('id'));
return new JsonResponse(true);
}
/**
* @Route("/fraud-flag-logs-csv", name="get_fraud_flag_csv", methods={"GET"})
*/
public function getFraudFlagLogsCsvAction(Request $request)
{
$dateRange = $request->query->get('dateRange') ?? null;
if ($dateRange == null) {
$dateStart = null;
$dateEnd = null;
} else {
$dateRangeArray = explode(' - ', $dateRange);
$dateStart = date('Y-m-d', strtotime($dateRangeArray[0]));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($dateRangeArray[1])));
}
$queryParams = $request->query->all();
$affiliateIdArray = !empty($queryParams['affiliates']) && is_string($queryParams['affiliates']) ? explode(",", $queryParams['affiliates']) : [];
$offerIdArray = !empty($queryParams['offers']) && is_string($queryParams['offers']) ? explode(",", $queryParams['offers']) : [];
$advertiserArray = !empty($queryParams['advertisers']) && is_string($queryParams['advertisers']) ? explode(",", $queryParams['advertisers']) : [];
$fraudFlagData = $this->commonCalls->getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd);
$dataToExport = [];
if (!empty($fraudFlagData)) {
$headers = [
'Transaction Id',
'Affiliate Id',
'Offer Id',
'Advertiser Id',
'Source',
'AdvSub1',
'Date Inserted'
];
$dataToExport[] = implode(",", $headers);
foreach ($fraudFlagData as $key => $value) {
$data = [
$value['transactionId'],
$value['affiliateId'] . ' - ' . str_replace(",", " ", $value['affiliateName']),
$value['offerId'] . ' - ' . str_replace(",", " ", $value['offerName']),
$value['advertiserId'] . ' - ' . str_replace(",", " ", $value['advertiserName']),
$value['source'],
$value['advSub1'],
$value['date_inserted']
];
array_push($dataToExport, implode(",", $data));
}
}
$response = new Response(implode("\n", $dataToExport));
$response->headers->set('Content-Type', 'text/csv');
return $response;
}
/**
* @Route("/offers/{offerId}", name="get_offer", methods={"GET"})
*/
public function getOfferAction(Request $request, $offerId)
{
// $offerInfo = $this->commonCalls->populateOfferDetailsByOfferId($offerId);
$this->commonCalls->populateDbByOfferId($offerId);
die;
}
/**
* @Route("/offers", name="get_offers", methods={"GET"})
*/
public function getOffersAction(Request $request)
{
ini_set('memory_limit', '512M');
$limit = $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
$page = $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
$sortBy = $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
$sortType = $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
$queryParams = $request->query->all();
$statusArr = $queryParams['status'] ?? [];
$categoriesIdArr = $queryParams['categoryIds'] ?? [];
$geoArr = $queryParams['geos'] ?? [];
$tagArr = $queryParams['tags'] ?? [];
$excludedTagArr = $queryParams['excludedTags'] ?? [];
$appIdsRequested = $queryParams['appIds'] ?? [];
$offerIds = $queryParams['offerIds'] ?? [];
$mafoOfferIds = $queryParams['mafoOfferIds'] ?? [];
$advertiserManagerIds = $queryParams['advertiserManagerIds'] ?? [];
$advertiserIds = $queryParams['advertiserIds'] ?? [];
$search = $request->query->get('search') != '' ? $request->query->get('search') : null;
$advancedFilters = $queryParams['advancedFilters'] ?? null;
$getGoals = $request->query->get('getGoals') == 1;
$getCreativeFiles = $request->query->get('getCreativeFiles') == 1;
$getOfferWhitelist = $request->query->get('getOfferWhitelist') == 1;
$pullOfferDataFromHo = $request->query->get('pullOfferDataFromHo') == 1;
$downloadDataAsCSV = $request->query->get('csv') == 1;
$tuneAccount = $request->query->all('tuneAccount') ?? null;
$offerType = $queryParams['offerType'] ?? [];
if ($pullOfferDataFromHo && is_array($advancedFilters) && $tuneAccount !== null) {
$tuneAccount = $tuneAccount[0];
foreach ($advancedFilters as $key => $value) {
if (
is_array($value) && isset($value['field']) && isset($value['comparison']) && isset($value['value']) &&
$value['field'] == 'offerId' && $value['comparison'] == 'EQUAL_TO'
) {
$this->commonCalls->populateDbByOfferId($value['value'], [
'calledFromCronJob' => false,
'tuneAccount' => $tuneAccount
]);
}
}
}
$offerIdsToSearch = [];
$offersByCategory = [];
if ($categoriesIdArr && is_array($categoriesIdArr) && sizeof($categoriesIdArr) > 0) {
$offerCategoryData = $this->doctrine->getRepository(OfferCategoryRelationship::class)->getOfferCategoryDataByCategoryIds($categoriesIdArr, $tuneAccount);
foreach ($offerCategoryData as $key => $value) {
if (!in_array($value['offerId'], $offersByCategory)) {
array_push($offersByCategory, $value['offerId']);
}
}
$offerIdsToSearch = ($offersByCategory && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch, $offersByCategory)) : $offersByCategory;
}
if ($advertiserManagerIds && is_array($advertiserManagerIds) && sizeof($advertiserManagerIds) > 0) {
$advertiserAccountManagerData = $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAccountManagerDataByIds($advertiserManagerIds, $tuneAccount);
$advertiserIdsByAccountManagerIds = [];
foreach ($advertiserAccountManagerData as $key => $value) {
if (!in_array($value['advertiserId'], $advertiserIdsByAccountManagerIds)) {
$advertiserIdsByAccountManagerIds[] = "{$value['advertiserId']}";
}
}
$advertiserIds = array_values(array_unique(array_merge($advertiserIdsByAccountManagerIds, $advertiserIds)));
}
$offersByGeo = [];
// if ($geoArr && is_array($geoArr) && sizeof($geoArr) > 0) {
// $offerGeoData = $this->doctrine->getRepository(OfferGeoRelationship::class)->getOfferGeoDataByGeos($geoArr);
// foreach ($offerGeoData as $key => $value) {
// if (!in_array($value['offerId'], $offersByGeo)) {
// array_push($offersByGeo, $value['offerId']);
// }
// }
// $offerIdsToSearch = ($offersByGeo && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch, $offersByGeo)) : $offersByGeo;
// }
$offersByTag = [];
if ($tagArr && is_array($tagArr) && sizeof($tagArr) > 0) {
$offerTagData = $this->doctrine->getRepository(OfferTagRelationship::class)->getOfferTagDataByTagIds($tagArr, $tuneAccount);
foreach ($offerTagData as $key => $value) {
if (!in_array($value['offerId'], $offersByTag)) {
array_push($offersByTag, $value['offerId']);
}
}
$offerIdsToSearch = ($offersByTag && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch, $offersByTag)) : $offersByTag;
}
$offersByExcludedTag = [];
if ($excludedTagArr && is_array($excludedTagArr) && sizeof($excludedTagArr) > 0) {
$offerTagData = $this->doctrine->getRepository(OfferTagRelationship::class)->getOfferTagDataByExcludedTagIds($excludedTagArr, $tuneAccount);
foreach ($offerTagData as $key => $value) {
if (!in_array($value['offerId'], $offersByExcludedTag)) {
array_push($offersByExcludedTag, $value['offerId']);
}
}
$offerIdsToSearch = ($offersByExcludedTag && $offerIdsToSearch) ? array_values(array_intersect($offerIdsToSearch, $offersByExcludedTag)) : $offersByExcludedTag;
}
if ($offerIds && is_array($offerIds) && sizeof($offerIds) > 0) {
$offerIdsToSearch = array_values(array_unique(array_merge($offerIdsToSearch, $offerIds)));
}
if (($offersByCategory || $offersByGeo || $offersByTag || $offersByExcludedTag) && !$offerIdsToSearch) {
$offerIdsToSearch = [0];
}
$data = $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->getOfferInfo($limit, $page, $sortBy, $sortType, $statusArr, $search, $advancedFilters, $advertiserIds, $appIdsRequested, $offerIdsToSearch, $geoArr, $mafoOfferIds, $tuneAccount, $offerType);
$finalArray = $offerIds = $advertiserIdsForManager = $appIds = $appIdsByOffer = [];
foreach ($data as $key => $value) {
$advertiserIdsForManager[] = $value['advertiserId'];
$finalArray[$value['offerId']][] = $value;
$appIdsByOffer[$value['offerId']] = ((string)$this->commonCalls->getScraper()->getAppId($value['previewUrl']));
// Get the last added record index
$lastIndex = count($finalArray[$value['offerId']]) - 1;
$finalArray[$value['offerId']][$lastIndex]['geoIdsJson'] = $value['geoIdsJson'] ? json_decode($value['geoIdsJson'], true) : [];
$finalArray[$value['offerId']][$lastIndex]['categoryIdsJson'] = $value['categoryIdsJson'] ? json_decode($value['categoryIdsJson'], true) : [];
$finalArray[$value['offerId']][$lastIndex]['tagIdsJson'] = $value['tagIdsJson'] ? json_decode($value['tagIdsJson'], true) : [];
$finalArray[$value['offerId']][$lastIndex]['whitelistIpsJson'] = $value['whitelistIpsJson'] ? json_decode($value['whitelistIpsJson'], true) : [];
$finalArray[$value['offerId']][$lastIndex]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
$finalArray[$value['offerId']][$lastIndex]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
$finalArray[$value['offerId']][$lastIndex]['defaultPayout'] = round($value['defaultPayout'], 2);
$finalArray[$value['offerId']][$lastIndex]['maxPayout'] = round($value['maxPayout'], 2);
$finalArray[$value['offerId']][$lastIndex]['isSkadNetworkApiEnabled'] = $value['isSkadNetworkApiEnabled'];
$finalArray[$value['offerId']][$lastIndex]['skadNetworkAdjustTracker'] = $value['skadNetworkAdjustTracker'];
$finalArray[$value['offerId']][$lastIndex]['skadNetworkBranchAffiliateIds'] = $value['skadNetworkBranchAffiliateIds'] ?? [];
$finalArray[$value['offerId']][$lastIndex]['tuneAccount'] = $value['tuneAccount'];
$finalArray[$value['offerId']][$lastIndex]['mafoOfferId'] = $value['mafoOfferId'];
$finalArray[$value['offerId']][$lastIndex]['offerType'] = $value['offerType'] ? [
'value' => $value['offerType'],
'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'])
] : null;
$finalArray[$value['offerId']][$lastIndex]['geoPretty'] = [];
if ($finalArray[$value['offerId']][$lastIndex]['geoIdsJson']) {
$geosPretty = [];
foreach ($finalArray[$value['offerId']][$lastIndex]['geoIdsJson'] as $k => $v) {
$v = $v === 'UK' ? 'GB' : $v;
$geosPretty[] = array_key_exists($v, Config::COUNTRIES) ? Config::COUNTRIES[$v]['name'] : $v;
}
$finalArray[$value['offerId']][$lastIndex]['geoPretty'] = $geosPretty;
}
if ($getGoals) {
$finalArray[$value['offerId']][$lastIndex]['goals'] = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferId($value['offerId'], $tuneAccount);
} else {
$finalArray[$value['offerId']][$lastIndex]['goals'] = [];
}
if ($getOfferWhitelist) {
$finalArray[$value['offerId']][$lastIndex]['offerWhitelist'] = $this->doctrine->getRepository(OfferWhitelist::class)->getOfferWhitelistByOfferId($value['offerId'], $tuneAccount);
} else {
$finalArray[$value['offerId']][$lastIndex]['offerWhitelist'] = [];
}
if ($getCreativeFiles) {
$finalArray[$value['offerId']][$lastIndex]['creativeFiles'] = $this->doctrine->getRepository(OfferCreativeFile::class)->getCreativeFilesByOfferId($value['offerId'], $tuneAccount);
} else {
$finalArray[$value['offerId']][$lastIndex]['creativeFiles'] = [];
}
}
if ($downloadDataAsCSV == TRUE) {
$appIds = array_values($appIdsByOffer);
$appInformationGroupedByAppId = array();
$appInfoArr = $this->doctrine->getRepository(\App\Entity\AppInfo::class)->getDataByAppIds($appIds);
foreach ($appInfoArr as $key => $appInfo) {
$appInformationGroupedByAppId[$appInfo['appId']] = $appInfo;
}
$accountManagers = $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAdvertiserManagerDataGroupByAdvertiserIds($advertiserIdsForManager);
$advertiserListWithKeys = $this->commonCalls->getAdvertisersListByStatusWithKeys();
$exportableData = array_values($finalArray);
$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"];
$rows[] = $header;
$i = 0;
foreach ($exportableData as $data) {
foreach ($data as $fields) {
$platform = "";
$appName = "";
$offerId = $fields['offerId'];
if (isset($appIdsByOffer[$offerId])) {
$appId = $appIdsByOffer[$offerId];
$appName = isset($appInformationGroupedByAppId[$appId]) ? $appInformationGroupedByAppId[$appId]['title'] : "";
$platform = isset($appInformationGroupedByAppId[$appId]) ? $appInformationGroupedByAppId[$appId]['platform'] : "";
}
$accountManager = isset($accountManagers[$fields["advertiserId"]]) ?
$accountManagers[$fields['advertiserId']]['firstName'] . " " . $accountManagers[$fields['advertiserId']]['lastName'] . "<" . $accountManagers[$fields['advertiserId']]['email'] . '>' : "";
$advertiserName = array_key_exists($fields["advertiserId"], $advertiserListWithKeys) ? $advertiserListWithKeys[$fields["advertiserId"]]['name'] : '';
$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"]];
$rows[] = $row;
$i++;
}
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')
->setLastModifiedBy('MAFO')
->setTitle('Offers')
->setSubject('Offers')
->setDescription('Searched Offers');
$i = 0;
$spreadsheet->getActiveSheet()
->fromArray(
$rows,
NULL,
'A1'
);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="offers.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
} else {
$totalOffers = 1;
if (!$pullOfferDataFromHo) {
$totalOffers = $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->getTotalData($statusArr, $search, $advancedFilters, $advertiserIds, $appIdsRequested, $offerIdsToSearch, $geoArr, $mafoOfferIds, $tuneAccount, $offerType);
}
$noOfPages = ceil($totalOffers / $limit);
$response["response"]["success"] = true;
$response["response"]["httpStatus"] = 200;
// Flatten the grouped offers array while preserving database sort order
$flattenedData = [];
foreach ($data as $originalRecord) {
$offerId = $originalRecord['offerId'];
if (isset($finalArray[$offerId])) {
foreach ($finalArray[$offerId] as $offer) {
// Only add if this is the original record (to avoid duplicates)
if ($offer['id'] == $originalRecord['id']) {
$flattenedData[] = $offer;
break;
}
}
}
}
$response["response"]["data"] = [
"data" => $flattenedData,
"metaData" => [
"total" => $totalOffers,
"limit" => $limit,
"page" => $page,
"pages" => $noOfPages
]
];
return new JsonResponse($response);
}
}
/**
* @Route("/offers/{offerId}", name="patch_offers", methods={"PATCH"})
*/
public function patchOffersAction(Request $request, $offerId)
{
$payload = json_decode($request->getContent(), true);
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$offerType = $payload['offerType'] ?? null;
if ($offerType && !in_array($offerType, array_map('strtolower', Config::OFFER_TYPES))) {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => ['Invalid Offer Type.']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
foreach ($payload as $key => $value) {
if ($value === null || $value === '') {
unset($payload[$key]);
}
}
// if (
// isset($payload['offerUrl'])
// && is_string($payload['offerUrl'])
// && !$payload['whitelistIps']
// ) {
// $payload['whitelistIps'] = $this->commonCalls->getWhitelistIPsAppsflyerOrAdjust($payload['offerUrl']);
// }
$hoResponse = $this->commonCalls->updateOffer($offerId, $payload, $payload['countries'], $payload['categories'], $payload['tags'], $payload['whitelistIps'] ?? [], $tuneAccount);
if ($hoResponse['response']['status'] === 1) {
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => $hoResponse['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_OK);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $hoResponse['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/offers", name="post_offers", methods={"POST"})
*/
public function postOffersAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$offerType = $payload['offerType'] ?? null;
if ($offerType && !in_array($offerType, array_map('strtolower', Config::OFFER_TYPES))) {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => ['Invalid Offer Type.']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
foreach ($payload as $key => $value) {
if ($value === null || $value === '') {
unset($payload[$key]);
}
}
// if (
// isset($payload['offerUrl'])
// && is_string($payload['offerUrl'])
// && !$payload['whitelistIps']
// ) {
// $payload['whitelistIps'] = $this->commonCalls->getWhitelistIPsAppsflyerOrAdjust($payload['offerUrl']);
// }
$hoResponse = $this->commonCalls->createNewOffer($payload, $payload['countries'], $payload['categories'], $payload['tags'], $payload['whitelistIps'] ?? [], $tuneAccount);
if ($hoResponse['response']['status'] === 1) {
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
'data' => $hoResponse['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_CREATED);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $hoResponse['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/offer-goals/{offerId}", name="get_offer_goals", methods={"GET"})
*/
public function getOfferGoalsAction(Request $request, $offerId)
{
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$offerGoalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferId($offerId, $tuneAccount);
foreach ($offerGoalData as $key => $value) {
$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']] : '');
$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']] : '');
$offerGoalData[$key]['protocolToDisplay'] = array_key_exists($value['protocol'], Config::CONVERSION_TRACKING_MAPPING_FOR_UI) ? Config::CONVERSION_TRACKING_MAPPING_FOR_UI[$value['protocol']] : '';
$offerGoalData[$key]['value'] = $value['goalId'];
$offerGoalData[$key]['label'] = $value['goalId'] . ' - ' . $value['name'];
}
return new JsonResponse($offerGoalData);
}
/**
* @Route("/offer-scheduled-changes", name="get_offer_scheduled_changes", methods={"GET"})
*/
public function getOfferScheduledChangesAction(Request $request)
{
$offerId = $request->query->get('offerId');
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$data = $this->doctrine->getRepository(OfferScheduledChanges::class)->getOfferScheduledChangesByOfferId($offerId, Config::DELETED_STATUS, $tuneAccount);
$users = $this->commonCalls->getMafoUsersWithEmailIdAsKey();
foreach ($data as $key => $value) {
$data[$key]['addedByName'] = isset($users[$value['addedByEmail']]) ? $users[$value['addedByEmail']]['name'] : '';
$data[$key]['ruleTimezonePretty'] = Config::TIMEZONES[$value['ruleTimezone']];
$data[$key]['ruleTimezonePretty'] = Config::TIMEZONES[$value['ruleTimezone']];
$temp = [];
foreach ($value['daysRuleIsActive'] as $v) {
$temp[] = Config::DAYS_OF_WEEK[$v];
}
$data[$key]['daysRuleIsActivePretty'] = $temp;
}
return new JsonResponse($data);
}
/**
* @Route("/offer-scheduled-changes/{id}", name="patch_offer_scheduled_changes", methods={"PATCH"})
*/
public function patchOfferScheduledChangesAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$dataToUpdate = [];
if (
isset($payload['startTime']) &&
isset($payload['endTime']) &&
// str_replace(":", "", $payload['startTime']) < str_replace(":", "", $payload['endTime']) &&
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $payload['startTime']) &&
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $payload['endTime'])
) {
$dataToUpdate['startTime'] = $payload['startTime'];
$dataToUpdate['endTime'] = $payload['endTime'];
}
if (isset($payload['ruleTimezone']) && array_key_exists($payload['ruleTimezone'], Config::TIMEZONES)) {
$dataToUpdate['ruleTimezone'] = $payload['ruleTimezone'];
}
if (isset($payload['ruleStatueOnStart']) && in_array($payload['ruleStatueOnStart'], [Config::ACTIVE_STATUS, Config::PAUSED_STATUS])) {
$dataToUpdate['ruleStatusOnStart'] = $payload['ruleStatusOnStart'];
}
if (isset($payload['ruleStatusOnEnd']) && in_array($payload['ruleStatusOnEnd'], [Config::ACTIVE_STATUS, Config::PAUSED_STATUS])) {
$dataToUpdate['ruleStatusOnEnd'] = $payload['ruleStatusOnEnd'];
}
if (isset($payload['ruleStatus']) && in_array($payload['ruleStatus'], [Config::ACTIVE_STATUS, Config::PAUSED_STATUS, Config::DELETED_STATUS])) {
$dataToUpdate['ruleStatus'] = $payload['ruleStatus'];
}
$dataToUpdate['addedByEmail'] = $this->getUser()->getEmail();
$this->getDoctrine()->getRepository(OfferScheduledChanges::class)->updateOfferScheduledChangesById(
$id,
$dataToUpdate
);
return new JsonResponse(true);
}
/**
* @Route("/offer-scheduled-changes", name="post_offer_scheduled_changes", methods={"POST"})
*/
public function postOfferScheduledChangesAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$ruleTimezone = $payload['ruleTimezone'];
$ruleStatusOnEnd = $payload['ruleStatueOnEnd'];
$ruleStatusOnStart = $payload['ruleStatueOnStart'];
$ruleProperty = $payload['offerProperty'];
$startTime = $payload['startTime'];
$endTime = $payload['endTime'];
$offerId = $payload['offerId'];
$daysRuleIsActive = $payload['daysRuleIsActive'];
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$error = null;
// if(str_replace(":", "", $startTime) > str_replace(":", "", $endTime)) {
// $error = 'Start Time cannot be greater than End Time.';
// }
if (
$this->getDoctrine()->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId]) &&
sizeof(array_values(array_intersect(array_keys(Config::DAYS_OF_WEEK), $daysRuleIsActive))) === sizeof($daysRuleIsActive) &&
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $startTime) &&
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $endTime) &&
// str_replace(":", "", $startTime) < str_replace(":", "", $endTime) &&
array_key_exists($ruleTimezone, Config::TIMEZONES) &&
in_array($ruleProperty, Config::OFFER_SCHEDULING_PROPERTIES) &&
in_array($ruleStatusOnStart, [Config::ACTIVE_STATUS, Config::PAUSED_STATUS]) &&
in_array($ruleStatusOnEnd, [Config::ACTIVE_STATUS, Config::PAUSED_STATUS]) &&
!$error
) {
$offerExists = $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->getOfferScheduledChangesByOfferIdAndRuleProperty($offerId, $ruleProperty, Config::DELETED_STATUS, $tuneAccount);
foreach ($offerExists as $key => $value) {
if (
sizeof(array_values(array_intersect($daysRuleIsActive, $value['daysRuleIsActive'])))
) {
$error = 'Property you are saving already exist for given date/dates.';
}
}
if (!$offerExists || !$error) {
$this->getDoctrine()->getRepository(OfferScheduledChanges::class)->insertToOfferScheduledChanges(
$offerId,
$startTime,
$endTime,
$ruleStatusOnStart,
$ruleStatusOnEnd,
$daysRuleIsActive,
$ruleProperty,
$ruleTimezone,
Config::ACTIVE_STATUS,
$this->getUser()->getEmail(),
$tuneAccount
);
}
// else {
//
// $this->getDoctrine()->getRepository(OfferScheduledChanges::class)->updateOfferScheduledChangesByOfferId(
// $offerId, [
// 'startTime' => $startTime,
// 'endTime' => $endTime,
// 'ruleStatusOnStart' => $ruleStatusOnStart,
// 'ruleStatusOnEnd' => $ruleStatusOnEnd,
//// 'daysRuleIsActive' => $daysRuleIsActive,
//// 'ruleProperty' => $ruleProperty,
// 'ruleTimezone' => $ruleTimezone,
// 'ruleStatus' => Config::ACTIVE_STATUS,
// 'addedByEmail' => $this->getUser()->getEmail()
// ]
// );
// }
}
if ($error) {
return new JsonResponse($error, Config::HTTP_STATUS_CODE_BAD_REQUEST);
} else {
return new JsonResponse(true);
}
}
/**
* @Route("/offer-goals", name="post_offer_goals", methods={"POST"})
*/
public function postOfferGoalsAction(Request $request)
{
$payload = json_decode($request->getContent(), true)['data'];
foreach ($payload as $key => $value) {
if ($value === null || $value === '') {
unset($payload[$key]);
}
}
$dataToPushToHO = [];
foreach ($payload as $key => $value) {
$dataToPushToHO[$this->commonCalls->convertStringFromCamelCaseToSnakeCase($key)] = $value;
}
$hoResponse = $this->commonCalls->createNewOfferGoal($dataToPushToHO);
if ($hoResponse['response']['status'] === 1) {
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
'data' => $hoResponse['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_CREATED);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $hoResponse['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/goals/{goalId}", name="get_goal", methods={"GET"})
*/
public function getGoalAction(Request $request, $goalId)
{
$goalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalInfoByGoalId($goalId);
$goalData['conversionTrackingMultiselectValue'] = [
'label' => Config::CONVERSION_TRACKING_MAPPING_FOR_UI[$goalData['protocol']],
'value' => $goalData['protocol']
];
return new JsonResponse([$goalId => $goalData]);
}
/**
* @Route("/goals/{goalId}", name="patch_goals", methods={"PATCH"})
*/
public function patchGoalAction(Request $request, $goalId)
{
$payload = json_decode($request->getContent(), true)['payload'];
foreach ($payload as $key => $value) {
if ($value === null || $value === '') {
unset($payload[$key]);
}
}
$dataToPushToHO = [];
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
unset($payload['tuneAccount']);
foreach ($payload as $key => $value) {
$dataToPushToHO[$this->commonCalls->convertStringFromCamelCaseToSnakeCase($key)] = $value;
}
$hoResponse = $this->commonCalls->updateOfferGoal($goalId, $dataToPushToHO, $tuneAccount);
if ($hoResponse['response']['status'] === 1) {
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_CREATED,
'data' => $hoResponse['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_CREATED);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $hoResponse['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/offer-creatives", name="post_offer_creatives", methods={"POST"})
*/
public function postOfferCreativesAction(Request $request)
{
$files = [];
for ($fileCount = 0; $fileCount < $request->request->get('fileCount'); $fileCount++) {
$files[] = $request->files->get("file_$fileCount");
}
$offerId = $request->request->get('offerId');
$type = $request->request->get('type');
$isPrivate = $request->request->get('isPrivate');
foreach ($files as $file) {
$response = $this->commonCalls->uploadFile($offerId, $file, $type, $isPrivate);
if ($response['response']['status'] == 1) {
$response = $response['response']['data']['OfferFile'];
$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']);
}
}
return new JsonResponse(true);
}
/**
* @Route("/offer-creative-files/{offerId}", name="delete_offer_creative_files", methods={"DELETE"})
*/
public function deleteOfferCreativesAction(Request $request, $offerId)
{
$offerCreativeFileData = $this->doctrine->getRepository(OfferCreativeFile::class)->getCreativeFilesByOfferId($offerId);
foreach ($offerCreativeFileData as $key => $value) {
$hoResponse = $this->brandHasofferApi->setOfferCreativeFileStatusByFileId($value['fileId'], Config::DELETED_STATUS);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($value['fileId'], Config::DELETED_STATUS);
}
}
return new JsonResponse(true);
}
/**
* @Route("/creative-files/{fileId}", name="delete_creative_files", methods={"DELETE"})
*/
public function deleteCreativeFileAction(Request $request, $fileId)
{
$hoResponse = $this->brandHasofferApi->setOfferCreativeFileStatusByFileId($fileId, Config::DELETED_STATUS);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($fileId, Config::DELETED_STATUS);
}
return new JsonResponse(true);
}
/**
* @Route("/offer-whitelist/{offerId}", name="get_offer_whitelist_by_offer_id", methods={"GET"})
*/
public function getOfferWhitelistByOfferIdAction(Request $request, $offerId)
{
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$offerWhitelistData = $this->doctrine->getRepository(OfferWhitelist::class)->getOfferWhitelistByOfferId($offerId, $tuneAccount);
return new JsonResponse($offerWhitelistData);
}
/**
* @Route("/offer-whitelist", name="post_offer_whitelist_by_offer_id", methods={"POST"})
*/
public function postOfferWhitelistAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$offerId = $payload['offerId'];
$tuneAccount = $payload['tuneAccount'];
$contentArr = $payload['content'];
$type = $payload['type'];
$contentType = $payload['contentType'];
foreach ($contentArr as $content) {
$data = $this->brandHasofferApi->addIpWhitelistToOffer($offerId, $content, $contentType, $type, $tuneAccount);
echo json_encode($data);
}
return new JsonResponse(true);
}
/**
* @Route("/offer-whitelist/{offerWhitelistId}", name="delete_offer_whitelist_by_offer_id", methods={"DELETE"})
*/
public function deleteOffer(Request $request, $offerWhitelistId)
{
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$hoResponse = $this->brandHasofferApi->deleteOfferWhitelistById($offerWhitelistId, $tuneAccount);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(OfferWhitelist::class)->deleteByWhitelistId($offerWhitelistId, $tuneAccount);
}
return new JsonResponse(true);
}
/**
* @Route("/postback-control-logs", name="get_postback_control_logs", methods={"GET"})
*/
public function getPostbackControlLogsAction(Request $request)
{
$queryParams = $request->query->all();
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$advertiserIds = $queryParams['advertiserIds'] ?? [];
$offerIds = $queryParams['offerIds'] ?? [];
$downloadCSV = $request->query->get('downloadCSV');
$dateStart = date('Y-m-d', strtotime($request->query->get('dateStart')));
$dateEnd = date('Y-m-d', strtotime("+1 day", strtotime($request->query->get('dateEnd'))));
$postbackControlData = $this->doctrine->getRepository(PostbackControlLogs::class)->getPostbackControlLogs($advertiserIds, $affiliateIds, $offerIds, $dateStart, $dateEnd);
$columnKeys = [];
foreach ($postbackControlData as $key => $value) {
$postbackControlData[$key]['datetime'] = $value['datetime']->format('Y-m-d H:i:s');
$postbackControlData[$key]['sessionDatetime'] = $value['sessionDatetime']->format('Y-m-d H:i:s');
$postbackControlData[$key]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
$columnKeys = array_keys($value);
}
if ($downloadCSV) {
$headers = [];
foreach ($columnKeys as $value) {
array_push($headers, ucwords(implode(" ", preg_split('/(?=[A-Z])/', $value))));
}
$row[] = implode(",", $headers);
foreach ($postbackControlData as $key => $value) {
$row[] = implode(",", array_values($value));
}
$content = implode("\n", $row);
return new Response(
$content,
200,
array(
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="postback-control-logs.csv"'
)
);
} else {
return new JsonResponse($postbackControlData);
}
}
/**
* @Route("/blocked-offers", name="get_blocked_offers", methods={"GET"})
*/
public function getBlockedOffersAction(Request $request)
{
$queryParams = $request->query->all();
$offerIds = $queryParams['offerIds'] ?? [];
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$blockedFrom = $queryParams['blockedFrom'] ?? [];
$blockedOffersData = $this->doctrine->getRepository(AffiliateOfferBlock::class)->getBlockedOffersData($offerIds, $affiliateIds, $blockedFrom);
foreach ($blockedOffersData as $key => $value) {
$blockedOffersData[$key]['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
$blockedOffersData[$key]['blockedFrom'] = Config::OFFER_AFFILIATE_BLOCK_FROM_LIST[$value['blockedFrom']];
$blockedOffersData[$key]['tuneAccount'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['trackingAccount']] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
}
return new JsonResponse($blockedOffersData);
}
/**
* @Route("/approval-control-database", name="get_approval_control_database", methods={"GET"})
*/
public function approvalControlDatabaseGetAction(Request $request)
{
$byAdvertiser = $request->query->get('byAdvertiser');
$byOffer = $request->query->get('byOffer');
$queryParams = $request->query->all();
$advertiserIds = $queryParams['advertiserIds'] ?? [];
$offerIds = $queryParams['offerIds'] ?? [];
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$affiliateTagIds = $queryParams['affiliateTagIds'] ?? [];
$downloadCSV = $request->query->get('downloadCSV') == true;
$limit = $request->query->get('limit') ? $request->query->get('limit') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_SIZE;
$page = $request->query->get('page') ? $request->query->get('page') : Config::REPORTS_PAGINATION_DEFAULT_PAGE_NUMBER;
$approvalControlData = $this->doctrine->getRepository(ApprovalControl::class)->getPaginatedApprovalControlData($byAdvertiser, $byOffer, $advertiserIds, $offerIds, $affiliateIds, $affiliateTagIds, $limit, $page, true);
$uniqueOfferIds = array_map("trim", array_values(array_unique(array_filter(array_column($approvalControlData, 'offerId')))));
// $offerInfo = [];
// if ($uniqueOfferIds) {
// $offerInfo = $this->commonCalls->getOfferInfoByKey($uniqueOfferIds);
// }
$clickCapData = $this->doctrine->getRepository('App\Entity\ClickCap')->getClickCapDataByIsDeleted(0);
$clickCapDataRefactored = [];
foreach ($clickCapData as $key => $value) {
$index = md5($value['offerId'] . '#' . $value['advertiserId'] . '#' . $value['affiliateId']);
$clickCapDataRefactored[$index][] = $value;
}
$arr = [];
foreach ($approvalControlData as $key => $value) {
$index = md5($value['affiliateId'] . '#' . $value['affiliateTagId'] . '#' . $value['advertiserId'] . '#' . $value['offerId'] . '#' . $value['offerId']);
if (!isset($arr[$index])) {
$arr[$index]['ids'] = [];
$arr[$index]['affiliateId'] = $value['affiliateId'];
$arr[$index]['affiliateName'] = $value['affiliateName'];
$arr[$index]['advertiserId'] = $value['advertiserId'];
$arr[$index]['advertiserName'] = $value['advertiserName'];
$arr[$index]['offerId'] = $value['offerId'];
$arr[$index]['offerName'] = $value['offerName'];
$arr[$index]['isProcessed'] = $value['isProcessed'];
$arr[$index]['affiliateTagId'] = $value['affiliateTagId'];
$arr[$index]['affiliateTagId'] = $value['affiliateTagId'];
$arr[$index]['affiliateTagName'] = $value['affiliateTagName'];
$arr[$index]['tuneAccount'] = $value['tuneAccount'];
$arr[$index]['tuneAccountPretty'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['tuneAccount']] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$arr[$index]['addedBy'] = $value['addedBy'];
$arr[$index]['approvalType'] = Config::APPROVAL_CONTROL_APPROVAL_TYPE[$value['approvalType']];
$arr[$index]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
$arr[$index]['caps'] = [];
// $arr[$index]['offerName'] = isset($offerInfo[$arr[$index]['offerId']]) ? $offerInfo[$arr[$index]['offerId']]['name'] : '';
$indexes = [
md5($value['offerId'] . '#' . null . '#' . $value['affiliateId']),
md5($value['offerId'] . '#' . null . '#' . null),
md5(null . '#' . $value['advertiserId'] . '#' . null)
];
foreach ($indexes as $indexForClickCap) {
if (isset($clickCapDataRefactored[$indexForClickCap])) {
foreach ($clickCapDataRefactored[$indexForClickCap] as $k => $v) {
$str = ucfirst($v['blockPeriod']) . ' Click Cap By ';
$str .= $v['byOffer'] ? 'Offer' : '';
$str .= $v['byAffiliate'] ? 'Affiliate' : '';
$str .= $v['byAdvertiser'] ? 'Advertiser' : '';
$str .= $v['byOfferByAffiliate'] ? 'Affiliate And Offer' : '';
$arr[$index]['caps'][] = [
'capType' => $str,
'capValue' => $v['clickCap'],
];
}
}
}
}
$arr[$index]['ids'][] = $value['id'];
if ($value['capType']) {
$arr[$index]['caps'][] = [
'capType' => ucwords(str_replace("_", " ", $value['capType'])),
'capValue' => $value['capValue']
];
}
}
if ($downloadCSV) {
$header = [
'Offer Id',
'Advertiser Id',
'Affiliate Id',
'Affiliate Tag Id',
'Caps',
'Is Processed',
'Added By',
'Created At',
];
$rows = [$header];
foreach ($arr as $key => $value) {
$caps = "";
foreach ($value['caps'] as $k => $v) {
$caps .= "{$v['capType']}: {$v['capValue']}\n";
}
$rows[] = [
$value['offerId'],
$value['advertiserId'],
$value['affiliateId'],
$value['affiliateTagId'],
$caps,
$value['isProcessed'] ? "YES" : "NO",
$value['addedBy'],
$value['dateInserted'],
];
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')
->setLastModifiedBy('MAFO')
->setTitle('Approval Control')
->setSubject('Approval Control')
->setDescription('Approval Control');
$spreadsheet->getActiveSheet()
->fromArray(
$rows,
NULL,
'A1'
);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="approval control.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
} else {
$totalRecordCount = null;
if (!$advertiserIds && !$offerIds && !$affiliateIds && !$affiliateTagIds) {
if ($byOffer) {
$totalRecordCount = $this->elasticCache->redisGet(Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_OFFER);
} elseif ($byAdvertiser) {
$totalRecordCount = $this->elasticCache->redisGet(Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_ADVERTISER);
}
}
if (!$totalRecordCount || (!$advertiserIds && !$offerIds && !$affiliateIds && !$affiliateTagIds)) {
$totalRecordCount = $this->doctrine->getRepository(ApprovalControl::class)->getPaginatedApprovalControlData($byAdvertiser, $byOffer, $advertiserIds, $offerIds, $affiliateIds, $affiliateTagIds, $limit, $page, false);
}
$noOfPages = ceil($totalRecordCount / $limit);
$response["response"]["success"] = true;
$response["response"]["httpStatus"] = 200;
$response["response"]["data"] = [
"data" => array_values($arr),
"metaData" => [
"total" => (int)$totalRecordCount,
"limit" => (int)$limit,
"page" => (int)$page,
"pages" => $noOfPages
]
];
}
return new JsonResponse($response);
}
/**
* @Route("/approval-control", name="get_approval_control", methods={"GET"})
*/
public function approvalControlGetAction(Request $request)
{
$byAdvertiser = $request->query->get('byAdvertiser');
$byAdvertiserTag = $request->query->get('byAdvertiserTag');
$byOffer = $request->query->get('byOffer');
$queryParams = $request->query->all();
$advertiserTagIds = $queryParams['advertiserTagIds'] ?? [];
$advertiserIds = $queryParams['advertiserIds'] ?? [];
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$affiliateTagIds = $queryParams['affiliateTagIds'] ?? [];
$offerIds = $queryParams['offerIds'] ?? [];
$fromOfferDetailPage = $request->query->get('fromOfferDetailPage');
$downloadCSV = $request->query->get('downloadCSV') == true ? true : false;
$downloadCSVByApproved = $request->query->get('downloadCSVByApproved') == true ? true : false;
$downloadCSVByUnapproved = $request->query->get('downloadCSVByUnapproved') == true ? true : false;
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$dateStart = $request->query->get('dateStart');
$dateEnd = $request->query->get('dateEnd');
$dateStart = isset($dateStart) ? date('Y-m-d', strtotime($request->query->get('dateStart'))) : null;
$dateEnd = isset($dateEnd) ? date('Y-m-d', strtotime("+1 day", strtotime($request->query->get('dateEnd')))) : null;
$finalFinalArr = $finalArr = [
'byAdvertiser' => [],
'byAdvertiserTag' => [],
'byOffer' => []
];
$approvalControlData = $this->doctrine->getRepository(ApprovalControl::class)->getApprovalControlData($byAdvertiser, $byAdvertiserTag, $byOffer, $advertiserIds, $advertiserTagIds, $affiliateIds, $affiliateTagIds, $offerIds, $dateStart, $dateEnd, $tuneAccount);
$clickCaps = [
'byOffer' => [],
'byAdvertiser' => [],
'byAffiliate' => [],
'byOfferByAffiliate' => []
];
$clickCapData = $this->doctrine->getRepository('App\Entity\ClickCap')->getClickCapDataByIsDeleted(0);
foreach ($clickCapData as $key => $value) {
if ($value['byOffer']) {
$clickCaps['byOffer'][$value['offerId']][$value['blockPeriod']] = $value;
} elseif ($value['byAdvertiser']) {
$clickCaps['byAdvertiser'][$value['advertiserId']][$value['blockPeriod']] = $value;
} elseif ($value['byAffiliate']) {
$clickCaps['byAffiliate'][$value['affiliateId']][$value['blockPeriod']] = $value;
} elseif ($value['byOfferByAffiliate']) {
$clickCaps['byOfferByAffiliate'][$value['offerId']][$value['affiliateId']][$value['blockPeriod']] = $value;
}
}
$affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
$accountManagerInfo = $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys(array_keys($affiliateList), $tuneAccount);
$offerNameByOfferId = [];
foreach ($approvalControlData as $key => $value) {
$value['offerName'] = '';
if (isset($value['offerId'])) {
if (!array_key_exists($value['offerId'], $offerNameByOfferId)) {
$offerData = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offerId'], 'tuneAccount' => $tuneAccount]);
if ($offerData) {
$offerNameByOfferId[$value['offerId']] = $offerData->getName();
} else {
$offerNameByOfferId[$value['offerId']] = $value['offerId'];
}
}
$value['offerName'] = $offerNameByOfferId[$value['offerId']];
}
$value['accountManagerName'] = array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['name'] : '';
$value['dateUpdated'] = $value['dateUpdated']->format('Y-m-d H:i:s');
$value['capType'] = ucwords(str_replace("_", " ", $value['capType']));
$value['offerId'] = (string)$value['offerId'];
$value['approvalTypeRaw'] = $value['approvalType'];
$value['approvalType'] = Config::APPROVAL_CONTROL_APPROVAL_TYPE[$value['approvalType']];
$value['advertiserId'] || (!$value['advertiserId'] && !$value['advertiserTagId'] && !$value['offerId']) ? $finalArr['byAdvertiser'][] = $value : false;
$value['advertiserTagId'] ? $finalArr['byAdvertiserTag'][] = $value : false;
$value['offerId'] ? $finalArr['byOffer'][] = $value : false;
}
if (isset($fromOfferDetailPage) && $fromOfferDetailPage && sizeof($offerIds) == 1) {
$temp = [];
foreach ($finalArr['byOffer'] as $key => $value) {
if ($value['affiliateId']) {
$temp[$value['affiliateId']] = $value;
}
}
$affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
$approvedAffiliatesByOfferId = $this->brandHasofferApi->getApprovedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
$unapprovedAffiliatesByOfferId = $this->brandHasofferApi->getUnapprovedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
$affiliatesForOfferId = array_merge(!is_array($approvedAffiliatesByOfferId) ? [] : $approvedAffiliatesByOfferId, is_array($unapprovedAffiliatesByOfferId) ? $unapprovedAffiliatesByOfferId : []);
foreach ($affiliatesForOfferId as $affiliateId) {
$approvalType = Config::APPROVAL_CONTROL_APPROVAL_TYPE_DISAPPROVE_ONCE;
if (in_array($affiliateId, $approvedAffiliatesByOfferId)) {
$approvalType = Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE;
}
if (!array_key_exists($affiliateId, $temp) && array_key_exists($affiliateId, $affiliateList)) {
$temp[$affiliateId] = [
'id' => null,
'affiliateId' => (int)$affiliateId,
'accountManagerName' => array_key_exists($affiliateId, $accountManagerInfo) ? $accountManagerInfo[$affiliateId]['firstName'] . ' ' . $accountManagerInfo[$affiliateId]['lastName'] : '',
'affiliateTagId' => null,
'affiliateTagName' => null,
'advertiserId' => null,
'advertiserTagId' => null,
'offerId' => (string)$offerIds[0],
'approvalTypeRaw' => $approvalType,
'approvalType' => Config::APPROVAL_CONTROL_APPROVAL_TYPE[$approvalType],
'isProcessed' => true,
'addedBy' => null,
'dateUpdated' => null,
'capType' => null,
'capValue' => null,
'addedFrom' => null,
'dateInserted' => null,
'offerName' => isset($offerNameByOfferId[$offerIds[0]]) ? $offerNameByOfferId[$offerIds[0]] : ''
];
}
}
ksort($temp);
$finalArr['byOffer'] = array_values($temp);
$finalArr['byAdvertiser'] = [];
$finalArr['byAdvertiserTag'] = [];
}
foreach ($finalArr as $key => $value) {
foreach ($value as $k => $v) {
$index = md5($v['affiliateId'] . '#' . $v['affiliateTagId'] . '#' . $v['advertiserId'] . '#' . $v['advertiserTagId'] . '#' . $v['offerId'] . '#' . $v['isProcessed'] . '#' . $v['addedBy'] . '#' . $v['addedFrom'] . '#' . $v['approvalType']);
if (!array_key_exists($key, $finalFinalArr)) {
$finalFinalArr[$key] = [];
}
if (!array_key_exists($index, $finalFinalArr[$key])) {
$finalFinalArr[$key][$index] = [
'affiliateId' => $v['affiliateId'],
'affiliateTagId' => $v['affiliateTagId'],
'advertiserId' => $v['advertiserId'],
'advertiserTagId' => $v['advertiserTagId'],
'offerId' => $v['offerId'],
'isProcessed' => $v['isProcessed'],
'addedBy' => $v['addedBy'],
'addedFrom' => $v['addedFrom'],
'accountManagerName' => $v['accountManagerName'],
'offerName' => $v['offerName'],
'approvalTypeRaw' => $v['approvalTypeRaw'],
'dateUpdated' => $v['dateUpdated'],
'approvalType' => $v['approvalType'],
'caps' => [],
'ids' => []
];
}
$finalFinalArr[$key][$index]['ids'][] = $v['id'];
if ($v['capType']) {
$finalFinalArr[$key][$index]['caps'][] = [
'capType' => $v['capType'],
'capValue' => $v['capValue']
];
}
}
}
foreach ($finalFinalArr as $key => $value) {
foreach ($value as $k => $v) {
if (array_key_exists($v['affiliateId'], $clickCaps['byAffiliate'])) {
foreach ($clickCaps['byAffiliate'][$v['affiliateId']] as $blockPeriod => $capValue) {
$finalFinalArr[$key][$k]['caps'][] = [
'capType' => ucfirst($blockPeriod) . ' Click Cap By Affiliate',
'capValue' => $capValue['clickCap']
];
}
}
if (array_key_exists($v['offerId'], $clickCaps['byOffer'])) {
foreach ($clickCaps['byOffer'][$v['offerId']] as $blockPeriod => $capValue) {
$finalFinalArr[$key][$k]['caps'][] = [
'capType' => ucfirst($blockPeriod) . ' Click Cap By Offer',
'capValue' => $capValue['clickCap']
];
}
}
if (array_key_exists($v['advertiserId'], $clickCaps['byAdvertiser'])) {
foreach ($clickCaps['byAdvertiser'][$v['advertiserId']] as $blockPeriod => $capValue) {
$finalFinalArr[$key][$k]['caps'][] = [
'capType' => ucfirst($blockPeriod) . ' Click Cap By Advertiser',
'capValue' => $capValue['clickCap']
];
}
}
if (array_key_exists($v['offerId'], $clickCaps['byOfferByAffiliate']) && array_key_exists($v['affiliateId'], $clickCaps['byOfferByAffiliate'][$v['offerId']])) {
foreach ($clickCaps['byOfferByAffiliate'][$v['offerId']][$v['affiliateId']] as $blockPeriod => $capValue) {
$finalFinalArr[$key][$k]['caps'][] = [
'capType' => ucfirst($blockPeriod) . ' Click Cap By Offer By Affiliate',
'capValue' => $capValue['clickCap']
];
}
}
}
$value = $finalFinalArr[$key];
$finalFinalArr[$key] = array_values($value);
}
if ($downloadCSV) {
$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'];
$advertiserList = [];
if (sizeof($finalArr['byAdvertiser'])) {
$advertiserList = $this->commonCalls->getAdvertisersListByStatusWithKeys([
'tuneAccount' => $tuneAccount
]);
}
$affiliateTagList = $this->commonCalls->getAffiliateTagListByStatusWithKeys($tuneAccount);
$row[] = $headers;
foreach ($finalFinalArr as $k => $v) {
foreach ($v as $key => $value) {
if (
(
$downloadCSVByApproved &&
(
$value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE_ONCE ||
$value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_APPROVE
)
) ||
(
$downloadCSVByUnapproved &&
(
$value['approvalTypeRaw'] == Config::APPROVAL_CONTROL_APPROVAL_TYPE_DISAPPROVE_ONCE
)
)
) {
foreach ($value['caps'] as $capIndex => $capVal) {
$temp = [
$value['offerId'],
$value['offerName'],
$value['advertiserId'],
array_key_exists($value['advertiserId'], $advertiserList) ? $advertiserList[$value['advertiserId']]['name'] : '',
$value['affiliateId'],
array_key_exists($value['affiliateId'], $affiliateList) ? str_replace(",", " ", $affiliateList[$value['affiliateId']]['name']) : $value['affiliateId'],
$value['affiliateTagId'],
array_key_exists($value['affiliateTagId'], $affiliateTagList) ? str_replace(",", " ", $affiliateTagList[$value['affiliateTagId']]['name']) : '',
$value['accountManagerName'],
// array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['employeeId'] : null,
$value['addedBy'],
$value['approvalType'],
$capVal['capType'],
$capVal['capValue'],
ucfirst(str_replace("_", " ", $value['addedFrom'])),
$value['dateUpdated'],
];
$row[] = $temp;
}
}
}
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')
->setLastModifiedBy('MAFO')
->setTitle('Approval Control')
->setSubject('Approval Control')
->setDescription('Approval Control');
$spreadsheet->getActiveSheet()
->fromArray(
$row,
NULL,
'A1'
);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="approval control.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
} else {
return new JsonResponse($finalFinalArr);
}
}
/**
* @Route("/approval-control", name="post_approval_control", methods={"POST"})
*/
public function approvalControlPostAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
// $advertiserIds = $payload['advertiserIds'];
$advertiserIdsWithTuneAccount = $payload['advertiserIdsWithTuneAccount'] ?? [];
$advertiserTagIds = $payload['advertiserTagIds'] ?? [];
$affiliateIds = $payload['affiliateIds'];
$affiliateTagIds = $payload['affiliateTagIds'] ?? [];
// $offerIdsPayload = $payload['offerIds'];
$offerIdsWithTuneAccount = $payload['offerIdsWithTuneAccount'] ?? [];
$approvalType = $payload['approvalType'];
$capTypes = $payload['approveCapType'];
$capValue = $payload['capValue'];
// $tuneAccount = $payload['tuneAccount'] ? $payload['tuneAccount'] : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$addedFrom = isset($payload['addedFrom']) ? $payload['addedFrom'] : Config::APPROVAL_CONTROL_ADDED_FROM_APPROVAL_CONTROL;
// $offerIds = [];
// foreach ($offerIdsWithTuneAccount as $offerDetails) {
// $offerIds[] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $offerId));
// }
if (!array_key_exists($approvalType, Config::APPROVAL_CONTROL_APPROVAL_TYPE)) {
return new JsonResponse(true);
}
foreach ($affiliateIds as $affiliateId) {
if ($capTypes) {
foreach ($capTypes as $capType) {
if (in_array($capType, Config::AFFILIATE_OFFER_CAP_TYPE) && $capValue > 0) {
foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
$advertiserId = $advertiserDetails['value'];
$tuneAccount = $advertiserDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy([
'affiliateId' => $affiliateId,
'capType' => $capType,
'advertiserId' => $advertiserId,
'tuneAccount' => $tuneAccount
]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, $advertiserId, null, null, $approvalType, $this->getUser()->getName(), $capType, $capValue, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'capValue' => $capValue,
'addedFrom' => $addedFrom
]);
}
}
foreach ($advertiserTagIds as $advertiserTagId) {
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => $capType, 'advertiserTagId' => $advertiserTagId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, null, $advertiserTagId, null, $approvalType, $this->getUser()->getName(), $capType, $capValue, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'capValue' => $capValue,
'addedFrom' => $addedFrom
]);
}
}
foreach ($offerIdsWithTuneAccount as $offerDetails) {
$offerId = $offerDetails['value'];
$tuneAccount = $offerDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => $capType, 'offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, null, null, $offerId, $approvalType, $this->getUser()->getName(), $capType, $capValue, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'capValue' => $capValue,
'addedFrom' => $addedFrom
]);
}
}
}
}
} else {
foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
$advertiserId = $advertiserDetails['value'];
$tuneAccount = $advertiserDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => null, 'advertiserId' => $advertiserId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, $advertiserId, null, null, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
foreach ($advertiserTagIds as $advertiserTagId) {
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => null, 'advertiserTagId' => $advertiserTagId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, null, $advertiserTagId, null, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
foreach ($offerIdsWithTuneAccount as $offerDetails) {
$offerId = $offerDetails['value'];
$tuneAccount = $offerDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => null, 'offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, null, null, $offerId, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
}
}
foreach ($affiliateTagIds as $affiliateTagId) {
if ($capTypes) {
foreach ($capTypes as $capType) {
if (in_array($capType, Config::AFFILIATE_OFFER_CAP_TYPE) && $capValue > 0) {
foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
$advertiserId = $advertiserDetails['value'];
$tuneAccount = $advertiserDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId, 'capType' => $capType, 'advertiserId' => $advertiserId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null, $affiliateTagId, $advertiserId, null, null, $approvalType, $this->getUser()->getName(), $capType, $capValue, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'capValue' => $capValue,
'addedFrom' => $addedFrom
]);
}
}
foreach ($offerIdsWithTuneAccount as $offerDetails) {
$offerId = $offerDetails['value'];
$tuneAccount = $offerDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId, 'capType' => $capType, 'offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null, $affiliateTagId, null, null, $offerId, $approvalType, $this->getUser()->getName(), $capType, $capValue, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'capValue' => $capValue,
'addedFrom' => $addedFrom
]);
}
}
}
}
} else {
foreach ($advertiserIdsWithTuneAccount as $advertiserDetails) {
$advertiserId = $advertiserDetails['value'];
$tuneAccount = $advertiserDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId, 'capType' => null, 'advertiserId' => $advertiserId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null, $affiliateTagId, $advertiserId, null, null, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
foreach ($offerIdsWithTuneAccount as $offerDetails) {
$offerId = $offerDetails['value'];
$tuneAccount = $offerDetails['tuneAccount'];
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateTagId' => $affiliateTagId, 'capType' => null, 'offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl(null, $affiliateTagId, null, null, $offerId, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
}
}
foreach ($affiliateIds as $affiliateId) {
if (empty($advertiserIdsWithTuneAccount) && empty($advertiserTagIds) && empty($offerIdsWithTuneAccount)) {
$combinationExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['affiliateId' => $affiliateId, 'capType' => null, 'offerId' => null, 'tuneAccount' => $tuneAccount]);
if (!$combinationExist) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($affiliateId, null, null, null, null, $approvalType, $this->getUser()->getName(), null, null, $addedFrom, $tuneAccount);
} else {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($combinationExist->getId(), [
'approvalType' => $approvalType,
'isProcessed' => 0,
'isDeleted' => 0,
'addedFrom' => $addedFrom
]);
}
}
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:approvalControl true --env=prod > /dev/null &";
exec($execCommand);
$execCommand = "php " . $this->projectDir . "/bin/console app:updateCache " . Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_OFFER . " --env=prod > /dev/null &";
exec($execCommand);
$execCommand = "php " . $this->projectDir . "/bin/console app:updateCache " . Config::CACHE_REDIS_APPROVAL_CONTROL_TOTAL_RECORDS_BY_ADVERTISER . " --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/approval-control/{id}", name="patch_approval_control", methods={"PATCH"})
*/
public function patchApprovalControlAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$payload['isProcessed'] = 0;
$payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$payload['addedBy'] = $this->getUser()->getName();
$idExist = $this->doctrine->getRepository(ApprovalControl::class)->findOneBy(['id' => $id]);
if ($idExist) {
$ids = $id != '' ? explode(",", $id) : [];
foreach ($ids as $id) {
$this->doctrine->getRepository(ApprovalControl::class)->updateApprovalControlById($id, $payload);
}
} elseif (isset($payload['affiliateId']) && isset($payload['offerId']) && isset($payload['approvalType'])) {
$this->doctrine->getRepository(ApprovalControl::class)->insertToApprovalControl($payload['affiliateId'], null, null, null, $payload['offerId'], $payload['approvalType'], $this->getUser()->getName(), null, null, Config::APPROVAL_CONTROL_ADDED_FROM_OFFER_INFO, $payload['tuneAccount']);
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:approvalControl true --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/block-control", name="get_block_control", methods={"GET"})
*/
public function getBlockControlAction(Request $request)
{
$queryParams = $request->query->all();
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$affiliateTagIds = $queryParams['affiliateTagIds'] ?? [];
$offerIds = $queryParams['offerIds'] ?? [];
$fromOfferDetailPage = $request->query->get('fromOfferDetailPage');
$downloadCSV = $request->query->get('downloadCSV') == true ? true : false;
$downloadCSVByBlocked = $request->query->get('downloadCSVByBlocked') == true ? true : false;
$downloadCSVByUnblocked = $request->query->get('downloadCSVByUnblocked') == true ? true : false;
$tuneAccount = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$dateStart = $request->query->get('dateStart');
$dateEnd = $request->query->get('dateEnd');
$dateStart = isset($dateStart) ? date('Y-m-d', strtotime($request->query->get('dateStart'))) : null;
$dateEnd = isset($dateEnd) ? date('Y-m-d', strtotime("+1 day", strtotime($request->query->get('dateEnd')))) : null;
$blockControlData = $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->getScheduledOfferBlockData($affiliateIds, $affiliateTagIds, $offerIds, $dateStart, $dateEnd, $tuneAccount);
$affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
$accountManagerInfo = $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys(array_keys($affiliateList), $tuneAccount);
foreach ($blockControlData as $key => $value) {
$blockControlData[$key]['accountManagerName'] = array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['firstName'] . ' ' . $accountManagerInfo[$value['affiliateId']]['firstName'] : '';
$blockControlData[$key]['blockTypeRaw'] = $value['blockType'];
$blockControlData[$key]['offerId'] = (string)$value['offerId'];
$blockControlData[$key]['blockType'] = ucfirst($value['blockType']) . 'ed';
}
if (isset($fromOfferDetailPage) && $fromOfferDetailPage && sizeof($offerIds) == 1) {
$temp = [];
foreach ($blockControlData as $key => $value) {
if ($value['affiliateId']) {
$temp[$value['affiliateId']] = $value;
}
}
$blockedAffiliateIds = $this->brandHasofferApi->getBlockedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
$unBlockedAffiliateIds = $this->brandHasofferApi->getUnblockedAffiliateIdsByOfferId($offerIds[0], $tuneAccount)['response']['data'];
$affiliatesForOfferId = array_merge($blockedAffiliateIds === "" ? [] : $blockedAffiliateIds, $unBlockedAffiliateIds === "" ? [] : $unBlockedAffiliateIds);
foreach ($affiliatesForOfferId as $affiliateId) {
$blockType = Config::AFFILIATE_OFFER_UNBLOCK_MACRO;
if (in_array($affiliateId, $blockedAffiliateIds)) {
$blockType = Config::AFFILIATE_OFFER_BLOCK_MACRO;
}
if (!array_key_exists($affiliateId, $temp) && array_key_exists($affiliateId, $affiliateList)) {
$temp[$affiliateId] = [
'id' => null,
'affiliateId' => (int)$affiliateId,
'accountManagerName' => array_key_exists($affiliateId, $accountManagerInfo) ? $accountManagerInfo[$affiliateId]['firstName'] . ' ' . $accountManagerInfo[$affiliateId]['lastName'] : '',
'affiliateTagId' => null,
'offerId' => (string)$offerIds[0],
'isProcessed' => true,
'addedBy' => null,
'dateUpdated' => null,
'dateInserted' => null,
'blockTypeRaw' => $blockType,
'blockType' => ucfirst($blockType) . 'ed'
];
}
}
ksort($temp);
$blockControlData = array_values($temp);
}
if ($downloadCSV) {
$headers = ['Offer Id', 'Affiliate Id', 'Affiliate Name', 'Account Manager Id', 'Account Manager Name', 'Block Type'];
$row[] = implode(",", $headers);
foreach ($blockControlData as $key => $value) {
if (
(
$downloadCSVByBlocked &&
(
$value['blockTypeRaw'] == Config::AFFILIATE_OFFER_BLOCK_MACRO
)
) ||
(
$downloadCSVByUnblocked &&
(
$value['blockTypeRaw'] == Config::AFFILIATE_OFFER_UNBLOCK_MACRO
)
)
) {
$temp = [
$value['offerId'],
$value['affiliateId'],
array_key_exists($value['affiliateId'], $affiliateList) ? str_replace(",", " ", $affiliateList[$value['affiliateId']]['name']) : $value['affiliateId'],
array_key_exists($value['affiliateId'], $accountManagerInfo) ? $accountManagerInfo[$value['affiliateId']]['employeeId'] : null,
$value['accountManagerName'],
ucfirst($value['blockType'])
];
$row[] = implode(",", array_values($temp));
}
}
$content = implode("\n", $row);
return new Response(
$content,
200,
array(
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="approval-control.csv"'
)
);
} else {
return new JsonResponse($blockControlData);
}
}
/**
* @Route("/block-control", name="post_block_control", methods={"POST"})
*/
public function postBlockControlAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$offerIds = $payload['offerIds'];
$affiliateIds = $payload['affiliateIds'];
$affiliateTagIds = $payload['affiliateTagIds'];
$blockType = $payload['blockType'];
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$blockedFrom = isset($payload['blockedFrom']) ? $payload['blockedFrom'] : Config::OFFER_AFFILIATE_BLOCK_FROM_OFFER_INFO;
foreach ($offerIds as $offerId) {
foreach ($affiliateIds as $affiliateId) {
$combinationExist = $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['offerId' => $offerId, 'affiliateId' => $affiliateId, 'tuneAccount' => $tuneAccount]);
if ($combinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($combinationExist->getId(), [
'isProcessed' => 0,
'addedBy' => $this->getUser()->getName(),
'blockType' => $blockType
]);
} else {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($offerId, $affiliateId, null, $blockedFrom, $this->getUser()->getName(), $blockType, $tuneAccount);
}
}
foreach ($affiliateTagIds as $affiliateTagId) {
$combinationExist = $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['offerId' => $offerId, 'affiliateTagId' => $affiliateTagId, 'tuneAccount' => $tuneAccount]);
if ($combinationExist) {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($combinationExist->getId(), [
'isProcessed' => 0,
'addedBy' => $this->getUser()->getName(),
'blockType' => $blockType
]);
} else {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($offerId, null, $affiliateTagId, $blockedFrom, $this->getUser()->getName(), $blockType, $tuneAccount);
}
}
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:processScheduledAffiliateOfferBlockCommand --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/block-control/{id}", name="patch_block_control", methods={"PATCH"})
*/
public function patchBlockControlAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$payload['addedBy'] = $this->getUser()->getName();
$payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$payload['isProcessed'] = 0;
$blockedFrom = Config::OFFER_AFFILIATE_BLOCK_FROM_OFFER_INFO;
$idExist = $this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->findOneBy(['id' => $id]);
if ($idExist) {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->updateBlockControlById($id, $payload);
} elseif (isset($payload['affiliateId']) && isset($payload['offerId']) && isset($payload['blockType'])) {
$this->doctrine->getRepository(ScheduledAffiliateOfferBlock::class)->insertToOfferAffiliateBlock($payload['offerId'], $payload['affiliateId'], null, $blockedFrom, $this->getUser()->getName(), $payload['blockType'], $payload['tuneAccount']);
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:processScheduledAffiliateOfferBlockCommand --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/disable-link-by-link" ,name = "get_disable_link_by_link", methods={"GET"})
*/
public function getDisableLinkByLinkAction(Request $request)
{
$payload = $request->query->all();
$decodedstat = isset($payload['token']) ? json_decode(base64_decode($payload['token']), true) : [];
$offerId = isset($decodedstat['offerId']) ? $decodedstat['offerId'] : "";
$advertiserId = isset($decodedstat['advertiserId']) ? $decodedstat['advertiserId'] : "";
$affiliateId = isset($decodedstat['affiliateId']) ? $decodedstat['affiliateId'] : "";
$source = isset($decodedstat['source']) ? $decodedstat['source'] : "";
$this->commonCalls->disableLink($offerId, $affiliateId, $source, Config::DEFAULT_AFF_SUB2, Config::DEFAULT_AFF_SUB3, Config::DEFAULT_AFF_SUB5, Config::DISABLE_LINK_FROM_APPNAME_CONTROL, $advertiserId, "[]");
return new JsonResponse([
'success' => true,
'message' => 'Blocked Successfully'
]);
}
/**
* @Route("/impressions", name="get_impressions", methods={"GET"})
*/
public function getImpressionsAction(Request $request)
{
$impressionsData = $this->impressionsApis->getImpressionsData();
$offers = [];
foreach ($impressionsData as $key => $value) {
if (!array_key_exists($value['offer_id'], $offers)) {
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offer_id']]);
$offers[$value['offer_id']] = $offerInfo ? $offerInfo->getName() : '';
}
$impressionsData[$key]['offer_name'] = $offers[$value['offer_id']];
}
return new JsonResponse(array_values($impressionsData));
}
/**
* @Route("/impressions/{id}", name="delete_impressions", methods={"DELETE"})
*/
public function deleteImpressionsAction(Request $request, $id)
{
$this->impressionsApis->deleteImpressionsDataById($id);
return new JsonResponse(true);
}
/**
* @Route("/impressions/{id}", name="put_impressions", methods={"PUT"})
*/
public function putImpressionsAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
if ($payload['ctr'] >= 0) {
$this->impressionsApis->putImpressionsDataById($id, $payload);
}
return new JsonResponse(true);
}
/**
* @Route("/impressions", name="post_impressions", methods={"POST"})
*/
public function postImpressionsAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$offerIds = $payload['offerIds'];
$impressionLink = trim($payload['impressionLink']);
$ctr = trim($payload['ctr']);
foreach ($offerIds as $offerId) {
if ($ctr >= 0) {
$this->impressionsApis->postImpressionsData([
'offer_id' => $offerId,
'ctr' => $ctr,
'impression_link' => $impressionLink,
'added_by' => $this->getUser()->getName(),
'added_by_id' => md5($this->getUser()->getName())
]);
}
}
return new JsonResponse(true);
}
/**
* @Route("/affiliates", name="get_affiliates", methods={"GET"})
*/
public function getAffiliatesAction(Request $request)
{
$limit = $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
$page = $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
$sortBy = $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
$sortType = $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
$queryParams = $request->query->all();
$statusArr = $queryParams['status'] ?? [];
$accountManagerIds = $queryParams['accountManagerIds'] ?? [];
$affiliateTagIds = $queryParams['affiliateTagIds'] ?? [];
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$mmpPartnerIds = $queryParams['mmpPartnerIds'] ?? [];
$mafoAffiliateIds = $queryParams['mafoAffiliateIds'] ?? [];
$mmpSources = $queryParams['mmpSources'] ?? [];
$search = $request->query->get('search') != '' ? $request->query->get('search') : null;
$pullAffiliateDataFromHO = $request->query->get('pullAffiliateDataFromHO') == 1 ? true : false;
$withAffiliateIdKey = $request->query->get('withKeys') == 1 ? true : false;
$downloadDataAsCSV = $request->query->get('downloadCSV') == 1 ? true : false;
$tuneAccount = $request->query->all('tuneAccount') != '' ? $request->query->all('tuneAccount') : [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE];
if ($pullAffiliateDataFromHO && $search && $tuneAccount !== null) {
$tuneAccount = $tuneAccount[0];
$this->commonCalls->updateAffiliateDBByIds([$search], [
'tuneAccount' => $tuneAccount
]);
}
if ($affiliateTagIds) {
$tagIdsDataForAffiliate = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByTagIdArr($affiliateTagIds, $tuneAccount);
foreach ($tagIdsDataForAffiliate as $key => $value) {
!in_array($value['affiliateId'], $affiliateIds) ? array_push($affiliateIds, $value['affiliateId']) : false;
}
}
if ($mmpSources) {
$mappedMmpSourcesAffiliates = $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByMmpSources($mmpSources, $tuneAccount);
if ($affiliateIds) {
$affiliateIds = array_values(array_intersect($affiliateIds, array_values(array_unique(array_column($mappedMmpSourcesAffiliates, 'hoAffiliateId')))));
} else {
$affiliateIds = array_values(array_unique(array_column($mappedMmpSourcesAffiliates, 'hoAffiliateId')));
}
}
if ($mmpPartnerIds) {
$mappedMmpPartnerAffiliates = $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByMmpPartnerIds($mmpPartnerIds, $tuneAccount);
if ($affiliateIds) {
$affiliateIds = array_values(array_intersect($affiliateIds, array_values(array_unique(array_column($mappedMmpPartnerAffiliates, 'hoAffiliateId')))));
} else {
$affiliateIds = array_values(array_unique(array_column($mappedMmpPartnerAffiliates, 'hoAffiliateId')));
}
}
$data = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateInfo(null, null, null, null, $search, $statusArr, $accountManagerIds, $affiliateIds, $mafoAffiliateIds, $tuneAccount);
$distinctAccountManagerIds = [];
$distinctAffiliateIds = [];
$tagDataByAffiliateId = [];
$accountManagerDataByKey = [];
$tagDataByTagId = [];
foreach ($data as $key => $value) {
!in_array($value['accountManagerId'], $distinctAccountManagerIds) ? array_push($distinctAccountManagerIds, $value['accountManagerId']) : false;
!in_array($value['affiliateId'], $distinctAffiliateIds) ? array_push($distinctAffiliateIds, $value['affiliateId']) : false;
}
if ($distinctAccountManagerIds) {
$accountManagerData = $this->doctrine->getRepository(AffiliateAccountManager::class)->getAccountManagerDataByIds($distinctAccountManagerIds, $tuneAccount);
foreach ($accountManagerData as $key => $value) {
$accountManagerDataByKey[$value['employeeId']] = $value;
}
}
if ($distinctAffiliateIds) {
$affiliateTagData = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByAffiliateIdArr($distinctAffiliateIds, $tuneAccount);
$distinctTagIds = [];
foreach ($affiliateTagData as $key => $value) {
!in_array($value['tagId'], $distinctTagIds) ? array_push($distinctTagIds, $value['tagId']) : false;
if (!array_key_exists($value['affiliateId'], $tagDataByAffiliateId)) {
$tagDataByAffiliateId[$value['affiliateId']] = [];
}
$tagDataByAffiliateId[$value['affiliateId']][] = $value['tagId'];
}
if ($distinctTagIds) {
$tagData = $this->doctrine->getRepository(Tag::class)->getTagIdDataByTagIdArr($distinctTagIds, $tuneAccount);
foreach ($tagData as $key => $value) {
$tagDataByTagId[$value['tagId']] = $value;
}
}
}
$affiliateData = [];
foreach ($data as $key => $value) {
$value['accountManagerName'] = array_key_exists($value['accountManagerId'], $accountManagerDataByKey) ? $accountManagerDataByKey[$value['accountManagerId']]['firstName'] . ' ' . $accountManagerDataByKey[$value['accountManagerId']]['lastName'] : '';
if (array_key_exists($value['affiliateId'], $tagDataByAffiliateId)) {
$temp = [];
foreach ($tagDataByAffiliateId[$value['affiliateId']] as $k => $v) {
$temp[] = [
'tagId' => $v,
'tagName' => array_key_exists($v, $tagDataByTagId) ? $tagDataByTagId[$v]['name'] : '',
];
}
$value['tagData'] = $temp;
} else {
$value['tagData'] = [];
}
$affiliateData[$value['affiliateId']] = $value;
}
if ($pullAffiliateDataFromHO && $affiliateData) {
$affiliateInfoFromHO = $this->brandHasofferApi->getAffiliateInfoByAffiliateIdsArr(array_keys($affiliateData), $tuneAccount)['response']['data'];
foreach ($affiliateInfoFromHO as $key => $value) {
$value['Affiliate']['countryName'] = '';
if (isset($value['Affiliate']['country'])) {
$value['Affiliate']['countryName'] = array_key_exists($value['Affiliate']['country'], Config::COUNTRIES) ? Config::COUNTRIES[$value['Affiliate']['country']]['name'] : '';
}
$affiliateData[$value['Affiliate']['id']]['dataFromHO'] = $value;
};
}
$mmpHoMappedDataByAffiliateId = [];
if ($distinctAffiliateIds) {
$mmpHoMappedData = $this->doctrine->getRepository(HoAffiliateMmpPartnerMapping::class)->getMappingByTuneAffiliateIds($distinctAffiliateIds, 0, $tuneAccount);
foreach ($mmpHoMappedData as $key => $value) {
$mmpHoMappedDataByAffiliateId[$value['hoAffiliateId']][] = [
'mmpSource' => $value['mmpPartnerSource'],
'mmpPartnerId' => $value['mmpPartnerId']
];
}
}
foreach ($affiliateData as $key => $value) {
$affiliateData[$key]['mmpMappedData'] = [];
if (array_key_exists($value['affiliateId'], $mmpHoMappedDataByAffiliateId)) {
$affiliateData[$key]['mmpMappedData'] = $mmpHoMappedDataByAffiliateId[$value['affiliateId']];
}
}
if ($downloadDataAsCSV) {
$rows = [['Affiliate Id', 'MAFO Partner Id', 'Company', 'Status', 'Account Manager Id', 'Account Manager Name']];
foreach ($affiliateData as $key => $value) {
$rows[] = [
$value['affiliateId'],
$value['mafoAffiliateId'],
$value['company'],
$value['status'],
$value['accountManagerId'],
$value['accountManagerName'],
];
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')
->setLastModifiedBy('MAFO')
->setTitle('Affiliates')
->setSubject('Affiliates')
->setDescription('Searched Affiliates');
$i = 0;
$spreadsheet->getActiveSheet()
->fromArray(
$rows,
NULL,
'A1'
);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="affiliates.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
} else {
// $totalAffiliates = $this->doctrine->getRepository('App\Entity\Tune\AffiliateInfo')->getTotalDataForForAffiliateInfo($statusArr, $search, $accountManagerIds, $affiliateIds);
// $noOfPages = ceil($totalAffiliates / $limit);
$finalArr = $affiliateData;
$totalRecordCount = $noOfPages = 1;
if (!$withAffiliateIdKey) {
$affiliateData = array_values($affiliateData);
if (sizeof($affiliateData)) {
$entity = $affiliateData[0];
if (array_key_exists($sortBy, $entity)) {
$sortFlag = 3;
if ($sortType == Config::SORT_TYPE_ASC) {
$sortFlag = 4;
}
array_multisort(array_column($affiliateData, $sortBy), $sortFlag, $affiliateData);
}
}
$offset = $limit * ($page - 1);
$totalRecordCount = sizeof($affiliateData);
$noOfPages = ceil($totalRecordCount / $limit);
$finalArr = array_slice($affiliateData, $offset, $limit);
}
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => 200,
'data' => [
'data' => $finalArr,
'metaData' => [
'total' => $totalRecordCount,
'limit' => $limit,
'page' => $page,
'pages' => $noOfPages
]
]
]
]);
}
}
/**
* @Route("/affiliates/skadnetwork-api-token-refresh/{id}", name="get_affiliates_skadnetwork_api_token_refresh", methods={"GET"})
*/
public function getSkadNetworkApiTokenRefreshAction(Request $request, $id)
{
$key = implode('-', str_split(substr(strtolower(md5(microtime() . rand(1000, 9999))), 0, 30), 6));
return new JsonResponse($key);
}
/**
* @Route("/affiliates/{id}/offer-access", name="get_affiliates_offer_access", methods={"GET"})
*/
public function getAffiliateOfferAccessAction(Request $request, $id)
{
$activeOfferIds = $this->brandHasofferApi->getOfferIdsByStatus(Config::ACTIVE_STATUS)['response']['data'];
$blockedOfferIds = $this->brandHasofferApi->getBlockedOfferIdsByAffiliateId($id)['response']['data'];
$approvedOfferIds = $this->brandHasofferApi->getApprovedOfferIdsByAffiliateId($id)['response']['data'];
$blockedActiveOfferIds = array_values(array_intersect($activeOfferIds, $blockedOfferIds));
$unblockedActiveOfferIds = array_values(array_diff($activeOfferIds, $blockedActiveOfferIds));
$approvedActiveOfferIds = array_values(array_intersect($activeOfferIds, $approvedOfferIds));
$unapprovedActiveOfferIds = array_values(array_diff($activeOfferIds, $approvedActiveOfferIds));
$approvedAndUnblockedOfferIds = array_values(array_intersect($approvedActiveOfferIds, $unblockedActiveOfferIds));
$unapprovedAndUnblockedOfferIds = array_values(array_intersect($unapprovedActiveOfferIds, $unblockedActiveOfferIds));
$approvedAndUnblockedOffers = [];
$unapprovedAndUnblockedOffers = [];
$blockedOffers = [];
$distinctOfferIds = array_values(array_unique(array_merge($approvedAndUnblockedOfferIds, $unapprovedAndUnblockedOfferIds, $blockedActiveOfferIds)));
$offerInfo = $this->commonCalls->getOfferInfoByKey($distinctOfferIds);
foreach ($approvedAndUnblockedOfferIds as $offerId) {
$offerName = $advertiserId = $advertiserName = '';
if (array_key_exists($offerId, $offerInfo)) {
$offerName = $offerInfo[$offerId]['name'];
$advertiserName = $offerInfo[$offerId]['advertiserName'];
$advertiserId = $offerInfo[$offerId]['advertiserId'];
}
$approvedAndUnblockedOffers[] = [
'value' => $offerId,
'label' => $offerId . ' ' . $offerName,
'offerId' => $offerId,
'offerName' => $offerName,
'advertiserId' => $advertiserId,
'advertiserName' => $advertiserName,
'addedBy' => ''
];
}
foreach ($unapprovedAndUnblockedOfferIds as $offerId) {
$offerName = $advertiserId = $advertiserName = '';
if (array_key_exists($offerId, $offerInfo)) {
$offerName = $offerInfo[$offerId]['name'];
$advertiserName = $offerInfo[$offerId]['advertiserName'];
$advertiserId = $offerInfo[$offerId]['advertiserId'];
}
$unapprovedAndUnblockedOffers[] = [
'value' => $offerId,
'label' => $offerId . ' ' . $offerName,
'offerId' => $offerId,
'offerName' => $offerName,
'advertiserId' => $advertiserId,
'advertiserName' => $advertiserName,
'addedBy' => ''
];
}
foreach ($blockedActiveOfferIds as $offerId) {
$offerName = $advertiserId = $advertiserName = '';
if (array_key_exists($offerId, $offerInfo)) {
$offerName = $offerInfo[$offerId]['name'];
$advertiserName = $offerInfo[$offerId]['advertiserName'];
$advertiserId = $offerInfo[$offerId]['advertiserId'];
}
$blockedOffers[] = [
'value' => $offerId,
'label' => $offerId . ' ' . $offerName,
'offerId' => $offerId,
'offerName' => $offerName,
'advertiserId' => $advertiserId,
'advertiserName' => $advertiserName,
'addedBy' => ''
];
}
return new JsonResponse([
'blockedOffers' => $blockedOffers,
'approvedAndUnblockedOffers' => $approvedAndUnblockedOffers,
'unapprovedAndUnblockedOffers' => $unapprovedAndUnblockedOffers
]);
}
/**
* @Route("/affiliates", name="post_affiliates", methods={"POST"})
*/
public function postAffiliatesAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$tuneAccount = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$affiliateData = $this->brandHasofferApi->createOrUpdateAffiliate(null, [
'accountManagerId' => $payload['accountManagerId'],
'address1' => $payload['address1'],
'address2' => $payload['address2'],
'city' => $payload['city'],
'company' => $payload['company'],
'country' => $payload['country'],
'phone' => $payload['phone'],
'region' => $payload['region'],
'status' => $payload['status'] ?? Config::ACTIVE_STATUS,
'zipcode' => $payload['zipcode']
], $tuneAccount);
if ($affiliateData['response']['status'] == 1) {
if (is_array($payload['tags']) && sizeof($payload['tags'])) {
$this->brandHasofferApi->setTagIdsForAffiliate($affiliateData['response']['data']['Affiliate']['id'], $payload['tags'], $tuneAccount);
}
$this->brandHasofferApi->createOrUpdateAffiliateUser(null, [
'title' => $payload['title'],
'status' => $payload['status'],
'phone' => $payload['phone'],
'password' => $payload['password'],
'passwordConfirmation' => $payload['confirmPassword'],
'lastName' => $payload['lastName'],
'firstName' => $payload['firstName'],
'email' => $payload['emailAddress'],
'cellPhone' => $payload['phone'],
'affiliateId' => $affiliateData['response']['data']['Affiliate']['id']
], $tuneAccount);
$this->commonCalls->updateAffiliateDBByIds([$affiliateData['response']['data']['Affiliate']['id']], [
'tuneAccount' => $tuneAccount
]);
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => $affiliateData['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_OK);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $affiliateData['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/affiliates/{id}", name="patch_affiliates", methods={"PATCH"})
*/
public function patchAffiliatesAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$tuneAccount = $request->query->get('tuneAccount') != '' ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
if (array_key_exists('updateHO', $payload)) {
$affiliateData = $this->brandHasofferApi->createOrUpdateAffiliate($id, [
'accountManagerId' => $payload['accountManagerId'] ?? null,
'address1' => $payload['address1'],
'address2' => $payload['address2'],
'city' => $payload['city'],
'company' => $payload['company'],
'country' => $payload['country'] ?? null,
'phone' => $payload['phone'],
'region' => $payload['region'],
'status' => $payload['status'],
'zipcode' => $payload['zipcode']
], $tuneAccount);
if ($affiliateData['response']['status'] == 1) {
if (is_array($payload['tags']) && sizeof($payload['tags'])) {
$this->brandHasofferApi->setTagIdsForAffiliate($affiliateData['response']['data']['Affiliate']['id'], $payload['tags'], $tuneAccount);
}
$this->commonCalls->updateAffiliateDBByIds([$affiliateData['response']['data']['Affiliate']['id']], [
'tuneAccount' => $tuneAccount
]);
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => $affiliateData['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_OK);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $affiliateData['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
} else {
$this->commonCalls->updateAffiliateDBByIds([$id], [
'createApiKeyIfNotExist' => true,
'tuneAccount' => $tuneAccount
]);
$this->doctrine->getRepository(AffiliateInfo::class)->updateAffiliateInfoByAffiliateId($id, $payload, $tuneAccount);
return new JsonResponse(true);
}
}
/**
* @Route("/advertisers", name="get_advertisers", methods={"GET"})
*/
public function getAdvertisersAction(Request $request)
{
$limit = $request->query->get('limit') ? $request->query->get('limit') : Config::DATABASE_OFFERS_DEFAULT_PAGE_SIZE;
$page = $request->query->get('page') ? $request->query->get('page') : Config::DATABASE_OFFERS_DEFAULT_PAGE_NUMBER;
$sortBy = $request->query->get('sortBy') ? $request->query->get('sortBy') : Config::DATABASE_OFFERS_DEFAULT_SORT_BY;
$sortType = $request->query->get('sortType') ? $request->query->get('sortType') : Config::DATABASE_OFFERS_DEFAULT_SORT_TYPE;
$queryParams = $request->query->all();
$statusArr = $queryParams['status'] ?? [];
$accountManagerIds = $queryParams['accountManagerIds'] ?? [];
$tagIds = $queryParams['tagIds'] ?? [];
$mafoAdvertiserIds = $queryParams['mafoAdvertiserIds'] ?? [];
$advertiserIds = $queryParams['advertiserIds'] ?? [];
$search = $request->query->get('search') != '' ? $request->query->get('search') : null;
$pullAdvertiserDataFromHO = $request->query->get('pullAdvertiserDataFromHO') == 1;
$withAdvertiserIdKey = $request->query->get('withKeys') == 1;
$downloadDataAsCSV = $request->query->get('downloadCSV') == 1 ? true : false;
$tuneAccount = $request->query->all('tuneAccount') != '' ? $request->query->all('tuneAccount') : [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE];
if ($pullAdvertiserDataFromHO && $search) {
$tuneAccount = $tuneAccount[0];
$this->commonCalls->updateAdvertiserDBByIds(advertiserIds: [$search], tuneAccount: $tuneAccount);
}
if ($tagIds) {
$tagIdsDataForAdvertiser = $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByTagIdArr($tagIds);
foreach ($tagIdsDataForAdvertiser as $key => $value) {
!in_array($value['advertiserId'], $advertiserIds) ? array_push($advertiserIds, $value['advertiserId']) : false;
}
}
if ($tagIds && !$advertiserIds) {
$data = [];
} else {
$data = $this->doctrine->getRepository('App\Entity\Tune\AdvertiserInfo')->getAdvertiserInfo($limit, $page, $sortBy, $sortType, $search, $statusArr, $accountManagerIds, $advertiserIds, $mafoAdvertiserIds, $tuneAccount);
}
$distinctAccountManagerIds = [];
$distinctAdvertiserIds = [];
$tagDataByAdvertiserId = [];
$accountManagerDataByKey = [];
$tagDataByTagId = [];
foreach ($data as $key => $value) {
!in_array($value['accountManagerId'], $distinctAccountManagerIds) ? array_push($distinctAccountManagerIds, $value['accountManagerId']) : false;
!in_array($value['advertiserId'], $distinctAdvertiserIds) ? array_push($distinctAdvertiserIds, $value['advertiserId']) : false;
}
if ($distinctAccountManagerIds) {
$accountManagerData = $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAccountManagerDataByIds($distinctAccountManagerIds, $tuneAccount);
foreach ($accountManagerData as $key => $value) {
$accountManagerDataByKey[$value['employeeId']] = $value;
}
}
if ($distinctAdvertiserIds) {
$advertiserTagData = $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByAdvertiserIdArr($distinctAdvertiserIds, [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE, Config::MAFO_SYSTEM_IDENTIFIER_TUNE_WEB]);
$distinctTagIds = [];
foreach ($advertiserTagData as $key => $value) {
!in_array($value['tagId'], $distinctTagIds) ? array_push($distinctTagIds, $value['tagId']) : false;
if (!array_key_exists($value['advertiserId'], $tagDataByAdvertiserId)) {
$tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']] = [];
}
$tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']][] = $value['tagId'];
}
if ($distinctTagIds) {
$tagData = $this->doctrine->getRepository(Tag::class)->getTagIdDataByTagIdArr($distinctTagIds, [Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE, Config::MAFO_SYSTEM_IDENTIFIER_TUNE_WEB]);
foreach ($tagData as $key => $value) {
$tagDataByTagId[$value['tagId']][$value['tuneAccount']] = $value;
}
}
}
$advertiserData = [];
foreach ($data as $key => $value) {
$value['accountManagerName'] = array_key_exists($value['accountManagerId'], $accountManagerDataByKey) ? $accountManagerDataByKey[$value['accountManagerId']]['firstName'] . ' ' . $accountManagerDataByKey[$value['accountManagerId']]['lastName'] : '';
if (array_key_exists($value['advertiserId'], $tagDataByAdvertiserId)) {
$temp = [];
foreach ($tagDataByAdvertiserId[$value['advertiserId']][$value['tuneAccount']] as $k => $v) {
$temp[] = [
'tagId' => $v,
'tagName' => array_key_exists($v, $tagDataByTagId) ? $tagDataByTagId[$v][$value['tuneAccount']]['name'] : '',
];
}
$value['tagData'] = $temp;
} else {
$value['tagData'] = [];
}
$value['discountType'] = !in_array($value['discountType'], Config::ADVERTISER_DISCOUNT_TYPES) ? Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT : $value['discountType'];
$value['discountTypePretty'] = ucwords(str_replace("_", " ", $value['discountType']));
$advertiserData[$value['advertiserId']] = $value;
}
if ($pullAdvertiserDataFromHO && $advertiserData) {
$advertiserInfoFromHO = $this->brandHasofferApi->getAdvertiserInfoByAdvertiserIdsArr(array_keys($advertiserData), $tuneAccount)['response']['data'];
foreach ($advertiserInfoFromHO as $key => $value) {
$value['Advertiser']['countryName'] = '';
if (isset($value['Affiliate']['country'])) {
$value['Advertiser']['countryName'] = array_key_exists($value['Advertiser']['country'], Config::COUNTRIES) ? Config::COUNTRIES[$value['Advertiser']['country']]['name'] : '';
}
$advertiserData[$value['Advertiser']['id']]['dataFromHO'] = $value;
};
}
if ($downloadDataAsCSV) {
$rows = [['Advertiser Id', 'Company', 'Status', 'Account Manager Id', 'Account Manager Name']];
foreach ($advertiserData as $key => $value) {
$rows[] = [
$value['advertiserId'],
$value['company'],
$value['status'],
$value['accountManagerId'],
$value['accountManagerName'],
];
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')
->setLastModifiedBy('MAFO')
->setTitle('Advertisers')
->setSubject('Advertisers')
->setDescription('Searched Advertisers');
$i = 0;
$spreadsheet->getActiveSheet()
->fromArray(
$rows,
NULL,
'A1'
);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="advertisers.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
} else {
$totalAdvertisers = $this->doctrine->getRepository('App\Entity\Tune\AdvertiserInfo')->getTotalDataForForAdvertiserInfo($statusArr, $search, $accountManagerIds, $advertiserIds, $tuneAccount);
$noOfPages = ceil($totalAdvertisers / $limit);
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => 200,
'data' => [
'data' => $withAdvertiserIdKey ? $advertiserData : array_values($advertiserData),
'metaData' => [
'total' => $totalAdvertisers,
'limit' => $limit,
'page' => $page,
'pages' => $noOfPages
]
]
]
]);
}
}
/**
* @Route("/advertisers", name="post_advertisers", methods={"POST"})
*/
public function postAdvertisersAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$payload['tuneAccount'] = $payload['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
if (strlen($payload['address1']) < 3) {
$payload['address1'] = $payload['address1'] . ' ' . $payload['company'];
}
$advertiserData = $this->brandHasofferApi->createOrUpdateAdvertiser(null, [
'accountManagerId' => $payload['accountManagerId'] ?? null,
'address1' => $payload['address1'] ?? null,
'address2' => $payload['address2'] ?? null,
'city' => $payload['city'] ?? null,
'company' => $payload['company'] ?? null,
'country' => $payload['country'] ?? null,
'phone' => $payload['phone'] ?? null,
'region' => $payload['region'] ?? null,
'status' => $payload['status'] ?? Config::ACTIVE_STATUS,
'zipcode' => $payload['zipcode'] ?? null
], $payload['tuneAccount']);
if ($advertiserData['response']['status'] == 1) {
if (is_array($payload['tags']) && sizeof($payload['tags'])) {
$this->brandHasofferApi->setTagIdsForAdvertiser($advertiserData['response']['data']['Advertiser']['id'], $payload['tags'], $payload['tuneAccount']);
}
$this->brandHasofferApi->createOrUpdateAdvertiserUser(null, [
'title' => $payload['title'] ?? null,
'status' => $payload['status'] ?? null,
'phone' => $payload['phone'] ?? null,
'password' => $payload['password'] ?? null,
'passwordConfirmation' => $payload['confirmPassword'] ?? null,
'lastName' => $payload['lastName'] ?? null,
'firstName' => $payload['firstName'] ?? null,
'email' => $payload['emailAddress'] ?? null,
'cellPhone' => $payload['phone'] ?? null,
'advertiserId' => $advertiserData['response']['data']['Advertiser']['id'] ?? null
], $payload['tuneAccount']);
$metaData = [
'advertiserDiscountType' => $payload['advertiserDiscountType'],
'advertiserDiscountValue' => $payload['advertiserDiscountValue'] ?? null,
];
$this->commonCalls->updateAdvertiserDBById($advertiserData['response']['data']['Advertiser']['id'], $metaData, $payload['tuneAccount']);
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => $advertiserData['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_OK);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $advertiserData['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/advertisers/{id}/skad-network", name="patch_advertisers_skad_network", methods={"PATCH"})
*/
public function patchAdvertisersSKAdNetworkAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$skadNetworkFlag = $payload['skadNetworkFlag'] ?? false;
$skadNetworkId = $payload['skadNetworkId'] ?? null;
$skadNetworkPrivateKey = $payload['skadNetworkPrivateKey'] ?? null;
$this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserByAdvertiserId($id, [
'skadNetworkFlag' => $skadNetworkFlag,
'skadNetworkId' => $skadNetworkId,
'skadNetworkPrivateKey' => $skadNetworkPrivateKey,
]);
return new JsonResponse(true);
}
/**
* @Route("/advertisers/{id}", name="patch_advertisers", methods={"PATCH"})
*/
public function patchAdvertisersAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$payload['tuneAccount'] = $request->query->get('tuneAccount') ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$advertiserData = $this->brandHasofferApi->createOrUpdateAdvertiser($id, [
'accountManagerId' => $payload['accountManagerId'] ?? null,
'address1' => $payload['address1'],
'address2' => $payload['address2'],
'city' => $payload['city'],
'company' => $payload['company'],
'country' => $payload['country'] ?? null,
'phone' => $payload['phone'],
'region' => $payload['region'],
'status' => $payload['status'],
'zipcode' => $payload['zipcode']
], $payload['tuneAccount']);
$metaData = [
'advertiserDiscountType' => $payload['advertiserDiscountType'],
'advertiserDiscountValue' => $payload['advertiserDiscountValue'],
];
if ($advertiserData['response']['status'] == 1) {
if (is_array($payload['tags']) && sizeof($payload['tags'])) {
$this->brandHasofferApi->setTagIdsForAdvertiser($advertiserData['response']['data']['Advertiser']['id'], $payload['tags'], $payload['tuneAccount']);
}
$this->commonCalls->updateAdvertiserDBById($advertiserData['response']['data']['Advertiser']['id'], $metaData, $payload['tuneAccount']);
return new JsonResponse([
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => $advertiserData['response']['data'],
'error' => null
]
], Config::HTTP_STATUS_CODE_OK);
} else {
return new JsonResponse([
'response' => [
'success' => false,
'httpStatus' => Config::HTTP_STATUS_CODE_BAD_REQUEST,
'data' => null,
'error' => $advertiserData['response']['errors']
]
], Config::HTTP_STATUS_CODE_BAD_REQUEST);
}
}
/**
* @Route("/advertisers/affiliate-access/{id}", name="get_advertiser_affiliate_access", methods={"GET"})
*/
public function getAdvertiserAffiliateAccessAction(Request $request, $id)
{
$tuneAccount = $request->query->get('tuneAccount') != '' ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$blockedAffiliates = $this->brandHasofferApi->getBlockedAffiliateIdsByAdvertiserId($id, $tuneAccount);
$unblockedAffiliateIds = $this->brandHasofferApi->getUnblockedAffiliateIdsByAdvertiserId($id, $tuneAccount);
$blockedAffiliateIds = $blockedAffiliates['response']['status'] == 1 ? $blockedAffiliates['response']['data'] : [];
$unblockedAffiliateIds = $unblockedAffiliateIds['response']['status'] == 1 ? $unblockedAffiliateIds['response']['data'] : [];
$affiliateData = $this->commonCalls->getAffiliateListByStatusWithKeys($tuneAccount);
$accountManagerData = $this->commonCalls->getAccountManagerInfoByAffiliateIdArrWithKeys($blockedAffiliateIds, $tuneAccount);
$blockAffiliatesData = [];
$unblockedAffiliatesData = [];
foreach ($blockedAffiliateIds as $affiliateId) {
if (array_key_exists($affiliateId, $affiliateData)) {
$blockAffiliatesData[$affiliateId] = [
'value' => $affiliateData[$affiliateId]['id'],
'label' => $affiliateData[$affiliateId]['id'] . ' - ' . $affiliateData[$affiliateId]['name'],
'accountManagerName' => array_key_exists($affiliateId, $accountManagerData) ? $accountManagerData[$affiliateId]['firstName'] . ' ' . $accountManagerData[$affiliateId]['lastName'] : '',
'status' => $affiliateData[$affiliateId]['status']
];
} else {
$blockAffiliatesData[$affiliateId] = [
'value' => $affiliateId,
'label' => $affiliateId,
'accountManagerName' => '',
'status' => '',
];
}
}
foreach ($unblockedAffiliateIds as $affiliateId) {
if (array_key_exists($affiliateId, $affiliateData)) {
$unblockedAffiliatesData[$affiliateId] = [
'value' => $affiliateData[$affiliateId]['id'],
'label' => $affiliateData[$affiliateId]['id'] . ' - ' . $affiliateData[$affiliateId]['name'],
'accountManagerName' => array_key_exists($affiliateId, $accountManagerData) ? $accountManagerData[$affiliateId]['firstName'] . ' ' . $accountManagerData[$affiliateId]['lastName'] : '',
'status' => $affiliateData[$affiliateId]['status']
];
} else {
$unblockedAffiliatesData[$affiliateId] = [
'value' => $affiliateId,
'label' => $affiliateId,
'accountManagerName' => '',
'status' => '',
];
}
}
return new JsonResponse([
'blockedAffiliatesData' => array_values($blockAffiliatesData),
'unblockedAffiliatesData' => array_values($unblockedAffiliatesData)
]);
}
/**
* @Route("/advertisers/affiliate-access", name="post_advertiser_affiliate_access", methods={"POST"})
*/
public function postAdvertiserAccessAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
if (
isset($payload['advertiserId']) &&
isset($payload['tuneAccount']) &&
isset($payload['affiliateId']) &&
isset($payload['blockType']) &&
$this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $payload['affiliateId'], 'tuneAccount' => $payload['tuneAccount']]) &&
$this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $payload['advertiserId'], 'tuneAccount' => $payload['tuneAccount']]) &&
in_array($payload['blockType'], [Config::AFFILIATE_OFFER_BLOCK_MACRO, Config::AFFILIATE_OFFER_UNBLOCK_MACRO])
) {
if ($payload['blockType'] == Config::AFFILIATE_OFFER_BLOCK_MACRO) {
$this->brandHasofferApi->blockAffiliateForAdvertiser($payload['affiliateId'], $payload['advertiserId'], $payload['tuneAccount']);
} elseif ($payload['blockType'] == Config::AFFILIATE_OFFER_UNBLOCK_MACRO) {
$this->brandHasofferApi->unblockAffiliateForAdvertiser($payload['affiliateId'], $payload['advertiserId'], $payload['tuneAccount']);
}
}
return new JsonResponse($payload);
}
/**
* @Route("/disable-links" ,name = "post_disable_links", methods={"POST"})
*/
public function postDisableLinksAction(Request $request)
{
$file = $request->files->get('file');
$payload = [];
if ($file) {
$file = fopen($request->files->get('file')->getPathName(), 'r');
$index = 0;
while (($line = fgetcsv($file)) !== FALSE) {
if ($line && $index != 0) {
foreach ($line as $key => $value) {
if (preg_match("/\t/", $value)) {
$value = explode("\t", $value)[0];
} else if ($this->commonCalls->checkForString($value, ';')) {
$value = explode(";", $value)[0];
}
$line[$key] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $value));
}
$subIdType = $line[2];
if (
$subIdType == Config::DISABLE_LINK_SUB_TYPE_SOURCE ||
$subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 ||
$subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 ||
$subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5
) {
$payload[] = [
'affiliateId' => $line[0],
'offerId' => $line[1],
Config::DISABLE_LINK_SUB_TYPE_SOURCE => $subIdType == Config::DISABLE_LINK_SUB_TYPE_SOURCE ? $line[3] : Config::DEFAULT_SOURCE,
Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO2 ? $line[3] : Config::DEFAULT_AFF_SUB2,
Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO3 ? $line[3] : Config::DEFAULT_AFF_SUB3,
Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5 => $subIdType == Config::DISABLE_LINK_SUB_TYPE_AFF_INFO5 ? $line[3] : Config::DEFAULT_AFF_SUB5,
];
}
}
$index += 1;
}
fclose($file);
}
foreach ($payload as $key => $value) {
$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());
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:processScheduledOfferDisableLinks --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/price-bulk-edit", name="get_price_bulk_edit", methods={"GET"})
*/
public function getPriceBulkEditAction(Request $request)
{
$queryParams = $request->query->all();
$offerIds = $queryParams['offerIds'] ?? [];
$affiliateIds = $queryParams['affiliateIds'] ?? [];
$affiliateTagIds = $queryParams['affiliateTagIds'] ?? [];
$byAffiliate = $request->query->get('byAffiliate');
$byAffiliateTag = $request->query->get('byAffiliateTag');
$dateStart = date('Y-m-d', strtotime($request->query->get('dateStart')));
$dateEnd = date('Y-m-d', strtotime('+1 day', strtotime($request->query->get('dateEnd'))));
$priceBulkData = $this->doctrine->getRepository(PriceBulkEdit::class)->getPriceBulkEditByFilters($affiliateTagIds, $affiliateIds, $offerIds, $dateStart, $dateEnd, $byAffiliate, $byAffiliateTag, 0);
// $affiliateTagsList = $this->commonCalls->getAffiliateTagListByStatusWithKeys();
// $affiliateList = $this->commonCalls->getAffiliateListByStatusWithKeys();
// $uniqueOfferIds = [];
// $offerInfoWithKeys = [];
// $uniqueOfferGoalIds = [];
// $offerGoalInfoWithKeys = [];
// foreach ($priceBulkData as $key => $value) {
// !in_array($value['goalId'], $uniqueOfferGoalIds) ? array_push($uniqueOfferGoalIds, $value['goalId']) : false;
// !in_array($value['offerId'], $uniqueOfferIds) ? array_push($uniqueOfferIds, $value['offerId']) : false;
// }
// if ($uniqueOfferIds) {
// $offerInfoWithKeys = $this->commonCalls->getOfferInfoByKey($uniqueOfferIds);
// }
// if ($uniqueOfferGoalIds) {
// $offerGoalInfoWithKeys = $this->commonCalls->getOfferGoalInfoByOfferGoalIdArrWithKeys($uniqueOfferGoalIds);
// }
foreach ($priceBulkData as $key => $value) {
$priceBulkData[$key]['dateInserted'] = $value['dateUpdated']->format('Y-m-d H:i:s');
// $priceBulkData[$key]['offerName'] = array_key_exists($value['offerId'], $offerInfoWithKeys) ? $offerInfoWithKeys[$value['offerId']]['name'] : '';
// $priceBulkData[$key]['goalName'] = array_key_exists($value['goalId'], $offerGoalInfoWithKeys) ? $offerGoalInfoWithKeys[$value['goalId']]['name'] : '';
// $priceBulkData[$key]['affiliateTagName'] = array_key_exists($value['affiliateTagId'], $affiliateTagsList) ? $affiliateTagsList[$value['affiliateTagId']]['name'] : '';
// $priceBulkData[$key]['affiliateName'] = array_key_exists($value['affiliateId'], $affiliateList) ? $affiliateList[$value['affiliateId']]['name'] : '';
}
return new JsonResponse($priceBulkData);
}
/**
* @Route("/price-bulk-edit", name="post_price_bulk_edit", methods={"POST"})
*/
public function postPriceBulkEditAction(Request $request)
{
$file = $request->files->get('file');
$payload = [];
if ($file) {
$file = fopen($request->files->get('file')->getPathName(), 'r');
$index = 0;
while (($line = fgetcsv($file)) !== FALSE) {
if ($line && $index != 0) {
foreach ($line as $key => $value) {
if (preg_match("/\t/", $value)) {
$value = explode("\t", $value)[0];
} else if ($this->commonCalls->checkForString($value, ';')) {
$value = explode(";", $value)[0];
}
$line[$key] = trim(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $value));
}
$payload[] = [
'offerId' => $line[0],
'goalId' => $line[1] === '' ? null : $line[1],
'affiliateId' => $line[2] === '' ? null : $line[2],
'affiliateTag' => $line[3] === '' ? null : $line[3],
'priceType' => $line[4],
'price' => $line[5],
'tuneAccount' => $line[6] === '' ? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE : $line[6]
];
}
$index += 1;
}
} else {
$request = json_decode($request->getContent(), true);
$offerIds = $request['offerIds'];
$affiliateIds = $request['affiliateIds'];
$affiliateTagIds = $request['affiliateTagIds'];
$offerGoalIds = $request['offerGoalIds'];
$priceType = $request['priceType'];
$price = $request['price'];
$tuneAccount = $request['tuneAccount'];
foreach ($offerIds as $offerId) {
foreach ($affiliateIds as $affiliateId) {
if ($offerGoalIds) {
foreach ($offerGoalIds as $offerGoalId) {
$payload[] = [
'offerId' => $offerId,
'goalId' => $offerGoalId,
'affiliateId' => $affiliateId,
'affiliateTag' => null,
'priceType' => $priceType,
'price' => $price,
'tuneAccount' => $tuneAccount
];
}
} else {
$payload[] = [
'offerId' => $offerId,
'goalId' => null,
'affiliateId' => $affiliateId,
'affiliateTag' => null,
'priceType' => $priceType,
'price' => $price,
'tuneAccount' => $tuneAccount
];
}
}
foreach ($affiliateTagIds as $affiliateTagId) {
$tagInfo = $this->doctrine->getRepository(Tag::class)->findOneBy(['tagId' => $affiliateTagId, 'tuneAccount' => $tuneAccount]);
if ($offerGoalIds) {
foreach ($offerGoalIds as $offerGoalId) {
$payload[] = [
'offerId' => $offerId,
'goalId' => $offerGoalId,
'affiliateId' => null,
'affiliateTag' => $tagInfo->getName(),
'affiliateTagId' => $affiliateTagId,
'priceType' => $priceType,
'price' => $price,
'tuneAccount' => $tuneAccount
];
}
} else {
$payload[] = [
'offerId' => $offerId,
'goalId' => null,
'affiliateId' => null,
'affiliateTag' => $tagInfo->getName(),
'affiliateTagId' => $affiliateTagId,
'priceType' => $priceType,
'price' => $price,
'tuneAccount' => $tuneAccount
];
}
}
}
}
foreach ($payload as $key => $value) {
if ($value['goalId']) {
$goalExist = $this->doctrine->getRepository(OfferGoalsInfo::class)->findOneBy([
'offerId' => $value['offerId'],
'goalId' => $value['goalId'],
'tuneAccount' => $value['tuneAccount']
]);
if (!$goalExist) {
continue;
}
}
$value['affiliateTagId'] = null;
if ($value['affiliateTag']) {
$tagExist = $this->doctrine->getRepository(Tag::class)->findOneBy(['name' => $value['affiliateTag'], 'tuneAccount' => $value['tuneAccount']]);
if ($tagExist) {
$value['affiliateTagId'] = $tagExist->getTagId();
} else {
continue;
}
}
if ($value['affiliateId']) {
$affiliateExist = $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['affiliateId'], 'tuneAccount' => $value['tuneAccount']]);
if (!$affiliateExist) {
continue;
}
}
if ($value['affiliateTag'] && $value['affiliateId']) {
continue;
}
if (
in_array($value['priceType'], Config::PRICE_BULK_EDIT_PRICE_TYPES) &&
$value['price'] > 0 &&
$this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['offerId']])
) {
$combinationExist = $this->doctrine->getRepository(PriceBulkEdit::class)->findOneBy([
'affiliateId' => $value['affiliateId'],
'affiliateTagId' => $value['affiliateTagId'],
'offerId' => $value['offerId'],
'goalId' => $value['goalId'],
'priceType' => $value['priceType'],
'tuneAccount' => $value['tuneAccount']
]);
if (!$combinationExist) {
$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']);
} else {
$this->doctrine->getRepository(PriceBulkEdit::class)->updatePriceBulkEditById($combinationExist->getId(), [
'price' => $value['price'],
'addedBy' => $this->getUser()->getName(),
'isDeleted' => 0,
'isScheduled' => 1
]);
}
}
}
if ($this->getParameter('kernel.environment') != Config::ENVIRONMENT_DEV) {
$execCommand = "php " . $this->projectDir . "/bin/console app:priceBulkEdit --env=prod > /dev/null &";
exec($execCommand);
}
return new JsonResponse(true);
}
/**
* @Route("/price-bulk-edit/{id}", name="patch_price_bulk_edit", methods={"PATCH"})
*/
public function patchPriceBulkEditAction(Request $request, $id)
{
$payload = json_decode($request->getContent(), true);
$payload['addedBy'] = $this->getUser()->getName();
$this->doctrine->getRepository(PriceBulkEdit::class)->updatePriceBulkEditById($id, $payload);
return new JsonResponse(true);
}
/**
* @Route("/link-hyper-client-with-tune-advertiser", name="post_link_hyper_tune", methods={"POST"})
*/
public function postLinkHyperClientWithTuneAdvertiser(Request $request, MafoObjectsComponents $mafoObjectsComponents, HyperApis $hyperApis)
{
$payload = json_decode($request->getContent(), true);
$hyperClientId = $payload['hyperClientId'];
$tuneAdvertiserId = $payload['tuneAdvertiserId'];
$mafoAdvertisersMapping = $this->doctrine->getRepository(MafoAdvertisersMapping::class)->findOneBy([
'systemIdentifier' => Config::MAFO_SYSTEM_IDENTIFIER_TUNE,
'systemIdentifierId' => $tuneAdvertiserId
]);
if (!$mafoAdvertisersMapping) {
$mafoObjectsComponents->createOrUpdateAdvertiser(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $tuneAdvertiserId);
}
$mafoAdvertisersMapping = $this->doctrine->getRepository(MafoAdvertisersMapping::class)->findOneBy([
'systemIdentifier' => Config::MAFO_SYSTEM_IDENTIFIER_TUNE,
'systemIdentifierId' => $tuneAdvertiserId
]);
if ($mafoAdvertisersMapping) {
$this->doctrine->getRepository(MafoAdvertisersMapping::class)->updateMafoAdvertisersMappingById($mafoAdvertisersMapping->getId(), [
'hyperClientId' => $hyperClientId
]);
}
$advertiserName = null;
$advertiserInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy([
'advertiserId' => $tuneAdvertiserId
]);
if ($advertiserInfo) {
$advertiserName = $advertiserInfo->getCompany();
}
// TODO: remove later when we shift web account completely to default account's hyper
if ($this->doctrine->getRepository(ObjectMappingWithTuneWebAccount::class)->findOneBy([
'defaultAccountId' => $tuneAdvertiserId,
'objectType' => Config::TUNE_ACCOUNT_MAPPING_OBJECT_TYPE_ADVERTISER
])) {
return new JsonResponse(true);
}
$hyperApis->mapTuneAdvertiserWithHyper($tuneAdvertiserId, $advertiserName, $hyperClientId);
return new JsonResponse(true);
}
/**
* @Route("/affiliate-rating", methods={"GET"})
*/
public function affiliateRatingGetAction(Request $request)
{
$tuneAccount = $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$period = date('Y-m-01', strtotime("-1 month"));
$affiliateRatingData = $this->doctrine->getRepository(AffiliateRating::class)->getAffiliateRatingDataByPeriod($request->query->get('affiliateId'), $period);
return new JsonResponse($affiliateRatingData);
}
/**
* @Route("/affiliate-rating", methods={"POST"})
*/
public function affiliateRatingAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
$tuneAccount = $request->query->get('tuneAccount') ? $request->query->get('tuneAccount') : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
extract($payload);
$period = new \Datetime(date('Y-m-01', strtotime("-1 month")));
$checkAffiliateExistForPeriod = $this->doctrine->getRepository(AffiliateRating::class)->findOneBy([
'affiliateId' => $affiliateId,
'period' => $period,
'tuneAccount' => $tuneAccount
]);
if ($checkAffiliateExistForPeriod) {
$this->doctrine->getRepository(AffiliateRating::class)->updateAdjustAppDetailsById($checkAffiliateExistForPeriod->getId(), [
'qualityFeedback' => $qualityFeedback,
'responsivenessFeedback' => $responsivenessFeedback,
'clickControlFeedback' => $clickControlFeedback,
'impressionControlFeedback' => $impressionControlFeedback,
]);
} else {
$this->doctrine->getRepository(AffiliateRating::class)->insertToAffiliateRating($affiliateId, $period, $qualityFeedback, $clickControlFeedback, $impressionControlFeedback, $responsivenessFeedback, [], $tuneAccount);
}
return new JsonResponse(true);
}
}