src/Services/Common.php line 96

Open in your IDE?
  1. <?php
  2. namespace App\Services;
  3. use App\Config;
  4. use App\Entity\AdjustAppDetails;
  5. use App\Entity\Tune\AdvertiserInfo;
  6. use App\Entity\Tune\AffiliateAccountManager;
  7. use App\Entity\Tune\AffiliateInfo;
  8. use App\Entity\Tune\AffiliateOfferApproval;
  9. use App\Entity\AffiliateOfferBlockLogs;
  10. use App\Entity\AffiliateTagRelationship;
  11. use App\Entity\MafoId\MafoAffiliates;
  12. use App\Entity\AlertMeta;
  13. use App\Entity\AppInfo;
  14. use App\Entity\CommandLogger;
  15. use App\Entity\DeductionControl;
  16. use App\Entity\MafoId\MafoDeductionControl;
  17. use App\Entity\Employees;
  18. use App\Entity\MafoUserNotifications;
  19. use App\Entity\MmpAdvertisers;
  20. use App\Entity\MmpMobileApps;
  21. use App\Entity\ObjectMappingWithTuneWebAccount;
  22. use App\Entity\OfferCategories;
  23. use App\Entity\OfferCategoryRelationship;
  24. use App\Entity\OfferCreativeFile;
  25. use App\Entity\OfferGeoRelationship;
  26. use App\Entity\OfferGoalsInfo;
  27. use App\Entity\Tune\OfferInfo;
  28. use App\Entity\OfferTagRelationship;
  29. use App\Entity\OfferWhitelist;
  30. use App\Entity\SkadNetworkApiLogs;
  31. use App\Entity\SkadNetworkManualPostbackMapping;
  32. use App\Entity\SkadNetworkPostbackLogs;
  33. use App\Entity\Tag;
  34. use App\Entity\UserApiKey;
  35. use App\Entity\Users;
  36. use App\Entity\MafoId\MafoAdvertisers;
  37. use App\Entity\MafoId\MafoOffers;
  38. use App\Repository\AdvertiserAccountManagerRepository;
  39. use Aws\Credentials\Credentials;
  40. use Aws\S3\Exception\S3Exception;
  41. use Aws\Exception\MultipartUploadException;
  42. use Aws\S3\MultipartUploader;
  43. use Aws\S3\ObjectUploader;
  44. use Aws\S3\S3Client;
  45. use Doctrine\ORM\EntityManagerInterface;
  46. use PhpOffice\PhpSpreadsheet\IOFactory;
  47. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  48. use Psr\Log\LoggerInterface;
  49. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  50. use Symfony\Component\Mercure\HubInterface;
  51. use Symfony\Component\Mercure\Update;
  52. use Twig\Environment;
  53. /**
  54. *
  55. * Common functions which are used throughout the project
  56. *
  57. * Class Common
  58. * @package App\Services
  59. */
  60. class Common
  61. {
  62. private $em;
  63. private $brandApi;
  64. private $doctrine;
  65. private $scraper;
  66. private $elasticCache;
  67. private $rootPath;
  68. private $usersComponents;
  69. private $mafoObjectsComponents;
  70. private $hyperApis;
  71. private LoggerInterface $logger;
  72. private HubInterface $hub;
  73. public function __construct(
  74. MysqlQueries $em,
  75. BrandHasofferAPI $brandApi,
  76. EntityManagerInterface $doctrine,
  77. Scraper $scraper,
  78. Environment $templating,
  79. Aws\ElasticCache $elasticCache,
  80. ParameterBagInterface $params,
  81. UsersComponents $usersComponents,
  82. MafoObjectsComponents $mafoObjectsComponents,
  83. HyperApis $hyperApis,
  84. LoggerInterface $logger,
  85. HubInterface $hub
  86. ) {
  87. $this->em = $em;
  88. $this->brandApi = $brandApi;
  89. $this->doctrine = $doctrine;
  90. $this->scraper = $scraper;
  91. $this->template = $templating;
  92. $this->elasticCache = $elasticCache;
  93. $this->rootPath = $params->get('kernel.project_dir');
  94. $this->usersComponents = $usersComponents;
  95. $this->mafoObjectsComponents = $mafoObjectsComponents;
  96. $this->hyperApis = $hyperApis;
  97. $this->logger = $logger;
  98. $this->hub = $hub;
  99. }
  100. public function getAdvertisersListByStatusWithKeys($arr = [])
  101. {
  102. $statuses = isset($arr['statuses']) && sizeof($arr['statuses']) > 0 ? $arr['statuses'] : [Config::ACTIVE_STATUS];
  103. $tuneAccount = isset($arr['tuneAccount']) ? $arr['tuneAccount'] : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  104. $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT . '_' . $tuneAccount);
  105. if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
  106. $advertiserList = $this->getWarmedUpHoAdvertiserList($statuses, $tuneAccount);
  107. } else {
  108. $advertiserList = json_decode($cachedList, true);
  109. }
  110. ksort($advertiserList);
  111. return $advertiserList;
  112. }
  113. public function getWarmedUpHoAdvertiserList($statuses, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  114. {
  115. $advertiserList = [];
  116. $advertiserData = $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserListByStatus($statuses, $tuneAccount);
  117. $employeesInfo = $this->getEmployeesByEmployeeId();
  118. foreach ($advertiserData as $key => $value) {
  119. $temp = [
  120. 'status' => $value['status'],
  121. 'name' => $value['company'],
  122. 'accountManagerId' => $value['accountManagerId'],
  123. 'accountManagerEmail' => null,
  124. 'accountManagerName' => null,
  125. 'id' => (int)$value['advertiserId']
  126. ];
  127. if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  128. $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  129. $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  130. }
  131. $advertiserList[$value['advertiserId']] = $temp;
  132. }
  133. return $advertiserList;
  134. }
  135. public function getAffiliateListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  136. {
  137. $statuses = [Config::ACTIVE_STATUS];
  138. $tuneAccountCacheKey = Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT . '_' . $tuneAccount;
  139. $cachedList = $this->elasticCache->redisGet($tuneAccountCacheKey);
  140. if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
  141. $affiliateList = $this->getWarmedUpHoAffiliateList($statuses, $tuneAccount);
  142. } else {
  143. $affiliateList = json_decode($cachedList, true);
  144. }
  145. ksort($affiliateList);
  146. return $affiliateList;
  147. }
  148. public function getPublisherAffiliateListByStatusWithKeys($statuses = [Config::ACTIVE_STATUS], $affiliateIds = null)
  149. {
  150. // $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT);
  151. //
  152. // if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
  153. // $affiliateList = $this->getWarmedUpHoPublisherAffiliateList($statuses);
  154. // } else {
  155. // $affiliateList = json_decode($cachedList, true);
  156. // }
  157. $affiliateList = $this->getWarmedUpHoPublisherAffiliateList($statuses, $affiliateIds);
  158. ksort($affiliateList);
  159. return $affiliateList;
  160. }
  161. public function getWarmedUpHoAffiliateList($statuses, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  162. {
  163. $affiliateList = [];
  164. $affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses, $tuneAccount);
  165. $employeesInfo = $this->getEmployeesByEmployeeId();
  166. foreach ($affiliateData as $key => $value) {
  167. $temp = [
  168. 'status' => $value['status'],
  169. 'name' => $value['company'],
  170. 'accountManagerId' => $value['accountManagerId'],
  171. 'accountManagerEmail' => null,
  172. 'accountManagerName' => null,
  173. 'id' => (int)$value['affiliateId']
  174. ];
  175. if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  176. $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  177. $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  178. }
  179. $affiliateList[$value['affiliateId']] = $temp;
  180. }
  181. return $affiliateList;
  182. }
  183. public function getWarmedUpHoPublisherAffiliateList(array $statuses, array $affiliateIds = [])
  184. {
  185. $affiliateList = [];
  186. // Fetch affiliate data based on status
  187. $affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses);
  188. // Get employee information
  189. $employeesInfo = $this->getEmployeesByEmployeeId();
  190. foreach ($affiliateData as $value) {
  191. // Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
  192. if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
  193. $temp = [
  194. 'status' => $value['status'],
  195. 'name' => $value['company'],
  196. 'accountManagerId' => $value['accountManagerId'],
  197. 'accountManagerEmail' => null,
  198. 'accountManagerName' => null,
  199. 'id' => (int)$value['affiliateId']
  200. ];
  201. // Check if account manager info is available
  202. if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  203. $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  204. $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  205. }
  206. // Add to affiliate list
  207. $affiliateList[$value['affiliateId']] = $temp;
  208. }
  209. }
  210. return $affiliateList;
  211. }
  212. public function getWarmedUpHoPublisherMafoAffiliateList(array $statuses, array $affiliateIds = [])
  213. {
  214. $affiliateList = [];
  215. // Fetch affiliate data based on status
  216. $affiliateData = $this->doctrine->getRepository(MafoAffiliates::class)->getAffiliateListByStatusArr($statuses);
  217. // Get employee information
  218. $employeesInfo = $this->getEmployeesByEmployeeId();
  219. foreach ($affiliateData as $value) {
  220. // Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
  221. if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
  222. $temp = [
  223. 'status' => $value['status'],
  224. 'name' => $value['name'],
  225. 'accountManagerId' => $value['accountManagerId'],
  226. 'accountManagerEmail' => null,
  227. 'accountManagerName' => null,
  228. 'id' => (int)$value['id']
  229. ];
  230. // Check if account manager info is available
  231. if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  232. $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  233. $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  234. }
  235. // Add to affiliate list
  236. $affiliateList[$value['id']] = $temp;
  237. }
  238. }
  239. return $affiliateList;
  240. }
  241. public function getHyperClientCachedListByKeys()
  242. {
  243. $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_CLIENT_LIST);
  244. if (!$cachedList) {
  245. $clientList = $this->getHyperClientListByKeys();
  246. } else {
  247. $clientList = json_decode($cachedList, true);
  248. }
  249. return $clientList;
  250. }
  251. public function getHyperClientListByKeys()
  252. {
  253. $hyperData = $this->hyperApis->getHyperClientList();
  254. $clientList = [];
  255. if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  256. foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  257. $countryCode = null;
  258. foreach (Config::COUNTRIES as $k => $v) {
  259. if ($this->checkForString($value['Country'], $v['name'])) {
  260. $countryCode = $k;
  261. break;
  262. }
  263. }
  264. $value['countryCode'] = $countryCode;
  265. $clientList[$value['ClientNumber']] = $value;
  266. }
  267. }
  268. $this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LIST, json_encode($clientList));
  269. return $clientList;
  270. }
  271. public function getHyperPublisherCachedListByKeys()
  272. {
  273. $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_PUBLISHER_LIST);
  274. if (!$cachedList) {
  275. $clientList = $this->getHyperPublisherListByKeys();
  276. } else {
  277. $clientList = json_decode($cachedList, true);
  278. }
  279. return $clientList;
  280. }
  281. public function getHyperPublisherListByKeys()
  282. {
  283. $hyperData = $this->hyperApis->getHyperPublisherInfo();
  284. $clientList = [];
  285. if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  286. foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  287. $countryCode = null;
  288. foreach (Config::COUNTRIES as $k => $v) {
  289. if ($this->checkForString($value['Country'], $v['name'])) {
  290. $countryCode = $k;
  291. break;
  292. }
  293. }
  294. $value['countryCode'] = $countryCode;
  295. $clientList[$value['SupplierNumber']] = $value;
  296. }
  297. }
  298. return $clientList;
  299. }
  300. public function getHyperAffiliateListByKeys()
  301. {
  302. $hyperData = $this->hyperApis->getHyperClientList();
  303. $clientList = [];
  304. if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  305. foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  306. $countryCode = null;
  307. foreach (Config::COUNTRIES as $k => $v) {
  308. if ($this->checkForString($value['Country'], $v['name'])) {
  309. $countryCode = $k;
  310. break;
  311. }
  312. }
  313. $value['countryCode'] = $countryCode;
  314. $clientList[$value['ClientNumber']] = $value;
  315. }
  316. }
  317. $this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LIST, json_encode($clientList));
  318. return $clientList;
  319. }
  320. public function getMmpAdvertisersListWithKeys()
  321. {
  322. $advertisers = $this->doctrine->getRepository(MmpAdvertisers::class)->getMmpAdvertisers();
  323. $data = [];
  324. foreach ($advertisers as $key => $value) {
  325. $data[$value['id']] = [
  326. 'value' => $value['id'],
  327. 'label' => $value['name']
  328. ];
  329. }
  330. ksort($data);
  331. return $data;
  332. }
  333. public function getAffiliateTagListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  334. {
  335. $tagsInDb = $this->doctrine->getRepository(Tag::class)->getTags(1, null, null, 1, $tuneAccount);
  336. $tagList = [];
  337. foreach ($tagsInDb as $key => $value) {
  338. $tagList[$value['tagId']] = [
  339. 'value' => $value['tagId'],
  340. 'name' => $value['name']
  341. ];
  342. }
  343. ksort($tagList);
  344. return $tagList;
  345. }
  346. public function getOfferCategoriesListByStatusWithKeys($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  347. {
  348. $status = Config::ACTIVE_STATUS;
  349. $offerCategoriesData = $this->doctrine->getRepository(OfferCategories::class)->getOfferCategoriesByStatus($status, $tuneAccount);
  350. $offerCategoryList = [];
  351. foreach ($offerCategoriesData as $key => $value) {
  352. $offerCategoryList[$value['categoryId']] = [
  353. 'name' => $value['name'],
  354. 'id' => (int)$value['categoryId']
  355. ];
  356. }
  357. ksort($offerCategoryList);
  358. return $offerCategoryList;
  359. }
  360. public function getAdvertiserListByAdvertiserIdArr($advertiserIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  361. {
  362. $advertiserDataByAdvertiserId = [];
  363. if ($advertiserIdArr) {
  364. $advertiserInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserInfoByAdvertiserIdArr($advertiserIdArr, $tuneAccount);
  365. foreach ($advertiserInfo as $key => $value) {
  366. $advertiserDataByAdvertiserId[$value['advertiserId']] = [
  367. 'id' => (int)$value['advertiserId'],
  368. 'name' => $value['company']
  369. ];
  370. }
  371. }
  372. return $advertiserDataByAdvertiserId;
  373. }
  374. public function getGoalDisableLinkData($offerId)
  375. {
  376. $data = $this->em->getGoalDisableLinkData($offerId);
  377. $distinctOfferIds = [];
  378. foreach ($data as $key => $value) {
  379. if (!in_array($value['offerId'], $distinctOfferIds)) {
  380. $distinctOfferIds[] = $value['offerId'];
  381. }
  382. }
  383. $offerGoalsByOfferId = [];
  384. if ($distinctOfferIds) {
  385. $offerGoalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferIdArr($distinctOfferIds);
  386. if ($offerGoalData) {
  387. foreach ($offerGoalData as $key => $value) {
  388. $offerGoalsByOfferId[$value['offerId']][] = $value['goalId'];
  389. }
  390. }
  391. }
  392. $bifurcatedData = [];
  393. foreach ($data as $key => $value) {
  394. if (array_key_exists($value['offerId'], $offerGoalsByOfferId) && in_array($value['goalId'], $offerGoalsByOfferId[$value['offerId']])) {
  395. $bifurcatedData[$value['addedFrom']][] = $value;
  396. }
  397. }
  398. return $bifurcatedData;
  399. }
  400. public function disableLink($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $addedFrom, $advertiserId, $jsonMetaDataStr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  401. {
  402. $disableLinkMd5 = $this->getDisableLinkMd5($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $tuneAccount);
  403. $md5Exist = $this->em->getDisableLinkByMd5($disableLinkMd5);
  404. if (!$md5Exist) {
  405. $data = $this->brandApi->saveOfferDisabledLink($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $tuneAccount);
  406. if ($data['response']['status'] === 1) {
  407. $this->em->insertToDisableLink($disableLinkMd5, $offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $addedFrom, $advertiserId, $jsonMetaDataStr);
  408. }
  409. }
  410. }
  411. public function getDisableLinkMd5($offerId, $affiliateId, $source, $affsub2, $affSub3, $affSub5, $trackingAccount = Config::TUNE_ACCOUNT_DEFAULT, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  412. {
  413. $trackingAccountStr = $trackingAccount == Config::TUNE_ACCOUNT_DEFAULT ? '' : Config::TUNE_ACCOUNT_WEB;
  414. return md5($offerId . $affiliateId . $source . $affsub2 . $affSub3 . $affSub5 . $trackingAccountStr . $tuneAccount);
  415. }
  416. public function automaticDisableLinkData($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  417. {
  418. $automaticDisableLinkData = $this->em->getAutomaticDisableLinkData($tuneAccount);
  419. $finalArr['byAdvertiser'] = [];
  420. $finalArr['byAffiliate'] = [];
  421. $finalArr['byOffer'] = [];
  422. foreach ($automaticDisableLinkData as $key => $value) {
  423. $value['tuneAccountPretty'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['tuneAccount']];
  424. $value['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  425. if ($value['advertiserId']) {
  426. $finalArr['byAdvertiser'][] = $value;
  427. }
  428. if ($value['affiliateId']) {
  429. $finalArr['byAffiliate'][] = $value;
  430. }
  431. if ($value['offerId']) {
  432. $finalArr['byOffer'][] = $value;
  433. }
  434. }
  435. return $finalArr;
  436. }
  437. public function deleteDisableLinkByMd5($md5, $id, $trackingAccount = Config::TUNE_ACCOUNT_DEFAULT)
  438. {
  439. $disableLink = $this->em->getDisableLinkByMd5($md5);
  440. if ($disableLink) {
  441. $offerId = $disableLink->getOfferId();
  442. $affiliateId = $disableLink->getAffiliateId();
  443. $source = $disableLink->getSource();
  444. $affSub2 = $disableLink->getAffsub2();
  445. $affSub3 = $disableLink->getAffsub3();
  446. $affSub5 = $disableLink->getAffsub5();
  447. $advertiserId = $disableLink->getAdvertiserId();
  448. $addedFrom = $disableLink->getAddedFrom();
  449. $meta = $disableLink->getMeta();
  450. $wasInsertedOn = $disableLink->getDateInserted();
  451. $trackingAccount = $disableLink->getTrackingAccount();
  452. $strict = 0;
  453. $disableLinkData = $this->brandApi->findDisableLink($offerId, $affiliateId, $source, $strict, $affSub2, $affSub3, $affSub5, $trackingAccount)['response']['data'];
  454. foreach ($disableLinkData as $k => $v) {
  455. $this->brandApi->deleteDisableLink($k, $trackingAccount);
  456. }
  457. $this->em->deleteDisableLinkByMd5($md5);
  458. // Removing dump from mysql and added dump of DisableLinks to mongo
  459. // $this->em->insertToDisableLinkDump($md5, $offerId, $affiliateId, $source, $affSub2, $addedFrom, $advertiserId, $meta, $wasInsertedOn, $affSub3, $affSub5, $trackingAccount);
  460. } else {
  461. $this->brandApi->deleteDisableLink($id);
  462. }
  463. }
  464. public function checkForNonIncentInString($string)
  465. {
  466. 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')) {
  467. return true;
  468. }
  469. return false;
  470. }
  471. public function checkForString($superString, $checkString)
  472. {
  473. if (strpos(strtolower($superString), strtolower($checkString)) !== false) {
  474. return true;
  475. } else {
  476. return false;
  477. }
  478. }
  479. public function filterSource($source)
  480. {
  481. if ($this->checkForString($source, "_")) {
  482. $source = explode("_", $source);
  483. if (($source[0] == "" && $source[1] != "") || ($source[0] != "" && $source[1] == "") || ($source[0] == "" && $source[1] == "")) {
  484. $source = implode("_", $source);
  485. } else {
  486. $source = $source[0];
  487. }
  488. }
  489. return $source;
  490. }
  491. public function filterSourceByAffiliate($source, $affiliateId)
  492. {
  493. if ($affiliateId == 3467) {
  494. $actualSource = $source;
  495. if (substr($source, 0, 4) === "114_") {
  496. $actualSource = substr($source, 4);
  497. }
  498. return $actualSource;
  499. }
  500. return $source;
  501. }
  502. public function filterSourceByAffiliateAndLtr($source, $affiliateId, $clicks, $conversions)
  503. {
  504. if ($affiliateId == 3467) {
  505. $actualSource = $source;
  506. if (substr($source, 0, 4) === "114_") {
  507. $actualSource = substr($source, 4);
  508. }
  509. if ($conversions > 15 && (($conversions / $clicks) * 100 > 30)) {
  510. return $actualSource;
  511. } else {
  512. return false;
  513. }
  514. }
  515. return $source;
  516. }
  517. public function getBulkCapData()
  518. {
  519. $bulkData = $this->em->getBulkCapData();
  520. foreach ($bulkData as $key => $value) {
  521. $bulkData[$key]['affiliateOfferCapType'] = str_replace("_", " ", ucfirst($value['affiliateOfferCapType']));
  522. $bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
  523. }
  524. return $bulkData;
  525. }
  526. public function getBulkCapByAffiliateData()
  527. {
  528. $bulkData = $this->em->getBulkCapByAffiliateData();
  529. foreach ($bulkData as $key => $value) {
  530. $bulkData[$key]['affiliateOfferCapType'] = str_replace("_", " ", ucfirst($value['affiliateOfferCapType']));
  531. $bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
  532. }
  533. return $bulkData;
  534. }
  535. public function getAccountManagerInfoByTuneAdvertiserId($advertiserId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  536. {
  537. $accountManagerInfo = $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAdvertiserAccountManagerByAdvertiserId($advertiserId, $tuneAccount);
  538. $email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  539. $firstName = '';
  540. $lastName = '';
  541. if ($accountManagerInfo) {
  542. $email = $accountManagerInfo->getEmail();
  543. $firstName = $accountManagerInfo->getFirstName();
  544. $lastName = $accountManagerInfo->getLastName();
  545. }
  546. return [
  547. 'emailId' => $email,
  548. 'firstName' => $firstName,
  549. 'lastName' => $lastName
  550. ];
  551. }
  552. public function getAccountManagerInfoByMafoAdvertiserId($advertiserId)
  553. {
  554. $mafoAdvertiserInfo = $this->doctrine->getRepository(MafoAdvertisers::class)->findOneBy(['id' => $advertiserId]);
  555. $email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  556. $firstName = '';
  557. $lastName = '';
  558. if ($mafoAdvertiserInfo) {
  559. $accountManagerInfo = $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAdvertiserInfo->getAccountManagerEmail()]);
  560. $email = $mafoAdvertiserInfo->getAccountManagerEmail();
  561. $name = $accountManagerInfo->getName();
  562. $nameArr = explode(" ", $name);
  563. $firstName = $nameArr[0];
  564. $lastName = $nameArr[1];
  565. }
  566. return [
  567. 'emailId' => $email,
  568. 'firstName' => $firstName,
  569. 'lastName' => $lastName
  570. ];
  571. }
  572. public function getAccountManagerInfoByTuneAffiliateId($affiliateId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  573. {
  574. $accountManagerInfo = $this->doctrine->getRepository(AffiliateAccountManager::class)->getAffiliateAccountManagerByAffiliateId($affiliateId, $tuneAccount);
  575. $email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  576. $firstName = '';
  577. $lastName = '';
  578. if ($accountManagerInfo) {
  579. $email = $accountManagerInfo->getEmail();
  580. $firstName = $accountManagerInfo->getFirstName();
  581. $lastName = $accountManagerInfo->getLastName();
  582. }
  583. return [
  584. 'emailId' => $email,
  585. 'firstName' => $firstName,
  586. 'lastName' => $lastName
  587. ];
  588. }
  589. public function getAccountManagerInfoByMafoAffiliateId($affiliateId)
  590. {
  591. $mafoAffiliateInfo = $this->doctrine->getRepository(MafoAffiliates::class)->findOneBy(['id' => $affiliateId]);
  592. $email = Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  593. $firstName = '';
  594. $lastName = '';
  595. if ($mafoAffiliateInfo) {
  596. $accountManagerInfo = $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAffiliateInfo->getAccountManagerEmail()]);
  597. $email = $mafoAffiliateInfo->getAccountManagerEmail();
  598. $name = $accountManagerInfo->getName();
  599. $nameArr = explode(" ", $name);
  600. $firstName = $nameArr[0];
  601. $lastName = $nameArr[1];
  602. }
  603. return [
  604. 'emailId' => $email,
  605. 'firstName' => $firstName,
  606. 'lastName' => $lastName
  607. ];
  608. }
  609. public function getAccountManagerInfoByAffiliateIdArrWithKeys($affiliateIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  610. {
  611. $accountManagerInfoDB = $this->doctrine->getRepository(AffiliateAccountManager::class)->getDataByAffiliateIds($affiliateIdArr, $tuneAccount);
  612. $accountManagerInfo = [];
  613. foreach ($accountManagerInfoDB as $key => $value) {
  614. $accountManagerInfo[$value['affiliateId']] = $value;
  615. $accountManagerInfo[$value['affiliateId']]['id'] = $value['employeeId'];
  616. $accountManagerInfo[$value['affiliateId']]['name'] = $value['firstName'] . ' ' . $value['lastName'];
  617. }
  618. return $accountManagerInfo;
  619. }
  620. public function getAccountManagerInfoByOfferId($offerId)
  621. {
  622. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->checkOfferIdExist($offerId);
  623. return $this->getAccountManagerInfoByTuneAdvertiserId($offerInfo ? $offerInfo->getAdvertiserId() : null);
  624. }
  625. public function getDisableLinkLogs($affiliateIdArray, $offerIdArray, $sourceIdArray, $advertiserArray, $addedFromArr, $dateStart, $dateEnd, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  626. {
  627. $disableLinksMyMd5 = [];
  628. $disableLinkData = [];
  629. if (empty($addedFromArr) || in_array(Config::DISABLE_LINKS_FROM_HO_PANEL, $addedFromArr)) {
  630. $disableLinkDataFromHO = $this->brandApi->findDisableLinksDyDateRange($offerIdArray, $affiliateIdArray, $sourceIdArray, [], $dateStart, $dateEnd, $tuneAccount)['response']['data']['data'];
  631. $disableLinkData = [];
  632. $md5Arr = [];
  633. foreach ($disableLinkDataFromHO as $key => $value) {
  634. $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);
  635. $disableLinkData[] = [
  636. 'affiliateId' => $value['OfferDisabledLink']['affiliate_id'],
  637. 'offerId' => $value['OfferDisabledLink']['offer_id'],
  638. 'source' => $value['OfferDisabledLink']['source'],
  639. 'advertiserId' => null,
  640. 'dateInserted' => $value['OfferDisabledLink']['datetime'],
  641. 'addedFrom' => null,
  642. 'md5' => $md5,
  643. 'tuneAccount' => $tuneAccount,
  644. 'id' => $value['OfferDisabledLink']['id']
  645. ];
  646. $md5Arr[] = $md5;
  647. }
  648. if (!empty($md5Arr)) {
  649. $savedDisableLinkData = $this->em->getDisableLinksByMd5Arr($md5Arr);
  650. foreach ($savedDisableLinkData as $key => $value) {
  651. $disableLinksMyMd5[$value['md5']] = $value;
  652. }
  653. }
  654. } else {
  655. $disableLinkData = $this->em->getDisableLinkLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $sourceIdArray, $addedFromArr, $dateStart, $dateEnd);
  656. foreach ($disableLinkData as $key => $value) {
  657. $disableLinksMyMd5[$value['md5']] = $value;
  658. $disableLinkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  659. }
  660. }
  661. $distinctOfferIdArr = [];
  662. $distinctAffiliateIdArr = [];
  663. foreach ($disableLinkData as $key => $value) {
  664. if (!in_array($value['offerId'], $distinctOfferIdArr)) {
  665. array_push($distinctOfferIdArr, $value['offerId']);
  666. }
  667. if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
  668. array_push($distinctAffiliateIdArr, $value['affiliateId']);
  669. }
  670. $disableLinkData[$key]['date_inserted'] = $value['dateInserted'];
  671. }
  672. $offerInfo = [];
  673. if (!empty($distinctOfferIdArr)) {
  674. $offerInfo = $this->getOfferInfoByKey($distinctOfferIdArr, $tuneAccount);
  675. }
  676. $advertiserList = $this->getAdvertisersListByStatusWithKeys([
  677. 'tuneAccount' => $tuneAccount
  678. ]);
  679. $affiliateList = $this->getAffiliateListByStatusWithKeys($tuneAccount);
  680. foreach ($disableLinkData as $key => $value) {
  681. if (!array_key_exists($value['offerId'], $offerInfo)) {
  682. unset($disableLinkData[$key]);
  683. continue;
  684. }
  685. $offerName = $offerInfo[$value['offerId']]['name'] ?? '';
  686. $advertiserName = array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
  687. $advertiserId = $offerInfo[$value['offerId']]['advertiserId'] ?? '';
  688. $affiliateName = array_key_exists($value['affiliateId'], $affiliateList) ? $affiliateList[$value['affiliateId']]['name'] : '';
  689. $meta = [];
  690. $addedFrom = Config::DISABLE_LINKS_FROM_HO_PANEL;
  691. if (array_key_exists($value['md5'], $disableLinksMyMd5)) {
  692. $meta = json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) != null ? json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) : [];
  693. $addedFrom = $disableLinksMyMd5[$value['md5']]['addedFrom'];
  694. }
  695. if (
  696. (!empty($addedFromArr) && !in_array($addedFrom, $addedFromArr)) ||
  697. (sizeof($advertiserArray) && !in_array($advertiserId, $advertiserArray))
  698. ) {
  699. unset($disableLinkData[$key]);
  700. continue;
  701. }
  702. $disableLinkData[$key]['affiliateName'] = $affiliateName;
  703. $disableLinkData[$key]['advertiserName'] = $advertiserName;
  704. $disableLinkData[$key]['advertiserId'] = $advertiserId;
  705. $disableLinkData[$key]['offerName'] = $offerName;
  706. $disableLinkData[$key]['addedFrom'] = $addedFrom;
  707. $disableLinkData[$key]['meta'] = $meta;
  708. }
  709. return $disableLinkData;
  710. }
  711. public function createUpdateRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  712. {
  713. $retentionOptimisationExist = $this->em->getRetentionOptimisationByParams($offerId, $goalId, $tuneAccount);
  714. if ($retentionOptimisationExist) {
  715. if ($sendAlert === null) {
  716. $sendAlert = $retentionOptimisationExist->getSendAlert();
  717. }
  718. if ($autoBlock === null) {
  719. $autoBlock = $retentionOptimisationExist->getAutoBlock();
  720. }
  721. $this->em->updateRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount);
  722. } else {
  723. $this->em->insertRetentionOptimisation($offerId, $goalId, $retentionRate, $minimumBudget, $sendAlert, $autoBlock, $tuneAccount);
  724. }
  725. }
  726. public function getRetentionOptimisationData($offerId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  727. {
  728. $retentionOptimisationData = $this->em->getRetentionOptimisation($offerId, $tuneAccount);
  729. $distinctOfferIds = [];
  730. foreach ($retentionOptimisationData as $key => $value) {
  731. if (!in_array($value['offerId'], $distinctOfferIds)) {
  732. array_push($distinctOfferIds, $value['offerId']);
  733. }
  734. }
  735. foreach ($retentionOptimisationData as $key => $value) {
  736. // $retentionOptimisationData[$key]['offerName'] = $offerInfo[$value['offerId']]['name'] ?? "";
  737. // $retentionOptimisationData[$key]['advertiserId'] = $offerInfo[$value['offerId']]['advertiserId'] ?? "";
  738. // $retentionOptimisationData[$key]['advertiserName'] = $offerInfo[$value['offerId']]['Advertiser']['company'] ?? "";
  739. // $retentionOptimisationData[$key]['advertiserName'] = array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
  740. // $retentionOptimisationData[$key]['goalName'] = $offerInfo[$value['offerId']]['Goal'][$value['goalId']]['name'] ?? "";
  741. $retentionOptimisationData[$key]['dateInserted'] = $value['dateUpdated']->format("Y-m-d H:s:i");
  742. }
  743. return array_values($retentionOptimisationData);
  744. }
  745. public function changeCamelCaseToWords($camelCaseString)
  746. {
  747. return ucfirst(implode(" ", preg_split('/(?=[A-Z])/', $camelCaseString)));
  748. }
  749. public function setOfferAffiliateCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  750. {
  751. $capExist = $this->em->getCombinationFromAffiliateOfferCapping($affiliateId, $offerId, $affiliateOfferCapType, $tuneAccount);
  752. if (!$capExist || ($capExist->getCapValue() != $capValue)) {
  753. if ($capExist) {
  754. $this->em->deleteAffiliateOfferCapById($capExist->getId());
  755. }
  756. $hoResponse = $this->brandApi->setAffiliateOfferCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount);
  757. if ($hoResponse['response']['status'] == 1) {
  758. $this->em->insertToAffiliateOfferCap($affiliateId, $offerId, $affiliateOfferCapType, $capValue, $tuneAccount);
  759. }
  760. }
  761. }
  762. public function getImpressionOptimisationData()
  763. {
  764. $impressionOptimisations = $this->em->getActiveImpressionOptimisation();
  765. foreach ($impressionOptimisations as $key => $value) {
  766. $impressionOptimisations[$key]['dateUpdated'] = $value['dateUpdated']->format("Y-m-d H:s:i");
  767. $impressionOptimisations[$key]['dateInserted'] = $value['dateInserted']->format("Y-m-d H:s:i");
  768. }
  769. return $impressionOptimisations;
  770. }
  771. public function createUpdateImpressionOptimisation($offerId, $affiliate_id, $ctr, $addedBy)
  772. {
  773. return $this->em->createUpdateImpression($offerId, $affiliate_id, $ctr, $addedBy);
  774. }
  775. public function getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd)
  776. {
  777. $fraudFlagData = [];
  778. $fraudFlagData = $this->em->getFraudFlagLogs($affiliateIdArray, $offerIdArray, $advertiserArray, $dateStart, $dateEnd);
  779. // foreach ($fraudFlagData as $key => $value) {
  780. // $fraudFlagData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  781. // }
  782. $distinctOfferIdArr = [];
  783. $distinctAffiliateIdArr = [];
  784. foreach ($fraudFlagData as $key => $value) {
  785. if (!in_array($value['offerId'], $distinctOfferIdArr)) {
  786. array_push($distinctOfferIdArr, $value['offerId']);
  787. }
  788. if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
  789. array_push($distinctAffiliateIdArr, $value['affiliateId']);
  790. }
  791. $fraudFlagData[$key]['date_inserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  792. }
  793. if (!empty($distinctOfferIdArr)) {
  794. $offerInfo = $this->brandApi->getOffersByOfferIdsArr($distinctOfferIdArr)['response']['data'];
  795. }
  796. if (!empty($distinctAffiliateIdArr)) {
  797. $affiliateInfo = $this->brandApi->getAffiliatesByAffiliateIdArr($distinctAffiliateIdArr)['response']['data'];
  798. }
  799. foreach ($fraudFlagData as $key => $value) {
  800. $offerName = $offerInfo[$value['offerId']]['Offer']['name'] ?? '';
  801. $advertiserName = $offerInfo[$value['offerId']]['Advertiser']['company'] ?? '';
  802. $advertiserId = $offerInfo[$value['offerId']]['Advertiser']['id'] ?? '';
  803. $affiliateName = $affiliateInfo[$value['affiliateId']]['Affiliate']['company'] ?? '';
  804. $fraudFlagData[$key]['affiliateName'] = $affiliateName;
  805. $fraudFlagData[$key]['advertiserName'] = $advertiserName;
  806. $fraudFlagData[$key]['advertiserId'] = $advertiserId;
  807. $fraudFlagData[$key]['offerName'] = $offerName;
  808. }
  809. return $fraudFlagData;
  810. }
  811. public function deleteFraudFlagLogs($id)
  812. {
  813. $this->em->deleteFraudFlagLogs($id);
  814. }
  815. public function blockOfferForAffiliate($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  816. {
  817. $combinationExist = $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->findOneBy([
  818. 'offerId' => $offerId,
  819. 'affiliateId' => $affiliateId,
  820. 'trackingAccount' => $trackingAccount
  821. ]);
  822. $affiliateOfferBlockedInHO = $this->brandApi->getAffiliateOfferBlock($offerId, $affiliateId, $trackingAccount)['response']['data']['data'];
  823. if (array_key_exists($offerId, $affiliateOfferBlockedInHO) && $affiliateOfferBlockedInHO[$offerId]['OfferAffiliateBlock']['affiliate_id'] == $affiliateId && !$combinationExist) {
  824. return false;
  825. }
  826. if (!$combinationExist) {
  827. if ($blockType === Config::AFFILIATE_OFFER_BLOCK_MACRO) {
  828. $hoResponse = $this->brandApi->blockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
  829. } elseif ($blockType === Config::AFFILIATE_OFFER_UNBLOCK_MACRO) {
  830. $hoResponse = $this->brandApi->unblockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
  831. }
  832. if (isset($hoResponse['response']['status']) && $hoResponse['response']['status'] == 1) {
  833. $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->insertToOfferAffiliateBlock($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount);
  834. // Removing dump from mysql and added dump of AffiliateOfferBlock to mongo
  835. // $this->doctrine->getRepository('App\Entity\AffiliateOfferBlockLogs')->insertToOfferAffiliateBlockLogs($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount);
  836. return true;
  837. }
  838. }
  839. return false;
  840. }
  841. public function deleteOfferAffiliateBlock($offerId, $affiliateId, $trackingAccount)
  842. {
  843. $hoResponse = $this->brandApi->unblockOfferAffiliate($offerId, $affiliateId, $trackingAccount);
  844. if ($hoResponse['response']['status'] == 1) {
  845. $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->deleteOfferAffiliateBlock($offerId, $affiliateId, $trackingAccount);
  846. }
  847. }
  848. public function populateDbByOfferId($offerId, $metaData = [])
  849. {
  850. $calledFromCronJob = $metaData['calledFromCronJob'] ?? true;
  851. $tuneAccount = $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  852. $offerExistInDB = $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->findOneBy([
  853. 'offerId' => $offerId,
  854. 'tuneAccount' => $tuneAccount
  855. ]);
  856. $offerInfo[$offerId] = $this->brandApi->getOfferByOfferId($offerId, $tuneAccount)['response']['data'];
  857. $offerIpWhitelistHoData = $this->brandApi->getIpWhitelistByOfferId($offerId, $tuneAccount)['response']['data'];
  858. $offerFileCreativesHoData = $this->brandApi->getOfferFilesByOfferId($offerId, $tuneAccount);
  859. $offerIpWhitelistArray = [];
  860. foreach ($offerIpWhitelistHoData as $key => $value) {
  861. if ($value['OfferWhitelist']['type'] == Config::OFFER_IP_WHITELIST_TYPE_POSTBACK) {
  862. array_push($offerIpWhitelistArray, $value['OfferWhitelist']['content']);
  863. }
  864. }
  865. $offerCountryIdArray = isset($offerInfo[$offerId]['Country']) ? array_keys($offerInfo[$offerId]['Country']) : [];
  866. $offerCategoryIdArray = isset($offerInfo[$offerId]['OfferCategory']) ? array_keys($offerInfo[$offerId]['OfferCategory']) : [];
  867. $offerTagIdArray = isset($offerInfo[$offerId]['OfferTag']) ? array_keys($offerInfo[$offerId]['OfferTag']) : [];
  868. $offerGoalArray = isset($offerInfo[$offerId]['Goal']) ? array_values($offerInfo[$offerId]['Goal']) : [];
  869. foreach ($offerGoalArray as $key => $value) {
  870. foreach ($value as $k => $v) {
  871. $offerGoalArray[$key][lcfirst(implode('', array_map('ucfirst', explode('_', $k))))] = $v;
  872. if ($this->checkForString($k, '_')) {
  873. unset($offerGoalArray[$key][$k]);
  874. }
  875. }
  876. }
  877. if ($offerExistInDB) {
  878. $offerDataToUpdate = [];
  879. foreach ($offerInfo[$offerId]['Offer'] as $key => $value) {
  880. $appId = $this->scraper->getAppId($offerInfo[$offerId]['Offer']['preview_url']);
  881. if (!$appId) {
  882. $appId = 'Not Found';
  883. }
  884. $offerDataToUpdate['appId'] = $appId;
  885. $offerDataToUpdate[lcfirst(implode('', array_map('ucfirst', explode('_', $key))))] = $value;
  886. }
  887. $offerDataToUpdate['geoIdsJson'] = json_encode($offerCountryIdArray);
  888. $offerDataToUpdate['categoryIdsJson'] = json_encode($offerCategoryIdArray);
  889. $offerDataToUpdate['tagIdsJson'] = json_encode($offerTagIdArray);
  890. // $offerDataToUpdate['whitelistIpsJson'] = json_encode($offerIpWhitelistArray);
  891. if ($offerInfo[$offerId]['Thumbnail'] && isset($offerInfo[$offerId]['Thumbnail']['preview_uri'])) {
  892. $offerDataToUpdate['thumbnail'] = $offerInfo[$offerId]['Thumbnail']['preview_uri'];
  893. }
  894. $this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId, $offerDataToUpdate, $tuneAccount);
  895. } else {
  896. $offerValue = $offerInfo[$offerId];
  897. $domain = $offerInfo[$offerId]['Hostname']['domain'] ?? '';
  898. $appId = $this->scraper->getAppId($offerValue['Offer']['preview_url']);
  899. if (!$appId) {
  900. $appId = 'Not Found';
  901. }
  902. $offerValue['Offer']['app_id'] = $appId;
  903. if (!$offerValue['Offer']['advertiser_id']) {
  904. $offerValue['Offer']['advertiser_id'] = 0;
  905. }
  906. $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, null);
  907. }
  908. $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
  909. foreach ($offerGoalArray as $key => $value) {
  910. $goalExistInDB = $this->doctrine->getRepository(OfferGoalsInfo::class)->findOneBy(['goalId' => $value['id'], 'tuneAccount' => $tuneAccount]);
  911. if ($goalExistInDB) {
  912. $this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($value['id'], $value, $tuneAccount);
  913. } else {
  914. $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);
  915. }
  916. }
  917. if ($calledFromCronJob) {
  918. $this->scraper->getAppDetailsByPreviewUrl($offerInfo[$offerId]['Offer']['preview_url']);
  919. if (is_array($offerTagIdArray)) {
  920. $this->doctrine->getRepository(OfferTagRelationship::class)->deleteOfferTagRelationByOfferId($offerId, $tuneAccount);
  921. foreach ($offerTagIdArray as $tagId) {
  922. $this->doctrine->getRepository(OfferTagRelationship::class)->insertToOfferTagRelationship($offerId, $tagId, $tuneAccount);
  923. }
  924. }
  925. if (is_array($offerCategoryIdArray)) {
  926. $this->doctrine->getRepository(OfferCategoryRelationship::class)->deleteOfferCategoryRelationByOfferId($offerId, $tuneAccount);
  927. foreach ($offerCategoryIdArray as $categoryId) {
  928. $this->doctrine->getRepository(OfferCategoryRelationship::class)->insertToOfferCategoryRelationship($offerId, $categoryId, $tuneAccount);
  929. }
  930. }
  931. if (is_array($offerCountryIdArray)) {
  932. $this->doctrine->getRepository(OfferGeoRelationship::class)->deleteOfferGeoRelationByOfferId($offerId, $tuneAccount);
  933. foreach ($offerCountryIdArray as $geo) {
  934. $this->doctrine->getRepository(OfferGeoRelationship::class)->insertToOfferGeoRelationship($offerId, $geo, $tuneAccount);
  935. }
  936. }
  937. }
  938. if (!$calledFromCronJob) {
  939. $offerWhitelistIdArrFromHO = [];
  940. foreach ($offerIpWhitelistHoData as $key => $value) {
  941. $value = $value['OfferWhitelist'];
  942. $value['tuneAccount'] = $tuneAccount;
  943. $offerWhitelistExist = $this->doctrine->getRepository(OfferWhitelist::class)->findOneBy(['whitelistId' => $value['id'], 'tuneAccount' => $tuneAccount]);
  944. if (!$offerWhitelistExist) {
  945. $this->doctrine->getRepository(OfferWhitelist::class)->insertToOfferWhitelist($value['id'], $value['offer_id'], $value['type'], $value['content_type'], $value['content'], $tuneAccount);
  946. } else {
  947. $this->doctrine->getRepository(OfferWhitelist::class)->updateOfferWhitelistByWhitelistId($value['id'], $value, $tuneAccount);
  948. }
  949. array_push($offerWhitelistIdArrFromHO, $value['id']);
  950. }
  951. if (sizeof($offerWhitelistIdArrFromHO)) {
  952. $offerWhitelistToBeDeleted = $this->doctrine->getRepository(OfferWhitelist::class)->getDeletedOfferWhitelistIds($offerId, $offerWhitelistIdArrFromHO, $tuneAccount);
  953. foreach ($offerWhitelistToBeDeleted as $key => $value) {
  954. $this->doctrine->getRepository(OfferWhitelist::class)->deleteByWhitelistId($value['whitelistId'], $tuneAccount);
  955. }
  956. }
  957. foreach ($offerFileCreativesHoData as $key => $value) {
  958. $fileExist = $this->doctrine->getRepository(OfferCreativeFile::class)->findOneBy(['fileId' => $key, 'tuneAccount' => $tuneAccount]);
  959. if (isset($value['OfferFile'])) {
  960. if (!$fileExist) {
  961. $response = $value['OfferFile'];
  962. if ($response['status'] == Config::DELETED_STATUS || $response['status'] == Config::PENDING_STATUS) {
  963. continue;
  964. }
  965. $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);
  966. } elseif ($fileExist->getStatus() != $value['OfferFile']['status']) {
  967. $this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($value['OfferFile']['id'], $value['OfferFile']['status'], $tuneAccount);
  968. }
  969. }
  970. }
  971. }
  972. }
  973. public function updateOffer($offerId, $offerDetails, $offerCountries, $offerCategories, $offerTags, $offerWhitelistIps, $tuneAccount)
  974. {
  975. $offerCreateHoResponse = $this->brandApi->createOrUpdateOffer($offerId, $offerDetails, $tuneAccount);
  976. if ($offerCreateHoResponse['response']['status'] === 1) {
  977. $offerInfo = $offerCreateHoResponse['response']['data']['Offer'];
  978. $offerId = $offerInfo['id'];
  979. $this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId, $offerDetails, $tuneAccount);
  980. $this->updateOfferCountries($offerId, $offerCountries, $tuneAccount);
  981. $this->updateOfferCategories($offerId, $offerCategories, $tuneAccount);
  982. $this->updateOfferTags($offerId, $offerTags, $tuneAccount);
  983. $this->updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount);
  984. $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
  985. }
  986. return $offerCreateHoResponse;
  987. }
  988. public function createNewOffer($offerDetails, $offerCountries, $offerCategories, $offerTags, $offerWhitelistIps, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  989. {
  990. $offerCreateHoResponse = $this->brandApi->createOrUpdateOffer(null, $offerDetails, $tuneAccount);
  991. if ($offerCreateHoResponse['response']['status'] === 1) {
  992. $offerInfo = $offerCreateHoResponse['response']['data']['Offer'];
  993. $offerId = $offerInfo['id'];
  994. $appId = $this->scraper->getAppId($offerInfo['preview_url']);
  995. if (!$appId) {
  996. $appId = 'Not Found';
  997. }
  998. $offerInfo['app_id'] = $appId;
  999. $this->doctrine->getRepository('App\Entity\Tune\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, null);
  1000. $this->updateOfferCountries($offerId, $offerCountries, $tuneAccount);
  1001. $this->updateOfferCategories($offerId, $offerCategories, $tuneAccount);
  1002. $this->updateOfferTags($offerId, $offerTags, $tuneAccount);
  1003. $this->updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount);
  1004. $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount, $offerId);
  1005. $appDetails = $this->scraper->getAppDetailsByPreviewUrl($offerInfo['preview_url']);
  1006. if ($appDetails) {
  1007. $fileResponse = $this->uploadFile($offerId, $appDetails['icon'], Config::FILE_TYPE_THUMBNAIL, 0);
  1008. if ($fileResponse['response']['status'] == 1) {
  1009. $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->updateOfferByOfferId($offerId, ['thumbnail' => $fileResponse['response']['data']['OfferFile']['url']], $tuneAccount);
  1010. }
  1011. }
  1012. }
  1013. return $offerCreateHoResponse;
  1014. }
  1015. public function updateOfferCountries($offerId, $offerCountries, $tuneAccount)
  1016. {
  1017. $savedOfferInfo = $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->findOneBy(['offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
  1018. $savedGeos = json_decode($savedOfferInfo->getGeoIdsJson(), true);
  1019. foreach ($savedGeos as $geo) {
  1020. if (!in_array($geo, $offerCountries)) {
  1021. $this->brandApi->removeGeoFromOffer($offerId, $geo, $tuneAccount);
  1022. }
  1023. }
  1024. foreach ($offerCountries as $geo) {
  1025. $this->brandApi->addGeoToOffer($offerId, $geo, $tuneAccount);
  1026. }
  1027. $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->updateOfferByOfferId($offerId, ['geoIdsJson' => json_encode($offerCountries)], $tuneAccount);
  1028. }
  1029. public function updateOfferCategories($offerId, $offerCategories, $tuneAccount)
  1030. {
  1031. if (is_array($offerCategories) && count($offerCategories) > 0) {
  1032. $this->brandApi->setCategoryToOffer($offerId, $offerCategories, $tuneAccount);
  1033. $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->updateOfferByOfferId($offerId, ['categoryIdsJson' => json_encode($offerCategories)], $tuneAccount);
  1034. }
  1035. }
  1036. public function updateOfferTags($offerId, $offerTags, $tuneAccount)
  1037. {
  1038. if (is_array($offerTags) && count($offerTags) > 0) {
  1039. foreach ($offerTags as $tagId) {
  1040. $this->brandApi->addTagToOffer($offerId, $tagId, $tuneAccount);
  1041. }
  1042. $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->updateOfferByOfferId($offerId, ['tagIdsJson' => json_encode($offerTags)], $tuneAccount);
  1043. }
  1044. }
  1045. public function updateOfferWhitelist($offerId, $offerWhitelistIps, $tuneAccount)
  1046. {
  1047. if (is_array($offerWhitelistIps) && count($offerWhitelistIps) > 0) {
  1048. foreach ($offerWhitelistIps as $whitelistIp) {
  1049. $this->brandApi->addIpWhitelistToOffer($offerId, $whitelistIp, Config::OFFER_IP_WHITELIST_CONTENT_TYPE_IP_ADDRESS, Config::OFFER_IP_WHITELIST_TYPE_POSTBACK, $tuneAccount);
  1050. }
  1051. // echo json_encode($offerWhitelistIps);
  1052. // $this->doctrine->getRepository('App\Entity\Tune\OfferInfo')->updateOfferByOfferId($offerId, ['whitelistIpsJson' => json_encode($offerWhitelistIps)], $tuneAccount);
  1053. }
  1054. }
  1055. public function updateOfferGoal($goalId, $offerGoalDetails, $tuneAccount)
  1056. {
  1057. if (isset($offerGoalDetails['goal_id'])) {
  1058. unset($offerGoalDetails['goal_id']);
  1059. }
  1060. $offerGoalCreateHoResponse = $this->brandApi->createOrUpdateOfferGoal($goalId, $offerGoalDetails, $tuneAccount);
  1061. if ($offerGoalCreateHoResponse['response']['status'] === 1) {
  1062. $dataToUpdate = [];
  1063. foreach ($offerGoalCreateHoResponse['response']['data']['Goal'] as $key => $value) {
  1064. if ($key === 'id') {
  1065. continue;
  1066. }
  1067. $dataToUpdate[$this->convertStringFromSnakeCaseToCamelCase($key)] = $value;
  1068. }
  1069. $this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($goalId, $dataToUpdate, $tuneAccount);
  1070. }
  1071. return $offerGoalCreateHoResponse;
  1072. }
  1073. public function createNewOfferGoal($offerGoalDetails, $tuneAccount)
  1074. {
  1075. $offerGoalCreateHoResponse = $this->brandApi->createOrUpdateOfferGoal(null, $offerGoalDetails, $tuneAccount);
  1076. if ($offerGoalCreateHoResponse['response']['status'] === 1) {
  1077. $offerGoalCreateHoResponseData = $offerGoalCreateHoResponse['response']['data']['Goal'];
  1078. $this->doctrine->getRepository(OfferGoalsInfo::class)->insertToOfferGoalsInfo(
  1079. $offerGoalCreateHoResponseData['id'],
  1080. $offerGoalCreateHoResponseData['offer_id'],
  1081. $offerGoalCreateHoResponseData['name'],
  1082. $offerGoalCreateHoResponseData['description'],
  1083. $offerGoalCreateHoResponseData['status'],
  1084. $offerGoalCreateHoResponseData['is_private'],
  1085. $offerGoalCreateHoResponseData['payout_type'],
  1086. $offerGoalCreateHoResponseData['default_payout'],
  1087. $offerGoalCreateHoResponseData['revenue_type'],
  1088. $offerGoalCreateHoResponseData['max_payout'],
  1089. $offerGoalCreateHoResponseData['tiered_payout'],
  1090. $offerGoalCreateHoResponseData['tiered_revenue'],
  1091. $offerGoalCreateHoResponseData['use_payout_groups'],
  1092. $offerGoalCreateHoResponseData['use_revenue_groups'],
  1093. $offerGoalCreateHoResponseData['advertiser_id'],
  1094. $offerGoalCreateHoResponseData['protocol'],
  1095. $offerGoalCreateHoResponseData['allow_multiple_conversions'],
  1096. $offerGoalCreateHoResponseData['approve_conversions'],
  1097. $offerGoalCreateHoResponseData['enforce_encrypt_tracking_pixels'],
  1098. $offerGoalCreateHoResponseData['is_end_point'],
  1099. $offerGoalCreateHoResponseData['ref_id'],
  1100. $tuneAccount
  1101. );
  1102. }
  1103. return $offerGoalCreateHoResponse;
  1104. }
  1105. public function uploadFile($offerId, $fileUrlToUpload, $creativeType, $isPrivate)
  1106. {
  1107. $fileData = @file_get_contents($fileUrlToUpload);
  1108. $fileExtension = pathinfo($fileUrlToUpload, PATHINFO_EXTENSION);
  1109. $fileName = $fileExtension === '' ? $offerId . "_" . basename($fileUrlToUpload) . '.png' : $offerId . "_" . basename($fileUrlToUpload);
  1110. file_put_contents($fileName, $fileData);
  1111. $fileResponse = $this->brandApi->offerFileAPI($offerId, $creativeType, $fileName, $fileName, $isPrivate);
  1112. unlink($fileName);
  1113. return $fileResponse;
  1114. }
  1115. public function convertStringFromCamelCaseToSnakeCase($input)
  1116. {
  1117. preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
  1118. $ret = $matches[0];
  1119. foreach ($ret as &$match) {
  1120. $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
  1121. }
  1122. return implode('_', $ret);
  1123. }
  1124. public function convertStringFromSnakeCaseToCamelCase($input)
  1125. {
  1126. return lcfirst(implode('', array_map('ucfirst', explode('_', $input))));
  1127. }
  1128. public function getScraper()
  1129. {
  1130. return $this->scraper;
  1131. }
  1132. public function getOfferListByOfferIdArr($offerIdArr)
  1133. {
  1134. $response = [];
  1135. if ($offerIdArr) {
  1136. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
  1137. foreach ($offerInfo as $key => $value) {
  1138. $response[$value['offerId']] = [
  1139. 'id' => (int)$value['offerId'],
  1140. 'name' => $value['name']
  1141. ];
  1142. }
  1143. }
  1144. return $response;
  1145. }
  1146. public function checkOfferAffiliateCapping($offerId, $affiliateId, $goalId)
  1147. {
  1148. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->getOfferDataByOfferId($offerId);
  1149. if (!$offerInfo) {
  1150. return false;
  1151. }
  1152. $conversionCapByOfferIdHOData = $this->brandApi->getCappingByOfferId($offerId)['response']['data'];
  1153. $conversionCap = $offerInfo->getConversionCap();
  1154. $payoutCap = $offerInfo->getPayoutCap();
  1155. $revenueCap = $offerInfo->getRevenueCap();
  1156. $monthlyConversionCap = $offerInfo->getMonthlyConversionCap();
  1157. $monthlyPayoutCap = $offerInfo->getMonthlyPayoutCap();
  1158. $monthlyRevenueCap = $offerInfo->getMonthlyRevenueCap();
  1159. foreach ($conversionCapByOfferIdHOData as $key => $value) {
  1160. if ($value['OfferConversionCap']['offer_id'] == $offerId && $value['OfferConversionCap']['affiliate_id'] == $affiliateId) {
  1161. $conversionCap = $value['OfferConversionCap']['conversion_cap'];
  1162. $payoutCap = $value['OfferConversionCap']['payout_cap'];
  1163. $revenueCap = $value['OfferConversionCap']['revenue_cap'];
  1164. $monthlyConversionCap = $value['OfferConversionCap']['monthly_conversion_cap'];
  1165. $monthlyPayoutCap = $value['OfferConversionCap']['monthly_payout_cap'];
  1166. $monthlyRevenueCap = $value['OfferConversionCap']['monthly_revenue_cap'];
  1167. break;
  1168. }
  1169. }
  1170. $dailyConversionGenerated = 0;
  1171. $dailyPayoutGenerated = 0;
  1172. $dailyRevenueGenerated = 0;
  1173. $monthlyConversionGenerated = 0;
  1174. $monthlyPayoutGenerated = 0;
  1175. $monthlyRevenueGenerated = 0;
  1176. $statByDay = $this->brandApi->getStatsForCappingCheck($offerId, $affiliateId, $goalId, true, false)['response']['data']['data'];
  1177. if (!empty($statByDay)) {
  1178. $dailyConversionGenerated = $statByDay[0]['Stat']['conversions'];
  1179. $dailyPayoutGenerated = $statByDay[0]['Stat']['payout'];
  1180. $dailyRevenueGenerated = $statByDay[0]['Stat']['revenue'];
  1181. }
  1182. $statByMonth = $this->brandApi->getStatsForCappingCheck($offerId, $affiliateId, $goalId, false, true)['response']['data']['data'];
  1183. if (!empty($statByMonth) && isset($statByDay[0])) {
  1184. $monthlyConversionGenerated = $statByDay[0]['Stat']['conversions'];
  1185. $monthlyPayoutGenerated = $statByDay[0]['Stat']['payout'];
  1186. $monthlyRevenueGenerated = $statByDay[0]['Stat']['revenue'];
  1187. }
  1188. $conversionCapReached = $dailyConversionGenerated >= $conversionCap && $conversionCap != 0;
  1189. $payoutCapReached = $dailyPayoutGenerated >= $payoutCap && $payoutCap != 0;
  1190. $revenueCapReached = $dailyRevenueGenerated >= $revenueCap && $revenueCap != 0;
  1191. $monthlyConversionCapReached = $monthlyConversionGenerated >= $monthlyConversionCap && $monthlyConversionCap != 0;
  1192. $monthlyPayoutCapReached = $monthlyPayoutGenerated >= $monthlyPayoutCap && $monthlyPayoutCap != 0;
  1193. $monthlyRevenueCapReached = $monthlyRevenueGenerated >= $monthlyRevenueCap && $monthlyRevenueCap != 0;
  1194. $cappingReached = false;
  1195. if ($conversionCapReached || $payoutCapReached || $revenueCapReached || $monthlyConversionCapReached || $monthlyPayoutCapReached || $monthlyRevenueCapReached) {
  1196. $cappingReached = true;
  1197. }
  1198. return [
  1199. 'conversionCap' => $conversionCap,
  1200. 'payoutCap' => $payoutCap,
  1201. 'revenueCap' => $revenueCap,
  1202. 'monthlyConversionCap' => $monthlyConversionCap,
  1203. 'monthlyPayoutCap' => $monthlyPayoutCap,
  1204. 'monthlyRevenueCap' => $monthlyRevenueCap,
  1205. 'dailyConversionGenerated' => $dailyConversionGenerated,
  1206. 'dailyPayoutGenerated' => $dailyPayoutGenerated,
  1207. 'dailyRevenueGenerated' => $dailyRevenueGenerated,
  1208. 'monthlyConversionGenerated' => $monthlyConversionGenerated,
  1209. 'monthlyPayoutGenerated' => $monthlyPayoutGenerated,
  1210. 'monthlyRevenueGenerated' => $monthlyRevenueGenerated,
  1211. 'conversionCapReached' => $conversionCapReached,
  1212. 'payoutCapReached' => $payoutCapReached,
  1213. 'revenueCapReached' => $revenueCapReached,
  1214. 'monthlyConversionCapReached' => $monthlyConversionCapReached,
  1215. 'monthlyPayoutCapReached' => $monthlyPayoutCapReached,
  1216. 'monthlyRevenueCapReached' => $monthlyRevenueCapReached,
  1217. 'cappingReached' => $cappingReached
  1218. ];
  1219. }
  1220. public function appsBlackAndWhiteList($data)
  1221. {
  1222. $dateRange = 30;
  1223. $minClicks = 100;
  1224. $dataToProcess = [];
  1225. foreach ($data as $key => $value) {
  1226. $value['offerId'] ? $dataToProcess['offer'][$value['offerId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1227. $value['advertiserId'] ? $dataToProcess['advertiser'][$value['advertiserId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1228. $value['affiliateId'] ? $dataToProcess['affiliate'][$value['affiliateId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1229. }
  1230. $dataToBlock = [];
  1231. foreach ($dataToProcess as $entityType => $entity) {
  1232. foreach ($entity as $entityId => $entityData) {
  1233. foreach ($entityData as $param => $paramData) {
  1234. $advertiserId = $entityType == 'advertiser' ? $entityId : null;
  1235. $affiliateId = $entityType == 'affiliate' ? $entityId : null;
  1236. $offerId = $entityType == 'offer' ? $entityId : null;
  1237. if ($advertiserId) {
  1238. $addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_ADVERTISER;
  1239. } elseif ($affiliateId) {
  1240. $addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_AFFILIATE;
  1241. } else {
  1242. $addedFrom = Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_OFFER;
  1243. }
  1244. if ($advertiserId == null && $affiliateId == null && $offerId == null) {
  1245. continue;
  1246. }
  1247. $statData = $this->brandApi->getStatsForAppBlackAndWhiteList($offerId, $affiliateId, $advertiserId, $dateRange, $minClicks, $param)['response']['data']['data'];
  1248. foreach ($paramData as $listType => $appIds) {
  1249. foreach ($statData as $key => $value) {
  1250. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['Stat']['offer_id']]);
  1251. if (
  1252. !$offerInfo ||
  1253. !in_array($offerInfo->getAppId(), $appIds)
  1254. ) {
  1255. continue;
  1256. }
  1257. $temp = [
  1258. 'offerId' => $value['Stat']['offer_id'],
  1259. 'affiliateId' => $value['Stat']['affiliate_id'],
  1260. 'advertiserId' => $value['Stat']['advertiser_id'],
  1261. 'param' => $param,
  1262. 'paramValue' => $value['Stat'][$param],
  1263. 'clicks' => $value['Stat']['clicks'],
  1264. 'conversions' => $value['Stat']['conversions'],
  1265. 'addedFrom' => $addedFrom,
  1266. 'listType' => $listType
  1267. ];
  1268. if (array_key_exists('blacklist', $paramData) && in_array($value['Stat'][$param], $paramData['blacklist'])) {
  1269. $dataToBlock[] = $temp;
  1270. }
  1271. if (array_key_exists('whitelist', $paramData) && !in_array($value['Stat'][$param], $paramData['whitelist'])) {
  1272. $dataToBlock[] = $temp;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. return $dataToBlock;
  1280. }
  1281. public function setAffiliateOfferApproval($offerId, $affiliateId, $status, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1282. {
  1283. $combinationExist = $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($offerId, $affiliateId, $tuneAccount);
  1284. if ($combinationExist && $combinationExist->getApprovalStatus() != $status) {
  1285. $hoResponse = $this->brandApi->setOfferApprovalForAffiliate($offerId, $affiliateId, $status, $tuneAccount);
  1286. if ($hoResponse['response']['status'] == 1) {
  1287. $this->doctrine->getRepository(AffiliateOfferApproval::class)->updateAffiliateOfferApprovalById($combinationExist->getId(), [
  1288. 'approvalStatus' => $status
  1289. ]);
  1290. }
  1291. } elseif (!$combinationExist) {
  1292. $hoResponse = $this->brandApi->setOfferApprovalForAffiliate($offerId, $affiliateId, $status, $tuneAccount);
  1293. if ($hoResponse['response']['status'] == 1) {
  1294. $this->doctrine->getRepository(AffiliateOfferApproval::class)->insertToAffiliateOfferApproval(null, $affiliateId, null, $offerId, null, null, null, $status, null, null, $tuneAccount);
  1295. }
  1296. }
  1297. }
  1298. public function disableLinkByExternalUrl($offerId, $advertiserId, $affiliateId, $source, $affSub2, $affSub3, $affSub5)
  1299. {
  1300. $stat = [
  1301. 'offerId' => $offerId,
  1302. 'advertiserId' => $advertiserId,
  1303. 'affiliateId' => $affiliateId,
  1304. 'source' => $source,
  1305. 'affSub2' => $affSub2,
  1306. 'affSub3' => $affSub3,
  1307. 'affSub5' => $affSub5
  1308. ];
  1309. $link = Config::DISABLE_LINK_EXTERNAL_ENDPOINT . '?token=' . base64_encode(json_encode($stat));
  1310. return $link;
  1311. }
  1312. public function getOfferInfoByKey($offerIdArr, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1313. {
  1314. if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
  1315. return [];
  1316. }
  1317. $offerData = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr, $tuneAccount);
  1318. $offerInfo = [];
  1319. foreach ($offerData as $key => $value) {
  1320. $offerInfo[$value['offerId']] = $value;
  1321. }
  1322. return $offerInfo;
  1323. }
  1324. public function getMafoOfferInfoByKey($offerIdArr)
  1325. {
  1326. if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
  1327. return [];
  1328. }
  1329. $offerData = $this->doctrine->getRepository(MafoOffers::class)->getMafoOffersByOfferIdsArr($offerIdArr);
  1330. $offerInfo = [];
  1331. foreach ($offerData as $key => $value) {
  1332. $offerInfo[$value['id']] = $value;
  1333. }
  1334. return $offerInfo;
  1335. }
  1336. public function getEmployeesByEmployeeId()
  1337. {
  1338. $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
  1339. if (!$cachedList) {
  1340. $employeeList = $this->getWarmedUpEmployeesByEmployeeId();
  1341. } else {
  1342. $employeeList = json_decode($cachedList, true);
  1343. }
  1344. ksort($employeeList);
  1345. return $employeeList;
  1346. }
  1347. public function getWarmedUpEmployeesByEmployeeId()
  1348. {
  1349. $employeesData = $this->doctrine->getRepository(Employees::class)->getEmployees();
  1350. $data = [];
  1351. foreach ($employeesData as $key => $value) {
  1352. $data[$value['employeeId']] = [
  1353. 'firstName' => $value['firstName'],
  1354. 'lastName' => $value['lastName'],
  1355. 'email' => $value['email'],
  1356. 'fullName' => $value['fullName']
  1357. ];
  1358. }
  1359. return $data;
  1360. }
  1361. public function getMd5ForMmpReport($advertiser, $offerCountry, $offerRegion, $offerCity, $appId, $event, $revenueModel, $payoutModel)
  1362. {
  1363. return md5(strtolower($advertiser) . '#' . strtolower($offerCountry) . '#' . strtolower($offerRegion) . '#' . strtolower($offerCity) . '#' . strtolower($appId) . '#' . strtolower($event) . '#' . strtolower($revenueModel) . '#' . strtolower($payoutModel));
  1364. }
  1365. public function updateAffiliateDBByIds($affiliateIds, $metaData)
  1366. {
  1367. $createApiKeyIfNotExist = $metaData['createApiKeyIfNotExist'] ?? false;
  1368. $tuneAccount = $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1369. $affiliateInfoArr = $this->brandApi->getAffiliateInfoByAffiliateIdsArr($affiliateIds, $tuneAccount)['response']['data'];
  1370. foreach ($affiliateInfoArr as $key => $value) {
  1371. $affiliateDBInfo = $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1372. if ($affiliateDBInfo) {
  1373. $this->doctrine->getRepository(AffiliateInfo::class)->updateAffiliateInfoByAffiliateId($value['Affiliate']['id'], [
  1374. 'status' => $value['Affiliate']['status'],
  1375. 'accountManagerId' => $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null,
  1376. 'company' => $value['Affiliate']['company']
  1377. ], $tuneAccount);
  1378. } else {
  1379. $this->doctrine->getRepository(AffiliateInfo::class)->insertToAffiliateInfo($value['Affiliate']['id'], $value['Affiliate']['company'], $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null, $value['Affiliate']['status'], $tuneAccount);
  1380. }
  1381. // $this->mafoObjectsComponents->createOrUpdateAffiliate(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Affiliate']['id']);
  1382. // $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
  1383. // exec($execCommand);
  1384. if ($value['AffiliateUser'] !== null) {
  1385. foreach ($value['AffiliateUser'] as $k => $v) {
  1386. if ($v['status'] == Config::ACTIVE_STATUS) {
  1387. if ($createApiKeyIfNotExist) {
  1388. $apiKeyData = $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1389. if (!$apiKeyData) {
  1390. $this->brandApi->generateApiKeyByUserId($k, $tuneAccount);
  1391. }
  1392. }
  1393. $userApiData = $this->brandApi->getUserApiKey($k)['response']['data'];
  1394. if ($userApiData) {
  1395. $userApiKey = $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['userId' => $k, 'tuneAccount' => $tuneAccount]);
  1396. if ($userApiKey) {
  1397. $this->doctrine->getRepository(UserApiKey::class)->updateUserApiKeyByUserId($k, [
  1398. 'affiliateId' => $value['Affiliate']['id'],
  1399. 'userType' => $userApiData['user_type'],
  1400. 'apiKey' => $userApiData['api_key'],
  1401. 'apiKeyStatus' => $userApiData['status'],
  1402. 'userStatus' => $v['status']
  1403. ], $tuneAccount);
  1404. } else {
  1405. $this->doctrine->getRepository(UserApiKey::class)->insertToUserApiKey($value['Affiliate']['id'], $k, $userApiData['user_type'], $userApiData['api_key'], $userApiData['status'], $v['status'], $tuneAccount);
  1406. }
  1407. }
  1408. }
  1409. }
  1410. }
  1411. if ($value['AccountManager'] !== null) {
  1412. $affiliateAccountManagerDBInfo = $this->doctrine->getRepository(AffiliateAccountManager::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1413. if ($affiliateAccountManagerDBInfo) {
  1414. $this->doctrine->getRepository(AffiliateAccountManager::class)->updateDataByAffiliateId($value['Affiliate']['id'], [
  1415. 'employeeId' => $value['AccountManager']['id'],
  1416. 'email' => $value['AccountManager']['email'],
  1417. 'firstName' => $value['AccountManager']['first_name'],
  1418. 'lastName' => $value['AccountManager']['last_name'],
  1419. 'status' => $value['AccountManager']['status'],
  1420. ], $tuneAccount);
  1421. } else {
  1422. $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);
  1423. }
  1424. }
  1425. $affiliateTagRelationship = $this->brandApi->getAffiliateTagRelationByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1426. if ($affiliateTagRelationship['response']['status'] == 1) {
  1427. $affiliateTags = [];
  1428. foreach ($affiliateTagRelationship['response']['data']['data'] as $k => $v) {
  1429. !in_array($v['AffiliatesTags']['tag_id'], $affiliateTags) ? array_push($affiliateTags, $v['AffiliatesTags']['tag_id']) : false;
  1430. }
  1431. $affiliateDBTagsData = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1432. $affiliateDBTags = [];
  1433. foreach ($affiliateDBTagsData as $k => $v) {
  1434. !in_array($v['tagId'], $affiliateDBTags) ? array_push($affiliateDBTags, $v['tagId']) : false;
  1435. }
  1436. if ($affiliateDBTags != $affiliateTags) {
  1437. $this->doctrine->getRepository(AffiliateTagRelationship::class)->deleteAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1438. foreach ($affiliateTags as $affiliateTag) {
  1439. $this->doctrine->getRepository(AffiliateTagRelationship::class)->insertToAffiliateTagRelationship($affiliateTag, $value['Affiliate']['id'], $tuneAccount);
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. public function updateAdvertiserDBById($advertiserId, $metaData, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1446. {
  1447. $this->updateAdvertiserDBByIds([$advertiserId], $tuneAccount);
  1448. if ($this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId, 'tuneAccount' => $tuneAccount])) {
  1449. $advertiserDiscountType = $metaData['advertiserDiscountType'] ?? Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
  1450. $advertiserDiscountValue = $metaData['advertiserDiscountValue'] ?? null;
  1451. if ($advertiserDiscountValue < 1 || $advertiserDiscountValue > 100) {
  1452. $advertiserDiscountType = Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
  1453. $advertiserDiscountValue = null;
  1454. }
  1455. $this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($advertiserId, [
  1456. 'discountValue' => $advertiserDiscountType !== Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT ? $advertiserDiscountValue : 0,
  1457. 'discountType' => $advertiserDiscountType,
  1458. ], $tuneAccount);
  1459. }
  1460. }
  1461. public function updateAdvertiserDBByIds($advertiserIds, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1462. {
  1463. $advertiserInfoArr = $this->brandApi->getAdvertiserInfoByAdvertiserIdsArr($advertiserIds, $tuneAccount)['response']['data'];
  1464. foreach ($advertiserInfoArr as $key => $value) {
  1465. $advertiserDBInfo = $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy([
  1466. 'advertiserId' => $value['Advertiser']['id'],
  1467. 'tuneAccount' => $tuneAccount
  1468. ]);
  1469. if ($advertiserDBInfo) {
  1470. $this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($value['Advertiser']['id'], [
  1471. 'status' => $value['Advertiser']['status'],
  1472. 'accountManagerId' => $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null,
  1473. 'company' => $value['Advertiser']['company']
  1474. ], $tuneAccount);
  1475. } else {
  1476. $this->doctrine->getRepository(AdvertiserInfo::class)->insertToAdvertiserInfo($value['Advertiser']['id'], $value['Advertiser']['company'], $value['AccountManager'] !== null ? $value['AccountManager']['id'] : null, $value['Advertiser']['status'], $tuneAccount);
  1477. }
  1478. // $this->mafoObjectsComponents->createOrUpdateAdvertiser(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Advertiser']['id']);
  1479. // $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
  1480. // exec($execCommand);
  1481. if ($value['AccountManager'] !== null) {
  1482. $affiliateAccountManagerDBInfo = $this->doctrine->getRepository(AdvertiserAccountManager::class)->findOneBy(['advertiserId' => $value['Advertiser']['id']]);
  1483. if ($affiliateAccountManagerDBInfo) {
  1484. $this->doctrine->getRepository(AdvertiserAccountManager::class)->updateDataByAdvertiserId($value['Advertiser']['id'], [
  1485. 'employeeId' => $value['AccountManager']['id'],
  1486. 'email' => $value['AccountManager']['email'],
  1487. 'firstName' => $value['AccountManager']['first_name'],
  1488. 'lastName' => $value['AccountManager']['last_name'],
  1489. 'status' => $value['AccountManager']['status'],
  1490. ], $tuneAccount);
  1491. } else {
  1492. $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);
  1493. }
  1494. }
  1495. $advertiserTagRelationship = $this->brandApi->getAdvertiserTagRelationByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1496. if ($advertiserTagRelationship['response']['status'] == 1) {
  1497. $advertiserTags = [];
  1498. foreach ($advertiserTagRelationship['response']['data']['data'] as $k => $v) {
  1499. !in_array($v['AdvertisersTags']['tag_id'], $advertiserTags) ? array_push($advertiserTags, $v['AdvertisersTags']['tag_id']) : false;
  1500. }
  1501. $advertiserDBTagsData = $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1502. $advertiserDBTags = [];
  1503. foreach ($advertiserDBTagsData as $k => $v) {
  1504. !in_array($v['tagId'], $advertiserDBTags) ? array_push($advertiserDBTags, $v['tagId']) : false;
  1505. }
  1506. if ($advertiserDBTags != $advertiserTags) {
  1507. $this->doctrine->getRepository(AdvertiserTagRelationship::class)->deleteAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1508. foreach ($advertiserTags as $advertiserTag) {
  1509. $this->doctrine->getRepository(AdvertiserTagRelationship::class)->insertToAdvertiserTagRelationship($advertiserTag, $value['Advertiser']['id'], $tuneAccount);
  1510. }
  1511. }
  1512. }
  1513. }
  1514. }
  1515. public function getEmployeesWithEmailAsKey()
  1516. {
  1517. $employeesData = $this->doctrine->getRepository(Employees::class)->getEmployees();
  1518. $employees = [];
  1519. foreach ($employeesData as $key => $value) {
  1520. $employees[strtolower($value['email'])] = $value;
  1521. }
  1522. return $employees;
  1523. }
  1524. public function getNewsletterBuilderTemplate($offerIds, $introduction, $unsubscribeEmailId = '')
  1525. {
  1526. $offerInfoFromApi = [];
  1527. if ($offerIds) {
  1528. $offerInfoFromApi = $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
  1529. }
  1530. $offerInfoByOfferId = [];
  1531. foreach ($offerIds as $offerId) {
  1532. foreach ($offerInfoFromApi as $key => $value) {
  1533. if ($offerId == $value['offerId']) {
  1534. $value['geos'] = json_decode($value['geoIdsJson'], true);
  1535. $offerInfoByOfferId[] = $value;
  1536. }
  1537. }
  1538. }
  1539. return $this->template->render('components/newsletterBuilder.html.twig', [
  1540. 'offerDetails' => $offerInfoByOfferId,
  1541. 'introduction' => $introduction,
  1542. 'unsubscribeLink' => "http://firehose.mobupps.com/api/unsubscribe/" . $unsubscribeEmailId
  1543. ]);
  1544. }
  1545. public function getOfferGoalInfoByOfferGoalIdArrWithKeys($offerGoalIdArr)
  1546. {
  1547. $offerGoalData = $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalInfoByGoalIdArr($offerGoalIdArr);
  1548. $data = [];
  1549. foreach ($offerGoalData as $key => $value) {
  1550. $data[$value['goalId']] = $value;
  1551. }
  1552. return $data;
  1553. }
  1554. public function getSkadNetworkMessageSeparator()
  1555. {
  1556. return mb_chr(Config::SKADNETWORK_MESSAGE_SEPARATOR_CODE);
  1557. }
  1558. public function setCommandLoggerData($identifier, $commandName, $meta)
  1559. {
  1560. $identifierExists = $this->doctrine->getRepository(CommandLogger::class)->findOneBy([
  1561. 'identifier' => $identifier
  1562. ]);
  1563. if (is_array($meta)) {
  1564. $meta = json_encode($meta);
  1565. }
  1566. $currentTimestamp = strtotime('now');
  1567. if (!$identifierExists) {
  1568. $this->doctrine->getRepository(CommandLogger::class)->insertToCommandLogger($identifier, $commandName, $currentTimestamp, null, null, null);
  1569. } else {
  1570. $this->doctrine->getRepository(CommandLogger::class)->updateCommandLoggerById($identifierExists->getId(), [
  1571. 'endTimestamp' => $currentTimestamp,
  1572. 'timestampDiff' => $currentTimestamp - $identifierExists->getStartTimestamp(),
  1573. 'meta' => $meta
  1574. ]);
  1575. }
  1576. }
  1577. public function getMafoUsersWithEmailIdAsKey()
  1578. {
  1579. $users = $this->doctrine->getRepository('App\Entity\Users')->getUsers();
  1580. $arr = [];
  1581. foreach ($users as $key => $value) {
  1582. $name = explode(' ', $value['name']);
  1583. $value['firstName'] = $name[0];
  1584. $arr[$value['email']] = $value;
  1585. }
  1586. return $arr;
  1587. }
  1588. public function checkAlertMetaExists($identifier, $type)
  1589. {
  1590. $identifierExists = $this->doctrine->getRepository(AlertMeta::class)->findOneBy(['identifier' => $identifier]);
  1591. if (!$identifierExists) {
  1592. $this->doctrine->getRepository(AlertMeta::class)->insertToAlertMeta($identifier, $type);
  1593. return false;
  1594. } else {
  1595. return true;
  1596. }
  1597. }
  1598. public function getHourOffsetFromTimezoneString($timezone)
  1599. {
  1600. $hourOffset = '+0:00';
  1601. if (array_key_exists($timezone, Config::TIMEZONES)) {
  1602. $timezone = Config::TIMEZONES[$timezone];
  1603. $timezone = explode(" ", $timezone)[0];
  1604. $timezone = str_replace("(GMT", "", $timezone);
  1605. $hourOffset = str_replace(")", "", $timezone);
  1606. }
  1607. return $hourOffset;
  1608. }
  1609. public function processPendingPostback($postbackLogId)
  1610. {
  1611. $postbackLogData = $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->findOneBy(['id' => $postbackLogId]);
  1612. $endpoint = $postbackLogData->getEndpoint();
  1613. $appId = $postbackLogData->getAppId();
  1614. $campaignId = $postbackLogData->getCampaignId();
  1615. $payload = json_decode($postbackLogData->getRequest(), true);
  1616. $isAttributionSignatureValid = $postbackLogData->getIsAttributionSignatureValid();
  1617. $postbackTimestamp = $postbackLogData->getDateInserted()->getTimestamp();
  1618. $offerId = null;
  1619. $affiliateId = null;
  1620. $skadNetworkPostbackMappingExists = null;
  1621. if ($endpoint == Config::SKADNETWORK_POSTBACK_ENDPOINT_WMADV) {
  1622. $skadNetworkPostbackMappingExists = $this->doctrine->getRepository(SkadNetworkManualPostbackMapping::class)->findOneBy([
  1623. 'appId' => $appId,
  1624. 'campaignId' => $campaignId,
  1625. 'isDeleted' => 0
  1626. ]);
  1627. if ($skadNetworkPostbackMappingExists) {
  1628. $offerId = $skadNetworkPostbackMappingExists->getOfferId();
  1629. $affiliateId = $skadNetworkPostbackMappingExists->getAffiliateId();
  1630. }
  1631. } else {
  1632. $apiLogsData = $this->doctrine->getRepository(SkadNetworkApiLogs::class)->findOneBy(['appId' => $appId, 'campaignId' => $campaignId]);
  1633. if ($apiLogsData) {
  1634. $offerId = $apiLogsData->getOfferId();
  1635. $affiliateId = $apiLogsData->getAffiliateId();
  1636. }
  1637. }
  1638. $postbacksToMake = [];
  1639. if ($isAttributionSignatureValid && $postbackLogData->getDidWin()) {
  1640. if ($offerId) {
  1641. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId]);
  1642. if ($offerInfo && $offerInfo->getSkadNetworkMmp() && in_array($offerInfo->getSkadNetworkMmp(), Config::SKADNETOWRK_MMP)) {
  1643. if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_ADJUST && $offerInfo->getSkadNetworkAdjustTracker()) {
  1644. $offerGeoRelationship = $this->doctrine->getRepository(OfferGeoRelationship::class)->findOneBy(['offerId' => $offerInfo->getOfferId()]);
  1645. $postbackParams = [
  1646. 'tracker' => $offerInfo->getSkadNetworkAdjustTracker(),
  1647. 'sk_payload' => urlencode($payload),
  1648. 'sk_ts' => strtotime('now')
  1649. ];
  1650. if ($offerGeoRelationship && $offerGeoRelationship->getGeo()) {
  1651. $postbackParams['country'] = strtolower($offerGeoRelationship->getGeo());
  1652. }
  1653. $postbacksToMake[] = [
  1654. 'requestType' => Config::HTTP_METHOD_POST,
  1655. 'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()] . '?' . http_build_query($postbackParams),
  1656. 'postbackForMmp' => true,
  1657. 'skadNetworkMmp' => Config::SKADNETWORK_MMP_ADJUST
  1658. ];
  1659. } else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_BRANCH) {
  1660. $postbacksToMake[] = [
  1661. 'requestType' => Config::HTTP_METHOD_POST,
  1662. 'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[Config::SKADNETWORK_MMP_BRANCH],
  1663. 'postbackForMmp' => true,
  1664. 'skadNetworkMmp' => Config::SKADNETWORK_MMP_BRANCH
  1665. ];
  1666. if ($skadNetworkPostbackMappingExists) {
  1667. if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignId()) {
  1668. $payload['partner-campaign-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignId();
  1669. }
  1670. if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignName()) {
  1671. $payload['partner-campaign-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignName();
  1672. }
  1673. if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetId()) {
  1674. $payload['partner-ad-set-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetId();
  1675. }
  1676. if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetName()) {
  1677. $payload['partner-ad-set-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetName();
  1678. }
  1679. if ($skadNetworkPostbackMappingExists->getBranchPartnerAdId()) {
  1680. $payload['partner-ad-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdId();
  1681. }
  1682. if ($skadNetworkPostbackMappingExists->getBranchPartnerAdName()) {
  1683. $payload['partner-ad-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdName();
  1684. }
  1685. if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeId()) {
  1686. $payload['partner-creative-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeId();
  1687. }
  1688. if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeName()) {
  1689. $payload['partner-creative-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeName();
  1690. }
  1691. }
  1692. } else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_APPSFLYER) {
  1693. // $payload['ad-network-campaign-id'] = $campaignId . "";
  1694. // $payload['ad-network-campaign-name'] = $offerId . "";
  1695. // $payload['ad-network-country-code'] = implode(",", json_decode($offerInfo->getGeoIdsJson(), true));
  1696. // $payload['timestamp'] = $postbackTimestamp;
  1697. // if($affiliateId) {
  1698. // $payload['source-app-id'] = $affiliateId."";
  1699. // $payload['ad-network-source-app-id'] = $affiliateId."";
  1700. // }
  1701. $postbacksToMake[] = [
  1702. 'requestType' => Config::HTTP_METHOD_POST,
  1703. 'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
  1704. 'postbackForMmp' => true,
  1705. 'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
  1706. ];
  1707. } else {
  1708. $postbacksToMake[] = [
  1709. 'requestType' => Config::HTTP_METHOD_POST,
  1710. 'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
  1711. 'postbackForMmp' => true,
  1712. 'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
  1713. ];
  1714. }
  1715. }
  1716. }
  1717. if ($affiliateId) {
  1718. $affiliateInfo = $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId]);
  1719. if ($affiliateInfo && $affiliateInfo->getSkadNetworkPostbackUrl()) {
  1720. $postbacksToMake[] = [
  1721. 'requestType' => Config::HTTP_METHOD_POST,
  1722. 'requestUrl' => $affiliateInfo->getSkadNetworkPostbackUrl(),
  1723. 'postbackForMmp' => false
  1724. ];
  1725. }
  1726. }
  1727. foreach ($postbacksToMake as $key => $value) {
  1728. $result = false;
  1729. if ($value['requestType'] == Config::HTTP_METHOD_POST) {
  1730. $postdata = json_encode($payload);
  1731. $ch = curl_init($value['requestUrl']);
  1732. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1733. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  1734. curl_setopt($ch, CURLOPT_POST, 1);
  1735. curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  1736. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1737. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  1738. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  1739. $result = curl_exec($ch);
  1740. curl_close($ch);
  1741. } elseif ($value['requestType'] == Config::HTTP_METHOD_GET) {
  1742. $ch = curl_init($value['requestUrl']);
  1743. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1744. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  1745. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  1746. $result = curl_exec($ch);
  1747. curl_close($ch);
  1748. }
  1749. if ($result) {
  1750. if (array_key_exists('postbackForMmp', $value) && $value['postbackForMmp']) {
  1751. if (
  1752. array_key_exists('skadNetworkMmp', $value) &&
  1753. $value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_BRANCH
  1754. ) {
  1755. $result = json_decode($result, true);
  1756. if (array_key_exists('id', $result)) {
  1757. $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1758. 'isPostbackScheduledForMmp' => false,
  1759. 'branchPostbackId' => $result['id']
  1760. ]);
  1761. }
  1762. } else if ($value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_APPSFLYER) {
  1763. $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1764. 'isPostbackScheduledForMmp' => false
  1765. ]);
  1766. }
  1767. } else {
  1768. $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1769. 'isPostbackScheduledForAffiliate' => false
  1770. ]);
  1771. }
  1772. }
  1773. }
  1774. }
  1775. }
  1776. public function getAppInfoByAppIdArrWithKeys($appIdArr)
  1777. {
  1778. $appData = [];
  1779. if ($appIdArr) {
  1780. $appData = $this->doctrine->getRepository(AppInfo::class)->getDataByAppIds($appIdArr);
  1781. }
  1782. $arr = [];
  1783. foreach ($appData as $key => $value) {
  1784. $arr[$value['appId']] = $value;
  1785. }
  1786. return $arr;
  1787. }
  1788. public function getAppInfoWithKeys($fromCache = true)
  1789. {
  1790. $arr = [];
  1791. if ($fromCache) {
  1792. $arr = $this->elasticCache->redisGet(Config::CACHE_REDIS_APP_INFO_KEY);
  1793. }
  1794. if (!$arr) {
  1795. $appData = $this->doctrine->getRepository(AppInfo::class)->getAppIds();
  1796. $arr = [];
  1797. foreach ($appData as $key => $value) {
  1798. $arr[$value['appId']] = $value;
  1799. }
  1800. } else {
  1801. $arr = json_decode($arr, true);
  1802. }
  1803. return $arr;
  1804. }
  1805. public function getDataFromJsonFile($jsonFileName)
  1806. {
  1807. $json = file_get_contents($this->rootPath . "/src/Resources/json/" . $jsonFileName . ".json");
  1808. if (in_array($jsonFileName, [Config::JSON_FILE_FINANCIAL_TOOLS_GAP_CONTROL, Config::JSON_FILE_FINANCIAL_TOOLS_MAFO_GAP_CONTROL])) {
  1809. $teamsByTeamId = $this->usersComponents->getTeamsByTeamId();
  1810. $usersByTeamId = $this->usersComponents->getMafoUsersByTeamIds();
  1811. $columnsData = json_decode($json, true);
  1812. foreach ($usersByTeamId as $teamId => $users) {
  1813. if (sizeof($users)) {
  1814. $columnsData[$teamsByTeamId[$teamId]['label'] . 'Cost'] = [
  1815. 'header' => $teamsByTeamId[$teamId]['label'] . ' Media Cost',
  1816. 'accessor' => $teamsByTeamId[$teamId]['label'] . 'Cost',
  1817. 'percentageWidth' => 5,
  1818. 'show' => true,
  1819. 'disabled' => false,
  1820. 'customClass' => 'text-right',
  1821. 'category' => 'statistics',
  1822. 'footerEnabled' => true,
  1823. 'aggregate' => 'sum',
  1824. // 'alwaysEnabled' => true
  1825. ];
  1826. }
  1827. }
  1828. $itemsToBePushedToEnd = ['totalAffiliateCost', 'gap'];
  1829. $arrToBePushedToEnd = [];
  1830. foreach ($itemsToBePushedToEnd as $key => $value) {
  1831. $arrToBePushedToEnd[$value] = $columnsData[$value];
  1832. unset($columnsData[$value]);
  1833. }
  1834. $columnsData = array_merge($columnsData, $arrToBePushedToEnd);
  1835. $json = json_encode($columnsData);
  1836. }
  1837. return json_decode($json, true);
  1838. }
  1839. public function changeColumnVisibilityForTable($tableColumns, $selectedColumns, $groupedColumns)
  1840. {
  1841. foreach ($tableColumns as $key => $value) {
  1842. $tableColumns[$key]['show'] = false;
  1843. foreach ($selectedColumns as $k => $v) {
  1844. if ($value['accessor'] === $k && $v !== 'undefined') {
  1845. $tableColumns[$key]['show'] = $v == '0' ? false : true;
  1846. break;
  1847. }
  1848. }
  1849. foreach ($groupedColumns as $k => $v) {
  1850. if ($value['accessor'] === $k && $v !== 'undefined') {
  1851. $tableColumns[$key]['groupBy'] = !($v == '0');
  1852. !($v == '0') ? $tableColumns[$key]['show'] = true : null;
  1853. break;
  1854. }
  1855. }
  1856. }
  1857. return $tableColumns;
  1858. }
  1859. public function downloadCSV($tableColumns, $data, $reportNamePretty)
  1860. {
  1861. $reportName = str_replace(" ", "-", strtolower($reportNamePretty));
  1862. $header = [];
  1863. foreach ($tableColumns as $key => $value) {
  1864. if ($value['show'] == 1) {
  1865. $headerValue = isset($value['Header']) ? $value['Header'] : (isset($value['header']) ? $value['header'] : null);
  1866. array_push($header, $headerValue);
  1867. }
  1868. }
  1869. $rows = [$header];
  1870. foreach ($data as $key => $value) {
  1871. $row = [];
  1872. foreach ($tableColumns as $k => $v) {
  1873. if ($v['show'] == 1) {
  1874. if ($v['accessor'] == 'comments' && is_array($value[$v['accessor']])) {
  1875. $comments = '';
  1876. foreach ($value[$v['accessor']] as $commentKey => $commentValue) {
  1877. $commentValue['comment'] = $commentValue['isDeleted'] ? "**This comment was deleted.**" : $commentValue['comment'];
  1878. $comments .= "{$commentValue['addedByName']} [{$commentValue['dateInserted']}]: {$commentValue['comment']}\n";
  1879. }
  1880. $value[$v['accessor']] = $comments;
  1881. } elseif ($v['accessor'] == 'attachedFiles') {
  1882. $value[$v['accessor']] = $value['linkToFile'];
  1883. } elseif (is_array($value[$v['accessor']])) {
  1884. $items = '';
  1885. if (array_key_exists('label', $value[$v['accessor']])) {
  1886. $items .= $value[$v['accessor']]['label'];
  1887. } else {
  1888. foreach ($value[$v['accessor']] as $kk => $vv) {
  1889. if (array_key_Exists('label', $vv)) {
  1890. $items .= $vv['label'] . "\n";
  1891. }
  1892. }
  1893. }
  1894. $value[$v['accessor']] = $items;
  1895. }
  1896. array_push($row, $value[$v['accessor']]);
  1897. }
  1898. }
  1899. $rows[] = $row;
  1900. }
  1901. $spreadsheet = new Spreadsheet();
  1902. $spreadsheet->getProperties()->setCreator('MAFO')->setLastModifiedBy('MAFO')->setTitle($reportNamePretty . ' Report')->setSubject($reportNamePretty)->setDescription($reportNamePretty);
  1903. // echo json_encode($rows);die;
  1904. $spreadsheet->getActiveSheet()->fromArray($rows, null, 'A1');
  1905. header('Content-Type: application/vnd.ms-excel');
  1906. header('Content-Disposition: attachment;filename="' . $reportName . '.xls"');
  1907. header('Cache-Control: max-age=0');
  1908. $writer = IOFactory::createWriter($spreadsheet, 'Xls');
  1909. $writer->save('php://output');
  1910. exit;
  1911. }
  1912. public function getReportResponse($finalArr, $tableColumns, $limit, $page, $sortBy, $sortType)
  1913. {
  1914. foreach ($finalArr as $key => $value) {
  1915. foreach ($tableColumns as $k => $v) {
  1916. if (isset($v['footerEnabled'])) {
  1917. if (!array_key_exists('Footer', $v)) {
  1918. $tableColumns[$k]['Footer'] = 0;
  1919. }
  1920. if (array_key_exists($v['accessor'], $value)) {
  1921. $tableColumns[$k]['Footer'] += $value[$v['accessor']];
  1922. }
  1923. }
  1924. }
  1925. }
  1926. foreach ($tableColumns as $key => $value) {
  1927. if (isset($value['footerEnabled']) && isset($value['Footer'])) {
  1928. $tableColumns[$key]['Footer'] = round($value['Footer'], 2);
  1929. }
  1930. }
  1931. if (sizeof($finalArr)) {
  1932. $entity = $finalArr[0];
  1933. if (array_key_exists($sortBy, $entity)) {
  1934. $sortFlag = 3;
  1935. if ($sortType == Config::SORT_TYPE_ASC) {
  1936. $sortFlag = 4;
  1937. }
  1938. array_multisort(array_column($finalArr, $sortBy), $sortFlag, $finalArr);
  1939. }
  1940. }
  1941. $offset = $limit * ($page - 1);
  1942. $totalRecordCount = sizeof($finalArr);
  1943. $noOfPages = ceil($totalRecordCount / $limit);
  1944. $finalArr = array_slice($finalArr, $offset, $limit);
  1945. return [
  1946. 'response' => [
  1947. 'success' => true,
  1948. 'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  1949. 'data' => [
  1950. 'tableColumns' => $tableColumns,
  1951. 'data' => $finalArr,
  1952. 'metaData' => [
  1953. "total" => $totalRecordCount,
  1954. "limit" => $limit,
  1955. "page" => $page,
  1956. "pages" => $noOfPages
  1957. ]
  1958. ],
  1959. 'error' => null
  1960. ]
  1961. ];
  1962. }
  1963. public function getDeductionForAdvertiserAndAffiliateForPeriod($offerId, $advertiserId, $affiliateId, $startDate, $endDate)
  1964. {
  1965. $totalDeduction = 0;
  1966. $approvedDeduction = 0;
  1967. if (
  1968. $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId]) &&
  1969. $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId])
  1970. ) {
  1971. $deductionControlData = $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData($offerId ? [$offerId] : [], $advertiserId ? [$advertiserId] : [], $affiliateId ? [$affiliateId] : [], [], [], $startDate, $endDate, 0, []);
  1972. foreach ($deductionControlData as $key => $value) {
  1973. $totalDeduction += $value['deductionValue'];
  1974. if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
  1975. $approvedDeduction += $value['deductionValue'];
  1976. }
  1977. }
  1978. }
  1979. return [
  1980. 'advertiserId' => $advertiserId,
  1981. 'affiliateId' => $affiliateId,
  1982. 'totalDeduction' => round($totalDeduction, 2),
  1983. 'approvedDeduction' => round($approvedDeduction, 2),
  1984. ];
  1985. }
  1986. public function getMafoDeductionForAdvertiserAndAffiliateForPeriod($offerId, $advertiserId, $affiliateId, $startDate, $endDate)
  1987. {
  1988. $totalDeduction = 0;
  1989. $approvedDeduction = 0;
  1990. if (
  1991. $this->doctrine->getRepository(MafoAdvertisers::class)->findOneBy(['id' => $advertiserId]) &&
  1992. $this->doctrine->getRepository(MafoAffiliates::class)->findOneBy(['id' => $affiliateId])
  1993. ) {
  1994. $deductionControlData = $this->doctrine->getRepository(MafoDeductionControl::class)->getMafoDeductionControlData($offerId ? [$offerId] : [], $advertiserId ? [$advertiserId] : [], $affiliateId ? [$affiliateId] : [], [], [], $startDate, $endDate, 0, []);
  1995. foreach ($deductionControlData as $key => $value) {
  1996. $totalDeduction += $value['deductionValue'];
  1997. if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
  1998. $approvedDeduction += $value['deductionValue'];
  1999. }
  2000. }
  2001. }
  2002. return [
  2003. 'advertiserId' => $advertiserId,
  2004. 'affiliateId' => $affiliateId,
  2005. 'totalDeduction' => round($totalDeduction, 2),
  2006. 'approvedDeduction' => round($approvedDeduction, 2),
  2007. ];
  2008. }
  2009. public function getIndexedDeductionFromDeductionControlByAdvertiserAndAffiliate($startDate, $endDate)
  2010. {
  2011. $indexedDeduction = [];
  2012. $deductionControlData = $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData([], [], [], [], [], $startDate, $endDate, 0, []);
  2013. foreach ($deductionControlData as $key => $value) {
  2014. $deductionPeriod = $value['deductionPeriod']->format('Y-m');
  2015. if (!isset($indexedDeduction[$deductionPeriod])) {
  2016. $indexedDeduction[$deductionPeriod] = [];
  2017. }
  2018. if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']])) {
  2019. $indexedDeduction[$deductionPeriod][$value['advertiserId']] = [];
  2020. }
  2021. if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']])) {
  2022. $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']] = [
  2023. 'advertiserId' => $value['advertiserId'],
  2024. 'affiliateId' => $value['affiliateId'],
  2025. 'totalDeduction' => 0,
  2026. 'approvedDeduction' => 0
  2027. ];
  2028. }
  2029. $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['totalDeduction'] += $value['deductionValue'];
  2030. if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
  2031. $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['approvedDeduction'] += $value['deductionValue'];
  2032. }
  2033. }
  2034. return $indexedDeduction;
  2035. }
  2036. public function detectCSVDelimiter($csvFile)
  2037. {
  2038. $delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];
  2039. $handle = fopen($csvFile, "r");
  2040. $firstLine = fgets($handle);
  2041. fclose($handle);
  2042. foreach ($delimiters as $delimiter => &$count) {
  2043. $count = count(str_getcsv($firstLine, $delimiter));
  2044. }
  2045. return array_search(max($delimiters), $delimiters);
  2046. }
  2047. public function assignTagsToOffers()
  2048. {
  2049. $activeOffers = $this->doctrine->getRepository(OfferInfo::class)->getOfferInfoByStatus(Config::ACTIVE_STATUS);
  2050. foreach ($activeOffers as $key => $value) {
  2051. if ($value['offerUrl']) {
  2052. foreach (Config::HASOFFER_TRACKING_LINK_KEYWORDS_BY_TAG_ID as $k => $v) {
  2053. if ($k == Config::HASOFFER_ADJUST_OFFER_TAG_ID) {
  2054. $adjustAppDetails = $this->doctrine->getRepository(AdjustAppDetails::class)->getAdjustAppDetails();
  2055. foreach ($adjustAppDetails as $kk => $vv) {
  2056. if (
  2057. $this->checkForString($value['offerUrl'], $vv['appToken']) &&
  2058. array_key_exists($vv['account'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING)
  2059. ) {
  2060. $this->brandApi->addTagToOffer($value['offerId'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING[$vv['account']]);
  2061. $this->populateDbByOfferId($value['offerId']);
  2062. break 2;
  2063. }
  2064. }
  2065. } else {
  2066. foreach ($v as $subLink) {
  2067. if (
  2068. isset($value['offerUrl']) &&
  2069. $this->checkForString($value['offerUrl'], $subLink) &&
  2070. !$this->doctrine->getRepository(OfferTagRelationship::class)->findOneBy(['tagId' => $k, 'offerId' => $value['offerId']])
  2071. ) {
  2072. $this->brandApi->addTagToOffer($value['offerId'], $k);
  2073. $this->populateDbByOfferId($value['offerId']);
  2074. break 2;
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. }
  2081. }
  2082. public function getReportsRowWiseDataByAggregation($tableColumns, $selectedColumns, $rowWiseData)
  2083. {
  2084. $finalArr = [];
  2085. foreach ($rowWiseData as $rowWiseIndex => $rowWiseValue) {
  2086. $indexArr = [];
  2087. foreach ($selectedColumns as $key => $value) {
  2088. if (
  2089. array_key_exists($key, $tableColumns) &&
  2090. $value &&
  2091. in_array($tableColumns[$key]['category'], ['data_fields', 'item_interval'])
  2092. ) {
  2093. $indexArr[] = $rowWiseValue[$key];
  2094. }
  2095. }
  2096. $index = md5(implode("#", $indexArr));
  2097. if (!array_key_exists($index, $finalArr)) {
  2098. foreach ($selectedColumns as $key => $value) {
  2099. if (array_key_exists($key, $tableColumns) && $value && array_key_exists($key, $rowWiseValue)) {
  2100. if (in_array($tableColumns[$key]['category'], ['data_fields', 'item_interval'])) {
  2101. $finalArr[$index][$key] = $rowWiseValue[$key];
  2102. }
  2103. }
  2104. }
  2105. foreach ($tableColumns as $key => $value) {
  2106. if ($value['category'] == 'statistics') {
  2107. $finalArr[$index][$key] = 0;
  2108. }
  2109. }
  2110. }
  2111. foreach ($tableColumns as $key => $value) {
  2112. if (
  2113. (
  2114. $value['category'] == 'statistics' && !isset($value['calculationType'])
  2115. ) ||
  2116. (
  2117. isset($value['calculationType']) && $value['category'] == 'statistics' && $value['calculationType'] != 'percentage'
  2118. )
  2119. ) {
  2120. $finalArr[$index][$key] += $rowWiseValue[$key];
  2121. $finalArr[$index][$key] = round($finalArr[$index][$key], 2);
  2122. }
  2123. }
  2124. }
  2125. return $finalArr;
  2126. }
  2127. public function getPaginatedResponseForReports($reportData, $tableColumns, $selectedColumns, $sortBy, $sortType, $limit, $page)
  2128. {
  2129. $reportData = array_values($reportData);
  2130. if (sizeof($reportData)) {
  2131. $entity = $reportData[0];
  2132. if (array_key_exists($sortBy, $entity)) {
  2133. $sortFlag = 3;
  2134. if ($sortType == Config::SORT_TYPE_ASC) {
  2135. $sortFlag = 4;
  2136. }
  2137. array_multisort(array_column($reportData, $sortBy), $sortFlag, $reportData);
  2138. }
  2139. }
  2140. $offset = $limit * ($page - 1);
  2141. $totalRecordCount = sizeof($reportData);
  2142. $noOfPages = ceil($totalRecordCount / $limit);
  2143. foreach ($tableColumns as $key => $value) {
  2144. if (isset($value['aggregate'])) {
  2145. if ($value['aggregate'] == 'sum') {
  2146. $tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData, $value['accessor'])), 2));
  2147. }
  2148. if ($value['aggregate'] == 'average' && count($reportData) > 0) {
  2149. $tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData, $value['accessor'])) / count($reportData), 2));
  2150. }
  2151. }
  2152. }
  2153. $tableColumns = $this->changeColumnVisibilityForTable(array_values($tableColumns), $selectedColumns, []);
  2154. return [
  2155. 'response' => [
  2156. 'success' => true,
  2157. 'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  2158. 'data' => [
  2159. 'tableColumns' => array_values($tableColumns),
  2160. 'data' => array_slice($reportData, $offset, $limit),
  2161. 'metaData' => [
  2162. 'total' => $totalRecordCount,
  2163. 'limit' => (int)$limit,
  2164. 'page' => (int)$page,
  2165. 'pages' => (int)$noOfPages,
  2166. ]
  2167. ],
  2168. 'error' => null
  2169. ]
  2170. ];
  2171. }
  2172. public function getAffiliateCategoryByAffiliateId($tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  2173. {
  2174. $affiliateTagRelationshipData = $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByTagIdArr([Config::HASOFFER_AFFILIATE_CATEGORY_A_TAG_ID, Config::HASOFFER_AFFILIATE_CATEGORY_B_TAG_ID], $tuneAccount);
  2175. $data = [];
  2176. foreach ($affiliateTagRelationshipData as $key => $value) {
  2177. $data[$key] = [
  2178. 'category' => Config::HASOFFER_AFFILIATE_CATEGORY_ARRAY[$value['tagId']],
  2179. 'affiliateId' => $value['affiliateId']
  2180. ];
  2181. }
  2182. $affiliateData = $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByArrToSearch([], $tuneAccount);
  2183. foreach ($affiliateData as $key => $value) {
  2184. if (!array_key_exists($value['affiliateId'], $data)) {
  2185. $data[$value['affiliateId']] = [
  2186. 'category' => Config::HASOFFER_AFFILIATE_CATEGORY_UNCATEGORISED_TAG_NAME,
  2187. 'affiliateId' => $value['affiliateId']
  2188. ];
  2189. }
  2190. }
  2191. return $data;
  2192. }
  2193. public function getPidByOfferId($offerId, $tuneAccount = Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  2194. {
  2195. $tunePid = null;
  2196. $offerInfo = $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId, 'tuneAccount' => $tuneAccount]);
  2197. if ($offerInfo) {
  2198. $parsedUrl = parse_url($offerInfo->getOfferUrl());
  2199. if (isset($parsedUrl['query'])) {
  2200. parse_str($parsedUrl['query'], $query);
  2201. if (isset($query['pid']) && in_array($query['pid'], Config::TUNE_APPSFLYER_PIDS)) {
  2202. $tunePid = $query['pid'];
  2203. }
  2204. }
  2205. }
  2206. return $tunePid;
  2207. }
  2208. public function getWhitelistIPsAppsflyerOrAdjust($offerUrl)
  2209. {
  2210. $whitelistIps = [];
  2211. if (stripos($offerUrl, Config::APPSFLYER_DOMAIN) !== false) {
  2212. $whitelistIps = Config::WIZARD_APPSFLYER_WHITE_LIST;
  2213. }
  2214. if (
  2215. stripos($offerUrl, Config::ADJUST_IO_DOMAIN) !== false
  2216. || stripos($offerUrl, Config::ADJUST_COM_DOMAIN) !== false
  2217. ) {
  2218. $whitelistIps = Config::WIZARD_ADJUST_WHITE_LIST;
  2219. }
  2220. return $whitelistIps;
  2221. }
  2222. public function updateNotificationUnreadCountByUser($userEmail, $unreadNotificationCount)
  2223. {
  2224. $cacheKey = Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER . $userEmail;
  2225. if (is_null($this->elasticCache->redisGet($cacheKey))) {
  2226. $userData = $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
  2227. 'sentToUserId' => $userEmail,
  2228. 'isRead' => 0
  2229. ]);
  2230. $notificationCount = count($userData);
  2231. } else {
  2232. $notificationCount = $this->elasticCache->redisGet($cacheKey);
  2233. }
  2234. $unreadNotificationCount += $notificationCount;
  2235. $this->elasticCache->redisSet($cacheKey, $unreadNotificationCount);
  2236. }
  2237. public function getUnreadNotificationCountByUser($userEmail)
  2238. {
  2239. $cacheKey = Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER . $userEmail;
  2240. if (is_null($this->elasticCache->redisGet($cacheKey))) {
  2241. $userData = $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
  2242. 'sentToUserId' => $userEmail,
  2243. 'isRead' => 0
  2244. ]);
  2245. $notificationCount = count($userData);
  2246. } else {
  2247. $notificationCount = $this->elasticCache->redisGet($cacheKey);
  2248. }
  2249. return $notificationCount;
  2250. }
  2251. public function sendPushNotification($topic, $topicData)
  2252. {
  2253. try {
  2254. $update = new Update(
  2255. $topic,
  2256. $topicData
  2257. // ,true
  2258. );
  2259. $this->hub->publish($update);
  2260. } catch (\Exception $e) {
  2261. $this->logger->error('Error occurred: ' . $e);
  2262. }
  2263. }
  2264. public function getEmployeesByUserId()
  2265. {
  2266. $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
  2267. if (!$cachedList) {
  2268. $employeeList = $this->getWarmedUpUsersByUserId();
  2269. } else {
  2270. $employeeList = json_decode($cachedList, true);
  2271. }
  2272. ksort($employeeList);
  2273. return $employeeList;
  2274. }
  2275. public function getWarmedUpUsersByUserId()
  2276. {
  2277. $employeesData = $this->doctrine->getRepository(Users::class)->getEmployees();
  2278. $data = [];
  2279. foreach ($employeesData as $key => $value) {
  2280. $data[$value['email']] = [
  2281. 'firstName' => $value['name'],
  2282. 'email' => $value['email']
  2283. ];
  2284. }
  2285. return $data;
  2286. }
  2287. /**
  2288. * Transform array data to dropdown format
  2289. *
  2290. * @param array $data Array of data to transform
  2291. * @param string $valueKey Key to use as the value (default: 'id')
  2292. * @param array $labelKeys Array of keys to concatenate for label (default: ['firstName', 'lastName'])
  2293. * @param string $fallbackKey Key to use as fallback if label is empty (default: 'email')
  2294. * @param string $separator Separator to use between label keys (default: ' ')
  2295. * @return array Transformed dropdown data
  2296. */
  2297. public function transformToDropdownFormat(array $data, string $valueKey = 'id', array $labelKeys = ['firstName', 'lastName'], string $fallbackKey = 'email', string $separator = ' '): array
  2298. {
  2299. return array_map(function ($item) use ($valueKey, $labelKeys, $fallbackKey, $separator) {
  2300. $labelParts = [];
  2301. foreach ($labelKeys as $key) {
  2302. if (isset($item[$key]) && !empty($item[$key])) {
  2303. $labelParts[] = trim($item[$key]);
  2304. }
  2305. }
  2306. $label = implode($separator, $labelParts);
  2307. if (empty($label) && isset($item[$fallbackKey])) {
  2308. $label = $item[$fallbackKey];
  2309. }
  2310. return [
  2311. 'value' => $item[$valueKey] ?? null,
  2312. 'label' => $label
  2313. ];
  2314. }, $data);
  2315. }
  2316. }