src/Service/ActiveCampaignHelper.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Session;
  4. use App\Entity\UserPlacementTest;
  5. use Symfony\Component\DependencyInjection\ContainerInterface as Container;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use App\Entity\SubscriptionOrder;
  8. use App\Entity\SessionOrder;
  9. use App\Entity\EmailListUnsubscribeLog;
  10. use App\Entity\EmailListSubscribeLostLog;
  11. use App\Entity\EmailListActionLog;
  12. use App\Repository\SubscriptionOrderRepository;
  13. use App\Repository\SessionOrderRepository;
  14. use TestMonitor\ActiveCampaign\Resources\Contact;
  15. use TestMonitor\ActiveCampaign\Resources\CustomField;
  16. class ActiveCampaignHelper
  17. {
  18. protected $container;
  19. protected $em;
  20. private $activeCampaign;
  21. private $Activecampaign_url;
  22. private $subscriptionOrderRepository;
  23. private $sessionOrderRepository;
  24. const ID_LIST_SUBSCRIBE_PRIVATE = 168; // List : élèves actuels = 168
  25. const ID_LIST_SUBSCRIBE_GROUP = 169; // List : élèves Cours collectif = 169
  26. const ID_LIST_UNSUBSCRIBE_PRIVATE = 140; // List : Anciens élèves = 140
  27. const ID_LIST_UNSUBSCRIBE_GROUP = 167; // list : Anciens étudiants collectifs = 167
  28. const ID_LIST_MAIN = 175; // List principale
  29. public function __construct(Container $container, EntityManagerInterface $entityManager, SubscriptionOrderRepository $subscriptionOrderRepository, SessionOrderRepository $sessionOrderRepository)
  30. {
  31. $this->container = $container;
  32. $this->em = $entityManager;
  33. $Activecampaign_url = $this->container->getParameter('ACTIVECAMPAIGN_URL');
  34. $Activecampaign_api_key = $this->container->getParameter('ACTIVECAMPAIGN_API_KEY');
  35. $activeCampaign = new ActiveCampaignApi($Activecampaign_url, $Activecampaign_api_key);
  36. $this->activeCampaign = $activeCampaign;
  37. $this->Activecampaign_url = $Activecampaign_url;
  38. $this->subscriptionOrderRepository = $subscriptionOrderRepository;
  39. $this->sessionOrderRepository = $sessionOrderRepository;
  40. }
  41. public function getAllListsByName($name)
  42. {
  43. $data = [];
  44. $res = $this->activeCampaign->findListByLimit($name, 50);
  45. return $res;
  46. }
  47. public function getAllListsChoiceField()
  48. {
  49. $data = [];
  50. $res = $this->getAllListsByName('lists');
  51. foreach ($res as $e) {
  52. $data[$e->name] = $e->id;
  53. }
  54. return $data;
  55. }
  56. public function getAllTagsChoiceField()
  57. {
  58. $data = [];
  59. $res = $this->getAllListsByName('tags');
  60. //var_dump($res);
  61. foreach ($res as $e) {
  62. $data[$e->tag] = $e->tag;
  63. }
  64. return $data;
  65. }
  66. public function getOrCreateContact($order)
  67. {
  68. $contact = null;
  69. if (
  70. $order != null
  71. ) {
  72. $lastName = "";
  73. $firstName = "";
  74. $email = "";
  75. $phone = "";
  76. $participant = null;
  77. $user = null;
  78. if ($order instanceof SubscriptionOrder) {
  79. $participant = $order->getParticipant();
  80. $user = $order->getUser();
  81. }
  82. if ($order instanceof SessionOrder) {
  83. $participant = $order->getParticipant();
  84. $user = $order->getStudents();
  85. }
  86. if ($order instanceof UserPlacementTest) {
  87. $participant = $order->getParticipant();
  88. $user = $order->getUser();
  89. }
  90. if ($user != null) {
  91. $lastName = $user->getLastName();
  92. $firstName = $user->getFirstName();
  93. $email = $user->getEmail();
  94. if ($participant != null && $participant->getLastName() != "" && $participant->getFirstName() != "") {
  95. $lastName = $participant->getLastName();
  96. $firstName = $participant->getFirstName();
  97. }
  98. $phone = "";
  99. }
  100. // Find or create a contact.
  101. $contact = $this->activeCampaign->findOrCreateContact($email, $firstName, $lastName, $phone);
  102. }
  103. return $contact;
  104. }
  105. // Get Lists ID & TAGS to subscribe or unnsubscribe
  106. public function getListsAndTags($order, $isUnsubscribe = false)
  107. {
  108. $addToListPrivate = false;
  109. $addToListGroup = false;
  110. $lists = [];
  111. $tags = [];
  112. // Attacher les listes par defaut selon le type Entity
  113. $periods = [];
  114. $subjects = [];
  115. if ($order instanceof SubscriptionOrder) {
  116. // Attacher Tag language
  117. $user = $order->getUser();
  118. if ($user != null) {
  119. $tagLanguage = $user->getLanguage();
  120. // Verifier si Abonnement
  121. if (!$isUnsubscribe)
  122. $tags[] = $tagLanguage;
  123. }
  124. // Attacher Categorie Arabe or Coran
  125. $category = $order->getCategory();
  126. if ($category != null) {
  127. // Remonter tag category lors de l'abonnement
  128. $tags[] = $category->getName();
  129. }
  130. $subject = $order->getSubject();
  131. if ($subject != null) {
  132. $subjects[] = $subject->getId();
  133. // Remonter tag subject lors de l'abonnement
  134. $tags[] = $subject->getTagName();
  135. }
  136. $addToListPrivate = true;
  137. }
  138. if ($order instanceof SessionOrder) {
  139. // Attacher Tag language
  140. $user = $order->getStudents();
  141. if ($user != null) {
  142. $tagLanguage = $user->getLanguage();
  143. // Verifier si Abonnement
  144. if (!$isUnsubscribe)
  145. $tags[] = $tagLanguage;
  146. }
  147. // Attacher session Exemple : juillet2021
  148. $session = $order->getSession();
  149. if ($session != null) {
  150. // Remonter Period subject lors de l'abonnement
  151. $tags[] = $session->getPeriod();
  152. $periods[] = $session->getPeriod();
  153. // Attacher session Exemple : Niveau 1
  154. $level = $session->getLevel();
  155. if ($level != null) {
  156. // Remonter level subject lors de l'abonnement
  157. $tags[] = $level->getName();
  158. $subject = $level->getSubject();
  159. if ($subject != null) {
  160. $subjects[] = $subject->getId();
  161. // Remonter tag subject lors de l'abonnement
  162. $tags[] = $subject->getTagName();
  163. }
  164. }
  165. }
  166. $addToListGroup = true;
  167. }
  168. if ($addToListPrivate) {
  169. $lists[] = self::ID_LIST_SUBSCRIBE_PRIVATE;
  170. } elseif ($addToListGroup) {
  171. $lists[] = self::ID_LIST_SUBSCRIBE_GROUP;
  172. }
  173. // Recuperer tous les Tags avec une requette SQL si desabonnement
  174. if ($isUnsubscribe) {
  175. $tags = $this->getTagsFromAllOrdersFromDB($order, $isUnsubscribe);
  176. }
  177. $lists = array_unique($lists);
  178. $tags = array_unique($tags);
  179. $res = [
  180. "lists" => $lists,
  181. "tags" => $tags
  182. ];
  183. return (object) $res;
  184. }
  185. public function getTagsFromAllOrdersFromDB($order, $isUnsubscribe = false)
  186. {
  187. $tags = [];
  188. if ($order instanceof SubscriptionOrder) {
  189. $user = $order->getUser();
  190. if ($user != null) {
  191. // recuperer les tags
  192. // Category
  193. $field = 'category';
  194. $tagsToAdd = $this->subscriptionOrderRepository->getTagsFromSubscriptionForUser($user, $isUnsubscribe, $field);
  195. $tags = array_merge($tags, $tagsToAdd);
  196. // Subject
  197. $field = 'subject';
  198. $tagsToAdd = $this->subscriptionOrderRepository->getTagsFromSubscriptionForUser($user, $isUnsubscribe, $field);
  199. $tags = array_merge($tags, $tagsToAdd);
  200. }
  201. }
  202. if ($order instanceof SessionOrder) {
  203. // Attacher Tag language
  204. $user = $order->getStudents();
  205. if ($user != null) {
  206. // recuperer les Tags
  207. // Period
  208. $field = 'period';
  209. $tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
  210. $tags = array_merge($tags, $tagsToAdd);
  211. // Level
  212. $field = 'level';
  213. $tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
  214. $tags = array_merge($tags, $tagsToAdd);
  215. // Subject
  216. $field = 'subject';
  217. $tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
  218. $tags = array_merge($tags, $tagsToAdd);
  219. }
  220. }
  221. return $tags;
  222. }
  223. public function getListsUnsubscribe($order, $unsubscribeAll = false)
  224. {
  225. $addToListPrivate = false;
  226. $addToListGroup = false;
  227. $lists = [];
  228. // Attacher les listes par defaut
  229. if ($order instanceof SubscriptionOrder) {
  230. $addToListPrivate = true;
  231. }
  232. if ($order instanceof SessionOrder) {
  233. $addToListGroup = true;
  234. }
  235. if ($unsubscribeAll) {
  236. $lists[] = self::ID_LIST_UNSUBSCRIBE_PRIVATE;
  237. $lists[] = self::ID_LIST_UNSUBSCRIBE_GROUP;
  238. } else {
  239. if ($addToListPrivate) {
  240. $lists[] = self::ID_LIST_UNSUBSCRIBE_PRIVATE;
  241. } elseif ($addToListGroup) {
  242. $lists[] = self::ID_LIST_UNSUBSCRIBE_GROUP;
  243. }
  244. }
  245. return $lists;
  246. }
  247. // Get Lists ID to subscribe
  248. public function getListIds($listAndTags)
  249. {
  250. $res = $listAndTags->lists;
  251. return $res;
  252. }
  253. // Get TAGS to subscribe
  254. public function getTags($listAndTags)
  255. {
  256. $res = [];
  257. $tags = $listAndTags->tags;
  258. foreach ($tags as $t) {
  259. if ($t != null) {
  260. $tag = $this->activeCampaign->findTagList($t);
  261. if ($tag != null) {
  262. $res[] = $tag;
  263. }
  264. }
  265. }
  266. return $res;
  267. }
  268. /*
  269. * Subscribe a contact to a list or unsubscribe a contact from a list.
  270. *
  271. * @param int $list ID of list to remove contact from
  272. * @param int $contact ID of contact to remove from list
  273. * @param bool $subscribe TRUE to subscribe, FALSE otherwise
  274. */
  275. public function updateContactLists($listsID = [], $contactID = "", $subscribe = true)
  276. {
  277. foreach ($listsID as $listID) {
  278. $this->activeCampaign->updateListStatus($listID, $contactID, $subscribe);
  279. }
  280. }
  281. /*
  282. Add Tags to contact
  283. */
  284. public function addTagsToContact($tags, $contact)
  285. {
  286. foreach ($tags as $tag) {
  287. //$tag = $this->activeCampaign->findTag($nameTag);
  288. $this->activeCampaign->addTagToContact($contact, $tag);
  289. }
  290. return $tags;
  291. }
  292. /*
  293. * Create Contact in ActiveCampain API
  294. */
  295. public function addOrder($order)
  296. {
  297. if ($this->checkApiDown($order))
  298. return false;
  299. if ($order != null) {
  300. try {
  301. $this->subscribeContactToLists($order);
  302. } catch (\Exception $e) {
  303. $this->logFailedAction(EmailListActionLog::ACTION_SUBSCRIBE, $e, $this->buildOrderContext($order));
  304. return false;
  305. }
  306. }
  307. return true;
  308. }
  309. /*
  310. * Subscribe contact to lists
  311. */
  312. public function subscribeContactToLists($order)
  313. {
  314. // Cree Contact dans ActiveCampaign
  315. $contact = $this->getOrCreateContact($order);
  316. if ($contact != null) {
  317. $contactID = $contact->id;
  318. $listAndTags = $this->getListsAndTags($order);
  319. $listsID = $this->getListIds($listAndTags);
  320. $tags = $this->getTags($listAndTags);
  321. $subscribe = true;
  322. $this->updateContactLists($listsID, $contactID, $subscribe);
  323. $this->addTagsToContact($tags, $contact);
  324. // Abonner à la liste principale
  325. $this->activeCampaign->updateListStatus(self::ID_LIST_MAIN, $contactID, true);
  326. // Unsubscribe contact in lists Archive
  327. $listsID = $this->getListsUnsubscribe($order);
  328. $subscribe = false;
  329. $this->updateContactLists($listsID, $contactID, $subscribe);
  330. }
  331. }
  332. /*
  333. * Unsubscribe contact from Old Lists
  334. */
  335. public function unsubscribeOrder($order)
  336. {
  337. if ($order != null) {
  338. try {
  339. $this->unsubscribeContactToLists($order);
  340. } catch (\Exception $e) {
  341. $this->logFailedAction(EmailListActionLog::ACTION_UNSUBSCRIBE, $e, $this->buildOrderContext($order));
  342. }
  343. }
  344. }
  345. public function removeTagsContact($contact, $tags)
  346. {
  347. foreach ($tags as $tag) {
  348. $this->activeCampaign->removeTagFromContact($contact, $tag);
  349. }
  350. }
  351. public function unsubscribeContactToLists($order)
  352. {
  353. // Cree Contact dans ActiveCampaign
  354. $contact = $this->getOrCreateContact($order);
  355. if ($contact != null) {
  356. $contactID = $contact->id;
  357. $isUnsubscribe = true;
  358. $listAndTags = $this->getListsAndTags($order, $isUnsubscribe);
  359. $listsID = $this->getListIds($listAndTags);
  360. $tags = $this->getTags($listAndTags);
  361. // Check if active SessionOrder or SubscriptionOrder exist
  362. $ordersActiveExist = $this->checkOrderSActiveExist($order);
  363. if ($ordersActiveExist) {
  364. // Unsubscribe from Lists ( Anciens élèves , Anciens étudiants collectifs )
  365. $listsID = $this->getListsUnsubscribe($order);
  366. $subscribe = false;
  367. $this->updateContactLists($listsID, $contactID, $subscribe);
  368. } else {
  369. // Unsubscribe from All Lists
  370. $subscribe = false;
  371. $this->updateContactLists($listsID, $contactID, $subscribe);
  372. // Subscribe contact in lists Archive
  373. $listsID = $this->getListsUnsubscribe($order);
  374. $subscribe = true;
  375. $this->updateContactLists($listsID, $contactID, $subscribe);
  376. }
  377. // Remove tags contact
  378. $this->removeTagsContact($contact, $tags);
  379. // add log
  380. $this->addLogUnsubscribeLog($order);
  381. }
  382. }
  383. public function checkOrderSActiveExist($order)
  384. {
  385. // verifier si order actif existe
  386. $exist = false;
  387. $nbOrders = 0;
  388. if ($order instanceof SubscriptionOrder) {
  389. $user = $order->getUser();
  390. $nbOrders = $this->subscriptionOrderRepository->getNumberActiveSubscriptionForUser($user);
  391. }
  392. if ($order instanceof SessionOrder) {
  393. $user = $order->getStudents();
  394. $nbOrders = $this->sessionOrderRepository->getNumberActiveSessionsForUser($user);
  395. }
  396. //echo " nbOrders : $nbOrders <br> ";
  397. if ($nbOrders > 0) {
  398. $exist = true;
  399. }
  400. return $exist;
  401. }
  402. public function addLogUnsubscribeLog($order)
  403. {
  404. //Ajouter log lors de désabonemement
  405. $emailListUnsubscribeLog = new EmailListUnsubscribeLog();
  406. if ($order instanceof SubscriptionOrder) {
  407. $emailListUnsubscribeLog->setSubscriptionOrder($order);
  408. }
  409. if ($order instanceof SessionOrder) {
  410. $emailListUnsubscribeLog->setSessionOrder($order);
  411. }
  412. $this->em->persist($emailListUnsubscribeLog);
  413. //$this->em->flush();
  414. }
  415. function checkApiDown($order)
  416. {
  417. if (!$this->checkOnline()) {
  418. $this->addLogSubscribeLostLog($order);
  419. return true;
  420. }
  421. return false;
  422. }
  423. function checkOnline()
  424. {
  425. $domain = $this->Activecampaign_url;
  426. $curlInit = curl_init($domain);
  427. curl_setopt($curlInit, CURLOPT_CONNECTTIMEOUT, 10);
  428. curl_setopt($curlInit, CURLOPT_HEADER, true);
  429. curl_setopt($curlInit, CURLOPT_NOBODY, true);
  430. curl_setopt($curlInit, CURLOPT_RETURNTRANSFER, true);
  431. $response = curl_exec($curlInit);
  432. $httpCode = curl_getinfo($curlInit, CURLINFO_HTTP_CODE);
  433. curl_close($curlInit);
  434. return $response !== false && $httpCode >= 200 && $httpCode < 300;
  435. }
  436. private function buildOrderContext($order): array
  437. {
  438. if ($order instanceof SubscriptionOrder) {
  439. return ['subscriptionOrder' => $order];
  440. }
  441. if ($order instanceof SessionOrder) {
  442. return ['sessionOrder' => $order];
  443. }
  444. return [];
  445. }
  446. private function logFailedAction(string $action, \Throwable $e, array $context = []): void
  447. {
  448. $log = new EmailListActionLog();
  449. $log->setAction($action);
  450. $log->setLastError($e->getMessage());
  451. if (!empty($context['subscriptionOrder'])) {
  452. $log->setSubscriptionOrder($context['subscriptionOrder']);
  453. }
  454. if (!empty($context['sessionOrder'])) {
  455. $log->setSessionOrder($context['sessionOrder']);
  456. }
  457. if (!empty($context['userPlacementTest'])) {
  458. $log->setUserPlacementTest($context['userPlacementTest']);
  459. }
  460. if (!empty($context['session'])) {
  461. $log->setSession($context['session']);
  462. }
  463. if (!empty($context['user'])) {
  464. $log->setUser($context['user']);
  465. }
  466. if (!empty($context['child'])) {
  467. $log->setChild($context['child']);
  468. }
  469. if (!empty($context['extraData'])) {
  470. $log->setExtraData($context['extraData']);
  471. }
  472. $this->em->persist($log);
  473. $this->em->flush();
  474. }
  475. public function addLogSubscribeLostLog($order)
  476. {
  477. //Ajouter log lors de désabonemement
  478. $emailListSubscribeLostLog = new EmailListSubscribeLostLog();
  479. if ($order instanceof SubscriptionOrder) {
  480. $emailListSubscribeLostLog->setSubscriptionOrder($order);
  481. }
  482. if ($order instanceof SessionOrder) {
  483. $emailListSubscribeLostLog->setSessionOrder($order);
  484. }
  485. $this->em->persist($emailListSubscribeLostLog);
  486. $this->em->flush();
  487. }
  488. //fait par moi
  489. public function sendTagToActiveCampaing($tag, $user, $participant)
  490. {
  491. if ($user != null) {
  492. try {
  493. $this->doSendTag($tag, $user, $participant);
  494. return true;
  495. } catch (\Exception $e) {
  496. $this->logFailedAction(EmailListActionLog::ACTION_SEND_TAG, $e, [
  497. 'user' => $user,
  498. 'child' => $participant,
  499. 'extraData' => ['tag' => $tag],
  500. ]);
  501. return false;
  502. }
  503. }
  504. return false;
  505. }
  506. private function doSendTag($tag, $user, $participant): void
  507. {
  508. $lastName = $user->getLastName();
  509. $firstName = $user->getFirstName();
  510. $email = $user->getEmail();
  511. $gender = $user->getGender()->getName();
  512. $language = $user->getLanguage();
  513. if ($participant !== null) {
  514. $lastName = $participant->getLastName();
  515. $firstName = $participant->getFirstName();
  516. $gender = $participant->getGender()->getName();
  517. }
  518. $contact = $this->activeCampaign->updateOrCreateContact($email, $firstName, $lastName, "");
  519. $this->activeCampaign->addTagsToContact($contact, [$tag, $gender, $language]);
  520. }
  521. /**
  522. * @param SessionOrder $order
  523. */
  524. function removeOrder($order)
  525. {
  526. try {
  527. $this->doRemoveOrder($order);
  528. } catch (\Exception $e) {
  529. $this->logFailedAction(EmailListActionLog::ACTION_REMOVE, $e, $this->buildOrderContext($order));
  530. }
  531. }
  532. private function doRemoveOrder($order): void
  533. {
  534. $contact = $this->getOrCreateContact($order);
  535. if ($contact !== null) {
  536. $contactID = $contact->id;
  537. $listAndTags = $this->getListsAndTags($order);
  538. $listsID = $this->getListIds($listAndTags);
  539. $tags = $this->getTags($listAndTags);
  540. $period = $order->getSession()->getPeriod();
  541. $level = $order->getSession()->getLevel();
  542. $subject = $level->getSubject();
  543. $otherSessionsInfo = ['period' => 0, 'level' => 0, 'subject' => 0];
  544. foreach ($order->getStudents()->getSessionOrder() as $sessionOrder) {
  545. if ($sessionOrder->getIsActif()) {
  546. if ($sessionOrder->getSession()->getPeriod() == $period) {
  547. $otherSessionsInfo['period']++;
  548. }
  549. if ($sessionOrder->getSession()->getLevel() == $level) {
  550. $otherSessionsInfo['level']++;
  551. }
  552. if ($sessionOrder->getSession()->getLevel()->getSubject() == $subject) {
  553. $otherSessionsInfo['subject']++;
  554. }
  555. }
  556. }
  557. foreach ($tags as $tag) {
  558. if ($order->getSession()->getPeriod() == $tag->tag && $otherSessionsInfo['period'] == 0) {
  559. $this->activeCampaign->removeTagFromContact($contact, $tag);
  560. }
  561. if ($order->getSession()->getLevel()->getName() == $tag->tag && $otherSessionsInfo['level'] == 0) {
  562. $this->activeCampaign->removeTagFromContact($contact, $tag);
  563. }
  564. if ($order->getSession()->getLevel()->getSubject() == $tag->tag && $otherSessionsInfo['subject'] == 0) {
  565. $this->activeCampaign->removeTagFromContact($contact, $tag);
  566. }
  567. }
  568. $this->updateContactLists($listsID, $contactID, false);
  569. }
  570. }
  571. /**
  572. * Trouve ou crée un contact AC, l'abonne à la liste donnée et lui ajoute le tag (créé si absent).
  573. *
  574. * @param SubscriptionOrder|SessionOrder $order
  575. * @param string $tagName
  576. * @param int $listId
  577. * @return bool
  578. */
  579. public function addCustomTagToContact($order, string $tagName, int $listId): bool
  580. {
  581. try {
  582. $this->doAddCustomTagToContact($order, $tagName, $listId);
  583. return true;
  584. } catch (\Exception $e) {
  585. $context = $this->buildOrderContext($order);
  586. $context['extraData'] = ['tagName' => $tagName, 'listId' => $listId];
  587. $this->logFailedAction(EmailListActionLog::ACTION_ADD_CUSTOM_TAG, $e, $context);
  588. return false;
  589. }
  590. }
  591. private function doAddCustomTagToContact($order, string $tagName, int $listId): void
  592. {
  593. $contact = $this->getOrCreateContact($order);
  594. if ($contact === null) {
  595. return;
  596. }
  597. $this->activeCampaign->updateListStatus($listId, $contact->id, true);
  598. $tag = $this->activeCampaign->findTagList($tagName);
  599. if ($tag !== null) {
  600. $this->activeCampaign->addTagToContact($contact, $tag);
  601. }
  602. }
  603. public function updateCustomFieldLastLevelTestForContact($contactEmail, Session $session)
  604. {
  605. try {
  606. $this->doUpdateFieldLevel($contactEmail, $session);
  607. } catch (\Exception $e) {
  608. $this->logFailedAction(EmailListActionLog::ACTION_UPDATE_FIELD_LEVEL, $e, [
  609. 'session' => $session,
  610. 'extraData' => ['contactEmail' => $contactEmail],
  611. ]);
  612. }
  613. }
  614. private function doUpdateFieldLevel(string $contactEmail, Session $session): void
  615. {
  616. $fieldID = null;
  617. $fieldDateID = null;
  618. switch ($session->getLevel()->getSubject()->getId()) {
  619. case 1:
  620. $fieldID = "Last Level AL KAAMIL";
  621. $fieldDateID = "Last Level AL KAAMIL DATE";
  622. break;
  623. case 33:
  624. $fieldID = "Last Level TAKALLAM";
  625. $fieldDateID = "Last Level TAKALLAM DATE";
  626. break;
  627. }
  628. $value = $session->getLevel()->getLevel();
  629. if ($fieldID !== null) {
  630. $contact = $this->activeCampaign->findContact($contactEmail);
  631. if ($contact instanceof Contact) {
  632. $customField = $this->activeCampaign->findCustomField($fieldID);
  633. if ($customField instanceof CustomField) {
  634. $this->activeCampaign->addCustomFieldToContact($contact, $customField, $value);
  635. }
  636. $customFieldDate = $this->activeCampaign->findCustomField($fieldDateID);
  637. if ($customFieldDate instanceof CustomField) {
  638. $this->activeCampaign->addCustomFieldToContact($contact, $customFieldDate, date('d/m/Y'));
  639. }
  640. }
  641. }
  642. }
  643. public function updateCustomFieldLastTestResultForContact($contactEmail, UserPlacementTest $userPlacementTest)
  644. {
  645. try {
  646. $this->doUpdateFieldTest($contactEmail, $userPlacementTest);
  647. } catch (\Exception $e) {
  648. $this->logFailedAction(EmailListActionLog::ACTION_UPDATE_FIELD_TEST, $e, [
  649. 'userPlacementTest' => $userPlacementTest,
  650. 'extraData' => ['contactEmail' => $contactEmail],
  651. ]);
  652. }
  653. }
  654. private function doUpdateFieldTest(string $contactEmail, UserPlacementTest $userPlacementTest): void
  655. {
  656. $fieldID = null;
  657. $fieldDateID = null;
  658. switch ($userPlacementTest->getSubject()->getId()) {
  659. case 1:
  660. $fieldID = "Level Test Result AL KAAMIL";
  661. $fieldDateID = "Last Level Test Result AL KAAMIL DATE";
  662. break;
  663. case 33:
  664. $fieldID = "Level Test Result TAKALLAM";
  665. $fieldDateID = "Last Level Test Result TAKALLAM DATE";
  666. break;
  667. }
  668. if ($fieldID !== null) {
  669. $contact = $this->activeCampaign->findContact($contactEmail);
  670. if ($contact instanceof Contact) {
  671. $customField = $this->activeCampaign->findCustomField($fieldID);
  672. if ($customField instanceof CustomField) {
  673. $this->activeCampaign->addCustomFieldToContact($contact, $customField, $userPlacementTest->getTestResult()->getLevel());
  674. }
  675. $customFieldDate = $this->activeCampaign->findCustomField($fieldDateID);
  676. if ($customFieldDate instanceof CustomField) {
  677. $this->activeCampaign->addCustomFieldToContact($contact, $customFieldDate, date('d/m/Y'));
  678. }
  679. }
  680. }
  681. }
  682. public function addTagsForPlacementTest(array $tags, UserPlacementTest $userPlacementTest): void
  683. {
  684. try {
  685. $this->doAddTagsForPlacementTest($tags, $userPlacementTest);
  686. } catch (\Exception $e) {
  687. $this->logFailedAction(EmailListActionLog::ACTION_ADD_TAGS_PLACEMENT, $e, [
  688. 'userPlacementTest' => $userPlacementTest,
  689. 'extraData' => ['tags' => $tags],
  690. ]);
  691. }
  692. }
  693. private function doAddTagsForPlacementTest(array $tagNames, UserPlacementTest $userPlacementTest): void
  694. {
  695. $contact = $this->getOrCreateContact($userPlacementTest);
  696. if ($contact !== null) {
  697. $resolvedTags = [];
  698. foreach ($tagNames as $tagName) {
  699. $tag = $this->activeCampaign->findTagList($tagName);
  700. if ($tag !== null) {
  701. $resolvedTags[] = $tag;
  702. }
  703. }
  704. $this->addTagsToContact($resolvedTags, $contact);
  705. }
  706. }
  707. /**
  708. * Exécute l'action d'un EmailListActionLog sans intercepter les exceptions.
  709. * Utilisé par la commande de retry pour pouvoir mettre à jour l'entrée de log existante.
  710. *
  711. * @throws \Exception si l'action échoue ou si les données requises sont manquantes
  712. */
  713. public function executeAction(EmailListActionLog $log): void
  714. {
  715. $action = $log->getAction();
  716. $subscriptionOrder = $log->getSubscriptionOrder();
  717. $sessionOrder = $log->getSessionOrder();
  718. $order = $subscriptionOrder ?? $sessionOrder;
  719. $extraData = $log->getExtraData() ?? [];
  720. switch ($action) {
  721. case EmailListActionLog::ACTION_SUBSCRIBE:
  722. if ($order === null) {
  723. throw new \RuntimeException('Order manquant pour action subscribe.');
  724. }
  725. $this->subscribeContactToLists($order);
  726. break;
  727. case EmailListActionLog::ACTION_UNSUBSCRIBE:
  728. if ($order === null) {
  729. throw new \RuntimeException('Order manquant pour action unsubscribe.');
  730. }
  731. $this->unsubscribeContactToLists($order);
  732. break;
  733. case EmailListActionLog::ACTION_REMOVE:
  734. if ($sessionOrder === null) {
  735. throw new \RuntimeException('SessionOrder manquant pour action remove.');
  736. }
  737. $this->doRemoveOrder($sessionOrder);
  738. break;
  739. case EmailListActionLog::ACTION_UPDATE_FIELD_LEVEL:
  740. if ($log->getSession() === null || empty($extraData['contactEmail'])) {
  741. throw new \RuntimeException('Session ou contactEmail manquant pour action update_field_level.');
  742. }
  743. $this->doUpdateFieldLevel($extraData['contactEmail'], $log->getSession());
  744. break;
  745. case EmailListActionLog::ACTION_UPDATE_FIELD_TEST:
  746. if ($log->getUserPlacementTest() === null || empty($extraData['contactEmail'])) {
  747. throw new \RuntimeException('UserPlacementTest ou contactEmail manquant pour action update_field_test.');
  748. }
  749. $this->doUpdateFieldTest($extraData['contactEmail'], $log->getUserPlacementTest());
  750. break;
  751. case EmailListActionLog::ACTION_SEND_TAG:
  752. if ($log->getUser() === null || empty($extraData['tag'])) {
  753. throw new \RuntimeException('User ou tag manquant pour action send_tag.');
  754. }
  755. $this->doSendTag($extraData['tag'], $log->getUser(), $log->getChild());
  756. break;
  757. case EmailListActionLog::ACTION_ADD_CUSTOM_TAG:
  758. if ($order === null || empty($extraData['tagName']) || !isset($extraData['listId'])) {
  759. throw new \RuntimeException('Order, tagName ou listId manquant pour action add_custom_tag.');
  760. }
  761. $this->doAddCustomTagToContact($order, $extraData['tagName'], (int) $extraData['listId']);
  762. break;
  763. case EmailListActionLog::ACTION_ADD_TAGS_PLACEMENT:
  764. if ($log->getUserPlacementTest() === null || empty($extraData['tags'])) {
  765. throw new \RuntimeException('UserPlacementTest ou tags manquant pour action add_tags_placement.');
  766. }
  767. $this->doAddTagsForPlacementTest($extraData['tags'], $log->getUserPlacementTest());
  768. break;
  769. default:
  770. throw new \RuntimeException(sprintf('Action inconnue : "%s".', $action));
  771. }
  772. }
  773. }