<?php
namespace App\Controller;
use App\Entity\AppAccount;
use App\Entity\AppAccountBankDetails;
use App\Entity\AppAccountHour;
use App\Entity\AppAccountHourType;
use App\Entity\AppAccountHourStatus;
use App\Entity\AppAccountResiliation;
use App\Entity\AppAccountTermination;
use App\Entity\AppAccountTerminationComment;
use App\Entity\AppAccountTerminationStatus;
use App\Entity\AppCustomFieldValue;
use App\Entity\AppMailAccount;
use App\Entity\AppMailAccountBox;
use App\Entity\AppMailServer;
use App\Entity\AppMailTemplate;
use App\Entity\AppService;
use App\Entity\AppServiceCategory;
use App\Entity\AppServiceMarketing;
use App\Entity\AppTermsOfService;
use App\Entity\AppUser;
use App\Entity\AppUserType;
use App\Entity\AppUserTypeAdmin;
use App\Entity\coefficy2\AppHistoryEvent;
use App\Entity\coefficy2\AppHistoryUser;
use App\Entity\RegCompany;
use App\Repository\ActionLinkServices;
use App\Repository\AdministrationServices;
use App\Repository\AppAccountBankDetailsServices;
use App\Repository\AppAccountHoursServices;
use App\Repository\AppAccountTerminationServices;
use App\Repository\AppCustomFieldServices;
use App\Repository\AppHistoryEventServices;
use App\Repository\AppMailAccountServices;
use App\Repository\AppMailServerServices;
use App\Repository\AppMailTemplateServices;
use App\Repository\AppServiceTermServices;
use App\Repository\AppTermsOfServiceServices;
use App\Repository\AppUserServices;
use App\Repository\AppUserTypeAdminServices;
use App\Repository\AppUserTypeServices;
use App\Repository\campaign\CampaignApiServices;
use App\Repository\campaign\CamPersonaServices;
use App\Repository\CompanyServices;
use App\Repository\ConnectionServices;
use App\Repository\CrmOpportunityServices;
use App\Repository\CrmRelaunchServices;
use App\Repository\eliott2\ApiAccountServices;
use App\Repository\EncryptionService;
use App\Repository\GenericFunctions;
use App\Repository\LeadformServices;
use App\Repository\LeBonLogicielServices;
use App\Repository\RegCountryServices;
use App\Repository\RoutineServices;
use App\Repository\SessionUtilisateur;
use App\Repository\Services_coefficy_utilisateurs;
use App\Repository\SshCommandServices;
use App\Repository\StaticData;
use App\Repository\AppAccountServices;
use App\Repository\RegCompanyServices;
use App\Entity\AppServiceType;
use App\Repository\AppServiceServices;
use App\Repository\AppAccountTypeServices;
use App\Entity\AppAccountType;
use App\Repository\TrackingAbonnementServices;
use Cassandra\Date;
use DateTimeZone;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
use Exception;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use ReflectionClass;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\CallApi;
use DateTime;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use App\Repository\RechercheHourServices;
/**
* Class AbonnementController
* @package App\Controller
*/
class AbonnementController extends BaseController
{
private $_request;
private $_session;
private $_user;
private $_idAccount;
private $_siren;
private $_referenceCustomer;
private $_accountTitle;
private $_companyName;
private $_userResponsableAccount;
private $_isFreemium;
private $_isOlder;
private $_isResponsable;
private $_isAdmin;
public $_isTerminated;
private $_api;
private $_confProAbono;
private $_urlProAbono;
private $_urlBackOfficeProAbono;
private $_tokenProAbono;
private $_segmentProAbono;
private $_urlAfterSynchro;
private $idBusiness;
private $_idAccountProabono;
private $_urlBackOfficeProabonoWithService;
private $_proAbonoUserState;
private $_idCustomer;
private $_idSubscription;
private $_isTrial;
private $_isEngaged;
private $_propalExists;
private $_propalNb;
private $_deleteCgv;
private $_refresh;
private $_isDisabled;
function __construct(RequestStack $requestStack, SessionInterface $session, ContainerInterface $container = null) {
date_default_timezone_set('UTC');
$this->container = $container;
$this->_session = $session;
$this->_request = $requestStack->getCurrentRequest();
$routinesRoute = array(
"new" => "newRoutine",
"update" => "updateRoutine",
"delete" => "DeleteRoutine"
);
$go = true;
// Si on appelle la route refresh directement (sans id), on bloque
if($this->_request->get("_route") == "abonnement_proabono_refresh"){
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
// Si on trigger/forward un refresh, pas besoin de calculs
if($this->_request->get("_route") == "trigger_refresh" or is_null($this->_request->get("_route"))){
$go = false;
}
if($go) {
SessionUtilisateur::checkUtilisateur($this->_session);
SessionUtilisateur::reload($this->_session);
$this->_user = $this->_session->get('user');
$this->setAttribute("user", $this->_user);
// Si on est pas responsable, on peut pas accéder à la partie abonnement
if (!in_array($this->_user['idUserType'], AppUserType::UT_RESPONSABLE)) {
// Sauf si routines
if(!in_array($this->_request->get("_route"),$routinesRoute)){
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
}
$this->_idAccount = null;
//$this->_isAdmin = (!SessionUtilisateur::isAdmin($this->_user)) ? false : (($this->_user['idCompany'] == RegCompany::COEFFICY) ? true : false);
$this->_isAdmin = (!SessionUtilisateur::isAdmin($this->_user)) ? false : ($this->_user['supportMode'] ? true : (in_array(AppService::ACCES_BACKOFFICE, $session->get('user')['services']) ? true : false));
$this->setAttribute("isAdmin", $this->_isAdmin);
$this->_isResponsable = SessionUtilisateur::isResponsable($this->_user);
$this->setAttribute("isResponsable", $this->_isResponsable);
if ($this->_isAdmin) {
if ($this->_request->query->has("idAccount")) {
if (AppAccountServices::getAccount($this->_request->query->get("idAccount"))) {
$idAccountCustomer = AppAccountServices::getAccount($this->_request->query->get("idAccount"));
$this->_idAccount = $this->_request->query->get("idAccount");
$this->_isFreemium = ($idAccountCustomer->getType()->getId() == AppAccountType::REFERRAL);
$this->_userResponsableAccount = AppUserServices::getUserResponsableAccount($this->_request->query->get("idAccount"), AppAccount::VenteCoeff);
$this->_companyName = $idAccountCustomer->getCompanyName();
if ($idAccountCustomer->getIdCompany() == RegCompany::COEFFICY or $idAccountCustomer->getIdCompany() == RegCompany::BUSINESS_SHARE) {
$this->_referenceCustomer = $idAccountCustomer->getSiren() . substr($idAccountCustomer->getId(), 0, 41);
$this->_siren = $idAccountCustomer->getSiren();
} else {
if (is_null($idAccountCustomer->getIdCompany())) {
$this->_referenceCustomer = null;
$this->_siren = null;
} else {
$this->_referenceCustomer = RegCompanyServices::getCompany(AppAccountServices::getAccount($this->_request->query->get("idAccount"))->getIdCompany())->getIdentifiedNumber();
$this->_siren = RegCompanyServices::getCompany(AppAccountServices::getAccount($this->_request->query->get("idAccount"))->getIdCompany())->getIdentifiedNumber();
}
}
} else {
throw $this->createNotFoundException("L'abonnement n'existe pas.");
}
} else {
$this->_isFreemium = (SessionUtilisateur::getTypeAbonnement($this->_user) == AppAccountType::REFERRAL);
$this->_userResponsableAccount = AppUserServices::getUserResponsableAccount($this->_user['idAccount'], AppAccount::VenteCoeff);
$this->_companyName = $this->_user['companyName'];
$this->_idAccount = $this->_user['idAccount'];
if ($this->_user['idCompany'] == RegCompany::COEFFICY or $this->_user['idCompany'] == RegCompany::BUSINESS_SHARE) {
$this->_referenceCustomer = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber() . substr($this->_idAccount, 0, 41);
$this->_siren = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
} else {
if (is_null($this->_user['idCompany'])) {
$this->_referenceCustomer = null;
$this->_siren = null;
} else {
$this->_referenceCustomer = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
$this->_siren = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
}
}
}
} else {
$this->_isFreemium = (SessionUtilisateur::getTypeAbonnement($this->_user) == AppAccountType::REFERRAL);
$this->_userResponsableAccount = AppUserServices::getUserResponsableAccount($this->_user['idAccount'], AppAccount::VenteCoeff);
$this->_companyName = $this->_user['companyName'];
$this->_idAccount = $this->_user['idAccount'];
if ($this->_user['idCompany'] == RegCompany::COEFFICY or $this->_user['idCompany'] == RegCompany::BUSINESS_SHARE) {
$this->_referenceCustomer = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber() . substr($this->_idAccount, 0, 41);
$this->_siren = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
} else {
if (is_null($this->_user['idCompany'])) {
$this->_referenceCustomer = null;
$this->_siren = null;
} else {
$this->_referenceCustomer = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
$this->_siren = RegCompanyServices::getCompany($this->_user['idCompany'])->getIdentifiedNumber();
}
}
}
$this->_isEngaged = false;
$this->_accountTitle = AppAccountServices::getAccount($this->_idAccount)->getType()->getTitle();
$this->setAttribute("accountTitle", $this->_accountTitle);
$this->setAttribute("isFreemium", $this->_isFreemium);
$this->setAttribute('userResponsableAccount', $this->_userResponsableAccount);
$this->setAttribute("siren", $this->_siren);
$this->setAttribute("referenceCustomer", $this->_referenceCustomer);
$this->setAttribute("companyName", $this->_companyName);
$this->setAttribute("idAccount", $this->_idAccount);
$this->_confProAbono = BaseController::getConfig()['proabono-api'];
$this->_urlProAbono = $this->_confProAbono['url'];
$this->setAttribute("urlProAbono", $this->_urlProAbono);
$this->_urlBackOfficeProAbono = $this->_confProAbono['url-backOffice'];
$this->setAttribute("urlBackOfficeProAbono", $this->_urlBackOfficeProAbono);
$this->_tokenProAbono = $this->_confProAbono['token'];
$this->_segmentProAbono = $this->_confProAbono['ref-segment'];
$this->_urlAfterSynchro = $this->_confProAbono['urlAfterSynchro'];
$this->_idBusiness = $this->_confProAbono['idBusiness'];
$this->_idAccountProabono = $this->_confProAbono['idAccount'];
$this->_urlNewBackOffice = $this->_confProAbono['urlNewBackOffice'];
$this->setAttribute("urlNewBackOffice", $this->_urlNewBackOffice);
$this->_api = new CallApi();
$this->_propalExists = false;
$this->_propalNb = null;
$this->_idSubscription = null;
$this->_idCustomer = null;
$this->_isOlder = false;
$this->_isTerminated = false;
$this->_isDisabled = false;
if($this->_request->get("_route") != 'Abonnement_parametre') {
$this->_proAbonoUserState = $this->getOffres($this->_api, $this->_urlBackOfficeProAbono, $this->_urlProAbono, $this->_tokenProAbono, $this->_referenceCustomer, $this->_idBusiness);
if ($this->_proAbonoUserState) {
$this->setAttribute('propal', $this->_proAbonoUserState["propal"]);
$this->setAttribute('isTrial', $this->_isTrial);
$this->_idCustomer = $this->_proAbonoUserState['IdCustomer'];
$this->_idSubscription = $this->_proAbonoUserState["current"]['IdActiveSubscription'];
$this->setAttribute('idCustomer', $this->_idCustomer);
if (is_null($this->_idSubscription)) {
$this->_isOlder = true;
$this->_isFreemium = false;
$this->setAttribute('isOlder', true);
} else {
$this->setAttribute('idSubscription', $this->_idSubscription);
}
$this->setAttribute('isOlder', $this->_isOlder);
if (count($this->_proAbonoUserState["propal"]) > 0) {
$this->_propalExists = true;
$this->_propalNb = count($this->_proAbonoUserState["propal"]);
}
$this->setAttribute("propalExists", $this->_propalExists);
$this->setAttribute("propalNb", $this->_propalNb);
}
else
{
$this->setAttribute('isOlder', $this->_isOlder);
}
}
$this->setAttribute('isDisabled',$this->_isDisabled);
$this->_deleteCgv = false;
$this->_refresh = false;
}
}
function cancelTermination($id,$nameOffer){
$terminationInProgress = AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($id);
if($terminationInProgress){
if($terminationInProgress->getTerminationStatus()->getIdTerminationStatus() == AppAccountTerminationStatus::EN_RESILIATION){
$terminationCancellationDate = new DateTime("today");
$termination = new AppAccountTermination(
$terminationInProgress->getIdTermination(),
$this->_idAccount,
$terminationInProgress->getIdSubscription(),
new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE),
$terminationInProgress->getTerminationReceptionDate(),
$terminationCancellationDate,
$terminationInProgress->getTerminationDate(),
null
);
$comment = new AppAccountTerminationComment(
null,
$terminationInProgress->getIdTermination(),
new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE),
AppUserServices::getUser(AppUser::ELIOTT_ID_USER),
"La résiliation a été annulée suite à la souscription du client à l'offre <strong>".$nameOffer."</strong>.",
null
);
AppAccountTerminationServices::setTermination($termination);
AppAccountTerminationServices::setComment($comment);
}
}
}
/**
* @Route("/Abonnement", name="Abonnement")
* @Route("/Abonnement", name="abonnement")
* @return Response
*
* @throws Exception
*/
public function index(Request $request)
{
try{
$this->setAttribute('shownPart','abonnement');
$this->setAttribute('search', $request->get('search'));
$ajax = false;
if($this->_isAdmin){
if($this->_request->query->has("idc")){
if(!empty($this->_request->query->get("idc"))){
if($this->_request->query->get("idc") != $this->_idCustomer){
$retrieve = $this->_api->callApi("GET", $this->_urlBackOfficeProAbono . "/Distribution/Customers/".$this->_request->query->get("idc")."?IdBusiness=".$this->_idBusiness, $this->_tokenProAbono, false);
if($retrieve[1] == 200){
$referenceCustomer = $retrieve[0]['ReferenceCustomer'];
if (strpos($referenceCustomer, "814045571") !== false) {
$keyword = str_replace("814045571", "", $referenceCustomer);
$appAccount = AppAccountServices::getAccountByKeyword($keyword);
} else if (strpos($referenceCustomer, "749836292") !== false) {
$keyword = str_replace("749836292", "", $referenceCustomer);
$appAccount = AppAccountServices::getAccountByKeyword($keyword);
} else {
$appAccount = AppAccountServices::getAccountBySiren($referenceCustomer);
}
return $this->redirect($this->generateUrl(
'Abonnement',
array("idAccount" => $appAccount->getId())
));
}
}
}
}
}
if($this->_deleteCgv){
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
foreach ($appAccount->getUsers() as $user) {
$delete = Services_coefficy_utilisateurs::deleteLastCgv($user);
}
}
if(!$this->_isOlder){
if(array_key_exists("Metadata",$this->_proAbonoUserState['current']['subscription']) &&
array_key_exists("previousPropal",$this->_proAbonoUserState['current']['subscription']['Metadata'])){
$msg = "La souscription à l'offre " . "<strong>" . $this->_proAbonoUserState['current']['subscription']['TitleLocalized'] . "</strong>" . " a bien été validée.";
$this->setAttribute('msgAfterSubscription', $msg);
$this->setAttribute('iconAfterSubscription', "checked");
$this->_refresh = true;
$id = $this->_proAbonoUserState['current']['subscription']['Metadata']['previousPropal'];
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/" . $id.'?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
if($this->_propalNb > 0){
if ($this->_propalNb == 1) {
$this->_proAbonoUserState['propal'] = [];
$this->_propalExists = false;
}
else{
unset($this->_proAbonoUserState['propal'][$id]);
}
$this->_propalNb--;
}
$newMetadatas['Metadata'] = $this->_proAbonoUserState['current']['subscription']['Metadata'];
unset($newMetadatas['Metadata']['previousPropal']);
$update = $this->_api->callApi("PATCH", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/" . $this->_idSubscription. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, json_encode($newMetadatas));
$countSubscriptions = $this->_api->callApi("GET", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$this->_idCustomer, $this->_tokenProAbono, false);
if($countSubscriptions[1] == 200){
$this->renameSubscription($this->_proAbonoUserState['current']['subscription']['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
}
}
$this->setAttribute("propalExists", $this->_propalExists);
$this->setAttribute("propalNb", $this->_propalNb);
}
if($this->_refresh){
$this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
$this->setAttribute('isAdmin',$this->_isAdmin);
if($this->_request->isMethod("POST")){
if($this->_request->request->has("ajax")){
if($this->_request->request->get("ajax") == "true"){
$ajax = true;
}
}
if($this->_request->request->has('addEditTermination')) {
if($this->_isFreemium or !$this->_isAdmin or $this->_isOlder or $this->_isDisabled){
$this->addFlash('error', "Impossible de saisir une demande de résiliation.");
}
else{
$post = $this->_request->request->get('addEditTermination');
if(isset($post['status']) and !empty($post['status']) and isset($post['action']) and !empty($post['action']) ){
if(isset($post['attachmentURL']) and !empty($post['attachmentURL']) and filter_var($post['attachmentURL'],FILTER_VALIDATE_URL) and isset($post['comment']) and !empty($post['comment'])) {
if($post['action'] == "new"){
if ($post['status'] == AppAccountTerminationStatus::EN_RESILIATION) {
if(isset($post['dateTermination']) and !empty($post['dateTermination'])
and isset($post['dateReception']) and !empty($post['dateReception'])){
$tomorrow = new DateTime("tomorrow");
$afterTomorrow = new DateTime("tomorrow + 1 day");
$dateTermination = DateTime::createFromFormat('d/m/Y', $post['dateTermination']);
$dateReception = DateTime::createFromFormat('d/m/Y', $post['dateReception']);
if($dateTermination->getTimestamp() >= $afterTomorrow->getTimeStamp() and $dateReception->getTimestamp() < $tomorrow->getTimestamp()){
$termination = new AppAccountTermination(
null,
$this->_idAccount,
$this->_idSubscription,
new AppAccountTerminationStatus(AppAccountTerminationStatus::EN_RESILIATION),
DateTime::createFromFormat('d/m/Y', $post['dateReception']),
null,
DateTime::createFromFormat('d/m/Y', $post['dateTermination']),
null
);
$idTermination = AppAccountTerminationServices::setTermination($termination);
if($idTermination){
$comment = new AppAccountTerminationComment(
null,
$idTermination,
$termination->getTerminationStatus(),
AppUserServices::getUser($this->_user['idUser']),
$post['comment'],
$post['attachmentURL']
);
if(AppAccountTerminationServices::setComment($comment)){
$this->addFlash('success', "La demande de résiliation a bien été enregistrée.");
}
else{
$this->addFlash('error', "Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
}
}
else{
$this->addFlash('error', "La date de fin d'abonnement est erronée.");
}
}
else{
$this->addFlash('error', "La date de fin d'abonnement est manquante.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée lors de l'enregistrement de la demande de résiliation.");
}
}
else if($post['action'] == 'update'){
if(isset($post['idTermination']) and !empty($post['idTermination']) and isset($post['idComment']) and !empty($post['idComment'])) {
$comment = AppAccountTerminationServices::getCommentByIdComment($post['idComment']);
$termination = AppAccountTerminationServices::getTerminationByIdTermination($post['idTermination']);
if ($comment and $termination) {
if ($post['status'] == AppAccountTerminationStatus::EN_RESILIATION) {
if (isset($post['dateTermination']) and !empty($post['dateTermination'])
and isset($post['dateReception']) and !empty($post['dateReception'])) {
$tomorrow = new DateTime("tomorrow");
$afterTomorrow = new DateTime("tomorrow + 1 day");
$dateTermination = DateTime::createFromFormat('d/m/Y', $post['dateTermination']);
$dateReception = DateTime::createFromFormat('d/m/Y', $post['dateReception']);
if($dateTermination->getTimestamp() >= $afterTomorrow->getTimeStamp() and $dateReception->getTimestamp() < $tomorrow->getTimestamp()) {
$newComment = new AppAccountTerminationComment(
$comment->getIdComment(),
$termination->getIdTermination(),
$termination->getTerminationStatus(),
$comment->getUser(),
$post['comment'],
$post['attachmentURL']
);
$updatedTermination = new AppAccountTermination(
$termination->getIdTermination(),
$termination->getIdAccount(),
$termination->getIdSubscription(),
$termination->getTerminationStatus(),
DateTime::createFromFormat('d/m/Y', $post['dateReception']),
null,
DateTime::createFromFormat('d/m/Y', $post['dateTermination']),
$termination->getComments()
);
if (AppAccountTerminationServices::setComment($newComment) and AppAccountTerminationServices::setTermination($updatedTermination)) {
$this->addFlash('success', "La demande de résiliation a bien été mise à jour.");
} else {
$this->addFlash('error', "Une erreur a été rencontrée lors de la mise à jour de la demande de résiliation.");
}
}
else{
$this->addFlash('error', "La date de fin d'abonnement est erronée.");
}
} else {
$this->addFlash('error', "La date de fin d'abonnement est manquante.");
}
} else if ($post['status'] == AppAccountTerminationStatus::ANNULE) {
if (isset($post['dateReception']) and !empty($post['dateReception'])) {
$tomorrow = new DateTime("tomorrow");
$dateReception = DateTime::createFromFormat('d/m/Y', $post['dateReception']);
if($dateReception->getTimestamp() < $tomorrow->getTimestamp()) {
$newStatus = new AppAccountTerminationStatus(AppAccountTerminationStatus::ANNULE);
$updatedComment = new AppAccountTerminationComment(
null,
$termination->getIdTermination(),
$newStatus,
$comment->getUser(),
$post['comment'],
$post['attachmentURL']
);
$updatedTermination = new AppAccountTermination(
$termination->getIdTermination(),
$termination->getIdAccount(),
$termination->getIdSubscription(),
$newStatus,
$termination->getTerminationReceptionDate(),
DateTime::createFromFormat('d/m/Y', $post['dateReception']),
$termination->getTerminationDate(),
$termination->getComments()
);
if (AppAccountTerminationServices::setComment($updatedComment) and AppAccountTerminationServices::setTermination($updatedTermination)) {
$this->addFlash('success', "La demande d'annulation a bien été prise en compte.");
} else {
$this->addFlash('error', "Une erreur a été rencontrée lors de l'annulation de la demande de résiliation.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
} else {
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
} else {
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash('error', "Certains champs sont manquants.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash('error', "Certains éléments du formulaire sont manquants.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
if($this->_request->query->has("idAccount")) {
return $this->redirect($this->generateUrl(
'Abonnement',
array("idAccount" => $this->_idAccount)
));
}
else{
return $this->redirect("/Abonnement");
}
}
else if($this->_request->request->has('updateComment')) {
if($this->_isFreemium or !$this->_isAdmin or $this->_isOlder or $this->_isDisabled){
$this->addFlash('error', "Impossible de saisir une demande de résiliation.");
}
else{
$post = $this->_request->request->get('updateComment');
if(!isset($post['attachment']) or empty($post['attachment']) or !filter_var($post['attachment'],FILTER_VALIDATE_URL)){
$this->addFlash('error', "L'URL de la pièce jointe est manquant ou incorrect.");
}
else if(!isset($post['content']) or empty($post['content'])){
$this->addFlash('error', "Le commentaire est manquant ou incorrect.");
}
else if((!isset($post['idComment']) or empty($post['idComment'])) or (!isset($post['idTermination']) or empty($post['idTermination']))){
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
else{
$comment = AppAccountTerminationServices::getCommentByIdComment($post['idComment']);
if($comment){
$updatedComment = new AppAccountTerminationComment(
$post['idComment'],
$post['idTermination'],
$comment->getTerminationStatus(),
$comment->getUser(),
$post['content'],
$post['attachment']
);
if(AppAccountTerminationServices::setComment($updatedComment)){
$this->addFlash('success', "Le commentaire a été mis à jour.");
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
}
if($this->_request->query->has("idAccount")) {
return $this->redirect($this->generateUrl(
'Abonnement',
array("idAccount" => $this->_idAccount)
));
}
else{
return $this->redirect("/Abonnement");
}
}
}
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount', $appAccount);
if($this->_session->has("msgFlashSubscription") && $this->_session->get("msgFlashSubscription") !== false){
$this->setAttribute("msgAfterSubscription",$this->_session->get("msgFlashSubscription"));
}
if($this->_session->has("iconFlashSubscription") && $this->_session->get("iconFlashSubscription") !== false){
$this->setAttribute("iconAfterSubscription",$this->_session->get("iconFlashSubscription"));
}
$this->_session->set("msgFlashSubscription",false);
$this->_session->set("iconFlashSubscription",false);
if(!$this->_isOlder){
$AllGuarantee = [];
if(isset($this->_proAbonoUserState["current"]['subscription']['Features'])) {
foreach ($this->_proAbonoUserState["current"]['subscription']['Features'] as $key => $Feature) {
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Feature?ReferenceFeature=" . $Feature['ReferenceFeature'], $this->_tokenProAbono, false);
if ($data[1] == 200) {
if (isset($data[0]['Metadata']['GuaranteeWording'])) {
$Guarantee['GuaranteeWording'] = $data[0]['Metadata']['GuaranteeWording'];
$Guarantee['GuaranteeText'] = $data[0]['Metadata']['GuaranteeText'];
$Guarantee['GuaranteeText2'] = $data[0]['Metadata']['GuaranteeText2'];
array_push($AllGuarantee, $Guarantee);
}
}
}
$this->_proAbonoUserState["current"]['subscription']['Guarantees'] = $AllGuarantee;
}
else{
$this->_proAbonoUserState["current"]['subscription']['Features'] = [];
}
$this->setAttribute('proAbonoUserState', $this->_proAbonoUserState);
$this->setAttribute('current',$this->_proAbonoUserState["current"]);
$this->setAttribute('outOfBundle',$this->_proAbonoUserState["current"]["outOfBundle"]);
$this->setAttribute('terminationStatutes',AppAccountTerminationServices::getTerminationStatus());
$actual_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$countTerminations = AppAccountTerminationServices::getCountTerminations($appAccount);
$nbrPages = intval(ceil($countTerminations / self::$NBRPERPAGE));
if ($this->_request->query->has("pTerminations") and $this->_request->query->get("pTerminations") != "") {
$p = $this->_request->query->get("pTerminations");
if (strpos($actual_url, "&pTerminations=") !== false) {
$url_sans_page = str_replace('&pTerminations=' . urlencode($p), '&pTerminations=', $actual_url);
}
else if (strpos($actual_url, "?pTerminations=") !== false) {
$url_sans_page = str_replace('?pTerminations=' . urlencode($p), '?pTerminations=', $actual_url);
}
if(intval($p) === 0){
$p = 1;
}
} else {
$p = 1;
if(empty($_SERVER['QUERY_STRING'])){
$url_sans_page = $actual_url . "?pTerminations=";
}
else{
$url_sans_page = $actual_url . "&pTerminations=";
}
}
if($p > $nbrPages){
$p = 1;
}
if (strpos($url_sans_page, "&pTerminations=") !== false) {
$url_premiere_page = str_replace('&pTerminations=', '&pTerminations=1', $url_sans_page);
$url_derniere_page = str_replace('&pTerminations=', '&pTerminations='.$nbrPages, $url_sans_page);
}
else if (strpos($url_sans_page, "?pTerminations=") !== false){
$url_premiere_page = str_replace('?pTerminations=', '?pTerminations=1', $url_sans_page);
$url_derniere_page = str_replace('?pTerminations=', '?pTerminations='.$nbrPages, $url_sans_page);
}
else{
$url_premiere_page = $url_sans_page . '?pTerminations=1';
$url_derniere_page = $url_sans_page . '?pTerminations=' . $nbrPages;
}
$offset = ($p - 1) * self::$NBRPERPAGE;
$this->setAttribute('currentSubscriptionTerminationStatus',AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($this->_idSubscription));
$this->setAttribute('url_sans_page',$url_sans_page);
$this->setAttribute('url_premiere_page',$url_premiere_page);
$this->setAttribute('url_derniere_page',$url_derniere_page);
$this->setAttribute('numero_de_page',$p);
$this->setAttribute('countTerminations',$countTerminations);
$this->setAttribute('nbrPages',$nbrPages);
$this->setAttribute('terminations',AppAccountTerminationServices::getTerminations($appAccount,$offset,self::$NBRPERPAGE));
}
}
catch(Exception $e){
if($ajax){
return new JsonResponse(array(
'status' => 404
));
}
else{
if($e->getCode() == 01){
$this->setAttribute("error", $e->getMessage());
}
else{
$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.");
}
}
}
if($ajax){
return $this->render('abonnement/onglets/abonnement/abonnement_abonnement.html.twig', $this->attribute);
}
else{
return $this->render('abonnement/index.html.twig', $this->attribute);
}
}
/**
* @Route("/Abonnement/Propal", name="Abonnement_propal")
* @Route("/Abonnement/Propal", name="abonnement_propal")
* @return Response
*
* @throws Exception
*/
public function abonnementPropal(Request $request)
{
$this->setAttribute('shownPart','propal');
$this->setAttribute('search', $request->get('search'));
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if(empty($this->_proAbonoUserState["propal"])){
throw new Exception("Il n'y a pas de propositions commerciales.",01);
}
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount',$appAccount);
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/Update", name="Abonnement_update")
* @Route("/Abonnement/Update", name="abonnement_update")
* @return Response
*
* @throws Exception
*/
public function abonnementUpdate(Request $request)
{
$this->setAttribute('shownPart','update');
$this->setAttribute('search', $request->get('search'));
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
$servicesCategories = AppServiceServices::getServicesCategories();
if($this->_request->query->has("action")){
if($this->_request->query->get("action") == "adjust"){
if($this->_isOlder){
throw new Exception("La page demandée n'existe pas",01);
}
else if($this->_isFreemium or $this->_isTerminated or $this->_isDisabled){
throw new Exception("Désolé mais votre abonnement ne peut pas être modifié.",01);
}
}
else if($this->_request->query->get("action") == "subscribe"){
if(empty($this->_proAbonoUserState['propal'])){
throw new Exception("La page demandée n'existe pas",01);
}
if (!is_null($this->_request->query->get('id'))){
$propalArrayKey = intval($this->_request->query->get('id'));
if(array_key_exists($propalArrayKey,$this->_proAbonoUserState["propal"])){
$currentPropal = $this->_proAbonoUserState["propal"][$propalArrayKey];
$this->setAttribute('currentPropal', $currentPropal);
}
else{
throw new Exception("La proposition commerciale demandée n'existe pas.",01);
}
}else{
throw new Exception("La proposition commerciale demandée n'existe pas.",01);
}
}
else if($this->_request->query->get("action") == "delayed"){
if(!empty($this->_proAbonoUserState['delayed'])){
$this->setAttribute('currentPropal', $this->_proAbonoUserState['delayed']);
}
else{
throw new Exception("La page demandée n'existe pas",01);
}
}
else{
throw new Exception("La page demandée n'existe pas",01);
}
}
$Newsletter6Actif = false;
$Newsletter12Actif = false;
if(isset($this->_proAbonoUserState['current']['subscription']['Features']))
{
$AllGuarantee = [];
foreach($this->_proAbonoUserState['current']['subscription']['Features'] as $key => $Feature)
{
if($Feature['ReferenceFeature'] == AppServiceMarketing::NEWSLETTER6)
{
$indexNewsletter6 = $key;
if($Feature['IsEnabled'])
{
$Newsletter6Actif = true;
}
}
if($Feature['ReferenceFeature'] == AppServiceMarketing::NEWSLETTER12)
{
$indexNewsletter12 = $key;
if($Feature['IsEnabled'])
{
$Newsletter12Actif = true;
}
}
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Feature?ReferenceFeature=".$Feature['ReferenceFeature'], $this->_tokenProAbono, false);
if($data[1] == 200)
{
if(isset($data[0]['Metadata']['GuaranteeWording']))
{
$Guarantee['GuaranteeWording'] = $data[0]['Metadata']['GuaranteeWording'];
$Guarantee['GuaranteeText'] = $data[0]['Metadata']['GuaranteeText'];
$Guarantee['GuaranteeText2'] = $data[0]['Metadata']['GuaranteeText2'];
array_push($AllGuarantee, $Guarantee);
}
}
}
$this->_proAbonoUserState["current"]['subscription']['Guarantees'] = $AllGuarantee;
}
if(isset($indexNewsletter6))
{
$this->_proAbonoUserState['current']['subscription']['Features'][$indexNewsletter6]['OtherNewsletter'] = $Newsletter12Actif;
}
if(isset($indexNewsletter12))
{
$this->_proAbonoUserState['current']['subscription']['Features'][$indexNewsletter12]['OtherNewsletter'] = $Newsletter6Actif;
}
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount',$appAccount);
$this->setAttribute('cgv', AppTermsOfService::TERMS_OF_SERVICE);
$servicesCategories = AppServiceServices::getServicesCategories();
$this->setAttribute('proAbonoUserState', $this->_proAbonoUserState);
$this->setAttribute('categories', $servicesCategories);
$this->setAttribute('countries', RegCountryServices::getCountryList());
$this->setAttribute('company', CompanyServices::getCompany($this->_user["idCompany"]));
$this->setAttribute("latestAcceptedCGV", AppTermsOfServiceServices::getContentOfLastestAcceptedCGV($this->_idAccount));
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/Utilisateur", name="Abonnement_utilisateur")
* @Route("/Abonnement/Utilisateur", name="abonnement_utilisateur")
* @return Response
*
* @throws Exception
*/
public function abonnementUtilisateurs($ajax = false,$parent = false,$id = false, SessionInterface $session, Request $request)
{
$this->setAttribute('shownPart','utilisateur');
$this->setAttribute('search', $request->get('search'));
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if($id){
$idAccount = $id;
}
else{
$idAccount = $this->_idAccount;
}
$appAccount = AppAccountServices::getAccount($idAccount);
if(empty($appAccount)){
throw $this->createNotFoundException("L'abonnement n'existe pas.");
} else{
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
$disabledUsers = [];
if(!empty($appAccount->getTermsOfService())){
foreach ($appAccount->getTermsOfService() as $term){
if(!array_key_exists($term->getIdUser(),$appAccount->getUsers())){
$user = AppUserServices::getUser($term->getIdUser());
if(!is_null($user)){
$disabledUsers[$user->getId()] = $user;
}
}
}
}
foreach ($appAccount->getUsers() as &$user){
if($this->isSupportUser($user->getEmail())){
$user->setIsSupport(true);
}
else{
$user->setIsSupport(false);
}
}
foreach ($appAccount->getServices() as &$service){
$service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
}
$this->setAttribute('appAccount', $appAccount);
$this->setAttribute('disabledUsers', $disabledUsers);
$solde = 0;
$nbLimit = 0;
if(!$this->_isOlder){
$idServiceUser = AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
$referenceFeatureUser = $idServiceUser->getIdCategory() . "-" . sprintf("%02d", $idServiceUser->getIdServiceMarketing());
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser, $this->_tokenProAbono, false);
$status = $data[1];
if($status == 200){
if(array_key_exists("QuantityIncluded",$data[0])){
$included = $data[0]['QuantityIncluded'];
}
else{
$included = INF;
}
if(array_key_exists("QuantityCurrent",$data[0])){
$current = $data[0]['QuantityCurrent'];
}
else{
$current = 0;
}
if(!is_infinite($included)){
if($data[0]['QuantityCurrent'] > $data[0]['QuantityIncluded']){
$solde = $appAccount->getServices()[AppService::NB_USER]->getSolde();
$nbLimit = $data[0]['QuantityCurrent'];
}
else{
$solde = $data[0]['QuantityIncluded'] - $data[0]['QuantityCurrent'];
$nbLimit = $data[0]['QuantityIncluded'];
}
}
else{
$solde = null;
$nbLimit = null;
}
}
}
else{
$solde = false;
$nbLimit = false;
}
$this->setAttribute('nbLimit', $nbLimit);
$this->setAttribute('solde', $solde);
$this->setAttribute('userTypes', array_filter(array_map(function($userType){
$listServiceAppAccount = array_map(function($e) {
return is_object($e) ? $e->getid() : $e->getid();
}, $this->getAttribute('appAccount')->getServices());
if(!in_array(AppService::ACCES_BACKOFFICE, $listServiceAppAccount )){
#if($this->getAttribute('appAccount')->getIdCompany() !== RegCompany::COEFFICY){
if($userType->getId() <= AppUserType::RESPONSABLE){
return $userType;
} else{
return null;
}
} else{
return $userType;
}
},AppUserTypeServices::getUserTypes()), function($item){
return !is_null($item);
}));
$this->setAttribute( 'userTypeAdmin', AppUserTypeAdminServices::getUserTypeAdmin());
}
if($this->_request->request->has('formEditUser_email'))
{
$idUserToEdit = '';
$error = false;
if($this->_request->request->has('formEditUser_id')
and !empty($this->_request->request->get('formEditUser_id'))){
$idUserToEdit = $this->_request->request->get('formEditUser_id');
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Erreur à l\'identification de l\'utilisateur.');
}
$needRefresh = false;
$licensing = false;
$outOfBundle = false;
$outOfControl = false;
if($idUserToEdit == "new")
{
$newUser = new AppUser();
if($this->_isFreemium){
if(!$this->_isAdmin and !$this->_request->query->has("idAccount")){
$error = true;
$this->addFlash('formEditUser_error', "L'abonnement REFERRAL ne permet pas d'ajouter de nouveaux utilisateurs.");
}
}
if($this->_request->request->has('formEditUser_lastName')
and !empty($this->_request->request->get('formEditUser_lastName'))){
$newUser->setLastName($this->_request->request->get('formEditUser_lastName'));
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier nom admin.');
}
if($this->_request->request->has('formEditUser_firstName')
and !empty($this->_request->request->get('formEditUser_firstName'))){
$newUser->setFirstName($this->_request->request->get('formEditUser_firstName'));
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier prénom.');
}
if($this->_request->request->has('formEditUser_email')
and !empty($this->_request->request->get('formEditUser_email'))){
if($this->isSupportUser($this->_request->request->get('formEditUser_email'))){
$error = true;
$this->addFlash('formEditUser_error', 'Veuillez utiliser le mode SUPPORT.');
}
$emailValidator = new EmailValidator();
if($emailValidator->isValid($this->_request->request->get('formEditUser_email'), new RFCValidation())){
if(AppUserServices::mailExistsNotActivated($this->_request->request->get('formEditUser_email'))){
$newUser->setEmail($this->_request->request->get('formEditUser_email'));
$newUser->setId(AppUserServices::getUserFromEmail($newUser->getEmail())->getId());
} elseif(!AppUserServices::mailExists($this->_request->request->get('formEditUser_email'))){
$newUser->setEmail($this->_request->request->get('formEditUser_email'));
} else{
$error = true;
$this->addFlash('formEditUser_error', "L'email indiqué est déjà utilisé.");
}
} else{
$error = true;
$this->addFlash('formEditUser_error', "L'email indiqué n'est pas valide.");
}
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier email.');
}
if($this->_request->request->has('formEditUser_phone')
and !empty($this->_request->request->get('formEditUser_phone'))){
$newUser->setPhone($this->_request->request->get('formEditUser_phone'));
}
if($this->_request->request->has('formEditUser_job')
and !empty($this->_request->request->get('formEditUser_job'))){
$newUser->setJob($this->_request->request->get('formEditUser_job'));
}
if($this->_request->request->has('formEditUser_calendly')
and !empty($this->_request->request->get('formEditUser_calendly'))){
if(!( filter_var($this->_request->request->get('formEditUser_calendly'), FILTER_VALIDATE_URL))
and $this->_request->request->get('formEditUser_calendly') != ''){
$error = true;
$this->addFlash('formEditUser_error', 'Erreur sur l\'url du lien du calendrier partagé.');
}else {
$newUser->setCalendlyLink($this->_request->request->get('formEditUser_calendly'));
}
}
if($appAccount->getType()->getId() == AppAccountType::START){
$newUser->setCampaignEngagedContactMaxDailyQuota(15);
}
else{
$newUser->setCampaignEngagedContactMaxDailyQuota(50);
}
if($this->_request->request->has('formEditUser_lbldescription')
and !empty($this->_request->request->get('formEditUser_lbldescription'))){
$newUser->setLBLdescription($this->_request->request->get('formEditUser_lbldescription'));
}
if($this->_request->request->has('formEditUser_typeAdmin')
and !empty($this->_request->request->get('formEditUser_typeAdmin'))){
$newUser->setTypeAdmn(new AppUserTypeAdmin($this->_request->request->get('formEditUser_typeAdmin'), null));
}
if($this->_request->request->has('formEditUser_type')
and !empty($this->_request->request->get('formEditUser_type'))
and !$error){
if(!($this->_request->request->get('formEditUser_type') > AppUserType::RESPONSABLE
and $appAccount->getIdCompany() !== RegCompany::COEFFICY)){
if($this->_isOlder){
$outOfControl = true;
if($this->_request->request->get('formEditUser_type') == "withoutLicence"){
$newUser->setUserTokenLicence(0);
$newUser->setType($this->getAttribute('userTypes')[1]);
}
else{
$newUser->setUserTokenLicence(1);
$newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
else{
$idServiceUser = AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
$referenceFeatureUser = $idServiceUser->getIdCategory() . "-" . sprintf("%02d", $idServiceUser->getIdServiceMarketing());
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser, $this->_tokenProAbono, false);
$status = $data[1];
if($status != 200){
$error = true;
$this->addFlash('formEditUser_error', 'Une erreur technique a été rencontrée. Veuillez réessayer ultérieurement.');
}
else{
if(array_key_exists("QuantityIncluded",$data[0])){
$included = $data[0]['QuantityIncluded'];
}
else{
$included = INF;
}
if(array_key_exists("QuantityCurrent",$data[0])){
$current = $data[0]['QuantityCurrent'];
}
else{
$current = 0;
}
if(!is_infinite($included)) {
$current = $data[0]['QuantityCurrent'];
$included = $data[0]['QuantityIncluded'];
if ($current == $included && $this->_request->request->get('formEditUser_type') != "withoutLicence") {
$error = true;
$this->addFlash('formEditUser_error', "Il n'y a pas assez de licences disponibles sur l'abonnement.");
} else {
$needRefresh = true;
if ($current > $included) {
$outOfBundle = true;
$this->setAttribute('nbLimit', $current);
if ($appAccount->getServices()[AppService::NB_USER]->getSolde() > 0) {
if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
$newUser->setUserTokenLicence(0);
$newUser->setType($this->getAttribute('userTypes')[1]);
$needRefresh = false;
} else {
$newUser->setUserTokenLicence(1);
$newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
} else {
$error = true;
$this->addFlash('formEditUser_error', "Il n'y a plus de licences disponibles.");
}
} else {
if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
$newUser->setUserTokenLicence(0);
$newUser->setType($this->getAttribute('userTypes')[1]);
$needRefresh = false;
} else {
if (is_null($this->_idSubscription)) {
$error = true;
$this->addFlash('formEditUser_error', 'Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.');
}
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current + 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, l'utilisateur n'a pas été ajouté.");
$error = true;
} else {
$newUser->setUserTokenLicence(1);
$newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
}
}
}
else{
$outOfControl = true;
if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
$newUser->setUserTokenLicence(0);
$newUser->setType($this->getAttribute('userTypes')[1]);
$needRefresh = false;
} else {
if (is_null($this->_idSubscription)) {
$error = true;
$this->addFlash('formEditUser_error', 'Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.');
}
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current + 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, l'utilisateur n'a pas été ajouté.");
$error = true;
} else {
$newUser->setUserTokenLicence(1);
$newUser->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
}
}
}
}
}
if(!$error){
$newUser->setIsActive(false);
$newUser->setDefaultSupply(0);
$newUser->setIdAccount($appAccount->getId());
$actionLinkKey = ActionLinkServices::generateKey();
if(empty($newUser->getId())){
$id = AppUserServices::setUser($newUser);
$newUser->setId($id);
} else{
AppUserServices::setUser($newUser);
}
ProfilController::postProfilPhoto($newUser->getId(), $newUser->getIdAccount(), $session->get('campaignApi')['token']);
if($needRefresh){
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
$appAccount = AppAccountServices::getAccount($idAccount);
foreach ($appAccount->getServices() as &$service){
$service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
}
if($outOfControl){
$this->setAttribute('solde', null);
$this->setAttribute('nbLimit', null);
}
else{
$this->setAttribute('solde', $appAccount->getServices()[AppService::NB_USER]->getSolde());
if(!$outOfBundle){
$this->setAttribute('nbLimit', $appAccount->getServices()[AppService::NB_USER]->getNbLimit());
}
}
if(ActionLinkServices::createActionLink($actionLinkKey, 5,$this->_user, $newUser)){
$supportMailAccount = AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
$to = $newUser->getEmailPretty();
$subject = "Invitation sur Coefficy";
$content =
"Bonjour " . $newUser->getLastName() . " " . $newUser->getFirstName() . ", <br><br>" .
"Vous avez une invitation sur Coefficy de la part de la société " . $appAccount->getCompanyName() . ".<br>" .
"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";
if(AppMailAccountServices::sendEmail($supportMailAccount, $to, null, null, $content, $subject) !== false){
$this->addFlash("formEditUser_success", "Utilisateur ajouté avec succès un mail lui a été envoyé");
} else{
$this->addFlash("formEditUser_warning", "Utilisateur ajouté avec succès, cependant le mail d'activation n'a pas pu être envoyé.");
}
if($this->_request->query->has("idAccount")){
return $this->redirect($this->generateUrl(
'Abonnement_utilisateur',
array("idAccount" => $this->_request->query->get("idAccount"))
));
}
else{
return $this->redirect('/Abonnement/Utilisateur');
}
} else{
$this->addFlash("formEditUser_error", "Erreur à la création du lien d'activation de l'utilisateur. si le problème persiste contacter le support.");
}
} else{
$this->addFlash('formEditUser_error', "Erreur sur un/plusieurs des champs");
if($this->_request->query->has("idAccount")){
return $this->redirect($this->generateUrl(
'Abonnement_utilisateur',
array("idAccount" => $this->_request->query->get("idAccount"))
));
}
}
}
elseif(array_key_exists($idUserToEdit, $appAccount->getUsers())) {
if($this->_request->request->has('formEditUser_lastName')
and !empty($this->_request->request->get('formEditUser_lastName'))){
$appAccount->getUsers()[$idUserToEdit]->setLastName($this->_request->request->get('formEditUser_lastName'));
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier nom admin.');
}
if($this->_request->request->has('formEditUser_firstName')
and !empty($this->_request->request->get('formEditUser_firstName'))){
$appAccount->getUsers()[$idUserToEdit]->setFirstName($this->_request->request->get('formEditUser_firstName'));
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier prénom.');
}
if($this->_request->request->has('formEditUser_email')
and !empty($this->_request->request->get('formEditUser_email'))){
if($this->isSupportUser($this->_request->request->get('formEditUser_email'))){
$error = true;
$this->addFlash('formEditUser_error', 'Veuillez utiliser le mode SUPPORT.');
}
if(!AppUserServices::mailExists($this->_request->request->get('formEditUser_email'))
or (AppUserServices::mailExists($this->_request->request->get('formEditUser_email')) and $this->_request->request->get('formEditUser_email') == $appAccount->getUsers()[$idUserToEdit]->getEmail())){
$appAccount->getUsers()[$idUserToEdit]->setEmail($this->_request->request->get('formEditUser_email'));
} else{
$error = true;
$this->addFlash('formEditUser_error', "L'email indiqué est déjà utilisé.");
}
} else{
$error = true;
$this->addFlash('formEditUser_error', 'Vérifier email.');
}
if($this->_request->request->has('formEditUser_phone')
and !empty($this->_request->request->get('formEditUser_phone'))){
$appAccount->getUsers()[$idUserToEdit]->setPhone($this->_request->request->get('formEditUser_phone'));
}
if($this->_request->request->has('formEditUser_job')
and !empty($this->_request->request->get('formEditUser_job'))){
$appAccount->getUsers()[$idUserToEdit]->setJob($this->_request->request->get('formEditUser_job'));
}
if($this->_request->request->has('formEditUser_calendly')
and !empty($this->_request->request->get('formEditUser_calendly'))){
if(!( filter_var($this->_request->request->get('formEditUser_calendly'), FILTER_VALIDATE_URL))
and $this->_request->request->get('formEditUser_calendly') != ''){
$error = true;
$this->addFlash('formEditUser_error', 'Erreur sur l\'url du lien du calendrier partagé.');
}else {
$appAccount->getUsers()[$idUserToEdit]->setCalendlyLink($this->_request->request->get('formEditUser_calendly'));
}
}
if($this->_request->request->has('formEditUser_campaignEngagedContactMaxDailyQuota')
and !empty($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota'))){
if($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota') < 0){
$error = true;
$this->addFlash('formEditUser_error', 'Erreur sur le quota max journalier de contacts engagés.');
}else {
$appAccount->getUsers()[$idUserToEdit]->setCampaignEngagedContactMaxDailyQuota($this->_request->request->get('formEditUser_campaignEngagedContactMaxDailyQuota'));
}
} else{
$appAccount->getUsers()[$idUserToEdit]->setCampaignEngagedContactMaxDailyQuota(50);
}
if($this->_request->request->has('formEditUser_lbldescription')
and !empty($this->_request->request->get('formEditUser_lbldescription'))){
$appAccount->getUsers()[$idUserToEdit]->setLBLdescription($this->_request->request->get('formEditUser_lbldescription'));
}
if($this->_request->request->has('formEditUser_typeAdmin')
and !empty($this->_request->request->get('formEditUser_typeAdmin'))){
$appAccount->getUsers()[$idUserToEdit]->setTypeAdmn(new AppUserTypeAdmin($this->_request->request->get('formEditUser_typeAdmin'), null));
}
if($this->_request->request->has('formEditUser_type')
and !empty($this->_request->request->get('formEditUser_type')) and !$error){
# if(!($this->_request->request->get('formEditUser_type') > AppUserType::RESPONSABLE and $appAccount->getIdCompany() !== RegCompany::COEFFICY)){
if($this->_isOlder){
$outOfControl = true;
if($this->_request->request->get('formEditUser_type') == "withoutLicence"){
if($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1){
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
}
}
else{
if($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0){
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
}
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
else{
$idServiceUser = AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
$referenceFeatureUser = $idServiceUser->getIdCategory() . "-" . sprintf("%02d", $idServiceUser->getIdServiceMarketing());
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Usage?ReferenceCustomer=" . $this->_referenceCustomer . "&ReferenceFeature=" . $referenceFeatureUser, $this->_tokenProAbono, false);
$status = $data[1];
if ($status != 200) {
$error = true;
$this->addFlash('formEditUser_error', 'Une erreur technique a été rencontrée. Veuillez réessayer ultérieurement.');
}
else {
if (array_key_exists("QuantityIncluded", $data[0])) {
$included = $data[0]['QuantityIncluded'];
} else {
$included = INF;
}
if (array_key_exists("QuantityCurrent", $data[0])) {
$current = $data[0]['QuantityCurrent'];
} else {
$current = 0;
}
if (!is_infinite($included)) {
$current = $data[0]['QuantityCurrent'];
$included = $data[0]['QuantityIncluded'];
if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1) {
if ($included >= $current) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? 0 : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été retiré.");
$error = true;
}
}
$needRefresh = true;
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
}
} else {
if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0) {
if ($current == $included) {
$this->addFlash('formEditUser_error', "Il n'y a plus de licences disponibles.");
$error = true;
} else if ($current < $included) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current + 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été ajoutée.");
$error = true;
} else {
$licensing = true;
$needRefresh = true;
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
} else {
if ($appAccount->getServices()[AppService::NB_USER]->getSolde() > 0) {
$needRefresh = true;
$outOfBundle = true;
$licensing = true;
$this->setAttribute('nbLimit', $current);
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
} else {
$this->addFlash('formEditUser_error', "Il n'y a plus de licences disponibles.");
$error = true;
}
}
} else {
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
} else {
$outOfControl = true;
if ($this->_request->request->get('formEditUser_type') == "withoutLicence") {
if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 1) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? 0 : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été retiré.");
$error = true;
} else {
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(0);
}
}
} else {
if ($appAccount->getUsers()[$idUserToEdit]->getUserTokenLicence() == 0) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current + 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
$this->addFlash('formEditUser_error', "Une erreur a été rencontrée, la licence de l'utilisateur n'a pas été ajoutée.");
$error = true;
} else {
$appAccount->getUsers()[$idUserToEdit]->setUserTokenLicence(1);
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
else{
$appAccount->getUsers()[$idUserToEdit]->setType($this->getAttribute('userTypes')[(int)$this->_request->request->get('formEditUser_type')]);
}
}
}
}
}
#}
}
if(!$error){
if(AppUserServices::setUser($appAccount->getUsers()[$idUserToEdit])){
$this->addFlash('formEditUser_success', 'Utilisateur modifié avec succès');
if($licensing and BaseController::getConfig()['env'] == "prod"){
$supportMailAccount = AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
$to = $appAccount->getUsers()[$idUserToEdit]->getEmailPretty();
$subject = $appAccount->getUsers()[$idUserToEdit]->getFirstName() . ", une licence Coefficy vous a été attribué";
$content = 'Bonjour ' . $appAccount->getUsers()[$idUserToEdit]->getFirstName() . ',<br><br>';
$content .= $this->_user['userFirstName'] . " " . $this->_user['userLastName'] . " vient de vous attribuer une licence utilisateur sur Coefficy." . "<br>";
$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>";
$content .= "Bonne acquisition client avec Coefficy !";
if(AppMailAccountServices::sendEmail($supportMailAccount, $to, null, null, $content, $subject) !== false){
$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.");
}
}
if($needRefresh){
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
$appAccount = AppAccountServices::getAccount($idAccount);
foreach ($appAccount->getServices() as &$service){
$service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
}
if($outOfControl){
$this->setAttribute('solde', null);
$this->setAttribute('nbLimit', null);
}
else{
$this->setAttribute('solde', $appAccount->getServices()[AppService::NB_USER]->getSolde());
if(!$outOfBundle){
$this->setAttribute('nbLimit', $appAccount->getServices()[AppService::NB_USER]->getNbLimit());
}
}
} else{
$this->addFlash('formEditUser_error', 'Erreur lors de l\'insertion/Mise à jour de l\'utilisateur');
}
} else{
$this->addFlash('formEditUser_error', "Erreur sur un/plusieurs des champs");
}
if($this->_request->query->has("idAccount")){
return $this->redirect($this->generateUrl(
'Abonnement_utilisateur',
array("idAccount" => $this->_request->query->get("idAccount"))
));
}
else{
return $this->redirect('/Abonnement/Utilisateur');
}
}
}
elseif($this->_request->request->has('formStopInvite')) {
$parameters = [];
$idUserToDelete = $parameters['formStopInvite[idUser]'] = intval($this->_request->get('formStopInvite')['idUser']);
if($this->_user['idUser'] == $idUserToDelete){
return new JsonResponse([
'success'=> false,
'code' => 403,
'message'=> "Un utilisateur ne peut pas s'auto supprimer",
'parameters' => $parameters
], 403);
}
$accountUser = $appAccount->getUsers();
$userToDelete = null;
foreach ($accountUser as $index => $kUser) {
if($idUserToDelete === $kUser->getId()){
$userToDelete = $kUser;
}
}
if($userToDelete === null && $idUserToDelete){
$userToDelete = false;
}
if($userToDelete === null){
return new JsonResponse([
'success'=> false,
'code' => 400,
'message'=> "Paramètre 'idUser' ne peut être null",
'parameters' => $parameters
], 400);
}
$needRefresh = false;
$newSolde = null;
$newNbLimit = null;
$outOfControl = false;
if($this->_isOlder){
$outOfControl = true;
}
else{
if($appAccount->getUsers()[$userToDelete->getId()]->getUserTokenLicence() == 1){
$idServiceUser = AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
$referenceFeatureUser = $idServiceUser->getIdCategory() . "-" . sprintf("%02d", $idServiceUser->getIdServiceMarketing());
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser, $this->_tokenProAbono, false);
$status = $data[1];
if($status != 200){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "Impossible de supprimer la licence attribué à l'invité.",
'parameters' => $parameters
], 404);
}
else{
if (array_key_exists("QuantityIncluded", $data[0])) {
$included = $data[0]['QuantityIncluded'];
} else {
$included = INF;
}
if (array_key_exists("QuantityCurrent", $data[0])) {
$current = $data[0]['QuantityCurrent'];
} else {
$current = 0;
}
if (!is_infinite($included)) {
$current = $data[0]['QuantityCurrent'];
$included = $data[0]['QuantityIncluded'];
if (is_null($this->_idSubscription)) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.",
'parameters' => $parameters
], 404);
}
if ($included >= $current) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? 0 : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Impossible de supprimer la licence attribué à l'invité",
'parameters' => $parameters
], 404);
} else {
$newSolde = $data[0]['QuantityCurrent'];
$newNbLimit = $data[0]['QuantityIncluded'];
$needRefresh = true;
}
} else {
$needRefresh = true;
$newSolde = $current == 0 ? $current : $current - 1;
$newNbLimit = $included;
}
}
else{
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? 0 : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Impossible de supprimer la licence attribué à l'invité",
'parameters' => $parameters
], 404);
}
}
}
}
}
if(Services_coefficy_utilisateurs::deleteUtilisateur($appAccount->getId(), $userToDelete->getId()) != false){
AppUserServices::setMailAccountIsActive($userToDelete->getId(), false);
ActionLinkServices::desactiveUserLinks($userToDelete->getId(), $appAccount->getId());
ProfilController::postProfilPhoto($userToDelete->getId(), $userToDelete->getIdAccount(), $session->get('campaignApi')['token']);
if($needRefresh){
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
return new JsonResponse([
'success'=> true,
'code' => 200,
'message'=> "Invitation stoppée avec succès",
'oldUser' => $userToDelete->getId(),
'result' => [
'stopInvite' => true,
'solde' => $newSolde,
'nbLimit' => $newNbLimit
],
'parameters' => $parameters
], 200);
} else{
return new JsonResponse([
'success'=> false,
'code' => 200,
'message'=> "Erreur à l'annulation de l'invitation",
'oldUser' => $userToDelete->getId(),
'result' => [
'stopInvite' => false
],
'parameters' => $parameters
], 200);
}
}
elseif($this->_request->request->has('formDeleteUser')) {
$parameters = [];
$idUserToDelete = $parameters['formDeleteUser[idUser]'] = intval($this->_request->get('formDeleteUser')['idUser']);
if($this->_user['idUser'] == $idUserToDelete){
return new JsonResponse([
'success'=> false,
'code' => 403,
'message'=> "Un utilisateur ne peut pas s'auto supprimer",
'parameters' => $parameters
], 403);
}
if($appAccount->hasService(AppService::CRM)) {
$relaunchOpportunitySupply = $parameters['formDeleteUser[relaunchOpportunitySupply]'] = $this->_request->get('formDeleteUser')['relaunchOpportunitySupply'] !== null ? intval($this->_request->get('formDeleteUser')['relaunchOpportunitySupply']) : null;
} else{
$relaunchOpportunitySupply = $parameters['formDeleteUser[relaunchOpportunitySupply]'] = null;
}
if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)
|| $appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
$campaignSequence = $parameters['formDeleteUser[campaignSequence]'] = $this->_request->get('formDeleteUser')['campaignSequence'] !== null ? intval($this->_request->get('formDeleteUser')['campaignSequence']) : null;
} else{
$campaignSequence = $parameters['formDeleteUser[campaignSequence]'] = null;
}
if($appAccount->hasService(AppService::NEWSLETTER)) {
$newsletterContact = $parameters['formDeleteUser[newsletterContact]'] = $this->_request->get('formDeleteUser')['newsletterContact'] !== null ? intval($this->_request->get('formDeleteUser')['newsletterContact']) : null;
} else {
$newsletterContact = $parameters['formDeleteUser[newsletterContact]'] = null;
}
if($appAccount->hasService(AppService::LEBONLOGICIEL)) {
$articleLbl = $parameters['formDeleteUser[articleLbl]'] = $this->_request->get('formDeleteUser')['articleLbl'] !== null ? intval($this->_request->get('formDeleteUser')['articleLbl']) : null;
} else{
$articleLbl = $parameters['formDeleteUser[articleLbl]'] = null;
}
if($appAccount->hasService(AppService::CRM)) {
$persona = $parameters['formDeleteUser[persona]'] = $this->_request->get('formDeleteUser')['persona'] !== null ? intval($this->_request->get('formDeleteUser')['persona']) : null;
} else{
$persona = $parameters['formDeleteUser[persona]'] = null;
}
if($appAccount->hasService(AppService::EMAIL_SUIVI)) {
$template = $parameters['formDeleteUser[template]'] = $this->_request->get('formDeleteUser')['template'] !== null ? intval($this->_request->get('formDeleteUser')['template']) : null;
} else{
$template = $parameters['formDeleteUser[template]'] = null;
}
if($appAccount->hasService(AppService::EDITION_LEADFORM)) {
$leadform = $parameters['formDeleteUser[leadform]'] = $this->_request->get('formDeleteUser')['leadform'] !== null ? intval($this->_request->get('formDeleteUser')['leadform']) : null;
} else{
$leadform = $parameters['formDeleteUser[leadform]'] = null;
}
$accountUser = $appAccount->getUsers();
$userToDelete = null;
$userRelaunchOpportunitySupply = null;
$userCampaignSequence = null;
$userNewsletterContact = null;
$userArticleLbl = null;
$userPersona = null;
$userTemplate = null;
$userLeadform = null;
foreach ($accountUser as $index => $kUser) {
if($idUserToDelete === $kUser->getId()){
$userToDelete = $kUser;
}
if($appAccount->hasService(AppService::CRM)){
if($relaunchOpportunitySupply === $kUser->getId()){
$userRelaunchOpportunitySupply = $kUser;
}
}
if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)
|| $appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
if($campaignSequence === $kUser->getId()){
$userCampaignSequence = $kUser;
}
}
if($appAccount->hasService(AppService::NEWSLETTER)) {
if($newsletterContact === $kUser->getId()){
$userNewsletterContact = $kUser;
}
}
if($appAccount->hasService(AppService::LEBONLOGICIEL)) {
if($articleLbl === $kUser->getId()){
$userArticleLbl = $kUser;
}
}
if($appAccount->hasService(AppService::CRM)) {
if($persona === $kUser->getId()){
$userPersona = $kUser;
}
}
if($appAccount->hasService(AppService::EMAIL_SUIVI)) {
if($template === $kUser->getId()){
$userTemplate = $kUser;
}
}
if($appAccount->hasService(AppService::EDITION_LEADFORM)) {
if($leadform === $kUser->getId()){
$userLeadform = $kUser;
}
}
}
if($userToDelete === null && $idUserToDelete){
$userToDelete = false;
}
if($userRelaunchOpportunitySupply === null && $relaunchOpportunitySupply){
$userRelaunchOpportunitySupply = false;
}
if($userCampaignSequence === null && $campaignSequence){
$userCampaignSequence = false;
}
if($userNewsletterContact === null && $newsletterContact){
$userNewsletterContact = false;
}
if($userArticleLbl === null && $articleLbl){
$userArticleLbl = false;
}
if($userPersona === null && $persona){
$userPersona = false;
}
if($userTemplate === null && $template){
$userTemplate = false;
}
if($userLeadform === null && $leadform){
$userLeadform = false;
}
if($userToDelete === null){
return new JsonResponse([
'success'=> false,
'code' => 400,
'message'=> "Paramètre 'idUser' ne peut être null",
'parameters' => $parameters
], 400);
}
if($userToDelete === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $idUserToDelete n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userRelaunchOpportunitySupply === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $relaunchOpportunitySupply n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userCampaignSequence === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $campaignSequence n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userNewsletterContact === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $newsletterContact n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userArticleLbl === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $articleLbl n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userPersona === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $persona n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userTemplate === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $template n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
if($userLeadform === false){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "L'utilisateur ayant pour id $leadform n'existe pas sur l'abonnement",
'parameters' => $parameters
], 404);
}
$resultRelaunch = null;
$resultOpportunity = null;
$resultSupply = null;
$resultCampaign = null;
$resultSequence = null;
$resultNewsletterContact = null;
$resultArticleLbl = null;
$resultPersona = null;
$resultTemplate = null;
$resultLeadform = null;
if($appAccount->hasService(AppService::CRM)){
if($userRelaunchOpportunitySupply){
$resultRelaunch = CrmRelaunchServices::updateUserOnRelaunch($userToDelete->getId(), $userToDelete->getIdAccount(), $userRelaunchOpportunitySupply->getId());
$resultOpportunity = CrmOpportunityServices::updateUserOnOpportunity($userToDelete->getId(), $userToDelete->getIdAccount(), $userRelaunchOpportunitySupply->getId());
$resultSupply = RoutineServices::updateUserOnRoutine($userToDelete->getId(), $userRelaunchOpportunitySupply->getId());
} else{
$resultRelaunch = CrmRelaunchServices::deleteUserFromRelaunch($userToDelete->getId(), $userToDelete->getIdAccount());
$resultOpportunity = CrmOpportunityServices::deleteUserOpportunity($userToDelete->getId(), $userToDelete->getIdAccount());
$resultSupply = RoutineServices::deleteUserFromRoutines($userToDelete->getId());
}
}
if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
if($userCampaignSequence){
$resultSequence = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'newIdUser' => $userCampaignSequence->getId(),
'idAccount' => $appAccount->getId()
]
);
} else{
$resultSequence = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['SEQUENCE_DELETEUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'idAccount' => $appAccount->getId()
]
);
}
}
if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
if($userCampaignSequence){
$resultCampaign = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'newIdUser' => $userCampaignSequence->getId(),
'idAccount' => $appAccount->getId()
]
);
} else{
$resultCampaign = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['CAMPAIGN_DELETEUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'idAccount' => $appAccount->getId()
]
);
}
}
if($appAccount->hasService(AppService::NEWSLETTER)) {
if($userCampaignSequence){
$resultNewsletterContact = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'newIdUser' => $userNewsletterContact->getId(),
'idAccount' => $appAccount->getId()
]
);
} else{
$resultNewsletterContact = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['NEWSLETTER_DELETEUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $userToDelete->getId(),
'idAccount' => $appAccount->getId()
]
);
}
}
if($appAccount->hasService(AppService::LEBONLOGICIEL)){
if($userArticleLbl){
$resultArticleLbl = LeBonLogicielServices::transfertArticleResponsable($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
} else{
$resultArticleLbl = LeBonLogicielServices::transfertArticleResponsableOldest($userToDelete->getId(), $appAccount->getId());
}
}
if($appAccount->hasService(AppService::CRM)){
if($userPersona){
$resultPersona = CamPersonaServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
} else{
$resultPersona = CamPersonaServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
}
}
if($appAccount->hasService(AppService::EMAIL_SUIVI)){
if($userTemplate){
$resultTemplate = AppMailTemplateServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
} else{
$resultTemplate = AppMailTemplateServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
}
}
if($appAccount->hasService(AppService::EDITION_LEADFORM)){
if($userLeadform){
$resultLeadform = LeadformServices::updateUser($userToDelete->getId(), $userArticleLbl->getId(), $appAccount->getId());
} else{
$resultLeadform = LeadformServices::updateUserOldestResponsable($userToDelete->getId(), $appAccount->getId());
}
}
$needRefresh = false;
$newSolde = null;
$newNbLimit = null;
if($this->_isOlder){
//
}
else{
if($appAccount->getUsers()[$userToDelete->getId()]->getUserTokenLicence() == 1){
$idServiceUser = AppServiceServices::getServiceMarketingByIdService(AppService::NB_USER);
$referenceFeatureUser = $idServiceUser->getIdCategory() . "-" . sprintf("%02d", $idServiceUser->getIdServiceMarketing());
$data = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Usage?ReferenceCustomer=".$this->_referenceCustomer."&ReferenceFeature=".$referenceFeatureUser, $this->_tokenProAbono, false);
$status = $data[1];
if($status != 200){
return new JsonResponse([
'success'=> false,
'code' => 404,
'message'=> "Une erreur a été rencontrée lors de la suppression de l'utilisateur.",
'parameters' => $parameters
], 404);
}
else{
if (array_key_exists("QuantityIncluded", $data[0])) {
$included = $data[0]['QuantityIncluded'];
} else {
$included = INF;
}
if (array_key_exists("QuantityCurrent", $data[0])) {
$current = $data[0]['QuantityCurrent'];
} else {
$current = 0;
}
if (!is_infinite($included)) {
$current = $data[0]['QuantityCurrent'];
$included = $data[0]['QuantityIncluded'];
if (is_null($this->_idSubscription)) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Une erreur technique a été rencontré. Veuillez réessayer ultérieurement.",
'parameters' => $parameters
], 404);
}
if ($included >= $current) {
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? $current : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Impossible de supprimer la licence de l'utilisateur.",
'parameters' => $parameters
], 404);
} else {
$needRefresh = true;
$newSolde = $data[0]['QuantityCurrent'];
$newNbLimit = $data[0]['QuantityIncluded'];
}
} else {
$needRefresh = true;
$outOfBundle = true;
$newSolde = $current == 0 ? $current : $current - 1;
$newNbLimit = $included;
}
}
else{
$params = json_encode(
array(
"ReferenceFeature" => $referenceFeatureUser,
"IdSubscription" => $this->_idSubscription,
"QuantityCurrent" => $current == 0 ? $current : $current - 1,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, $params);
$status = $data[1];
if ($status != 200) {
return new JsonResponse([
'success' => false,
'code' => 404,
'message' => "Impossible de supprimer la licence de l'utilisateur.",
'parameters' => $parameters
], 404);
}
}
}
}
}
if(Services_coefficy_utilisateurs::deleteUtilisateur($appAccount->getId(), $userToDelete->getId()) != false){
AppUserServices::setMailAccountIsActive($userToDelete->getId(), false);
ActionLinkServices::desactiveUserLinks($userToDelete->getId(), $appAccount->getId());
ProfilController::postProfilPhoto($userToDelete->getId(), $userToDelete->getIdAccount(), $session->get('campaignApi')['token']);
$resultDelete = true;
} else{
$resultDelete = false;
}
if($needRefresh){
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
return new JsonResponse([
'success'=> true,
'code' => 200,
'message'=> "Utilisateur supprimé avec succès",
'oldUser' => $userToDelete->getId(),
'result' => [
'relaunch' => $resultRelaunch,
'opportunity' => $resultOpportunity,
'supply' => $resultSupply,
'campaign' => $resultCampaign,
'sequence' => $resultSequence,
'newsletterContact' => $resultNewsletterContact,
'articleLbl' => $resultArticleLbl,
'persona' => $resultPersona,
'template' => $resultTemplate,
'leadform' => $resultLeadform,
'deleteUser' => $resultDelete,
'solde' => $newSolde,
'nbLimit' => $newNbLimit
],
'parameters' => $parameters
], 200);
}
elseif($this->_request->request->has('formRedoInvite_submit')) {
$error = false;
$idUser = null;
if($this->_request->request->has('formRedoInvite_id')
and !empty($this->_request->request->get('formRedoInvite_id'))){
$idUser = $this->_request->request->get('formRedoInvite_id');
} else{
$error = true;
$this->addFlash("formRedoInvite_error","Erreur à l'identification de l'utilisateur à réinviter");
}
if(!$error){
$actionLinkKey = ActionLinkServices::generateKey();
ActionLinkServices::desactiveUserLinks($idUser, $appAccount->getId());
if(ActionLinkServices::createActionLink($actionLinkKey, 5,$this->_user, $appAccount->getUsers()[$idUser])){
$supportMailAccount = AppMailAccountServices::getMailAccount(AppMailAccount::SUPPORT_COEFFICY_ACCOUNT);
$to = $appAccount->getUsers()[$idUser]->getEmailPretty();
$subject = "Invitation sur Coefficy";
$content =
"Bonjour " . $appAccount->getUsers()[$idUser]->getLastName() . " " . $appAccount->getUsers()[$idUser]->getFirstName() . ", <br><br>" .
"Vous avez une invitation sur Coefficy de la part de la société " . $appAccount->getCompanyName(). ".<br>" .
"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";
if(AppMailAccountServices::sendEmail($supportMailAccount, $to, null, null, $content, $subject) !== false){
$this->addFlash("formEditUser_success", "Le mail d'activation a été renvoyé");
} else{
$this->addFlash("formEditUser_warning", "Erreur à l'envoi du mail, réessayez.");
}
} else{
$this->addFlash("formEditUser_error", "Erreur à la création du lien d'activation de l'utilisateur. si le problème persiste contacter le support.");
}
if($this->_request->query->has("idAccount")){
return $this->redirect($this->generateUrl(
'Abonnement_utilisateur',
array("idAccount" => $this->_request->query->get("idAccount"))
));
}
}
else{
if($this->_request->query->has("idAccount")){
return $this->redirect($this->generateUrl(
'Abonnement_utilisateur',
array("idAccount" => $this->_request->query->get("idAccount"))
));
}
}
return $this->redirect('/Abonnement/Utilisateur');
}
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
if ($ajax) {
if($parent == "actualUserList"){
return $this->render('abonnement/onglets/utilisateurs/utilisateurs_actuels.html.twig', $this->attribute);
}
else{
return $this->render('abonnement/onglets/utilisateurs/utilisateurs_invites.html.twig', $this->attribute);
}
} else {
return $this->render('abonnement/index.html.twig', $this->attribute);
}
}
/**
* @Route("/Abonnement/Utilisateur/setAdmin", name="setAdmin")
* @param bool $ajax
* @param string $parent
* @return Response
* @throws Exception
*/
public function setAdmin($ajax = true)
{
try{
if(!$this->_proAbonoUserState or $this->_isTerminated){
throw new Exception();
}
$id_utilisateur = $this->_request->get('id', '');
$parent = $this->_request->get('parent','');
$admin = $this->_request->get('admin', 'nop');
$idAccount = $this->_request->get('idAccount',$this->_idAccount);
if(empty($parent) or empty($id_utilisateur)){
$response = $this->forward('App\Controller\AbonnementController::abonnementUtilisateurs');
return $response;
}
if ($this->_isResponsable and $this->_user['idUser'] != $id_utilisateur) {
if ($admin == 'nop') {
Services_coefficy_utilisateurs::setAdmin($idAccount, $id_utilisateur, 1);
} else {
Services_coefficy_utilisateurs::setAdmin($idAccount, $id_utilisateur, 2);
}
}
if ($ajax) {
$response = $this->forward('App\Controller\AbonnementController::abonnementUtilisateurs', [
'ajax' => true,
'parent' => $parent,
'idAccount' => $idAccount
]);
return $response;
} else {
return null;
}
}
catch(Exception $e){
if($ajax){
return new JsonResponse(array(
'status' => 404
));
}
else{
return null;
}
}
}
/**
* @Route("/Abonnement/Consommation", name="Abonnement_consommation")
* @Route("/Abonnement/Consommation", name="abonnement_consommation")
* @return Response
*
* @throws Exception
*/
public function abonnementConsommation(Request $request)
{
$this->setAttribute('shownPart','consommation');
$this->setAttribute('search', $request->get('search'));
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isDisabled){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if(!$this->_isOlder){
$this->setAttribute('totalOnboardingHoursInMinutes',AppAccountHoursServices::countOnboardingHours($this->_idAccount));
$this->setAttribute('onboardingHoursBalanceInMinutes',AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount));
$this->setAttribute('totalNewsletters',AppAccountHoursServices::countNewsletters($this->_idAccount));
$this->setAttribute('balanceNewsletter',AppAccountServices::getAccountnewsletterBalance($this->_idAccount));
}
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$consos = [];
$limitations = [];
foreach ($this->_proAbonoUserState["current"]["limitations"] as &$limitation){
$idCategory = explode('-', $limitation['ReferenceFeature'])[0];
$idServiceMarketing = explode('-', $limitation['ReferenceFeature'])[1];
if(in_array($idCategory,AppServiceCategory::UT_NEW_DISPLAYED)){
$service = AppServiceServices::getServicesToActivate($idCategory,$idServiceMarketing);
$service = reset($service);
$service->setSolde(AppServiceServices::getSoldeByIdentifiedNumber($appAccount->getId(),$service->getId())['accountServiceSolde']);
$limitation['solde'] = $service->getSolde();
$limitations[] = $limitation;
}
}
foreach ($this->_proAbonoUserState["current"]["consos"] as &$conso){
$idCategory = explode('-', $conso['ReferenceFeature'])[0];
$idServiceMarketing = explode('-', $conso['ReferenceFeature'])[1];
if(in_array($idCategory,AppServiceCategory::UT_NEW_DISPLAYED)){
if($conso['ReferenceFeature'] == AppServiceMarketing::CONTACTS){
$conso['order'] = 1;
}
else if($conso['ReferenceFeature'] == AppServiceMarketing::VISITEURS){
$conso['order'] = 2;
}
else if($conso['ReferenceFeature'] == AppServiceMarketing::COACHING){
$conso['order'] = 4;
$conso['TitleLocalized'] = "Un coach en acquisition client à votre disposition (/heure)";
$conso['QuantityIncluded'] = number_format($conso['QuantityIncluded'] / 60,2);
$conso['QuantityCurrent'] = number_format($conso['QuantityCurrent'] / 60,2);
$conso['price'] = $conso['price'] * 60;
}else if($conso['ReferenceFeature'] == AppServiceMarketing::CONTACTSABONNE){
$conso['order'] = 6;
}
else{
$conso['order'] = 7;
}
$consos[] = $conso;
}
}
if($appAccount->getType()->getId() != AppAccountType::REFERRAL) {
$conso = array(
"TitleLocalized" => "Onboarding : accompagnement personnalisé au démarrage avec un coach en acquisition client (/heure)",
"QuantityCurrent" => $this->getAttribute('totalOnboardingHoursInMinutes') / 60,
"QuantityTotal" => ($this->getAttribute('onboardingHoursBalanceInMinutes') / 60) + ($this->getAttribute('totalOnboardingHoursInMinutes') / 60),
"order" => 3
);
$consos[] = $conso;
}
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) ){
$conso = array(
"TitleLocalized" => "Prestation de rédaction de newsletter (/newsletter)",
"QuantityCurrent" => $this->getAttribute('totalNewsletters'),
"QuantityTotal" => $this->getAttribute('totalNewsletters') + $this->getAttribute('balanceNewsletter'),
"order" => 5
);
$consos[] = $conso;
}
$actual_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$totalHours = AppAccountHoursServices::getTotalSetOfHours($appAccount);
$nbrPages = intval(ceil($totalHours / self::$NBRPERPAGE));
if ($this->_request->query->has("pHours") and $this->_request->query->get("pHours") != "") {
$p = $this->_request->query->get("pHours");
if (strpos($actual_url, "&pHours=") !== false) {
$url_sans_page = str_replace('&pHours=' . urlencode($p), '&pHours=', $actual_url);
}
else if (strpos($actual_url, "?pHours=") !== false) {
$url_sans_page = str_replace('?pHours=' . urlencode($p), '?pHours=', $actual_url);
}
if(intval($p) === 0){
$p = 1;
}
} else {
$p = 1;
if(empty($_SERVER['QUERY_STRING'])){
$url_sans_page = $actual_url . "?pHours=";
}
else{
$url_sans_page = $actual_url . "&pHours=";
}
}
if($p > $nbrPages){
$p = 1;
}
if (strpos($url_sans_page, "&pHours=") !== false) {
$url_premiere_page = str_replace('&pHours=', '&pHours=1', $url_sans_page);
$url_derniere_page = str_replace('&pHours=', '&pHours='.$nbrPages, $url_sans_page);
}
else if (strpos($url_sans_page, "?pHours=") !== false){
$url_premiere_page = str_replace('?pHours=', '?pHours=1', $url_sans_page);
$url_derniere_page = str_replace('?pHours=', '?pHours='.$nbrPages, $url_sans_page);
}
else{
$url_premiere_page = $url_sans_page . '?pHours=1';
$url_derniere_page = $url_sans_page . '?pHours=' . $nbrPages;
}
$offset = ($p - 1) * self::$NBRPERPAGE;
$endStatusHours = AppAccountHoursServices::getEndStatusHours();
$stopStatusHours = AppAccountHoursServices::getStopStatusHours();
$listIdHistoricStatus = array_map(function($e) {
return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
}, $endStatusHours);
$listIdStopStatus = array_map(function($e) {
return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
}, $stopStatusHours);
$hoursType = AppAccountHoursServices::getHoursType();
$this->setAttribute('arrayHistoricStatus', $listIdHistoricStatus);
$this->setAttribute('arrayStopStatus', $listIdStopStatus);
$this->setAttribute('url_sans_page',$url_sans_page);
$this->setAttribute('url_premiere_page',$url_premiere_page);
$this->setAttribute('url_derniere_page',$url_derniere_page);
$this->setAttribute('numero_de_page',$p);
$this->setAttribute('totalHours',$totalHours);
$this->setAttribute('nbrPages',$nbrPages);
$this->setAttribute('accountHours',AppAccountHoursServices::getAccountHours($appAccount,$offset,self::$NBRPERPAGE));
$this->setAttribute('hoursTypes',$hoursType);
$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(null, null, null, new ReflectionExtractor())];
$serializer = new Serializer($normalizers, $encoders);
$this->setAttribute('hoursTypesSerial',json_decode($serializer->serialize($hoursType, 'json')));
$accountUsers = AppUserServices::getAccountUsers(AppAccount::VenteCoeff);
uasort($accountUsers,function($a, $b){
return $a->firstName <=> $b->firstName;
});
$this->setAttribute('responsablesSerial', json_decode($serializer->serialize($accountUsers, 'json')));
$this->setAttribute('hoursStatus', json_decode($serializer->serialize(AppAccountHoursServices::getHoursStatus(), 'json')));
$this->setAttribute('responsables',AppUserServices::getAccountUsers(AppAccount::VenteCoeff));
$this->setAttribute('appAccount',$appAccount);
$this->setAttribute('isAdmin',$this->_isAdmin);
$this->setAttribute('current',$this->_proAbonoUserState["current"]);
$this->setAttribute('limitations', $limitations);
$this->setAttribute('consos', $consos);
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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");
}
}
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/Suivi", name="Abonnement_suivi")
* @Route("/Abonnement/Suivi", name="abonnement_suivi")
* @param SessionInterface $session
* @param Request $request
* @return Response
*
* @throws Exception
*/
public function abonnementSuiviBackOffice(SessionInterface $session, Request $request)
{
$this->setAttribute('shownPart','suivibackoffice');
$this->setAttribute('search', $request->get('search'));
$currentHoursStatus = null;
if(!$this->_isAdmin && !in_array(AppService::ACCES_SUIVI_CLIENT, $session->get('user')['services'])){
throw new AccessDeniedHttpException();
}
try{
/*if(!$this->_proAbonoUserState){
throw new Exception();
}*/
/*if($this->_isDisabled){
throw new Exception();
}*/
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if(!$this->_isOlder){
$this->setAttribute('totalOnboardingHoursInMinutes',AppAccountHoursServices::countOnboardingHours($this->_idAccount));
$this->setAttribute('onboardingHoursBalanceInMinutes',AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount));
$this->setAttribute('totalNewsletters',AppAccountHoursServices::countNewsletters($this->_idAccount));
$this->setAttribute('balanceNewsletter',AppAccountServices::getAccountnewsletterBalance($this->_idAccount));
}
$typehoursUpdateProAbono = AppAccountHoursServices::getidHoursTypeToUpdateProAbono();
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount',$appAccount);
if ($this->_request->isMethod("POST")) {
if(!$this->_isAdmin){
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
if(!empty($_POST)){
if($this->_request->request->has('addEditHours')){
$post = $this->_request->request->get('addEditHours');
if(isset($post['formActionHoursConsulting']) and !empty($post['formActionHoursConsulting'])
and isset($post['titleHour']) and !empty($post['titleHour'])
and isset($post['commentHour']) and !empty($post['commentHour'])
and isset($post['duration'])
and isset($post['dateStartHoursConsulting']) and !empty($post['dateStartHoursConsulting'])
and isset($post['selectResponsableHours']) and !empty($post['selectResponsableHours'])
and isset($post['selectCreatorHours']) and !empty($post['selectCreatorHours'])
and isset($post['selectTypeHours']) and !empty($post['selectTypeHours'])
and isset($post['selectStatusHours']) and !empty($post['selectStatusHours'])
and isset($post['linkHour'])
and isset($post['valueHour']) ) {
$typeHours = AppAccountHoursServices::getHoursTypeById($post['selectTypeHours']);
$from = DateTime::createFromFormat('d/m/Y H:i', $post['dateStartHoursConsulting']);
if(isset($post['dateTermHoursConsulting']) and !empty($post['dateTermHoursConsulting'])) {
$to = DateTime::createFromFormat('d/m/Y H:i', $post['dateTermHoursConsulting']);
}
else{
$to = null;
}
if(isset($post['dateDueHoursConsulting']) and !empty($post['dateDueHoursConsulting']))
{
$due = DateTime::createFromFormat('d/m/Y H:i', $post['dateDueHoursConsulting']);
}
else{
$due = null;
}
if(empty($post['duration']))
{
$post['duration'] = null;
}
if($to != null and $from != null and $to->getTimestamp() === $from->getTimestamp()){
$this->addFlash("error","Les dates sélectionnées sont identiques.");
}
else if($to != null and $from != null and $to->getTimestamp() < $from->getTimestamp()){
$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)");
}
else if($to != null and $from != null and empty($post['duration']) or (!empty($post['duration']) and intval($post['duration']) < 15)){
$this->addFlash("error","Veuillez saisir un intervalle minimal de 0,25 heures entre les deux dates.");
}
else{
if(!in_array($post['selectTypeHours'],$typehoursUpdateProAbono)){
if($post['formActionHoursConsulting'] == "add"){
$flagOnboardingHours = true;
if(in_array($appAccount->getType()->getId(),AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)){
if($post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS and ($post['duration'] > $this->getAttribute('onboardingHoursBalanceInMinutes'))){
$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.");
$flagOnboardingHours = false;
}
}
if($flagOnboardingHours){
$accountHours = new AppAccountHour(
null,
$this->_idAccount,
$this->_idSubscription,
$post['titleHour'],
$post['commentHour'],
new AppAccountHourType($post['selectTypeHours']),
new AppAccountHourStatus($post['selectStatusHours']),
$post['duration'],
$from,
$to,
$due,
AppUserServices::getUser($post['selectResponsableHours']),
1,
$post['linkHour'],
!is_null($post['valueHour']) ?floatval($post['valueHour']):null,
!is_null($post['customervalueHour']) ?floatval($post['customervalueHour']):null,
AppUserServices::getUser($post['selectCreatorHours'])
);
if(!AppAccountHoursServices::setAccountHours($accountHours)){
$this->addFlash("error","Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
}
else{
$this->addFlash("success", "La saisie des heures a bien été réalisée.");
if($post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
}
if($post['selectTypeHours'] == AppAccountHourType::NEWSLETTERS){
AppAccountServices::updateBalanceNewsletter($this->_idAccount, false);
}
}
}
}
else if($post['formActionHoursConsulting'] == "update"){
if(isset($post['idHour']) and !empty($post['idHour'])) {
$actualHours = AppAccountHoursServices::getAccountHoursById($this->_idAccount, $post['idHour']);
if($actualHours){
$flagOnboardingHours = true;
if(in_array($appAccount->getType()->getId(),AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)
and $post['selectTypeHours'] == AppAccountHourType::ONBOARDING_HOURS){
if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']){
if($post['duration'] > $this->getAttribute('onboardingHoursBalanceInMinutes')){
$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.");
$flagOnboardingHours = false;
}
}
else{
if(($post['duration'] - $actualHours->getDurationInMinutes()) > $this->getAttribute('onboardingHoursBalanceInMinutes')){
$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.");
$flagOnboardingHours = false;
}
}
}
if($flagOnboardingHours){
if(!$actualHours->getIsBilled()){
$accountHours = new AppAccountHour(
$post['idHour'],
$this->_idAccount,
$actualHours->getIdSubscription(),
$post['titleHour'],
$post['commentHour'],
new AppAccountHourType($post['selectTypeHours']),
new AppAccountHourStatus($post['selectStatusHours']),
$post['duration'],
$from,
$to,
$due,
AppUserServices::getUser($post['selectResponsableHours']),
1,
$post['linkHour'],
!is_null($post['valueHour']) ?floatval($post['valueHour']):null,
!is_null($post['customervalueHour']) ?floatval($post['customervalueHour']):null,
AppUserServices::getUser($post['selectCreatorHours'])
);
$flag = true;
if($actualHours->getAccountHoursType()->getIdAccountHoursType() === AppAccountHourType::BILLED_HOURS){
$params = array(
"ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
"ReferenceCustomer" => $this->_referenceCustomer,
"Increment" => -$actualHours->getDurationInMinutes(),
"DateStamp" => date("c")
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, json_encode($params));
if($data[1] != 200){
$flag = false;
}
}
if($flag){
if(!AppAccountHoursServices::setAccountHours($accountHours)){
$this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
}
else{
$this->addFlash("success", "La modification des heures a bien été réalisée.");
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 ) ){
if($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS and $post['selectTypeHours'] != AppAccountHourType::ONBOARDING_HOURS)
{
if($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
}
}
else{
if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
}
else{
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($actualHours->getDurationInMinutes() + $this->getAttribute('onboardingHoursBalanceInMinutes') - $post['duration']));
}
}
}
if($post['selectTypeHours'] == AppAccountHourType::NEWSLETTERS){
if($actualHours->getAccountHoursType()->getIdAccountHoursType() != $post['selectTypeHours']) {
AppAccountServices::updateBalanceNewsletter($this->_idAccount, false);
}
}
else{
if($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS )
{
AppAccountServices::updateBalanceNewsletter($this->_idAccount, true);
}
}
}
}
else{
$this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
}
}
else{
$this->addFlash("error","Impossible de modifier ces heures. Elles ont déjà été facturées.");
}
}
}
else{
$this->addFlash("error","Une erreur a été rencontré lors de la récupération des heures consommées.");
}
}
else{
$this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
}
}
else{
if($post['formActionHoursConsulting'] == "add"){
$params = array(
"ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
"ReferenceCustomer" => $this->_referenceCustomer,
"Increment" => intval($post['duration']),
"DateStamp" => date("c")
);
$accountHours = new AppAccountHour(
null,
$this->_idAccount,
$this->_idSubscription,
$post['titleHour'],
$post['commentHour'],
new AppAccountHourType($post['selectTypeHours']),
new AppAccountHourStatus($post['selectStatusHours']),
$post['duration'],
$from,
$to,
$due,
AppUserServices::getUser($post['selectResponsableHours']),
0,
$post['linkHour'],
!is_null($post['valueHour']) ? floatval($post['valueHour']) : null,
!is_null($post['customervalueHour']) ?floatval($post['customervalueHour']):null,
AppUserServices::getUser($post['selectCreatorHours'])
);
if($post['selectStatusHours'] == 3)
{
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, json_encode($params));
if ($data[1] == 200) {
if (!AppAccountHoursServices::setAccountHours($accountHours)) {
$this->addFlash("error", "Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
} else {
$this->addFlash("success", "La saisie des heures a bien été réalisée.");
}
} else {
$this->addFlash("error", "Une erreur a été rencontrée lors de la facturation des heures consommées.");
}
}
else{
if (!AppAccountHoursServices::setAccountHours($accountHours)) {
$this->addFlash("error", "Une erreur a été rencontrée lors de l'enregistrement des heures consommées.");
} else {
$this->addFlash("success", "La saisie des heures a bien été réalisée.");
}
}
}
else if($post['formActionHoursConsulting'] == "update"){
if(isset($post['idHour']) and !empty($post['idHour'])){
$actualHours = AppAccountHoursServices::getAccountHoursById($this->_idAccount,$post['idHour']);
if($actualHours){
if(!$actualHours->getIsBilled()){
if($actualHours->getAccountHoursStatus()->getIdAccountHoursStatus() != 3)
{
$actualHours->setDurationInMinutes(0);
}
if(!in_array($actualHours->getAccountHoursType()->getIdAccountHoursType(),$typehoursUpdateProAbono)){
$increment = $post['duration'];
}
else{
$increment = $post['duration'] - $actualHours->getDurationInMinutes();
}
$accountHours = new AppAccountHour(
$post['idHour'],
$this->_idAccount,
$this->_idSubscription,
$post['titleHour'],
$post['commentHour'],
new AppAccountHourType($post['selectTypeHours']),
new AppAccountHourStatus($post['selectStatusHours']),
$post['duration'],
$from,
$to,
$due,
AppUserServices::getUser($post['selectResponsableHours']),
0,
$post['linkHour'],
!is_null($post['valueHour']) ? floatval($post['valueHour']) : null,
!is_null($post['customervalueHour']) ?floatval($post['customervalueHour']):null,
AppUserServices::getUser($post['selectCreatorHours'])
);
if($post['selectStatusHours'] == 3) {
$params = array(
"ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
"ReferenceCustomer" => $this->_referenceCustomer,
"Increment" => $increment,
"DateStamp" => date("c")
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, json_encode($params));
if ($data[1] == 200) {
if (!AppAccountHoursServices::setAccountHours($accountHours)) {
$this->addFlash("error", "Une erreur a été rencontrée lors de la modification des heures consommées.");
} else {
$this->addFlash("success", "La modification des heures a bien été réalisée.");
if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS) {
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount, ($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
}
if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS) {
AppAccountServices::updateBalanceNewsletter($this->_idAccount, true);
}
}
} else {
$this->addFlash("error", "Une erreur a été rencontrée lors de la facturation des heures consommées.");
}
}
else{
if($post['oldStatusHours'] == 3) {
$params = array(
"ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
"ReferenceCustomer" => $this->_referenceCustomer,
"Increment" => -$actualHours->getDurationInMinutes(),
"DateStamp" => date("c")
);
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, json_encode($params));
if($data[1] == 200){
if (!AppAccountHoursServices::setAccountHours($accountHours)) {
$this->addFlash("error","Une erreur a été rencontrée lors de la modification des heures consommées.");
}
else{
$this->addFlash("success","La modification des heures a bien été réalisée.");
}
}
else{
$this->addFlash("error","Une erreur a été rencontrée lors de la modification de la facturation.");
}
}
else{
if (!AppAccountHoursServices::setAccountHours($accountHours)) {
$this->addFlash("error", "Une erreur a été rencontrée lors de la modification des heures consommées.");
} else {
$this->addFlash("success", "La modification des heures a bien été réalisée.");
if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS) {
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount, ($this->getAttribute('onboardingHoursBalanceInMinutes') + $actualHours->getDurationInMinutes()));
}
if ($actualHours->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS) {
AppAccountServices::updateBalanceNewsletter($this->_idAccount, true);
}
}
}
}
}
else{
$this->addFlash("error","Impossible de modifier ces heures. Elles ont déjà été facturées.");
}
}
else{
$this->addFlash("error","Une erreur a été rencontré lors de la récupération des heures consommées.");
}
}
else{
$this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
}
}
else{
$this->addFlash("error","Le formulaire envoyé est incorrect. Veuillez réessayer ultérieurement.");
}
}
}
}
else{
$this->addFlash("error","Certaines données du formulaire sont manquantes ou erronées.");
}
}
else if($this->_request->request->has('formDeleteHour')){
$post = $this->_request->request->get('formDeleteHour');
if(isset($post['idHour']) and !empty($post['idHour'])){
$accountHour = AppAccountHoursServices::getAccountHoursById($this->_idAccount,$post['idHour']);
if($accountHour){
if(!in_array($accountHour->getAccountHoursType()->getIdAccountHoursType(),$typehoursUpdateProAbono)){
if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
$this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
}
else{
$this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
if($accountHour->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::ONBOARDING_HOURS){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,($this->getAttribute('onboardingHoursBalanceInMinutes') + $accountHour->getDurationInMinutes()));
}
if($accountHour->getAccountHoursType()->getIdAccountHoursType() == AppAccountHourType::NEWSLETTERS){
AppAccountServices::updateBalanceNewsletter($this->_idAccount, true);
}
}
}
else{
if(!$accountHour->getIsBilled()){
$params = array(
"ReferenceFeature" => $accountHour->getAccountHoursType()->getaccountHoursMarketingService(),
"ReferenceCustomer" => $this->_referenceCustomer,
"Increment" => -$accountHour->getDurationInMinutes(),
"DateStamp" => date("c")
);
if($post['statusHour'] == 3)
{
$data = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Usage", $this->_tokenProAbono, json_encode($params));
if($data[1] == 200){
if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
$this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
}
else{
$this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
}
}
else{
$this->addFlash("error","Une erreur a été rencontrée lors de la modification de la facturation.");
}
}
else{
if(!AppAccountHoursServices::deleteAccountHours($post['idHour'])){
$this->addFlash("error","Une erreur a été rencontrée lors de la suppression des heures.");
}
else{
$this->addFlash("success","Les heures sélectionnées ont bien été supprimées.");
}
}
}
else{
$this->addFlash("error","Impossible de supprimer ces heures. Elles ont déjà été facturées.");
}
}
}
else{
$this->addFlash("error","Une erreur a été rencontrée lors de la récupération des heures supprimés");
}
}
else{
$this->addFlash("error","Une erreur a été rencontrée lors de la suppression. Veuillez réessayer ultérieurement.");
}
}
}
else{
$this->addFlash("error","Aucune données n'a été envoyée.");
}
if($this->_request->query->has("idAccount")) {
return $this->redirect($this->generateUrl(
'Abonnement_suivi',
array("idAccount" => $this->_idAccount,
"client" => $request->query->get('client', null),
"typeHours" => $request->query->get('typeHours', null),
"statusHours" => $request->query->get('statusHours', null),
"responsable" => $request->query->get('responsable', null),
"creator" => $request->query->get('creator', null),
"retard" => $request->query->get('retard', null),
"futur" => $request->query->get('futur', null),
"historic" => $request->query->get('historic', null),
"datedebut" => $request->query->get('datedebut', null),
"datefin" => $request->query->get('datefin', null)
)
));
}
else{
return $this->redirect("/Abonnement/Suivi");
}
}
$actual_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ($this->_request->query->has("pHours") and $this->_request->query->get("pHours") != "") {
$p = $this->_request->query->get("pHours");
if (strpos($actual_url, "&pHours=") !== false) {
$url_sans_page = str_replace('&pHours=' . urlencode($p), '&pHours=', $actual_url);
}
else if (strpos($actual_url, "?pHours=") !== false) {
$url_sans_page = str_replace('?pHours=' . urlencode($p), '?pHours=', $actual_url);
}
if(intval($p) === 0){
$p = 1;
}
}
else {
$p = 1;
if(empty($_SERVER['QUERY_STRING'])){
$url_sans_page = $actual_url . "?pHours=";
}
else{
$url_sans_page = $actual_url . "&pHours=";
}
}
if($this->_isAdmin)
{
$ArrayCLient = [];
array_push($ArrayCLient, $appAccount->getIdCompany());
$request->query->set('client', $ArrayCLient);
$resultQuery = $this->hoursRecherche($request, $session, $p);
$this->setAttribute('totalHours',$resultQuery['count']);
$this->setAttribute('totalValue',$resultQuery['sum']['totMontant']);
$this->setAttribute('totalCustomValue',$resultQuery['sum']['totCustomMontant']);
$this->setAttribute('nbrPages',$resultQuery['nbrOfPage']);
$this->setAttribute('accountHours', $resultQuery['result']);
$nbrPages =$resultQuery['nbrOfPage'];
}
if($p > $nbrPages){
$p = 1;
}
if (strpos($url_sans_page, "&pHours=") !== false) {
$url_premiere_page = str_replace('&pHours=', '&pHours=1', $url_sans_page);
$url_derniere_page = str_replace('&pHours=', '&pHours='.$nbrPages, $url_sans_page);
}
else if (strpos($url_sans_page, "?pHours=") !== false){
$url_premiere_page = str_replace('?pHours=', '?pHours=1', $url_sans_page);
$url_derniere_page = str_replace('?pHours=', '?pHours='.$nbrPages, $url_sans_page);
}
else{
$url_premiere_page = $url_sans_page . '?pHours=1';
$url_derniere_page = $url_sans_page . '?pHours=' . $nbrPages;
}
$this->setAttribute('url_sans_page',$url_sans_page);
$this->setAttribute('url_premiere_page',$url_premiere_page);
$this->setAttribute('url_derniere_page',$url_derniere_page);
$this->setAttribute('numero_de_page',$p);
$this->setAttribute('companyClientList', AdministrationServices::getAllCompanyClient());
$endStatusHours = AppAccountHoursServices::getEndStatusHours();
$stopStatusHours = AppAccountHoursServices::getStopStatusHours();
$listIdHistoricStatus = array_map(function($e) {
return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
}, $endStatusHours);
$listIdStopStatus = array_map(function($e) {
return is_object($e) ? $e->getIdAccountHoursStatus() : $e['idAccountHoursStatus'];
}, $stopStatusHours);
$this->setAttribute('arrayHistoricStatus', $listIdHistoricStatus);
$this->setAttribute('arrayStopStatus', $listIdStopStatus);
$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(null, null, null, new ReflectionExtractor())];
$serializer = new Serializer($normalizers, $encoders);
$hoursType = AppAccountHoursServices::getHoursType();
$hoursStatus = AppAccountHoursServices::getHoursStatus();
$this->setAttribute('hoursStatus', json_decode($serializer->serialize($hoursStatus, 'json')));
$this->setAttribute('hoursTypesSerial',json_decode($serializer->serialize($hoursType, 'json')));
$this->setAttribute('hoursTypes',$hoursType);
$accountUsers = AppUserServices::getAccountUsers(AppAccount::VenteCoeff);
uasort($accountUsers,function($a, $b){
return $a->firstName <=> $b->firstName;
});
$this->setAttribute('responsablesSerial', json_decode($serializer->serialize($accountUsers, 'json')));
if($request->query->get('typeHours', null) != null)
{
$currentHoursStatus = AppAccountHoursServices::getHoursStatusByTypeHours($request->query->get('typeHours', null));
}
$this->setAttribute('currentHoursStatus',$currentHoursStatus);
$this->setAttribute('responsables',AppUserServices::getAccountUsers(AppAccount::VenteCoeff));
$this->setAttribute('isAdmin',$this->_isAdmin);
#$this->setAttribute('current',$this->_proAbonoUserState["current"]);
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/Parametre", name="Abonnement_parametre")
* @Route("/Abonnement/Parametre", name="abonnement_parametre")
* @return Response
* @throws Exception
*/
public function abonnementParametre(SessionInterface $session, Request $request)
{
$this->setAttribute('search', $request->get('search'));
if(!empty($_POST)){
$searchExistingRoutine = "formAccount_service_routine_list-select-idroutine-";
$searchNewRoutine = "formAccount_service_routine_list-select-new-";
$arrayRequest = $this->_request->request;
foreach ($arrayRequest as $key => $value) {
if (strpos($key, $searchExistingRoutine) !== false) {
$id = str_replace($searchExistingRoutine, "", $key);
//update la colonne dans la bdd
if(strpos($key, '-deleted') !== false){
RoutineServices::updateRoutineScoreMinAllowAlert($value, null);
}else{
RoutineServices::updateRoutineScoreMinAllowAlert($value, $this->_request->request->get("formAccount_service_routine_scoremin-idroutine-".$id));
}
}
if (strpos($key, $searchNewRoutine) !== false) {
$id = str_replace($searchNewRoutine, "", $key);
//update la colonne dans la bdd
if(strpos($key, '-deleted') !== false){
RoutineServices::updateRoutineScoreMinAllowAlert($value, null);
}else{
RoutineServices::updateRoutineScoreMinAllowAlert($value, $this->_request->request->get("formAccount_service_routine_scoremin-new-".$id));
}
}
}
}
if($this->_request->query->has("fromMenu")){
$this->setAttribute('fromMenu',true);
}
$this->setAttribute('shownPart','parametre');
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$routineList = RoutineServices::getRoutines($this->_idAccount);
$appAccountRoutineList = RoutineServices::getRoutineForAdmin($this->_idAccount);
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
foreach ($appAccount->getUsers() as &$user){
if($this->isSupportUser($user->getEmail())){
$user->setIsSupport(true);
}
else{
$user->setIsSupport(false);
}
$user->setMailAccounts(AppMailAccountServices::getMailAccountByIdUser($user->getId()));
}
$allUsers = $appAccount->getUsers();
$this->setAttribute('appAccount', $appAccount);
$this->setAttribute('routineList', $routineList);
$this->setAttribute('appAccountRoutineList', $appAccountRoutineList);
$this->setAttribute('userResponsableAccount',$this->_userResponsableAccount);
$this->setAttribute('isAdmin',$this->_isAdmin);
$this->setAttribute("customFieldList", AppCustomFieldServices::getCustomFieldList());
$this->setAttribute('user', $this->_user);
$this->setAttribute('account_users',$allUsers);
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/Facture", name="Abonnement_facture")
* @Route("/Abonnement/Facture", name="abonnement_facture")
* @return Response
*
* @throws Exception
*/
public function abonnementFacture(Request $request)
{
$this->setAttribute('shownPart','facture');
$this->setAttribute('search', $request->get('search'));
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount',$appAccount);
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if (!$this->_isOlder) {
$invoices = [];
$defaultUrl = $this->_urlProAbono . "/v1/Invoices?ReferenceCustomer=" . $this->_referenceCustomer . "&SizePage=".self::$NBRPERPAGE."&Page=";
$data = $this->_api->callApi("GET", $defaultUrl."1" , $this->_tokenProAbono, false);
$status = $data[1];
if ($status == 200) {
$actual_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$totalInvoices = $data[0]['TotalItems'];
$nbrPages = intval(ceil($totalInvoices / self::$NBRPERPAGE));
if ($this->_request->query->has("p") and $this->_request->query->get("p") != "") {
$p = $this->_request->query->get("p");
if (strpos($actual_url, "&p=") !== false) {
$url_sans_page = str_replace('&p=' . urlencode($p), '&p=', $actual_url);
}
else if (strpos($actual_url, "?p=") !== false) {
$url_sans_page = str_replace('?p=' . urlencode($p), '?p=', $actual_url);
}
if(intval($p) === 0){
$p = 1;
}
} else {
$p = 1;
if(empty($_SERVER['QUERY_STRING'])){
$url_sans_page = $actual_url . "?p=";
}
else{
$url_sans_page = $actual_url . "&p=";
}
}
if($p > $nbrPages){
$p = 1;
}
if (strpos($url_sans_page, "&p=") !== false) {
$url_premiere_page = str_replace('&p=', '&p=1', $url_sans_page);
$url_derniere_page = str_replace('&p=', '&p='.$nbrPages, $url_sans_page);
}
else if (strpos($url_sans_page, "?p=") !== false){
$url_premiere_page = str_replace('?p=', '?p=1', $url_sans_page);
$url_derniere_page = str_replace('?p=', '?p='.$nbrPages, $url_sans_page);
}
else{
$url_premiere_page = $url_sans_page . '?p=1';
$url_derniere_page = $url_sans_page . '?p=' . $nbrPages;
}
if($p == 1){
$invoices = array_merge($invoices, $data[0]['Items']);
}
else{
$data = $this->_api->callApi("GET", $defaultUrl.$p , $this->_tokenProAbono, false);
if($data[1] == 200){
$invoices = array_merge($invoices, $data[0]['Items']);
}
}
usort($invoices,function($a,$b){
return strtotime($b['DateIssue']) - strtotime($a['DateIssue']);
});
$this->setAttribute('url_sans_page',$url_sans_page);
$this->setAttribute('url_premiere_page',$url_premiere_page);
$this->setAttribute('url_derniere_page',$url_derniere_page);
$this->setAttribute('numero_de_page',$p);
$this->setAttribute('totalHours',$totalInvoices);
$this->setAttribute('nbrPages',$nbrPages);
}
$this->setAttribute('invoices', $invoices);
}
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
return $this->render('abonnement/index.html.twig', $this->attribute);
}
/**
* @Route("/Abonnement/SuiviUserEdit", name="Abonnement_suivi_user_edit")
* @Route("/Abonnement/SuiviUserEdit", name="abonnement_suivi_user_edit")
* @return Response
*
* @throws Exception
*/
public function abonnementSuiviUserEdit()
{
$this->setAttribute('shownPart','suivibackoffice');
$success = false;
$message = "";
if ($this->_request->isMethod("POST")) {
if($this->_request->request->has('addEditCommercial')) {
$post = $this->_request->request->get('addEditCommercial');
if(isset($post['selectCommercial']) ){
if(AppAccountServices::updateCommercialUser($this->_idAccount, $post['selectCommercial']))
{
$success = true;
$message = "Le commercial de l'abonnement a bien été changé.";
}
else
{
$success = false;
$message = "Une erreur est survenue lors de l'enregistrement du commercial.";
}
}
else{
$success = false;
$message = "Certaines données du formulaire sont manquantes ou erronées.";
}
}
if($this->_request->request->has('addEditCSM')) {
$post = $this->_request->request->get('addEditCSM');
if(isset($post['selectCSM']) ){
if(AppAccountServices::updateCSMUser($this->_idAccount, $post['selectCSM']))
{
$success = true;
$message = "Le CSM de l'abonnement a bien été changé.";
}
else
{
$success = false;
$message = "Une erreur est survenue lors de l'enregistrement du CSM.";
}
}
else{
$success = false;
$message = "Certaines données du formulaire sont manquantes ou erronées.";
}
}
if($this->_request->request->has('addEditSupport')) {
$post = $this->_request->request->get('addEditSupport');
if(isset($post['selectSupport']) ){
if(AppAccountServices::updateSupportUser($this->_idAccount, $post['selectSupport']))
{
$success = true;
$message = "Le support client de l'abonnement a bien été changé.";
}
else
{
$success = false;
$message = "Une erreur est survenue lors de l'enregistrement du support client.";
}
}
else{
$success = false;
$message = "Certaines données du formulaire sont manquantes ou erronées.";
}
}
}
$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer(null, null, null, new ReflectionExtractor())];
$serializer = new Serializer($normalizers, $encoders);
return new JsonResponse([
'success' => $success,
'message' => $message,
'data' => null
]);
}
/**
* @Route("/Abonnement/Paiement", name="Abonnement_paiement")
* @Route("/Abonnement/Paiement", name="abonnement_paiement")
* @return Response
*
* @throws Exception
*/
public function abonnementPaiement(Request $request)
{
$this->setAttribute('shownPart','paiement');
$this->setAttribute('search', $request->get('search'));
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$this->setAttribute('appAccount',$appAccount);
try{
if(!$this->_proAbonoUserState){
throw new Exception();
}
if($this->_isTerminated and !$this->_isAdmin){
throw new Exception("Une maintenance des abonnements est en cours, veuillez réessayer dans quelques minutes.",01);
}
if(!$this->_isOlder or $this->_request->get("ajax") or ($this->_isOlder and !empty($this->_proAbonoUserState['delayed']))){
if($this->_isFreemium and !$this->_request->get("ajax") and empty($this->_proAbonoUserState['delayed'])){
throw new Exception("Désolé mais votre abonnement ne vous permet pas de configurer un moyen de paiement.", 01);
}
else {
$flag = false;
$iframe = null;
if ($this->_request->isMethod("POST")) {
if(isset($_POST['formUpdateBillingAdress'])){
$post = $_POST['formUpdateBillingAdress'];
foreach ($post as &$value) {
$value = ltrim($value);
$value = rtrim($value);
}
if (isset($post['Email']) and !empty($post['Email'])
and isset($post['FirstName']) and !empty($post['FirstName'])
and isset($post['LastName']) and !empty($post['LastName'])
and isset($post['Company']) and !empty($post['Company'])
and isset($post['AddressLine1']) and !empty($post['AddressLine1'])
and isset($post['ZipCode']) and !empty($post['ZipCode'])
and isset($post['City']) and !empty($post['City'])){
$email = new \stdClass();
$email->Email = $post['Email'];
$customerInfos = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Customer?ReferenceCustomer=" . $this->_referenceCustomer, $this->_tokenProAbono, json_encode($email), false, true);
if (array_key_exists("Email", $post)) {
unset($post['Email']);
}
$billingAdress = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/CustomerBillingAddress?ReferenceCustomer=" . $this->_referenceCustomer, $this->_tokenProAbono, json_encode($post), false, true);
if (array_key_exists('Links', $customerInfos[0])) {
foreach ($customerInfos[0]['Links'] as $link) {
if ($link['rel'] == "hosted-register") {
$iframe = $link['href'];
}
}
}
if ($billingAdress[1] == 200 && $customerInfos[1] == 200) {
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => 200
));
}
else{
$flag = true;
$this->setAttribute('customerInfos', $customerInfos[0]);
$this->setAttribute('billingAdress', $billingAdress[0]);
$this->addFlash('success', "Les coordonnées de facturation ont bien été mise à jour.");
}
} else {
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => 404,
'errorBillingAdress' => $billingAdress,
'errorCustomerInfos' => $customerInfos
));
}
else{
$this->addFlash('error', "Une erreur a été rencontrée lors de la mise à jour de vos coordonnées.");
}
}
} else {
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);
}
}
else if(isset($_POST['formAddBankDetails'])){
$post = $_POST['formAddBankDetails'];
if(isset($post['owner']) and !empty(isset($post['owner']))
and isset($post['iban']) and !empty(isset($post['iban']))
and isset($post['bic']) and !empty(isset($post['bic']))
and isset($post['rum']) and !empty(isset($post['rum']))){
$payload = array(
"IdBusiness" => $this->_idBusiness,
"IdAccount" => $this->_idAccountProabono,
"IdCustomer" => $this->_idCustomer,
"NameDisplay" => $post['rum'],
"DataGateway" => array(
"ReferenceMandate" => $post['rum'],
"Iban" => $post['iban'],
"Bic" => $post['bic'],
"NameCustomer" => $post['owner'],
"DateSignature" => date("Y-m-d")
)
);
$callApi = $this->_api->callApi("POST",$this->_urlBackOfficeProAbono."/Gateway/GatewayPermissions", $this->_tokenProAbono, json_encode($payload), false, true);
$code = $callApi[1];
if($code == 201){
$details_iv = EncryptionService::generateIv();
$details_key = AppAccountBankDetailsServices::getEncryptionkey();
$details = new AppAccountBankDetails(
$this->_idAccount,
$this->_user['idUser'],
EncryptionService::encrypt($post['owner'], $details_iv, $details_key),
EncryptionService::encrypt($post['iban'], $details_iv, $details_key),
EncryptionService::encrypt($post['bic'], $details_iv, $details_key),
EncryptionService::encrypt($post['rum'], $details_iv, $details_key),
new DateTime("now", new DateTimeZone("Europe/Paris")),
(isset($post['link']) and !empty($post['link'])) ? $post['link'] : null,
null,
null,
$details_iv
);
if(AppAccountBankDetailsServices::setAccountBankDetails($details)){
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => 200
));
}
else{
$this->addFlash('success', "Le mandat de prélèvement a bien été signé.");
}
}
else{
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => 404,
'error' => "Erreur lors de l'ajout du mandat de prélèvement en base"
));
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
}
else{
if($code == 422){
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => $code,
'error' => "Erreur dans les champs du mandat de prélèvement",
'callApi' => $callApi
));
}
else{
$this->addFlash('error', "L'IBAN et/ou le BIC saisis ne sont pas valide, veuillez vérifier votre saisie.");
}
}
else{
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => $code,
'error' => "Erreur Proabono lors de la signature du mandat de prélèvement",
'callApi' => $callApi
));
}
else{
$this->addFlash('error', "Une erreur a été rencontrée lors de l'enregistrement du mandat de prélèvement. Veuillez réessayer ultérieurement.");
}
}
}
}
}
}
$this->setAttribute('countries', RegCountryServices::getCountryList());
$paymentSettings = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/CustomerSettingsPayment?ReferenceCustomer=" . $this->_referenceCustomer . "&page=1", $this->_tokenProAbono, false );
if ($paymentSettings[1] != "200") {
if ($paymentSettings[1] != "204") {
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);
}
} else {
$this->setAttribute('paymentType', $paymentSettings[0]['TypePayment']);
}
if (!$flag) {
$customerInfos = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/Customer?ReferenceCustomer=" . $this->_referenceCustomer . "&page=1", $this->_tokenProAbono, false);
$status = $customerInfos[1];
if ($status != 200) {
if ($status != 204) {
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);
}
} else {
$this->setAttribute('customerInfos', $customerInfos[0]);
$billingAdress = $this->_api->callApi("GET", $this->_urlProAbono . "/v1/CustomerBillingAddress?ReferenceCustomer=" . $this->_referenceCustomer . "&page=1", $this->_tokenProAbono, false);
if ($billingAdress[1] != "200") {
if ($billingAdress[1] != "204") {
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);
}
} else {
$this->setAttribute('billingAdress', $billingAdress[0]);
}
}
if(is_null($iframe)){
if (array_key_exists('Links', $customerInfos[0])) {
foreach ($customerInfos[0]['Links'] as $link) {
if ($link['rel'] == "hosted-register") {
$iframe = $link['href'];
}
}
}
}
$this->setAttribute('iframe', $iframe);
}
$this->setAttribute('RUM',"COEF".$this->_referenceCustomer.time());
if($paymentSettings[0]['TypePayment'] == "Batch"){
$callApi = $this->_api->callApi("GET",$this->_urlBackOfficeProAbono."/Gateway/GatewayPermissions?IdBusiness=".$this->_idBusiness."&StatePermission=Enabled&TypeGateway=BatchSepa&IdCustomer=".$this->_idCustomer, $this->_tokenProAbono, false);
if(isset($callApi) && $callApi != "" && $callApi != null) {
if ($callApi[1] == 200) {
if (count($callApi[0]['Items']) > 1) {
usort($callApi[0]['Items'], function ($a, $b) {
return strtotime($b['DateCreation']) - strtotime($a['DateCreation']);
});
}
$this->setAttribute("mandateLink", AppAccountBankDetailsServices::getAccountMandateLinkByIdAccount($this->_idAccount));
$this->setAttribute('appAccountBankDetails', $callApi[0]['Items'][0]);
} else {
throw new Exception("Une erreur a été rencontrée lors de la récupération de votre moyen de paiement.", 02);
}
}
}
}
}
}
catch(Exception $e){
if($this->_request->get("ajax")){
return new JsonResponse(array(
'status' => 404,
'error' => $e->getMessage()
));
}
else{
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else {
if ($e->getCode() == 02) {
$error['code'] = $e->getCode();
$error['message'] = $e->getMessage();
$this->setAttribute('error', $error);
} else {
$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.");
}
}
}
}
if($this->_request->get("ajax")){
if($this->_request->get("step") == 1){
$this->setAttribute("subscription",true);
return $this->render('abonnement/onglets/paiement/abonnement_paiement_form.html.twig', $this->attribute);
}
else{
$this->setAttribute('collapse',true);
return $this->render('abonnement/onglets/paiement/abonnement_paiement_type_with_modal_sepa.html.twig', $this->attribute);
}
}
else{
return $this->render('abonnement/index.html.twig', $this->attribute);
}
}
/**
* @Route("/abonnement/proabono/refresh", name="abonnement_proabono_refresh")
* @param $idCustomer
* @param Boolean $fromTrigger
* @param Boolean $fromScript
* @return Response
* @throws Exception
*/
public function abonnementRefresh($idCustomer,Bool $fromTrigger = false, $fromScript = false, Int $idSubscription = null){
$error = false;
try {
if(!is_null($idCustomer)) {
$api = new CallApi();
$confProAbono = BaseController::getConfig()['proabono-api'];
$urlProAbono = $confProAbono['url'];
$urlBackOfficeProAbono = $confProAbono['url-backOffice'];
$tokenProAbono = $confProAbono['token'];
$idBusiness = $confProAbono['idBusiness'];
$segmentProAbono = $confProAbono['ref-segment'];
$urlAfterSynchro = $confProAbono['urlAfterSynchro'];
$p = '/v1/Subscriptions?IdCustomer=' . $idCustomer . '&page=1';
$currentSubscription = null;
$dataSouscription = $api->callApi('GET', $urlProAbono . $p, $tokenProAbono, false, $fromScript);
$referenceCustomer = null;
if ($dataSouscription[1] === 200) {
if (!empty($dataSouscription[0]['Items'])){
$next = true;
while ($next) {
for ($v = 0; $v < count($dataSouscription[0]['Items']); $v++) {
if (is_null($referenceCustomer)) {
$referenceCustomer = $dataSouscription[0]['Items'][$v]['ReferenceCustomer'];
}
if ($dataSouscription[0]['Items'][$v]['Status'] == 'Active') {
$currentSubscription = $dataSouscription[0]['Items'][$v];
break;
}
}
if (array_key_exists('Links', $dataSouscription[0]) && is_null($currentSubscription)) {
if ($dataSouscription[0]['Links'][0]['rel'] == 'next') {
$dataSouscription = $api->callApi('GET', $urlProAbono . $dataSouscription[0]['Links'][0]['href'], $tokenProAbono, false, $fromScript);
} else if (count($dataSouscription[0]['Links']) > 1 && $dataSouscription[0]['Links'][1]['rel'] == 'next') {
$dataSouscription = $api->callApi('GET', $urlProAbono . $dataSouscription[0]['Links'][1]['href'], $tokenProAbono, false, $fromScript);
} else {
$next = false;
}
} else {
$next = false;
}
}
if (is_null($currentSubscription)) {
if (is_null($referenceCustomer)) {
throw new Exception("Impossible de retrouver un abonnement actif. Une erreur a été rencontrée lors de la récupération du ReferenceCustomer.");
}
$params = array(
"ReferenceCustomer" => $referenceCustomer,
"ReferenceOffer" => AppAccountType::REFERRAL,
"Metadata" => [
"event" => "createdAfterPreviousSubscriptionEnded",
]
);
$toReferral = $api->callApi('POST', $urlProAbono . "/v1/Subscription?tryStart=true", $tokenProAbono, json_encode($params), $fromScript);
if ($toReferral[1] !== 201) {
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.");
} else {
$countSubscriptions = $api->callApi("GET", $urlBackOfficeProAbono . "/Sub/Subscriptions?IdBusiness=".$idBusiness."&IdCustomer=".$idCustomer, $tokenProAbono, false, $fromScript);
if($countSubscriptions[1] == 200){
$params = array(
"Name" => "Abonnement ".$countSubscriptions[0]['TotalItems']
);
$api->callApi("PATCH", $urlBackOfficeProAbono . "/Sub/Subscriptions/" . $toReferral[0]['Id']. "&IdBusiness=" . $idBusiness, $tokenProAbono, json_encode($params), $fromScript);
}
$currentSubscription = $toReferral[0];
}
} else {
if(!is_null($idSubscription)){
if ($idSubscription != $currentSubscription['Id']) {
throw new Exception("L'id d'abonnement envoyée ne correspond pas à l'abonnement running. Pas besoin de refresh.");
}
}
}
$idAccountType = $currentSubscription['ReferenceOffer'];
$idSubscription = $currentSubscription['Id'];
$idAccount = null;
$identifiedNumber = $currentSubscription['ReferenceCustomer'];
$dateUpdate = $currentSubscription['DateUpdate'];
if (strpos($identifiedNumber, "814045571") !== false) {
$keyword = str_replace("814045571", "", $identifiedNumber);
$idAccount = AppAccountServices::getAccountByKeyword($keyword)->getId();
} else if (strpos($identifiedNumber, "749836292") !== false) {
$keyword = str_replace("749836292", "", $identifiedNumber);
$idAccount = AppAccountServices::getAccountByKeyword($keyword)->getId();
} else {
$idAccount = AppAccountServices::getAccountBySiren($identifiedNumber)->getId();
}
$appAccount = AppAccountServices::getAccount($idAccount);
$appAccount->setIdSubscription($idSubscription);
$setAccountEndDateFlag = true;
if($idAccountType == AppAccountType::DESACTIVE){
$appAccount->setAccountEndDate(null);
$appAccount->setAccountRenewalDate(null);
$appAccount->setAccountDateStart(null);
$appAccount->setAccountDatePeriodStart(null);
$appAccount->setAccountDatePeriodEnd(null);
}
else{
if(array_key_exists("DateStart",$currentSubscription)){
$appAccount->setAccountDateStart(new DateTime($currentSubscription['DateStart']));
AppAccountServices::setAccountDateStart($appAccount);
}
if(array_key_exists("DatePeriodEnd",$currentSubscription) && array_key_exists("DatePeriodStart",$currentSubscription)){
$appAccount->setAccountDatePeriodStart(new DateTime($currentSubscription['DatePeriodStart']));
$appAccount->setAccountDatePeriodEnd(new DateTime($currentSubscription['DatePeriodEnd']));
AppAccountServices::setAccountDatePeriod($appAccount);
}
if(array_key_exists("StateSubscriptionAfterTerm",$currentSubscription)){
if($currentSubscription['StateSubscriptionAfterTerm'] == "Terminated" or $currentSubscription['StateSubscriptionAfterTerm'] == "History" or $currentSubscription['StateSubscriptionAfterTerm'] == "EndedTerminated" or $currentSubscription['StateSubscriptionAfterTerm'] == "EndedComplete"){
$appAccount->setAccountEndDate(new DateTime($currentSubscription['DateTerm']));
$appAccount->setAccountRenewalDate(null);
}
else{
$terminationStatusOfCurrentSubscription = AppAccountTerminationServices::getTerminationStatusOfCurrentSubscription($currentSubscription['Id']);
if($terminationStatusOfCurrentSubscription){
if($terminationStatusOfCurrentSubscription->getTerminationStatus()->getIdTerminationStatus() == AppAccountTerminationStatus::EN_RESILIATION){// SI une resil en cours sur cet abonnement (idTermination Status 1 & idSubscription) on touche pas la date
$appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
$setAccountEndDateFlag = false;
}
else{
$appAccount->setAccountEndDate(null);
$appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
}
}
else{
$appAccount->setAccountEndDate(null);
$appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
}
}
}
else{
$appAccount->setAccountEndDate(null);
$appAccount->setAccountRenewalDate(new DateTime($currentSubscription['DateTerm']));
}
}
AppAccountServices::setAccountRenewalDate($appAccount);
AppAccountServices::setAccountIdSubscription($appAccount);
if($setAccountEndDateFlag){
AppAccountServices::setAccountEndDate($appAccount);
}
if ($idAccountType == AppAccountType::DESACTIVE) {
if ($appAccount->getType()->getId() != $idAccountType) {
$appAccountType = new AppAccountType($idAccountType);
$appAccount->setType($appAccountType);
if (!AppAccountServices::setAccountType($appAccount)) {
throw new Exception("Erreur lors de la mise à jour de l'idAccountType de l'abonnement (abonnement désactivé)");
}
}
$accountUser = AppUserServices::getAccountUsers($appAccount->getId());
if (!empty($appAccount->getServices())) {
if (!empty($accountUser)) {
if (!Services_coefficy_utilisateurs::deleteAllUsers($appAccount->getId())) {
throw new Exception("Erreur lors de la suppression de l'abonnement (abonnement désactivé)");
} else {
if (!AppUserServices::setMailAccountIsActiveByIdAccount($appAccount->getId(), false)) {
throw new Exception("Erreur lors de la desactivation du mailAccount de l'utilisateur (abonnement désactivé)");
} else {
if (!ActionLinkServices::desactiveUserLinksByIdAccount($appAccount->getId())) {
throw new Exception("Erreur lors de la desactivation des liens de l'utilisateur (abonnement désactivé)");
}
}
}
}
if (!AppAccountServices::deleteAllServices($idAccount)) {
throw new Exception("Erreur lors de la suppression des services (désactivé)");
} else {
AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
return new JsonResponse(array(
'message' => "L'abonnement a bien été désactivé"
), 200);
}
} else {
if (!empty($accountUser)) {
if (!Services_coefficy_utilisateurs::deleteAllUsers($appAccount->getId())) {
throw new Exception("Erreur lors de la suppression de l'abonnement (abonnement désactivé)");
} else {
if (!AppUserServices::setMailAccountIsActiveByIdAccount($appAccount->getId(), false)) {
throw new Exception("Erreur lors de la desactivation du mailAccount de l'utilisateur (abonnement désactivé)");
} else {
if (!ActionLinkServices::desactiveUserLinksByIdAccount($appAccount->getId())) {
throw new Exception("Erreur lors de la desactivation des liens de l'utilisateur (abonnement désactivé)");
}
}
}
}
AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
return new JsonResponse(array(
'message' => "L'abonnement a bien été désactivé (uniquement la désactivation des utilisateurs)"
), 200);
}
}
$nextPage = true;
$p = '/v1/Usages?IdCustomer=' . $idCustomer . '&page=1';
$items = [];
while ($nextPage) {
$data = $api->callApi('GET', $urlProAbono . $p, $tokenProAbono, false, $fromScript);
if($data[1] == 200){
if (array_key_exists('Links', $data[0])) {
if ($data[0]['Links'][0]['rel'] == 'next') {
$items = array_merge($items, $data[0]['Items']);
$p = $data[0]['Links'][0]['href'];
} else if (count($data[0]['Links']) > 1 && $data[0]['Links'][1]['rel'] == 'next') {
$items = array_merge($items, $data[0]['Items']);
$p = $data[0]['Links'][1]['href'];
} else {
$items = array_merge($items, $data[0]['Items']);
$nextPage = false;
}
} else {
$items = array_merge($items, $data[0]['Items']);
$nextPage = false;
}
} else {
throw new Exception();
}
}
$accountServices = [];
$nbLicences = null;
for ($i = 0; $i < count($items); $i++) {
if($items[$i]['TypeFeature'] == "OnOff"){
if(!$items[$i]['IsEnabled']){
continue;
}
}
$idCategory = explode('-', $items[$i]['ReferenceFeature'])[0];
$idServiceMarketing = explode('-', $items[$i]['ReferenceFeature'])[1];
$serviceList = AppServiceServices::getServicesToActivate($idCategory, $idServiceMarketing);
foreach ($serviceList as $key => $serviceObj) {
if($serviceObj->getId() == AppService::NB_USER){
if(array_key_exists("QuantityIncluded",$items[$i])){
$inc = $items[$i]['QuantityIncluded'];
}
else{
$inc = INF;
}
if(array_key_exists("QuantityCurrent",$items[$i])){
$c = $items[$i]['QuantityCurrent'];
}
else{
$c = 0;
}
if(!is_infinite($inc)){
if($c > $inc){
$nbLicences = $c;
}
else{
$nbLicences = $inc;
}
}
else{
$nbLicences = null;
}
}
if ($serviceObj->getServiceType()->getId() == AppServiceType::OnOff) {
$service = $this->createServiceOnOff($serviceObj->getId());
}
elseif ($serviceObj->getServiceType()->getId() == AppServiceType::Consommation) {
if ($serviceObj->getId() == AppService::LIMITATION_RECHERCHE_LINKEDIN) {
$service = $this->createServiceConsumption($serviceObj->getId(), $items[$i], $idAccount, $nbLicences, $appAccount->getAccountLinkedinSearchQuotaPerUser());
} else {
$service = $this->createServiceConsumption($serviceObj->getId(), $items[$i]);
}
}
elseif ($serviceObj->getServiceType()->getId() == AppServiceType::Limitation) {
$service = $this->createServiceLimitation($serviceObj->getId(), $idAccount, $items[$i],$fromScript);
}
if($items[$i]['TypeFeature'] == "Consumption" && $service->getServiceType()->getId() == AppServiceType::Consommation){
$service->setIsBilled(true);
}else{
$service->setIsBilled(false);
}
$accountServices[$service->getId()] = $service;
}
}
$currentServices = AppServiceServices::getAccountServices($idAccount);
$toDelete = [];
$toAdd = [];
foreach ($currentServices as $key => $oldService) {
if (!array_key_exists($key, $accountServices)) {
$toDelete[$key] = $oldService;
}
}
foreach ($accountServices as $key => $newService) {
if (!array_key_exists($key, $currentServices)) {
$toAdd[$key] = $newService;
unset($accountServices[$key]);
}
}
if (!empty($toDelete)) {
if (!AppAccountServices::deleteServices($toDelete, $appAccount)) {
throw new Exception("Erreur lors de la suppression des services");
}
}
if (!empty($toAdd)) {
foreach ($toAdd as $key => $ServiceAdded) {
if ($key == AppService::REDACTION_6_NEWSLETTER) {
AppAccountServices::setAccountBalanceNewsletter($idAccount, 0.5);
}
if ($key == AppService::REDACTION_12_NEWSLETTER) {
AppAccountServices::setAccountBalanceNewsletter($idAccount, 1);
}
if ($key == AppService::REDACTION_24_NEWSLETTER) {
AppAccountServices::setAccountBalanceNewsletter($idAccount, 2);
}
if ($key == AppService::REDACTION_2_CONTENU) {
AppAccountServices::setAccountBalanceNewsletter($idAccount, 0.16);
}
}
if (!AppAccountServices::addServices($toAdd, $appAccount)) {
throw new Exception("Erreur lors de l'ajout des services");
}
}
if (!AppAccountServices::updateServices($accountServices, $appAccount)) {
throw new Exception("Erreur lors de l'update des services");
}
$appAccount = AppAccountServices::getAccountWithoutService($idAccount);
if ($appAccount->getType()->getId() != $idAccountType) {
$appAccountType = new AppAccountType($idAccountType);
$appAccount->setType($appAccountType);
if (!AppAccountServices::setAccountType($appAccount)) {
throw new Exception("Erreur lors de l'update de l'idAccountType");
}
}
if (array_key_exists(AppService::CRM, $accountServices) || array_key_exists(AppService::PERSONA_FINDER, $accountServices)) {
CamPersonaServices::giveDefaultPersona($appAccount->getId(), false, $appAccount->getType()->getId());
}
}
else{
throw new Exception("Il n'y a aucun abonnement à récupérer.");
}
} else {
return new JsonResponse(array(
'error' => "Ce client n'a aucun abonnement (en cours, résilié, ou propal).",
'dump' => $dataSouscription
),400);
}
}
else{
throw new Exception("IdCustomer manquant");
}
}
catch(Exception $e){
return new JsonResponse(array(
'error' => $e->getMessage(),
'line' => $e->getLine()
),400);
}
AppAccountServices::updateSynchroDate($appAccount->getId(), $dateUpdate);
return new JsonResponse(array(
'message' => "Le refresh est OK",
'servicesAjoutés' => $toAdd,
'servicesSupprimés' => $toDelete,
'servicesMisAJour' => $accountServices
),200);
}
/**
* @Route("/Abonnement/Suivi/abonnementGetIdSubscription", name="abonnement_get_idsubscription")
* @Route("/Administration/Suivi/abonnementGetIdSubscription", name="administration_get_idsubscription")
* @param RequestStack $requestStack
* * @param Request $request
* @param SessionInterface $session
* @return Response
* @throws Exception
*/
public function abonnementGetIdSubscription(RequestStack $requestStack, Request $request, SessionInterface $session) : Response
{
$error = false;
$idSubscription = null;
if (!( in_array(AppService::ACCES_SUIVI_CLIENT, $session->get('user')['services']) && in_array($session->get('user')['idUserType'], AppUserType::UT_ADMIN)) && !$session->get('user')['supportMode']) {
throw new AccessDeniedHttpException();
}
try {
if (!is_null($request->get('idAccount', null))) {
$api = new CallApi();
$confProAbono = BaseController::getConfig()['proabono-api'];
$tokenProAbono = $confProAbono['token'];
$idBusiness = $confProAbono['idBusiness'];
$urlProAbono = $confProAbono['url'];
$urlBackOfficeProAbono = $confProAbono['url-backOffice'];
$currentHoursStatus = null;
$idAccount = $request->query->get('idAccount', null);
$appAccount = AppAccountServices::getAccount($idAccount);
$idCompany = $appAccount->getIdCompany();
if ($idCompany == RegCompany::COEFFICY or $idCompany == RegCompany::BUSINESS_SHARE) {
$referenceCustomer = RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber() . substr($idAccount, 0, 41);
} else {
if (is_null($idCompany)) {
$referenceCustomer = null;
} else {
$referenceCustomer = RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber();
}
}
$foobar = new AbonnementController($requestStack,$session); // correct
//$proAbonoUserState = $foobar->getOffres($api, $urlBackOfficeProAbono, $urlProAbono, $tokenProAbono, $referenceCustomer, $idBusiness);
$idSubscription = $appAccount->getIdSubscription();
}else{
return new JsonResponse(array(
'code' => 500,
'idSubscription' => null
),500);
}
}
catch(Exception $e){
return new JsonResponse(array(
'error' => $e->getMessage(),
'line' => $e->getLine()
),400);
}
return new JsonResponse(array(
'code' => 200,
'idSubscription' => $idSubscription
),200);
}
/**
* @Route("/Abonnement/Suivi/abonnementIncrementUsage", name="abonnement_increment_usage")
* @Route("/Administration/Suivi/abonnementIncrementUsage", name="administration_increment_usage")
* @param RequestStack $requestStack
* @param Request $request
* @param SessionInterface $session
* @return Response
* @throws Exception
*/
public function abonnementIncrementUsage(RequestStack $requestStack, Request $request, SessionInterface $session) : Response
{
$error = false;
$idSubscription = null;
try {
if ($this->_request->isMethod("POST")) {
$increment = $_POST['increment'];
$idAccount = $_POST['idAccount'];
$accountHoursType = $_POST['accountHoursType'];
if(is_null($increment) || !$idAccount || !$accountHoursType){
return new JsonResponse(array(
'error' => 'true',
'code' => 500,
'reason' => 'input manquant'
),500);
}
$appAccount = AppAccountServices::getAccount($idAccount);
$idCompany = $appAccount->getIdCompany();
if ($idCompany == RegCompany::COEFFICY or $idCompany == RegCompany::BUSINESS_SHARE) {
$referenceCustomer = RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber() . substr($idAccount, 0, 41);
} else {
if (is_null($idCompany)) {
$referenceCustomer = null;
} else {
$referenceCustomer = RegCompanyServices::getCompany($idCompany)->getIdentifiedNumber();
}
}
$api = new CallApi();
$confProAbono = BaseController::getConfig()['proabono-api'];
$tokenProAbono = $confProAbono['token'];
$idBusiness = $confProAbono['idBusiness'];
$urlProAbono = $confProAbono['url'];
$urlBackOfficeProAbono = $confProAbono['url-backOffice'];
$currentHoursStatus = null;
$typeHours = AppAccountHoursServices::getHoursTypeById($accountHoursType);
$params = array(
"ReferenceFeature" => $typeHours->getaccountHoursMarketingService(),
"ReferenceCustomer" => $referenceCustomer,
"Increment" => $increment,
"DateStamp" => date("c")
);
$data = $api->callApi("POST", $urlProAbono . "/v1/Usage", $tokenProAbono, json_encode($params));
if($data[1] !== 200){
return new JsonResponse(array(
'error' => 'true',
'code' => 500,
'reason' => $data
),500);
}
}else{
return new JsonResponse(array(
'error' => 'true',
'code' => 500
),500);
}
}
catch(Exception $e){
return new JsonResponse(array(
'error' => $e->getMessage(),
'line' => $e->getLine()
),400);
}
return new JsonResponse(array(
'code' => 200,
'idSubscription' => $idSubscription
),200);
}
/**
* @Route("/invoice/get", name="invoice_get")
* @return JsonResponse
* @throws Exception
*/
public function invoiceGet()
{
if (0 === strpos($this->_request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($this->_request->getContent(), true);
$this->_request->request->replace(is_array($data) ? $data : array());
}
return new JsonResponse(array(
'status' => 200,
'headers' => $this->_request->headers->all(),
'body'=> $this->_request->request->all(),
'POST' => $_POST
));
}
/**
* @Route("/trigger/refresh", name="trigger_refresh")
* @return JsonResponse
* @throws Exception
*/
public function triggerRefresh()
{
try{
$data = json_decode($this->_request->getContent(), true);
if(array_key_exists("TypeTrigger",$data)){
if($data['TypeTrigger'] == "SubscriptionRenewed" or $data['TypeTrigger'] == "SubscriptionTerminatedForUpgrade" or $data['TypeTrigger'] == "SubscriptionTerminated" or $data['TypeTrigger'] == "SubscriptionHistory"){
$idAccount = AppAccountServices::getAccountBySiren($data['Customer']['ReferenceCustomer'])->getId();
AppAccountHoursServices::setAllBillableHoursBilled($idAccount,$data['Subscription']['Id']);
}
}
if(array_key_exists("fromScript",$data['Customer'])){
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $data['Customer']['Id'],
'fromTrigger' => TRUE,
'fromScript' => TRUE,
'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
]);
}
else{
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $data['Customer']['Id'],
'fromTrigger' => TRUE,
'fromScript' => FALSE,
'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
]);
}
return $response;
/*
if($this->_request->headers->has('x-proabono-key') && $this->_request->headers->has('x-proabono-signature')){
$confProAbono = BaseController::getConfig()['proabono-api'];
$keyBusiness = $confProAbono['webhookKey'];
$calculated_hash = base64_encode(hash('sha256',$this->_request->headers->get('x-proabono-key').$keyBusiness,true));
if($this->_request->headers->get('x-proabono-signature') == $calculated_hash){
$data = json_decode($this->_request->getContent(), true);
$response = $this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $data['Customer']['Id'],
'fromTrigger' => TRUE,
'idSubscription' => array_key_exists("Subscription",$data) ? $data['Subscription']['Id'] : null
]);
return $response;
}
}
*/
}
catch(Exception $e){
return new JsonResponse(array(
'error' => $e->getMessage(),
'line' => $e->getLine()
),400);
}
return $this->redirectToRoute('Homepage');
}
public function createServiceOnOff($idService): AppService
{
$service = new AppService($idService, null);
$serviceType = new AppServiceType(AppServiceType::OnOff, 'OnOff');
$service->setServiceType($serviceType);
$accountServices[$service->getId()] = $service;
$service->setSolde(1);
return $service;
}
public function createServiceConsumption($idService, $item, $idAccount = false, $nbLicences = false, $quotaPerUser = false): AppService
{
$service = new AppService($idService, null);
$serviceType = new AppServiceType(AppServiceType::Consommation, 'Consommation');
$service->setServiceType($serviceType);
if(array_key_exists("QuantityIncluded",$item)){
$included = $item['QuantityIncluded'];
if($idService == AppService::LIMITATION_RECHERCHE_LINKEDIN){
if(is_null($nbLicences)){
$nbLicences = AppUserServices::getAccountUsersWithLicence($idAccount)['nb'];
}
$service->setNbLimit(floor($nbLicences * $quotaPerUser));
}
else{
$service->setNbLimit($included);
}
}
else{
if($idService == AppService::LIMITATION_RECHERCHE_LINKEDIN){
if(is_null($nbLicences)){
$nbLicences = AppUserServices::getAccountUsersWithLicence($idAccount)['nb'];
}
$service->setNbLimit(floor($nbLicences * $quotaPerUser));
}
else{
$service->setNbLimit(0);
}
}
if(array_key_exists("QuantityCurrent",$item)){
$current = $item['QuantityCurrent'];
$service->setSolde($current);
}
else{
$service->setSolde(0);
}
return $service;
}
public function createServiceLimitation($idService, $idAccount, $item, $fromScript): AppService
{
$api = new CallApi();
$confProAbono = BaseController::getConfig()['proabono-api'];
$urlProAbono = $confProAbono['url'];
$tokenProAbono = $confProAbono['token'];
$service = new AppService($idService, null);
$serviceType = new AppServiceType(AppServiceType::Limitation, 'Limitation');
$service->setServiceType($serviceType);
$arrServiceLimited = intval(AppServiceServices::getNumberLimited($idAccount, $idService)['nb']);
$outOfBundle = false;
if(array_key_exists("QuantityIncluded",$item)){
$included = $item['QuantityIncluded'];
$service->setNbLimit($included);
}
else{
$service->setNbLimit(null);
$included = INF;
}
if(array_key_exists("QuantityCurrent",$item)){
$current = $item['QuantityCurrent'];
}
else{
$current = 0;
}
if(!is_infinite($included)){
if($current > $included){
$outOfBundle = true;
$solde = $current - $arrServiceLimited;
}
else{
$solde = $included - $arrServiceLimited;
}
if ($solde < 0) {
$num = abs($solde);
$solde = 0;
if ($idService == AppService::NB_USER && $idService >= 1) {
$users = AppUserServices::getAccountUsersToDesactive($idAccount, $num);
for ($a = 0; $a < count($users); $a++) {
AppUserServices::setActiveTokenLicence($users[$a]->getId(), false);
}
} else if ($idService == AppService::ROUTINE) {
$routines = RoutineServices::getRoutineToDraft($idAccount, $num);
for ($a = 0; $a < count($routines); $a++) {
RoutineServices::setRoutineToDraftById($routines[$a]['idSupply']);
}
}
}
}
else{
$solde = null;
}
$service->setSolde($solde);
if((!$outOfBundle && $idService == AppService::NB_USER) or (!$outOfBundle && $idService == AppService::ROUTINE)){
$arrServiceLimited = intval(AppServiceServices::getNumberLimited($idAccount, $idService)['nb']);
$params = json_encode(
array(
"ReferenceFeature" => $item['ReferenceFeature'],
"IdSubscription" => $item['IdSubscription'],
"QuantityCurrent" => $arrServiceLimited,
"DateStamp" => date('Y-m-d\TH:i:s')
)
);
$data = $api->callApi("POST", $urlProAbono . "/v1/Usage", $tokenProAbono, $params, $fromScript);
}
return $service;
}
public function getOffres($api, $urlBackOfficeProAbono, $urlProAbono, $tokenProAbono, $referenceCustomer, $idBusiness){
try{
$current = null;
$propal = [];
$delayed = [];
$outOfBundleCurrent = [];
$limitations = [];
$onOff = [];
$consos = [];
$next = true;
$idActiveSubscription = null;
$idCustomer = null;
if(is_null($referenceCustomer)){
$this->_isOlder = true;
$this->_isFreemium = false;
}
else{
$data = $api->callApi('GET', $urlBackOfficeProAbono.'/Sub/Subscriptions?ReferenceCustomer='.$referenceCustomer. "&IdBusiness=" . $idBusiness, $tokenProAbono, false);
if($data[1] == 200){
if(empty($data[0]['Items'])){
$data = $api->callApi('GET', $urlProAbono.'/v1/Customer?ReferenceCustomer='.$referenceCustomer. "&IdBusiness=" . $idBusiness, $tokenProAbono, false);
if($data[1] == 200){
$this->_isOlder = true;
$this->_isFreemium = false;
$idCustomer = $data[0]['Id'];
}
else{
if($data[1] !== 403){
throw new Exception();
}
}
}
else{
$terminated = [];
$firstRunningSubscriptionMet = false;
while($next) {
for ($v = 0; $v < count($data[0]['Items']); $v++) {
$idCustomer = $data[0]['Items'][$v]['IdCustomer'];
if ($data[0]['Items'][$v]['Status'] == 'Active' and !$firstRunningSubscriptionMet) {
if($data[0]['Items'][$v]['Name'] == "SOUSCRIT, EN COURS"){
$countSubscriptions = $this->_api->callApi("GET", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$data[0]['Items'][$v]['IdCustomer'], $this->_tokenProAbono, false);
if($countSubscriptions[1] == 200){
$this->renameSubscription($data[0]['Items'][$v]['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
}
}
$firstRunningSubscriptionMet = true;
$idActiveSubscription = $data[0]['Items'][$v]['Id'];
$activeSubscriptionWithAdditionalInfos = $api->callApi('GET', $urlProAbono . '/v1/Subscription?IdSubscription=' . $idActiveSubscription.'&html=false', $tokenProAbono, false);
$this->_isEngaged = false;
if(array_key_exists("IsEngaged",$activeSubscriptionWithAdditionalInfos[0])){
if($activeSubscriptionWithAdditionalInfos[0]['IsEngaged']){
$this->_isEngaged = true;
}
}
/* $this->_isTrial = false;
if(array_key_exists("IsTrial",$activeSubscriptionWithAdditionalInfos[0])){
if($activeSubscriptionWithAdditionalInfos[0]['IsTrial'] and !in_array($activeSubscriptionWithAdditionalInfos[0]['ReferenceOffer'],AppAccountType::UT_MIGRATED_WITH_TRIAL)){
$this->_isTrial = true;
}
}*/
$dataActif = $api->callApi('GET', $urlProAbono.'/v1/Offer?html=false&idOffer='.$data[0]['Items'][$v]['IdOffer'].'&language=fr', $tokenProAbono, false);
if($activeSubscriptionWithAdditionalInfos[0]['ReferenceOffer'] == AppAccountType::DESACTIVE){
if(!$this->_isAdmin){
$this->_session->remove("user");
SessionUtilisateur::checkUtilisateur($this->_session);
}
else{
$this->_isDisabled = true;
$current["offer"] = $dataActif[0];
$current["subscription"] = $activeSubscriptionWithAdditionalInfos[0];
}
}
$featuresActiveSubscription = $api->callApi('GET', $urlBackOfficeProAbono . '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' . $data[0]['Items'][$v]['Id'], $tokenProAbono, false);
if($dataActif[1] == 200 && $activeSubscriptionWithAdditionalInfos[1] == 200 && $featuresActiveSubscription[1] == 200){
if(array_key_exists("ReferenceOffer",$dataActif[0])){
if($dataActif[0]['ReferenceOffer'] === AppAccountType::REFERRAL){
$this->_isFreemium = true;
}
}
$loop = true;
$features = [];
while($loop) {
for ($x = 0; $x < count($featuresActiveSubscription[0]['Items']); $x++) {
$array[$x] = $featuresActiveSubscription[0]['Items'][$x];
foreach ($activeSubscriptionWithAdditionalInfos[0]['Features'] as $f) {
if($f['ReferenceFeature'] == $featuresActiveSubscription[0]['Items'][$x]['ReferenceFeature']){
if(array_key_exists('TitleLocalized',$f)){
$array[$x]['TitleLocalized'] = $f['TitleLocalized'];
}
if(array_key_exists('PricingLocalized',$f)){
$array[$x]['PricingLocalized'] = $f['PricingLocalized'];
}
if(array_key_exists('TypeFeature',$f)){
$array[$x]['TypeFeature'] = $f['TypeFeature'];
}
}
}
$features[] = $array[$x];
}
if (array_key_exists('Links', $featuresActiveSubscription[0])) {
if ($featuresActiveSubscription[0]['Links'][0]['rel'] == 'next') {
$featuresActiveSubscription = $api->callApi('GET', $urlBackOfficeProAbono . $featuresActiveSubscription[0]['Links'][0]['href'], $tokenProAbono, false);
} else if (count($featuresActiveSubscription[0]['Links']) > 1 && $featuresActiveSubscription[0]['Links'][1]['rel'] == 'next') {
$featuresActiveSubscription = $api->callApi('GET', $urlBackOfficeProAbono . $featuresActiveSubscription[0]['Links'][1]['href'], $tokenProAbono, false);
} else {
$loop = false;
}
} else {
$loop = false;
}
}
usort($features,function($a,$b){
return $a['Id'] - $b['Id'];
});
$activeSubscriptionWithAdditionalInfos[0]['Features'] = $features;
$current["offer"] = $dataActif[0];
$current["subscription"] = $activeSubscriptionWithAdditionalInfos[0];
}
}
else {
if (($data[0]['Items'][$v]['StateSubscription'] == 'InitiatedAgent' or $data[0]['Items'][$v]['StateSubscription'] == 'DraftAgent') && array_key_exists('DateStart', $data[0]['Items'][$v]) &&
$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'])) ) {
if($data[0]['Items'][$v]['Name'] != "Proposition commerciale"){
$this->renameSubscription($data[0]['Items'][$v]['Id'],"Proposition commerciale");
}
$activePropalWithAdditionalInfos = $api->callApi('GET', $urlProAbono . '/v1/Subscription?IdSubscription=' . $data[0]['Items'][$v]['Id'].'&html=false', $tokenProAbono, false);
$propalOffer = $api->callApi('GET', $urlProAbono . '/v1/Offer?html=false&idOffer=' . $data[0]['Items'][$v]['IdOffer'] . '&language=fr', $tokenProAbono, false);
$featuresActivePropal = $api->callApi('GET', $urlBackOfficeProAbono . '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' . $data[0]['Items'][$v]['Id'], $tokenProAbono, false);
if ($propalOffer[1] == 200 && $activePropalWithAdditionalInfos[1] == 200 and $featuresActivePropal[1] == 200) {
$loop = true;
$features = [];
while($loop) {
for ($x = 0; $x < count($featuresActivePropal[0]['Items']); $x++) {
$array[$x] = $featuresActivePropal[0]['Items'][$x];
foreach ($activePropalWithAdditionalInfos[0]['Features'] as $f) {
if($f['ReferenceFeature'] == $featuresActivePropal[0]['Items'][$x]['ReferenceFeature']){
if(array_key_exists('TitleLocalized',$f)){
$array[$x]['TitleLocalized'] = $f['TitleLocalized'];
}
if(array_key_exists('PricingLocalized',$f)){
$array[$x]['PricingLocalized'] = $f['PricingLocalized'];
}
if(array_key_exists('TypeFeature',$f)){
$array[$x]['TypeFeature'] = $f['TypeFeature'];
}
}
}
$features[] = $array[$x];
}
if (array_key_exists('Links', $featuresActivePropal[0])) {
if ($featuresActivePropal[0]['Links'][0]['rel'] == 'next') {
$featuresActivePropal = $api->callApi('GET', $urlBackOfficeProAbono . $featuresActivePropal[0]['Links'][0]['href'], $tokenProAbono, false);
} else if (count($featuresActivePropal[0]['Links']) > 1 && $featuresActivePropal[0]['Links'][1]['rel'] == 'next') {
$featuresActivePropal = $api->callApi('GET', $urlBackOfficeProAbono . $featuresActivePropal[0]['Links'][1]['href'], $tokenProAbono, false);
} else {
$loop = false;
}
} else {
$loop = false;
}
}
usort($features,function($a,$b){
return $a['Id'] - $b['Id'];
});
$activePropalWithAdditionalInfos[0]['Features'] = $features;
$propal[$data[0]['Items'][$v]['Id']] = array("offer" => $propalOffer[0],
"propal" => $activePropalWithAdditionalInfos[0]
);
$outOfBundlePropal = [];
foreach ($propal[$data[0]['Items'][$v]['Id']]["propal"]['Features'] as &$feature) {
if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption'){
if(array_key_exists('QuantityCurrent', $feature)){
$quantityCurrent = $feature['QuantityCurrent'];
}
else{
$quantityCurrent = 0;
$feature['QuantityCurrent'] = $quantityCurrent;
}
if(array_key_exists('QuantityIncluded', $feature)){
$quantityIncluded = $feature['QuantityIncluded'];
}
else{
$quantityIncluded = null;
$feature['QuantityIncluded'] = $quantityIncluded;
}
}
$price = 0;
if (array_key_exists('PricingLocalized', $feature)) {
$price = (string)preg_replace('/[^0-9\.]/', "", $feature['PricingLocalized']);
if(substr($price,strlen($price)-1) == "."){
$price = substr_replace($price,"",-1);
}
}
$feature['price'] = $price;
if ($feature['TypeFeature'] == 'Limitation') {
if(!is_null($quantityIncluded)){
if ($quantityCurrent > $quantityIncluded) {
$outOfBundlePropal[] = $feature;
}
}
}
if ($feature['TypeFeature'] == 'OnOff') {
if($feature['IsIncluded'] == false && $feature['IsEnabled'] == true)
{
$outOfBundlePropal[] = $feature;
}
}
if ($feature['TypeFeature'] == 'Consumption') {
if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
{
$outOfBundlePropal[] = $feature;
}
}
}
if(count($outOfBundlePropal) > 0){
$propal[$data[0]['Items'][$v]['Id']]['outOfBundle'] = $outOfBundlePropal;
}
}
}
else if ( ($data[0]['Items'][$v]['StateSubscription'] == 'InitiatedAgent' or $data[0]['Items'][$v]['StateSubscription'] == 'DraftAgent') && array_key_exists("Metadata",$data[0]['Items'][$v])) {
if(array_key_exists("newSubscription",$data[0]['Items'][$v]['Metadata'])
and array_key_exists("delayed",$data[0]['Items'][$v]['Metadata'])
and $data[0]['Items'][$v]['Metadata']['delayed'] == true){
$delayedPropalWithAdditionalsInfos = $api->callApi('GET', $urlProAbono . '/v1/Subscription?IdSubscription=' . $data[0]['Items'][$v]['Id'].'&html=false', $tokenProAbono, false);
$propalOffer = $api->callApi('GET', $urlProAbono . '/v1/Offer?html=false&idOffer=' . $data[0]['Items'][$v]['IdOffer'] . '&language=fr', $tokenProAbono, false);
$featuresDelayedPropal = $api->callApi('GET', $urlBackOfficeProAbono . '/Sub/SubscriptionFeatures/?IdBusiness='.$idBusiness.'&IdSubscription=' . $data[0]['Items'][$v]['Id'], $tokenProAbono, false);
if ($propalOffer[1] == 200 && $delayedPropalWithAdditionalsInfos[1] == 200 && $featuresDelayedPropal[1] == 200) {
$loop = true;
$features = [];
while($loop) {
for ($x = 0; $x < count($featuresDelayedPropal[0]['Items']); $x++) {
$array[$x] = $featuresDelayedPropal[0]['Items'][$x];
foreach ($delayedPropalWithAdditionalsInfos[0]['Features'] as $f) {
if($f['ReferenceFeature'] == $featuresDelayedPropal[0]['Items'][$x]['ReferenceFeature']){
if(array_key_exists('TitleLocalized',$f)){
$array[$x]['TitleLocalized'] = $f['TitleLocalized'];
}
if(array_key_exists('PricingLocalized',$f)){
$array[$x]['PricingLocalized'] = $f['PricingLocalized'];
}
if(array_key_exists('TypeFeature',$f)){
$array[$x]['TypeFeature'] = $f['TypeFeature'];
}
}
}
$features[] = $array[$x];
}
if (array_key_exists('Links', $featuresDelayedPropal[0])) {
if ($featuresDelayedPropal[0]['Links'][0]['rel'] == 'next') {
$featuresDelayedPropal = $api->callApi('GET', $urlBackOfficeProAbono . $featuresDelayedPropal[0]['Links'][0]['href'], $tokenProAbono, false);
} else if (count($featuresDelayedPropal[0]['Links']) > 1 && $featuresDelayedPropal[0]['Links'][1]['rel'] == 'next') {
$featuresDelayedPropal = $api->callApi('GET', $urlBackOfficeProAbono . $featuresDelayedPropal[0]['Links'][1]['href'], $tokenProAbono, false);
} else {
$loop = false;
}
} else {
$loop = false;
}
}
usort($features,function($a,$b){
return $a['Id'] - $b['Id'];
});
$delayedPropalWithAdditionalsInfos[0]['Features'] = $features;
$delayed['offer'] = $propalOffer[0];
$delayed['propal'] = $delayedPropalWithAdditionalsInfos[0];
$outOfBundleDelayedPropal = [];
foreach ($delayed['propal']['Features'] as &$feature) {
if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption') {
if (array_key_exists('QuantityCurrent', $feature)) {
$quantityCurrent = $feature['QuantityCurrent'];
} else {
$quantityCurrent = 0;
$feature['QuantityCurrent'] = $quantityCurrent;
}
if (array_key_exists('QuantityIncluded', $feature)) {
$quantityIncluded = $feature['QuantityIncluded'];
} else {
$quantityIncluded = null;
$feature['QuantityIncluded'] = $quantityIncluded;
}
}
$price = 0;
if (array_key_exists('PricingLocalized', $feature)) {
$price = (string)preg_replace('/[^0-9\.]/', "", $feature['PricingLocalized']);
if(substr($price,strlen($price)-1) == "."){
$price = substr_replace($price,"",-1);
}
}
$feature['price'] = $price;
if ($feature['TypeFeature'] == 'Limitation') {
if(!is_null($quantityIncluded)){
if ($quantityCurrent > $quantityIncluded) {
$outOfBundleDelayedPropal[] = $feature;
}
}
}
if ($feature['TypeFeature'] == 'Consumption') {
if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
{
$outOfBundleDelayedPropal[] = $feature;
}
}
}
if(count($outOfBundleDelayedPropal) > 0){
$delayed['outOfBundle'] = $outOfBundleDelayedPropal;
}
}
}
}
if($data[0]['Items'][$v]['Status'] == 'Ended'){
if(empty($terminated)){
if(is_null($idActiveSubscription)){
$idActiveSubscription = $data[0]['Items'][$v]['Id'];
}
$terminated[] = $data[0]['Items'][$v];
}
}
}
}
if (array_key_exists('Links', $data[0])) {
if ($data[0]['Links'][0]['rel'] == 'next') {
$data = $api->callApi('GET', $urlBackOfficeProAbono . $data[0]['Links'][0]['href'], $tokenProAbono, false);
} else if (count($data[0]['Links']) > 1 && $data[0]['Links'][1]['rel'] == 'next') {
$data = $api->callApi('GET', $urlBackOfficeProAbono . $data[0]['Links'][1]['href'], $tokenProAbono, false);
} else {
$next = false;
}
} else {
$next = false;
}
}
if(is_null($current) and !empty($terminated)){
$dataActif = $api->callApi('GET', $urlProAbono.'/v1/Offer?html=false&idOffer='.$terminated[0]['IdOffer'].'&language=fr', $tokenProAbono, false);
if($dataActif[1] == 200){
$this->_isTerminated = true;
$current["offer"] = $dataActif[0];
$current["subscription"] = $terminated[0];
}
else{
throw new Exception();
}
}
if(is_null($current) and empty($terminated) and !empty($propal)){
$this->_isOlder = true;
$this->_isFreemium = false;
$idCustomer = reset($propal)['propal']['IdCustomer'];
}
if(!$this->_isTerminated and !$this->_isDisabled and !$this->_isOlder and !is_null($current)) {
foreach ($current['subscription']['Features'] as &$feature) {
if($feature['TypeFeature'] == 'Limitation' or $feature['TypeFeature'] == 'Consumption') {
if (array_key_exists('QuantityCurrent', $feature)) {
$quantityCurrent = $feature['QuantityCurrent'];
} else {
$quantityCurrent = 0;
$feature['QuantityCurrent'] = $quantityCurrent;
}
if (array_key_exists('QuantityIncluded', $feature)) {
$quantityIncluded = $feature['QuantityIncluded'];
} else {
$quantityIncluded = null;
$feature['QuantityIncluded'] = $quantityIncluded;
}
}
$price = 0;
if (array_key_exists('PricingLocalized', $feature)) {
$price = (string)preg_replace('/[^0-9\.]/', "", $feature['PricingLocalized']);
if(substr($price,strlen($price)-1) == "."){
$price = substr_replace($price,"",-1);
}
}
$feature['ReferenceCustomer'] = $current['subscription']['ReferenceCustomer'];
$feature['price'] = $price;
if ($feature['TypeFeature'] == 'Limitation') {
if (!is_null($quantityIncluded)) {
if($quantityCurrent > $quantityIncluded){
$outOfBundleCurrent[] = $feature;
}
}
$limitations[] = $feature;
}
else if($feature['TypeFeature'] == 'OnOff'){
$onOff[] = $feature;
}
else if ($feature['TypeFeature'] == 'Consumption') {
if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
{
$outOfBundleCurrent[] = $feature;
}
$consos[] = $feature;
}
}
}
}
}
else{
if($data[1] == 204){
$data = $api->callApi('GET', $urlProAbono.'/v1/Customer?ReferenceCustomer='.$referenceCustomer, $tokenProAbono, false);
if($data[1] == 200){
$this->_isOlder = true;
$this->_isFreemium = false;
$idCustomer = $data[0]['Id'];
}
}
else{
throw new Exception();
}
}
}
$retour = [];
$retour["IdCustomer"] = $idCustomer;
$retour["current"] = $current;
$retour["propal"] = $propal;
$retour["delayed"] = $delayed;
$retour["current"]["limitations"] = $limitations;
$retour["current"]["onoff"] = $onOff;
$retour["current"]["consos"] = $consos;
$retour["current"]["outOfBundle"] = $outOfBundleCurrent;
$retour["current"]["IdActiveSubscription"] = $idActiveSubscription;
}
catch(Exception $e){
$retour = false;
}
return $retour;
}
/**
* @Route("/Abonnement/Adjust", name="Abonnement_adjust")
* @Route("/Abonnement/Adjust", name="abonnement_adjust")
*/
public function adjust(){
try{
$fromAdmin = false;
if ($this->_request->isMethod("POST")) {
if(!empty($_POST)){
$currentFeature = $_POST['currentFeatures'];
$features = $_POST['Feature'];
if(isset($_POST['fromAdmin']) and !empty($_POST['fromAdmin'])){
$fromAdmin = $_POST['fromAdmin'];
}
$params = array();
foreach ($features as $key => $feature){
if(array_key_exists("IsEnabled",$features[$key])){
if($features[$key]['IsEnabled'] !== $currentFeature[$key]['IsEnabled']){
$params[] = $features[$key];
}
}
else if(array_key_exists("QuantityCurrent",$features[$key])){
if($features[$key]['QuantityCurrent'] !== $currentFeature[$key]['QuantityCurrent']){
$params[] = $features[$key];
}
}
}
if(count($params) > 0){
$dataActif = $this->_api->callApi('POST', $this->_urlProAbono . '/v1/Usages', $this->_tokenProAbono, json_encode($params), false, false);
if($dataActif[1] !== 200){
throw new Exception("Une erreur a été rencontrée lors de la mise à jour des caractéristiques de votre abonnement.");
}
else{
$params = array(
"ReferenceCustomer" => $this->_referenceCustomer
);
$bill = $this->_api->callApi('POST', $this->_urlProAbono . '/v1/Billing/Customer', $this->_tokenProAbono, json_encode($params), false, false);
$this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
}
}
else{
if($fromAdmin){
return $this->redirectToRoute('abonnement', ['idAccount' => $fromAdmin]);
}
else{
return $this->redirectToRoute('abonnement', []);
}
}
}
else{
throw new Exception("Aucune données n'a été envoyée.");
}
}
else{
throw new Exception("Aucune données n'a été envoyée.");
}
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$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.");
}
}
if($fromAdmin){
return $this->redirectToRoute('abonnement', ['idAccount' => $fromAdmin]);
}
else{
return $this->redirectToRoute('abonnement', []);
}
}
/**
* @Route("/Abonnement/NewCgv", name="Abonnement_newCgv")
* @Route("/Abonnement/NewCgv", name="abonnement_newCgv")
*/
public function setNewCgvAfterSubscription(){
try{
if ($this->_request->isMethod("POST")) {
if(!empty($_POST)){
if(isset($_POST['cgvText']) and !empty($_POST['cgvText']) and isset($_POST['idAccountType']) and !empty($_POST['idAccountType'])){
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
foreach ($appAccount->getUsers() as $user) {
if(!in_array($user->getType()->getId(),AppUserType::UT_ADMIN)) {
$data = Services_coefficy_utilisateurs::setNewCGV($user, $_POST['cgvText']);
if($user->getId() == $this->_user['idUser']){
AppTermsOfServiceServices::setAcceptedTermsAfterSubscription($this->_user,$data);
}
}
if($_POST['idAccountType'] == AppAccountType::START){
Services_coefficy_utilisateurs::setNewUserCampaignEngagedContactDailyQuota($user,15);
}
}
return new JsonResponse(array(
'status' => 200
));
}
else{
throw new Exception();
}
}
else{
throw new Exception();
}
}
else{
throw new Exception();
}
}
catch(Exception $e){
if ($this->_request->isMethod("POST")) {
return new JsonResponse(array(
'status' => 400,
'error' => $e->getMessage()
));
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
return $this->redirectToRoute('Abonnement');
}
/**
* @Route("/Abonnement/DeleteCgv", name="Abonnement_deleteCgv")
* @Route("/Abonnement/DeleteCgv", name="abonnement_deleteCgv")
*/
public function deleteCgvAfterSubscription(){
try{
if ($this->_request->isMethod("POST")) {
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
foreach ($appAccount->getUsers() as $user) {
Services_coefficy_utilisateurs::deleteLastCgv($user);
}
}
else{
throw new Exception();
}
}
catch(Exception $e){
return new JsonResponse(array(
'status' => 400,
'error' => $e->getMessage()
));
}
return new JsonResponse(array(
'status' => 200
));
}
/**
* @Route("/Abonnement/Subscribe", name="Abonnement_subscribe")
* @Route("/Abonnement/Subscribe", name="abonnement_subscribe")
*/
public function subscribe(){
try{
$exception = null;
if ($this->_request->isMethod("POST")) {
if(!empty($_POST)){
$delayed = false;
if(!isset($_POST['propal']) or empty($_POST['propal'])){
throw new Exception("E1");
}
$propal = json_decode($_POST['propal'],true);
if(isset($_POST['DateStart']) and !empty($_POST['DateStart'])){
$dateStart = date("Y-m-d", strtotime(str_replace('/','-',$_POST['DateStart'])));
$d = new DateTime();
$today = $d->format('Y-m-d');
if(strtotime($dateStart) > strtotime($today)){
$delayed = true;
$dateStart = $dateStart . "T00:00:00.00Z";
$features = array(
"DateStart" => $dateStart,
"ReferenceCustomer" => $this->_referenceCustomer,
"ReferenceOffer" => $propal['ReferenceOffer'],
"Features" => array_values($_POST['Feature']),
"Metadata" => [
"newSubscription" => true,
"delayed" => true,
"isOlder" => $this->_isOlder,
"DateSubscription" => $d->format("c"),
]
);
/* if(isset($propal['Metadata']))
{
$features['Metadata']= array_merge($features['Metadata'], $propal['Metadata'] );
}*/
}
else if(strtotime($dateStart) == strtotime($today)){
$features = array(
"ReferenceCustomer" => $this->_referenceCustomer,
"ReferenceOffer" => $propal['ReferenceOffer'],
"Features" => array_values($_POST['Feature']),
"Metadata" => [
"newSubscription" => true,
"delayed" => false,
"isOlder" => $this->_isOlder,
"DateSubscription" => $d->format("c"),
"previousPropal" => $propal['Id']
]
);
/*if(isset($propal['Metadata']))
{
$features['Metadata']= array_merge($features['Metadata'], $propal['Metadata'] );
}*/
}
else{
throw new Exception("E3");
}
}
else{
throw new Exception("E4");
}
$upgradeToTrialOrUpgradeWithFees = ((in_array($propal['ReferenceOffer'],AppAccountType::UT_TRIAL)) or (in_array($propal['ReferenceOffer'],AppAccountType::UT_START_FEES)) ? true : false);
foreach($features['Features'] as &$feature){
if(array_key_exists("Steps",$feature)){
$feature['Steps'] = json_decode($feature['Steps'],true);
if($feature['ReferenceFeature'] == "10-03" ||$feature['ReferenceFeature'] == "8-23" )
{
if(isset($feature['Steps'][0]['AmountCeiling']) and !isset($feature['Steps'][0]['AmountPerIncrement']))
{
$feature['QuantityCurrent'] = 1;
}
}
}
if(array_key_exists("QuantityIncluded",$feature)){
if($feature['QuantityIncluded'] == ""){
$feature['QuantityIncluded'] = null;
}
else{
$feature['QuantityIncluded'] = intval($feature['QuantityIncluded']);
}
}
if(array_key_exists("QuantityCurrent",$feature)){
$feature['QuantityCurrent'] = intval($feature['QuantityCurrent']);
}
}
$keys = array("AmountUpFront","AmountTrial","DurationTrial","UnitTrial","AmountRecurrence","DurationRecurrence","UnitRecurrence","CountRecurrences","CountMinRecurrences","AmountTermination");
$params = array();
$nameOffer = "";
if(array_key_exists("TitleLocalized",$propal)){
$nameOffer = $propal['TitleLocalized'];
$params['TitleLocalized'] = $propal['TitleLocalized'];
}
foreach ($keys as $key){
if(array_key_exists($key,$propal)){
$params[$key] = $propal[$key];
}
else{
if($key === "AmountUpFront"){
$params[$key] = 0;
}
}
}
$array = array_merge($params,$features);
// SI UN UPGRADE EST DEJA PREVUE, ON L'ANNULE
if(!$this->_isOlder){
if($this->_proAbonoUserState['current']['subscription']['StateSubscription'] == "UpgradeAtRenewal" or $this->_proAbonoUserState['current']['subscription']['StateSubscription'] == "ActiveDelayedUpgrade"){
$this->_api->callApi("POST", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$this->_idSubscription."/CancelUpgrade". '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
}
}
$refreshOnBoardingHours = false;
$onboardingHoursBalance = AppAccountServices::getAccountOnboardingHoursBalanceInMinutes($this->_idAccount);
if(!$onboardingHoursBalance){
$onboardingHoursBalance = 0;
}
// Si on passe d'un plan payant à un plan payant avec heures d'onboarding, on reporte les heures
if(in_array($propal['ReferenceOffer'],AppAccountType::UT_OFFERS_WITH_9_ONBOARDING_HOURS_INCLUDED)){
$creditOnboarding = AppAccountTypeServices::getcreditOnboardingHoursInMinutes($propal['ReferenceOffer']);
if(!isset($creditOnboarding))
{
$creditOnboarding = 0;
}
$refreshOnBoardingHours = true;
$newOnboardingHoursBalance = $onboardingHoursBalance + $creditOnboarding;
/*if(array_key_exists("AmountUpFront",$propal)){
if($propal["AmountUpFront"] > 0){
}
}*/
}
$createNewSubscription = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Subscription?ReferenceOffer=".$propal['ReferenceOffer']."&ReferenceCustomer=".$this->_referenceCustomer."&tryStart=false", $this->_tokenProAbono, json_encode($array));
if($createNewSubscription[1] == 201){
$this->renameSubscription($createNewSubscription[0]['Id'],"Abonnement ".$createNewSubscription[0]['TitleLocalized']." en attente de démarrage");
if(!$this->_isOlder){
// ON ANNULE LA RESILIATION SI IL Y EN A UNE
$this->cancelTermination($this->_idSubscription,$nameOffer);
}
if(!$delayed){
if($this->_isEngaged){
$data = array(
"CountMinRecurrences" => null
);
$removeEngagement = $this->_api->callApi("PATCH", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$this->_idSubscription. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, json_encode($data));
if($removeEngagement[1] !== 200){
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
$exception = $removeEngagement;
throw new Exception("E6");
}
}
if($this->_isOlder){
$start = $this->_api->callApi('POST', $this->_urlProAbono."/v1/Subscription/" . $createNewSubscription[0]['Id'] . "/Start?BillNow=true", $this->_tokenProAbono, false);
if($start[1] != 200){
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
}
else{
$this->renameSubscription($start[0]['Id'], "Abonnement 1");
if($refreshOnBoardingHours){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
}
}
}
else{
// SI L'OFFRE A DES FRAIS DE DEMARRAGE OU UNE PERIODE ESSAI, ON FAIT UN RESIL START
if($upgradeToTrialOrUpgradeWithFees){
$terminate = $this->_api->callApi('POST', $this->_urlProAbono."/v1/Subscription/" . $this->_idSubscription . "/Termination?Immediate=true", $this->_tokenProAbono, false);
if($terminate[1] != 200){
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
throw new Exception("E6");
}
else{
$start = $this->_api->callApi('POST', $this->_urlProAbono."/v1/Subscription/" . $createNewSubscription[0]['Id'] . "/Start?BillNow=true", $this->_tokenProAbono, false);
if($start[1] != 200){
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
throw new Exception("E6");
}
else{
if($refreshOnBoardingHours){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
}
if(array_key_exists("DateNextBilling",$start[0])){
$payload = json_encode(
array(
"DateNextBilling" => null
)
);
$res = $this->_api->callApi('POST', $this->_urlProAbono.'/v1/CustomerSettingsPayment?ReferenceCustomer='.$this->_referenceCustomer, $this->_tokenProAbono, $payload);
}
}
}
}
// SINON UPGRADE (PRORATISATION)
else{
$upgrade = $this->_api->callApi('POST', $this->_urlProAbono . '/v1/Subscription/' . $this->_idSubscription . '/Upgrade?IdSubscription=' . $createNewSubscription[0]['Id'] . '&BillNow=true', $this->_tokenProAbono, false);
if($upgrade[1] != 201){
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$createNewSubscription[0]['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
throw new Exception("E6");
}
if($refreshOnBoardingHours){
AppAccountServices::updateAccountOnboardingHoursBalanceInMinutes($this->_idAccount,$newOnboardingHoursBalance);
}
}
}
}
else{
$msg = "La souscription à l'offre " . "<strong>" . $nameOffer . "</strong>" . " a bien été validée.";
$this->_session->set("msgFlashSubscription",$msg);
$this->_session->set("iconFlashSubscription","checked");
$delete = $this->_api->callApi("DELETE", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$propal['Id']. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, false);
}
return new JsonResponse(array(
'status' => 200
));
}
else{
$exception = $createNewSubscription;
throw new Exception("E9");
}
}
else{
throw new Exception("E10");
}
}
else{
throw new Exception("E11");
}
}
catch(Exception $e){
if ($this->_request->isMethod("POST")) {
if(is_null($exception)){
return new JsonResponse(array(
'status' => 400,
'error' => $e->getMessage(),
'line' => $e->getLine()
));
}
else{
return new JsonResponse(array(
'status' => 400,
'error' => $e->getMessage(),
'line' => $e->getLine(),
'exception' => $exception
));
}
}
else{
$this->addFlash('error', "Une erreur a été rencontrée. Veuillez réessayer ultérieurement.");
}
}
if ($this->_request->isMethod("POST")) {
return new JsonResponse(array(
'status' => 200
));
}
else{
return $this->redirectToRoute('Abonnement');
}
}
public function renameSubscription(Int $id = null,$name = null){
if(!is_null($id) and !is_null($name)){
$params = array(
"Name" => $name
);
$rename = $this->_api->callApi("PATCH", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions/".$id. '?IdBusiness='.$this->_idBusiness, $this->_tokenProAbono, json_encode($params));
}
else{
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
}
/**
* @Route("/Abonnement/StopTrial", name="Abonnement_stopTrial")
* @Route("/Abonnement/StopTrial", name="abonnement_stopTrial")
*/
public function stopTrial(){
try{
if ($this->_request->isMethod("POST")) {
$params = array(
"ReferenceCustomer" => $this->_referenceCustomer,
"ReferenceOffer" => AppAccountType::REFERRAL
);
$start = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Subscription?TryStart=true", $this->_tokenProAbono, json_encode($params));
if ($start[1] == 201) {
$countSubscriptions = $this->_api->callApi("GET", $this->_urlBackOfficeProAbono . "/Sub/Subscriptions?IdBusiness=".$this->_idBusiness."&IdCustomer=".$this->_idCustomer, $this->_tokenProAbono, false);
if($countSubscriptions[1] == 200){
$this->renameSubscription($start[0]['Id'], "Abonnement ".$countSubscriptions[0]['TotalItems']);
}
$terminate = $this->_api->callApi("POST", $this->_urlProAbono . "/v1/Subscription/" . $this->_idSubscription . "/Termination?Immediate=true", $this->_tokenProAbono, false);
if ($terminate[1] !== 200) {
$this->_api->callApi("POST", $this->_urlProAbono . "/v1/Subscription/" . $start[0]['Id'] . "/Termination?Immediate=true", $this->_tokenProAbono, false);
throw new Exception();
}
else{
$appAccount = AppAccountServices::getAccount($this->_idAccount);
$appAccount->setUsers(AppUserServices::getAccountUsers($appAccount->getId()));
foreach ($appAccount->getUsers() as $user) {
$data = Services_coefficy_utilisateurs::setNewCGV($user,AppTermsOfService::TERMS_OF_SERVICE);
}
$this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
$msg = "Votre demande a bien été pris en compte. Vous avez désormais souscris à un abonnement REFERRAL.";
$this->_session->set("msgFlashSubscription",$msg);
$this->_session->set("iconFlashSubscription","checked");
if(!empty($this->_request->query->all())){
return $this->redirectToRoute('Abonnement',$this->_request->query->all());
}
else{
return $this->redirectToRoute('Abonnement');
}
}
} else {
throw new Exception();
}
}
else{
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
}
catch(Exception $e){
$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.");
}
if(!empty($this->_request->query->all())){
return $this->redirectToRoute('Abonnement_update',$this->_request->query->all());
}
else{
return $this->redirectToRoute('Abonnement_update');
}
}
/**
* @Route("/Abonnement/SupportMode", name="Abonnement_go_support_mode")
* @Route("/Abonnement/SupportMode", name="abonnement_go_support_mode")
*/
public function goSupportMode(SessionInterface $session){
try {
if(!in_array($this->_user['idUserType'],AppUserType::UT_ADMIN)){
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
if(array_key_exists("supportMode",$this->_user)){
if($this->_user['supportMode']){
throw new Exception("Vous êtes déjà en MODE SUPPORT.",01);
}
}
else{
throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
}
$emailSupport = "support" . rand(0,100000) . "+" . $this->_user['userEmail'];
$idUserSupport = null;
if(ConnectionServices::mailExistsActived($emailSupport)){
$existantSupportUser = AppUserServices::getUserFromEmail($emailSupport);
if($existantSupportUser->getIdAccount() !== $this->_idAccount){
$appAccount = AppAccountServices::getAccount($existantSupportUser->getIdAccount());
$responsableUserExist = Services_coefficy_utilisateurs::getOldestResponsableIdUser($existantSupportUser->getIdAccount());
if(!$responsableUserExist) {
if($appAccount->hasService(AppService::CRM)) {
if (!CrmRelaunchServices::deleteUserFromRelaunch($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
throw new Exception("Erreur lors de la suppression des relances de l'utilisateur support déjà existant.", 01);
}
if (!CrmOpportunityServices::deleteUserOpportunity($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
throw new Exception("Erreur lors de la suppression des opportunités de l'utilisateur support déjà existant.", 01);
}
if (!RoutineServices::deleteUserRoutines($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount())) {
throw new Exception("Erreur lors de la suppression des routines de l'utilisateur support déjà existant", 01);
}
if (!CamPersonaServices::deletePersonaByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression des personnas de l'utilisateur support déjà existant", 01);
}
}
if ($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
$sequences = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['SEQUENCE'],
$this->_session->get('campaignApi')['token'],
[
'idSequenceType' => 2,
'idUser' => $existantSupportUser->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
if (array_key_exists("result", $sequences)) {
if ($sequences['result']['success']) {
if (!empty($sequences['result']['result'])) {
foreach ($sequences['result']['result'] as $s) {
$sequence = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['SEQUENCE'],
$this->_session->get('campaignApi')['token'],
[
'idSequence' => $s['idSequence'],
'idAccount' => $existantSupportUser->getIdAccount(),
'idUserStopped' => $existantSupportUser->getIdUser()
]
);
if (array_key_exists("result", $sequence)) {
if (!$sequence['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
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);
}
} else {
throw new Exception ("Impossible de récupérer les séquences crées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
$campaignsUser = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $existantSupportUser->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
$campaignsUserCreator = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idUserCreator' => $existantSupportUser->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
if (array_key_exists("result", $campaignsUser) && array_key_exists("result", $campaignsUserCreator)) {
if ($campaignsUser['result']['success'] && $campaignsUserCreator['result']['success']) {
$allCampaigns = array();
foreach ($campaignsUser['result']['result'] as $c) {
if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
$allCampaigns[$c['idCampaign']] = $c;
}
}
foreach ($campaignsUserCreator['result']['result'] as $c) {
if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
$allCampaigns[$c['idCampaign']] = $c;
}
}
if (!empty($allCampaigns)) {
foreach ($allCampaigns as $c) {
$campaign = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idCampaign' => $c['idCampaign'],
'idUserStopped' => $c['idUser']
]
);
if (array_key_exists("result", $campaign)) {
if (!$campaign['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
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);
}
} else {
throw new Exception ("Impossible de récupérer les campagnes crées/attribuées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::NEWSLETTER)) {
$newsletters = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['NEWSLETTER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $existantSupportUser->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
if (array_key_exists("result", $newsletters)) {
if ($newsletters['result']['success']) {
if (!empty($newsletters['result']['result'])) {
foreach ($newsletters['result']['result'] as $n) {
$newsletter = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['NEWSLETTER'],
$this->_session->get('campaignApi')['token'],
[
'idNewsletter' => $n['idNewsletter'],
'idAccount' => $existantSupportUser->getIdAccount()
]
);
if (array_key_exists("result", $newsletter)) {
if (!$newsletter['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
throw new Exception ("Une erreur a été rencontrée lors de la récupération des newsletters crées par l'utilisateur support.", 01);
}
} else {
throw new Exception ("Impossible de récupérer les newsletters crées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::LEBONLOGICIEL)) {
if (!LeBonLogicielServices::deleteArticleByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression des articles LBL de l'utilisateur support déjà existant", 01);
}
if (!LeBonLogicielServices::deleteOrganizationByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression de la fiche editeur/intégrateur LBL de l'utilisateur support déjà existant", 01);
}
if (!LeBonLogicielServices::deleteSolutionVersionByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression des solutions éditées LBL de l'utilisateur support déjà existant", 01);
}
}
if ($appAccount->hasService(AppService::EMAIL_SUIVI)) {
if (!AppMailTemplateServices::deleteTemplateEmailByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression des templates email de l'utilisateur support déjà existant", 01);
}
}
if ($appAccount->hasService(AppService::EDITION_LEADFORM)) {
if (!LeadformServices::deleteFormsByUser($existantSupportUser->getIdUser())) {
throw new Exception("Erreur lors de la suppression des formulaires de l'utilisateur support déjà existant", 01);
}
}
}
else{
if($appAccount->hasService(AppService::CRM)){
if(!CrmRelaunchServices::updateUserOnRelaunch($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount(), $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des relances de l'utilisateur support déjà existant");
}
if(!CrmOpportunityServices::updateUserOnOpportunity($existantSupportUser->getIdUser(), $existantSupportUser->getIdAccount(), $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des opportunitées de l'utilisateur support déjà existant");
}
if(!RoutineServices::updateUserOnRoutine($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des routines de l'utilisateur support déjà existant");
}
if(!CamPersonaServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des personas de l'utilisateur support déjà existant");
}
}
if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
$resultSequence = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $existantSupportUser->getIdUser(),
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
}
if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
$resultCampaign = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $existantSupportUser->getIdUser(),
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
}
if($appAccount->hasService(AppService::NEWSLETTER)) {
$resultNewsletterContact = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $existantSupportUser->getIdUser(),
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $existantSupportUser->getIdAccount()
]
);
}
if($appAccount->hasService(AppService::LEBONLOGICIEL)){
if(!LeBonLogicielServices::transfertArticleResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des articles LBL de l'utilisateur support déjà existant");
}
if(!LeBonLogicielServices::transfertSolutionVersionResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser())){
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");
}
if(!LeBonLogicielServices::transfertOrganizationResponsable($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
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");
}
}
if($appAccount->hasService(AppService::EMAIL_SUIVI)){
if(!AppMailTemplateServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
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");
}
}
if($appAccount->hasService(AppService::EDITION_LEADFORM)){
if(!LeadformServices::updateUser($existantSupportUser->getIdUser(), $responsableUserExist->getIdUser(), $existantSupportUser->getIdAccount())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des leadforms de l'utilisateur support déjà existant");
}
}
}
if (!Services_coefficy_utilisateurs::deleteUser($existantSupportUser->getIdUser())) {
throw new Exception("Une erreur a été rencontrée lors de la suppression de l'utilisateur support déjà existant", 01);
}
$idUserSupport = Services_coefficy_utilisateurs::addSupportUser($this->_user,$this->_idAccount,$emailSupport);
}
else{
$idUserSupport = $existantSupportUser->getIdUser();
}
}
else{
$idUserSupport = Services_coefficy_utilisateurs::addSupportUser($this->_user,$this->_idAccount,$emailSupport);
}
if(is_null($idUserSupport)){
throw new Exception ("Une erreur a été rencontrée lors de la création du compte support.",01);
}
$connection = new ConnectionServices();
if($connection->connexion_standard($emailSupport, $this->_user['userPassword'], $this->_session, 1) !== 1){
throw new Exception("Une erreur a été rencontrée lors de la connexion au compte support.",01);
}
$this->forward('App\Controller\AbonnementController::abonnementRefresh', [
'idCustomer' => $this->_idCustomer,
'fromTrigger' => false,
'fromScript' => false
]);
$this->addFlash("success","Vous êtes en mode support.");
}
catch(Exception $e){
if($e->getCode() == 01){
$this->setAttribute('error', $e->getMessage());
}
else{
$this->setAttribute("error", "Impossible de rejoindre le mode SUPPORT. Une erreur a été rencontrée.");
}
return $this->redirectToRoute('Abonnement', ['idAccount' => $this->_idAccount]);
}
//Connexion OK il faut set des variables dans la session
SessionUtilisateur::setSessionVariables($session);
return $this->redirectToRoute('Abonnement');
}
/**
* @Route("/Abonnement/LeaveSupportMode", name="Abonnement_leave_support_mode")
* @Route("/Abonnement/LeaveSupportMode", name="abonnement_leave_support_mode")
*/
public function exitSupportMode(SessionInterface $session){
try {
if(!in_array($this->_user['idUserType'],AppUserType::UT_ADMIN)){
throw new AccessDeniedHttpException("Vous n'avez pas accès à cette page.");
}
if(array_key_exists("supportMode",$this->_user)){
if(!$this->_user['supportMode']){
throw new Exception("Vous n'êtes pas en mode SUPPORT, vous ne pouvez pas le quitter.",01);
}
}
else{
throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
}
if(!array_key_exists("idSupportUser",$this->_user)){
throw new Exception("Le mode support est indisponible pour le moment. Veuillez réessayer ultérieurement.",01);
}
$responsableUserExist = Services_coefficy_utilisateurs::getOldestResponsableIdUser($this->_idAccount);
$appAccount = AppAccountServices::getAccount($this->_idAccount);
if(!$responsableUserExist) {
if ($appAccount->hasService(AppService::CRM)) {
if (!CrmRelaunchServices::deleteUserFromRelaunch($this->_user['idUser'], $this->_idAccount)) {
throw new Exception("Erreur lors de la suppression des relances de l'utilisateur support.", 01);
}
if (!CrmOpportunityServices::deleteUserOpportunity($this->_user['idUser'], $this->_idAccount)) {
throw new Exception("Erreur lors de la suppression des opportunités de l'utilisateur support.", 01);
}
if (!RoutineServices::deleteUserRoutines($this->_user['idUser'], $this->_idAccount)) {
throw new Exception("Erreur lors de la suppression des routines de l'utilisateur support.", 01);
}
if (!CamPersonaServices::deletePersonaByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression des personnas de l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
$sequences = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['SEQUENCE'],
$this->_session->get('campaignApi')['token'],
[
'idSequenceType' => 2,
'idUser' => $this->_user['idUser'],
'idAccount' => $this->_idAccount
]
);
if (array_key_exists("result", $sequences)) {
if ($sequences['result']['success']) {
if (!empty($sequences['result']['result'])) {
foreach ($sequences['result']['result'] as $s) {
$sequence = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['SEQUENCE'],
$this->_session->get('campaignApi')['token'],
[
'idSequence' => $s['idSequence'],
'idAccount' => $this->_idAccount,
'idUserStopped' => $this->_user['idUser']
]
);
if (array_key_exists("result", $sequence)) {
if (!$sequence['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
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);
}
} else {
throw new Exception ("Impossible de récupérer les séquences crées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
$campaignsUser = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $this->_user['idUser'],
'idAccount' => $this->_idAccount
]
);
$campaignsUserCreator = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idUserCreator' => $this->_user['idUser'],
'idAccount' => $this->_idAccount
]
);
if (array_key_exists("result", $campaignsUser) && array_key_exists("result", $campaignsUserCreator)) {
if ($campaignsUser['result']['success'] && $campaignsUserCreator['result']['success']) {
$allCampaigns = array();
foreach ($campaignsUser['result']['result'] as $c) {
if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
$allCampaigns[$c['idCampaign']] = $c;
}
}
foreach ($campaignsUserCreator['result']['result'] as $c) {
if (!array_key_exists($c['idCampaign'], $allCampaigns)) {
$allCampaigns[$c['idCampaign']] = $c;
}
}
if (!empty($allCampaigns)) {
foreach ($allCampaigns as $c) {
$campaign = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['CAMPAIGN'],
$this->_session->get('campaignApi')['token'],
[
'idCampaign' => $c['idCampaign'],
'idUserStopped' => $c['idUser']
]
);
if (array_key_exists("result", $campaign)) {
if (!$campaign['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
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);
}
} else {
throw new Exception ("Impossible de récupérer les campagnes crées/attribuées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::NEWSLETTER)) {
$newsletters = CampaignApiServices::call(
'get',
CampaignApiServices::ENDPOINT['NEWSLETTER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $this->_user['idUser'],
'idAccount' => $this->_idAccount
]
);
if (array_key_exists("result", $newsletters)) {
if ($newsletters['result']['success']) {
if (!empty($newsletters['result']['result'])) {
foreach ($newsletters['result']['result'] as $n) {
$newsletter = CampaignApiServices::call(
'delete',
CampaignApiServices::ENDPOINT['NEWSLETTER'],
$this->_session->get('campaignApi')['token'],
[
'idNewsletter' => $n['idNewsletter'],
'idAccount' => $this->_idAccount
]
);
if (array_key_exists("result", $newsletter)) {
if (!$newsletter['result']['success']) {
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);
}
} else {
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);
}
}
}
} else {
throw new Exception ("Une erreur a été rencontrée lors de la récupération des newsletters crées par l'utilisateur support.", 01);
}
} else {
throw new Exception ("Impossible de récupérer les newsletters crées par l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::LEBONLOGICIEL)) {
if (!LeBonLogicielServices::deleteArticleByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression des articles LBL de l'utilisateur support.", 01);
}
if (!LeBonLogicielServices::deleteSolutionVersionByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression des solutions editées LBL de l'utilisateur support.", 01);
}
if (!LeBonLogicielServices::deleteOrganizationByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression de la fiche editeur/integrateur LBL de l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::EMAIL_SUIVI)) {
if (!AppMailTemplateServices::deleteTemplateEmailByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression des templates email de l'utilisateur support.", 01);
}
}
if ($appAccount->hasService(AppService::EDITION_LEADFORM)) {
if (!LeadformServices::deleteFormsByUser($this->_user['idUser'])) {
throw new Exception("Erreur lors de la suppression des formulaires de l'utilisateur support.", 01);
}
}
}
else{
if($appAccount->hasService(AppService::CRM)){
if(!CrmRelaunchServices::updateUserOnRelaunch($this->_user['idUser'], $this->_idAccount, $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des relances de l'utilisateur support");
}
if(!CrmOpportunityServices::updateUserOnOpportunity($this->_user['idUser'], $this->_idAccount, $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des opportunitées de l'utilisateur support");
}
if(!RoutineServices::updateUserOnRoutine($this->_user['idUser'], $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des routines de l'utilisateur support");
}
if(!CamPersonaServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des personas de l'utilisateur support");
}
}
if($appAccount->hasService(AppService::SEQUENCES_ENGAGEMENT)) {
$resultSequence = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['SEQUENCE_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $this->_user['idUser'],
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $this->_idAccount
]
);
}
if($appAccount->hasService(AppService::CAMPAIGN_ENGAGEMENT_AUTO)) {
$resultCampaign = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['CAMPAIGN_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $this->_user['idUser'],
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $this->_idAccount
]
);
}
if($appAccount->hasService(AppService::NEWSLETTER)) {
$resultNewsletterContact = CampaignApiServices::call(
'put',
CampaignApiServices::ENDPOINT['NEWSLETTER_TRANSFERTUSER'],
$this->_session->get('campaignApi')['token'],
[
'idUser' => $this->_user['idUser'],
'newIdUser' => $responsableUserExist->getIdUser(),
'idAccount' => $this->_idAccount
]
);
}
if($appAccount->hasService(AppService::LEBONLOGICIEL)){
if(!LeBonLogicielServices::transfertArticleResponsable($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des articles LBL de l'utilisateur support");
}
if(!LeBonLogicielServices::transfertOrganizationResponsable($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation de la fiche editeur/integrateur LBL de l'utilisateur support");
}
if(!LeBonLogicielServices::transfertSolutionVersionResponsable($this->_user['idUser'], $responsableUserExist->getIdUser())){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des solutions éditées LBL de l'utilisateur support");
}
}
if($appAccount->hasService(AppService::EMAIL_SUIVI)){
if(!AppMailTemplateServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des templates d'emails de l'utilisateur support");
}
}
if($appAccount->hasService(AppService::EDITION_LEADFORM)){
if(!LeadformServices::updateUser($this->_user['idUser'], $responsableUserExist->getIdUser(), $this->_idAccount)){
throw new Exception("Une erreur a été rencontrée lors de la réaffectation des leadforms de l'utilisateur support");
}
}
}
$userToConnectWith = AppUserServices::getUserArray($this->_user['idSupportUser']);
$connection = new ConnectionServices();
if($connection->connexion_standard($userToConnectWith['userEmail'], $userToConnectWith['userPassword'], $this->_session, 2) !== 1){
throw new Exception("Une erreur a été rencontrée lors de la connexion du compte support.",01);
}
else{
if(!Services_coefficy_utilisateurs::deleteUser($this->_user['idUser'])){
throw new Exception("Une erreur a été rencontrée lors de la suppression de l'utilisateur support.",01);
}
}
$this->addFlash("success","Vous avez quitté le mode support.");
}
catch(Exception $e){
if($e->getCode() == 01){
$this->addFlash("error",$e->getMessage());
}
else{
$this->addFlash("error", "Impossible de quitter le mode SUPPORT. Une erreur a été rencontrée.");
}
return $this->redirectToRoute('Abonnement');
}
//Connexion OK il faut set des variables dans la session
SessionUtilisateur::setSessionVariables($session);
return $this->redirectToRoute('Abonnement', ['idAccount' => $this->_idAccount]);
}
/**
* @Route("/Abonnement/loadHistoricCGV", name="Abonnement_LoadCGV")
* @Route("/Abonnement/loadHistoricCGV", name="abonnement_loadCGV")
*/
public function loadHistoricCGV(Request $request, SessionInterface $session){
$response = new Response();
$idAccount = $request->get('idAccount');
$method = 'GET';
$tokenApi = $session->get('campaignApi')['token'];
$data = array(
'idAccount' => $idAccount,
'isAccepted' => true);
$userTermServiceList = CampaignApiServices::call($method, CampaignApiServices::ENDPOINT['TERMS_OF_SERVICE'], $tokenApi, $data)['result']['result'];
$url = 'abonnement/onglets/utilisateurs/historic_cgv_accept.html.twig';
$html = $this->render($url,array(
'userTermServiceList' =>$userTermServiceList
))->getContent();
$response->setContent(json_encode($html));
return $response;
}
/**
* @return mixed
*/
public function getRequest()
{
return $this->_request;
}
/**
* @return SessionInterface
*/
public function getSession(): SessionInterface
{
return $this->_session;
}
/**
* @return mixed
*/
public function getUser()
{
return $this->_user;
}
/**
* @return mixed|null
*/
public function getIdAccount()
{
return $this->_idAccount;
}
/**
* @return string|null
*/
public function getSiren(): ?string
{
return $this->_siren;
}
/**
* @return string|null
*/
public function getReferenceCustomer(): ?string
{
return $this->_referenceCustomer;
}
/**
* @return string|null
*/
public function getAccountTitle(): ?string
{
return $this->_accountTitle;
}
/**
* @return mixed
*/
public function getCompanyName()
{
return $this->_companyName;
}
/**
* @return AppUser|\App\Repository\user|null
*/
public function getUserResponsableAccount()
{
return $this->_userResponsableAccount;
}
/**
* @return bool
*/
public function isIsFreemium(): bool
{
return $this->_isFreemium;
}
/**
* @return bool
*/
public function isIsOlder(): bool
{
return $this->_isOlder;
}
/**
* @return bool
*/
public function isIsResponsable(): bool
{
return $this->_isResponsable;
}
/**
* @return bool
*/
public function isIsAdmin(): bool
{
return $this->_isAdmin;
}
/**
* @return CallApi
*/
public function getApi(): CallApi
{
return $this->_api;
}
/**
* @return mixed
*/
public function getConfProAbono()
{
return $this->_confProAbono;
}
/**
* @return mixed
*/
public function getUrlProAbono()
{
return $this->_urlProAbono;
}
/**
* @return mixed
*/
public function getUrlBackOfficeProAbono()
{
return $this->_urlBackOfficeProAbono;
}
/**
* @return mixed
*/
public function getTokenProAbono()
{
return $this->_tokenProAbono;
}
/**
* @return mixed
*/
public function getSegmentProAbono()
{
return $this->_segmentProAbono;
}
/**
* @return array|false
*/
public function getProAbonoUserState()
{
return $this->_proAbonoUserState;
}
/**
* @return mixed|null
*/
public function getIdCustomer()
{
return $this->_idCustomer;
}
/**
* @return mixed|null
*/
public function getIdSubscription()
{
return $this->_idSubscription;
}
/**
* @return bool
*/
public function isPropalExists(): bool
{
return $this->_propalExists;
}
/**
* @return int|null
*/
public function getPropalNb(): ?int
{
return $this->_propalNb;
}
/**
* @return mixed
*/
public function getIdBusiness()
{
return $this->_idBusiness;
}
/**
* @param mixed $idBusiness
*/
public function setIdBusiness($idBusiness): void
{
$this->_idBusiness = $idBusiness;
}
/**
* @return mixed
*/
public function getIsEngaged()
{
return $this->_isEngaged;
}
/**
* @param mixed $IsEngaged
*/
public function setIsEngaged($IsEngaged): void
{
$this->_isEngaged = $IsEngaged;
}
/**
* @return bool
*/
public function getIsTerminated(): bool
{
return $this->_isTerminated;
}
/**
* @param bool $isTerminated
*/
public function setIsTerminated(bool $isTerminated): void
{
$this->_isTerminated = $isTerminated;
}
/**
* @param $request
* @param $session
* @param $pageNumber
* @return array
* @throws Exception
*/
public function hoursRecherche($request, $session, $pageNumber)
{
/** @var $session SessionInterface */
$hourServices = new RechercheHourServices();
$params = [
'responsableFilter' => $hourServices->responsableFilter($request->query->get('responsable', null)),
'companyFilter' => $hourServices->idCompanyFilter($request->query->get('client', null)),
'typehoursFilter' => $hourServices->typeHoursFilter($request->query->get('typeHours', null)),
'statusHoursFilter' => $hourServices->statusHoursFilter($request->query->get('statusHours', null)),
'echeanceFilter' => $hourServices->echeanceFilter($request->query->get('datedebut', null), $request->query->get('datefin', null), $request->query->get('statusHours', null), $request->query->get('typeHours', null)),
'retardFilter' => $hourServices->retardFilter($request->query->get('retard', null)),
'stopFilter' => $hourServices->stopFilter($request->query->get('stop', null)),
'futurFilter' => $hourServices->futurFilter($request->query->get('futur', null)),
'historicFilter' => $hourServices->historicFilter($request->query->get('historic', null)),
'creatorFilter' => $hourServices->creatorFilter($request->query->get('creator', null))
];
$filters = '';
foreach ($params as $filter) {
if ($filter !== null) {
$filters .= $filter.' AND ';
}
}
$filters = substr_replace($filters, '', -5);
if($request->query->get('orderby', null) != null && $request->query->get('columnorderby', null) != null)
{
$orderBy = "ORDER BY ah.".$request->query->get('columnorderby', null)." ".$request->query->get('orderby', null);
}
else
{
$orderBy = "ORDER BY ah.accountHoursDateDue desc, ah.accountHoursDateStart desc";
}
$count = $hourServices->getCount($filters);
$sum = $hourServices->getSumValue($filters);
$nbrOfPage = intval(ceil($count/ BaseController::$NBRPERPAGE100));
//RechercheFunctions::send_annexe_url($this, $count, $pageNumber, 'societe');
$result = $hourServices->getResult($filters, $orderBy,$pageNumber, BaseController::$NBRPERPAGE100);
return [
'result' => $result,
'nbrOfPage' => $nbrOfPage,
'count' => $count,
'sum'=>$sum
];
}
}