src/Service/ActiveCampaignHelper.php line 37

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\ActiveCampainUnsubscribeLog;
  10. use App\Entity\ActiveCampainSubscribeLostLog;
  11. use App\Repository\SubscriptionOrderRepository;
  12. use App\Repository\SessionOrderRepository;
  13. use TestMonitor\ActiveCampaign\Resources\Contact;
  14. use TestMonitor\ActiveCampaign\Resources\CustomField;
  15. class ActiveCampaignHelper
  16. {
  17.     protected $container;
  18.     protected $em;
  19.     private $activeCampaign;
  20.     private $Activecampaign_url;
  21.     private $subscriptionOrderRepository;
  22.     private $sessionOrderRepository;
  23.     const ID_LIST_SUBSCRIBE_PRIVATE 168;   // List : élèves actuels = 168
  24.     const ID_LIST_SUBSCRIBE_GROUP 169;     // List : élèves Cours collectif = 169
  25.     const ID_LIST_UNSUBSCRIBE_PRIVATE 140// List : Anciens élèves  = 140
  26.     const ID_LIST_UNSUBSCRIBE_GROUP 167;   // list : Anciens étudiants collectifs = 167
  27.     public function __construct(Container $containerEntityManagerInterface $entityManagerSubscriptionOrderRepository $subscriptionOrderRepositorySessionOrderRepository $sessionOrderRepository)
  28.     {
  29.         $this->container $container;
  30.         $this->em $entityManager;
  31.         $Activecampaign_url $this->container->getParameter('ACTIVECAMPAIGN_URL');
  32.         $Activecampaign_api_key $this->container->getParameter('ACTIVECAMPAIGN_API_KEY');
  33.         $activeCampaign = new ActiveCampaignApi($Activecampaign_url$Activecampaign_api_key);
  34.         $this->activeCampaign $activeCampaign;
  35.         $this->Activecampaign_url $Activecampaign_url;
  36.         $this->subscriptionOrderRepository $subscriptionOrderRepository;
  37.         $this->sessionOrderRepository $sessionOrderRepository;
  38.     }
  39.     public function getAllListsByName($name)
  40.     {
  41.         $data = [];
  42.         $res $this->activeCampaign->findListByLimit($name50);
  43.         return $res;
  44.     }
  45.     public function getAllListsChoiceField()
  46.     {
  47.         $data = [];
  48.         $res $this->getAllListsByName('lists');
  49.         foreach ($res as $e) {
  50.             $data[$e->name] = $e->id;
  51.         }
  52.         return $data;
  53.     }
  54.     public function getAllTagsChoiceField()
  55.     {
  56.         $data = [];
  57.         $res $this->getAllListsByName('tags');
  58.         //var_dump($res);
  59.         foreach ($res as $e) {
  60.             $data[$e->tag] = $e->tag;
  61.         }
  62.         return $data;
  63.     }
  64.     public function getOrCreateContact($order)
  65.     {
  66.         $contact null;
  67.         if (
  68.             $order != null
  69.         ) {
  70.             $lastName "";
  71.             $firstName "";
  72.             $email "";
  73.             $phone "";
  74.             $participant null;
  75.             $user null;
  76.             if ($order instanceof SubscriptionOrder) {
  77.                 $participant $order->getParticipant();
  78.                 $user $order->getUser();
  79.             }
  80.             if ($order instanceof SessionOrder) {
  81.                 $participant $order->getParticipant();
  82.                 $user $order->getStudents();
  83.             }
  84.             if ($order instanceof UserPlacementTest) {
  85.                 $participant $order->getParticipant();
  86.                 $user $order->getUser();
  87.             }
  88.             if ($user != null) {
  89.                 $lastName $user->getLastName();
  90.                 $firstName $user->getFirstName();
  91.                 $email $user->getEmail();
  92.                 if ($participant != null && $participant->getLastName() != "" && $participant->getFirstName() != "") {
  93.                     $lastName $participant->getLastName();
  94.                     $firstName $participant->getFirstName();
  95.                 }
  96.                 $phone "";
  97.             }
  98.                                     
  99.             // Find or create a contact.
  100.             $contact $this->activeCampaign->findOrCreateContact($email$firstName$lastName$phone);
  101.         }
  102.         return $contact;
  103.     }
  104.     // Get Lists ID & TAGS to subscribe or unnsubscribe
  105.     public function getListsAndTags($order$isUnsubscribe  false)
  106.     {
  107.         $addToListPrivate false;
  108.         $addToListGroup false;
  109.         $lists = [];
  110.         $tags = [];
  111.         // Attacher les listes par defaut selon le type Entity
  112.         $periods = [];
  113.         $subjects = [];
  114.         if ($order instanceof SubscriptionOrder) {
  115.             // Attacher Tag language 
  116.             $user $order->getUser();
  117.             if ($user != null) {
  118.                 $tagLanguage $user->getLanguage();
  119.                 // Verifier si Abonnement
  120.                 if (!$isUnsubscribe)
  121.                     $tags[] = $tagLanguage;
  122.             }
  123.             // Attacher Categorie Arabe or Coran
  124.             $category $order->getCategory();
  125.             if ($category != null) {
  126.                 // Remonter tag category lors de l'abonnement 
  127.                 $tags[] = $category->getName();
  128.             }
  129.             $subject $order->getSubject();
  130.             if ($subject != null) {
  131.                 $subjects[] = $subject->getId();
  132.                 // Remonter tag subject lors de l'abonnement 
  133.                 $tags[] = $subject->getTagName();
  134.             }
  135.             $addToListPrivate true;
  136.         }
  137.         if ($order instanceof SessionOrder) {
  138.             // Attacher Tag language 
  139.             $user $order->getStudents();
  140.             if ($user != null) {
  141.                 $tagLanguage $user->getLanguage();
  142.                 // Verifier si Abonnement
  143.                 if (!$isUnsubscribe)
  144.                     $tags[] = $tagLanguage;
  145.             }
  146.             // Attacher session Exemple : juillet2021
  147.             $session $order->getSession();
  148.             if ($session != null) {
  149.                 // Remonter Period subject lors de l'abonnement 
  150.                 $tags[] = $session->getPeriod();
  151.                 $periods[] = $session->getPeriod();
  152.                 // Attacher session Exemple : Niveau 1
  153.                 $level $session->getLevel();
  154.                 if ($level != null) {
  155.                     // Remonter level subject lors de l'abonnement 
  156.                     $tags[] = $level->getName();
  157.                     $subject $level->getSubject();
  158.                     if ($subject != null) {
  159.                         $subjects[] = $subject->getId();
  160.                         // Remonter tag subject lors de l'abonnement 
  161.                         $tags[] = $subject->getTagName();
  162.                     }
  163.                 }
  164.             }
  165.             $addToListGroup true;
  166.         }
  167.         if ($addToListPrivate) {
  168.             $lists[] = self::ID_LIST_SUBSCRIBE_PRIVATE;
  169.         } elseif ($addToListGroup) {
  170.             $lists[] = self::ID_LIST_SUBSCRIBE_GROUP;
  171.         }
  172.         // Recuperer tous les Tags avec une requette SQL si desabonnement
  173.         if ($isUnsubscribe) {
  174.             $tags $this->getTagsFromAllOrdersFromDB($order$isUnsubscribe);
  175.         }
  176.         $lists array_unique($lists);
  177.         $tags array_unique($tags);
  178.         
  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.         // Get Participant from SubscriptionOrder
  300.         if ($order != null) {
  301.             $this->subscribeContactToLists($order);
  302.         }
  303.         return true;
  304.     }
  305.     /*
  306.     *    Subscribe contact to lists
  307.     */
  308.     public function subscribeContactToLists($order)
  309.     {
  310.         //  Cree Contact dans ActiveCampaign
  311.         $contact $this->getOrCreateContact($order);
  312.         if ($contact != null) {
  313.             $contactID $contact->id;
  314.             $listAndTags $this->getListsAndTags($order);
  315.             $listsID $this->getListIds($listAndTags);
  316.             $tags $this->getTags($listAndTags);
  317.             $subscribe true;
  318.             $this->updateContactLists($listsID$contactID$subscribe);
  319.             $this->addTagsToContact($tags$contact);
  320.             // Unsubscribe contact in lists Archive
  321.             $listsID $this->getListsUnsubscribe($order);
  322.             $subscribe false;
  323.             $this->updateContactLists($listsID$contactID$subscribe);
  324.         }
  325.     }
  326.     /*
  327.     *    Unsubscribe contact from Old Lists
  328.     */
  329.     public function unsubscribeOrder($order)
  330.     {
  331.         // Get Participant from SubscriptionOrder
  332.         if ($order != null) {
  333.             $this->unsubscribeContactToLists($order);
  334.         }
  335.     }
  336.     public function removeTagsContact($contact$tags)
  337.     {
  338.         foreach ($tags as $tag) {
  339.             $this->activeCampaign->removeTagFromContact($contact$tag);
  340.         }
  341.     }
  342.     public function unsubscribeContactToLists($order)
  343.     {
  344.         //  Cree Contact dans ActiveCampaign
  345.         $contact $this->getOrCreateContact($order);
  346.         if ($contact != null) {
  347.             $contactID $contact->id;
  348.             $isUnsubscribe true;
  349.             $listAndTags $this->getListsAndTags($order$isUnsubscribe);
  350.             $listsID $this->getListIds($listAndTags);
  351.             $tags $this->getTags($listAndTags);
  352.             // Check if active SessionOrder or SubscriptionOrder exist
  353.             $ordersActiveExist $this->checkOrderSActiveExist($order);
  354.             if ($ordersActiveExist) {
  355.                 // Unsubscribe from Lists ( Anciens élèves , Anciens étudiants collectifs )
  356.                 $listsID $this->getListsUnsubscribe($order);
  357.                 $subscribe false;
  358.                 $this->updateContactLists($listsID$contactID$subscribe);
  359.             } else {
  360.                 // Unsubscribe from All Lists  
  361.                 $subscribe false;
  362.                 $this->updateContactLists($listsID$contactID$subscribe);
  363.                 // Subscribe contact in lists Archive
  364.                 $listsID $this->getListsUnsubscribe($order);
  365.                 $subscribe true;
  366.                 $this->updateContactLists($listsID$contactID$subscribe);
  367.             }
  368.             // Remove tags contact
  369.             $this->removeTagsContact($contact$tags);
  370.             // add log 
  371.             $this->addLogUnsubscribeLog($order);
  372.         }
  373.     }
  374.     public function checkOrderSActiveExist($order)
  375.     {
  376.         // verifier si order actif existe
  377.         $exist false;
  378.         $nbOrders 0;
  379.         if ($order instanceof SubscriptionOrder) {
  380.             $user $order->getUser();
  381.             $nbOrders $this->subscriptionOrderRepository->getNumberActiveSubscriptionForUser($user);
  382.         }
  383.         if ($order instanceof SessionOrder) {
  384.             $user $order->getStudents();
  385.             $nbOrders $this->sessionOrderRepository->getNumberActiveSessionsForUser($user);
  386.         }
  387.         //echo " nbOrders : $nbOrders <br> ";
  388.         if ($nbOrders 0) {
  389.             $exist true;
  390.         }
  391.         return $exist;
  392.     }
  393.     public function addLogUnsubscribeLog($order)
  394.     {
  395.         //Ajouter log lors de désabonemement 
  396.         $ActiveCampainUnsubscribeLog = new ActiveCampainUnsubscribeLog();
  397.         if ($order instanceof SubscriptionOrder) {
  398.             $ActiveCampainUnsubscribeLog->setSubscription($order);
  399.         }
  400.         if ($order instanceof SessionOrder) {
  401.             $ActiveCampainUnsubscribeLog->setGroupSession($order);
  402.         }
  403.         $this->em->persist($ActiveCampainUnsubscribeLog);
  404.         //$this->em->flush();
  405.     }
  406.     function checkApiDown($order)
  407.     {
  408.         if (!$this->checkOnline()) {
  409.             $this->addLogSubscribeLostLog($order);
  410.             return true;
  411.         }
  412.         return false;
  413.     }
  414.     function checkOnline()
  415.     {
  416.         $domain $this->Activecampaign_url;
  417.         $curlInit curl_init($domain);
  418.         curl_setopt($curlInitCURLOPT_CONNECTTIMEOUT10);
  419.         curl_setopt($curlInitCURLOPT_HEADERtrue);
  420.         curl_setopt($curlInitCURLOPT_NOBODYtrue);
  421.         curl_setopt($curlInitCURLOPT_RETURNTRANSFERtrue);
  422.         //get answer
  423.         $response curl_exec($curlInit);
  424.         curl_close($curlInit);
  425.         if ($response) return true;
  426.         return false;
  427.     }
  428.     public function addLogSubscribeLostLog($order)
  429.     {
  430.         //Ajouter log lors de désabonemement 
  431.         $activeCampainSubscribeLostLog = new ActiveCampainSubscribeLostLog();
  432.         if ($order instanceof SubscriptionOrder) {
  433.             $activeCampainSubscribeLostLog->setSubscription($order);
  434.         }
  435.         if ($order instanceof SessionOrder) {
  436.             $activeCampainSubscribeLostLog->setGroupSession($order);
  437.         }
  438.         $this->em->persist($activeCampainSubscribeLostLog);
  439.         $this->em->flush();
  440.     }
  441.     //fait par moi
  442.     public function sendTagToActiveCampaing($tag,$user,$participant)
  443.     {
  444.         if ($user != null) {
  445.             $lastName $user->getLastName();
  446.             $firstName $user->getFirstName();
  447.             $email $user->getEmail();
  448.             $gender $user->getGender()->getName();
  449.             $language $user->getLanguage();
  450.             if ($participant != null) {
  451.                 $lastName $participant->getLastName();
  452.                 $firstName $participant->getFirstName();
  453.                 $gender $participant->getGender()->getName();
  454.             }
  455.             $phone "";
  456.             $contact $this->activeCampaign->updateOrCreateContact($email$firstName$lastName$phone);
  457.             $tags = [$tag$gender$language];
  458.             $this->activeCampaign->addTagsToContact($contact$tags);
  459.             return  true;
  460.         }
  461.         return false;
  462.     }
  463.     /**
  464.      * @param SessionOrder $order
  465.      */
  466.     function removeOrder($order){
  467.         $contact $this->getOrCreateContact($order);
  468.         if ($contact != null) {
  469.             $contactID $contact->id;
  470.             $listAndTags $this->getListsAndTags($order);
  471.             $listsID $this->getListIds($listAndTags);
  472.             $tags $this->getTags($listAndTags);
  473.             $period $order->getSession()->getPeriod();
  474.             $level $order->getSession()->getLevel();
  475.             $subject $level->getSubject();
  476.             
  477.             // Get other sessions info
  478.             $otherSessionsInfo = ['period' => 0'level' => 0'subject' => 0];
  479.             foreach ($order->getStudents()->getSessionOrder() as $sessionOrder){
  480.                 if($sessionOrder->getIsActif()){
  481.                     if($sessionOrder->getSession()->getPeriod() == $period){
  482.                         $otherSessionsInfo['period']++;
  483.                     }
  484.                     if($sessionOrder->getSession()->getLevel() == $level){
  485.                         $otherSessionsInfo['level']++;
  486.                     }
  487.                     if($sessionOrder->getSession()->getLevel()->getSubject() == $subject){
  488.                         $otherSessionsInfo['subject']++;
  489.                     }
  490.                 }
  491.             }
  492.             foreach ($tags as $key => $tag) {
  493.                 if ($order->getSession()->getPeriod() == $tag->tag && $otherSessionsInfo['period'] == 0) {
  494.                     $this->activeCampaign->removeTagFromContact($contact$tag);
  495.                 }
  496.                 if ($order->getSession()->getLevel()->getName() == $tag->tag && $otherSessionsInfo['level'] == 0) {
  497.                     $this->activeCampaign->removeTagFromContact($contact$tag);
  498.                 }
  499.                 if ($order->getSession()->getLevel()->getSubject() == $tag->tag && $otherSessionsInfo['subject'] == 0) {
  500.                     $this->activeCampaign->removeTagFromContact($contact$tag);
  501.                 }
  502.             }
  503.             $this->updateContactLists($listsID$contactIDfalse);
  504.         }
  505.     }
  506.     public function updateCustomFieldLastLevelTestForContact($contactEmailSession $session) {
  507.         $fieldID null;
  508.         $fieldDateID null;
  509.         switch ($session->getLevel()->getSubject()->getId()) {
  510.             case 1:
  511.                 $fieldID "Last Level AL KAAMIL"//8;
  512.                 $fieldDateID "Last Level AL KAAMIL DATE"//13;
  513.                 break;
  514.             case 33:
  515.                 $fieldID "Last Level TAKALLAM"//6;
  516.                 $fieldDateID "Last Level TAKALLAM DATE"//14;
  517.                 break;
  518.         }
  519.         $value $session->getLevel()->getLevel();
  520.         if($fieldID !== null) {
  521.             $contact $this->activeCampaign->findContact($contactEmail);
  522.             if ($contact instanceof Contact) {
  523.                 $customField $this->activeCampaign->findCustomField($fieldID);
  524.                 if ($customField instanceof CustomField) {
  525.                     $this->activeCampaign->addCustomFieldToContact($contact$customField$value);
  526.                 }
  527.                 $customFieldDate $this->activeCampaign->findCustomField($fieldDateID);
  528.                 if ($customFieldDate instanceof CustomField) {
  529.                     $this->activeCampaign->addCustomFieldToContact($contact$customFieldDatedate('d/m/Y'));
  530.                 }
  531.             }
  532.         }
  533.     }
  534.     public function updateCustomFieldLastTestResultForContact($contactEmailUserPlacementTest $userPlacementTest) {
  535.         $fieldID null;
  536.         $fieldDateID null;
  537.         switch ($userPlacementTest->getSubject()->getId()) {
  538.             case 1:
  539.                 $fieldID "Level Test Result AL KAAMIL";// 7;
  540.                 $fieldDateID "Last Level Test Result AL KAAMIL DATE"//11;
  541.                 break;
  542.             case 33:
  543.                 $fieldID "Level Test Result TAKALLAM"// 9;
  544.                 $fieldDateID "Last Level Test Result TAKALLAM DATE"//12;
  545.                 break;
  546.         }
  547.         if($fieldID !== null) {
  548.             $contact $this->activeCampaign->findContact($contactEmail);
  549.             if ($contact instanceof Contact) {
  550.                 $customField $this->activeCampaign->findCustomField($fieldID);
  551.                 if ($customField instanceof CustomField) {
  552.                     $this->activeCampaign->addCustomFieldToContact($contact$customField$userPlacementTest->getTestResult()->getLevel());
  553.                 }
  554.                 $customFieldDate $this->activeCampaign->findCustomField($fieldDateID);
  555.                 if ($customFieldDate instanceof CustomField) {
  556.                     $this->activeCampaign->addCustomFieldToContact($contact$customFieldDatedate('d/m/Y'));
  557.                 }
  558.             }
  559.         }
  560.     }
  561. }