<?php
namespace App\Services;
use App\Config;
use App\Entity\AdjustAppDetails;
use App\Entity\AdvertiserAccountManager;
use App\Entity\AdvertiserInfo;
use App\Entity\AdvertiserTagRelationship;
use App\Entity\AffiliateAccountManager;
use App\Entity\AffiliateInfo;
use App\Entity\AffiliateOfferApproval;
use App\Entity\AffiliateOfferBlockLogs;
use App\Entity\AffiliateTagRelationship;
use App\Entity\MafoAffiliates;
use App\Entity\AlertMeta;
use App\Entity\AppInfo;
use App\Entity\CommandLogger;
use App\Entity\DeductionControl;
use App\Entity\Employees;
use App\Entity\MafoUserNotifications;
use App\Entity\MmpAdvertisers;
use App\Entity\MmpMobileApps;
use App\Entity\ObjectMappingWithTuneWebAccount;
use App\Entity\OfferCategories;
use App\Entity\OfferCategoryRelationship;
use App\Entity\OfferCreativeFile;
use App\Entity\OfferGeoRelationship;
use App\Entity\OfferGoalsInfo;
use App\Entity\OfferInfo;
use App\Entity\OfferTagRelationship;
use App\Entity\OfferWhitelist;
use App\Entity\SkadNetworkApiLogs;
use App\Entity\SkadNetworkManualPostbackMapping;
use App\Entity\SkadNetworkPostbackLogs;
use App\Entity\Tag;
use App\Entity\UserApiKey;
use App\Entity\Users;
use App\Entity\MafoAdvertisers;
use App\Entity\MafoOffers;
use App\Repository\AdvertiserAccountManagerRepository;
use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;
use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\ObjectUploader;
use Aws\S3\S3Client;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Twig\Environment;
/**
*
* Common functions which are used throughout the project
*
* Class Common
* @package App\Services
*/
class Common
{
private $em;
private $brandApi;
private $doctrine;
private $scraper;
private $elasticCache;
private $rootPath;
private $usersComponents;
private $mafoObjectsComponents;
private $hyperApis;
private LoggerInterface $logger;
private HubInterface $hub;
public function __construct(
MysqlQueries $em,
BrandHasofferAPI $brandApi,
EntityManagerInterface $doctrine,
Scraper $scraper,
Environment $templating,
Aws\ElasticCache $elasticCache,
ParameterBagInterface $params,
UsersComponents $usersComponents,
MafoObjectsComponents $mafoObjectsComponents,
HyperApis $hyperApis,
LoggerInterface $logger,
HubInterface $hub
) {
$this->em = $em;
$this->brandApi = $brandApi;
$this->doctrine = $doctrine;
$this->scraper = $scraper;
$this->template = $templating;
$this->elasticCache = $elasticCache;
$this->rootPath = $params->get('kernel.project_dir');
$this->usersComponents = $usersComponents;
$this->mafoObjectsComponents = $mafoObjectsComponents;
$this->hyperApis = $hyperApis;
$this->logger = $logger;
$this->hub = $hub;
}
public function getAdvertisersListByStatusWithKeys($arr = [])
{
$statuses = isset($arr['statuses']) && sizeof($arr['statuses']) > 0 ? $arr['statuses'] : [Config::ACTIVE_STATUS];
$tuneAccount = isset($arr['tuneAccount']) ? $arr['tuneAccount'] : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT . '_' . $tuneAccount);
if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
$advertiserList = $this->getWarmedUpHoAdvertiserList($statuses, $tuneAccount);
} else {
$advertiserList = json_decode($cachedList, true);
}
ksort($advertiserList);
return $advertiserList;
}
public function getWarmedUpHoAdvertiserList($statuses, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$advertiserList = [];
$advertiserData = $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserListByStatus($statuses, $tuneAccount );
$employeesInfo = $this->getEmployeesByEmployeeId();
foreach ($advertiserData as $key => $value) {
$temp = [
'status' => $value['status'],
'name' => $value['company'],
'accountManagerId' => $value['accountManagerId'],
'accountManagerEmail' => null,
'accountManagerName' => null,
'id' => (int)$value['advertiserId']
];
if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
$temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
$temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
}
$advertiserList[$value['advertiserId']] = $temp;
}
return $advertiserList;
}
public function getAffiliateListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$statuses = [Config::ACTIVE_STATUS];
$tuneAccountCacheKey = Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT . '_' . $tuneAccount;
$cachedList = $this->elasticCache->redisGet($tuneAccountCacheKey);
if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
$affiliateList = $this->getWarmedUpHoAffiliateList($statuses, $tuneAccount);
} else {
$affiliateList = json_decode($cachedList, true);
}
ksort($affiliateList);
return $affiliateList;
}
public function getPublisherAffiliateListByStatusWithKeys($statuses = [Config::ACTIVE_STATUS], $affiliateIds)
{
// $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT);
//
// if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
// $affiliateList = $this->getWarmedUpHoPublisherAffiliateList($statuses);
// } else {
// $affiliateList = json_decode($cachedList, true);
// }
$affiliateList = $this->getWarmedUpHoPublisherAffiliateList($statuses, $affiliateIds);
ksort($affiliateList);
return $affiliateList;
}
public function getWarmedUpHoAffiliateList($statuses, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$affiliateList = [];
$affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses, $tuneAccount);
$employeesInfo = $this->getEmployeesByEmployeeId();
foreach ($affiliateData as $key => $value) {
$temp = [
'status' => $value['status'],
'name' => $value['company'],
'accountManagerId' => $value['accountManagerId'],
'accountManagerEmail' => null,
'accountManagerName' => null,
'id' => (int)$value['affiliateId']
];
if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
$temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
$temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
}
$affiliateList[$value['affiliateId']] = $temp;
}
return $affiliateList;
}
public function getWarmedUpHoPublisherAffiliateList(array $statuses, array $affiliateIds = [])
{
$affiliateList = [];
// Fetch affiliate data based on status
$affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses);
// Get employee information
$employeesInfo = $this->getEmployeesByEmployeeId();
foreach ($affiliateData as $value) {
// Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
$temp = [
'status' => $value['status'],
'name' => $value['company'],
'accountManagerId' => $value['accountManagerId'],
'accountManagerEmail' => null,
'accountManagerName' => null,
'id' => (int)$value['affiliateId']
];
// Check if account manager info is available
if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
$temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
$temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
}
// Add to affiliate list
$affiliateList[$value['affiliateId']] = $temp;
}
}
return $affiliateList;
}
public function getWarmedUpHoPublisherMafoAffiliateList(array $statuses, array $affiliateIds = [])
{
$affiliateList = [];
// Fetch affiliate data based on status
$affiliateData = $this->doctrine->getRepository(MafoAffiliates::class)->getAffiliateListByStatusArr($statuses);
// Get employee information
$employeesInfo = $this->getEmployeesByEmployeeId();
foreach ($affiliateData as $value) {
// Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
$temp = [
'status' => $value['status'],
'name' => $value['name'],
'accountManagerId' => $value['accountManagerId'],
'accountManagerEmail' => null,
'accountManagerName' => null,
'id' => (int)$value['id']
];
// Check if account manager info is available
if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
$temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
$temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
}
// Add to affiliate list
$affiliateList[$value['id']] = $temp;
}
}
return $affiliateList;
}
public function getHyperClientCachedListByKeys()
{
$cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_CLIENT_LIST);
if (!$cachedList) {
$clientList = $this->getHyperClientListByKeys();
} else {
$clientList = json_decode($cachedList, true);
}
return $clientList;
}
public function getHyperClientListByKeys()
{
$hyperData = $this->hyperApis->getHyperClientList();
$clientList = [];
if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
foreach ($hyperData['ResultData']['Data'] as $key => $value) {
$countryCode = null;
foreach (Config::COUNTRIES as $k => $v) {
if ($this->checkForString($value['Country'], $v['name'])) {
$countryCode = $k;
break;
}
}
$value['countryCode'] = $countryCode;
$clientList[$value['ClientNumber']] = $value;
}
}
$this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LIST, json_encode($clientList));
return $clientList;
}
public function getHyperPublisherCachedListByKeys()
{
$cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_PUBLISHER_LIST);
if (!$cachedList) {
$clientList = $this->getHyperPublisherListByKeys();
} else {
$clientList = json_decode($cachedList, true);
}
return $clientList;
}
public function getHyperPublisherListByKeys()
{
$hyperData = $this->hyperApis->getHyperPublisherInfo();
$clientList = [];
if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
foreach ($hyperData['ResultData']['Data'] as $key => $value) {
$countryCode = null;
foreach (Config::COUNTRIES as $k => $v) {
if ($this->checkForString($value['Country'], $v['name'])) {
$countryCode = $k;
break;
}
}
$value['countryCode'] = $countryCode;
$clientList[$value['SupplierNumber']] = $value;
}
}
return $clientList;
}
public function getHyperAffiliateListByKeys()
{
$hyperData = $this->hyperApis->getHyperClientList();
$clientList = [];
if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
foreach ($hyperData['ResultData']['Data'] as $key => $value) {
$countryCode = null;
foreach (Config::COUNTRIES as $k => $v) {
if ($this->checkForString($value['Country'], $v['name'])) {
$countryCode = $k;
break;
}
}
$value['countryCode'] = $countryCode;
$clientList[$value['ClientNumber']] = $value;
}
}
$this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LIST, json_encode($clientList));
return $clientList;
}
public function getMmpAdvertisersListWithKeys()
{
$advertisers = $this->doctrine->getRepository(MmpAdvertisers::class)->getMmpAdvertisers();
$data = [];
foreach ($advertisers as $key => $value) {
$data[$value['id']] = [
'value' => $value['id'],
'label' => $value['name']
];
}
ksort($data);
return $data;
}
public function getAffiliateTagListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$tagsInDb = $this->doctrine->getRepository(Tag::class)->getTags(1, null, null, 1, $tuneAccount);
$tagList = [];
foreach ($tagsInDb as $key => $value) {
$tagList[$value['tagId']] = [
'value' => $value['tagId'],
'name' => $value['name']
];
}
ksort($tagList);
return $tagList;
}
public function getOfferCategoriesListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$status = Config::ACTIVE_STATUS;
$offerCategoriesData = $this->doctrine->getRepository(OfferCategories::class)->getOfferCategoriesByStatus($status, $tuneAccount);
$offerCategoryList = [];
foreach ($offerCategoriesData as $key => $value) {
$offerCategoryList[$value['categoryId']] = [
'name' => $value['name'],
'id' => (int)$value['categoryId']
];
}
ksort($offerCategoryList);
return $offerCategoryList;
}
public function getAdvertiserListByAdvertiserIdArr($advertiserIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$advertiserDataByAdvertiserId = [];
if ($advertiserIdArr) {
$advertiserInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserInfoByAdvertiserIdArr($advertiserIdArr, $tuneAccount);
foreach ($advertiserInfo as $key => $value) {
$advertiserDataByAdvertiserId[$value['advertiserId']] = [
'id' => (int)$value['advertiserId'],
'name' => $value['company']
];
}
}
return $advertiserDataByAdvertiserId;
}
public function getGoalDisableLinkData($offerId)
{
$data = $this->em->getGoalDisableLinkData($offerId);
$distinctOfferIds = [];
foreach ($data as $key => $value) {
if (!in_array($value['offerId'], $distinctOfferIds)) {
$distinctOfferIds[] = $value['offerId'];
}
}
$offerGoalsByOfferId = [];
if ($distinctOfferIds) {
$offerGoalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferIdArr($distinctOfferIds);
if ($offerGoalData) {
foreach ($offerGoalData as $key => $value) {
$offerGoalsByOfferId[$value['offerId']][] = $value['goalId'];
}
}
}
$bifurcatedData = [];
foreach ($data as $key => $value) {
if (array_key_exists($value['offerId'], $offerGoalsByOfferId) && in_array($value['goalId'], $offerGoalsByOfferId[$value['offerId']])) {
$bifurcatedData[$value['addedFrom']][] = $value;
}
}
return $bifurcatedData;
}
public function disableLink($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $addedFrom, $advertiserId, $jsonMetaDataStr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$disableLinkMd5 = $this->getDisableLinkMd5($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $tuneAccount);
$md5Exist = $this->em->getDisableLinkByMd5($disableLinkMd5);
if (!$md5Exist) {
$data = $this->brandApi->saveOfferDisabledLink($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $tuneAccount);
if ($data['response']['status'] === 1) {
$this->em->insertToDisableLink($disableLinkMd5, $offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $addedFrom, $advertiserId, $jsonMetaDataStr);
}
}
}
public function getDisableLinkMd5($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $trackingAccount = Config::TUNE_ACCOUNT_DEFAULT, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$trackingAccountStr = $trackingAccount == Config::TUNE_ACCOUNT_DEFAULT ? '' : Config::TUNE_ACCOUNT_WEB;
return md5($offerId . $affiliateId . $source . $affsub2 . $affSub3 . $affSub5 . $trackingAccountStr . $tuneAccount);
}
public function automaticDisableLinkData($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$automaticDisableLinkData = $this->em->getAutomaticDisableLinkData($tuneAccount);
$finalArr['byAdvertiser'] = [];
$finalArr['byAffiliate'] = [];
$finalArr['byOffer'] = [];
foreach ($automaticDisableLinkData as $key => $value) {
$value['tuneAccountPretty'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['tuneAccount']];
$value['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
if ($value['advertiserId']) {
$finalArr['byAdvertiser'][] = $value;
}
if ($value['affiliateId']) {
$finalArr['byAffiliate'][] = $value;
}
if ($value['offerId']) {
$finalArr['byOffer'][] = $value;
}
}
return $finalArr;
}
public function deleteDisableLinkByMd5($md5, $id, $trackingAccount = Config::TUNE_ACCOUNT_DEFAULT)
{
$disableLink = $this->em->getDisableLinkByMd5($md5);
if ($disableLink) {
$offerId = $disableLink->getOfferId();
$affiliateId = $disableLink->getAffiliateId();
$source = $disableLink->getSource();
$affSub2 = $disableLink->getAffsub2();
$affSub3 = $disableLink->getAffsub3();
$affSub5 = $disableLink->getAffsub5();
$advertiserId = $disableLink->getAdvertiserId();
$addedFrom = $disableLink->getAddedFrom();
$meta = $disableLink->getMeta();
$wasInsertedOn = $disableLink->getDateInserted();
$trackingAccount = $disableLink->getTrackingAccount();
$strict = 0;
$disableLinkData = $this->brandApi->findDisableLink($offerId, $affiliateId, $source, $strict, $affSub2, $affSub3, $affSub5, $trackingAccount)['response']['data'];
foreach ($disableLinkData as $k => $v) {
$this->brandApi->deleteDisableLink($k, $trackingAccount);
}
$this->em->deleteDisableLinkByMd5($md5);
// Removing dump from mysql and added dump of DisableLinks to mongo
// $this->em->insertToDisableLinkDump($md5, $offerId, $affiliateId, $source, $affSub2, $addedFrom, $advertiserId, $meta, $wasInsertedOn, $affSub3, $affSub5, $trackingAccount);
} else {
$this->brandApi->deleteDisableLink($id);
}
}
public function checkForNonIncentInString($string)
{
if ($this->checkForString($string, 'Non Incent') || $this->checkForString($string, 'NO Incent') || $this->checkForString($string, 'No-Incent') || $this->checkForString($string, 'Non-Incent') || $this->checkForString($string, 'NonIncent') || $this->checkForString($string, 'NoIncent') || $this->checkForString($string, 'No_Incent') || $this->checkForString($string, 'Non_Incent')) {
return true;
}
return false;
}
public function checkForString($superString, $checkString)
{
if (strpos(strtolower($superString), strtolower($checkString)) !== false) {
return true;
} else {
return false;
}
}
public function filterSource($source)
{
if ($this->checkForString($source, "_")) {
$source = explode("_", $source);
if (($source[0] == "" && $source[1] != "") || ($source[0] != "" && $source[1] == "") || ($source[0] == "" && $source[1] == "")) {
$source = implode("_", $source);
} else {
$source = $source[0];
}
}
return $source;
}
public function filterSourceByAffiliate($source, $affiliateId)
{
if ($affiliateId == 3467) {
$actualSource = $source;
if (substr($source, 0, 4) === "114_") {
$actualSource = substr($source, 4);
}
return $actualSource;
}
return $source;
}
public function filterSourceByAffiliateAndLtr($source, $affiliateId, $clicks, $conversions)
{
if ($affiliateId == 3467) {
$actualSource = $source;
if (substr($source, 0, 4) === "114_") {
$actualSource = substr($source, 4);
}
if ($conversions > 15 && (($conversions / $clicks) * 100 > 30)) {
return $actualSource;
} else {
return false;
}
}
return $source;
}
public function getBulkCapData()
{
$bulkData = $this->em->getBulkCapData();
foreach ($bulkData as $key => $value) {
$bulkData[$key]['affiliateOfferCapType'] = str_replace("_", " ", ucfirst($value['affiliateOfferCapType']));
$bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
}
return $bulkData;
}
public function getBulkCapByAffiliateData()
{
$bulkData = $this->em->getBulkCapByAffiliateData();
foreach ($bulkData as $key => $value) {
$bulkData[$key]['affiliateOfferCapType'] = str_replace("_", " ", ucfirst($value['affiliateOfferCapType']));
$bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
}
return $bulkData;
}
public function getAccountManagerInfoByTuneAdvertiserId($advertiserId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$accountManagerInfo = $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAdvertiserAccountManagerByAdvertiserId($advertiserId, $tuneAccount);
$email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
$firstName = '';
$lastName = '';
if ($accountManagerInfo) {
$email = $accountManagerInfo->getEmail();
$firstName = $accountManagerInfo->getFirstName();
$lastName = $accountManagerInfo->getLastName();
}
return [
'emailId' => $email,
'firstName' => $firstName,
'lastName' => $lastName
];
}
public function getAccountManagerInfoByMafoAdvertiserId($advertiserId)
{
$mafoAdvertiserInfo = $this->doctrine->getRepository(MafoAdvertisers::class)->findOneBy(['id' => $advertiserId]);
$email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
$firstName = '';
$lastName = '';
if ($mafoAdvertiserInfo) {
$accountManagerInfo = $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAdvertiserInfo->getAccountManagerEmail()]);
$email = $mafoAdvertiserInfo->getAccountManagerEmail();
$name = $accountManagerInfo->getName();
$nameArr = explode(" ", $name);
$firstName = $nameArr[0];
$lastName = $nameArr[1];
}
return [
'emailId' => $email,
'firstName' => $firstName,
'lastName' => $lastName
];
}
public function getAccountManagerInfoByTuneAffiliateId($affiliateId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$accountManagerInfo = $this->doctrine->getRepository(AffiliateAccountManager::class)->getAffiliateAccountManagerByAffiliateId($affiliateId, $tuneAccount);
$email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
$firstName = '';
$lastName = '';
if ($accountManagerInfo) {
$email = $accountManagerInfo->getEmail();
$firstName = $accountManagerInfo->getFirstName();
$lastName = $accountManagerInfo->getLastName();
}
return [
'emailId' => $email,
'firstName' => $firstName,
'lastName' => $lastName
];
}
public function getAccountManagerInfoByMafoAffiliateId($affiliateId)
{
$mafoAffiliateInfo = $this->doctrine->getRepository(MafoAffiliates::class)->findOneBy(['id' => $affiliateId]);
$email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
$firstName = '';
$lastName = '';
if ($mafoAffiliateInfo) {
$accountManagerInfo = $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAffiliateInfo->getAccountManagerEmail()]);
$email = $mafoAffiliateInfo->getAccountManagerEmail();
$name = $accountManagerInfo->getName();
$nameArr = explode(" ", $name);
$firstName = $nameArr[0];
$lastName = $nameArr[1];
}
return [
'emailId' => $email,
'firstName' => $firstName,
'lastName' => $lastName
];
}
public function getAccountManagerInfoByAffiliateIdArrWithKeys($affiliateIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$accountManagerInfoDB = $this->doctrine->getRepository(AffiliateAccountManager::class)->getDataByAffiliateIds($affiliateIdArr, $tuneAccount );
$accountManagerInfo = [];
foreach ($accountManagerInfoDB as $key => $value) {
$accountManagerInfo[$value['affiliateId']] = $value;
$accountManagerInfo[$value['affiliateId']]['id'] = $value['employeeId'];
$accountManagerInfo[$value['affiliateId']]['name'] = $value['firstName'] . ' ' . $value['lastName'];
}
return $accountManagerInfo;
}
public function getAccountManagerInfoByOfferId($offerId)
{
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->checkOfferIdExist($offerId);
return $this->getAccountManagerInfoByTuneAdvertiserId($offerInfo ? $offerInfo->getAdvertiserId() : null);
}
public function getDisableLinkLogs($affiliateIdArray, $offerIdArray, $sourceIdArray, $advertiserArray, $addedFromArr, $dateStart, $dateEnd, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$disableLinksMyMd5 = [];
$disableLinkData = [];
if (empty($addedFromArr) || in_array(Config::DISABLE_LINKS_FROM_HO_PANEL, $addedFromArr)) {
$disableLinkDataFromHO = $this->brandApi->findDisableLinksDyDateRange($offerIdArray, $affiliateIdArray, $sourceIdArray, [], $dateStart, $dateEnd, $tuneAccount)['response']['data']['data'];
$disableLinkData = [];
$md5Arr = [];
foreach ($disableLinkDataFromHO as $key => $value) {
$md5 = $this->getDisableLinkMd5($value['OfferDisabledLink']['offer_id'], $value['OfferDisabledLink']['affiliate_id'], $value['OfferDisabledLink']['source'], Config::DEFAULT_AFF_SUB2, Config::DEFAULT_AFF_SUB3, Config::DEFAULT_AFF_SUB5, $tuneAccount);
$disableLinkData[] = [
'affiliateId' => $value['OfferDisabledLink']['affiliate_id'],
'offerId' => $value['OfferDisabledLink']['offer_id'],
'source' => $value['OfferDisabledLink']['source'],
'advertiserId' => null,
'dateInserted' => $value['OfferDisabledLink']['datetime'],
'addedFrom' => null,
'md5' => $md5,
'tuneAccount' => $tuneAccount,
'id' => $value['OfferDisabledLink']['id']
];
$md5Arr[] = $md5;
}
if (!empty($md5Arr)) {
$savedDisableLinkData = $this->em->getDisableLinksByMd5Arr($md5Arr);
foreach ($savedDisableLinkData as $key => $value) {
$disableLinksMyMd5[$value['md5']] = $value;
}
}
} else {
$disableLinkData = $this->em->getDisableLinkLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $sourceIdArray, $addedFromArr, $dateStart, $dateEnd);
foreach ($disableLinkData as $key => $value) {
$disableLinksMyMd5[$value['md5']] = $value;
$disableLinkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
}
}
$distinctOfferIdArr = [];
$distinctAffiliateIdArr = [];
foreach ($disableLinkData as $key => $value) {
if (!in_array($value['offerId'], $distinctOfferIdArr)) {
array_push($distinctOfferIdArr, $value['offerId']);
}
if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
array_push($distinctAffiliateIdArr, $value['affiliateId']);
}
$disableLinkData[$key]['date_inserted'] = $value['dateInserted'];
}
$offerInfo = [];
if (!empty($distinctOfferIdArr)) {
$offerInfo = $this->getOfferInfoByKey($distinctOfferIdArr, $tuneAccount);
}
$advertiserList = $this->getAdvertisersListByStatusWithKeys([
'tuneAccount' => $tuneAccount
]);
$affiliateList = $this->getAffiliateListByStatusWithKeys($tuneAccount);
foreach ($disableLinkData as $key => $value) {
if (!array_key_exists($value['offerId'], $offerInfo)) {
unset($disableLinkData[$key]);
continue;
}
$offerName = $offerInfo[$value['offerId']]['name'] ?? '';
$advertiserName = array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
$advertiserId = $offerInfo[$value['offerId']]['advertiserId'] ?? '';
$affiliateName = array_key_exists($value['affiliateId'], $affiliateList) ? $affiliateList[$value['affiliateId']]['name'] : '';
$meta = [];
$addedFrom = Config::DISABLE_LINKS_FROM_HO_PANEL;
if (array_key_exists($value['md5'], $disableLinksMyMd5)) {
$meta = json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) != null ? json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) : [];
$addedFrom = $disableLinksMyMd5[$value['md5']]['addedFrom'];
}
if (
(!empty($addedFromArr) && !in_array($addedFrom, $addedFromArr)) ||
(sizeof($advertiserArray) && !in_array($advertiserId, $advertiserArray))
) {
unset($disableLinkData[$key]);
continue;
}
$disableLinkData[$key]['affiliateName'] = $affiliateName;
$disableLinkData[$key]['advertiserName'] = $advertiserName;
$disableLinkData[$key]['advertiserId'] = $advertiserId;
$disableLinkData[$key]['offerName'] = $offerName;
$disableLinkData[$key]['addedFrom'] = $addedFrom;
$disableLinkData[$key]['meta'] = $meta;
}
return $disableLinkData;
}
public function createUpdateRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$retentionOptimisationExist = $this->em->getRetentionOptimisationByParams($offerId, $goalId, $tuneAccount);
if ($retentionOptimisationExist) {
if ($sendAlert === null) {
$sendAlert = $retentionOptimisationExist->getSendAlert();
}
if ($autoBlock === null) {
$autoBlock = $retentionOptimisationExist->getAutoBlock();
}
$this->em->updateRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount);
} else {
$this->em->insertRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount);
}
}
public function getRetentionOptimisationData($offerId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$retentionOptimisationData = $this->em->getRetentionOptimisation($offerId, $tuneAccount);
$distinctOfferIds = [];
foreach ($retentionOptimisationData as $key => $value) {
if (!in_array($value['offerId'], $distinctOfferIds)) {
array_push($distinctOfferIds, $value['offerId']);
}
}
foreach ($retentionOptimisationData as $key => $value) {
// $retentionOptimisationData[$key]['offerName'] = $offerInfo[$value['offerId']]['name'] ?? "";
// $retentionOptimisationData[$key]['advertiserId'] = $offerInfo[$value['offerId']]['advertiserId'] ?? "";
// $retentionOptimisationData[$key]['advertiserName'] = $offerInfo[$value['offerId']]['Advertiser']['company'] ?? "";
// $retentionOptimisationData[$key]['advertiserName'] = array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
// $retentionOptimisationData[$key]['goalName'] = $offerInfo[$value['offerId']]['Goal'][$value['goalId']]['name'] ?? "";
$retentionOptimisationData[$key]['dateInserted'] = $value['dateUpdated']->format("Y-m-d H:s:i");
}
return array_values($retentionOptimisationData);
}
public function changeCamelCaseToWords($camelCaseString)
{
return ucfirst(implode(" ", preg_split('/(?=[A-Z])/', $camelCaseString)));
}
public function setOfferAffiliateCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$capExist = $this->em->getCombinationFromAffiliateOfferCapping($affiliateId, $offerId, $affiliateOfferCapType, $tuneAccount);
if (!$capExist || ($capExist->getCapValue() != $capValue)) {
if ($capExist) {
$this->em->deleteAffiliateOfferCapById($capExist->getId());
}
$hoResponse = $this->brandApi->setAffiliateOfferCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount);
if ($hoResponse['response']['status'] == 1) {
$this->em->insertToAffiliateOfferCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount);
}
}
}
public function getImpressionOptimisationData()
{
$impressionOptimisations = $this->em->getActiveImpressionOptimisation();
foreach ($impressionOptimisations as $key => $value) {
$impressionOptimisations[$key]['dateUpdated'] = $value['dateUpdated']->format("Y-m-d H:s:i");
$impressionOptimisations[$key]['dateInserted'] = $value['dateInserted']->format("Y-m-d H:s:i");
}
return $impressionOptimisations;
}
public function createUpdateImpressionOptimisation($offerId, $affiliate_id, $ctr, $addedBy)
{
return $this->em->createUpdateImpression($offerId, $affiliate_id, $ctr, $addedBy);
}
public function getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd)
{
$fraudFlagData = [];
$fraudFlagData = $this->em->getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd);
// foreach ($fraudFlagData as $key => $value) {
// $fraudFlagData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
// }
$distinctOfferIdArr = [];
$distinctAffiliateIdArr = [];
foreach ($fraudFlagData as $key => $value) {
if (!in_array($value['offerId'], $distinctOfferIdArr)) {
array_push($distinctOfferIdArr, $value['offerId']);
}
if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
array_push($distinctAffiliateIdArr, $value['affiliateId']);
}
$fraudFlagData[$key]['date_inserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
}
if (!empty($distinctOfferIdArr)) {
$offerInfo = $this->brandApi->getOffersByOfferIdsArr($distinctOfferIdArr)['response']['data'];
}
if (!empty($distinctAffiliateIdArr)) {
$affiliateInfo = $this->brandApi->getAffiliatesByAffiliateIdArr($distinctAffiliateIdArr)['response']['data'];
}
foreach ($fraudFlagData as $key => $value) {
$offerName = $offerInfo[$value['offerId']]['Offer']['name'] ?? '';
$advertiserName = $offerInfo[$value['offerId']]['Advertiser']['company'] ?? '';
$advertiserId = $offerInfo[$value['offerId']]['Advertiser']['id'] ?? '';
$affiliateName = $affiliateInfo[$value['affiliateId']]['Affiliate']['company'] ?? '';
$fraudFlagData[$key]['affiliateName'] = $affiliateName;
$fraudFlagData[$key]['advertiserName'] = $advertiserName;
$fraudFlagData[$key]['advertiserId'] = $advertiserId;
$fraudFlagData[$key]['offerName'] = $offerName;
}
return $fraudFlagData;
}
public function deleteFraudFlagLogs($id)
{
$this->em->deleteFraudFlagLogs($id);
}
public function blockOfferForAffiliate($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$combinationExist = $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->findOneBy([
'offerId' => $offerId,
'affiliateId' => $affiliateId,
'trackingAccount' => $trackingAccount
]);
$affiliateOfferBlockedInHO = $this->brandApi->getAffiliateOfferBlock($offerId, $affiliateId, $trackingAccount)['response']['data']['data'];
if (array_key_exists($offerId, $affiliateOfferBlockedInHO) && $affiliateOfferBlockedInHO[$offerId]['OfferAffiliateBlock']['affiliate_id'] == $affiliateId && !$combinationExist) {
return false;
}
if (!$combinationExist) {
if ($blockType === Config::AFFILIATE_OFFER_BLOCK_MACRO) {
$hoResponse = $this->brandApi->blockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
} elseif ($blockType === Config::AFFILIATE_OFFER_UNBLOCK_MACRO) {
$hoResponse = $this->brandApi->unblockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
}
if (isset($hoResponse['response']['status']) && $hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->insertToOfferAffiliateBlock($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount);
// Removing dump from mysql and added dump of AffiliateOfferBlock to mongo
// $this->doctrine->getRepository('App\Entity\AffiliateOfferBlockLogs')->insertToOfferAffiliateBlockLogs($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount);
return true;
}
}
return false;
}
public function deleteOfferAffiliateBlock($offerId, $affiliateId, $trackingAccount)
{
$hoResponse = $this->brandApi->unblockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->deleteOfferAffiliateBlock($offerId, $affiliateId, $trackingAccount);
}
}
public function populateDbByOfferId($offerId, $metaData = [])
{
$calledFromCronJob = $metaData['calledFromCronJob'] ?? true;
$tuneAccount = $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$offerExistInDB = $this->doctrine->getRepository('App\Entity\OfferInfo')->findOneBy([
'offerId' => $offerId,
'tuneAccount' => $tuneAccount
]);
$offerInfo[$offerId] = $this->brandApi->getOfferByOfferId($offerId, $tuneAccount)['response']['data'];
$offerIpWhitelistHoData = $this->brandApi->getIpWhitelistByOfferId($offerId, $tuneAccount)['response']['data'];
$offerFileCreativesHoData = $this->brandApi->getOfferFilesByOfferId($offerId, $tuneAccount);
$offerIpWhitelistArray = [];
foreach ($offerIpWhitelistHoData as $key => $value) {
if ($value['OfferWhitelist']['type'] == Config::OFFER_IP_WHITELIST_TYPE_POSTBACK) {
array_push($offerIpWhitelistArray, $value['OfferWhitelist']['content']);
}
}
$offerCountryIdArray = isset($offerInfo[$offerId]['Country']) ? array_keys($offerInfo[$offerId]['Country']) : [];
$offerCategoryIdArray = isset($offerInfo[$offerId]['OfferCategory']) ? array_keys($offerInfo[$offerId]['OfferCategory']) : [];
$offerTagIdArray = isset($offerInfo[$offerId]['OfferTag']) ? array_keys($offerInfo[$offerId]['OfferTag']) : [];
$offerGoalArray = isset($offerInfo[$offerId]['Goal']) ? array_values($offerInfo[$offerId]['Goal']) : [];
foreach ($offerGoalArray as $key => $value) {
foreach ($value as $k => $v) {
$offerGoalArray[$key][lcfirst(implode('', array_map('ucfirst', explode('_', $k))))] = $v;
if ($this->checkForString($k, '_')) {
unset($offerGoalArray[$key][$k]);
}
}
}
if ($offerExistInDB) {
$offerDataToUpdate = [];
foreach ($offerInfo[$offerId]['Offer'] as $key => $value) {
$appId = $this->scraper->getAppId($offerInfo[$offerId]['Offer']['preview_url']);
if (!$appId) {
$appId = 'Not Found';
}
$offerDataToUpdate['appId'] = $appId;
$offerDataToUpdate[lcfirst(implode('', array_map('ucfirst', explode('_', $key))))] = $value;
}
$offerDataToUpdate['geoIdsJson'] = json_encode($offerCountryIdArray);
$offerDataToUpdate['categoryIdsJson'] = json_encode($offerCategoryIdArray);
$offerDataToUpdate['tagIdsJson'] = json_encode($offerTagIdArray);
// $offerDataToUpdate['whitelistIpsJson'] = json_encode($offerIpWhitelistArray);
if ($offerInfo[$offerId]['Thumbnail'] && isset($offerInfo[$offerId]['Thumbnail']['preview_uri'])) {
$offerDataToUpdate['thumbnail'] = $offerInfo[$offerId]['Thumbnail']['preview_uri'];
}
$this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId, $offerDataToUpdate, $tuneAccount);
} else {
$offerValue = $offerInfo[$offerId];
$domain = $offerInfo[$offerId]['Hostname']['domain'] ?? '';
$appId = $this->scraper->getAppId($offerValue['Offer']['preview_url']);
if (!$appId) {
$appId = 'Not Found';
}
$offerValue['Offer']['app_id'] = $appId;
if (!$offerValue['Offer']['advertiser_id']) {
$offerValue['Offer']['advertiser_id'] = 0;
}
$this->doctrine->getRepository(OfferInfo::class)->insertToOfferInfo($offerValue['Offer']['id'], $offerValue['Offer']['advertiser_id'], $offerValue['Offer']['name'], $offerValue['Offer']['description'], $offerValue['Offer']['require_approval'], $offerValue['Offer']['preview_url'], $offerValue['Thumbnail']['preview_uri'] ?? null, $offerValue['Offer']['offer_url'], $offerValue['Offer']['currency'], $offerValue['Offer']['default_payout'], $offerValue['Offer']['payout_type'], $offerValue['Offer']['max_payout'], $offerValue['Offer']['revenue_type'], $offerValue['Offer']['status'], $offerValue['Offer']['redirect_offer_id'], $offerValue['Offer']['ref_id'], $offerValue['Offer']['conversion_cap'], $offerValue['Offer']['monthly_conversion_cap'], $offerValue['Offer']['payout_cap'], $offerValue['Offer']['monthly_payout_cap'], $offerValue['Offer']['revenue_cap'], $offerValue['Offer']['monthly_revenue_cap'], json_encode($offerCountryIdArray), json_encode($offerCategoryIdArray), $offerValue['Offer']['is_private'], $offerValue['Offer']['default_goal_name'], $offerValue['Offer']['note'], $offerValue['Offer']['has_goals_enabled'], $offerValue['Offer']['enforce_secure_tracking_link'], $offerValue['Offer']['enable_offer_whitelist'], $offerValue['Offer']['lifetime_conversion_cap'], $offerValue['Offer']['lifetime_payout_cap'], $offerValue['Offer']['lifetime_revenue_cap'], json_encode($offerTagIdArray), json_encode([]), $offerValue['Offer']['protocol'], $offerValue['Offer']['app_id'], $offerValue['Offer']['approve_conversions'], $domain, $tuneAccount);
}
$this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
foreach ($offerGoalArray as $key => $value) {
$goalExistInDB = $this->doctrine->getRepository(OfferGoalsInfo::class)->findOneBy(['goalId' => $value['id'], 'tuneAccount' => $tuneAccount]);
if ($goalExistInDB) {
$this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($value['id'], $value, $tuneAccount);
} else {
$this->doctrine->getRepository(OfferGoalsInfo::class)->insertToOfferGoalsInfo($value['id'], $offerId, $value['name'], $value['description'], $value['status'], $value['isPrivate'], $value['payoutType'], $value['defaultPayout'], $value['revenueType'], $value['maxPayout'], $value['tieredPayout'], $value['tieredRevenue'], $value['usePayoutGroups'], $value['useRevenueGroups'], $value['advertiserId'], $value['protocol'], $value['allowMultipleConversions'], $value['approveConversions'], $value['enforceEncryptTrackingPixels'], $value['isEndPoint'], $value['refId'], $tuneAccount);
}
}
if ($calledFromCronJob) {
$this->scraper->getAppDetailsByPreviewUrl($offerInfo[$offerId]['Offer']['preview_url']);
if (is_array($offerTagIdArray)) {
$this->doctrine->getRepository(OfferTagRelationship::class)->deleteOfferTagRelationByOfferId($offerId, $tuneAccount);
foreach ($offerTagIdArray as $tagId) {
$this->doctrine->getRepository(OfferTagRelationship::class)->insertToOfferTagRelationship($offerId, $tagId, $tuneAccount);
}
}
if (is_array($offerCategoryIdArray)) {
$this->doctrine->getRepository(OfferCategoryRelationship::class)->deleteOfferCategoryRelationByOfferId($offerId, $tuneAccount);
foreach ($offerCategoryIdArray as $categoryId) {
$this->doctrine->getRepository(OfferCategoryRelationship::class)->insertToOfferCategoryRelationship($offerId, $categoryId, $tuneAccount);
}
}
if (is_array($offerCountryIdArray)) {
$this->doctrine->getRepository(OfferGeoRelationship::class)->deleteOfferGeoRelationByOfferId($offerId, $tuneAccount);
foreach ($offerCountryIdArray as $geo) {
$this->doctrine->getRepository(OfferGeoRelationship::class)->insertToOfferGeoRelationship($offerId, $geo, $tuneAccount);
}
}
}
if (!$calledFromCronJob) {
$offerWhitelistIdArrFromHO = [];
foreach ($offerIpWhitelistHoData as $key => $value) {
$value = $value['OfferWhitelist'];
$value['tuneAccount'] = $tuneAccount;
$offerWhitelistExist = $this->doctrine->getRepository(OfferWhitelist::class)->findOneBy(['whitelistId' => $value['id'], 'tuneAccount' => $tuneAccount]);
if (!$offerWhitelistExist) {
$this->doctrine->getRepository(OfferWhitelist::class)->insertToOfferWhitelist($value['id'], $value['offer_id'], $value['type'], $value['content_type'], $value['content'], $tuneAccount);
} else {
$this->doctrine->getRepository(OfferWhitelist::class)->updateOfferWhitelistByWhitelistId($value['id'], $value, $tuneAccount);
}
array_push($offerWhitelistIdArrFromHO, $value['id']);
}
if (sizeof($offerWhitelistIdArrFromHO)) {
$offerWhitelistToBeDeleted = $this->doctrine->getRepository(OfferWhitelist::class)->getDeletedOfferWhitelistIds($offerId, $offerWhitelistIdArrFromHO, $tuneAccount);
foreach ($offerWhitelistToBeDeleted as $key => $value) {
$this->doctrine->getRepository(OfferWhitelist::class)->deleteByWhitelistId($value['whitelistId'], $tuneAccount);
}
}
foreach ($offerFileCreativesHoData as $key => $value) {
$fileExist = $this->doctrine->getRepository(OfferCreativeFile::class)->findOneBy(['fileId' => $key, 'tuneAccount' => $tuneAccount]);
if (isset($value['OfferFile'])) {
if (!$fileExist) {
$response = $value['OfferFile'];
if ($response['status'] == Config::DELETED_STATUS || $response['status'] == Config::PENDING_STATUS) {
continue;
}
$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'], $tuneAccount);
} elseif ($fileExist->getStatus() != $value['OfferFile']['status']) {
$this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($value['OfferFile']['id'], $value['OfferFile']['status'], $tuneAccount);
}
}
}
}
}
public function updateOffer($offerId, $offerDetails, $offerCountries, $offerCategories, $offerTags, $offerWhitelistIps, $tuneAccount)
{
$offerCreateHoResponse = $this->brandApi->createOrUpdateOffer($offerId, $offerDetails, $tuneAccount);
if ($offerCreateHoResponse['response']['status'] === 1) {
$offerInfo = $offerCreateHoResponse['response']['data']['Offer'];
$offerId = $offerInfo['id'];
$this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId, $offerDetails, $tuneAccount);
$this->updateOfferCountries($offerId, $offerCountries, $tuneAccount);
$this->updateOfferCategories($offerId, $offerCategories, $tuneAccount);
$this->updateOfferTags($offerId, $offerTags, $tuneAccount);
$this->updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount);
$this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
}
return $offerCreateHoResponse;
}
public function createNewOffer($offerDetails, $offerCountries, $offerCategories, $offerTags, $offerWhitelistIps, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$offerCreateHoResponse = $this->brandApi->createOrUpdateOffer(null, $offerDetails, $tuneAccount);
if ($offerCreateHoResponse['response']['status'] === 1) {
$offerInfo = $offerCreateHoResponse['response']['data']['Offer'];
$offerId = $offerInfo['id'];
$appId = $this->scraper->getAppId($offerInfo['preview_url']);
if (!$appId) {
$appId = 'Not Found';
}
$offerInfo['app_id'] = $appId;
$this->doctrine->getRepository('App\Entity\OfferInfo')->insertToOfferInfo($offerId, $offerInfo['advertiser_id'], $offerInfo['name'], $offerInfo['description'], $offerInfo['require_approval'], $offerInfo['preview_url'], null, $offerInfo['offer_url'], $offerInfo['currency'], $offerInfo['default_payout'], $offerInfo['payout_type'], $offerInfo['max_payout'], $offerInfo['revenue_type'], $offerInfo['status'], $offerInfo['redirect_offer_id'], $offerInfo['ref_id'], $offerInfo['conversion_cap'], $offerInfo['monthly_conversion_cap'], $offerInfo['payout_cap'], $offerInfo['monthly_payout_cap'], $offerInfo['revenue_cap'], $offerInfo['monthly_revenue_cap'], '[]', '[]', $offerInfo['is_private'], $offerInfo['default_goal_name'], $offerInfo['note'], $offerInfo['has_goals_enabled'], $offerInfo['enforce_secure_tracking_link'], $offerInfo['enable_offer_whitelist'], $offerInfo['lifetime_conversion_cap'], $offerInfo['lifetime_payout_cap'], $offerInfo['lifetime_revenue_cap'], '[]', '[]', $offerInfo['protocol'], $offerInfo['app_id'], null, $offerDetails['trackingDomain'] ?? null, $tuneAccount);
$this->updateOfferCountries($offerId, $offerCountries, $tuneAccount);
$this->updateOfferCategories($offerId, $offerCategories, $tuneAccount);
$this->updateOfferTags($offerId, $offerTags, $tuneAccount);
$this->updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount);
$this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
$appDetails = $this->scraper->getAppDetailsByPreviewUrl($offerInfo['preview_url']);
if ($appDetails) {
$fileResponse = $this->uploadFile($offerId, $appDetails['icon'], Config::FILE_TYPE_THUMBNAIL, 0);
if ($fileResponse['response']['status'] == 1) {
$this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['thumbnail' => $fileResponse['response']['data']['OfferFile']['url']], $tuneAccount);
}
}
}
return $offerCreateHoResponse;
}
public function updateOfferCountries($offerId, $offerCountries, $tuneAccount)
{
$savedOfferInfo = $this->doctrine->getRepository('App\Entity\OfferInfo')->findOneBy(['offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
$savedGeos = json_decode($savedOfferInfo->getGeoIdsJson(), true);
foreach ($savedGeos as $geo) {
if (!in_array($geo, $offerCountries)) {
$this->brandApi->removeGeoFromOffer($offerId, $geo, $tuneAccount);
}
}
foreach ($offerCountries as $geo) {
$this->brandApi->addGeoToOffer($offerId, $geo, $tuneAccount);
}
$this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['geoIdsJson' => json_encode($offerCountries)], $tuneAccount);
}
public function updateOfferCategories($offerId, $offerCategories, $tuneAccount)
{
if (is_array($offerCategories) && count($offerCategories) > 0) {
$this->brandApi->setCategoryToOffer($offerId, $offerCategories, $tuneAccount);
$this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['categoryIdsJson' => json_encode($offerCategories)], $tuneAccount);
}
}
public function updateOfferTags($offerId, $offerTags, $tuneAccount)
{
if (is_array($offerTags) && count($offerTags) > 0) {
foreach ($offerTags as $tagId) {
$this->brandApi->addTagToOffer($offerId, $tagId, $tuneAccount);
}
$this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['tagIdsJson' => json_encode($offerTags)], $tuneAccount);
}
}
public function updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount)
{
if (is_array($offerWhitelistIps) && count($offerWhitelistIps) > 0) {
foreach ($offerWhitelistIps as $whitelistIp) {
$this->brandApi->addIpWhitelistToOffer($offerId, $whitelistIp, Config::OFFER_IP_WHITELIST_CONTENT_TYPE_IP_ADDRESS, Config::OFFER_IP_WHITELIST_TYPE_POSTBACK, $tuneAccount);
}
// echo json_encode($offerWhitelistIps);
// $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['whitelistIpsJson' => json_encode($offerWhitelistIps)], $tuneAccount);
}
}
public function updateOfferGoal($goalId, $offerGoalDetails, $tuneAccount)
{
if (isset($offerGoalDetails['goal_id'])) {
unset($offerGoalDetails['goal_id']);
}
$offerGoalCreateHoResponse = $this->brandApi->createOrUpdateOfferGoal($goalId, $offerGoalDetails, $tuneAccount);
if ($offerGoalCreateHoResponse['response']['status'] === 1) {
$dataToUpdate = [];
foreach ($offerGoalCreateHoResponse['response']['data']['Goal'] as $key => $value) {
if ($key === 'id') {
continue;
}
$dataToUpdate[$this->convertStringFromSnakeCaseToCamelCase($key)] = $value;
}
$this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($goalId, $dataToUpdate, $tuneAccount);
}
return $offerGoalCreateHoResponse;
}
public function createNewOfferGoal($offerGoalDetails, $tuneAccount)
{
$offerGoalCreateHoResponse = $this->brandApi->createOrUpdateOfferGoal(null, $offerGoalDetails, $tuneAccount);
if ($offerGoalCreateHoResponse['response']['status'] === 1) {
$offerGoalCreateHoResponseData = $offerGoalCreateHoResponse['response']['data']['Goal'];
$this->doctrine->getRepository(OfferGoalsInfo::class)->insertToOfferGoalsInfo(
$offerGoalCreateHoResponseData['id'],
$offerGoalCreateHoResponseData['offer_id'],
$offerGoalCreateHoResponseData['name'],
$offerGoalCreateHoResponseData['description'],
$offerGoalCreateHoResponseData['status'],
$offerGoalCreateHoResponseData['is_private'],
$offerGoalCreateHoResponseData['payout_type'],
$offerGoalCreateHoResponseData['default_payout'],
$offerGoalCreateHoResponseData['revenue_type'],
$offerGoalCreateHoResponseData['max_payout'],
$offerGoalCreateHoResponseData['tiered_payout'],
$offerGoalCreateHoResponseData['tiered_revenue'],
$offerGoalCreateHoResponseData['use_payout_groups'],
$offerGoalCreateHoResponseData['use_revenue_groups'],
$offerGoalCreateHoResponseData['advertiser_id'],
$offerGoalCreateHoResponseData['protocol'],
$offerGoalCreateHoResponseData['allow_multiple_conversions'],
$offerGoalCreateHoResponseData['approve_conversions'],
$offerGoalCreateHoResponseData['enforce_encrypt_tracking_pixels'],
$offerGoalCreateHoResponseData['is_end_point'],
$offerGoalCreateHoResponseData['ref_id'],
$tuneAccount
);
}
return $offerGoalCreateHoResponse;
}
public function uploadFile($offerId, $fileUrlToUpload, $creativeType, $isPrivate)
{
$fileData = @file_get_contents($fileUrlToUpload);
$fileExtension = pathinfo($fileUrlToUpload, PATHINFO_EXTENSION);
$fileName = $fileExtension === '' ? $offerId . "_" . basename($fileUrlToUpload) . '.png' : $offerId . "_" . basename($fileUrlToUpload);
file_put_contents($fileName, $fileData);
$fileResponse = $this->brandApi->offerFileAPI($offerId, $creativeType, $fileName, $fileName, $isPrivate);
unlink($fileName);
return $fileResponse;
}
public function convertStringFromCamelCaseToSnakeCase($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
public function convertStringFromSnakeCaseToCamelCase($input)
{
return lcfirst(implode('', array_map('ucfirst', explode('_', $input))));
}
public function getScraper()
{
return $this->scraper;
}
public function getOfferListByOfferIdArr($offerIdArr)
{
$response = [];
if ($offerIdArr) {
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
foreach ($offerInfo as $key => $value) {
$response[$value['offerId']] = [
'id' => (int)$value['offerId'],
'name' => $value['name']
];
}
}
return $response;
}
public function checkOfferAffiliateCapping($offerId, $affiliateId, $goalId)
{
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOfferDataByOfferId($offerId);
if (!$offerInfo) {
return false;
}
$conversionCapByOfferIdHOData = $this->brandApi->getCappingByOfferId($offerId)['response']['data'];
$conversionCap = $offerInfo->getConversionCap();
$payoutCap = $offerInfo->getPayoutCap();
$revenueCap = $offerInfo->getRevenueCap();
$monthlyConversionCap = $offerInfo->getMonthlyConversionCap();
$monthlyPayoutCap = $offerInfo->getMonthlyPayoutCap();
$monthlyRevenueCap = $offerInfo->getMonthlyRevenueCap();
foreach ($conversionCapByOfferIdHOData as $key => $value) {
if ($value['OfferConversionCap']['offer_id'] == $offerId && $value['OfferConversionCap']['affiliate_id'] == $affiliateId) {
$conversionCap = $value['OfferConversionCap']['conversion_cap'];
$payoutCap = $value['OfferConversionCap']['payout_cap'];
$revenueCap = $value['OfferConversionCap']['revenue_cap'];
$monthlyConversionCap = $value['OfferConversionCap']['monthly_conversion_cap'];
$monthlyPayoutCap = $value['OfferConversionCap']['monthly_payout_cap'];
$monthlyRevenueCap = $value['OfferConversionCap']['monthly_revenue_cap'];
break;
}
}
$dailyConversionGenerated = 0;
$dailyPayoutGenerated = 0;
$dailyRevenueGenerated = 0;
$monthlyConversionGenerated = 0;
$monthlyPayoutGenerated = 0;
$monthlyRevenueGenerated = 0;
$statByDay = $this->brandApi->getStatsForCappingCheck($offerId, $affiliateId, $goalId, true, false)['response']['data']['data'];
if (!empty($statByDay)) {
$dailyConversionGenerated = $statByDay[0]['Stat']['conversions'];
$dailyPayoutGenerated = $statByDay[0]['Stat']['payout'];
$dailyRevenueGenerated = $statByDay[0]['Stat']['revenue'];
}
$statByMonth = $this->brandApi->getStatsForCappingCheck($offerId, $affiliateId, $goalId, false, true)['response']['data']['data'];
if (!empty($statByMonth) && isset($statByDay[0])) {
$monthlyConversionGenerated = $statByDay[0]['Stat']['conversions'];
$monthlyPayoutGenerated = $statByDay[0]['Stat']['payout'];
$monthlyRevenueGenerated = $statByDay[0]['Stat']['revenue'];
}
$conversionCapReached = $dailyConversionGenerated >= $conversionCap && $conversionCap != 0;
$payoutCapReached = $dailyPayoutGenerated >= $payoutCap && $payoutCap != 0;
$revenueCapReached = $dailyRevenueGenerated >= $revenueCap && $revenueCap != 0;
$monthlyConversionCapReached = $monthlyConversionGenerated >= $monthlyConversionCap && $monthlyConversionCap != 0;
$monthlyPayoutCapReached = $monthlyPayoutGenerated >= $monthlyPayoutCap && $monthlyPayoutCap != 0;
$monthlyRevenueCapReached = $monthlyRevenueGenerated >= $monthlyRevenueCap && $monthlyRevenueCap != 0;
$cappingReached = false;
if ($conversionCapReached || $payoutCapReached || $revenueCapReached || $monthlyConversionCapReached || $monthlyPayoutCapReached || $monthlyRevenueCapReached) {
$cappingReached = true;
}
return [
'conversionCap' => $conversionCap,
'payoutCap' => $payoutCap,
'revenueCap' => $revenueCap,
'monthlyConversionCap' => $monthlyConversionCap,
'monthlyPayoutCap' => $monthlyPayoutCap,
'monthlyRevenueCap' => $monthlyRevenueCap,
'dailyConversionGenerated' => $dailyConversionGenerated,
'dailyPayoutGenerated' => $dailyPayoutGenerated,
'dailyRevenueGenerated' => $dailyRevenueGenerated,
'monthlyConversionGenerated' => $monthlyConversionGenerated,
'monthlyPayoutGenerated' => $monthlyPayoutGenerated,
'monthlyRevenueGenerated' => $monthlyRevenueGenerated,
'conversionCapReached' => $conversionCapReached,
'payoutCapReached' => $payoutCapReached,
'revenueCapReached' => $revenueCapReached,
'monthlyConversionCapReached' => $monthlyConversionCapReached,
'monthlyPayoutCapReached' => $monthlyPayoutCapReached,
'monthlyRevenueCapReached' => $monthlyRevenueCapReached,
'cappingReached' => $cappingReached
];
}
public function appsBlackAndWhiteList($data)
{
$dateRange = 30;
$minClicks = 100;
$dataToProcess = [];
foreach ($data as $key => $value) {
$value['offerId'] ? $dataToProcess['offer'][$value['offerId']][$value['param']][$value['listType']][] = $value['appId'] : false;
$value['advertiserId'] ? $dataToProcess['advertiser'][$value['advertiserId']][$value['param']][$value['listType']][] = $value['appId'] : false;
$value['affiliateId'] ? $dataToProcess['affiliate'][$value['affiliateId']][$value['param']][$value['listType']][] = $value['appId'] : false;
}
$dataToBlock = [];
foreach ($dataToProcess as $entityType => $entity) {
foreach ($entity as $entityId => $entityData) {
foreach ($entityData as $param => $paramData) {
$advertiserId = $entityType == 'advertiser' ? $entityId : null;
$affiliateId = $entityType == 'affiliate' ? $entityId : null;
$offerId = $entityType == 'offer' ? $entityId : null;
if ($advertiserId) {
$addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_ADVERTISER;
} elseif ($affiliateId) {
$addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_AFFILIATE;
} else {
$addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_OFFER;
}
if ($advertiserId == null && $affiliateId == null && $offerId == null) {
continue;
}
$statData = $this->brandApi->getStatsForAppBlackAndWhiteList($offerId, $affiliateId, $advertiserId, $dateRange, $minClicks, $param)['response']['data']['data'];
foreach ($paramData as $listType => $appIds) {
foreach ($statData as $key => $value) {
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['Stat']['offer_id']]);
if (
!$offerInfo ||
!in_array($offerInfo->getAppId(), $appIds)
) {
continue;
}
$temp = [
'offerId' => $value['Stat']['offer_id'],
'affiliateId' => $value['Stat']['affiliate_id'],
'advertiserId' => $value['Stat']['advertiser_id'],
'param' => $param,
'paramValue' => $value['Stat'][$param],
'clicks' => $value['Stat']['clicks'],
'conversions' => $value['Stat']['conversions'],
'addedFrom' => $addedFrom,
'listType' => $listType
];
if (array_key_exists('blacklist', $paramData) && in_array($value['Stat'][$param], $paramData['blacklist'])) {
$dataToBlock[] = $temp;
}
if (array_key_exists('whitelist', $paramData) && !in_array($value['Stat'][$param], $paramData['whitelist'])) {
$dataToBlock[] = $temp;
}
}
}
}
}
}
return $dataToBlock;
}
public function setAffiliateOfferApproval($offerId, $affiliateId, $status, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$combinationExist = $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($offerId, $affiliateId, $tuneAccount);
if ($combinationExist && $combinationExist->getApprovalStatus() != $status) {
$hoResponse = $this->brandApi->setOfferApprovalForAffiliate($offerId, $affiliateId, $status, $tuneAccount);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(AffiliateOfferApproval::class)->updateAffiliateOfferApprovalById($combinationExist->getId(), [
'approvalStatus' => $status
]);
}
} elseif (!$combinationExist) {
$hoResponse = $this->brandApi->setOfferApprovalForAffiliate($offerId, $affiliateId, $status, $tuneAccount);
if ($hoResponse['response']['status'] == 1) {
$this->doctrine->getRepository(AffiliateOfferApproval::class)->insertToAffiliateOfferApproval(null, $affiliateId, null, $offerId, null, null, null, $status, null, null, $tuneAccount);
}
}
}
public function disableLinkByExternalUrl($offerId, $advertiserId, $affiliateId, $source, $affSub2, $affSub3, $affSub5)
{
$stat = [
'offerId' => $offerId,
'advertiserId' => $advertiserId,
'affiliateId' => $affiliateId,
'source' => $source,
'affSub2' => $affSub2,
'affSub3' => $affSub3,
'affSub5' => $affSub5
];
$link = Config::DISABLE_LINK_EXTERNAL_ENDPOINT . '?token=' . base64_encode(json_encode($stat));
return $link;
}
public function getOfferInfoByKey($offerIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
return [];
}
$offerData = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr, $tuneAccount);
$offerInfo = [];
foreach ($offerData as $key => $value) {
$offerInfo[$value['offerId']] = $value;
}
return $offerInfo;
}
public function getMafoOfferInfoByKey($offerIdArr)
{
if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
return [];
}
$offerData = $this->doctrine->getRepository(MafoOffers::class)->getMafoOffersByOfferIdsArr($offerIdArr);
$offerInfo = [];
foreach ($offerData as $key => $value) {
$offerInfo[$value['id']] = $value;
}
return $offerInfo;
}
public function getEmployeesByEmployeeId()
{
$cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
if (!$cachedList) {
$employeeList = $this->getWarmedUpEmployeesByEmployeeId();
} else {
$employeeList = json_decode($cachedList, true);
}
ksort($employeeList);
return $employeeList;
}
public function getWarmedUpEmployeesByEmployeeId()
{
$employeesData = $this->doctrine->getRepository(Employees::class)->getEmployees();
$data = [];
foreach ($employeesData as $key => $value) {
$data[$value['employeeId']] = [
'firstName' => $value['firstName'],
'lastName' => $value['lastName'],
'email' => $value['email'],
'fullName' => $value['fullName']
];
}
return $data;
}
public function getMd5ForMmpReport($advertiser, $offerCountry, $offerRegion, $offerCity, $appId, $event, $revenueModel, $payoutModel)
{
return md5(strtolower($advertiser) . '#' . strtolower($offerCountry) . '#' . strtolower($offerRegion) . '#' . strtolower($offerCity) . '#' . strtolower($appId) . '#' . strtolower($event) . '#' . strtolower($revenueModel) . '#' . strtolower($payoutModel));
}
public function updateAffiliateDBByIds($affiliateIds, $metaData)
{
$createApiKeyIfNotExist = $metaData['createApiKeyIfNotExist'] ?? false;
$tuneAccount = $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
$affiliateInfoArr = $this->brandApi->getAffiliateInfoByAffiliateIdsArr($affiliateIds, $tuneAccount)['response']['data'];
foreach ($affiliateInfoArr as $key => $value) {
$affiliateDBInfo = $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
if ($affiliateDBInfo) {
$this->doctrine->getRepository(AffiliateInfo::class)->updateAffiliateInfoByAffiliateId($value['Affiliate']['id'], [
'status' => $value['Affiliate']['status'],
'accountManagerId' => $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null,
'company' => $value['Affiliate']['company']
], $tuneAccount);
} else {
$this->doctrine->getRepository(AffiliateInfo::class)->insertToAffiliateInfo($value['Affiliate']['id'], $value['Affiliate']['company'], $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null, $value['Affiliate']['status'], $tuneAccount);
}
// $this->mafoObjectsComponents->createOrUpdateAffiliate(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Affiliate']['id']);
// $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
// exec($execCommand);
if ($value['AffiliateUser'] !== null) {
foreach ($value['AffiliateUser'] as $k => $v) {
if ($v['status'] == Config::ACTIVE_STATUS) {
if ($createApiKeyIfNotExist) {
$apiKeyData = $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
if (!$apiKeyData) {
$this->brandApi->generateApiKeyByUserId($k, $tuneAccount);
}
}
$userApiData = $this->brandApi->getUserApiKey($k)['response']['data'];
if ($userApiData) {
$userApiKey = $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['userId' => $k, 'tuneAccount' => $tuneAccount]);
if ($userApiKey) {
$this->doctrine->getRepository(UserApiKey::class)->updateUserApiKeyByUserId($k, [
'affiliateId' => $value['Affiliate']['id'],
'userType' => $userApiData['user_type'],
'apiKey' => $userApiData['api_key'],
'apiKeyStatus' => $userApiData['status'],
'userStatus' => $v['status']
], $tuneAccount);
} else {
$this->doctrine->getRepository(UserApiKey::class)->insertToUserApiKey($value['Affiliate']['id'], $k, $userApiData['user_type'], $userApiData['api_key'], $userApiData['status'], $v['status'], $tuneAccount);
}
}
}
}
}
if ($value['AccountManager'] !== null) {
$affiliateAccountManagerDBInfo = $this->doctrine->getRepository(AffiliateAccountManager::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
if ($affiliateAccountManagerDBInfo) {
$this->doctrine->getRepository(AffiliateAccountManager::class)->updateDataByAffiliateId($value['Affiliate']['id'], [
'employeeId' => $value['AccountManager']['id'],
'email' => $value['AccountManager']['email'],
'firstName' => $value['AccountManager']['first_name'],
'lastName' => $value['AccountManager']['last_name'],
'status' => $value['AccountManager']['status'],
], $tuneAccount);
} else {
$this->doctrine->getRepository(AffiliateAccountManager::class)->insertToAffiliateAccountManager($value['Affiliate']['id'], $value['AccountManager']['id'], $value['AccountManager']['email'], $value['AccountManager']['first_name'], $value['AccountManager']['last_name'], $value['AccountManager']['status'], $tuneAccount);
}
}
$affiliateTagRelationship = $this->brandApi->getAffiliateTagRelationByAffiliateId($value['Affiliate']['id'], $tuneAccount);
if ($affiliateTagRelationship['response']['status'] == 1) {
$affiliateTags = [];
foreach ($affiliateTagRelationship['response']['data']['data'] as $k => $v) {
!in_array($v['AffiliatesTags']['tag_id'], $affiliateTags) ? array_push($affiliateTags, $v['AffiliatesTags']['tag_id']) : false;
}
$affiliateDBTagsData = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
$affiliateDBTags = [];
foreach ($affiliateDBTagsData as $k => $v) {
!in_array($v['tagId'], $affiliateDBTags) ? array_push($affiliateDBTags, $v['tagId']) : false;
}
if ($affiliateDBTags != $affiliateTags) {
$this->doctrine->getRepository(AffiliateTagRelationship::class)->deleteAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
foreach ($affiliateTags as $affiliateTag) {
$this->doctrine->getRepository(AffiliateTagRelationship::class)->insertToAffiliateTagRelationship($affiliateTag, $value['Affiliate']['id'], $tuneAccount);
}
}
}
}
}
public function updateAdvertiserDBById($advertiserId, $metaData, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$this->updateAdvertiserDBByIds([$advertiserId], $tuneAccount);
if ($this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId, 'tuneAccount' => $tuneAccount])) {
$advertiserDiscountType = $metaData['advertiserDiscountType'] ?? Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
$advertiserDiscountValue = $metaData['advertiserDiscountValue'] ?? null;
if ($advertiserDiscountValue < 1 || $advertiserDiscountValue > 100) {
$advertiserDiscountType = Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
$advertiserDiscountValue = null;
}
$this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($advertiserId, [
'discountValue' => $advertiserDiscountType !== Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT ? $advertiserDiscountValue : 0,
'discountType' => $advertiserDiscountType,
], $tuneAccount);
}
}
public function updateAdvertiserDBByIds($advertiserIds, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$advertiserInfoArr = $this->brandApi->getAdvertiserInfoByAdvertiserIdsArr($advertiserIds, $tuneAccount)['response']['data'];
foreach ($advertiserInfoArr as $key => $value) {
$advertiserDBInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy([
'advertiserId' => $value['Advertiser']['id'],
'tuneAccount' => $tuneAccount
]);
if ($advertiserDBInfo) {
$this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($value['Advertiser']['id'], [
'status' => $value['Advertiser']['status'],
'accountManagerId' => $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null,
'company' => $value['Advertiser']['company']
], $tuneAccount);
} else {
$this->doctrine->getRepository(AdvertiserInfo::class)->insertToAdvertiserInfo($value['Advertiser']['id'], $value['Advertiser']['company'], $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null, $value['Advertiser']['status'], $tuneAccount);
}
// $this->mafoObjectsComponents->createOrUpdateAdvertiser(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Advertiser']['id']);
// $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
// exec($execCommand);
if ($value['AccountManager'] !== null) {
$affiliateAccountManagerDBInfo = $this->doctrine->getRepository(AdvertiserAccountManager::class)->findOneBy(['advertiserId' => $value['Advertiser']['id']]);
if ($affiliateAccountManagerDBInfo) {
$this->doctrine->getRepository(AdvertiserAccountManager::class)->updateDataByAdvertiserId($value['Advertiser']['id'], [
'employeeId' => $value['AccountManager']['id'],
'email' => $value['AccountManager']['email'],
'firstName' => $value['AccountManager']['first_name'],
'lastName' => $value['AccountManager']['last_name'],
'status' => $value['AccountManager']['status'],
], $tuneAccount);
} else {
$this->doctrine->getRepository(AdvertiserAccountManager::class)->insertToAdvertiserAccountManager($value['Advertiser']['id'], $value['AccountManager']['id'], $value['AccountManager']['email'], $value['AccountManager']['first_name'], $value['AccountManager']['last_name'], $value['AccountManager']['status'], $tuneAccount);
}
}
$advertiserTagRelationship = $this->brandApi->getAdvertiserTagRelationByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
if ($advertiserTagRelationship['response']['status'] == 1) {
$advertiserTags = [];
foreach ($advertiserTagRelationship['response']['data']['data'] as $k => $v) {
!in_array($v['AdvertisersTags']['tag_id'], $advertiserTags) ? array_push($advertiserTags, $v['AdvertisersTags']['tag_id']) : false;
}
$advertiserDBTagsData = $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
$advertiserDBTags = [];
foreach ($advertiserDBTagsData as $k => $v) {
!in_array($v['tagId'], $advertiserDBTags) ? array_push($advertiserDBTags, $v['tagId']) : false;
}
if ($advertiserDBTags != $advertiserTags) {
$this->doctrine->getRepository(AdvertiserTagRelationship::class)->deleteAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
foreach ($advertiserTags as $advertiserTag) {
$this->doctrine->getRepository(AdvertiserTagRelationship::class)->insertToAdvertiserTagRelationship($advertiserTag, $value['Advertiser']['id'], $tuneAccount);
}
}
}
}
}
public function getEmployeesWithEmailAsKey()
{
$employeesData = $this->doctrine->getRepository(Employees::class)->getEmployees();
$employees = [];
foreach ($employeesData as $key => $value) {
$employees[strtolower($value['email'])] = $value;
}
return $employees;
}
public function getNewsletterBuilderTemplate($offerIds, $introduction, $unsubscribeEmailId = '')
{
$offerInfoFromApi = [];
if ($offerIds) {
$offerInfoFromApi = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
}
$offerInfoByOfferId = [];
foreach ($offerIds as $offerId) {
foreach ($offerInfoFromApi as $key => $value) {
if ($offerId == $value['offerId']) {
$value['geos'] = json_decode($value['geoIdsJson'], true);
$offerInfoByOfferId[] = $value;
}
}
}
return $this->template->render('components/newsletterBuilder.html.twig', [
'offerDetails' => $offerInfoByOfferId,
'introduction' => $introduction,
'unsubscribeLink' => "http://firehose.mobupps.com/api/unsubscribe/" . $unsubscribeEmailId
]);
}
public function getOfferGoalInfoByOfferGoalIdArrWithKeys($offerGoalIdArr)
{
$offerGoalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalInfoByGoalIdArr($offerGoalIdArr);
$data = [];
foreach ($offerGoalData as $key => $value) {
$data[$value['goalId']] = $value;
}
return $data;
}
public function getSkadNetworkMessageSeparator()
{
return mb_chr(Config::SKADNETWORK_MESSAGE_SEPARATOR_CODE);
}
public function setCommandLoggerData($identifier, $commandName, $meta)
{
$identifierExists = $this->doctrine->getRepository(CommandLogger::class)->findOneBy([
'identifier' => $identifier
]);
if (is_array($meta)) {
$meta = json_encode($meta);
}
$currentTimestamp = strtotime('now');
if (!$identifierExists) {
$this->doctrine->getRepository(CommandLogger::class)->insertToCommandLogger($identifier, $commandName, $currentTimestamp, null, null, null);
} else {
$this->doctrine->getRepository(CommandLogger::class)->updateCommandLoggerById($identifierExists->getId(), [
'endTimestamp' => $currentTimestamp,
'timestampDiff' => $currentTimestamp - $identifierExists->getStartTimestamp(),
'meta' => $meta
]);
}
}
public function getMafoUsersWithEmailIdAsKey()
{
$users = $this->doctrine->getRepository('App\Entity\Users')->getUsers();
$arr = [];
foreach ($users as $key => $value) {
$name = explode(' ', $value['name']);
$value['firstName'] = $name[0];
$arr[$value['email']] = $value;
}
return $arr;
}
public function checkAlertMetaExists($identifier, $type)
{
$identifierExists = $this->doctrine->getRepository(AlertMeta::class)->findOneBy(['identifier' => $identifier]);
if (!$identifierExists) {
$this->doctrine->getRepository(AlertMeta::class)->insertToAlertMeta($identifier, $type);
return false;
} else {
return true;
}
}
public function getHourOffsetFromTimezoneString($timezone)
{
$hourOffset = '+0:00';
if (array_key_exists($timezone, Config::TIMEZONES)) {
$timezone = Config::TIMEZONES[$timezone];
$timezone = explode(" ", $timezone)[0];
$timezone = str_replace("(GMT", "", $timezone);
$hourOffset = str_replace(")", "", $timezone);
}
return $hourOffset;
}
public function processPendingPostback($postbackLogId)
{
$postbackLogData = $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->findOneBy(['id' => $postbackLogId]);
$endpoint = $postbackLogData->getEndpoint();
$appId = $postbackLogData->getAppId();
$campaignId = $postbackLogData->getCampaignId();
$payload = json_decode($postbackLogData->getRequest(), true);
$isAttributionSignatureValid = $postbackLogData->getIsAttributionSignatureValid();
$postbackTimestamp = $postbackLogData->getDateInserted()->getTimestamp();
$offerId = null;
$affiliateId = null;
$skadNetworkPostbackMappingExists = null;
if ($endpoint == Config::SKADNETWORK_POSTBACK_ENDPOINT_WMADV) {
$skadNetworkPostbackMappingExists = $this->doctrine->getRepository(SkadNetworkManualPostbackMapping::class)->findOneBy([
'appId' => $appId,
'campaignId' => $campaignId,
'isDeleted' => 0
]);
if ($skadNetworkPostbackMappingExists) {
$offerId = $skadNetworkPostbackMappingExists->getOfferId();
$affiliateId = $skadNetworkPostbackMappingExists->getAffiliateId();
}
} else {
$apiLogsData = $this->doctrine->getRepository(SkadNetworkApiLogs::class)->findOneBy(['appId' => $appId, 'campaignId' => $campaignId]);
if ($apiLogsData) {
$offerId = $apiLogsData->getOfferId();
$affiliateId = $apiLogsData->getAffiliateId();
}
}
$postbacksToMake = [];
if ($isAttributionSignatureValid && $postbackLogData->getDidWin()) {
if ($offerId) {
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId]);
if ($offerInfo && $offerInfo->getSkadNetworkMmp() && in_array($offerInfo->getSkadNetworkMmp(), Config::SKADNETOWRK_MMP)) {
if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_ADJUST && $offerInfo->getSkadNetworkAdjustTracker()) {
$offerGeoRelationship = $this->doctrine->getRepository(OfferGeoRelationship::class)->findOneBy(['offerId' => $offerInfo->getOfferId()]);
$postbackParams = [
'tracker' => $offerInfo->getSkadNetworkAdjustTracker(),
'sk_payload' => urlencode($payload),
'sk_ts' => strtotime('now')
];
if ($offerGeoRelationship && $offerGeoRelationship->getGeo()) {
$postbackParams['country'] = strtolower($offerGeoRelationship->getGeo());
}
$postbacksToMake[] = [
'requestType' => Config::HTTP_METHOD_POST,
'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()] . '?' . http_build_query($postbackParams),
'postbackForMmp' => true,
'skadNetworkMmp' => Config::SKADNETWORK_MMP_ADJUST
];
} else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_BRANCH) {
$postbacksToMake[] = [
'requestType' => Config::HTTP_METHOD_POST,
'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[Config::SKADNETWORK_MMP_BRANCH],
'postbackForMmp' => true,
'skadNetworkMmp' => Config::SKADNETWORK_MMP_BRANCH
];
if ($skadNetworkPostbackMappingExists) {
if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignId()) {
$payload['partner-campaign-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignId();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignName()) {
$payload['partner-campaign-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignName();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetId()) {
$payload['partner-ad-set-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetId();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetName()) {
$payload['partner-ad-set-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetName();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerAdId()) {
$payload['partner-ad-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdId();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerAdName()) {
$payload['partner-ad-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdName();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeId()) {
$payload['partner-creative-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeId();
}
if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeName()) {
$payload['partner-creative-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeName();
}
}
} else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_APPSFLYER) {
// $payload['ad-network-campaign-id'] = $campaignId . "";
// $payload['ad-network-campaign-name'] = $offerId . "";
// $payload['ad-network-country-code'] = implode(",", json_decode($offerInfo->getGeoIdsJson(), true));
// $payload['timestamp'] = $postbackTimestamp;
// if($affiliateId) {
// $payload['source-app-id'] = $affiliateId."";
// $payload['ad-network-source-app-id'] = $affiliateId."";
// }
$postbacksToMake[] = [
'requestType' => Config::HTTP_METHOD_POST,
'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
'postbackForMmp' => true,
'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
];
} else {
$postbacksToMake[] = [
'requestType' => Config::HTTP_METHOD_POST,
'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
'postbackForMmp' => true,
'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
];
}
}
}
if ($affiliateId) {
$affiliateInfo = $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId]);
if ($affiliateInfo && $affiliateInfo->getSkadNetworkPostbackUrl()) {
$postbacksToMake[] = [
'requestType' => Config::HTTP_METHOD_POST,
'requestUrl' => $affiliateInfo->getSkadNetworkPostbackUrl(),
'postbackForMmp' => false
];
}
}
foreach ($postbacksToMake as $key => $value) {
$result = false;
if ($value['requestType'] == Config::HTTP_METHOD_POST) {
$postdata = json_encode($payload);
$ch = curl_init($value['requestUrl']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
} elseif ($value['requestType'] == Config::HTTP_METHOD_GET) {
$ch = curl_init($value['requestUrl']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
}
if ($result) {
if (array_key_exists('postbackForMmp', $value) && $value['postbackForMmp']) {
if (
array_key_exists('skadNetworkMmp', $value) &&
$value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_BRANCH
) {
$result = json_decode($result, true);
if (array_key_exists('id', $result)) {
$this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
'isPostbackScheduledForMmp' => false,
'branchPostbackId' => $result['id']
]);
}
} else if ($value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_APPSFLYER) {
$this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
'isPostbackScheduledForMmp' => false
]);
}
} else {
$this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
'isPostbackScheduledForAffiliate' => false
]);
}
}
}
}
}
public function getAppInfoByAppIdArrWithKeys($appIdArr)
{
$appData = [];
if ($appIdArr) {
$appData = $this->doctrine->getRepository(AppInfo::class)->getDataByAppIds($appIdArr);
}
$arr = [];
foreach ($appData as $key => $value) {
$arr[$value['appId']] = $value;
}
return $arr;
}
public function getAppInfoWithKeys($fromCache = true)
{
$arr = [];
if ($fromCache) {
$arr = $this->elasticCache->redisGet(Config::CACHE_REDIS_APP_INFO_KEY);
}
if (!$arr) {
$appData = $this->doctrine->getRepository(AppInfo::class)->getAppIds();
$arr = [];
foreach ($appData as $key => $value) {
$arr[$value['appId']] = $value;
}
} else {
$arr = json_decode($arr, true);
}
return $arr;
}
public function getDataFromJsonFile($jsonFileName)
{
$json = file_get_contents($this->rootPath . "/src/Resources/json/" . $jsonFileName . ".json");
if (in_array($jsonFileName, [Config::JSON_FILE_FINANCIAL_TOOLS_GAP_CONTROL, Config::JSON_FILE_FINANCIAL_TOOLS_MAFO_GAP_CONTROL])) {
$teamsByTeamId = $this->usersComponents->getTeamsByTeamId();
$usersByTeamId = $this->usersComponents->getMafoUsersByTeamIds();
$columnsData = json_decode($json, true);
foreach ($usersByTeamId as $teamId => $users) {
if (sizeof($users)) {
$columnsData[$teamsByTeamId[$teamId]['label'] . 'Cost'] = [
'header' => $teamsByTeamId[$teamId]['label'] . ' Media Cost',
'accessor' => $teamsByTeamId[$teamId]['label'] . 'Cost',
'percentageWidth' => 5,
'show' => true,
'disabled' => false,
'customClass' => 'text-right',
'category' => 'statistics',
'footerEnabled' => true,
'aggregate' => 'sum',
// 'alwaysEnabled' => true
];
}
}
$itemsToBePushedToEnd = ['totalAffiliateCost', 'gap'];
$arrToBePushedToEnd = [];
foreach ($itemsToBePushedToEnd as $key => $value) {
$arrToBePushedToEnd[$value] = $columnsData[$value];
unset($columnsData[$value]);
}
$columnsData = array_merge($columnsData, $arrToBePushedToEnd);
$json = json_encode($columnsData);
}
return json_decode($json, true);
}
public function changeColumnVisibilityForTable($tableColumns, $selectedColumns, $groupedColumns)
{
foreach ($tableColumns as $key => $value) {
$tableColumns[$key]['show'] = false;
foreach ($selectedColumns as $k => $v) {
if ($value['accessor'] === $k && $v !== 'undefined') {
$tableColumns[$key]['show'] = $v == '0' ? false : true;
break;
}
}
foreach ($groupedColumns as $k => $v) {
if ($value['accessor'] === $k && $v !== 'undefined') {
$tableColumns[$key]['groupBy'] = !($v == '0');
!($v == '0') ? $tableColumns[$key]['show'] = true : null;
break;
}
}
}
return $tableColumns;
}
public function downloadCSV($tableColumns, $data, $reportNamePretty)
{
$reportName = str_replace(" ", "-", strtolower($reportNamePretty));
$header = [];
foreach ($tableColumns as $key => $value) {
if ($value['show'] == 1) {
$headerValue = isset($value['Header']) ? $value['Header'] : (isset($value['header']) ? $value['header'] : null);
array_push($header, $headerValue);
}
}
$rows = [$header];
foreach ($data as $key => $value) {
$row = [];
foreach ($tableColumns as $k => $v) {
if ($v['show'] == 1) {
if ($v['accessor'] == 'comments' && is_array($value[$v['accessor']])) {
$comments = '';
foreach ($value[$v['accessor']] as $commentKey => $commentValue) {
$commentValue['comment'] = $commentValue['isDeleted'] ? "**This comment was deleted.**" : $commentValue['comment'];
$comments .= "{$commentValue['addedByName']} [{$commentValue['dateInserted']}]: {$commentValue['comment']}\n";
}
$value[$v['accessor']] = $comments;
} elseif ($v['accessor'] == 'attachedFiles') {
$value[$v['accessor']] = $value['linkToFile'];
} elseif (is_array($value[$v['accessor']])) {
$items = '';
if (array_key_exists('label', $value[$v['accessor']])) {
$items .= $value[$v['accessor']]['label'];
} else {
foreach ($value[$v['accessor']] as $kk => $vv) {
if (array_key_Exists('label', $vv)) {
$items .= $vv['label'] . "\n";
}
}
}
$value[$v['accessor']] = $items;
}
array_push($row, $value[$v['accessor']]);
}
}
$rows[] = $row;
}
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('MAFO')->setLastModifiedBy('MAFO')->setTitle($reportNamePretty . ' Report')->setSubject($reportNamePretty)->setDescription($reportNamePretty);
// echo json_encode($rows);die;
$spreadsheet->getActiveSheet()->fromArray($rows, null, 'A1');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $reportName . '.xls"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
}
public function getReportResponse($finalArr, $tableColumns, $limit, $page, $sortBy, $sortType)
{
foreach ($finalArr as $key => $value) {
foreach ($tableColumns as $k => $v) {
if (isset($v['footerEnabled'])) {
if (!array_key_exists('Footer', $v)) {
$tableColumns[$k]['Footer'] = 0;
}
if (array_key_exists($v['accessor'], $value)) {
$tableColumns[$k]['Footer'] += $value[$v['accessor']];
}
}
}
}
foreach ($tableColumns as $key => $value) {
if (isset($value['footerEnabled']) && isset($value['Footer'])) {
$tableColumns[$key]['Footer'] = round($value['Footer'], 2);
}
}
if (sizeof($finalArr)) {
$entity = $finalArr[0];
if (array_key_exists($sortBy, $entity)) {
$sortFlag = 3;
if ($sortType == Config::SORT_TYPE_ASC) {
$sortFlag = 4;
}
array_multisort(array_column($finalArr, $sortBy), $sortFlag, $finalArr);
}
}
$offset = $limit * ($page - 1);
$totalRecordCount = sizeof($finalArr);
$noOfPages = ceil($totalRecordCount / $limit);
$finalArr = array_slice($finalArr, $offset, $limit);
return [
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => [
'tableColumns' => $tableColumns,
'data' => $finalArr,
'metaData' => [
"total" => $totalRecordCount,
"limit" => $limit,
"page" => $page,
"pages" => $noOfPages
]
],
'error' => null
]
];
}
public function getDeductionForAdvertiserAndAffiliateForPeriod($offerId, $advertiserId, $affiliateId, $startDate, $endDate)
{
$totalDeduction = 0;
$approvedDeduction = 0;
if (
$this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId]) &&
$this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId])
) {
$deductionControlData = $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData($offerId ? [$offerId] : [], $advertiserId ? [$advertiserId] : [], $affiliateId ? [$affiliateId] : [], [], [], $startDate, $endDate, 0, []);
foreach ($deductionControlData as $key => $value) {
$totalDeduction += $value['deductionValue'];
if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
$approvedDeduction += $value['deductionValue'];
}
}
}
return [
'advertiserId' => $advertiserId,
'affiliateId' => $affiliateId,
'totalDeduction' => round($totalDeduction, 2),
'approvedDeduction' => round($approvedDeduction, 2),
];
}
public function getIndexedDeductionFromDeductionControlByAdvertiserAndAffiliate($startDate, $endDate)
{
$indexedDeduction = [];
$deductionControlData = $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData([], [], [], [], [], $startDate, $endDate, 0, []);
foreach ($deductionControlData as $key => $value) {
$deductionPeriod = $value['deductionPeriod']->format('Y-m');
if (!isset($indexedDeduction[$deductionPeriod])) {
$indexedDeduction[$deductionPeriod] = [];
}
if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']])) {
$indexedDeduction[$deductionPeriod][$value['advertiserId']] = [];
}
if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']])) {
$indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']] = [
'advertiserId' => $value['advertiserId'],
'affiliateId' => $value['affiliateId'],
'totalDeduction' => 0,
'approvedDeduction' => 0
];
}
$indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['totalDeduction'] += $value['deductionValue'];
if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
$indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['approvedDeduction'] += $value['deductionValue'];
}
}
return $indexedDeduction;
}
public function detectCSVDelimiter($csvFile)
{
$delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];
$handle = fopen($csvFile, "r");
$firstLine = fgets($handle);
fclose($handle);
foreach ($delimiters as $delimiter => &$count) {
$count = count(str_getcsv($firstLine, $delimiter));
}
return array_search(max($delimiters), $delimiters);
}
public function assignTagsToOffers()
{
$activeOffers = $this->doctrine->getRepository(OfferInfo::class)->getOfferInfoByStatus(Config::ACTIVE_STATUS);
foreach ($activeOffers as $key => $value) {
if ($value['offerUrl']) {
foreach (Config::HASOFFER_TRACKING_LINK_KEYWORDS_BY_TAG_ID as $k => $v) {
if ($k == Config::HASOFFER_ADJUST_OFFER_TAG_ID) {
$adjustAppDetails = $this->doctrine->getRepository(AdjustAppDetails::class)->getAdjustAppDetails();
foreach ($adjustAppDetails as $kk => $vv) {
if (
$this->checkForString($value['offerUrl'], $vv['appToken']) &&
array_key_exists($vv['account'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING)
) {
$this->brandApi->addTagToOffer($value['offerId'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING[$vv['account']]);
$this->populateDbByOfferId($value['offerId']);
break 2;
}
}
} else {
foreach ($v as $subLink) {
if (
isset($value['offerUrl']) &&
$this->checkForString($value['offerUrl'], $subLink) &&
!$this->doctrine->getRepository(OfferTagRelationship::class)->findOneBy(['tagId' => $k, 'offerId' => $value['offerId']])
) {
$this->brandApi->addTagToOffer($value['offerId'], $k);
$this->populateDbByOfferId($value['offerId']);
break 2;
}
}
}
}
}
}
}
public function getReportsRowWiseDataByAggregation($tableColumns, $selectedColumns, $rowWiseData)
{
$finalArr = [];
foreach ($rowWiseData as $rowWiseIndex => $rowWiseValue) {
$indexArr = [];
foreach ($selectedColumns as $key => $value) {
if (
array_key_exists($key, $tableColumns) &&
$value &&
in_array($tableColumns[$key]['category'], ['data_fields', 'item_interval'])
) {
$indexArr[] = $rowWiseValue[$key];
}
}
$index = md5(implode("#", $indexArr));
if (!array_key_exists($index, $finalArr)) {
foreach ($selectedColumns as $key => $value) {
if (array_key_exists($key, $tableColumns) && $value && array_key_exists($key, $rowWiseValue)) {
if (in_array($tableColumns[$key]['category'], ['data_fields', 'item_interval'])) {
$finalArr[$index][$key] = $rowWiseValue[$key];
}
}
}
foreach ($tableColumns as $key => $value) {
if ($value['category'] == 'statistics') {
$finalArr[$index][$key] = 0;
}
}
}
foreach ($tableColumns as $key => $value) {
if (
(
$value['category'] == 'statistics' && !isset($value['calculationType'])
) ||
(
isset($value['calculationType']) && $value['category'] == 'statistics' && $value['calculationType'] != 'percentage'
)
) {
$finalArr[$index][$key] += $rowWiseValue[$key];
$finalArr[$index][$key] = round($finalArr[$index][$key], 2);
}
}
}
return $finalArr;
}
public function getPaginatedResponseForReports($reportData, $tableColumns, $selectedColumns, $sortBy, $sortType, $limit, $page)
{
$reportData = array_values($reportData);
if (sizeof($reportData)) {
$entity = $reportData[0];
if (array_key_exists($sortBy, $entity)) {
$sortFlag = 3;
if ($sortType == Config::SORT_TYPE_ASC) {
$sortFlag = 4;
}
array_multisort(array_column($reportData, $sortBy), $sortFlag, $reportData);
}
}
$offset = $limit * ($page - 1);
$totalRecordCount = sizeof($reportData);
$noOfPages = ceil($totalRecordCount / $limit);
foreach ($tableColumns as $key => $value) {
if (isset($value['aggregate'])) {
if ($value['aggregate'] == 'sum') {
$tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData, $value['accessor'])), 2));
}
if ($value['aggregate'] == 'average' && count($reportData) > 0) {
$tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData, $value['accessor'])) / count($reportData), 2));
}
}
}
$tableColumns = $this->changeColumnVisibilityForTable(array_values($tableColumns), $selectedColumns, []);
return [
'response' => [
'success' => true,
'httpStatus' => Config::HTTP_STATUS_CODE_OK,
'data' => [
'tableColumns' => array_values($tableColumns),
'data' => array_slice($reportData, $offset, $limit),
'metaData' => [
'total' => $totalRecordCount,
'limit' => (int)$limit,
'page' => (int)$page,
'pages' => (int)$noOfPages,
]
],
'error' => null
]
];
}
public function getAffiliateCategoryByAffiliateId($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$affiliateTagRelationshipData = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByTagIdArr([Config::HASOFFER_AFFILIATE_CATEGORY_A_TAG_ID, Config::HASOFFER_AFFILIATE_CATEGORY_B_TAG_ID], $tuneAccount);
$data = [];
foreach ($affiliateTagRelationshipData as $key => $value) {
$data[$key] = [
'category' => Config::HASOFFER_AFFILIATE_CATEGORY_ARRAY[$value['tagId']],
'affiliateId' => $value['affiliateId']
];
}
$affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByArrToSearch([], $tuneAccount);
foreach ($affiliateData as $key => $value) {
if (!array_key_exists($value['affiliateId'], $data)) {
$data[$value['affiliateId']] = [
'category' => Config::HASOFFER_AFFILIATE_CATEGORY_UNCATEGORISED_TAG_NAME,
'affiliateId' => $value['affiliateId']
];
}
}
return $data;
}
public function getPidByOfferId($offerId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
{
$tunePid = null;
$offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
if ($offerInfo) {
$parsedUrl = parse_url($offerInfo->getOfferUrl());
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $query);
if (isset($query['pid']) && in_array($query['pid'], Config::TUNE_APPSFLYER_PIDS)) {
$tunePid = $query['pid'];
}
}
}
return $tunePid;
}
public function getWhitelistIPsAppsflyerOrAdjust($offerUrl)
{
$whitelistIps = [];
if (stripos($offerUrl, Config::APPSFLYER_DOMAIN) !== false) {
$whitelistIps = Config::WIZARD_APPSFLYER_WHITE_LIST;
}
if (
stripos($offerUrl, Config::ADJUST_IO_DOMAIN) !== false
|| stripos($offerUrl, Config::ADJUST_COM_DOMAIN) !== false
) {
$whitelistIps = Config::WIZARD_ADJUST_WHITE_LIST;
}
return $whitelistIps;
}
public function updateNotificationUnreadCountByUser($userEmail, $unreadNotificationCount)
{
$cacheKey = Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER . $userEmail;
if (is_null($this->elasticCache->redisGet($cacheKey))) {
$userData = $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
'sentToUserId' => $userEmail,
'isRead' => 0
]);
$notificationCount = count($userData);
} else {
$notificationCount = $this->elasticCache->redisGet($cacheKey);
}
$unreadNotificationCount += $notificationCount;
$this->elasticCache->redisSet($cacheKey, $unreadNotificationCount);
}
public function getUnreadNotificationCountByUser($userEmail)
{
$cacheKey = Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER . $userEmail;
if (is_null($this->elasticCache->redisGet($cacheKey))) {
$userData = $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
'sentToUserId' => $userEmail,
'isRead' => 0
]);
$notificationCount = count($userData);
} else {
$notificationCount = $this->elasticCache->redisGet($cacheKey);
}
return $notificationCount;
}
public function sendPushNotification($topic, $topicData)
{
try {
$update = new Update(
$topic,
$topicData
// ,true
);
$this->hub->publish($update);
} catch (\Exception $e) {
$this->logger->error('Error occurred: ' . $e);
}
}
public function getEmployeesByUserId()
{
$cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
if (!$cachedList) {
$employeeList = $this->getWarmedUpUsersByUserId();
} else {
$employeeList = json_decode($cachedList, true);
}
ksort($employeeList);
return $employeeList;
}
public function getWarmedUpUsersByUserId()
{
$employeesData = $this->doctrine->getRepository(Users::class)->getEmployees();
$data = [];
foreach ($employeesData as $key => $value) {
$data[$value['email']] = [
'firstName' => $value['name'],
'email' => $value['email']
];
}
return $data;
}
}