src/AppBundle/Controller/ExtranetController.php line 728

Open in your IDE?
  1. <?php
  2. namespace App\AppBundle\Controller;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use Sg\DatatablesBundle\Datatable\DatatableFactory as DatatableFactory;
  5. use Sg\DatatablesBundle\Response\DatatableResponse;
  6. use App\AppBundle\Datatables\UserDatatable;
  7. use App\AppBundle\Datatables\FlatDatatable;
  8. use App\AppBundle\Datatables\ReprisBailDatatable;
  9. use JMS\Serializer\SerializerInterface;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use App\AppBundle\Entity\Flat;
  12. use App\AppBundle\Entity\FlatNote;
  13. use App\AppBundle\Entity\Recompense;
  14. use App\AppBundle\Entity\PreavisSortie;
  15. use App\AppBundle\Entity\HelpMessage;
  16. use App\AppBundle\Entity\FlatDescription;
  17. use App\AppBundle\Entity\Sepa;
  18. use App\AppBundle\Entity\Mandate;
  19. use App\AppBundle\Entity\User;
  20. use App\AppBundle\Entity\Notification;
  21. use App\AppBundle\Entity\Message;
  22. use JMS\Serializer\SerializerBuilder;
  23. use Symfony\Component\Form\Extension\Core\Type\ButtonType;
  24. use App\AppBundle\Form\MessageType;
  25. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. use Doctrine\ORM\Mapping;
  28. use Symfony\Component\HttpFoundation\JsonResponse;
  29. use Symfony\Component\HttpFoundation\Request;
  30. use Doctrine\Common\Annotations\Annotation;
  31. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  34. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  35. use App\AppBundle\Entity\AircallCall;
  36. use libphonenumber\PhoneNumberUtil;
  37. use App\AppBundle\Entity\NotificationBo;
  38. use App\AppBundle\Entity\RgpdAutorisation;
  39. use App\AppBundle\Entity\UserRgpdAutorisation;
  40. use App\AppBundle\Entity\UserRgpdText;
  41. use App\AppBundle\Entity\RgpdText;
  42. use App\AppBundle\Entity\FlatProp;
  43. use App\AppBundle\Entity\Application;
  44. use App\AppBundle\Entity\VerifDoss;
  45. use App\AppBundle\Entity\VisiteDate;
  46. use App\AppBundle\Entity\UserLoc;
  47. use App\AppBundle\Entity\Ticket;
  48. use App\AppBundle\Entity\TicketAnswer;
  49. use App\AppBundle\Entity\TicketUser;
  50. use App\AppBundle\Entity\NoteSuiviUser;
  51. use App\Aws\Rekognition\RekognitionClient;
  52. use \Mailjet\Resources;
  53. /**
  54.  * Contrôleur de l'accueil, des annonces, des utilisateurs et des conversations
  55.  *
  56.  * @package AppBundle\Controller
  57.  */
  58. class ExtranetController extends AbstractController
  59. {
  60. private $getDoctrine;
  61.  
  62.     
  63.     private $serializer;
  64.     private $dtFactory;
  65.     private $dtResponse;
  66.     public function __construct(ManagerRegistry $getDoctrineSerializerInterface $serializer,DatatableFactory $datatableFactoryDatatableResponse $datatableResponse){
  67.         $this->getDoctrine $getDoctrine;
  68.     $this->_serializer=$serializer;
  69.     $this->dtFactory $datatableFactory;
  70.     $this->dtResponse $datatableResponse;
  71.     }
  72.     public function getUser2(){
  73.         $em =  $this->getDoctrine;
  74.         $usersManager $em->getRepository('App\AppBundle\Entity\User');
  75.         $myuser $usersManager->find(1);
  76.         return $myuser;
  77.     }
  78.     
  79.     /*
  80.     protected function getUser(): User
  81.     {
  82.         return parent::getUser();
  83.     }
  84.     */
  85.     
  86.     
  87.     /**
  88.      * verifier iban depuis le BO pour un contrat
  89.      *
  90.      * @param Request $request
  91.      * @return JsonResponse
  92.      * @Route("/frombocheckibanaction", name="frombocheckibanaction", options={"expose"=true})
  93.      * @Method({"GET","POST"})
  94.      */
  95.     public function formBoCheckIbanAction(Request $request)
  96.     {
  97.         $iban $_POST['iban'];
  98.         $curl curl_init();
  99.         $post = [
  100.             'format' => 'json',
  101.             'api_key' => '7d35694399f14f197e488187deaab0fa',
  102.             'iban'   => $iban,
  103.         ];
  104.         curl_setopt_array($curl, array(
  105.             CURLOPT_URL => 'https://api.iban.com/clients/api/v4/iban/',
  106.             CURLOPT_RETURNTRANSFER => true,
  107.             CURLOPT_POSTFIELDS => $post
  108.         ));
  109.         $output curl_exec($curl);
  110.         $result json_decode($output);
  111.         //print_r($result);
  112.         curl_close($curl);
  113.         $response = new Response();
  114.         $response->setStatusCode(200);
  115.         $vv json_encode($result);
  116.         $response->setContent($vv);
  117.         return new JsonResponse($output);
  118.     }
  119.     /**
  120.      * Generer un sepa depuis le BO our un contrat
  121.      *
  122.      * @param Request $request
  123.      * @param $doctrine
  124.      * @return JsonResponse
  125.      * @Route("/generatesepafrombo", name="generatesepafrombo", options={"expose"=true})
  126.      * @Method({"GET","POST"})
  127.      */
  128.     public function generateSepaAction(Request $request$doctrine)
  129.     {
  130.         $arr $_POST['sepa'];
  131.         $em =  $this->getDoctrine->getManager();
  132.         $contract $em->getRepository('AppBundle:Contract')->find($_POST['cid']);
  133.         $sepa = new Sepa();
  134.         $sepas $contract->getSepas();
  135.         foreach ($sepas as $rsepa){
  136.             $rsepa->setStatut(2);
  137.             $em->persist($rsepa);
  138.             $em->flush();
  139.         }
  140.         $sepa->setContract($contract);
  141.         $sepa->setAdresse($arr['adresse']);
  142.         $sepa->setBic($arr['bic']);
  143.         $sepa->setCodePostal($arr['code_postal']);
  144.         $sepa->setEmail($arr['email']);
  145.         $sepa->setIban($arr['iban']);
  146.         $sepa->setIsOther($arr['isOther']);
  147.         $sepa->setMobilePhone($arr['mobile_phone']);
  148.         $sepa->setNom($arr['nom']);
  149.         $sepa->setPrenom($arr['prenom']);
  150.         $sepa->setVille($arr['ville']);
  151.         $sepa->setStatut(1);
  152.         $em->persist($sepa);
  153.         $em->flush();
  154.         // generateDocument(Contract $contract, $category, $id = null, SecActOfGuarantee $secgarid = null,Sepa $sepa = null)
  155.         $this->get('app.contract')->generateDocument($contract'sepa'null,null,$sepa);
  156.         $em->flush();
  157.         if ($contract->getDocuments()->count()) {
  158.             $indice $contract->getDocuments()->count() -1;
  159.             $sepa->setDocument($contract->getDocuments()[$indice]);
  160.         }
  161.         $sepa->setContract($contract);
  162.         $sepa->setStatut(2);
  163.         $em->persist($sepa);
  164.         $em->flush();
  165.         $contract->addSepa($sepa);
  166.         return new JsonResponse('mandat généré');
  167.     }
  168.     /**
  169.      * faire un reset de la date de relance
  170.      *
  171.      * @param Request $request
  172.      * @return JsonResponse
  173.      * @Route("/resetdatesuivirappel/{id}", name="resetdatesuivirappel", options={"expose"=true})
  174.      * @Method({"GET","POST"})
  175.      */
  176.     public function resetdatesuivirappelAction($id)
  177.     {
  178.         $namedb $this->getParameter('dbreqpdo');
  179.         $udb $this->getParameter('userreqpdo');
  180. $pdb $this->getParameter('passreqpdo');
  181. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  182.         $sthd $bdd->prepare("update app.user SET suivirappel = null where id =".$id);
  183.         $sthd->execute();
  184.         return $this->redirect$this->generateUrl('editUser', array('id' => $id)) );
  185.     }
  186.     /**
  187.      * compter les leads a traiter
  188.      *
  189.      * @param Request $request
  190.      * @return JsonResponse
  191.      * @Route("/countmylead", name="countmylead", options={"expose"=true})
  192.      * @Method({"GET","POST"})
  193.      */
  194.     public function countMyLeadsAction()
  195.     {
  196.         $namedb $this->getParameter('dbreqpdo');
  197.         $udb $this->getParameter('userreqpdo');
  198. $pdb $this->getParameter('passreqpdo');
  199. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  200.         $comuser $this->getUser();
  201.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  202.         /*
  203.                 $sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
  204.         f.title, f.companyName as flatcompanyName, u.firstname, u.name, u.id as userid, f.price ,f.city as flatcity, f.created_at as flatcreated, f.publish_at, f.offre, f.offre_vendue
  205.         FROM app.user as u
  206.         inner join app.flat as f on u.id = f.owned_by_id";
  207.         */
  208.         $sql "SELECT count(*) as res
  209. FROM app.user as u ";
  210.         $condition ' where (suivipar LIKE "'.$suivipar.'" and suivistatus is null  )  ';
  211.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  212.         $sthd $bdd->prepare($sql.$condition);
  213.         $sthd->execute();
  214.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  215.         //return New JsonResponse($comuser->getUsername());
  216.         return New JsonResponse($max); //
  217.     }
  218.     /**
  219.      * compter les leads a traiter
  220.      *
  221.      * @param Request $request
  222.      * @return JsonResponse
  223.      * @Route("/countmyticket", name="countmyticket", options={"expose"=true})
  224.      * @Method({"GET","POST"})
  225.      */
  226.     public function countMyTicketAction()
  227.     {
  228.         $namedb $this->getParameter('dbreqpdo');
  229.         $udb $this->getParameter('userreqpdo');
  230. $pdb $this->getParameter('passreqpdo');
  231. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  232.         $sql "SELECT count(t.id) as number FROM ticket as t
  233.         inner join ticket_user as tu on t.id = tu.ticket_id
  234.         inner join user as u on u.id = tu.user_id
  235.         where t.seen_answer = 1 and t.user_from_id = ".$this->getUser()->getId()." group by t.id";
  236.         $sthd $bdd->prepare($sql);
  237.         $sthd->execute();
  238.         $max $sthd->fetchAll();
  239.         $res = [];
  240.         $res['res'] = count($max);
  241.         $sql "SELECT count(t.id) as number FROM ticket as t
  242.         inner join ticket_user as tu on t.id = tu.ticket_id
  243.         inner join user as u on u.id = tu.user_id
  244.         where tu.status = 1 and tu.user_id = ".$this->getUser()->getId()." group by t.id";
  245.         $sthd $bdd->prepare($sql);
  246.         $sthd->execute();
  247.         $max $sthd->fetchAll();
  248.         $res['res'] = $res['res'] + count($max);
  249.         return New JsonResponse($res);
  250.     }
  251.     /**
  252.      * compter les leads a traiter pour un user
  253.      *
  254.      * @param Request $request
  255.      * @return JsonResponse
  256.      * @Route("/countuserlead/{id}", name="countuserlead", options={"expose"=true})
  257.      * @Method({"GET","POST"})
  258.      */
  259.     public function countUserLeadsAction($id)
  260.     {
  261.         $namedb $this->getParameter('dbreqpdo');
  262.         $udb $this->getParameter('userreqpdo');
  263. $pdb $this->getParameter('passreqpdo');
  264. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  265.         $comuser $this->getUser();
  266.         $suivipar $id;
  267.         $sql "SELECT count(*) as res
  268. FROM app.user as u ";
  269.         $condition ' where (suivipar LIKE "'.$suivipar.'" and suivistatus is null  )  ';
  270.         $sthd $bdd->prepare($sql.$condition);
  271.         $sthd->execute();
  272.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  273.         return New JsonResponse($max); //
  274.     }
  275.     /**
  276.      * compter les leads piges a traiter
  277.      *
  278.      * @param Request $request
  279.      * @return JsonResponse
  280.      * @Route("/countmypigelead", name="countmypigelead", options={"expose"=true})
  281.      * @Method({"GET","POST"})
  282.      */
  283.     public function countMyPigeLeadsAction()
  284.     {
  285.         $namedb $this->getParameter('dbreqpdo');
  286.         $udb $this->getParameter('userreqpdo');
  287. $pdb $this->getParameter('passreqpdo');
  288. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  289.         $comuser $this->getUser();
  290.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  291.         $sql "SELECT count(*) as res
  292. FROM app.annoncescsv as u ";
  293.         $condition ' where (commercial LIKE "'.$suivipar.'" and status is null  )  ';
  294.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  295.         $sthd $bdd->prepare($sql.$condition);
  296.         $sthd->execute();
  297.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  298.         //return New JsonResponse($comuser->getUsername());
  299.         return New JsonResponse($max); //
  300.     }
  301.     /**
  302.      * compter les leads piges a traiter
  303.      *
  304.      * @param Request $request
  305.      * @return JsonResponse
  306.      * @Route("/countmypigeleadjj", name="countmypigeleadjj", options={"expose"=true})
  307.      * @Method({"GET","POST"})
  308.      */
  309.     public function countMyPigeLeadsjjAction()
  310.     {
  311.         $namedb $this->getParameter('dbreqpdo');
  312.         $udb $this->getParameter('userreqpdo');
  313. $pdb $this->getParameter('passreqpdo');
  314. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  315.         $comuser $this->getUser();
  316.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  317.         $sql "SELECT count(*) as res
  318. FROM app.annoncescsv as u ";
  319.         $jmoinsdeux = new \DateTime("2 days ago");
  320.         $condition ' where ( commercial LIKE "'.$suivipar.'" AND rappel < "'.$jmoinsdeux->format('Y-m-d').'" AND status = 11  )  ';
  321.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  322.         $sthd $bdd->prepare($sql.$condition);
  323.         $sthd->execute();
  324.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  325.         //return New JsonResponse($comuser->getUsername());
  326.         return New JsonResponse($max); //
  327.     }
  328.     /**
  329.      * compter les leads piges a traiter
  330.      *
  331.      * @param Request $request
  332.      * @return JsonResponse
  333.      * @Route("/countuserpigelead/{id}", name="countuserpigelead", options={"expose"=true})
  334.      * @Method({"GET","POST"})
  335.      */
  336.     public function countUserPigeLeadsAction($id)
  337.     {
  338.         $namedb $this->getParameter('dbreqpdo');
  339.         $udb $this->getParameter('userreqpdo');
  340. $pdb $this->getParameter('passreqpdo');
  341. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  342.         $comuser $this->getUser();
  343.         $suivipar $id;
  344.         $sql "SELECT count(*) as res
  345. FROM app.annoncescsv as u ";
  346.         $condition ' where (commercial LIKE "'.$suivipar.'" and status is null  )  ';
  347.         $sthd $bdd->prepare($sql.$condition);
  348.         $sthd->execute();
  349.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  350.         return New JsonResponse($max); //
  351.     }
  352.     /**
  353.      * compter les  dossier a verifier
  354.      *
  355.      * @param Request $request
  356.      * @return JsonResponse
  357.      * @Route("/countmydostoverif", name="countmydostoverif", options={"expose"=true})
  358.      * @Method({"GET","POST"})
  359.      */
  360.     public function countMyDosToVerifAction()
  361.     {
  362.         $namedb $this->getParameter('dbreqpdo');
  363.         $udb $this->getParameter('userreqpdo');
  364. $pdb $this->getParameter('passreqpdo');
  365. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  366.         $comuser $this->getUser();
  367.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  368.         $sql "SELECT count(app.taskdocstatus) as res FROM app.contract as vd
  369.                 inner join application as app on app.id = vd.application_id
  370.                 where app.taskdocstatus =0 and vd.taskdoctriger = 1";
  371.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  372.         $sthd $bdd->prepare($sql);
  373.         $sthd->execute();
  374.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  375.         //return New JsonResponse($comuser->getUsername());
  376.         return New JsonResponse($max); //
  377.     }
  378.     /**
  379.      * permet a un utilisateur de se désinscrir des email marketing
  380.      *
  381.      * @param Request $request
  382.      * @return JsonResponse
  383.      * @Route("/stopcampagnemail", name="stopcampagnemail", options={"expose"=true})
  384.      * @Method({"GET","POST"})
  385.      */
  386.     public function stopEmailAction(Request $request)
  387.     {
  388.         $em =  $this->getDoctrine->getManager();
  389.         $usersManager $em->getRepository('App\AppBundle\Entity\User');
  390.         $email $request->get('email');
  391.         $myuser $usersManager->findBy(['email'=> $email] );
  392.         $myuser[0]->setStopmail(true);
  393.         $em->persist($myuser[0]);
  394.         $em->flush();
  395.         return new JsonResponse('stop email activé');
  396.     }
  397.     /**
  398.      * Envoyer une note de suivi en ajax
  399.      *
  400.      * @param Request $request
  401.      * @return JsonResponse
  402.      * @Route("/sendajaxnotesuivi", name="sendajaxnotesuivi", options={"expose"=true})
  403.      * @Method({"GET","POST"})
  404.      */
  405.     public function sendajaxnotesuiviAction(Request $request)
  406.     {
  407.         $em =  $this->getDoctrine->getManager();
  408.         $noteManager $em->getRepository('App\AppBundle\Entity\NoteSuiviUser');
  409.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  410.         $user $userManager->find($request->get('user'));
  411.         $note = new NoteSuiviUser();
  412.         $note->setUser($user);
  413.         $note->setEditor($this->getUser());
  414.         $note->setNote($request->get('note'));
  415.         $note->setCreatedAt(new \DateTime());
  416.         $em->persist($note);
  417.         $em->flush();
  418.         return new JsonResponse('stop email activé');
  419.     }
  420.     /**
  421.      * Envoyer une note de suivi en ajax
  422.      *
  423.      * @param Request $request
  424.      * @return JsonResponse
  425.      * @Route("/sendajaxreatributeusercom", name="sendajaxreatributeusercom", options={"expose"=true})
  426.      * @Method({"GET","POST"})
  427.      */
  428.     public function sendajaxreatributeusercomAction(Request $request)
  429.     {
  430.         $em =  $this->getDoctrine->getManager();
  431.         $noteManager $em->getRepository('App\AppBundle\Entity\NoteSuiviUser');
  432.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  433.         $user $userManager->find($request->get('user'));
  434.         $suivipar $request->get('suivipar');
  435.         $note = new NoteSuiviUser();
  436.         $note->setUser($user);
  437.         $note->setEditor($this->getUser());
  438.         $note->setNote('utilisateur réatribué pour la raison suivante : '.$request->get('note'));
  439.         $note->setCreatedAt(new \DateTime());
  440.         $em->persist($note);
  441.         $em->flush();
  442.         $user->setSuivipar($suivipar);
  443.         $em->persist($user);
  444.         $em->flush();
  445.         return new JsonResponse('stop email activé');
  446.     }
  447.     /**
  448.      * Récupérer l'adresse de l'api à utiliser
  449.      * @param Request $request
  450.      * @return JsonResponse
  451.      *
  452.      * @Route("/getprodapiurltouse", name="getprodapiurltouse", options={"expose"=true})
  453.      *
  454.      */
  455.     public function getprodapiurltouseAction()
  456.     {
  457.         $api $this->getParameter('apiadress');
  458.         return new JsonResponse($api);
  459.     }
  460.     /**
  461.      * observatoire des prix
  462.      * @param Request $request
  463.      * @return JsonResponse
  464.      *
  465.      * @Route("/getprimcare/{cp}/{s}/{t}", name="getprimcare", options={"expose"=true})
  466.      * @Method({"GET","POST"})
  467.      *
  468.      */
  469.     public function getprimcareAction($cp,$s,$t)
  470.     {
  471.         if($t 'AP'){
  472.             $tringtype " and (type like 'AP' or type like 'LX') ";
  473.         }else{
  474.             $tringtype " and type like 'MA' ";
  475.         }
  476.         $nbEchantVoulu 25;
  477.         $echantillon 0;
  478.         $iterations 0;
  479.         $iterationsgeneral 0;
  480.         $smin =  $s;
  481.         $smax =  $s;
  482.         $data = [];
  483.         $namedb $this->getParameter('dbreqpdo');
  484.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  485.         while ($echantillon $nbEchantVoulu){
  486.             $echantillon $bdd->query("
  487.         SELECT count(*) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
  488.                              ")->fetchColumn();
  489.             if($echantillon $nbEchantVoulu){
  490.                 $smax $smax +2;
  491.                 $smin $smin -2;
  492.             }
  493.             $iterations ++;
  494.             $iterationsgeneral ++;
  495.             if($iterations == 30){
  496.                 $nbEchantVoulu $nbEchantVoulu 1;
  497.                 $iterations 0;
  498.             }
  499.         }
  500.         $moyene $bdd->query("
  501.         SELECT (sum(loyer)/sum(surface)) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
  502.                              ")->fetchColumn();
  503.         $max $bdd->query("
  504.         SELECT max(loyer) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
  505.                              ")->fetchColumn();
  506.         $min $bdd->query("
  507.         SELECT min(loyer) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
  508.                              ")->fetchColumn();
  509.         switch ($iterationsgeneral) {
  510.             case 1:
  511.                 $data['confiance'] = 5;
  512.                 break;
  513.             case 2:
  514.                 $data['confiance'] = '4.5';
  515.                 break;
  516.             case 3:
  517.                 $data['confiance'] = 4;
  518.                 break;
  519.             case 4:
  520.                 $data['confiance'] = '3.5';
  521.                 break;
  522.             case 5:
  523.                 $data['confiance'] = 3;
  524.                 break;
  525.             case 6:
  526.                 $data['confiance'] = '2.5';
  527.                 break;
  528.             case 7:
  529.                 $data['confiance'] = 2;
  530.                 break;
  531.             case 8:
  532.                 $data['confiance'] = '1.5';
  533.                 break;
  534.             case 9:
  535.                 $data['confiance'] = 1;
  536.                 break;
  537.             case 10:
  538.                 $data['confiance'] = '0.5';
  539.                 break;
  540.             default:
  541.                 $data['confiance'] = 0;
  542.                 break;
  543.         }
  544.         $data['countresult'] = $echantillon;
  545.         $data['moyenmcare'] = $moyene;
  546.         $data['prixmoycalc'] = $moyene*$s;
  547.         $data['max'] = $max;
  548.         $data['min'] = $min;
  549.         $data['smin'] = $smin;
  550.         $data['smax'] = $smax;
  551.         return new JsonResponse(json_encode($data));
  552.     }
  553.     /**
  554.      * Récupérer le nombre d'annonces publiée
  555.      * @param Request $request
  556.      * @return JsonResponse
  557.      *
  558.      * @Route("/countpub", name="countpub", options={"expose"=true})
  559.      *
  560.      */
  561.     public function countpubAction()
  562.     {
  563.         $countpub =  $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates(nullnull2);
  564.         return new JsonResponse($countpub);
  565.     }
  566.     /**
  567.      * Récupérer le nombre de candidature
  568.      * @param Request $request
  569.      * @return JsonResponse
  570.      *
  571.      * @Route("/countcandidatures", name="countcandidatures", options={"expose"=true})
  572.      *
  573.      */
  574.     public function countcandidaturesAction()
  575.     {
  576.         $countcandidatures =  $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates(nullnull);
  577.         return new JsonResponse($countcandidatures);
  578.     }
  579.     /**
  580.      * Stats equipe
  581.      *
  582.      * @Route("/", name="homepage")
  583.      * @return Response
  584.      */
  585.     public function indexAction()
  586.     {
  587.         if(or $this->getUser()->hasRole('ROLE_TIFFANY')){
  588.             return $this->statistiqueAction();
  589.         } else {
  590.             $em =  $this->getDoctrine;
  591.             $stats1 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
  592.             $stats2 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
  593.             $stats2array = [];
  594.             foreach ($stats2 as $key => $stat2){
  595.                 $user $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
  596.                 $stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
  597.                 $stats2array[$key]['type'] = $stat2->getType();
  598.                 $stats2array[$key]['valeur'] = $stat2->getValeur();
  599.                 $stats2array[$key]['target'] = $stat2->getTarget();
  600.             }
  601.             return $this->render('stats/statsAdmin.html.twig', array(
  602.                 'stats1' => $stats1,
  603.                 'stats2' => $stats2array
  604.             ));
  605.         }
  606.     }
  607.     /**
  608.      * Récupérer les statistiques perso
  609.      *
  610.      * @Route("/statistiquesuser", name="statistiquesuser")
  611.      * @return Response
  612.      */
  613.     public function statistiqueUserAction()
  614.     {
  615.         return $this->render('stats/statsUser.html.twig', [
  616.         ]);
  617.     }
  618.     /**
  619.      * Récupérer les pages prime
  620.      *
  621.      * @Route("/primes", name="primespage")
  622.      * @return Response
  623.      */
  624.     public function primesAction()
  625.     {
  626.         return $this->render('stats/primes.html.twig', [
  627.         ]);
  628.     }
  629.     /**
  630.      * json request primes
  631.      *
  632.      * @param Request $request
  633.      * @Route("/stats/getprimes", name="stats_getprimes", options={"expose"=true})
  634.      * @Method({"GET","POST"})
  635.      * @return JsonResponse
  636.      */
  637.     public function getPrimesAction(Request $request)
  638.     {
  639.         $user $this->getUser();
  640.         if($user->hasRole('ROLE_ADMIN')){
  641.             $userFilter false;
  642.         } else {
  643.             $userFilter true;
  644.         }
  645.         $date date_create_from_format('m-Y'$request->get('date'));
  646.         $datestart $date->format('Y-m').'-01';
  647.         $dateend $date->format('Y-m-t');
  648.         $namedb $this->getParameter('dbreqpdo');
  649.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  650.         $sql "SELECT c.id as 'contract_id', owner.id as 'owner_id', renter.id as 'renter_id', com.id as 'commercial_id',
  651.         CONCAT(owner.firstname, ' ', owner.name) as 'owner_name', 
  652.         CONCAT(renter.firstname, ' ', renter.name) as 'renter_name', 
  653.         CONCAT(com.firstname, ' ', com.name) as 'commercial_name',
  654.         lg.signatureDate, lg.entryDate, (lg.signatureDate = lg.entryDate) newlot,
  655.         (f.price + f.charges) * (ot.gestion / 100) as 'marge', lg.id as 'lid'
  656.         FROM app.contract as c
  657.         INNER JOIN app.application as a on a.id = c.application_id
  658.         INNER JOIN app.flat as f on f.id = a.flat
  659.         INNER JOIN app.user as owner on owner.id = f.owned_by_id
  660.         INNER JOIN app.user as renter on renter.id = a.user
  661.         INNER JOIN app.lots_geres as lg on lg.contract = c.id
  662.         INNER JOIN app.user as com on com.id = owner.suivipar
  663.         LEFT JOIN app.offre_tarif as ot on ot.id = c.offre_tarif_id
  664.         WHERE c.status = 2 
  665.         AND ((
  666.             c.is_reprise = true
  667.             AND c.reprise_date BETWEEN '".$datestart."' AND '".$dateend."'
  668.         ) OR (
  669.             (c.is_reprise = false OR c.is_reprise IS NULL)
  670.             AND c.effective_date BETWEEN '".$datestart."' AND '".$dateend."'
  671.         ))
  672.         ". ($userFilter ' AND com.id = '.$user->getId() : '' ) ."
  673.         ORDER BY com.id ASC, newlot ASC;";
  674.         $entrees $bdd->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
  675.         foreach($entrees as $key => $entree){
  676.             if($entree['newlot'] == 0){
  677.                 $sql2 "SELECT lgh.id as 'lghid', ot.gestion as 'gestion', lgh.entryDate as 'entryDate', (f.charges + f.price) * (ot.gestion / 100) as 'marge' 
  678.                          FROM app.lots_geres_historic as lgh 
  679.                          INNER JOIN app.contract as c on c.id = lgh.contractId
  680.                          INNER JOIN app.application as a on a.id = c.application_id
  681.                          INNER JOIN app.flat as f on f.id = a.flat
  682.                          INNER JOIN app.offre_tarif as ot on ot.id = c.offre_tarif_id
  683.                          WHERE lgh.lotsGeresId = "$entree['lid'] ."
  684.                          ORDER BY lgh.entryDate DESC";
  685.                 $cs $bdd->query($sql2)->fetchAll(\PDO::FETCH_ASSOC);
  686.                 $entrees[$key]['sql'] = $sql;
  687.                 $entrees[$key]['sql2'] = $sql2;
  688.                 if(array_key_exists(1$cs)){
  689.                     $entrees[$key]['newmarge'] = $cs[0]['marge'] - $cs[1]['marge'];
  690.                 } else {
  691.                     $entrees[$key]['newmarge'] = 0;
  692.                 }
  693.             } else {
  694.                 $entrees[$key]['newmarge'] = 0;
  695.             }
  696.             $sql3 "SELECT com.firstname, com.name FROM app.distrib_flat as df
  697.                             inner join app.user as u on u.id = df.user
  698.                             inner join app.user as com on df.commercial = com.id
  699.                             where u.id = ".$entree['owner_id']." limit 1";
  700.             $originalcom $bdd->query($sql3)->fetchAll(\PDO::FETCH_ASSOC);
  701.             $entrees[$key]['sql3'] = $sql3;
  702.             if (isset($originalcom[0])) {
  703.                 $entrees[$key]['originalcom']= $originalcom[0]['firstname'].' '.$originalcom[0]['name'];
  704.             }
  705.             
  706.         }
  707.         $serializer SerializerBuilder::create()->build();
  708.         $jsonStats $serializer->serialize($entrees'json');
  709.         return new JsonResponse($jsonStats);
  710.     }
  711.     /**
  712.      * Récupérer les statistiques perso
  713.      *
  714.      * @Route("/marketing", name="marketingpage")
  715.      * @return Response
  716.      */
  717.     public function marketingPageAction()
  718.     {
  719.         $namedb $this->getParameter('dbreqpdo');
  720.         $udb $this->getParameter('userreqpdo');
  721. $pdb $this->getParameter('passreqpdo');
  722. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  723.         $sql "SELECT avg(YEAR(CURDATE()) - YEAR(u.birthdate)) as 'avg' FROM app.user as u
  724.                 INNER JOIN app.flat as f on f.owned_by_id = u.id
  725.                 INNER JOIN app.application as a on a.flat = f.id
  726.                 INNER JOIN app.contract as c on c.application_id = a.id
  727.                 where birthdate is not null and initial_mode = 2";
  728.         $sthd $bdd->prepare($sql);
  729.         $sthd->execute();
  730.         $result $sthd->fetch(\PDO::FETCH_ASSOC);
  731.         return $this->render('stats/marketing.html.twig', [
  732.             'avgAge' => $result['avg']
  733.         ]);
  734.     }
  735.     /**
  736.      * Récupérer les statistiques de l'accueil
  737.      *
  738.      * @Route("/statistiquesglobal", name="statistiquesglobal")
  739.      * @return Response
  740.      */
  741.     public function statistiqueAction()
  742.     {
  743.         $myMinData = (new \DateTime('2018-01-01'))->setTime(00);
  744.         $today = (new \DateTime())->setTime(00);
  745.         $renterNumber =  $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(1$myMinData, new \DateTime());
  746.         $renterTodayNumber =  $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(1$today, new \DateTime());
  747.         $ownerNumber =  $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(2$myMinData, new \DateTime());
  748.         $ownerTodayNumber =  $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(2$today, new \DateTime());
  749.         $flatNumber =  $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates($myMinData, new \DateTime(), 2);
  750.         $flatTodayNumber =  $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates($today, new \DateTime(), 2);
  751.         $flatMultidifNumber =  $this->getDoctrine->getRepository('AppBundle:Flat')->counMultidif();
  752.         $countLike =  $this->getDoctrine->getRepository('AppBundle:FlatLike')->countLike();
  753.         $countVideo =  $this->getDoctrine->getRepository('AppBundle:VideoTask')->countVideo();
  754.         $mandateNumber =  $this->getDoctrine->getRepository('AppBundle:Mandate')->countByDates($myMinData, new \DateTime());
  755.         $mandateTodayNumber =  $this->getDoctrine->getRepository('AppBundle:Mandate')->countByDates($today, new \DateTime());
  756.         $applicationNumber =  $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates($myMinData, new \DateTime());
  757.         $applicationTodayNumber =  $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates($today, new \DateTime());
  758.         $contractNumber =  $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->countDoneByDatesAndCategory($myMinData, new \DateTime());
  759.         $contractTodayNumber =  $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->countDoneByDatesAndCategory($today, new \DateTime());
  760.         // countTaskByDates
  761.         $tasknumber =  $this->getDoctrine->getRepository('AppBundle:Contract')->countTaskByDates($myMinData, new \DateTime());
  762.         $taskTodayNumber =  $this->getDoctrine->getRepository('AppBundle:Contract')->countTaskByDates($today, new \DateTime());
  763.         $countGreenContract =  $this->getDoctrine->getRepository('AppBundle:Contract')->countGreen();
  764.         $countRedContract =  $this->getDoctrine->getRepository('AppBundle:Contract')->countRed();
  765.         return $this->render('stats/stats.html.twig', [
  766.             'renterNumber' => $renterNumber,
  767.             'renterTodayNumber' => $renterTodayNumber,
  768.             'ownerNumber' => $ownerNumber,
  769.             'ownerTodayNumber' => $ownerTodayNumber,
  770.             'flatNumber' => $flatNumber,
  771.             'flatTodayNumber' => $flatTodayNumber,
  772.             'mandateNumber' => $mandateNumber,
  773.             'mandateTodayNumber' => $mandateTodayNumber,
  774.             'applicationNumber' => $applicationNumber,
  775.             'applicationTodayNumber' => $applicationTodayNumber,
  776.             'contractNumber' => $contractNumber,
  777.             'contractTodayNumber' => $contractTodayNumber,
  778.             'taskNumber' => $tasknumber,
  779.             'taskTodayNumber' => $taskTodayNumber,
  780.             'flatMultidifNumber' => $flatMultidifNumber,
  781.             'totalLikes' => $countLike,
  782.             'totalVideos' => $countVideo,
  783.             'greenContract' => $countGreenContract,
  784.             'redContract' => $countRedContract
  785.         ]);
  786.     }
  787.     /**
  788.      * Récupérer les statistiques de l'accueil
  789.      *
  790.      * @Route("/statistiques_sales", name="statistiques_sales")
  791.      * @return Response
  792.      */
  793.     public function statistiqueSalesAction()
  794.     {
  795.         $em =  $this->getDoctrine;
  796.         $stats1 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
  797.         $stats2 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
  798.         $stats2array = [];
  799.         foreach ($stats2 as $key => $stat2){
  800.             $user $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
  801.             $stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
  802.             $stats2array[$key]['type'] = $stat2->getType();
  803.             $stats2array[$key]['valeur'] = $stat2->getValeur();
  804.             $stats2array[$key]['target'] = $stat2->getTarget();
  805.         }
  806.         $namedb $this->getParameter('dbreqpdo');
  807.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  808.         // prop sans annonces
  809.         $propsansflat $bdd->query("SELECT sum(fl.charges + fl.price) as qtotal FROM app.lots_geres as l 
  810.                         INNER Join flat as fl on fl.id = l.flat
  811.                         INNER JOIN contract as c on c.id = l.contract
  812.                         WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
  813.                         INNER JOIN app.contract as c on c.id = l.contract
  814.                         INNER JOIN app.application as a on a.id = c.application_id
  815.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn))
  816.                         and l.flat not in (select flat from app.churn) and c.status <> 3
  817.                              ")->fetchColumn();
  818.         $nblot $bdd->query("SELECT count(*) as qtotal FROM app.lots_geres as l 
  819.                   WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
  820.                         INNER JOIN app.contract as c on c.id = l.contract
  821.                         INNER JOIN app.application as a on a.id = c.application_id
  822.                         
  823.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn))
  824.                         and l.flat not in (select flat from app.churn)
  825.                              ")->fetchColumn();
  826.         $CATOTAL $bdd->query("SELECT sum( ( (fl.charges + fl.price)* ot.gestion/100) + ( (fl.charges + fl.price)* ot.assurance/100) ) as qtotal FROM app.lots_geres as l 
  827. INNER Join flat as fl on fl.id = l.flat
  828. inner Join contract as cec on cec.id = l.contract
  829. inner Join offre_tarif as ot on ot.id = cec.offre_tarif_id
  830.                   WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
  831.                         INNER JOIN app.contract as c on c.id = l.contract
  832.                         INNER JOIN app.application as a on a.id = c.application_id
  833.                         
  834.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn))
  835.                         and l.flat not in (select flat from app.churn) and cec.status <> 3")->fetchColumn();
  836.         $annonceparprop $bdd->query("SELECT (count(lg.id) / count(distinct(u.id))) as 'number' FROM app.lots_geres as lg
  837. inner join app.contract as c on c.id = lg.contract
  838. inner join app.application as a on a.id = c.application_id
  839. inner join app.flat as f on f.id =a.flat
  840. inner join app.user as u on u.id = f.owned_by_id;")->fetchColumn();
  841.         // nombre de contrats visal
  842.         $nbcontratvisale $bdd->query("SELECT count(*) as number FROM app.contract as c
  843.                                                 where c.status = 2
  844.                                                 and offre_tarif_id in(2,5,9,12,14,16,18);")->fetchColumn();
  845.         // nombre de contyrats GLI
  846.         $nbcontratgli $bdd->query("SELECT count(*) as number FROM app.contract as c
  847.                                                     where c.status = 2
  848.                                                     and offre_tarif_id not in(2,5,9,12,14,16,18,8,17);")->fetchColumn();
  849.         $quittMoy = (float)$propsansflat / (float)$nblot;
  850.         $camoy = (float)$CATOTAL / (float)$nblot;
  851.         $pourcentmoylot = (float)$camoy / (float)$quittMoy;
  852.         return $this->render('stats/sales.html.twig', [
  853.             'stats1' => $stats1,
  854.             'stats2' => $stats2array,
  855.             'quittTotal' => number_format(round($propsansflat,2),2,"."," ").' €',
  856.             'quittmoy'=> number_format(round($quittMoy,2),2,"."," ").' €',
  857.             'quitcount' => $nblot.' €',
  858.             'catotal' => number_format(round($CATOTAL,2),2,"."," ").' €',
  859.             'camoy' => number_format(round($camoy,2),2,"."," ").' €',
  860.             'valo' => number_format(round($CATOTAL 12 4,2),2,"."," ").' €',
  861.             'pcentmoy' => round(($pourcentmoylot 100 ),2).' %',
  862.             'ltv' => number_format(round((1/(4/414) * 47) ,2),2,"."," ").' €',
  863.             'annonceparprop' => number_format(round($annonceparprop ,2),2,"."," ").'',
  864.             'nbcontratvisale'=> $nbcontratvisale,
  865.             'nbcontratgli'=> $nbcontratgli
  866.         ]);
  867.     }
  868.     /**
  869.      * json requette obtention evolution quitancement moyen loyer
  870.      *
  871.      * @param Request $request
  872.      * @Route("/stats/statEvoloyermoyparlots", name="stats_statEvoloyermoyparlots", options={"expose"=true})
  873.      * @Method({"GET","POST"})
  874.      * @return JsonResponse
  875.      */
  876.     public function statEvoloyermoyparlotsAction(Request $request)
  877.     {
  878.         $firstDate $request->query->get('first_date');
  879.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  880.         $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getQuittancementNblotsByDates($firstDate,$lastDate);
  881.         $results['ca'] = $basique;
  882.         $serializer SerializerBuilder::create()->build();
  883.         $jsonStats $serializer->serialize($results'json');
  884.         return new JsonResponse($jsonStats);
  885.     }
  886.     /**
  887.      * json requette obtention evolution quitancement moyen loyer
  888.      *
  889.      * @param Request $request
  890.      * @Route("/stats/statoriginclientprop", name="stats_statoriginclientprop", options={"expose"=true})
  891.      * @Method({"GET","POST"})
  892.      * @return JsonResponse
  893.      */
  894.     public function statOriginClientPropAction(Request $request)
  895.     {
  896.         $firstDate $request->query->get('first_date');
  897.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  898.         $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOriginesClient();
  899.         $results['ca'] = $basique;
  900.         $serializer SerializerBuilder::create()->build();
  901.         $jsonStats $serializer->serialize($results'json');
  902.         return new JsonResponse($jsonStats);
  903.     }
  904.     /**
  905.      * json requette obtention evolution quitancement moyen loyer
  906.      *
  907.      * @param Request $request
  908.      * @Route("/stats/statpourcentageevo", name="stats_statpourcentageevo", options={"expose"=true})
  909.      * @Method({"GET","POST"})
  910.      * @return JsonResponse
  911.      */
  912.     public function statpourcentageevoAction(Request $request)
  913.     {
  914.         $firstDate $request->query->get('first_date');
  915.         $lastDate $request->query->get('last_date');
  916.         $months $this->getDatesBetweenJustMonth($firstDate$lastDate);
  917.         $em =  $this->getDoctrine->getManager();
  918.         $datas = [];
  919.         foreach ($months as $key1 => $month) {
  920.             $sql "SELECT sum(f.price + f.charges) as 'quittotal', (count(l.id)) as nblot, 
  921.                     (sum(((f.charges + f.price) * ot.gestion/100) + ((f.charges + f.price)*ot.assurance/100))) as catotal,
  922.                     ((sum(((f.charges + f.price)*ot.gestion/100) + ((f.charges + f.price)*ot.assurance/100) )) / (sum(f.price + f.charges)) * 100) as number
  923.                     FROM lots_geres_historic as lgh
  924.                     INNER JOIN app.lots_geres as l on l.id = lgh.lotsGeresId
  925.                     INNER JOIN app.contract as c on c.id = lgh.contractId
  926.                     INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
  927.                     INNER JOIN app.offre_tarif as ot on coh.offreId = ot.id
  928.                     INNER JOIN app.application as app on app.id = c.application_id
  929.                     INNER JOIN app.flat as f on f.id = app.flat
  930.                     WHERE lgh.entryDate < :date2 
  931.                     AND (coh.startDate < :date2 AND (coh.endDate is null OR coh.endDate >= :date2))
  932.                     AND l.id not in 
  933.                     (
  934.                         SELECT l.id FROM app.lots_geres as l
  935.                         INNER JOIN app.contract as c on c.id = l.contract
  936.                         INNER JOIN app.application as a on a.id = c.application_id
  937.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn)
  938.                     )
  939.                     AND l.flat not in (select flat from app.churn)
  940.                     ORDER BY l.entryDate ASC";
  941.             $stmt $em->getConnection()->prepare($sql);
  942.             $datemonth = new \DateTime($month.'-01');
  943.             $param1 $datemonth->format('Y-m-d');
  944.             $param2 $datemonth->format('Y-m-t').' 23:59:59';
  945.             $stmt->bindParam(':date1'$param1);
  946.             $stmt->bindParam(':date2'$param2);
  947.             $resultSet $stmt->executeQuery();
  948.             $avg $resultSet->fetchAll();
  949.             //$avg = $stmt->fetchAll();
  950.             if($key1 !== count($months)){
  951.                 $datas[$key1] = ['date' => $datemonth->format('Y-m')];
  952.                 $datas[$key1]['number'] = isset($avg[0]['number']) ? $avg[0]['number'] : 0;
  953.             }
  954.         }
  955.         $results['ca'] = $datas;
  956.         $serializer SerializerBuilder::create()->build();
  957.         $jsonStats $serializer->serialize($results'json');
  958.         return new JsonResponse($jsonStats);
  959.     }
  960.     /**
  961.      * json requette obtention evolution quitancement moyen loyer
  962.      *
  963.      * @param Request $request
  964.      * @Route("/stats/statnblots", name="stats_statnblots", options={"expose"=true})
  965.      * @Method({"GET","POST"})
  966.      * @return JsonResponse
  967.      */
  968.     public function statnblotsAction(Request $request)
  969.     {
  970.         $firstDate $request->query->get('first_date');
  971.         $lastDate $request->query->get('last_date');
  972.         $months $this->getDatesBetweenJustMonth($firstDate$lastDate);
  973.         $em =  $this->getDoctrine->getManager();
  974.         $datas = [];
  975.         foreach ($months as $key1 => $month) {
  976.             $sql "SELECT count(l.id) as nblot
  977.                     FROM lots_geres as l
  978.                     INNER JOIN app.contract as c on c.id = l.contract
  979.                     INNER JOIN app.application as app on app.id = c.application_id
  980.                     INNER JOIN app.flat as f on f.id = app.flat
  981.                     WHERE l.entryDate <= :date2
  982.                     AND l.id not in 
  983.                     (
  984.                         SELECT l.id FROM app.lots_geres as l
  985.                         INNER JOIN app.contract as c on c.id = l.contract
  986.                         INNER JOIN app.application as a on a.id = c.application_id
  987.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn)
  988.                     )
  989.                     AND l.flat not in (select flat from app.churn)
  990.                     ORDER BY l.entryDate ASC";
  991.             $stmt $em->getConnection()->prepare($sql);
  992.             $datemonth = new \DateTime($month.'-01');
  993.             $param2 $datemonth->format('Y-m-t').' 23:59:59';
  994.             $stmt->bindParam(':date2'$param2);
  995.             $resultSet $stmt->executeQuery();
  996.             $avg $resultSet->fetchAll();
  997.             //$avg = $stmt->fetchAll();
  998.             if($key1 !== count($months)){
  999.                 $datas[$key1] = ['date' => $datemonth->format('Y-m')];
  1000.                 $datas[$key1]['nblot'] = isset($avg[0]['nblot']) ? $avg[0]['nblot'] : 0;
  1001.             }
  1002.         }
  1003.         $results['ca'] = $datas;
  1004.         $serializer SerializerBuilder::create()->build();
  1005.         $jsonStats $serializer->serialize($results'json');
  1006.         return new JsonResponse($jsonStats);
  1007.     }
  1008.     /**
  1009.      * Récupérer les statistiques de l'accueil
  1010.      *
  1011.      * @Route("/indexnew", name="homepagenew")
  1012.      * @return Response
  1013.      */
  1014.     public function indexNewAction()
  1015.     {
  1016.         $em =  $this->getDoctrine->getManager();
  1017.         $pr $em->getRepository('App\AppBundle\Entity\PhraseJour');
  1018.         $phrases $pr->findBy(['actif' => 1]);
  1019.         $phrase $phrases[0];
  1020.         $data = [];
  1021.         $data['phrase'] = $phrase;
  1022.         $namedb $this->getParameter('dbreqpdo');
  1023.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  1024.         // prop sans annonces
  1025.         $propsansflat $bdd->query("
  1026.         SELECT count(*) FROM app.user where id not in (select app.flat.owned_by_id from app.flat) and initial_mode = 2
  1027.                              ")->fetchColumn();
  1028.         $data['propsansflat'] = $propsansflat;
  1029.         // controle des annonces
  1030.         $controleflat $bdd->query("
  1031.         SELECT count(*) FROM app.flat where status = 2 and can_multidif = 0
  1032.                              ")->fetchColumn();
  1033.         $data['controleflat'] = $controleflat;
  1034.         // Annonces sans candidatures sous 72 heures
  1035.         $time mktime(date("H")-72date("i"), date("s"), date("m"), date("d"), date("Y"));
  1036.         $heureref date("Y-m-d H:i:s"$time);
  1037.         $flatsanscandidat $bdd->query("
  1038.         SELECT count(*) FROM app.flat where id not in (select app.application.flat from app.application) and status = 2 and created_at < '".$heureref."'")->fetchColumn();
  1039.         $data['flatsanscandidat'] = $flatsanscandidat;
  1040.         // Candidature sans date de visite
  1041.         $candsansdatevisite $bdd->query("
  1042.         SELECT count(*) FROM app.application where id not in (select app.visite_date.application_id from app.visite_date) and status = 2")->fetchColumn();
  1043.         $data['candsansdatevisite'] = $candsansdatevisite;
  1044.         // Locataires sans candidatures sur WIZI
  1045.         $locsanscandidat $bdd->query("
  1046.         SELECT count(*) FROM app.user where initial_mode = 1  and id not in (select app.application.user from app.application) and enabled = 1")->fetchColumn();
  1047.         $data['locsanscandidat'] = $locsanscandidat;
  1048.         // dossiers a vériffier
  1049.         $dostoverif $bdd->query("
  1050.         Select count(*) from contract as c inner join application as apps on apps.id = c.application_id where apps.taskdocstatus = 0 and c.taskdoctriger = 1")->fetchColumn();
  1051.         $data['dostoverif'] = $dostoverif;
  1052.         // dossiers attente de vérification
  1053.         $dosattenteverif $bdd->query("
  1054.         Select count(*) from app.application where status = 5")->fetchColumn();
  1055.         $data['dosattenteverif'] = $dosattenteverif;
  1056.         /// partie tableau des objectiffs
  1057.         $date date("Y-m-d");
  1058.         $startdate $date.' 00:00:00';
  1059.         $startend $date.' 23:59:59';
  1060.         // locataires inscrits
  1061.         $locinscrits $bdd->query("
  1062.         Select count(*) from app.user where initial_mode = 1 and created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
  1063.         $data['locinscrits'] = $locinscrits;
  1064.         // prop inscrits
  1065.         $propinscrits $bdd->query("
  1066.         Select count(*) from app.user where initial_mode = 2 and created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
  1067.         $data['propinscrits'] = $propinscrits;
  1068.         // candidatures du jour
  1069.         $appday $bdd->query("
  1070.         Select count(*) from app.application where  created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
  1071.         $data['appday'] = $appday;
  1072.         // annonces du jour
  1073.         $flatday $bdd->query("
  1074.         Select count(*) from app.application where  created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
  1075.         $data['flatday'] = $flatday;
  1076.         // contrats du jour
  1077.         $contractday $bdd->query("
  1078.         Select count(*) from app.contract where  created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
  1079.         $data['contractday'] = $contractday;
  1080.         $em =  $this->getDoctrine->getManager();
  1081.         $obj $em->getRepository('App\AppBundle\Entity\DailyObjectif');
  1082.         $objs $obj->findBy([],array('id' => 'DESC'));
  1083.         $ob $objs[0];
  1084.         $data['dayobs'] = $ob;
  1085.         return $this->render('Extranet/homepagenew.html.twig'$data);
  1086.     }
  1087.     /**
  1088.      * Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
  1089.      *
  1090.      * @param Request $request
  1091.      * @return JsonResponse
  1092.      * @Route("/stats/caparlots", name="stats_caparlots_date", options={"expose"=true})
  1093.      * @Method({"GET","POST"})
  1094.      */
  1095.     public function statsCaParLotDateAction(Request $request)
  1096.     {
  1097.         $firstDate $request->query->get('first_date');
  1098.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1099.         $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaByDates($firstDate,$lastDate);
  1100.         $results['ca'] = $basique;
  1101.         $serializer SerializerBuilder::create()->build();
  1102.         $jsonStats $serializer->serialize($results'json');
  1103.         return new JsonResponse($jsonStats);
  1104.     }
  1105.     /**
  1106.      * Etat des lots geres
  1107.      *
  1108.      * @return JsonResponse
  1109.      * @Route("/stats/statelotsgeres", name="stats_statelotsgeres", options={"expose"=true})
  1110.      * @Method({"GET","POST"})
  1111.      */
  1112.     public function statsStatelotsgeresAction()
  1113.     {
  1114.         $data =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getStateLots();
  1115.         $results['data'] = $data;
  1116.         $serializer SerializerBuilder::create()->build();
  1117.         $jsonStats $serializer->serialize($results'json');
  1118.         return new JsonResponse($jsonStats);
  1119.     }
  1120.     /**
  1121.      * Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
  1122.      *
  1123.      * @param Request $request
  1124.      * @return JsonResponse
  1125.      * @Route("/stats/evocaparlotss", name="stats_evocaparlots_date", options={"expose"=true})
  1126.      * @Method({"GET","POST"})
  1127.      */
  1128.     public function statsEvoCaParLotDateAction(Request $request)
  1129.     {
  1130.         $firstDate $request->query->get('first_date');
  1131.         $lastDate $request->query->get('last_date');
  1132.         $months $this->getDatesBetweenJustMonth($firstDate$lastDate);
  1133.         $em =  $this->getDoctrine->getManager();
  1134.         $datas = [];
  1135.         foreach ($months as $key1 => $month) {
  1136.             $sql "SELECT AVG(((f.price + f.charges) * (ot.gestion + ot.assurance)) / 100) as average
  1137.                     FROM lots_geres_historic as lgh
  1138.                     INNER JOIN app.lots_geres as l on l.id = lgh.lotsGeresId
  1139.                     INNER JOIN app.contract as c on c.id = lgh.contractId
  1140.                     INNER JOIN app.application as app on app.id = c.application_id
  1141.                     INNER JOIN app.flat as f on f.id = app.flat
  1142.                     INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
  1143.                     INNER JOIN app.offre_tarif as ot on coh.offreId = ot.id
  1144.                     WHERE lgh.entryDate BETWEEN :date1 AND :date2
  1145.                     AND coh.startDate BETWEEN :date1 and :date2
  1146.                     ORDER BY lgh.entryDate ASC";
  1147.             $stmt $em->getConnection()->prepare($sql);
  1148.             $datemonth = new \DateTime($month.'-01');
  1149.             $param1 $datemonth->format('Y-m-d');
  1150.             $param2 $datemonth->format('Y-m-t').' 23:59:59';
  1151.             $stmt->bindParam(':date1'$param1);
  1152.             $stmt->bindParam(':date2'$param2);
  1153.             $resultSet $stmt->executeQuery();
  1154.             $avg $resultSet->fetchAll();
  1155.             
  1156.             if($key1 !== count($months)){
  1157.                 $datas[$key1] = ['date' => $datemonth->format('Y-m')];
  1158.                 $datas[$key1]['number'] = isset($avg[0]['average']) ? $avg[0]['average'] : 0;
  1159.             }
  1160.         }
  1161.         $results['ca'] = $datas;
  1162.         $serializer SerializerBuilder::create()->build();
  1163.         $jsonStats $serializer->serialize($results'json');
  1164.         return new JsonResponse($jsonStats);
  1165.     }
  1166.     /**
  1167.      * Récupérer le CA pur par lots entre deux dates
  1168.      *
  1169.      * @param Request $request
  1170.      * @return JsonResponse
  1171.      * @Route("/stats/evocapurparlotss", name="stats_evocapurparlots_date", options={"expose"=true})
  1172.      * @Method({"GET","POST"})
  1173.      */
  1174.     public function statsEvoCaPurParLotDateAction(Request $request)
  1175.     {
  1176.         $em =  $this->getDoctrine->getManager();
  1177.         $startDate $request->get('first_date');
  1178.         $endDate $request->get('last_date');
  1179.         $months $this->getDatesBetweenJustMonth($startDate$endDate);
  1180.         $hon = [];
  1181.         $dg = [];
  1182.         $ca = [];
  1183.         foreach ($months as $mkey => $month) {
  1184.             $datemonth = new \DateTime($month.'-01');
  1185.             $assurance[$mkey] =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getAssuranceByMonth($month)[0];
  1186.             $hon[$mkey] =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaPurByMonth($month)[0];
  1187.             $hon[$mkey]["number"] = (($hon[$mkey]["number"] - $assurance[$mkey]["number"]) / 1.2) + $assurance[$mkey]["number"];
  1188.             $dg[$mkey] =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getDgByMonth($month)[0];
  1189.             $dg[$mkey]["number"] = $dg[$mkey]["number"] / 1.2;
  1190.             // Calculer Upsell
  1191.             $upsell[$mkey] =  $this->getDoctrine->getRepository('AppBundle:FinancesFournisseur')->getUpSellByMonth($month)[0];
  1192.             $upsell[$mkey]["number"] = $upsell[$mkey]["number"] / 1.2;
  1193.             $ca[$mkey] = ["number" => $hon[$mkey]["number"] + $dg[$mkey]["number"] + $upsell[$mkey]["number"], "date" => $datemonth->format('Y-m')];
  1194.         }
  1195.         // $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaPurDates($firstDate,$lastDate);
  1196.         $results['ca'] = $ca;
  1197.         $serializer SerializerBuilder::create()->build();
  1198.         $jsonStats $serializer->serialize($results'json');
  1199.         return new JsonResponse($jsonStats);
  1200.     }
  1201.     /**
  1202.      * Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
  1203.      *
  1204.      * @param Request $request
  1205.      * @return JsonResponse
  1206.      * @Route("/stats/ByTarteFlatOffredate", name="stats_tarte_offre_flat_date", options={"expose"=true})
  1207.      * @Method({"GET","POST"})
  1208.      */
  1209.     public function statsByTarteFlatOffreDateAction(Request $request)
  1210.     {
  1211.         $firstDate $request->query->get('first_date');
  1212.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1213.         $basique =  $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate1);
  1214.         $classique =  $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate2);
  1215.         $securite =  $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate3);
  1216.         $serenite =  $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate4);
  1217.         $plenitude =  $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate5);
  1218.         $results['basique'] = $basique;
  1219.         $results['classique'] = $classique;
  1220.         $results['securite'] = $securite;
  1221.         $results['serenite'] = $serenite;
  1222.         $results['plenitude'] = $plenitude;
  1223.         $serializer SerializerBuilder::create()->build();
  1224.         $jsonStats $serializer->serialize($results'json');
  1225.         return new JsonResponse($jsonStats);
  1226.     }
  1227.     /**
  1228.      * Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
  1229.      *
  1230.      * @param Request $request
  1231.      * @return JsonResponse
  1232.      * @Route("/stats/statsLotsGeresByCommercial", name="statsLotsGeresByCommercial", options={"expose"=true})
  1233.      * @Method({"GET","POST"})
  1234.      */
  1235.     public function statsLotsGeresByCommercialAction(Request $request)
  1236.     {
  1237.         $firstDate $request->query->get('first_date');
  1238.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1239.         $lastDatei $request->query->get('last_date');
  1240.         $date $this->getDatesBetweenJustMonth($firstDate$lastDatei);
  1241.         $results = ['date' => $date];
  1242.         $commerciaux =  $this->getDoctrine->getRepository('AppBundle:User')->findByRoles('ROLE_COMMERCIAL');
  1243.         foreach ($commerciaux as $key => $commercial){
  1244.             $results['data'][$key] =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getLotsByDatesByCommercial($firstDate,$lastDate$commercial->getId());
  1245.         }
  1246.         $serializer SerializerBuilder::create()->build();
  1247.         $jsonStats $serializer->serialize($results'json');
  1248.         return new JsonResponse($jsonStats);
  1249.     }
  1250.     /**
  1251.      * Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
  1252.      *
  1253.      * @param Request $request
  1254.      * @return JsonResponse
  1255.      * @Route("/stats/statsnouveauxLotsDate", name="statsnouveauxLotsDate_date", options={"expose"=true})
  1256.      * @Method({"GET","POST"})
  1257.      */
  1258.     public function statsnouveauxLotsDateAction(Request $request)
  1259.     {
  1260.         $firstDate $request->query->get('first_date');
  1261.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1262.         $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getLotsByDates($firstDate,$lastDate);
  1263.         $results['newlots'] = $basique;
  1264.         $serializer SerializerBuilder::create()->build();
  1265.         $jsonStats $serializer->serialize($results'json');
  1266.         return new JsonResponse($jsonStats);
  1267.     }
  1268.     /**
  1269.      * json requette obtention détail de contrat remporté dans les Stats Général
  1270.      *
  1271.      * @param Request $request
  1272.      * @Route("/stats/statsQuittancementEtPlus", name="stats_statsQuittancement", options={"expose"=true})
  1273.      * @Method({"GET","POST"})
  1274.      * @return JsonResponse
  1275.      */
  1276.     public function statsQuitancementEtPlusAction(Request $request)
  1277.     {
  1278.         $firstDate $request->query->get('first_date');
  1279.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1280.         $basique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getQuittancementByDates($firstDate,$lastDate);
  1281.         $results['quittancement'] = $basique;
  1282.         $serializer SerializerBuilder::create()->build();
  1283.         $jsonStats $serializer->serialize($results'json');
  1284.         return new JsonResponse($jsonStats);
  1285.     }
  1286.     /**
  1287.      * json requette obtention détail de contrat remporté dans les Stats Général
  1288.      *
  1289.      * @param Request $request
  1290.      * @Route("/stats/churn", name="stats_churn", options={"expose"=true})
  1291.      * @Method({"GET","POST"})
  1292.      * @return JsonResponse
  1293.      */
  1294.     public function statsChurnAction(Request $request)
  1295.     {
  1296.         $firstDate $request->query->get('first_date');
  1297.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1298.         $basique =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnsByDates($firstDate,$lastDate);
  1299.         $results['churn'] = $basique;
  1300.         $serializer SerializerBuilder::create()->build();
  1301.         $jsonStats $serializer->serialize($results'json');
  1302.         return new JsonResponse($jsonStats);
  1303.     }
  1304.     /**
  1305.      * function getDatesBetween
  1306.      * renvoie un tableau contenant toutes les dates, jour par jour,
  1307.      * comprises entre les deux dates passées en paramètre.
  1308.      * NB : les dates doivent être au format aaaa-mm-dd (mais on peut changer le parsing)
  1309.      * @param (string) $dStart : date de départ
  1310.      * @param (string) $dEnd : date de fin
  1311.      * @return (array) aDates : tableau des dates si succès
  1312.      * @return (bool) false : si échec
  1313.      */
  1314.     public function getDatesBetween ($dStart$dEnd) {
  1315.         $iStart strtotime ($dStart);
  1316.         $iEnd strtotime ($dEnd);
  1317.         if (false === $iStart || false === $iEnd) {
  1318.             return false;
  1319.         }
  1320.         $aStart explode ('-'$dStart);
  1321.         $aEnd explode ('-'$dEnd);
  1322.         if (count ($aStart) !== || count ($aEnd) !== 3) {
  1323.             return false;
  1324.         }
  1325.         if (false === checkdate ($aStart[1], $aStart[2], $aStart[0]) || false === checkdate ($aEnd[1], $aEnd[2], $aEnd[0]) || $iEnd <= $iStart) {
  1326.             return false;
  1327.         }
  1328.         for ($i $iStart$i $iEnd 86400$i strtotime ('+1 day'$i) ) {
  1329.             $sDateToArr strftime ('%Y-%m-%d'$i);
  1330.             $sYear substr ($sDateToArr04);
  1331.             $sMonth substr ($sDateToArr52);
  1332.             $aDates[$sYear][$sMonth][] = $sDateToArr;
  1333.         }
  1334.         if (isset ($aDates) && !empty ($aDates)) {
  1335.             return $aDates;
  1336.         } else {
  1337.             return false;
  1338.         }
  1339.     }
  1340.     /**
  1341.      * function getDatesBetween
  1342.      * renvoie un tableau contenant toutes les dates, jour par jour,
  1343.      * comprises entre les deux dates passées en paramètre.
  1344.      * NB : les dates doivent être au format aaaa-mm-dd (mais on peut changer le parsing)
  1345.      * @param (string) $dStart : date de départ
  1346.      * @param (string) $dEnd : date de fin
  1347.      * @return (array) aDates : tableau des dates si succès
  1348.      * @return (bool) false : si échec
  1349.      */
  1350.     public function getDatesBetweenJustMonth ($dStart$dEnd) {
  1351.         $monthyear = [];
  1352.         $holdmy '';
  1353.         $iStart strtotime ($dStart);
  1354.         $iEnd strtotime ($dEnd);
  1355.         if (false === $iStart || false === $iEnd) {
  1356.             return false;
  1357.         }
  1358.         $aStart explode ('-'$dStart);
  1359.         $aEnd explode ('-'$dEnd);
  1360.         if (count ($aStart) !== || count ($aEnd) !== 3) {
  1361.             return false;
  1362.         }
  1363.         if (false === checkdate ($aStart[1], $aStart[2], $aStart[0]) || false === checkdate ($aEnd[1], $aEnd[2], $aEnd[0]) || $iEnd <= $iStart) {
  1364.             return false;
  1365.         }
  1366.         for ($i $iStart$i $iEnd 86400$i strtotime ('+1 day'$i) ) {
  1367.             $sDateToArr strftime ('%Y-%m-%d'$i);
  1368.             $sYear substr ($sDateToArr04);
  1369.             $sMonth substr ($sDateToArr52);
  1370.             $aDates[$sYear][$sMonth][] = $sDateToArr;
  1371.             if (($sYear.'-'.$sMonth) != $holdmy) {
  1372.                 $monthyear[]= $sYear.'-'.$sMonth;
  1373.             }
  1374.             $holdmy $sYear.'-'.$sMonth;
  1375.         }
  1376.         if (isset ($aDates) && !empty ($aDates)) {
  1377.             return $monthyear;
  1378.         } else {
  1379.             return false;
  1380.         }
  1381.     }
  1382.     /**
  1383.      * json requette obtention détail de contrat remporté dans les Stats Général
  1384.      *
  1385.      * @param Request $request
  1386.      * @Route("/stats/offrevendu", name="stats_offrevendu", options={"expose"=true})
  1387.      * @Method({"GET","POST"})
  1388.      * @return JsonResponse
  1389.      */
  1390.     public function statsoffrevenduAction(Request $request)
  1391.     {
  1392.         $firstDate $request->query->get('first_date');
  1393.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1394.         $lastDatei $request->query->get('last_date');
  1395.         $test $this->getDatesBetweenJustMonth ($firstDate$lastDatei);
  1396.         $ctest count($test);
  1397.         $iterations 1;
  1398.         foreach ($test as $my) {
  1399.             $mymonT explode("-"$my);
  1400.             if ($iterations == 1) {
  1401.                 $fdparam $firstDate;
  1402.                 $ldparam date("Y-m-t"strtotime($firstDate));
  1403.             }elseif ($iterations == $ctest) {
  1404.                 $fdparam $my.'-01';
  1405.                 $ldparam $lastDate;
  1406.             }else{
  1407.                 $fdparam $my.'-01';
  1408.                 $ldparam date("Y-m-t"strtotime($fdparam)). ' 23:59:59';
  1409.             }
  1410.             $rcl =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam2);
  1411.             if( $rcl ){
  1412.                 $results['classique'][] = $rcl[0];
  1413.             }else{
  1414.                 $results['classique'][] = ['number' => 0'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
  1415.             }
  1416.             $rsec =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam3);
  1417.             if( $rsec ){
  1418.                 $results['securite'][] = $rsec[0];
  1419.             }else{
  1420.                 $results['securite'][] = ['number' => 0'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
  1421.             }
  1422.             $rseren =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam4);
  1423.             if ( $rseren) {
  1424.                 $results['serenite'][] = $rseren[0];
  1425.             } else {
  1426.                 $results['serenite'][] = ['number' => 0'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
  1427.             }
  1428.             $plein =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam5);
  1429.             if ( $plein) {
  1430.                 $results['plenitude'][] = $plein[0];
  1431.             } else {
  1432.                 $results['plenitude'][] = ['number' => 0'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
  1433.             }
  1434.             $iterations++;
  1435.         }
  1436.         /*
  1437.         $results['classique'] = $classiqueT;
  1438.         $results['securite'] = $securiteT;
  1439.         $results['serenite'] = $sereniteT;
  1440.         $results['plenitude'] = $plenitudeT;
  1441.         */
  1442.         $serializer SerializerBuilder::create()->build();
  1443.         $jsonStats $serializer->serialize($results'json');
  1444.         return new JsonResponse($jsonStats);
  1445.     }
  1446.     /**
  1447.      * json requette obtention détail de contrat remporté dans les Stats Général
  1448.      *
  1449.      * @param Request $request
  1450.      * @Route("/stats/offrevendupercentage", name="stats_offrevendupercentage", options={"expose"=true})
  1451.      * @Method({"GET","POST"})
  1452.      * @return JsonResponse
  1453.      */
  1454.     public function statsoffrevenduPercentageAction(Request $request)
  1455.     {
  1456.         $em =  $this->getDoctrine->getManager();
  1457.         $firstDate $request->query->get('first_date');
  1458.         $lastDate $request->query->get('last_date');
  1459.         $months $this->getDatesBetweenJustMonth($firstDate$lastDate);
  1460.         $datas = [];
  1461.         foreach ($months as $key1 => $month) {
  1462.             $sql "SELECT * FROM app.lots_geres_historic as lgh
  1463.                     INNER JOIN app.contract as c on c.id = lgh.contractId
  1464.                     INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
  1465.                     INNER JOIN app.offre_tarif as ot on ot.id = coh.offreId
  1466.                     WHERE lgh.entryDate < :date2  and lgh.entryDate > :date1
  1467.                     AND coh.startDate BETWEEN :date1 and :date2  ";
  1468.             $stmt $em->getConnection()->prepare($sql);
  1469.             $datemonth = new \DateTime($month.'-01');
  1470.             $param1 $datemonth->format('Y-m-d');
  1471.             $param2 $datemonth->format('Y-m-t').' 23:59:59';
  1472.             $stmt->bindParam(':date1'$param1);
  1473.             $stmt->bindParam(':date2'$param2);
  1474.             $resultSet $stmt->executeQuery();
  1475.             $lghs $resultSet->fetchAll();
  1476.             
  1477.             $datas[$key1] = ['plenitude' => 0'securite' => 0'classique' => 0'serenite' => 0'date' => $datemonth->format('Y-m')];
  1478.             foreach ($lghs as $key2 => $lgh) {
  1479.                 switch ($lgh['generic_id']) {
  1480.                     case 2:
  1481.                         $datas[$key1]['classique'] += 1;
  1482.                         break;
  1483.                     case 3:
  1484.                         $datas[$key1]['securite'] += 1;
  1485.                         break;
  1486.                     case 4:
  1487.                         $datas[$key1]['serenite'] += 1;
  1488.                         break;
  1489.                     case 5:
  1490.                         $datas[$key1]['plenitude'] += 1;
  1491.                         break;
  1492.                 }
  1493.             }
  1494.             $datas[$key1]['classique'] = count($lghs) == $datas[$key1]['classique'] / count($lghs) * 100;
  1495.             $datas[$key1]['securite'] = count($lghs) == $datas[$key1]['securite'] / count($lghs) * 100;
  1496.             $datas[$key1]['serenite'] = count($lghs) == $datas[$key1]['serenite'] / count($lghs) * 100;
  1497.             $datas[$key1]['plenitude'] = count($lghs) == $datas[$key1]['plenitude'] / count($lghs) * 100;
  1498.         }
  1499.         $serializer $this->_serializer;
  1500.         $serializedResult $serializer->serialize($datas'json');
  1501.         $response json_decode($serializedResult);
  1502.         return new JsonResponse($response);
  1503.     }
  1504.     /**
  1505.      * json requette obtention répartition instantanée des offres detaillée
  1506.      *
  1507.      * @param Request $request
  1508.      * @Route("/stats/repartitionofrredetaill", name="stats_repartitionofrredetaill", options={"expose"=true})
  1509.      * @Method({"GET","POST"})
  1510.      * @return JsonResponse
  1511.      */
  1512.     public function getRepartitionOfrreDetaillAction(Request $request)
  1513.     {
  1514.         $classique =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(2);
  1515.         $securite =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(3);
  1516.         $serenite =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(4);
  1517.         $plenitude =  $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(5);
  1518.         $results['classique'] = $classique;
  1519.         $results['securite'] = $securite;
  1520.         $results['serenite'] = $serenite;
  1521.         $results['plenitude'] = $plenitude;
  1522.         $serializer SerializerBuilder::create()->build();
  1523.         $jsonStats $serializer->serialize($results'json');
  1524.         return new JsonResponse($jsonStats);
  1525.     }
  1526.     /**
  1527.      * json requette obtention répartition instantanée des Churn
  1528.      *
  1529.      * @param Request $request
  1530.      * @Route("/stats/repartitionchurndetaill", name="stats_repartitionchurndetaill", options={"expose"=true})
  1531.      * @Method({"GET","POST"})
  1532.      * @return JsonResponse
  1533.      */
  1534.     public function getRepartitionChurnDetaillAction(Request $request)
  1535.     {
  1536.         $rais0 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(0);
  1537.         $results['rais0'] = $rais0;
  1538.         $rais1 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(1);
  1539.         $results['rais1'] = $rais1;
  1540.         $rais2 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(2);
  1541.         $results['rais2'] = $rais2;
  1542.         $rais3 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(3);
  1543.         $results['rais3'] = $rais3;
  1544.         $rais4 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(4);
  1545.         $results['rais4'] = $rais4;
  1546.         $rais5 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(5);
  1547.         $results['rais5'] = $rais5;
  1548.         $rais6 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(6);
  1549.         $results['rais6'] = $rais6;
  1550.         $rais7 =  $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(7);
  1551.         $results['rais7'] = $rais7;
  1552.         $serializer SerializerBuilder::create()->build();
  1553.         $jsonStats $serializer->serialize($results'json');
  1554.         return new JsonResponse($jsonStats);
  1555.     }
  1556.     /**
  1557.      * Récupérer le nombre de locataires inscrits par mois
  1558.      *
  1559.      * @param Request $request
  1560.      * @return JsonResponse
  1561.      * @Route("/stats/ByGraphRenterdate", name="stats_graph_renter_date", options={"expose"=true})
  1562.      */
  1563.     public function statsByGraphRenterDateAction(Request $request)
  1564.     {
  1565.         $firstDate $request->query->get('first_date');
  1566.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1567.         $subscriptions =  $this->getDoctrine->getRepository('AppBundle:User')->getTenantRenterByDates($firstDate,$lastDate);
  1568.         $results['subscriptions'] = $subscriptions;
  1569.         $serializer SerializerBuilder::create()->build();
  1570.         $jsonStats $serializer->serialize($results'json');
  1571.         return new JsonResponse($jsonStats);
  1572.     }
  1573.     /**
  1574.      * Récupérer le nombre de propriétaires inscrits par mois
  1575.      *
  1576.      * @param Request $request
  1577.      * @return JsonResponse
  1578.      * @Route("/stats/ByGraphOwnerdate", name="stats_graph_owner_date", options={"expose"=true})
  1579.      */
  1580.     public function statsByGraphOwnerDateAction(Request $request)
  1581.     {
  1582.         $firstDate $request->query->get('first_date');
  1583.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1584.         $subscriptions =  $this->getDoctrine->getRepository('AppBundle:User')->getTenantOwnerByDates($firstDate,$lastDate);
  1585.         $results['subscriptions'] = $subscriptions;
  1586.         $serializer SerializerBuilder::create()->build();
  1587.         $jsonStats $serializer->serialize($results'json');
  1588.         return new JsonResponse($jsonStats);
  1589.     }
  1590.     /**
  1591.      * Récupérer le nombre d'annonces par mois
  1592.      *
  1593.      * @param Request $request
  1594.      * @return JsonResponse
  1595.      * @Route("/stats/flats-by-date", name="stats_flats_by_date", options={"expose"=true})
  1596.      */
  1597.     public function statsFlatsByDateAction(Request $request)
  1598.     {
  1599.         $firstDate $request->query->get('first_date');
  1600.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1601.         $flats =  $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatByDates($firstDate$lastDate$request->query->get('status'));
  1602.         $results['flats'] = $flats;
  1603.         $serializer SerializerBuilder::create()->build();
  1604.         $jsonStats $serializer->serialize($results'json');
  1605.         return new JsonResponse($jsonStats);
  1606.     }
  1607.     /**
  1608.      * Récupérer le nombre d'annonces avec offre payante par mois
  1609.      *
  1610.      * @param Request $request
  1611.      * @return JsonResponse
  1612.      * @Route("/stats/flats-vip-by-date", name="stats_flats_vip_by_date", options={"expose"=true})
  1613.      */
  1614.     public function statsFlatsVipByDateAction(Request $request)
  1615.     {
  1616.         $firstDate $request->query->get('first_date');
  1617.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1618.         $flats =  $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatVipDates($firstDate$lastDate);
  1619.         $results['flats'] = $flats;
  1620.         $serializer SerializerBuilder::create()->build();
  1621.         $jsonStats $serializer->serialize($results'json');
  1622.         return new JsonResponse($jsonStats);
  1623.     }
  1624.     /**
  1625.      * Récupérer le nombre d'annonces, qui ont été publiées et qui ne le sont plus, par mois entre deux dates
  1626.      *
  1627.      * @param Request $request
  1628.      * @return JsonResponse
  1629.      * @Route("/stats/flats-unpublished-by-date", name="stats_flats_unpublished_by_date", options={"expose"=true})
  1630.      */
  1631.     public function statsFlatsUnpublishedByDateAction(Request $request)
  1632.     {
  1633.         $firstDate $request->query->get('first_date');
  1634.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1635.         $flats =  $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatUnpublishedByDates($firstDate$lastDate);
  1636.         $results['flatsu'] = $flats;
  1637.         $serializer SerializerBuilder::create()->build();
  1638.         $jsonStats $serializer->serialize($results'json');
  1639.         return new JsonResponse($jsonStats);
  1640.     }
  1641.     /**
  1642.      * Récupérer le nombre de mandats par mois
  1643.      *
  1644.      * @param Request $request
  1645.      * @return JsonResponse
  1646.      * @Route("/stats/mandates-by-date", name="stats_mandates_by_date", options={"expose"=true})
  1647.      */
  1648.     public function statsMandatesByDateAction(Request $request)
  1649.     {
  1650.         $firstDate $request->query->get('first_date');
  1651.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1652.         $mandates =  $this->getDoctrine->getRepository('AppBundle:Mandate')->countByMonthAndDates($firstDate$lastDate);
  1653.         $results['mandates'] = $mandates;
  1654.         $serializer SerializerBuilder::create()->build();
  1655.         $jsonStats $serializer->serialize($results'json');
  1656.         return new JsonResponse($jsonStats);
  1657.     }
  1658.     /**
  1659.      * Récupérer le nombre de candidatures par mois
  1660.      *
  1661.      * @param Request $request
  1662.      * @return JsonResponse
  1663.      * @Route("/stats/ByCandidatdate", name="stats_candidat_date", options={"expose"=true})
  1664.      */
  1665.     public function statsByCandidatDateAction(Request $request)
  1666.     {
  1667.         $firstDate $request->query->get('first_date');
  1668.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1669.         $candidats =  $this->getDoctrine->getRepository('AppBundle:Application')->getApplicationByDates($firstDate,$lastDate);
  1670.         $results['candidats'] = $candidats;
  1671.         $serializer SerializerBuilder::create()->build();
  1672.         $jsonStats $serializer->serialize($results'json');
  1673.         return new JsonResponse($jsonStats);
  1674.     }
  1675.     /**
  1676.      * Récupérer le nombre de contrats par mois
  1677.      *
  1678.      * @param Request $request
  1679.      * @return JsonResponse
  1680.      * @Route("/stats/ByBauxdate", name="stats_baux_date", options={"expose"=true})
  1681.      */
  1682.     public function statsByBauxDateAction(Request $request)
  1683.     {
  1684.         $firstDate $request->query->get('first_date');
  1685.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1686.         $baux =  $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->getSignedByDates($firstDate,$lastDate);
  1687.         $results['baux'] = $baux;
  1688.         $serializer SerializerBuilder::create()->build();
  1689.         $jsonStats $serializer->serialize($results'json');
  1690.         return new JsonResponse($jsonStats);
  1691.     }
  1692.     /**
  1693.      * Récupérer les nombre de connexion par mois
  1694.      *
  1695.      * @param Request $request
  1696.      * @return JsonResponse
  1697.      * @Route("/stats/ByConnexiondate", name="stats_connexion_date", options={"expose"=true})
  1698.      */
  1699.     public function statsByConnexionDateAction(Request $request)
  1700.     {
  1701.         $firstDate $request->query->get('first_date');
  1702.         $lastDate $request->query->get('last_date'). ' 23:59:59';
  1703.         $connexion =  $this->getDoctrine->getRepository('AppBundle:UserHistoric')->getConnexionByDates($firstDate,$lastDate);
  1704.         $results['connexion'] = $connexion;
  1705.         $serializer SerializerBuilder::create()->build();
  1706.         $jsonStats $serializer->serialize($results'json');
  1707.         return new JsonResponse($jsonStats);
  1708.     }
  1709.     /**
  1710.      * Lister les annonces
  1711.      *
  1712.      * @Route("/flat/listing", name="flatListing")
  1713.      * @return Response
  1714.      */
  1715.     public function flatListingAction()
  1716.     {
  1717.         //$datatable = $this->get('app.datatable.flat');
  1718.         //$datatable->buildDatatable();
  1719.         $datatable $this->dtFactory->create(FlatDatatable::class);
  1720.         $datatable->buildDatatable();
  1721.         return $this->render('Extranet/index.html.twig', array(
  1722.             'datatable' => $datatable,
  1723.         ));
  1724.     }
  1725.     /**
  1726.      * Lister les annonces
  1727.      *
  1728.      * @Route("/flat/listingexport", name="flatListingexport")
  1729.      * @return Response
  1730.      */
  1731.     public function flatexpListingAction()
  1732.     {
  1733.         $datatable $this->get('app.datatable.flatexp');
  1734.         $datatable->buildDatatable();
  1735.         return $this->render('Extranet/multidiffusion.html.twig', array(
  1736.             'datatable' => $datatable,
  1737.         ));
  1738.     }
  1739.     /**
  1740.      * Filtrer les annonces
  1741.      *
  1742.      * @Route("/flat/results", name="flat_results")
  1743.      */
  1744.     public function indexFlatResultsAction()
  1745.     {
  1746.         $datatable $this->dtFactory->create(FlatDatatable::class);
  1747.         $datatable->buildDatatable();
  1748.         $query $this->dtResponse;
  1749.         $query->setDatatable($datatable);
  1750.         $query->getDatatableQueryBuilder();
  1751.         return $query->getResponse();
  1752.         //$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1753.         //return $query->getResponse();
  1754.     }
  1755.     /**
  1756.      * Filtrer les annonces
  1757.      *
  1758.      * @Route("/flat/resultsexp", name="flat_resultsexp")
  1759.      */
  1760.     public function indexFlatResultsexpAction()
  1761.     {
  1762.         $datatable $this->get('app.datatable.flatexp');
  1763.         $datatable->buildDatatable();
  1764.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1765.         return $query->getResponse();
  1766.     }
  1767.     /**
  1768.      * Lister les
  1769.      *
  1770.      * @Route("/glireprisebailbo/listing", name="glireprisebailboardListingbo")
  1771.      * @return Response
  1772.      */
  1773.     public function glireprisebailListingAction()
  1774.     {
  1775.         $datatable $this->dtFactory->create(ReprisBailDatatable::class);
  1776.         //$datatable = $this->get('app.datatable.reprisebail');
  1777.         $datatable->buildDatatable();
  1778.         return $this->render('Extranet/reprisebaillist.html.twig', array(
  1779.             'datatable' => $datatable,
  1780.         ));
  1781.     }
  1782.     /**
  1783.      * Filtrer les
  1784.      *
  1785.      * @Route("/glireprisebailboard/resultsbo", name="glireprisebail_resultsbo")
  1786.      */
  1787.     public function indexglireprisebailResultsAction()
  1788.     {
  1789.         $datatable $this->get('app.datatable.reprisebail');
  1790.         $datatable->buildDatatable();
  1791.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1792.         return $query->getResponse();
  1793.     }
  1794.     /**
  1795.      * Lister les candidatures
  1796.      *
  1797.      * @Route("/applicationboard/listing", name="applicationboardListing")
  1798.      * @return Response
  1799.      */
  1800.     public function applicationboardListingAction()
  1801.     {
  1802.         $datatable $this->get('app.datatable.application');
  1803.         $datatable->buildDatatable();
  1804.         return $this->render('Extranet/application.html.twig', array(
  1805.             'datatable' => $datatable,
  1806.         ));
  1807.     }
  1808.     /**
  1809.      * Filtrer les candidatures
  1810.      *
  1811.      * @Route("/applicationboard/results", name="applicationboard_results")
  1812.      */
  1813.     public function indexApplicationboardResultsAction()
  1814.     {
  1815.         $datatable $this->get('app.datatable.application');
  1816.         $datatable->buildDatatable();
  1817.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1818.         return $query->getResponse();
  1819.     }
  1820.     /**
  1821.      * Lister les utilisateurs
  1822.      *
  1823.      * @Route("/user/listing", name="userListing")
  1824.      * @return Response
  1825.      */
  1826.     public function userListingAction(Request $request)
  1827.     {
  1828.         $isAjax $request->isXmlHttpRequest();
  1829.         //$datatable = $this->get('app.datatable.user');
  1830.         $datatable $this->dtFactory->create(UserDatatable::class);
  1831.         $datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
  1832.         if ($isAjax) {
  1833.         $responseService $this->dtResponse;
  1834.         $responseService->setDatatable($datatable);
  1835.         $responseService->getDatatableQueryBuilder();
  1836.         return $responseService->getResponse();
  1837.         }
  1838.         return $this->render('Extranet/users.html.twig', array(
  1839.             'datatable' => $datatable,
  1840.         ));
  1841.     }
  1842.     /**
  1843.      * Filtrer les utilisateurs
  1844.      *
  1845.      * @Route("/user/results", name="user_results")
  1846.      */
  1847.     public function indexResultsAction()
  1848.     {
  1849.         $datatable $this->dtFactory->create(UserDatatable::class);
  1850.         $datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
  1851.         $query $this->dtResponse;
  1852.         $query->setDatatable($datatable);
  1853.         $query->getDatatableQueryBuilder();
  1854.         return $query->getResponse();
  1855.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1856.         $function = function($qb)
  1857.         {
  1858.             $qb->andWhere("user.name <> :name");
  1859.             $qb->setParameter('name''proprietaire');
  1860.         };
  1861.         $query->addWhereAll($function);
  1862.         return $query->getResponse();
  1863.     }
  1864.     /**
  1865.      * Lister les lots en vacances locative
  1866.      *
  1867.      * @Route("/listlotsenvacances", name="listlotsenvacances")
  1868.      * @return Response
  1869.      */
  1870.     public function listlotsenvacancesAction()
  1871.     {
  1872.         $data = [];
  1873.         $namedb $this->getParameter('dbreqpdo');
  1874.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  1875.         $sthd $bdd->prepare("SELECT c.id as 'contrat', prop.name as 'pnom',prop.firstname as 'pprenom',
  1876. loc.name as 'lnom',loc.firstname as 'lprenom',
  1877. CONCAT(\"https://app.wizi.eu/contract/edit/\",c.id) AS lien
  1878. FROM app.lots_geres as l
  1879.                         INNER JOIN app.contract as c on c.id = l.contract
  1880.                         INNER JOIN app.application as a on a.id = c.application_id
  1881.                         INNER JOIN app.flat as fl on fl.id = a.flat
  1882.                         INNER JOIN app.user as prop on prop.id = fl.owned_by_id
  1883.                         INNER JOIN app.user as loc on loc.id = a.user
  1884.                         WHERE c.status = 4 and l.flat not in (select flat from app.churn)
  1885.                         and l.flat not in (
  1886.                             select fl.id from contract as c
  1887.                             INNER JOIN app.application as a on a.id = c.application_id
  1888.                             INNER JOIN app.flat as fl on fl.id = a.flat
  1889.                             where c.status = 2
  1890.                         );");
  1891.         $sthd->execute();
  1892.         $data $sthd->fetchAll(\PDO::FETCH_ASSOC);
  1893.         return $this->render('Extranet/vacloc.html.twig', array(
  1894.             'data' => $data,
  1895.         ));
  1896.     }
  1897.     /*
  1898.     -------------
  1899.     */
  1900.     /**
  1901.      * Lister les utilisateurs
  1902.      *
  1903.      * @Route("/userlistingreview", name="userListingreview")
  1904.      * @return Response
  1905.      */
  1906.     public function userListingreviewAction()
  1907.     {
  1908.         $datatable $this->get('app.datatable.userreview');
  1909.         $datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
  1910.         return $this->render('Extranet/usersreview.html.twig', array(
  1911.             'datatable' => $datatable,
  1912.         ));
  1913.     }
  1914.     /**
  1915.      * Filtrer les utilisateurs
  1916.      *
  1917.      * @Route("/userresultsreview", name="user_resultsreview")
  1918.      */
  1919.     public function indexResultsreviewAction()
  1920.     {
  1921.         $datatable $this->get('app.datatable.userreview');
  1922.         $datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
  1923.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  1924.         $function = function($qb)
  1925.         {
  1926.             $qb->andWhere("user.name <> :name");
  1927.             $qb->setParameter('name''proprietaire');
  1928.             $qb->andWhere("user.suiviStatus = :suivistat");
  1929.             $qb->setParameter('suivistat'99);
  1930.             $qb->andWhere("user.suivipar = :suivipar");
  1931.             $qb->setParameter('suivipar'$this->getUser()->getId());
  1932.         };
  1933.         $query->addWhereAll($function);
  1934.         return $query->getResponse();
  1935.     }
  1936.     /**
  1937.      * mettre des utilisateur en statut portefeuille
  1938.      *
  1939.      * @Route("/userreviewdispatch/{number}", name="userreviewdispatch", options={"expose"=true})
  1940.      * @Method({"GET","POST"})
  1941.      * @return Response
  1942.      */
  1943.     public function userReviewDispachAction(Request $request$number)
  1944.     {
  1945.         // jo
  1946.         $sql "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
  1947.         $namedb $this->getParameter('dbreqpdo');
  1948.         $conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  1949.         $stmt1 $conn->prepare($sql);
  1950.         $stmt1->execute();
  1951.         $result $stmt1->fetchAll(\PDO::FETCH_ASSOC);
  1952.         foreach ($result as $s){
  1953.             $sqlupdate "update app.user set suivistatus = 99, suivipar = 29896 where id = ".$s['id'];
  1954.             $stmt2 $conn->prepare($sqlupdate);
  1955.             $stmt2->execute();
  1956.         }
  1957.         // sandra
  1958.         $sql "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
  1959.         $namedb $this->getParameter('dbreqpdo');
  1960.         $conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  1961.         $stmt1 $conn->prepare($sql);
  1962.         $stmt1->execute();
  1963.         $result $stmt1->fetchAll(\PDO::FETCH_ASSOC);
  1964.         foreach ($result as $s){
  1965.             $sqlupdate "update app.user set suivistatus = 99, suivipar = 81354 where id = ".$s['id'];
  1966.             $stmt2 $conn->prepare($sqlupdate);
  1967.             $stmt2->execute();
  1968.         }
  1969.         // Hadrien
  1970.         $sql "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
  1971.         $namedb $this->getParameter('dbreqpdo');
  1972.         $conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  1973.         $stmt1 $conn->prepare($sql);
  1974.         $stmt1->execute();
  1975.         $result $stmt1->fetchAll(\PDO::FETCH_ASSOC);
  1976.         foreach ($result as $s){
  1977.             $sqlupdate "update app.user set suivistatus = 99, suivipar = 120144 where id = ".$s['id'];
  1978.             $stmt2 $conn->prepare($sqlupdate);
  1979.             $stmt2->execute();
  1980.         }
  1981.         return new JsonResponse('ok');
  1982.     }
  1983.     /**
  1984.      * compter les leads a traiter revue de portefeuil
  1985.      *
  1986.      * @param Request $request
  1987.      * @return JsonResponse
  1988.      * @Route("/countmyleadreview", name="countmyleadreview", options={"expose"=true})
  1989.      * @Method({"GET","POST"})
  1990.      */
  1991.     public function countmyleadreviewAction()
  1992.     {
  1993.         $namedb $this->getParameter('dbreqpdo');
  1994.         $udb $this->getParameter('userreqpdo');
  1995. $pdb $this->getParameter('passreqpdo');
  1996. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  1997.         $comuser $this->getUser();
  1998.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  1999.         $sql "SELECT count(*) as res
  2000. FROM app.user as u ";
  2001.         $condition ' where (suivipar LIKE "'.$suivipar.'" and suivistatus = 99  )  ';
  2002.         $sthd $bdd->prepare($sql.$condition);
  2003.         $sthd->execute();
  2004.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  2005.         return New JsonResponse($max); //
  2006.     }
  2007.     /**
  2008.      * compter les leads review dans team stat
  2009.      *
  2010.      * @param Request $request
  2011.      * @return JsonResponse
  2012.      * @Route("/countmyleadreviewstat/{id}", name="countmyleadreviewstat", options={"expose"=true})
  2013.      * @Method({"GET","POST"})
  2014.      */
  2015.     public function countmyleadreviewstatAction($id)
  2016.     {
  2017.         $namedb $this->getParameter('dbreqpdo');
  2018.         $udb $this->getParameter('userreqpdo');
  2019. $pdb $this->getParameter('passreqpdo');
  2020. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  2021.         $comuser $this->getUser();
  2022.         $suivipar $id;
  2023.         $sql "SELECT count(*) as res
  2024. FROM app.user as u ";
  2025.         $condition ' where (suivipar LIKE "'.$suivipar.'" and suivistatus = 99  )  ';
  2026.         $sthd $bdd->prepare($sql.$condition);
  2027.         $sthd->execute();
  2028.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  2029.         return New JsonResponse($max); //
  2030.     }
  2031.     /*
  2032.     -------------
  2033.     */
  2034.     /**
  2035.      * Créer un utilisateur
  2036.      *
  2037.      * @Route("/user/add", name="addUser", options={"expose"=true})
  2038.      * @param Request $request
  2039.      * @return Response
  2040.      */
  2041.     public function addUserAction(Request $request)
  2042.     {
  2043.         $user = new User();
  2044.         $form $this->createForm('App\AppBundle\Form\UserType'$user, [
  2045.             'renter_status' => $this->getParameter('renter_status'),
  2046.             'owner_status' => $this->getParameter('owner_status'),
  2047.             'initial_mode' => $this->getParameter('user_status')
  2048.         ]);
  2049.         $form->handleRequest($request);
  2050.         if ($form->isSubmitted() && $form->isValid()) {
  2051.             $newUser $form->getData();
  2052.             $em =  $this->getDoctrine->getManager();
  2053.             $em->persist($newUser);
  2054.             $em->flush();
  2055.             return $this->redirectToRoute('userListing');
  2056.         }
  2057.         return $this->render('Extranet/Security/addUser.html.twig', array(
  2058.             'form' => $form->createView(),
  2059.         ));
  2060.     }
  2061.     /**
  2062.      * Créer une annonce
  2063.      *
  2064.      * @Route("/flat/add", name="addFlat", options={"expose"=true})
  2065.      * @param Request $request
  2066.      * @return Response
  2067.      */
  2068.     public function addFlatAction(Request $request)
  2069.     {
  2070.         $flat = new Flat();
  2071.         $form $this->createForm('App\AppBundle\Form\FlatType'$flat,['flat_status' => $this->getParameter('flat_status')]);
  2072.         $form->handleRequest($request);
  2073.         if ($form->isSubmitted() && $form->isValid()) {
  2074.             $newFlat $form->getData();
  2075.             $em =  $this->getDoctrine->getManager();
  2076.             $em->persist($newFlat);
  2077.             $em->flush();
  2078.             return $this->redirectToRoute('flatListing');
  2079.         }
  2080.         return $this->render('Extranet/add.html.twig', array(
  2081.             'form' => $form->createView(),
  2082.         ));
  2083.     }
  2084.     /**
  2085.      * Duppliquer une annonce
  2086.      *
  2087.      * @Route("/flat/duplicate/{id}", name="duplicateFlat", options={"expoe"=true})
  2088.      * @Method({"GET","POST"})
  2089.      * @param Request $request
  2090.      * @param integer $id
  2091.      * @return $thiss
  2092.      */
  2093.     public function duplicateFlatAction(Request $request$id)
  2094.     {
  2095.         $em =  $this->getDoctrine->getManager();
  2096.         $flatsManager $em->getRepository('App\AppBundle\Entity\Flat');
  2097.         $flat $flatsManager->find($id);
  2098.         //$flat = new Flat();
  2099.         $newflat = new Flat();
  2100.         $newflat->setAdress($flat->getAdress());
  2101.         $newflat->setBedrooms($flat->getBedrooms());
  2102.         $newflat->setCanMultidif($flat->getCanMultidif());
  2103.         $newflat->setCharges($flat->getCharges());
  2104.         $newflat->setOffre($flat->getOffre());
  2105.         $newflat->setOffreVendue($flat->getOffreVendue());
  2106.         $newflat->setOffreContract($flat->getOffreContract());
  2107.         $newflat->setScoreSl($flat->getScoreSl());
  2108.         $newflat->setScoreLbc($flat->getScoreLbc());
  2109.         $newflat->setScoreGr($flat->getScoreGr());
  2110.         $newflat->setScoreFb($flat->getScoreFb());
  2111.         $newflat->setEvermulti($flat->getEvermulti());
  2112.         $newflat->setIsSci($flat->getIsSci());
  2113.         $newflat->setSiren($flat->getSiren());
  2114.         $newflat->setCompanyName($flat->getCompanyName());
  2115.         $newflat->setCompanyCountry($flat->getCompanyCountry());
  2116.         $newflat->setCompanyCity($flat->getCompanyCity());
  2117.         $newflat->setCompanyAddress($flat->getCompanyAddress());
  2118.         $newflat->setCompanyPostalCode($flat->getCompanyPostalCode());
  2119.         $newflat->setMeuble($flat->getMeuble());
  2120.         $newflat->setInsurance($flat->getInsurance());
  2121.         $newflat->setOwnedBy($flat->getOwnedBy());
  2122.         $newflat->setDescription($flat->getDescription());
  2123.         $newflat->setTitle($flat->getTitle().' (COPIE)');
  2124.         $newflat->setLogementType($flat->getLogementType());
  2125.         $newflat->setSurface($flat->getSurface());
  2126.         $newflat->setPrice($flat->getPrice());
  2127.         $newflat->setCharges($flat->getCharges());
  2128.         $newflat->setFloors($flat->getFloors());
  2129.         $newflat->setBedrooms($flat->getBedrooms());
  2130.         $newflat->setLongitude($flat->getLongitude());
  2131.         $newflat->setLatitude($flat->getLatitude());
  2132.         $newflat->setCity($flat->getCity());
  2133.         $newflat->setCountry($flat->getCountry());
  2134.         $newflat->setAdress($flat->getAdress());
  2135.         $newflat->setPostalCode($flat->getPostalCode());
  2136.         $newflat->setStatus($flat->getStatus());
  2137.         $newflat->setDpe($flat->getDpe());
  2138.         $newflat->setGes($flat->getGes());
  2139.         $newflat->setCurrencyUnit($flat->getCurrencyUnit());
  2140.         $fd $flat->getFullDescription();
  2141.         // full description
  2142.         $fulldescription = new FlatDescription();
  2143.         $fulldescription->setType($fd->getType());
  2144.         $fulldescription->setNiceView($fd->getNiceView());
  2145.         $fulldescription->setBalcony($fd->getBalcony());
  2146.         $fulldescription->setTerrace($fd->getTerrace());
  2147.         $fulldescription->setElevator($fd->getElevator());
  2148.         $fulldescription->setOpticalFiber($fd->getOpticalFiber());
  2149.         $fulldescription->setParking($fd->getParking());
  2150.         $fulldescription->setAirConditioner($fd->getAirConditioner());
  2151.         $fulldescription->setGarden($fd->getGarden());
  2152.         $fulldescription->setGarage($fd->getGarage());
  2153.         $em->persist($fulldescription);
  2154.         $em->flush();
  2155.         $newflat->setFullDescription($fulldescription);
  2156.         $em->persist($newflat);
  2157.         $em->flush();
  2158.         $docs $flat->getDocuments();
  2159.         foreach ($docs as $doc){
  2160.             $newflat->addDocument($doc);
  2161.         }
  2162.         $em->persist($newflat);
  2163.         $em->flush();
  2164.         // plusieurs propriétaires
  2165.         $flprops $flat->getFlatprops();
  2166.         foreach ($flprops as $fp){
  2167.             $newflprop = new FlatProp();
  2168.             $newflprop->setAdress($fp->getAdress());
  2169.             $newflprop->setBio($fp->getBio());
  2170.             $newflprop->setCity($fp->getCity());
  2171.             $newflprop->setCountry($fp->getCountry());
  2172.             $newflprop->setEmail($fp->getEmail());
  2173.             $newflprop->setCreatedAt($fp->getCreatedAt());
  2174.             $newflprop->setFirstname($fp->getFirstname());
  2175.             $newflprop->setMobilePhone($fp->getMobiePhone());
  2176.             $newflprop->setName($fp->getName());
  2177.             $newflprop->setPostalCode($fp->getPostalCode());
  2178.             $newflprop->setFlatRef($newflat);
  2179.             $em->persist($newflprop);
  2180.             $em->flush();
  2181.         }
  2182.         // return new Response('ok');
  2183.         $newid $newflat->getId();
  2184.         return $this->redirect$this->generateUrl('editFlat', array('id' => $newid)) );
  2185.     }
  2186.     /**
  2187.      * Modifier une annonce
  2188.      *
  2189.      * @Route("/flat/edit/{id}", name="editFlat", options={"expose"=true})
  2190.      * @param Request $request
  2191.      * @param integer $id
  2192.      * @return $this
  2193.      */
  2194.     public function editFlatAction(Request $request$id)
  2195.     {
  2196.         $em =  $this->getDoctrine;
  2197.         $flatsManager $em->getRepository('App\AppBundle\Entity\Flat');
  2198.         $flat $flatsManager->find($id);
  2199.         $initialFlat = clone($flat);
  2200.         $recompenses $em->getRepository('App\AppBundle\Entity\Recompense')->findAll();
  2201.         $form $this->createForm('App\AppBundle\Form\FlatType'$flat,['flat_status' => $this->getParameter('flat_status')]);
  2202.         $form->handleRequest($request);
  2203.         $deleteForm $this->createFlatDeleteForm($id);
  2204.         if ($form->isSubmitted() && $form->isValid()) {
  2205.             $newFlat $form->getData();
  2206.             $em =  $this->getDoctrine->getManager();
  2207.             $em->persist($newFlat);
  2208.             $em->flush();
  2209. //            file_put_contents('./debugnotifadmin.txt', '$flat->getStatus()'.$initialFlat->getStatus().PHP_EOL, FILE_APPEND);
  2210. //            file_put_contents('./debugnotifadmin.txt', '$newFlat->getStatus()'.$newFlat->getStatus().PHP_EOL, FILE_APPEND);
  2211.             /*
  2212.              * gestion des notifs de publications
  2213.              */
  2214.             if ($initialFlat->getStatus() == && $newFlat->getStatus() == 2){
  2215.                 $datePublication = new \DateTime();
  2216.                 $newFlat->setPublishAt($datePublication);
  2217.                 $userManager $em->getRepository('App\AppBundle\Entity\User');
  2218.                 $usernotif $userManager->find($newFlat->getOwnedBy());
  2219.                 $description "Annonce ".$newFlat->getId()." publiée par Wizi";
  2220.                 // adminnotif 26
  2221.                 $notifier $this->get('app.notifparse');
  2222.                 $notifier->doAll(  26'Flat',$newFlat->getId(),'notif');
  2223.                 /*
  2224.                 $notification = new Notification();
  2225.                 $notification->setEmplacement('notif');
  2226.                 $notification->setUser($usernotif);
  2227.                 $notification->setDescription($description);
  2228.                 $notification->setIcon('far fa-newspaper icon');
  2229.                 $notification->setColor('#717171');
  2230.                 $notification->setLink('/#/app/search');
  2231.                 $em->persist($notification);
  2232.                 $em->flush();
  2233.                 */
  2234.             }
  2235.             /*
  2236.              * gestion des notifs de depublications
  2237.              */
  2238.             if ($initialFlat->getStatus() == && $newFlat->getStatus() == 1){
  2239.                 $datePublication = new \DateTime();
  2240.                 $newFlat->setPublishAt($datePublication);
  2241.                 $userManager $em->getRepository('App\AppBundle\Entity\User');
  2242.                 $usernotif $userManager->find($newFlat->getOwnedBy());
  2243.                 $description "Annonce ".$newFlat->getId()." dépubliée par Wizi";
  2244.                 // adminnotif 27
  2245.                 $notifier $this->get('app.notifparse');
  2246.                 $notifier->doAll(  27'Flat',$newFlat->getId(),'notif');
  2247.                 /*
  2248.                 $notification = new Notification();
  2249.                 $notification->setEmplacement('notif');
  2250.                 $notification->setUser($usernotif);
  2251.                 $notification->setDescription($description);
  2252.                 $notification->setIcon('far fa-newspaper icon');
  2253.                 $notification->setColor('#717171');
  2254.                 $notification->setLink('/#/app/search');
  2255.                 $em->persist($notification);
  2256.                 */
  2257.                 if($flat->getApplications()){
  2258.                     foreach ($flat->getApplications() as $application){
  2259.                         if($application->getStatus() != 3){
  2260.                             // desactivavion des refus auto de candidature lors de dépublications annonces
  2261.                             // $application->setStatus(3);
  2262.                             // $notification = new Notification();
  2263.                             // $notification->setEmplacement('notif');
  2264.                             // $notification->setUser($application->getUser());
  2265.                             // $notification->setDescription('Annonce '.$flat->getId().' : '.$flat->getOwnedBy()->getFirstname().' '.$flat->getOwnedBy()->getName().' a refusé votre candidature');
  2266.                             // $notification->setColor('#e74c3c');
  2267.                             // $notification->setIcon('far fa-sad-tear icon');
  2268.                             // $em->persist($notification);
  2269.                             // $em->persist($application);
  2270.                         }
  2271.                     }
  2272.                 }
  2273.                 $em->flush();
  2274.             }
  2275.             return $this->redirectToRoute('flatListing');
  2276.         }
  2277.         $em =  $this->getDoctrine;
  2278.         $flatsManager $em->getRepository('App\AppBundle\Entity\FlatHistoric');
  2279.         $applyManager $em->getRepository('App\AppBundle\Entity\Application');
  2280.         $flatHistorics $flatsManager->findBy(['flat' => $flat],['id'=>'DESC']);
  2281.         $flatAppls $applyManager->findBy(['flat' => $flat],['id'=>'DESC']);
  2282.         /* regarder l'éxistance de contrats */
  2283.         $arraycontrats = [];
  2284.         foreach ($flatAppls as $flatAppl) {
  2285.             $c $flatAppl->getContract();
  2286.             if($c != null && $c->getStatus() == 2){
  2287.                 $arraycontrats[]= $c;
  2288.             }
  2289.         }
  2290.         $flatsVideos $em->getRepository('App\AppBundle\Entity\VideoTask')
  2291.             ->findBy(['objectName' => 'Flat','objectId' => $flat->getId()],['id'=>'DESC']);
  2292.         $nbvideo 0;
  2293.         if (count($flatsVideos) == 1) {
  2294.             $nbvideo 1;
  2295.         }
  2296.         /*le candidats seloger non inscrits */
  2297.         $electedfl $id;
  2298.         $res = [];
  2299.         $namedb $this->getParameter('dbreqpdo');
  2300.         $bdd = new \PDO('mysql:host=localhost;dbname=app;charset=utf8''root''ahv2Ohchaik0');
  2301.         $bddSchortlink = new \PDO('mysql:host=localhost;dbname=wzishortlink;charset=utf8''root''ahv2Ohchaik0');
  2302.         $sql "SELECT mailUser,appliDate,tel,flatUrl,idfl FROM app.multidif_user 
  2303.                 where 
  2304.                 multidif_user.idfl = ".$electedfl." AND
  2305.                 multidif_user.tel not in (select username from app.user)";
  2306.         $sthd2 $bdd->prepare($sql);
  2307.         $sthd2->execute();
  2308.         $users $sthd2->fetchAll(\PDO::FETCH_ASSOC);
  2309.         $res $users;
  2310.         /*le candidats seloger n              on inscrits */
  2311.         return $this->render('Extranet/add.html.twig', array(
  2312.             'form' => $form->createView(),
  2313.             'flat' => $flat,
  2314.             'flatHistorics' => $flatHistorics,
  2315.             //'flatHistorics' => array(),
  2316.             'flatAppls' => $flatAppls,
  2317.             'deleteForm' => $deleteForm->createView(),
  2318.             'recompenses' => $recompenses,
  2319.             'nbvideo' => $nbvideo,
  2320.             'selogeruser'=> $res,
  2321.             'contratsactif' => $arraycontrats
  2322.         ));
  2323.     }
  2324.     /**
  2325.      * Récupérer la dropzone des images d'une annonce
  2326.      * @Route("/flat/get-documents-content/{id}", name="flat_get_documents_content", options={"expose"=true})
  2327.      * @Method("GET")
  2328.      *
  2329.      * @param $id
  2330.      * @return \Symfony\Component\HttpFoundation\Response
  2331.      */
  2332.     public function getDocumentsContentAction($id)
  2333.     {
  2334.         return $this->render(':Extranet/Flat:_documents_content.html.twig', [
  2335.             'flatId' => $id,
  2336.         ]);
  2337.     }
  2338.     /**
  2339.      * Lister les images d'une annonce
  2340.      *
  2341.      * @Route("/flat/get-documents-data/{id}", name="flat_get_documents_data")
  2342.      * @Method("GET")
  2343.      *
  2344.      * @param $id
  2345.      * @return JsonResponse
  2346.      */
  2347.     public function getDocumentsDataAction($id)
  2348.     {
  2349.         $em =  $this->getDoctrine->getManager();
  2350.         $flat $em->getRepository('AppBundle:Flat')->find($id);
  2351.         $documents = [];
  2352.         foreach ($flat->getDocuments() as $document) {
  2353.             if ($document->getCategory() == 'full_picture') {
  2354.                 $documents[] = $document;
  2355.             }
  2356.         }
  2357.         $serializer $this->_serializer;
  2358.         $serializedDocuments $serializer->serialize($documents'json');
  2359.         return new JsonResponse($serializedDocuments);
  2360.     }
  2361.     /**
  2362.      * Modifier un utilisateur
  2363.      *
  2364.      * @Route("/user/edit/{id}", name="editUser", options={"expose"=true})
  2365.      * @param Request $request
  2366.      * @param integer $id
  2367.      * @return $this
  2368.      */
  2369.     public function editUserAction(Request $request$id)
  2370.     {
  2371.         $em =  $this->getDoctrine;
  2372.         $usersManager $em->getRepository('App\AppBundle\Entity\User');
  2373.         $recompenses $em->getRepository('App\AppBundle\Entity\Recompense')->findAll();
  2374.         $user $usersManager->find($id);
  2375.         $sms 'undefined';
  2376.         $email 'undefined';
  2377.         $push 'undefined';
  2378.         /*
  2379.          * rgpd
  2380.          */
  2381.         $repositoryone $em->getRepository('AppBundle:UserRgpdAutorisation');
  2382.         $repositorytwo $em->getRepository('AppBundle:RgpdAutorisation');
  2383.         $rgpdautorisation $repositorytwo->findAll();
  2384.         $userrgpdautorisations $repositoryone->findByUser($user);
  2385.         $tab = [];
  2386.         $i 0;
  2387.         foreach ($rgpdautorisation as $a){
  2388.             foreach ($userrgpdautorisations as $r){
  2389.                 if($r->getCodemessagesource() == $a->getCodemessage()){
  2390.                     if($r->getCodemessagesource() == 'sms_autorisation') {
  2391.                         $sms $r->getSwiped();
  2392.                     }
  2393.                     if($r->getCodemessagesource() == 'push_autorisation') {
  2394.                         $push $r->getSwiped();
  2395.                     }
  2396.                     if($r->getCodemessagesource() == 'email_autorisation') {
  2397.                         $email $r->getSwiped();
  2398.                     }
  2399.                     $tab[$i] = $r;
  2400.                 }
  2401.             }
  2402.             $i++;
  2403.         }
  2404.         /*
  2405.          * fin rgpd
  2406.          */
  2407.         $form $this->createForm('App\AppBundle\Form\UserBoType'$user, ['updated' => true'renter_status' => $this->getParameter('renter_status'), 'owner_status' => $this->getParameter('owner_status'), 'initial_mode' => $this->getParameter('user_status')] );
  2408.         $form->handleRequest($request);
  2409.         if ($form->isSubmitted() && $form->isValid()) {
  2410.             $newUser $form->getData();
  2411.             $em =  $this->getDoctrine->getManager();
  2412.             if($user->isEnabled() && !$newUser->isEnabled()){
  2413.                 // adminnotif 28
  2414.                 $notifier $this->get('app.notifparse');
  2415.                 $notifier->doAll(  28'User',$user->getId(),'notif');
  2416.                 /*
  2417.                 $notification = new Notification();
  2418.                 $notification->setEmplacement('notif');
  2419.                 $notification->setUser($user);
  2420.                 $notification->setDescription('Wizi a désactivé le compte de "'.$newUser->getFirstname().' '.$newUser->getName().'".');
  2421.                 $notification->setIcon('far fa-times-square icon');
  2422.                 $notification->setColor('#e74c3c');
  2423.                 $em->persist($notification);
  2424.                 */
  2425.                 $variables '{"firstname": "' $user->getFirstname() . '"}';
  2426.                 $this->get('app.mailjet')->sendMailjet(480160$user->getEmail(), $variables'Votre compte a été désactivé');
  2427.                 if($user->getApplications()){
  2428.                     foreach ($user->getApplications() as $application){
  2429.                         $application->setStatus(3);
  2430.                         $application->setRemoved(true);
  2431.                         $em->persist($application);
  2432.                         // adminnotif 29
  2433.                         $notifier $this->get('app.notifparse');
  2434.                         $notifier->doAll(  29'Application',$application->getId(),'notif');
  2435.                         /*
  2436.                         $notification = new Notification();
  2437.                         $notification->setEmplacement('notif');
  2438.                         $notification->setUser($application->getFlat()->getOwnedBy());
  2439.                         $notification->setDescription('Annonce '.$application->getFlat()->getId().' : '.$user->getFirstname().' '.$user->getName().'" a retiré sa candidature');
  2440.                         $notification->setIcon('far fa-times-square icon');
  2441.                         $em->persist($notification);
  2442.                         */
  2443.                     }
  2444.                     $em->flush();
  2445.                 }
  2446.                 if($user->getFlats()){
  2447.                     foreach ($user->getFlats() as $flat){
  2448.                         $flat->setStatus(1);
  2449.                         // adminnotif 30
  2450.                         $notifier $this->get('app.notifparse');
  2451.                         $notifier->doAll(  30'Flat',$flat->getId(),'notif');
  2452.                         /*
  2453.                         $notification = new Notification();
  2454.                         $notification->setEmplacement('notif');
  2455.                         $notification->setUser($user);
  2456.                         $notification->setDescription('Annonce '.$flat->getId().' : dépubliée');
  2457.                         $notification->setIcon('far fa-newspaper icon');
  2458.                         $notification->setColor('#717171');
  2459.                         $em->persist($notification);
  2460.                         */
  2461.                         foreach ($flat->getApplications() as $application){
  2462.                             $application->setStatus(3);
  2463.                             $em->persist($application);
  2464.                             // adminnotif 31
  2465.                             $notifier $this->get('app.notifparse');
  2466.                             $notifier->doAll(  31'Application',$application->getId(),'notif');
  2467.                             /*
  2468.                             $notification = new Notification();
  2469.                             $notification->setEmplacement('notif');
  2470.                             $notification->setUser($application->getUser());
  2471.                             $notification->setDescription('Annonce '.$application->getFlat()->getId().' : '.$user->getFirstname().' '.$user->getName().'" a refusé votre candidature');
  2472.                             $notification->setColor('#e74c3c');
  2473.                             $notification->setIcon('far fa-sad-tear icon');
  2474.                             $em->persist($notification);
  2475.                             */
  2476.                         }
  2477.                         $em->flush();
  2478.                     }
  2479.                 }
  2480.             }
  2481.             $em->persist($newUser);
  2482.             $em->flush();
  2483.             // return $this->redirectToRoute('userListing');
  2484.         }
  2485.         $em =  $this->getDoctrine;
  2486.         $usersManager $em->getRepository('App\AppBundle\Entity\UserHistoric');
  2487.         $userHistorics $usersManager->findBy(['modifiedUser' => $user'action' => null],['id'=>'DESC']);
  2488.         /**
  2489.         recherche aircall sur user
  2490.          */
  2491.         $usertel $user->getMobilePhone();
  2492.         $usertelwithoutspace str_replace ' ' '' $usertel );
  2493.         $telWttire str_replace '-' '' $usertelwithoutspace );
  2494.         $myphonelib \libphonenumber\PhoneNumberUtil::getInstance();
  2495.         try {
  2496.             $thistestlibph $myphonelib->parse($telWttirePhoneNumberUtil::UNKNOWN_REGION);
  2497.         } catch(\Exception $e){
  2498.         }
  2499. //$thistestlibph = $this->get('libphonenumber.phone_number_util')->parse($telWttire, PhoneNumberUtil::UNKNOWN_REGION);
  2500.         if($telWttire[0] != '+'){
  2501.             $formatednumber '+33 '.$telWttire[1].' '.$telWttire[2].$telWttire[3].' '.$telWttire[4].$telWttire[5].' '.$telWttire[6].$telWttire[7].' '.$telWttire[8].$telWttire[9];
  2502.         }
  2503.         elseif($telWttire[0].$telWttire[1].$telWttire[2] == '+33')
  2504.         {
  2505.             $formatednumber $telWttire[0].$telWttire[1].$telWttire[2].$telWttire[3].' '.$telWttire[4].$telWttire[5].' '.$telWttire[6].$telWttire[7].' '.$telWttire[8].$telWttire[9].' '.$telWttire[10].$telWttire[11];
  2506.         }
  2507.         elseif($telWttire[0].$telWttire[1].$telWttire[2] == '+32')
  2508.         {
  2509.             $formatednumber $telWttire[0].$telWttire[1].$telWttire[2].' '.$telWttire[3].$telWttire[4].$telWttire[5].' '.$telWttire[6].$telWttire[7].' '.$telWttire[8].$telWttire[9].' '.$telWttire[10].$telWttire[11];
  2510.         }
  2511.         $mycalls $em->getRepository('AppBundle:AircallCall')->findByRawDigits($formatednumber);
  2512.         $namedb $this->getParameter('dbreqpdo');
  2513.         $udb $this->getParameter('userreqpdo');
  2514.         $pdb $this->getParameter('passreqpdo');
  2515.         $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  2516.         $sthd $bdd->prepare("SELECT com.firstname, com.name FROM app.distrib_flat as df
  2517. inner join app.user as u on u.id = df.user
  2518. inner join app.user as com on df.commercial = com.id
  2519. where u.id = ".$user->getId());
  2520.         $sthd->execute();
  2521.         $resultd $sthd->fetchAll(\PDO::FETCH_ASSOC);
  2522.         $tikets $em->getRepository('App\AppBundle\Entity\Ticket')->findBy(['userLink' => $id] );
  2523.         $notifsBo = [];
  2524.         foreach ($user->getNotificationsBo() as $key => $item) {
  2525.             $notifsBo[$key]['id'] = $item->getId();
  2526.             $notifsBo[$key]['createdAt'] = $item->getCreatedAt();
  2527.             $notifsBo[$key]['description'] = $item->getDescription();
  2528.             $notifsBo[$key]['exp'] = $item->getExp();
  2529.             $notifsBo[$key]['dest'] = $item->getDest();
  2530.             $notifsBo[$key]['link'] = $item->getLink();
  2531.             $notifsBo[$key]['status'] = $item->getStatus();
  2532.             $notifsBo[$key]['typeofnot'] = $item->getTypeOfnot();
  2533.             $notifsBo[$key]['idoftype'] = $item->getIdOfType();
  2534.             if($item->getTypeOfnot() == 'chat') {
  2535.                 $thisMessage $em->getRepository('App\AppBundle\Entity\Message')->find($item->getIdOfType());
  2536.                 if($thisMessage->getDocument()) {
  2537.                     $notifsBo[$key]['document'] = $thisMessage->getDocument()->getId();
  2538.                 }
  2539.             }
  2540.         }
  2541.         return $this->render('Extranet/Security/addUser.html.twig', array(
  2542.             'form' => $form->createView(),
  2543.             'user' => $user,
  2544.             'notifsBo' => $notifsBo,
  2545.             //'userHistorics' => array(),
  2546.             'userHistorics' => $userHistorics,
  2547.             'calls' => $mycalls,
  2548.             'rgpd' => $tab,
  2549.             'sms' => $sms,
  2550.             'push' => $push,
  2551.             'email' => $email,
  2552.             'userinitial' => $resultd,
  2553.             'tickets' => $tikets,
  2554.             'recompenses' => $recompenses
  2555.         ));
  2556.     }
  2557.     /**
  2558.      *  Ajouter un loc secondaire
  2559.      *
  2560.      * @Route("/test/addlocform/{user}", name="testaddlocform", options={"expose"=true})
  2561.      * @Method({"GET","POST"})
  2562.      * @return Response
  2563.      */
  2564.     public function addlocformAction(Request $requestUser $user)
  2565.     {
  2566.         $em $this->get('doctrine')->getManager();
  2567.         $entity = new UserLoc();
  2568.         $entity->setOwnedBy($user);
  2569.         $em->persist($entity);
  2570.         $em->flush();
  2571.         // Puis on redirige vers la page de visualisation de cet article
  2572.         return $this->redirect$this->generateUrl('editUser', array('id' => $user)) );
  2573.         //return $this->render('Etl/locform.html.twig', array());
  2574.     }
  2575.     /**
  2576.      *  supprimer un loc secondaire
  2577.      *
  2578.      * @Route("/test/supplocform/{user}/{userloc}", name="testaddlocformsupp", options={"expose"=true})
  2579.      * @Method({"GET","POST"})
  2580.      * @return Response
  2581.      */
  2582.     public function supplocformAction(Request $requestUser $userUserLoc $userloc)
  2583.     {
  2584.         $em $this->get('doctrine')->getManager();
  2585.         $em->remove($userloc);
  2586.         $em->flush();
  2587.         // Puis on redirige vers la page de visualisation de cet article
  2588.         return $this->redirect$this->generateUrl('editUser', array('id' => $user)) );
  2589.         //return $this->render('Etl/locform.html.twig', array());
  2590.     }
  2591.     /**
  2592.      * Traiter le formulaire d'un propriétaire secondaire
  2593.      *
  2594.      * @param Request $request
  2595.      * @param UserLoc $entity
  2596.      *
  2597.      * @return JsonResponse
  2598.      *
  2599.      * @Route("/editflatpropbo", name="edit_flatprop_bo", options={"expose"=true}, methods={"POST"})
  2600.      */
  2601.     public function editflatpropboAction(Request $request)
  2602.     {
  2603.         // UserLoc
  2604.         $logger $this->get('logger');
  2605.         $em =  $this->getDoctrine->getManager();
  2606.         $request_body $request->getContent();
  2607.         $logger->critical($request_body);
  2608.         $request_bodyArray = array();
  2609.         $request_bodyArray \json_decode($request_bodytrue);
  2610.         $reencode \json_encode($request_bodyArray);
  2611.         $arr $request_bodyArray;
  2612.         // file_put_contents('/home/app/public_html3/locsecondaire.txt', $this->get('request')->request->get('userLoc_periodeEssai'), FILE_APPEND);
  2613.         $userloc $em->getRepository('AppBundle:FlatProp')->find($this->get('request')->request->get('userLoc_id'));
  2614.         $userloc->setName($this->get('request')->request->get('userLoc_name'));
  2615.         $userloc->setFirstname($this->get('request')->request->get('userLoc_firstname'));
  2616.         $userloc->setEmail($this->get('request')->request->get('userLoc_email'));
  2617.         $userloc->setCountry($this->get('request')->request->get('userLoc_country'));
  2618.         $userloc->setCity($this->get('request')->request->get('userLoc_city'));
  2619.         $userloc->setAdress($this->get('request')->request->get('userLoc_adress'));
  2620.         $userloc->setPostalCode($this->get('request')->request->get('userLoc_postalCode'));
  2621.         $userloc->setBio($this->get('request')->request->get('userLoc_bio'));
  2622.         $userloc->setMobilePhone($this->get('request')->request->get('userLoc_mobilePhone'));
  2623.         $userloc->setUpdatedAt(new \DateTime());
  2624.         $userloc->setBirthdate(new \DateTime($this->get('request')->request->get('userLoc_birthdate')));
  2625.         $userloc->setJob($this->get('request')->request->get('userLoc_job'));
  2626.         $userloc->setNationalite($this->get('request')->request->get('userLoc_nationalite'));
  2627.         $userloc->setBirthplace($this->get('request')->request->get('userLoc_birthplace'));
  2628.         ////
  2629.         $em->persist($userloc);
  2630.         $em->flush();
  2631.         //$entity->setOwnedBy($this->getUser());
  2632.         //$em->persist($entity);
  2633.         //$em->flush();
  2634.         $response = new Response();
  2635.         $response->setContent(json_encode($this->get('request')->request->get('userLoc_periodeEssai')));
  2636.         $response->setStatusCode('200');
  2637.         return $response;
  2638.     }
  2639.     /**
  2640.      *  Ajouter un proprietaire secondaire
  2641.      *
  2642.      * @Route("/test/addpropsec/{flat}", name="testaddpropsec", options={"expose"=true})
  2643.      * @Method({"GET","POST"})
  2644.      * @return Response
  2645.      */
  2646.     public function addpropsecformAction(Request $requestFlat $flat)
  2647.     {
  2648.         $em $this->get('doctrine')->getManager();
  2649.         $entity = new FlatProp();
  2650.         $entity->setFlatRef($flat);
  2651.         $em->persist($entity);
  2652.         $em->flush();
  2653.         // Puis on redirige vers la page de visualisation de cet article
  2654.         return $this->redirect$this->generateUrl('editFlat', array('id' => $flat->getId())) );
  2655.         //return $this->render('Etl/locform.html.twig', array());
  2656.     }
  2657.     /**
  2658.      *  supprimer un loc secondaire
  2659.      *
  2660.      * @Route("/test/supppropsec/{flat}/{flatprop}", name="testsupppropsec", options={"expose"=true})
  2661.      * @Method({"GET","POST"})
  2662.      * @return Response
  2663.      */
  2664.     public function supppropsecAction(Request $requestFlat $flatFlatProp $flatprop )
  2665.     {
  2666.         $em $this->get('doctrine')->getManager();
  2667.         $em->remove($flatprop);
  2668.         $em->flush();
  2669.         // Puis on redirige vers la page de visualisation de cet article
  2670.         return $this->redirect$this->generateUrl('editFlat', array('id' => $flat->getId())) );
  2671.         //return $this->render('Etl/locform.html.twig', array());
  2672.     }
  2673.     /**
  2674.      * Traiter le formulaire d'un locataire utilisateur
  2675.      *
  2676.      * @param Request $request
  2677.      * @param UserLoc $entity
  2678.      *
  2679.      * @return JsonResponse
  2680.      *
  2681.      * @Route("/edituserlocform", name="edit_user_loc_bo", options={"expose"=true}, methods={"POST"})
  2682.      */
  2683.     public function editUserLocFormAction(Request $request)
  2684.     {
  2685.         // UserLoc
  2686.         $logger $this->get('logger');
  2687.         $em =  $this->getDoctrine->getManager();
  2688.         $request_body $request->getContent();
  2689.         $logger->critical($request_body);
  2690.         $request_bodyArray = array();
  2691.         $request_bodyArray \json_decode($request_bodytrue);
  2692.         $reencode \json_encode($request_bodyArray);
  2693.         $arr $request_bodyArray;
  2694.         $userloc $em->getRepository('AppBundle:UserLoc')->find($this->get('request')->request->get('userLoc_id'));
  2695.         $userloc->setName($this->get('request')->request->get('userLoc_name'));
  2696.         $userloc->setFirstname($this->get('request')->request->get('userLoc_firstname'));
  2697.         $userloc->setEmail($this->get('request')->request->get('userLoc_email'));
  2698.         $userloc->setCountry($this->get('request')->request->get('userLoc_country'));
  2699.         $userloc->setCity($this->get('request')->request->get('userLoc_city'));
  2700.         $userloc->setAdress($this->get('request')->request->get('userLoc_adress'));
  2701.         $userloc->setPostalCode($this->get('request')->request->get('userLoc_postalCode'));
  2702.         $userloc->setBio($this->get('request')->request->get('userLoc_bio'));
  2703.         $userloc->setMobilePhone($this->get('request')->request->get('userLoc_mobilePhone'));
  2704.         $userloc->setUpdatedAt(new \DateTime());
  2705.         $userloc->setIncome($this->get('request')->request->get('userLoc_income'));
  2706.         $userloc->setRenterStatus($this->get('request')->request->get('userLoc_renterStatus'));
  2707.         $userloc->setGarant($this->get('request')->request->get('userLoc_garant'));
  2708.         $userloc->setBirthdate(new \DateTime($this->get('request')->request->get('userLoc_birthdate')));
  2709.         $userloc->setPeriodeEssai($this->get('request')->request->get('userLoc_periodeEssai'));
  2710.         $userloc->setDureeContrat($this->get('request')->request->get('userLoc_dureeContrat'));
  2711.         $userloc->setGarantIncome($this->get('request')->request->get('userLoc_garantIncome'));
  2712.         $userloc->setGarantStatus($this->get('request')->request->get('userLoc_garantStatus'));
  2713.         $userloc->setGarantPeriodeEssai($this->get('request')->request->get('userLoc_garantPeriodeEssai'));
  2714.         $userloc->setJob($this->get('request')->request->get('userLoc_job'));
  2715.         $userloc->setNationalite($this->get('request')->request->get('userLoc_nationalite'));
  2716.         $userloc->setBirthplace($this->get('request')->request->get('userLoc_birthplace'));
  2717.         $em->persist($userloc);
  2718.         $em->flush();
  2719.         //$entity->setOwnedBy($this->getUser());
  2720.         //$em->persist($entity);
  2721.         //$em->flush();
  2722.         $response = new Response();
  2723.         $response->setContent(json_encode($this->get('request')->request->get('userLoc_periodeEssai')));
  2724.         $response->setStatusCode('200');
  2725.         return $response;
  2726.     }
  2727.     /**
  2728.      * Créer un message
  2729.      *
  2730.      * @Route("/conversation/view", name="conversation_view", options={"expose"=true})
  2731.      * @param  Request $request
  2732.      * @return $this
  2733.      */
  2734.     public function conversationViewAction(Request $request)
  2735.     {
  2736.         $em =  $this->getDoctrine->getRepository('AppBundle:Conversation');
  2737.         $m = new Message($this->getUser2());
  2738.         $form $this->createForm('App\AppBundle\Form\MessageType'$m);
  2739.         $form->add('save'ButtonType::class, [
  2740.             'label' => 'Envoyer',
  2741.             'attr' => [
  2742.                 'class' => 'btn btn-success submit',
  2743.             ],
  2744.         ]);
  2745.         $form->handleRequest($request);
  2746.         if ($form->isSubmitted() && $form->isValid()) {
  2747.             $message $form->getData();
  2748.             $message->setUser($this->getUser2());
  2749.             $em =  $this->getDoctrine->getManager();
  2750.             $em->persist($message);
  2751.             $em->flush();
  2752.             foreach ($message->getConversation()->getUsers() as $user) {
  2753.                 if($message->getUser()->getId() !== $user->getId()){
  2754.                     $notifBo = new NotificationBo();
  2755.                     $notifBo->setUser($message->getUser());
  2756.                     $temp $message->getUser();
  2757.                     if($temp->hasRole('ROLE_ADMIN')){
  2758.                         $notifBo->setUser($user);
  2759.                     }else{
  2760.                         $notifBo->setUser($message->getUser());
  2761.                     }
  2762.                     $notifBo->setDescription($message->getContent());
  2763.                     $notifBo->setExp($message->getUser()->getId());
  2764.                     $notifBo->setDest($user->getId());
  2765.                     $notifBo->setTypeOfnot("chat");
  2766.                     $notifBo->setIdOfType($message->getId());
  2767.                     $em->persist($notifBo);
  2768.                     $em->flush();
  2769.                 }
  2770.                 // if($myexpediteur == $user ){
  2771.                 // $desc = "Vous avez reçu un message de ".$message->getUser()->getFirstname().' '.$message->getUser()->getName() ;
  2772.                 // $this->get('app.contract')->sendPush([$user->getDeviceToken()], 'Tchat Wizi', $desc);
  2773.                 // }
  2774.             }
  2775.             return $this->redirectToRoute('userListing');
  2776.         }
  2777.         $conversations $em->userConversationsNotnul($this->getUser2(),10);
  2778.         $allConversations $em->userConversationsNotnul($this->getUser2(),1);
  2779.         return $this->render('Extranet/Conversation/index.html.twig', array(
  2780.             'form' => $form->createView(),
  2781.             'conversations' => $conversations,
  2782.             'allConversations' => $allConversations,
  2783.             'user' => $this->getUser2(),
  2784.         ));
  2785.     }
  2786.     /**
  2787.      * Créer un message
  2788.      *
  2789.      * @Route("/conversation/view/{id}", name="conversation_view_param")
  2790.      * @param  Request $request
  2791.      * @return $this
  2792.      */
  2793.     public function conversationViewMsgAction(Request $request$id)
  2794.     {
  2795.         $em =  $this->getDoctrine->getRepository('AppBundle:Conversation');
  2796.         $form $this->createForm('App\AppBundle\Form\MessageType', new Message($this->getUser2()));
  2797.         $form->add('save'ButtonType::class, [
  2798.             'label' => 'Envoyer',
  2799.             'attr' => [
  2800.                 'class' => 'btn btn-success submit',
  2801.             ],
  2802.         ]);
  2803.         $form->handleRequest($request);
  2804.         if ($form->isSubmitted() && $form->isValid()) {
  2805.             $newUser $form->getData();
  2806.             $em =  $this->getDoctrine->getManager();
  2807.             $em->persist($newUser);
  2808.             $em->flush();
  2809.             return $this->redirectToRoute('userListing');
  2810.         }
  2811.         $conversation[] = $em->find($id);
  2812.         return $this->render('Extranet/Conversation/index.html.twig', array(
  2813.             'form' => $form->createView(),
  2814.             'conversations' => $conversation,
  2815.             'user' => $this->getUser2(),
  2816.         ));
  2817.     }
  2818.     /**
  2819.      * Lister les conversations
  2820.      *
  2821.      * @Route("/conversation/filter/{data}", name="conversation_filter", methods={"GET"}, options={"expose"=true})
  2822.      *
  2823.      * @return \Symfony\Component\HttpFoundation\Response
  2824.      */
  2825.     public function filterAction(Request $request$data null)
  2826.     {
  2827.         $em =  $this->getDoctrine->getRepository('AppBundle:Conversation');
  2828.         $conversations $em->userConversations($this->getUser2(),10null,$data);
  2829.         return $this->render('Extranet/Conversation/timeline.html.twig', array(
  2830.             'conversations' => $conversations,
  2831.         ));
  2832.     }
  2833.     /**
  2834.      * Lister les conversations
  2835.      *
  2836.      * @Route("/maxTen/{from}/{data}", name="conversation_maxten", methods={"GET"}, options={"expose"=true})
  2837.      *
  2838.      * @return \Symfony\Component\HttpFoundation\Response
  2839.      */
  2840.     public function maxTenAction(Request $request,$from$data null)
  2841.     {
  2842.         $em =  $this->getDoctrine->getRepository('AppBundle:Conversation');
  2843.         $conversations $em->userConversationsNotnul($this->getUser2(),10$from,$data);
  2844.         return $this->render('Extranet/Conversation/list.html.twig', array(
  2845.             'conversations' => $conversations,
  2846.         ));
  2847.     }
  2848.     /**
  2849.      * Marquer une annonce à exporter sur les sites
  2850.      *
  2851.      * @Route("/flat/exportAdd/{id}", name="flat_export_add", options={"expose"=true})
  2852.      */
  2853.     public function exportAddAction($id)
  2854.     {
  2855.         $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  2856.         $flat->setExported(true);
  2857.         $em =  $this->getDoctrine->getManager();
  2858.         $em->flush();
  2859.         $numberOfExportedFlats $em->getRepository('AppBundle:Flat')->countExported();
  2860.         $exportLogin $this->getParameter('ftp_login');
  2861.         $exportPassword $this->getParameter('ftp_password');
  2862.         $url curl_init();
  2863.         curl_setopt($urlCURLOPT_URL'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
  2864.         curl_setopt($urlCURLOPT_RETURNTRANSFER1);
  2865.         $urlResult curl_exec ($url);
  2866.         curl_close($url);
  2867.         $exportLimit 0;
  2868.         $webSiteDatas = new \SimpleXMLElement($urlResult);
  2869.         foreach ($webSiteDatas as $webSiteData) {
  2870.             if (intval($webSiteData->nb_annonces_max) > $exportLimit) {
  2871.                 $exportLimit intval($webSiteData->nb_annonces_max);
  2872.             }
  2873.         }
  2874.         $message '';
  2875.         if ($exportLimit and $exportLimit $numberOfExportedFlats) {
  2876.             $message "Vous avez dépassé la limite d'annonces à exporter.";
  2877.         }
  2878.         return new JsonResponse(['message' => $message]);
  2879.     }
  2880.     /**
  2881.      * Marquer une annonce à exporter sur les sites
  2882.      *
  2883.      * @Route("/flat/exportselectAdd/{id}/{site}", name="flat_exportselect_add", options={"expose"=true})
  2884.      */
  2885.     public function exportselectAddAction($id,$site)
  2886.     {
  2887.         /*
  2888.          * sites :
  2889.          * 1 tous les autres
  2890.          * 2 le bon coin
  2891.          * 3 seloger
  2892.          *
  2893.          */
  2894.         $message '';
  2895.         $exportLimit 0;
  2896.         switch ($site) {
  2897.             case 1:
  2898.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  2899.                 $flat->setExported(true);
  2900.                 $em =  $this->getDoctrine->getManager();
  2901.                 $numberOfExportedFlats $em->getRepository('AppBundle:Flat')->countExported();
  2902.                 $exportLimit 0;
  2903.                 if ($exportLimit and $exportLimit $numberOfExportedFlats) {
  2904.                     $message "Vous avez dépassé la limite d'annonces à exporter.";
  2905.                     return new JsonResponse(['message' => $message]);
  2906.                 }else{
  2907.                     $em->flush();
  2908.                     $exportLogin $this->getParameter('ftp_login');
  2909.                     $exportPassword $this->getParameter('ftp_password');
  2910.                     $url curl_init();
  2911.                     curl_setopt($urlCURLOPT_URL'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
  2912.                     curl_setopt($urlCURLOPT_RETURNTRANSFER1);
  2913.                     $urlResult curl_exec ($url);
  2914.                     curl_close($url);
  2915.                     $message "multidif site gratuit ajoute";
  2916.                     return new JsonResponse(['message' => $message]);
  2917.                 }
  2918.                 break;
  2919.             case 2:
  2920.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  2921.                 $flat->setLbcexport(true);
  2922.                 $em =  $this->getDoctrine->getManager();
  2923.                 $numberOfExportedFlats $em->getRepository('AppBundle:Flat')->countLbcexport();
  2924.                 $exportLimit 50;
  2925.                 if ($exportLimit and $exportLimit $numberOfExportedFlats) {
  2926.                     $message "Vous avez dépassé la limite d'annonces à exporter sur le bon coin.";
  2927.                     return new JsonResponse(['message' => $message]);
  2928.                 }else{
  2929.                     $em->flush();
  2930.                     $exportLogin $this->getParameter('ftp_login');
  2931.                     $exportPassword $this->getParameter('ftp_password');
  2932.                     $url curl_init();
  2933.                     curl_setopt($urlCURLOPT_URL'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
  2934.                     curl_setopt($urlCURLOPT_RETURNTRANSFER1);
  2935.                     $urlResult curl_exec ($url);
  2936.                     curl_close($url);
  2937.                     $message "multidif site le bon coin ajoute";
  2938.                     return new JsonResponse(['message' => $message]);
  2939.                 }
  2940.                 break;
  2941.             case 3:
  2942.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  2943.                 $flat->setSlexport(true);
  2944.                 $em =  $this->getDoctrine->getManager();
  2945.                 $numberOfExportedFlats $em->getRepository('AppBundle:Flat')->countSlexport();
  2946.                 $exportLimit 350;
  2947.                 if ($exportLimit and $exportLimit $numberOfExportedFlats) {
  2948.                     $message "Vous avez dépassé la limite d'annonces à exporter sur Se loger.";
  2949.                     return new JsonResponse(['message' => $message]);
  2950.                 }else{
  2951.                     $em->flush();
  2952.                     $exportLogin $this->getParameter('ftp_login');
  2953.                     $exportPassword $this->getParameter('ftp_password');
  2954.                     $url curl_init();
  2955.                     curl_setopt($urlCURLOPT_URL'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
  2956.                     curl_setopt($urlCURLOPT_RETURNTRANSFER1);
  2957.                     $urlResult curl_exec ($url);
  2958.                     curl_close($url);
  2959.                     $message "multidif se loger ajoute";
  2960.                     return new JsonResponse(['message' => $message]);
  2961.                 }
  2962.                 break;
  2963.             case 4:
  2964.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  2965.                 $flat->setOuestexport(true);
  2966.                 $em =  $this->getDoctrine->getManager();
  2967.                 $numberOfExportedFlats $em->getRepository('AppBundle:Flat')->countOuestexport();
  2968.                 $exportLimit 30;
  2969.                 if ($exportLimit and $exportLimit $numberOfExportedFlats) {
  2970.                     $message "Vous avez dépassé la limite d'annonces à exporter sur Ouest France immo.";
  2971.                     return new JsonResponse(['message' => $message]);
  2972.                 }else{
  2973.                     $em->flush();
  2974.                     $exportLogin $this->getParameter('ftp_login');
  2975.                     $exportPassword $this->getParameter('ftp_password');
  2976.                     $url curl_init();
  2977.                     curl_setopt($urlCURLOPT_URL'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
  2978.                     curl_setopt($urlCURLOPT_RETURNTRANSFER1);
  2979.                     $urlResult curl_exec ($url);
  2980.                     curl_close($url);
  2981.                     $message "multidif Ouest ajoute";
  2982.                     return new JsonResponse(['message' => $message]);
  2983.                 }
  2984.                 break;
  2985.         }
  2986. //        $webSiteDatas = new \SimpleXMLElement($urlResult);
  2987. //        foreach ($webSiteDatas as $webSiteData) {
  2988. //            if (intval($webSiteData->nb_annonces_max) > $exportLimit) {
  2989. //                $exportLimit = intval($webSiteData->nb_annonces_max);
  2990. //            }
  2991. //        }
  2992.     }
  2993.     /**
  2994.      * Marquer une annonce à ne plus exporter sur les sites
  2995.      *
  2996.      * @Route("/flat/exportselectRemove/{id}/{site}", name="flat_exportselect_remove", options={"expose"=true})
  2997.      */
  2998.     public function exportselectDeleteAction($id,$site)
  2999.     {
  3000.         switch ($site) {
  3001.             case 1:
  3002.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  3003.                 $flat->setExported(false);
  3004.                 $em =  $this->getDoctrine->getManager();
  3005.                 $em->flush();
  3006.                 $message 'site gratuit efface';
  3007.                 return new JsonResponse(['message' => $message]);
  3008.                 break;
  3009.             case 2:
  3010.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  3011.                 $flat->setLbcexport(false);
  3012.                 $em =  $this->getDoctrine->getManager();
  3013.                 $em->flush();
  3014.                 $message 'site le bon coin efface';
  3015.                 return new JsonResponse(['message' => $message]);
  3016.                 break;
  3017.             case 3:
  3018.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  3019.                 $flat->setSlexport(false);
  3020.                 $em =  $this->getDoctrine->getManager();
  3021.                 $em->flush();
  3022.                 $message 'site se loger efface';
  3023.                 return new JsonResponse(['message' => $message]);
  3024.                 break;
  3025.             case 4:
  3026.                 $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  3027.                 $flat->setOuestexport(false);
  3028.                 $em =  $this->getDoctrine->getManager();
  3029.                 $em->flush();
  3030.                 $message 'site Ouest france immo efface';
  3031.                 return new JsonResponse(['message' => $message]);
  3032.                 break;
  3033.         }
  3034.     }
  3035.     /**
  3036.      * Marquer une annonce à ne plus exporter sur les sites
  3037.      *
  3038.      * @Route("/flat/exportRemove/{id}", name="flat_export_remove", options={"expose"=true})
  3039.      */
  3040.     public function exportDeleteAction($id)
  3041.     {
  3042.         $flat =  $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
  3043.         $flat->setExported(false);
  3044.         $em =  $this->getDoctrine->getManager();
  3045.         $em->flush();
  3046.         return new JsonResponse();
  3047.     }
  3048.     /**
  3049.      * Supprimer une annonce
  3050.      *
  3051.      * @Route("/flat/{id}/delete", name="flatDelete", options={"expose"=true})
  3052.      * @Method("DELETE")
  3053.      */
  3054.     public function flatDeleteAction(Request $requestFlat $flat)
  3055.     {
  3056.         $form $this->createFlatDeleteForm($flat->getId());
  3057.         $form->handleRequest($request);
  3058.         if ($form->isSubmitted() && $form->isValid()) {
  3059.             $em =  $this->getDoctrine->getManager();
  3060.             $em->remove($flat);
  3061.             $em->flush();
  3062.         }
  3063.         return $this->redirectToRoute('flatListing');
  3064.     }
  3065.     /**
  3066.      * Construit un formulaire de suppression d'annonce
  3067.      *
  3068.      * @param $id
  3069.      *
  3070.      * @return \Symfony\Component\Form\Form|\Symfony\Component\Form\FormInterface
  3071.      */
  3072.     private function createFlatDeleteForm($id)
  3073.     {
  3074.         return $this->createFormBuilder()
  3075.             ->setAction($this->generateUrl('flatDelete', array('id' => $id)))
  3076.             ->setMethod('DELETE')
  3077.             ->add('submit''submit', array('label' => 'Supprimer','attr' => array('class' => 'btn btn-danger')))
  3078.             ->getForm()
  3079.             ;
  3080.     }
  3081.     /**
  3082.      * Récupère un mandat pdf
  3083.      *
  3084.      * @Route("/mandate/show-pdf-saved/{id}", name="mandate_show_pdf_saved", options={"expose" = true})
  3085.      * @Method("GET")
  3086.      *
  3087.      * @param Mandate $mandate
  3088.      * @return \Symfony\Component\HttpFoundation\Response
  3089.      */
  3090.     public function getMandateShowPdfSavedAction(Request $requestMandate $mandate)
  3091.     {
  3092.         $em =  $this->getDoctrine->getManager();
  3093.         $candidatureInitie $mandate->getFlat()->getApplications()->count();
  3094.         if($candidatureInitie){
  3095.             $candidatures $mandate->getFlat()->getApplications();
  3096.             foreach ($candidatures as $application){
  3097.                 $contract $application->getContract();
  3098.                 if($contract){
  3099.                     $signmandate $contract->getDocument("signed_mandate");
  3100.                     if($signmandate){
  3101.                         $content file_get_contents($signmandate->getAbsolutePath());
  3102.                         return new Response($content200, [
  3103.                             'Content-Type' => 'application/pdf',
  3104.                             'Content-Disposition' => 'inline; filename="file.pdf"',
  3105.                         ]);
  3106.                     }
  3107.                 }
  3108.             }
  3109.         }
  3110. //        if($mandate->getFlat()){
  3111. //            $c = $mandate->getFlat()->getMandates()->count();
  3112. //            $lm = $mandate->getFlat()->getMandates()[$c-1];
  3113. //            $content = file_get_contents($lm->getDocument()->getAbsolutePath());
  3114. //        }else{
  3115.         $content file_get_contents($mandate->getDocument()->getAbsolutePath());
  3116. //        }
  3117.         return new Response($content200, [
  3118.             'Content-Type' => 'application/pdf',
  3119.             'Content-Disposition' => 'inline; filename="file.pdf"',
  3120.         ]);
  3121.     }
  3122.     /**
  3123.      * Modifier le statut d'une candidature
  3124.      *
  3125.      * @Route("/application/status/edit/{id}/{status}", name="edit_status", options={"expose"=true})
  3126.      * @param Request $request
  3127.      *
  3128.      * @return JsonResponse
  3129.      */
  3130.     public function editStatusAction($id$status)
  3131.     {
  3132.         $em =  $this->getDoctrine->getManager();
  3133.         $application =  $this->getDoctrine->getRepository('AppBundle:Application')->find($id);
  3134.         if ($status == 99) {
  3135.             $application->setRemoved(true);
  3136.             $application->setStatus(3);
  3137.             // adminnotif 32
  3138.             $notifier $this->get('app.notifparse');
  3139.             $notifier->doAll(  32'Application',$application->getId(),'notif');
  3140.             // Notif Propriétaire
  3141.             /*
  3142.             $notification = new Notification();
  3143.             $notification->setEmplacement('notif');
  3144.             $notification->setUser($application->getFlat()->getOwnedBy());
  3145.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' retirée ');
  3146.             $notification->setIcon('far fa-times-square icon');
  3147.             $notification->setColor('#e74c3c');
  3148.             $em->persist($notification);
  3149.             */
  3150.             // adminnotif 33
  3151.             $notifier $this->get('app.notifparse');
  3152.             $notifier->doAll(  33'Application',$application->getId(),'notif');
  3153.             // Notif Locataire
  3154.             /*
  3155.             $notification = new Notification();
  3156.             $notification->setEmplacement('notif');
  3157.             $notification->setUser($application->getUser());
  3158.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature retirée par Wizi');
  3159.             $notification->setIcon('far fa-times-square icon');
  3160.             $notification->setColor('#e74c3c');
  3161.             $em->persist($notification);
  3162.             */
  3163.         } elseif ($status == 1){
  3164.             $application->setStatus($status);
  3165.             $application->setRemoved(NULL);
  3166.         } elseif ($status == 2){
  3167.             $application->setStatus($status);
  3168.             $application->setRemoved(NULL);
  3169.             // adminnotif 34
  3170.             $notifier $this->get('app.notifparse');
  3171.             $notifier->doAll(  34'Application',$application->getId(),'notif');
  3172.             // Notif Propriétaire
  3173.             /*
  3174.             $notification = new Notification();
  3175.             $notification->setEmplacement('notif');
  3176.             $notification->setUser($application->getFlat()->getOwnedBy());
  3177.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' acceptée par Wizi ');
  3178.             $notification->setIcon('ion-document-text icon');
  3179.             $em->persist($notification);
  3180.             */
  3181.             // adminnotif 36
  3182.             $notifier $this->get('app.notifparse');
  3183.             $notifier->doAll(  36'Application',$application->getId(),'notif');
  3184.             // Notif Locataire
  3185.             /*
  3186.             $notification = new Notification();
  3187.             $notification->setEmplacement('notif');
  3188.             $notification->setUser($application->getUser());
  3189.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature acceptée');
  3190.             $notification->setIcon('ion-document-text icon');
  3191.             $em->persist($notification);
  3192.             */
  3193.         } elseif ($status == 3){
  3194.             $application->setStatus($status);
  3195.             $application->setRemoved(NULL);
  3196.             // adminnotif 37
  3197.             $notifier $this->get('app.notifparse');
  3198.             $notifier->doAll(  37'Application',$application->getId(),'notif');
  3199.             // Notif Propriétaire
  3200.             /*
  3201.             $notification = new Notification();
  3202.             $notification->setEmplacement('notif');
  3203.             $notification->setUser($application->getFlat()->getOwnedBy());
  3204.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' refusée par Wizi ');
  3205.             $notification->setIcon('ion-document-text icon');
  3206.             $em->persist($notification);
  3207.             */
  3208.             // adminnotif 38
  3209.             $notifier $this->get('app.notifparse');
  3210.             $notifier->doAll(  38'Application',$application->getId(),'notif');
  3211.             // Notif Locataire
  3212.             /*
  3213.             $notification = new Notification();
  3214.             $notification->setEmplacement('notif');
  3215.             $notification->setUser($application->getUser());
  3216.             $notification->setDescription('Annonce '.$application->getFlat()->getId().' :  candidature refusée');
  3217.             $notification->setIcon('ion-document-text icon');
  3218.             $em->persist($notification);
  3219.             */
  3220.         }
  3221.         $em->persist($application);
  3222.         $em->flush();
  3223.         return new JsonResponse('Statut modifié');
  3224.     }
  3225.     /**
  3226.      * Lister les conversations
  3227.      *
  3228.      * @Route("/message/notif", name="notif_msg", methods={"GET"}, options={"expose"=true})
  3229.      *
  3230.      * @return \Symfony\Component\HttpFoundation\Response
  3231.      */
  3232.     public function notifMsgAction()
  3233.     {
  3234.         $em =  $this->getDoctrine->getRepository('AppBundle:Conversation');
  3235.         $nbMsgNotRead $em->nbMsgNotRead($this->getUser2());
  3236.         $convsNotReadArr $em->conversationsByIdNotRead($this->getUser2());
  3237.         $convsNotRead array_map('current'$convsNotReadArr);
  3238.         return new JsonResponse(['nb' => $nbMsgNotRead'convs'=> $convsNotRead]);
  3239.     }
  3240.     /**
  3241.      *  Lister les ask
  3242.      *
  3243.      * @Route("/ask/listing", name="askListing")
  3244.      *
  3245.      * @return string
  3246.      */
  3247.     public function indexAskAction()
  3248.     {
  3249.         $em =  $this->getDoctrine;
  3250.         $askManager $em->getRepository('App\AppBundle\Entity\Ask');
  3251.         $asks $askManager->findAll();
  3252.         //$datatable = $this->get('app.datatable.ask');
  3253.         // $datatable->buildDatatable();
  3254.         return $this->render('Extranet/Ask/ask.html.twig', array(
  3255.             'datatable' => $asks,
  3256.         ));
  3257.     }
  3258.     /**
  3259.      * Filtrer les Ask
  3260.      *
  3261.      * @Route("/ask/results", name="ask_results")
  3262.      */
  3263.     public function askboardResultsAction()
  3264.     {
  3265.         $datatable $this->get('app.datatable.ask');
  3266.         $datatable->buildDatatable();
  3267.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  3268.         return $query->getResponse();
  3269.     }
  3270.     /**
  3271.      * Page bibliothèque Wizi
  3272.      *
  3273.      * @Route("/biblio", name="biblioPage")
  3274.      * @return Response
  3275.      */
  3276.     public function biblioPageAction()
  3277.     {
  3278.         return $this->render('bibliotheque/bibliotheque.html.twig',[]);
  3279.     }
  3280.     /**
  3281.      * Lister les annonces
  3282.      *
  3283.      * @Route("/parrainage/listing", name="parrainageListing")
  3284.      * @return Response
  3285.      */
  3286.     public function parrainageListingAction()
  3287.     {
  3288.         return $this->render('Extranet/parrainage.html.twig',[]);
  3289.     }
  3290.     /**
  3291.      * Filtrer les Ask
  3292.      *
  3293.      * @param Request $request
  3294.      * @Route("/parrainage/results", name="parrainage_results", options={"expose"=true})
  3295.      * @return JsonResponse
  3296.      */
  3297.     public function parrainageboardResultsAction(Request $request,\App\AppBundle\Service\TabledataService $TabledataService)
  3298.     {
  3299.         $sql "SELECT fil.id as filid, concat(fil.firstname, ' ', fil.name) as filleul, par.id as parid, concat(par.firstname, ' ', par.name) as parrain, concat(concat(pro.firstname, ' ', pro.name), ' - ', concat(pro.mobile_phone, ' - ', pro.email)) as pro, fil.created_at as datee
  3300.         FROM app.user as fil 
  3301.         LEFT JOIN app.user as par on par.code_parrain = fil.code_filleul 
  3302.         LEFT JOIN app.parrainage_pro as pro on pro.code = fil.code_filleul ";
  3303.         $condition "WHERE fil.code_filleul IS NOT NULL";
  3304.         $fields = [
  3305.             ['name' => 'filid'],
  3306.             ['name' => 'filleul'],
  3307.             ['name' => 'parid'],
  3308.             ['name' => 'parrain'],
  3309.             ['name' => 'pro'],
  3310.             ['name' => 'datee']
  3311.         ];
  3312.         //$datatable = $this->get('app.tabledata')->datatablePdo($sql, $fields, $request, $condition);
  3313.         $datatable $TabledataService->datatablePdo($sql$fields$request,$condition);
  3314.         for ($i 0$i count($datatable['data']); $i++){
  3315.             if($datatable['data'][$i][0]) {
  3316.                 $route1 $this->generateUrl('editUser', ['id' => $datatable['data'][$i][0]]);
  3317.                 $datatable['data'][$i][0] = '<a style="text-decoration: underline" href="'.$route1.'">'.$datatable['data'][$i][1].'</a>';
  3318.             }
  3319.             unset($datatable['data'][$i][1]);
  3320.             if($datatable['data'][$i][2]) {
  3321.                 $route2 $this->generateUrl('editUser', ['id' => $datatable['data'][$i][2]]);
  3322.                 $datatable['data'][$i][2] = '<a style="text-decoration: underline" href="'.$route2.'">'.$datatable['data'][$i][3].'</a>';
  3323.             }
  3324.             unset($datatable['data'][$i][3]);
  3325.             $datatable['data'][$i] = array_values($datatable['data'][$i]);
  3326.         }
  3327.         return new JsonResponse($datatable);
  3328.     }
  3329.     /**
  3330.      * Lister les upsells
  3331.      *
  3332.      * @Route("/upsells/listing", name="upsellListing")
  3333.      * @return Response
  3334.      */
  3335.     public function upsellListingAction()
  3336.     {
  3337.         return $this->render('Extranet/upsell.html.twig',[]);
  3338.     }
  3339.     /**
  3340.      * Filtrer les Ask
  3341.      *
  3342.      * @param Request $request
  3343.      * @Route("/upsell/results", name="upsell_results", options={"expose"=true})
  3344.      * @return JsonResponse
  3345.      */
  3346.     public function upsellResultsAction(Request $request)
  3347.     {
  3348.         $sql "SELECT * FROM app.contract ";
  3349. //        $condition = "WHERE code_filleul IS NOT NULL";
  3350.         $fields = [
  3351.             ['name' => 'id'],
  3352.             ['name' => 'wizi_internet''translation' => [null => 'N.C.'=> 'Oui'=> 'Non']],
  3353.             ['name' => 'wizi_energie''translation' => [null => 'N.C.'=> 'Oui'=> 'Non']],
  3354.             ['name' => 'wizi_mrh''translation' => [null => 'N.C.'=> 'Oui'=> 'Non']],
  3355.             ['name' => 'wizi_diagnostics''translation' => [null => 'N.C.'=> 'Oui'=> 'Non']],
  3356.             ['name' => 'wizi_pno''translation' => [null => 'N.C.'=> 'Oui'=> 'Non']],
  3357.             ['name' => 'status''translation' => [=> 'En préparation'=> 'En cours'=> 'Archivé'=> 'Annulé']],
  3358.         ];
  3359.         $datatable $this->get('app.tabledata')->datatablePdo($sql$fields$request);
  3360.         for ($i 0$i count($datatable['data']); $i++){
  3361.             $route $this->generateUrl('contract_edit', ['id' => $datatable['data'][$i][0]]);
  3362.             $datatable['data'][$i][0] = '<a class="btn btn-primary wizi-btn-purple" href="'.$route.'">'$datatable['data'][$i][0] .'</a>';
  3363. //            array_push($datatable['data'][$i], '<a class="btn btn-primary wizi-btn-purple" href="'.$route.'"><i class="fa fa-edit"></i></a>');
  3364.         }
  3365.         return new JsonResponse($datatable);
  3366.     }
  3367.     /**
  3368.      * Lister les dossiers a vérifier
  3369.      *
  3370.      * @Route("/verifdoss", name="verifdossListing")
  3371.      * @return Response
  3372.      */
  3373.     public function verifdossListingAction()
  3374.     {
  3375.         $datatable $this->get('app.datatable.verifdoss');
  3376.         $datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
  3377.         return $this->render('Extranet/Verifdoss/list.html.twig', array(
  3378.             'datatable' => $datatable,
  3379.         ));
  3380.     }
  3381.     /**
  3382.      * Filtrer les dossiers a vérifier
  3383.      *
  3384.      * @Route("/verifdoss/results", name="verifdoss_results")
  3385.      */
  3386.     public function verifdossResultsAction()
  3387.     {
  3388.         $datatable $this->get('app.datatable.verifdoss');
  3389.         $datatable->buildDatatable();
  3390.         $query $this->get('sg_datatables.query')->getQueryFrom($datatable);
  3391.         $function = function($qb)
  3392.         {
  3393.             $qb->andWhere("contract.taskdoctriger = :status");
  3394.             $qb->setParameter('status'"1");
  3395.         };
  3396.         $query->addWhereAll($function);
  3397.         return $query->getResponse();
  3398.     }
  3399.     /**
  3400.      *  micro task detailée
  3401.      *
  3402.      * @Route("/verifdoss/results/{application}", name="verifdoss_edit", options={"expose"=true})
  3403.      * @Method({"GET","POST"})
  3404.      * @return Response
  3405.      */
  3406.     public function detailcandidatureAction(Request $request,Application $application)
  3407.     {
  3408.         return $this->render('Extranet/Application/revisiontask.html.twig', array(
  3409.             'application' => $application,
  3410.             // 'form' => $form->createView(),
  3411.         ));
  3412.     }
  3413.     /**
  3414.      *  mettre a jour les salaires dans les dossiers a verifier
  3415.      *
  3416.      * @Route("/verifdoss/updateusersalaireup/send", name="updateusersalaireup_send", options={"expose"=true})
  3417.      * @Method({"GET","POST"})
  3418.      * @return Response
  3419.      */
  3420.     public function updateusersalaireupAction(Request $request)
  3421.     {
  3422.         $m $this->get('request')->request->get('salupone');
  3423.         $m2 $this->get('request')->request->get('saluptwo');
  3424.         $m3 $this->get('request')->request->get('salupthree');
  3425.         $uid $this->get('request')->request->get('uid');
  3426.         $em =  $this->getDoctrine->getManager();
  3427.         $userRepo =  $this->getDoctrine->getRepository('AppBundle:User');
  3428.         $user $userRepo->find($uid);
  3429.         $user->setIncomeOne($m);
  3430.         $user->setIncomeTwo($m2);
  3431.         $user->setIncomeThree($m3);
  3432.         $em->persist($user);
  3433.         $em->flush();
  3434.         $response = new Response();
  3435.         $response->setContent(json_encode('ok'));
  3436.         $response->setStatusCode('200');
  3437.         return $response;
  3438.     }
  3439.     /**
  3440.      *  mettre a jour les infos imposition dans les dossiers a verifier
  3441.      *
  3442.      * @Route("/verifdoss/updateuserimpos/send", name="updateuserimpos_send", options={"expose"=true})
  3443.      * @Method({"GET","POST"})
  3444.      * @return Response
  3445.      */
  3446.     public function updateuserimposAction(Request $request)
  3447.     {
  3448.         $revfiscalref $this->get('request')->request->get('revref');
  3449.         $uid $this->get('request')->request->get('uid');
  3450.         $em =  $this->getDoctrine->getManager();
  3451.         $userRepo =  $this->getDoctrine->getRepository('AppBundle:User');
  3452.         $user $userRepo->find($uid);
  3453.         $user->setRevfiscalref($revfiscalref);
  3454.         $em->persist($user);
  3455.         $em->flush();
  3456.         $response = new Response();
  3457.         $response->setContent(json_encode('ok'));
  3458.         $response->setStatusCode('200');
  3459.         return $response;
  3460.     }
  3461.     /**
  3462.      *  micro task detailée
  3463.      *
  3464.      * @Route("/verifdoss/send", name="verifdoss_send", options={"expose"=true})
  3465.      * @Method({"GET","POST"})
  3466.      * @return Response
  3467.      */
  3468.     public function detailcandidaturesendAction(Request $request)
  3469.     {
  3470.         $em =  $this->getDoctrine->getManager();
  3471.         $verDossRepo =  $this->getDoctrine->getRepository('AppBundle:VerifDoss');
  3472.         $logger $this->get('logger');
  3473.         $em =  $this->getDoctrine->getManager();
  3474.         $request_body $request->getContent();
  3475.         $logger->critical($request_body);
  3476.         $request_bodyArray = array();
  3477.         $request_bodyArray \json_decode($request_bodytrue);
  3478.         $reencode \json_encode($request_bodyArray);
  3479.         $arr $request_bodyArray;
  3480.         $principal $this->get('request')->request->get('principal');
  3481.         $secondaires $this->get('request')->request->get('secondaire');
  3482.         $appid $this->get('request')->request->get('appid');
  3483.         $usp = new Verifdoss();
  3484.         $olddoss $verDossRepo->findBy(array('applicationId'=> $appid));
  3485.         foreach ($olddoss as $d) {
  3486.             $em->remove($d);
  3487.             $em->flush();
  3488.         }
  3489.         foreach ($principal as $key => $value) {
  3490.             //$metodstring = 'set'.$value['param'];
  3491.             //json_decode(json)
  3492.             if($value['uid']['param'] != 'Other'){
  3493.                 $metodstring "set".$value['uid']['param'];
  3494.                 $metodstring2 "setMust".$value['uid']['param'];
  3495.                 $usp->{$metodstring}($value['uid']['val']);
  3496.                 $usp->{$metodstring2}(1);
  3497.             }
  3498.             $usp->setUserId($value['uid']['usid']);
  3499.         }
  3500.         $usp->setApplicationId($appid);
  3501.         $em->persist($usp);
  3502.         $em->flush();
  3503.         /* traitement des user sec*/
  3504.         if(isset($secondaires) && count($secondaires) > 0){
  3505.             $oldusId '';
  3506.             $usl '';
  3507.             foreach ($secondaires as $key => $value) {
  3508.                 if($oldusId != $value['uid']['usid']){
  3509.                     if ($usl != '') {
  3510.                         $em->persist($usl);
  3511.                         $em->flush();
  3512.                     }
  3513.                     $usl = new Verifdoss();
  3514.                 }
  3515.                 //$metodstring = 'set'.$value['param'];
  3516.                 //json_decode(json)
  3517.                 if($value['uid']['param'] != 'Other'){
  3518.                     $metodstring "set".$value['uid']['param'];
  3519.                     $metodstring2 "setMust".$value['uid']['param'];
  3520.                     $usl->{$metodstring}($value['uid']['val']);
  3521.                     $usl->{$metodstring2}(1);
  3522.                 }
  3523.                 $usl->setUserLocId($value['uid']['usid']);
  3524.                 $usl->setApplicationId($appid);
  3525.                 $oldusId $value['uid']['usid'];
  3526.             }
  3527.             $em->persist($usl);
  3528.             $em->flush();
  3529.         }
  3530.         //concsel: selconc,conctxt: textconc
  3531.         $apptxt $this->get('request')->request->get('conctxt');
  3532.         $appsel $this->get('request')->request->get('concsel');
  3533.         $application =  $this->getDoctrine->getRepository('AppBundle:Application')->find($appid);
  3534.         // $suivipar
  3535.         $commercialId $application->getFlat()->getOwnedBy()->getSuivipar();
  3536.         $CommObject =  $this->getDoctrine->getRepository('AppBundle:User')->find($commercialId);
  3537.         if($application->getTaskdocstatus() != && $appsel == 1){
  3538.             // adminnotif 39
  3539.             $notifier $this->get('app.notifparse');
  3540.             $notifier->doAll(  39'Application',$application->getId(),'notif');
  3541.             // notification locataire
  3542.             $description ='Félicitations, votre dossier de location a été contrôlé et validé par Wizi. Votre propriétaire en a été informé.';
  3543.             /*
  3544.             $notification = new Notification();
  3545.             $notification->setEmplacement('contrat');
  3546.             $notification->setStatus(1);
  3547.             $notification->setUser($application->getUser());
  3548.             
  3549.             $notification->setDescription($description);
  3550.             $notification->setIcon('far fa-file-certificate icon');
  3551.             $notification->setColor('#029398');
  3552.             $notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
  3553.             $em->persist($notification);
  3554.             */
  3555.             $em->flush();
  3556.             // sms
  3557.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3558.             $fields = array(
  3559.                 'apiKey'=> $apikey,
  3560.                 'sender' => 'Wizi',
  3561.                 'SMSList'=> array(
  3562.                     array(
  3563.                         'phoneNumber'=> $application->getUser()->getMobilePhone(),
  3564.                         'message'=> $description,
  3565.                         'gamme' => 1
  3566.                     )
  3567.                 )
  3568.             );
  3569.             $curl curl_init();
  3570.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3571.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3572.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3573.             curl_setopt($curlCURLOPT_POST1);
  3574.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3575.             $result curl_exec($curl);
  3576.             curl_close($curl);
  3577.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3578.         $body = [
  3579.             'Messages' => [
  3580.                 [
  3581.                     'From' => [
  3582.                         'Email' => "laura@wizi.eu",
  3583.                         'Name' => "Laura de Wizi"
  3584.                     ],
  3585.                     'To' => [
  3586.                         [
  3587.                             'Email' => $application->getUser()->getEmail(),
  3588.                             'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
  3589.                         ]
  3590.                     ],
  3591.                     'Subject' => "changement sur le dossier locataire",
  3592.                     'TextPart' => $description,
  3593.                     'HTMLPart' => $description
  3594.                 ]
  3595.             ]
  3596.         ];
  3597.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3598.         $responsemail->success() && $responsemail->getData();
  3599.             // adminnotif 40
  3600.             $notifier $this->get('app.notifparse');
  3601.             $notifier->doAll(  40'Application',$application->getId(),'notif');
  3602.             // notification propriétaire
  3603.             $description ='Le dossier de votre locataire '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' a été contrôlé et validé par Wizi. Vous pouvez maintenant passer à la signature de votre contrat de location.';
  3604.             /*
  3605.             $notification = new Notification();
  3606.             $notification->setEmplacement('notif');
  3607.             $notification->setStatus(1);
  3608.             $notification->setUser($application->getFlat()->getOwnedBy());
  3609.             
  3610.             $notification->setDescription($description);
  3611.             $notification->setIcon('ion-ios-checkmark icon');
  3612.             $notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
  3613.             $em->persist($notification);
  3614.             */
  3615.             $em->flush();
  3616.             // sms
  3617.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3618.             $fields = array(
  3619.                 'apiKey'=> $apikey,
  3620.                 'sender' => 'Wizi',
  3621.                 'SMSList'=> array(
  3622.                     array(
  3623.                         'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
  3624.                         'message'=> $description,
  3625.                         'gamme' => 1
  3626.                     )
  3627.                 )
  3628.             );
  3629.             $curl curl_init();
  3630.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3631.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3632.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3633.             curl_setopt($curlCURLOPT_POST1);
  3634.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3635.             $result curl_exec($curl);
  3636.             curl_close($curl);
  3637.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3638.         $body = [
  3639.             'Messages' => [
  3640.                 [
  3641.                     'From' => [
  3642.                         'Email' => "laura@wizi.eu",
  3643.                         'Name' => "Laura de Wizi"
  3644.                     ],
  3645.                     'To' => [
  3646.                         [
  3647.                             'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
  3648.                             'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
  3649.                         ]
  3650.                     ],
  3651.                     'Subject' => "changement sur le dossier Wizi de votre locataire",
  3652.                     'TextPart' => $description,
  3653.                     'HTMLPart' => $description
  3654.                 ]
  3655.             ]
  3656.         ];
  3657.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3658.         $responsemail->success() && $responsemail->getData();
  3659.             // on envoie le mail au commercial :
  3660.             // $CommObject
  3661.             $to      $CommObject->getEmail();
  3662.             $subject 'Changement de statut dossier locataire';
  3663.             $message $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
  3664.             $headers 'From: laura@wizi.eu' "\r\n" .
  3665.                 'Reply-To: laura@wizi.eu' "\r\n" .
  3666.                 'X-Mailer: PHP/' phpversion();
  3667.             mail($to$subject$message$headers);
  3668.             // ici on test existance de signatures
  3669.             $contract $application->getContract();
  3670.             $docs $contract->getDocuments();
  3671.             foreach ($docs as $doc) {
  3672.                 //dump($doc->getCategory());
  3673.                 if($doc->getCategory() == 'contract'){
  3674.                     $signatures $doc->getSignatures();
  3675.                     foreach ($signatures as $sign) {
  3676.                         $userid $sign->getUser()->getId();
  3677.                         $uppuid $application->getUser()->getId();
  3678.                         $sdone $sign->getDone();
  3679.                         $renter $application->getUser();
  3680.                         $owner $application->getFlat()->getOwnedBy();
  3681.                         if($userid == $uppuid && $sdone != true){
  3682.                             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51'true, ['version' => 'v3.1']);
  3683.                             $body = [
  3684.                                 'Messages' => [
  3685.                                     [
  3686.                                         'From' => [
  3687.                                             'Email' => "laura@wizi.eu",
  3688.                                             'Name' => "Laura de Wizi"
  3689.                                         ],
  3690.                                         'To' => [
  3691.                                             [
  3692.                                                 'Email' => $renter->getEmail(),
  3693.                                                 'Name' => $renter->getFirstname()
  3694.                                             ]
  3695.                                         ],
  3696.                                         'TemplateID' => 551440,
  3697.                                         'TemplateLanguage' => true,
  3698.                                         'Subject' => "Bail signé par le proprietaire",
  3699.                                         'Variables' => json_decode('{
  3700.                                     "firstname": "' .  $renter->getFirstname()  . '",
  3701.                                     "title": "' .  $application->getFlat()->getTitle()  . '",
  3702.                                     "propname": "' .  $owner->getFirstname().' '.$owner->getName()  . '"
  3703.                                 }'true)
  3704.                                     ]
  3705.                                 ]
  3706.                             ];
  3707.                             $response $mj->post(Resources::$Email, ['body' => $body]);
  3708.                             $response->success() && $response->getData();
  3709.                         }
  3710.                     }
  3711.                 }
  3712.             }
  3713.         }
  3714.         if($application->getTaskdocstatus() != && $appsel == 2){
  3715.             // adminnotif 41
  3716.             $notifier $this->get('app.notifparse');
  3717.             $notifier->doAll(  41'Application',$application->getId(),'notif');
  3718.             // notification locataire
  3719.             $description ='Votre dossier de location a été contrôlé par Wizi. Malheureusement, il est incomplet. Connectez-vous à votre espace Wizi pour voir le détail et ajouter vos documents.';
  3720.             $description "Votre dossier de location vient d'être contrôle par Wizi. Il est incomplet.
  3721. Connectez-vous à votre espace Wizi pour voir le détail et ajouter les documents manquants.";
  3722.             /*
  3723.             $notification = new Notification();
  3724.             $notification->setEmplacement('contrat');
  3725.             $notification->setStatus(1);
  3726.             $notification->setUser($application->getUser());
  3727.             
  3728.             $notification->setDescription($description);
  3729.             $notification->setColor('#e74c3c');
  3730.             $notification->setIcon('far fa-thumbs-down icon');
  3731.             $notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
  3732.             $em->persist($notification);
  3733.             $em->flush();
  3734.             */
  3735.             // sms
  3736.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3737.             $fields = array(
  3738.                 'apiKey'=> $apikey,
  3739.                 'sender' => 'Wizi',
  3740.                 'SMSList'=> array(
  3741.                     array(
  3742.                         'phoneNumber'=> $application->getUser()->getMobilePhone(),
  3743.                         'message'=> $description,
  3744.                         'gamme' => 1
  3745.                     )
  3746.                 )
  3747.             );
  3748.             $curl curl_init();
  3749.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3750.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3751.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3752.             curl_setopt($curlCURLOPT_POST1);
  3753.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3754.             $result curl_exec($curl);
  3755.             curl_close($curl);
  3756.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3757.         $body = [
  3758.             'Messages' => [
  3759.                 [
  3760.                     'From' => [
  3761.                         'Email' => "laura@wizi.eu",
  3762.                         'Name' => "Laura de Wizi"
  3763.                     ],
  3764.                     'To' => [
  3765.                         [
  3766.                             'Email' => $application->getUser()->getEmail(),
  3767.                             'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
  3768.                         ]
  3769.                     ],
  3770.                     'Subject' => "changement sur le dossier Wizi ",
  3771.                     'TextPart' => $description,
  3772.                     'HTMLPart' => $description
  3773.                 ]
  3774.             ]
  3775.         ];
  3776.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3777.         $responsemail->success() && $responsemail->getData();
  3778.             // adminnotif 42
  3779.             $notifier $this->get('app.notifparse');
  3780.             $notifier->doAll(  42'Application',$application->getId(),'notif');
  3781.             // notification propriétaire
  3782.             $description ='Le dossier de votre candidat locataire '.
  3783.             $application->getUser()->getFirstname().' '.$application->getUser()->getName()
  3784.                 .' a été contrôlé par Wizi, Malheureusement il est incomplet, nous avons relancé votre locataire pour obtenir des documents complémentaires.';
  3785.             $description "Le dossier de ".
  3786.             $application->getUser()->getFirstname().' '.$application->getUser()->getName()
  3787.                 . " vient d'être contrôle par Wizi. Il est incomplet.
  3788. Nous venons de le relancer pour qu'il ajoute les documents manquants sur son espace Wizi. Vous serez informés en temps réel de l'évolution du statut de son dossier.";
  3789.             /*    
  3790.             $notification = new Notification();
  3791.             $notification->setEmplacement('notif');
  3792.             $notification->setStatus(1);
  3793.             $notification->setUser($application->getFlat()->getOwnedBy());
  3794.             
  3795.                 $notification->setDescription($description);
  3796.             $notification->setIcon('ion-ios-checkmark icon');
  3797.             $notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
  3798.             $em->persist($notification);
  3799.             $em->flush();
  3800.             */
  3801.             // sms
  3802.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3803.             $fields = array(
  3804.                 'apiKey'=> $apikey,
  3805.                 'sender' => 'Wizi',
  3806.                 'SMSList'=> array(
  3807.                     array(
  3808.                         'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
  3809.                         'message'=> $description,
  3810.                         'gamme' => 1
  3811.                     )
  3812.                 )
  3813.             );
  3814.             $curl curl_init();
  3815.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3816.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3817.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3818.             curl_setopt($curlCURLOPT_POST1);
  3819.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3820.             $result curl_exec($curl);
  3821.             curl_close($curl);
  3822.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3823.         $body = [
  3824.             'Messages' => [
  3825.                 [
  3826.                     'From' => [
  3827.                         'Email' => "laura@wizi.eu",
  3828.                         'Name' => "Laura de Wizi"
  3829.                     ],
  3830.                     'To' => [
  3831.                         [
  3832.                             'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
  3833.                             'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
  3834.                         ]
  3835.                     ],
  3836.                     'Subject' => "changement sur le dossier Wizi ",
  3837.                     'TextPart' => $description,
  3838.                     'HTMLPart' => $description
  3839.                 ]
  3840.             ]
  3841.         ];
  3842.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3843.         $responsemail->success() && $responsemail->getData();
  3844.             // on envoie le mail au commercial :
  3845.             // $CommObject
  3846.             $to      $CommObject->getEmail();
  3847.             $subject 'Changement de statut dossier locataire';
  3848.             $message $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
  3849.             $headers 'From: laura@wizi.eu' "\r\n" .
  3850.                 'Reply-To: laura@wizi.eu' "\r\n" .
  3851.                 'X-Mailer: PHP/' phpversion();
  3852.             mail($to$subject$message$headers);
  3853.         }
  3854.         if($application->getTaskdocstatus() != && $appsel == 3){
  3855.             // adminnotif 43
  3856.             $notifier $this->get('app.notifparse');
  3857.             $notifier->doAll(  43'Application',$application->getId(),'notif');
  3858.             // notification locataire
  3859.             $description ='Votre dossier de location a été contrôlé par Wizi. Malheureusement, il a été refusé, rapprochez vous de votre conseiller Wizi pour en savoir +';
  3860.             /*
  3861.             $notification = new Notification();
  3862.             $notification->setEmplacement('contrat');
  3863.             $notification->setStatus(1);
  3864.             $notification->setUser($application->getUser());
  3865.             
  3866.             $notification->setDescription($description);
  3867.             $notification->setColor('#e74c3c');
  3868.             $notification->setIcon('far fa-thumbs-down icon');
  3869.             $notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
  3870.             $em->persist($notification);
  3871.             $em->flush();
  3872.             */
  3873.             // sms
  3874.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3875.             $fields = array(
  3876.                 'apiKey'=> $apikey,
  3877.                 'sender' => 'Wizi',
  3878.                 'SMSList'=> array(
  3879.                     array(
  3880.                         'phoneNumber'=> $application->getUser()->getMobilePhone(),
  3881.                         'message'=> $description,
  3882.                         'gamme' => 1
  3883.                     )
  3884.                 )
  3885.             );
  3886.             $curl curl_init();
  3887.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3888.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3889.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3890.             curl_setopt($curlCURLOPT_POST1);
  3891.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3892.             $result curl_exec($curl);
  3893.             curl_close($curl);
  3894.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3895.         $body = [
  3896.             'Messages' => [
  3897.                 [
  3898.                     'From' => [
  3899.                         'Email' => "laura@wizi.eu",
  3900.                         'Name' => "Laura de Wizi"
  3901.                     ],
  3902.                     'To' => [
  3903.                         [
  3904.                             'Email' => $application->getUser()->getEmail(),
  3905.                             'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
  3906.                         ]
  3907.                     ],
  3908.                     'Subject' => "changement sur le dossier Wizi ",
  3909.                     'TextPart' => $description,
  3910.                     'HTMLPart' => $description
  3911.                 ]
  3912.             ]
  3913.         ];
  3914.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3915.         $responsemail->success() && $responsemail->getData();
  3916.             // adminnotif 44
  3917.             $notifier $this->get('app.notifparse');
  3918.             $notifier->doAll(  44'Application',$application->getId(),'notif');
  3919.             // notification propriétaire
  3920.             $description ='Le dossier de votre locataire '.
  3921.             $application->getUser()->getFirstname().' '.$application->getUser()->getName()
  3922.                 .' a été contrôlé par Wizi, Malheureusement, il a été refusé, rapprochez vous de votre conseiller Wizi pour en savoir +.';
  3923.             /*
  3924.             $notification = new Notification();
  3925.             $notification->setEmplacement('notif');
  3926.             $notification->setStatus(1);
  3927.             $notification->setUser($application->getFlat()->getOwnedBy());
  3928.             
  3929.                 $notification->setDescription($description);
  3930.             $notification->setIcon('ion-ios-checkmark icon');
  3931.             $notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
  3932.             $em->persist($notification);
  3933.             $em->flush();
  3934.             */
  3935.             // sms
  3936.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  3937.             $fields = array(
  3938.                 'apiKey'=> $apikey,
  3939.                 'sender' => 'Wizi',
  3940.                 'SMSList'=> array(
  3941.                     array(
  3942.                         'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
  3943.                         'message'=> $description,
  3944.                         'gamme' => 1
  3945.                     )
  3946.                 )
  3947.             );
  3948.             $curl curl_init();
  3949.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  3950.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  3951.             curl_setopt($curlCURLOPT_TIMEOUT10);
  3952.             curl_setopt($curlCURLOPT_POST1);
  3953.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  3954.             $result curl_exec($curl);
  3955.             curl_close($curl);
  3956.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  3957.         $body = [
  3958.             'Messages' => [
  3959.                 [
  3960.                     'From' => [
  3961.                         'Email' => "laura@wizi.eu",
  3962.                         'Name' => "Laura de Wizi"
  3963.                     ],
  3964.                     'To' => [
  3965.                         [
  3966.                             'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
  3967.                             'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
  3968.                         ]
  3969.                     ],
  3970.                     'Subject' => "changement sur le dossier Wizi ",
  3971.                     'TextPart' => $description,
  3972.                     'HTMLPart' => $description
  3973.                 ]
  3974.             ]
  3975.         ];
  3976.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  3977.         $responsemail->success() && $responsemail->getData();
  3978.             // on envoie le mail au commercial :
  3979.             // $CommObject
  3980.             $to      $CommObject->getEmail();
  3981.             $subject 'Changement de statut dossier locataire';
  3982.             $message $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
  3983.             $headers 'From: laura@wizi.eu' "\r\n" .
  3984.                 'Reply-To: laura@wizi.eu' "\r\n" .
  3985.                 'X-Mailer: PHP/' phpversion();
  3986.             mail($to$subject$message$headers);
  3987.         }
  3988.         if($application->getTaskdocstatus() != && $appsel == 4){
  3989.             // adminnotif 45
  3990.             $notifier $this->get('app.notifparse');
  3991.             $notifier->doAll(  45'Application',$application->getId(),'notif');
  3992.             // notification locataire
  3993.             $description ="Votre dossier de location a été contrôlé par Wizi. Un conseiller va vous appeler très rapidement pour finaliser l'étude de votre dossier, merci de votre disponibilité par téléphone ou SMS";
  3994.             /*
  3995.             $notification = new Notification();
  3996.             $notification->setEmplacement('contrat');
  3997.             $notification->setStatus(1);
  3998.             $notification->setUser($application->getUser());
  3999.             
  4000.             $notification->setDescription($description);
  4001.             $notification->setColor('#e74c3c');
  4002.             $notification->setIcon('far fa-thumbs-down icon');
  4003.             $notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
  4004.             $em->persist($notification);
  4005.             $em->flush();
  4006.             */
  4007.             // sms
  4008.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  4009.             $fields = array(
  4010.                 'apiKey'=> $apikey,
  4011.                 'sender' => 'Wizi',
  4012.                 'SMSList'=> array(
  4013.                     array(
  4014.                         'phoneNumber'=> $application->getUser()->getMobilePhone(),
  4015.                         'message'=> $description,
  4016.                         'gamme' => 1
  4017.                     )
  4018.                 )
  4019.             );
  4020.             $curl curl_init();
  4021.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  4022.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  4023.             curl_setopt($curlCURLOPT_TIMEOUT10);
  4024.             curl_setopt($curlCURLOPT_POST1);
  4025.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  4026.             $result curl_exec($curl);
  4027.             curl_close($curl);
  4028.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  4029.         $body = [
  4030.             'Messages' => [
  4031.                 [
  4032.                     'From' => [
  4033.                         'Email' => "laura@wizi.eu",
  4034.                         'Name' => "Laura de Wizi"
  4035.                     ],
  4036.                     'To' => [
  4037.                         [
  4038.                             'Email' => $application->getUser()->getEmail(),
  4039.                             'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
  4040.                         ]
  4041.                     ],
  4042.                     'Subject' => "changement sur le dossier Wizi ",
  4043.                     'TextPart' => $description,
  4044.                     'HTMLPart' => $description
  4045.                 ]
  4046.             ]
  4047.         ];
  4048.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  4049.         $responsemail->success() && $responsemail->getData();
  4050.             // adminnotif 46
  4051.             $notifier $this->get('app.notifparse');
  4052.             $notifier->doAll(  46'Application',$application->getId(),'notif');
  4053.             // notification propriétaire
  4054.             $description ='Le dossier de votre locataire '.
  4055.                 $application->getUser()->getFirstname().' '.$application->getUser()->getName().
  4056.                 " est en cours d'étude par Wizi. Nous prenons contact avec lui ce jour et reviendrons vers vous dans les 48H.";
  4057.             /*
  4058.             $notification = new Notification();
  4059.             $notification->setEmplacement('notif');
  4060.             $notification->setStatus(1);
  4061.             $notification->setUser($application->getFlat()->getOwnedBy());
  4062.             
  4063.             $notification->setDescription($description);
  4064.             $notification->setIcon('ion-ios-checkmark icon');
  4065.             $notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
  4066.             $em->persist($notification);
  4067.             $em->flush();
  4068.             */
  4069.             // sms
  4070.             $apikey 'cab64310293a12d7098233ff702dbcfcf66c784a';
  4071.             $fields = array(
  4072.                 'apiKey'=> $apikey,
  4073.                 'sender' => 'Wizi',
  4074.                 'SMSList'=> array(
  4075.                     array(
  4076.                         'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
  4077.                         'message'=> $description,
  4078.                         'gamme' => 1
  4079.                     )
  4080.                 )
  4081.             );
  4082.             $curl curl_init();
  4083.             curl_setopt($curlCURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
  4084.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  4085.             curl_setopt($curlCURLOPT_TIMEOUT10);
  4086.             curl_setopt($curlCURLOPT_POST1);
  4087.             curl_setopt($curlCURLOPT_POSTFIELDS,json_encode($fields));
  4088.             $result curl_exec($curl);
  4089.             curl_close($curl);
  4090.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
  4091.         $body = [
  4092.             'Messages' => [
  4093.                 [
  4094.                     'From' => [
  4095.                         'Email' => "laura@wizi.eu",
  4096.                         'Name' => "Laura de Wizi"
  4097.                     ],
  4098.                     'To' => [
  4099.                         [
  4100.                             'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
  4101.                             'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
  4102.                         ]
  4103.                     ],
  4104.                     'Subject' => "changement sur le dossier Wizi ",
  4105.                     'TextPart' => $description,
  4106.                     'HTMLPart' => $description
  4107.                 ]
  4108.             ]
  4109.         ];
  4110.         $responsemail $mj->post(Resources::$Email, ['body' => $body]);
  4111.         $responsemail->success() && $responsemail->getData();
  4112.             // on envoie le mail au commercial :
  4113.             // $CommObject
  4114.             $to      $CommObject->getEmail();
  4115.             $subject 'Changement de statut dossier locataire';
  4116.             $message $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
  4117.             $headers 'From: laura@wizi.eu' "\r\n" .
  4118.                 'Reply-To: laura@wizi.eu' "\r\n" .
  4119.                 'X-Mailer: PHP/' phpversion();
  4120.             mail($to$subject$message$headers);
  4121.         }
  4122.         $application->setTaskdoctxt($apptxt);
  4123.         $application->setTaskdocstatus($appsel);
  4124.         $em->persist($application);
  4125.         $em->flush();
  4126.         if($appsel == 0){
  4127.             $ctr $application->getContract();
  4128.             $ctr->setTaskdoctriger(1);
  4129.             $ctr->setTaskdocAt(new \DateTime());
  4130.             $em->persist($ctr);
  4131.             $em->flush();
  4132.         }
  4133.         
  4134.         $response = new Response();
  4135.         $response->setContent(json_encode($appsel));
  4136.         $response->setStatusCode('200');
  4137.         return $response;
  4138.     }
  4139.     /**
  4140.      *  micro task detailée
  4141.      *
  4142.      * @Route("/verifdoss/loaddata", name="verifdoss_loaddata", options={"expose"=true})
  4143.      * @Method({"GET","POST"})
  4144.      * @return Response
  4145.      */
  4146.     public function detailcandidaturesendloaddataAction(Request $request)
  4147.     {
  4148.         $em =  $this->getDoctrine->getManager();
  4149.         $verDossRepo =  $this->getDoctrine->getRepository('AppBundle:VerifDoss');
  4150.         $appid $this->get('request')->request->get('appid');
  4151.         $verifs $verDossRepo->findBy(array('applicationId' => $appid));
  4152.         $uptab = [];
  4153.         $ustab = [];
  4154.         foreach ($verifs as $vd) {
  4155.             if ($vd->getUserId() != null) {
  4156.                 $uptab[] = $vd;
  4157.             }else{
  4158.                 $ustab[] = $vd;
  4159.             }
  4160.         }
  4161.         /*
  4162.         $response = new Response();
  4163.         $response->setContent($verifs);
  4164.         $response->setStatusCode('200');
  4165.         return $response;
  4166.         */
  4167.         $results = [];
  4168.         $results['principal'] = $uptab;
  4169.         $results['secondaires'] = $ustab;
  4170.         $serializer SerializerBuilder::create()->build();
  4171.         if(count($verifs) > 0){
  4172.             $jsonStats $serializer->serialize($results'json');
  4173.         }else{
  4174.             $jsonStats $serializer->serialize('vide''json');
  4175.         }
  4176.         return new JsonResponse($jsonStats);
  4177.     }
  4178.     /**
  4179.      *  evaluation des prix par région
  4180.      *
  4181.      * @Route("/evaluateprice", name="evaluateprice", options={"expose"=true})
  4182.      * @Method({"GET","POST"})
  4183.      * @return Response
  4184.      */
  4185.     public function evaluatepriceAction(Request $request)
  4186.     {
  4187.         $totalprixmettrecarre 0;
  4188.         $prixmini 10000;
  4189.         $prixmax 0;
  4190.         $em =  $this->getDoctrine->getManager();
  4191.         $flatRepo =  $this->getDoctrine->getRepository('AppBundle:Flat');
  4192.         /*
  4193.         $params = [
  4194.             'status' => 2,
  4195.             'distance' => 2,
  4196.             'limit' => 3,
  4197.             'positions' => [ 0 =>
  4198.                 ['latitude' => $lat,
  4199.                     'longitude' => $long
  4200.                 ]
  4201.             ]
  4202.         ];
  4203.         */
  4204.         $postalcode '06100';
  4205.         $result $flatRepo->findBy(array('postalCode'=> $postalcode ));
  4206.         $cresult count($result);
  4207.         if(count($result) > 0){
  4208.             foreach ($result as $f) {
  4209.                 $prixHC $f->getCharges();
  4210.                 $surf $f->getSurface();
  4211.                 if($surf>0){
  4212.                     $prixmettrecarre = ($prixHC $surf);
  4213.                     $totalprixmettrecarre $totalprixmettrecarre $prixmettrecarre;
  4214.                     if($prixmini $prixmettrecarre && $prixmettrecarre !=0){
  4215.                         $prixmini $prixmettrecarre;
  4216.                     }
  4217.                     if($prixmax $prixmettrecarre){
  4218.                         $prixmax $prixmettrecarre;
  4219.                     }
  4220.                 }
  4221.             }
  4222.             $pmoymc $totalprixmettrecarre $cresult;
  4223.             $results = [
  4224.                 'nombre_flat' => $cresult,
  4225.                 'prix_mini' => $prixmini,
  4226.                 'prix_max' => $prixmax,
  4227.                 'prix_moyen' => $pmoymc,
  4228.             ];
  4229.             $serializer SerializerBuilder::create()->build();
  4230.             $jsonStats $serializer->serialize($results'json');
  4231.             return new JsonResponse($jsonStats);
  4232.         }
  4233.         $serializer SerializerBuilder::create()->build();
  4234.         $jsonStats $serializer->serialize('0 annonces''json');
  4235.         return new JsonResponse($jsonStats);
  4236.     }
  4237.     /**
  4238.      *  micro task verifier document de dossier
  4239.      *
  4240.      * @Route("/verifcontractdoss", name="verifcontractdoss_loaddata", options={"expose"=true})
  4241.      * @Method({"GET","POST"})
  4242.      * @return Response
  4243.      */
  4244.     public function verifdosscontreacAction(Request $request)
  4245.     {
  4246.         $em =  $this->getDoctrine->getManager();
  4247.         $verDossRepo =  $this->getDoctrine->getRepository('AppBundle:Contract');
  4248.         $contractid $this->get('request')->request->get('id');
  4249.         $cat $this->get('request')->request->get('cat');
  4250.         $val $this->get('request')->request->get('val');
  4251.         $contract $verDossRepo->find($contractid);
  4252.         switch ($cat) {
  4253.             case 'insurance':
  4254.                 $contract->setMrhvalide($val);
  4255.                 break;
  4256.             case 'diagnostic':
  4257.                 $contract->setDiagvalide($val);
  4258.                 break;
  4259.             case 'proof_of_ownership':
  4260.                 $contract->setPropvalide($val);
  4261.                 break;
  4262.             case 'otheradmin':
  4263.                 $contract->setUtilvalide($val);
  4264.                 break;
  4265.         }
  4266.         $em->persist($contract);
  4267.         $em->flush();
  4268.         $serializer SerializerBuilder::create()->build();
  4269.         $jsonStats $serializer->serialize('vide''json');
  4270.         return new JsonResponse($jsonStats);
  4271.     }
  4272.     /**
  4273.      * Afficher agenda visites
  4274.      *
  4275.      * @Route("/viewrdvvisite", name="viewrdvvisite")
  4276.      * @return Response
  4277.      */
  4278.     public function viewVisiteRdvAction()
  4279.     {
  4280.         $em =  $this->getDoctrine->getManager();
  4281.         $VisiteDates =  $this->getDoctrine->getRepository('AppBundle:VisiteDate')->findAll();
  4282.         $data =  array();
  4283.         return $this->render('Extranet/viewrdvvisite.html.twig', [
  4284.             'data' => $data,
  4285.         ]);
  4286.     }
  4287.     /**
  4288.      * Récupérer les rdvs
  4289.      * @param Request $request
  4290.      * @return JsonResponse
  4291.      *
  4292.      * @Route("/viewrdvvisitejson", name="viewrdvvisitejson", options={"expose"=true})
  4293.      *
  4294.      */
  4295.     public function getviewrdvvisitejsonAction()
  4296.     {
  4297.         /*
  4298.         $em =  $this->getDoctrine->getManager();
  4299.         $VisiteDates =  $this->getDoctrine->getRepository('AppBundle:VisiteDate')->findAll();
  4300.         $serializer = SerializerBuilder::create()->build();
  4301.         $jsonStats = $serializer->serialize($VisiteDates, 'json');
  4302.         */
  4303.         $namedb $this->getParameter('dbreqpdo');
  4304.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4305.         $sthd $bdd->prepare("SELECT own.firstname as ownerFirstname, 
  4306.                                 own.firstname as ownerName, 
  4307.                                 rent.firstname as renterFirstname, 
  4308.                                 rent.name as renterName, 
  4309.                                 vd.date,
  4310.                                 vd.id,
  4311.                                 flat.id as flatId, 
  4312.                                 application.id as applicationId, 
  4313.                                 vd.time  
  4314.                             FROM app.visite_date as vd
  4315.                             INNER JOIN app.application as application on application.id = application_id
  4316.                             INNER JOIN app.flat as flat on flat.id = application.flat
  4317.                             INNER JOIN app.user as own on own.id = flat.owned_by_id
  4318.                             INNER JOIN app.user as rent on rent.id = application.user");
  4319.         $sthd->execute();
  4320.         $resultd $sthd->fetchAll(\PDO::FETCH_ASSOC);
  4321.         return new JsonResponse($resultd);
  4322.     }
  4323.     /**
  4324.      * [SEARCH BO] Retrouver utilisateur
  4325.      *
  4326.      * @param Request $request
  4327.      * @Route("/bosearch/userquery", name="bosearchuserquery", options={"expose"=true})
  4328.      *
  4329.      * @return JsonResponse
  4330.      */
  4331.     public function getBoSearchUserQueryAction(Request $request)
  4332.     {
  4333.         $namedb $this->getParameter('dbreqpdo');
  4334.         $query $request->get('query');
  4335.         $explodedquery explode(' '$query);
  4336.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4337.         // Search in user
  4338.         $sqlQuery "SELECT u.firstname, u.name, u.id FROM ".$namedb.".user as u WHERE ";
  4339.         $UserLocSqlQuery "SELECT u.name, u.firstname, u.owned_by_id as id FROM ".$namedb.".user_loc as u WHERE ";
  4340.         $UserPropSqlQuery "SELECT u.name, u.firstname, f.owned_by_id as id FROM ".$namedb.".flat_prop as u INNER JOIN ".$namedb.".flat AS f ON u.flat_ref_id = f.id WHERE ";
  4341.         $SciPropSqlQuery "SELECT u.name, u.firstname, u.id, f.companyName FROM ".$namedb.".flat as f INNER JOIN ".$namedb.".user AS u ON u.id = f.owned_by_id WHERE ";
  4342.         foreach ($explodedquery as $key => $q){
  4343.             if($key 0){
  4344.                 $sqlQuery .= " AND ";
  4345.                 $UserLocSqlQuery .= " AND ";
  4346.                 $UserPropSqlQuery .= " AND ";
  4347.                 $SciPropSqlQuery .= " AND ";
  4348.             }
  4349.             $sqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
  4350.             $UserLocSqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
  4351.             $UserPropSqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
  4352.             $SciPropSqlQuery .= "(f.companyName LIKE '%".$q."%')";
  4353.         }
  4354.         $sqlQuery .= " ORDER BY u.id DESC LIMIT 0, 10";
  4355.         $UserLocSqlQuery .= " ORDER BY u.owned_by_id DESC LIMIT 0, 5";
  4356.         $UserPropSqlQuery .= " ORDER BY f.owned_by_id DESC LIMIT 0, 5";
  4357.         $SciPropSqlQuery .= " GROUP BY u.id ORDER BY f.owned_by_id DESC LIMIT 0, 5";
  4358.         // Execution des query
  4359.         $sthd $bdd->prepare($sqlQuery);
  4360.         $sthd->execute();
  4361.         $result $sthd->fetchAll(\PDO::FETCH_ASSOC);
  4362.         $userlocsthd $bdd->prepare($UserLocSqlQuery);
  4363.         $userlocsthd->execute();
  4364.         $userlocresult $userlocsthd->fetchAll(\PDO::FETCH_ASSOC);
  4365.         $flatpropsthd $bdd->prepare($UserPropSqlQuery);
  4366.         $flatpropsthd->execute();
  4367.         $flatpropresult $flatpropsthd->fetchAll(\PDO::FETCH_ASSOC);
  4368.         $scisthd $bdd->prepare($SciPropSqlQuery);
  4369.         $scisthd->execute();
  4370.         $sciresult $scisthd->fetchAll(\PDO::FETCH_ASSOC);
  4371.         $sec = [];
  4372.         foreach ($userlocresult as $u){
  4373.             array_push($sec$u);
  4374.         }
  4375.         foreach ($flatpropresult as $f){
  4376.             array_push($sec$f);
  4377.         }
  4378.         foreach ($sciresult as $s){
  4379.             array_push($sec$s);
  4380.         }
  4381.         $resultd = [
  4382.             'user' => $result,
  4383.             'sec' => $sec
  4384.         ];
  4385.         return new JsonResponse($resultd);
  4386.     }
  4387.     /**
  4388.      * [SEARCH BO] Retrouver connections via user
  4389.      *
  4390.      * @param Request $request
  4391.      * @Route("/bosearch/fromuser", name="bosearchfromuser", options={"expose"=true})
  4392.      *
  4393.      * @return JsonResponse
  4394.      */
  4395.     public function getBoSearchFromUserAction(Request $request)
  4396.     {
  4397.         $namedb $this->getParameter('dbreqpdo');
  4398.         $userid $request->get('userid');
  4399.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4400.         $UserSqlQuery "SELECT u.name, u.firstname, u.id FROM ".$namedb.".user as u WHERE u.id = ".$userid;
  4401.         $Usersthd $bdd->prepare($UserSqlQuery);
  4402.         $Usersthd->execute();
  4403.         $user $Usersthd->fetchAll(\PDO::FETCH_ASSOC);
  4404.         $FlatSqlQuery "SELECT f.id, f.title, f.city, f.status FROM ".$namedb.".flat as f WHERE f.owned_by_id = ".$userid." ORDER BY FIELD(f.status, 2, 3, 1) LIMIT 0, 10";
  4405.         $Flatsthd $bdd->prepare($FlatSqlQuery);
  4406.         $Flatsthd->execute();
  4407.         $flats $Flatsthd->fetchAll(\PDO::FETCH_ASSOC);
  4408.         $ContractSqlQuery "SELECT renter.firstname as renter_firstname, renter.name as renter_name, renter.id as renter_id, owner.firstname as owner_firstname, owner.name as owner_name, owner.id as owner_id, c.status, c.id as contract_id 
  4409.         FROM ".$namedb.".contract as c 
  4410.         INNER JOIN ".$namedb.".application as a on c.application_id = a.id
  4411.         INNER JOIN ".$namedb.".user as renter on a.user = renter.id
  4412.         INNER JOIN ".$namedb.".flat as f on a.flat = f.id
  4413.         INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
  4414.         WHERE owner.id = ".$userid."
  4415.         OR renter.id = ".$userid."
  4416.         ORDER BY FIELD(c.status, 2, 1, 3, 4)
  4417.         LIMIT 0, 10";
  4418.         $Contractsthd $bdd->prepare($ContractSqlQuery);
  4419.         $Contractsthd->execute();
  4420.         $contracts $Contractsthd->fetchAll(\PDO::FETCH_ASSOC);
  4421.         $ApplicarionSqlQuery "SELECT  renter.firstname as renter_firstname, renter.name as renter_name, renter.id as renter_id, owner.firstname as owner_firstname, owner.name as owner_name, owner.id as owner_id, a.id, f.title, a.status
  4422.         FROM ".$namedb.".application as a
  4423.         INNER JOIN ".$namedb.".user as renter on a.user = renter.id
  4424.         INNER JOIN ".$namedb.".flat as f on a.flat = f.id
  4425.         INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
  4426.         WHERE (owner.id = ".$userid."
  4427.         OR renter.id = ".$userid.")
  4428.         AND a.status <> 3
  4429.         ORDER BY FIELD(a.status, 5, 2)
  4430.         LIMIT 0, 10";
  4431.         $Applicarionsthd $bdd->prepare($ApplicarionSqlQuery);
  4432.         $Applicarionsthd->execute();
  4433.         $applications $Applicarionsthd->fetchAll(\PDO::FETCH_ASSOC);
  4434.         $result = [
  4435.             'user' => $user,
  4436.             'flats' => $flats,
  4437.             'contracts' => $contracts,
  4438.             'applications' => $applications
  4439.         ];
  4440.         return new JsonResponse($result);
  4441.     }
  4442.     /**
  4443.      * [SEARCH BO] Retrouver connections via id
  4444.      *
  4445.      * @param Request $request
  4446.      * @Route("/bosearch/fromid", name="bosearchfromid", options={"expose"=true})
  4447.      *
  4448.      * @return JsonResponse
  4449.      */
  4450.     public function getBoSearchFromIdAction(Request $request)
  4451.     {
  4452.         $namedb $this->getParameter('dbreqpdo');
  4453.         $id $request->get('id');
  4454.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4455.         $UserSqlQuery "SELECT u.name, u.firstname, u.id FROM ".$namedb.".user as u WHERE u.id = ".$id;
  4456.         $Usersthd $bdd->prepare($UserSqlQuery);
  4457.         $Usersthd->execute();
  4458.         $user $Usersthd->fetchAll(\PDO::FETCH_ASSOC);
  4459.         $FlatSqlQuery "SELECT f.id, f.title, f.city, f.status, u.firstname, u.name FROM ".$namedb.".flat as f INNER JOIN ".$namedb.".user as u on u.id = f.owned_by_id WHERE f.id = ".$id;
  4460.         $Flatsthd $bdd->prepare($FlatSqlQuery);
  4461.         $Flatsthd->execute();
  4462.         $flats $Flatsthd->fetchAll(\PDO::FETCH_ASSOC);
  4463.         $ContractSqlQuery "SELECT renter.firstname as renter_firstname, renter.name as renter_name, renter.id as renter_id, owner.firstname as owner_firstname, owner.name as owner_name, owner.id as owner_id, c.status, c.id as contract_id 
  4464.         FROM ".$namedb.".contract as c 
  4465.         INNER JOIN ".$namedb.".application as a on c.application_id = a.id
  4466.         INNER JOIN ".$namedb.".user as renter on a.user = renter.id
  4467.         INNER JOIN ".$namedb.".flat as f on a.flat = f.id
  4468.         INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
  4469.         WHERE c.id = ".$id;
  4470.         $Contractsthd $bdd->prepare($ContractSqlQuery);
  4471.         $Contractsthd->execute();
  4472.         $contracts $Contractsthd->fetchAll(\PDO::FETCH_ASSOC);
  4473.         $ApplicarionSqlQuery "SELECT  renter.firstname as renter_firstname, renter.name as renter_name, renter.id as renter_id, owner.firstname as owner_firstname, owner.name as owner_name, owner.id as owner_id, a.id, f.title, a.status
  4474.         FROM ".$namedb.".application as a
  4475.         INNER JOIN ".$namedb.".user as renter on a.user = renter.id
  4476.         INNER JOIN ".$namedb.".flat as f on a.flat = f.id
  4477.         INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
  4478.         WHERE a.id = " .$id;
  4479.         $Applicarionsthd $bdd->prepare($ApplicarionSqlQuery);
  4480.         $Applicarionsthd->execute();
  4481.         $applications $Applicarionsthd->fetchAll(\PDO::FETCH_ASSOC);
  4482.         $result = [
  4483.             'user' => $user,
  4484.             'flats' => $flats,
  4485.             'contracts' => $contracts,
  4486.             'applications' => $applications
  4487.         ];
  4488.         return new JsonResponse($result);
  4489.     }
  4490.     /**
  4491.      * Afficher la page des stats admin
  4492.      *
  4493.      * @Route("/statsAdmin", name="statsAdmin")
  4494.      * @return Response
  4495.      */
  4496.     public function statsAdminAction()
  4497.     {
  4498.         $em =  $this->getDoctrine;
  4499.         $stats1 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
  4500.         $stats2 $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
  4501.         $stats2array = [];
  4502.         foreach ($stats2 as $key => $stat2){
  4503.             $user $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
  4504.             $stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
  4505.             $stats2array[$key]['type'] = $stat2->getType();
  4506.             $stats2array[$key]['valeur'] = $stat2->getValeur();
  4507.             $stats2array[$key]['target'] = $stat2->getTarget();
  4508.         }
  4509.         return $this->render('stats/statsAdmin.html.twig', array(
  4510.             'stats1' => $stats1,
  4511.             'stats2' => $stats2array
  4512.         ));
  4513.     }
  4514.     /**
  4515.      * envoyer des message helpdesk
  4516.      *
  4517.      * @Route("/chathelpdesk", name="chathelpdesk", options={"expose"=true})
  4518.      * @Method({"GET","POST"})
  4519.      * @return Response
  4520.      */
  4521.     public function chathelpdeskAction(Request $request)
  4522.     {
  4523.         $em =  $this->getDoctrine->getManager();
  4524.         $madate = new \DateTime();
  4525.         $hmess = new HelpMessage();
  4526.         $hmess->setCreatedAt($madate);
  4527.         $hmess->setStatus(1);
  4528.         $hmess->setDestinataire(1);
  4529.         $hmess->setExpediteur($request->get('token'));
  4530.         $hmess->setMessage($request->get('message'));
  4531.         $em->persist($hmess);
  4532.         $em->flush();
  4533.         $tr = [
  4534.             'message' => $request->get('message'),
  4535.             'token' => $request->get('token'),
  4536.             'maxid' => $hmess->getId()
  4537.         ];
  4538.         $response = new JsonResponse(json_encode($tr));
  4539.         return $response;
  4540.     }
  4541.     /**
  4542.      * envoyer des message helpdesk
  4543.      *
  4544.      * @Route("/chathelpdeskfbo", name="chathelpdeskfbo", options={"expose"=true})
  4545.      * @Method({"GET","POST"})
  4546.      * @return Response
  4547.      */
  4548.     public function chathelpdeskfboAction(Request $request)
  4549.     {
  4550.         $em =  $this->getDoctrine->getManager();
  4551.         $namedb $this->getParameter('dbreqpdo');
  4552.         $token $request->get('token');
  4553.         $UserSqlQuery "UPDATE ".$namedb.".help_message SET status = 2 WHERE expediteur = '".$token."' ";
  4554.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4555.         $re $bdd->prepare($UserSqlQuery);
  4556.         $re->execute();
  4557.         $madate = new \DateTime();
  4558.         $hmess = new HelpMessage();
  4559.         $hmess->setCreatedAt($madate);
  4560.         $hmess->setStatus(1);
  4561.         $hmess->setDestinataire($request->get('token'));
  4562.         $hmess->setExpediteur(1);
  4563.         $hmess->setMessage($request->get('message'));
  4564.         $em->persist($hmess);
  4565.         $em->flush();
  4566.         $tr = [
  4567.             'message' => $request->get('message'),
  4568.             'token' => $request->get('token'),
  4569.         ];
  4570.         $response = new JsonResponse(json_encode($tr));
  4571.         return $response;
  4572.     }
  4573.     /**
  4574.      * envoyer des message helpdesk
  4575.      *
  4576.      * @Route("/chathelpdeskvtoken", name="chathelpdeskvtoken", options={"expose"=true})
  4577.      * @Method({"GET","POST"})
  4578.      * @return Response
  4579.      */
  4580.     public function chathelpdeskvtokenAction(Request $request)
  4581.     {
  4582.         $namedb $this->getParameter('dbreqpdo');
  4583.         $token $request->get('token');
  4584.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4585.         $UserSqlQuery "SELECT expediteur FROM ".$namedb.".help_message as u WHERE u.expediteur = ".$token;
  4586.         $re $bdd->prepare($UserSqlQuery);
  4587.         $re->execute();
  4588.         $d $re->fetchAll(\PDO::FETCH_ASSOC);
  4589.         if(count($d)> 0){
  4590.             $response = new JsonResponse(json_encode('false'));
  4591.             return $response;
  4592.         }else{
  4593.             $response = new JsonResponse(json_encode('true'));
  4594.             return $response;
  4595.         }
  4596.     }
  4597.     /**
  4598.      * envoyer des message helpdesk
  4599.      *
  4600.      * @Route("/chathelpdeskallmessages", name="chathelpdeskallmessages", options={"expose"=true})
  4601.      * @Method({"GET","POST"})
  4602.      * @return Response
  4603.      */
  4604.     public function chathelpdeskallmessagesAction(Request $request)
  4605.     {
  4606.         $namedb $this->getParameter('dbreqpdo');
  4607.         $token $request->get('token');
  4608.         $maxid $request->get('maxid');
  4609.         if ($maxid !== 'false') {
  4610.             $UserSqlQuery "SELECT * FROM ".$namedb.".help_message as u WHERE (u.expediteur = '".
  4611.                 $token."' OR u.destinataire = '".$token."') and u.id > ".(int)$maxid;
  4612.         }
  4613.         else
  4614.         {
  4615.             $UserSqlQuery "SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$token."' OR u.destinataire = '".$token."' ";
  4616.         }
  4617.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4618.         $re $bdd->prepare($UserSqlQuery);
  4619.         $re->execute();
  4620.         $d $re->fetchAll(\PDO::FETCH_ASSOC);
  4621.         $response = new JsonResponse($d);
  4622.         return $response;
  4623.     }
  4624.     /**
  4625.      * envoyer des message helpdesk
  4626.      *
  4627.      * @Route("/admchathelpdeskboard", name="chathelpdeskboard", options={"expose"=true})
  4628.      * @Method({"GET","POST"})
  4629.      * @param Request $request
  4630.      * @return Response
  4631.      */
  4632.     public function chathelpdeskboardAction(Request $request)
  4633.     {
  4634.         $namedb $this->getParameter('dbreqpdo');
  4635.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4636.         $sqlconv "SELECT distinct expediteur FROM app.help_message where expediteur <> 1";
  4637.         $re $bdd->prepare($sqlconv);
  4638.         $re->execute();
  4639.         $convs $re->fetchAll(\PDO::FETCH_ASSOC);
  4640.         $data= [];
  4641.         foreach ($convs as $conv){
  4642.             $sqlmess ="SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$conv['expediteur']
  4643.                 ."' OR u.destinataire = '".$conv['expediteur']."' ";
  4644.             $rem $bdd->prepare($sqlmess);
  4645.             $rem->execute();
  4646.             $messages $rem->fetchAll(\PDO::FETCH_ASSOC);
  4647.             $data[$conv['expediteur']] = $messages;
  4648.         }
  4649.         return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
  4650.     }
  4651.     /**
  4652.      * envoyer des message helpdesk
  4653.      *
  4654.      * @Route("/admtestcompareface", name="admtestcompareface", options={"expose"=true})
  4655.      * @Method({"GET","POST"})
  4656.      * @param Request $request
  4657.      * @return Response
  4658.      */
  4659.     public function admtestcomparefaceAction(Request $request)
  4660.     {
  4661.         $namedb $this->getParameter('dbreqpdo');
  4662.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4663.         $sqlconv "SELECT distinct expediteur FROM app.help_message where expediteur <> 1";
  4664.         $re $bdd->prepare($sqlconv);
  4665.         $re->execute();
  4666.         $convs $re->fetchAll(\PDO::FETCH_ASSOC);
  4667.         $data= [];
  4668.         foreach ($convs as $conv){
  4669.             $sqlmess ="SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$conv['expediteur']
  4670.                 ."' OR u.destinataire = '".$conv['expediteur']."' ";
  4671.             $rem $bdd->prepare($sqlmess);
  4672.             $rem->execute();
  4673.             $messages $rem->fetchAll(\PDO::FETCH_ASSOC);
  4674.             $data[$conv['expediteur']] = $messages;
  4675.         }
  4676.         $args = [
  4677.             'credentials' => [
  4678.                 'key' => 'AKIAUHKWPN22W5Z4BQJM',
  4679.                 'secret' => 'DFcqs/4zwpBjBOAQ791N9twddebeHGk89DBhsHJJ'
  4680.             ],
  4681.             'region' => 'us-east-1',
  4682.             'version' => 'latest'
  4683.         ];
  4684.         $client = new RekognitionClient($args);
  4685.         $result $client->compareFaces([
  4686.             'SimilarityThreshold' => 70,
  4687.             'SourceImage' => [
  4688.                 'Bytes' => file_get_contents('recoimg/1.jpg')
  4689.             ],
  4690.             'TargetImage' => [
  4691.                 'Bytes' => file_get_contents('recoimg/2.jpg')
  4692.             ]
  4693.         ]);
  4694.         dump($result);
  4695.         return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
  4696.     }
  4697.     /**
  4698.      * envoyer des message helpdesk
  4699.      *
  4700.      * @Route("/chathelpdeskfaq", name="chathelpdeskfaq", options={"expose"=true})
  4701.      * @Method({"GET","POST"})
  4702.      * @return Response
  4703.      */
  4704.     public function chathelpdeskfaqAction(Request $request)
  4705.     {
  4706.         $namedb $this->getParameter('dbreqpdo');
  4707.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4708.         $sqlfaq "SELECT * FROM app.smart_faq";
  4709.         $re $bdd->prepare($sqlfaq);
  4710.         $re->execute();
  4711.         $faq $re->fetchAll(\PDO::FETCH_ASSOC);
  4712.         $tr = [
  4713.             'faq' => $faq
  4714.         ];
  4715.         $response = new JsonResponse(json_encode($tr));
  4716.         return $response;
  4717.     }
  4718.     /**
  4719.      * envoyer des message helpdesk
  4720.      *
  4721.      * @Route("/chathelpdeskfaqask", name="chathelpdeskfaqask", options={"expose"=true})
  4722.      * @Method({"GET","POST"})
  4723.      * @return Response
  4724.      */
  4725.     public function chathelpdeskfaqaskAction(Request $request)
  4726.     {
  4727.         $message $request->get('message');
  4728.         $namedb $this->getParameter('dbreqpdo');
  4729.         $bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8''root''ahv2Ohchaik0');
  4730.         $sqlfaq "SELECT * FROM app.smart_faq";
  4731.         $re $bdd->prepare($sqlfaq);
  4732.         $re->execute();
  4733.         $faqs $re->fetchAll(\PDO::FETCH_ASSOC);
  4734.         $faqres = [];
  4735.         foreach ($faqs as $faq){
  4736.             $tags $faq['tags'];
  4737.             $tagsTab explode(',',$tags);
  4738.             $tagcount 0;
  4739.             foreach ($tagsTab as $t){
  4740.                 $pos strpos($message$t);
  4741.                 if ($pos === false){
  4742.                 }else{
  4743.                     $tagcount $tagcount +1;
  4744.                 }
  4745.             }
  4746.             if($tagcount == ){
  4747.                 if ($faq["categorie"] != "ia") {
  4748.                     $faqres[] = $faq;
  4749.                 }
  4750.             } elseif ($tagcount >= 3) {
  4751.                 /* si on determine que la question est claire on fait repondre direct par le bot */
  4752.                 $em =  $this->getDoctrine->getManager();
  4753.                 $madate = new \DateTime();
  4754.                 $hmess = new HelpMessage();
  4755.                 $hmess->setCreatedAt($madate);
  4756.                 $hmess->setStatus(1);
  4757.                 $hmess->setDestinataire($request->get('token'));
  4758.                 $hmess->setExpediteur(1);
  4759.                 $hmess->setMessage($faq['reponse']);
  4760.                 $em->persist($hmess);
  4761.                 $em->flush();
  4762.                 $tr = [];
  4763.                 $response = new JsonResponse($tr);
  4764.                 return $response;
  4765.             }
  4766.         }
  4767.         $tr = [
  4768.             $faqres
  4769.         ];
  4770.         $response = new JsonResponse($tr);
  4771.         return $response;
  4772.     }
  4773.     /**
  4774.      * compter les quittances a fournir
  4775.      *
  4776.      * @param Request $request
  4777.      * @return JsonResponse
  4778.      * @Route("/countdemandesdequittances", name="countdemandesdequittances", options={"expose"=true})
  4779.      * @Method({"GET","POST"})
  4780.      */
  4781.     public function countdemandesdequittancesAction()
  4782.     {
  4783.         $namedb $this->getParameter('dbreqpdo');
  4784.         $udb $this->getParameter('userreqpdo');
  4785. $pdb $this->getParameter('passreqpdo');
  4786. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  4787.         $comuser $this->getUser();
  4788.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  4789.         /*
  4790.                 $sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
  4791.         f.title, f.companyName as flatcompanyName, u.firstname, u.name, u.id as userid, f.price ,f.city as flatcity, f.created_at as flatcreated, f.publish_at, f.offre, f.offre_vendue
  4792.         FROM app.user as u
  4793.         inner join app.flat as f on u.id = f.owned_by_id";
  4794.         */
  4795.         $sql "SELECT count(*) as res
  4796. FROM app.quittance_ask as u ";
  4797.         $condition ' where ( status = 1  )  ';
  4798.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  4799.         $sthd $bdd->prepare($sql.$condition);
  4800.         $sthd->execute();
  4801.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  4802.         //return New JsonResponse($comuser->getUsername());
  4803.         return New JsonResponse($max); //
  4804.     }
  4805.     /**
  4806.      * compter les rapports de gérance a fournir
  4807.      *
  4808.      * @param Request $request
  4809.      * @return JsonResponse
  4810.      * @Route("/countdemandesrapportgerance", name="countdemandesrapportgerance", options={"expose"=true})
  4811.      * @Method({"GET","POST"})
  4812.      */
  4813.     public function countdemandesrapportgeranceAction()
  4814.     {
  4815.         $namedb $this->getParameter('dbreqpdo');
  4816.         $udb $this->getParameter('userreqpdo');
  4817. $pdb $this->getParameter('passreqpdo');
  4818. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  4819.         $comuser $this->getUser();
  4820.         $suivipar $comuser->getId() == '29896' $comuser->getId();
  4821.         /*
  4822.                 $sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
  4823.         f.title, f.companyName as flatcompanyName, u.firstname, u.name, u.id as userid, f.price ,f.city as flatcity, f.created_at as flatcreated, f.publish_at, f.offre, f.offre_vendue
  4824.         FROM app.user as u
  4825.         inner join app.flat as f on u.id = f.owned_by_id";
  4826.         */
  4827.         $sql "SELECT count(*) as res
  4828. FROM app.rapport_gerance_ask as u ";
  4829.         $condition ' where ( status = 1  )  ';
  4830.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  4831.         $sthd $bdd->prepare($sql.$condition);
  4832.         $sthd->execute();
  4833.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  4834.         //return New JsonResponse($comuser->getUsername());
  4835.         return New JsonResponse($max); //
  4836.     }
  4837.     /**
  4838.      * Generer un sepa depuis le BO our un contrat
  4839.      *
  4840.      * @param Request $request
  4841.      * @return JsonResponse
  4842.      * @Route("/majpreavistraitement", name="majpreavistraitement", options={"expose"=true})
  4843.      * @Method({"GET","POST"})
  4844.      */
  4845.     public function majpreavistraitementAction(Request $request)
  4846.     {
  4847.         $arr $_POST['preavis'];
  4848.         $id $arr['id'];
  4849.         $traitement $arr['traitement'];
  4850.         $contractid $_POST['cid'];
  4851.         $em =  $this->getDoctrine->getManager();
  4852.         $PreavisSortie =  $this->getDoctrine->getRepository('AppBundle:PreavisSortie')->find($id);
  4853.         $contract =  $this->getDoctrine->getRepository('AppBundle:Contract')->find($contractid);
  4854.         $PreavisSortie->setTraitement($traitement);
  4855.         $em->persist($PreavisSortie);
  4856.         $em->flush();
  4857.         if($PreavisSortie->getTraitement() == 2){
  4858.             // préavis accepté
  4859.             /*
  4860.             mail locataire :
  4861.             votre préavis de depart à bien été pris en compte il est accepté
  4862.             lien vers le contrat coté locataire
  4863.             https://desk.wizi.eu/#/app/contract_renter/2515/menu
  4864.             */
  4865.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51'true, ['version' => 'v3.1']);
  4866.             $mailto $contract->getApplication()->getUser()->getEmail();
  4867.             $emailtoname $contract->getApplication()->getUser()->getName();
  4868.             $demandeur $contract->getApplication()->getUser()->getFirstname();
  4869.             $iddemande $contract->getId();
  4870.             // https://desk.wizi.eu/#/app/contract_owner/{{var:iddemande}}/menu
  4871.             $body = [
  4872.                 'Messages' => [
  4873.                     [
  4874.                         'From' => [
  4875.                             'Email' => "laura@wizi.eu",
  4876.                             'Name' => "Laura de Wizi"
  4877.                         ],
  4878.                         'To' => [
  4879.                             [
  4880.                                 'Email' => $mailto,
  4881.                                 'Name' => $emailtoname
  4882.                             ]
  4883.                         ],
  4884.                         'TemplateID' => 1556106,
  4885.                         'TemplateLanguage' => true,
  4886.                         'Subject' => "Votre préavis de départ est accepté",
  4887.                         'Variables' => json_decode('
  4888.                             {"demandeur": "' $demandeur '",
  4889.                             "iddemande": "' 'home' '"
  4890.                             }'true)
  4891.                     ]
  4892.                 ]
  4893.             ];
  4894.             $response $mj->post(Resources::$Email, ['body' => $body]);
  4895.             $response->success() && $response->getData();
  4896.             /*
  4897.             mail commercial :
  4898.             le locataire d'un de vos contrat vient de se faire valider un préavis de départ
  4899.             lien vers le contrat coté BO
  4900.             https://app.wizi.eu/contract/edit/2394
  4901.             */
  4902.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51'true, ['version' => 'v3.1']);
  4903.             $usercom =  $this->getDoctrine->getRepository('AppBundle:User')->find($contract->getApplication()->getFlat()->getOwnedBy()->getSuivipar());
  4904.             $mailto $usercom->getEmail();
  4905.             $emailtoname $usercom->getName();
  4906.             $demandeur $contract->getApplication()->getUser()->getFirstname();
  4907.             $iddemande $contract->getId();
  4908.             $body = [
  4909.                 'Messages' => [
  4910.                     [
  4911.                         'From' => [
  4912.                             'Email' => "laura@wizi.eu",
  4913.                             'Name' => "Laura de Wizi"
  4914.                         ],
  4915.                         'To' => [
  4916.                             [
  4917.                                 'Email' => $mailto,
  4918.                                 'Name' => $emailtoname
  4919.                             ]
  4920.                         ],
  4921.                         'TemplateID' => 1556091,
  4922.                         'TemplateLanguage' => true,
  4923.                         'Subject' => "Nouveau Préavis de départ accepté",
  4924.                         'Variables' => json_decode('
  4925.                             {"demandeur": "' $demandeur '",
  4926.                             "iddemande": "' $iddemande '"
  4927.                             }'true)
  4928.                     ]
  4929.                 ]
  4930.             ];
  4931.             $response $mj->post(Resources::$Email, ['body' => $body]);
  4932.             $response->success() && $response->getData();
  4933.             /*
  4934.             mail propriétaire :
  4935.             Votre locataire vient de déposer un préavis de depart validé par Wizi
  4936.             https://desk.wizi.eu/#/app/contract_owner/2476/menu
  4937.             */
  4938.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51'true, ['version' => 'v3.1']);
  4939.             $mailto $contract->getApplication()->getFlat()->getOwnedBy()->getEmail();
  4940.             $emailtoname $contract->getApplication()->getFlat()->getOwnedBy()->getName();
  4941.             $demandeur $contract->getApplication()->getUser()->getFirstname();
  4942.             $iddemande $contract->getId();
  4943.             $iddemande 'home';
  4944.             $body = [
  4945.                 'Messages' => [
  4946.                     [
  4947.                         'From' => [
  4948.                             'Email' => "laura@wizi.eu",
  4949.                             'Name' => "Laura de Wizi"
  4950.                         ],
  4951.                         'To' => [
  4952.                             [
  4953.                                 'Email' => $mailto,
  4954.                                 'Name' => $emailtoname
  4955.                             ]
  4956.                         ],
  4957.                         'TemplateID' => 1556081,
  4958.                         'TemplateLanguage' => true,
  4959.                         'Subject' => "Votre locataire dépose son préavis de départ",
  4960.                         'Variables' => json_decode('
  4961.                             {"demandeur": "' $demandeur '",
  4962.                             "iddemande": "' $iddemande '"
  4963.                             }'true)
  4964.                     ]
  4965.                 ]
  4966.             ];
  4967.             $response $mj->post(Resources::$Email, ['body' => $body]);
  4968.             $response->success() && $response->getData();
  4969.         }
  4970.         if($PreavisSortie->getTraitement() == 3){
  4971.             // préavis refusé
  4972.             /*
  4973.             mail locataire :
  4974.             demande de préavis refusée
  4975.             https://desk.wizi.eu/#/app/contract_renter/2515/menu
  4976.             */
  4977.             $mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48''c868648747688a02902d23babd895c51'true, ['version' => 'v3.1']);
  4978.             $mailto $contract->getApplication()->getUser()->getEmail();
  4979.             $emailtoname $contract->getApplication()->getUser()->getName();
  4980.             $demandeur $contract->getApplication()->getUser()->getFirstname();
  4981.             $iddemande $contract->getId();
  4982.             $body = [
  4983.                 'Messages' => [
  4984.                     [
  4985.                         'From' => [
  4986.                             'Email' => "laura@wizi.eu",
  4987.                             'Name' => "Laura de Wizi"
  4988.                         ],
  4989.                         'To' => [
  4990.                             [
  4991.                                 'Email' => $mailto,
  4992.                                 'Name' => $emailtoname
  4993.                             ]
  4994.                         ],
  4995.                         'TemplateID' => 1556086,
  4996.                         'TemplateLanguage' => true,
  4997.                         'Subject' => "Votre préavis de départ est refusée",
  4998.                         'Variables' => json_decode('
  4999.                             {"demandeur": "' $demandeur '",
  5000.                             "iddemande": "' $iddemande '"
  5001.                             }'true)
  5002.                     ]
  5003.                 ]
  5004.             ];
  5005.             $response $mj->post(Resources::$Email, ['body' => $body]);
  5006.             $response->success() && $response->getData();
  5007.         }
  5008.         return New JsonResponse('ok');
  5009.     }
  5010.     /**
  5011.      * compter les leads a traiter
  5012.      *
  5013.      * @param Request $request
  5014.      * @return JsonResponse
  5015.      * @Route("/countuserhelprdv", name="countuserhelprdv", options={"expose"=true})
  5016.      * @Method({"GET","POST"})
  5017.      */
  5018.     public function countUserhelprdvAction()
  5019.     {
  5020.         $namedb $this->getParameter('dbreqpdo');
  5021.         $udb $this->getParameter('userreqpdo');
  5022. $pdb $this->getParameter('passreqpdo');
  5023. $bdd = new \PDO('mysql:host=localhost;dbname=' $namedb ';charset=utf8'$udb$pdb);
  5024.         $sql "
  5025. SELECT count(*) as res
  5026. FROM app.user_help_rdv as u  ";
  5027.         $condition ' where ( status = 1 )  ';
  5028.         //$max = $bdd->query($sql.$condition)->fetchColumn();
  5029.         $sthd $bdd->prepare($sql.$condition);
  5030.         $sthd->execute();
  5031.         $max $sthd->fetch(\PDO::FETCH_ASSOC);
  5032.         //return New JsonResponse($comuser->getUsername());
  5033.         return New JsonResponse($max); //
  5034.     }
  5035.     /**
  5036.      * Verifier un utilisateur video et carte d'identitée
  5037.      *
  5038.      * @Route("/certificateusercnicheck", name="certificateusercnicheck", options={"expose"=true})
  5039.      * @Method({"GET","POST"})
  5040.      * @param Request $request
  5041.      * @return Response
  5042.      */
  5043.     public function certificateusercnicheckAction(Request $request)
  5044.     {
  5045.         $data= [];
  5046.         $args = [
  5047.             'credentials' => [
  5048.                 'key' => 'AKIAUHKWPN22W5Z4BQJM',
  5049.                 'secret' => 'DFcqs/4zwpBjBOAQ791N9twddebeHGk89DBhsHJJ'
  5050.             ],
  5051.             'region' => 'us-east-1',
  5052.             'version' => 'latest'
  5053.         ];
  5054.         $client = new RekognitionClient($args);
  5055.         /*
  5056.         $result = $client->compareFaces([
  5057.             'SimilarityThreshold' => 60,
  5058.             'SourceImage' => [
  5059.                 'Bytes' => file_get_contents('recoimg/1.jpg')
  5060.             ],
  5061.             'TargetImage' => [
  5062.                 'Bytes' => file_get_contents('recoimg/2.jpg')
  5063.             ]
  5064.         ]);
  5065.         */
  5066.         $result $client->compareFaces([
  5067.             'SimilarityThreshold' => 50,
  5068.             'SourceImage' => [
  5069.                 'Bytes' => file_get_contents($_FILES['image']['tmp_name'])
  5070.             ],
  5071.             'TargetImage' => [
  5072.                 'Bytes' => file_get_contents($_FILES['image2']['tmp_name'])
  5073.             ]
  5074.         ]);
  5075.         if(isset($result['FaceMatches'][0])){
  5076.             // var_dump($result['FaceMatches'][0]['Similarity']);
  5077.             return New JsonResponse($result['FaceMatches'][0]['Similarity']);
  5078.         }else{
  5079.             // var_dump($result);
  5080.             return New JsonResponse(0);
  5081.         }
  5082.         // return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
  5083.     }
  5084.     /**
  5085.      * Verifier un utilisateur video et carte d'identitée
  5086.      *
  5087.      * @Route("/certificateusercnicheckcnipasseport", name="certificateusercnicheckcnipasseport", options={"expose"=true})
  5088.      * @Method({"GET","POST"})
  5089.      * @param Request $request
  5090.      * @return Response
  5091.      */
  5092.     public function certificateusercnicheckcnipasseportAction(Request $request)
  5093.     {
  5094.         $data= [];
  5095.         $args = [
  5096.             'credentials' => [
  5097.                 'key' => 'AKIAUHKWPN22W5Z4BQJM',
  5098.                 'secret' => 'DFcqs/4zwpBjBOAQ791N9twddebeHGk89DBhsHJJ'
  5099.             ],
  5100.             'region' => 'us-east-1',
  5101.             'version' => 'latest'
  5102.         ];
  5103.         $client = new RekognitionClient($args);
  5104.         /*
  5105.         $result = $client->compareFaces([
  5106.             'SimilarityThreshold' => 60,
  5107.             'SourceImage' => [
  5108.                 'Bytes' => file_get_contents('recoimg/1.jpg')
  5109.             ],
  5110.             'TargetImage' => [
  5111.                 'Bytes' => file_get_contents('recoimg/2.jpg')
  5112.             ]
  5113.         ]);
  5114.         */
  5115.         /*
  5116.         $result = $client->compareFaces([
  5117.             'SimilarityThreshold' => 50,
  5118.             'SourceImage' => [
  5119.                 'Bytes' => file_get_contents($_FILES['image']['tmp_name'])
  5120.             ],
  5121.             'TargetImage' => [
  5122.                 'Bytes' => file_get_contents($_FILES['image2']['tmp_name'])
  5123.             ]
  5124.         ]);
  5125.         */
  5126.         /*
  5127.         $result = $client->detectText([
  5128.                 'Image' => array(
  5129.                     'Bytes' => file_get_contents($_FILES['image']['tmp_name']),
  5130.                 ),
  5131.             ]);
  5132.         */
  5133.         /*
  5134.         $result = $client->detectText([
  5135.                 'Image' => array(
  5136.                     'Bytes' => file_get_contents('/home/app/public_html/recoocr/CNIscan.jpg'),
  5137.                 ),
  5138.             ])['TextDetections'];
  5139.         */
  5140.         $result $client->detectText([
  5141.             'Image' => array(
  5142.                 'Bytes' => file_get_contents($_FILES['image']['tmp_name']),
  5143.             ),
  5144.         ])['TextDetections'];
  5145.         $stringtab = [];
  5146.         $type "Documment inconnu";
  5147.         foreach($result as $item)
  5148.         {
  5149.             if($item['Type'] === 'LINE')
  5150.             {
  5151.                 $word "CARTE NATIONALE D'IDENTITE";
  5152.                 $wordpassport "PASSEPORT";
  5153.                 $stringtab[] = $item['DetectedText'];
  5154.                 $mystring $item['DetectedText'];
  5155.                 // Test if string contains the word
  5156.                 if(stristr($mystring$word) !== false){
  5157.                     $type "votre carte d'identité";
  5158.                 }elseif (stristr($mystring$wordpassport) !== false) {
  5159.                     $type "votre un passeport";
  5160.                 }
  5161.             }
  5162.         }
  5163.         //var_dump($stringtab);
  5164.         return New JsonResponse($type);
  5165.         // return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
  5166.     }
  5167.     /**
  5168.      *  Ajouter une agence
  5169.      *
  5170.      * @Route("/test/adduseragence", name="testadduseragence", options={"expose"=true})
  5171.      * @Method({"GET","POST"})
  5172.      * @return Response
  5173.      */
  5174.     public function adduserAgenceAction(Request $request)
  5175.     {
  5176.         if ($request->isMethod('post')) {
  5177.             /*
  5178.             let datasend = {
  5179.                 firstname : $("#formFirstnameLoc").val(),
  5180.                 name : $("#formNameLoc").val(),
  5181.                 email : $("#formEmailLoc").val(),
  5182.                 phone : $("#formPhoneLoc").val(),
  5183.                 adresse : $("#formAdressLoc").val(),
  5184.                 codepostal : $("#formPostalcodeLoc").val(),
  5185.                 ville : $("#formCityLoc").val(),
  5186.                 codeubiflow : $("#codeUbiflow").val(),
  5187.             }
  5188.             */
  5189.             $firstname $request->get('firstname');
  5190.             $name $request->get('name');
  5191.             $email $request->get('email');
  5192.             $phone $request->get('phone');
  5193.             $adresse $request->get('adresse');
  5194.             $codepostal $request->get('codepostal');
  5195.             $ville $request->get('ville');
  5196.             $codeubiflow $request->get('codeubiflow');
  5197.             $password random_int(10009999);
  5198.             $userManager $this->get('fos_user.user_manager');
  5199.             $em =  $this->getDoctrine->getManager();
  5200.             $usersRepository $em->getRepository("AppBundle:User");
  5201.             $email_exist $usersRepository->findOneBy(array('email' => $email));
  5202.             if($email_exist){
  5203.                 return new JsonResponse("l'agence existe deja");
  5204.             }
  5205.             $user $userManager->createUser();
  5206.             $user->setUsername($phone);
  5207.             $user->setEmail($email);
  5208.             $user->setEmailCanonical($email);
  5209.             $user->setEnabled(1);
  5210.             // this method will encrypt the password with the default settings :)
  5211.             $user->setPlainPassword($password);
  5212.             $userManager->updateUser($user);
  5213.             $useragence $usersRepository->findOneBy(array('email' => $email));
  5214.             $useragence->setFirstname($firstname);
  5215.             $useragence->setName($name);
  5216.             $useragence->setMobilePhone($phone);
  5217.             $useragence->setAdress($adresse);
  5218.             $useragence->setPostalCode($codepostal);
  5219.             $useragence->setCity($ville);//setIsClientUbiflow
  5220.             $useragence->setIsClientUbiflow(1);
  5221.             $useragence->setCodeClientUbiflow($codeubiflow);//setInitialMode // setMode // ->addRole('ROLE_API')
  5222.             $useragence->setInitialMode(2);
  5223.             $useragence->setMode(2);
  5224.             $useragence->addRole('ROLE_API'); // setTemporyPass()
  5225.             $useragence->setTemporyPass($password);
  5226.             $em->persist($useragence);
  5227.             $em->flush();
  5228.             return new JsonResponse('utilisateur ok');
  5229.         }
  5230.         else{
  5231.             return $this->render('Extranet/Security/addUserAgence.html.twig', array(
  5232.             ));
  5233.         }
  5234.     }
  5235.     /**
  5236.      * Envoyer une recompense user en ajax
  5237.      *
  5238.      * @param Request $request
  5239.      * @return JsonResponse
  5240.      * @Route("/sendajaxrecompense", name="sendajaxrecompense", options={"expose"=true})
  5241.      * @Method({"GET","POST"})
  5242.      */
  5243.     public function sendajaxrecompenseAction(Request $request)
  5244.     {
  5245.         $em =  $this->getDoctrine->getManager();
  5246.         $noteManager $em->getRepository('App\AppBundle\Entity\Recompense');
  5247.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  5248.         $user $userManager->find($request->get('user'));
  5249.         $recompense $noteManager->find($request->get('note'));
  5250.         $user->addRecompense($recompense);
  5251.         $em->persist($user);
  5252.         $em->flush();
  5253.         return new JsonResponse('recompense activée');
  5254.     }
  5255.     /**
  5256.      * effacer une recompense utilisateur
  5257.      *
  5258.      * @param Request $request
  5259.      * @return JsonResponse
  5260.      * @Route("/deldajaxrecompense", name="deldajaxrecompense", options={"expose"=true})
  5261.      * @Method({"GET","POST"})
  5262.      */
  5263.     public function delajaxrecompenseAction(Request $request)
  5264.     {
  5265.         $em =  $this->getDoctrine->getManager();
  5266.         $noteManager $em->getRepository('App\AppBundle\Entity\Recompense');
  5267.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  5268.         $user $userManager->find($request->get('user'));
  5269.         $recompense $noteManager->find($request->get('note'));
  5270.         $user->removeRecompense($recompense);
  5271.         $em->persist($user);
  5272.         $em->flush();
  5273.         return new JsonResponse('recompense effacé');
  5274.     }
  5275.     /**
  5276.      * Envoyer une recompense flat en ajax
  5277.      *
  5278.      * @param Request $request
  5279.      * @return JsonResponse
  5280.      * @Route("/sendajaxrecompenseflat", name="sendajaxrecompenseflat", options={"expose"=true})
  5281.      * @Method({"GET","POST"})
  5282.      */
  5283.     public function sendajaxrecompenseflatAction(Request $request)
  5284.     {
  5285.         $em =  $this->getDoctrine->getManager();
  5286.         $noteManager $em->getRepository('App\AppBundle\Entity\Recompense');
  5287.         $flatManager $em->getRepository('App\AppBundle\Entity\Flat');
  5288.         $flat $flatManager->find($request->get('flat'));
  5289.         $recompense $noteManager->find($request->get('note'));
  5290.         $flat->addRecompense($recompense);
  5291.         $em->persist($flat);
  5292.         $em->flush();
  5293.         return new JsonResponse('recompense activée');
  5294.     }
  5295.     /**
  5296.      * effacer une recompense flat ajax
  5297.      *
  5298.      * @param Request $request
  5299.      * @return JsonResponse
  5300.      * @Route("/deldajaxrecompenseflat", name="deldajaxrecompenseflat", options={"expose"=true})
  5301.      * @Method({"GET","POST"})
  5302.      */
  5303.     public function delajaxrecompenseflatAction(Request $request)
  5304.     {
  5305.         $em =  $this->getDoctrine->getManager();
  5306.         $noteManager $em->getRepository('App\AppBundle\Entity\Recompense');
  5307.         $flatManager $em->getRepository('App\AppBundle\Entity\Flat');
  5308.         $flat $flatManager->find($request->get('flat'));
  5309.         $recompense $noteManager->find($request->get('note'));
  5310.         $flat->removeRecompense($recompense);
  5311.         $em->persist($flat);
  5312.         $em->flush();
  5313.         return new JsonResponse('recompense effacé');
  5314.     }
  5315.     // boadduserticket
  5316.     /**
  5317.      * effacer une recompense flat ajax
  5318.      *
  5319.      * @param Request $request
  5320.      * @return JsonResponse
  5321.      * @Route("/boadduserticket/{ticket}", name="boadduserticket", options={"expose"=true})
  5322.      * @Method({"GET","POST"})
  5323.      */
  5324.     public function boadduserticketAction(Request $requestTicket $ticket)
  5325.     {
  5326.         $em =  $this->getDoctrine->getManager();
  5327.         $users $em->getRepository('App\AppBundle\Entity\User')->findByRoles('TICKET');
  5328.         if ($request->isMethod('post') && $request->get('uid')) {
  5329.             $noteManager $em->getRepository('App\AppBundle\Entity\Ticket');
  5330.             $uid $request->get('uid');
  5331.             $u $em->getRepository('App\AppBundle\Entity\User')->find($uid);
  5332.             $tu = new TicketUser();
  5333.             $tu->setUser($u);
  5334.             $tu->setStatus(1);
  5335.             $tu->setTicket($ticket);
  5336.             $em->persist($tu);
  5337.             $em->flush();
  5338.             return new JsonResponse('utilisateur ajout');
  5339.         }
  5340.         else{
  5341.             return $this->render('Extranet/Security/addUserTicket.html.twig', array(
  5342.                 "ticket" => $ticket,
  5343.                 "users" => $users
  5344.             ));
  5345.         }
  5346.     }
  5347.     /**
  5348.      * Noter une annonce ajax
  5349.      *
  5350.      * @param Request $request
  5351.      * @return JsonResponse
  5352.      * @Route("/noteflatnoteajax", name="noteflatnoteajax", options={"expose"=true})
  5353.      * @Method({"GET","POST"})
  5354.      */
  5355.     public function noteflatajaxAction(Request $request)
  5356.     {
  5357.         $em =  $this->getDoctrine->getManager();
  5358.         $flatnoteManager $em->getRepository('App\AppBundle\Entity\FlatNote');
  5359.         $flatManager $em->getRepository('App\AppBundle\Entity\Flat');
  5360.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  5361.         $user $userManager->find($request->get('user'));
  5362.         $flat $flatManager->find($request->get('flat'));
  5363.         $comment $request->get('comment');
  5364.         $note $request->get('note');
  5365.         $existFlat $flatnoteManager->findOneBy(['user'=> $user,'flat'=> $flat]);
  5366.         if($existFlat){
  5367.             $existFlat->setNote($note);
  5368.             $existFlat->setStatus(1);
  5369.             $existFlat->setComment($comment);
  5370.             $em->persist($existFlat);
  5371.         } else {
  5372.             $flatNote = new FlatNote();
  5373.             $flatNote->setUser($user);
  5374.             $flatNote->setFlat($flat);
  5375.             $flatNote->setNote($note);
  5376.             $flatNote->setStatus(1);
  5377.             $flatNote->setComment($comment);
  5378.             $em->persist($flatNote);
  5379.         }
  5380.         $em->flush();
  5381.         return new JsonResponse('Note Ajoutée');
  5382.     }
  5383.     /**
  5384.      * Stop Alert annonces dispos ajax
  5385.      *
  5386.      * @param Request $request
  5387.      * @return JsonResponse
  5388.      * @Route("/stopalertannonceajax", name="stopalertannonceajax", options={"expose"=true})
  5389.      * @Method({"GET","POST"})
  5390.      */
  5391.     public function stopalertannonceajaxAction(Request $request)
  5392.     {
  5393.         $em =  $this->getDoctrine->getManager();
  5394.         $userManager $em->getRepository('App\AppBundle\Entity\User');
  5395.         $user $userManager->find($request->get('user'));
  5396.         $user->setAlertNewFlat(1);
  5397.         $em->persist($user);
  5398.         $em->flush();
  5399.         return new JsonResponse('Alertes Annonces desactivees');
  5400.     }
  5401.     /**
  5402.      * Effacer les utilisateurs innactifs depuis plus de trois ans
  5403.      *
  5404.      * @param Request $request
  5405.      * @return JsonResponse
  5406.      * @Route("/rgpddeleteusertroisyears", name="rgpddeleteusertroisyears", options={"expose"=true})
  5407.      * @Method({"GET","POST"})
  5408.      */
  5409.     public function rgpddeleteusertroisyearsAction(Request $request)
  5410.     {
  5411.         $request "SELECT * FROM app.user
  5412.                     where last_login < DATE_SUB(curdate(), INTERVAL 3 YEAR)
  5413.                     and
  5414.                     user.id not in (
  5415.                     select loc.id from contract
  5416.                     inner join application as apps on contract.application_id = apps.id
  5417.                     inner join user as loc on apps.user = loc.id
  5418.                     where contract.status = 2
  5419.                     or
  5420.                     contract.status = 4
  5421.                     or
  5422.                     contract.status = 1
  5423.                     )
  5424.                     and
  5425.                     user.id not in (
  5426.                     select fl.owned_by_id from contract
  5427.                     inner join application as apps on contract.application_id = apps.id
  5428.                     inner join user as loc on apps.user = loc.id
  5429.                     inner join flat as fl on apps.flat = fl.id
  5430.                     where contract.status = 2
  5431.                     or
  5432.                     contract.status = 4
  5433.                     or
  5434.                     contract.status = 1
  5435.                     )";
  5436.         
  5437.         return new JsonResponse('Alertes Annonces desactivees');
  5438.     }
  5439. }