src/Controller/AbonnementController.php line 4023

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AppAccount;
  4. use App\Entity\AppAccountBankDetails;
  5. use App\Entity\AppAccountHour;
  6. use App\Entity\AppAccountHourType;
  7. use App\Entity\AppAccountHourStatus;
  8. use App\Entity\AppAccountResiliation;
  9. use App\Entity\AppAccountTermination;
  10. use App\Entity\AppAccountTerminationComment;
  11. use App\Entity\AppAccountTerminationStatus;
  12. use App\Entity\AppCustomFieldValue;
  13. use App\Entity\AppMailAccount;
  14. use App\Entity\AppMailAccountBox;
  15. use App\Entity\AppMailServer;
  16. use App\Entity\AppMailTemplate;
  17. use App\Entity\AppService;
  18. use App\Entity\AppServiceCategory;
  19. use App\Entity\AppServiceMarketing;
  20. use App\Entity\AppTermsOfService;
  21. use App\Entity\AppUser;
  22. use App\Entity\AppUserType;
  23. use App\Entity\AppUserTypeAdmin;
  24. use App\Entity\coefficy2\AppHistoryEvent;
  25. use App\Entity\coefficy2\AppHistoryUser;
  26. use App\Entity\RegCompany;
  27. use App\Repository\ActionLinkServices;
  28. use App\Repository\AdministrationServices;
  29. use App\Repository\AppAccountBankDetailsServices;
  30. use App\Repository\AppAccountHoursServices;
  31. use App\Repository\AppAccountTerminationServices;
  32. use App\Repository\AppCustomFieldServices;
  33. use App\Repository\AppHistoryEventServices;
  34. use App\Repository\AppMailAccountServices;
  35. use App\Repository\AppMailServerServices;
  36. use App\Repository\AppMailTemplateServices;
  37. use App\Repository\AppServiceTermServices;
  38. use App\Repository\AppTermsOfServiceServices;
  39. use App\Repository\AppUserServices;
  40. use App\Repository\AppUserTypeAdminServices;
  41. use App\Repository\AppUserTypeServices;
  42. use App\Repository\campaign\CampaignApiServices;
  43. use App\Repository\campaign\CamPersonaServices;
  44. use App\Repository\CompanyServices;
  45. use App\Repository\ConnectionServices;
  46. use App\Repository\CrmOpportunityServices;
  47. use App\Repository\CrmRelaunchServices;
  48. use App\Repository\eliott2\ApiAccountServices;
  49. use App\Repository\EncryptionService;
  50. use App\Repository\GenericFunctions;
  51. use App\Repository\LeadformServices;
  52. use App\Repository\LeBonLogicielServices;
  53. use App\Repository\RegCountryServices;
  54. use App\Repository\RoutineServices;
  55. use App\Repository\SessionUtilisateur;
  56. use App\Repository\Services_coefficy_utilisateurs;
  57. use App\Repository\SshCommandServices;
  58. use App\Repository\StaticData;
  59. use App\Repository\AppAccountServices;
  60. use App\Repository\RegCompanyServices;
  61. use App\Entity\AppServiceType;
  62. use App\Repository\AppServiceServices;
  63. use App\Repository\AppAccountTypeServices;
  64. use App\Entity\AppAccountType;
  65. use App\Repository\TrackingAbonnementServices;
  66. use Cassandra\Date;
  67. use DateTimeZone;
  68. use Egulias\EmailValidator\EmailValidator;
  69. use Egulias\EmailValidator\Validation\RFCValidation;
  70. use Exception;
  71. use FOS\CKEditorBundle\Form\Type\CKEditorType;
  72. use ReflectionClass;
  73. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  74. use Symfony\Component\Form\FormError;
  75. use Symfony\Component\HttpFoundation\RedirectResponse;
  76. use Symfony\Component\HttpFoundation\Request;
  77. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  78. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  79. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  80. use Symfony\Component\Routing\Annotation\Route;
  81. use Symfony\Component\HttpFoundation\Response;
  82. use Symfony\Component\HttpFoundation\JsonResponse;
  83. use App\Repository\CallApi;
  84. use DateTime;
  85. use Symfony\Component\HttpFoundation\RequestStack;
  86. use Symfony\Component\DependencyInjection\ContainerInterface;
  87. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  88. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  89. use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
  90. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  91. use Symfony\Component\Serializer\Serializer;
  92. use App\Repository\RechercheHourServices;
  93. /**
  94.  * Class AbonnementController
  95.  * @package App\Controller
  96.  */
  97. class AbonnementController extends BaseController
  98. {
  99.     private $_request;
  100.     private $_session;
  101.     private $_user;
  102.     private $_idAccount;
  103.     private $_siren;
  104.     private $_referenceCustomer;
  105.     private $_accountTitle;
  106.     private $_companyName;
  107.     private $_userResponsableAccount;
  108.     private $_isFreemium;
  109.     private $_isOlder;
  110.     private $_isResponsable;
  111.     private $_isAdmin;
  112.     public $_isTerminated;
  113.     private $_api;
  114.     private $_confProAbono;
  115.     private $_urlProAbono;
  116.     private $_urlBackOfficeProAbono;
  117.     private $_tokenProAbono;
  118.     private $_segmentProAbono;
  119.     private $_urlAfterSynchro;
  120.     private $idBusiness;
  121.     private $_idAccountProabono;
  122.     private $_urlBackOfficeProabonoWithService;
  123.     private $_proAbonoUserState;
  124.     private $_idCustomer;
  125.     private $_idSubscription;
  126.     private $_isTrial;
  127.     private $_isEngaged;
  128.     private $_propalExists;
  129.     private $_propalNb;
  130.     private $_deleteCgv;
  131.     private $_refresh;
  132.     private $_isDisabled;
  133.     function __construct(RequestStack $requestStackSessionInterface $sessionContainerInterface $container null) {
  134.         date_default_timezone_set('UTC');
  135.         $this->container $container;
  136.         $this->_session $session;
  137.         $this->_request $requestStack->getCurrentRequest();
  138.         $routinesRoute = array(
  139.             "new" => "newRoutine",
  140.             "update" => "updateRoutine",
  141.             "delete" => "DeleteRoutine"
  142.         );
  143.         $go true;
  144.         // Si on appelle la route refresh directement (sans id), on bloque
  145.         if($this->_request->get("_route") == "abonnement_proabono_refresh"){
  146.             throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  147.         }
  148.         // Si on trigger/forward un refresh, pas besoin de calculs
  149.         if($this->_request->get("_route") == "trigger_refresh" or is_null($this->_request->get("_route"))){
  150.             $go false;
  151.         }
  152.         if($go) {
  153.                 SessionUtilisateur::checkUtilisateur($this->_session);
  154.                 SessionUtilisateur::reload($this->_session);
  155.                 $this->_user $this->_session->get('user');
  156.                 $this->setAttribute("user"$this->_user);
  157.                 // Si on est pas responsable, on peut pas accéder à la partie abonnement
  158.                 if (!in_array($this->_user['idUserType'], AppUserType::UT_RESPONSABLE)) {
  159.                     // Sauf si routines
  160.                     if(!in_array($this->_request->get("_route"),$routinesRoute)){
  161.                         throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  162.                     }
  163.                 }
  164.                 $this->_idAccount null;
  165.                 //$this->_isAdmin = (!SessionUtilisateur::isAdmin($this->_user)) ? false : (($this->_user['idCompany'] == RegCompany::COEFFICY) ? true : false);
  166.                 $this->_isAdmin = (!SessionUtilisateur::isAdmin($this->_user)) ? false : ($this->_user['supportMode'] ? true : (in_array(AppService::ACCES_BACKOFFICE$session->get('user')['services']) ? true false));
  167.                 $this->setAttribute("isAdmin"$this->_isAdmin);
  168.                 $this->_isResponsable SessionUtilisateur::isResponsable($this->_user);
  169.                 $this->setAttribute("isResponsable"$this->_isResponsable);
  170.                 if ($this->_isAdmin) {
  171.                     if ($this->_request->query->has("idAccount")) {
  172.                         if (AppAccountServices::getAccount($this->_request->query->get("idAccount"))) {
  173.                             $idAccountCustomer AppAccountServices::getAccount($this->_request->query->get("idAccount"));
  174.                             $this->_idAccount $this->_request->query->get("idAccount");
  175.                             $this->_isFreemium = ($idAccountCustomer->getType()->getId() == AppAccountType::REFERRAL);
  176.                             $this->_userResponsableAccount AppUserServices::getUserResponsableAccount($this->_request->query->get("idAccount"), AppAccount::VenteCoeff);
  177.                             $this->_companyName $idAccountCustomer->getCompanyName();
  178.                             if ($idAccountCustomer->getIdCompany() == RegCompany::COEFFICY or $idAccountCustomer->getIdCompany() == RegCompany::BUSINESS_SHARE) {
  179.                                 $this->_referenceCustomer $idAccountCustomer->getSiren() . substr($idAccountCustomer->getId(), 041);
  180.                                 $this->_siren $idAccountCustomer->getSiren();
  181.                             } else {
  182.                                 if (is_null($idAccountCustomer->getIdCompany())) {
  183.                                     $this->_referenceCustomer null;
  184.                                     $this->_siren null;
  185.                                 } else {
  186.                                     $this->_referenceCustomer RegCompanyServices::getCompany(AppAccountServices::getAccount($this->_request->query->get("idAccount"))->getIdCompany())->getIdentifiedNumber();
  187.                                     $this->_siren RegCompanyServices::getCompany(AppAccountServices::getAccount($this->_request->query->get("idAccount"))->getIdCompany())->getIdentifiedNumber();
  188.                                 }
  189.                             }
  190.                         } else {
  191.                             throw $this->createNotFoundException("L'abonnement n'existe pas.");
  192.                         }
  193.                     } else {
  194.                         $this->_isFreemium = (SessionUtilisateur::getTypeAbonnement($this->_user) == AppAccountType::REFERRAL);
  195.                         $this->_userResponsableAccount AppUserServices::getUserResponsableAccount($this->_user['idAccount'], AppAccount::VenteCoeff);
  196.                         $this->_companyName $this->_user['companyName'];
  197.                         $this->_idAccount $this->_user['idAccount'];
  198.                         if ($this->_user['idCompany'] == RegCompany::COEFFICY or $this->_user['idCompany'] == RegCompany::BUSINESS_SHARE) {
  199.                             $this->_referenceCustomer RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber() . substr($this->_idAccount041);
  200.                             $this->_siren RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  201.                         } else {
  202.                             if (is_null($this->_user['idCompany'])) {
  203.                                 $this->_referenceCustomer null;
  204.                                 $this->_siren null;
  205.                             } else {
  206.                                 $this->_referenceCustomer RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  207.                                 $this->_siren RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  208.                             }
  209.                         }
  210.                     }
  211.                 } else {
  212.                     $this->_isFreemium = (SessionUtilisateur::getTypeAbonnement($this->_user) == AppAccountType::REFERRAL);
  213.                     $this->_userResponsableAccount AppUserServices::getUserResponsableAccount($this->_user['idAccount'], AppAccount::VenteCoeff);
  214.                     $this->_companyName $this->_user['companyName'];
  215.                     $this->_idAccount $this->_user['idAccount'];
  216.                     if ($this->_user['idCompany'] == RegCompany::COEFFICY or $this->_user['idCompany'] == RegCompany::BUSINESS_SHARE) {
  217.                         $this->_referenceCustomer RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber() . substr($this->_idAccount041);
  218.                         $this->_siren RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  219.                     } else {
  220.                         if (is_null($this->_user['idCompany'])) {
  221.                             $this->_referenceCustomer null;
  222.                             $this->_siren null;
  223.                         } else {
  224.                             $this->_referenceCustomer RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  225.                             $this->_siren RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
  226.                         }
  227.                     }
  228.                 }
  229.                 $this->_isEngaged false;
  230.                 $this->_accountTitle AppAccountServices::getAccount($this->_idAccount)->getType()->getTitle();
  231.                 $this->setAttribute("accountTitle"$this->_accountTitle);
  232.                 $this->setAttribute("isFreemium"$this->_isFreemium);
  233.                 $this->setAttribute('userResponsableAccount'$this->_userResponsableAccount);
  234.                 $this->setAttribute("siren"$this->_siren);
  235.                 $this->setAttribute("referenceCustomer"$this->_referenceCustomer);
  236.                 $this->setAttribute("companyName"$this->_companyName);
  237.                 $this->setAttribute("idAccount"$this->_idAccount);
  238.                 $this->_confProAbono BaseController::getConfig()['proabono-api'];
  239.                 $this->_urlProAbono $this->_confProAbono['url'];
  240.                 $this->setAttribute("urlProAbono"$this->_urlProAbono);
  241.                 $this->_urlBackOfficeProAbono $this->_confProAbono['url-backOffice'];
  242.                 $this->setAttribute("urlBackOfficeProAbono"$this->_urlBackOfficeProAbono);
  243.                 $this->_tokenProAbono $this->_confProAbono['token'];
  244.                 $this->_segmentProAbono $this->_confProAbono['ref-segment'];
  245.                 $this->_urlAfterSynchro $this->_confProAbono['urlAfterSynchro'];
  246.                 $this->_idBusiness $this->_confProAbono['idBusiness'];
  247.                 $this->_idAccountProabono $this->_confProAbono['idAccount'];
  248.                 $this->_urlNewBackOffice $this->_confProAbono['urlNewBackOffice'];
  249.                 $this->setAttribute("urlNewBackOffice"$this->_urlNewBackOffice);
  250.                 $this->_api = new CallApi();
  251.                 $this->_propalExists false;
  252.                 $this->_propalNb null;
  253.                 $this->_idSubscription null;
  254.                 $this->_idCustomer null;
  255.                 $this->_isOlder false;
  256.                 $this->_isTerminated false;
  257.                 $this->_isDisabled false;
  258.                 if($this->_request->get("_route") != 'Abonnement_parametre') {
  259.                     $this->_proAbonoUserState $this->getOffres($this->_api$this->_urlBackOfficeProAbono$this->_urlProAbono$this->_tokenProAbono$this->_referenceCustomer$this->_idBusiness);
  260.                     if ($this->_proAbonoUserState) {
  261.                         $this->setAttribute('propal'$this->_proAbonoUserState["propal"]);
  262.                         $this->setAttribute('isTrial'$this->_isTrial);
  263.                         $this->_idCustomer $this->_proAbonoUserState['IdCustomer'];
  264.                         $this->_idSubscription $this->_proAbonoUserState["current"]['IdActiveSubscription'];
  265.                         $this->setAttribute('idCustomer'$this->_idCustomer);
  266.                         if (is_null($this->_idSubscription)) {
  267.                             $this->_isOlder true;
  268.                             $this->_isFreemium false;
  269.                             $this->setAttribute('isOlder'true);
  270.                         } else {
  271.                             $this->setAttribute('idSubscription'$this->_idSubscription);
  272.                         }
  273.                         $this->setAttribute('isOlder'$this->_isOlder);
  274.                         if (count($this->_proAbonoUserState["propal"]) > 0) {
  275.                             $this->_propalExists true;
  276.                             $this->_propalNb count($this->_proAbonoUserState["propal"]);
  277.                         }
  278.                         $this->setAttribute("propalExists"$this->_propalExists);
  279.                         $this->setAttribute("propalNb"$this->_propalNb);
  280.                     }
  281.                     else
  282.                     {
  283.                         $this->setAttribute('isOlder'$this->_isOlder);
  284.                     }
  285.                 }
  286.                 $this->setAttribute('isDisabled',$this->_isDisabled);
  287.                 $this->_deleteCgv false;
  288.                 $this->_refresh false;
  289.         }
  290.     }
  291.     function cancelTermination($id,$nameOffer){
  292.         $terminationInProgress AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($id);
  293.         if($terminationInProgress){
  294.             if($terminationInProgress->getTerminationStatus()->getIdTerminationStatus() == AppAccountTerminationStatus::EN_RESILIATION){
  295.                 $terminationCancellationDate = new DateTime("today");
  296.                 $termination = new AppAccountTermination(
  297.                     $terminationInProgress->getIdTermination(),
  298.                     $this->_idAccount,
  299.                     $terminationInProgress->getIdSubscription(),
  300.                     new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE),
  301.                     $terminationInProgress->getTerminationReceptionDate(),
  302.                     $terminationCancellationDate,
  303.                     $terminationInProgress->getTerminationDate(),
  304.                     null
  305.                 );
  306.                 $comment = new AppAccountTerminationComment(
  307.                     null,
  308.                     $terminationInProgress->getIdTermination(),
  309.                     new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE),
  310.                     AppUserServices::getUser(AppUser::ELIOTT_ID_USER),
  311.                     "La résiliation a été annulée suite à la souscription du client à l'offre <strong>".$nameOffer."</strong>.",
  312.                     null
  313.                 );
  314.                 AppAccountTerminationServices::setTermination($termination);
  315.                 AppAccountTerminationServices::setComment($comment);
  316.             }
  317.         }
  318.     }
  319.     /**
  320.      * @Route("/Abonnement", name="Abonnement")
  321.      * @Route("/Abonnement", name="abonnement")
  322.      * @return Response
  323.      *
  324.      * @throws Exception
  325.      */
  326.     public function index(Request $request)
  327.     {
  328.         try{
  329.             $this->setAttribute('shownPart','abonnement');
  330.             $this->setAttribute('search'$request->get('search'));
  331.             $ajax false;
  332.             if($this->_isAdmin){
  333.                 if($this->_request->query->has("idc")){
  334.                     if(!empty($this->_request->query->get("idc"))){
  335.                         if($this->_request->query->get("idc") != $this->_idCustomer){
  336.                             $retrieve $this->_api->callApi("GET"$this->_urlBackOfficeProAbono "/Distribution/Customers/".$this->_request->query->get("idc")."?IdBusiness=".$this->_idBusiness$this->_tokenProAbonofalse);
  337.                             if($retrieve[1] == 200){
  338.                                 $referenceCustomer $retrieve[0]['ReferenceCustomer'];
  339.                                 if (strpos($referenceCustomer"814045571") !== false) {
  340.                                     $keyword str_replace("814045571"""$referenceCustomer);
  341.                                     $appAccount AppAccountServices::getAccountByKeyword($keyword);
  342.                                 } else if (strpos($referenceCustomer"749836292") !== false) {
  343.                                     $keyword str_replace("749836292"""$referenceCustomer);
  344.                                     $appAccount AppAccountServices::getAccountByKeyword($keyword);
  345.                                 } else {
  346.                                     $appAccount AppAccountServices::getAccountBySiren($referenceCustomer);
  347.                                 }
  348.                                 return $this->redirect($this->generateUrl(
  349.                                     'Abonnement',
  350.                                     array("idAccount" => $appAccount->getId())
  351.                                 ));
  352.                             }
  353.                         }
  354.                     }
  355.                 }
  356.             }
  357.             if($this->_deleteCgv){
  358.                 $appAccount AppAccountServices::getAccount($this->_idAccount);
  359.                 $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  360.                 foreach ($appAccount->getUsers() as $user) {
  361.                     $delete Services_coefficy_utilisateurs::deleteLastCgv($user);
  362.                 }
  363.             }
  364.             if(!$this->_isOlder){
  365.                 if(array_key_exists("Metadata",$this->_proAbonoUserState['current']['subscription']) &&
  366.                     array_key_exists("previousPropal",$this->_proAbonoUserState['current']['subscription']['Metadata'])){
  367.                     $msg "La souscription à l'offre " "<strong>" $this->_proAbonoUserState['current']['subscription']['TitleLocalized'] . "</strong>" " a bien été validée.";
  368.                     $this->setAttribute('msgAfterSubscription'$msg);
  369.                     $this->setAttribute('iconAfterSubscription'"checked");
  370.                     $this->_refresh true;
  371.                     $id $this->_proAbonoUserState['current']['subscription']['Metadata']['previousPropal'];
  372.                     $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/" $id.'?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  373.                     if($this->_propalNb 0){
  374.                         if ($this->_propalNb == 1) {
  375.                             $this->_proAbonoUserState['propal'] = [];
  376.                             $this->_propalExists false;
  377.                         }
  378.                         else{
  379.                             unset($this->_proAbonoUserState['propal'][$id]);
  380.                         }
  381.                         $this->_propalNb--;
  382.                     }
  383.                     $newMetadatas['Metadata'] = $this->_proAbonoUserState['current']['subscription']['Metadata'];
  384.                     unset($newMetadatas['Metadata']['previousPropal']);
  385.                     $update $this->_api->callApi("PATCH"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/" $this->_idSubscription'?IdBusiness='.$this->_idBusiness$this->_tokenProAbonojson_encode($newMetadatas));
  386.                     $countSubscriptions $this->_api->callApi("GET"$this->_urlBackOfficeProAbono "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$this->_idCustomer$this->_tokenProAbonofalse);
  387.                     if($countSubscriptions[1] == 200){
  388.                         $this->renameSubscription($this->_proAbonoUserState['current']['subscription']['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
  389.                     }
  390.                 }
  391.                 $this->setAttribute("propalExists"$this->_propalExists);
  392.                 $this->setAttribute("propalNb"$this->_propalNb);
  393.             }
  394.             if($this->_refresh){
  395.                 $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  396.                     'idCustomer'  => $this->_idCustomer,
  397.                     'fromTrigger' => false,
  398.                     'fromScript' => false
  399.                 ]);
  400.             }
  401.             if(!$this->_proAbonoUserState){
  402.                 throw new Exception();
  403.             }
  404.             if($this->_isTerminated and !$this->_isAdmin){
  405.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  406.             }
  407.             $this->setAttribute('isAdmin',$this->_isAdmin);
  408.             if($this->_request->isMethod("POST")){
  409.                 if($this->_request->request->has("ajax")){
  410.                     if($this->_request->request->get("ajax") == "true"){
  411.                         $ajax true;
  412.                     }
  413.                 }
  414.                 if($this->_request->request->has('addEditTermination')) {
  415.                     if($this->_isFreemium or !$this->_isAdmin or $this->_isOlder or $this->_isDisabled){
  416.                         $this->addFlash('error'"Impossible de saisir une demande de résiliation.");
  417.                     }
  418.                     else{
  419.                         $post $this->_request->request->get('addEditTermination');
  420.                         if(isset($post['status']) and !empty($post['status']) and isset($post['action']) and !empty($post['action']) ){
  421.                             if(isset($post['attachmentURL']) and !empty($post['attachmentURL']) and filter_var($post['attachmentURL'],FILTER_VALIDATE_URL) and isset($post['comment']) and !empty($post['comment'])) {
  422.                                 if($post['action'] == "new"){
  423.                                     if ($post['status'] == AppAccountTerminationStatus::EN_RESILIATION) {
  424.                                         if(isset($post['dateTermination']) and !empty($post['dateTermination'])
  425.                                             and isset($post['dateReception']) and !empty($post['dateReception'])){
  426.                                             $tomorrow = new DateTime("tomorrow");
  427.                                             $afterTomorrow = new DateTime("tomorrow + 1 day");
  428.                                             $dateTermination DateTime::createFromFormat('d/m/Y'$post['dateTermination']);
  429.                                             $dateReception DateTime::createFromFormat('d/m/Y'$post['dateReception']);
  430.                                             if($dateTermination->getTimestamp() >= $afterTomorrow->getTimeStamp() and $dateReception->getTimestamp() < $tomorrow->getTimestamp()){
  431.                                                 $termination = new AppAccountTermination(
  432.                                                     null,
  433.                                                     $this->_idAccount,
  434.                                                     $this->_idSubscription,
  435.                                                     new AppAccountTerminationStatus(AppAccountTerminationStatus::EN_RESILIATION),
  436.                                                     DateTime::createFromFormat('d/m/Y'$post['dateReception']),
  437.                                                     null,
  438.                                                     DateTime::createFromFormat('d/m/Y'$post['dateTermination']),
  439.                                                     null
  440.                                                 );
  441.                                                 $idTermination AppAccountTerminationServices::setTermination($termination);
  442.                                                 if($idTermination){
  443.                                                     $comment = new AppAccountTerminationComment(
  444.                                                         null,
  445.                                                         $idTermination,
  446.                                                         $termination->getTerminationStatus(),
  447.                                                         AppUserServices::getUser($this->_user['idUser']),
  448.                                                         $post['comment'],
  449.                                                         $post['attachmentURL']
  450.                                                     );
  451.                                                     if(AppAccountTerminationServices::setComment($comment)){
  452.                                                         $this->addFlash('success'"La demande de résiliation a bien été enregistrée.");
  453.                                                     }
  454.                                                     else{
  455.                                                         $this->addFlash('error'"Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
  456.                                                     }
  457.                                                 }
  458.                                                 else{
  459.                                                     $this->addFlash('error'"Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
  460.                                                 }
  461.                                             }
  462.                                             else{
  463.                                                 $this->addFlash('error'"La date de fin d'abonnement est erronée.");
  464.                                             }
  465.                                         }
  466.                                         else{
  467.                                             $this->addFlash('error'"La date de fin d'abonnement est manquante.");
  468.                                         }
  469.                                     }
  470.                                     else{
  471.                                         $this->addFlash('error'"Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
  472.                                     }
  473.                                 }
  474.                                 else if($post['action'] == 'update'){
  475.                                     if(isset($post['idTermination']) and !empty($post['idTermination']) and isset($post['idComment']) and !empty($post['idComment'])) {
  476.                                         $comment AppAccountTerminationServices::getCommentByIdComment($post['idComment']);
  477.                                         $termination AppAccountTerminationServices::getTerminationByIdTermination($post['idTermination']);
  478.                                         if ($comment and $termination) {
  479.                                             if ($post['status'] == AppAccountTerminationStatus::EN_RESILIATION) {
  480.                                                 if (isset($post['dateTermination']) and !empty($post['dateTermination'])
  481.                                                     and isset($post['dateReception']) and !empty($post['dateReception'])) {
  482.                                                     $tomorrow = new DateTime("tomorrow");
  483.                                                     $afterTomorrow = new DateTime("tomorrow + 1 day");
  484.                                                     $dateTermination DateTime::createFromFormat('d/m/Y'$post['dateTermination']);
  485.                                                     $dateReception DateTime::createFromFormat('d/m/Y'$post['dateReception']);
  486.                                                     if($dateTermination->getTimestamp() >= $afterTomorrow->getTimeStamp() and $dateReception->getTimestamp() < $tomorrow->getTimestamp()) {
  487.                                                         $newComment = new AppAccountTerminationComment(
  488.                                                             $comment->getIdComment(),
  489.                                                             $termination->getIdTermination(),
  490.                                                             $termination->getTerminationStatus(),
  491.                                                             $comment->getUser(),
  492.                                                             $post['comment'],
  493.                                                             $post['attachmentURL']
  494.                                                         );
  495.                                                         $updatedTermination = new AppAccountTermination(
  496.                                                             $termination->getIdTermination(),
  497.                                                             $termination->getIdAccount(),
  498.                                                             $termination->getIdSubscription(),
  499.                                                             $termination->getTerminationStatus(),
  500.                                                             DateTime::createFromFormat('d/m/Y'$post['dateReception']),
  501.                                                             null,
  502.                                                             DateTime::createFromFormat('d/m/Y'$post['dateTermination']),
  503.                                                             $termination->getComments()
  504.                                                         );
  505.                                                         if (AppAccountTerminationServices::setComment($newComment) and AppAccountTerminationServices::setTermination($updatedTermination)) {
  506.                                                             $this->addFlash('success'"La demande de résiliation a bien été mise à jour.");
  507.                                                         } else {
  508.                                                             $this->addFlash('error'"Une erreur a été rencontrée lors de la mise à jour de la demande de résiliation.");
  509.                                                         }
  510.                                                     }
  511.                                                     else{
  512.                                                         $this->addFlash('error'"La date de fin d'abonnement est erronée.");
  513.                                                     }
  514.                                                 } else {
  515.                                                     $this->addFlash('error'"La date de fin d'abonnement est manquante.");
  516.                                                 }
  517.                                             } else if ($post['status'] == AppAccountTerminationStatus::ANNULE) {
  518.                                                 if (isset($post['dateReception']) and !empty($post['dateReception'])) {
  519.                                                     $tomorrow = new DateTime("tomorrow");
  520.                                                     $dateReception DateTime::createFromFormat('d/m/Y'$post['dateReception']);
  521.                                                     if($dateReception->getTimestamp() < $tomorrow->getTimestamp()) {
  522.                                                         $newStatus = new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE);
  523.                                                         $updatedComment = new AppAccountTerminationComment(
  524.                                                             null,
  525.                                                             $termination->getIdTermination(),
  526.                                                             $newStatus,
  527.                                                             $comment->getUser(),
  528.                                                             $post['comment'],
  529.                                                             $post['attachmentURL']
  530.                                                         );
  531.                                                         $updatedTermination = new AppAccountTermination(
  532.                                                             $termination->getIdTermination(),
  533.                                                             $termination->getIdAccount(),
  534.                                                             $termination->getIdSubscription(),
  535.                                                             $newStatus,
  536.                                                             $termination->getTerminationReceptionDate(),
  537.                                                             DateTime::createFromFormat('d/m/Y'$post['dateReception']),
  538.                                                             $termination->getTerminationDate(),
  539.                                                             $termination->getComments()
  540.                                                         );
  541.                                                         if (AppAccountTerminationServices::setComment($updatedComment) and AppAccountTerminationServices::setTermination($updatedTermination)) {
  542.                                                             $this->addFlash('success'"La demande d'annulation a bien été prise en compte.");
  543.                                                         } else {
  544.                                                             $this->addFlash('error'"Une erreur a été rencontrée lors de l'annulation de la demande de résiliation.");
  545.                                                         }
  546.                                                     }
  547.                                                     else{
  548.                                                         $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  549.                                                     }
  550.                                                 }
  551.                                                 else{
  552.                                                     $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  553.                                                 }
  554.                                             } else {
  555.                                                 $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  556.                                             }
  557.                                         } else {
  558.                                             $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  559.                                         }
  560.                                     }
  561.                                     else{
  562.                                         $this->addFlash('error'"Certains champs sont manquants.");
  563.                                     }
  564.                                 }
  565.                                 else{
  566.                                     $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  567.                                 }
  568.                             }
  569.                             else{
  570.                                 $this->addFlash('error'"Certains éléments du formulaire sont manquants.");
  571.                             }
  572.                         }
  573.                         else{
  574.                             $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  575.                         }
  576.                     }
  577.                     if($this->_request->query->has("idAccount")) {
  578.                         return $this->redirect($this->generateUrl(
  579.                             'Abonnement',
  580.                             array("idAccount" => $this->_idAccount)
  581.                         ));
  582.                     }
  583.                     else{
  584.                         return $this->redirect("/Abonnement");
  585.                     }
  586.                 }
  587.                 else if($this->_request->request->has('updateComment')) {
  588.                     if($this->_isFreemium or !$this->_isAdmin or $this->_isOlder or $this->_isDisabled){
  589.                         $this->addFlash('error'"Impossible de saisir une demande de résiliation.");
  590.                     }
  591.                     else{
  592.                         $post $this->_request->request->get('updateComment');
  593.                         if(!isset($post['attachment']) or empty($post['attachment']) or !filter_var($post['attachment'],FILTER_VALIDATE_URL)){
  594.                             $this->addFlash('error'"L'URL de la pièce jointe est manquant ou incorrect.");
  595.                         }
  596.                         else if(!isset($post['content']) or empty($post['content'])){
  597.                             $this->addFlash('error'"Le commentaire est manquant ou incorrect.");
  598.                         }
  599.                         else if((!isset($post['idComment']) or empty($post['idComment'])) or (!isset($post['idTermination']) or empty($post['idTermination']))){
  600.                             $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  601.                         }
  602.                         else{
  603.                             $comment AppAccountTerminationServices::getCommentByIdComment($post['idComment']);
  604.                             if($comment){
  605.                                 $updatedComment = new AppAccountTerminationComment(
  606.                                     $post['idComment'],
  607.                                     $post['idTermination'],
  608.                                     $comment->getTerminationStatus(),
  609.                                     $comment->getUser(),
  610.                                     $post['content'],
  611.                                     $post['attachment']
  612.                                 );
  613.                                 if(AppAccountTerminationServices::setComment($updatedComment)){
  614.                                     $this->addFlash('success'"Le commentaire a été mis à jour.");
  615.                                 }
  616.                                 else{
  617.                                     $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  618.                                 }
  619.                             }
  620.                             else{
  621.                                 $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  622.                             }
  623.                         }
  624.                     }
  625.                     if($this->_request->query->has("idAccount")) {
  626.                         return $this->redirect($this->generateUrl(
  627.                             'Abonnement',
  628.                             array("idAccount" => $this->_idAccount)
  629.                         ));
  630.                     }
  631.                     else{
  632.                         return $this->redirect("/Abonnement");
  633.                     }
  634.                 }
  635.             }
  636.             $appAccount AppAccountServices::getAccount($this->_idAccount);
  637.             $this->setAttribute('appAccount'$appAccount);
  638.             if($this->_session->has("msgFlashSubscription") && $this->_session->get("msgFlashSubscription") !== false){
  639.                 $this->setAttribute("msgAfterSubscription",$this->_session->get("msgFlashSubscription"));
  640.             }
  641.             if($this->_session->has("iconFlashSubscription") && $this->_session->get("iconFlashSubscription") !== false){
  642.                 $this->setAttribute("iconAfterSubscription",$this->_session->get("iconFlashSubscription"));
  643.             }
  644.             $this->_session->set("msgFlashSubscription",false);
  645.             $this->_session->set("iconFlashSubscription",false);
  646.             if(!$this->_isOlder){
  647.                 $AllGuarantee = [];
  648.                 if(isset($this->_proAbonoUserState["current"]['subscription']['Features'])) {
  649.                     foreach ($this->_proAbonoUserState["current"]['subscription']['Features'] as $key => $Feature) {
  650.                         $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Feature?ReferenceFeature=" $Feature['ReferenceFeature'], $this->_tokenProAbonofalse);
  651.                         if ($data[1] == 200) {
  652.                             if (isset($data[0]['Metadata']['GuaranteeWording'])) {
  653.                                 $Guarantee['GuaranteeWording'] = $data[0]['Metadata']['GuaranteeWording'];
  654.                                 $Guarantee['GuaranteeText'] = $data[0]['Metadata']['GuaranteeText'];
  655.                                 $Guarantee['GuaranteeText2'] = $data[0]['Metadata']['GuaranteeText2'];
  656.                                 array_push($AllGuarantee$Guarantee);
  657.                             }
  658.                         }
  659.                     }
  660.                     $this->_proAbonoUserState["current"]['subscription']['Guarantees'] = $AllGuarantee;
  661.                 }
  662.                 else{
  663.                     $this->_proAbonoUserState["current"]['subscription']['Features'] = [];
  664.                 }
  665.                 $this->setAttribute('proAbonoUserState'$this->_proAbonoUserState);
  666.                 $this->setAttribute('current',$this->_proAbonoUserState["current"]);
  667.                 $this->setAttribute('outOfBundle',$this->_proAbonoUserState["current"]["outOfBundle"]);
  668.                 $this->setAttribute('terminationStatutes',AppAccountTerminationServices::getTerminationStatus());
  669.                 $actual_url "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  670.                 $countTerminations AppAccountTerminationServices::getCountTerminations($appAccount);
  671.                 $nbrPages intval(ceil($countTerminations self::$NBRPERPAGE));
  672.                 if ($this->_request->query->has("pTerminations") and $this->_request->query->get("pTerminations") != "") {
  673.                     $p $this->_request->query->get("pTerminations");
  674.                     if (strpos($actual_url"&pTerminations=") !== false) {
  675.                         $url_sans_page str_replace('&pTerminations=' urlencode($p), '&pTerminations='$actual_url);
  676.                     }
  677.                     else if (strpos($actual_url"?pTerminations=") !== false) {
  678.                         $url_sans_page str_replace('?pTerminations=' urlencode($p), '?pTerminations='$actual_url);
  679.                     }
  680.                     if(intval($p) === 0){
  681.                         $p 1;
  682.                     }
  683.                 } else {
  684.                     $p 1;
  685.                     if(empty($_SERVER['QUERY_STRING'])){
  686.                         $url_sans_page $actual_url "?pTerminations=";
  687.                     }
  688.                     else{
  689.                         $url_sans_page $actual_url "&pTerminations=";
  690.                     }
  691.                 }
  692.                 if($p $nbrPages){
  693.                     $p 1;
  694.                 }
  695.                 if (strpos($url_sans_page"&pTerminations=") !== false) {
  696.                     $url_premiere_page str_replace('&pTerminations=''&pTerminations=1'$url_sans_page);
  697.                     $url_derniere_page str_replace('&pTerminations=''&pTerminations='.$nbrPages$url_sans_page);
  698.                 }
  699.                 else if (strpos($url_sans_page"?pTerminations=") !== false){
  700.                     $url_premiere_page str_replace('?pTerminations=''?pTerminations=1'$url_sans_page);
  701.                     $url_derniere_page str_replace('?pTerminations=''?pTerminations='.$nbrPages$url_sans_page);
  702.                 }
  703.                 else{
  704.                     $url_premiere_page $url_sans_page '?pTerminations=1';
  705.                     $url_derniere_page $url_sans_page '?pTerminations=' $nbrPages;
  706.                 }
  707.                 $offset = ($p 1) * self::$NBRPERPAGE;
  708.                 $this->setAttribute('currentSubscriptionTerminationStatus',AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($this->_idSubscription));
  709.                 $this->setAttribute('url_sans_page',$url_sans_page);
  710.                 $this->setAttribute('url_premiere_page',$url_premiere_page);
  711.                 $this->setAttribute('url_derniere_page',$url_derniere_page);
  712.                 $this->setAttribute('numero_de_page',$p);
  713.                 $this->setAttribute('countTerminations',$countTerminations);
  714.                 $this->setAttribute('nbrPages',$nbrPages);
  715.                 $this->setAttribute('terminations',AppAccountTerminationServices::getTerminations($appAccount,$offset,self::$NBRPERPAGE));
  716.             }
  717.         }
  718.         catch(Exception $e){
  719.             if($ajax){
  720.                 return new JsonResponse(array(
  721.                     'status' => 404
  722.                 ));
  723.             }
  724.             else{
  725.                 if($e->getCode() == 01){
  726.                     $this->setAttribute("error"$e->getMessage());
  727.                 }
  728.                 else{
  729.                     $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  730.                 }
  731.             }
  732.         }
  733.         if($ajax){
  734.             return $this->render('abonnement/onglets/abonnement/abonnement_abonnement.html.twig'$this->attribute);
  735.         }
  736.         else{
  737.             return $this->render('abonnement/index.html.twig'$this->attribute);
  738.         }
  739.     }
  740.     /**
  741.      * @Route("/Abonnement/Propal", name="Abonnement_propal")
  742.      * @Route("/Abonnement/Propal", name="abonnement_propal")
  743.      * @return Response
  744.      *
  745.      * @throws Exception
  746.      */
  747.     public function abonnementPropal(Request $request)
  748.     {
  749.         $this->setAttribute('shownPart','propal');
  750.         $this->setAttribute('search'$request->get('search'));
  751.         try{
  752.             if(!$this->_proAbonoUserState){
  753.                 throw new Exception();
  754.             }
  755.             if($this->_isTerminated and !$this->_isAdmin){
  756.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  757.             }
  758.             if(empty($this->_proAbonoUserState["propal"])){
  759.                 throw new Exception("Il n'y a pas de propositions commerciales.",01);
  760.             }
  761.         }
  762.         catch(Exception $e){
  763.             if($e->getCode() == 01){
  764.                 $this->setAttribute('error'$e->getMessage());
  765.             }
  766.             else{
  767.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  768.             }
  769.         }
  770.         $appAccount AppAccountServices::getAccount($this->_idAccount);
  771.         $this->setAttribute('appAccount',$appAccount);
  772.         return $this->render('abonnement/index.html.twig'$this->attribute);
  773.     }
  774.     /**
  775.      * @Route("/Abonnement/Update", name="Abonnement_update")
  776.      * @Route("/Abonnement/Update", name="abonnement_update")
  777.      * @return Response
  778.      *
  779.      * @throws Exception
  780.      */
  781.     public function abonnementUpdate(Request $request)
  782.     {
  783.         $this->setAttribute('shownPart','update');
  784.         $this->setAttribute('search'$request->get('search'));
  785.         try{
  786.             if(!$this->_proAbonoUserState){
  787.                 throw new Exception();
  788.             }
  789.             if($this->_isTerminated and !$this->_isAdmin){
  790.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  791.             }
  792.             $servicesCategories AppServiceServices::getServicesCategories();
  793.             if($this->_request->query->has("action")){
  794.                 if($this->_request->query->get("action") ==  "adjust"){
  795.                     if($this->_isOlder){
  796.                         throw new Exception("La page demandée n'existe pas",01);
  797.                     }
  798.                     else if($this->_isFreemium or $this->_isTerminated or $this->_isDisabled){
  799.                         throw new Exception("Désolé mais votre abonnement ne peut pas être modifié.",01);
  800.                     }
  801.                 }
  802.                 else if($this->_request->query->get("action") ==  "subscribe"){
  803.                     if(empty($this->_proAbonoUserState['propal'])){
  804.                         throw new Exception("La page demandée n'existe pas",01);
  805.                     }
  806.                     if (!is_null($this->_request->query->get('id'))){
  807.                         $propalArrayKey intval($this->_request->query->get('id'));
  808.                         if(array_key_exists($propalArrayKey,$this->_proAbonoUserState["propal"])){
  809.                             $currentPropal $this->_proAbonoUserState["propal"][$propalArrayKey];
  810.                             $this->setAttribute('currentPropal'$currentPropal);
  811.                         }
  812.                         else{
  813.                             throw new Exception("La proposition commerciale demandée n'existe pas.",01);
  814.                         }
  815.                     }else{
  816.                         throw new Exception("La proposition commerciale demandée n'existe pas.",01);
  817.                     }
  818.                 }
  819.                 else if($this->_request->query->get("action") ==  "delayed"){
  820.                     if(!empty($this->_proAbonoUserState['delayed'])){
  821.                         $this->setAttribute('currentPropal'$this->_proAbonoUserState['delayed']);
  822.                     }
  823.                     else{
  824.                         throw new Exception("La page demandée n'existe pas",01);
  825.                     }
  826.                 }
  827.                 else{
  828.                     throw new Exception("La page demandée n'existe pas",01);
  829.                 }
  830.             }
  831.             $Newsletter6Actif false;
  832.             $Newsletter12Actif false;
  833.             if(isset($this->_proAbonoUserState['current']['subscription']['Features']))
  834.             {
  835.                 $AllGuarantee = [];
  836.                 foreach($this->_proAbonoUserState['current']['subscription']['Features'] as $key => $Feature)
  837.                 {
  838.                     if($Feature['ReferenceFeature'] == AppServiceMarketing::NEWSLETTER6)
  839.                     {
  840.                         $indexNewsletter6 $key;
  841.                         if($Feature['IsEnabled'])
  842.                         {
  843.                             $Newsletter6Actif true;
  844.                         }
  845.                     }
  846.                     if($Feature['ReferenceFeature'] == AppServiceMarketing::NEWSLETTER12)
  847.                     {
  848.                         $indexNewsletter12 $key;
  849.                         if($Feature['IsEnabled'])
  850.                         {
  851.                             $Newsletter12Actif true;
  852.                         }
  853.                     }
  854.                     $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Feature?ReferenceFeature=".$Feature['ReferenceFeature'], $this->_tokenProAbonofalse);
  855.                     if($data[1] == 200)
  856.                     {
  857.                         if(isset($data[0]['Metadata']['GuaranteeWording']))
  858.                         {
  859.                             $Guarantee['GuaranteeWording'] = $data[0]['Metadata']['GuaranteeWording'];
  860.                             $Guarantee['GuaranteeText'] = $data[0]['Metadata']['GuaranteeText'];
  861.                             $Guarantee['GuaranteeText2'] = $data[0]['Metadata']['GuaranteeText2'];
  862.                             array_push($AllGuarantee$Guarantee);
  863.                         }
  864.                     }
  865.                 }
  866.                 $this->_proAbonoUserState["current"]['subscription']['Guarantees'] = $AllGuarantee;
  867.             }
  868.             if(isset($indexNewsletter6))
  869.             {
  870.                 $this->_proAbonoUserState['current']['subscription']['Features'][$indexNewsletter6]['OtherNewsletter'] = $Newsletter12Actif;
  871.             }
  872.             if(isset($indexNewsletter12))
  873.             {
  874.                 $this->_proAbonoUserState['current']['subscription']['Features'][$indexNewsletter12]['OtherNewsletter'] = $Newsletter6Actif;
  875.             }
  876.             $appAccount AppAccountServices::getAccount($this->_idAccount);
  877.             $this->setAttribute('appAccount',$appAccount);
  878.             $this->setAttribute('cgv'AppTermsOfService::TERMS_OF_SERVICE);
  879.             $servicesCategories AppServiceServices::getServicesCategories();
  880.             $this->setAttribute('proAbonoUserState'$this->_proAbonoUserState);
  881.             $this->setAttribute('categories'$servicesCategories);
  882.             $this->setAttribute('countries'RegCountryServices::getCountryList());
  883.             $this->setAttribute('company'CompanyServices::getCompany($this->_user["idCompany"]));
  884.             $this->setAttribute("latestAcceptedCGV"AppTermsOfServiceServices::getContentOfLastestAcceptedCGV($this->_idAccount));
  885.         }
  886.         catch(Exception $e){
  887.             if($e->getCode() == 01){
  888.                 $this->setAttribute('error'$e->getMessage());
  889.             }
  890.             else{
  891.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  892.             }
  893.         }
  894.         return $this->render('abonnement/index.html.twig'$this->attribute);
  895.     }
  896.     /**
  897.      * @Route("/Abonnement/Utilisateur", name="Abonnement_utilisateur")
  898.      * @Route("/Abonnement/Utilisateur", name="abonnement_utilisateur")
  899.      * @return Response
  900.      *
  901.      * @throws Exception
  902.      */
  903.     public function abonnementUtilisateurs($ajax false,$parent false,$id falseSessionInterface $sessionRequest $request)
  904.     {
  905.         $this->setAttribute('shownPart','utilisateur');
  906.         $this->setAttribute('search'$request->get('search'));
  907.         try{
  908.             if(!$this->_proAbonoUserState){
  909.                 throw new Exception();
  910.             }
  911.             if($this->_isTerminated and !$this->_isAdmin){
  912.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  913.             }
  914.             if($id){
  915.                 $idAccount $id;
  916.             }
  917.             else{
  918.                 $idAccount $this->_idAccount;
  919.             }
  920.             $appAccount AppAccountServices::getAccount($idAccount);
  921.             if(empty($appAccount)){
  922.                 throw $this->createNotFoundException("L'abonnement n'existe pas.");
  923.             } else{
  924.                 $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  925.                 $disabledUsers = [];
  926.                 if(!empty($appAccount->getTermsOfService())){
  927.                     foreach ($appAccount->getTermsOfService() as $term){
  928.                         if(!array_key_exists($term->getIdUser(),$appAccount->getUsers())){
  929.                             $user AppUserServices::getUser($term->getIdUser());
  930.                             if(!is_null($user)){
  931.                                 $disabledUsers[$user->getId()] = $user;
  932.                             }
  933.                         }
  934.                     }
  935.                 }
  936.                 foreach ($appAccount->getUsers() as &$user){
  937.                     if($this->isSupportUser($user->getEmail())){
  938.                         $user->setIsSupport(true);
  939.                     }
  940.                     else{
  941.                         $user->setIsSupport(false);
  942.                     }
  943.                 }
  944.                 foreach ($appAccount->getServices() as &$service){
  945.                     $service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
  946.                 }
  947.                 $this->setAttribute('appAccount'$appAccount);
  948.                 $this->setAttribute('disabledUsers'$disabledUsers);
  949.                 $solde 0;
  950.                 $nbLimit 0;
  951.                 if(!$this->_isOlder){
  952.                     $idServiceUser AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
  953.                     $referenceFeatureUser $idServiceUser->getIdCategory() . "-" sprintf("%02d"$idServiceUser->getIdServiceMarketing());
  954.                     $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser$this->_tokenProAbonofalse);
  955.                     $status $data[1];
  956.                     if($status == 200){
  957.                         if(array_key_exists("QuantityIncluded",$data[0])){
  958.                             $included $data[0]['QuantityIncluded'];
  959.                         }
  960.                         else{
  961.                             $included INF;
  962.                         }
  963.                         if(array_key_exists("QuantityCurrent",$data[0])){
  964.                             $current $data[0]['QuantityCurrent'];
  965.                         }
  966.                         else{
  967.                             $current 0;
  968.                         }
  969.                         if(!is_infinite($included)){
  970.                             if($data[0]['QuantityCurrent'] > $data[0]['QuantityIncluded']){
  971.                                 $solde $appAccount->getServices()[AppService::NB_USER]->getSolde();
  972.                                 $nbLimit $data[0]['QuantityCurrent'];
  973.                             }
  974.                             else{
  975.                                 $solde $data[0]['QuantityIncluded'] - $data[0]['QuantityCurrent'];
  976.                                 $nbLimit $data[0]['QuantityIncluded'];
  977.                             }
  978.                         }
  979.                         else{
  980.                             $solde null;
  981.                             $nbLimit null;
  982.                         }
  983.                     }
  984.                 }
  985.                 else{
  986.                     $solde false;
  987.                     $nbLimit false;
  988.                 }
  989.                 $this->setAttribute('nbLimit'$nbLimit);
  990.                 $this->setAttribute('solde'$solde);
  991.                 $this->setAttribute('userTypes'array_filter(array_map(function($userType){
  992.                     $listServiceAppAccount array_map(function($e) {
  993.                         return is_object($e) ? $e->getid() : $e->getid();
  994.                     }, $this->getAttribute('appAccount')->getServices());
  995.                     if(!in_array(AppService::ACCES_BACKOFFICE$listServiceAppAccount )){
  996.                     #if($this->getAttribute('appAccount')->getIdCompany() !== RegCompany::COEFFICY){
  997.                         if($userType->getId() <= AppUserType::RESPONSABLE){
  998.                             return $userType;
  999.                         } else{
  1000.                             return null;
  1001.                         }
  1002.                     } else{
  1003.                         return $userType;
  1004.                     }
  1005.                 },AppUserTypeServices::getUserTypes()), function($item){
  1006.                     return !is_null($item);
  1007.                 }));
  1008.                 $this->setAttribute'userTypeAdmin'AppUserTypeAdminServices::getUserTypeAdmin());
  1009.             }
  1010.             if($this->_request->request->has('formEditUser_email'))
  1011.             {
  1012.                 $idUserToEdit '';
  1013.                 $error false;
  1014.                 if($this->_request->request->has('formEditUser_id')
  1015.                     and !empty($this->_request->request->get('formEditUser_id'))){
  1016.                     $idUserToEdit $this->_request->request->get('formEditUser_id');
  1017.                 } else{
  1018.                     $error true;
  1019.                     $this->addFlash('formEditUser_error''Erreur à l\'identification de l\'utilisateur.');
  1020.                 }
  1021.                 $needRefresh false;
  1022.                 $licensing false;
  1023.                 $outOfBundle false;
  1024.                 $outOfControl false;
  1025.                 if($idUserToEdit == "new")
  1026.                 {
  1027.                     $newUser = new AppUser();
  1028.                     if($this->_isFreemium){
  1029.                         if(!$this->_isAdmin and !$this->_request->query->has("idAccount")){
  1030.                             $error true;
  1031.                             $this->addFlash('formEditUser_error'"L'abonnement REFERRAL ne permet pas d'ajouter de nouveaux utilisateurs.");
  1032.                         }
  1033.                     }
  1034.                     if($this->_request->request->has('formEditUser_lastName')
  1035.                         and !empty($this->_request->request->get('formEditUser_lastName'))){
  1036.                         $newUser->setLastName($this->_request->request->get('formEditUser_lastName'));
  1037.                     } else{
  1038.                         $error true;
  1039.                         $this->addFlash('formEditUser_error''Vérifier nom admin.');
  1040.                     }
  1041.                     if($this->_request->request->has('formEditUser_firstName')
  1042.                         and !empty($this->_request->request->get('formEditUser_firstName'))){
  1043.                         $newUser->setFirstName($this->_request->request->get('formEditUser_firstName'));
  1044.                     } else{
  1045.                         $error true;
  1046.                         $this->addFlash('formEditUser_error''Vérifier prénom.');
  1047.                     }
  1048.                     if($this->_request->request->has('formEditUser_email')
  1049.                         and !empty($this->_request->request->get('formEditUser_email'))){
  1050.                         if($this->isSupportUser($this->_request->request->get('formEditUser_email'))){
  1051.                             $error true;
  1052.                             $this->addFlash('formEditUser_error''Veuillez utiliser le mode SUPPORT.');
  1053.                         }
  1054.                         $emailValidator = new EmailValidator();
  1055.                         if($emailValidator->isValid($this->_request->request->get('formEditUser_email'), new RFCValidation())){
  1056.                             if(AppUserServices::mailExistsNotActivated($this->_request->request->get('formEditUser_email'))){
  1057.                                 $newUser->setEmail($this->_request->request->get('formEditUser_email'));
  1058.                                 $newUser->setId(AppUserServices::getUserFromEmail($newUser->getEmail())->getId());
  1059.                             } elseif(!AppUserServices::mailExists($this->_request->request->get('formEditUser_email'))){
  1060.                                 $newUser->setEmail($this->_request->request->get('formEditUser_email'));
  1061.                             } else{
  1062.                                 $error true;
  1063.                                 $this->addFlash('formEditUser_error'"L'email indiqué est déjà utilisé.");
  1064.                             }
  1065.                         } else{
  1066.                             $error true;
  1067.                             $this->addFlash('formEditUser_error'"L'email indiqué n'est pas valide.");
  1068.                         }
  1069.                     } else{
  1070.                         $error true;
  1071.                         $this->addFlash('formEditUser_error''Vérifier email.');
  1072.                     }
  1073.                     if($this->_request->request->has('formEditUser_phone')
  1074.                         and !empty($this->_request->request->get('formEditUser_phone'))){
  1075.                         $newUser->setPhone($this->_request->request->get('formEditUser_phone'));
  1076.                     }
  1077.                     if($this->_request->request->has('formEditUser_job')
  1078.                         and !empty($this->_request->request->get('formEditUser_job'))){
  1079.                         $newUser->setJob($this->_request->request->get('formEditUser_job'));
  1080.                     }
  1081.                     if($this->_request->request->has('formEditUser_calendly')
  1082.                         and !empty($this->_request->request->get('formEditUser_calendly'))){
  1083.                         if(!( filter_var($this->_request->request->get('formEditUser_calendly'), FILTER_VALIDATE_URL))
  1084.                             and $this->_request->request->get('formEditUser_calendly') != ''){
  1085.                             $error true;
  1086.                             $this->addFlash('formEditUser_error''Erreur sur l\'url du lien du calendrier partagé.');
  1087.                         }else {
  1088.                             $newUser->setCalendlyLink($this->_request->request->get('formEditUser_calendly'));
  1089.                         }
  1090.                     }
  1091.                     if($appAccount->getType()->getId() == AppAccountType::START){
  1092.                         $newUser->setCampaignEngagedContactMaxDailyQuota(15);
  1093.                     }
  1094.                     else{
  1095.                         $newUser->setCampaignEngagedContactMaxDailyQuota(50);
  1096.                     }
  1097.                     if($this->_request->request->has('formEditUser_lbldescription')
  1098.                         and !empty($this->_request->request->get('formEditUser_lbldescription'))){
  1099.                         $newUser->setLBLdescription($this->_request->request->get('formEditUser_lbldescription'));
  1100.                     }
  1101.                     if($this->_request->request->has('formEditUser_typeAdmin')
  1102.                         and !empty($this->_request->request->get('formEditUser_typeAdmin'))){
  1103.                         $newUser->setTypeAdmn(new AppUserTypeAdmin($this->_request->request->get('formEditUser_typeAdmin'), null));
  1104.                     }
  1105.                     if($this->_request->request->has('formEditUser_type')
  1106.                         and !empty($this->_request->request->get('formEditUser_type'))
  1107.                         and !$error){
  1108.                             if(!($this->_request->request->get('formEditUser_type') > AppUserType::RESPONSABLE
  1109.                                 and $appAccount->getIdCompany() !== RegCompany::COEFFICY)){
  1110.                                 if($this->_isOlder){
  1111.                                     $outOfControl true;
  1112.                                     if($this->_request->request->get('formEditUser_type') == "withoutLicence"){
  1113.                                         $newUser->setUserTokenLicence(0);
  1114.                                         $newUser->setType($this->getAttribute('userTypes')[1]);
  1115.                                     }
  1116.                                     else{
  1117.                                         $newUser->setUserTokenLicence(1);
  1118.                                         $newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1119.                                     }
  1120.                                 }
  1121.                                 else{
  1122.                                     $idServiceUser AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
  1123.                                     $referenceFeatureUser $idServiceUser->getIdCategory() . "-" sprintf("%02d"$idServiceUser->getIdServiceMarketing());
  1124.                                     $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser$this->_tokenProAbonofalse);
  1125.                                     $status $data[1];
  1126.                                     if($status != 200){
  1127.                                         $error true;
  1128.                                         $this->addFlash('formEditUser_error''Une erreur technique a été rencontrée. Veuillez réessayer ultérieurement.');
  1129.                                     }
  1130.                                     else{
  1131.                                         if(array_key_exists("QuantityIncluded",$data[0])){
  1132.                                             $included $data[0]['QuantityIncluded'];
  1133.                                         }
  1134.                                         else{
  1135.                                             $included INF;
  1136.                                         }
  1137.                                         if(array_key_exists("QuantityCurrent",$data[0])){
  1138.                                             $current $data[0]['QuantityCurrent'];
  1139.                                         }
  1140.                                         else{
  1141.                                             $current 0;
  1142.                                         }
  1143.                                         if(!is_infinite($included)) {
  1144.                                             $current $data[0]['QuantityCurrent'];
  1145.                                             $included $data[0]['QuantityIncluded'];
  1146.                                             if ($current == $included && $this->_request->request->get('formEditUser_type') != "withoutLicence") {
  1147.                                                 $error true;
  1148.                                                 $this->addFlash('formEditUser_error'"Il n'y a pas assez de licences disponibles sur l'abonnement.");
  1149.                                             } else {
  1150.                                                 $needRefresh true;
  1151.                                                 if ($current $included) {
  1152.                                                     $outOfBundle true;
  1153.                                                     $this->setAttribute('nbLimit'$current);
  1154.                                                     if ($appAccount->getServices()[AppService::NB_USER]->getSolde() > 0) {
  1155.                                                         if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
  1156.                                                             $newUser->setUserTokenLicence(0);
  1157.                                                             $newUser->setType($this->getAttribute('userTypes')[1]);
  1158.                                                             $needRefresh false;
  1159.                                                         } else {
  1160.                                                             $newUser->setUserTokenLicence(1);
  1161.                                                             $newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1162.                                                         }
  1163.                                                     } else {
  1164.                                                         $error true;
  1165.                                                         $this->addFlash('formEditUser_error'"Il n'y a plus de licences disponibles.");
  1166.                                                     }
  1167.                                                 } else {
  1168.                                                     if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
  1169.                                                         $newUser->setUserTokenLicence(0);
  1170.                                                         $newUser->setType($this->getAttribute('userTypes')[1]);
  1171.                                                         $needRefresh false;
  1172.                                                     } else {
  1173.                                                         if (is_null($this->_idSubscription)) {
  1174.                                                             $error true;
  1175.                                                             $this->addFlash('formEditUser_error''Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.');
  1176.                                                         }
  1177.                                                         $params json_encode(
  1178.                                                             array(
  1179.                                                                 "ReferenceFeature" => $referenceFeatureUser,
  1180.                                                                 "IdSubscription" => $this->_idSubscription,
  1181.                                                                 "QuantityCurrent" => $current 1,
  1182.                                                                 "DateStamp" => date('Y-m-d\TH:i:s')
  1183.                                                             )
  1184.                                                         );
  1185.                                                         $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1186.                                                         $status $data[1];
  1187.                                                         if ($status != 200) {
  1188.                                                             $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, l'utilisateur n'a pas été ajouté.");
  1189.                                                             $error true;
  1190.                                                         } else {
  1191.                                                             $newUser->setUserTokenLicence(1);
  1192.                                                             $newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1193.                                                         }
  1194.                                                     }
  1195.                                                 }
  1196.                                             }
  1197.                                         }
  1198.                                         else{
  1199.                                             $outOfControl true;
  1200.                                             if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
  1201.                                                 $newUser->setUserTokenLicence(0);
  1202.                                                 $newUser->setType($this->getAttribute('userTypes')[1]);
  1203.                                                 $needRefresh false;
  1204.                                             } else {
  1205.                                                 if (is_null($this->_idSubscription)) {
  1206.                                                     $error true;
  1207.                                                     $this->addFlash('formEditUser_error''Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.');
  1208.                                                 }
  1209.                                                 $params json_encode(
  1210.                                                     array(
  1211.                                                         "ReferenceFeature" => $referenceFeatureUser,
  1212.                                                         "IdSubscription" => $this->_idSubscription,
  1213.                                                         "QuantityCurrent" => $current 1,
  1214.                                                         "DateStamp" => date('Y-m-d\TH:i:s')
  1215.                                                     )
  1216.                                                 );
  1217.                                                 $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1218.                                                 $status $data[1];
  1219.                                                 if ($status != 200) {
  1220.                                                     $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, l'utilisateur n'a pas été ajouté.");
  1221.                                                     $error true;
  1222.                                                 } else {
  1223.                                                     $newUser->setUserTokenLicence(1);
  1224.                                                     $newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1225.                                                 }
  1226.                                             }
  1227.                                         }
  1228.                                     }
  1229.                                 }
  1230.                             }
  1231.                     }
  1232.                     if(!$error){
  1233.                         $newUser->setIsActive(false);
  1234.                         $newUser->setDefaultSupply(0);
  1235.                         $newUser->setIdAccount($appAccount->getId());
  1236.                         $actionLinkKey ActionLinkServices::generateKey();
  1237.                         if(empty($newUser->getId())){
  1238.                             $id AppUserServices::setUser($newUser);
  1239.                             $newUser->setId($id);
  1240.                         } else{
  1241.                             AppUserServices::setUser($newUser);
  1242.                         }
  1243.                         ProfilController::postProfilPhoto($newUser->getId(), $newUser->getIdAccount(), $session->get('campaignApi')['token']);
  1244.                         if($needRefresh){
  1245.                             $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  1246.                                 'idCustomer'  => $this->_idCustomer,
  1247.                                 'fromTrigger' => false,
  1248.                                 'fromScript' => false
  1249.                             ]);
  1250.                         }
  1251.                         $appAccount AppAccountServices::getAccount($idAccount);
  1252.                         foreach ($appAccount->getServices() as &$service){
  1253.                             $service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
  1254.                         }
  1255.                         if($outOfControl){
  1256.                             $this->setAttribute('solde'null);
  1257.                             $this->setAttribute('nbLimit'null);
  1258.                         }
  1259.                         else{
  1260.                             $this->setAttribute('solde'$appAccount->getServices()[AppService::NB_USER]->getSolde());
  1261.                             if(!$outOfBundle){
  1262.                                 $this->setAttribute('nbLimit'$appAccount->getServices()[AppService::NB_USER]->getNbLimit());
  1263.                             }
  1264.                         }
  1265.                         if(ActionLinkServices::createActionLink($actionLinkKey5,$this->_user$newUser)){
  1266.                             $supportMailAccount AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
  1267.                             $to $newUser->getEmailPretty();
  1268.                             $subject "Invitation sur Coefficy";
  1269.                             $content =
  1270.                                 "Bonjour " $newUser->getLastName() . " " $newUser->getFirstName() . ", <br><br>" .
  1271.                                 "Vous avez une invitation sur Coefficy de la part de la société " $appAccount->getCompanyName() . ".<br>" .
  1272.                                 "Pour activer votre compte veuillez suivre ce <a href='https://" $this->_request->server->get('SERVER_NAME') . "/ActionLink?key=" $actionLinkKey "' target='_blank'>lien</a>. <br><br>L'équipe Coefficy";
  1273.                             if(AppMailAccountServices::sendEmail($supportMailAccount$tonullnull$content$subject) !== false){
  1274.                                 $this->addFlash("formEditUser_success""Utilisateur ajouté avec succès un mail lui a été envoyé");
  1275.                             } else{
  1276.                                 $this->addFlash("formEditUser_warning""Utilisateur ajouté avec succès, cependant le mail d'activation n'a pas pu être envoyé.");
  1277.                             }
  1278.                             if($this->_request->query->has("idAccount")){
  1279.                                 return $this->redirect($this->generateUrl(
  1280.                                     'Abonnement_utilisateur',
  1281.                                     array("idAccount" => $this->_request->query->get("idAccount"))
  1282.                                 ));
  1283.                             }
  1284.                             else{
  1285.                                 return $this->redirect('/Abonnement/Utilisateur');
  1286.                             }
  1287.                         } else{
  1288.                             $this->addFlash("formEditUser_error""Erreur à la création du lien d'activation de l'utilisateur. si le problème persiste contacter le support.");
  1289.                         }
  1290.                     } else{
  1291.                         $this->addFlash('formEditUser_error'"Erreur sur un/plusieurs des champs");
  1292.                         if($this->_request->query->has("idAccount")){
  1293.                             return $this->redirect($this->generateUrl(
  1294.                                 'Abonnement_utilisateur',
  1295.                                 array("idAccount" => $this->_request->query->get("idAccount"))
  1296.                             ));
  1297.                         }
  1298.                     }
  1299.                 }
  1300.                 elseif(array_key_exists($idUserToEdit$appAccount->getUsers())) {
  1301.                     if($this->_request->request->has('formEditUser_lastName')
  1302.                         and !empty($this->_request->request->get('formEditUser_lastName'))){
  1303.                         $appAccount->getUsers()[$idUserToEdit]->setLastName($this->_request->request->get('formEditUser_lastName'));
  1304.                     } else{
  1305.                         $error true;
  1306.                         $this->addFlash('formEditUser_error''Vérifier nom admin.');
  1307.                     }
  1308.                     if($this->_request->request->has('formEditUser_firstName')
  1309.                         and !empty($this->_request->request->get('formEditUser_firstName'))){
  1310.                         $appAccount->getUsers()[$idUserToEdit]->setFirstName($this->_request->request->get('formEditUser_firstName'));
  1311.                     } else{
  1312.                         $error true;
  1313.                         $this->addFlash('formEditUser_error''Vérifier prénom.');
  1314.                     }
  1315.                     if($this->_request->request->has('formEditUser_email')
  1316.                         and !empty($this->_request->request->get('formEditUser_email'))){
  1317.                         if($this->isSupportUser($this->_request->request->get('formEditUser_email'))){
  1318.                             $error true;
  1319.                             $this->addFlash('formEditUser_error''Veuillez utiliser le mode SUPPORT.');
  1320.                         }
  1321.                         if(!AppUserServices::mailExists($this->_request->request->get('formEditUser_email'))
  1322.                             or (AppUserServices::mailExists($this->_request->request->get('formEditUser_email')) and $this->_request->request->get('formEditUser_email') == $appAccount->getUsers()[$idUserToEdit]->getEmail())){
  1323.                             $appAccount->getUsers()[$idUserToEdit]->setEmail($this->_request->request->get('formEditUser_email'));
  1324.                         } else{
  1325.                             $error true;
  1326.                             $this->addFlash('formEditUser_error'"L'email indiqué est déjà utilisé.");
  1327.                         }
  1328.                     } else{
  1329.                         $error true;
  1330.                         $this->addFlash('formEditUser_error''Vérifier email.');
  1331.                     }
  1332.                     if($this->_request->request->has('formEditUser_phone')
  1333.                         and !empty($this->_request->request->get('formEditUser_phone'))){
  1334.                         $appAccount->getUsers()[$idUserToEdit]->setPhone($this->_request->request->get('formEditUser_phone'));
  1335.                     }
  1336.                     if($this->_request->request->has('formEditUser_job')
  1337.                         and !empty($this->_request->request->get('formEditUser_job'))){
  1338.                         $appAccount->getUsers()[$idUserToEdit]->setJob($this->_request->request->get('formEditUser_job'));
  1339.                     }
  1340.                     if($this->_request->request->has('formEditUser_calendly')
  1341.                         and !empty($this->_request->request->get('formEditUser_calendly'))){
  1342.                         if(!( filter_var($this->_request->request->get('formEditUser_calendly'), FILTER_VALIDATE_URL))
  1343.                             and $this->_request->request->get('formEditUser_calendly') != ''){
  1344.                             $error true;
  1345.                             $this->addFlash('formEditUser_error''Erreur sur l\'url du lien du calendrier partagé.');
  1346.                         }else {
  1347.                             $appAccount->getUsers()[$idUserToEdit]->setCalendlyLink($this->_request->request->get('formEditUser_calendly'));
  1348.                         }
  1349.                     }
  1350.                     if($this->_request->request->has('formEditUser_campaignEngagedContactMaxDailyQuota')
  1351.                         and !empty($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota'))){
  1352.                         if($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota') < 0){
  1353.                             $error true;
  1354.                             $this->addFlash('formEditUser_error''Erreur sur le quota max journalier de contacts engagés.');
  1355.                         }else {
  1356.                             $appAccount->getUsers()[$idUserToEdit]->setCampaignEngagedContactMaxDailyQuota($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota'));
  1357.                         }
  1358.                     } else{
  1359.                         $appAccount->getUsers()[$idUserToEdit]->setCampaignEngagedContactMaxDailyQuota(50);
  1360.                     }
  1361.                     if($this->_request->request->has('formEditUser_lbldescription')
  1362.                         and !empty($this->_request->request->get('formEditUser_lbldescription'))){
  1363.                         $appAccount->getUsers()[$idUserToEdit]->setLBLdescription($this->_request->request->get('formEditUser_lbldescription'));
  1364.                     }
  1365.                     if($this->_request->request->has('formEditUser_typeAdmin')
  1366.                         and !empty($this->_request->request->get('formEditUser_typeAdmin'))){
  1367.                         $appAccount->getUsers()[$idUserToEdit]->setTypeAdmn(new AppUserTypeAdmin($this->_request->request->get('formEditUser_typeAdmin'), null));
  1368.                     }
  1369.                     if($this->_request->request->has('formEditUser_type')
  1370.                         and !empty($this->_request->request->get('formEditUser_type')) and !$error){
  1371.                        # if(!($this->_request->request->get('formEditUser_type') > AppUserType::RESPONSABLE and $appAccount->getIdCompany() !== RegCompany::COEFFICY)){
  1372.                             if($this->_isOlder){
  1373.                                 $outOfControl true;
  1374.                                 if($this->_request->request->get('formEditUser_type') == "withoutLicence"){
  1375.                                     if($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1){
  1376.                                         $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
  1377.                                     }
  1378.                                 }
  1379.                                 else{
  1380.                                     if($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0){
  1381.                                         $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
  1382.                                     }
  1383.                                     $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1384.                                 }
  1385.                             }
  1386.                             else{
  1387.                                 $idServiceUser AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
  1388.                                 $referenceFeatureUser $idServiceUser->getIdCategory() . "-" sprintf("%02d"$idServiceUser->getIdServiceMarketing());
  1389.                                 $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Usage?ReferenceCustomer=" $this->_referenceCustomer "&ReferenceFeature=" $referenceFeatureUser$this->_tokenProAbonofalse);
  1390.                                 $status $data[1];
  1391.                                 if ($status != 200) {
  1392.                                     $error true;
  1393.                                     $this->addFlash('formEditUser_error''Une erreur technique a été rencontrée. Veuillez réessayer ultérieurement.');
  1394.                                 }
  1395.                                 else {
  1396.                                     if (array_key_exists("QuantityIncluded"$data[0])) {
  1397.                                         $included $data[0]['QuantityIncluded'];
  1398.                                     } else {
  1399.                                         $included INF;
  1400.                                     }
  1401.                                     if (array_key_exists("QuantityCurrent"$data[0])) {
  1402.                                         $current $data[0]['QuantityCurrent'];
  1403.                                     } else {
  1404.                                         $current 0;
  1405.                                     }
  1406.                                     if (!is_infinite($included)) {
  1407.                                         $current $data[0]['QuantityCurrent'];
  1408.                                         $included $data[0]['QuantityIncluded'];
  1409.                                         if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
  1410.                                             if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1) {
  1411.                                                 if ($included >= $current) {
  1412.                                                     $params json_encode(
  1413.                                                         array(
  1414.                                                             "ReferenceFeature" => $referenceFeatureUser,
  1415.                                                             "IdSubscription" => $this->_idSubscription,
  1416.                                                             "QuantityCurrent" => $current == $current 1,
  1417.                                                             "DateStamp" => date('Y-m-d\TH:i:s')
  1418.                                                         )
  1419.                                                     );
  1420.                                                     $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1421.                                                     $status $data[1];
  1422.                                                     if ($status != 200) {
  1423.                                                         $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été retiré.");
  1424.                                                         $error true;
  1425.                                                     }
  1426.                                                 }
  1427.                                                 $needRefresh true;
  1428.                                                 $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
  1429.                                             }
  1430.                                         } else {
  1431.                                             if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0) {
  1432.                                                 if ($current == $included) {
  1433.                                                     $this->addFlash('formEditUser_error'"Il n'y a plus de licences disponibles.");
  1434.                                                     $error true;
  1435.                                                 } else if ($current $included) {
  1436.                                                     $params json_encode(
  1437.                                                         array(
  1438.                                                             "ReferenceFeature" => $referenceFeatureUser,
  1439.                                                             "IdSubscription" => $this->_idSubscription,
  1440.                                                             "QuantityCurrent" => $current 1,
  1441.                                                             "DateStamp" => date('Y-m-d\TH:i:s')
  1442.                                                         )
  1443.                                                     );
  1444.                                                     $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1445.                                                     $status $data[1];
  1446.                                                     if ($status != 200) {
  1447.                                                         $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été ajoutée.");
  1448.                                                         $error true;
  1449.                                                     } else {
  1450.                                                         $licensing true;
  1451.                                                         $needRefresh true;
  1452.                                                         $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
  1453.                                                         $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1454.                                                     }
  1455.                                                 } else {
  1456.                                                     if ($appAccount->getServices()[AppService::NB_USER]->getSolde() > 0) {
  1457.                                                         $needRefresh true;
  1458.                                                         $outOfBundle true;
  1459.                                                         $licensing true;
  1460.                                                         $this->setAttribute('nbLimit'$current);
  1461.                                                         $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
  1462.                                                         $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1463.                                                     } else {
  1464.                                                         $this->addFlash('formEditUser_error'"Il n'y a plus de licences disponibles.");
  1465.                                                         $error true;
  1466.                                                     }
  1467.                                                 }
  1468.                                             } else {
  1469.                                                 $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1470.                                             }
  1471.                                         }
  1472.                                     } else {
  1473.                                         $outOfControl true;
  1474.                                         if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
  1475.                                             if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1) {
  1476.                                                 $params json_encode(
  1477.                                                     array(
  1478.                                                         "ReferenceFeature" => $referenceFeatureUser,
  1479.                                                         "IdSubscription" => $this->_idSubscription,
  1480.                                                         "QuantityCurrent" => $current == $current 1,
  1481.                                                         "DateStamp" => date('Y-m-d\TH:i:s')
  1482.                                                     )
  1483.                                                 );
  1484.                                                 $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1485.                                                 $status $data[1];
  1486.                                                 if ($status != 200) {
  1487.                                                     $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été retiré.");
  1488.                                                     $error true;
  1489.                                                 } else {
  1490.                                                     $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
  1491.                                                 }
  1492.                                             }
  1493.                                         } else {
  1494.                                             if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0) {
  1495.                                                 $params json_encode(
  1496.                                                     array(
  1497.                                                         "ReferenceFeature" => $referenceFeatureUser,
  1498.                                                         "IdSubscription" => $this->_idSubscription,
  1499.                                                         "QuantityCurrent" => $current 1,
  1500.                                                         "DateStamp" => date('Y-m-d\TH:i:s')
  1501.                                                     )
  1502.                                                 );
  1503.                                                 $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1504.                                                 $status $data[1];
  1505.                                                 if ($status != 200) {
  1506.                                                     $this->addFlash('formEditUser_error'"Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été ajoutée.");
  1507.                                                     $error true;
  1508.                                                 } else {
  1509.                                                     $appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
  1510.                                                     $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1511.                                                 }
  1512.                                             }
  1513.                                             else{
  1514.                                                 $appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
  1515.                                             }
  1516.                                         }
  1517.                                     }
  1518.                                 }
  1519.                             }
  1520.                         #}
  1521.                     }
  1522.                     if(!$error){
  1523.                         if(AppUserServices::setUser($appAccount->getUsers()[$idUserToEdit])){
  1524.                             $this->addFlash('formEditUser_success''Utilisateur modifié avec succès');
  1525.                             if($licensing and BaseController::getConfig()['env'] == "prod"){
  1526.                                 $supportMailAccount AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
  1527.                                 $to $appAccount->getUsers()[$idUserToEdit]->getEmailPretty();
  1528.                                 $subject $appAccount->getUsers()[$idUserToEdit]->getFirstName() . ", une licence Coefficy vous a été attribué";
  1529.                                 $content 'Bonjour ' $appAccount->getUsers()[$idUserToEdit]->getFirstName() . ',<br><br>';
  1530.                                 $content .= $this->_user['userFirstName'] . " " $this->_user['userLastName'] . " vient de vous attribuer une licence utilisateur sur Coefficy." "<br>";
  1531.                                 $content .= "Passez à l'action dès maintenant en cliquant sur le lien suivant : " "<a href='https://"$_SERVER['SERVER_NAME'] ."/Abonnement/Utilisateurs' target='_blank'>Me connecter à Coefficy</a> <br><br>";
  1532.                                 $content .= "Bonne acquisition client avec Coefficy !";
  1533.                                 if(AppMailAccountServices::sendEmail($supportMailAccount$tonullnull$content$subject) !== false){
  1534.                                     $this->addFlash("formEditUser_success""Un email a été envoyé à " $appAccount->getUsers()[$idUserToEdit]->getFirstName() . " pour le notifier qu'il bénéficie désormais d'une licence.");
  1535.                                 }
  1536.                             }
  1537.                             if($needRefresh){
  1538.                                 $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  1539.                                     'idCustomer'  => $this->_idCustomer,
  1540.                                     'fromTrigger' => false,
  1541.                                     'fromScript' => false
  1542.                                 ]);
  1543.                             }
  1544.                             $appAccount AppAccountServices::getAccount($idAccount);
  1545.                             foreach ($appAccount->getServices() as &$service){
  1546.                                 $service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
  1547.                             }
  1548.                             if($outOfControl){
  1549.                                 $this->setAttribute('solde'null);
  1550.                                 $this->setAttribute('nbLimit'null);
  1551.                             }
  1552.                             else{
  1553.                                 $this->setAttribute('solde'$appAccount->getServices()[AppService::NB_USER]->getSolde());
  1554.                                 if(!$outOfBundle){
  1555.                                     $this->setAttribute('nbLimit'$appAccount->getServices()[AppService::NB_USER]->getNbLimit());
  1556.                                 }
  1557.                             }
  1558.                         } else{
  1559.                             $this->addFlash('formEditUser_error''Erreur lors de l\'insertion/Mise à jour de l\'utilisateur');
  1560.                         }
  1561.                     } else{
  1562.                         $this->addFlash('formEditUser_error'"Erreur sur un/plusieurs des champs");
  1563.                     }
  1564.                     if($this->_request->query->has("idAccount")){
  1565.                         return $this->redirect($this->generateUrl(
  1566.                             'Abonnement_utilisateur',
  1567.                             array("idAccount" => $this->_request->query->get("idAccount"))
  1568.                         ));
  1569.                     }
  1570.                     else{
  1571.                         return $this->redirect('/Abonnement/Utilisateur');
  1572.                     }
  1573.                 }
  1574.             }
  1575.             elseif($this->_request->request->has('formStopInvite')) {
  1576.                 $parameters = [];
  1577.                 $idUserToDelete $parameters['formStopInvite[idUser]'] = intval($this->_request->get('formStopInvite')['idUser']);
  1578.                 if($this->_user['idUser'] == $idUserToDelete){
  1579.                     return new JsonResponse([
  1580.                         'success'=> false,
  1581.                         'code' => 403,
  1582.                         'message'=> "Un utilisateur ne peut pas s'auto supprimer",
  1583.                         'parameters' => $parameters
  1584.                     ], 403);
  1585.                 }
  1586.                 $accountUser $appAccount->getUsers();
  1587.                 $userToDelete null;
  1588.                 foreach ($accountUser as $index => $kUser) {
  1589.                     if($idUserToDelete === $kUser->getId()){
  1590.                         $userToDelete $kUser;
  1591.                     }
  1592.                 }
  1593.                 if($userToDelete === null && $idUserToDelete){
  1594.                     $userToDelete false;
  1595.                 }
  1596.                 if($userToDelete === null){
  1597.                     return new JsonResponse([
  1598.                         'success'=> false,
  1599.                         'code' => 400,
  1600.                         'message'=> "Paramètre 'idUser' ne peut être null",
  1601.                         'parameters' => $parameters
  1602.                     ], 400);
  1603.                 }
  1604.                 $needRefresh false;
  1605.                 $newSolde null;
  1606.                 $newNbLimit null;
  1607.                 $outOfControl false;
  1608.                 if($this->_isOlder){
  1609.                    $outOfControl true;
  1610.                 }
  1611.                  else{
  1612.                     if($appAccount->getUsers()[$userToDelete->getId()]->getUserTokenLicence() == 1){
  1613.                         $idServiceUser AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
  1614.                         $referenceFeatureUser $idServiceUser->getIdCategory() . "-" sprintf("%02d"$idServiceUser->getIdServiceMarketing());
  1615.                         $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser$this->_tokenProAbonofalse);
  1616.                         $status $data[1];
  1617.                         if($status != 200){
  1618.                             return new JsonResponse([
  1619.                                 'success'=> false,
  1620.                                 'code' => 404,
  1621.                                 'message'=> "Impossible de supprimer la licence attribué à l'invité.",
  1622.                                 'parameters' => $parameters
  1623.                             ], 404);
  1624.                         }
  1625.                         else{
  1626.                             if (array_key_exists("QuantityIncluded"$data[0])) {
  1627.                                 $included $data[0]['QuantityIncluded'];
  1628.                             } else {
  1629.                                 $included INF;
  1630.                             }
  1631.                             if (array_key_exists("QuantityCurrent"$data[0])) {
  1632.                                 $current $data[0]['QuantityCurrent'];
  1633.                             } else {
  1634.                                 $current 0;
  1635.                             }
  1636.                             if (!is_infinite($included)) {
  1637.                                 $current $data[0]['QuantityCurrent'];
  1638.                                 $included $data[0]['QuantityIncluded'];
  1639.                                 if (is_null($this->_idSubscription)) {
  1640.                                     return new JsonResponse([
  1641.                                         'success' => false,
  1642.                                         'code' => 404,
  1643.                                         'message' => "Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.",
  1644.                                         'parameters' => $parameters
  1645.                                     ], 404);
  1646.                                 }
  1647.                                 if ($included >= $current) {
  1648.                                     $params json_encode(
  1649.                                         array(
  1650.                                             "ReferenceFeature" => $referenceFeatureUser,
  1651.                                             "IdSubscription" => $this->_idSubscription,
  1652.                                             "QuantityCurrent" => $current == $current 1,
  1653.                                             "DateStamp" => date('Y-m-d\TH:i:s')
  1654.                                         )
  1655.                                     );
  1656.                                     $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1657.                                     $status $data[1];
  1658.                                     if ($status != 200) {
  1659.                                         return new JsonResponse([
  1660.                                             'success' => false,
  1661.                                             'code' => 404,
  1662.                                             'message' => "Impossible de supprimer la licence attribué à l'invité",
  1663.                                             'parameters' => $parameters
  1664.                                         ], 404);
  1665.                                     } else {
  1666.                                         $newSolde $data[0]['QuantityCurrent'];
  1667.                                         $newNbLimit $data[0]['QuantityIncluded'];
  1668.                                         $needRefresh true;
  1669.                                     }
  1670.                                 } else {
  1671.                                     $needRefresh true;
  1672.                                     $newSolde $current == $current $current 1;
  1673.                                     $newNbLimit $included;
  1674.                                 }
  1675.                             }
  1676.                             else{
  1677.                                 $params json_encode(
  1678.                                     array(
  1679.                                         "ReferenceFeature" => $referenceFeatureUser,
  1680.                                         "IdSubscription" => $this->_idSubscription,
  1681.                                         "QuantityCurrent" => $current == $current 1,
  1682.                                         "DateStamp" => date('Y-m-d\TH:i:s')
  1683.                                     )
  1684.                                 );
  1685.                                 $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  1686.                                 $status $data[1];
  1687.                                 if ($status != 200) {
  1688.                                     return new JsonResponse([
  1689.                                         'success' => false,
  1690.                                         'code' => 404,
  1691.                                         'message' => "Impossible de supprimer la licence attribué à l'invité",
  1692.                                         'parameters' => $parameters
  1693.                                     ], 404);
  1694.                                 }
  1695.                             }
  1696.                         }
  1697.                     }
  1698.                 }
  1699.                 if(Services_coefficy_utilisateurs::deleteUtilisateur($appAccount->getId(), $userToDelete->getId()) != false){
  1700.                     AppUserServices::setMailAccountIsActive($userToDelete->getId(), false);
  1701.                     ActionLinkServices::desactiveUserLinks($userToDelete->getId(), $appAccount->getId());
  1702.                     ProfilController::postProfilPhoto($userToDelete->getId(), $userToDelete->getIdAccount(), $session->get('campaignApi')['token']);
  1703.                     if($needRefresh){
  1704.                         $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  1705.                             'idCustomer'  => $this->_idCustomer,
  1706.                             'fromTrigger' => false,
  1707.                             'fromScript' => false
  1708.                         ]);
  1709.                     }
  1710.                     return new JsonResponse([
  1711.                         'success'=> true,
  1712.                         'code' => 200,
  1713.                         'message'=> "Invitation stoppée avec succès",
  1714.                         'oldUser' => $userToDelete->getId(),
  1715.                         'result' => [
  1716.                             'stopInvite' => true,
  1717.                             'solde' => $newSolde,
  1718.                             'nbLimit' => $newNbLimit
  1719.                         ],
  1720.                         'parameters' => $parameters
  1721.                     ], 200);
  1722.                 } else{
  1723.                     return new JsonResponse([
  1724.                         'success'=> false,
  1725.                         'code' => 200,
  1726.                         'message'=> "Erreur à l'annulation de l'invitation",
  1727.                         'oldUser' => $userToDelete->getId(),
  1728.                         'result' => [
  1729.                             'stopInvite' => false
  1730.                         ],
  1731.                         'parameters' => $parameters
  1732.                     ], 200);
  1733.                 }
  1734.             }
  1735.             elseif($this->_request->request->has('formDeleteUser')) {
  1736.                 $parameters = [];
  1737.                 $idUserToDelete $parameters['formDeleteUser[idUser]'] = intval($this->_request->get('formDeleteUser')['idUser']);
  1738.                 if($this->_user['idUser'] == $idUserToDelete){
  1739.                     return new JsonResponse([
  1740.                         'success'=> false,
  1741.                         'code' => 403,
  1742.                         'message'=> "Un utilisateur ne peut pas s'auto supprimer",
  1743.                         'parameters' => $parameters
  1744.                     ], 403);
  1745.                 }
  1746.                 if($appAccount->hasService(AppService::CRM)) {
  1747.                     $relaunchOpportunitySupply $parameters['formDeleteUser[relaunchOpportunitySupply]'] = $this->_request->get('formDeleteUser')['relaunchOpportunitySupply'] !== null intval($this->_request->get('formDeleteUser')['relaunchOpportunitySupply']) : null;
  1748.                 } else{
  1749.                     $relaunchOpportunitySupply $parameters['formDeleteUser[relaunchOpportunitySupply]'] = null;
  1750.                 }
  1751.                 if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)
  1752.                     || $appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  1753.                     $campaignSequence $parameters['formDeleteUser[campaignSequence]'] = $this->_request->get('formDeleteUser')['campaignSequence'] !== null intval($this->_request->get('formDeleteUser')['campaignSequence']) : null;
  1754.                 } else{
  1755.                     $campaignSequence $parameters['formDeleteUser[campaignSequence]'] = null;
  1756.                 }
  1757.                 if($appAccount->hasService(AppService::NEWSLETTER)) {
  1758.                     $newsletterContact $parameters['formDeleteUser[newsletterContact]'] = $this->_request->get('formDeleteUser')['newsletterContact'] !== null intval($this->_request->get('formDeleteUser')['newsletterContact']) : null;
  1759.                 } else {
  1760.                     $newsletterContact $parameters['formDeleteUser[newsletterContact]'] = null;
  1761.                 }
  1762.                 if($appAccount->hasService(AppService::LEBONLOGICIEL)) {
  1763.                     $articleLbl $parameters['formDeleteUser[articleLbl]'] = $this->_request->get('formDeleteUser')['articleLbl'] !== null intval($this->_request->get('formDeleteUser')['articleLbl']) : null;
  1764.                 } else{
  1765.                     $articleLbl $parameters['formDeleteUser[articleLbl]'] = null;
  1766.                 }
  1767.                 if($appAccount->hasService(AppService::CRM)) {
  1768.                     $persona $parameters['formDeleteUser[persona]'] = $this->_request->get('formDeleteUser')['persona'] !== null intval($this->_request->get('formDeleteUser')['persona']) : null;
  1769.                 } else{
  1770.                     $persona $parameters['formDeleteUser[persona]'] = null;
  1771.                 }
  1772.                 if($appAccount->hasService(AppService::EMAIL_SUIVI)) {
  1773.                     $template $parameters['formDeleteUser[template]'] = $this->_request->get('formDeleteUser')['template'] !== null intval($this->_request->get('formDeleteUser')['template']) : null;
  1774.                 } else{
  1775.                     $template $parameters['formDeleteUser[template]'] = null;
  1776.                 }
  1777.                 if($appAccount->hasService(AppService::EDITION_LEADFORM)) {
  1778.                     $leadform $parameters['formDeleteUser[leadform]'] = $this->_request->get('formDeleteUser')['leadform'] !== null intval($this->_request->get('formDeleteUser')['leadform']) : null;
  1779.                 } else{
  1780.                     $leadform $parameters['formDeleteUser[leadform]'] = null;
  1781.                 }
  1782.                 $accountUser $appAccount->getUsers();
  1783.                 $userToDelete null;
  1784.                 $userRelaunchOpportunitySupply null;
  1785.                 $userCampaignSequence null;
  1786.                 $userNewsletterContact null;
  1787.                 $userArticleLbl null;
  1788.                 $userPersona null;
  1789.                 $userTemplate null;
  1790.                 $userLeadform null;
  1791.                 foreach ($accountUser as $index => $kUser) {
  1792.                     if($idUserToDelete === $kUser->getId()){
  1793.                         $userToDelete $kUser;
  1794.                     }
  1795.                     if($appAccount->hasService(AppService::CRM)){
  1796.                         if($relaunchOpportunitySupply === $kUser->getId()){
  1797.                             $userRelaunchOpportunitySupply $kUser;
  1798.                         }
  1799.                     }
  1800.                     if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)
  1801.                         || $appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  1802.                         if($campaignSequence === $kUser->getId()){
  1803.                             $userCampaignSequence $kUser;
  1804.                         }
  1805.                     }
  1806.                     if($appAccount->hasService(AppService::NEWSLETTER)) {
  1807.                         if($newsletterContact === $kUser->getId()){
  1808.                             $userNewsletterContact $kUser;
  1809.                         }
  1810.                     }
  1811.                     if($appAccount->hasService(AppService::LEBONLOGICIEL)) {
  1812.                         if($articleLbl === $kUser->getId()){
  1813.                             $userArticleLbl $kUser;
  1814.                         }
  1815.                     }
  1816.                     if($appAccount->hasService(AppService::CRM)) {
  1817.                         if($persona === $kUser->getId()){
  1818.                             $userPersona $kUser;
  1819.                         }
  1820.                     }
  1821.                     if($appAccount->hasService(AppService::EMAIL_SUIVI)) {
  1822.                         if($template === $kUser->getId()){
  1823.                             $userTemplate $kUser;
  1824.                         }
  1825.                     }
  1826.                     if($appAccount->hasService(AppService::EDITION_LEADFORM)) {
  1827.                         if($leadform === $kUser->getId()){
  1828.                             $userLeadform $kUser;
  1829.                         }
  1830.                     }
  1831.                 }
  1832.                 if($userToDelete === null && $idUserToDelete){
  1833.                     $userToDelete false;
  1834.                 }
  1835.                 if($userRelaunchOpportunitySupply === null && $relaunchOpportunitySupply){
  1836.                     $userRelaunchOpportunitySupply false;
  1837.                 }
  1838.                 if($userCampaignSequence === null && $campaignSequence){
  1839.                     $userCampaignSequence false;
  1840.                 }
  1841.                 if($userNewsletterContact === null && $newsletterContact){
  1842.                     $userNewsletterContact false;
  1843.                 }
  1844.                 if($userArticleLbl === null && $articleLbl){
  1845.                     $userArticleLbl false;
  1846.                 }
  1847.                 if($userPersona === null && $persona){
  1848.                     $userPersona false;
  1849.                 }
  1850.                 if($userTemplate === null && $template){
  1851.                     $userTemplate false;
  1852.                 }
  1853.                 if($userLeadform === null && $leadform){
  1854.                     $userLeadform false;
  1855.                 }
  1856.                 if($userToDelete === null){
  1857.                     return new JsonResponse([
  1858.                         'success'=> false,
  1859.                         'code' => 400,
  1860.                         'message'=> "Paramètre 'idUser' ne peut être null",
  1861.                         'parameters' => $parameters
  1862.                     ], 400);
  1863.                 }
  1864.                 if($userToDelete === false){
  1865.                     return new JsonResponse([
  1866.                         'success'=> false,
  1867.                         'code' => 404,
  1868.                         'message'=> "L'utilisateur ayant pour id $idUserToDelete n'existe pas sur l'abonnement",
  1869.                         'parameters' => $parameters
  1870.                     ], 404);
  1871.                 }
  1872.                 if($userRelaunchOpportunitySupply === false){
  1873.                     return new JsonResponse([
  1874.                         'success'=> false,
  1875.                         'code' => 404,
  1876.                         'message'=> "L'utilisateur ayant pour id $relaunchOpportunitySupply n'existe pas sur l'abonnement",
  1877.                         'parameters' => $parameters
  1878.                     ], 404);
  1879.                 }
  1880.                 if($userCampaignSequence === false){
  1881.                     return new JsonResponse([
  1882.                         'success'=> false,
  1883.                         'code' => 404,
  1884.                         'message'=> "L'utilisateur ayant pour id $campaignSequence n'existe pas sur l'abonnement",
  1885.                         'parameters' => $parameters
  1886.                     ], 404);
  1887.                 }
  1888.                 if($userNewsletterContact === false){
  1889.                     return new JsonResponse([
  1890.                         'success'=> false,
  1891.                         'code' => 404,
  1892.                         'message'=> "L'utilisateur ayant pour id $newsletterContact n'existe pas sur l'abonnement",
  1893.                         'parameters' => $parameters
  1894.                     ], 404);
  1895.                 }
  1896.                 if($userArticleLbl === false){
  1897.                     return new JsonResponse([
  1898.                         'success'=> false,
  1899.                         'code' => 404,
  1900.                         'message'=> "L'utilisateur ayant pour id $articleLbl n'existe pas sur l'abonnement",
  1901.                         'parameters' => $parameters
  1902.                     ], 404);
  1903.                 }
  1904.                 if($userPersona === false){
  1905.                     return new JsonResponse([
  1906.                         'success'=> false,
  1907.                         'code' => 404,
  1908.                         'message'=> "L'utilisateur ayant pour id $persona n'existe pas sur l'abonnement",
  1909.                         'parameters' => $parameters
  1910.                     ], 404);
  1911.                 }
  1912.                 if($userTemplate === false){
  1913.                     return new JsonResponse([
  1914.                         'success'=> false,
  1915.                         'code' => 404,
  1916.                         'message'=> "L'utilisateur ayant pour id $template n'existe pas sur l'abonnement",
  1917.                         'parameters' => $parameters
  1918.                     ], 404);
  1919.                 }
  1920.                 if($userLeadform === false){
  1921.                     return new JsonResponse([
  1922.                         'success'=> false,
  1923.                         'code' => 404,
  1924.                         'message'=> "L'utilisateur ayant pour id $leadform n'existe pas sur l'abonnement",
  1925.                         'parameters' => $parameters
  1926.                     ], 404);
  1927.                 }
  1928.                 $resultRelaunch null;
  1929.                 $resultOpportunity null;
  1930.                 $resultSupply null;
  1931.                 $resultCampaign null;
  1932.                 $resultSequence null;
  1933.                 $resultNewsletterContact null;
  1934.                 $resultArticleLbl null;
  1935.                 $resultPersona null;
  1936.                 $resultTemplate null;
  1937.                 $resultLeadform null;
  1938.                 if($appAccount->hasService(AppService::CRM)){
  1939.                     if($userRelaunchOpportunitySupply){
  1940.                         $resultRelaunch CrmRelaunchServices::updateUserOnRelaunch($userToDelete->getId(), $userToDelete->getIdAccount(), $userRelaunchOpportunitySupply->getId());
  1941.                         $resultOpportunity CrmOpportunityServices::updateUserOnOpportunity($userToDelete->getId(), $userToDelete->getIdAccount(), $userRelaunchOpportunitySupply->getId());
  1942.                         $resultSupply RoutineServices::updateUserOnRoutine($userToDelete->getId(), $userRelaunchOpportunitySupply->getId());
  1943.                     } else{
  1944.                         $resultRelaunch CrmRelaunchServices::deleteUserFromRelaunch($userToDelete->getId(), $userToDelete->getIdAccount());
  1945.                         $resultOpportunity CrmOpportunityServices::deleteUserOpportunity($userToDelete->getId(), $userToDelete->getIdAccount());
  1946.                         $resultSupply RoutineServices::deleteUserFromRoutines($userToDelete->getId());
  1947.                     }
  1948.                 }
  1949.                 if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  1950.                     if($userCampaignSequence){
  1951.                         $resultSequence CampaignApiServices::call(
  1952.                             'put',
  1953.                             CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
  1954.                             $this->_session->get('campaignApi')['token'],
  1955.                             [
  1956.                                 'idUser' => $userToDelete->getId(),
  1957.                                 'newIdUser' => $userCampaignSequence->getId(),
  1958.                                 'idAccount' => $appAccount->getId()
  1959.                             ]
  1960.                         );
  1961.                     } else{
  1962.                         $resultSequence CampaignApiServices::call(
  1963.                             'put',
  1964.                             CampaignApiServices::ENDPOINT['SEQUENCE_DELETEUSER'],
  1965.                             $this->_session->get('campaignApi')['token'],
  1966.                             [
  1967.                                 'idUser' => $userToDelete->getId(),
  1968.                                 'idAccount' => $appAccount->getId()
  1969.                             ]
  1970.                         );
  1971.                     }
  1972.                 }
  1973.                 if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
  1974.                     if($userCampaignSequence){
  1975.                         $resultCampaign CampaignApiServices::call(
  1976.                             'put',
  1977.                             CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
  1978.                             $this->_session->get('campaignApi')['token'],
  1979.                             [
  1980.                                 'idUser' => $userToDelete->getId(),
  1981.                                 'newIdUser' => $userCampaignSequence->getId(),
  1982.                                 'idAccount' => $appAccount->getId()
  1983.                             ]
  1984.                         );
  1985.                     } else{
  1986.                         $resultCampaign CampaignApiServices::call(
  1987.                             'put',
  1988.                             CampaignApiServices::ENDPOINT['CAMPAIGN_DELETEUSER'],
  1989.                             $this->_session->get('campaignApi')['token'],
  1990.                             [
  1991.                                 'idUser' => $userToDelete->getId(),
  1992.                                 'idAccount' => $appAccount->getId()
  1993.                             ]
  1994.                         );
  1995.                     }
  1996.                 }
  1997.                 if($appAccount->hasService(AppService::NEWSLETTER)) {
  1998.                     if($userCampaignSequence){
  1999.                         $resultNewsletterContact CampaignApiServices::call(
  2000.                             'put',
  2001.                             CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
  2002.                             $this->_session->get('campaignApi')['token'],
  2003.                             [
  2004.                                 'idUser' => $userToDelete->getId(),
  2005.                                 'newIdUser' => $userNewsletterContact->getId(),
  2006.                                 'idAccount' => $appAccount->getId()
  2007.                             ]
  2008.                         );
  2009.                     } else{
  2010.                         $resultNewsletterContact CampaignApiServices::call(
  2011.                             'put',
  2012.                             CampaignApiServices::ENDPOINT['NEWSLETTER_DELETEUSER'],
  2013.                             $this->_session->get('campaignApi')['token'],
  2014.                             [
  2015.                                 'idUser' => $userToDelete->getId(),
  2016.                                 'idAccount' => $appAccount->getId()
  2017.                             ]
  2018.                         );
  2019.                     }
  2020.                 }
  2021.                 if($appAccount->hasService(AppService::LEBONLOGICIEL)){
  2022.                     if($userArticleLbl){
  2023.                         $resultArticleLbl LeBonLogicielServices::transfertArticleResponsable($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
  2024.                     } else{
  2025.                         $resultArticleLbl LeBonLogicielServices::transfertArticleResponsableOldest($userToDelete->getId(), $appAccount->getId());
  2026.                     }
  2027.                 }
  2028.                 if($appAccount->hasService(AppService::CRM)){
  2029.                     if($userPersona){
  2030.                         $resultPersona CamPersonaServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
  2031.                     } else{
  2032.                         $resultPersona CamPersonaServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
  2033.                     }
  2034.                 }
  2035.                 if($appAccount->hasService(AppService::EMAIL_SUIVI)){
  2036.                     if($userTemplate){
  2037.                         $resultTemplate AppMailTemplateServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
  2038.                     } else{
  2039.                         $resultTemplate AppMailTemplateServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
  2040.                     }
  2041.                 }
  2042.                 if($appAccount->hasService(AppService::EDITION_LEADFORM)){
  2043.                     if($userLeadform){
  2044.                         $resultLeadform LeadformServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
  2045.                     } else{
  2046.                         $resultLeadform LeadformServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
  2047.                     }
  2048.                 }
  2049.                 $needRefresh false;
  2050.                 $newSolde null;
  2051.                 $newNbLimit null;
  2052.                 if($this->_isOlder){
  2053.                     //
  2054.                 }
  2055.                 else{
  2056.                     if($appAccount->getUsers()[$userToDelete->getId()]->getUserTokenLicence() == 1){
  2057.                         $idServiceUser AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
  2058.                         $referenceFeatureUser $idServiceUser->getIdCategory() . "-" sprintf("%02d"$idServiceUser->getIdServiceMarketing());
  2059.                         $data $this->_api->callApi("GET"$this->_urlProAbono "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser$this->_tokenProAbonofalse);
  2060.                         $status $data[1];
  2061.                         if($status != 200){
  2062.                             return new JsonResponse([
  2063.                                 'success'=> false,
  2064.                                 'code' => 404,
  2065.                                 'message'=> "Une erreur a été rencontrée lors de la suppression de l'utilisateur.",
  2066.                                 'parameters' => $parameters
  2067.                             ], 404);
  2068.                         }
  2069.                         else{
  2070.                             if (array_key_exists("QuantityIncluded"$data[0])) {
  2071.                                 $included $data[0]['QuantityIncluded'];
  2072.                             } else {
  2073.                                 $included INF;
  2074.                             }
  2075.                             if (array_key_exists("QuantityCurrent"$data[0])) {
  2076.                                 $current $data[0]['QuantityCurrent'];
  2077.                             } else {
  2078.                                 $current 0;
  2079.                             }
  2080.                             if (!is_infinite($included)) {
  2081.                                 $current $data[0]['QuantityCurrent'];
  2082.                                 $included $data[0]['QuantityIncluded'];
  2083.                                 if (is_null($this->_idSubscription)) {
  2084.                                     return new JsonResponse([
  2085.                                         'success' => false,
  2086.                                         'code' => 404,
  2087.                                         'message' => "Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.",
  2088.                                         'parameters' => $parameters
  2089.                                     ], 404);
  2090.                                 }
  2091.                                 if ($included >= $current) {
  2092.                                     $params json_encode(
  2093.                                         array(
  2094.                                             "ReferenceFeature" => $referenceFeatureUser,
  2095.                                             "IdSubscription" => $this->_idSubscription,
  2096.                                             "QuantityCurrent" => $current == $current $current 1,
  2097.                                             "DateStamp" => date('Y-m-d\TH:i:s')
  2098.                                         )
  2099.                                     );
  2100.                                     $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  2101.                                     $status $data[1];
  2102.                                     if ($status != 200) {
  2103.                                         return new JsonResponse([
  2104.                                             'success' => false,
  2105.                                             'code' => 404,
  2106.                                             'message' => "Impossible de supprimer la licence de l'utilisateur.",
  2107.                                             'parameters' => $parameters
  2108.                                         ], 404);
  2109.                                     } else {
  2110.                                         $needRefresh true;
  2111.                                         $newSolde $data[0]['QuantityCurrent'];
  2112.                                         $newNbLimit $data[0]['QuantityIncluded'];
  2113.                                     }
  2114.                                 } else {
  2115.                                     $needRefresh true;
  2116.                                     $outOfBundle true;
  2117.                                     $newSolde $current == $current $current 1;
  2118.                                     $newNbLimit $included;
  2119.                                 }
  2120.                             }
  2121.                             else{
  2122.                                 $params json_encode(
  2123.                                     array(
  2124.                                         "ReferenceFeature" => $referenceFeatureUser,
  2125.                                         "IdSubscription" => $this->_idSubscription,
  2126.                                         "QuantityCurrent" => $current == $current $current 1,
  2127.                                         "DateStamp" => date('Y-m-d\TH:i:s')
  2128.                                     )
  2129.                                 );
  2130.                                 $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbono$params);
  2131.                                 $status $data[1];
  2132.                                 if ($status != 200) {
  2133.                                     return new JsonResponse([
  2134.                                         'success' => false,
  2135.                                         'code' => 404,
  2136.                                         'message' => "Impossible de supprimer la licence de l'utilisateur.",
  2137.                                         'parameters' => $parameters
  2138.                                     ], 404);
  2139.                                 }
  2140.                             }
  2141.                         }
  2142.                     }
  2143.                 }
  2144.                 if(Services_coefficy_utilisateurs::deleteUtilisateur($appAccount->getId(), $userToDelete->getId()) != false){
  2145.                     AppUserServices::setMailAccountIsActive($userToDelete->getId(), false);
  2146.                     ActionLinkServices::desactiveUserLinks($userToDelete->getId(), $appAccount->getId());
  2147.                     ProfilController::postProfilPhoto($userToDelete->getId(), $userToDelete->getIdAccount(), $session->get('campaignApi')['token']);
  2148.                     $resultDelete true;
  2149.                 } else{
  2150.                     $resultDelete false;
  2151.                 }
  2152.                 if($needRefresh){
  2153.                     $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  2154.                         'idCustomer'  => $this->_idCustomer,
  2155.                         'fromTrigger' => false,
  2156.                         'fromScript' => false
  2157.                     ]);
  2158.                 }
  2159.                 return new JsonResponse([
  2160.                     'success'=> true,
  2161.                     'code' => 200,
  2162.                     'message'=> "Utilisateur supprimé avec succès",
  2163.                     'oldUser' => $userToDelete->getId(),
  2164.                     'result' => [
  2165.                         'relaunch' => $resultRelaunch,
  2166.                         'opportunity' => $resultOpportunity,
  2167.                         'supply' => $resultSupply,
  2168.                         'campaign' => $resultCampaign,
  2169.                         'sequence' => $resultSequence,
  2170.                         'newsletterContact' => $resultNewsletterContact,
  2171.                         'articleLbl' => $resultArticleLbl,
  2172.                         'persona' => $resultPersona,
  2173.                         'template' => $resultTemplate,
  2174.                         'leadform' => $resultLeadform,
  2175.                         'deleteUser' => $resultDelete,
  2176.                         'solde' => $newSolde,
  2177.                         'nbLimit' => $newNbLimit
  2178.                     ],
  2179.                     'parameters' => $parameters
  2180.                 ], 200);
  2181.             }
  2182.             elseif($this->_request->request->has('formRedoInvite_submit')) {
  2183.                 $error false;
  2184.                 $idUser null;
  2185.                 if($this->_request->request->has('formRedoInvite_id')
  2186.                     and !empty($this->_request->request->get('formRedoInvite_id'))){
  2187.                     $idUser $this->_request->request->get('formRedoInvite_id');
  2188.                 } else{
  2189.                     $error true;
  2190.                     $this->addFlash("formRedoInvite_error","Erreur à l'identification de l'utilisateur à réinviter");
  2191.                 }
  2192.                 if(!$error){
  2193.                     $actionLinkKey ActionLinkServices::generateKey();
  2194.                     ActionLinkServices::desactiveUserLinks($idUser$appAccount->getId());
  2195.                     if(ActionLinkServices::createActionLink($actionLinkKey5,$this->_user$appAccount->getUsers()[$idUser])){
  2196.                         $supportMailAccount AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
  2197.                         $to $appAccount->getUsers()[$idUser]->getEmailPretty();
  2198.                         $subject "Invitation sur Coefficy";
  2199.                         $content =
  2200.                             "Bonjour " $appAccount->getUsers()[$idUser]->getLastName() . " " $appAccount->getUsers()[$idUser]->getFirstName() . ", <br><br>" .
  2201.                             "Vous avez une invitation sur Coefficy de la part de la société " $appAccount->getCompanyName(). ".<br>" .
  2202.                             "Pour activer votre compte, veuillez suivre ce <a href='https://" $this->_request->server->get('SERVER_NAME') . "/ActionLink?key=" $actionLinkKey "' target='_blank'>lien</a>. <br><br>L'équipe Coefficy";
  2203.                         if(AppMailAccountServices::sendEmail($supportMailAccount$tonullnull$content$subject) !== false){
  2204.                             $this->addFlash("formEditUser_success""Le mail d'activation a été renvoyé");
  2205.                         } else{
  2206.                             $this->addFlash("formEditUser_warning""Erreur à l'envoi du mail, réessayez.");
  2207.                         }
  2208.                     } else{
  2209.                         $this->addFlash("formEditUser_error""Erreur à la création du lien d'activation de l'utilisateur. si le problème persiste contacter le support.");
  2210.                     }
  2211.                     if($this->_request->query->has("idAccount")){
  2212.                         return $this->redirect($this->generateUrl(
  2213.                             'Abonnement_utilisateur',
  2214.                             array("idAccount" => $this->_request->query->get("idAccount"))
  2215.                         ));
  2216.                     }
  2217.                 }
  2218.                 else{
  2219.                     if($this->_request->query->has("idAccount")){
  2220.                         return $this->redirect($this->generateUrl(
  2221.                             'Abonnement_utilisateur',
  2222.                             array("idAccount" => $this->_request->query->get("idAccount"))
  2223.                         ));
  2224.                     }
  2225.                 }
  2226.                 return $this->redirect('/Abonnement/Utilisateur');
  2227.             }
  2228.         }
  2229.         catch(Exception $e){
  2230.             if($e->getCode() == 01){
  2231.                 $this->setAttribute('error'$e->getMessage());
  2232.             }
  2233.             else{
  2234.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  2235.             }
  2236.         }
  2237.         if ($ajax) {
  2238.             if($parent == "actualUserList"){
  2239.                 return $this->render('abonnement/onglets/utilisateurs/utilisateurs_actuels.html.twig'$this->attribute);
  2240.             }
  2241.             else{
  2242.                 return $this->render('abonnement/onglets/utilisateurs/utilisateurs_invites.html.twig'$this->attribute);
  2243.             }
  2244.         } else {
  2245.             return $this->render('abonnement/index.html.twig'$this->attribute);
  2246.         }
  2247.     }
  2248.     /**
  2249.      * @Route("/Abonnement/Utilisateur/setAdmin", name="setAdmin")
  2250.      * @param bool $ajax
  2251.      * @param string $parent
  2252.      * @return Response
  2253.      * @throws Exception
  2254.      */
  2255.     public function setAdmin($ajax true)
  2256.     {
  2257.         try{
  2258.             if(!$this->_proAbonoUserState or $this->_isTerminated){
  2259.                 throw new Exception();
  2260.             }
  2261.             $id_utilisateur $this->_request->get('id''');
  2262.             $parent $this->_request->get('parent','');
  2263.             $admin $this->_request->get('admin''nop');
  2264.             $idAccount $this->_request->get('idAccount',$this->_idAccount);
  2265.             if(empty($parent) or empty($id_utilisateur)){
  2266.                 $response $this->forward('App\Controller\AbonnementController::abonnementUtilisateurs');
  2267.                 return $response;
  2268.             }
  2269.             if ($this->_isResponsable and $this->_user['idUser'] != $id_utilisateur) {
  2270.                 if ($admin == 'nop') {
  2271.                     Services_coefficy_utilisateurs::setAdmin($idAccount$id_utilisateur1);
  2272.                 } else {
  2273.                     Services_coefficy_utilisateurs::setAdmin($idAccount$id_utilisateur2);
  2274.                 }
  2275.             }
  2276.             if ($ajax) {
  2277.                 $response $this->forward('App\Controller\AbonnementController::abonnementUtilisateurs', [
  2278.                     'ajax' => true,
  2279.                     'parent' => $parent,
  2280.                     'idAccount' => $idAccount
  2281.                 ]);
  2282.                 return $response;
  2283.             } else {
  2284.                 return null;
  2285.             }
  2286.         }
  2287.         catch(Exception $e){
  2288.             if($ajax){
  2289.                 return new JsonResponse(array(
  2290.                     'status' => 404
  2291.                 ));
  2292.             }
  2293.             else{
  2294.                 return null;
  2295.             }
  2296.         }
  2297.     }
  2298.     /**
  2299.      * @Route("/Abonnement/Consommation", name="Abonnement_consommation")
  2300.      * @Route("/Abonnement/Consommation", name="abonnement_consommation")
  2301.      * @return Response
  2302.      *
  2303.      * @throws Exception
  2304.      */
  2305.     public function abonnementConsommation(Request $request)
  2306.     {
  2307.         $this->setAttribute('shownPart','consommation');
  2308.         $this->setAttribute('search'$request->get('search'));
  2309.         try{
  2310.             if(!$this->_proAbonoUserState){
  2311.                 throw new Exception();
  2312.             }
  2313.             if($this->_isDisabled){
  2314.                 throw new Exception();
  2315.             }
  2316.             if($this->_isTerminated and !$this->_isAdmin){
  2317.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  2318.             }
  2319.             if(!$this->_isOlder){
  2320.                 $this->setAttribute('totalOnboardingHoursInMinutes',AppAccountHoursServices::countOnboardingHours($this->_idAccount));
  2321.                 $this->setAttribute('onboardingHoursBalanceInMinutes',AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount));
  2322.                 $this->setAttribute('totalNewsletters',AppAccountHoursServices::countNewsletters($this->_idAccount));
  2323.                 $this->setAttribute('balanceNewsletter',AppAccountServices::getAccountnewsletterBalance($this->_idAccount));
  2324.             }
  2325.             $appAccount AppAccountServices::getAccount($this->_idAccount);
  2326.             $consos = [];
  2327.             $limitations = [];
  2328.             foreach ($this->_proAbonoUserState["current"]["limitations"] as &$limitation){
  2329.                 $idCategory explode('-'$limitation['ReferenceFeature'])[0];
  2330.                 $idServiceMarketing explode('-'$limitation['ReferenceFeature'])[1];
  2331.                 if(in_array($idCategory,AppServiceCategory::UT_NEW_DISPLAYED)){
  2332.                     $service AppServiceServices::getServicesToActivate($idCategory,$idServiceMarketing);
  2333.                     $service reset($service);
  2334.                     $service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
  2335.                     $limitation['solde'] = $service->getSolde();
  2336.                     $limitations[] = $limitation;
  2337.                 }
  2338.             }
  2339.             foreach ($this->_proAbonoUserState["current"]["consos"] as &$conso){
  2340.                 $idCategory explode('-'$conso['ReferenceFeature'])[0];
  2341.                 $idServiceMarketing explode('-'$conso['ReferenceFeature'])[1];
  2342.                 if(in_array($idCategory,AppServiceCategory::UT_NEW_DISPLAYED)){
  2343.                     if($conso['ReferenceFeature'] == AppServiceMarketing::CONTACTS){
  2344.                         $conso['order'] = 1;
  2345.                     }
  2346.                     else if($conso['ReferenceFeature'] == AppServiceMarketing::VISITEURS){
  2347.                         $conso['order'] = 2;
  2348.                     }
  2349.                     else if($conso['ReferenceFeature'] == AppServiceMarketing::COACHING){
  2350.                         $conso['order'] = 4;
  2351.                         $conso['TitleLocalized'] = "Un coach en acquisition client à votre disposition (/heure)";
  2352.                         $conso['QuantityIncluded'] = number_format($conso['QuantityIncluded'] / 60,2);
  2353.                         $conso['QuantityCurrent'] = number_format($conso['QuantityCurrent'] / 60,2);
  2354.                         $conso['price'] = $conso['price'] * 60;
  2355.                     }else if($conso['ReferenceFeature'] == AppServiceMarketing::CONTACTSABONNE){
  2356.                         $conso['order'] = 6;
  2357.                     }
  2358.                     else{
  2359.                         $conso['order'] = 7;
  2360.                     }
  2361.                     $consos[] = $conso;
  2362.                 }
  2363.             }
  2364.             if($appAccount->getType()->getId() != AppAccountType::REFERRAL) {
  2365.                 $conso = array(
  2366.                     "TitleLocalized" => "Onboarding : accompagnement personnalisé au démarrage avec un coach en acquisition client (/heure)",
  2367.                     "QuantityCurrent" => $this->getAttribute('totalOnboardingHoursInMinutes') / 60,
  2368.                     "QuantityTotal" => ($this->getAttribute('onboardingHoursBalanceInMinutes') / 60) + ($this->getAttribute('totalOnboardingHoursInMinutes') / 60),
  2369.                     "order" => 3
  2370.                 );
  2371.                 $consos[] = $conso;
  2372.             }
  2373.             if($appAccount->hasService(AppService::REDACTION_6_NEWSLETTER) || $appAccount->hasService(AppService::REDACTION_12_NEWSLETTER) || $appAccount->hasService(AppService::REDACTION_24_NEWSLETTER)  || $appAccount->hasService(AppService::REDACTION_2_CONTENU)  ){
  2374.                 $conso = array(
  2375.                     "TitleLocalized" => "Prestation de rédaction de newsletter (/newsletter)",
  2376.                     "QuantityCurrent" => $this->getAttribute('totalNewsletters'),
  2377.                     "QuantityTotal" => $this->getAttribute('totalNewsletters') + $this->getAttribute('balanceNewsletter'),
  2378.                     "order" => 5
  2379.                 );
  2380.                 $consos[] = $conso;
  2381.             }
  2382.             $actual_url "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  2383.             $totalHours AppAccountHoursServices::getTotalSetOfHours($appAccount);
  2384.             $nbrPages intval(ceil($totalHours self::$NBRPERPAGE));
  2385.             if ($this->_request->query->has("pHours") and $this->_request->query->get("pHours") != "") {
  2386.                 $p $this->_request->query->get("pHours");
  2387.                 if (strpos($actual_url"&pHours=") !== false) {
  2388.                     $url_sans_page str_replace('&pHours=' urlencode($p), '&pHours='$actual_url);
  2389.                 }
  2390.                 else if (strpos($actual_url"?pHours=") !== false) {
  2391.                     $url_sans_page str_replace('?pHours=' urlencode($p), '?pHours='$actual_url);
  2392.                 }
  2393.                 if(intval($p) === 0){
  2394.                     $p 1;
  2395.                 }
  2396.             } else {
  2397.                 $p 1;
  2398.                 if(empty($_SERVER['QUERY_STRING'])){
  2399.                     $url_sans_page $actual_url "?pHours=";
  2400.                 }
  2401.                 else{
  2402.                     $url_sans_page $actual_url "&pHours=";
  2403.                 }
  2404.             }
  2405.             if($p $nbrPages){
  2406.                 $p 1;
  2407.             }
  2408.             if (strpos($url_sans_page"&pHours=") !== false) {
  2409.                 $url_premiere_page str_replace('&pHours=''&pHours=1'$url_sans_page);
  2410.                 $url_derniere_page str_replace('&pHours=''&pHours='.$nbrPages$url_sans_page);
  2411.             }
  2412.             else if (strpos($url_sans_page"?pHours=") !== false){
  2413.                 $url_premiere_page str_replace('?pHours=''?pHours=1'$url_sans_page);
  2414.                 $url_derniere_page str_replace('?pHours=''?pHours='.$nbrPages$url_sans_page);
  2415.             }
  2416.             else{
  2417.                 $url_premiere_page $url_sans_page '?pHours=1';
  2418.                 $url_derniere_page $url_sans_page '?pHours=' $nbrPages;
  2419.             }
  2420.             $offset = ($p 1) * self::$NBRPERPAGE;
  2421.             $endStatusHours AppAccountHoursServices::getEndStatusHours();
  2422.             $stopStatusHours AppAccountHoursServices::getStopStatusHours();
  2423.             $listIdHistoricStatus array_map(function($e) {
  2424.                 return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
  2425.             }, $endStatusHours);
  2426.             $listIdStopStatus array_map(function($e) {
  2427.                 return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
  2428.             }, $stopStatusHours);
  2429.             $hoursType AppAccountHoursServices::getHoursType();
  2430.             $this->setAttribute('arrayHistoricStatus'$listIdHistoricStatus);
  2431.             $this->setAttribute('arrayStopStatus'$listIdStopStatus);
  2432.             $this->setAttribute('url_sans_page',$url_sans_page);
  2433.             $this->setAttribute('url_premiere_page',$url_premiere_page);
  2434.             $this->setAttribute('url_derniere_page',$url_derniere_page);
  2435.             $this->setAttribute('numero_de_page',$p);
  2436.             $this->setAttribute('totalHours',$totalHours);
  2437.             $this->setAttribute('nbrPages',$nbrPages);
  2438.             $this->setAttribute('accountHours',AppAccountHoursServices::getAccountHours($appAccount,$offset,self::$NBRPERPAGE));
  2439.             $this->setAttribute('hoursTypes',$hoursType);
  2440.             $encoders = [new JsonEncoder()];
  2441.             $normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(nullnullnull, new ReflectionExtractor())];
  2442.             $serializer = new Serializer($normalizers$encoders);
  2443.             $this->setAttribute('hoursTypesSerial',json_decode($serializer->serialize($hoursType'json')));
  2444.             $accountUsers AppUserServices::getAccountUsers(AppAccount::VenteCoeff);
  2445.             uasort($accountUsers,function($a$b){
  2446.                 return $a->firstName <=> $b->firstName;
  2447.             });
  2448.             $this->setAttribute('responsablesSerial'json_decode($serializer->serialize($accountUsers'json')));
  2449.             $this->setAttribute('hoursStatus'json_decode($serializer->serialize(AppAccountHoursServices::getHoursStatus(), 'json')));
  2450.             $this->setAttribute('responsables',AppUserServices::getAccountUsers(AppAccount::VenteCoeff));
  2451.             $this->setAttribute('appAccount',$appAccount);
  2452.             $this->setAttribute('isAdmin',$this->_isAdmin);
  2453.             $this->setAttribute('current',$this->_proAbonoUserState["current"]);
  2454.             $this->setAttribute('limitations'$limitations);
  2455.             $this->setAttribute('consos'$consos);
  2456.         }
  2457.         catch(Exception $e){
  2458.             if($e->getCode() == 01){
  2459.                 $this->setAttribute('error'$e->getMessage());
  2460.             }
  2461.             else{
  2462.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.2");
  2463.             }
  2464.         }
  2465.         return $this->render('abonnement/index.html.twig'$this->attribute);
  2466.     }
  2467.     /**
  2468.      * @Route("/Abonnement/Suivi", name="Abonnement_suivi")
  2469.      * @Route("/Abonnement/Suivi", name="abonnement_suivi")
  2470.      * @param SessionInterface $session
  2471.      * @param Request $request
  2472.      * @return Response
  2473.      *
  2474.      * @throws Exception
  2475.      */
  2476.     public function abonnementSuiviBackOffice(SessionInterface $sessionRequest $request)
  2477.     {
  2478.         $this->setAttribute('shownPart','suivibackoffice');
  2479.         $this->setAttribute('search'$request->get('search'));
  2480.         $currentHoursStatus null;
  2481.         if(!$this->_isAdmin && !in_array(AppService::ACCES_SUIVI_CLIENT$session->get('user')['services'])){
  2482.             throw new AccessDeniedHttpException();
  2483.         }
  2484.         try{
  2485.             /*if(!$this->_proAbonoUserState){
  2486.                 throw new Exception();
  2487.             }*/
  2488.             /*if($this->_isDisabled){
  2489.                 throw new Exception();
  2490.             }*/
  2491.             if($this->_isTerminated and !$this->_isAdmin){
  2492.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  2493.             }
  2494.             if(!$this->_isOlder){
  2495.                 $this->setAttribute('totalOnboardingHoursInMinutes',AppAccountHoursServices::countOnboardingHours($this->_idAccount));
  2496.                 $this->setAttribute('onboardingHoursBalanceInMinutes',AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount));
  2497.                 $this->setAttribute('totalNewsletters',AppAccountHoursServices::countNewsletters($this->_idAccount));
  2498.                 $this->setAttribute('balanceNewsletter',AppAccountServices::getAccountnewsletterBalance($this->_idAccount));
  2499.             }
  2500.             $typehoursUpdateProAbono AppAccountHoursServices::getidHoursTypeToUpdateProAbono();
  2501.             $appAccount AppAccountServices::getAccount($this->_idAccount);
  2502.             $this->setAttribute('appAccount',$appAccount);
  2503.             if ($this->_request->isMethod("POST")) {
  2504.                 if(!$this->_isAdmin){
  2505.                     throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  2506.                 }
  2507.                 if(!empty($_POST)){
  2508.                     if($this->_request->request->has('addEditHours')){
  2509.                         $post $this->_request->request->get('addEditHours');
  2510.                         if(isset($post['formActionHoursConsulting']) and !empty($post['formActionHoursConsulting'])
  2511.                             and isset($post['titleHour']) and !empty($post['titleHour'])
  2512.                             and isset($post['commentHour']) and !empty($post['commentHour'])
  2513.                             and isset($post['duration'])
  2514.                             and isset($post['dateStartHoursConsulting']) and !empty($post['dateStartHoursConsulting'])
  2515.                             and isset($post['selectResponsableHours']) and !empty($post['selectResponsableHours'])
  2516.                             and isset($post['selectCreatorHours']) and !empty($post['selectCreatorHours'])
  2517.                             and isset($post['selectTypeHours']) and !empty($post['selectTypeHours'])
  2518.                             and isset($post['selectStatusHours']) and !empty($post['selectStatusHours'])
  2519.                             and isset($post['linkHour'])
  2520.                             and isset($post['valueHour']) ) {
  2521.                             $typeHours AppAccountHoursServices::getHoursTypeById($post['selectTypeHours']);
  2522.                             $from DateTime::createFromFormat('d/m/Y H:i'$post['dateStartHoursConsulting']);
  2523.                             if(isset($post['dateTermHoursConsulting']) and !empty($post['dateTermHoursConsulting'])) {
  2524.                                 $to DateTime::createFromFormat('d/m/Y H:i'$post['dateTermHoursConsulting']);
  2525.                             }
  2526.                             else{
  2527.                                 $to null;
  2528.                             }
  2529.                             if(isset($post['dateDueHoursConsulting']) and !empty($post['dateDueHoursConsulting']))
  2530.                             {
  2531.                                 $due DateTime::createFromFormat('d/m/Y H:i'$post['dateDueHoursConsulting']);
  2532.                             }
  2533.                             else{
  2534.                                 $due null;
  2535.                             }
  2536.                             if(empty($post['duration']))
  2537.                             {
  2538.                                 $post['duration'] = null;
  2539.                             }
  2540.                             if($to != null and $from != null and $to->getTimestamp() === $from->getTimestamp()){
  2541.                                 $this->addFlash("error","Les dates sélectionnées sont identiques.");
  2542.                             }
  2543.                             else if($to != null and $from != null and $to->getTimestamp() < $from->getTimestamp()){
  2544.                                 $this->addFlash("error","Les dates sélectionnées ne sont pas valide. La date de début (".$from->format('d/m/Y H:i')."H) est supérieur à la date de fin (".$to->format('d/m/Y H:i')."H)");
  2545.                             }
  2546.                             else if($to != null and $from != null and empty($post['duration']) or (!empty($post['duration']) and intval($post['duration']) < 15)){
  2547.                                 $this->addFlash("error","Veuillez saisir un intervalle minimal de 0,25 heures entre les deux dates.");
  2548.                             }
  2549.                             else{
  2550.                                 if(!in_array($post['selectTypeHours'],$typehoursUpdateProAbono)){
  2551.                                     if($post['formActionHoursConsulting'] == "add"){
  2552.                                         $flagOnboardingHours true;
  2553.                                         if(in_array($appAccount->getType()->getId(),AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)){
  2554.                                             if($post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS and ($post['duration']  > $this->getAttribute('onboardingHoursBalanceInMinutes'))){
  2555.                                                 $this->addFlash("error","Les heures saisies n'ont pas été ajoutées. Impossible d'ajouter plus que le solde de ".($this->getAttribute('onboardingHoursBalanceInMinutes')/60)." heure(s) d'onboarding.");
  2556.                                                 $flagOnboardingHours false;
  2557.                                             }
  2558.                                         }
  2559.                                         if($flagOnboardingHours){
  2560.                                             $accountHours = new AppAccountHour(
  2561.                                                 null,
  2562.                                                 $this->_idAccount,
  2563.                                                 $this->_idSubscription,
  2564.                                                 $post['titleHour'],
  2565.                                                 $post['commentHour'],
  2566.                                                 new AppAccountHourType($post['selectTypeHours']),
  2567.                                                 new AppAccountHourStatus($post['selectStatusHours']),
  2568.                                                 $post['duration'],
  2569.                                                 $from,
  2570.                                                 $to,
  2571.                                                 $due,
  2572.                                                 AppUserServices::getUser($post['selectResponsableHours']),
  2573.                                                 1,
  2574.                                                 $post['linkHour'],
  2575.                                                 !is_null($post['valueHour'])  ?floatval($post['valueHour']):null,
  2576.                                                 !is_null($post['customervalueHour'])  ?floatval($post['customervalueHour']):null,
  2577.                                                 AppUserServices::getUser($post['selectCreatorHours'])
  2578.                                             );
  2579.                                             if(!AppAccountHoursServices::setAccountHours($accountHours)){
  2580.                                                 $this->addFlash("error","Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
  2581.                                             }
  2582.                                             else{
  2583.                                                 $this->addFlash("success""La saisie des heures a bien été réalisée.");
  2584.                                                 if($post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS){
  2585.                                                     AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
  2586.                                                 }
  2587.                                                 if($post['selectTypeHours'] == AppAccountHourType::NEWSLETTERS){
  2588.                                                     AppAccountServices::updateBalanceNewsletter($this->_idAccountfalse);
  2589.                                                 }
  2590.                                             }
  2591.                                         }
  2592.                                     }
  2593.                                     else if($post['formActionHoursConsulting'] == "update"){
  2594.                                         if(isset($post['idHour']) and !empty($post['idHour'])) {
  2595.                                             $actualHours AppAccountHoursServices::getAccountHoursById($this->_idAccount$post['idHour']);
  2596.                                             if($actualHours){
  2597.                                                 $flagOnboardingHours true;
  2598.                                                 if(in_array($appAccount->getType()->getId(),AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)
  2599.                                                     and $post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS){
  2600.                                                     if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']){
  2601.                                                         if($post['duration'] > $this->getAttribute('onboardingHoursBalanceInMinutes')){
  2602.                                                             $this->addFlash("error","Les heures saisies n'ont pas été ajoutées. Impossible d'ajouter plus que le solde de ".($this->getAttribute('onboardingHoursBalanceInMinutes')/60)." heure(s) d'onboarding.");
  2603.                                                             $flagOnboardingHours false;
  2604.                                                         }
  2605.                                                     }
  2606.                                                     else{
  2607.                                                         if(($post['duration'] - $actualHours->getDurationInMinutes()) > $this->getAttribute('onboardingHoursBalanceInMinutes')){
  2608.                                                             $this->addFlash("error","Les heures saisies n'ont pas été ajoutées. Impossible d'ajouter plus que le solde de ".($this->getAttribute('onboardingHoursBalanceInMinutes')/60)." heure(s) d'onboarding.");
  2609.                                                             $flagOnboardingHours false;
  2610.                                                         }
  2611.                                                     }
  2612.                                                 }
  2613.                                                 if($flagOnboardingHours){
  2614.                                                     if(!$actualHours->getIsBilled()){
  2615.                                                         $accountHours = new AppAccountHour(
  2616.                                                             $post['idHour'],
  2617.                                                             $this->_idAccount,
  2618.                                                             $actualHours->getIdSubscription(),
  2619.                                                             $post['titleHour'],
  2620.                                                             $post['commentHour'],
  2621.                                                             new AppAccountHourType($post['selectTypeHours']),
  2622.                                                             new AppAccountHourStatus($post['selectStatusHours']),
  2623.                                                             $post['duration'],
  2624.                                                             $from,
  2625.                                                             $to,
  2626.                                                             $due,
  2627.                                                             AppUserServices::getUser($post['selectResponsableHours']),
  2628.                                                             1,
  2629.                                                             $post['linkHour'],
  2630.                                                             !is_null($post['valueHour']) ?floatval($post['valueHour']):null,
  2631.                                                             !is_null($post['customervalueHour'])  ?floatval($post['customervalueHour']):null,
  2632.                                                             AppUserServices::getUser($post['selectCreatorHours'])
  2633.                                                         );
  2634.                                                         $flag true;
  2635.                                                         if($actualHours->getAccountHoursType()->getIdAccountHoursType() === AppAccountHourType::BILLED_HOURS){
  2636.                                                             $params = array(
  2637.                                                                 "ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
  2638.                                                                 "ReferenceCustomer" => $this->_referenceCustomer,
  2639.                                                                 "Increment" => -$actualHours->getDurationInMinutes(),
  2640.                                                                 "DateStamp" => date("c")
  2641.                                                             );
  2642.                                                             $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbonojson_encode($params));
  2643.                                                             if($data[1] != 200){
  2644.                                                                 $flag false;
  2645.                                                             }
  2646.                                                         }
  2647.                                                         if($flag){
  2648.                                                             if(!AppAccountHoursServices::setAccountHours($accountHours)){
  2649.                                                                 $this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
  2650.                                                             }
  2651.                                                             else{
  2652.                                                                 $this->addFlash("success""La modification des heures a bien été réalisée.");
  2653.                                                                 if(in_array($appAccount->getType()->getId(),AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED) and ($post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS  or $actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS ) ){
  2654.                                                                     if($actualHours->getAccountHoursType()->getIdAccountHoursType()  == AppAccountHourType::ONBOARDING_HOURS and $post['selectTypeHours'] != AppAccountHourType::ONBOARDING_HOURS)
  2655.                                                                     {
  2656.                                                                         if($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS){
  2657.                                                                             AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
  2658.                                                                         }
  2659.                                                                     }
  2660.                                                                     else{
  2661.                                                                         if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']){
  2662.                                                                             AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
  2663.                                                                         }
  2664.                                                                         else{
  2665.                                                                             AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($actualHours->getDurationInMinutes() + $this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
  2666.                                                                         }
  2667.                                                                     }
  2668.                                                                 }
  2669.                                                                 if($post['selectTypeHours'] == AppAccountHourType::NEWSLETTERS){
  2670.                                                                     if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']) {
  2671.                                                                         AppAccountServices::updateBalanceNewsletter($this->_idAccountfalse);
  2672.                                                                     }
  2673.                                                                 }
  2674.                                                                 else{
  2675.                                                                     if($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS )
  2676.                                                                     {
  2677.                                                                         AppAccountServices::updateBalanceNewsletter($this->_idAccounttrue);
  2678.                                                                     }
  2679.                                                                 }
  2680.                                                             }
  2681.                                                         }
  2682.                                                         else{
  2683.                                                             $this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
  2684.                                                         }
  2685.                                                     }
  2686.                                                     else{
  2687.                                                         $this->addFlash("error","Impossible de modifier ces heures. Elles ont déjà été facturées.");
  2688.                                                     }
  2689.                                                 }
  2690.                                             }
  2691.                                             else{
  2692.                                                 $this->addFlash("error","Une erreur a été rencontré lors de la récupération des heures consommées.");
  2693.                                             }
  2694.                                         }
  2695.                                         else{
  2696.                                             $this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
  2697.                                         }
  2698.                                     }
  2699.                                     else{
  2700.                                         $this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
  2701.                                     }
  2702.                                 }
  2703.                                 else{
  2704.                                     if($post['formActionHoursConsulting'] == "add"){
  2705.                                         $params = array(
  2706.                                             "ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
  2707.                                             "ReferenceCustomer" => $this->_referenceCustomer,
  2708.                                             "Increment" => intval($post['duration']),
  2709.                                             "DateStamp" => date("c")
  2710.                                         );
  2711.                                         $accountHours = new AppAccountHour(
  2712.                                             null,
  2713.                                             $this->_idAccount,
  2714.                                             $this->_idSubscription,
  2715.                                             $post['titleHour'],
  2716.                                             $post['commentHour'],
  2717.                                             new AppAccountHourType($post['selectTypeHours']),
  2718.                                             new AppAccountHourStatus($post['selectStatusHours']),
  2719.                                             $post['duration'],
  2720.                                             $from,
  2721.                                             $to,
  2722.                                             $due,
  2723.                                             AppUserServices::getUser($post['selectResponsableHours']),
  2724.                                             0,
  2725.                                             $post['linkHour'],
  2726.                                             !is_null($post['valueHour']) ? floatval($post['valueHour']) : null,
  2727.                                             !is_null($post['customervalueHour'])  ?floatval($post['customervalueHour']):null,
  2728.                                             AppUserServices::getUser($post['selectCreatorHours'])
  2729.                                         );
  2730.                                         if($post['selectStatusHours'] == 3)
  2731.                                         {
  2732.                                             $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbonojson_encode($params));
  2733.                                             if ($data[1] == 200) {
  2734.                                                 if (!AppAccountHoursServices::setAccountHours($accountHours)) {
  2735.                                                     $this->addFlash("error""Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
  2736.                                                 } else {
  2737.                                                     $this->addFlash("success""La saisie des heures a bien été réalisée.");
  2738.                                                 }
  2739.                                             } else {
  2740.                                                 $this->addFlash("error""Une erreur a été rencontrée lors de la facturation des heures consommées.");
  2741.                                             }
  2742.                                         }
  2743.                                         else{
  2744.                                             if (!AppAccountHoursServices::setAccountHours($accountHours)) {
  2745.                                                 $this->addFlash("error""Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
  2746.                                             } else {
  2747.                                                 $this->addFlash("success""La saisie des heures a bien été réalisée.");
  2748.                                             }
  2749.                                         }
  2750.                                     }
  2751.                                     else if($post['formActionHoursConsulting'] == "update"){
  2752.                                         if(isset($post['idHour']) and !empty($post['idHour'])){
  2753.                                             $actualHours AppAccountHoursServices::getAccountHoursById($this->_idAccount,$post['idHour']);
  2754.                                             if($actualHours){
  2755.                                                 if(!$actualHours->getIsBilled()){
  2756.                                                     if($actualHours->getAccountHoursStatus()->getIdAccountHoursStatus() != 3)
  2757.                                                     {
  2758.                                                         $actualHours->setDurationInMinutes(0);
  2759.                                                     }
  2760.                                                     if(!in_array($actualHours->getAccountHoursType()->getIdAccountHoursType(),$typehoursUpdateProAbono)){
  2761.                                                         $increment $post['duration'];
  2762.                                                     }
  2763.                                                     else{
  2764.                                                         $increment $post['duration'] - $actualHours->getDurationInMinutes();
  2765.                                                     }
  2766.                                                     $accountHours = new AppAccountHour(
  2767.                                                         $post['idHour'],
  2768.                                                         $this->_idAccount,
  2769.                                                         $this->_idSubscription,
  2770.                                                         $post['titleHour'],
  2771.                                                         $post['commentHour'],
  2772.                                                         new AppAccountHourType($post['selectTypeHours']),
  2773.                                                         new AppAccountHourStatus($post['selectStatusHours']),
  2774.                                                         $post['duration'],
  2775.                                                         $from,
  2776.                                                         $to,
  2777.                                                         $due,
  2778.                                                         AppUserServices::getUser($post['selectResponsableHours']),
  2779.                                                         0,
  2780.                                                         $post['linkHour'],
  2781.                                                         !is_null($post['valueHour']) ? floatval($post['valueHour']) : null,
  2782.                                                         !is_null($post['customervalueHour'])  ?floatval($post['customervalueHour']):null,
  2783.                                                         AppUserServices::getUser($post['selectCreatorHours'])
  2784.                                                     );
  2785.                                                     if($post['selectStatusHours'] == 3) {
  2786.                                                         $params = array(
  2787.                                                             "ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
  2788.                                                             "ReferenceCustomer" => $this->_referenceCustomer,
  2789.                                                             "Increment" => $increment,
  2790.                                                             "DateStamp" => date("c")
  2791.                                                         );
  2792.                                                         $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbonojson_encode($params));
  2793.                                                         if ($data[1] == 200) {
  2794.                                                             if (!AppAccountHoursServices::setAccountHours($accountHours)) {
  2795.                                                                 $this->addFlash("error""Une erreur a été rencontrée lors de la modification des heures consommées.");
  2796.                                                             } else {
  2797.                                                                 $this->addFlash("success""La modification des heures a bien été réalisée.");
  2798.                                                                 if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS) {
  2799.                                                                     AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount, ($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
  2800.                                                                 }
  2801.                                                                 if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS) {
  2802.                                                                     AppAccountServices::updateBalanceNewsletter($this->_idAccounttrue);
  2803.                                                                 }
  2804.                                                             }
  2805.                                                         } else {
  2806.                                                             $this->addFlash("error""Une erreur a été rencontrée lors de la facturation des heures consommées.");
  2807.                                                         }
  2808.                                                     }
  2809.                                                     else{
  2810.                                                         if($post['oldStatusHours'] == 3) {
  2811.                                                             $params = array(
  2812.                                                                 "ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
  2813.                                                                 "ReferenceCustomer" => $this->_referenceCustomer,
  2814.                                                                 "Increment" => -$actualHours->getDurationInMinutes(),
  2815.                                                                 "DateStamp" => date("c")
  2816.                                                             );
  2817.                                                             $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbonojson_encode($params));
  2818.                                                             if($data[1] == 200){
  2819.                                                                 if (!AppAccountHoursServices::setAccountHours($accountHours)) {
  2820.                                                                     $this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
  2821.                                                                 }
  2822.                                                                 else{
  2823.                                                                     $this->addFlash("success","La modification des heures a bien été réalisée.");
  2824.                                                                 }
  2825.                                                             }
  2826.                                                             else{
  2827.                                                                 $this->addFlash("error","Une erreur a été rencontrée lors de la modification de la facturation.");
  2828.                                                             }
  2829.                                                         }
  2830.                                                         else{
  2831.                                                             if (!AppAccountHoursServices::setAccountHours($accountHours)) {
  2832.                                                                 $this->addFlash("error""Une erreur a été rencontrée lors de la modification des heures consommées.");
  2833.                                                             } else {
  2834.                                                                 $this->addFlash("success""La modification des heures a bien été réalisée.");
  2835.                                                                 if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS) {
  2836.                                                                     AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount, ($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
  2837.                                                                 }
  2838.                                                                 if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS) {
  2839.                                                                     AppAccountServices::updateBalanceNewsletter($this->_idAccounttrue);
  2840.                                                                 }
  2841.                                                             }
  2842.                                                         }
  2843.                                                     }
  2844.                                                 }
  2845.                                                 else{
  2846.                                                     $this->addFlash("error","Impossible de modifier ces heures. Elles ont déjà été facturées.");
  2847.                                                 }
  2848.                                             }
  2849.                                             else{
  2850.                                                 $this->addFlash("error","Une erreur a été rencontré lors de la récupération des heures consommées.");
  2851.                                             }
  2852.                                         }
  2853.                                         else{
  2854.                                             $this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
  2855.                                         }
  2856.                                     }
  2857.                                     else{
  2858.                                         $this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
  2859.                                     }
  2860.                                 }
  2861.                             }
  2862.                         }
  2863.                         else{
  2864.                             $this->addFlash("error","Certaines données du formulaire sont manquantes ou erronées.");
  2865.                         }
  2866.                     }
  2867.                     else if($this->_request->request->has('formDeleteHour')){
  2868.                         $post $this->_request->request->get('formDeleteHour');
  2869.                         if(isset($post['idHour']) and !empty($post['idHour'])){
  2870.                             $accountHour AppAccountHoursServices::getAccountHoursById($this->_idAccount,$post['idHour']);
  2871.                             if($accountHour){
  2872.                                 if(!in_array($accountHour->getAccountHoursType()->getIdAccountHoursType(),$typehoursUpdateProAbono)){
  2873.                                     if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
  2874.                                         $this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
  2875.                                     }
  2876.                                     else{
  2877.                                         $this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
  2878.                                         if($accountHour->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS){
  2879.                                             AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') + $accountHour->getDurationInMinutes()));
  2880.                                         }
  2881.                                         if($accountHour->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS){
  2882.                                             AppAccountServices::updateBalanceNewsletter($this->_idAccounttrue);
  2883.                                         }
  2884.                                     }
  2885.                                 }
  2886.                                 else{
  2887.                                     if(!$accountHour->getIsBilled()){
  2888.                                         $params = array(
  2889.                                             "ReferenceFeature" => $accountHour->getAccountHoursType()->getaccountHoursMarketingService(),
  2890.                                             "ReferenceCustomer" => $this->_referenceCustomer,
  2891.                                             "Increment" => -$accountHour->getDurationInMinutes(),
  2892.                                             "DateStamp" => date("c")
  2893.                                         );
  2894.                                         if($post['statusHour'] == 3)
  2895.                                         {
  2896.                                             $data $this->_api->callApi("POST"$this->_urlProAbono "/v1/Usage"$this->_tokenProAbonojson_encode($params));
  2897.                                             if($data[1] == 200){
  2898.                                                 if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
  2899.                                                     $this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
  2900.                                                 }
  2901.                                                 else{
  2902.                                                     $this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
  2903.                                                 }
  2904.                                             }
  2905.                                             else{
  2906.                                                 $this->addFlash("error","Une erreur a été rencontrée lors de la modification de la facturation.");
  2907.                                             }
  2908.                                         }
  2909.                                         else{
  2910.                                             if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
  2911.                                                 $this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
  2912.                                             }
  2913.                                             else{
  2914.                                                 $this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
  2915.                                             }
  2916.                                         }
  2917.                                     }
  2918.                                     else{
  2919.                                         $this->addFlash("error","Impossible de supprimer ces heures. Elles ont déjà été facturées.");
  2920.                                     }
  2921.                                 }
  2922.                             }
  2923.                             else{
  2924.                                 $this->addFlash("error","Une erreur a été rencontrée lors de la récupération des heures supprimés");
  2925.                             }
  2926.                         }
  2927.                         else{
  2928.                             $this->addFlash("error","Une erreur a été rencontrée lors de la suppression. Veuillez réessayer ultérieurement.");
  2929.                         }
  2930.                     }
  2931.                 }
  2932.                 else{
  2933.                     $this->addFlash("error","Aucune données n'a été envoyée.");
  2934.                 }
  2935.                 if($this->_request->query->has("idAccount")) {
  2936.                     return $this->redirect($this->generateUrl(
  2937.                         'Abonnement_suivi',
  2938.                         array("idAccount" => $this->_idAccount,
  2939.                         "client" => $request->query->get('client'null),
  2940.                         "typeHours" => $request->query->get('typeHours'null),
  2941.                         "statusHours" => $request->query->get('statusHours'null),
  2942.                         "responsable" => $request->query->get('responsable'null),
  2943.                         "creator" => $request->query->get('creator'null),
  2944.                         "retard" => $request->query->get('retard'null),
  2945.                         "futur" => $request->query->get('futur'null),
  2946.                         "historic" => $request->query->get('historic'null),
  2947.                         "datedebut" => $request->query->get('datedebut'null),
  2948.                         "datefin" => $request->query->get('datefin'null)
  2949.                         )
  2950.                     ));
  2951.                 }
  2952.                 else{
  2953.                     return $this->redirect("/Abonnement/Suivi");
  2954.                 }
  2955.             }
  2956.             $actual_url "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  2957.             if ($this->_request->query->has("pHours") and $this->_request->query->get("pHours") != "") {
  2958.                 $p $this->_request->query->get("pHours");
  2959.                 if (strpos($actual_url"&pHours=") !== false) {
  2960.                     $url_sans_page str_replace('&pHours=' urlencode($p), '&pHours='$actual_url);
  2961.                 }
  2962.                 else if (strpos($actual_url"?pHours=") !== false) {
  2963.                     $url_sans_page str_replace('?pHours=' urlencode($p), '?pHours='$actual_url);
  2964.                 }
  2965.                 if(intval($p) === 0){
  2966.                     $p 1;
  2967.                 }
  2968.             }
  2969.             else {
  2970.                 $p 1;
  2971.                 if(empty($_SERVER['QUERY_STRING'])){
  2972.                     $url_sans_page $actual_url "?pHours=";
  2973.                 }
  2974.                 else{
  2975.                     $url_sans_page $actual_url "&pHours=";
  2976.                 }
  2977.             }
  2978.             if($this->_isAdmin)
  2979.             {
  2980.                 $ArrayCLient = [];
  2981.                 array_push($ArrayCLient$appAccount->getIdCompany());
  2982.                 $request->query->set('client'$ArrayCLient);
  2983.                 $resultQuery $this->hoursRecherche($request$session$p);
  2984.                 $this->setAttribute('totalHours',$resultQuery['count']);
  2985.                 $this->setAttribute('totalValue',$resultQuery['sum']['totMontant']);
  2986.                 $this->setAttribute('totalCustomValue',$resultQuery['sum']['totCustomMontant']);
  2987.                 $this->setAttribute('nbrPages',$resultQuery['nbrOfPage']);
  2988.                 $this->setAttribute('accountHours'$resultQuery['result']);
  2989.                 $nbrPages =$resultQuery['nbrOfPage'];
  2990.             }
  2991.             if($p $nbrPages){
  2992.                 $p 1;
  2993.             }
  2994.             if (strpos($url_sans_page"&pHours=") !== false) {
  2995.                 $url_premiere_page str_replace('&pHours=''&pHours=1'$url_sans_page);
  2996.                 $url_derniere_page str_replace('&pHours=''&pHours='.$nbrPages$url_sans_page);
  2997.             }
  2998.             else if (strpos($url_sans_page"?pHours=") !== false){
  2999.                 $url_premiere_page str_replace('?pHours=''?pHours=1'$url_sans_page);
  3000.                 $url_derniere_page str_replace('?pHours=''?pHours='.$nbrPages$url_sans_page);
  3001.             }
  3002.             else{
  3003.                 $url_premiere_page $url_sans_page '?pHours=1';
  3004.                 $url_derniere_page $url_sans_page '?pHours=' $nbrPages;
  3005.             }
  3006.             $this->setAttribute('url_sans_page',$url_sans_page);
  3007.             $this->setAttribute('url_premiere_page',$url_premiere_page);
  3008.             $this->setAttribute('url_derniere_page',$url_derniere_page);
  3009.             $this->setAttribute('numero_de_page',$p);
  3010.             $this->setAttribute('companyClientList'AdministrationServices::getAllCompanyClient());
  3011.             $endStatusHours AppAccountHoursServices::getEndStatusHours();
  3012.             $stopStatusHours AppAccountHoursServices::getStopStatusHours();
  3013.             $listIdHistoricStatus array_map(function($e) {
  3014.                 return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
  3015.             }, $endStatusHours);
  3016.             $listIdStopStatus array_map(function($e) {
  3017.                 return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
  3018.             }, $stopStatusHours);
  3019.             $this->setAttribute('arrayHistoricStatus'$listIdHistoricStatus);
  3020.             $this->setAttribute('arrayStopStatus'$listIdStopStatus);
  3021.             $encoders = [new JsonEncoder()];
  3022.             $normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(nullnullnull, new ReflectionExtractor())];
  3023.             $serializer = new Serializer($normalizers$encoders);
  3024.             $hoursType AppAccountHoursServices::getHoursType();
  3025.             $hoursStatus AppAccountHoursServices::getHoursStatus();
  3026.             $this->setAttribute('hoursStatus'json_decode($serializer->serialize($hoursStatus'json')));
  3027.             $this->setAttribute('hoursTypesSerial',json_decode($serializer->serialize($hoursType'json')));
  3028.             $this->setAttribute('hoursTypes',$hoursType);
  3029.             $accountUsers AppUserServices::getAccountUsers(AppAccount::VenteCoeff);
  3030.             uasort($accountUsers,function($a$b){
  3031.                 return $a->firstName <=> $b->firstName;
  3032.             });
  3033.             $this->setAttribute('responsablesSerial'json_decode($serializer->serialize($accountUsers'json')));
  3034.             if($request->query->get('typeHours'null) != null)
  3035.             {
  3036.                 $currentHoursStatus AppAccountHoursServices::getHoursStatusByTypeHours($request->query->get('typeHours'null));
  3037.             }
  3038.             $this->setAttribute('currentHoursStatus',$currentHoursStatus);
  3039.             $this->setAttribute('responsables',AppUserServices::getAccountUsers(AppAccount::VenteCoeff));
  3040.             $this->setAttribute('isAdmin',$this->_isAdmin);
  3041.             #$this->setAttribute('current',$this->_proAbonoUserState["current"]);
  3042.         }
  3043.         catch(Exception $e){
  3044.             if($e->getCode() == 01){
  3045.                 $this->setAttribute('error'$e->getMessage());
  3046.             }
  3047.             else{
  3048.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  3049.             }
  3050.         }
  3051.         return $this->render('abonnement/index.html.twig'$this->attribute);
  3052.     }
  3053.     /**
  3054.      * @Route("/Abonnement/Parametre", name="Abonnement_parametre")
  3055.      * @Route("/Abonnement/Parametre", name="abonnement_parametre")
  3056.      * @return Response
  3057.      * @throws Exception
  3058.      */
  3059.     public function abonnementParametre(SessionInterface $sessionRequest $request)
  3060.     {
  3061.         $this->setAttribute('search'$request->get('search'));
  3062.         if(!empty($_POST)){
  3063.             $searchExistingRoutine "formAccount_service_routine_list-select-idroutine-";
  3064.             $searchNewRoutine "formAccount_service_routine_list-select-new-";
  3065.             $arrayRequest $this->_request->request;
  3066.             foreach ($arrayRequest as $key => $value) {
  3067.                 if (strpos($key$searchExistingRoutine) !== false) {
  3068.                     $id str_replace($searchExistingRoutine""$key);
  3069.                     //update la colonne dans la bdd
  3070.                     if(strpos($key'-deleted') !== false){
  3071.                         RoutineServices::updateRoutineScoreMinAllowAlert($valuenull);
  3072.                     }else{
  3073.                         RoutineServices::updateRoutineScoreMinAllowAlert($value$this->_request->request->get("formAccount_service_routine_scoremin-idroutine-".$id));
  3074.                     }
  3075.                 }
  3076.                 if (strpos($key$searchNewRoutine) !== false) {
  3077.                     $id str_replace($searchNewRoutine""$key);
  3078.                     //update la colonne dans la bdd
  3079.                     if(strpos($key'-deleted') !== false){
  3080.                         RoutineServices::updateRoutineScoreMinAllowAlert($valuenull);
  3081.                     }else{
  3082.                         RoutineServices::updateRoutineScoreMinAllowAlert($value$this->_request->request->get("formAccount_service_routine_scoremin-new-".$id));
  3083.                     }
  3084.                 }
  3085.             }
  3086.         }
  3087.         if($this->_request->query->has("fromMenu")){
  3088.             $this->setAttribute('fromMenu',true);
  3089.         }
  3090.         $this->setAttribute('shownPart','parametre');
  3091.         $appAccount AppAccountServices::getAccount($this->_idAccount);
  3092.         $routineList RoutineServices::getRoutines($this->_idAccount);
  3093.         $appAccountRoutineList RoutineServices::getRoutineForAdmin($this->_idAccount);
  3094.         $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  3095.         foreach ($appAccount->getUsers() as &$user){
  3096.             if($this->isSupportUser($user->getEmail())){
  3097.                 $user->setIsSupport(true);
  3098.             }
  3099.             else{
  3100.                 $user->setIsSupport(false);
  3101.             }
  3102.             $user->setMailAccounts(AppMailAccountServices::getMailAccountByIdUser($user->getId()));
  3103.         }
  3104.         $allUsers $appAccount->getUsers();
  3105.         $this->setAttribute('appAccount'$appAccount);
  3106.         $this->setAttribute('routineList'$routineList);
  3107.         $this->setAttribute('appAccountRoutineList'$appAccountRoutineList);
  3108.         $this->setAttribute('userResponsableAccount',$this->_userResponsableAccount);
  3109.         $this->setAttribute('isAdmin',$this->_isAdmin);
  3110.         $this->setAttribute("customFieldList"AppCustomFieldServices::getCustomFieldList());
  3111.         $this->setAttribute('user'$this->_user);
  3112.         $this->setAttribute('account_users',$allUsers);
  3113.         return $this->render('abonnement/index.html.twig'$this->attribute);
  3114.     }
  3115.     /**
  3116.      * @Route("/Abonnement/Facture", name="Abonnement_facture")
  3117.      * @Route("/Abonnement/Facture", name="abonnement_facture")
  3118.      * @return Response
  3119.      *
  3120.      * @throws Exception
  3121.      */
  3122.     public function abonnementFacture(Request $request)
  3123.     {
  3124.         $this->setAttribute('shownPart','facture');
  3125.         $this->setAttribute('search'$request->get('search'));
  3126.         $appAccount AppAccountServices::getAccount($this->_idAccount);
  3127.         $this->setAttribute('appAccount',$appAccount);
  3128.         try{
  3129.             if(!$this->_proAbonoUserState){
  3130.                 throw new Exception();
  3131.             }
  3132.             if($this->_isTerminated and !$this->_isAdmin){
  3133.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  3134.             }
  3135.             if (!$this->_isOlder) {
  3136.                 $invoices = [];
  3137.                 $defaultUrl $this->_urlProAbono "/v1/Invoices?ReferenceCustomer=" $this->_referenceCustomer "&SizePage=".self::$NBRPERPAGE."&Page=";
  3138.                 $data $this->_api->callApi("GET"$defaultUrl."1" $this->_tokenProAbonofalse);
  3139.                 $status $data[1];
  3140.                 if ($status == 200) {
  3141.                     $actual_url "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  3142.                     $totalInvoices $data[0]['TotalItems'];
  3143.                     $nbrPages intval(ceil($totalInvoices self::$NBRPERPAGE));
  3144.                     if ($this->_request->query->has("p") and $this->_request->query->get("p") != "") {
  3145.                         $p $this->_request->query->get("p");
  3146.                         if (strpos($actual_url"&p=") !== false) {
  3147.                             $url_sans_page str_replace('&p=' urlencode($p), '&p='$actual_url);
  3148.                         }
  3149.                         else if (strpos($actual_url"?p=") !== false) {
  3150.                             $url_sans_page str_replace('?p=' urlencode($p), '?p='$actual_url);
  3151.                         }
  3152.                         if(intval($p) === 0){
  3153.                             $p 1;
  3154.                         }
  3155.                     } else {
  3156.                         $p 1;
  3157.                         if(empty($_SERVER['QUERY_STRING'])){
  3158.                             $url_sans_page $actual_url "?p=";
  3159.                         }
  3160.                         else{
  3161.                             $url_sans_page $actual_url "&p=";
  3162.                         }
  3163.                     }
  3164.                     if($p $nbrPages){
  3165.                         $p 1;
  3166.                     }
  3167.                     if (strpos($url_sans_page"&p=") !== false) {
  3168.                         $url_premiere_page str_replace('&p=''&p=1'$url_sans_page);
  3169.                         $url_derniere_page str_replace('&p=''&p='.$nbrPages$url_sans_page);
  3170.                     }
  3171.                     else if (strpos($url_sans_page"?p=") !== false){
  3172.                         $url_premiere_page str_replace('?p=''?p=1'$url_sans_page);
  3173.                         $url_derniere_page str_replace('?p=''?p='.$nbrPages$url_sans_page);
  3174.                     }
  3175.                     else{
  3176.                         $url_premiere_page $url_sans_page '?p=1';
  3177.                         $url_derniere_page $url_sans_page '?p=' $nbrPages;
  3178.                     }
  3179.                     if($p == 1){
  3180.                         $invoices array_merge($invoices$data[0]['Items']);
  3181.                     }
  3182.                     else{
  3183.                         $data $this->_api->callApi("GET"$defaultUrl.$p $this->_tokenProAbonofalse);
  3184.                         if($data[1] == 200){
  3185.                             $invoices array_merge($invoices$data[0]['Items']);
  3186.                         }
  3187.                     }
  3188.                     usort($invoices,function($a,$b){
  3189.                         return strtotime($b['DateIssue']) - strtotime($a['DateIssue']);
  3190.                     });
  3191.                     $this->setAttribute('url_sans_page',$url_sans_page);
  3192.                     $this->setAttribute('url_premiere_page',$url_premiere_page);
  3193.                     $this->setAttribute('url_derniere_page',$url_derniere_page);
  3194.                     $this->setAttribute('numero_de_page',$p);
  3195.                     $this->setAttribute('totalHours',$totalInvoices);
  3196.                     $this->setAttribute('nbrPages',$nbrPages);
  3197.                 }
  3198.                 $this->setAttribute('invoices'$invoices);
  3199.             }
  3200.         }
  3201.         catch(Exception $e){
  3202.             if($e->getCode() == 01){
  3203.                 $this->setAttribute('error'$e->getMessage());
  3204.             }
  3205.             else{
  3206.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  3207.             }
  3208.         }
  3209.         return $this->render('abonnement/index.html.twig'$this->attribute);
  3210.     }
  3211.     /**
  3212.      * @Route("/Abonnement/SuiviUserEdit", name="Abonnement_suivi_user_edit")
  3213.      * @Route("/Abonnement/SuiviUserEdit", name="abonnement_suivi_user_edit")
  3214.      * @return Response
  3215.      *
  3216.      * @throws Exception
  3217.      */
  3218.     public function abonnementSuiviUserEdit()
  3219.     {
  3220.         $this->setAttribute('shownPart','suivibackoffice');
  3221.         $success false;
  3222.         $message "";
  3223.         if ($this->_request->isMethod("POST")) {
  3224.             if($this->_request->request->has('addEditCommercial')) {
  3225.                 $post $this->_request->request->get('addEditCommercial');
  3226.                 if(isset($post['selectCommercial']) ){
  3227.                     if(AppAccountServices::updateCommercialUser($this->_idAccount$post['selectCommercial']))
  3228.                     {
  3229.                         $success true;
  3230.                         $message =  "Le commercial de l'abonnement a bien été changé.";
  3231.                     }
  3232.                     else
  3233.                     {
  3234.                         $success false;
  3235.                         $message =  "Une erreur est survenue lors de l'enregistrement du commercial.";
  3236.                     }
  3237.                 }
  3238.                 else{
  3239.                     $success false;
  3240.                     $message =  "Certaines données du formulaire sont manquantes ou erronées.";
  3241.                 }
  3242.             }
  3243.             if($this->_request->request->has('addEditCSM')) {
  3244.                 $post $this->_request->request->get('addEditCSM');
  3245.                 if(isset($post['selectCSM']) ){
  3246.                     if(AppAccountServices::updateCSMUser($this->_idAccount$post['selectCSM']))
  3247.                     {
  3248.                         $success true;
  3249.                         $message "Le CSM  de l'abonnement a bien été changé.";
  3250.                     }
  3251.                     else
  3252.                     {
  3253.                         $success false;
  3254.                         $message =  "Une erreur est survenue lors de l'enregistrement du CSM.";
  3255.                     }
  3256.                 }
  3257.                 else{
  3258.                     $success false;
  3259.                     $message =  "Certaines données du formulaire sont manquantes ou erronées.";
  3260.                 }
  3261.             }
  3262.             if($this->_request->request->has('addEditSupport')) {
  3263.                 $post $this->_request->request->get('addEditSupport');
  3264.                 if(isset($post['selectSupport']) ){
  3265.                     if(AppAccountServices::updateSupportUser($this->_idAccount$post['selectSupport']))
  3266.                     {
  3267.                         $success true;
  3268.                         $message =  "Le support client de l'abonnement a bien été changé.";
  3269.                     }
  3270.                     else
  3271.                     {
  3272.                         $success false;
  3273.                         $message =  "Une erreur est survenue lors de l'enregistrement du support client.";
  3274.                     }
  3275.                 }
  3276.                 else{
  3277.                     $success false;
  3278.                     $message =  "Certaines données du formulaire sont manquantes ou erronées.";
  3279.                 }
  3280.             }
  3281.         }
  3282.         $encoders = [new JsonEncoder()];
  3283.         $normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(nullnullnull, new ReflectionExtractor())];
  3284.         $serializer = new Serializer($normalizers$encoders);
  3285.         return new JsonResponse([
  3286.             'success' => $success,
  3287.             'message' => $message,
  3288.             'data' => null
  3289.         ]);
  3290.     }
  3291.     /**
  3292.      * @Route("/Abonnement/Paiement", name="Abonnement_paiement")
  3293.      * @Route("/Abonnement/Paiement", name="abonnement_paiement")
  3294.      * @return Response
  3295.      *
  3296.      * @throws Exception
  3297.      */
  3298.     public function abonnementPaiement(Request $request)
  3299.     {
  3300.         $this->setAttribute('shownPart','paiement');
  3301.         $this->setAttribute('search'$request->get('search'));
  3302.         $appAccount AppAccountServices::getAccount($this->_idAccount);
  3303.         $this->setAttribute('appAccount',$appAccount);
  3304.         try{
  3305.             if(!$this->_proAbonoUserState){
  3306.                 throw new Exception();
  3307.             }
  3308.             if($this->_isTerminated and !$this->_isAdmin){
  3309.                 throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
  3310.             }
  3311.             if(!$this->_isOlder or $this->_request->get("ajax") or ($this->_isOlder and !empty($this->_proAbonoUserState['delayed']))){
  3312.                 if($this->_isFreemium and !$this->_request->get("ajax") and empty($this->_proAbonoUserState['delayed'])){
  3313.                     throw new Exception("Désolé mais votre abonnement ne vous permet pas de configurer un moyen de paiement."01);
  3314.                 }
  3315.                 else {
  3316.                     $flag false;
  3317.                     $iframe null;
  3318.                     if ($this->_request->isMethod("POST")) {
  3319.                         if(isset($_POST['formUpdateBillingAdress'])){
  3320.                             $post $_POST['formUpdateBillingAdress'];
  3321.                             foreach ($post as &$value) {
  3322.                                 $value ltrim($value);
  3323.                                 $value rtrim($value);
  3324.                             }
  3325.                             if (isset($post['Email']) and !empty($post['Email'])
  3326.                                 and isset($post['FirstName']) and !empty($post['FirstName'])
  3327.                                 and isset($post['LastName']) and !empty($post['LastName'])
  3328.                                 and isset($post['Company']) and !empty($post['Company'])
  3329.                                 and isset($post['AddressLine1']) and !empty($post['AddressLine1'])
  3330.                                 and isset($post['ZipCode']) and !empty($post['ZipCode'])
  3331.                                 and isset($post['City']) and !empty($post['City'])){
  3332.                                 $email = new \stdClass();
  3333.                                 $email->Email $post['Email'];
  3334.                                 $customerInfos $this->_api->callApi("POST"$this->_urlProAbono "/v1/Customer?ReferenceCustomer=" $this->_referenceCustomer$this->_tokenProAbonojson_encode($email), falsetrue);
  3335.                                 if (array_key_exists("Email"$post)) {
  3336.                                     unset($post['Email']);
  3337.                                 }
  3338.                                 $billingAdress $this->_api->callApi("POST"$this->_urlProAbono "/v1/CustomerBillingAddress?ReferenceCustomer=" $this->_referenceCustomer$this->_tokenProAbonojson_encode($post), falsetrue);
  3339.                                 if (array_key_exists('Links'$customerInfos[0])) {
  3340.                                     foreach ($customerInfos[0]['Links'] as $link) {
  3341.                                         if ($link['rel'] == "hosted-register") {
  3342.                                             $iframe $link['href'];
  3343.                                         }
  3344.                                     }
  3345.                                 }
  3346.                                 if ($billingAdress[1] == 200 && $customerInfos[1] == 200) {
  3347.                                     if($this->_request->get("ajax")){
  3348.                                         return new JsonResponse(array(
  3349.                                             'status' => 200
  3350.                                         ));
  3351.                                     }
  3352.                                     else{
  3353.                                         $flag true;
  3354.                                         $this->setAttribute('customerInfos'$customerInfos[0]);
  3355.                                         $this->setAttribute('billingAdress'$billingAdress[0]);
  3356.                                         $this->addFlash('success'"Les coordonnées de facturation ont bien été mise à jour.");
  3357.                                     }
  3358.                                 } else {
  3359.                                     if($this->_request->get("ajax")){
  3360.                                         return new JsonResponse(array(
  3361.                                             'status' => 404,
  3362.                                             'errorBillingAdress' => $billingAdress,
  3363.                                             'errorCustomerInfos' => $customerInfos
  3364.                                         ));
  3365.                                     }
  3366.                                     else{
  3367.                                         $this->addFlash('error'"Une erreur a été rencontrée lors de la mise à jour de vos coordonnées.");
  3368.                                     }
  3369.                                 }
  3370.                             } else {
  3371.                                 throw new Exception("Une erreur technique à été rencontrée lors de la mise à jour de vos coordonnées de facturation. Veuillez réessayer ultérieurement."01);
  3372.                             }
  3373.                         }
  3374.                         else if(isset($_POST['formAddBankDetails'])){
  3375.                             $post $_POST['formAddBankDetails'];
  3376.                             if(isset($post['owner']) and !empty(isset($post['owner']))
  3377.                                 and isset($post['iban']) and !empty(isset($post['iban']))
  3378.                                 and isset($post['bic']) and !empty(isset($post['bic']))
  3379.                                 and isset($post['rum']) and !empty(isset($post['rum']))){
  3380.                                 $payload = array(
  3381.                                     "IdBusiness" => $this->_idBusiness,
  3382.                                     "IdAccount" => $this->_idAccountProabono,
  3383.                                     "IdCustomer" => $this->_idCustomer,
  3384.                                     "NameDisplay" => $post['rum'],
  3385.                                     "DataGateway" => array(
  3386.                                         "ReferenceMandate" => $post['rum'],
  3387.                                         "Iban" => $post['iban'],
  3388.                                         "Bic" => $post['bic'],
  3389.                                         "NameCustomer" => $post['owner'],
  3390.                                         "DateSignature" => date("Y-m-d")
  3391.                                     )
  3392.                                 );
  3393.                                 $callApi $this->_api->callApi("POST",$this->_urlBackOfficeProAbono."/Gateway/GatewayPermissions"$this->_tokenProAbonojson_encode($payload), falsetrue);
  3394.                                 $code $callApi[1];
  3395.                                 if($code == 201){
  3396.                                     $details_iv EncryptionService::generateIv();
  3397.                                     $details_key AppAccountBankDetailsServices::getEncryptionkey();
  3398.                                     $details = new AppAccountBankDetails(
  3399.                                         $this->_idAccount,
  3400.                                         $this->_user['idUser'],
  3401.                                         EncryptionService::encrypt($post['owner'], $details_iv$details_key),
  3402.                                         EncryptionService::encrypt($post['iban'], $details_iv$details_key),
  3403.                                         EncryptionService::encrypt($post['bic'], $details_iv$details_key),
  3404.                                         EncryptionService::encrypt($post['rum'], $details_iv$details_key),
  3405.                                         new DateTime("now", new DateTimeZone("Europe/Paris")),
  3406.                                         (isset($post['link']) and !empty($post['link'])) ? $post['link'] : null,
  3407.                                         null,
  3408.                                         null,
  3409.                                         $details_iv
  3410.                                     );
  3411.                                     if(AppAccountBankDetailsServices::setAccountBankDetails($details)){
  3412.                                         if($this->_request->get("ajax")){
  3413.                                             return new JsonResponse(array(
  3414.                                                 'status' => 200
  3415.                                             ));
  3416.                                         }
  3417.                                         else{
  3418.                                             $this->addFlash('success'"Le mandat de prélèvement a bien été signé.");
  3419.                                         }
  3420.                                     }
  3421.                                     else{
  3422.                                         if($this->_request->get("ajax")){
  3423.                                             return new JsonResponse(array(
  3424.                                                 'status' => 404,
  3425.                                                 'error' => "Erreur lors de l'ajout du mandat de prélèvement en base"
  3426.                                             ));
  3427.                                         }
  3428.                                         else{
  3429.                                             $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  3430.                                         }
  3431.                                     }
  3432.                                 }
  3433.                                 else{
  3434.                                     if($code == 422){
  3435.                                         if($this->_request->get("ajax")){
  3436.                                             return new JsonResponse(array(
  3437.                                                 'status' => $code,
  3438.                                                 'error' => "Erreur dans les champs du mandat de prélèvement",
  3439.                                                 'callApi' => $callApi
  3440.                                             ));
  3441.                                         }
  3442.                                         else{
  3443.                                             $this->addFlash('error'"L'IBAN et/ou le BIC saisis ne sont pas valide, veuillez vérifier votre saisie.");
  3444.                                         }
  3445.                                     }
  3446.                                     else{
  3447.                                         if($this->_request->get("ajax")){
  3448.                                             return new JsonResponse(array(
  3449.                                                 'status' => $code,
  3450.                                                 'error' => "Erreur Proabono lors de la signature du mandat de prélèvement",
  3451.                                                 'callApi' => $callApi
  3452.                                             ));
  3453.                                         }
  3454.                                         else{
  3455.                                             $this->addFlash('error'"Une erreur a été rencontrée lors de l'enregistrement du mandat de prélèvement. Veuillez réessayer ultérieurement.");
  3456.                                         }
  3457.                                     }
  3458.                                 }
  3459.                             }
  3460.                         }
  3461.                     }
  3462.                     $this->setAttribute('countries'RegCountryServices::getCountryList());
  3463.                     $paymentSettings $this->_api->callApi("GET"$this->_urlProAbono "/v1/CustomerSettingsPayment?ReferenceCustomer=" $this->_referenceCustomer "&page=1"$this->_tokenProAbonofalse );
  3464.                     if ($paymentSettings[1] != "200") {
  3465.                         if ($paymentSettings[1] != "204") {
  3466.                             throw new Exception("Une erreur technique à été rencontré lors de la récupération de vos informations de paiement. Veuillez réessayer ultérieurement."01);
  3467.                         }
  3468.                     } else {
  3469.                         $this->setAttribute('paymentType'$paymentSettings[0]['TypePayment']);
  3470.                     }
  3471.                     if (!$flag) {
  3472.                         $customerInfos $this->_api->callApi("GET"$this->_urlProAbono "/v1/Customer?ReferenceCustomer=" $this->_referenceCustomer "&page=1"$this->_tokenProAbonofalse);
  3473.                         $status $customerInfos[1];
  3474.                         if ($status != 200) {
  3475.                             if ($status != 204) {
  3476.                                 throw new Exception("Une erreur technique à été rencontré lors de la récupération de vos coordonnées de facturation. Veuillez réessayer ultérieurement."01);
  3477.                             }
  3478.                         } else {
  3479.                             $this->setAttribute('customerInfos'$customerInfos[0]);
  3480.                             $billingAdress $this->_api->callApi("GET"$this->_urlProAbono "/v1/CustomerBillingAddress?ReferenceCustomer=" $this->_referenceCustomer "&page=1"$this->_tokenProAbonofalse);
  3481.                             if ($billingAdress[1] != "200") {
  3482.                                 if ($billingAdress[1] != "204") {
  3483.                                     throw new Exception("Une erreur technique à été rencontré lors de la récupération de vos coordonnées de facturation. Veuillez réessayer ultérieurement."01);
  3484.                                 }
  3485.                             } else {
  3486.                                 $this->setAttribute('billingAdress'$billingAdress[0]);
  3487.                             }
  3488.                         }
  3489.                         if(is_null($iframe)){
  3490.                             if (array_key_exists('Links'$customerInfos[0])) {
  3491.                                 foreach ($customerInfos[0]['Links'] as $link) {
  3492.                                     if ($link['rel'] == "hosted-register") {
  3493.                                         $iframe $link['href'];
  3494.                                     }
  3495.                                 }
  3496.                             }
  3497.                         }
  3498.                         $this->setAttribute('iframe'$iframe);
  3499.                     }
  3500.                     $this->setAttribute('RUM',"COEF".$this->_referenceCustomer.time());
  3501.                     if($paymentSettings[0]['TypePayment'] == "Batch"){
  3502.                         $callApi $this->_api->callApi("GET",$this->_urlBackOfficeProAbono."/Gateway/GatewayPermissions?IdBusiness=".$this->_idBusiness."&StatePermission=Enabled&TypeGateway=BatchSepa&IdCustomer=".$this->_idCustomer$this->_tokenProAbonofalse);
  3503.                         if(isset($callApi) && $callApi != "" && $callApi != null) {
  3504.                             if ($callApi[1] == 200) {
  3505.                                 if (count($callApi[0]['Items']) > 1) {
  3506.                                     usort($callApi[0]['Items'], function ($a$b) {
  3507.                                         return strtotime($b['DateCreation']) - strtotime($a['DateCreation']);
  3508.                                     });
  3509.                                 }
  3510.                                 $this->setAttribute("mandateLink"AppAccountBankDetailsServices::getAccountMandateLinkByIdAccount($this->_idAccount));
  3511.                                 $this->setAttribute('appAccountBankDetails'$callApi[0]['Items'][0]);
  3512.                             } else {
  3513.                                 throw new Exception("Une erreur a été rencontrée lors de la récupération de votre moyen de paiement."02);
  3514.                             }
  3515.                         }
  3516.                     }
  3517.                 }
  3518.             }
  3519.         }
  3520.         catch(Exception $e){
  3521.             if($this->_request->get("ajax")){
  3522.                 return new JsonResponse(array(
  3523.                     'status' => 404,
  3524.                     'error' => $e->getMessage()
  3525.                 ));
  3526.             }
  3527.             else{
  3528.                 if($e->getCode() == 01){
  3529.                     $this->setAttribute('error'$e->getMessage());
  3530.                 }
  3531.                 else {
  3532.                     if ($e->getCode() == 02) {
  3533.                         $error['code'] = $e->getCode();
  3534.                         $error['message'] = $e->getMessage();
  3535.                         $this->setAttribute('error'$error);
  3536.                     } else {
  3537.                         $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  3538.                     }
  3539.                 }
  3540.             }
  3541.         }
  3542.         if($this->_request->get("ajax")){
  3543.             if($this->_request->get("step") == 1){
  3544.                 $this->setAttribute("subscription",true);
  3545.                 return $this->render('abonnement/onglets/paiement/abonnement_paiement_form.html.twig'$this->attribute);
  3546.             }
  3547.             else{
  3548.                 $this->setAttribute('collapse',true);
  3549.                 return $this->render('abonnement/onglets/paiement/abonnement_paiement_type_with_modal_sepa.html.twig'$this->attribute);
  3550.             }
  3551.         }
  3552.         else{
  3553.             return $this->render('abonnement/index.html.twig'$this->attribute);
  3554.         }
  3555.     }
  3556.     /**
  3557.      * @Route("/abonnement/proabono/refresh", name="abonnement_proabono_refresh")
  3558.      * @param $idCustomer
  3559.      * @param Boolean $fromTrigger
  3560.      * @param Boolean $fromScript
  3561.      * @return Response
  3562.      * @throws Exception
  3563.      */
  3564.     public function abonnementRefresh($idCustomer,Bool $fromTrigger false$fromScript falseInt $idSubscription null){
  3565.         $error false;
  3566.         try {
  3567.             if(!is_null($idCustomer)) {
  3568.                 $api = new CallApi();
  3569.                 $confProAbono BaseController::getConfig()['proabono-api'];
  3570.                 $urlProAbono $confProAbono['url'];
  3571.                 $urlBackOfficeProAbono $confProAbono['url-backOffice'];
  3572.                 $tokenProAbono $confProAbono['token'];
  3573.                 $idBusiness $confProAbono['idBusiness'];
  3574.                 $segmentProAbono $confProAbono['ref-segment'];
  3575.                 $urlAfterSynchro $confProAbono['urlAfterSynchro'];
  3576.                 $p '/v1/Subscriptions?IdCustomer=' $idCustomer '&page=1';
  3577.                 $currentSubscription null;
  3578.                 $dataSouscription $api->callApi('GET'$urlProAbono $p$tokenProAbonofalse$fromScript);
  3579.                 $referenceCustomer null;
  3580.                 if ($dataSouscription[1] === 200) {
  3581.                     if (!empty($dataSouscription[0]['Items'])){
  3582.                         $next true;
  3583.                         while ($next) {
  3584.                             for ($v 0$v count($dataSouscription[0]['Items']); $v++) {
  3585.                                 if (is_null($referenceCustomer)) {
  3586.                                     $referenceCustomer $dataSouscription[0]['Items'][$v]['ReferenceCustomer'];
  3587.                                 }
  3588.                                 if ($dataSouscription[0]['Items'][$v]['Status'] == 'Active') {
  3589.                                     $currentSubscription $dataSouscription[0]['Items'][$v];
  3590.                                     break;
  3591.                                 }
  3592.                             }
  3593.                             if (array_key_exists('Links'$dataSouscription[0]) && is_null($currentSubscription)) {
  3594.                                 if ($dataSouscription[0]['Links'][0]['rel'] == 'next') {
  3595.                                     $dataSouscription $api->callApi('GET'$urlProAbono $dataSouscription[0]['Links'][0]['href'], $tokenProAbonofalse$fromScript);
  3596.                                 } else if (count($dataSouscription[0]['Links']) > && $dataSouscription[0]['Links'][1]['rel'] == 'next') {
  3597.                                     $dataSouscription $api->callApi('GET'$urlProAbono $dataSouscription[0]['Links'][1]['href'], $tokenProAbonofalse$fromScript);
  3598.                                 } else {
  3599.                                     $next false;
  3600.                                 }
  3601.                             } else {
  3602.                                 $next false;
  3603.                             }
  3604.                         }
  3605.                         if (is_null($currentSubscription)) {
  3606.                             if (is_null($referenceCustomer)) {
  3607.                                 throw new Exception("Impossible de retrouver un abonnement actif. Une erreur a été rencontrée lors de la récupération du ReferenceCustomer.");
  3608.                             }
  3609.                             $params = array(
  3610.                                 "ReferenceCustomer" => $referenceCustomer,
  3611.                                 "ReferenceOffer" => AppAccountType::REFERRAL,
  3612.                                 "Metadata" => [
  3613.                                     "event" => "createdAfterPreviousSubscriptionEnded",
  3614.                                 ]
  3615.                             );
  3616.                             $toReferral $api->callApi('POST'$urlProAbono "/v1/Subscription?tryStart=true"$tokenProAbonojson_encode($params), $fromScript);
  3617.                             if ($toReferral[1] !== 201) {
  3618.                                 throw new Exception("Impossible de retrouver un abonnement actif. Une erreur a été rencontrée lors de la création automatique de l'abonnement REFERRAL.");
  3619.                             } else {
  3620.                                 $countSubscriptions $api->callApi("GET"$urlBackOfficeProAbono "/Sub/Subscriptions?IdBusiness=".$idBusiness."&IdCustomer=".$idCustomer$tokenProAbonofalse$fromScript);
  3621.                                 if($countSubscriptions[1] == 200){
  3622.                                     $params = array(
  3623.                                         "Name" => "Abonnement ".$countSubscriptions[0]['TotalItems']
  3624.                                     );
  3625.                                     $api->callApi("PATCH"$urlBackOfficeProAbono "/Sub/Subscriptions/" $toReferral[0]['Id']. "&IdBusiness=" $idBusiness$tokenProAbonojson_encode($params), $fromScript);
  3626.                                 }
  3627.                                 $currentSubscription $toReferral[0];
  3628.                             }
  3629.                         } else {
  3630.                             if(!is_null($idSubscription)){
  3631.                                 if ($idSubscription != $currentSubscription['Id']) {
  3632.                                     throw new Exception("L'id d'abonnement envoyée ne correspond pas à l'abonnement running. Pas besoin de refresh.");
  3633.                                 }
  3634.                             }
  3635.                         }
  3636.                         $idAccountType $currentSubscription['ReferenceOffer'];
  3637.                         $idSubscription $currentSubscription['Id'];
  3638.                         $idAccount null;
  3639.                         $identifiedNumber $currentSubscription['ReferenceCustomer'];
  3640.                         $dateUpdate $currentSubscription['DateUpdate'];
  3641.                         if (strpos($identifiedNumber"814045571") !== false) {
  3642.                             $keyword str_replace("814045571"""$identifiedNumber);
  3643.                             $idAccount AppAccountServices::getAccountByKeyword($keyword)->getId();
  3644.                         } else if (strpos($identifiedNumber"749836292") !== false) {
  3645.                             $keyword str_replace("749836292"""$identifiedNumber);
  3646.                             $idAccount AppAccountServices::getAccountByKeyword($keyword)->getId();
  3647.                         } else {
  3648.                             $idAccount AppAccountServices::getAccountBySiren($identifiedNumber)->getId();
  3649.                         }
  3650.                         $appAccount AppAccountServices::getAccount($idAccount);
  3651.                         $appAccount->setIdSubscription($idSubscription);
  3652.                         $setAccountEndDateFlag true;
  3653.                         if($idAccountType == AppAccountType::DESACTIVE){
  3654.                             $appAccount->setAccountEndDate(null);
  3655.                             $appAccount->setAccountRenewalDate(null);
  3656.                             $appAccount->setAccountDateStart(null);
  3657.                             $appAccount->setAccountDatePeriodStart(null);
  3658.                             $appAccount->setAccountDatePeriodEnd(null);
  3659.                         }
  3660.                         else{
  3661.                             if(array_key_exists("DateStart",$currentSubscription)){
  3662.                                 $appAccount->setAccountDateStart(new DateTime($currentSubscription['DateStart']));
  3663.                                 AppAccountServices::setAccountDateStart($appAccount);
  3664.                             }
  3665.                             if(array_key_exists("DatePeriodEnd",$currentSubscription) && array_key_exists("DatePeriodStart",$currentSubscription)){
  3666.                                 $appAccount->setAccountDatePeriodStart(new DateTime($currentSubscription['DatePeriodStart']));
  3667.                                 $appAccount->setAccountDatePeriodEnd(new DateTime($currentSubscription['DatePeriodEnd']));
  3668.                                 AppAccountServices::setAccountDatePeriod($appAccount);
  3669.                             }
  3670.                             if(array_key_exists("StateSubscriptionAfterTerm",$currentSubscription)){
  3671.                                 if($currentSubscription['StateSubscriptionAfterTerm'] == "Terminated" or $currentSubscription['StateSubscriptionAfterTerm'] == "History" or $currentSubscription['StateSubscriptionAfterTerm'] == "EndedTerminated" or $currentSubscription['StateSubscriptionAfterTerm'] == "EndedComplete"){
  3672.                                     $appAccount->setAccountEndDate(new DateTime($currentSubscription['DateTerm']));
  3673.                                     $appAccount->setAccountRenewalDate(null);
  3674.                                 }
  3675.                                 else{
  3676.                                     $terminationStatusOfCurrentSubscription AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($currentSubscription['Id']);
  3677.                                     if($terminationStatusOfCurrentSubscription){
  3678.                                         if($terminationStatusOfCurrentSubscription->getTerminationStatus()->getIdTerminationStatus() == AppAccountTerminationStatus::EN_RESILIATION){// SI une resil en cours sur cet abonnement (idTermination Status 1 & idSubscription) on touche pas la date
  3679.                                             $appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
  3680.                                             $setAccountEndDateFlag false;
  3681.                                         }
  3682.                                         else{
  3683.                                             $appAccount->setAccountEndDate(null);
  3684.                                             $appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
  3685.                                         }
  3686.                                     }
  3687.                                     else{
  3688.                                         $appAccount->setAccountEndDate(null);
  3689.                                         $appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
  3690.                                     }
  3691.                                 }
  3692.                             }
  3693.                             else{
  3694.                                 $appAccount->setAccountEndDate(null);
  3695.                                 $appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
  3696.                             }
  3697.                         }
  3698.                         AppAccountServices::setAccountRenewalDate($appAccount);
  3699.                         AppAccountServices::setAccountIdSubscription($appAccount);
  3700.                         if($setAccountEndDateFlag){
  3701.                             AppAccountServices::setAccountEndDate($appAccount);
  3702.                         }
  3703.                         if ($idAccountType == AppAccountType::DESACTIVE) {
  3704.                             if ($appAccount->getType()->getId() != $idAccountType) {
  3705.                                 $appAccountType = new AppAccountType($idAccountType);
  3706.                                 $appAccount->setType($appAccountType);
  3707.                                 if (!AppAccountServices::setAccountType($appAccount)) {
  3708.                                     throw new Exception("Erreur lors de la mise à jour de l'idAccountType de l'abonnement (abonnement désactivé)");
  3709.                                 }
  3710.                             }
  3711.                             $accountUser AppUserServices::getAccountUsers($appAccount->getId());
  3712.                             if (!empty($appAccount->getServices())) {
  3713.                                 if (!empty($accountUser)) {
  3714.                                     if (!Services_coefficy_utilisateurs::deleteAllUsers($appAccount->getId())) {
  3715.                                         throw new Exception("Erreur lors de la suppression de l'abonnement (abonnement désactivé)");
  3716.                                     } else {
  3717.                                         if (!AppUserServices::setMailAccountIsActiveByIdAccount($appAccount->getId(), false)) {
  3718.                                             throw new Exception("Erreur lors de la desactivation du mailAccount de l'utilisateur (abonnement désactivé)");
  3719.                                         } else {
  3720.                                             if (!ActionLinkServices::desactiveUserLinksByIdAccount($appAccount->getId())) {
  3721.                                                 throw new Exception("Erreur lors de la desactivation des liens de l'utilisateur (abonnement désactivé)");
  3722.                                             }
  3723.                                         }
  3724.                                     }
  3725.                                 }
  3726.                                 if (!AppAccountServices::deleteAllServices($idAccount)) {
  3727.                                     throw new Exception("Erreur lors de la suppression des services (désactivé)");
  3728.                                 } else {
  3729.                                     AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
  3730.                                     return new JsonResponse(array(
  3731.                                         'message' => "L'abonnement a bien été désactivé"
  3732.                                     ), 200);
  3733.                                 }
  3734.                             } else {
  3735.                                 if (!empty($accountUser)) {
  3736.                                     if (!Services_coefficy_utilisateurs::deleteAllUsers($appAccount->getId())) {
  3737.                                         throw new Exception("Erreur lors de la suppression de l'abonnement (abonnement désactivé)");
  3738.                                     } else {
  3739.                                         if (!AppUserServices::setMailAccountIsActiveByIdAccount($appAccount->getId(), false)) {
  3740.                                             throw new Exception("Erreur lors de la desactivation du mailAccount de l'utilisateur  (abonnement désactivé)");
  3741.                                         } else {
  3742.                                             if (!ActionLinkServices::desactiveUserLinksByIdAccount($appAccount->getId())) {
  3743.                                                 throw new Exception("Erreur lors de la desactivation des liens de l'utilisateur (abonnement désactivé)");
  3744.                                             }
  3745.                                         }
  3746.                                     }
  3747.                                 }
  3748.                                 AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
  3749.                                 return new JsonResponse(array(
  3750.                                     'message' => "L'abonnement a bien été désactivé (uniquement la désactivation des utilisateurs)"
  3751.                                 ), 200);
  3752.                             }
  3753.                         }
  3754.                         $nextPage true;
  3755.                         $p '/v1/Usages?IdCustomer=' $idCustomer '&page=1';
  3756.                         $items = [];
  3757.                         while ($nextPage) {
  3758.                             $data $api->callApi('GET'$urlProAbono $p$tokenProAbonofalse$fromScript);
  3759.                             if($data[1] == 200){
  3760.                                 if (array_key_exists('Links'$data[0])) {
  3761.                                     if ($data[0]['Links'][0]['rel'] == 'next') {
  3762.                                         $items array_merge($items$data[0]['Items']);
  3763.                                         $p $data[0]['Links'][0]['href'];
  3764.                                     } else if (count($data[0]['Links']) > && $data[0]['Links'][1]['rel'] == 'next') {
  3765.                                         $items array_merge($items$data[0]['Items']);
  3766.                                         $p $data[0]['Links'][1]['href'];
  3767.                                     } else {
  3768.                                         $items array_merge($items$data[0]['Items']);
  3769.                                         $nextPage false;
  3770.                                     }
  3771.                                 } else {
  3772.                                     $items array_merge($items$data[0]['Items']);
  3773.                                     $nextPage false;
  3774.                                 }
  3775.                             } else {
  3776.                                 throw new Exception();
  3777.                             }
  3778.                         }
  3779.                         $accountServices = [];
  3780.                         $nbLicences null;
  3781.                         for ($i 0$i count($items); $i++) {
  3782.                             if($items[$i]['TypeFeature'] == "OnOff"){
  3783.                                 if(!$items[$i]['IsEnabled']){
  3784.                                     continue;
  3785.                                 }
  3786.                             }
  3787.                             $idCategory explode('-'$items[$i]['ReferenceFeature'])[0];
  3788.                             $idServiceMarketing explode('-'$items[$i]['ReferenceFeature'])[1];
  3789.                             $serviceList AppServiceServices::getServicesToActivate($idCategory$idServiceMarketing);
  3790.                             foreach ($serviceList as $key => $serviceObj) {
  3791.                                 if($serviceObj->getId() == AppService::NB_USER){
  3792.                                     if(array_key_exists("QuantityIncluded",$items[$i])){
  3793.                                         $inc $items[$i]['QuantityIncluded'];
  3794.                                     }
  3795.                                     else{
  3796.                                         $inc INF;
  3797.                                     }
  3798.                                     if(array_key_exists("QuantityCurrent",$items[$i])){
  3799.                                         $c $items[$i]['QuantityCurrent'];
  3800.                                     }
  3801.                                     else{
  3802.                                         $c 0;
  3803.                                     }
  3804.                                     if(!is_infinite($inc)){
  3805.                                         if($c $inc){
  3806.                                             $nbLicences $c;
  3807.                                         }
  3808.                                         else{
  3809.                                             $nbLicences $inc;
  3810.                                         }
  3811.                                     }
  3812.                                     else{
  3813.                                         $nbLicences null;
  3814.                                     }
  3815.                                 }
  3816.                                 if ($serviceObj->getServiceType()->getId() == AppServiceType::OnOff) {
  3817.                                     $service $this->createServiceOnOff($serviceObj->getId());
  3818.                                 }
  3819.                                 elseif ($serviceObj->getServiceType()->getId() == AppServiceType::Consommation) {
  3820.                                     if ($serviceObj->getId() == AppService::LIMITATION_RECHERCHE_LINKEDIN) {
  3821.                                         $service $this->createServiceConsumption($serviceObj->getId(), $items[$i], $idAccount$nbLicences$appAccount->getAccountLinkedinSearchQuotaPerUser());
  3822.                                     } else {
  3823.                                         $service $this->createServiceConsumption($serviceObj->getId(), $items[$i]);
  3824.                                     }
  3825.                                 }
  3826.                                 elseif ($serviceObj->getServiceType()->getId() == AppServiceType::Limitation) {
  3827.                                     $service $this->createServiceLimitation($serviceObj->getId(), $idAccount$items[$i],$fromScript);
  3828.                                 }
  3829.                                 if($items[$i]['TypeFeature'] == "Consumption" && $service->getServiceType()->getId() == AppServiceType::Consommation){
  3830.                                     $service->setIsBilled(true);
  3831.                                 }else{
  3832.                                     $service->setIsBilled(false);
  3833.                                 }
  3834.                                 $accountServices[$service->getId()] = $service;
  3835.                             }
  3836.                         }
  3837.                         $currentServices AppServiceServices::getAccountServices($idAccount);
  3838.                         $toDelete = [];
  3839.                         $toAdd = [];
  3840.                         foreach ($currentServices as $key => $oldService) {
  3841.                             if (!array_key_exists($key$accountServices)) {
  3842.                                 $toDelete[$key] = $oldService;
  3843.                             }
  3844.                         }
  3845.                         foreach ($accountServices as $key => $newService) {
  3846.                             if (!array_key_exists($key$currentServices)) {
  3847.                                 $toAdd[$key] = $newService;
  3848.                                 unset($accountServices[$key]);
  3849.                             }
  3850.                         }
  3851.                         if (!empty($toDelete)) {
  3852.                             if (!AppAccountServices::deleteServices($toDelete$appAccount)) {
  3853.                                 throw new Exception("Erreur lors de la suppression des services");
  3854.                             }
  3855.                         }
  3856.                         if (!empty($toAdd)) {
  3857.                             foreach ($toAdd as $key => $ServiceAdded) {
  3858.                                 if ($key == AppService::REDACTION_6_NEWSLETTER) {
  3859.                                     AppAccountServices::setAccountBalanceNewsletter($idAccount0.5);
  3860.                                 }
  3861.                                 if ($key == AppService::REDACTION_12_NEWSLETTER) {
  3862.                                     AppAccountServices::setAccountBalanceNewsletter($idAccount1);
  3863.                                 }
  3864.                                 if ($key == AppService::REDACTION_24_NEWSLETTER) {
  3865.                                     AppAccountServices::setAccountBalanceNewsletter($idAccount2);
  3866.                                 }
  3867.                                 if ($key == AppService::REDACTION_2_CONTENU) {
  3868.                                     AppAccountServices::setAccountBalanceNewsletter($idAccount0.16);
  3869.                                 }
  3870.                             }
  3871.                             if (!AppAccountServices::addServices($toAdd$appAccount)) {
  3872.                                 throw new Exception("Erreur lors de l'ajout des services");
  3873.                             }
  3874.                         }
  3875.                         if (!AppAccountServices::updateServices($accountServices$appAccount)) {
  3876.                             throw new Exception("Erreur lors de l'update des services");
  3877.                         }
  3878.                         $appAccount AppAccountServices::getAccountWithoutService($idAccount);
  3879.                         if ($appAccount->getType()->getId() != $idAccountType) {
  3880.                             $appAccountType = new AppAccountType($idAccountType);
  3881.                             $appAccount->setType($appAccountType);
  3882.                             if (!AppAccountServices::setAccountType($appAccount)) {
  3883.                                 throw new Exception("Erreur lors de l'update de l'idAccountType");
  3884.                             }
  3885.                         }
  3886.                         if (array_key_exists(AppService::CRM$accountServices) || array_key_exists(AppService::PERSONA_FINDER$accountServices)) {
  3887.                             CamPersonaServices::giveDefaultPersona($appAccount->getId(), false$appAccount->getType()->getId());
  3888.                         }
  3889.                     }
  3890.                     else{
  3891.                         throw new Exception("Il n'y a aucun abonnement à récupérer.");
  3892.                     }
  3893.                 } else {
  3894.                     return new JsonResponse(array(
  3895.                         'error' => "Ce client n'a aucun abonnement (en cours, résilié, ou propal).",
  3896.                         'dump' => $dataSouscription
  3897.                     ),400);
  3898.                 }
  3899.             }
  3900.             else{
  3901.                 throw new Exception("IdCustomer manquant");
  3902.             }
  3903.         }
  3904.         catch(Exception $e){
  3905.             return new JsonResponse(array(
  3906.                 'error' => $e->getMessage(),
  3907.                 'line' => $e->getLine()
  3908.             ),400);
  3909.         }
  3910.         AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
  3911.         return new JsonResponse(array(
  3912.             'message' => "Le refresh est OK",
  3913.             'servicesAjoutés' => $toAdd,
  3914.             'servicesSupprimés' => $toDelete,
  3915.             'servicesMisAJour' => $accountServices
  3916.         ),200);
  3917.     }
  3918.     /**
  3919.      * @Route("/Abonnement/Suivi/abonnementGetIdSubscription", name="abonnement_get_idsubscription")
  3920.      * @Route("/Administration/Suivi/abonnementGetIdSubscription", name="administration_get_idsubscription")
  3921.      * @param RequestStack $requestStack
  3922.      * * @param Request $request
  3923.      * @param SessionInterface $session
  3924.      * @return Response
  3925.      * @throws Exception
  3926.      */
  3927.     public function abonnementGetIdSubscription(RequestStack $requestStackRequest $requestSessionInterface $session) : Response
  3928.     {
  3929.         $error false;
  3930.         $idSubscription null;
  3931.         if (!( in_array(AppService::ACCES_SUIVI_CLIENT$session->get('user')['services']) && in_array($session->get('user')['idUserType'], AppUserType::UT_ADMIN)) && !$session->get('user')['supportMode']) {
  3932.             throw new AccessDeniedHttpException();
  3933.         }
  3934.         try {
  3935.             if (!is_null($request->get('idAccount'null))) {
  3936.                 $api = new CallApi();
  3937.                 $confProAbono BaseController::getConfig()['proabono-api'];
  3938.                 $tokenProAbono $confProAbono['token'];
  3939.                 $idBusiness $confProAbono['idBusiness'];
  3940.                 $urlProAbono $confProAbono['url'];
  3941.                 $urlBackOfficeProAbono $confProAbono['url-backOffice'];
  3942.                 $currentHoursStatus null;
  3943.                 $idAccount $request->query->get('idAccount'null);
  3944.                 $appAccount AppAccountServices::getAccount($idAccount);
  3945.                 $idCompany $appAccount->getIdCompany();
  3946.                 if ($idCompany == RegCompany::COEFFICY or $idCompany == RegCompany::BUSINESS_SHARE) {
  3947.                     $referenceCustomer RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber() . substr($idAccount041);
  3948.                 } else {
  3949.                     if (is_null($idCompany)) {
  3950.                         $referenceCustomer null;
  3951.                     } else {
  3952.                         $referenceCustomer RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber();
  3953.                     }
  3954.                 }
  3955.                 $foobar = new AbonnementController($requestStack,$session);  // correct
  3956.                 //$proAbonoUserState = $foobar->getOffres($api, $urlBackOfficeProAbono, $urlProAbono, $tokenProAbono, $referenceCustomer, $idBusiness);
  3957.                 $idSubscription $appAccount->getIdSubscription();
  3958.             }else{
  3959.                 return new JsonResponse(array(
  3960.                     'code' => 500,
  3961.                     'idSubscription' => null
  3962.                 ),500);
  3963.             }
  3964.         }
  3965.         catch(Exception $e){
  3966.             return new JsonResponse(array(
  3967.                 'error' => $e->getMessage(),
  3968.                 'line' => $e->getLine()
  3969.             ),400);
  3970.         }
  3971.         return new JsonResponse(array(
  3972.             'code' => 200,
  3973.             'idSubscription' => $idSubscription
  3974.         ),200);
  3975.     }
  3976.     /**
  3977.      * @Route("/Abonnement/Suivi/abonnementIncrementUsage", name="abonnement_increment_usage")
  3978.      * @Route("/Administration/Suivi/abonnementIncrementUsage", name="administration_increment_usage")
  3979.      * @param RequestStack $requestStack
  3980.      * @param Request $request
  3981.      * @param SessionInterface $session
  3982.      * @return Response
  3983.      * @throws Exception
  3984.      */
  3985.     public function abonnementIncrementUsage(RequestStack $requestStackRequest $requestSessionInterface $session) : Response
  3986.     {
  3987.         $error false;
  3988.         $idSubscription null;
  3989.         try {
  3990.             if ($this->_request->isMethod("POST")) {
  3991.                 $increment $_POST['increment'];
  3992.                 $idAccount $_POST['idAccount'];
  3993.                 $accountHoursType $_POST['accountHoursType'];
  3994.                 if(is_null($increment) || !$idAccount || !$accountHoursType){
  3995.                     return new JsonResponse(array(
  3996.                         'error' => 'true',
  3997.                         'code' => 500,
  3998.                         'reason' => 'input manquant'
  3999.                     ),500);
  4000.                 }
  4001.                 $appAccount AppAccountServices::getAccount($idAccount);
  4002.                 $idCompany $appAccount->getIdCompany();
  4003.                 if ($idCompany == RegCompany::COEFFICY or $idCompany == RegCompany::BUSINESS_SHARE) {
  4004.                     $referenceCustomer RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber() . substr($idAccount041);
  4005.                 } else {
  4006.                     if (is_null($idCompany)) {
  4007.                         $referenceCustomer null;
  4008.                     } else {
  4009.                         $referenceCustomer RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber();
  4010.                     }
  4011.                 }
  4012.                 $api = new CallApi();
  4013.                 $confProAbono BaseController::getConfig()['proabono-api'];
  4014.                 $tokenProAbono $confProAbono['token'];
  4015.                 $idBusiness $confProAbono['idBusiness'];
  4016.                 $urlProAbono $confProAbono['url'];
  4017.                 $urlBackOfficeProAbono $confProAbono['url-backOffice'];
  4018.                 $currentHoursStatus null;
  4019.                 $typeHours AppAccountHoursServices::getHoursTypeById($accountHoursType);
  4020.                 $params = array(
  4021.                     "ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
  4022.                     "ReferenceCustomer" => $referenceCustomer,
  4023.                     "Increment" => $increment,
  4024.                     "DateStamp" => date("c")
  4025.                 );
  4026.                 $data $api->callApi("POST"$urlProAbono "/v1/Usage"$tokenProAbonojson_encode($params));
  4027.                 if($data[1] !== 200){
  4028.                     return new JsonResponse(array(
  4029.                         'error' => 'true',
  4030.                         'code' => 500,
  4031.                         'reason' => $data
  4032.                     ),500);
  4033.                 }
  4034.             }else{
  4035.                 return new JsonResponse(array(
  4036.                     'error' => 'true',
  4037.                     'code' => 500
  4038.                 ),500);
  4039.             }
  4040.         }
  4041.         catch(Exception $e){
  4042.             return new JsonResponse(array(
  4043.                 'error' => $e->getMessage(),
  4044.                 'line' => $e->getLine()
  4045.             ),400);
  4046.         }
  4047.         return new JsonResponse(array(
  4048.             'code' => 200,
  4049.             'idSubscription' => $idSubscription
  4050.         ),200);
  4051.     }
  4052.     /**
  4053.      * @Route("/invoice/get", name="invoice_get")
  4054.      * @return JsonResponse
  4055.      * @throws Exception
  4056.      */
  4057.     public function invoiceGet()
  4058.     {
  4059.         if (=== strpos($this->_request->headers->get('Content-Type'), 'application/json')) {
  4060.             $data json_decode($this->_request->getContent(), true);
  4061.             $this->_request->request->replace(is_array($data) ? $data : array());
  4062.         }
  4063.         return new JsonResponse(array(
  4064.             'status' => 200,
  4065.             'headers' => $this->_request->headers->all(),
  4066.             'body'=> $this->_request->request->all(),
  4067.             'POST' => $_POST
  4068.         ));
  4069.     }
  4070.     /**
  4071.      * @Route("/trigger/refresh", name="trigger_refresh")
  4072.      * @return JsonResponse
  4073.      * @throws Exception
  4074.      */
  4075.     public function triggerRefresh()
  4076.     {
  4077.         try{
  4078.             $data json_decode($this->_request->getContent(), true);
  4079.             if(array_key_exists("TypeTrigger",$data)){
  4080.                 if($data['TypeTrigger'] == "SubscriptionRenewed" or $data['TypeTrigger'] == "SubscriptionTerminatedForUpgrade" or $data['TypeTrigger'] == "SubscriptionTerminated" or $data['TypeTrigger'] == "SubscriptionHistory"){
  4081.                     $idAccount AppAccountServices::getAccountBySiren($data['Customer']['ReferenceCustomer'])->getId();
  4082.                     AppAccountHoursServices::setAllBillableHoursBilled($idAccount,$data['Subscription']['Id']);
  4083.                 }
  4084.             }
  4085.             if(array_key_exists("fromScript",$data['Customer'])){
  4086.                 $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  4087.                     'idCustomer'  => $data['Customer']['Id'],
  4088.                     'fromTrigger' => TRUE,
  4089.                     'fromScript' => TRUE,
  4090.                     'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
  4091.                 ]);
  4092.             }
  4093.             else{
  4094.                 $response $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  4095.                     'idCustomer'  => $data['Customer']['Id'],
  4096.                     'fromTrigger' => TRUE,
  4097.                     'fromScript' => FALSE,
  4098.                     'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
  4099.                 ]);
  4100.             }
  4101.             return $response;
  4102.             /*
  4103.             if($this->_request->headers->has('x-proabono-key') && $this->_request->headers->has('x-proabono-signature')){
  4104.                 $confProAbono = BaseController::getConfig()['proabono-api'];
  4105.                 $keyBusiness = $confProAbono['webhookKey'];
  4106.                 $calculated_hash = base64_encode(hash('sha256',$this->_request->headers->get('x-proabono-key').$keyBusiness,true));
  4107.                 if($this->_request->headers->get('x-proabono-signature') == $calculated_hash){
  4108.                     $data = json_decode($this->_request->getContent(), true);
  4109.                     $response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  4110.                         'idCustomer'  => $data['Customer']['Id'],
  4111.                         'fromTrigger' => TRUE,
  4112.                         'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
  4113.                     ]);
  4114.                     return $response;
  4115.                 }
  4116.             }
  4117.             */
  4118.         }
  4119.         catch(Exception $e){
  4120.             return new JsonResponse(array(
  4121.                 'error' => $e->getMessage(),
  4122.                 'line' => $e->getLine()
  4123.             ),400);
  4124.         }
  4125.         return $this->redirectToRoute('Homepage');
  4126.     }
  4127.     public function createServiceOnOff($idService): AppService
  4128.     {
  4129.         $service = new AppService($idServicenull);
  4130.         $serviceType = new AppServiceType(AppServiceType::OnOff'OnOff');
  4131.         $service->setServiceType($serviceType);
  4132.         $accountServices[$service->getId()] = $service;
  4133.         $service->setSolde(1);
  4134.         return $service;
  4135.     }
  4136.     public function createServiceConsumption($idService$item$idAccount false$nbLicences false$quotaPerUser false): AppService
  4137.     {
  4138.         $service = new AppService($idServicenull);
  4139.         $serviceType = new AppServiceType(AppServiceType::Consommation'Consommation');
  4140.         $service->setServiceType($serviceType);
  4141.         if(array_key_exists("QuantityIncluded",$item)){
  4142.             $included $item['QuantityIncluded'];
  4143.             if($idService == AppService::LIMITATION_RECHERCHE_LINKEDIN){
  4144.                 if(is_null($nbLicences)){
  4145.                     $nbLicences AppUserServices::getAccountUsersWithLicence($idAccount)['nb'];
  4146.                 }
  4147.                 $service->setNbLimit(floor($nbLicences $quotaPerUser));
  4148.             }
  4149.             else{
  4150.                 $service->setNbLimit($included);
  4151.             }
  4152.         }
  4153.         else{
  4154.             if($idService == AppService::LIMITATION_RECHERCHE_LINKEDIN){
  4155.                 if(is_null($nbLicences)){
  4156.                     $nbLicences AppUserServices::getAccountUsersWithLicence($idAccount)['nb'];
  4157.                 }
  4158.                 $service->setNbLimit(floor($nbLicences $quotaPerUser));
  4159.             }
  4160.             else{
  4161.                 $service->setNbLimit(0);
  4162.             }
  4163.         }
  4164.         if(array_key_exists("QuantityCurrent",$item)){
  4165.             $current $item['QuantityCurrent'];
  4166.             $service->setSolde($current);
  4167.         }
  4168.         else{
  4169.             $service->setSolde(0);
  4170.         }
  4171.         return $service;
  4172.     }
  4173.     public function createServiceLimitation($idService$idAccount$item$fromScript): AppService
  4174.     {
  4175.         $api = new CallApi();
  4176.         $confProAbono BaseController::getConfig()['proabono-api'];
  4177.         $urlProAbono $confProAbono['url'];
  4178.         $tokenProAbono $confProAbono['token'];
  4179.         $service = new AppService($idServicenull);
  4180.         $serviceType = new AppServiceType(AppServiceType::Limitation'Limitation');
  4181.         $service->setServiceType($serviceType);
  4182.         $arrServiceLimited intval(AppServiceServices::getNumberLimited($idAccount$idService)['nb']);
  4183.         $outOfBundle false;
  4184.         if(array_key_exists("QuantityIncluded",$item)){
  4185.             $included $item['QuantityIncluded'];
  4186.             $service->setNbLimit($included);
  4187.         }
  4188.         else{
  4189.             $service->setNbLimit(null);
  4190.             $included INF;
  4191.         }
  4192.         if(array_key_exists("QuantityCurrent",$item)){
  4193.             $current $item['QuantityCurrent'];
  4194.         }
  4195.         else{
  4196.             $current 0;
  4197.         }
  4198.         if(!is_infinite($included)){
  4199.             if($current $included){
  4200.                 $outOfBundle true;
  4201.                 $solde $current $arrServiceLimited;
  4202.             }
  4203.             else{
  4204.                 $solde $included $arrServiceLimited;
  4205.             }
  4206.             if ($solde 0) {
  4207.                 $num abs($solde);
  4208.                 $solde 0;
  4209.                 if ($idService == AppService::NB_USER && $idService >= 1) {
  4210.                     $users AppUserServices::getAccountUsersToDesactive($idAccount$num);
  4211.                     for ($a 0$a count($users); $a++) {
  4212.                         AppUserServices::setActiveTokenLicence($users[$a]->getId(), false);
  4213.                     }
  4214.                 } else if ($idService == AppService::ROUTINE) {
  4215.                     $routines RoutineServices::getRoutineToDraft($idAccount$num);
  4216.                     for ($a 0$a count($routines); $a++) {
  4217.                         RoutineServices::setRoutineToDraftById($routines[$a]['idSupply']);
  4218.                     }
  4219.                 }
  4220.             }
  4221.         }
  4222.         else{
  4223.             $solde null;
  4224.         }
  4225.         $service->setSolde($solde);
  4226.         if((!$outOfBundle && $idService == AppService::NB_USER) or (!$outOfBundle && $idService == AppService::ROUTINE)){
  4227.             $arrServiceLimited intval(AppServiceServices::getNumberLimited($idAccount$idService)['nb']);
  4228.             $params json_encode(
  4229.                 array(
  4230.                     "ReferenceFeature" => $item['ReferenceFeature'],
  4231.                     "IdSubscription" => $item['IdSubscription'],
  4232.                     "QuantityCurrent" => $arrServiceLimited,
  4233.                     "DateStamp" => date('Y-m-d\TH:i:s')
  4234.                 )
  4235.             );
  4236.             $data $api->callApi("POST"$urlProAbono "/v1/Usage"$tokenProAbono$params$fromScript);
  4237.         }
  4238.         return $service;
  4239.     }
  4240.     public function getOffres($api$urlBackOfficeProAbono$urlProAbono$tokenProAbono$referenceCustomer$idBusiness){
  4241.         try{
  4242.             $current null;
  4243.             $propal = [];
  4244.             $delayed = [];
  4245.             $outOfBundleCurrent = [];
  4246.             $limitations = [];
  4247.             $onOff = [];
  4248.             $consos = [];
  4249.             $next true;
  4250.             $idActiveSubscription null;
  4251.             $idCustomer null;
  4252.             if(is_null($referenceCustomer)){
  4253.                 $this->_isOlder true;
  4254.                 $this->_isFreemium false;
  4255.             }
  4256.             else{
  4257.                 $data $api->callApi('GET'$urlBackOfficeProAbono.'/Sub/Subscriptions?ReferenceCustomer='.$referenceCustomer"&IdBusiness=" $idBusiness$tokenProAbonofalse);
  4258.                 if($data[1] == 200){
  4259.                     if(empty($data[0]['Items'])){
  4260.                         $data $api->callApi('GET'$urlProAbono.'/v1/Customer?ReferenceCustomer='.$referenceCustomer"&IdBusiness=" $idBusiness$tokenProAbonofalse);
  4261.                         if($data[1] == 200){
  4262.                             $this->_isOlder true;
  4263.                             $this->_isFreemium false;
  4264.                             $idCustomer $data[0]['Id'];
  4265.                         }
  4266.                         else{
  4267.                             if($data[1] !== 403){
  4268.                                 throw new Exception();
  4269.                             }
  4270.                         }
  4271.                     }
  4272.                     else{
  4273.                         $terminated = [];
  4274.                         $firstRunningSubscriptionMet false;
  4275.                         while($next) {
  4276.                             for ($v 0$v count($data[0]['Items']); $v++) {
  4277.                                 $idCustomer $data[0]['Items'][$v]['IdCustomer'];
  4278.                                 if ($data[0]['Items'][$v]['Status'] == 'Active'  and !$firstRunningSubscriptionMet) {
  4279.                                     if($data[0]['Items'][$v]['Name'] == "SOUSCRIT, EN COURS"){
  4280.                                         $countSubscriptions $this->_api->callApi("GET"$this->_urlBackOfficeProAbono "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$data[0]['Items'][$v]['IdCustomer'], $this->_tokenProAbonofalse);
  4281.                                         if($countSubscriptions[1] == 200){
  4282.                                             $this->renameSubscription($data[0]['Items'][$v]['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
  4283.                                         }
  4284.                                     }
  4285.                                     $firstRunningSubscriptionMet true;
  4286.                                     $idActiveSubscription $data[0]['Items'][$v]['Id'];
  4287.                                     $activeSubscriptionWithAdditionalInfos $api->callApi('GET'$urlProAbono '/v1/Subscription?IdSubscription=' $idActiveSubscription.'&html=false'$tokenProAbonofalse);
  4288.                                     $this->_isEngaged false;
  4289.                                     if(array_key_exists("IsEngaged",$activeSubscriptionWithAdditionalInfos[0])){
  4290.                                         if($activeSubscriptionWithAdditionalInfos[0]['IsEngaged']){
  4291.                                             $this->_isEngaged true;
  4292.                                         }
  4293.                                     }
  4294.                                    /* $this->_isTrial = false;
  4295.                                     if(array_key_exists("IsTrial",$activeSubscriptionWithAdditionalInfos[0])){
  4296.                                         if($activeSubscriptionWithAdditionalInfos[0]['IsTrial'] and !in_array($activeSubscriptionWithAdditionalInfos[0]['ReferenceOffer'],AppAccountType::UT_MIGRATED_WITH_TRIAL)){
  4297.                                             $this->_isTrial = true;
  4298.                                         }
  4299.                                     }*/
  4300.                                     $dataActif $api->callApi('GET'$urlProAbono.'/v1/Offer?html=false&idOffer='.$data[0]['Items'][$v]['IdOffer'].'&language=fr'$tokenProAbonofalse);
  4301.                                     if($activeSubscriptionWithAdditionalInfos[0]['ReferenceOffer'] == AppAccountType::DESACTIVE){
  4302.                                         if(!$this->_isAdmin){
  4303.                                             $this->_session->remove("user");
  4304.                                             SessionUtilisateur::checkUtilisateur($this->_session);
  4305.                                         }
  4306.                                         else{
  4307.                                             $this->_isDisabled true;
  4308.                                             $current["offer"] = $dataActif[0];
  4309.                                             $current["subscription"] = $activeSubscriptionWithAdditionalInfos[0];
  4310.                                         }
  4311.                                     }
  4312.                                     $featuresActiveSubscription $api->callApi('GET'$urlBackOfficeProAbono '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' $data[0]['Items'][$v]['Id'], $tokenProAbonofalse);
  4313.                                     if($dataActif[1] == 200 && $activeSubscriptionWithAdditionalInfos[1] == 200 && $featuresActiveSubscription[1] == 200){
  4314.                                         if(array_key_exists("ReferenceOffer",$dataActif[0])){
  4315.                                             if($dataActif[0]['ReferenceOffer'] === AppAccountType::REFERRAL){
  4316.                                                 $this->_isFreemium true;
  4317.                                             }
  4318.                                         }
  4319.                                         $loop true;
  4320.                                         $features = [];
  4321.                                         while($loop) {
  4322.                                             for ($x 0$x count($featuresActiveSubscription[0]['Items']); $x++) {
  4323.                                                 $array[$x] = $featuresActiveSubscription[0]['Items'][$x];
  4324.                                                 foreach ($activeSubscriptionWithAdditionalInfos[0]['Features'] as $f) {
  4325.                                                     if($f['ReferenceFeature'] == $featuresActiveSubscription[0]['Items'][$x]['ReferenceFeature']){
  4326.                                                         if(array_key_exists('TitleLocalized',$f)){
  4327.                                                             $array[$x]['TitleLocalized'] = $f['TitleLocalized'];
  4328.                                                         }
  4329.                                                         if(array_key_exists('PricingLocalized',$f)){
  4330.                                                             $array[$x]['PricingLocalized'] = $f['PricingLocalized'];
  4331.                                                         }
  4332.                                                         if(array_key_exists('TypeFeature',$f)){
  4333.                                                             $array[$x]['TypeFeature'] = $f['TypeFeature'];
  4334.                                                         }
  4335.                                                     }
  4336.                                                 }
  4337.                                                 $features[] = $array[$x];
  4338.                                             }
  4339.                                             if (array_key_exists('Links'$featuresActiveSubscription[0])) {
  4340.                                                 if ($featuresActiveSubscription[0]['Links'][0]['rel'] == 'next') {
  4341.                                                     $featuresActiveSubscription $api->callApi('GET'$urlBackOfficeProAbono $featuresActiveSubscription[0]['Links'][0]['href'], $tokenProAbonofalse);
  4342.                                                 } else if (count($featuresActiveSubscription[0]['Links']) > && $featuresActiveSubscription[0]['Links'][1]['rel'] == 'next') {
  4343.                                                     $featuresActiveSubscription $api->callApi('GET'$urlBackOfficeProAbono $featuresActiveSubscription[0]['Links'][1]['href'], $tokenProAbonofalse);
  4344.                                                 } else {
  4345.                                                     $loop false;
  4346.                                                 }
  4347.                                             } else {
  4348.                                                 $loop false;
  4349.                                             }
  4350.                                         }
  4351.                                         usort($features,function($a,$b){
  4352.                                             return $a['Id'] - $b['Id'];
  4353.                                         });
  4354.                                         $activeSubscriptionWithAdditionalInfos[0]['Features'] = $features;
  4355.                                         $current["offer"] = $dataActif[0];
  4356.                                         $current["subscription"] = $activeSubscriptionWithAdditionalInfos[0];
  4357.                                     }
  4358.                                 }
  4359.                                 else {
  4360.                                     if (($data[0]['Items'][$v]['StateSubscription'] == 'InitiatedAgent' or $data[0]['Items'][$v]['StateSubscription'] == 'DraftAgent')  && array_key_exists('DateStart'$data[0]['Items'][$v]) &&
  4361.                                         $data[0]['Items'][$v]['DateStart'] > date("Y-m-d H:i:s") && (!array_key_exists("Metadata",$data[0]['Items'][$v]) or array_key_exists("GuaranteeWording",$data[0]['Items'][$v]['Metadata'])) ) {
  4362.                                         if($data[0]['Items'][$v]['Name'] != "Proposition commerciale"){
  4363.                                             $this->renameSubscription($data[0]['Items'][$v]['Id'],"Proposition commerciale");
  4364.                                         }
  4365.                                         $activePropalWithAdditionalInfos $api->callApi('GET'$urlProAbono '/v1/Subscription?IdSubscription=' $data[0]['Items'][$v]['Id'].'&html=false'$tokenProAbonofalse);
  4366.                                         $propalOffer $api->callApi('GET'$urlProAbono '/v1/Offer?html=false&idOffer=' $data[0]['Items'][$v]['IdOffer'] . '&language=fr'$tokenProAbonofalse);
  4367.                                         $featuresActivePropal $api->callApi('GET'$urlBackOfficeProAbono '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' $data[0]['Items'][$v]['Id'], $tokenProAbonofalse);
  4368.                                         if ($propalOffer[1] == 200 && $activePropalWithAdditionalInfos[1] == 200 and $featuresActivePropal[1] == 200) {
  4369.                                             $loop true;
  4370.                                             $features = [];
  4371.                                             while($loop) {
  4372.                                                 for ($x 0$x count($featuresActivePropal[0]['Items']); $x++) {
  4373.                                                     $array[$x] = $featuresActivePropal[0]['Items'][$x];
  4374.                                                     foreach ($activePropalWithAdditionalInfos[0]['Features'] as $f) {
  4375.                                                         if($f['ReferenceFeature'] == $featuresActivePropal[0]['Items'][$x]['ReferenceFeature']){
  4376.                                                             if(array_key_exists('TitleLocalized',$f)){
  4377.                                                                 $array[$x]['TitleLocalized'] = $f['TitleLocalized'];
  4378.                                                             }
  4379.                                                             if(array_key_exists('PricingLocalized',$f)){
  4380.                                                                 $array[$x]['PricingLocalized'] = $f['PricingLocalized'];
  4381.                                                             }
  4382.                                                             if(array_key_exists('TypeFeature',$f)){
  4383.                                                                 $array[$x]['TypeFeature'] = $f['TypeFeature'];
  4384.                                                             }
  4385.                                                         }
  4386.                                                     }
  4387.                                                     $features[] = $array[$x];
  4388.                                                 }
  4389.                                                 if (array_key_exists('Links'$featuresActivePropal[0])) {
  4390.                                                     if ($featuresActivePropal[0]['Links'][0]['rel'] == 'next') {
  4391.                                                         $featuresActivePropal $api->callApi('GET'$urlBackOfficeProAbono $featuresActivePropal[0]['Links'][0]['href'], $tokenProAbonofalse);
  4392.                                                     } else if (count($featuresActivePropal[0]['Links']) > && $featuresActivePropal[0]['Links'][1]['rel'] == 'next') {
  4393.                                                         $featuresActivePropal $api->callApi('GET'$urlBackOfficeProAbono $featuresActivePropal[0]['Links'][1]['href'], $tokenProAbonofalse);
  4394.                                                     } else {
  4395.                                                         $loop false;
  4396.                                                     }
  4397.                                                 } else {
  4398.                                                     $loop false;
  4399.                                                 }
  4400.                                             }
  4401.                                             usort($features,function($a,$b){
  4402.                                                 return $a['Id'] - $b['Id'];
  4403.                                             });
  4404.                                             $activePropalWithAdditionalInfos[0]['Features'] = $features;
  4405.                                             $propal[$data[0]['Items'][$v]['Id']] = array("offer" => $propalOffer[0],
  4406.                                                 "propal" => $activePropalWithAdditionalInfos[0]
  4407.                                             );
  4408.                                             $outOfBundlePropal = [];
  4409.                                             foreach ($propal[$data[0]['Items'][$v]['Id']]["propal"]['Features'] as &$feature) {
  4410.                                                 if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption'){
  4411.                                                     if(array_key_exists('QuantityCurrent'$feature)){
  4412.                                                         $quantityCurrent $feature['QuantityCurrent'];
  4413.                                                     }
  4414.                                                     else{
  4415.                                                         $quantityCurrent 0;
  4416.                                                         $feature['QuantityCurrent'] = $quantityCurrent;
  4417.                                                     }
  4418.                                                     if(array_key_exists('QuantityIncluded'$feature)){
  4419.                                                         $quantityIncluded $feature['QuantityIncluded'];
  4420.                                                     }
  4421.                                                     else{
  4422.                                                         $quantityIncluded null;
  4423.                                                         $feature['QuantityIncluded'] = $quantityIncluded;
  4424.                                                     }
  4425.                                                 }
  4426.                                                 $price 0;
  4427.                                                 if (array_key_exists('PricingLocalized'$feature)) {
  4428.                                                     $price = (string)preg_replace('/[^0-9\.]/'""$feature['PricingLocalized']);
  4429.                                                     if(substr($price,strlen($price)-1) == "."){
  4430.                                                         $price substr_replace($price,"",-1);
  4431.                                                     }
  4432.                                                 }
  4433.                                                 $feature['price'] = $price;
  4434.                                                 if ($feature['TypeFeature'] == 'Limitation') {
  4435.                                                     if(!is_null($quantityIncluded)){
  4436.                                                         if ($quantityCurrent $quantityIncluded) {
  4437.                                                             $outOfBundlePropal[] = $feature;
  4438.                                                         }
  4439.                                                     }
  4440.                                                 }
  4441.                                                 if ($feature['TypeFeature'] == 'OnOff') {
  4442.                                                     if($feature['IsIncluded'] == false && $feature['IsEnabled'] == true)
  4443.                                                     {
  4444.                                                         $outOfBundlePropal[] = $feature;
  4445.                                                     }
  4446.                                                 }
  4447.                                                 if ($feature['TypeFeature'] == 'Consumption') {
  4448.                                                     if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
  4449.                                                     {
  4450.                                                         $outOfBundlePropal[] = $feature;
  4451.                                                     }
  4452.                                                 }
  4453.                                             }
  4454.                                             if(count($outOfBundlePropal) > 0){
  4455.                                                 $propal[$data[0]['Items'][$v]['Id']]['outOfBundle'] = $outOfBundlePropal;
  4456.                                             }
  4457.                                         }
  4458.                                     }
  4459.                                     else if ( ($data[0]['Items'][$v]['StateSubscription'] == 'InitiatedAgent' or $data[0]['Items'][$v]['StateSubscription'] == 'DraftAgent') && array_key_exists("Metadata",$data[0]['Items'][$v])) {
  4460.                                         if(array_key_exists("newSubscription",$data[0]['Items'][$v]['Metadata'])
  4461.                                             and array_key_exists("delayed",$data[0]['Items'][$v]['Metadata'])
  4462.                                             and $data[0]['Items'][$v]['Metadata']['delayed'] == true){
  4463.                                             $delayedPropalWithAdditionalsInfos $api->callApi('GET'$urlProAbono '/v1/Subscription?IdSubscription=' $data[0]['Items'][$v]['Id'].'&html=false'$tokenProAbonofalse);
  4464.                                             $propalOffer $api->callApi('GET'$urlProAbono '/v1/Offer?html=false&idOffer=' $data[0]['Items'][$v]['IdOffer'] . '&language=fr'$tokenProAbonofalse);
  4465.                                             $featuresDelayedPropal $api->callApi('GET'$urlBackOfficeProAbono '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' $data[0]['Items'][$v]['Id'], $tokenProAbonofalse);
  4466.                                             if ($propalOffer[1] == 200 && $delayedPropalWithAdditionalsInfos[1] == 200 && $featuresDelayedPropal[1] == 200) {
  4467.                                                 $loop true;
  4468.                                                 $features = [];
  4469.                                                 while($loop) {
  4470.                                                     for ($x 0$x count($featuresDelayedPropal[0]['Items']); $x++) {
  4471.                                                         $array[$x] = $featuresDelayedPropal[0]['Items'][$x];
  4472.                                                         foreach ($delayedPropalWithAdditionalsInfos[0]['Features'] as $f) {
  4473.                                                             if($f['ReferenceFeature'] == $featuresDelayedPropal[0]['Items'][$x]['ReferenceFeature']){
  4474.                                                                 if(array_key_exists('TitleLocalized',$f)){
  4475.                                                                     $array[$x]['TitleLocalized'] = $f['TitleLocalized'];
  4476.                                                                 }
  4477.                                                                 if(array_key_exists('PricingLocalized',$f)){
  4478.                                                                     $array[$x]['PricingLocalized'] = $f['PricingLocalized'];
  4479.                                                                 }
  4480.                                                                 if(array_key_exists('TypeFeature',$f)){
  4481.                                                                     $array[$x]['TypeFeature'] = $f['TypeFeature'];
  4482.                                                                 }
  4483.                                                             }
  4484.                                                         }
  4485.                                                         $features[] = $array[$x];
  4486.                                                     }
  4487.                                                     if (array_key_exists('Links'$featuresDelayedPropal[0])) {
  4488.                                                         if ($featuresDelayedPropal[0]['Links'][0]['rel'] == 'next') {
  4489.                                                             $featuresDelayedPropal $api->callApi('GET'$urlBackOfficeProAbono $featuresDelayedPropal[0]['Links'][0]['href'], $tokenProAbonofalse);
  4490.                                                         } else if (count($featuresDelayedPropal[0]['Links']) > && $featuresDelayedPropal[0]['Links'][1]['rel'] == 'next') {
  4491.                                                             $featuresDelayedPropal $api->callApi('GET'$urlBackOfficeProAbono $featuresDelayedPropal[0]['Links'][1]['href'], $tokenProAbonofalse);
  4492.                                                         } else {
  4493.                                                             $loop false;
  4494.                                                         }
  4495.                                                     } else {
  4496.                                                         $loop false;
  4497.                                                     }
  4498.                                                 }
  4499.                                                 usort($features,function($a,$b){
  4500.                                                     return $a['Id'] - $b['Id'];
  4501.                                                 });
  4502.                                                 $delayedPropalWithAdditionalsInfos[0]['Features'] = $features;
  4503.                                                 $delayed['offer'] = $propalOffer[0];
  4504.                                                 $delayed['propal'] = $delayedPropalWithAdditionalsInfos[0];
  4505.                                                 $outOfBundleDelayedPropal = [];
  4506.                                                 foreach ($delayed['propal']['Features'] as &$feature) {
  4507.                                                     if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption') {
  4508.                                                         if (array_key_exists('QuantityCurrent'$feature)) {
  4509.                                                             $quantityCurrent $feature['QuantityCurrent'];
  4510.                                                         } else {
  4511.                                                             $quantityCurrent 0;
  4512.                                                             $feature['QuantityCurrent'] = $quantityCurrent;
  4513.                                                         }
  4514.                                                         if (array_key_exists('QuantityIncluded'$feature)) {
  4515.                                                             $quantityIncluded $feature['QuantityIncluded'];
  4516.                                                         } else {
  4517.                                                             $quantityIncluded null;
  4518.                                                             $feature['QuantityIncluded'] = $quantityIncluded;
  4519.                                                         }
  4520.                                                     }
  4521.                                                     $price 0;
  4522.                                                     if (array_key_exists('PricingLocalized'$feature)) {
  4523.                                                         $price = (string)preg_replace('/[^0-9\.]/'""$feature['PricingLocalized']);
  4524.                                                         if(substr($price,strlen($price)-1) == "."){
  4525.                                                             $price substr_replace($price,"",-1);
  4526.                                                         }
  4527.                                                     }
  4528.                                                     $feature['price'] = $price;
  4529.                                                     if ($feature['TypeFeature'] == 'Limitation') {
  4530.                                                         if(!is_null($quantityIncluded)){
  4531.                                                             if ($quantityCurrent $quantityIncluded) {
  4532.                                                                 $outOfBundleDelayedPropal[] = $feature;
  4533.                                                             }
  4534.                                                         }
  4535.                                                     }
  4536.                                                     if ($feature['TypeFeature'] == 'Consumption') {
  4537.                                                         if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
  4538.                                                         {
  4539.                                                             $outOfBundleDelayedPropal[] = $feature;
  4540.                                                         }
  4541.                                                     }
  4542.                                                 }
  4543.                                                 if(count($outOfBundleDelayedPropal) > 0){
  4544.                                                     $delayed['outOfBundle'] = $outOfBundleDelayedPropal;
  4545.                                                 }
  4546.                                             }
  4547.                                         }
  4548.                                     }
  4549.                                     if($data[0]['Items'][$v]['Status'] == 'Ended'){
  4550.                                         if(empty($terminated)){
  4551.                                             if(is_null($idActiveSubscription)){
  4552.                                                 $idActiveSubscription $data[0]['Items'][$v]['Id'];
  4553.                                             }
  4554.                                             $terminated[] = $data[0]['Items'][$v];
  4555.                                         }
  4556.                                     }
  4557.                                 }
  4558.                             }
  4559.                             if (array_key_exists('Links'$data[0])) {
  4560.                                 if ($data[0]['Links'][0]['rel'] == 'next') {
  4561.                                     $data $api->callApi('GET'$urlBackOfficeProAbono $data[0]['Links'][0]['href'], $tokenProAbonofalse);
  4562.                                 } else if (count($data[0]['Links']) > && $data[0]['Links'][1]['rel'] == 'next') {
  4563.                                     $data $api->callApi('GET'$urlBackOfficeProAbono $data[0]['Links'][1]['href'], $tokenProAbonofalse);
  4564.                                 } else {
  4565.                                     $next false;
  4566.                                 }
  4567.                             } else {
  4568.                                 $next false;
  4569.                             }
  4570.                         }
  4571.                         if(is_null($current) and !empty($terminated)){
  4572.                             $dataActif $api->callApi('GET'$urlProAbono.'/v1/Offer?html=false&idOffer='.$terminated[0]['IdOffer'].'&language=fr'$tokenProAbonofalse);
  4573.                             if($dataActif[1] == 200){
  4574.                                 $this->_isTerminated true;
  4575.                                 $current["offer"] = $dataActif[0];
  4576.                                 $current["subscription"] = $terminated[0];
  4577.                             }
  4578.                             else{
  4579.                                 throw new Exception();
  4580.                             }
  4581.                         }
  4582.                         if(is_null($current) and empty($terminated) and !empty($propal)){
  4583.                             $this->_isOlder true;
  4584.                             $this->_isFreemium false;
  4585.                             $idCustomer reset($propal)['propal']['IdCustomer'];
  4586.                         }
  4587.                         if(!$this->_isTerminated and !$this->_isDisabled and !$this->_isOlder and !is_null($current)) {
  4588.                             foreach ($current['subscription']['Features'] as &$feature) {
  4589.                                 if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption') {
  4590.                                     if (array_key_exists('QuantityCurrent'$feature)) {
  4591.                                         $quantityCurrent $feature['QuantityCurrent'];
  4592.                                     } else {
  4593.                                         $quantityCurrent 0;
  4594.                                         $feature['QuantityCurrent'] = $quantityCurrent;
  4595.                                     }
  4596.                                     if (array_key_exists('QuantityIncluded'$feature)) {
  4597.                                         $quantityIncluded $feature['QuantityIncluded'];
  4598.                                     } else {
  4599.                                         $quantityIncluded null;
  4600.                                         $feature['QuantityIncluded'] = $quantityIncluded;
  4601.                                     }
  4602.                                 }
  4603.                                 $price 0;
  4604.                                 if (array_key_exists('PricingLocalized'$feature)) {
  4605.                                     $price = (string)preg_replace('/[^0-9\.]/'""$feature['PricingLocalized']);
  4606.                                     if(substr($price,strlen($price)-1) == "."){
  4607.                                         $price substr_replace($price,"",-1);
  4608.                                     }
  4609.                                 }
  4610.                                 $feature['ReferenceCustomer'] = $current['subscription']['ReferenceCustomer'];
  4611.                                 $feature['price'] = $price;
  4612.                                 if ($feature['TypeFeature'] == 'Limitation') {
  4613.                                     if (!is_null($quantityIncluded)) {
  4614.                                         if($quantityCurrent $quantityIncluded){
  4615.                                             $outOfBundleCurrent[] = $feature;
  4616.                                         }
  4617.                                     }
  4618.                                     $limitations[] = $feature;
  4619.                                 }
  4620.                                 else if($feature['TypeFeature'] == 'OnOff'){
  4621.                                     $onOff[] = $feature;
  4622.                                 }
  4623.                                 else if ($feature['TypeFeature'] == 'Consumption') {
  4624.                                     if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
  4625.                                     {
  4626.                                         $outOfBundleCurrent[] = $feature;
  4627.                                     }
  4628.                                     $consos[] = $feature;
  4629.                                 }
  4630.                             }
  4631.                         }
  4632.                     }
  4633.                 }
  4634.                 else{
  4635.                     if($data[1] == 204){
  4636.                         $data $api->callApi('GET'$urlProAbono.'/v1/Customer?ReferenceCustomer='.$referenceCustomer$tokenProAbonofalse);
  4637.                         if($data[1] == 200){
  4638.                             $this->_isOlder true;
  4639.                             $this->_isFreemium false;
  4640.                             $idCustomer $data[0]['Id'];
  4641.                         }
  4642.                     }
  4643.                     else{
  4644.                         throw new Exception();
  4645.                     }
  4646.                 }
  4647.             }
  4648.             $retour = [];
  4649.             $retour["IdCustomer"] = $idCustomer;
  4650.             $retour["current"] = $current;
  4651.             $retour["propal"] = $propal;
  4652.             $retour["delayed"] = $delayed;
  4653.             $retour["current"]["limitations"] = $limitations;
  4654.             $retour["current"]["onoff"] = $onOff;
  4655.             $retour["current"]["consos"] = $consos;
  4656.             $retour["current"]["outOfBundle"] = $outOfBundleCurrent;
  4657.             $retour["current"]["IdActiveSubscription"] = $idActiveSubscription;
  4658.         }
  4659.         catch(Exception $e){
  4660.             $retour false;
  4661.         }
  4662.         return $retour;
  4663.     }
  4664.     /**
  4665.      * @Route("/Abonnement/Adjust", name="Abonnement_adjust")
  4666.      * @Route("/Abonnement/Adjust", name="abonnement_adjust")
  4667.      */
  4668.     public function adjust(){
  4669.         try{
  4670.             $fromAdmin false;
  4671.             if ($this->_request->isMethod("POST")) {
  4672.                 if(!empty($_POST)){
  4673.                     $currentFeature $_POST['currentFeatures'];
  4674.                     $features $_POST['Feature'];
  4675.                     if(isset($_POST['fromAdmin']) and !empty($_POST['fromAdmin'])){
  4676.                         $fromAdmin $_POST['fromAdmin'];
  4677.                     }
  4678.                     $params = array();
  4679.                     foreach ($features as $key => $feature){
  4680.                         if(array_key_exists("IsEnabled",$features[$key])){
  4681.                             if($features[$key]['IsEnabled'] !== $currentFeature[$key]['IsEnabled']){
  4682.                                 $params[] = $features[$key];
  4683.                             }
  4684.                         }
  4685.                         else if(array_key_exists("QuantityCurrent",$features[$key])){
  4686.                             if($features[$key]['QuantityCurrent'] !== $currentFeature[$key]['QuantityCurrent']){
  4687.                                 $params[] = $features[$key];
  4688.                             }
  4689.                         }
  4690.                     }
  4691.                     if(count($params) > 0){
  4692.                         $dataActif $this->_api->callApi('POST'$this->_urlProAbono '/v1/Usages'$this->_tokenProAbonojson_encode($params), falsefalse);
  4693.                         if($dataActif[1] !== 200){
  4694.                             throw new Exception("Une erreur a été rencontrée lors de la mise à jour des caractéristiques de votre abonnement.");
  4695.                         }
  4696.                         else{
  4697.                             $params = array(
  4698.                                 "ReferenceCustomer" => $this->_referenceCustomer
  4699.                             );
  4700.                             $bill $this->_api->callApi('POST'$this->_urlProAbono '/v1/Billing/Customer'$this->_tokenProAbonojson_encode($params), falsefalse);
  4701.                             $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  4702.                                 'idCustomer'  => $this->_idCustomer,
  4703.                                 'fromTrigger' => false,
  4704.                                 'fromScript' => false
  4705.                             ]);
  4706.                         }
  4707.                     }
  4708.                     else{
  4709.                         if($fromAdmin){
  4710.                             return $this->redirectToRoute('abonnement', ['idAccount' => $fromAdmin]);
  4711.                         }
  4712.                         else{
  4713.                             return $this->redirectToRoute('abonnement', []);
  4714.                         }
  4715.                     }
  4716.                 }
  4717.                 else{
  4718.                     throw new Exception("Aucune données n'a été envoyée.");
  4719.                 }
  4720.             }
  4721.             else{
  4722.                 throw new Exception("Aucune données n'a été envoyée.");
  4723.             }
  4724.         }
  4725.         catch(Exception $e){
  4726.             if($e->getCode() == 01){
  4727.                 $this->setAttribute('error'$e->getMessage());
  4728.             }
  4729.             else{
  4730.                 $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  4731.             }
  4732.         }
  4733.         if($fromAdmin){
  4734.             return $this->redirectToRoute('abonnement', ['idAccount' => $fromAdmin]);
  4735.         }
  4736.         else{
  4737.             return $this->redirectToRoute('abonnement', []);
  4738.         }
  4739.     }
  4740.     /**
  4741.      * @Route("/Abonnement/NewCgv", name="Abonnement_newCgv")
  4742.      * @Route("/Abonnement/NewCgv", name="abonnement_newCgv")
  4743.      */
  4744.     public function setNewCgvAfterSubscription(){
  4745.         try{
  4746.             if ($this->_request->isMethod("POST")) {
  4747.                 if(!empty($_POST)){
  4748.                     if(isset($_POST['cgvText']) and !empty($_POST['cgvText']) and isset($_POST['idAccountType']) and !empty($_POST['idAccountType'])){
  4749.                         $appAccount AppAccountServices::getAccount($this->_idAccount);
  4750.                         $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  4751.                         foreach ($appAccount->getUsers() as $user) {
  4752.                             if(!in_array($user->getType()->getId(),AppUserType::UT_ADMIN)) {
  4753.                                 $data Services_coefficy_utilisateurs::setNewCGV($user$_POST['cgvText']);
  4754.                                 if($user->getId() == $this->_user['idUser']){
  4755.                                     AppTermsOfServiceServices::setAcceptedTermsAfterSubscription($this->_user,$data);
  4756.                                 }
  4757.                             }
  4758.                             if($_POST['idAccountType'] == AppAccountType::START){
  4759.                                 Services_coefficy_utilisateurs::setNewUserCampaignEngagedContactDailyQuota($user,15);
  4760.                             }
  4761.                         }
  4762.                         return new JsonResponse(array(
  4763.                             'status' => 200
  4764.                         ));
  4765.                     }
  4766.                     else{
  4767.                         throw new Exception();
  4768.                     }
  4769.                 }
  4770.                 else{
  4771.                     throw new Exception();
  4772.                 }
  4773.             }
  4774.             else{
  4775.                 throw new Exception();
  4776.             }
  4777.         }
  4778.         catch(Exception $e){
  4779.             if ($this->_request->isMethod("POST")) {
  4780.                 return new JsonResponse(array(
  4781.                     'status' => 400,
  4782.                     'error' => $e->getMessage()
  4783.                 ));
  4784.             }
  4785.             else{
  4786.                 $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  4787.             }
  4788.         }
  4789.         return $this->redirectToRoute('Abonnement');
  4790.     }
  4791.     /**
  4792.      * @Route("/Abonnement/DeleteCgv", name="Abonnement_deleteCgv")
  4793.      * @Route("/Abonnement/DeleteCgv", name="abonnement_deleteCgv")
  4794.      */
  4795.     public function deleteCgvAfterSubscription(){
  4796.         try{
  4797.             if ($this->_request->isMethod("POST")) {
  4798.                 $appAccount AppAccountServices::getAccount($this->_idAccount);
  4799.                 $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  4800.                 foreach ($appAccount->getUsers() as $user) {
  4801.                     Services_coefficy_utilisateurs::deleteLastCgv($user);
  4802.                 }
  4803.             }
  4804.             else{
  4805.                 throw new Exception();
  4806.             }
  4807.         }
  4808.         catch(Exception $e){
  4809.             return new JsonResponse(array(
  4810.                 'status' => 400,
  4811.                 'error' => $e->getMessage()
  4812.             ));
  4813.         }
  4814.         return new JsonResponse(array(
  4815.             'status' => 200
  4816.         ));
  4817.     }
  4818.     /**
  4819.      * @Route("/Abonnement/Subscribe", name="Abonnement_subscribe")
  4820.      * @Route("/Abonnement/Subscribe", name="abonnement_subscribe")
  4821.      */
  4822.     public function subscribe(){
  4823.         try{
  4824.             $exception null;
  4825.             if ($this->_request->isMethod("POST")) {
  4826.                 if(!empty($_POST)){
  4827.                     $delayed false;
  4828.                     if(!isset($_POST['propal']) or empty($_POST['propal'])){
  4829.                         throw new Exception("E1");
  4830.                     }
  4831.                     $propal json_decode($_POST['propal'],true);
  4832.                     if(isset($_POST['DateStart']) and !empty($_POST['DateStart'])){
  4833.                         $dateStart date("Y-m-d"strtotime(str_replace('/','-',$_POST['DateStart'])));
  4834.                         $d = new DateTime();
  4835.                         $today $d->format('Y-m-d');
  4836.                         if(strtotime($dateStart) > strtotime($today)){
  4837.                             $delayed true;
  4838.                             $dateStart $dateStart "T00:00:00.00Z";
  4839.                             $features = array(
  4840.                                 "DateStart" => $dateStart,
  4841.                                 "ReferenceCustomer" => $this->_referenceCustomer,
  4842.                                 "ReferenceOffer" => $propal['ReferenceOffer'],
  4843.                                 "Features" => array_values($_POST['Feature']),
  4844.                                 "Metadata" => [
  4845.                                     "newSubscription" => true,
  4846.                                     "delayed" => true,
  4847.                                     "isOlder" => $this->_isOlder,
  4848.                                     "DateSubscription" => $d->format("c"),
  4849.                                 ]
  4850.                             );
  4851.                            /* if(isset($propal['Metadata']))
  4852.                             {
  4853.                                 $features['Metadata']= array_merge($features['Metadata'], $propal['Metadata'] );
  4854.                             }*/
  4855.                         }
  4856.                         else if(strtotime($dateStart) == strtotime($today)){
  4857.                             $features = array(
  4858.                                 "ReferenceCustomer" => $this->_referenceCustomer,
  4859.                                 "ReferenceOffer" => $propal['ReferenceOffer'],
  4860.                                 "Features" => array_values($_POST['Feature']),
  4861.                                 "Metadata" => [
  4862.                                     "newSubscription" => true,
  4863.                                     "delayed" => false,
  4864.                                     "isOlder" => $this->_isOlder,
  4865.                                     "DateSubscription" => $d->format("c"),
  4866.                                     "previousPropal" => $propal['Id']
  4867.                                 ]
  4868.                             );
  4869.                             /*if(isset($propal['Metadata']))
  4870.                             {
  4871.                                 $features['Metadata']= array_merge($features['Metadata'], $propal['Metadata'] );
  4872.                             }*/
  4873.                         }
  4874.                         else{
  4875.                             throw new Exception("E3");
  4876.                         }
  4877.                     }
  4878.                     else{
  4879.                         throw new Exception("E4");
  4880.                     }
  4881.                     $upgradeToTrialOrUpgradeWithFees = ((in_array($propal['ReferenceOffer'],AppAccountType::UT_TRIAL)) or (in_array($propal['ReferenceOffer'],AppAccountType::UT_START_FEES)) ? true false);
  4882.                     foreach($features['Features'] as &$feature){
  4883.                         if(array_key_exists("Steps",$feature)){
  4884.                             $feature['Steps'] = json_decode($feature['Steps'],true);
  4885.                             if($feature['ReferenceFeature'] == "10-03" ||$feature['ReferenceFeature'] == "8-23" )
  4886.                             {
  4887.                                 if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
  4888.                                 {
  4889.                                     $feature['QuantityCurrent'] = 1;
  4890.                                 }
  4891.                             }
  4892.                         }
  4893.                         if(array_key_exists("QuantityIncluded",$feature)){
  4894.                             if($feature['QuantityIncluded'] == ""){
  4895.                                 $feature['QuantityIncluded'] = null;
  4896.                             }
  4897.                             else{
  4898.                                 $feature['QuantityIncluded'] = intval($feature['QuantityIncluded']);
  4899.                             }
  4900.                         }
  4901.                         if(array_key_exists("QuantityCurrent",$feature)){
  4902.                             $feature['QuantityCurrent'] = intval($feature['QuantityCurrent']);
  4903.                         }
  4904.                     }
  4905.                     $keys = array("AmountUpFront","AmountTrial","DurationTrial","UnitTrial","AmountRecurrence","DurationRecurrence","UnitRecurrence","CountRecurrences","CountMinRecurrences","AmountTermination");
  4906.                     $params = array();
  4907.                     $nameOffer "";
  4908.                     if(array_key_exists("TitleLocalized",$propal)){
  4909.                         $nameOffer $propal['TitleLocalized'];
  4910.                         $params['TitleLocalized'] = $propal['TitleLocalized'];
  4911.                     }
  4912.                     foreach ($keys as $key){
  4913.                         if(array_key_exists($key,$propal)){
  4914.                             $params[$key] = $propal[$key];
  4915.                         }
  4916.                         else{
  4917.                             if($key === "AmountUpFront"){
  4918.                                 $params[$key] = 0;
  4919.                             }
  4920.                         }
  4921.                     }
  4922.                     $array array_merge($params,$features);
  4923.                     // SI UN UPGRADE EST DEJA PREVUE, ON L'ANNULE
  4924.                     if(!$this->_isOlder){
  4925.                         if($this->_proAbonoUserState['current']['subscription']['StateSubscription'] == "UpgradeAtRenewal" or $this->_proAbonoUserState['current']['subscription']['StateSubscription'] == "ActiveDelayedUpgrade"){
  4926.                             $this->_api->callApi("POST"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$this->_idSubscription."/CancelUpgrade"'?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  4927.                         }
  4928.                     }
  4929.                     $refreshOnBoardingHours false;
  4930.                     $onboardingHoursBalance AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount);
  4931.                     if(!$onboardingHoursBalance){
  4932.                         $onboardingHoursBalance 0;
  4933.                     }
  4934.                     // Si on passe d'un plan payant à un plan payant avec heures d'onboarding, on reporte les heures
  4935.                     if(in_array($propal['ReferenceOffer'],AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)){
  4936.                         $creditOnboarding AppAccountTypeServices::getcreditOnboardingHoursInMinutes($propal['ReferenceOffer']);
  4937.                         if(!isset($creditOnboarding))
  4938.                         {
  4939.                             $creditOnboarding 0;
  4940.                         }
  4941.                         $refreshOnBoardingHours true;
  4942.                         $newOnboardingHoursBalance $onboardingHoursBalance $creditOnboarding;
  4943.                         /*if(array_key_exists("AmountUpFront",$propal)){
  4944.                             if($propal["AmountUpFront"] > 0){
  4945.                             }
  4946.                         }*/
  4947.                     }
  4948.                     $createNewSubscription $this->_api->callApi("POST"$this->_urlProAbono "/v1/Subscription?ReferenceOffer=".$propal['ReferenceOffer']."&ReferenceCustomer=".$this->_referenceCustomer."&tryStart=false"$this->_tokenProAbonojson_encode($array));
  4949.                     if($createNewSubscription[1] == 201){
  4950.                         $this->renameSubscription($createNewSubscription[0]['Id'],"Abonnement ".$createNewSubscription[0]['TitleLocalized']." en attente de démarrage");
  4951.                         if(!$this->_isOlder){
  4952.                             // ON ANNULE LA RESILIATION SI IL Y EN A UNE
  4953.                             $this->cancelTermination($this->_idSubscription,$nameOffer);
  4954.                         }
  4955.                         if(!$delayed){
  4956.                             if($this->_isEngaged){
  4957.                                 $data = array(
  4958.                                     "CountMinRecurrences" => null
  4959.                                 );
  4960.                                 $removeEngagement $this->_api->callApi("PATCH"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$this->_idSubscription'?IdBusiness='.$this->_idBusiness$this->_tokenProAbonojson_encode($data));
  4961.                                 if($removeEngagement[1] !== 200){
  4962.                                     $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  4963.                                     $exception $removeEngagement;
  4964.                                     throw new Exception("E6");
  4965.                                 }
  4966.                             }
  4967.                             if($this->_isOlder){
  4968.                                 $start $this->_api->callApi('POST'$this->_urlProAbono."/v1/Subscription/" $createNewSubscription[0]['Id'] . "/Start?BillNow=true"$this->_tokenProAbonofalse);
  4969.                                 if($start[1] != 200){
  4970.                                     $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  4971.                                 }
  4972.                                 else{
  4973.                                     $this->renameSubscription($start[0]['Id'], "Abonnement 1");
  4974.                                     if($refreshOnBoardingHours){
  4975.                                         AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
  4976.                                     }
  4977.                                 }
  4978.                             }
  4979.                             else{
  4980.                                // SI L'OFFRE A DES FRAIS DE DEMARRAGE OU UNE PERIODE ESSAI, ON FAIT UN RESIL START
  4981.                                 if($upgradeToTrialOrUpgradeWithFees){
  4982.                                     $terminate $this->_api->callApi('POST'$this->_urlProAbono."/v1/Subscription/" $this->_idSubscription "/Termination?Immediate=true"$this->_tokenProAbonofalse);
  4983.                                     if($terminate[1] != 200){
  4984.                                         $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  4985.                                         throw new Exception("E6");
  4986.                                     }
  4987.                                     else{
  4988.                                         $start $this->_api->callApi('POST'$this->_urlProAbono."/v1/Subscription/" $createNewSubscription[0]['Id'] . "/Start?BillNow=true"$this->_tokenProAbonofalse);
  4989.                                         if($start[1] != 200){
  4990.                                             $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  4991.                                             throw new Exception("E6");
  4992.                                         }
  4993.                                         else{
  4994.                                             if($refreshOnBoardingHours){
  4995.                                                 AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
  4996.                                             }
  4997.                                             if(array_key_exists("DateNextBilling",$start[0])){
  4998.                                                 $payload json_encode(
  4999.                                                     array(
  5000.                                                         "DateNextBilling" => null
  5001.                                                     )
  5002.                                                 );
  5003.                                                 $res $this->_api->callApi('POST'$this->_urlProAbono.'/v1/CustomerSettingsPayment?ReferenceCustomer='.$this->_referenceCustomer$this->_tokenProAbono$payload);
  5004.                                             }
  5005.                                         }
  5006.                                     }
  5007.                                 }
  5008.                                 // SINON UPGRADE (PRORATISATION)
  5009.                                 else{
  5010.                                     $upgrade $this->_api->callApi('POST'$this->_urlProAbono '/v1/Subscription/' $this->_idSubscription '/Upgrade?IdSubscription=' $createNewSubscription[0]['Id'] . '&BillNow=true'$this->_tokenProAbonofalse);
  5011.                                     if($upgrade[1] != 201){
  5012.                                         $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  5013.                                         throw new Exception("E6");
  5014.                                     }
  5015.                                     if($refreshOnBoardingHours){
  5016.                                         AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
  5017.                                     }
  5018.                                 }
  5019.                             }
  5020.                         }
  5021.                         else{
  5022.                             $msg "La souscription à l'offre " "<strong>" $nameOffer "</strong>" " a bien été validée.";
  5023.                             $this->_session->set("msgFlashSubscription",$msg);
  5024.                             $this->_session->set("iconFlashSubscription","checked");
  5025.                             $delete $this->_api->callApi("DELETE"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$propal['Id']. '?IdBusiness='.$this->_idBusiness$this->_tokenProAbonofalse);
  5026.                         }
  5027.                         return new JsonResponse(array(
  5028.                             'status' => 200
  5029.                         ));
  5030.                     }
  5031.                     else{
  5032.                         $exception $createNewSubscription;
  5033.                         throw new Exception("E9");
  5034.                     }
  5035.                 }
  5036.                 else{
  5037.                     throw new Exception("E10");
  5038.                 }
  5039.             }
  5040.             else{
  5041.                 throw new Exception("E11");
  5042.             }
  5043.         }
  5044.         catch(Exception $e){
  5045.             if ($this->_request->isMethod("POST")) {
  5046.                 if(is_null($exception)){
  5047.                     return new JsonResponse(array(
  5048.                         'status' => 400,
  5049.                         'error' => $e->getMessage(),
  5050.                         'line' => $e->getLine()
  5051.                     ));
  5052.                 }
  5053.                 else{
  5054.                     return new JsonResponse(array(
  5055.                         'status' => 400,
  5056.                         'error' => $e->getMessage(),
  5057.                         'line' => $e->getLine(),
  5058.                         'exception' => $exception
  5059.                     ));
  5060.                 }
  5061.             }
  5062.             else{
  5063.                 $this->addFlash('error'"Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
  5064.             }
  5065.         }
  5066.         if ($this->_request->isMethod("POST")) {
  5067.             return new JsonResponse(array(
  5068.                 'status' => 200
  5069.             ));
  5070.         }
  5071.         else{
  5072.             return $this->redirectToRoute('Abonnement');
  5073.         }
  5074.     }
  5075.     public function renameSubscription(Int $id null,$name null){
  5076.         if(!is_null($id) and !is_null($name)){
  5077.             $params = array(
  5078.                 "Name" => $name
  5079.             );
  5080.             $rename $this->_api->callApi("PATCH"$this->_urlBackOfficeProAbono "/Sub/Subscriptions/".$id'?IdBusiness='.$this->_idBusiness$this->_tokenProAbonojson_encode($params));
  5081.         }
  5082.         else{
  5083.             throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  5084.         }
  5085.     }
  5086.     /**
  5087.      * @Route("/Abonnement/StopTrial", name="Abonnement_stopTrial")
  5088.      * @Route("/Abonnement/StopTrial", name="abonnement_stopTrial")
  5089.      */
  5090.     public function stopTrial(){
  5091.         try{
  5092.   
  5093.             if ($this->_request->isMethod("POST")) {
  5094.                 $params = array(
  5095.                     "ReferenceCustomer" => $this->_referenceCustomer,
  5096.                     "ReferenceOffer" => AppAccountType::REFERRAL
  5097.                 );
  5098.                 $start $this->_api->callApi("POST"$this->_urlProAbono "/v1/Subscription?TryStart=true"$this->_tokenProAbonojson_encode($params));
  5099.                 if ($start[1] == 201) {
  5100.                     $countSubscriptions $this->_api->callApi("GET"$this->_urlBackOfficeProAbono "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$this->_idCustomer$this->_tokenProAbonofalse);
  5101.                     if($countSubscriptions[1] == 200){
  5102.                         $this->renameSubscription($start[0]['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
  5103.                     }
  5104.                     $terminate $this->_api->callApi("POST"$this->_urlProAbono "/v1/Subscription/" $this->_idSubscription "/Termination?Immediate=true"$this->_tokenProAbonofalse);
  5105.                     if ($terminate[1] !== 200) {
  5106.                         $this->_api->callApi("POST"$this->_urlProAbono "/v1/Subscription/" $start[0]['Id'] . "/Termination?Immediate=true"$this->_tokenProAbonofalse);
  5107.                         throw new Exception();
  5108.                     }
  5109.                     else{
  5110.                         $appAccount AppAccountServices::getAccount($this->_idAccount);
  5111.                         $appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
  5112.                         foreach ($appAccount->getUsers() as $user) {
  5113.                             $data Services_coefficy_utilisateurs::setNewCGV($user,AppTermsOfService::TERMS_OF_SERVICE);
  5114.                         }
  5115.                         $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  5116.                             'idCustomer'  => $this->_idCustomer,
  5117.                             'fromTrigger' => false,
  5118.                             'fromScript' => false
  5119.                         ]);
  5120.                         $msg "Votre demande a bien été pris en compte. Vous avez désormais souscris à un abonnement REFERRAL.";
  5121.                         $this->_session->set("msgFlashSubscription",$msg);
  5122.                         $this->_session->set("iconFlashSubscription","checked");
  5123.                         if(!empty($this->_request->query->all())){
  5124.                             return $this->redirectToRoute('Abonnement',$this->_request->query->all());
  5125.                         }
  5126.                         else{
  5127.                             return $this->redirectToRoute('Abonnement');
  5128.                         }
  5129.                     }
  5130.                 } else {
  5131.                     throw new Exception();
  5132.                 }
  5133.             }
  5134.             else{
  5135.                 throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  5136.             }
  5137.         }
  5138.         catch(Exception $e){
  5139.             $this->setAttribute("error""Une opération de maintenance est en cours sur notre back office rendant la gestion de votre abonnement indisponible à cet instant. Veuillez réessayer ultérieurement.");
  5140.         }
  5141.         if(!empty($this->_request->query->all())){
  5142.             return $this->redirectToRoute('Abonnement_update',$this->_request->query->all());
  5143.         }
  5144.         else{
  5145.             return $this->redirectToRoute('Abonnement_update');
  5146.         }
  5147.     }
  5148.     /**
  5149.      * @Route("/Abonnement/SupportMode", name="Abonnement_go_support_mode")
  5150.      * @Route("/Abonnement/SupportMode", name="abonnement_go_support_mode")
  5151.      */
  5152.     public function goSupportMode(SessionInterface $session){
  5153.         try {
  5154.             if(!in_array($this->_user['idUserType'],AppUserType::UT_ADMIN)){
  5155.                 throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  5156.             }
  5157.             if(array_key_exists("supportMode",$this->_user)){
  5158.                 if($this->_user['supportMode']){
  5159.                     throw new Exception("Vous êtes déjà en MODE SUPPORT.",01);
  5160.                 }
  5161.             }
  5162.             else{
  5163.                 throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
  5164.             }
  5165.             $emailSupport "support" rand(0,100000) . "+" $this->_user['userEmail'];
  5166.             $idUserSupport null;
  5167.             if(ConnectionServices::mailExistsActived($emailSupport)){
  5168.                 $existantSupportUser AppUserServices::getUserFromEmail($emailSupport);
  5169.                 if($existantSupportUser->getIdAccount() !== $this->_idAccount){
  5170.                     $appAccount AppAccountServices::getAccount($existantSupportUser->getIdAccount());
  5171.                     $responsableUserExist Services_coefficy_utilisateurs::getOldestResponsableIdUser($existantSupportUser->getIdAccount());
  5172.                     if(!$responsableUserExist) {
  5173.                         if($appAccount->hasService(AppService::CRM)) {
  5174.                             if (!CrmRelaunchServices::deleteUserFromRelaunch($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
  5175.                                 throw new Exception("Erreur lors de la suppression des relances de l'utilisateur support déjà existant."01);
  5176.                             }
  5177.                             if (!CrmOpportunityServices::deleteUserOpportunity($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
  5178.                                 throw new Exception("Erreur lors de la suppression des opportunités de l'utilisateur support déjà existant."01);
  5179.                             }
  5180.                             if (!RoutineServices::deleteUserRoutines($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
  5181.                                 throw new Exception("Erreur lors de la suppression des routines de l'utilisateur support déjà existant"01);
  5182.                             }
  5183.                             if (!CamPersonaServices::deletePersonaByUser($existantSupportUser->getIdUser())) {
  5184.                                 throw new Exception("Erreur lors de la suppression des personnas de l'utilisateur support déjà existant"01);
  5185.                             }
  5186.                         }
  5187.                         if ($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  5188.                             $sequences CampaignApiServices::call(
  5189.                                 'get',
  5190.                                 CampaignApiServices::ENDPOINT['SEQUENCE'],
  5191.                                 $this->_session->get('campaignApi')['token'],
  5192.                                 [
  5193.                                     'idSequenceType' => 2,
  5194.                                     'idUser' => $existantSupportUser->getIdUser(),
  5195.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5196.                                 ]
  5197.                             );
  5198.                             if (array_key_exists("result"$sequences)) {
  5199.                                 if ($sequences['result']['success']) {
  5200.                                     if (!empty($sequences['result']['result'])) {
  5201.                                         foreach ($sequences['result']['result'] as $s) {
  5202.                                             $sequence CampaignApiServices::call(
  5203.                                                 'delete',
  5204.                                                 CampaignApiServices::ENDPOINT['SEQUENCE'],
  5205.                                                 $this->_session->get('campaignApi')['token'],
  5206.                                                 [
  5207.                                                     'idSequence' => $s['idSequence'],
  5208.                                                     'idAccount' => $existantSupportUser->getIdAccount(),
  5209.                                                     'idUserStopped' => $existantSupportUser->getIdUser()
  5210.                                                 ]
  5211.                                             );
  5212.                                             if (array_key_exists("result"$sequence)) {
  5213.                                                 if (!$sequence['result']['success']) {
  5214.                                                     throw new Exception ("Une erreur a été rencontrée lors de la suppression de la séquence . " $s['idSequence'] . " crée par l'utilisateur support."01);
  5215.                                                 }
  5216.                                             } else {
  5217.                                                 throw new Exception ("Une erreur a été rencontrée lors de la suppression de la séquence . " $s['idSequence'] . " crée par l'utilisateur support."01);
  5218.                                             }
  5219.                                         }
  5220.                                     }
  5221.                                 } else {
  5222.                                     throw new Exception ("Une erreur a été rencontrée lors de la récupération des séquences crées par l'utilisateur support."01);
  5223.                                 }
  5224.                             } else {
  5225.                                 throw new Exception ("Impossible de récupérer les séquences crées par l'utilisateur support."01);
  5226.                             }
  5227.                         }
  5228.                         if ($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
  5229.                             $campaignsUser CampaignApiServices::call(
  5230.                                 'get',
  5231.                                 CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5232.                                 $this->_session->get('campaignApi')['token'],
  5233.                                 [
  5234.                                     'idUser' => $existantSupportUser->getIdUser(),
  5235.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5236.                                 ]
  5237.                             );
  5238.                             $campaignsUserCreator CampaignApiServices::call(
  5239.                                 'get',
  5240.                                 CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5241.                                 $this->_session->get('campaignApi')['token'],
  5242.                                 [
  5243.                                     'idUserCreator' => $existantSupportUser->getIdUser(),
  5244.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5245.                                 ]
  5246.                             );
  5247.                             if (array_key_exists("result"$campaignsUser) && array_key_exists("result"$campaignsUserCreator)) {
  5248.                                 if ($campaignsUser['result']['success'] && $campaignsUserCreator['result']['success']) {
  5249.                                     $allCampaigns = array();
  5250.                                     foreach ($campaignsUser['result']['result'] as $c) {
  5251.                                         if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
  5252.                                             $allCampaigns[$c['idCampaign']] = $c;
  5253.                                         }
  5254.                                     }
  5255.                                     foreach ($campaignsUserCreator['result']['result'] as $c) {
  5256.                                         if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
  5257.                                             $allCampaigns[$c['idCampaign']] = $c;
  5258.                                         }
  5259.                                     }
  5260.                                     if (!empty($allCampaigns)) {
  5261.                                         foreach ($allCampaigns as $c) {
  5262.                                             $campaign CampaignApiServices::call(
  5263.                                                 'delete',
  5264.                                                 CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5265.                                                 $this->_session->get('campaignApi')['token'],
  5266.                                                 [
  5267.                                                     'idCampaign' => $c['idCampaign'],
  5268.                                                     'idUserStopped' => $c['idUser']
  5269.                                                 ]
  5270.                                             );
  5271.                                             if (array_key_exists("result"$campaign)) {
  5272.                                                 if (!$campaign['result']['success']) {
  5273.                                                     throw new Exception ("Une erreur a été rencontrée lors de la suppression de la campagne . " $c['idCampaign'] . " crée/attribuée par l'utilisateur support."01);
  5274.                                                 }
  5275.                                             } else {
  5276.                                                 throw new Exception ("Une erreur a été rencontrée lors de la suppression de la campagne . " $c['idCampaign'] . " crée/attribuée par l'utilisateur support."01);
  5277.                                             }
  5278.                                         }
  5279.                                     }
  5280.                                 } else {
  5281.                                     throw new Exception ("Une erreur a été rencontrée lors de la récupération des campagnes crées/attribuées par l'utilisateur support."01);
  5282.                                 }
  5283.                             } else {
  5284.                                 throw new Exception ("Impossible de récupérer les campagnes crées/attribuées par l'utilisateur support."01);
  5285.                             }
  5286.                         }
  5287.                         if ($appAccount->hasService(AppService::NEWSLETTER)) {
  5288.                             $newsletters CampaignApiServices::call(
  5289.                                 'get',
  5290.                                 CampaignApiServices::ENDPOINT['NEWSLETTER'],
  5291.                                 $this->_session->get('campaignApi')['token'],
  5292.                                 [
  5293.                                     'idUser' => $existantSupportUser->getIdUser(),
  5294.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5295.                                 ]
  5296.                             );
  5297.                             if (array_key_exists("result"$newsletters)) {
  5298.                                 if ($newsletters['result']['success']) {
  5299.                                     if (!empty($newsletters['result']['result'])) {
  5300.                                         foreach ($newsletters['result']['result'] as $n) {
  5301.                                             $newsletter CampaignApiServices::call(
  5302.                                                 'delete',
  5303.                                                 CampaignApiServices::ENDPOINT['NEWSLETTER'],
  5304.                                                 $this->_session->get('campaignApi')['token'],
  5305.                                                 [
  5306.                                                     'idNewsletter' => $n['idNewsletter'],
  5307.                                                     'idAccount' => $existantSupportUser->getIdAccount()
  5308.                                                 ]
  5309.                                             );
  5310.                                             if (array_key_exists("result"$newsletter)) {
  5311.                                                 if (!$newsletter['result']['success']) {
  5312.                                                     throw new Exception ("Une erreur a été rencontrée lors de la suppression de la newsletter . " $n['idNewsletter'] . " crée par l'utilisateur support."01);
  5313.                                                 }
  5314.                                             } else {
  5315.                                                 throw new Exception ("Une erreur a été rencontrée lors de la suppression de la newsletter . " $n['idNewsletter'] . " crée par l'utilisateur support."01);
  5316.                                             }
  5317.                                         }
  5318.                                     }
  5319.                                 } else {
  5320.                                     throw new Exception ("Une erreur a été rencontrée lors de la récupération des newsletters crées par l'utilisateur support."01);
  5321.                                 }
  5322.                             } else {
  5323.                                 throw new Exception ("Impossible de récupérer les newsletters crées par l'utilisateur support."01);
  5324.                             }
  5325.                         }
  5326.                         if ($appAccount->hasService(AppService::LEBONLOGICIEL)) {
  5327.                             if (!LeBonLogicielServices::deleteArticleByUser($existantSupportUser->getIdUser())) {
  5328.                                 throw new Exception("Erreur lors de la suppression des articles LBL de l'utilisateur support déjà existant"01);
  5329.                             }
  5330.                             if (!LeBonLogicielServices::deleteOrganizationByUser($existantSupportUser->getIdUser())) {
  5331.                                 throw new Exception("Erreur lors de la suppression de la fiche editeur/intégrateur LBL de l'utilisateur support déjà existant"01);
  5332.                             }
  5333.                             if (!LeBonLogicielServices::deleteSolutionVersionByUser($existantSupportUser->getIdUser())) {
  5334.                                 throw new Exception("Erreur lors de la suppression des solutions éditées LBL de l'utilisateur support déjà existant"01);
  5335.                             }
  5336.                         }
  5337.                         if ($appAccount->hasService(AppService::EMAIL_SUIVI)) {
  5338.                             if (!AppMailTemplateServices::deleteTemplateEmailByUser($existantSupportUser->getIdUser())) {
  5339.                                 throw new Exception("Erreur lors de la suppression des templates email de l'utilisateur support déjà existant"01);
  5340.                             }
  5341.                         }
  5342.                         if ($appAccount->hasService(AppService::EDITION_LEADFORM)) {
  5343.                             if (!LeadformServices::deleteFormsByUser($existantSupportUser->getIdUser())) {
  5344.                                 throw new Exception("Erreur lors de la suppression des formulaires de l'utilisateur support déjà existant"01);
  5345.                             }
  5346.                         }
  5347.                     }
  5348.                     else{
  5349.                         if($appAccount->hasService(AppService::CRM)){
  5350.                             if(!CrmRelaunchServices::updateUserOnRelaunch($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount(), $responsableUserExist->getIdUser())){
  5351.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des relances de l'utilisateur support déjà existant");
  5352.                             }
  5353.                             if(!CrmOpportunityServices::updateUserOnOpportunity($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount(), $responsableUserExist->getIdUser())){
  5354.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des opportunitées de l'utilisateur support déjà existant");
  5355.                             }
  5356.                             if(!RoutineServices::updateUserOnRoutine($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser())){
  5357.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des routines de l'utilisateur support déjà existant");
  5358.                             }
  5359.                             if(!CamPersonaServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
  5360.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des personas de l'utilisateur support déjà existant");
  5361.                             }
  5362.                         }
  5363.                         if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  5364.                             $resultSequence CampaignApiServices::call(
  5365.                                 'put',
  5366.                                 CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
  5367.                                 $this->_session->get('campaignApi')['token'],
  5368.                                 [
  5369.                                     'idUser' => $existantSupportUser->getIdUser(),
  5370.                                     'newIdUser' => $responsableUserExist->getIdUser(),
  5371.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5372.                                 ]
  5373.                             );
  5374.                         }
  5375.                         if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
  5376.                             $resultCampaign CampaignApiServices::call(
  5377.                                 'put',
  5378.                                 CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
  5379.                                 $this->_session->get('campaignApi')['token'],
  5380.                                 [
  5381.                                     'idUser' => $existantSupportUser->getIdUser(),
  5382.                                     'newIdUser' => $responsableUserExist->getIdUser(),
  5383.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5384.                                 ]
  5385.                             );
  5386.                         }
  5387.                         if($appAccount->hasService(AppService::NEWSLETTER)) {
  5388.                             $resultNewsletterContact CampaignApiServices::call(
  5389.                                 'put',
  5390.                                 CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
  5391.                                 $this->_session->get('campaignApi')['token'],
  5392.                                 [
  5393.                                     'idUser' => $existantSupportUser->getIdUser(),
  5394.                                     'newIdUser' => $responsableUserExist->getIdUser(),
  5395.                                     'idAccount' => $existantSupportUser->getIdAccount()
  5396.                                 ]
  5397.                             );
  5398.                         }
  5399.                         if($appAccount->hasService(AppService::LEBONLOGICIEL)){
  5400.                             if(!LeBonLogicielServices::transfertArticleResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
  5401.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des articles LBL de l'utilisateur support déjà existant");
  5402.                             }
  5403.                             if(!LeBonLogicielServices::transfertSolutionVersionResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser())){
  5404.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des solutions éditées LBL de l'utilisateur support déjà existant");
  5405.                             }
  5406.                             if(!LeBonLogicielServices::transfertOrganizationResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
  5407.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation de la fiche éditeur/intégrateur LBL de l'utilisateur support déjà existant");
  5408.                             }
  5409.                         }
  5410.                         if($appAccount->hasService(AppService::EMAIL_SUIVI)){
  5411.                             if(!AppMailTemplateServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
  5412.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des templates d'emails de l'utilisateur support déjà existant");
  5413.                             }
  5414.                         }
  5415.                         if($appAccount->hasService(AppService::EDITION_LEADFORM)){
  5416.                             if(!LeadformServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
  5417.                                 throw new Exception("Une erreur a été rencontrée lors de la réaffectation des leadforms de l'utilisateur support déjà existant");
  5418.                             }
  5419.                         }
  5420.                     }
  5421.                     if (!Services_coefficy_utilisateurs::deleteUser($existantSupportUser->getIdUser())) {
  5422.                         throw new Exception("Une erreur a été rencontrée lors de la suppression de l'utilisateur support déjà existant"01);
  5423.                     }
  5424.                     $idUserSupport Services_coefficy_utilisateurs::addSupportUser($this->_user,$this->_idAccount,$emailSupport);
  5425.                 }
  5426.                 else{
  5427.                     $idUserSupport $existantSupportUser->getIdUser();
  5428.                 }
  5429.             }
  5430.             else{
  5431.                 $idUserSupport Services_coefficy_utilisateurs::addSupportUser($this->_user,$this->_idAccount,$emailSupport);
  5432.             }
  5433.             if(is_null($idUserSupport)){
  5434.                 throw new Exception ("Une erreur a été rencontrée lors de la création du compte support.",01);
  5435.             }
  5436.             $connection = new ConnectionServices();
  5437.             if($connection->connexion_standard($emailSupport$this->_user['userPassword'], $this->_session1) !== 1){
  5438.                 throw new Exception("Une erreur a été rencontrée lors de la connexion au compte support.",01);
  5439.             }
  5440.             $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
  5441.                 'idCustomer'  => $this->_idCustomer,
  5442.                 'fromTrigger' => false,
  5443.                 'fromScript' => false
  5444.             ]);
  5445.             $this->addFlash("success","Vous êtes en mode support.");
  5446.         }
  5447.         catch(Exception $e){
  5448.             if($e->getCode() == 01){
  5449.                 $this->setAttribute('error'$e->getMessage());
  5450.             }
  5451.             else{
  5452.                 $this->setAttribute("error""Impossible de rejoindre le mode SUPPORT. Une erreur a été rencontrée.");
  5453.             }
  5454.             return $this->redirectToRoute('Abonnement', ['idAccount' => $this->_idAccount]);
  5455.         }
  5456.         //Connexion OK il faut set des variables dans la session
  5457.         SessionUtilisateur::setSessionVariables($session);
  5458.         return $this->redirectToRoute('Abonnement');
  5459.     }
  5460.     /**
  5461.      * @Route("/Abonnement/LeaveSupportMode", name="Abonnement_leave_support_mode")
  5462.      * @Route("/Abonnement/LeaveSupportMode", name="abonnement_leave_support_mode")
  5463.      */
  5464.     public function exitSupportMode(SessionInterface $session){
  5465.         try {
  5466.             if(!in_array($this->_user['idUserType'],AppUserType::UT_ADMIN)){
  5467.                 throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
  5468.             }
  5469.             if(array_key_exists("supportMode",$this->_user)){
  5470.                 if(!$this->_user['supportMode']){
  5471.                     throw new Exception("Vous n'êtes pas en mode SUPPORT, vous ne pouvez pas le quitter.",01);
  5472.                 }
  5473.             }
  5474.             else{
  5475.                 throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
  5476.             }
  5477.             if(!array_key_exists("idSupportUser",$this->_user)){
  5478.                 throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
  5479.             }
  5480.             $responsableUserExist Services_coefficy_utilisateurs::getOldestResponsableIdUser($this->_idAccount);
  5481.             $appAccount AppAccountServices::getAccount($this->_idAccount);
  5482.             if(!$responsableUserExist) {
  5483.                 if ($appAccount->hasService(AppService::CRM)) {
  5484.                     if (!CrmRelaunchServices::deleteUserFromRelaunch($this->_user['idUser'], $this->_idAccount)) {
  5485.                         throw new Exception("Erreur lors de la suppression des relances de l'utilisateur support."01);
  5486.                     }
  5487.                     if (!CrmOpportunityServices::deleteUserOpportunity($this->_user['idUser'], $this->_idAccount)) {
  5488.                         throw new Exception("Erreur lors de la suppression des opportunités de l'utilisateur support."01);
  5489.                     }
  5490.                     if (!RoutineServices::deleteUserRoutines($this->_user['idUser'], $this->_idAccount)) {
  5491.                         throw new Exception("Erreur lors de la suppression des routines de l'utilisateur support."01);
  5492.                     }
  5493.                     if (!CamPersonaServices::deletePersonaByUser($this->_user['idUser'])) {
  5494.                         throw new Exception("Erreur lors de la suppression des personnas de l'utilisateur support."01);
  5495.                     }
  5496.                 }
  5497.                 if ($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  5498.                     $sequences CampaignApiServices::call(
  5499.                         'get',
  5500.                         CampaignApiServices::ENDPOINT['SEQUENCE'],
  5501.                         $this->_session->get('campaignApi')['token'],
  5502.                         [
  5503.                             'idSequenceType' => 2,
  5504.                             'idUser' => $this->_user['idUser'],
  5505.                             'idAccount' => $this->_idAccount
  5506.                         ]
  5507.                     );
  5508.                     if (array_key_exists("result"$sequences)) {
  5509.                         if ($sequences['result']['success']) {
  5510.                             if (!empty($sequences['result']['result'])) {
  5511.                                 foreach ($sequences['result']['result'] as $s) {
  5512.                                     $sequence CampaignApiServices::call(
  5513.                                         'delete',
  5514.                                         CampaignApiServices::ENDPOINT['SEQUENCE'],
  5515.                                         $this->_session->get('campaignApi')['token'],
  5516.                                         [
  5517.                                             'idSequence' => $s['idSequence'],
  5518.                                             'idAccount' => $this->_idAccount,
  5519.                                             'idUserStopped' => $this->_user['idUser']
  5520.                                         ]
  5521.                                     );
  5522.                                     if (array_key_exists("result"$sequence)) {
  5523.                                         if (!$sequence['result']['success']) {
  5524.                                             throw new Exception ("Une erreur a été rencontrée lors de la suppression de la séquence . " $s['idSequence'] . " crée par l'utilisateur support."01);
  5525.                                         }
  5526.                                     } else {
  5527.                                         throw new Exception ("Une erreur a été rencontrée lors de la suppression de la séquence . " $s['idSequence'] . " crée par l'utilisateur support."01);
  5528.                                     }
  5529.                                 }
  5530.                             }
  5531.                         } else {
  5532.                             throw new Exception ("Une erreur a été rencontrée lors de la récupération des séquences crées par l'utilisateur support."01);
  5533.                         }
  5534.                     } else {
  5535.                         throw new Exception ("Impossible de récupérer les séquences crées par l'utilisateur support."01);
  5536.                     }
  5537.                 }
  5538.                 if ($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
  5539.                     $campaignsUser CampaignApiServices::call(
  5540.                         'get',
  5541.                         CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5542.                         $this->_session->get('campaignApi')['token'],
  5543.                         [
  5544.                             'idUser' => $this->_user['idUser'],
  5545.                             'idAccount' => $this->_idAccount
  5546.                         ]
  5547.                     );
  5548.                     $campaignsUserCreator CampaignApiServices::call(
  5549.                         'get',
  5550.                         CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5551.                         $this->_session->get('campaignApi')['token'],
  5552.                         [
  5553.                             'idUserCreator' => $this->_user['idUser'],
  5554.                             'idAccount' => $this->_idAccount
  5555.                         ]
  5556.                     );
  5557.                     if (array_key_exists("result"$campaignsUser) && array_key_exists("result"$campaignsUserCreator)) {
  5558.                         if ($campaignsUser['result']['success'] && $campaignsUserCreator['result']['success']) {
  5559.                             $allCampaigns = array();
  5560.                             foreach ($campaignsUser['result']['result'] as $c) {
  5561.                                 if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
  5562.                                     $allCampaigns[$c['idCampaign']] = $c;
  5563.                                 }
  5564.                             }
  5565.                             foreach ($campaignsUserCreator['result']['result'] as $c) {
  5566.                                 if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
  5567.                                     $allCampaigns[$c['idCampaign']] = $c;
  5568.                                 }
  5569.                             }
  5570.                             if (!empty($allCampaigns)) {
  5571.                                 foreach ($allCampaigns as $c) {
  5572.                                     $campaign CampaignApiServices::call(
  5573.                                         'delete',
  5574.                                         CampaignApiServices::ENDPOINT['CAMPAIGN'],
  5575.                                         $this->_session->get('campaignApi')['token'],
  5576.                                         [
  5577.                                             'idCampaign' => $c['idCampaign'],
  5578.                                             'idUserStopped' => $c['idUser']
  5579.                                         ]
  5580.                                     );
  5581.                                     if (array_key_exists("result"$campaign)) {
  5582.                                         if (!$campaign['result']['success']) {
  5583.                                             throw new Exception ("Une erreur a été rencontrée lors de la suppression de la campagne . " $c['idCampaign'] . " crée/attribuée par l'utilisateur support."01);
  5584.                                         }
  5585.                                     } else {
  5586.                                         throw new Exception ("Une erreur a été rencontrée lors de la suppression de la campagne . " $c['idCampaign'] . " crée/attribuée par l'utilisateur support."01);
  5587.                                     }
  5588.                                 }
  5589.                             }
  5590.                         } else {
  5591.                             throw new Exception ("Une erreur a été rencontrée lors de la récupération des campagnes crées/attribuées par l'utilisateur support."01);
  5592.                         }
  5593.                     } else {
  5594.                         throw new Exception ("Impossible de récupérer les campagnes crées/attribuées par l'utilisateur support."01);
  5595.                     }
  5596.                 }
  5597.                 if ($appAccount->hasService(AppService::NEWSLETTER)) {
  5598.                     $newsletters CampaignApiServices::call(
  5599.                         'get',
  5600.                         CampaignApiServices::ENDPOINT['NEWSLETTER'],
  5601.                         $this->_session->get('campaignApi')['token'],
  5602.                         [
  5603.                             'idUser' => $this->_user['idUser'],
  5604.                             'idAccount' => $this->_idAccount
  5605.                         ]
  5606.                     );
  5607.                     if (array_key_exists("result"$newsletters)) {
  5608.                         if ($newsletters['result']['success']) {
  5609.                             if (!empty($newsletters['result']['result'])) {
  5610.                                 foreach ($newsletters['result']['result'] as $n) {
  5611.                                     $newsletter CampaignApiServices::call(
  5612.                                         'delete',
  5613.                                         CampaignApiServices::ENDPOINT['NEWSLETTER'],
  5614.                                         $this->_session->get('campaignApi')['token'],
  5615.                                         [
  5616.                                             'idNewsletter' => $n['idNewsletter'],
  5617.                                             'idAccount' => $this->_idAccount
  5618.                                         ]
  5619.                                     );
  5620.                                     if (array_key_exists("result"$newsletter)) {
  5621.                                         if (!$newsletter['result']['success']) {
  5622.                                             throw new Exception ("Une erreur a été rencontrée lors de la suppression de la newsletter . " $n['idNewsletter'] . " crée par l'utilisateur support."01);
  5623.                                         }
  5624.                                     } else {
  5625.                                         throw new Exception ("Une erreur a été rencontrée lors de la suppression de la newsletter . " $n['idNewsletter'] . " crée par l'utilisateur support."01);
  5626.                                     }
  5627.                                 }
  5628.                             }
  5629.                         } else {
  5630.                             throw new Exception ("Une erreur a été rencontrée lors de la récupération des newsletters crées par l'utilisateur support."01);
  5631.                         }
  5632.                     } else {
  5633.                         throw new Exception ("Impossible de récupérer les newsletters crées par l'utilisateur support."01);
  5634.                     }
  5635.                 }
  5636.                 if ($appAccount->hasService(AppService::LEBONLOGICIEL)) {
  5637.                     if (!LeBonLogicielServices::deleteArticleByUser($this->_user['idUser'])) {
  5638.                         throw new Exception("Erreur lors de la suppression des articles LBL de l'utilisateur support."01);
  5639.                     }
  5640.                     if (!LeBonLogicielServices::deleteSolutionVersionByUser($this->_user['idUser'])) {
  5641.                         throw new Exception("Erreur lors de la suppression des solutions editées LBL de l'utilisateur support."01);
  5642.                     }
  5643.                     if (!LeBonLogicielServices::deleteOrganizationByUser($this->_user['idUser'])) {
  5644.                         throw new Exception("Erreur lors de la suppression de la fiche editeur/integrateur LBL de l'utilisateur support."01);
  5645.                     }
  5646.                 }
  5647.                 if ($appAccount->hasService(AppService::EMAIL_SUIVI)) {
  5648.                     if (!AppMailTemplateServices::deleteTemplateEmailByUser($this->_user['idUser'])) {
  5649.                         throw new Exception("Erreur lors de la suppression des templates email de l'utilisateur support."01);
  5650.                     }
  5651.                 }
  5652.                 if ($appAccount->hasService(AppService::EDITION_LEADFORM)) {
  5653.                     if (!LeadformServices::deleteFormsByUser($this->_user['idUser'])) {
  5654.                         throw new Exception("Erreur lors de la suppression des formulaires de l'utilisateur support."01);
  5655.                     }
  5656.                 }
  5657.             }
  5658.             else{
  5659.                 if($appAccount->hasService(AppService::CRM)){
  5660.                     if(!CrmRelaunchServices::updateUserOnRelaunch($this->_user['idUser'], $this->_idAccount$responsableUserExist->getIdUser())){
  5661.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des relances de l'utilisateur support");
  5662.                     }
  5663.                     if(!CrmOpportunityServices::updateUserOnOpportunity($this->_user['idUser'], $this->_idAccount$responsableUserExist->getIdUser())){
  5664.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des opportunitées de l'utilisateur support");
  5665.                     }
  5666.                     if(!RoutineServices::updateUserOnRoutine($this->_user['idUser'], $responsableUserExist->getIdUser())){
  5667.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des routines de l'utilisateur support");
  5668.                     }
  5669.                     if(!CamPersonaServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
  5670.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des personas de l'utilisateur support");
  5671.                     }
  5672.                 }
  5673.                 if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
  5674.                     $resultSequence CampaignApiServices::call(
  5675.                         'put',
  5676.                         CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
  5677.                         $this->_session->get('campaignApi')['token'],
  5678.                         [
  5679.                             'idUser' => $this->_user['idUser'],
  5680.                             'newIdUser' => $responsableUserExist->getIdUser(),
  5681.                             'idAccount' => $this->_idAccount
  5682.                         ]
  5683.                     );
  5684.                 }
  5685.                 if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
  5686.                     $resultCampaign CampaignApiServices::call(
  5687.                         'put',
  5688.                         CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
  5689.                         $this->_session->get('campaignApi')['token'],
  5690.                         [
  5691.                             'idUser' => $this->_user['idUser'],
  5692.                             'newIdUser' => $responsableUserExist->getIdUser(),
  5693.                             'idAccount' => $this->_idAccount
  5694.                         ]
  5695.                     );
  5696.                 }
  5697.                 if($appAccount->hasService(AppService::NEWSLETTER)) {
  5698.                     $resultNewsletterContact CampaignApiServices::call(
  5699.                         'put',
  5700.                         CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
  5701.                         $this->_session->get('campaignApi')['token'],
  5702.                         [
  5703.                             'idUser' => $this->_user['idUser'],
  5704.                             'newIdUser' => $responsableUserExist->getIdUser(),
  5705.                             'idAccount' => $this->_idAccount
  5706.                         ]
  5707.                     );
  5708.                 }
  5709.                 if($appAccount->hasService(AppService::LEBONLOGICIEL)){
  5710.                     if(!LeBonLogicielServices::transfertArticleResponsable($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
  5711.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des articles LBL de l'utilisateur support");
  5712.                     }
  5713.                     if(!LeBonLogicielServices::transfertOrganizationResponsable($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
  5714.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation de la fiche editeur/integrateur LBL de l'utilisateur support");
  5715.                     }
  5716.                     if(!LeBonLogicielServices::transfertSolutionVersionResponsable($this->_user['idUser'], $responsableUserExist->getIdUser())){
  5717.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des solutions éditées LBL de l'utilisateur support");
  5718.                     }
  5719.                 }
  5720.                 if($appAccount->hasService(AppService::EMAIL_SUIVI)){
  5721.                     if(!AppMailTemplateServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
  5722.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des templates d'emails de l'utilisateur support");
  5723.                     }
  5724.                 }
  5725.                 if($appAccount->hasService(AppService::EDITION_LEADFORM)){
  5726.                     if(!LeadformServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
  5727.                         throw new Exception("Une erreur a été rencontrée lors de la réaffectation des leadforms de l'utilisateur support");
  5728.                     }
  5729.                 }
  5730.             }
  5731.             $userToConnectWith AppUserServices::getUserArray($this->_user['idSupportUser']);
  5732.             $connection = new ConnectionServices();
  5733.             if($connection->connexion_standard($userToConnectWith['userEmail'], $userToConnectWith['userPassword'], $this->_session2) !== 1){
  5734.                 throw new Exception("Une erreur a été rencontrée lors de la connexion du compte support.",01);
  5735.             }
  5736.             else{
  5737.                 if(!Services_coefficy_utilisateurs::deleteUser($this->_user['idUser'])){
  5738.                     throw new Exception("Une erreur a été rencontrée lors de la suppression de l'utilisateur support.",01);
  5739.                 }
  5740.             }
  5741.             $this->addFlash("success","Vous avez quitté le mode support.");
  5742.         }
  5743.         catch(Exception $e){
  5744.             if($e->getCode() == 01){
  5745.                 $this->addFlash("error",$e->getMessage());
  5746.             }
  5747.             else{
  5748.                 $this->addFlash("error""Impossible de quitter le mode SUPPORT. Une erreur a été rencontrée.");
  5749.             }
  5750.             return $this->redirectToRoute('Abonnement');
  5751.         }
  5752.         //Connexion OK il faut set des variables dans la session
  5753.         SessionUtilisateur::setSessionVariables($session);
  5754.         return $this->redirectToRoute('Abonnement', ['idAccount' => $this->_idAccount]);
  5755.     }
  5756.     /**
  5757.      * @Route("/Abonnement/loadHistoricCGV", name="Abonnement_LoadCGV")
  5758.      * @Route("/Abonnement/loadHistoricCGV", name="abonnement_loadCGV")
  5759.      */
  5760.     public function loadHistoricCGV(Request $requestSessionInterface $session){
  5761.         $response = new Response();
  5762.         $idAccount $request->get('idAccount');
  5763.         $method 'GET';
  5764.         $tokenApi $session->get('campaignApi')['token'];
  5765.         $data = array(
  5766.             'idAccount' => $idAccount,
  5767.             'isAccepted' => true);
  5768.         $userTermServiceList CampaignApiServices::call($methodCampaignApiServices::ENDPOINT['TERMS_OF_SERVICE'], $tokenApi$data)['result']['result'];
  5769.         $url 'abonnement/onglets/utilisateurs/historic_cgv_accept.html.twig';
  5770.         $html $this->render($url,array(
  5771.             'userTermServiceList' =>$userTermServiceList
  5772.         ))->getContent();
  5773.         $response->setContent(json_encode($html));
  5774.         return $response;
  5775.     }
  5776.     /**
  5777.      * @return mixed
  5778.      */
  5779.     public function getRequest()
  5780.     {
  5781.         return $this->_request;
  5782.     }
  5783.     /**
  5784.      * @return SessionInterface
  5785.      */
  5786.     public function getSession(): SessionInterface
  5787.     {
  5788.         return $this->_session;
  5789.     }
  5790.     /**
  5791.      * @return mixed
  5792.      */
  5793.     public function getUser()
  5794.     {
  5795.         return $this->_user;
  5796.     }
  5797.     /**
  5798.      * @return mixed|null
  5799.      */
  5800.     public function getIdAccount()
  5801.     {
  5802.         return $this->_idAccount;
  5803.     }
  5804.     /**
  5805.      * @return string|null
  5806.      */
  5807.     public function getSiren(): ?string
  5808.     {
  5809.         return $this->_siren;
  5810.     }
  5811.     /**
  5812.      * @return string|null
  5813.      */
  5814.     public function getReferenceCustomer(): ?string
  5815.     {
  5816.         return $this->_referenceCustomer;
  5817.     }
  5818.     /**
  5819.      * @return string|null
  5820.      */
  5821.     public function getAccountTitle(): ?string
  5822.     {
  5823.         return $this->_accountTitle;
  5824.     }
  5825.     /**
  5826.      * @return mixed
  5827.      */
  5828.     public function getCompanyName()
  5829.     {
  5830.         return $this->_companyName;
  5831.     }
  5832.     /**
  5833.      * @return AppUser|\App\Repository\user|null
  5834.      */
  5835.     public function getUserResponsableAccount()
  5836.     {
  5837.         return $this->_userResponsableAccount;
  5838.     }
  5839.     /**
  5840.      * @return bool
  5841.      */
  5842.     public function isIsFreemium(): bool
  5843.     {
  5844.         return $this->_isFreemium;
  5845.     }
  5846.     /**
  5847.      * @return bool
  5848.      */
  5849.     public function isIsOlder(): bool
  5850.     {
  5851.         return $this->_isOlder;
  5852.     }
  5853.     /**
  5854.      * @return bool
  5855.      */
  5856.     public function isIsResponsable(): bool
  5857.     {
  5858.         return $this->_isResponsable;
  5859.     }
  5860.     /**
  5861.      * @return bool
  5862.      */
  5863.     public function isIsAdmin(): bool
  5864.     {
  5865.         return $this->_isAdmin;
  5866.     }
  5867.     /**
  5868.      * @return CallApi
  5869.      */
  5870.     public function getApi(): CallApi
  5871.     {
  5872.         return $this->_api;
  5873.     }
  5874.     /**
  5875.      * @return mixed
  5876.      */
  5877.     public function getConfProAbono()
  5878.     {
  5879.         return $this->_confProAbono;
  5880.     }
  5881.     /**
  5882.      * @return mixed
  5883.      */
  5884.     public function getUrlProAbono()
  5885.     {
  5886.         return $this->_urlProAbono;
  5887.     }
  5888.     /**
  5889.      * @return mixed
  5890.      */
  5891.     public function getUrlBackOfficeProAbono()
  5892.     {
  5893.         return $this->_urlBackOfficeProAbono;
  5894.     }
  5895.     /**
  5896.      * @return mixed
  5897.      */
  5898.     public function getTokenProAbono()
  5899.     {
  5900.         return $this->_tokenProAbono;
  5901.     }
  5902.     /**
  5903.      * @return mixed
  5904.      */
  5905.     public function getSegmentProAbono()
  5906.     {
  5907.         return $this->_segmentProAbono;
  5908.     }
  5909.     /**
  5910.      * @return array|false
  5911.      */
  5912.     public function getProAbonoUserState()
  5913.     {
  5914.         return $this->_proAbonoUserState;
  5915.     }
  5916.     /**
  5917.      * @return mixed|null
  5918.      */
  5919.     public function getIdCustomer()
  5920.     {
  5921.         return $this->_idCustomer;
  5922.     }
  5923.     /**
  5924.      * @return mixed|null
  5925.      */
  5926.     public function getIdSubscription()
  5927.     {
  5928.         return $this->_idSubscription;
  5929.     }
  5930.     /**
  5931.      * @return bool
  5932.      */
  5933.     public function isPropalExists(): bool
  5934.     {
  5935.         return $this->_propalExists;
  5936.     }
  5937.     /**
  5938.      * @return int|null
  5939.      */
  5940.     public function getPropalNb(): ?int
  5941.     {
  5942.         return $this->_propalNb;
  5943.     }
  5944.     /**
  5945.      * @return mixed
  5946.      */
  5947.     public function getIdBusiness()
  5948.     {
  5949.         return $this->_idBusiness;
  5950.     }
  5951.     /**
  5952.      * @param mixed $idBusiness
  5953.      */
  5954.     public function setIdBusiness($idBusiness): void
  5955.     {
  5956.         $this->_idBusiness $idBusiness;
  5957.     }
  5958.     /**
  5959.      * @return mixed
  5960.      */
  5961.     public function getIsEngaged()
  5962.     {
  5963.         return $this->_isEngaged;
  5964.     }
  5965.     /**
  5966.      * @param mixed $IsEngaged
  5967.      */
  5968.     public function setIsEngaged($IsEngaged): void
  5969.     {
  5970.         $this->_isEngaged $IsEngaged;
  5971.     }
  5972.     /**
  5973.      * @return bool
  5974.      */
  5975.     public function getIsTerminated(): bool
  5976.     {
  5977.         return $this->_isTerminated;
  5978.     }
  5979.     /**
  5980.      * @param bool $isTerminated
  5981.      */
  5982.     public function setIsTerminated(bool $isTerminated): void
  5983.     {
  5984.         $this->_isTerminated $isTerminated;
  5985.     }
  5986.     /**
  5987.      * @param $request
  5988.      * @param $session
  5989.      * @param $pageNumber
  5990.      * @return array
  5991.      * @throws Exception
  5992.      */
  5993.     public function hoursRecherche($request$session$pageNumber)
  5994.     {
  5995.         /** @var $session SessionInterface */
  5996.         $hourServices = new RechercheHourServices();
  5997.         $params = [
  5998.             'responsableFilter' => $hourServices->responsableFilter($request->query->get('responsable'null)),
  5999.             'companyFilter' => $hourServices->idCompanyFilter($request->query->get('client'null)),
  6000.             'typehoursFilter' => $hourServices->typeHoursFilter($request->query->get('typeHours'null)),
  6001.             'statusHoursFilter' => $hourServices->statusHoursFilter($request->query->get('statusHours'null)),
  6002.             'echeanceFilter' => $hourServices->echeanceFilter($request->query->get('datedebut'null), $request->query->get('datefin'null), $request->query->get('statusHours'null), $request->query->get('typeHours'null)),
  6003.             'retardFilter' => $hourServices->retardFilter($request->query->get('retard'null)),
  6004.             'stopFilter' => $hourServices->stopFilter($request->query->get('stop'null)),
  6005.             'futurFilter' => $hourServices->futurFilter($request->query->get('futur'null)),
  6006.             'historicFilter' => $hourServices->historicFilter($request->query->get('historic'null)),
  6007.             'creatorFilter' => $hourServices->creatorFilter($request->query->get('creator'null))
  6008.         ];
  6009.         $filters '';
  6010.         foreach ($params as $filter) {
  6011.             if ($filter !== null) {
  6012.                 $filters .= $filter.' AND ';
  6013.             }
  6014.         }
  6015.         $filters substr_replace($filters'', -5);
  6016.         if($request->query->get('orderby'null) != null &&  $request->query->get('columnorderby'null) != null)
  6017.         {
  6018.             $orderBy "ORDER BY ah.".$request->query->get('columnorderby'null)." ".$request->query->get('orderby'null);
  6019.         }
  6020.         else
  6021.         {
  6022.             $orderBy "ORDER BY ah.accountHoursDateDue desc,  ah.accountHoursDateStart desc";
  6023.         }
  6024.         $count $hourServices->getCount($filters);
  6025.         $sum $hourServices->getSumValue($filters);
  6026.         $nbrOfPage intval(ceil($countBaseController::$NBRPERPAGE100));
  6027.         //RechercheFunctions::send_annexe_url($this, $count, $pageNumber, 'societe');
  6028.         $result $hourServices->getResult($filters$orderBy,$pageNumberBaseController::$NBRPERPAGE100);
  6029.         return [
  6030.             'result' => $result,
  6031.             'nbrOfPage' => $nbrOfPage,
  6032.             'count' => $count,
  6033.             'sum'=>$sum
  6034.         ];
  6035.     }
  6036. }