<?php
namespace App\AppBundle\Controller;
use Doctrine\Persistence\ManagerRegistry;
use Sg\DatatablesBundle\Datatable\DatatableFactory as DatatableFactory;
use Sg\DatatablesBundle\Response\DatatableResponse;
use App\AppBundle\Datatables\UserDatatable;
use App\AppBundle\Datatables\FlatDatatable;
use App\AppBundle\Datatables\ReprisBailDatatable;
use JMS\Serializer\SerializerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\AppBundle\Entity\Flat;
use App\AppBundle\Entity\FlatNote;
use App\AppBundle\Entity\Recompense;
use App\AppBundle\Entity\PreavisSortie;
use App\AppBundle\Entity\HelpMessage;
use App\AppBundle\Entity\FlatDescription;
use App\AppBundle\Entity\Sepa;
use App\AppBundle\Entity\Mandate;
use App\AppBundle\Entity\User;
use App\AppBundle\Entity\Notification;
use App\AppBundle\Entity\Message;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use App\AppBundle\Form\MessageType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\Mapping;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Annotations\Annotation;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\AppBundle\Entity\AircallCall;
use libphonenumber\PhoneNumberUtil;
use App\AppBundle\Entity\NotificationBo;
use App\AppBundle\Entity\RgpdAutorisation;
use App\AppBundle\Entity\UserRgpdAutorisation;
use App\AppBundle\Entity\UserRgpdText;
use App\AppBundle\Entity\RgpdText;
use App\AppBundle\Entity\FlatProp;
use App\AppBundle\Entity\Application;
use App\AppBundle\Entity\VerifDoss;
use App\AppBundle\Entity\VisiteDate;
use App\AppBundle\Entity\UserLoc;
use App\AppBundle\Entity\Ticket;
use App\AppBundle\Entity\TicketAnswer;
use App\AppBundle\Entity\TicketUser;
use App\AppBundle\Entity\NoteSuiviUser;
use App\Aws\Rekognition\RekognitionClient;
use \Mailjet\Resources;
/**
* Contrôleur de l'accueil, des annonces, des utilisateurs et des conversations
*
* @package AppBundle\Controller
*/
class ExtranetController extends AbstractController
{
private $getDoctrine;
private $serializer;
private $dtFactory;
private $dtResponse;
public function __construct(ManagerRegistry $getDoctrine, SerializerInterface $serializer,DatatableFactory $datatableFactory, DatatableResponse $datatableResponse){
$this->getDoctrine = $getDoctrine;
$this->_serializer=$serializer;
$this->dtFactory = $datatableFactory;
$this->dtResponse = $datatableResponse;
}
public function getUser2(){
$em = $this->getDoctrine;
$usersManager = $em->getRepository('App\AppBundle\Entity\User');
$myuser = $usersManager->find(1);
return $myuser;
}
/*
protected function getUser(): User
{
return parent::getUser();
}
*/
/**
* verifier iban depuis le BO pour un contrat
*
* @param Request $request
* @return JsonResponse
* @Route("/frombocheckibanaction", name="frombocheckibanaction", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function formBoCheckIbanAction(Request $request)
{
$iban = $_POST['iban'];
$curl = curl_init();
$post = [
'format' => 'json',
'api_key' => '7d35694399f14f197e488187deaab0fa',
'iban' => $iban,
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.iban.com/clients/api/v4/iban/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $post
));
$output = curl_exec($curl);
$result = json_decode($output);
//print_r($result);
curl_close($curl);
$response = new Response();
$response->setStatusCode(200);
$vv = json_encode($result);
$response->setContent($vv);
return new JsonResponse($output);
}
/**
* Generer un sepa depuis le BO our un contrat
*
* @param Request $request
* @param $doctrine
* @return JsonResponse
* @Route("/generatesepafrombo", name="generatesepafrombo", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function generateSepaAction(Request $request, $doctrine)
{
$arr = $_POST['sepa'];
$em = $this->getDoctrine->getManager();
$contract = $em->getRepository('AppBundle:Contract')->find($_POST['cid']);
$sepa = new Sepa();
$sepas = $contract->getSepas();
foreach ($sepas as $rsepa){
$rsepa->setStatut(2);
$em->persist($rsepa);
$em->flush();
}
$sepa->setContract($contract);
$sepa->setAdresse($arr['adresse']);
$sepa->setBic($arr['bic']);
$sepa->setCodePostal($arr['code_postal']);
$sepa->setEmail($arr['email']);
$sepa->setIban($arr['iban']);
$sepa->setIsOther($arr['isOther']);
$sepa->setMobilePhone($arr['mobile_phone']);
$sepa->setNom($arr['nom']);
$sepa->setPrenom($arr['prenom']);
$sepa->setVille($arr['ville']);
$sepa->setStatut(1);
$em->persist($sepa);
$em->flush();
// generateDocument(Contract $contract, $category, $id = null, SecActOfGuarantee $secgarid = null,Sepa $sepa = null)
$this->get('app.contract')->generateDocument($contract, 'sepa', null,null,$sepa);
$em->flush();
if ($contract->getDocuments()->count()) {
$indice = $contract->getDocuments()->count() -1;
$sepa->setDocument($contract->getDocuments()[$indice]);
}
$sepa->setContract($contract);
$sepa->setStatut(2);
$em->persist($sepa);
$em->flush();
$contract->addSepa($sepa);
return new JsonResponse('mandat généré');
}
/**
* faire un reset de la date de relance
*
* @param Request $request
* @return JsonResponse
* @Route("/resetdatesuivirappel/{id}", name="resetdatesuivirappel", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function resetdatesuivirappelAction($id)
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$sthd = $bdd->prepare("update app.user SET suivirappel = null where id =".$id);
$sthd->execute();
return $this->redirect( $this->generateUrl('editUser', array('id' => $id)) );
}
/**
* compter les leads a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countmylead", name="countmylead", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countMyLeadsAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
/*
$sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
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
FROM app.user as u
inner join app.flat as f on u.id = f.owned_by_id";
*/
$sql = "SELECT count(*) as res
FROM app.user as u ";
$condition = ' where (suivipar LIKE "'.$suivipar.'" and suivistatus is null ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* compter les leads a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countmyticket", name="countmyticket", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countMyTicketAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$sql = "SELECT count(t.id) as number FROM ticket as t
inner join ticket_user as tu on t.id = tu.ticket_id
inner join user as u on u.id = tu.user_id
where t.seen_answer = 1 and t.user_from_id = ".$this->getUser()->getId()." group by t.id";
$sthd = $bdd->prepare($sql);
$sthd->execute();
$max = $sthd->fetchAll();
$res = [];
$res['res'] = count($max);
$sql = "SELECT count(t.id) as number FROM ticket as t
inner join ticket_user as tu on t.id = tu.ticket_id
inner join user as u on u.id = tu.user_id
where tu.status = 1 and tu.user_id = ".$this->getUser()->getId()." group by t.id";
$sthd = $bdd->prepare($sql);
$sthd->execute();
$max = $sthd->fetchAll();
$res['res'] = $res['res'] + count($max);
return New JsonResponse($res);
}
/**
* compter les leads a traiter pour un user
*
* @param Request $request
* @return JsonResponse
* @Route("/countuserlead/{id}", name="countuserlead", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countUserLeadsAction($id)
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $id;
$sql = "SELECT count(*) as res
FROM app.user as u ";
$condition = ' where (suivipar LIKE "'.$suivipar.'" and suivistatus is null ) ';
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
return New JsonResponse($max); //
}
/**
* compter les leads piges a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countmypigelead", name="countmypigelead", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countMyPigeLeadsAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
$sql = "SELECT count(*) as res
FROM app.annoncescsv as u ";
$condition = ' where (commercial LIKE "'.$suivipar.'" and status is null ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* compter les leads piges a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countmypigeleadjj", name="countmypigeleadjj", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countMyPigeLeadsjjAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
$sql = "SELECT count(*) as res
FROM app.annoncescsv as u ";
$jmoinsdeux = new \DateTime("2 days ago");
$condition = ' where ( commercial LIKE "'.$suivipar.'" AND rappel < "'.$jmoinsdeux->format('Y-m-d').'" AND status = 11 ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* compter les leads piges a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countuserpigelead/{id}", name="countuserpigelead", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countUserPigeLeadsAction($id)
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $id;
$sql = "SELECT count(*) as res
FROM app.annoncescsv as u ";
$condition = ' where (commercial LIKE "'.$suivipar.'" and status is null ) ';
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
return New JsonResponse($max); //
}
/**
* compter les dossier a verifier
*
* @param Request $request
* @return JsonResponse
* @Route("/countmydostoverif", name="countmydostoverif", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countMyDosToVerifAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
$sql = "SELECT count(app.taskdocstatus) as res FROM app.contract as vd
inner join application as app on app.id = vd.application_id
where app.taskdocstatus =0 and vd.taskdoctriger = 1";
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* permet a un utilisateur de se désinscrir des email marketing
*
* @param Request $request
* @return JsonResponse
* @Route("/stopcampagnemail", name="stopcampagnemail", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function stopEmailAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$usersManager = $em->getRepository('App\AppBundle\Entity\User');
$email = $request->get('email');
$myuser = $usersManager->findBy(['email'=> $email] );
$myuser[0]->setStopmail(true);
$em->persist($myuser[0]);
$em->flush();
return new JsonResponse('stop email activé');
}
/**
* Envoyer une note de suivi en ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/sendajaxnotesuivi", name="sendajaxnotesuivi", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function sendajaxnotesuiviAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\NoteSuiviUser');
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$note = new NoteSuiviUser();
$note->setUser($user);
$note->setEditor($this->getUser());
$note->setNote($request->get('note'));
$note->setCreatedAt(new \DateTime());
$em->persist($note);
$em->flush();
return new JsonResponse('stop email activé');
}
/**
* Envoyer une note de suivi en ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/sendajaxreatributeusercom", name="sendajaxreatributeusercom", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function sendajaxreatributeusercomAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\NoteSuiviUser');
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$suivipar = $request->get('suivipar');
$note = new NoteSuiviUser();
$note->setUser($user);
$note->setEditor($this->getUser());
$note->setNote('utilisateur réatribué pour la raison suivante : '.$request->get('note'));
$note->setCreatedAt(new \DateTime());
$em->persist($note);
$em->flush();
$user->setSuivipar($suivipar);
$em->persist($user);
$em->flush();
return new JsonResponse('stop email activé');
}
/**
* Récupérer l'adresse de l'api à utiliser
* @param Request $request
* @return JsonResponse
*
* @Route("/getprodapiurltouse", name="getprodapiurltouse", options={"expose"=true})
*
*/
public function getprodapiurltouseAction()
{
$api = $this->getParameter('apiadress');
return new JsonResponse($api);
}
/**
* observatoire des prix
* @param Request $request
* @return JsonResponse
*
* @Route("/getprimcare/{cp}/{s}/{t}", name="getprimcare", options={"expose"=true})
* @Method({"GET","POST"})
*
*/
public function getprimcareAction($cp,$s,$t)
{
if($t = 'AP'){
$tringtype = " and (type like 'AP' or type like 'LX') ";
}else{
$tringtype = " and type like 'MA' ";
}
$nbEchantVoulu = 25;
$echantillon = 0;
$iterations = 0;
$iterationsgeneral = 0;
$smin = $s;
$smax = $s;
$data = [];
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
while ($echantillon < $nbEchantVoulu){
$echantillon = $bdd->query("
SELECT count(*) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
")->fetchColumn();
if($echantillon < $nbEchantVoulu){
$smax = $smax +2;
$smin = $smin -2;
}
$iterations ++;
$iterationsgeneral ++;
if($iterations == 30){
$nbEchantVoulu = $nbEchantVoulu - 1;
$iterations = 0;
}
}
$moyene = $bdd->query("
SELECT (sum(loyer)/sum(surface)) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
")->fetchColumn();
$max = $bdd->query("
SELECT max(loyer) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
")->fetchColumn();
$min = $bdd->query("
SELECT min(loyer) FROM app.locations where cp like '".$cp."%' ".$tringtype." and surface > (".$smin."-1) and surface < (".$smax."+1) limit 10000000;
")->fetchColumn();
switch ($iterationsgeneral) {
case 1:
$data['confiance'] = 5;
break;
case 2:
$data['confiance'] = '4.5';
break;
case 3:
$data['confiance'] = 4;
break;
case 4:
$data['confiance'] = '3.5';
break;
case 5:
$data['confiance'] = 3;
break;
case 6:
$data['confiance'] = '2.5';
break;
case 7:
$data['confiance'] = 2;
break;
case 8:
$data['confiance'] = '1.5';
break;
case 9:
$data['confiance'] = 1;
break;
case 10:
$data['confiance'] = '0.5';
break;
default:
$data['confiance'] = 0;
break;
}
$data['countresult'] = $echantillon;
$data['moyenmcare'] = $moyene;
$data['prixmoycalc'] = $moyene*$s;
$data['max'] = $max;
$data['min'] = $min;
$data['smin'] = $smin;
$data['smax'] = $smax;
return new JsonResponse(json_encode($data));
}
/**
* Récupérer le nombre d'annonces publiée
* @param Request $request
* @return JsonResponse
*
* @Route("/countpub", name="countpub", options={"expose"=true})
*
*/
public function countpubAction()
{
$countpub = $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates(null, null, 2);
return new JsonResponse($countpub);
}
/**
* Récupérer le nombre de candidature
* @param Request $request
* @return JsonResponse
*
* @Route("/countcandidatures", name="countcandidatures", options={"expose"=true})
*
*/
public function countcandidaturesAction()
{
$countcandidatures = $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates(null, null);
return new JsonResponse($countcandidatures);
}
/**
* Stats equipe
*
* @Route("/", name="homepage")
* @return Response
*/
public function indexAction()
{
if(1 or $this->getUser()->hasRole('ROLE_TIFFANY')){
return $this->statistiqueAction();
} else {
$em = $this->getDoctrine;
$stats1 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
$stats2 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
$stats2array = [];
foreach ($stats2 as $key => $stat2){
$user = $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
$stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
$stats2array[$key]['type'] = $stat2->getType();
$stats2array[$key]['valeur'] = $stat2->getValeur();
$stats2array[$key]['target'] = $stat2->getTarget();
}
return $this->render('stats/statsAdmin.html.twig', array(
'stats1' => $stats1,
'stats2' => $stats2array
));
}
}
/**
* Récupérer les statistiques perso
*
* @Route("/statistiquesuser", name="statistiquesuser")
* @return Response
*/
public function statistiqueUserAction()
{
return $this->render('stats/statsUser.html.twig', [
]);
}
/**
* Récupérer les pages prime
*
* @Route("/primes", name="primespage")
* @return Response
*/
public function primesAction()
{
return $this->render('stats/primes.html.twig', [
]);
}
/**
* json request primes
*
* @param Request $request
* @Route("/stats/getprimes", name="stats_getprimes", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function getPrimesAction(Request $request)
{
$user = $this->getUser();
if($user->hasRole('ROLE_ADMIN')){
$userFilter = false;
} else {
$userFilter = true;
}
$date = date_create_from_format('m-Y', $request->get('date'));
$datestart = $date->format('Y-m').'-01';
$dateend = $date->format('Y-m-t');
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sql = "SELECT c.id as 'contract_id', owner.id as 'owner_id', renter.id as 'renter_id', com.id as 'commercial_id',
CONCAT(owner.firstname, ' ', owner.name) as 'owner_name',
CONCAT(renter.firstname, ' ', renter.name) as 'renter_name',
CONCAT(com.firstname, ' ', com.name) as 'commercial_name',
lg.signatureDate, lg.entryDate, (lg.signatureDate = lg.entryDate) newlot,
(f.price + f.charges) * (ot.gestion / 100) as 'marge', lg.id as 'lid'
FROM app.contract as c
INNER JOIN app.application as a on a.id = c.application_id
INNER JOIN app.flat as f on f.id = a.flat
INNER JOIN app.user as owner on owner.id = f.owned_by_id
INNER JOIN app.user as renter on renter.id = a.user
INNER JOIN app.lots_geres as lg on lg.contract = c.id
INNER JOIN app.user as com on com.id = owner.suivipar
LEFT JOIN app.offre_tarif as ot on ot.id = c.offre_tarif_id
WHERE c.status = 2
AND ((
c.is_reprise = true
AND c.reprise_date BETWEEN '".$datestart."' AND '".$dateend."'
) OR (
(c.is_reprise = false OR c.is_reprise IS NULL)
AND c.effective_date BETWEEN '".$datestart."' AND '".$dateend."'
))
". ($userFilter ? ' AND com.id = '.$user->getId() : '' ) ."
ORDER BY com.id ASC, newlot ASC;";
$entrees = $bdd->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
foreach($entrees as $key => $entree){
if($entree['newlot'] == 0){
$sql2 = "SELECT lgh.id as 'lghid', ot.gestion as 'gestion', lgh.entryDate as 'entryDate', (f.charges + f.price) * (ot.gestion / 100) as 'marge'
FROM app.lots_geres_historic as lgh
INNER JOIN app.contract as c on c.id = lgh.contractId
INNER JOIN app.application as a on a.id = c.application_id
INNER JOIN app.flat as f on f.id = a.flat
INNER JOIN app.offre_tarif as ot on ot.id = c.offre_tarif_id
WHERE lgh.lotsGeresId = ". $entree['lid'] ."
ORDER BY lgh.entryDate DESC";
$cs = $bdd->query($sql2)->fetchAll(\PDO::FETCH_ASSOC);
$entrees[$key]['sql'] = $sql;
$entrees[$key]['sql2'] = $sql2;
if(array_key_exists(1, $cs)){
$entrees[$key]['newmarge'] = $cs[0]['marge'] - $cs[1]['marge'];
} else {
$entrees[$key]['newmarge'] = 0;
}
} else {
$entrees[$key]['newmarge'] = 0;
}
$sql3 = "SELECT com.firstname, com.name FROM app.distrib_flat as df
inner join app.user as u on u.id = df.user
inner join app.user as com on df.commercial = com.id
where u.id = ".$entree['owner_id']." limit 1";
$originalcom = $bdd->query($sql3)->fetchAll(\PDO::FETCH_ASSOC);
$entrees[$key]['sql3'] = $sql3;
if (isset($originalcom[0])) {
$entrees[$key]['originalcom']= $originalcom[0]['firstname'].' '.$originalcom[0]['name'];
}
}
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($entrees, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer les statistiques perso
*
* @Route("/marketing", name="marketingpage")
* @return Response
*/
public function marketingPageAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$sql = "SELECT avg(YEAR(CURDATE()) - YEAR(u.birthdate)) as 'avg' FROM app.user as u
INNER JOIN app.flat as f on f.owned_by_id = u.id
INNER JOIN app.application as a on a.flat = f.id
INNER JOIN app.contract as c on c.application_id = a.id
where birthdate is not null and initial_mode = 2";
$sthd = $bdd->prepare($sql);
$sthd->execute();
$result = $sthd->fetch(\PDO::FETCH_ASSOC);
return $this->render('stats/marketing.html.twig', [
'avgAge' => $result['avg']
]);
}
/**
* Récupérer les statistiques de l'accueil
*
* @Route("/statistiquesglobal", name="statistiquesglobal")
* @return Response
*/
public function statistiqueAction()
{
$myMinData = (new \DateTime('2018-01-01'))->setTime(0, 0);
$today = (new \DateTime())->setTime(0, 0);
$renterNumber = $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(1, $myMinData, new \DateTime());
$renterTodayNumber = $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(1, $today, new \DateTime());
$ownerNumber = $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(2, $myMinData, new \DateTime());
$ownerTodayNumber = $this->getDoctrine->getRepository('AppBundle:User')->countByModeAndDates(2, $today, new \DateTime());
$flatNumber = $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates($myMinData, new \DateTime(), 2);
$flatTodayNumber = $this->getDoctrine->getRepository('AppBundle:Flat')->countByDates($today, new \DateTime(), 2);
$flatMultidifNumber = $this->getDoctrine->getRepository('AppBundle:Flat')->counMultidif();
$countLike = $this->getDoctrine->getRepository('AppBundle:FlatLike')->countLike();
$countVideo = $this->getDoctrine->getRepository('AppBundle:VideoTask')->countVideo();
$mandateNumber = $this->getDoctrine->getRepository('AppBundle:Mandate')->countByDates($myMinData, new \DateTime());
$mandateTodayNumber = $this->getDoctrine->getRepository('AppBundle:Mandate')->countByDates($today, new \DateTime());
$applicationNumber = $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates($myMinData, new \DateTime());
$applicationTodayNumber = $this->getDoctrine->getRepository('AppBundle:Application')->countApplicationByDates($today, new \DateTime());
$contractNumber = $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->countDoneByDatesAndCategory($myMinData, new \DateTime());
$contractTodayNumber = $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->countDoneByDatesAndCategory($today, new \DateTime());
// countTaskByDates
$tasknumber = $this->getDoctrine->getRepository('AppBundle:Contract')->countTaskByDates($myMinData, new \DateTime());
$taskTodayNumber = $this->getDoctrine->getRepository('AppBundle:Contract')->countTaskByDates($today, new \DateTime());
$countGreenContract = $this->getDoctrine->getRepository('AppBundle:Contract')->countGreen();
$countRedContract = $this->getDoctrine->getRepository('AppBundle:Contract')->countRed();
return $this->render('stats/stats.html.twig', [
'renterNumber' => $renterNumber,
'renterTodayNumber' => $renterTodayNumber,
'ownerNumber' => $ownerNumber,
'ownerTodayNumber' => $ownerTodayNumber,
'flatNumber' => $flatNumber,
'flatTodayNumber' => $flatTodayNumber,
'mandateNumber' => $mandateNumber,
'mandateTodayNumber' => $mandateTodayNumber,
'applicationNumber' => $applicationNumber,
'applicationTodayNumber' => $applicationTodayNumber,
'contractNumber' => $contractNumber,
'contractTodayNumber' => $contractTodayNumber,
'taskNumber' => $tasknumber,
'taskTodayNumber' => $taskTodayNumber,
'flatMultidifNumber' => $flatMultidifNumber,
'totalLikes' => $countLike,
'totalVideos' => $countVideo,
'greenContract' => $countGreenContract,
'redContract' => $countRedContract
]);
}
/**
* Récupérer les statistiques de l'accueil
*
* @Route("/statistiques_sales", name="statistiques_sales")
* @return Response
*/
public function statistiqueSalesAction()
{
$em = $this->getDoctrine;
$stats1 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
$stats2 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
$stats2array = [];
foreach ($stats2 as $key => $stat2){
$user = $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
$stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
$stats2array[$key]['type'] = $stat2->getType();
$stats2array[$key]['valeur'] = $stat2->getValeur();
$stats2array[$key]['target'] = $stat2->getTarget();
}
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
// prop sans annonces
$propsansflat = $bdd->query("SELECT sum(fl.charges + fl.price) as qtotal FROM app.lots_geres as l
INNER Join flat as fl on fl.id = l.flat
INNER JOIN contract as c on c.id = l.contract
WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
WHERE c.status = 4 and l.flat not in (select flat from app.churn))
and l.flat not in (select flat from app.churn) and c.status <> 3
")->fetchColumn();
$nblot = $bdd->query("SELECT count(*) as qtotal FROM app.lots_geres as l
WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
WHERE c.status = 4 and l.flat not in (select flat from app.churn))
and l.flat not in (select flat from app.churn)
")->fetchColumn();
$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
INNER Join flat as fl on fl.id = l.flat
inner Join contract as cec on cec.id = l.contract
inner Join offre_tarif as ot on ot.id = cec.offre_tarif_id
WHERE l.id not in (SELECT l.id FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
WHERE c.status = 4 and l.flat not in (select flat from app.churn))
and l.flat not in (select flat from app.churn) and cec.status <> 3")->fetchColumn();
$annonceparprop = $bdd->query("SELECT (count(lg.id) / count(distinct(u.id))) as 'number' FROM app.lots_geres as lg
inner join app.contract as c on c.id = lg.contract
inner join app.application as a on a.id = c.application_id
inner join app.flat as f on f.id =a.flat
inner join app.user as u on u.id = f.owned_by_id;")->fetchColumn();
// nombre de contrats visal
$nbcontratvisale = $bdd->query("SELECT count(*) as number FROM app.contract as c
where c.status = 2
and offre_tarif_id in(2,5,9,12,14,16,18);")->fetchColumn();
// nombre de contyrats GLI
$nbcontratgli = $bdd->query("SELECT count(*) as number FROM app.contract as c
where c.status = 2
and offre_tarif_id not in(2,5,9,12,14,16,18,8,17);")->fetchColumn();
$quittMoy = (float)$propsansflat / (float)$nblot;
$camoy = (float)$CATOTAL / (float)$nblot;
$pourcentmoylot = (float)$camoy / (float)$quittMoy;
return $this->render('stats/sales.html.twig', [
'stats1' => $stats1,
'stats2' => $stats2array,
'quittTotal' => number_format(round($propsansflat,2),2,"."," ").' €',
'quittmoy'=> number_format(round($quittMoy,2),2,"."," ").' €',
'quitcount' => $nblot.' €',
'catotal' => number_format(round($CATOTAL,2),2,"."," ").' €',
'camoy' => number_format(round($camoy,2),2,"."," ").' €',
'valo' => number_format(round($CATOTAL * 12 * 4,2),2,"."," ").' €',
'pcentmoy' => round(($pourcentmoylot * 100 ),2).' %',
'ltv' => number_format(round((1/(4/414) * 47) ,2),2,"."," ").' €',
'annonceparprop' => number_format(round($annonceparprop ,2),2,"."," ").'',
'nbcontratvisale'=> $nbcontratvisale,
'nbcontratgli'=> $nbcontratgli
]);
}
/**
* json requette obtention evolution quitancement moyen loyer
*
* @param Request $request
* @Route("/stats/statEvoloyermoyparlots", name="stats_statEvoloyermoyparlots", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statEvoloyermoyparlotsAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getQuittancementNblotsByDates($firstDate,$lastDate);
$results['ca'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention evolution quitancement moyen loyer
*
* @param Request $request
* @Route("/stats/statoriginclientprop", name="stats_statoriginclientprop", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statOriginClientPropAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOriginesClient();
$results['ca'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention evolution quitancement moyen loyer
*
* @param Request $request
* @Route("/stats/statpourcentageevo", name="stats_statpourcentageevo", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statpourcentageevoAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date');
$months = $this->getDatesBetweenJustMonth($firstDate, $lastDate);
$em = $this->getDoctrine->getManager();
$datas = [];
foreach ($months as $key1 => $month) {
$sql = "SELECT sum(f.price + f.charges) as 'quittotal', (count(l.id)) as nblot,
(sum(((f.charges + f.price) * ot.gestion/100) + ((f.charges + f.price)*ot.assurance/100))) as catotal,
((sum(((f.charges + f.price)*ot.gestion/100) + ((f.charges + f.price)*ot.assurance/100) )) / (sum(f.price + f.charges)) * 100) as number
FROM lots_geres_historic as lgh
INNER JOIN app.lots_geres as l on l.id = lgh.lotsGeresId
INNER JOIN app.contract as c on c.id = lgh.contractId
INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
INNER JOIN app.offre_tarif as ot on coh.offreId = ot.id
INNER JOIN app.application as app on app.id = c.application_id
INNER JOIN app.flat as f on f.id = app.flat
WHERE lgh.entryDate < :date2
AND (coh.startDate < :date2 AND (coh.endDate is null OR coh.endDate >= :date2))
AND l.id not in
(
SELECT l.id FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
WHERE c.status = 4 and l.flat not in (select flat from app.churn)
)
AND l.flat not in (select flat from app.churn)
ORDER BY l.entryDate ASC";
$stmt = $em->getConnection()->prepare($sql);
$datemonth = new \DateTime($month.'-01');
$param1 = $datemonth->format('Y-m-d');
$param2 = $datemonth->format('Y-m-t').' 23:59:59';
$stmt->bindParam(':date1', $param1);
$stmt->bindParam(':date2', $param2);
$resultSet = $stmt->executeQuery();
$avg = $resultSet->fetchAll();
//$avg = $stmt->fetchAll();
if($key1 + 1 !== count($months)){
$datas[$key1] = ['date' => $datemonth->format('Y-m')];
$datas[$key1]['number'] = isset($avg[0]['number']) ? $avg[0]['number'] : 0;
}
}
$results['ca'] = $datas;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention evolution quitancement moyen loyer
*
* @param Request $request
* @Route("/stats/statnblots", name="stats_statnblots", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statnblotsAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date');
$months = $this->getDatesBetweenJustMonth($firstDate, $lastDate);
$em = $this->getDoctrine->getManager();
$datas = [];
foreach ($months as $key1 => $month) {
$sql = "SELECT count(l.id) as nblot
FROM lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as app on app.id = c.application_id
INNER JOIN app.flat as f on f.id = app.flat
WHERE l.entryDate <= :date2
AND l.id not in
(
SELECT l.id FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
WHERE c.status = 4 and l.flat not in (select flat from app.churn)
)
AND l.flat not in (select flat from app.churn)
ORDER BY l.entryDate ASC";
$stmt = $em->getConnection()->prepare($sql);
$datemonth = new \DateTime($month.'-01');
$param2 = $datemonth->format('Y-m-t').' 23:59:59';
$stmt->bindParam(':date2', $param2);
$resultSet = $stmt->executeQuery();
$avg = $resultSet->fetchAll();
//$avg = $stmt->fetchAll();
if($key1 + 1 !== count($months)){
$datas[$key1] = ['date' => $datemonth->format('Y-m')];
$datas[$key1]['nblot'] = isset($avg[0]['nblot']) ? $avg[0]['nblot'] : 0;
}
}
$results['ca'] = $datas;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer les statistiques de l'accueil
*
* @Route("/indexnew", name="homepagenew")
* @return Response
*/
public function indexNewAction()
{
$em = $this->getDoctrine->getManager();
$pr = $em->getRepository('App\AppBundle\Entity\PhraseJour');
$phrases = $pr->findBy(['actif' => 1]);
$phrase = $phrases[0];
$data = [];
$data['phrase'] = $phrase;
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
// prop sans annonces
$propsansflat = $bdd->query("
SELECT count(*) FROM app.user where id not in (select app.flat.owned_by_id from app.flat) and initial_mode = 2
")->fetchColumn();
$data['propsansflat'] = $propsansflat;
// controle des annonces
$controleflat = $bdd->query("
SELECT count(*) FROM app.flat where status = 2 and can_multidif = 0
")->fetchColumn();
$data['controleflat'] = $controleflat;
// Annonces sans candidatures sous 72 heures
$time = mktime(date("H")-72, date("i"), date("s"), date("m"), date("d"), date("Y"));
$heureref = date("Y-m-d H:i:s", $time);
$flatsanscandidat = $bdd->query("
SELECT count(*) FROM app.flat where id not in (select app.application.flat from app.application) and status = 2 and created_at < '".$heureref."'")->fetchColumn();
$data['flatsanscandidat'] = $flatsanscandidat;
// Candidature sans date de visite
$candsansdatevisite = $bdd->query("
SELECT count(*) FROM app.application where id not in (select app.visite_date.application_id from app.visite_date) and status = 2")->fetchColumn();
$data['candsansdatevisite'] = $candsansdatevisite;
// Locataires sans candidatures sur WIZI
$locsanscandidat = $bdd->query("
SELECT count(*) FROM app.user where initial_mode = 1 and id not in (select app.application.user from app.application) and enabled = 1")->fetchColumn();
$data['locsanscandidat'] = $locsanscandidat;
// dossiers a vériffier
$dostoverif = $bdd->query("
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();
$data['dostoverif'] = $dostoverif;
// dossiers attente de vérification
$dosattenteverif = $bdd->query("
Select count(*) from app.application where status = 5")->fetchColumn();
$data['dosattenteverif'] = $dosattenteverif;
/// partie tableau des objectiffs
$date = date("Y-m-d");
$startdate = $date.' 00:00:00';
$startend = $date.' 23:59:59';
// locataires inscrits
$locinscrits = $bdd->query("
Select count(*) from app.user where initial_mode = 1 and created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
$data['locinscrits'] = $locinscrits;
// prop inscrits
$propinscrits = $bdd->query("
Select count(*) from app.user where initial_mode = 2 and created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
$data['propinscrits'] = $propinscrits;
// candidatures du jour
$appday = $bdd->query("
Select count(*) from app.application where created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
$data['appday'] = $appday;
// annonces du jour
$flatday = $bdd->query("
Select count(*) from app.application where created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
$data['flatday'] = $flatday;
// contrats du jour
$contractday = $bdd->query("
Select count(*) from app.contract where created_at > '".$startdate."'and created_at < '".$startend."'")->fetchColumn();
$data['contractday'] = $contractday;
$em = $this->getDoctrine->getManager();
$obj = $em->getRepository('App\AppBundle\Entity\DailyObjectif');
$objs = $obj->findBy([],array('id' => 'DESC'));
$ob = $objs[0];
$data['dayobs'] = $ob;
return $this->render('Extranet/homepagenew.html.twig', $data);
}
/**
* Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/caparlots", name="stats_caparlots_date", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsCaParLotDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaByDates($firstDate,$lastDate);
$results['ca'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Etat des lots geres
*
* @return JsonResponse
* @Route("/stats/statelotsgeres", name="stats_statelotsgeres", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsStatelotsgeresAction()
{
$data = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getStateLots();
$results['data'] = $data;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/evocaparlotss", name="stats_evocaparlots_date", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsEvoCaParLotDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date');
$months = $this->getDatesBetweenJustMonth($firstDate, $lastDate);
$em = $this->getDoctrine->getManager();
$datas = [];
foreach ($months as $key1 => $month) {
$sql = "SELECT AVG(((f.price + f.charges) * (ot.gestion + ot.assurance)) / 100) as average
FROM lots_geres_historic as lgh
INNER JOIN app.lots_geres as l on l.id = lgh.lotsGeresId
INNER JOIN app.contract as c on c.id = lgh.contractId
INNER JOIN app.application as app on app.id = c.application_id
INNER JOIN app.flat as f on f.id = app.flat
INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
INNER JOIN app.offre_tarif as ot on coh.offreId = ot.id
WHERE lgh.entryDate BETWEEN :date1 AND :date2
AND coh.startDate BETWEEN :date1 and :date2
ORDER BY lgh.entryDate ASC";
$stmt = $em->getConnection()->prepare($sql);
$datemonth = new \DateTime($month.'-01');
$param1 = $datemonth->format('Y-m-d');
$param2 = $datemonth->format('Y-m-t').' 23:59:59';
$stmt->bindParam(':date1', $param1);
$stmt->bindParam(':date2', $param2);
$resultSet = $stmt->executeQuery();
$avg = $resultSet->fetchAll();
if($key1 + 1 !== count($months)){
$datas[$key1] = ['date' => $datemonth->format('Y-m')];
$datas[$key1]['number'] = isset($avg[0]['average']) ? $avg[0]['average'] : 0;
}
}
$results['ca'] = $datas;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le CA pur par lots entre deux dates
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/evocapurparlotss", name="stats_evocapurparlots_date", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsEvoCaPurParLotDateAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$startDate = $request->get('first_date');
$endDate = $request->get('last_date');
$months = $this->getDatesBetweenJustMonth($startDate, $endDate);
$hon = [];
$dg = [];
$ca = [];
foreach ($months as $mkey => $month) {
$datemonth = new \DateTime($month.'-01');
$assurance[$mkey] = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getAssuranceByMonth($month)[0];
$hon[$mkey] = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaPurByMonth($month)[0];
$hon[$mkey]["number"] = (($hon[$mkey]["number"] - $assurance[$mkey]["number"]) / 1.2) + $assurance[$mkey]["number"];
$dg[$mkey] = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getDgByMonth($month)[0];
$dg[$mkey]["number"] = $dg[$mkey]["number"] / 1.2;
// Calculer Upsell
$upsell[$mkey] = $this->getDoctrine->getRepository('AppBundle:FinancesFournisseur')->getUpSellByMonth($month)[0];
$upsell[$mkey]["number"] = $upsell[$mkey]["number"] / 1.2;
$ca[$mkey] = ["number" => $hon[$mkey]["number"] + $dg[$mkey]["number"] + $upsell[$mkey]["number"], "date" => $datemonth->format('Y-m')];
}
// $basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getCaPurDates($firstDate,$lastDate);
$results['ca'] = $ca;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByTarteFlatOffredate", name="stats_tarte_offre_flat_date", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsByTarteFlatOffreDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate, 1);
$classique = $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate, 2);
$securite = $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate, 3);
$serenite = $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate, 4);
$plenitude = $this->getDoctrine->getRepository('AppBundle:Flat')->getOffreByDates($firstDate,$lastDate, 5);
$results['basique'] = $basique;
$results['classique'] = $classique;
$results['securite'] = $securite;
$results['serenite'] = $serenite;
$results['plenitude'] = $plenitude;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/statsLotsGeresByCommercial", name="statsLotsGeresByCommercial", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsLotsGeresByCommercialAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$lastDatei = $request->query->get('last_date');
$date = $this->getDatesBetweenJustMonth($firstDate, $lastDatei);
$results = ['date' => $date];
$commerciaux = $this->getDoctrine->getRepository('AppBundle:User')->findByRoles('ROLE_COMMERCIAL');
foreach ($commerciaux as $key => $commercial){
$results['data'][$key] = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getLotsByDatesByCommercial($firstDate,$lastDate, $commercial->getId());
}
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer la tarte de repartition des choix d'ofrres lors de creation annonce
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/statsnouveauxLotsDate", name="statsnouveauxLotsDate_date", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function statsnouveauxLotsDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getLotsByDates($firstDate,$lastDate);
$results['newlots'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention détail de contrat remporté dans les Stats Général
*
* @param Request $request
* @Route("/stats/statsQuittancementEtPlus", name="stats_statsQuittancement", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statsQuitancementEtPlusAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getQuittancementByDates($firstDate,$lastDate);
$results['quittancement'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention détail de contrat remporté dans les Stats Général
*
* @param Request $request
* @Route("/stats/churn", name="stats_churn", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statsChurnAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$basique = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnsByDates($firstDate,$lastDate);
$results['churn'] = $basique;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* function getDatesBetween
* renvoie un tableau contenant toutes les dates, jour par jour,
* comprises entre les deux dates passées en paramètre.
* NB : les dates doivent être au format aaaa-mm-dd (mais on peut changer le parsing)
* @param (string) $dStart : date de départ
* @param (string) $dEnd : date de fin
* @return (array) aDates : tableau des dates si succès
* @return (bool) false : si échec
*/
public function getDatesBetween ($dStart, $dEnd) {
$iStart = strtotime ($dStart);
$iEnd = strtotime ($dEnd);
if (false === $iStart || false === $iEnd) {
return false;
}
$aStart = explode ('-', $dStart);
$aEnd = explode ('-', $dEnd);
if (count ($aStart) !== 3 || count ($aEnd) !== 3) {
return false;
}
if (false === checkdate ($aStart[1], $aStart[2], $aStart[0]) || false === checkdate ($aEnd[1], $aEnd[2], $aEnd[0]) || $iEnd <= $iStart) {
return false;
}
for ($i = $iStart; $i < $iEnd + 86400; $i = strtotime ('+1 day', $i) ) {
$sDateToArr = strftime ('%Y-%m-%d', $i);
$sYear = substr ($sDateToArr, 0, 4);
$sMonth = substr ($sDateToArr, 5, 2);
$aDates[$sYear][$sMonth][] = $sDateToArr;
}
if (isset ($aDates) && !empty ($aDates)) {
return $aDates;
} else {
return false;
}
}
/**
* function getDatesBetween
* renvoie un tableau contenant toutes les dates, jour par jour,
* comprises entre les deux dates passées en paramètre.
* NB : les dates doivent être au format aaaa-mm-dd (mais on peut changer le parsing)
* @param (string) $dStart : date de départ
* @param (string) $dEnd : date de fin
* @return (array) aDates : tableau des dates si succès
* @return (bool) false : si échec
*/
public function getDatesBetweenJustMonth ($dStart, $dEnd) {
$monthyear = [];
$holdmy = '';
$iStart = strtotime ($dStart);
$iEnd = strtotime ($dEnd);
if (false === $iStart || false === $iEnd) {
return false;
}
$aStart = explode ('-', $dStart);
$aEnd = explode ('-', $dEnd);
if (count ($aStart) !== 3 || count ($aEnd) !== 3) {
return false;
}
if (false === checkdate ($aStart[1], $aStart[2], $aStart[0]) || false === checkdate ($aEnd[1], $aEnd[2], $aEnd[0]) || $iEnd <= $iStart) {
return false;
}
for ($i = $iStart; $i < $iEnd + 86400; $i = strtotime ('+1 day', $i) ) {
$sDateToArr = strftime ('%Y-%m-%d', $i);
$sYear = substr ($sDateToArr, 0, 4);
$sMonth = substr ($sDateToArr, 5, 2);
$aDates[$sYear][$sMonth][] = $sDateToArr;
if (($sYear.'-'.$sMonth) != $holdmy) {
$monthyear[]= $sYear.'-'.$sMonth;
}
$holdmy = $sYear.'-'.$sMonth;
}
if (isset ($aDates) && !empty ($aDates)) {
return $monthyear;
} else {
return false;
}
}
/**
* json requette obtention détail de contrat remporté dans les Stats Général
*
* @param Request $request
* @Route("/stats/offrevendu", name="stats_offrevendu", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statsoffrevenduAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$lastDatei = $request->query->get('last_date');
$test = $this->getDatesBetweenJustMonth ($firstDate, $lastDatei);
$ctest = count($test);
$iterations = 1;
foreach ($test as $my) {
$mymonT = explode("-", $my);
if ($iterations == 1) {
$fdparam = $firstDate;
$ldparam = date("Y-m-t", strtotime($firstDate));
}elseif ($iterations == $ctest) {
$fdparam = $my.'-01';
$ldparam = $lastDate;
}else{
$fdparam = $my.'-01';
$ldparam = date("Y-m-t", strtotime($fdparam)). ' 23:59:59';
}
$rcl = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam, 2);
if( $rcl ){
$results['classique'][] = $rcl[0];
}else{
$results['classique'][] = ['number' => 0, 'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
}
$rsec = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam, 3);
if( $rsec ){
$results['securite'][] = $rsec[0];
}else{
$results['securite'][] = ['number' => 0, 'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
}
$rseren = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam, 4);
if ( $rseren) {
$results['serenite'][] = $rseren[0];
} else {
$results['serenite'][] = ['number' => 0, 'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
}
$plein = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldByDates($fdparam,$ldparam, 5);
if ( $plein) {
$results['plenitude'][] = $plein[0];
} else {
$results['plenitude'][] = ['number' => 0, 'month' => $mymonT[1], 'date' => $mymonT[1].'-'.$mymonT[0] ];
}
$iterations++;
}
/*
$results['classique'] = $classiqueT;
$results['securite'] = $securiteT;
$results['serenite'] = $sereniteT;
$results['plenitude'] = $plenitudeT;
*/
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention détail de contrat remporté dans les Stats Général
*
* @param Request $request
* @Route("/stats/offrevendupercentage", name="stats_offrevendupercentage", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function statsoffrevenduPercentageAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date');
$months = $this->getDatesBetweenJustMonth($firstDate, $lastDate);
$datas = [];
foreach ($months as $key1 => $month) {
$sql = "SELECT * FROM app.lots_geres_historic as lgh
INNER JOIN app.contract as c on c.id = lgh.contractId
INNER JOIN app.contract_offre_historic as coh on coh.contractId = c.id
INNER JOIN app.offre_tarif as ot on ot.id = coh.offreId
WHERE lgh.entryDate < :date2 and lgh.entryDate > :date1
AND coh.startDate BETWEEN :date1 and :date2 ";
$stmt = $em->getConnection()->prepare($sql);
$datemonth = new \DateTime($month.'-01');
$param1 = $datemonth->format('Y-m-d');
$param2 = $datemonth->format('Y-m-t').' 23:59:59';
$stmt->bindParam(':date1', $param1);
$stmt->bindParam(':date2', $param2);
$resultSet = $stmt->executeQuery();
$lghs = $resultSet->fetchAll();
$datas[$key1] = ['plenitude' => 0, 'securite' => 0, 'classique' => 0, 'serenite' => 0, 'date' => $datemonth->format('Y-m')];
foreach ($lghs as $key2 => $lgh) {
switch ($lgh['generic_id']) {
case 2:
$datas[$key1]['classique'] += 1;
break;
case 3:
$datas[$key1]['securite'] += 1;
break;
case 4:
$datas[$key1]['serenite'] += 1;
break;
case 5:
$datas[$key1]['plenitude'] += 1;
break;
}
}
$datas[$key1]['classique'] = count($lghs) == 0 ? 0 : $datas[$key1]['classique'] / count($lghs) * 100;
$datas[$key1]['securite'] = count($lghs) == 0 ? 0 : $datas[$key1]['securite'] / count($lghs) * 100;
$datas[$key1]['serenite'] = count($lghs) == 0 ? 0 : $datas[$key1]['serenite'] / count($lghs) * 100;
$datas[$key1]['plenitude'] = count($lghs) == 0 ? 0 : $datas[$key1]['plenitude'] / count($lghs) * 100;
}
$serializer = $this->_serializer;
$serializedResult = $serializer->serialize($datas, 'json');
$response = json_decode($serializedResult);
return new JsonResponse($response);
}
/**
* json requette obtention répartition instantanée des offres detaillée
*
* @param Request $request
* @Route("/stats/repartitionofrredetaill", name="stats_repartitionofrredetaill", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function getRepartitionOfrreDetaillAction(Request $request)
{
$classique = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(2);
$securite = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(3);
$serenite = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(4);
$plenitude = $this->getDoctrine->getRepository('AppBundle:LotsGeres')->getOffreSoldOnContract(5);
$results['classique'] = $classique;
$results['securite'] = $securite;
$results['serenite'] = $serenite;
$results['plenitude'] = $plenitude;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* json requette obtention répartition instantanée des Churn
*
* @param Request $request
* @Route("/stats/repartitionchurndetaill", name="stats_repartitionchurndetaill", options={"expose"=true})
* @Method({"GET","POST"})
* @return JsonResponse
*/
public function getRepartitionChurnDetaillAction(Request $request)
{
$rais0 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(0);
$results['rais0'] = $rais0;
$rais1 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(1);
$results['rais1'] = $rais1;
$rais2 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(2);
$results['rais2'] = $rais2;
$rais3 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(3);
$results['rais3'] = $rais3;
$rais4 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(4);
$results['rais4'] = $rais4;
$rais5 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(5);
$results['rais5'] = $rais5;
$rais6 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(6);
$results['rais6'] = $rais6;
$rais7 = $this->getDoctrine->getRepository('AppBundle:Churn')->getChurnDispach(7);
$results['rais7'] = $rais7;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre de locataires inscrits par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByGraphRenterdate", name="stats_graph_renter_date", options={"expose"=true})
*/
public function statsByGraphRenterDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$subscriptions = $this->getDoctrine->getRepository('AppBundle:User')->getTenantRenterByDates($firstDate,$lastDate);
$results['subscriptions'] = $subscriptions;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre de propriétaires inscrits par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByGraphOwnerdate", name="stats_graph_owner_date", options={"expose"=true})
*/
public function statsByGraphOwnerDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$subscriptions = $this->getDoctrine->getRepository('AppBundle:User')->getTenantOwnerByDates($firstDate,$lastDate);
$results['subscriptions'] = $subscriptions;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre d'annonces par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/flats-by-date", name="stats_flats_by_date", options={"expose"=true})
*/
public function statsFlatsByDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$flats = $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatByDates($firstDate, $lastDate, $request->query->get('status'));
$results['flats'] = $flats;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre d'annonces avec offre payante par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/flats-vip-by-date", name="stats_flats_vip_by_date", options={"expose"=true})
*/
public function statsFlatsVipByDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$flats = $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatVipDates($firstDate, $lastDate);
$results['flats'] = $flats;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre d'annonces, qui ont été publiées et qui ne le sont plus, par mois entre deux dates
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/flats-unpublished-by-date", name="stats_flats_unpublished_by_date", options={"expose"=true})
*/
public function statsFlatsUnpublishedByDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$flats = $this->getDoctrine->getRepository('AppBundle:Flat')->getFlatUnpublishedByDates($firstDate, $lastDate);
$results['flatsu'] = $flats;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre de mandats par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/mandates-by-date", name="stats_mandates_by_date", options={"expose"=true})
*/
public function statsMandatesByDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$mandates = $this->getDoctrine->getRepository('AppBundle:Mandate')->countByMonthAndDates($firstDate, $lastDate);
$results['mandates'] = $mandates;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre de candidatures par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByCandidatdate", name="stats_candidat_date", options={"expose"=true})
*/
public function statsByCandidatDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$candidats = $this->getDoctrine->getRepository('AppBundle:Application')->getApplicationByDates($firstDate,$lastDate);
$results['candidats'] = $candidats;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer le nombre de contrats par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByBauxdate", name="stats_baux_date", options={"expose"=true})
*/
public function statsByBauxDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$baux = $this->getDoctrine->getRepository('AppBundle:DocumentSignature')->getSignedByDates($firstDate,$lastDate);
$results['baux'] = $baux;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Récupérer les nombre de connexion par mois
*
* @param Request $request
* @return JsonResponse
* @Route("/stats/ByConnexiondate", name="stats_connexion_date", options={"expose"=true})
*/
public function statsByConnexionDateAction(Request $request)
{
$firstDate = $request->query->get('first_date');
$lastDate = $request->query->get('last_date'). ' 23:59:59';
$connexion = $this->getDoctrine->getRepository('AppBundle:UserHistoric')->getConnexionByDates($firstDate,$lastDate);
$results['connexion'] = $connexion;
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
/**
* Lister les annonces
*
* @Route("/flat/listing", name="flatListing")
* @return Response
*/
public function flatListingAction()
{
//$datatable = $this->get('app.datatable.flat');
//$datatable->buildDatatable();
$datatable = $this->dtFactory->create(FlatDatatable::class);
$datatable->buildDatatable();
return $this->render('Extranet/index.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Lister les annonces
*
* @Route("/flat/listingexport", name="flatListingexport")
* @return Response
*/
public function flatexpListingAction()
{
$datatable = $this->get('app.datatable.flatexp');
$datatable->buildDatatable();
return $this->render('Extranet/multidiffusion.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les annonces
*
* @Route("/flat/results", name="flat_results")
*/
public function indexFlatResultsAction()
{
$datatable = $this->dtFactory->create(FlatDatatable::class);
$datatable->buildDatatable();
$query = $this->dtResponse;
$query->setDatatable($datatable);
$query->getDatatableQueryBuilder();
return $query->getResponse();
//$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
//return $query->getResponse();
}
/**
* Filtrer les annonces
*
* @Route("/flat/resultsexp", name="flat_resultsexp")
*/
public function indexFlatResultsexpAction()
{
$datatable = $this->get('app.datatable.flatexp');
$datatable->buildDatatable();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
return $query->getResponse();
}
/**
* Lister les
*
* @Route("/glireprisebailbo/listing", name="glireprisebailboardListingbo")
* @return Response
*/
public function glireprisebailListingAction()
{
$datatable = $this->dtFactory->create(ReprisBailDatatable::class);
//$datatable = $this->get('app.datatable.reprisebail');
$datatable->buildDatatable();
return $this->render('Extranet/reprisebaillist.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les
*
* @Route("/glireprisebailboard/resultsbo", name="glireprisebail_resultsbo")
*/
public function indexglireprisebailResultsAction()
{
$datatable = $this->get('app.datatable.reprisebail');
$datatable->buildDatatable();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
return $query->getResponse();
}
/**
* Lister les candidatures
*
* @Route("/applicationboard/listing", name="applicationboardListing")
* @return Response
*/
public function applicationboardListingAction()
{
$datatable = $this->get('app.datatable.application');
$datatable->buildDatatable();
return $this->render('Extranet/application.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les candidatures
*
* @Route("/applicationboard/results", name="applicationboard_results")
*/
public function indexApplicationboardResultsAction()
{
$datatable = $this->get('app.datatable.application');
$datatable->buildDatatable();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
return $query->getResponse();
}
/**
* Lister les utilisateurs
*
* @Route("/user/listing", name="userListing")
* @return Response
*/
public function userListingAction(Request $request)
{
$isAjax = $request->isXmlHttpRequest();
//$datatable = $this->get('app.datatable.user');
$datatable = $this->dtFactory->create(UserDatatable::class);
$datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
if ($isAjax) {
$responseService = $this->dtResponse;
$responseService->setDatatable($datatable);
$responseService->getDatatableQueryBuilder();
return $responseService->getResponse();
}
return $this->render('Extranet/users.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les utilisateurs
*
* @Route("/user/results", name="user_results")
*/
public function indexResultsAction()
{
$datatable = $this->dtFactory->create(UserDatatable::class);
$datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
$query = $this->dtResponse;
$query->setDatatable($datatable);
$query->getDatatableQueryBuilder();
return $query->getResponse();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
$function = function($qb)
{
$qb->andWhere("user.name <> :name");
$qb->setParameter('name', 'proprietaire');
};
$query->addWhereAll($function);
return $query->getResponse();
}
/**
* Lister les lots en vacances locative
*
* @Route("/listlotsenvacances", name="listlotsenvacances")
* @return Response
*/
public function listlotsenvacancesAction()
{
$data = [];
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sthd = $bdd->prepare("SELECT c.id as 'contrat', prop.name as 'pnom',prop.firstname as 'pprenom',
loc.name as 'lnom',loc.firstname as 'lprenom',
CONCAT(\"https://app.wizi.eu/contract/edit/\",c.id) AS lien
FROM app.lots_geres as l
INNER JOIN app.contract as c on c.id = l.contract
INNER JOIN app.application as a on a.id = c.application_id
INNER JOIN app.flat as fl on fl.id = a.flat
INNER JOIN app.user as prop on prop.id = fl.owned_by_id
INNER JOIN app.user as loc on loc.id = a.user
WHERE c.status = 4 and l.flat not in (select flat from app.churn)
and l.flat not in (
select fl.id from contract as c
INNER JOIN app.application as a on a.id = c.application_id
INNER JOIN app.flat as fl on fl.id = a.flat
where c.status = 2
);");
$sthd->execute();
$data = $sthd->fetchAll(\PDO::FETCH_ASSOC);
return $this->render('Extranet/vacloc.html.twig', array(
'data' => $data,
));
}
/*
-------------
*/
/**
* Lister les utilisateurs
*
* @Route("/userlistingreview", name="userListingreview")
* @return Response
*/
public function userListingreviewAction()
{
$datatable = $this->get('app.datatable.userreview');
$datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
return $this->render('Extranet/usersreview.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les utilisateurs
*
* @Route("/userresultsreview", name="user_resultsreview")
*/
public function indexResultsreviewAction()
{
$datatable = $this->get('app.datatable.userreview');
$datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
$function = function($qb)
{
$qb->andWhere("user.name <> :name");
$qb->setParameter('name', 'proprietaire');
$qb->andWhere("user.suiviStatus = :suivistat");
$qb->setParameter('suivistat', 99);
$qb->andWhere("user.suivipar = :suivipar");
$qb->setParameter('suivipar', $this->getUser()->getId());
};
$query->addWhereAll($function);
return $query->getResponse();
}
/**
* mettre des utilisateur en statut portefeuille
*
* @Route("/userreviewdispatch/{number}", name="userreviewdispatch", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function userReviewDispachAction(Request $request, $number)
{
// jo
$sql = "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
$namedb = $this->getParameter('dbreqpdo');
$conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$stmt1 = $conn->prepare($sql);
$stmt1->execute();
$result = $stmt1->fetchAll(\PDO::FETCH_ASSOC);
foreach ($result as $s){
$sqlupdate = "update app.user set suivistatus = 99, suivipar = 29896 where id = ".$s['id'];
$stmt2 = $conn->prepare($sqlupdate);
$stmt2->execute();
}
// sandra
$sql = "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
$namedb = $this->getParameter('dbreqpdo');
$conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$stmt1 = $conn->prepare($sql);
$stmt1->execute();
$result = $stmt1->fetchAll(\PDO::FETCH_ASSOC);
foreach ($result as $s){
$sqlupdate = "update app.user set suivistatus = 99, suivipar = 81354 where id = ".$s['id'];
$stmt2 = $conn->prepare($sqlupdate);
$stmt2->execute();
}
// Hadrien
$sql = "SELECT * FROM app.user where suivipar is null and initial_mode = 2 and suivistatus is null order by id desc limit ".$number;
$namedb = $this->getParameter('dbreqpdo');
$conn = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$stmt1 = $conn->prepare($sql);
$stmt1->execute();
$result = $stmt1->fetchAll(\PDO::FETCH_ASSOC);
foreach ($result as $s){
$sqlupdate = "update app.user set suivistatus = 99, suivipar = 120144 where id = ".$s['id'];
$stmt2 = $conn->prepare($sqlupdate);
$stmt2->execute();
}
return new JsonResponse('ok');
}
/**
* compter les leads a traiter revue de portefeuil
*
* @param Request $request
* @return JsonResponse
* @Route("/countmyleadreview", name="countmyleadreview", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countmyleadreviewAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
$sql = "SELECT count(*) as res
FROM app.user as u ";
$condition = ' where (suivipar LIKE "'.$suivipar.'" and suivistatus = 99 ) ';
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
return New JsonResponse($max); //
}
/**
* compter les leads review dans team stat
*
* @param Request $request
* @return JsonResponse
* @Route("/countmyleadreviewstat/{id}", name="countmyleadreviewstat", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countmyleadreviewstatAction($id)
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $id;
$sql = "SELECT count(*) as res
FROM app.user as u ";
$condition = ' where (suivipar LIKE "'.$suivipar.'" and suivistatus = 99 ) ';
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
return New JsonResponse($max); //
}
/*
-------------
*/
/**
* Créer un utilisateur
*
* @Route("/user/add", name="addUser", options={"expose"=true})
* @param Request $request
* @return Response
*/
public function addUserAction(Request $request)
{
$user = new User();
$form = $this->createForm('App\AppBundle\Form\UserType', $user, [
'renter_status' => $this->getParameter('renter_status'),
'owner_status' => $this->getParameter('owner_status'),
'initial_mode' => $this->getParameter('user_status')
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newUser = $form->getData();
$em = $this->getDoctrine->getManager();
$em->persist($newUser);
$em->flush();
return $this->redirectToRoute('userListing');
}
return $this->render('Extranet/Security/addUser.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Créer une annonce
*
* @Route("/flat/add", name="addFlat", options={"expose"=true})
* @param Request $request
* @return Response
*/
public function addFlatAction(Request $request)
{
$flat = new Flat();
$form = $this->createForm('App\AppBundle\Form\FlatType', $flat,['flat_status' => $this->getParameter('flat_status')]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newFlat = $form->getData();
$em = $this->getDoctrine->getManager();
$em->persist($newFlat);
$em->flush();
return $this->redirectToRoute('flatListing');
}
return $this->render('Extranet/add.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Duppliquer une annonce
*
* @Route("/flat/duplicate/{id}", name="duplicateFlat", options={"expoe"=true})
* @Method({"GET","POST"})
* @param Request $request
* @param integer $id
* @return $thiss
*/
public function duplicateFlatAction(Request $request, $id)
{
$em = $this->getDoctrine->getManager();
$flatsManager = $em->getRepository('App\AppBundle\Entity\Flat');
$flat = $flatsManager->find($id);
//$flat = new Flat();
$newflat = new Flat();
$newflat->setAdress($flat->getAdress());
$newflat->setBedrooms($flat->getBedrooms());
$newflat->setCanMultidif($flat->getCanMultidif());
$newflat->setCharges($flat->getCharges());
$newflat->setOffre($flat->getOffre());
$newflat->setOffreVendue($flat->getOffreVendue());
$newflat->setOffreContract($flat->getOffreContract());
$newflat->setScoreSl($flat->getScoreSl());
$newflat->setScoreLbc($flat->getScoreLbc());
$newflat->setScoreGr($flat->getScoreGr());
$newflat->setScoreFb($flat->getScoreFb());
$newflat->setEvermulti($flat->getEvermulti());
$newflat->setIsSci($flat->getIsSci());
$newflat->setSiren($flat->getSiren());
$newflat->setCompanyName($flat->getCompanyName());
$newflat->setCompanyCountry($flat->getCompanyCountry());
$newflat->setCompanyCity($flat->getCompanyCity());
$newflat->setCompanyAddress($flat->getCompanyAddress());
$newflat->setCompanyPostalCode($flat->getCompanyPostalCode());
$newflat->setMeuble($flat->getMeuble());
$newflat->setInsurance($flat->getInsurance());
$newflat->setOwnedBy($flat->getOwnedBy());
$newflat->setDescription($flat->getDescription());
$newflat->setTitle($flat->getTitle().' (COPIE)');
$newflat->setLogementType($flat->getLogementType());
$newflat->setSurface($flat->getSurface());
$newflat->setPrice($flat->getPrice());
$newflat->setCharges($flat->getCharges());
$newflat->setFloors($flat->getFloors());
$newflat->setBedrooms($flat->getBedrooms());
$newflat->setLongitude($flat->getLongitude());
$newflat->setLatitude($flat->getLatitude());
$newflat->setCity($flat->getCity());
$newflat->setCountry($flat->getCountry());
$newflat->setAdress($flat->getAdress());
$newflat->setPostalCode($flat->getPostalCode());
$newflat->setStatus($flat->getStatus());
$newflat->setDpe($flat->getDpe());
$newflat->setGes($flat->getGes());
$newflat->setCurrencyUnit($flat->getCurrencyUnit());
$fd = $flat->getFullDescription();
// full description
$fulldescription = new FlatDescription();
$fulldescription->setType($fd->getType());
$fulldescription->setNiceView($fd->getNiceView());
$fulldescription->setBalcony($fd->getBalcony());
$fulldescription->setTerrace($fd->getTerrace());
$fulldescription->setElevator($fd->getElevator());
$fulldescription->setOpticalFiber($fd->getOpticalFiber());
$fulldescription->setParking($fd->getParking());
$fulldescription->setAirConditioner($fd->getAirConditioner());
$fulldescription->setGarden($fd->getGarden());
$fulldescription->setGarage($fd->getGarage());
$em->persist($fulldescription);
$em->flush();
$newflat->setFullDescription($fulldescription);
$em->persist($newflat);
$em->flush();
$docs = $flat->getDocuments();
foreach ($docs as $doc){
$newflat->addDocument($doc);
}
$em->persist($newflat);
$em->flush();
// plusieurs propriétaires
$flprops = $flat->getFlatprops();
foreach ($flprops as $fp){
$newflprop = new FlatProp();
$newflprop->setAdress($fp->getAdress());
$newflprop->setBio($fp->getBio());
$newflprop->setCity($fp->getCity());
$newflprop->setCountry($fp->getCountry());
$newflprop->setEmail($fp->getEmail());
$newflprop->setCreatedAt($fp->getCreatedAt());
$newflprop->setFirstname($fp->getFirstname());
$newflprop->setMobilePhone($fp->getMobiePhone());
$newflprop->setName($fp->getName());
$newflprop->setPostalCode($fp->getPostalCode());
$newflprop->setFlatRef($newflat);
$em->persist($newflprop);
$em->flush();
}
// return new Response('ok');
$newid = $newflat->getId();
return $this->redirect( $this->generateUrl('editFlat', array('id' => $newid)) );
}
/**
* Modifier une annonce
*
* @Route("/flat/edit/{id}", name="editFlat", options={"expose"=true})
* @param Request $request
* @param integer $id
* @return $this
*/
public function editFlatAction(Request $request, $id)
{
$em = $this->getDoctrine;
$flatsManager = $em->getRepository('App\AppBundle\Entity\Flat');
$flat = $flatsManager->find($id);
$initialFlat = clone($flat);
$recompenses = $em->getRepository('App\AppBundle\Entity\Recompense')->findAll();
$form = $this->createForm('App\AppBundle\Form\FlatType', $flat,['flat_status' => $this->getParameter('flat_status')]);
$form->handleRequest($request);
$deleteForm = $this->createFlatDeleteForm($id);
if ($form->isSubmitted() && $form->isValid()) {
$newFlat = $form->getData();
$em = $this->getDoctrine->getManager();
$em->persist($newFlat);
$em->flush();
// file_put_contents('./debugnotifadmin.txt', '$flat->getStatus()'.$initialFlat->getStatus().PHP_EOL, FILE_APPEND);
// file_put_contents('./debugnotifadmin.txt', '$newFlat->getStatus()'.$newFlat->getStatus().PHP_EOL, FILE_APPEND);
/*
* gestion des notifs de publications
*/
if ($initialFlat->getStatus() == 1 && $newFlat->getStatus() == 2){
$datePublication = new \DateTime();
$newFlat->setPublishAt($datePublication);
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$usernotif = $userManager->find($newFlat->getOwnedBy());
$description = "Annonce ".$newFlat->getId()." publiée par Wizi";
// adminnotif 26
$notifier = $this->get('app.notifparse');
$notifier->doAll( 26, 'Flat',$newFlat->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($usernotif);
$notification->setDescription($description);
$notification->setIcon('far fa-newspaper icon');
$notification->setColor('#717171');
$notification->setLink('/#/app/search');
$em->persist($notification);
$em->flush();
*/
}
/*
* gestion des notifs de depublications
*/
if ($initialFlat->getStatus() == 2 && $newFlat->getStatus() == 1){
$datePublication = new \DateTime();
$newFlat->setPublishAt($datePublication);
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$usernotif = $userManager->find($newFlat->getOwnedBy());
$description = "Annonce ".$newFlat->getId()." dépubliée par Wizi";
// adminnotif 27
$notifier = $this->get('app.notifparse');
$notifier->doAll( 27, 'Flat',$newFlat->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($usernotif);
$notification->setDescription($description);
$notification->setIcon('far fa-newspaper icon');
$notification->setColor('#717171');
$notification->setLink('/#/app/search');
$em->persist($notification);
*/
if($flat->getApplications()){
foreach ($flat->getApplications() as $application){
if($application->getStatus() != 3){
// desactivavion des refus auto de candidature lors de dépublications annonces
// $application->setStatus(3);
// $notification = new Notification();
// $notification->setEmplacement('notif');
// $notification->setUser($application->getUser());
// $notification->setDescription('Annonce '.$flat->getId().' : '.$flat->getOwnedBy()->getFirstname().' '.$flat->getOwnedBy()->getName().' a refusé votre candidature');
// $notification->setColor('#e74c3c');
// $notification->setIcon('far fa-sad-tear icon');
// $em->persist($notification);
// $em->persist($application);
}
}
}
$em->flush();
}
return $this->redirectToRoute('flatListing');
}
$em = $this->getDoctrine;
$flatsManager = $em->getRepository('App\AppBundle\Entity\FlatHistoric');
$applyManager = $em->getRepository('App\AppBundle\Entity\Application');
$flatHistorics = $flatsManager->findBy(['flat' => $flat],['id'=>'DESC']);
$flatAppls = $applyManager->findBy(['flat' => $flat],['id'=>'DESC']);
/* regarder l'éxistance de contrats */
$arraycontrats = [];
foreach ($flatAppls as $flatAppl) {
$c = $flatAppl->getContract();
if($c != null && $c->getStatus() == 2){
$arraycontrats[]= $c;
}
}
$flatsVideos = $em->getRepository('App\AppBundle\Entity\VideoTask')
->findBy(['objectName' => 'Flat','objectId' => $flat->getId()],['id'=>'DESC']);
$nbvideo = 0;
if (count($flatsVideos) == 1) {
$nbvideo = 1;
}
/*le candidats seloger non inscrits */
$electedfl = $id;
$res = [];
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=app;charset=utf8', 'root', 'ahv2Ohchaik0');
$bddSchortlink = new \PDO('mysql:host=localhost;dbname=wzishortlink;charset=utf8', 'root', 'ahv2Ohchaik0');
$sql = "SELECT mailUser,appliDate,tel,flatUrl,idfl FROM app.multidif_user
where
multidif_user.idfl = ".$electedfl." AND
multidif_user.tel not in (select username from app.user)";
$sthd2 = $bdd->prepare($sql);
$sthd2->execute();
$users = $sthd2->fetchAll(\PDO::FETCH_ASSOC);
$res = $users;
/*le candidats seloger n on inscrits */
return $this->render('Extranet/add.html.twig', array(
'form' => $form->createView(),
'flat' => $flat,
'flatHistorics' => $flatHistorics,
//'flatHistorics' => array(),
'flatAppls' => $flatAppls,
'deleteForm' => $deleteForm->createView(),
'recompenses' => $recompenses,
'nbvideo' => $nbvideo,
'selogeruser'=> $res,
'contratsactif' => $arraycontrats
));
}
/**
* Récupérer la dropzone des images d'une annonce
* @Route("/flat/get-documents-content/{id}", name="flat_get_documents_content", options={"expose"=true})
* @Method("GET")
*
* @param $id
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getDocumentsContentAction($id)
{
return $this->render(':Extranet/Flat:_documents_content.html.twig', [
'flatId' => $id,
]);
}
/**
* Lister les images d'une annonce
*
* @Route("/flat/get-documents-data/{id}", name="flat_get_documents_data")
* @Method("GET")
*
* @param $id
* @return JsonResponse
*/
public function getDocumentsDataAction($id)
{
$em = $this->getDoctrine->getManager();
$flat = $em->getRepository('AppBundle:Flat')->find($id);
$documents = [];
foreach ($flat->getDocuments() as $document) {
if ($document->getCategory() == 'full_picture') {
$documents[] = $document;
}
}
$serializer = $this->_serializer;
$serializedDocuments = $serializer->serialize($documents, 'json');
return new JsonResponse($serializedDocuments);
}
/**
* Modifier un utilisateur
*
* @Route("/user/edit/{id}", name="editUser", options={"expose"=true})
* @param Request $request
* @param integer $id
* @return $this
*/
public function editUserAction(Request $request, $id)
{
$em = $this->getDoctrine;
$usersManager = $em->getRepository('App\AppBundle\Entity\User');
$recompenses = $em->getRepository('App\AppBundle\Entity\Recompense')->findAll();
$user = $usersManager->find($id);
$sms = 'undefined';
$email = 'undefined';
$push = 'undefined';
/*
* rgpd
*/
$repositoryone = $em->getRepository('AppBundle:UserRgpdAutorisation');
$repositorytwo = $em->getRepository('AppBundle:RgpdAutorisation');
$rgpdautorisation = $repositorytwo->findAll();
$userrgpdautorisations = $repositoryone->findByUser($user);
$tab = [];
$i = 0;
foreach ($rgpdautorisation as $a){
foreach ($userrgpdautorisations as $r){
if($r->getCodemessagesource() == $a->getCodemessage()){
if($r->getCodemessagesource() == 'sms_autorisation') {
$sms = $r->getSwiped();
}
if($r->getCodemessagesource() == 'push_autorisation') {
$push = $r->getSwiped();
}
if($r->getCodemessagesource() == 'email_autorisation') {
$email = $r->getSwiped();
}
$tab[$i] = $r;
}
}
$i++;
}
/*
* fin rgpd
*/
$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')] );
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newUser = $form->getData();
$em = $this->getDoctrine->getManager();
if($user->isEnabled() && !$newUser->isEnabled()){
// adminnotif 28
$notifier = $this->get('app.notifparse');
$notifier->doAll( 28, 'User',$user->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($user);
$notification->setDescription('Wizi a désactivé le compte de "'.$newUser->getFirstname().' '.$newUser->getName().'".');
$notification->setIcon('far fa-times-square icon');
$notification->setColor('#e74c3c');
$em->persist($notification);
*/
$variables = '{"firstname": "' . $user->getFirstname() . '"}';
$this->get('app.mailjet')->sendMailjet(480160, $user->getEmail(), $variables, 'Votre compte a été désactivé');
if($user->getApplications()){
foreach ($user->getApplications() as $application){
$application->setStatus(3);
$application->setRemoved(true);
$em->persist($application);
// adminnotif 29
$notifier = $this->get('app.notifparse');
$notifier->doAll( 29, 'Application',$application->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : '.$user->getFirstname().' '.$user->getName().'" a retiré sa candidature');
$notification->setIcon('far fa-times-square icon');
$em->persist($notification);
*/
}
$em->flush();
}
if($user->getFlats()){
foreach ($user->getFlats() as $flat){
$flat->setStatus(1);
// adminnotif 30
$notifier = $this->get('app.notifparse');
$notifier->doAll( 30, 'Flat',$flat->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($user);
$notification->setDescription('Annonce '.$flat->getId().' : dépubliée');
$notification->setIcon('far fa-newspaper icon');
$notification->setColor('#717171');
$em->persist($notification);
*/
foreach ($flat->getApplications() as $application){
$application->setStatus(3);
$em->persist($application);
// adminnotif 31
$notifier = $this->get('app.notifparse');
$notifier->doAll( 31, 'Application',$application->getId(),'notif');
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getUser());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : '.$user->getFirstname().' '.$user->getName().'" a refusé votre candidature');
$notification->setColor('#e74c3c');
$notification->setIcon('far fa-sad-tear icon');
$em->persist($notification);
*/
}
$em->flush();
}
}
}
$em->persist($newUser);
$em->flush();
// return $this->redirectToRoute('userListing');
}
$em = $this->getDoctrine;
$usersManager = $em->getRepository('App\AppBundle\Entity\UserHistoric');
$userHistorics = $usersManager->findBy(['modifiedUser' => $user, 'action' => null],['id'=>'DESC']);
/**
recherche aircall sur user
*/
$usertel = $user->getMobilePhone();
$usertelwithoutspace = str_replace ( ' ' , '' , $usertel );
$telWttire = str_replace ( '-' , '' , $usertelwithoutspace );
$myphonelib = \libphonenumber\PhoneNumberUtil::getInstance();
try {
$thistestlibph = $myphonelib->parse($telWttire, PhoneNumberUtil::UNKNOWN_REGION);
} catch(\Exception $e){
}
//$thistestlibph = $this->get('libphonenumber.phone_number_util')->parse($telWttire, PhoneNumberUtil::UNKNOWN_REGION);
if($telWttire[0] != '+'){
$formatednumber = '+33 '.$telWttire[1].' '.$telWttire[2].$telWttire[3].' '.$telWttire[4].$telWttire[5].' '.$telWttire[6].$telWttire[7].' '.$telWttire[8].$telWttire[9];
}
elseif($telWttire[0].$telWttire[1].$telWttire[2] == '+33')
{
$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];
}
elseif($telWttire[0].$telWttire[1].$telWttire[2] == '+32')
{
$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];
}
$mycalls = $em->getRepository('AppBundle:AircallCall')->findByRawDigits($formatednumber);
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$sthd = $bdd->prepare("SELECT com.firstname, com.name FROM app.distrib_flat as df
inner join app.user as u on u.id = df.user
inner join app.user as com on df.commercial = com.id
where u.id = ".$user->getId());
$sthd->execute();
$resultd = $sthd->fetchAll(\PDO::FETCH_ASSOC);
$tikets = $em->getRepository('App\AppBundle\Entity\Ticket')->findBy(['userLink' => $id] );
$notifsBo = [];
foreach ($user->getNotificationsBo() as $key => $item) {
$notifsBo[$key]['id'] = $item->getId();
$notifsBo[$key]['createdAt'] = $item->getCreatedAt();
$notifsBo[$key]['description'] = $item->getDescription();
$notifsBo[$key]['exp'] = $item->getExp();
$notifsBo[$key]['dest'] = $item->getDest();
$notifsBo[$key]['link'] = $item->getLink();
$notifsBo[$key]['status'] = $item->getStatus();
$notifsBo[$key]['typeofnot'] = $item->getTypeOfnot();
$notifsBo[$key]['idoftype'] = $item->getIdOfType();
if($item->getTypeOfnot() == 'chat') {
$thisMessage = $em->getRepository('App\AppBundle\Entity\Message')->find($item->getIdOfType());
if($thisMessage->getDocument()) {
$notifsBo[$key]['document'] = $thisMessage->getDocument()->getId();
}
}
}
return $this->render('Extranet/Security/addUser.html.twig', array(
'form' => $form->createView(),
'user' => $user,
'notifsBo' => $notifsBo,
//'userHistorics' => array(),
'userHistorics' => $userHistorics,
'calls' => $mycalls,
'rgpd' => $tab,
'sms' => $sms,
'push' => $push,
'email' => $email,
'userinitial' => $resultd,
'tickets' => $tikets,
'recompenses' => $recompenses
));
}
/**
* Ajouter un loc secondaire
*
* @Route("/test/addlocform/{user}", name="testaddlocform", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function addlocformAction(Request $request, User $user)
{
$em = $this->get('doctrine')->getManager();
$entity = new UserLoc();
$entity->setOwnedBy($user);
$em->persist($entity);
$em->flush();
// Puis on redirige vers la page de visualisation de cet article
return $this->redirect( $this->generateUrl('editUser', array('id' => $user)) );
//return $this->render('Etl/locform.html.twig', array());
}
/**
* supprimer un loc secondaire
*
* @Route("/test/supplocform/{user}/{userloc}", name="testaddlocformsupp", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function supplocformAction(Request $request, User $user, UserLoc $userloc)
{
$em = $this->get('doctrine')->getManager();
$em->remove($userloc);
$em->flush();
// Puis on redirige vers la page de visualisation de cet article
return $this->redirect( $this->generateUrl('editUser', array('id' => $user)) );
//return $this->render('Etl/locform.html.twig', array());
}
/**
* Traiter le formulaire d'un propriétaire secondaire
*
* @param Request $request
* @param UserLoc $entity
*
* @return JsonResponse
*
* @Route("/editflatpropbo", name="edit_flatprop_bo", options={"expose"=true}, methods={"POST"})
*/
public function editflatpropboAction(Request $request)
{
// UserLoc
$logger = $this->get('logger');
$em = $this->getDoctrine->getManager();
$request_body = $request->getContent();
$logger->critical($request_body);
$request_bodyArray = array();
$request_bodyArray = \json_decode($request_body, true);
$reencode = \json_encode($request_bodyArray);
$arr = $request_bodyArray;
// file_put_contents('/home/app/public_html3/locsecondaire.txt', $this->get('request')->request->get('userLoc_periodeEssai'), FILE_APPEND);
$userloc = $em->getRepository('AppBundle:FlatProp')->find($this->get('request')->request->get('userLoc_id'));
$userloc->setName($this->get('request')->request->get('userLoc_name'));
$userloc->setFirstname($this->get('request')->request->get('userLoc_firstname'));
$userloc->setEmail($this->get('request')->request->get('userLoc_email'));
$userloc->setCountry($this->get('request')->request->get('userLoc_country'));
$userloc->setCity($this->get('request')->request->get('userLoc_city'));
$userloc->setAdress($this->get('request')->request->get('userLoc_adress'));
$userloc->setPostalCode($this->get('request')->request->get('userLoc_postalCode'));
$userloc->setBio($this->get('request')->request->get('userLoc_bio'));
$userloc->setMobilePhone($this->get('request')->request->get('userLoc_mobilePhone'));
$userloc->setUpdatedAt(new \DateTime());
$userloc->setBirthdate(new \DateTime($this->get('request')->request->get('userLoc_birthdate')));
$userloc->setJob($this->get('request')->request->get('userLoc_job'));
$userloc->setNationalite($this->get('request')->request->get('userLoc_nationalite'));
$userloc->setBirthplace($this->get('request')->request->get('userLoc_birthplace'));
////
$em->persist($userloc);
$em->flush();
//$entity->setOwnedBy($this->getUser());
//$em->persist($entity);
//$em->flush();
$response = new Response();
$response->setContent(json_encode($this->get('request')->request->get('userLoc_periodeEssai')));
$response->setStatusCode('200');
return $response;
}
/**
* Ajouter un proprietaire secondaire
*
* @Route("/test/addpropsec/{flat}", name="testaddpropsec", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function addpropsecformAction(Request $request, Flat $flat)
{
$em = $this->get('doctrine')->getManager();
$entity = new FlatProp();
$entity->setFlatRef($flat);
$em->persist($entity);
$em->flush();
// Puis on redirige vers la page de visualisation de cet article
return $this->redirect( $this->generateUrl('editFlat', array('id' => $flat->getId())) );
//return $this->render('Etl/locform.html.twig', array());
}
/**
* supprimer un loc secondaire
*
* @Route("/test/supppropsec/{flat}/{flatprop}", name="testsupppropsec", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function supppropsecAction(Request $request, Flat $flat, FlatProp $flatprop )
{
$em = $this->get('doctrine')->getManager();
$em->remove($flatprop);
$em->flush();
// Puis on redirige vers la page de visualisation de cet article
return $this->redirect( $this->generateUrl('editFlat', array('id' => $flat->getId())) );
//return $this->render('Etl/locform.html.twig', array());
}
/**
* Traiter le formulaire d'un locataire utilisateur
*
* @param Request $request
* @param UserLoc $entity
*
* @return JsonResponse
*
* @Route("/edituserlocform", name="edit_user_loc_bo", options={"expose"=true}, methods={"POST"})
*/
public function editUserLocFormAction(Request $request)
{
// UserLoc
$logger = $this->get('logger');
$em = $this->getDoctrine->getManager();
$request_body = $request->getContent();
$logger->critical($request_body);
$request_bodyArray = array();
$request_bodyArray = \json_decode($request_body, true);
$reencode = \json_encode($request_bodyArray);
$arr = $request_bodyArray;
$userloc = $em->getRepository('AppBundle:UserLoc')->find($this->get('request')->request->get('userLoc_id'));
$userloc->setName($this->get('request')->request->get('userLoc_name'));
$userloc->setFirstname($this->get('request')->request->get('userLoc_firstname'));
$userloc->setEmail($this->get('request')->request->get('userLoc_email'));
$userloc->setCountry($this->get('request')->request->get('userLoc_country'));
$userloc->setCity($this->get('request')->request->get('userLoc_city'));
$userloc->setAdress($this->get('request')->request->get('userLoc_adress'));
$userloc->setPostalCode($this->get('request')->request->get('userLoc_postalCode'));
$userloc->setBio($this->get('request')->request->get('userLoc_bio'));
$userloc->setMobilePhone($this->get('request')->request->get('userLoc_mobilePhone'));
$userloc->setUpdatedAt(new \DateTime());
$userloc->setIncome($this->get('request')->request->get('userLoc_income'));
$userloc->setRenterStatus($this->get('request')->request->get('userLoc_renterStatus'));
$userloc->setGarant($this->get('request')->request->get('userLoc_garant'));
$userloc->setBirthdate(new \DateTime($this->get('request')->request->get('userLoc_birthdate')));
$userloc->setPeriodeEssai($this->get('request')->request->get('userLoc_periodeEssai'));
$userloc->setDureeContrat($this->get('request')->request->get('userLoc_dureeContrat'));
$userloc->setGarantIncome($this->get('request')->request->get('userLoc_garantIncome'));
$userloc->setGarantStatus($this->get('request')->request->get('userLoc_garantStatus'));
$userloc->setGarantPeriodeEssai($this->get('request')->request->get('userLoc_garantPeriodeEssai'));
$userloc->setJob($this->get('request')->request->get('userLoc_job'));
$userloc->setNationalite($this->get('request')->request->get('userLoc_nationalite'));
$userloc->setBirthplace($this->get('request')->request->get('userLoc_birthplace'));
$em->persist($userloc);
$em->flush();
//$entity->setOwnedBy($this->getUser());
//$em->persist($entity);
//$em->flush();
$response = new Response();
$response->setContent(json_encode($this->get('request')->request->get('userLoc_periodeEssai')));
$response->setStatusCode('200');
return $response;
}
/**
* Créer un message
*
* @Route("/conversation/view", name="conversation_view", options={"expose"=true})
* @param Request $request
* @return $this
*/
public function conversationViewAction(Request $request)
{
$em = $this->getDoctrine->getRepository('AppBundle:Conversation');
$m = new Message($this->getUser2());
$form = $this->createForm('App\AppBundle\Form\MessageType', $m);
$form->add('save', ButtonType::class, [
'label' => 'Envoyer',
'attr' => [
'class' => 'btn btn-success submit',
],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$message = $form->getData();
$message->setUser($this->getUser2());
$em = $this->getDoctrine->getManager();
$em->persist($message);
$em->flush();
foreach ($message->getConversation()->getUsers() as $user) {
if($message->getUser()->getId() !== $user->getId()){
$notifBo = new NotificationBo();
$notifBo->setUser($message->getUser());
$temp = $message->getUser();
if($temp->hasRole('ROLE_ADMIN')){
$notifBo->setUser($user);
}else{
$notifBo->setUser($message->getUser());
}
$notifBo->setDescription($message->getContent());
$notifBo->setExp($message->getUser()->getId());
$notifBo->setDest($user->getId());
$notifBo->setTypeOfnot("chat");
$notifBo->setIdOfType($message->getId());
$em->persist($notifBo);
$em->flush();
}
// if($myexpediteur == $user ){
// $desc = "Vous avez reçu un message de ".$message->getUser()->getFirstname().' '.$message->getUser()->getName() ;
// $this->get('app.contract')->sendPush([$user->getDeviceToken()], 'Tchat Wizi', $desc);
// }
}
return $this->redirectToRoute('userListing');
}
$conversations = $em->userConversationsNotnul($this->getUser2(),10);
$allConversations = $em->userConversationsNotnul($this->getUser2(),1);
return $this->render('Extranet/Conversation/index.html.twig', array(
'form' => $form->createView(),
'conversations' => $conversations,
'allConversations' => $allConversations,
'user' => $this->getUser2(),
));
}
/**
* Créer un message
*
* @Route("/conversation/view/{id}", name="conversation_view_param")
* @param Request $request
* @return $this
*/
public function conversationViewMsgAction(Request $request, $id)
{
$em = $this->getDoctrine->getRepository('AppBundle:Conversation');
$form = $this->createForm('App\AppBundle\Form\MessageType', new Message($this->getUser2()));
$form->add('save', ButtonType::class, [
'label' => 'Envoyer',
'attr' => [
'class' => 'btn btn-success submit',
],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newUser = $form->getData();
$em = $this->getDoctrine->getManager();
$em->persist($newUser);
$em->flush();
return $this->redirectToRoute('userListing');
}
$conversation[] = $em->find($id);
return $this->render('Extranet/Conversation/index.html.twig', array(
'form' => $form->createView(),
'conversations' => $conversation,
'user' => $this->getUser2(),
));
}
/**
* Lister les conversations
*
* @Route("/conversation/filter/{data}", name="conversation_filter", methods={"GET"}, options={"expose"=true})
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function filterAction(Request $request, $data = null)
{
$em = $this->getDoctrine->getRepository('AppBundle:Conversation');
$conversations = $em->userConversations($this->getUser2(),10, null,$data);
return $this->render('Extranet/Conversation/timeline.html.twig', array(
'conversations' => $conversations,
));
}
/**
* Lister les conversations
*
* @Route("/maxTen/{from}/{data}", name="conversation_maxten", methods={"GET"}, options={"expose"=true})
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function maxTenAction(Request $request,$from, $data = null)
{
$em = $this->getDoctrine->getRepository('AppBundle:Conversation');
$conversations = $em->userConversationsNotnul($this->getUser2(),10, $from,$data);
return $this->render('Extranet/Conversation/list.html.twig', array(
'conversations' => $conversations,
));
}
/**
* Marquer une annonce à exporter sur les sites
*
* @Route("/flat/exportAdd/{id}", name="flat_export_add", options={"expose"=true})
*/
public function exportAddAction($id)
{
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setExported(true);
$em = $this->getDoctrine->getManager();
$em->flush();
$numberOfExportedFlats = $em->getRepository('AppBundle:Flat')->countExported();
$exportLogin = $this->getParameter('ftp_login');
$exportPassword = $this->getParameter('ftp_password');
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$urlResult = curl_exec ($url);
curl_close($url);
$exportLimit = 0;
$webSiteDatas = new \SimpleXMLElement($urlResult);
foreach ($webSiteDatas as $webSiteData) {
if (intval($webSiteData->nb_annonces_max) > $exportLimit) {
$exportLimit = intval($webSiteData->nb_annonces_max);
}
}
$message = '';
if ($exportLimit > 0 and $exportLimit < $numberOfExportedFlats) {
$message = "Vous avez dépassé la limite d'annonces à exporter.";
}
return new JsonResponse(['message' => $message]);
}
/**
* Marquer une annonce à exporter sur les sites
*
* @Route("/flat/exportselectAdd/{id}/{site}", name="flat_exportselect_add", options={"expose"=true})
*/
public function exportselectAddAction($id,$site)
{
/*
* sites :
* 1 tous les autres
* 2 le bon coin
* 3 seloger
*
*/
$message = '';
$exportLimit = 0;
switch ($site) {
case 1:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setExported(true);
$em = $this->getDoctrine->getManager();
$numberOfExportedFlats = $em->getRepository('AppBundle:Flat')->countExported();
$exportLimit = 0;
if ($exportLimit > 0 and $exportLimit < $numberOfExportedFlats) {
$message = "Vous avez dépassé la limite d'annonces à exporter.";
return new JsonResponse(['message' => $message]);
}else{
$em->flush();
$exportLogin = $this->getParameter('ftp_login');
$exportPassword = $this->getParameter('ftp_password');
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$urlResult = curl_exec ($url);
curl_close($url);
$message = "multidif site gratuit ajoute";
return new JsonResponse(['message' => $message]);
}
break;
case 2:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setLbcexport(true);
$em = $this->getDoctrine->getManager();
$numberOfExportedFlats = $em->getRepository('AppBundle:Flat')->countLbcexport();
$exportLimit = 50;
if ($exportLimit > 0 and $exportLimit < $numberOfExportedFlats) {
$message = "Vous avez dépassé la limite d'annonces à exporter sur le bon coin.";
return new JsonResponse(['message' => $message]);
}else{
$em->flush();
$exportLogin = $this->getParameter('ftp_login');
$exportPassword = $this->getParameter('ftp_password');
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$urlResult = curl_exec ($url);
curl_close($url);
$message = "multidif site le bon coin ajoute";
return new JsonResponse(['message' => $message]);
}
break;
case 3:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setSlexport(true);
$em = $this->getDoctrine->getManager();
$numberOfExportedFlats = $em->getRepository('AppBundle:Flat')->countSlexport();
$exportLimit = 350;
if ($exportLimit > 0 and $exportLimit < $numberOfExportedFlats) {
$message = "Vous avez dépassé la limite d'annonces à exporter sur Se loger.";
return new JsonResponse(['message' => $message]);
}else{
$em->flush();
$exportLogin = $this->getParameter('ftp_login');
$exportPassword = $this->getParameter('ftp_password');
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$urlResult = curl_exec ($url);
curl_close($url);
$message = "multidif se loger ajoute";
return new JsonResponse(['message' => $message]);
}
break;
case 4:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setOuestexport(true);
$em = $this->getDoctrine->getManager();
$numberOfExportedFlats = $em->getRepository('AppBundle:Flat')->countOuestexport();
$exportLimit = 30;
if ($exportLimit > 0 and $exportLimit < $numberOfExportedFlats) {
$message = "Vous avez dépassé la limite d'annonces à exporter sur Ouest France immo.";
return new JsonResponse(['message' => $message]);
}else{
$em->flush();
$exportLogin = $this->getParameter('ftp_login');
$exportPassword = $this->getParameter('ftp_password');
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://sw.ubiflow.net/diffusions_actives_client.php?login='.$exportLogin.'&mot_de_passe='.$exportPassword);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$urlResult = curl_exec ($url);
curl_close($url);
$message = "multidif Ouest ajoute";
return new JsonResponse(['message' => $message]);
}
break;
}
// $webSiteDatas = new \SimpleXMLElement($urlResult);
// foreach ($webSiteDatas as $webSiteData) {
// if (intval($webSiteData->nb_annonces_max) > $exportLimit) {
// $exportLimit = intval($webSiteData->nb_annonces_max);
// }
// }
}
/**
* Marquer une annonce à ne plus exporter sur les sites
*
* @Route("/flat/exportselectRemove/{id}/{site}", name="flat_exportselect_remove", options={"expose"=true})
*/
public function exportselectDeleteAction($id,$site)
{
switch ($site) {
case 1:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setExported(false);
$em = $this->getDoctrine->getManager();
$em->flush();
$message = 'site gratuit efface';
return new JsonResponse(['message' => $message]);
break;
case 2:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setLbcexport(false);
$em = $this->getDoctrine->getManager();
$em->flush();
$message = 'site le bon coin efface';
return new JsonResponse(['message' => $message]);
break;
case 3:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setSlexport(false);
$em = $this->getDoctrine->getManager();
$em->flush();
$message = 'site se loger efface';
return new JsonResponse(['message' => $message]);
break;
case 4:
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setOuestexport(false);
$em = $this->getDoctrine->getManager();
$em->flush();
$message = 'site Ouest france immo efface';
return new JsonResponse(['message' => $message]);
break;
}
}
/**
* Marquer une annonce à ne plus exporter sur les sites
*
* @Route("/flat/exportRemove/{id}", name="flat_export_remove", options={"expose"=true})
*/
public function exportDeleteAction($id)
{
$flat = $this->getDoctrine->getRepository('AppBundle:Flat')->find($id);
$flat->setExported(false);
$em = $this->getDoctrine->getManager();
$em->flush();
return new JsonResponse();
}
/**
* Supprimer une annonce
*
* @Route("/flat/{id}/delete", name="flatDelete", options={"expose"=true})
* @Method("DELETE")
*/
public function flatDeleteAction(Request $request, Flat $flat)
{
$form = $this->createFlatDeleteForm($flat->getId());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine->getManager();
$em->remove($flat);
$em->flush();
}
return $this->redirectToRoute('flatListing');
}
/**
* Construit un formulaire de suppression d'annonce
*
* @param $id
*
* @return \Symfony\Component\Form\Form|\Symfony\Component\Form\FormInterface
*/
private function createFlatDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('flatDelete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Supprimer','attr' => array('class' => 'btn btn-danger')))
->getForm()
;
}
/**
* Récupère un mandat pdf
*
* @Route("/mandate/show-pdf-saved/{id}", name="mandate_show_pdf_saved", options={"expose" = true})
* @Method("GET")
*
* @param Mandate $mandate
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getMandateShowPdfSavedAction(Request $request, Mandate $mandate)
{
$em = $this->getDoctrine->getManager();
$candidatureInitie = $mandate->getFlat()->getApplications()->count();
if($candidatureInitie){
$candidatures = $mandate->getFlat()->getApplications();
foreach ($candidatures as $application){
$contract = $application->getContract();
if($contract){
$signmandate = $contract->getDocument("signed_mandate");
if($signmandate){
$content = file_get_contents($signmandate->getAbsolutePath());
return new Response($content, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="file.pdf"',
]);
}
}
}
}
// if($mandate->getFlat()){
// $c = $mandate->getFlat()->getMandates()->count();
// $lm = $mandate->getFlat()->getMandates()[$c-1];
// $content = file_get_contents($lm->getDocument()->getAbsolutePath());
// }else{
$content = file_get_contents($mandate->getDocument()->getAbsolutePath());
// }
return new Response($content, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="file.pdf"',
]);
}
/**
* Modifier le statut d'une candidature
*
* @Route("/application/status/edit/{id}/{status}", name="edit_status", options={"expose"=true})
* @param Request $request
*
* @return JsonResponse
*/
public function editStatusAction($id, $status)
{
$em = $this->getDoctrine->getManager();
$application = $this->getDoctrine->getRepository('AppBundle:Application')->find($id);
if ($status == 99) {
$application->setRemoved(true);
$application->setStatus(3);
// adminnotif 32
$notifier = $this->get('app.notifparse');
$notifier->doAll( 32, 'Application',$application->getId(),'notif');
// Notif Propriétaire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' retirée ');
$notification->setIcon('far fa-times-square icon');
$notification->setColor('#e74c3c');
$em->persist($notification);
*/
// adminnotif 33
$notifier = $this->get('app.notifparse');
$notifier->doAll( 33, 'Application',$application->getId(),'notif');
// Notif Locataire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getUser());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature retirée par Wizi');
$notification->setIcon('far fa-times-square icon');
$notification->setColor('#e74c3c');
$em->persist($notification);
*/
} elseif ($status == 1){
$application->setStatus($status);
$application->setRemoved(NULL);
} elseif ($status == 2){
$application->setStatus($status);
$application->setRemoved(NULL);
// adminnotif 34
$notifier = $this->get('app.notifparse');
$notifier->doAll( 34, 'Application',$application->getId(),'notif');
// Notif Propriétaire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' acceptée par Wizi ');
$notification->setIcon('ion-document-text icon');
$em->persist($notification);
*/
// adminnotif 36
$notifier = $this->get('app.notifparse');
$notifier->doAll( 36, 'Application',$application->getId(),'notif');
// Notif Locataire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getUser());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature acceptée');
$notification->setIcon('ion-document-text icon');
$em->persist($notification);
*/
} elseif ($status == 3){
$application->setStatus($status);
$application->setRemoved(NULL);
// adminnotif 37
$notifier = $this->get('app.notifparse');
$notifier->doAll( 37, 'Application',$application->getId(),'notif');
// Notif Propriétaire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature de '.$application->getUser()->getFirstname().' '.$application->getUser()->getName().' refusée par Wizi ');
$notification->setIcon('ion-document-text icon');
$em->persist($notification);
*/
// adminnotif 38
$notifier = $this->get('app.notifparse');
$notifier->doAll( 38, 'Application',$application->getId(),'notif');
// Notif Locataire
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setUser($application->getUser());
$notification->setDescription('Annonce '.$application->getFlat()->getId().' : candidature refusée');
$notification->setIcon('ion-document-text icon');
$em->persist($notification);
*/
}
$em->persist($application);
$em->flush();
return new JsonResponse('Statut modifié');
}
/**
* Lister les conversations
*
* @Route("/message/notif", name="notif_msg", methods={"GET"}, options={"expose"=true})
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function notifMsgAction()
{
$em = $this->getDoctrine->getRepository('AppBundle:Conversation');
$nbMsgNotRead = $em->nbMsgNotRead($this->getUser2());
$convsNotReadArr = $em->conversationsByIdNotRead($this->getUser2());
$convsNotRead = array_map('current', $convsNotReadArr);
return new JsonResponse(['nb' => $nbMsgNotRead, 'convs'=> $convsNotRead]);
}
/**
* Lister les ask
*
* @Route("/ask/listing", name="askListing")
*
* @return string
*/
public function indexAskAction()
{
$em = $this->getDoctrine;
$askManager = $em->getRepository('App\AppBundle\Entity\Ask');
$asks = $askManager->findAll();
//$datatable = $this->get('app.datatable.ask');
// $datatable->buildDatatable();
return $this->render('Extranet/Ask/ask.html.twig', array(
'datatable' => $asks,
));
}
/**
* Filtrer les Ask
*
* @Route("/ask/results", name="ask_results")
*/
public function askboardResultsAction()
{
$datatable = $this->get('app.datatable.ask');
$datatable->buildDatatable();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
return $query->getResponse();
}
/**
* Page bibliothèque Wizi
*
* @Route("/biblio", name="biblioPage")
* @return Response
*/
public function biblioPageAction()
{
return $this->render('bibliotheque/bibliotheque.html.twig',[]);
}
/**
* Lister les annonces
*
* @Route("/parrainage/listing", name="parrainageListing")
* @return Response
*/
public function parrainageListingAction()
{
return $this->render('Extranet/parrainage.html.twig',[]);
}
/**
* Filtrer les Ask
*
* @param Request $request
* @Route("/parrainage/results", name="parrainage_results", options={"expose"=true})
* @return JsonResponse
*/
public function parrainageboardResultsAction(Request $request,\App\AppBundle\Service\TabledataService $TabledataService)
{
$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
FROM app.user as fil
LEFT JOIN app.user as par on par.code_parrain = fil.code_filleul
LEFT JOIN app.parrainage_pro as pro on pro.code = fil.code_filleul ";
$condition = "WHERE fil.code_filleul IS NOT NULL";
$fields = [
['name' => 'filid'],
['name' => 'filleul'],
['name' => 'parid'],
['name' => 'parrain'],
['name' => 'pro'],
['name' => 'datee']
];
//$datatable = $this->get('app.tabledata')->datatablePdo($sql, $fields, $request, $condition);
$datatable = $TabledataService->datatablePdo($sql, $fields, $request,$condition);
for ($i = 0; $i < count($datatable['data']); $i++){
if($datatable['data'][$i][0]) {
$route1 = $this->generateUrl('editUser', ['id' => $datatable['data'][$i][0]]);
$datatable['data'][$i][0] = '<a style="text-decoration: underline" href="'.$route1.'">'.$datatable['data'][$i][1].'</a>';
}
unset($datatable['data'][$i][1]);
if($datatable['data'][$i][2]) {
$route2 = $this->generateUrl('editUser', ['id' => $datatable['data'][$i][2]]);
$datatable['data'][$i][2] = '<a style="text-decoration: underline" href="'.$route2.'">'.$datatable['data'][$i][3].'</a>';
}
unset($datatable['data'][$i][3]);
$datatable['data'][$i] = array_values($datatable['data'][$i]);
}
return new JsonResponse($datatable);
}
/**
* Lister les upsells
*
* @Route("/upsells/listing", name="upsellListing")
* @return Response
*/
public function upsellListingAction()
{
return $this->render('Extranet/upsell.html.twig',[]);
}
/**
* Filtrer les Ask
*
* @param Request $request
* @Route("/upsell/results", name="upsell_results", options={"expose"=true})
* @return JsonResponse
*/
public function upsellResultsAction(Request $request)
{
$sql = "SELECT * FROM app.contract ";
// $condition = "WHERE code_filleul IS NOT NULL";
$fields = [
['name' => 'id'],
['name' => 'wizi_internet', 'translation' => [null => 'N.C.', 1 => 'Oui', 0 => 'Non']],
['name' => 'wizi_energie', 'translation' => [null => 'N.C.', 1 => 'Oui', 0 => 'Non']],
['name' => 'wizi_mrh', 'translation' => [null => 'N.C.', 1 => 'Oui', 0 => 'Non']],
['name' => 'wizi_diagnostics', 'translation' => [null => 'N.C.', 1 => 'Oui', 0 => 'Non']],
['name' => 'wizi_pno', 'translation' => [null => 'N.C.', 1 => 'Oui', 0 => 'Non']],
['name' => 'status', 'translation' => [1 => 'En préparation', 2 => 'En cours', 3 => 'Archivé', 4 => 'Annulé']],
];
$datatable = $this->get('app.tabledata')->datatablePdo($sql, $fields, $request);
for ($i = 0; $i < count($datatable['data']); $i++){
$route = $this->generateUrl('contract_edit', ['id' => $datatable['data'][$i][0]]);
$datatable['data'][$i][0] = '<a class="btn btn-primary wizi-btn-purple" href="'.$route.'">'. $datatable['data'][$i][0] .'</a>';
// array_push($datatable['data'][$i], '<a class="btn btn-primary wizi-btn-purple" href="'.$route.'"><i class="fa fa-edit"></i></a>');
}
return new JsonResponse($datatable);
}
/**
* Lister les dossiers a vérifier
*
* @Route("/verifdoss", name="verifdossListing")
* @return Response
*/
public function verifdossListingAction()
{
$datatable = $this->get('app.datatable.verifdoss');
$datatable->buildDatatable(array('user_status' => $this->getParameter('user_status')));
return $this->render('Extranet/Verifdoss/list.html.twig', array(
'datatable' => $datatable,
));
}
/**
* Filtrer les dossiers a vérifier
*
* @Route("/verifdoss/results", name="verifdoss_results")
*/
public function verifdossResultsAction()
{
$datatable = $this->get('app.datatable.verifdoss');
$datatable->buildDatatable();
$query = $this->get('sg_datatables.query')->getQueryFrom($datatable);
$function = function($qb)
{
$qb->andWhere("contract.taskdoctriger = :status");
$qb->setParameter('status', "1");
};
$query->addWhereAll($function);
return $query->getResponse();
}
/**
* micro task detailée
*
* @Route("/verifdoss/results/{application}", name="verifdoss_edit", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function detailcandidatureAction(Request $request,Application $application)
{
return $this->render('Extranet/Application/revisiontask.html.twig', array(
'application' => $application,
// 'form' => $form->createView(),
));
}
/**
* mettre a jour les salaires dans les dossiers a verifier
*
* @Route("/verifdoss/updateusersalaireup/send", name="updateusersalaireup_send", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function updateusersalaireupAction(Request $request)
{
$m = $this->get('request')->request->get('salupone');
$m2 = $this->get('request')->request->get('saluptwo');
$m3 = $this->get('request')->request->get('salupthree');
$uid = $this->get('request')->request->get('uid');
$em = $this->getDoctrine->getManager();
$userRepo = $this->getDoctrine->getRepository('AppBundle:User');
$user = $userRepo->find($uid);
$user->setIncomeOne($m);
$user->setIncomeTwo($m2);
$user->setIncomeThree($m3);
$em->persist($user);
$em->flush();
$response = new Response();
$response->setContent(json_encode('ok'));
$response->setStatusCode('200');
return $response;
}
/**
* mettre a jour les infos imposition dans les dossiers a verifier
*
* @Route("/verifdoss/updateuserimpos/send", name="updateuserimpos_send", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function updateuserimposAction(Request $request)
{
$revfiscalref = $this->get('request')->request->get('revref');
$uid = $this->get('request')->request->get('uid');
$em = $this->getDoctrine->getManager();
$userRepo = $this->getDoctrine->getRepository('AppBundle:User');
$user = $userRepo->find($uid);
$user->setRevfiscalref($revfiscalref);
$em->persist($user);
$em->flush();
$response = new Response();
$response->setContent(json_encode('ok'));
$response->setStatusCode('200');
return $response;
}
/**
* micro task detailée
*
* @Route("/verifdoss/send", name="verifdoss_send", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function detailcandidaturesendAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$verDossRepo = $this->getDoctrine->getRepository('AppBundle:VerifDoss');
$logger = $this->get('logger');
$em = $this->getDoctrine->getManager();
$request_body = $request->getContent();
$logger->critical($request_body);
$request_bodyArray = array();
$request_bodyArray = \json_decode($request_body, true);
$reencode = \json_encode($request_bodyArray);
$arr = $request_bodyArray;
$principal = $this->get('request')->request->get('principal');
$secondaires = $this->get('request')->request->get('secondaire');
$appid = $this->get('request')->request->get('appid');
$usp = new Verifdoss();
$olddoss = $verDossRepo->findBy(array('applicationId'=> $appid));
foreach ($olddoss as $d) {
$em->remove($d);
$em->flush();
}
foreach ($principal as $key => $value) {
//$metodstring = 'set'.$value['param'];
//json_decode(json)
if($value['uid']['param'] != 'Other'){
$metodstring = "set".$value['uid']['param'];
$metodstring2 = "setMust".$value['uid']['param'];
$usp->{$metodstring}($value['uid']['val']);
$usp->{$metodstring2}(1);
}
$usp->setUserId($value['uid']['usid']);
}
$usp->setApplicationId($appid);
$em->persist($usp);
$em->flush();
/* traitement des user sec*/
if(isset($secondaires) && count($secondaires) > 0){
$oldusId = '';
$usl = '';
foreach ($secondaires as $key => $value) {
if($oldusId != $value['uid']['usid']){
if ($usl != '') {
$em->persist($usl);
$em->flush();
}
$usl = new Verifdoss();
}
//$metodstring = 'set'.$value['param'];
//json_decode(json)
if($value['uid']['param'] != 'Other'){
$metodstring = "set".$value['uid']['param'];
$metodstring2 = "setMust".$value['uid']['param'];
$usl->{$metodstring}($value['uid']['val']);
$usl->{$metodstring2}(1);
}
$usl->setUserLocId($value['uid']['usid']);
$usl->setApplicationId($appid);
$oldusId = $value['uid']['usid'];
}
$em->persist($usl);
$em->flush();
}
//concsel: selconc,conctxt: textconc
$apptxt = $this->get('request')->request->get('conctxt');
$appsel = $this->get('request')->request->get('concsel');
$application = $this->getDoctrine->getRepository('AppBundle:Application')->find($appid);
// $suivipar
$commercialId = $application->getFlat()->getOwnedBy()->getSuivipar();
$CommObject = $this->getDoctrine->getRepository('AppBundle:User')->find($commercialId);
if($application->getTaskdocstatus() != 1 && $appsel == 1){
// adminnotif 39
$notifier = $this->get('app.notifparse');
$notifier->doAll( 39, 'Application',$application->getId(),'notif');
// notification locataire
$description ='Félicitations, votre dossier de location a été contrôlé et validé par Wizi. Votre propriétaire en a été informé.';
/*
$notification = new Notification();
$notification->setEmplacement('contrat');
$notification->setStatus(1);
$notification->setUser($application->getUser());
$notification->setDescription($description);
$notification->setIcon('far fa-file-certificate icon');
$notification->setColor('#029398');
$notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
*/
$em->flush();
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getUser()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getUser()->getEmail(),
'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
]
],
'Subject' => "changement sur le dossier locataire",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// adminnotif 40
$notifier = $this->get('app.notifparse');
$notifier->doAll( 40, 'Application',$application->getId(),'notif');
// notification propriétaire
$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.';
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setStatus(1);
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription($description);
$notification->setIcon('ion-ios-checkmark icon');
$notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
*/
$em->flush();
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
]
],
'Subject' => "changement sur le dossier Wizi de votre locataire",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// on envoie le mail au commercial :
// $CommObject
$to = $CommObject->getEmail();
$subject = 'Changement de statut dossier locataire';
$message = $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
$headers = 'From: laura@wizi.eu' . "\r\n" .
'Reply-To: laura@wizi.eu' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
// ici on test existance de signatures
$contract = $application->getContract();
$docs = $contract->getDocuments();
foreach ($docs as $doc) {
//dump($doc->getCategory());
if($doc->getCategory() == 'contract'){
$signatures = $doc->getSignatures();
foreach ($signatures as $sign) {
$userid = $sign->getUser()->getId();
$uppuid = $application->getUser()->getId();
$sdone = $sign->getDone();
$renter = $application->getUser();
$owner = $application->getFlat()->getOwnedBy();
if($userid == $uppuid && $sdone != true){
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51', true, ['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $renter->getEmail(),
'Name' => $renter->getFirstname()
]
],
'TemplateID' => 551440,
'TemplateLanguage' => true,
'Subject' => "Bail signé par le proprietaire",
'Variables' => json_decode('{
"firstname": "' . $renter->getFirstname() . '",
"title": "' . $application->getFlat()->getTitle() . '",
"propname": "' . $owner->getFirstname().' '.$owner->getName() . '"
}', true)
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && $response->getData();
}
}
}
}
}
if($application->getTaskdocstatus() != 1 && $appsel == 2){
// adminnotif 41
$notifier = $this->get('app.notifparse');
$notifier->doAll( 41, 'Application',$application->getId(),'notif');
// notification locataire
$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.';
$description = "Votre dossier de location vient d'être contrôle par Wizi. Il est incomplet.
Connectez-vous à votre espace Wizi pour voir le détail et ajouter les documents manquants.";
/*
$notification = new Notification();
$notification->setEmplacement('contrat');
$notification->setStatus(1);
$notification->setUser($application->getUser());
$notification->setDescription($description);
$notification->setColor('#e74c3c');
$notification->setIcon('far fa-thumbs-down icon');
$notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getUser()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getUser()->getEmail(),
'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// adminnotif 42
$notifier = $this->get('app.notifparse');
$notifier->doAll( 42, 'Application',$application->getId(),'notif');
// notification propriétaire
$description ='Le dossier de votre candidat locataire '.
$application->getUser()->getFirstname().' '.$application->getUser()->getName()
.' a été contrôlé par Wizi, Malheureusement il est incomplet, nous avons relancé votre locataire pour obtenir des documents complémentaires.';
$description = "Le dossier de ".
$application->getUser()->getFirstname().' '.$application->getUser()->getName()
. " vient d'être contrôle par Wizi. Il est incomplet.
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.";
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setStatus(1);
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription($description);
$notification->setIcon('ion-ios-checkmark icon');
$notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// on envoie le mail au commercial :
// $CommObject
$to = $CommObject->getEmail();
$subject = 'Changement de statut dossier locataire';
$message = $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
$headers = 'From: laura@wizi.eu' . "\r\n" .
'Reply-To: laura@wizi.eu' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
if($application->getTaskdocstatus() != 1 && $appsel == 3){
// adminnotif 43
$notifier = $this->get('app.notifparse');
$notifier->doAll( 43, 'Application',$application->getId(),'notif');
// notification locataire
$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 +';
/*
$notification = new Notification();
$notification->setEmplacement('contrat');
$notification->setStatus(1);
$notification->setUser($application->getUser());
$notification->setDescription($description);
$notification->setColor('#e74c3c');
$notification->setIcon('far fa-thumbs-down icon');
$notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getUser()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getUser()->getEmail(),
'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// adminnotif 44
$notifier = $this->get('app.notifparse');
$notifier->doAll( 44, 'Application',$application->getId(),'notif');
// notification propriétaire
$description ='Le dossier de votre locataire '.
$application->getUser()->getFirstname().' '.$application->getUser()->getName()
.' a été contrôlé par Wizi, Malheureusement, il a été refusé, rapprochez vous de votre conseiller Wizi pour en savoir +.';
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setStatus(1);
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription($description);
$notification->setIcon('ion-ios-checkmark icon');
$notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// on envoie le mail au commercial :
// $CommObject
$to = $CommObject->getEmail();
$subject = 'Changement de statut dossier locataire';
$message = $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
$headers = 'From: laura@wizi.eu' . "\r\n" .
'Reply-To: laura@wizi.eu' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
if($application->getTaskdocstatus() != 1 && $appsel == 4){
// adminnotif 45
$notifier = $this->get('app.notifparse');
$notifier->doAll( 45, 'Application',$application->getId(),'notif');
// notification locataire
$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";
/*
$notification = new Notification();
$notification->setEmplacement('contrat');
$notification->setStatus(1);
$notification->setUser($application->getUser());
$notification->setDescription($description);
$notification->setColor('#e74c3c');
$notification->setIcon('far fa-thumbs-down icon');
$notification->setLink('/#/app/contract_renter/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getUser()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getUser()->getEmail(),
'Name' => $application->getUser()->getFirstname()." ".$application->getUser()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// adminnotif 46
$notifier = $this->get('app.notifparse');
$notifier->doAll( 46, 'Application',$application->getId(),'notif');
// notification propriétaire
$description ='Le dossier de votre locataire '.
$application->getUser()->getFirstname().' '.$application->getUser()->getName().
" est en cours d'étude par Wizi. Nous prenons contact avec lui ce jour et reviendrons vers vous dans les 48H.";
/*
$notification = new Notification();
$notification->setEmplacement('notif');
$notification->setStatus(1);
$notification->setUser($application->getFlat()->getOwnedBy());
$notification->setDescription($description);
$notification->setIcon('ion-ios-checkmark icon');
$notification->setLink('/#/app/contract_owner/'.$application->getContract()->getId().'/menu');
$em->persist($notification);
$em->flush();
*/
// sms
$apikey = 'cab64310293a12d7098233ff702dbcfcf66c784a';
$fields = array(
'apiKey'=> $apikey,
'sender' => 'Wizi',
'SMSList'=> array(
array(
'phoneNumber'=> $application->getFlat()->getOwnedBy()->getMobilePhone(),
'message'=> $description,
'gamme' => 1
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/bulk-send');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51',true,['version' => 'v3.1']);
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $application->getFlat()->getOwnedBy()->getEmail(),
'Name' => $application->getFlat()->getOwnedBy()->getFirstname()." ".$application->getFlat()->getOwnedBy()->getName()
]
],
'Subject' => "changement sur le dossier Wizi ",
'TextPart' => $description,
'HTMLPart' => $description
]
]
];
$responsemail = $mj->post(Resources::$Email, ['body' => $body]);
$responsemail->success() && $responsemail->getData();
// on envoie le mail au commercial :
// $CommObject
$to = $CommObject->getEmail();
$subject = 'Changement de statut dossier locataire';
$message = $description.' : '.$application->getFlat()->getOwnedBy()->getFirstname().' '.$application->getFlat()->getOwnedBy()->getName();
$headers = 'From: laura@wizi.eu' . "\r\n" .
'Reply-To: laura@wizi.eu' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
$application->setTaskdoctxt($apptxt);
$application->setTaskdocstatus($appsel);
$em->persist($application);
$em->flush();
if($appsel == 0){
$ctr = $application->getContract();
$ctr->setTaskdoctriger(1);
$ctr->setTaskdocAt(new \DateTime());
$em->persist($ctr);
$em->flush();
}
$response = new Response();
$response->setContent(json_encode($appsel));
$response->setStatusCode('200');
return $response;
}
/**
* micro task detailée
*
* @Route("/verifdoss/loaddata", name="verifdoss_loaddata", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function detailcandidaturesendloaddataAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$verDossRepo = $this->getDoctrine->getRepository('AppBundle:VerifDoss');
$appid = $this->get('request')->request->get('appid');
$verifs = $verDossRepo->findBy(array('applicationId' => $appid));
$uptab = [];
$ustab = [];
foreach ($verifs as $vd) {
if ($vd->getUserId() != null) {
$uptab[] = $vd;
}else{
$ustab[] = $vd;
}
}
/*
$response = new Response();
$response->setContent($verifs);
$response->setStatusCode('200');
return $response;
*/
$results = [];
$results['principal'] = $uptab;
$results['secondaires'] = $ustab;
$serializer = SerializerBuilder::create()->build();
if(count($verifs) > 0){
$jsonStats = $serializer->serialize($results, 'json');
}else{
$jsonStats = $serializer->serialize('vide', 'json');
}
return new JsonResponse($jsonStats);
}
/**
* evaluation des prix par région
*
* @Route("/evaluateprice", name="evaluateprice", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function evaluatepriceAction(Request $request)
{
$totalprixmettrecarre = 0;
$prixmini = 10000;
$prixmax = 0;
$em = $this->getDoctrine->getManager();
$flatRepo = $this->getDoctrine->getRepository('AppBundle:Flat');
/*
$params = [
'status' => 2,
'distance' => 2,
'limit' => 3,
'positions' => [ 0 =>
['latitude' => $lat,
'longitude' => $long
]
]
];
*/
$postalcode = '06100';
$result = $flatRepo->findBy(array('postalCode'=> $postalcode ));
$cresult = count($result);
if(count($result) > 0){
foreach ($result as $f) {
$prixHC = $f->getCharges();
$surf = $f->getSurface();
if($surf>0){
$prixmettrecarre = ($prixHC / $surf);
$totalprixmettrecarre = $totalprixmettrecarre + $prixmettrecarre;
if($prixmini > $prixmettrecarre && $prixmettrecarre !=0){
$prixmini = $prixmettrecarre;
}
if($prixmax < $prixmettrecarre){
$prixmax = $prixmettrecarre;
}
}
}
$pmoymc = $totalprixmettrecarre / $cresult;
$results = [
'nombre_flat' => $cresult,
'prix_mini' => $prixmini,
'prix_max' => $prixmax,
'prix_moyen' => $pmoymc,
];
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($results, 'json');
return new JsonResponse($jsonStats);
}
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize('0 annonces', 'json');
return new JsonResponse($jsonStats);
}
/**
* micro task verifier document de dossier
*
* @Route("/verifcontractdoss", name="verifcontractdoss_loaddata", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function verifdosscontreacAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$verDossRepo = $this->getDoctrine->getRepository('AppBundle:Contract');
$contractid = $this->get('request')->request->get('id');
$cat = $this->get('request')->request->get('cat');
$val = $this->get('request')->request->get('val');
$contract = $verDossRepo->find($contractid);
switch ($cat) {
case 'insurance':
$contract->setMrhvalide($val);
break;
case 'diagnostic':
$contract->setDiagvalide($val);
break;
case 'proof_of_ownership':
$contract->setPropvalide($val);
break;
case 'otheradmin':
$contract->setUtilvalide($val);
break;
}
$em->persist($contract);
$em->flush();
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize('vide', 'json');
return new JsonResponse($jsonStats);
}
/**
* Afficher agenda visites
*
* @Route("/viewrdvvisite", name="viewrdvvisite")
* @return Response
*/
public function viewVisiteRdvAction()
{
$em = $this->getDoctrine->getManager();
$VisiteDates = $this->getDoctrine->getRepository('AppBundle:VisiteDate')->findAll();
$data = array();
return $this->render('Extranet/viewrdvvisite.html.twig', [
'data' => $data,
]);
}
/**
* Récupérer les rdvs
* @param Request $request
* @return JsonResponse
*
* @Route("/viewrdvvisitejson", name="viewrdvvisitejson", options={"expose"=true})
*
*/
public function getviewrdvvisitejsonAction()
{
/*
$em = $this->getDoctrine->getManager();
$VisiteDates = $this->getDoctrine->getRepository('AppBundle:VisiteDate')->findAll();
$serializer = SerializerBuilder::create()->build();
$jsonStats = $serializer->serialize($VisiteDates, 'json');
*/
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sthd = $bdd->prepare("SELECT own.firstname as ownerFirstname,
own.firstname as ownerName,
rent.firstname as renterFirstname,
rent.name as renterName,
vd.date,
vd.id,
flat.id as flatId,
application.id as applicationId,
vd.time
FROM app.visite_date as vd
INNER JOIN app.application as application on application.id = application_id
INNER JOIN app.flat as flat on flat.id = application.flat
INNER JOIN app.user as own on own.id = flat.owned_by_id
INNER JOIN app.user as rent on rent.id = application.user");
$sthd->execute();
$resultd = $sthd->fetchAll(\PDO::FETCH_ASSOC);
return new JsonResponse($resultd);
}
/**
* [SEARCH BO] Retrouver utilisateur
*
* @param Request $request
* @Route("/bosearch/userquery", name="bosearchuserquery", options={"expose"=true})
*
* @return JsonResponse
*/
public function getBoSearchUserQueryAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$query = $request->get('query');
$explodedquery = explode(' ', $query);
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
// Search in user
$sqlQuery = "SELECT u.firstname, u.name, u.id FROM ".$namedb.".user as u WHERE ";
$UserLocSqlQuery = "SELECT u.name, u.firstname, u.owned_by_id as id FROM ".$namedb.".user_loc as u WHERE ";
$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 ";
$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 ";
foreach ($explodedquery as $key => $q){
if($key > 0){
$sqlQuery .= " AND ";
$UserLocSqlQuery .= " AND ";
$UserPropSqlQuery .= " AND ";
$SciPropSqlQuery .= " AND ";
}
$sqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
$UserLocSqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
$UserPropSqlQuery .= "(u.name LIKE '%".$q."%' OR u.firstname LIKE '%".$q."%')";
$SciPropSqlQuery .= "(f.companyName LIKE '%".$q."%')";
}
$sqlQuery .= " ORDER BY u.id DESC LIMIT 0, 10";
$UserLocSqlQuery .= " ORDER BY u.owned_by_id DESC LIMIT 0, 5";
$UserPropSqlQuery .= " ORDER BY f.owned_by_id DESC LIMIT 0, 5";
$SciPropSqlQuery .= " GROUP BY u.id ORDER BY f.owned_by_id DESC LIMIT 0, 5";
// Execution des query
$sthd = $bdd->prepare($sqlQuery);
$sthd->execute();
$result = $sthd->fetchAll(\PDO::FETCH_ASSOC);
$userlocsthd = $bdd->prepare($UserLocSqlQuery);
$userlocsthd->execute();
$userlocresult = $userlocsthd->fetchAll(\PDO::FETCH_ASSOC);
$flatpropsthd = $bdd->prepare($UserPropSqlQuery);
$flatpropsthd->execute();
$flatpropresult = $flatpropsthd->fetchAll(\PDO::FETCH_ASSOC);
$scisthd = $bdd->prepare($SciPropSqlQuery);
$scisthd->execute();
$sciresult = $scisthd->fetchAll(\PDO::FETCH_ASSOC);
$sec = [];
foreach ($userlocresult as $u){
array_push($sec, $u);
}
foreach ($flatpropresult as $f){
array_push($sec, $f);
}
foreach ($sciresult as $s){
array_push($sec, $s);
}
$resultd = [
'user' => $result,
'sec' => $sec
];
return new JsonResponse($resultd);
}
/**
* [SEARCH BO] Retrouver connections via user
*
* @param Request $request
* @Route("/bosearch/fromuser", name="bosearchfromuser", options={"expose"=true})
*
* @return JsonResponse
*/
public function getBoSearchFromUserAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$userid = $request->get('userid');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$UserSqlQuery = "SELECT u.name, u.firstname, u.id FROM ".$namedb.".user as u WHERE u.id = ".$userid;
$Usersthd = $bdd->prepare($UserSqlQuery);
$Usersthd->execute();
$user = $Usersthd->fetchAll(\PDO::FETCH_ASSOC);
$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";
$Flatsthd = $bdd->prepare($FlatSqlQuery);
$Flatsthd->execute();
$flats = $Flatsthd->fetchAll(\PDO::FETCH_ASSOC);
$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
FROM ".$namedb.".contract as c
INNER JOIN ".$namedb.".application as a on c.application_id = a.id
INNER JOIN ".$namedb.".user as renter on a.user = renter.id
INNER JOIN ".$namedb.".flat as f on a.flat = f.id
INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
WHERE owner.id = ".$userid."
OR renter.id = ".$userid."
ORDER BY FIELD(c.status, 2, 1, 3, 4)
LIMIT 0, 10";
$Contractsthd = $bdd->prepare($ContractSqlQuery);
$Contractsthd->execute();
$contracts = $Contractsthd->fetchAll(\PDO::FETCH_ASSOC);
$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
FROM ".$namedb.".application as a
INNER JOIN ".$namedb.".user as renter on a.user = renter.id
INNER JOIN ".$namedb.".flat as f on a.flat = f.id
INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
WHERE (owner.id = ".$userid."
OR renter.id = ".$userid.")
AND a.status <> 3
ORDER BY FIELD(a.status, 5, 2)
LIMIT 0, 10";
$Applicarionsthd = $bdd->prepare($ApplicarionSqlQuery);
$Applicarionsthd->execute();
$applications = $Applicarionsthd->fetchAll(\PDO::FETCH_ASSOC);
$result = [
'user' => $user,
'flats' => $flats,
'contracts' => $contracts,
'applications' => $applications
];
return new JsonResponse($result);
}
/**
* [SEARCH BO] Retrouver connections via id
*
* @param Request $request
* @Route("/bosearch/fromid", name="bosearchfromid", options={"expose"=true})
*
* @return JsonResponse
*/
public function getBoSearchFromIdAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$id = $request->get('id');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$UserSqlQuery = "SELECT u.name, u.firstname, u.id FROM ".$namedb.".user as u WHERE u.id = ".$id;
$Usersthd = $bdd->prepare($UserSqlQuery);
$Usersthd->execute();
$user = $Usersthd->fetchAll(\PDO::FETCH_ASSOC);
$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;
$Flatsthd = $bdd->prepare($FlatSqlQuery);
$Flatsthd->execute();
$flats = $Flatsthd->fetchAll(\PDO::FETCH_ASSOC);
$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
FROM ".$namedb.".contract as c
INNER JOIN ".$namedb.".application as a on c.application_id = a.id
INNER JOIN ".$namedb.".user as renter on a.user = renter.id
INNER JOIN ".$namedb.".flat as f on a.flat = f.id
INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
WHERE c.id = ".$id;
$Contractsthd = $bdd->prepare($ContractSqlQuery);
$Contractsthd->execute();
$contracts = $Contractsthd->fetchAll(\PDO::FETCH_ASSOC);
$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
FROM ".$namedb.".application as a
INNER JOIN ".$namedb.".user as renter on a.user = renter.id
INNER JOIN ".$namedb.".flat as f on a.flat = f.id
INNER JOIN ".$namedb.".user as owner on f.owned_by_id = owner.id
WHERE a.id = " .$id;
$Applicarionsthd = $bdd->prepare($ApplicarionSqlQuery);
$Applicarionsthd->execute();
$applications = $Applicarionsthd->fetchAll(\PDO::FETCH_ASSOC);
$result = [
'user' => $user,
'flats' => $flats,
'contracts' => $contracts,
'applications' => $applications
];
return new JsonResponse($result);
}
/**
* Afficher la page des stats admin
*
* @Route("/statsAdmin", name="statsAdmin")
* @return Response
*/
public function statsAdminAction()
{
$em = $this->getDoctrine;
$stats1 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 1]);
$stats2 = $em->getRepository('App\AppBundle\Entity\TempStat')->findBy(['type' => 2]);
$stats2array = [];
foreach ($stats2 as $key => $stat2){
$user = $em->getRepository('App\AppBundle\Entity\User')->find($stat2->getUser());
$stats2array[$key]['user'] = ['firstname' => $user->getFirstname(), 'name' => $user->getName(), 'picture' => $user->getPicture()->getId(), 'id' => $user->getId()];
$stats2array[$key]['type'] = $stat2->getType();
$stats2array[$key]['valeur'] = $stat2->getValeur();
$stats2array[$key]['target'] = $stat2->getTarget();
}
return $this->render('stats/statsAdmin.html.twig', array(
'stats1' => $stats1,
'stats2' => $stats2array
));
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdesk", name="chathelpdesk", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$madate = new \DateTime();
$hmess = new HelpMessage();
$hmess->setCreatedAt($madate);
$hmess->setStatus(1);
$hmess->setDestinataire(1);
$hmess->setExpediteur($request->get('token'));
$hmess->setMessage($request->get('message'));
$em->persist($hmess);
$em->flush();
$tr = [
'message' => $request->get('message'),
'token' => $request->get('token'),
'maxid' => $hmess->getId()
];
$response = new JsonResponse(json_encode($tr));
return $response;
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdeskfbo", name="chathelpdeskfbo", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskfboAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$namedb = $this->getParameter('dbreqpdo');
$token = $request->get('token');
$UserSqlQuery = "UPDATE ".$namedb.".help_message SET status = 2 WHERE expediteur = '".$token."' ";
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$re = $bdd->prepare($UserSqlQuery);
$re->execute();
$madate = new \DateTime();
$hmess = new HelpMessage();
$hmess->setCreatedAt($madate);
$hmess->setStatus(1);
$hmess->setDestinataire($request->get('token'));
$hmess->setExpediteur(1);
$hmess->setMessage($request->get('message'));
$em->persist($hmess);
$em->flush();
$tr = [
'message' => $request->get('message'),
'token' => $request->get('token'),
];
$response = new JsonResponse(json_encode($tr));
return $response;
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdeskvtoken", name="chathelpdeskvtoken", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskvtokenAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$token = $request->get('token');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$UserSqlQuery = "SELECT expediteur FROM ".$namedb.".help_message as u WHERE u.expediteur = ".$token;
$re = $bdd->prepare($UserSqlQuery);
$re->execute();
$d = $re->fetchAll(\PDO::FETCH_ASSOC);
if(count($d)> 0){
$response = new JsonResponse(json_encode('false'));
return $response;
}else{
$response = new JsonResponse(json_encode('true'));
return $response;
}
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdeskallmessages", name="chathelpdeskallmessages", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskallmessagesAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$token = $request->get('token');
$maxid = $request->get('maxid');
if ($maxid !== 'false') {
$UserSqlQuery = "SELECT * FROM ".$namedb.".help_message as u WHERE (u.expediteur = '".
$token."' OR u.destinataire = '".$token."') and u.id > ".(int)$maxid;
}
else
{
$UserSqlQuery = "SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$token."' OR u.destinataire = '".$token."' ";
}
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$re = $bdd->prepare($UserSqlQuery);
$re->execute();
$d = $re->fetchAll(\PDO::FETCH_ASSOC);
$response = new JsonResponse($d);
return $response;
}
/**
* envoyer des message helpdesk
*
* @Route("/admchathelpdeskboard", name="chathelpdeskboard", options={"expose"=true})
* @Method({"GET","POST"})
* @param Request $request
* @return Response
*/
public function chathelpdeskboardAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sqlconv = "SELECT distinct expediteur FROM app.help_message where expediteur <> 1";
$re = $bdd->prepare($sqlconv);
$re->execute();
$convs = $re->fetchAll(\PDO::FETCH_ASSOC);
$data= [];
foreach ($convs as $conv){
$sqlmess ="SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$conv['expediteur']
."' OR u.destinataire = '".$conv['expediteur']."' ";
$rem = $bdd->prepare($sqlmess);
$rem->execute();
$messages = $rem->fetchAll(\PDO::FETCH_ASSOC);
$data[$conv['expediteur']] = $messages;
}
return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
}
/**
* envoyer des message helpdesk
*
* @Route("/admtestcompareface", name="admtestcompareface", options={"expose"=true})
* @Method({"GET","POST"})
* @param Request $request
* @return Response
*/
public function admtestcomparefaceAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sqlconv = "SELECT distinct expediteur FROM app.help_message where expediteur <> 1";
$re = $bdd->prepare($sqlconv);
$re->execute();
$convs = $re->fetchAll(\PDO::FETCH_ASSOC);
$data= [];
foreach ($convs as $conv){
$sqlmess ="SELECT * FROM ".$namedb.".help_message as u WHERE u.expediteur = '".$conv['expediteur']
."' OR u.destinataire = '".$conv['expediteur']."' ";
$rem = $bdd->prepare($sqlmess);
$rem->execute();
$messages = $rem->fetchAll(\PDO::FETCH_ASSOC);
$data[$conv['expediteur']] = $messages;
}
$args = [
'credentials' => [
'key' => 'AKIAUHKWPN22W5Z4BQJM',
'secret' => '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'
],
'region' => 'us-east-1',
'version' => 'latest'
];
$client = new RekognitionClient($args);
$result = $client->compareFaces([
'SimilarityThreshold' => 70,
'SourceImage' => [
'Bytes' => file_get_contents('recoimg/1.jpg')
],
'TargetImage' => [
'Bytes' => file_get_contents('recoimg/2.jpg')
]
]);
dump($result);
return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdeskfaq", name="chathelpdeskfaq", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskfaqAction(Request $request)
{
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sqlfaq = "SELECT * FROM app.smart_faq";
$re = $bdd->prepare($sqlfaq);
$re->execute();
$faq = $re->fetchAll(\PDO::FETCH_ASSOC);
$tr = [
'faq' => $faq
];
$response = new JsonResponse(json_encode($tr));
return $response;
}
/**
* envoyer des message helpdesk
*
* @Route("/chathelpdeskfaqask", name="chathelpdeskfaqask", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function chathelpdeskfaqaskAction(Request $request)
{
$message = $request->get('message');
$namedb = $this->getParameter('dbreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname='.$namedb.';charset=utf8', 'root', 'ahv2Ohchaik0');
$sqlfaq = "SELECT * FROM app.smart_faq";
$re = $bdd->prepare($sqlfaq);
$re->execute();
$faqs = $re->fetchAll(\PDO::FETCH_ASSOC);
$faqres = [];
foreach ($faqs as $faq){
$tags = $faq['tags'];
$tagsTab = explode(',',$tags);
$tagcount = 0;
foreach ($tagsTab as $t){
$pos = strpos($message, $t);
if ($pos === false){
}else{
$tagcount = $tagcount +1;
}
}
if($tagcount == 2 ){
if ($faq["categorie"] != "ia") {
$faqres[] = $faq;
}
} elseif ($tagcount >= 3) {
/* si on determine que la question est claire on fait repondre direct par le bot */
$em = $this->getDoctrine->getManager();
$madate = new \DateTime();
$hmess = new HelpMessage();
$hmess->setCreatedAt($madate);
$hmess->setStatus(1);
$hmess->setDestinataire($request->get('token'));
$hmess->setExpediteur(1);
$hmess->setMessage($faq['reponse']);
$em->persist($hmess);
$em->flush();
$tr = [];
$response = new JsonResponse($tr);
return $response;
}
}
$tr = [
$faqres
];
$response = new JsonResponse($tr);
return $response;
}
/**
* compter les quittances a fournir
*
* @param Request $request
* @return JsonResponse
* @Route("/countdemandesdequittances", name="countdemandesdequittances", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countdemandesdequittancesAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
/*
$sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
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
FROM app.user as u
inner join app.flat as f on u.id = f.owned_by_id";
*/
$sql = "SELECT count(*) as res
FROM app.quittance_ask as u ";
$condition = ' where ( status = 1 ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* compter les rapports de gérance a fournir
*
* @param Request $request
* @return JsonResponse
* @Route("/countdemandesrapportgerance", name="countdemandesrapportgerance", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countdemandesrapportgeranceAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$comuser = $this->getUser();
$suivipar = $comuser->getId() == 1 ? '29896' : $comuser->getId();
/*
$sql = "SELECT u.suivipar,u.suivistatus,u.suivirappel,f.status as flatstatus , f.id as flatid ,
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
FROM app.user as u
inner join app.flat as f on u.id = f.owned_by_id";
*/
$sql = "SELECT count(*) as res
FROM app.rapport_gerance_ask as u ";
$condition = ' where ( status = 1 ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* Generer un sepa depuis le BO our un contrat
*
* @param Request $request
* @return JsonResponse
* @Route("/majpreavistraitement", name="majpreavistraitement", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function majpreavistraitementAction(Request $request)
{
$arr = $_POST['preavis'];
$id = $arr['id'];
$traitement = $arr['traitement'];
$contractid = $_POST['cid'];
$em = $this->getDoctrine->getManager();
$PreavisSortie = $this->getDoctrine->getRepository('AppBundle:PreavisSortie')->find($id);
$contract = $this->getDoctrine->getRepository('AppBundle:Contract')->find($contractid);
$PreavisSortie->setTraitement($traitement);
$em->persist($PreavisSortie);
$em->flush();
if($PreavisSortie->getTraitement() == 2){
// préavis accepté
/*
mail locataire :
votre préavis de depart à bien été pris en compte il est accepté
lien vers le contrat coté locataire
https://desk.wizi.eu/#/app/contract_renter/2515/menu
*/
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51', true, ['version' => 'v3.1']);
$mailto = $contract->getApplication()->getUser()->getEmail();
$emailtoname = $contract->getApplication()->getUser()->getName();
$demandeur = $contract->getApplication()->getUser()->getFirstname();
$iddemande = $contract->getId();
// https://desk.wizi.eu/#/app/contract_owner/{{var:iddemande}}/menu
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $mailto,
'Name' => $emailtoname
]
],
'TemplateID' => 1556106,
'TemplateLanguage' => true,
'Subject' => "Votre préavis de départ est accepté",
'Variables' => json_decode('
{"demandeur": "' . $demandeur . '",
"iddemande": "' . 'home' . '"
}', true)
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && $response->getData();
/*
mail commercial :
le locataire d'un de vos contrat vient de se faire valider un préavis de départ
lien vers le contrat coté BO
https://app.wizi.eu/contract/edit/2394
*/
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51', true, ['version' => 'v3.1']);
$usercom = $this->getDoctrine->getRepository('AppBundle:User')->find($contract->getApplication()->getFlat()->getOwnedBy()->getSuivipar());
$mailto = $usercom->getEmail();
$emailtoname = $usercom->getName();
$demandeur = $contract->getApplication()->getUser()->getFirstname();
$iddemande = $contract->getId();
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $mailto,
'Name' => $emailtoname
]
],
'TemplateID' => 1556091,
'TemplateLanguage' => true,
'Subject' => "Nouveau Préavis de départ accepté",
'Variables' => json_decode('
{"demandeur": "' . $demandeur . '",
"iddemande": "' . $iddemande . '"
}', true)
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && $response->getData();
/*
mail propriétaire :
Votre locataire vient de déposer un préavis de depart validé par Wizi
https://desk.wizi.eu/#/app/contract_owner/2476/menu
*/
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51', true, ['version' => 'v3.1']);
$mailto = $contract->getApplication()->getFlat()->getOwnedBy()->getEmail();
$emailtoname = $contract->getApplication()->getFlat()->getOwnedBy()->getName();
$demandeur = $contract->getApplication()->getUser()->getFirstname();
$iddemande = $contract->getId();
$iddemande = 'home';
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $mailto,
'Name' => $emailtoname
]
],
'TemplateID' => 1556081,
'TemplateLanguage' => true,
'Subject' => "Votre locataire dépose son préavis de départ",
'Variables' => json_decode('
{"demandeur": "' . $demandeur . '",
"iddemande": "' . $iddemande . '"
}', true)
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && $response->getData();
}
if($PreavisSortie->getTraitement() == 3){
// préavis refusé
/*
mail locataire :
demande de préavis refusée
https://desk.wizi.eu/#/app/contract_renter/2515/menu
*/
$mj = new \Mailjet\Client('94cad0ae03c89d27d428b9549de10c48', 'c868648747688a02902d23babd895c51', true, ['version' => 'v3.1']);
$mailto = $contract->getApplication()->getUser()->getEmail();
$emailtoname = $contract->getApplication()->getUser()->getName();
$demandeur = $contract->getApplication()->getUser()->getFirstname();
$iddemande = $contract->getId();
$body = [
'Messages' => [
[
'From' => [
'Email' => "laura@wizi.eu",
'Name' => "Laura de Wizi"
],
'To' => [
[
'Email' => $mailto,
'Name' => $emailtoname
]
],
'TemplateID' => 1556086,
'TemplateLanguage' => true,
'Subject' => "Votre préavis de départ est refusée",
'Variables' => json_decode('
{"demandeur": "' . $demandeur . '",
"iddemande": "' . $iddemande . '"
}', true)
]
]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && $response->getData();
}
return New JsonResponse('ok');
}
/**
* compter les leads a traiter
*
* @param Request $request
* @return JsonResponse
* @Route("/countuserhelprdv", name="countuserhelprdv", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function countUserhelprdvAction()
{
$namedb = $this->getParameter('dbreqpdo');
$udb = $this->getParameter('userreqpdo');
$pdb = $this->getParameter('passreqpdo');
$bdd = new \PDO('mysql:host=localhost;dbname=' . $namedb . ';charset=utf8', $udb, $pdb);
$sql = "
SELECT count(*) as res
FROM app.user_help_rdv as u ";
$condition = ' where ( status = 1 ) ';
//$max = $bdd->query($sql.$condition)->fetchColumn();
$sthd = $bdd->prepare($sql.$condition);
$sthd->execute();
$max = $sthd->fetch(\PDO::FETCH_ASSOC);
//return New JsonResponse($comuser->getUsername());
return New JsonResponse($max); //
}
/**
* Verifier un utilisateur video et carte d'identitée
*
* @Route("/certificateusercnicheck", name="certificateusercnicheck", options={"expose"=true})
* @Method({"GET","POST"})
* @param Request $request
* @return Response
*/
public function certificateusercnicheckAction(Request $request)
{
$data= [];
$args = [
'credentials' => [
'key' => 'AKIAUHKWPN22W5Z4BQJM',
'secret' => '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'
],
'region' => 'us-east-1',
'version' => 'latest'
];
$client = new RekognitionClient($args);
/*
$result = $client->compareFaces([
'SimilarityThreshold' => 60,
'SourceImage' => [
'Bytes' => file_get_contents('recoimg/1.jpg')
],
'TargetImage' => [
'Bytes' => file_get_contents('recoimg/2.jpg')
]
]);
*/
$result = $client->compareFaces([
'SimilarityThreshold' => 50,
'SourceImage' => [
'Bytes' => file_get_contents($_FILES['image']['tmp_name'])
],
'TargetImage' => [
'Bytes' => file_get_contents($_FILES['image2']['tmp_name'])
]
]);
if(isset($result['FaceMatches'][0])){
// var_dump($result['FaceMatches'][0]['Similarity']);
return New JsonResponse($result['FaceMatches'][0]['Similarity']);
}else{
// var_dump($result);
return New JsonResponse(0);
}
// return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
}
/**
* Verifier un utilisateur video et carte d'identitée
*
* @Route("/certificateusercnicheckcnipasseport", name="certificateusercnicheckcnipasseport", options={"expose"=true})
* @Method({"GET","POST"})
* @param Request $request
* @return Response
*/
public function certificateusercnicheckcnipasseportAction(Request $request)
{
$data= [];
$args = [
'credentials' => [
'key' => 'AKIAUHKWPN22W5Z4BQJM',
'secret' => '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'
],
'region' => 'us-east-1',
'version' => 'latest'
];
$client = new RekognitionClient($args);
/*
$result = $client->compareFaces([
'SimilarityThreshold' => 60,
'SourceImage' => [
'Bytes' => file_get_contents('recoimg/1.jpg')
],
'TargetImage' => [
'Bytes' => file_get_contents('recoimg/2.jpg')
]
]);
*/
/*
$result = $client->compareFaces([
'SimilarityThreshold' => 50,
'SourceImage' => [
'Bytes' => file_get_contents($_FILES['image']['tmp_name'])
],
'TargetImage' => [
'Bytes' => file_get_contents($_FILES['image2']['tmp_name'])
]
]);
*/
/*
$result = $client->detectText([
'Image' => array(
'Bytes' => file_get_contents($_FILES['image']['tmp_name']),
),
]);
*/
/*
$result = $client->detectText([
'Image' => array(
'Bytes' => file_get_contents('/home/app/public_html/recoocr/CNIscan.jpg'),
),
])['TextDetections'];
*/
$result = $client->detectText([
'Image' => array(
'Bytes' => file_get_contents($_FILES['image']['tmp_name']),
),
])['TextDetections'];
$stringtab = [];
$type = "Documment inconnu";
foreach($result as $item)
{
if($item['Type'] === 'LINE')
{
$word = "CARTE NATIONALE D'IDENTITE";
$wordpassport = "PASSEPORT";
$stringtab[] = $item['DetectedText'];
$mystring = $item['DetectedText'];
// Test if string contains the word
if(stristr($mystring, $word) !== false){
$type = "votre carte d'identité";
}elseif (stristr($mystring, $wordpassport) !== false) {
$type = "votre un passeport";
}
}
}
//var_dump($stringtab);
return New JsonResponse($type);
// return $this->render('Extranet/User/helpdesk.html.twig',['data' =>$data]);
}
/**
* Ajouter une agence
*
* @Route("/test/adduseragence", name="testadduseragence", options={"expose"=true})
* @Method({"GET","POST"})
* @return Response
*/
public function adduserAgenceAction(Request $request)
{
if ($request->isMethod('post')) {
/*
let datasend = {
firstname : $("#formFirstnameLoc").val(),
name : $("#formNameLoc").val(),
email : $("#formEmailLoc").val(),
phone : $("#formPhoneLoc").val(),
adresse : $("#formAdressLoc").val(),
codepostal : $("#formPostalcodeLoc").val(),
ville : $("#formCityLoc").val(),
codeubiflow : $("#codeUbiflow").val(),
}
*/
$firstname = $request->get('firstname');
$name = $request->get('name');
$email = $request->get('email');
$phone = $request->get('phone');
$adresse = $request->get('adresse');
$codepostal = $request->get('codepostal');
$ville = $request->get('ville');
$codeubiflow = $request->get('codeubiflow');
$password = random_int(1000, 9999);
$userManager = $this->get('fos_user.user_manager');
$em = $this->getDoctrine->getManager();
$usersRepository = $em->getRepository("AppBundle:User");
$email_exist = $usersRepository->findOneBy(array('email' => $email));
if($email_exist){
return new JsonResponse("l'agence existe deja");
}
$user = $userManager->createUser();
$user->setUsername($phone);
$user->setEmail($email);
$user->setEmailCanonical($email);
$user->setEnabled(1);
// this method will encrypt the password with the default settings :)
$user->setPlainPassword($password);
$userManager->updateUser($user);
$useragence = $usersRepository->findOneBy(array('email' => $email));
$useragence->setFirstname($firstname);
$useragence->setName($name);
$useragence->setMobilePhone($phone);
$useragence->setAdress($adresse);
$useragence->setPostalCode($codepostal);
$useragence->setCity($ville);//setIsClientUbiflow
$useragence->setIsClientUbiflow(1);
$useragence->setCodeClientUbiflow($codeubiflow);//setInitialMode // setMode // ->addRole('ROLE_API')
$useragence->setInitialMode(2);
$useragence->setMode(2);
$useragence->addRole('ROLE_API'); // setTemporyPass()
$useragence->setTemporyPass($password);
$em->persist($useragence);
$em->flush();
return new JsonResponse('utilisateur ok');
}
else{
return $this->render('Extranet/Security/addUserAgence.html.twig', array(
));
}
}
/**
* Envoyer une recompense user en ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/sendajaxrecompense", name="sendajaxrecompense", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function sendajaxrecompenseAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\Recompense');
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$recompense = $noteManager->find($request->get('note'));
$user->addRecompense($recompense);
$em->persist($user);
$em->flush();
return new JsonResponse('recompense activée');
}
/**
* effacer une recompense utilisateur
*
* @param Request $request
* @return JsonResponse
* @Route("/deldajaxrecompense", name="deldajaxrecompense", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function delajaxrecompenseAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\Recompense');
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$recompense = $noteManager->find($request->get('note'));
$user->removeRecompense($recompense);
$em->persist($user);
$em->flush();
return new JsonResponse('recompense effacé');
}
/**
* Envoyer une recompense flat en ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/sendajaxrecompenseflat", name="sendajaxrecompenseflat", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function sendajaxrecompenseflatAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\Recompense');
$flatManager = $em->getRepository('App\AppBundle\Entity\Flat');
$flat = $flatManager->find($request->get('flat'));
$recompense = $noteManager->find($request->get('note'));
$flat->addRecompense($recompense);
$em->persist($flat);
$em->flush();
return new JsonResponse('recompense activée');
}
/**
* effacer une recompense flat ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/deldajaxrecompenseflat", name="deldajaxrecompenseflat", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function delajaxrecompenseflatAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$noteManager = $em->getRepository('App\AppBundle\Entity\Recompense');
$flatManager = $em->getRepository('App\AppBundle\Entity\Flat');
$flat = $flatManager->find($request->get('flat'));
$recompense = $noteManager->find($request->get('note'));
$flat->removeRecompense($recompense);
$em->persist($flat);
$em->flush();
return new JsonResponse('recompense effacé');
}
// boadduserticket
/**
* effacer une recompense flat ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/boadduserticket/{ticket}", name="boadduserticket", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function boadduserticketAction(Request $request, Ticket $ticket)
{
$em = $this->getDoctrine->getManager();
$users = $em->getRepository('App\AppBundle\Entity\User')->findByRoles('TICKET');
if ($request->isMethod('post') && $request->get('uid')) {
$noteManager = $em->getRepository('App\AppBundle\Entity\Ticket');
$uid = $request->get('uid');
$u = $em->getRepository('App\AppBundle\Entity\User')->find($uid);
$tu = new TicketUser();
$tu->setUser($u);
$tu->setStatus(1);
$tu->setTicket($ticket);
$em->persist($tu);
$em->flush();
return new JsonResponse('utilisateur ajout');
}
else{
return $this->render('Extranet/Security/addUserTicket.html.twig', array(
"ticket" => $ticket,
"users" => $users
));
}
}
/**
* Noter une annonce ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/noteflatnoteajax", name="noteflatnoteajax", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function noteflatajaxAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$flatnoteManager = $em->getRepository('App\AppBundle\Entity\FlatNote');
$flatManager = $em->getRepository('App\AppBundle\Entity\Flat');
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$flat = $flatManager->find($request->get('flat'));
$comment = $request->get('comment');
$note = $request->get('note');
$existFlat = $flatnoteManager->findOneBy(['user'=> $user,'flat'=> $flat]);
if($existFlat){
$existFlat->setNote($note);
$existFlat->setStatus(1);
$existFlat->setComment($comment);
$em->persist($existFlat);
} else {
$flatNote = new FlatNote();
$flatNote->setUser($user);
$flatNote->setFlat($flat);
$flatNote->setNote($note);
$flatNote->setStatus(1);
$flatNote->setComment($comment);
$em->persist($flatNote);
}
$em->flush();
return new JsonResponse('Note Ajoutée');
}
/**
* Stop Alert annonces dispos ajax
*
* @param Request $request
* @return JsonResponse
* @Route("/stopalertannonceajax", name="stopalertannonceajax", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function stopalertannonceajaxAction(Request $request)
{
$em = $this->getDoctrine->getManager();
$userManager = $em->getRepository('App\AppBundle\Entity\User');
$user = $userManager->find($request->get('user'));
$user->setAlertNewFlat(1);
$em->persist($user);
$em->flush();
return new JsonResponse('Alertes Annonces desactivees');
}
/**
* Effacer les utilisateurs innactifs depuis plus de trois ans
*
* @param Request $request
* @return JsonResponse
* @Route("/rgpddeleteusertroisyears", name="rgpddeleteusertroisyears", options={"expose"=true})
* @Method({"GET","POST"})
*/
public function rgpddeleteusertroisyearsAction(Request $request)
{
$request = "SELECT * FROM app.user
where last_login < DATE_SUB(curdate(), INTERVAL 3 YEAR)
and
user.id not in (
select loc.id from contract
inner join application as apps on contract.application_id = apps.id
inner join user as loc on apps.user = loc.id
where contract.status = 2
or
contract.status = 4
or
contract.status = 1
)
and
user.id not in (
select fl.owned_by_id from contract
inner join application as apps on contract.application_id = apps.id
inner join user as loc on apps.user = loc.id
inner join flat as fl on apps.flat = fl.id
where contract.status = 2
or
contract.status = 4
or
contract.status = 1
)";
return new JsonResponse('Alertes Annonces desactivees');
}
}