<?php
/**
* Created by PhpStorm.
* User: anthony
* Date: 25/05/18
* Time: 10:45
*/
namespace App\Controller;
use App\Entity\Auth\AuthUser;
use App\Entity\Client;
use App\Entity\ClientRoleUser;
use App\Entity\Coupure;
use App\Entity\Mailling;
use App\Entity\PieceJointeMailling;
use App\Ovh\OvhSend;
use App\Service\Coupure\GenerateCoupureInterface;
use App\Service\MaillingEnCour\MaillingEnCour;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Spipu\Html2Pdf\Html2Pdf;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Doctrine\Common\Annotations\AnnotationReader;
class MaillingController extends Controller
{
/**
* @Route("api/maillings/maillings/getErreur/{idMailling}", methods={"GET"}, name="get.erreur.mailling.en.cours")
*/
public function getErreurMaillingEnCourAction($idMailling, EntityManagerInterface $em, MaillingEnCour $maillingEnCour){
$maillingEnCoursErreur = $maillingEnCour->getMaillingErreur($idMailling);
$encoders = array(new XmlEncoder(), new JsonEncoder());
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new PropertyNormalizer($classMetadataFactory);
$dateTimeNormalizer = new DateTimeNormalizer('d-m-y H:i');
$serializer = new Serializer([$normalizer,$dateTimeNormalizer], $encoders);
$jsonContent = $serializer->normalize($maillingEnCoursErreur, null, array('groups' => array('email_retour')));
$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/maillings/content/{id}",methods={"GET"},name="get.mailling.content")
*/
public function getMaillingContentAction($id, Request $request, KernelInterface $kernel)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository('App\Entity\Mailling')
->find($request->get('id'));
$path = $kernel->getRootDir() . '/../public/maillings/' . $mailling->getAncienId() . '.html';
$read = file_get_contents($path);
return new JsonResponse(utf8_encode($read));
}
/**
* @Route("/maillings/getNbEnvoyer/{id}",methods={"GET"},name="get.mailling.nb.envoyer")
*/
public function getMaillingNbEnvoyer($id)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository('App\Entity\Mailling')
->findOneBy(['ancienId' => $id]);
return new JsonResponse($mailling->getNbMailEnvoye());
}
/**
* @Route("/maillings/checkDelete",methods={"GET"},name="mail.check")
*/
public function getCheckMailAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$maillings = $em->getRepository("App\Entity\Mailling")
->findBy(['envoyer' => 0 , 'enCour' => 0 ]);
$checkIfMaillingExist = $this->get('check.mailling.exist');
$anomalieGestion = $this->get('gestion.anomalie');
foreach ($maillings as $mailling){
if($checkIfMaillingExist->checKMailling($mailling) < 1){
$suivitOuvertures = $em->getRepository('App:SuivitOuvertureMailling')
->findBy(['mailling' => $mailling]);
if(count($suivitOuvertures) < 1){
$em->remove($mailling);
}
else{
$anomalieGestion->addAnomalieDeleteWithSuivit($mailling);
}
}
}
$em->flush();
return new Response('ok');
}
/**
* @Route("/maillings/send/test/{idMailling}/{idAuthUser}",methods={"GET"},name="send.mailling.test")
*/
public function getSendMailTestAction($idMailling, $idAuthUser, MaillingEnCour $maillingEnCour, KernelInterface $kernel)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
$authUser = $em->getRepository("App\Entity\Auth\AuthUser")
->find($idAuthUser);
if($authUser){
if($mailling){
/** @var Mailling $mailling
* @var AuthUser $authUser
*/
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$maillingEnCour->addTestSend($mailling,$authUser);
return new JsonResponse('mail test lancé en envoie');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
} else {
return new JsonResponse('l\'utilisateur n\'existe pas');
}
}
/**
* @Route("/maillings/send/veille/{id}", methods={"GET"}, name="mailling.veille.send")
*/
public function sendVeilleAction(MaillingEnCour $maillingEnCour, EntityManagerInterface $em, $id){
$veille = $em->getRepository('App:Veille')->find($id);
if($veille){
$match_date = $veille->getDate();
$date = new \DateTime();
$interval = $date->diff($match_date);
if($interval->days == 0) {
if(!$veille->getValider()){
$veille->setValider(true);
$em->persist($veille);
$em->flush();
$maillingEnCour->addVeilleSend($veille);
return new JsonResponse('veille lancer en envoie');
}
}
}
return new JsonResponse('veille déja envoyé');
}
/**
* @Route("/maillings/send/date/{idMailling}",methods={"GET"},name="send.mail.date")
*/
public function getSendMaillingDateAction($idMailling , MaillingEnCour $maillingEnCour, Request $request)
{
ini_set('memory_limit',-1);
set_time_limit(0);
$dateEnvoie = $request->query->get('date');
$dateEnvoie = new \DateTime($dateEnvoie);
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
if($mailling){
if($mailling->getValiderEnvoi()){
if(!$mailling->getEnCour()){
if(!$mailling->getEnvoyer()){
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$mailling->setEnCour(true);
$em->persist($mailling);
$em->flush();
if($maillingEnCour->addMaillingSend($mailling, $dateEnvoie, true) == false){
return new JsonResponse('le mailling est déja en cours d\'envoi');
}
return new JsonResponse('le mailling a été lancé en envoi');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling est déjà en envoyé');
}
} else {
return new JsonResponse('le mailling est déjà en cours d\'envoi');
}
} else {
return new JsonResponse('le mailling doit être validé');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
}
/**
* @Route("/maillings/send/{idMailling}",methods={"GET"},name="send.mail.reel")
*/
public function getSendMaillingAction($idMailling , MaillingEnCour $maillingEnCour)
{
ini_set('memory_limit',-1);
set_time_limit(0);
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
/** @var Mailling $mailling */
if($mailling){
if($mailling->getValiderEnvoi()){
if(!$mailling->getEnCour()){
if(!$mailling->getEnvoyer()){
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$mailling->setEnCour(true);
$em->persist($mailling);
$em->flush();
if($maillingEnCour->addMaillingSend($mailling, new \DateTime('now')) == false){
return new JsonResponse('le mailling est déja en cours d\'envoi');
}
return new JsonResponse('le mailling a été lancé en envoi');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling est déjà en envoyé');
}
} else {
return new JsonResponse('le mailling est déjà en cours d\'envoi');
}
} else {
return new JsonResponse('le mailling doit être validé');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
}
/**
* @Route("/mailling/enCour/{idMailling}", methods={"GET"}, name="mailling.en.cour.status")
*/
public function getMaillingInfoEnCourAction($idMailling, EntityManagerInterface $em, MaillingEnCour $maillingEnCour){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
$retour = [];
if($mailling){
$debutMailling = $maillingEnCour->getIfMaillingBegin($mailling);
if($debutMailling !== false){
$nbMailling = $maillingEnCour->getNbMailMailling($mailling);
$nbMaillingAttente = $maillingEnCour->getNbMailRestantAvantFin($mailling);
if($nbMaillingAttente != false){
$dateFurtureEnvoie = $maillingEnCour->getHeureEnvoieFuture($mailling);
if( $dateFurtureEnvoie == false){
$retour['nbMaillAttente'] = $nbMaillingAttente;
$retour['nbMailToSend'] = $nbMailling[0];
$retour['nbMailSend'] = $nbMailling[1];
} else {
$retour['message_erreur'] = 'le mailling commencera a être envoyé le ' . $dateFurtureEnvoie;
}
} else {
if($mailling->getEnvoyer() == true){
$retour['message_erreur'] = 'le mailling a fini d\'être envoyé';
}
$retour['message_erreur'] = 'Le mailling est en cours d\'envoi, l\'affichage du diagramme peut prendre plusieurs minutes. Merci de patienter.';
}
} else {
$retour['message_erreur'] = 'le mailling n\'est pas en envoie';
}
} else {
$retour['message_erreur'] = 'le mailling n\'existe pas';
}
return new JsonResponse($retour);
}
/**
* @Route("/maillings/deleteMailling/{idMailling}", methods={"DELETE"}, name="delete.mailling")
*/
public function deleteMailling($idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
if($mailling->getEnCour() === false){
$maillingsEnCour = $em->getRepository('App:MaillingEnCour')->findBy(['mailling' => $mailling]);
foreach ($maillingsEnCour as $maillingEnCour){
$em->remove($maillingEnCour);
}
$em->remove($mailling);
$em->flush();
$retour['message'] = 'le mailling a été supprimmer';
} else {
$retour['message'] = 'le mailling a déja été lancé en envoie';
}
return new JsonResponse($retour);
}
/**
* @Route("/maillings/prepareCoupure/{idClient}", methods={"GET"}, name="mailling.cree.coupure")
*/
public function creeMaillingCoupure($idClient, EntityManagerInterface $em, GenerateCoupureInterface $generateCoupure){
$client = $em->getRepository('App:Client')->find($idClient);
if($client){
/** @var Client $client */
$mailling = $em->getRepository('App:Mailling')->findOneBy(['client' => $client, 'typeMail' => 'Coupure', 'envoyer' => false]);
/** @var Mailling $mailling */
if($mailling){
foreach ($mailling->getPiecesJointes() as $piecesJointe){
$mailling->removePiecesJointe($piecesJointe);
$em->remove($piecesJointe);
}
$em->flush();
} else{
$mailling = new Mailling();
$mailling->setClient($client);
$date = new \DateTime('now');
$mailling->setNom('Retombées presse '. $client->getNom(). ' du '.date_format($date, 'd/m/Y'));
$mailling->setObjet('Retombées presse '. $client->getNom(). ' du '.date_format($date, 'd/m/Y'));
foreach ($client->getRolesUserClient() as $roleUserClient){
/** @var ClientRoleUser $roleUserClient */
if($roleUserClient->getRole() == 'Bo'){
$mailling->setEnvoyePar($roleUserClient->getAuthUser());
$mailling->setReplyTo($roleUserClient->getAuthUser());
}
}
$mailling->setTypeMail('Coupure');
}
$coupuresClient = $em->getRepository('App:Coupure')->findBy(['client' => $client, 'envoyer' => false]);
foreach ($coupuresClient as $coupure){
/** @var Coupure $coupure */
$pieceJointeMailling = new PieceJointeMailling();
$pieceJointeMailling->setUrl($coupure->getPiecesJointe());
$pieceJointeMailling->setCoupure($coupure);
$pieceJointeMailling->setMailling($mailling);
$mailling->addPiecesJointe($pieceJointeMailling);
}
$mailling->setValiderEnvoi(0);
$mailling->setEnCour(0);
$mailling->setEnvoyer(0);
$mailling->setNbMail(0);
$mailling->setNbMailEnvoye(0);
$mailling->setDebutMailCoupure($generateCoupure->generateDebutMail($mailling));
$mailling->setFinMailCoupure($generateCoupure->generateFinMail($mailling));
$mailling->sethyperlien(1);
$em->persist($mailling);
$em->flush();
} else {
$retour['message_erreur'] = 'le client n\'existe pas';
}
return new JsonResponse(['idMailling' => $mailling->getId()]);
}
/**
* @Route("/maillings/information/{idMailling}", methods={"GET"}, name="nb.mail.envoyer")
*/
public function getNombreMailEnvoyer($idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->findBy(['ancienId' => $idMailling]);
if(!isset($mailling[0])){
return new JsonResponse(0);
}
$mailling = $mailling[0];
return new JsonResponse($mailling->getNbMailEnvoye());
}
/**
* @Route("/maillings/refreshNbMail/{idMailling}", methods={"GET"}, name="nb.mail.envoyer.refresh")
*/
public function getRefreshNombreMail(OvhSend $ovhSend, $idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
/** @var Mailling $mailling */
$contactsSend = $ovhSend->getContactSend($mailling);
$nbMail = 0;
foreach ($contactsSend as $contactSend) {
$userInfo = explode('#', $contactSend);
$userMail = trim($userInfo[0]);
$blackList = $em->getRepository('App:BlackList')
->findOneBy(['email'=> $userMail]);
if(!$blackList) {
$nbMail = $nbMail + 1;
}
}
if($mailling->getNbMail() != $nbMail){
$mailling->setNbMail($nbMail);
}
$em->persist($mailling);
$em->flush();
return new JsonResponse($mailling->getNbMail());
}
/**
* @Route("/mailing/contactsenvoireel/{idMailling}", methods={"GET"}, name="mailing.contact.Envoi.reel")
*/
public function getContactsEnvoiReel($idMailling, EntityManagerInterface $em) {
$mailing = $em->getRepository('App:Mailling')->findOneBy(["ancienId" => $idMailling]);
$mailingsEnCours = $em->getRepository('App:MaillingEnCour')->findBy(["mailling" => $mailing->getId()]);
$contactsIDIntranet = [];
foreach ($mailingsEnCours as $mailingEncours) {
if(!is_null($mailingEncours->getUserId()))
$contactsIDIntranet[] = $mailingEncours->getUserId();
}
return new JsonResponse($contactsIDIntranet);
}
}